Is there a way to use the TikZ
libraries cd
and external
together?
This does not work:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{cd, external}
\tikzexternalize
\begin{document}
\begin{tikzcd}
A \arrow[rd] \arrow[r, "\varphi"] & B \\ & C
\end{tikzcd}
\end{document}
Error:
Runaway argument?
! File ended while scanning use of \tikzexternal@laTeX@collect@until@end@tikzpicture.
I’m using TikZ/PGF
version 3.0.0 and tikz-cd
version 0.9b.
Best Answer
The problem is the same as that in Problem with environment expansion and the Tikz external library. in that TeX does not see the
\end{tikzpicture}
inside the\end{tikzcd}
. The solution in Problem with environment expansion and the Tikz external library. is to pack everything inside a macro to ensure that the customised end-of-environment is expanded before TeX starts gobbling so that the hidden\end{tikzpicture}
is revealed. The adaptation of that in the question above is not the same because it adds an extra\end{tikzpicture}
instead of unpacking the hidden one, and this leads to nesting of TikZ pictures which is Not A Good Idea.(Nonetheless, just because something is not a good idea doesn't mean that it isn't the best idea, just that it should be used with extreme caution.)
If all your pictures are
tikzcd
environments then it seems that the right solution might be to tell TeX to look fortikzcd
instead oftikzpicture
. This is a reasonable thing to try to do because the first thing that\begin{tikzcd}
does is to start atikzpicture
and the last thing that\end{tikzcd}
does is to end it. However, my experiments at trying to change alltikzpicture
s in the externalisation code totikzcd
didn't work so I'm abandoning this for the time being (what would be nice would be an adaptation of the externalisation library that worked for any environment, not justtikzpicture
s).Here's an adaptation of your adaptation of my answer to the linked question which instead of wrapping the
tikzcd
environment in atikzpicture
simply exposes the innertikzpicture
. Well, except that it doesn't since the innertikzpicture
is written as\tikzpicture ... \endtikzpicture
which wouldn't match so we have to redefine thetikzcd
environment to make the\tikzpicture
and\endtikzpicture
into\begin{tikzpicture}
and\end{tikzpicture}
. Elegant, it ain't, but it does avoid the nesting issue.