代码之家  ›  专栏  ›  技术社区  ›  kolypto

LaTex\NewCommand默认参数:为空?

  •  36
  • kolypto  · 技术社区  · 15 年前

    我正在尝试编写一个简单的示例命令,它不带参数就不打印任何内容,但使用一个参数,它会用一些东西包围它。

    我已经读到默认值应该是 \@empty 简单的 \ifx\@empty#1 条件应该可以做到:

    \newcommand{\optarg}[1][\@empty]{%
    \ifx\@empty#1  {}  \else  {(((#1)))}  \fi
    }
    
    \optarg % (((empty)))
    \optarg{} % (((empty)))
    \optarg{test} % (((empty))) test
    

    后三个命令全部打印 empty 因为某种原因,我希望前两个不打印,最后一个不打印 (((test))) .

    我在使用TexLive/Ubuntu。一个想法?

    4 回复  |  直到 14 年前
        1
  •  45
  •   godbyk    15 年前

    尝试以下测试:

    \documentclass{article}
    
    \usepackage{xifthen}% provides \isempty test
    
    \newcommand{\optarg}[1][]{%
      \ifthenelse{\isempty{#1}}%
        {}% if #1 is empty
        {(((#1)))}% if #1 is not empty
    }
    
    \begin{document}
    
    Testing \verb|\optarg|: \optarg% prints nothing
    
    Testing \verb|\optarg[]|: \optarg[]% prints nothing
    
    Testing \verb|\optarg[test]|: \optarg[test]% prints (((test)))
    
    \end{document}
    

    这个 xifthen package 提供 \ifthenelse 构造和 \isempty 测试。

    另一种选择是使用 ifmtarg 包装(见 ifmtarg.sty file 文件)。

        2
  •  11
  •   Joseph Wright    15 年前

    使用latex3 xparse包:

    \usepackage{xparse}
    \NewDocumentCommand\optarg{g}{%
      \IfNoValueF{#1}{(((#1)))}%
    }
    
        3
  •  8
  •   Norman Ramsey    15 年前

    在编写LaTex的底层Tex引擎中,命令可以接受的参数数量是固定的。你对违约的处理 [\@empty] 是让乳胶检查下一个令牌,看看它是否是一个方括号 [ .如果是这样,则LaTex将方括号的内容作为参数,如果不是,则将下一个标记放回输入流中,并使用默认值 \@empty 改为使用参数。所以要想让你的想法生效,你必须使用 广场 括号分隔可选参数(如果存在):

    \optarg
    \optarg[]
    \optarg[test]
    

    你应该对这个符号有更好的运气。

    你不能用同样的括号来表示可选参数,这很烦人,因为你用括号来表示必需的参数,但事实就是这样。

        4
  •  3
  •   barraq Ascendant    14 年前
    \documentclass{article}
    
    \usepackage{ifthen} % provides \ifthenelse test  
    \usepackage{xifthen} % provides \isempty test
    
    \newcommand{\inlinenote}[2][]{%
        {\bfseries{Note:}}%  
        \ifthenelse{\isempty{#1}}  
                {#2}               % if no title option given
                {~\emph{#1} #2}    % if title given
    }
    
    \begin{document}
    
    \inlinenote{
        simple note
    }
    
    \inlinenote[the title]{
        simple note with title
    }
    
    \end{document}