Working with XeLaTeX and Pygments

I am trying to use XeLaTeX typesetting engine together with Pygments syntax highlighter. XeLaTex enables me to use all the fonts that are available to the operating system; Pygments helps me to color the code.

I added the following two lines into the LaTeX file generated by Pygments.

\usepackage{fontspec}
\setmainfont{Monaco}


I was expecting to see the final PDF file with colored code in Monaco font, but I didn't. How can I edit the latex file generated by Pygments in order to specify my desired fonts?

Monaco font looks like this:

But I was getting the something like this (screenshot of the PDF file generated by XeLaTex):

[This problem is solved, thanks to the comment of @TorbjørnT.]

-

migrated from stackoverflow.comDec 10 '11 at 1:38

This question came from our site for professional and enthusiast programmers.

Does \setmonofont{Monaco} instead of \setmainfont{Monaco} help? – Torbjørn T. Dec 10 '11 at 2:39
@TorbjørnT. Thank you! It helps. – Ning Dec 10 '11 at 3:33
@TorbjørnT.: Please turn your comment into an answer, and add the necessary detail to make the solution comprehensible to future readers. – Werner Dec 10 '11 at 3:58
@Werner Will do. – Torbjørn T. Dec 10 '11 at 9:38
@Ning: It would also be great if you'd mention whether you use Pygments directly or via the minted package. – Joseph Wright Dec 10 '11 at 9:38

When choosing fonts with fontspec you have to use different commands for the different families, "normal" serif fonts, sans serif fonts, monospaced fonts. A typical setup may be

\usepackage{fontspec}
\setmainfont{Linux Libertine O}
\setsansfont{Linux Biolinum O}
\setmonofont{Inconsolata}


which will use Linux Libertine O as the standard, serif, font of the document, Linux Biolinum O as the sans serif font, and Inconsolata as the monospace font.

The font family used for code listings is the monospaced one, \ttfamily, and as such it is \setmonofont that influences it. Hence, you should use

\usemonofont{Monaco}


One small addendum: If you're going to be writing a document with several listings, you might consider using the minted package, which uses Pygments. (Another package that provides syntax highlighted code listings is listings.)

Instead of the mess created by

pygmentize -f latex -O full -l python code.py > code.tex


you can have a document such as

\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{python}
def(hallais):
print("Hello TeX.sx!")
\end{minted}
\end{document}


or instead of the minted environment, you can input a file with your code, e.g.,

 \inputminted[linenos=true]{python}{demo.py}


This needs to be compiled with -shell-escape enabled, e.g.,

xelatex -shell-escape filename.tex


See the minted manual for more details.

-
This is a great help! – Ning Dec 11 '11 at 4:00