Latex: Easy Code Syntax Highlight with pygments and texments

One of the things that one has to do regularly in LaTeX is to put code in documents.

To accomplish this the easiest way is probably by using python’s pygments (install with easy_install -U Pygments from terminal) and texments a latex package that wraps around pygments.

A minimal working LaTeX document would be:

\documentclass{article}
\usepackage{texments}
\begin{document}
 
% Mandatory
\usestyle{default} %other useful styles are, bw,  borland, vs
 
% Include the source code 
\includecode{filename.py}
 
%A one liner example for getting all styles from shell
\pygment{sh}{
python -c 'from pygments.styles import STYLE_MAP; print STYLE_MAP.keys()'
}
\end{document}

Notice that you included texments in the preamble of the document and then used the mandatory usestyle command. Then you can include your code from a file with the includecode command, or if you have a one liner you can use the pygment command.

This will output something like (depending on what you have in your code file):

pygments-latex.png

There are other alternatives to source code inclusion. Try using the listings package (great for inline BW code).