Редактировать

Редактировать

Картины (на основе tikz), которые я создаю, часто являются модульными. Поэтому было бы идеально использовать один и тот же источник для разных вариантов картинок.

В идеале это должно быть основано на standalone, поскольку это то, что я уже использую, и предоставить новую среду, которая определяет условные блоки (я назвал среду conditionallyниже). Эти условные блоки кода могут быть включены с помощью includestandaloneопции:

main.tex:

\documentclass{article}

\usepackage{standalone}
\usepackage{tikz}

\begin{document}
\includestandalone[enableall]{figure}

\includestandalone[enable=detour]{figure}

\includestandalone[enable={detour,longer-detour}]{figure}

\end{document}

figure.tex:

\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\pgfmathsetmacro{\myRadius}{2}

\coordinate (loop-start) at (-170:\myRadius);

\draw[
  ->,
  line width=7pt,
]
(loop-start)
arc (-170:170:\myRadius)
coordinate[pos=0.75] (detour-start)
coordinate[pos=0.25] (detour-end)
coordinate[pos=0.27] (detour-end-2)
;

\begin{conditionally}{detour}
  \draw[
    ->,
    line width=3pt,
    red,
  ] (detour-start) to[out=160, in=220, distance=6cm] (detour-end);
\end{conditionally}

\begin{conditionally}{longer-detour}
  \draw[
    ->,
    line width=3pt,
    red,
  ] (detour-start) to[out=45, in=-30, distance=10cm] (detour-end-2);
\end{conditionally}

\end{tikzpicture}
\end{document}

Возможно ли что-то подобное?

решение1

Это решение включает целевой синтаксис для standaloneфайла, содержащего tikzpicture, но использует пользовательскую команду в основном файле.

Точнее, conditionallyэто среда, которая принимает один обязательный аргумент.

  • Аргумент должен состоять из простого тега/метки, используемой для идентификации содержимого.
  • В примере это используется как часть tikzpicture, но решение не зависит от этого. Тот же механизм можно было бы использовать для включения выборки цитат, скажем, или произвольных фрагментов кода.

\flowconditional[<key-value list>]{<filename>}используется в основном документе для выбора фрагментов по тегу/метке из <filename>.

  • В настоящее время определен только один ключ: enable.
  • enableпринимает список значений, разделенных запятыми.
  • Каждое значение должно быть либо тегом/меткой, <filename>либо *, где *указывает на то, что должен быть включен весь доступный код.
  • Однако это требование не соблюдается: если переданное значение enableне определено в filename, то это значение будет молчаливо проигнорировано.

Учитывая, что файл рисунка OP называется \jobname-fig.tex, мы можем записать

\flowconditionalpic[enable=*]{\jobname-fig}

\flowconditionalpic[enable=detour]{\jobname-fig}

\flowconditionalpic[enable={detour,longer-detour}]{\jobname-fig}

для создания целевого поведения.

целевой выход

Тот же фреймворк можно использовать для включения или невключения tabularокружений (хотя включение наборов строк потребует немного больше работы). Например,

\begin{table}
  \caption{Tables rather than pictures}
  \flowconditional[enable=tab1]{\jobname-tab}
  \flowconditional[enable=tab2]{\jobname-tab}
\end{table}

\begin{table}
  \caption{Order is irrelevant}
  \flowconditional[enable=*]{\jobname-tab}
  \flowconditional[enable={tab2,tab1}]{\jobname-tab}
\end{table}

где \jobname-tab.texсодержится

\documentclass{standalone}
\usepackage{array}
\usepackage{booktabs}
\begin{document}
\sffamily
\begin{conditionally}{tab1}
  \begin{tabular} {ll}
    \toprule
    \bfseries Column 1 & \bfseries Column 2 \\
    \midrule
    Row 1 & Cell A \\
    \bottomrule
  \end{tabular}
\end{conditionally}
\begin{conditionally}{tab2}
  \begin{tabular} {ll}
    \toprule
    \bfseries Column 1 & \bfseries Column 2 \\
    \midrule
    Row 1 & Cell A \\
    Row 2 & Cell B \\
    \bottomrule
  \end{tabular}
\end{conditionally}
\end{document}

та же идея с таблицами, а не частями tikzpicture

Полный код:

\begin{filecontents}[overwrite]{\jobname-fig.tex}
\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}  
  \pgfmathsetmacro{\myRadius}{2} 
  \coordinate (loop-start) at (-170:\myRadius);  
  \draw[->,line width=7pt,]
  (loop-start)
  arc (-170:170:\myRadius)
  coordinate[pos=0.75] (detour-start)
  coordinate[pos=0.25] (detour-end)
  coordinate[pos=0.27] (detour-end-2)
  ;  
  \begin{conditionally}{detour}
    \draw[
    ->,
    line width=3pt,
    red,
    ] (detour-start) to[out=160, in=220, distance=6cm] (detour-end);
  \end{conditionally}  
  \begin{conditionally}{longer-detour}
    \draw[
    ->,
    line width=3pt,
    red,
    ] (detour-start) to[out=45, in=-30, distance=10cm] (detour-end-2);
  \end{conditionally}
