我想创建一个有两个参数,其中一个可选LaTeX指令。一般情况下我这样做,因为

\newcommand{\whatever}[2][default]{first #1 second #2}

其中default为第一个参数的默认值。但对于这个命令我想要的第二个参数的值被用作第一个参数的默认值 - 即,我想

\whatever{blah}
\whatever{foo}
\whatever[lol]{rofl}

等同于

\whatever[blah]{blah}
\whatever[foo]{foo}
\whatever[lol]{rofl}

有谁知道如何做到这一点?我可以在必要时下降到纯的TeX。

有帮助吗?

解决方案

在乳胶内核有这样做的一个内置的方法中,虽然它没有被广泛使用。下面是一个例子:

\makeatletter
\newcommand\@foo[2][]{[1: #1, 2: #2.] }
\newcommand\foo{\@dblarg\@foo}
\makeatother

\foo{same}
\foo[hello]{world}

显然,\makeatletter命令可以被丢弃,如果你是一个.sty.cls文件中这样做。

其他提示

这是难看的黑客:

\usepackage{ifthen}

...

\newcommand{\whatever}[2][uniquenonesense]{
   ... 
   \ifthenelse{\equal{#2}{uniquenonesense}}{#1}{#2}
   ...
}

大概你想要的东西更清洁,但是这是我得到了什么。

根据您的语义,uniquenonesense可能是空的。

    \newcommand{\haha}[2]{\backslash whatever \left[ #1 \right] 
    \left[   #1     \right] }

    \begin{document}
    $\haha{blah}{blah}$\\
    $\haha{stupid}{Idiot}$
    \end{document} % This works very well.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top