# Problems with tikz-cd and etoolbox

I have started using tikz-cd and it seems there is a problematic interaction with toggles. In particular, when I try to add a second "column" to the diagram, the code breaks. More specifically, this

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz-cd}
\newtoggle{mytoggle}
\toggletrue{mytoggle}

\begin{document}

Hello
\iftoggle{mytoggle}{
\begin{tikzcd}
X
\end{tikzcd}
}{goodbye}

\end{document}


works, while if I replace the line X with X & Y, my code will not compile and I get a bunch of "undefined control sequence. }{goodbye}" and a "package pgf Error: Single ampersand used with wrong catcode. }{goodbye}". Any tips?

tikz-cd uses the same mechanism of TikZ matrices, so & can't be used when the diagram is in the argument to another command.

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz-cd}
\newtoggle{mytoggle}
\toggletrue{mytoggle}

\begin{document}

Hello
\iftoggle{mytoggle}{%
\begin{tikzcd}[ampersand replacement=\&]
X \arrow[r] \& Y
\end{tikzcd}
}{goodbye}

\end{document}


will work.

Environment tikzcd changes the category code of & and makes it active. Inside an argument of another macro the environment is already read and category changes come too late. It is the same reason, why verbatim commands do not work inside macros of other arguments.

TeX switches can be used as workaround:

documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz-cd}
\newtoggle{mytoggle}
\toggletrue{mytoggle}

\begin{document}

Hello
\iftoggle{mytoggle}{\iftrue}{goodbye\iffalse}%
\begin{tikzcd}
X & Y
\end{tikzcd}
\fi

\end{document}