我希望使用\newcommand
inside \newcommand
。我可以做一个基本的版本,但我无法弄清楚的一点是如何为 inner 构造一个非平凡的名称\newcommand
(即通过在 outer 的参数前添加前缀\newcommand
)。
举一个最简单的例子来说明这个问题:
\documentclass{report}
\newcommand{\defpill}[3]{
\newcommand{\blue#1}{#2}
\newcommand{\red#1}{#3}
}
\begin{document}
Let me define a pill (with apologies to chemists).
\defpill{aspirin}{$A_2Sp_3$}{$A_2Sp_5$}
This should not print anything.
But I should now be able to use my new commands, for example the one
giving the formula of the red aspirin: \redaspirin. Or the blue one:
\blueaspirin.
\end{document}
我怀疑不起作用的部分是内部命令的变量名称(\blue#1
等)。一个更简单的例子是内部命令的名称可以正常#1
工作,但我必须提供两个名称,而不是用\defpill
一个后缀为我构建它们。
我怎么做?
答案1
\csname
是你的朋友:
\documentclass{report}
\newcommand{\defpill}[3]{%
\expandafter\newcommand\csname blue#1\endcsname{#2}%
\expandafter\newcommand\csname red#1\endcsname{#3}%
}
\begin{document}
Let me define a pill (with apologies to chemists).%
\defpill{aspirin}{$A_2Sp_3$}{$A_2Sp_5$}
This should not print anything.
But I should now be able to use my new commands, for example the one
giving the formula of the red aspirin: \redaspirin. Or the blue one:
\blueaspirin.
\end{document}
答案2
根据 egreg 对我更复杂问题的回答这里,您还应该考虑使用\@namedef
:
\documentclass{report}
\makeatletter
\newcommand{\defpill}[3]{%
\@namedef{blue#1}{#2}%
\@namedef{red#1}{#3}%
}
\makeatother
\begin{document}
Let me define a pill (with apologies to chemists).%
\defpill{aspirin}{$A_2Sp_3$}{$A_2Sp_5$}
This should not print anything.
But I should now be able to use my new commands, for example the one
giving the formula of the red aspirin: \redaspirin. Or the blue one:
\blueaspirin.
\end{document}