# treat newcommand as a symbol

I have defined a \newcommand

\newcommand{\pt}{\ensuremath{p_{T}}\xspace}


I would like to write

For this I try:

$$\pt_{,a}$$


The error for this approach is:

! Double subscript.


If I try

$${\pt}_{,a}$$


the result is not what is expected:

Is it possible to treat the result of \pt as a symbol in order to add a subscript, or is there any other solution that does not require cloning the contents of \pt into the equation?

• You can make \pt a math atom by wrapping it in, for instance \mathord: \newcommand{\pt}{\mathord{\ensuremath{p_{T}}}\xspace}, or \mathop, depending on what it means... – Phelype Oleinik Oct 29 '18 at 12:14
• @PhelypeOleinik, your solution adds \xspace into the combined subscript. – Viesturs Oct 29 '18 at 12:17
• Sorry, I don't know what would be the correct placement for \xspace here... I would go for a command that uses \xspace only if not in math-mode. Or better, I wouldn't use \xspace at all. And I would insert a negative kern before the _{,a} ;) – Phelype Oleinik Oct 29 '18 at 12:30

It's easy with the “embellishment” argument type of xparse:

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\pt}{e{_}}{%
\IfNoValueTF{#1}{p^{}_{T}}{p^{}_{T,#1}}%
}

\begin{document}

$\pt$

$\pt_{a}$

\end{document}


I left out \ensuremath and \xspace, of course; such a command is for math, so there's no reason to allow it outside math formulas. And this avoids all the quirks associated to \xspace (which sometimes works and sometimes doesn't).

In this particular case you may want to tuck the comma a bit into T:

\NewDocumentCommand{\pt}{e{_}}{%
\IfNoValueTF{#1}{p^{}_{T}}{p^{}_{T,#1}}%
}


The same output as in the second case can also be obtained with “classical” methods:

\makeatletter
\newcommand{\pt}{\@ifnextchar_{\pt@plus}{p^{}_{T}}}
\def\pt@plus_#1{p^{}_{T\!,#1}}
\makeatother


The simplest variation on your MWE that I can think of is

\newcommand*{\pt}[1]{\ensuremath{p_{T,#1}}\xspace}


which you could then invoke as

\pt{a}

• I wouldn't use neither \ensuremath nor \xspace in such a definition. – Ulrike Fischer Oct 29 '18 at 12:49