[Tex/LaTex] Negative phantom inside equations

equationsmacrosspacing

The following code produces a negative phantom (from the comment in this answer):

\newcommand{\negphantom}[1]{\settowidth{\dimen0}{#1}\hspace*{-\dimen0}}

However, when used inside an equation like

$$a\negphantom{\inf_{t>0}t^2}b$$

I get an error. The solution is to do

$$a\negphantom{$\inf_{t>0}t^2$}b$$

Is it possible to define negphantom in such a way that it respects being inside an equation or not? (the latter solution is not perfect, since the \inf is not in displaystyle).

Best Answer

You check for math mode and then use \mathpalette:

\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newlength{\negph@wd}
\DeclareRobustCommand{\negphantom}[1]{%
  \ifmmode
    \mathpalette\negph@math{#1}%
  \else
    \negph@do{#1}%
  \fi
}
\newcommand{\negph@math}[2]{\negph@do{$\m@th#1#2$}}
\newcommand{\negph@do}[1]{%
  \settowidth{\negph@wd}{#1}%
%  \hspace*{-\negph@wd}% % for TESTING
  \hspace*{\negph@wd}% % for TESTING
}
\makeatother

\begin{document}

\begin{gather}
a\negphantom{\inf_{t>0}t^2}b \\
a{\inf_{t>0}t^2}b \\
\textstyle a\negphantom{\inf_{t>0}t^2}b \\
\textstyle a{\inf_{t>0}t^2}b \\
\scriptstyle a\negphantom{\inf_{t>0}t^2}b \\
\scriptstyle a{\inf_{t>0}t^2}b \\
\scriptscriptstyle a\negphantom{\inf_{t>0}t^2}b \\
\scriptscriptstyle a{\inf_{t>0}t^2}b
\end{gather}

\end{document}

enter image description here

Now that we're sure the space is correct in all cases, we can remove the debugging bits and write down the final definition:

\makeatletter
\newlength{\negph@wd}
\DeclareRobustCommand{\negphantom}[1]{%
  \ifmmode
    \mathpalette\negph@math{#1}%
  \else
    \negph@do{#1}%
  \fi
}
\newcommand{\negph@math}[2]{\negph@do{$\m@th#1#2$}}
\newcommand{\negph@do}[1]{%
  \settowidth{\negph@wd}{#1}%
  \hspace*{-\negph@wd}%
}
\makeatother