\end{tikzpicture}
\end{document}
\end{filecontents}
\begin{filecontents}[overwrite]{\jobname-tab.tex}
\documentclass{standalone}
\usepackage{array}
\usepackage{booktabs}
\begin{document}
\sffamily
\begin{conditionally}{tab1}
  \begin{tabular} {ll}
    \toprule
    \bfseries Column 1 & \bfseries Column 2 \\
    \midrule
    Row 1 & Cell A \\
    \bottomrule
  \end{tabular}
\end{conditionally}
\begin{conditionally}{tab2}
  \begin{tabular} {ll}
    \toprule
    \bfseries Column 1 & \bfseries Column 2 \\
    \midrule
    Row 1 & Cell A \\
    Row 2 & Cell B \\
    \bottomrule
  \end{tabular}
\end{conditionally}
\end{document}
\end{filecontents}

\documentclass{article}
% ateb: https://tex.stackexchange.com/a/705487/ addaswyd o gwestiwn Flow: https://tex.stackexchange.com/q/705458/
\usepackage[subpreambles]{standalone}
\usepackage{tikz}
\ExplSyntaxOn
\bool_new:N \l_flow_condition_bool
\bool_set_false:N \l_flow_condition_bool
\keys_define:nn { flow }
{
  enable .clist_set:N = \l_flow_conditions_clist,
  enable .initial:n = ,
  enable .default:n = ,
}
\NewDocumentEnvironment { conditionally } { m +b }
{
  \clist_if_in:NnT \l_flow_conditions_clist { #1 }
  { \bool_set_true:N \l_flow_condition_bool } 
  \clist_if_in:NnT \l_flow_conditions_clist { * }
  { \bool_set_true:N \l_flow_condition_bool } 
  \bool_if:NT \l_flow_condition_bool { #2 }
}{  }
\NewDocumentCommand \flowconditional { O {} m }
{
  \group_begin:
    \keys_set:nn { flow } { #1 }
    \includestandalone { #2 }
  \group_end:
}
\ExplSyntaxOff

\begin{document}
\flowconditional[enable=*]{\jobname-fig}

\flowconditional[enable=detour]{\jobname-fig}

\flowconditional[enable={detour,longer-detour}]{\jobname-fig}


\begin{table}
  \caption{Tables rather than pictures}
  \flowconditional[enable=tab1]{\jobname-tab}
  \flowconditional[enable=tab2]{\jobname-tab}
\end{table}

\begin{table}
  \caption{Order is irrelevant}
  \flowconditional[enable=*]{\jobname-tab}
  \flowconditional[enable={tab2,tab1}]{\jobname-tab}
\end{table}

\end{document}

Редактировать

Следующий пример добавляет дополнительный ключ standalone options. Изначально он установлен на mode = tex. Использование ключа без значения очистит параметры. Использование ключа со значением установит параметры на это значение. В примере ниже начальное значение применяется в большинстве случаев, а angle=90используется для демонстрации эффекта изменения параметра.

\documentclass{article}
% ateb: https://tex.stackexchange.com/a/705487/ addaswyd o gwestiwn Flow: https://tex.stackexchange.com/q/705458/
\usepackage[subpreambles]{standalone}
\usepackage{tikz}
\ExplSyntaxOn
\bool_new:N \l_flow_condition_bool
\bool_set_false:N \l_flow_condition_bool
\keys_define:nn { flow }
{
  enable .clist_set:N = \l_flow_conditions_clist,
  enable .initial:n = ,
  enable .default:n = ,
  standalone ~ options .tl_set:N = \l_flow_standalone_tl,
  standalone ~ options .default:n = ,
  standalone ~ options .initial:n = {mode = tex},
}
\NewDocumentEnvironment { conditionally } { m +b }
{
  \clist_if_in:NnT \l_flow_conditions_clist { #1 }
  { \bool_set_true:N \l_flow_condition_bool } 
  \clist_if_in:NnT \l_flow_conditions_clist { * }
  { \bool_set_true:N \l_flow_condition_bool } 
  \bool_if:NT \l_flow_condition_bool { #2 }
}{  }
\NewDocumentCommand \flowconditional { O {} m }
{
  \group_begin:
    \keys_set:nn { flow } { #1 }
    \flow_includestandalone:Vn \l_flow_standalone_tl { #2 }
  \group_end:
}
\cs_new_protected:Nn \flow_includestandalone:nn
{
  \includestandalone [ #1 ] { #2 }
}
\cs_generate_variant:Nn \flow_includestandalone:nn { Vn }
\ExplSyntaxOff

\begin{document}
\flowconditional[enable=*]{\jobname-fig}

\flowconditional[enable=detour,standalone options={angle=90}]{\jobname-fig}

\flowconditional[enable={detour,longer-detour}]{\jobname-fig}


\begin{table}
  \caption{Tables rather than pictures}
  \flowconditional[enable=tab1]{\jobname-tab}
  \flowconditional[enable=tab2]{\jobname-tab}
\end{table}

\begin{table}
  \caption{Order is irrelevant}
  \flowconditional[enable=*]{\jobname-tab}
  \flowconditional[enable={tab2,tab1}]{\jobname-tab}
\end{table}

\end{document}

эффект установки `standalone options={angle=90}

решение2

Вы можете использовать \pic:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\tikzset{
    pics/conditional loop/.style={
        code={
            \tikzset{conditional loop/.cd, #1}
            \coordinate
                (-loop-start)
                at (-170:{\pgfkeysvalueof{/tikz/conditional loop/radius}})
            ;
            \draw[
              ->,
              line width=7pt,
            ]
                (-loop-start)
                arc[
                    start angle=-170, 
                    end angle=170, 
                    radius={\pgfkeysvalueof{/tikz/conditional loop/radius}}
                ]
                coordinate[pos=0.75] (-detour-start)
                coordinate[pos=0.25] (-detour-end-short)
                coordinate[pos=0.27] (-detour-end-long)
            ;
            \foreach \o/\i/\d/\e in \conditionallooploopsettings {
                \draw[
                    ->,
                    line width=3pt,
                    red,
                ] 
                    (-detour-start) 
                    to[out=\o, in=\i, distance=\d] 
                    (-\e)
                ;
            }
        }
    },
    conditional loop/radius/.initial={2},
    conditional loop/loop settings/.store in=\conditionallooploopsettings,
    conditional loop/loop settings={},
    conditional loop/all/.style={
        loop settings={160/220/6cm/detour-end-short,45/-30/10cm/detour-end-long}
    },
    conditional loop/detour/.style={
        loop settings={160/220/6cm/detour-end-short}
    },
    conditional loop/longer detour/.style={
        loop settings={45/-30/10cm/detour-end-long}
    }
}

\begin{tikzpicture}

\pic at (0,0) {conditional loop};

\pic at (0,-10) {conditional loop={all}};

\pic at (0,-20) {conditional loop={detour}};

\pic at (0,-30) {conditional loop={longer detour}};

\pic at (0,-40) {conditional loop={radius=1cm, all}};

\end{tikzpicture}
\end{document}

введите описание изображения здесь

Вариант, который также позволяет conditional loop={detour, longer detour}:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\tikzset{
    pics/conditional loop/.style={
        code={
            \tikzset{conditional loop/.cd, #1}
            \coordinate
                (-loop-start)
                at (-170:{\pgfkeysvalueof{/tikz/conditional loop/radius}})
            ;
            \draw[
              ->,
              line width=7pt,
            ]
                (-loop-start)
                arc[
                    start angle=-170, 
                    end angle=170, 
                    radius={\pgfkeysvalueof{/tikz/conditional loop/radius}}
                ]
                coordinate[pos=0.75] (-detour-start)
                coordinate[pos=0.25] (-detour-end-short)
                coordinate[pos=0.27] (-detour-end-long)
            ;
            \pgfkeys{/tikz/conditional loop/draw loops}
        }
    },
    conditional loop/detour arrow/.style={
        ->,
        line width=3pt,
        red,
    },
    conditional loop/radius/.initial={2},
    conditional loop/loop settings/.store in=\conditionallooploopsettings,
    conditional loop/draw loops/.initial={},
    conditional loop/detour/.style={
        draw loops/.append code={
            \draw[conditional loop/detour arrow]
                (-detour-start) 
                to[out=160, in=220, distance=6cm] 
                (-detour-end-short);
        }
    },
    conditional loop/longer detour/.style={
        draw loops/.append code={
            \draw[conditional loop/detour arrow]
                (-detour-start) 
                to[out=34, in=-30, distance=10cm] 
                (-detour-end-long);
        }
    },
    conditional loop/all/.style={
        detour,
        longer detour
    }
}

\begin{tikzpicture}

\pic at (0,0) {conditional loop};

\pic at (0,-10) {conditional loop={all}};

\pic at (0,-20) {conditional loop={detour}};

\pic at (0,-30) {conditional loop={longer detour}};

\pic at (0,-40) {conditional loop={detour, longer detour}};

\end{tikzpicture}
\end{document}

введите описание изображения здесь

Связанный контент