42

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

我已经读过默认值应该是\@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

4 回答 4

60

尝试以下测试:

\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提供\ifthenelse构造和\isempty测试。

另一种选择是使用该ifmtarg软件包(请参阅ifmtarg.sty文件以获取文档)。

于 2010-01-27T08:06:45.083 回答
12

使用 LaTeX3 xparse 包:

\usepackage{xparse}
\NewDocumentCommand\optarg{g}{%
  \IfNoValueF{#1}{(((#1)))}%
}
于 2010-01-27T08:23:47.320 回答
9

在编写 LaTeX 的底层 TeX 引擎中,命令可以采用的参数数量是固定的。你对默认值所做的[\@empty]就是让 LaTeX 检查下一个标记,看它是否是一个开放的方括号[。如果是这样,LaTeX 将方括号的内容作为参数,如果不是,则将下一个标记放回输入流中,并使用默认\@empty参数代替。因此,为了让您的想法发挥作用,您必须使用括号来分隔可选参数(如果存在):

\optarg
\optarg[]
\optarg[test]

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

令人讨厌的是,您不能对可选参数使用与必需参数相同的括号,但事实就是如此。

于 2010-01-27T02:26:51.427 回答
3
\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}
于 2011-07-13T10:25:56.607 回答