My \john
command is defined like so:
\def\john{\DontExpandMe}
I would now like to repeatedly change its definition, to keep adding some extra stuff on the front.
\foreach\i in {ape,bat,cow,dog} {
\xdef\john{\i,\unexpanded{\john}}
\show\john
}
My intention is that the \show\john
command at each iteration should result in:
\john=macro: -> \DontExpandMe.
\john=macro: -> ape,\DontExpandMe.
\john=macro: -> bat,ape,\DontExpandMe.
\john=macro: -> cow,bat,ape,\DontExpandMe.
\john=macro: -> dog,cow,bat,ape,\DontExpandMe.
That is to say, I would like \john
to be "partially expanded" in some sense. But I can't make that work. I have tried the following
- If I use an
\xdef
, then the whole command is expanded, including the\DontExpandMe
part. - If I just use a
\gdef
, then the\i
is not expanded. - If I use
\xdef
with\unexpanded{...}
around\john
(as I have in my current code) then I get\john=macro: -> ape,\john.
and\john=macro: -> bat,\john.
and so on.
Here is my code.
\documentclass{article}
\usepackage{pgffor}
\begin{document}
\def\john{\DontExpandMe}
\show\john
\foreach\i in {ape,bat,cow,dog} {
\xdef\john{\i,\unexpanded{\john}}
\show\john
}
\end{document}
Best Answer
The line in question is:
\i
should expanded (full/once?) and\john
should be expanded oncePartial expansion with
\xdef
and\unexpanded
:Before
\unexpanded
reads the open curly brace, it is in expanding mode for gobbling spaces. Therefore it can be used to sneak in a\expandafter
:(Without this trick, two
\expandafter
would be needed:The same can also be achieved without e-TeX by using a token register:
The contents of the token register is not further expanded inside
\edef
.One expansion step for
\i
and\john
:Same as above, but for
\i
, too:\expandafter
orgy with\gdef
:First
\john
is expanded once, then\i
.