6

This question already has an answer here:

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?

marked as duplicate by Werner, egreg, Martin Schröder, mafp, Claudio Fiandrino Jun 11 '13 at 18:02

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • you need to build the csname first: \newcommand{\buildcommand}[1]{\expandafter\newcommand\csname someprefix#1\endcsname{do stuff}} – clemens Jun 11 '13 at 16:19
  • @cgnieder why not turning your comment into an answer? – Gonzalo Medina Jun 11 '13 at 16:33
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.

  • 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... – clemens Jun 11 '13 at 17:47

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