Tag Archives: LaTeX

Source code syntax highlighting in LaTeX using Pygments

A number of LaTeX packages provide environments for displaying source code, a comprehensive list of them is available here. For a long time I have preferred to use the fancyvrb package to format computer source code. I have just found an excellent alternative, called minted (it is also available at CTAN).

Minted uses Pygments, a general purpose syntax highlighter written in the Python programming language. Python and Pigments have to be installed in order to use minted, and a few other LaTeX packages are also required. (See the documentation for detailed installation instructions.)

The following simple example shows how to use minted:



public class Fibonacci {

  // The golden ratio $\phi = \frac{1 + \sqrt{5}}{2}$.
  public static final double PHI = (1.0 + Math.sqrt(5.0)) / 2.0;

  public static double fibonacci(long n) {
    if (n < 0) throw new IllegalArgumentException();
    return Math.floor(Math.pow(PHI, n) / Math.sqrt(5.0) + 0.5);



Click here to see the result.

The language java in line 6 can be replaced with many other languages, such as c, c++, sql, tex or xml. Pygments currently supports more than 200 programming, template and markup languages, see the output of the command

pygmentize -L lexers

for an exhaustive list of them. It is very important that LaTeX source files using the minted package must be compiled with the -shell-escape option, such as

pdflatex -shell-escape file.tex

Minted provides a number of options to customize formatting. For convenience, you can choose any of the styles provided with Pygments (you can also write your own style).

A major limitation of the package is that it supports only the Latin-1 character encoding. To overcome this problem the documentation suggests to use the command xelatex instead of the command pdflatex. (xelatex is part of XeTeX, an extension of TeX that comes with built-in support for Unicode.) Unfortunately, this solution does not work for me. If I try to compile the above LaTeX file with xelatex I always get the following error:

! Undefined control sequence.
l.27 \ifnum\pdf@shellescape

Thanks to Jabba Laci the great pythonist for introducing me to minted.

Tagged ,