Decorate text above and below a \sim $\sim$, like xrightarrow

arrowsxrightarrow

Just like \xrightarrow allows to decorate \rightarrow with text above and below, I would like to do exactly the same for \sim instead or \rightarrow

Is there an easy way to do it ?

PS : I can get a fixed length \sim via

$A \overset{x}{\underset{\mathclap{\varphi}}{\sim}} B$

Best Answer

The following code defines a user command named extoverset, which takes two mandatory arguments and acts like \overset, except that it stretches the width of the 2nd argument (say, \sim) to equal the width of the first argument. An optional third argument can be used to fine-tune the resulting widths.

Certainly not perfect -- but hopefully it's a (decent?) start.

enter image description here

\documentclass{article}
\usepackage{amsmath}    % for '\overset' macro
\usepackage{calc}       % for '\widthof' macro
\usepackage{graphicx}   % for '\resizebox' macro

\newcommand\xxoverset[3]{%
  \resizebox{#1+\widthof{\scriptsize #2}}{\height}{$#3$}}
\newcommand\extoverset[3][0pt]{%
  \mathrel{\overset{\textup{#2}}{\xxoverset{#1}{#2}{#3}}}}

\begin{document}
\obeylines % just for this example
$A \overset{aa}{\sim} B$
$A \extoverset{$aa$}{\sim} B$
$A \extoverset[6pt]{long expression}{\sim} B$
$A \extoverset[8pt]{long expression}{=} B$
\end{document}