How-to: code snippets in your LaTeX documents


Formatted Ruby code in PDF generated from LaTeX

There are numerous ways to include formatted code in a LaTeX document. Here’s my favourite. Nothing original or clever here, just brief notes for my (and perhaps, your) benefit. Based largely on this how-to.

As ever, some variant of Ubuntu/Debian Linux is assumed throughout. I also assume you have a full, working TeX installation. A quick way to ensure that is sudo apt-get install kile.

1. Install pygments
The guts of the operation is Pygments, an excellent syntax highlighter written in Python.

sudo apt-get install python-pygments

2. Create working directory and pygments.tex
I’ll assume that you have a directory for your project, named myproject. Under that is one subdirectory with code (let’s say Ruby), myproject/code/ruby/myfile.rb and another for LaTeX, myproject/latex.

First, run pygments over any source code file in code/ruby to generate the file pygments.tex:

cd myproject
pygmentize -O full -f latex -o latex/pygments.tex code/ruby/myfile.rb 

Next, edit latex/pygments.tex as follows:

  • Comment out \documentclass{article} (by adding % at the start)
  • Comment out \usepackage[UTF-8]{inputenc}
  • Delete everything after \makeatother

3. Create and edit LaTeX files
I’ll assume that your LaTeX document is in latex/mydoc.tex. Somewhere near the top, between the preamble and the title, add this:


Now, any time you want to format a source code file in code/ruby, just run it through pygmentize, omitting the “-O full” switch and write the output to the latex directory. For example, again using the file code/ruby/myfile.rb:

pygmentize -f latex -o latex/myfile.tex code/ruby/myfile.rb

Pygments is very good at recognising the programming language used, based on the file name suffix. You can also specify it using the “-l” switch.

Finally: just include the LaTeX-formatted file in the main mydoc.tex LaTeX file:


Shown at top-right, a small example from a presentation that I wrote recently using LaTeX Beamer. Don’t forget \begin{frame}[fragile] when including code snippets in Beamer frames.

3 thoughts on “How-to: code snippets in your LaTeX documents

  1. polyphydont

    Good how-to.

    You obviously know this already, but using \input{myfile} instead of the include command will avoid placing the object on a new page.

Comments are closed.