6

I'm trying to write a command that will declare another command with a name that will be based on the input given to the outer command: e.g.

\newcommand{\buildcommand}[1]{
  \newcommand{\someprefix#1}{do stuff}
}

But this doesn't seem to work as I keep getting errors. How should I go about getting this to work?

gablin
  • 17,006

1 Answers1

6

You need to build the name of the command sequence first before you can define the command with \newcommand. This is done with \csname <macro name without leading backslash>\endcsname. Since \csname needs to be expanded before \newcommand (you don't want to define \csname itself) an \expandafter is needed:

\newcommand{\buildcommand}[1]{%
  \expandafter\newcommand\csname someprefix#1\endcsname{do stuff}%
}

If you want to keep the braces around the new command name you need to “step over them” with another \expandafter:

\newcommand{\buildcommand}[1]{%
  \expandafter\newcommand\expandafter{\csname someprefix#1\endcsname}{do stuff}%
}

I also added % at the end of the first two lines of the definition in order to avoid spurious spaces, see Why the end-of-line % in macro definitions? and What is the use of percent signs (%) at the end of lines? for further explanation on that.

cgnieder
  • 66,645
  • I'd mention \@namedef. – egreg Jun 11 '13 at 17:40
  • @egreg I thought about that but left it out because it hasn't \newcommand's checks... And since it is unclear what the code is supposed to do in the end I was being lazy, anyway... – cgnieder Jun 11 '13 at 17:47