代码之家  ›  专栏  ›  技术社区  ›  David Z

LaTeX:如何使用必需的参数作为可选参数的默认值?

  •  3
  • David Z  · 技术社区  · 17 年前

    我试图创建一个带有两个参数的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}
    

    有人知道怎么做吗?如有必要,我可以降到普通特克斯。

    3 回复  |  直到 17 年前
        1
  •  6
  •   Will Robertson    17 年前

    LaTeX内核有一个内置的方法来实现这一点,尽管它没有被广泛使用。下面是一个例子:

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

    显然 \makeatletter .sty .cls 文件

        2
  •  2
  •   dmckee --- ex-moderator kitten    17 年前

    丑陋的黑客:

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

    根据你的语意, uniquenonesense

        3
  •  0
  •   vaman    9 年前
        \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.