2

For a long time, I thougt I understood how LaTeX expands commands. But apparently, I don't.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \edef\r{1 and 2}
  \draw (0,0) ellipse (2 and 4); % this works
  \draw (0,0) ellipse (\r); % this causes the error
\end{tikzpicture}
\end{document}

When attempting to compile the above code, I get the following error:

! Package PGF Math Error: Unknown operator `a' or `an' (in '1 and 2').

Can someone explain to me why the above error happens, and what can be done to circumvent this problem?

carsten
  • 2,966
  • It has to see an explicit and operator while parsing the content of \r then expands. It does not first expand and then checks the content. – percusse Nov 19 '16 at 15:11
  • How come it works in Marks answer here: http://tex.stackexchange.com/questions/339828/pgf-3d-pie-chart-revival? – carsten Nov 19 '16 at 15:12
  • That's an arc syntax not ellipse – percusse Nov 19 '16 at 15:15
  • I wasn't aware the expansion behavior is different between the two - why is that? – carsten Nov 19 '16 at 15:18
  • 3
    Only the developers can answer that I think. But the syntax for ellipse is the deprecated one, they recommend using [x radius=2,y radius=4] which is convenient in this case too since you can set the keys instead of a macro def – percusse Nov 19 '16 at 15:19
  • Doing \edef\r overwrites an existing macro within the current scope. \def followed by a single letter (or common word) macro name is never wise. – cfr Nov 20 '16 at 01:31
  • Note, from \path (or equivalent) to the terminating semicolon, tikz does its own parsing. To insert a latex command inside a path, use \pgfextra{...}. To insert a tikz command inside an option one should put it inside braces. – John Kormylo Nov 20 '16 at 17:55

1 Answers1

3

This issue is so omnipresent that PGF actually develops a canonical way to bypass it.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \edef\r{1 and 2}
  \draw (0,0) ellipse (2 and 4); % this works
  \edef\pgfmarshal{\noexpand\draw (0,0) ellipse (\r);}
  \pgfmarshal
\end{tikzpicture}
\end{document}

(there are 232 \pgf@marshal in the whole package.)

Symbol 1
  • 36,855