I've been using Hendrik Vogt's answer to my earlier question Redefine underscore to produce roman subscript, in which he explained how to make the underscore character active and assign a macro to it so that it can be redefined to produce roman type in subscripts:
\catcode`_=\active
\newcommand_[1]{\ensuremath{\sb{\mathrm{#1}}}}
The solution works like a charm in maths and text environments, however I've run into trouble when I use it in 'literal' environments, such as file names or references, where making _ active breaks things.
Question: How can I make the underscore produce roman subscript, yet still function as a normal character in file names, labels, references and the like? I only need the subscript function in maths environments.
MWE:
\documentclass{article}
\catcode`_=\active
\newcommand_[1]{\ensuremath{\sb{\mathrm{#1}}}}
\begin{document}
$D_H$
\label{sec_a} % This causes a "! Missing \endcsname inserted." error
\end{document}