2012年11月21日星期三

Multiple Optional Arguments for New Command Definition

The normal command defining methods, namely the "\newcommand", "\renewcommand", and "\providecommand", provide a optional argument session, where we can provide a default value for an argument, if the argument is not explicitly specified. Usually, the default value is used for the first argument "#1".

If you want to add more than one optional arguments, the following straightforward extension would cause a error:

\newcommand{\def}[3][default]{\textit{#1}+\textbf{#2}-\texttt{#3}}

One possible solution is to use the "relaying technique", which embeds one command into another, both of which contain an optional argument. As a result, the superior command will take two optional arguments to outward seeming. However, it is just a computational trick.

Also, attention should be paid when using the above method: the inferior command must be set at the end of the command definition for the superior one; its argument will also be attached after the argument of the superior one. Following is a simple example:


\newcommand\ABC[2][default1]{#1+\textbf{#2}}
\newcommand\DEF[1][default2]{#1-\ABC}

Then:


  • "\DEF{obligatory}" yields "default2-default1+obligatory"
  • "\DEF[real2][real1]{obligatory}" yields "real-real+obligatory"
  • "\DEF" yields an error

没有评论:

发表评论