[Tex/LaTex] Why does a combination of `textsc` and `texttt` cause an “Undefined control sequence.” error

errorsmath-mode

Consider this MnotWE:

\documentclass[12pt,letterpaper]{article}

\usepackage{lmodern}
\usepackage[T1]{fontenc}

\newcommand*{\fnn}[1]{\text{\texttt{#1}}}
\newcommand*{\Ker}[1]{\textsc{ker}(\fnn{#1})}

\begin{document}
     $\Ker{f}$
\end{document}

It produces the error:

Undefined control sequence. $\Ker{f}

However, this compiles just fine:

\documentclass[12pt,letterpaper]{article}

\usepackage{lmodern}
\usepackage[T1]{fontenc}

\newcommand*{\fnn}[1]{\text{\texttt{#1}}}
\newcommand*{\Ker}[1]{\textsc{ker}(#1)}

\begin{document}
     $\Ker{f}$
\end{document}

Why?

Best Answer

The \text macro requires amsmath (or at least amstext that amsmath loads).

However, once amsmath is loaded, \text becomes redundant and \texttt suffices also if \fnn is in a subscript or superscript. You should consider \mathtt, though. The reason should be clear from the following example:

\documentclass{article}
\usepackage{amsmath}

\newcommand*{\fnn}[1]{\texttt{#1}}
\newcommand*{\Ker}[1]{\textsc{ker}(\fnn{#1})}

\newtheorem{theorem}{Theorem}

\begin{document}

Some text with $\Ker{f}$ and $X_{\fnn{f}}$

\begin{theorem}
Some text with $\Ker{f}$ and $X_{\fnn{f}}$
\end{theorem}

\end{document}

As you see, the italic context also acts on the argument to \fnn. Adding \text would do nothing better.

enter image description here

Here's a possibly better definition:

\documentclass{article}
\usepackage{amsmath}

\newcommand*{\fnn}[1]{\mathtt{#1}}
\newcommand*{\Ker}[1]{\operatorname{\textsc{ker}}(\fnn{#1})}

\newtheorem{theorem}{Theorem}

\begin{document}

Some text with $\Ker{f}$ and $X_{\fnn{f}}$

\begin{theorem}
Some text with $\Ker{f}$ and $X_{\fnn{f}}$
\end{theorem}

\end{document}

enter image description here

If you are not short of math groups, adding

\DeclareMathAlphabet{\mathsc}{\encodingdefault}{\familydefault}{m}{sc}

would be even better:

\documentclass{article}
\usepackage{amsmath}

\DeclareMathAlphabet{\mathsc}{\encodingdefault}{\familydefault}{m}{sc}

\newcommand*{\fnn}[1]{\mathtt{#1}}
\newcommand*{\Ker}[1]{\operatorname{\mathsc{ker}}(\fnn{#1})}

\newtheorem{theorem}{Theorem}

\begin{document}

Some text with $\Ker{f}$ and $X_{\fnn{f}}$

\begin{theorem}
Some text with $\Ker{f}$ and $X_{\fnn{f}}$
\end{theorem}

\end{document}

The output is the same, but with the “easy version” above you might risk shape changes in case the context where you use \Ker is italic or boldface and the font family you use provides variant shape/weight for small caps.

Note: I didn't load lmodern just to make the example more general. It would be the same with it.