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'd like to have a macro to split up another macro content, with field separator being a space. So:

\def\mytext{foo bar}
\def\secondof#1 #2{#2}
\secondof\mytext

What? What do you mean: "runaway argument"? Oh right, I guess \mytext counts as only one argument and you're expecting two. Ok, so

\expandafter\secondof\mytext

and indeed, the result is "bar", just as I was hoping for.

But alas, then comes something rather surprising:

\def\firstof#1 #2{#1}
\expandafter\firstof\mytext

"fooar"? You got to be kidding me! How on earth did you—dear and beloved TeX—ever come to such a ridiculous decision? You did so well with the \secondof, after all. What gives?

(just to make this a complete MWE, I'm going to add a \bye here)

share|improve this question
add comment

1 Answer

up vote 11 down vote accepted

\firstof foo bar will simply take foo as first argument and b as second one. So the ar is left afterwards and will by typeset as ordinary text. For that reason you got foo + ar = fooar as result.

If you don't want this behaviour, you need to add an end delimiter, \nil or \@nil is often used for that purpose:

\def\firstof#1 #2\nil{#1}
\expandafter\firstof\mytext\nil

Now #1 will get foo and #2 will get all the rest until \nil, i.e. bar.

share|improve this answer
    
Ah, an end delimiter, ofcourse! Thanks! But how come the \secondof works as expected? –  morbusg Nov 27 '11 at 19:53
1  
@morbusg: Change the definition of secondof to \def\secondof#1 #2([[#2]]) and you'll see what is happening. –  Aditya Nov 27 '11 at 20:03
    
And more importantly, how did the #2 "bleed" into the #1? –  morbusg Nov 27 '11 at 20:09
    
\secondof did not worked as expected. \expandafter\secondof\mytext gives you only b. The ar is left and will be typeset as ordinary text, so the end result will be b+ar. (The same way \firstof gave you foo + ar = fooar.) Change \secondof to \def\secondof#1 #2{(#2)} and you'll see that only the b will be typeset in parens. –  Axel Sommerfeldt Nov 27 '11 at 20:19
    
facepalm. D'oh, now it's clear, thanks! –  morbusg Nov 27 '11 at 20:31
add comment

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.