9

I've got an expansion issue with the following code:

\def\sizes{huge, LARGE, Large, large, normalsize, small, footnotesize, scriptsize, tiny}
\forcsvlist\sampletext{\sizes}

My problem is that \sizes should be expanded before being passed to \forcsvlist, otherwise \sampletext will simply receive the list and not know how to parse it.

How can I make it so that \sizes is expanded?

Note: Putting the list hardcoded in the \sampletext call works, but I don't want to do that because I might override \sizes with other values.

13

This is the standard way:

\expandafter\forcsvlist\expandafter\sampletext\expandafter{\sizes}

The first \expandafter expands the second one, which in turn expands the third and this last does the job, expanding \sizes. The primitive \expandafter expands to nothing, after having caused the expansion of the second token after it; just jump over one token, when checking the action of \expandafter. It's a bit more complicated when there are arguments, but \expandafter and \sizes don't take them. The expansion performed by \expandafter is only one step: after

\def\y{\z} \def\z{a}

saying

\expandafter\x\y

is like saying

\x\z

In your case the three \expandafter commands vanish, but TeX now has

\forcsvlist\sampletext{huge,LARGE,...}

and continues expanding from here.

Another trick is

\begingroup\edef\x{\endgroup\noexpand\forcsvlist\noexpand\sampletext{\sizes}}\x

which works because the expansion of \sizes consists of characters; it wouldn't if \sizes had been defined as

\def\sizes{\huge,\LARGE,...}
  • \expandafter is still something a bit hard for me to grasp. I don't get why I have to use 3 of them. – ℝaphink Jul 5 '11 at 15:48
  • See edited answer – egreg Jul 5 '11 at 15:58
  • Any explanation about the "Another trick", I don't quite understand them, thanks. – ollydbg23 May 8 '14 at 2:52
  • 1
    @ollydbg23 This defines \x to expand to \endgroup\forcsvlist{<full expansion of \sizes>}; executing \x will close the group started with \begingroup and do \forcsvlist. – egreg May 8 '14 at 7:25
  • @egreg thanks, why \noexpand is put before {\sizes}? I generally think I need not a \noexpand before {\sizes}, because I can let \edef to expand the {\sizes} to {<full expansion of \sizes>}. – ollydbg23 May 8 '14 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.