6

Assume I want to use some nice TikZ feature, such as casting a shadow, or something else. I may want to do that inside or outside a tikzpicture environment. So I am wondering if there is a (simple) way to find out if a command is executed in a tikzpicture environment. To be more specific, consider the MWE:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fadings}
\tikzset{CastShadow/.style={anchor=south,inner sep=0,font=\ttfamily\Huge}}
\newcommand{\CastShadowOutsideTikZ}[2][]{
\begin{tikzpicture}[baseline=(temp.base)]
  \node[CastShadow,#1](temp){#2};
  \node[scope fading=south,opacity=0.4,yscale=-1,CastShadow,#1]{#2};
\end{tikzpicture}
}
\newcommand{\CastShadowInsideTikZ}[2][]{
  \node[CastShadow,#1]{#2};
  \node[scope fading=south,opacity=0.4,yscale=-1,CastShadow,#1]{#2};
}

\begin{document}
\CastShadowOutsideTikZ{Quack} \CastShadowOutsideTikZ[scale=2]{Quack}

\begin{tikzpicture}
\CastShadowInsideTikZ[at={(0,0)},scale=2]{Feep}
\end{tikzpicture}
\end{document}

I'd like to unify the commands \CastShadowOutsideTikZ and \CastShadowInsideTikZ to a single command \CastShadow, which behaves like \CastShadowInsideTikZ when called within a tizkpicture and like \CastShadowOutsideTikZ otherwise.

(I am aware of this post), but my question is whether there is a simpler way.)

6

You should make the code below more robust by adding an error message in the fourth argument of \apptocmd, just in case TikZ internals were to change.

\documentclass{article}
\usepackage{tikz,etoolbox}
\usetikzlibrary{fadings}
\newtoggle{intikz}
\makeatletter
\apptocmd{\tikz@startup@env}{\toggletrue{intikz}}{}{}
\makeatother
\tikzset{CastShadow/.style={anchor=south,inner sep=0,font=\ttfamily\Huge}}
\newcommand{\CastShadowOutsideTikZ}[2][]{
\begin{tikzpicture}[baseline=(temp.base)]
  \node[CastShadow,#1](temp){#2};
  \node[scope fading=south,opacity=0.4,yscale=-1,CastShadow,#1]{#2};
\end{tikzpicture}
}
\newcommand{\CastShadowInsideTikZ}[2][]{
  \node[CastShadow,#1]{#2};
  \node[scope fading=south,opacity=0.4,yscale=-1,CastShadow,#1]{#2};
}
\newcommand\CastShadow{\iftoggle{intikz}{\CastShadowInsideTikZ}{\CastShadowOutsideTikZ}}
\begin{document}
\CastShadow{Quack} \CastShadowOutsideTikZ[scale=2]{Quack}

\begin{tikzpicture}
\CastShadow[at={(0,0)},scale=2]{Feep}
\end{tikzpicture}
\end{document}
  • Of course, all bets are off if you place a non-tikz environment inside your tikz environment! (It could be handled too, with a bit more work. You would just have to toggle intikz off on entry to every environment.) – Harald Hanche-Olsen Jan 27 '18 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy