Define \textunderscore to mimic look of standard underscore

I noticed that the look of the underscore _ differs greatly from the look of \textunderscore

How can I redefine \textunderscore to look like the standard underscore of the set font? I want to avoid changing the catcode, so redefining it seems to be the best option to me.

\documentclass{minimal}

\catcode\_11%

\begin{document}

{\ttfamily
\textunderscore _
}

\end{document}


• Not a direct answer to your query, but possibly still of relevance: If you run \usepackage[T1]{fontenc} before \catcode_11%, the two underscore characters turn out to be the same. Likewise, if you omit \catcode\_11% and type \ttfamily \textunderscore \_, both characters turn out be the same again, but now of the lighter, OT1 variety
– Mico
Feb 27, 2021 at 16:48
• do you have to use OT1-encoding? Feb 27, 2021 at 16:52
• The only reason for supporting OT1 a legacy 7-bit encoding is backwards compatibility, so it is what it is, you get different results in T1 or TU encodings which all current documents should use. Feb 27, 2021 at 17:24

\documentclass{article}

\begin{document}

\fontencoding{TU}\selectfont
\textrm{[\_][\string_]} \texttt{[\_][\string_]}

\fontencoding{T1}\selectfont
\textrm{[\_][\string_]} \texttt{[\_][\string_]}

\fontencoding{OT1}\selectfont
\textrm{[\_][\string_]} \texttt{[\_][\string_]}
\end{document}


Ideally \textunderscore (\_) would simply access the _ character in the current font, and that is what happens in encodings that have _. The original TeX encoding as used in the minimal class example in the question does not have _ at all, the slot is taken with the accent character as seen in the image. Just the tt font has _ to allow verbatim, but for OT1 LaTeX defines \_ as a tex-drawn rule independent of the font.

• One addition: \fontencoding{T1}\selectfontdoes not work if put into the preamble. Mar 1, 2021 at 18:53
• @UweZiegenhagen the document default font is set at begin document, so that setting will be undone unless you make the document default T1, the usual way in the preamble is \usepackage[T1]{fontenc}` Mar 1, 2021 at 18:56