4

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:

output of example

4

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.

enter image description here

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}
| improve this answer | |
  • Hello. What is the best method between xparse and etoolbox ? – projetmbc Jul 13 at 12:32
3

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} 

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.