[Tex/LaTex] What exactly does \DeclareOldFontCommand and \DeclareRobustCommand do

fontslatex-basemacros

In the article class appears the following code related with the font selection:

\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm}
\DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
\DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt}
\DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf}
\DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit}
\DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl}
\DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc}
\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal}
\DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal}

What exactly does the commands at the code?

Best Answer

The declaration

\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm}

does

\DeclareRobustCommand\rm{\@fontswitch{\normalfont\rmfamily}{\mathrm}}

Let's see what happens when LaTeX finds $\rm a$ in the following minimal document:

\documentclass{article}
\begin{document}
$\rm a$
\end{document}

Let's start:

\rm ->\protect \rm  

\rm is a robust command, so this is its normal expansion. Now, since \protect is \relax, \rm is expanded:

\rm  ->\@fontswitch {\normalfont \rmfamily }{\mathrm }

Next \@fontswitch is expanded:

\@fontswitch #1#2->\ifmmode \let \math@bgroup \relax 
\def \math@egroup {\let \math@bgroup \@@math@bgroup
\let \math@egroup \@@math@egroup }#2\relax \else #1\fi 
#1<-\normalfont \rmfamily 
#2<-\mathrm 

We see the arguments. Since we are in math mode, the "true" branch is followed, so the redefinitions of \math@bgroup and \math@egroup are performed and \mathrm is expanded:

\mathrm ->\protect \mathrm  

\mathrm  ->\relax \ifmmode \else \non@alpherr \mathrm  \fi
\use@mathgroup \M@OT1 \symoperators 

\use@mathgroup #1#2->\relax \ifmmode \math@bgroup \expandafter
\ifx \csname M@\f@encoding \endcsname #1\else #1\fi \mathgroup #2\relax   
\expandafter \math@egroup \fi 
#1<-\M@OT1 
#2<-\symoperators 

Again, we're in math mode (\mathrm has some code for disallowing its use outside of it); the tests are performed using the fact that the expansion of \f@encoding is

\f@encoding ->OT1

Now it remains to expand \math@egroup:

\math@egroup ->\let \math@bgroup \@@math@bgroup
\let \math@egroup \@@math@egroup 

and the business is finished. Essentially, this is transformed into

${\mathrm{a}}$

If {\rm a} is found in text mode, then it becomes essentially

{\normalfont\rmfamily a}

that is, the old behavior of the \rm command is emulated.

This is why {\sf\sl a} won't use a slanted sans serif font, but a serif slanted one: it becomes equivalent to

{\normalfont\sffamily\normalfont\slshape a}

Moral: never use the old font commands. You gain nothing and lose much of the flexibility of the new ones. Well, after 18 years they aren't really new.