newcommand 和可选参数的问题

newcommand 和可选参数的问题

我想要一个执行以下操作的命令:

\documentclass[a4paper]{letter}
\newcommand{\stuffing}[2][]{\ensuremath{W_{\mathtt{#2}}^{^{\left[#1\right]}}}}

\begin{document}
what I want: $W_\mathtt{a}$ and \stuffing[5]{a}

but what I get: \stuffing{a} and \stuffing[5]{a}
\end{document}

那么,有没有办法只在包含可选参数时包含括号?或者我应该在添加上标时添加新注释?因为我无法输入以下内容:\stuffing[\left[5\right]]{a}

示例输出:

示例输出

答案1

您想测试可选参数是否为空:

\documentclass[a4paper]{article}

\newcommand{\stuffing}[2][]{%
  W_{\mathtt{#2}}%
  \if\relax\detokenize{#1}\relax
  \else
    ^{^{[#1]}}%
  \fi
}

\begin{document}
what I want: $W_\mathtt{a}$ and $\stuffing[5]{a}$

but what I get: $\stuffing{a}$ and $\stuffing[5]{a}$
\end{document}

我删除了它,因为这是数学,所以它应该被适当分离,如果不使用几次,\ensuremath你收获的就很少。$...$

在此处输入图片描述

xparse可以使用o参数类型:

\documentclass[a4paper]{article}
\usepackage{xparse}

\NewDocumentCommand{\stuffing}{om}{%
  W_{\mathtt{#2}}%
  \IfValueT{#1}{^{^{[#1]}}}%
}

\begin{document}
what I want: $W_\mathtt{a}$ and $\stuffing[5]{a}$

but what I get: $\stuffing{a}$ and $\stuffing[5]{a}$
\end{document}

答案2

etoolbox

\documentclass[a4paper]{letter}
\usepackage{etoolbox}
\newcommand{\stuffing}[2][]{\ensuremath{W_{\mathtt{#2}}\ifblank{#1}{}{^{^{\left[#1\right]}}}}}

\begin{document}

what I want: $W_\mathtt{a}$ and \stuffing[5]{a}

and what I get: \stuffing{a} and \stuffing[5]{a}

\end{document} 

在此处输入图片描述

相关内容