# Underscore in textmode vs mathmode

I use _ character often in text mode, so I changed category of underscore: \catcode\_=12, but that applies also to mathmode and now I'm unable to make subscripts with underscore in mathmode. Is there a way to make latex interpret underscore in text mode as the underscore character, and in mathmode as subscript?

-
Check the underscore package. –  Ulrike Fischer Jul 9 '12 at 11:23

You can make _ math active:

\AtBeginDocument{
\catcode_=12
\begingroup\lccode~=_
\lowercase{\endgroup\let~}\sb
\mathcode_="8000
}

MWE:

\documentclass{article}
\usepackage[T1]{fontenc}

\AtBeginDocument{
\catcode_=12
\begingroup\lccode~=_
\lowercase{\endgroup\let~}\sb
\mathcode_="8000
}

\begin{document}
a_b $a_b$
\end{document}

-
What are the advantages of this code over my more simplistic solution (below)? –  JLDiaz Jul 9 '12 at 11:29
This code is in general more robust: in \write operations the underscore will be written as is. Active characters may do surprising things, at times; math active characters, on the contrary, assume the "active aspect" only when typesetting math, so well down TeX's digestive process. –  egreg Jul 9 '12 at 11:34
@egreg: I think you have a spurious \def\mathunderscore in your first code snippet. –  Bruno Le Floch Jul 9 '12 at 12:10
@JLDiaz: I don't know where to paste your answer. This solution worked after pasting after usepackage but before begindocument –  qwe Jul 16 '12 at 7:29