繁体   English   中英

LaTeX \ newcommand默认参数:是空的?

[英]LaTeX \newcommand default argument: is empty?

我正在尝试编写一个简单的示例命令,在没有参数的情况下打印任何内容,但是使用参数将其包围起来。

我已经读过默认值应该是\\@empty而simple \\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。 一个想法?

尝试以下测试:

\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文件以获取文档)。

使用LaTeX3 xparse包:

\usepackage{xparse}
\NewDocumentCommand\optarg{g}{%
  \IfNoValueF{#1}{(((#1)))}%
}

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

\optarg
\optarg[]
\optarg[test]

你应该用这种表示法获得更好的运气。

令人讨厌的是,您不能使用相同的括号作为可选参数,因为您使用了必需的参数,但这就是它的方式。

\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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM