In order to use & inside align I applied this great answer https://tex.stackexchange.com/a/619983/116348, which basically sets & as active using:
\ExplSyntaxOn
\NewDocumentCommand{\zx}{O{}+m}{%
\tl_rescan:nn { \char_set_catcode_active:N \& } { \begin{mytikzcd}[#1] #2 \end{mytikzcd} }
}
\ExplSyntaxOff
Unfortunately, I don't know why, but when this code is wrapped into an align, it is evaluated twice (and if the tikz picture takes a lot of time to evaluate... then the twice is multiplied by 2).
I understand that align may parse the token twice, but I'm surprise that the token are actually evaluated twice. Any idea if it's possible to evaluate it only a single time, or if it's a fundamental issue?
MWE
$ pdflatex twice.tex | grep XXX
XXX No align:
XXX>>Called...
XXX With align:
XXX>>Called...
XXX>>Called...
XXX End
\documentclass[]{article}
\usepackage{amsmath}
\usepackage{tikz-cd}
\usepackage{lipsum}
\ExplSyntaxOn
\NewDocumentCommand{\zx}{O{}+m}{%
\message{XXX >> Called...^^J}%
\tl_rescan:nn { \char_set_catcode_active:N & } { \begin{tikzcd}[#1] #2 \end{tikzcd} }
}
\ExplSyntaxOff
\begin{document}
\message{^^JXXX No align:^^J}
\zx{A}
\message{XXX With align:^^J}
In align:
\begin{align}
\zx{A}
\end{align}
\message{XXX End^^J}
\end{document}
align. – egreg Feb 08 '22 at 16:08aligngets evaluated twice, not everything in the document. And one *needs* this double evaluation. – egreg Feb 08 '22 at 16:10align, then the time can be quite long. And this is my case as tikz-external takes like one second to evaluate, if I've only 60 symbols in my paper, then the paper already takes 1mn to compile, which gives 2mn when used inside align environment. And 60 symbols is not a lot. But I didn't know it was needed to evaluate twice, that's true even normal macro get evaluated twice. What's the reason for that? I guess align could avoid that by using boxes or similar, no? – tobiasBora Feb 08 '22 at 16:17aligntypesets its contents twice, the first time for measuring and the second time to actually print stuff. In order to prevent code from being duplicated,amsmathprovides the conditional\ifmeasuring@see e.g. https://tex.stackexchange.com/q/105836/82917 – campa Feb 08 '22 at 16:17alignyou're welcome to propose them on the GitHub site. Since it has been doing so for more than a quarter of a century… – egreg Feb 08 '22 at 16:20\ifmeasuring@to build the picture and save it in a box, and then re-insert it when\ifmeasuring@is false... But then I'm not sure how to use properly boxes for that, as I need a way to garbage collect the boxes, without reusing boxes that are already used by other boxes I guess... It's maybe a bit too much work for the benefit. – tobiasBora Feb 08 '22 at 16:21\sbox\myboxbefore the alignment the\usebox\myboxso you just unpack the box twice which is essentially free. – David Carlisle Feb 08 '22 at 16:36\begin{align}seems rather insignificant to me. – David Carlisle Feb 08 '22 at 16:45