答案1
答案2
需要进行一些测量:
\documentclass{article}
\usepackage{amsmath,mathtools}
\NewDocumentCommand{\WH}{m e{^_}}{%
\IfNoValueTF{#3}{% no subscript
\IfNoValueTF{#2}{% no superscript
\widehat{#1}%
}{% superscript
\widehat{#1^{#2}}%
}%
}{% subscript
\WHdo{#1}{#2}{#3}%
}%
}
\makeatletter
\NewDocumentCommand{\WHdo}{mmm}{\mathpalette\WHdo@{{#1}{#2}{#3}}}
\newcommand{\WHdo@}[2]{\WHdo@@#1#2}
\newcommand{\WHdo@@}[4]{%
% measure without the wide hat
\sbox0{$\m@th#1#2\IfValueT{#3}{^{#3}}_{#4}$}%
% measure without the subscript
\sbox2{$\m@th#1#2\IfValueT{#3}{^{#3}}$}%
% output with a zero width subscript
\widehat{#2\IfValueT{#3}{^{#3}}_{\mathrlap{#4}}}
% fix the spacing
\kern\dimexpr\wd0-\wd2\relax
}
\makeatother
\begin{document}
\begin{gather*}
\WH{T}^{2}_{X,Y}+x \\
T^{2}_{X,Y}+x \\
\WH{T}_{X,Y}+x \\
T_{X,Y}+x \\
\textstyle \WH{T}^{2}_{X,Y}+x \\
\textstyle T^{2}_{X,Y}+x \\
\WH{a}^{2}_{X,Y}+x \\
a^{2}_{X,Y}+x
\end{gather*}
\end{document}