Redefine underscore to produce roman subscript without breaking file names

If you only need the _ in math, then \mathcode does the trick. However, TeX seems to see the \catcode before the \mathcode, so I changed that, too:

\documentclass{article}

\begingroup
  \catcode`\_=\active
  \gdef_#1{\ensuremath{\sb{\mathrm{#1}}}}
\endgroup
\mathcode`\_=\string"8000
\catcode`\_=12

\begin{document}
$D_H$
\label{sec_a} % This no longer causes a "! Missing \endcsname inserted." error
\end{document}

For simplicity I used \gdef here; this can be avoided if you want to.


You can test for mathmode using \ifmmode like \ensuremath is doing it. This should then be done with two macros so that the "normal underscore" doesn't take an argument:

\documentclass{article}

\catcode`_=\active
\newcommand{_}{\ifmmode\expandafter\sbrm\else\string_\fi}
\newcommand{\sbrm}[1]{\sb{\mathrm{#1}}}

\begin{filecontents}{\jobname_test.tex}
   Read input file test Test!
\end{filecontents}

\begin{document}
\label{sec_a} % Works now
$D_H$

\input{\jobname_test}

\end{document}