[Tex/LaTex] Double superscript/subscript issue with macros

subscripts

I would like to be able to define a macro like \newcommand{\Zs}{Z^*} and then somewhere within the text say $\Zs^T$ and have the effect of writing $Z^{* T}$. It should also be possible to write $\Zs$ without the subscript. Is there a simple solution to make this possible? Preferably, the solution should allow one to do this for many symbols with relative ease.

I guess one way is to define a macro with an argument like \newcommand{\Zss}[1]{Z^{* #1}} and the use either $\Zss{}$ or $\Zss{T}$, but this does not seem very elegant.

Can we define a blueprint command, called starred so that whenever we want a starred symbol, we can write \newcommand\Xs{\starred{X}}?

Best Answer

You have to be disciplined and write, if a subscript is needed,

\Zs^{<superscript>}_{<subscript>}

Here's the code:

\documentclass{article}

\makeatletter
\newcommand{\passerby@genericstarred}[1]{%
  #1\@ifnextchar^\passerby@eathat{^*}%
}
\def\passerby@eathat#1#2{% #1 is ^
  ^{*#2}%
}
\newcommand{\definegenericstarred}[1]{%
  \@for\next:=#1\do{%
    \expandafter\edef\csname\next s\endcsname{%
      \noexpand\passerby@genericstarred{\next}}%
  }%
}
\makeatother

\definegenericstarred{X,Y,Z,W}

\begin{document}
$\Xs+\Zs^T+\Ws+\Ys^2$
\end{document}

The same with LaTeX3:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\definegenericstarred}{m}
 {
  \clist_map_inline:nn { #1 }
   {
    \cs_new_protected:cpn { ##1s } { \passerby_generic_starred:n { ##1 } }
   }
 }

\cs_new_protected:Npn \passerby_generic_starred:n #1
 {
  #1 % print the main letter
  \peek_catcode_remove:NTF ^ % check if a ^ follows 
   { \passerby_add_star:n }  % yes, add the * to the explicit superscript
   { ^{*} }                  % no, just add the *
 }
\cs_new_protected:Npn \passerby_add_star:n #1
 {
  ^{*#1} % the final superscript
 }
\ExplSyntaxOff

\definegenericstarred{X,Y,Z,W}

\begin{document}
$\Xs+\Zs^T+\Ws+\Ys^2$
\end{document}

enter image description here