The second \Alt
command in Martin Scharrer's answer is excellent; however, it can cause problems when used with Beamer's incremental overlay specifications (e.g., <+>
). This is because Martin's implementation invokes the underlying \alt
command using \mathpalette
. \mathpalette
internally uses \mathchoice
, which actually typesets the contents given for each of the four math styles before deciding which to use in the final output.
Example of the issue
\documentclass{beamer}
% [Paste Martin's second set of `\Alt` macros here.]
\begin{document}
\begin{frame}
\begin{itemize}
\item Some stuff\dots
\pause
\item An equation I'll reveal in pieces:
\[
\frac{-4}{2} + \frac{9}{3} =
\Alt<+>{
\vcenter{\hbox{ ?\thinspace?}}
}{
\frac{-4 + 9}{2 + 3} = 1.
}
\]
\pause
\item Some more stuff\dots
\end{itemize}
\end{frame}
\end{document}
Compiling this code yields a document with seven slides rather than the desired four, as TeX is executing the Beamer \alt
macro---and thus incrementing the beamerpauses
counter---four times rather than one.
Solving the problem
Move the \alt
invocation outside of \mathpalette
/\mathchoice
. Unfortunately, this means that the new \Alt
command's arguments will be typeset eight times (four for each of the \alt
macro's two arguments) rather than four times as in Martin's code, but the added overhead seems necessary to make \Alt
behave the same as \alt
with respect to incremental overlays.
Also, it's a minor thing, but adding a \leavevmode
before typesetting the \Alt
content box seems to make the command behave a bit less surprisingly in some cases, e.g., at the start of a list item.
Revised code (supports incremental overlays)
\usepackage{etoolbox} % For `\ifbool`, `\ifnumcomp`.
\makeatletter
\newcommand*\Alt{\alt{\Alt@branch0}{\Alt@branch1}}
\newcommand\Alt@branch[3]{%
\begingroup
\ifbool{mmode}{%
\mathchoice{%
\Alt@math#1{\displaystyle}{#2}{#3}%
}{%
\Alt@math#1{\textstyle}{#2}{#3}%
}{%
\Alt@math#1{\scriptstyle}{#2}{#3}%
}{%
\Alt@math#1{\scriptscriptstyle}{#2}{#3}%
}%
}{%
\sbox0{#2}%
\sbox1{#3}%
\Alt@typeset#1%
}%
\endgroup
}
\newcommand\Alt@math[4]{%
\sbox0{$#2{#3}\m@th$}%
\sbox1{$#2{#4}\m@th$}%
\Alt@typeset#1%
}
\newcommand\Alt@typeset[1]{%
\ifnumcomp{\wd0}{>}{\wd1}{%
\def\setwider ##1##2{##2##1##2 0}%
\def\setnarrower##1##2{##2##1##2 1}%
}{%
\def\setwider ##1##2{##2##1##2 1}%
\def\setnarrower##1##2{##2##1##2 0}%
}%
\sbox2{}%
\sbox3{}%
\setwider2{\wd}%
\setwider2{\ht}%
\setwider2{\dp}%
\setnarrower3{\ht}%
\setnarrower3{\dp}%
\leavevmode
\rlap{\usebox#1}%
\usebox2%
\usebox3%
}
\makeatother
overprint
, but I only used it for whole lines/paragraphs, never for short material. See my answer at the question liked by Hendrik.overprint
is relevant, but because my particular use case is within a math expression it's not flexible enough.overlayarea
might work.