9

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).

  • \newcommand{\negphantom}[1]{\settowidth{\dimen0}{$#1$}\hspace*{-\dimen0}}? – Henri Menke Jun 24 '16 at 9:39
  • 1
    Or better: \newcommand{\negphantom}[1]{\ifmmode\settowidth{\dimen0}{$#1$}\else\settowidth{\dimen0}{#1}\fi\hspace*{-\dimen0}} – Henri Menke Jun 24 '16 at 9:40
  • @HenriMenke, Thank you! I came up with the first solution myself but I would like to use the command for both text- and math-mode. Your second solution works, but it doesn't respect the displaystyle of the outer equation mode. – Carucel Jun 24 '16 at 9:43
  • I think perhaps \mathchoice checks for the current style, but I'm trying to get it to work – Carucel Jun 24 '16 at 9:49
9

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.