6

I want to use sub- and superscript together in text mode. I've found this macro to solve the problem

\def\textsubsuperscript#1#2{\rlap{\textsubscript{#1}}\textsuperscript{#2}}

But it doesn't works well when the subscript is long. In that case the subscript overlaps with the following character.

What could be the macro to enable sub- and superscripting in all cases?

jutky
  • 2,017
  • Check out the comment to this answer: http://tex.stackexchange.com/questions/1013/how-to-typeset-subscript-in-usual-text-mode/2704#2704 – Andrey Vihrov Jul 25 '11 at 12:10

3 Answers3

8

We need to have enough space for the longest of the two sub-/superscripts. For that we can calculate the maximum of both sub-/superscripts' widths and make a box as wide as the maximum:

\documentclass{article}

\usepackage{fixltx2e} % For \textsubscript

\makeatletter
\newcommand{\textsubsuperscript}[2]{%
  \begingroup
    \settowidth{\@tempdima}{\textsubscript{#1}}%
    \settowidth{\@tempdimb}{\textsuperscript{#2}}%
    \ifdim\@tempdima<\@tempdimb
      \setlength{\@tempdima}{\@tempdimb}%
    \fi
    \makebox[\@tempdima][l]{%
      \rlap{\textsubscript{#1}}\textsuperscript{#2}}%
  \endgroup}
\makeatother

\begin{document}

A\textsubsuperscript{x}{yyy}B

A\textsubsuperscript{xxx}{y}B

\end{document}

The result

I refrained from using mathmode and \text because \textsuperscript and \textsubscript may have more complex implementations than it would seem (see realscripts, for example).

Andrey Vihrov
  • 22,325
  • Thanks for the answer. Can I ask, why there is a need to put a comment character in the end of each line? – jutky Jul 26 '11 at 18:53
  • @jutky: http://tex.stackexchange.com/questions/7453/what-is-the-use-of-percent-signs-at-the-end-of-lines – Andrey Vihrov Jul 26 '11 at 23:07
4
\makeatletter
\DeclareRobustCommand*\textsubsuperscript[2]{%
  \@textsubsuperscript{\selectfont#1}{\selectfont#2}}
\def\@textsubsuperscript#1#2{%
  {\m@th\ensuremath{_{\mbox{\fontsize\sf@size\z@#1}}
                    ^{\mbox{\fontsize\sf@size\z@#2}}}}}
\makeatother

It's just the same code as for \textsuperscript in the LaTeX kernel with subscripts added.

The result is the same as Andrey's.

egreg
  • 1,121,712
0

An expl3-version:

\cs_new_protected:Nn \my_super_sub:nn
  {
    \group_begin:
      \hbox_set:Nn \l_tmpa_box { \textsuperscript {#1} }
      \hbox_set:Nn \l_tmpb_box { \textsubscript {#2} }
      \hbox_to_wd:nn
        { \dim_max:nn { \box_wd:N \l_tmpa_box } { \box_wd:N \l_tmpb_box } }
        { \hbox_overlap_right:n { \box_use:N \l_tmpa_box } \box_use:N \l_tmpb_box }
    \group_end:
  }
meide
  • 1,165