95

Can you explain me what is the difference between \textrm{} and \mathrm{} when they are used in math mode. In what context one is preferred over the other?

Martin Scharrer
  • 262,582
Marco
  • 4,435

2 Answers2

71

\textrm (and the corresponding switch \rmfamily) changes an aspect of the font – in this case the family. If possible other aspects – like the series (bold or not) or the shape (italic) – are preserved. \text...-commands can be nested and their "aspect changes" are combined:

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

\begin{document} \sffamily\bfseries\itshape abc \textrm{abc}\textrm{\textup{abc}} \end{document}

text

\mathrm and the other math alphabets don't change only an aspect of a font. They switch to specific fonts. They make it possible to print symbols in special fonts. It is quite possible to setup things so that e.g. \mathrm use times, \mathbf is a bold palatino, \mathit a slanted Arial etc. You can also confuse everyone by defining \mathbf to be light itshape palatino and \mathit a bold Arial. You can define your own special math fonts e.g. \mathvector or \mathmatrix or \mathfancy. As all these commands switch to dedicated font they can't be nested. The last command (the inner one) always wins:

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

\begin{document}

$\mathit{A} \mathbf{A} \mathit{\mathbf{A}} \mathbf{\mathit{A}}$

\end{document}

math

Leone
  • 576
Ulrike Fischer
  • 327,261
7

Sorry for the necromancy, but, to go into a bit more detail:

The \textrm command uses the default font family, which is the one designated as \familydefault in NFSS or with \setmainfont if fontspec is loaded. It also uses the weight and shape parameters of the surrounding text. Therefore, the argument of \textrm will be italicized within an italic theorem statement or bold in a bold header. The contents will be rendered in text mode, so spaces will appear in the output.

The \mathrm command uses the alphabet declared as \mathrm. This is set with the \DeclareMathAlphabet or \DeclareSymbolFontAlphabet command in NFSS, or the \setmathrm command in fontspec. It will change the font to normal weight and upright shape, and the contents will be rendered in math mode, so spaces will be ignored.

Most font packages will set \mathrm and \textrm to the same font. One exception is eulerpx, which sets the default Roman font to Palatino and the math alphabet to AMS Euler.

Davislor
  • 44,045