# Double hats with improved alignment

I'm using the code from Tianren Liu's answer to How do I robustly typeset a double-hat? to typeset double-hat accents in math mode, but sometimes the horizontal alignment is off. To wit:

\documentclass{article}
\usepackage{statmath}
\makeatletter
\newcommand{\doublehat}[1]{%
\begingroup%
\let\macc@kerna\z@%
\let\macc@kernb\z@%
\let\macc@nucleus\@empty%
\hat{\raisebox{.35ex}{\vphantom{\ensuremath{#1}}}\smash{\hat{#1}}}%
\endgroup%
}
\makeatother
\begin{document}
$$\hat\bfbeta \quad \hat\bfu$$
$$\doublehat\bfbeta \quad \doublehat\bfu$$
\end{document}

This yields:

The double hat on the u is fine, but that on the beta is much further to the left than it should be, and doesn't look good. I lack the TeX skills to fix this, but would much appreciate the help of any wizard. Thanks!

You can measure the result of math-accent \hat (which is positioned by kern of nucleus with \skewchar). The \skewchar is not important in the following macro, we do only measuring the result by un-boxing boxes:

\def\measurehat#1{%
\setbox0=\vbox{$\hat{#1}\hfil\break$\null\par
\setbox0=\lastbox\unskip\unpenalty\global\setbox1=\lastbox}%
\setbox0=\hbox{\unhbox1 \unskip\unpenalty\unskip \global\setbox2=\lastbox}%
\setbox0=\vbox{\unvbox2 \setbox0=\lastbox}%
}
\def\doublehat#1{%
\measurehat{#1}\dimen0=\wd0 \measurehat{\kern0pt#1}%
\raise.35ex\rlap{\kern\dimexpr\dimen0-\wd0$\hat{\phantom{#1}}$}{\hat#1}%
}

% try this:
$$\hat\bfbeta \quad \hat\bfu$$
$$\doublehat\bfbeta \quad \doublehat\bfu$$
• Wow, excellent. That is exactly the kind of deep wizardry I was hoping for!
– chsk
Mar 11 at 19:59

This is not really a satisfying answer, because it requires the user to do two things: indicate whether the glyph to be hatted is rm or it in shape, and also to specify the tangent of the font's italic slant angle in the macro \tanslant.

With that, I introduce \hatsrm[<n>]{<token>} and \hatsit[<n>]{<token>} to place n hats (default 2) over the roman or italic token, respectively.

This is only set up currently for text or display style. If it is needed in the smaller math styles, let me know...perhaps something could be done.

\documentclass{article}
\usepackage{stackengine}
\def\tanslant{.25}
\newcommand\hatsrm[2][2]{\ensurestackMath{%
\ifnum#1>1%
\stackengine{-4pt}{\hatsrm[\numexpr#1-1\relax]{#2}}{%
\scriptstyle\char'136}{O}{c}{F}{T}{S}%
\else%
\stackengine{-3pt}{#2}{\scriptstyle\char'136}{O}{c}{F}{T}{S}%
\fi%
}}
\newcommand\hatsit[2][2]{\ensurestackMath{%
\sbox0{$#2$}%
\ifnum#1>1%
\stackengine{-4pt}{\hatsit[\numexpr#1-1\relax]{#2}}{%
\kern\tanslant\ht0\scriptstyle\char'136}{O}{c}{F}{T}{S}%
\else%
\stackengine{-3pt}{#2}{\kern\tanslant\ht0\scriptstyle\char'136}%
{O}{c}{F}{T}{S}%
\fi%
}}
\begin{document}
$\hatsit[1]{z}\neq\hatsrm{\Lambda}\neq\hatsrm[3]{\Delta}\neq\hatsit[4]{\beta}$
\end{document}