# I want to automatically ... mathrm

I want the symbol i (italic) to automatically convert to "straight" by the code

\AtBeginDocument{\renewcommand{\hat}[1]{\hat{\mathrm{#1}}}}


Thank you very much!

I'm not sure why you'd want that. Anyway, here's the code.

\documentclass{article}
\usepackage{amsmath}

\NewCommandCopy{\latexhat}{\hat}

\ExplSyntaxOn
\RenewDocumentCommand{\hat}{m}
{
\latexhat
{
\str_case:nnF { #1 }
{
{i}{\mathchar16}
{j}{\mathchar17}
}
{% other cases
\mathrm{#1}
}
}
}
\ExplSyntaxOff

\begin{document}

$\hat{a}+\hat{i}+\hat{j}+\hat{z}$

\end{document}


However, you should instead use a semantic command, say \vrs (for versor), without clobbering \hat.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn
\NewDocumentCommand{\vrs}{m}
{
\hat
{
\str_case:nnF { #1 }
{
{i}{\mathchar16}% dotless i
{j}{\mathchar17}% dotless j
}
{% other cases
\mathrm{#1}
}
}
}
\ExplSyntaxOff

\begin{document}

$\vrs{a}+\vrs{i}+\vrs{j}+\vrs{z}$

\end{document}


Note: the codes for dotless i and j work in standard pdflatex and may require adjustments for some math font packages; they're definitely wrong with unicode-math; in that case, use

\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}

\ExplSyntaxOn
\NewDocumentCommand{\vrs}{m}
{
\hat
{
\str_case:nnF { #1 }
{
{i}{\symrm{^^^^0131}}% dotless i
{j}{\symrm{^^^^0237}}% dotless j
}
{% other cases
\symrm{#1}
}
}
}
\ExplSyntaxOff

\begin{document}

$\vrs{a}+\vrs{i}+\vrs{j}+\vrs{z}$

\end{document}


If you really, truly, want to redefine the \hat command so that all variables with a hat, and only those, are upright, you want to save the original \hat command before you redefine it.

\documentclass{article}

\let\oldhat\hat
\AtBeginDocument{\renewcommand{\hat}[1]{\oldhat{\mathrm{#1}}}}

\begin{document}
$\hat{i}$
\end{document}


If you wanted the hat to replace the dot on the i or j, it won’t, so you would want to define commands that place the accent on a dotless letter, such as (without \hat redefined)

\newcommand\ihat{\hat{\mathrm{\i}}}
\newcommand\jhat{\hat{\mathrm{\j}}}


You might also find it more practical to call the upright-with-hat command something different, such as \uphat.

If you want all variables to be upright, you are better off loading a package that does this, such as \usepackage{eulervm} or \usepackage[math-style=upright]{unicode-math}.

• I see :) Thank you very much! Jul 4 at 5:11