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}?

2 Answers 2

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.

5
  • 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. Commented Jan 20, 2011 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}}$. Commented Jan 20, 2011 at 10:44
  • @Bruno: I'm too tired today. Jake explicitly asked for \mathrm. You should have written this answer ... Commented Jan 20, 2011 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. Commented Feb 15, 2013 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
    Commented Apr 9, 2014 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}
2
  • 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
    Commented Jan 20, 2011 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 ... :-)
    – user2478
    Commented Jan 20, 2011 at 11:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .