[Tex/LaTex] How to get a monospaced sans-serif font for the source code when using lstinputlisting

fontslistings

I have a document similar to this:

\usepackage{listings}
\begin{document}
\lstset{language=Matlab,%
  basicstyle=...
}

\subsection*{Matlab code}
\lstinputlisting{../myScript.m}

\end{document}

I have found several answers on how to use lstlisting with a monospaced font and a few on how to get a sans-serif font by setting basicstyle equal to \ttfamily or \sffamily respectively.

But what should I do if I like to display my source code in a monospaced AND sans-serif font?

Best Answer

Assuming you have access to fonts provided by your operating system, achieving your goal is straightforward: (a) Employ LuaLaTeX (or XeLaTeX) instead of pdfLaTeX; (b) load the fontspec package and load a suitable monospaced font via a \setmonofont directive; and (c) after loading the listings package, add the option basicstyle=\ttfamily to the argument(s) of \lstset.

enter image description here

\documentclass{article}
\usepackage{fontspec}
%\setmainfont{...} % select a suitable main text font
%\setsansfont{...} % select a sans-serif font
\setmonofont{Lucida Console}[Scale=MatchLowercase] % select a suitable monospaced font

\usepackage{listings}
\lstset{basicstyle=\ttfamily}

\begin{document}
Hello World. \lstinline{Hello World.}
\end{document}