Displaying Code in LaTeX

gioby of Bioinfo Blog! (an interesting read by the way) left a comment asking about displaying code in LaTeX documents. I’ve sort of been cludging around using \hspace‘s and \textcolor but I’ve always meant to figure out the right way to do things so this seemed like a good chance to figure out how to do it right.

LaTeX tends to ignore white space. This is good when you’re writing papers but not so good when you’re trying to show code where white space is an essential part (e.g. Python). Luckily there’s a builtin verbatim environment in LaTeX that is equivalent to html’s <pre>. So something like the following should preserve white space.

Code in LaTeX using verbatim
for i in range(1, 5):
  print i
  print "The for loop is over"

Unfortunately, you can’t use any normal LaTeX commands inside verbatim (since they’re displayed verbatim). But luckily there a handy package called fancyvrb that fixes this (the color package is also useful for adding colors). For example, if you wanted to highlight “for” in the above code, you can use the Verbatim (note the capital V) environment from fancyvrb:

Code in LaTeX using fancyvrb
\codeHighlight{for} i in range(1, 5):
  print i
  print "The for loop is over"
Code in LaTeX using pygmentize

If you really want to get fancy, the Pygments package in Python will output syntax highlighted latex code with a command like: pygmentize -f latex -O full test.py >py.tex The LaTeX it outputs is a bit hard to read but it’s not too bad (it helped me figure out the fancyvrb package) and it does make nice syntax highlighted output.

Here’s an example LaTeX file with the three examples above and the pdf it generates if you’re curious.


Comments (8)



WP_Folksonomy Screenshot

Aziz of metaBLOG suggests that the new tags in WordPress 2.3 can be used to create a “folksonomy” on WordPress blogs. For those not in the know (including me until a couple days ago), a folksonomy is is the practice and method of collaboratively creating and managing tags to annotate and categorize content according to Wikipedia. Basically it’s letting normal people (versus say artificial intelligence or an administrator) help describe things. For example, adding a tag on flickr or using del.icio.us.

So since WordPress doesn’t currently have anything like a public “Add a Tag” and I haven’t coded a WordPress plugin recently (although I did upgrade WP_MonsterID if anyone is using it), I thought I would code up a quick plugin to see how it works. So here is WP_Folksonomy. It’s fairly basic at the moment but I’d like to get it out there to see if it’s useful and if anyone is interested in it.

Since it uses WordPress’s tagging features WP it’s only going to be compatible with WordPress 2.3 and up.

Continue Reading »


Comments (52)