[Tex/LaTex] the least invasive way to set the font for listings

fontslistings

As has been asked often enough, to get bold keywords in lstlisting environments, one has to use a different typewriter font. Most answers suggest to include this or that package.

If just including a package changes the font, then the package must be applying some magic in the background to install itself. And unless the package was specifically made for listings, this means it potentially also changes other stuff.

How can I use another font in my listings while being sure that nothing else is affected, or at least that nothing but the default typewriter font is changed?

Best Answer

That's an excellent question. Many answers to questions about listings on this site tell you to load along with the fontenc package with option T1 (which is fine) along with a package such as courier or beramono in order to have access to boldface typewriter fonts. However, packages like beramono and courier change the default typewriter font family globally, which may not be what you want.

If you want a certain font only inside listings, you should simply select it in the basicstyle key.

basicstyle = \fontfamily{desired-font}\selectfont ...

I suggest you define a macro to easily select the font in question (see below). You should still load the fontenc package with option T1, but don't load beramono or the likes of it.

enter image description here

\documentclass{article}

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

% macro to select a scaled-down version of Bera Mono (for instance)
\makeatletter
\newcommand\BeraMonottfamily{%
  \def\fvm@Scale{0.85}% scales the font down
  \fontfamily{fvm}\selectfont% selects the Bera Mono font
}
\makeatother

\lstset{
  basicstyle=\BeraMonottfamily, 
  frame=single,
}

\begin{document}

\texttt{Computer Modern typewriter font, as usual}

\begin{lstlisting}[language=C,caption=listing typeset with Bera Mono]
/* Hello World program */

#include<stdio.h>

main()
{
    printf("Hello World");

}
\end{lstlisting}
\end{document}