Wednesday, 26 January 2011

Inserting computer code in LaTeX documents

After my post on lgrind, I searched a bit more for a good syntax highlighting utility I could use for inserting computer code into webpages and LaTeX documents. Good use of time, as I discovered that lgrind is a bit disappointing - it really pales in comparison with pygments and minted.

Pygments is a simple python-based command-line utility that transforms raw computer code into syntax-highlighted code in html, LaTeX and other formats. Much better as I said than lgrind - the output in fact is nearly perfect.

To install pygments on Mac OS 10.6, simply type

sudo easy_install pygments

After that, 'pygmentize' your code, say a C++ code into LaTeX, by typing

pygmentize -o mycode.tex mycode.cpp

With this, you only get the bare highlighted code; to get the full, compilable LaTeX document containing the highlighted code, type

pygmentize -O full -o mycode.tex mycode.cpp

More information, including the list of recognized computer languages, can be found on the pygments website.

With only pygments installed, you still have the job of inserting syntax-highlighted code into your LaTeX notes or presentations. Wouldn't it be simpler if LaTeX did the highlighting itself?

Install minted, a simple LaTeX package, and the job is done. Download the minted directory from ctan and run the makefile by typing

make

inside the minted directory. Then move the style (.sty) file and the documentation (.pdf) somewhere inside your LaTeX tree.

To use minted, use the following template:

\documentclass{article}
\usepackage{minted}
...
\begin{document}
...
\begin{minted}{matlab}
Your code here
end{minted}
...
\end{document}

Instead of Matlab, as above, use any of the programming languages recognised by pygments.

Note that minted is not a stand-alone package: it relies on pygments to generate the syntax-highlighted code and includes it when pygments' job is done. Not a perfect solution (the compilation can be a bit slow), but still quite a very good one.

No comments:

Post a Comment