[Tex/LaTex] How to set temporary math font

fontsmath-fontsmath-mode

I am wondering if there is a way to change the math font temporarily, similar to the way it can be done in text mode:

{\ttfamily Some text in typewriter font.}

Is there a way to do $\ttfamily a + b = c$ for example?

I know I could do $\mathtt{a + b = c}$, just like I could do \texttt{text}, but sometimes the other way results in cleaner code.

Please mind I am not looking for something like $\texttt{monospace} \textit{ in math.}$ I want to be able to write complicated formulas without having to mention the font in every word, as I would do in, for example, $\Sigma_{\mathtt{i} = 1}^{\mathtt{n}}$.

Best Answer

If all you need is to use the monospaced alphabet for variables:

\documentclass{article}
\usepackage{xpatch}

\DeclareMathVersion{ttmath}
\SetSymbolFont{letters}{ttmath}{OT1}{\ttdefault}{m}{n}

\xapptocmd{\ttfamily}{\mathversion{ttmath}}{}{}

\begin{document}

This is normal math: $a+b=c$

{\ttfamily This is tt math: $a+b=c$}

\texttt{This is tt math: $a+b=c$}

\end{document}

enter image description here

For a more complete setup, you can complement the monospaced text font with the concrete fonts (however, they are only available in bitmap format).

\documentclass{article}
\usepackage{xpatch}

\DeclareMathVersion{ttmath}
\DeclareSymbolFont{latinletters}{OT1}{\ttdefault}{m}{n}
%\SetSymbolFont{latinletters}{ttmath}{OT1}{\ttdefault}{m}{n}
\SetSymbolFont{letters}{ttmath}{OML}{ccm}{m}{it}
\SetSymbolFont{symbols}{ttmath}{OMS}{ccsy}{m}{n}
\SetSymbolFont{largesymbols}{ttmath}{OMX}{ccex}{m}{n}

\newcommand{\changeletters}{%
  \count255=`a
  \advance\count255 -1
  \loop\ifnum\count255<`z
    \advance\count255 1
    \mathcode\count255=\numexpr\number\symlatinletters*256+\count255\relax
  \repeat
  \count255=`0
  \advance\count255 -1
  \loop\ifnum\count255<`9
    \advance\count255 1
    \mathcode\count255=\numexpr\number\symlatinletters*256+\count255\relax
  \repeat
}

\xapptocmd{\ttfamily}{\mathversion{ttmath}\changeletters}{}{}

\begin{document}

This is normal math: $a+b=\alpha$

{\ttfamily This is tt math: $a+b=\alpha$}

\texttt{This is tt math: $a+b=\alpha$}

\bigskip

$\displaystyle\frac{1}{2\pi i}\oint \frac{1}{z}\,dz$
{\ttfamily$\displaystyle\frac{1}{2\pi i}\oint \frac{1}{z}\,dz$}

\end{document}

enter image description here