[Tex/LaTex] Defining a newcommand with sub- or superscript and avoiding “double subscript” error

subscriptssuperscripts

I often use shortcuts defined via \newcommand. However sometimes it causes a "double subscript" problem if a shortcut contains a subscript and I try to add one more subscript when using it.

I am aware of all kinds of workarounds, as illustrated in the example below. But what is the most robust way to define such shortcuts?

Example of the code:

\documentclass{article}
% define some shortcuts
\newcommand\xa{x_a}
\newcommand\xb{{x_b}}

\def\cmpto{\quad\textrm{compare to}\quad}

\begin{document}

% this produces a "double subscript" error
%\[  \xa_i   \]

This is a workaround, which produces a good result
\[    \xa{}_i \cmpto x_{ai}    \]

But still not ideal: watch the position of the superscript
\[    \xa{}_i^2 \cmpto x_{ai}^2    \]

The \verb+{x_b}+ below produces no error, but does not look good 
(watch the baseline of the subscripts)
%
\[    \xb_i \cmpto x_{bi}    \]

Also superscript does not look good
%
\[    \xb^2 \cmpto x_b^2    \]

\end{document}

enter image description here

Best Answer

This works so long as you put always subscripts next to the newly defined commands:

\documentclass[a4paper]{article}

\makeatletter
\newcommand\newsubcommand[3]{\newcommand#1{#2\sc@sub{#3}}}
\def\sc@sub#1{\def\sc@thesub{#1}\@ifnextchar_{\sc@mergesubs}{_{\sc@thesub}}}
\def\sc@mergesubs_#1{_{\sc@thesub#1}}
\makeatother

\newsubcommand{\xa}{x}{a}

\begin{document}
$\xa$

$\xa_i x_{ai}\xa^2 x_a^2$
\end{document}

It might be extended to support \xa^2_i, but it doesn't seem a good idea to add complications.

Explanation
The command \newsubcommand defines an abbreviation where the first argument is the command to define, the second is the main letter and the third is the fixed subscript.

The macro \xa defined in the example will look whether the following character is _ and, if so, it will merge the subscripts.