Use TikZ matrix inside a savebox: doesn't work because of "&"

TikZ changes the category code of & to be an active character to process the matrix. But the tikzpicture is used as argument for \savebox. When TeX parses an argument, then the text is tokenized with the current category code settings. Then, when TikZ changes the category code, it does not have an effect, because & is already tokenized.

LaTeX provides the environment lrbox as alternative to the commands \savebox or \sbox. In the environment form, the contents is not read as argument and category changes work:

\documentclass{article}
\usepackage{tikz}

\newsavebox{\testsbox}
\begin{lrbox}{\testsbox}
    \begin{tikzpicture} [borders/.style={draw, help lines}]
        \matrix[borders]{
            \node [borders] {11};
        &
            \node [borders] {12};
        \\
        };
    \end{tikzpicture}
\end{lrbox}

\begin{document}
    \begin{tikzpicture}
        \node {\usebox{\testsbox}};
    \end{tikzpicture}
\end{document}

Result

The environment lrbox also removes spaces at the begin and at the end of the body in opposite to \savebox/\sbox.


Use the ampersand replacement to replace & by an arbitrary command (most people choose \&).

\documentclass{article}
    \usepackage{tikz}

    \newsavebox{\testsbox}
    \savebox{\testsbox}{%
        \begin{tikzpicture} [borders/.style={draw, help lines}]
            \matrix[borders,ampersand replacement=\&]{
                \node [borders] {11};
            \&
                \node [borders] {12};
            \\
            };
        \end{tikzpicture}%
    }

\begin{document}
    This example stops working as soon as you add a second column (i.e. uncomment lines 9 and 10).
    \begin{tikzpicture}
        \node {\usebox{\testsbox}};
    \end{tikzpicture}
\end{document}

enter image description here