这个代码还能更紧凑一些吗?

这个代码还能更紧凑一些吗?

我有许多与此结构相同的命令,我想知道是否可以压缩代码以避免必须输入两次E_{KK_{\symup{trans}。我看不出有什么方法可以做到这一点而不产生破坏分组的问题。

我的 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}

更新:在我等待的时候,我得到了这个新的 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

这里有两种简化方法。第一种是

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

这两个分支的区别在于,如果true您有一个额外的{\textnormal{,}#2},您可以将测试放在下标内:

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

第二个有点棘手。您会看到,在 TeX 看到下标(或上标)标记后,括号{不必是显式括号:它可以是隐式括号,并且隐式括号不计入括号平衡。这两个都做同样的事情:

a_{bc}
a_\bgroup bc\egroup

因此您可以在宏中执行此操作:

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

\bgroup请注意,其中有两个,但只有一个,这没问题,因为实际上只能看到\egroup其中一个。\bgroup

相关内容