I've been trying to follow the insights from the following posts:
- Are the TikZ libraries cd and external incompatible with one another?
- How to avoid redefining ampersand & globally?
- Use & inside commands
(The user tobiasBora seems to be interested in achieving very similar things to me.) However, I've ended up in a jumble of nothing quite working in all possible cases.
In short, I want to use a tikzcd environment that
- works as you would expect it to (duh!)
- also works in conjunction with the externalize package
- also works if you want to embed it in an amsmath align environment
- works with the beamer document class
My current attempt is in the MWE below:
\documentclass{article}
\usepackage{tikz}
\usepackage{amsmath,xparse,etoolbox}
\usetikzlibrary{cd,external}
%we don't actually need externalisation to demonstrate the problem, so turn it off for now
%\tikzexternalize
\makeatletter
\NewDocumentEnvironment{quantikz}{O{}+b}{%
%local redefinition of catcode
\begingroup \catcode`&=\active
\def@temp{\tikzcd@[#1]\scantokens{#2}}%
\expandafter@temp\endtikzcd\endgroup
}{}
%replace commands with environment. seems to help with externalize.
\patchcmd\tikzcd@{\tikzpicture}{\begin{tikzpicture}}{}{}
\patchcmd\endtikzcd{\endtikzpicture}{\end{tikzpicture}}{}{}
\makeatother
\tikzcdset{nodes in empty cells}
%this works
%also works with external switched on
%also works when documentclass is beamer
\begin{document}
\begin{quantikz}
H & \ar[l]
\end{quantikz}
%this does not work
%neither does ampersand replacement
% \begin{align}
% \begin{quantikz}
% & \ar[l]
% \end{quantikz}
% \end{align}
%original environment works with ampersand replacement
%but does not externalize
\begin{align}
\begin{tikzcd}[ampersand replacement=&]
H & \ar[l]
\end{tikzcd}
\end{align}
\end{document}
I had wondered if a simple solution would be to get ampersand replacement working again within the new environment. But even if I directly replace all instances of & with \pgfmatrixnextcell, the quantikz environment doesn't seem to work inside align.
alignenvironment grabs its content at this point the catcode of&is fixed and you can't unfix it easily. (Though, we could possibly write a newtikzcdenvironment that takes its content and replaced all&with\pgfmatrixnextcell.) Are you actually using thealign*environment with alignment? With your example, just usingequation*would be enough. – Qrrbrbirlbel Apr 14 '23 at 10:48