11

I would like to redefine the underscore _ to automatically set subscripts in math mode in roman type, as I currently find myself almost always using _\mathrm{}. I can't find a way of redefining what _ does:
\renewcommand_ gives

! Missing control sequence inserted.
<inserted text> 
                \inaccessible 

and \show_ just tells me

subscript character _.

I found a description of how to make _ an active character on Anthony Lieken's website, but that just brings _ and ^ to text mode and does not change the behaviour in math mode.

Question: How do I make _x behave like _\mathrm{x}?

Caramdir
  • 89,023
  • 26
  • 255
  • 291
Jake
  • 232,450

2 Answers2

14

Making _ active was the right idea:

\documentclass{minimal}
\catcode`_=\active
\newcommand_[1]{\ensuremath{\sb{\mathrm{#1}}}}
\begin{document}
a_{text} $a_{text}$
\end{document}

Thanks to \ensuremath (and to Bruno) this can also be used in text mode. For the "old" _ you can then use \sb.

Hendrik Vogt
  • 37,935
  • 3
    And to write a normal subscript, you can use \sb. Also, if you write \ensuremath{\sb{\textrm{#1}}}, you have the added benefit of being able to use it in text mode. – Bruno Le Floch Jan 20 '11 at 10:32
  • 1
    After some testing, I would prefer \mathrm over \textrm: it scales better, for instance when writing $\sum\sb{n=n_{min}}\sp{n_{max}}$. – Bruno Le Floch Jan 20 '11 at 10:44
  • @Bruno: I'm too tired today. Jake explicitly asked for \mathrm. You should have written this answer ... – Hendrik Vogt Jan 20 '11 at 10:50
  • 1
    @Bruno, a late comment: If you load amsmath, then \mathrm and \textrm scale the same, but still, \mathrm is better since it gives the same output in an italic context. – Hendrik Vogt Feb 15 '13 at 16:10
  • Since \mathrm and \text are very common as subscript. What I did recently was to "overload" the unicode character to do just this (I also added a shortcut, control-altGR+"-" to type it) and added the code \catcode⌄ PRIMECHAR =\active \newcommand⌄[1]{\ensuremath{\sb{\mathrm{#1}}}} or ...\text{... (needs xelatex) – alfC Apr 09 '14 at 21:10
2
\documentclass[12pt]{article}

\catcode`\_=\active
\def_#1{\ensuremath{\sb{\mathrm{#1}}}}

\begin{document}

$f_{bar}$ f_x

\[ \int_a^b f(x) \mathrm{d}x \]
\[ \int\sb{a}^b f(x) \mathrm{d}x \]

\end{document}
  • Thanks Herbert! Could you explain why you would use \def in this case instead of \newcommand? Am I right in assuming that that's the only difference to Hendrik's/Bruno's answer? – Jake Jan 20 '11 at 11:19
  • 3
    @Jake: a matter of taste ... A personal decision, when working on TeX level I always use \def to make things clear, that it is no LaTeX specific code I am changing. And sometimes I am too lazy for typing long command names ... :-) –  Jan 20 '11 at 11:29