TeX/expandafter
Synopsis
[edit | edit source]\expandafter <macro> <tokens>
Description
[edit | edit source]The \expandafter command delays expanding a macro until its arguments have been expanded.
Examples
[edit | edit source]\def\a[#1]{A's argument was `#1'}
\def\args{[FOO]}
\a\args
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
\expandafter\a\args
This expands \args
before \a
, as if we had written the following in the first place:
\a[FOO]
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 invocations
[edit | edit source]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} }
\def\mycommandcontents{\onelevelexpanded}
\ea\def\ea\pra\ea{\mycommandcontents}
This expands \mycommandcontents
only once (in contrast to TeX/edef).