2

Inside a command I would like to define multiple new commands. Their names are parametrized by arguments, but they should also be able to call each other during definition. Here is an example:

\documentclass{article}  

\newcommand{\defFooAndBar}[2]{%
    \expandafter\newcommand\csname foo#1\endcsname{#2}
    \expandafter\newcommand\csname bar#1\endcsname{let us expand \foo#1 and show #2.}
}

\defFooAndBar{One}{the second argument}
\defFooAndBar{Two}{the second argument}

\begin{document}  

\fooOne
\barOne
\fooTwo
\barTwo

\end{document} 

However, there is an error generated:

! Undefined control sequence. \barOne ->let us expand \foo One and show the argument.

Apparently, Latex puts a blank space after \foo and therefore \foo#1 is not treated as a single entity. Is it possible to indicate the parser that they belong together?

  • It should be \csname foo#1\endcsname in the second line of the definition. – egreg Mar 30 '15 at 9:17
1

TeX works strictly with tokens. In your code

let us expand \foo#1 and show #2.

\foo makes a single token and #1 is a parameter token that will be replaced by the actual argument at macro call. So when you do

\defFooAndBar{One}{the second argument}

the second command is defined as

let us expand \foo One and show the second argument

(the space is just to show where one token ends).

Solution: form the token with \csname...\endcsname just as you do for building the tokens to be defined:

\newcommand{\defFooAndBar}[2]{%
    \expandafter\newcommand\csname foo#1\endcsname{#2}%
    \expandafter\newcommand\csname bar#1\endcsname{let us expand \csname foo#1\endcsname and show #2.}%
}

No \expandafter is needed here; it is necessary instead for forming the token \fooOne (or similar) before \newcommand enters into action.

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.