2

Based on this answer, I implement two versions of \widetilde, which is wide enough to cover all the text I want:

\documentclass{article}
\usepackage{amsmath,amssymb,stackengine,scalerel}
\newlength\A
\ExplSyntaxOn
%first method, based on stackon
\newcommand{\wtildea}[1]{
    \settowidth{\A}{#1}
    \stackon[-7pt]{$#1$}{\hstretch{\fp_eval:n{\dim_to_fp:n{\A}/21}}{\widetilde{\phantom{#1}}}}
}

%second method, based on tikz \usepackage{tikz,mathtools} \newcommand{\wtildeb}[1]{ \settowidth{\A}{$#1$} \ooalign{$\tikz{\node[xscale=\fp_eval:n{\dim_to_fp:n{\A}}/5.5]{$\widetilde{\phantom{x}}$}}$\cr\hidewidth$#1$\hidewidth\cr} } \ExplSyntaxOff

\begin{document} $$xxAAAAAAAAAAAAxx$$ $$xx\wtildea{AAAAAAAAAAAA}xx$$ $$xx\wtildeb{AAAAAAAAAAAA}xx$$ \end{document}

However, they both have spacing issues, and the first solution causes the text with tilde shifts to right: enter image description here

How can I fix that?

Qrrbrbirlbel
  • 119,821

1 Answers1

3

The TikZ solution needs inner sep of zero, this is a padding around the text that not only contributes to the width of the TikZ picture, it will also get scaled the same.

I've also added a \vphantom{#1} to it so that it gets the proper vertical dimensions. Using baseline and anchor = base makes sure the node is also placed correctly vertically.

As an option, I've added an alternative with \resizebox from the graphics package (loaded by graphicx which is loaded by tikz).

Both solutions won't work in subscripts or in superscripts. A little bit more work is necessary.

Code

\documentclass[varwidth]{standalone}
%\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage{tikz}
\newcommand*\wtildea[1]{%
  \begingroup
    \settowidth{\dimen0}{$#1$}%
    \rlap{\resizebox{\dimen0}{\totalheight}{$\widetilde{\phantom{x\vphantom{#1}}}$}}%
  \endgroup
  #1}
\newcommand*{\wtildeb}[1]{%
  \ooalign{%
    \tikz[baseline]
      \node[anchor=base, inner sep=+0pt, xscale={width("$#1$")/width("$x$")}]
        {$\widetilde{\phantom{x\vphantom{#1}}}$};%
    \cr\hidewidth$#1$\hidewidth\cr
  }%
}
\begin{document}
\[xx         AAAAAAAAAAAA xx\]
\[xx\wtildea{AAAAAAAAAAAA}xx\]
\[xx\wtildeb{AAAAAAAAAAAA}xx\]
\end{document}

Output

enter image description here

Qrrbrbirlbel
  • 119,821
  • Just curious, why do you add an x in \phantom{}? – Yijun Yuan Apr 14 '23 at 15:08
  • @YijunYuan It was in your original code as well. That's the base width for \widetilde, that's also the denominator for the xscale factor. (The \resizebox does these calculations internally.) If you put nothing in it you divide by 0 to get a scaling factor. You can, of course use something else or an explicit length instead. A \widetilde{x} covers the width of x perfectly while xxx or more leave a bit uncovered left and right which will get accentuated by the scaling. – Qrrbrbirlbel Apr 14 '23 at 15:18