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:
\include{pygments}
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:
\scriptsize \include{myfile}
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.
Hi Neil,
You might want to check out the Minted package (http://code.google.com/p/minted/) by Konrad Rudolph (also a bioinformatician). It makes inserting syntax-highlighted code much easier, so you don’t need to manually run `pygmentize’ on each script.
Personally, I’m more and more a fan of org-mode (and org-babel) for creating documents. See
http://orgmode.org/
and
http://orgmode.org/worg/org-contrib/babel/index.html
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.