< TeX


\expandafter <macro> <tokens>


The \expandafter command delays expanding a macro until its arguments have been expanded.


\def\a[#1]{A's argument was `#1'}

will not work, saying "! Use of \a doesn't match its definition." This is because while defining \a, the first argument (denoted #1) appeared in square braces. Therefore, \a expects its first argument to appear in square braces, while in \a\args, the immediate character after \a is not a left square bracket. Using \expandafter, we can write


This expands \args before \a, as if we had written the following in the first place:


As a result, TeX will print A's argument was `FOO'.

The \expandafter command first expands the tokens following <macro>, and then expands <macro>, with the expanded <tokens> following it as if they had been typed in the file.

Multiple invocationsEdit

One sometimes sees long chains of expandafters, which can normally be read as "expand after N", e.g.

% Chain of expandafters leads to \pra having definition ``\onelevelexpanded''
\def\onelevelexpanded{Page={\the\count0} }

This expands \mycommandcontents only once (in contrast to TeX/edef).


See Stephan Bechtolsheim's article.