我想使用该xparse
包定义一个带有可选参数的新命令。请考虑以下示例:
\documentclass{minimal}
\usepackage{xparse}
\DeclareDocumentCommand{\mycommand}{ O{mydefault} m o o o }{%
p:#2%
\IfNoValueTF{#3}%
{}%
{ p:#3}%
\IfNoValueTF{#4}%
{}%
{ p:#4}%
\IfNoValueTF{#5}%
{}%
{ p:#5}
p:#1
}
\begin{document}
\mycommand[one]{two} \par % p:two p:one
\mycommand[one]{two}[three] \par % p:two p:three p:one
\mycommand[one]{two}[three][four] \par % p:two p:three p:four p:one
\mycommand[one]{two}[three][four][five] \par % p:two p:three p:four p:five p:one
\mycommand[one]{two}[three][][five] \par % p:two p:three p: p:five p:one
\mycommand[one]{two}[][][five] % p:two p: p: p:five p:one
\end{document}
现在的问题是,当我在两个已填写的参数之间留空一些参数时,LaTeX 也会显示这些空参数。应用于最后一个例子,我想得到p:two p:five p:one
。
答案1
您必须对指定为 的参数进行额外比较[]
,因为从技术上讲,这与 不同\NoValue
。而且,您不能直接将它们排除在外,因为后续可选参数将按顺序使用。您可以使用ifmtarg
包裹:
\documentclass{minimal}
\usepackage{xparse}% http://ctan.org/pkg/xparse
\usepackage{ifmtarg}% http://ctan.org/pkg/ifmtarg
\makeatletter
\DeclareDocumentCommand{\mycommand}{ O{mydefault} m o o o }{%
p:#2%
\IfNoValueTF{#3}%
{}%
{\@ifmtarg{#3}{}{ p:#3}}%
\IfNoValueTF{#4}%
{}%
{\@ifmtarg{#4}{}{ p:#4}}%
\IfNoValueTF{#5}%
{}%
{\@ifmtarg{#5}{}{ p:#5}}
p:#1
}
\makeatother
\begin{document}
\mycommand[one]{two} \par % p:two p:one
\mycommand[one]{two}[three] \par % p:two p:three p:one
\mycommand[one]{two}[three][four] \par % p:two p:three p:four p:one
\mycommand[one]{two}[three][four][five] \par % p:two p:three p:four p:five p:one
\mycommand[one]{two}[three][][five] \par % p:two p:three p:five p:one
\mycommand[one]{two}[][][five] % p:two p:five p:one
\end{document}
答案2
无需其他包,你可以自己定义一个测试
\makeatletter
\def\IfEmptyTF#1{%
\if\relax\detokenize{#1}\relax
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother
\DeclareDocumentCommand{\mycommand}{ O{mydefault} m O{} O{} O{} }{%
p:#2%
\IfEmptyTF{#3}%
{}%
{ p:#3}%
\IfEmptyTF{#4}%
{}%
{ p:#4}%
\IfEmptyTF{#5}%
{}%
{ p:#5}
p:#1
}
问题是,\NoValue
如果可选参数是不是指定;但[]
意味着“可选参数为空”。
LaTeX3 包中已经提供了对空性的测试,因此其定义可以改为
\ExplSyntaxOn
\cs_set_eq:NN \IfEmptyTF \tl_if_blank:nTF
\ExplSyntaxOff