4

I have a number of commands with the same structure as this one and I'm wondering whether or not the code can be compacted to avoid having to type the E_{K and K_{\symup{trans} twice each. I don't see a way to do it without creating problems with breaking the grouping.

My MWE:

% !TEX TS-program = lualatexmk
% !TEX encoding = UTF-8 Unicode

\documentclass{article} % xparse is now automatically loaded

\NewDocumentCommand{\translationalkineticenergy}{ s d[] }{% % d[] must be used because of the way consecutive optional % arguments are handled. See xparse docs for details. \IfBooleanTF{#1}% {% We have a . \IfValueTF{#2}% {% E_{K{\symup{,}#2}}% }% {% E_{K}% }% }% {% We don't have a . \IfValueTF{#2}% {% K_{\symup{trans}{\textnormal{,}#2}}% }% {% K_{\symup{trans}}% }% }% }%

\begin{document}

( \translationalkineticenergy \quad \translationalkineticenergy[\symup{final}] \quad \translationalkineticenergy* \quad \translationalkineticenergy*[\symup{final}] )

\end{document}

UPDATE: While I was waiting I got it down to this new MWE.

% !TEX TS-program = lualatexmk
% !TEX encoding = UTF-8 Unicode

\documentclass{article} % xparse is now automatically loaded

\NewDocumentCommand{\translationalkineticenergy}{ s d[] }{% % d[] must be used because of the way consecutive optional % arguments are handled. See xparse docs for details. \IfBooleanTF{#1}% {% We have a . E_{K{\IfValueT{#2}{\symup{,}#2}}} }% {% We don't have a . K_{\symup{trans}\IfValueT{#2}{\symup{,}#2}} }% }%

\begin{document}

( \translationalkineticenergy \quad \translationalkineticenergy[\symup{final}] \quad \translationalkineticenergy* \quad \translationalkineticenergy*[\symup{final}] )

\end{document}

1 Answers1

3

There are two simplifications possible here. First is in

    \IfValueTF{#2}%
    {% 
      E_{K{\textnormal{,}#2}}%
    }%
    {% 
      E_{K}%
    }%

The difference between the two branches is that for true you have an extra {\textnormal{,}#2}, you can put the test inside the subscript:

      E_{K%
         \IfValueT{#2}{\textnormal{,}#2}%
        }%

The second one is a bit trickier. You see, after TeX sees a subscript (or superscript) token, the { doesn't have to be an explicit brace: it can be an implicit one, and implicit braces don't count for brace-balancing. Both these do the same:

a_{bc}
a_\bgroup bc\egroup

so you can do that in your macro:

\NewDocumentCommand{\translationalkineticenergy}{ s d[] }{%
  % d[] must be used because of the way consecutive optional
  %  arguments are handled. See xparse docs for details.
  \IfBooleanTF{#1}%
    {E_\bgroup K}% We have a *.
    {K_\bgroup \textnormal{trans}}% We don't have a *.
         \IfValueT{#2}{\textnormal{,}#2}%
       \egroup
  }%

note that you have two \bgroup in there, but only one \egroup, and that's fine because only one of the two \bgroup will be actually seen.