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?

2

1 Answer 1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .