{"id":437,"date":"2009-04-24T02:28:37","date_gmt":"2009-04-24T06:28:37","guid":{"rendered":"http:\/\/scott.sherrillmix.com\/blog\/?p=437"},"modified":"2009-04-24T02:28:37","modified_gmt":"2009-04-24T06:28:37","slug":"displaying-code-in-latex","status":"publish","type":"post","link":"http:\/\/scott.sherrillmix.com\/blog\/programmer\/displaying-code-in-latex\/","title":{"rendered":"Displaying Code in LaTeX"},"content":{"rendered":"

gioby of Bioinfo Blog!<\/a> (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<\/code>‘s and \\textcolor<\/code> 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.<\/p>\r\n\r\n

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<\/code> environment in LaTeX that is equivalent to html’s <pre><\/code>. So something like the following should preserve white space.<\/p>\r\n\"Code

\\begin{verbatim}\r\nfor i in range(1, 5):\r\n  print i\r\nelse:\r\n  print "The for loop is over"\r\n\\end{verbatim}<\/code><\/pre>\r\n\r\n

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

\\newcommand\\codeHighlight[1]{\\textcolor[rgb]{1,0,0}{\\textbf{#1}}}\r\n\\begin{Verbatim}[commandchars=\\\\\\{\\}]\r\n\\codeHighlight{for} i in range(1, 5):\r\n  print i\r\nelse:\r\n  print "The for loop is over"\r\n\\end{Verbatim}\r\n<\/code><\/pre>\r\n\r\n\"Code\r\n

If you really want to get fancy, the Pygments package<\/a> in Python will output syntax highlighted latex code with a command like: pygmentize -f latex -O full test.py >py.tex<\/code> 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.<\/p>\r\n\r\n

Here’s an example LaTeX file with the three examples above and the pdf it generates if you’re curious.<\/p>\r\n