I would like to define the \DrawLine macro below so that it can be invoked from within a {tikzpicture} environment or from outside:
\newcommand*{\DrawLine}[1]{%
\IfInTikzPic{}{\tikzpicture[remember picture]}
\draw[ultra thick, ->, #1] (0,) -- (1,1) node [right] {output of DrawLine};
\IfInTikzPic{}{\endtikzpicture}%
}
This works fine when invoked from within a {tikzpicture}, but not when it is invoked from outside (line is commented in the MWE). Invoking it from outside yields the error:
Missing \endgroup inserted.
The MWE below uses the first reference below. The other two references also fail on the commented out test case.
References:
Detecting if inside a tikzpicture node. Even though this solution is for detecting within a node, it appears to work to detect if you are within a
\tikzpicture(as the commented out code in the MWE shows).Is there a (simple) way to find out if a command is executed in a tikzpicture environment?.
How can I check if the current code is inside a certain environment?.
Code:
\documentclass{article}
\usepackage{tikz}
\makeatletter
\newcommand{\IfInTikzPic}[2]{% https://tex.stackexchange.com/a/121309/4301
\ifx\pgfpictureid@undefined#2\else#1\fi%
}
\makeatother
\newcommand*{\DrawLine}[1]{%
\IfInTikzPic{}{\tikzpicture[remember picture]}
\draw[ultra thick, ->, #1] (0,) -- (1,1) node [right] {output of DrawLine};
\IfInTikzPic{}{\endtikzpicture}%
}
\begin{document}
%%% The commented out code here is to show that \IfInTikzPic works as desired
%%% (in a tikzpicture, outside of a \node).
%%%
%\textbf{IfInTikzPic}\par
%\IfInTikzPic{inside}{outside}
%
%\begin{tikzpicture}
% \IfInTikzPic{\draw [red, ultra thick]}{\draw [blue, ultra thick]} (0,0) -- (1,0);
%\end{tikzpicture}
%
%\medskip% --------------------------
\textbf{DrawLine}: Actual Output\par
%\DrawLine{blue}% <---- How do I get this case to work?
\begin{tikzpicture}
\DrawLine{orange}
\end{tikzpicture}
\medskip% --------------------------
\textbf{DrawLine}: Desired Output\par
\begin{tikzpicture}
\DrawLine{blue}
\end{tikzpicture}
\begin{tikzpicture}
\DrawLine{orange}
\end{tikzpicture}
\end{document}


Undefined control sequence). – Peter Grill Nov 07 '18 at 20:06