2

I've have the following two pieces of code. The first one compiles; the second one doesn't. I don't understand why the second one fails. Could someone explain?

Example 1:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

   \matrix [column sep=0pt,every node/.style={draw,minimum size=2em}]
   {
     \node(m0) {a}; & \node(m1) {b}; & \node(m2) {c}; \\
   };

\end{tikzpicture}

\end{document}

Example 2:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\def\usemygrid{%%
   \matrix [column sep=0pt,every node/.style={draw,minimum size=2em}]
   {
     \node(m0) {a}; & \node(m1) {b}; & \node(m2) {c}; \\
   };
}

\begin{tikzpicture}

  \usemygrid 

\end{tikzpicture}

\end{document}

This second example results in the following error:

! Undefined control sequence.
<argument> \pgf@matrix@last@nextcell@options 

l.15       \usemygrid
5

TikZ makes & an active character, so that it can redefine it as needed, e.g. in tikzmatrix, where it is a shortcut for \pgfmatrixnextcell.

Outside of a TikZ environment, & isn't an active character, so your macro doesn't expand & as it would in the document.

To fix this, provide a replacement \& and use it in place of & in your macro.

\def\usemygrid{%%
   \matrix [column sep=0pt,every node/.style={draw,minimum size=2em},
            ampersand replacement=\&] % <-- here
   {
     \node(m0) {a}; \& \node(m1) {b}; \& \node(m2) {c}; \\
   };
}

See also this TeX.SX post.

Not the answer you're looking for? Browse other questions tagged or ask your own question.