Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I thought I had understood the principle of expansion ... but apparently not!

\def\a{AAA}
\def\b{BBB}   

\expandafter\detokenize\expandafter{\a\b}

I thought that the 2 \expandafter would store \detokenize and {} resp. and then expand \a into AAA and \b into BBB. Therefore after one round of expansion, we would have:

\detokenize{AAABBB}

and thus the output should be simply "AAABBB". But it is not the case. Where is my mistake?

share|improve this question
2  
Question titles must summaries the question. Please avoid titles which would fit 1000 largely different questions. –  Martin Scharrer Jun 9 '12 at 8:58
4  
\expandafter jumps over one token, expands once the following one (if it's expandable, otherwise nothing happens) and vanishes. –  egreg Jun 9 '12 at 9:20
    
You might be looking for \expandnext from etextools, which in your case could be used as \expandnext\detokenize\a\b. –  dgs Jun 9 '12 at 10:41

1 Answer 1

up vote 18 down vote accepted

\expandafter stores exactly one token. So the expansion order is \expandafter-\expandafter-\a.

After this everything is restored and \detokenize is executed.

This is the reason why you sometimes see crazy successions of \expandafter: To reverse the expansion order of n tokens you basically need 2^n-1 \expandafters. At least you don't need \expandafter before \detokenize because it will initiate expansion looking for its argument.

So

\detokenize\expandafter\expandafter\expandafter{\expandafter\a\b}

gives the expansion order you need: \expandafter-\expandafter-\expandafter-\b. After restoring there is

\detokenize\expandafter{\a BBB}

finally yielding the desired output.

In case your're interested in always fully expanding the contents of {} (whatever they are), you can't (in general). Depending on a concrete context, there may be alternatives. So if this answer is not what you were looking for, please elaborate.

share|improve this answer
1  
I've found Stephan Bechtolsheim's TUGboat article to be helpful on this topic, maybe you could include it as a reference showing more examples. (@nicolasroy) –  dgs Jun 9 '12 at 10:43
    
Thanks for the info. I simply had a wrong understanding of the expansion process. –  nicolas roy Jun 11 '12 at 8:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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