# Problem with newcommand and the optional argument

I want to have a command that does the following:

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


So, is there a way to include the brackets only when the optional argument is included? Or should I just make a new comment when the superscript is added? Since I cannot enter this: \stuffing[\left[5\right]]{a}

output of the example:

You want to test whether the optional argument is empty or not:

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


I removed \ensuremath because that's math and so it should be properly segregated and you gain very little in not using $...$ a few times.

With xparse you can use the o argument type:

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

• Hello. What is the best method between xparse and etoolbox ? Jul 13, 2020 at 12:32

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