[Tex/LaTex] Partially expanding a command

expansionmacrostex-core

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:

\xdef\john{\i,\unexpanded{\john}}

\i should expanded (full/once?) and \john should be expanded once

Partial 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:

\xdef\john{\i,\unexpanded\expandafter{\john}}

(Without this trick, two \expandafter would be needed:

\xdef\john{\i,\expandafter\unexpanded\expandafter{\john}}

The same can also be achieved without e-TeX by using a token register:

\toks0=\expandafter{\john}% similar trick as above to minimize the number of \expandafter
\xdef\john{\i,\the\toks0}

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:

    \xdef\john{\unexpanded\expandafter{\i},\unexpanded\expandafter{\john}}
    
  • \expandafter orgy with \gdef:

    \expandafter\expandafter\expandafter\gdef
    \expandafter\expandafter\expandafter\john
    \expandafter\expandafter\expandafter{%
      \expandafter\i\expandafter,\john
    }
    

    First \john is expanded once, then \i.

Related Question