oBook‎ > ‎Latex Tips‎ > ‎

Code in Latex

posted May 18, 2014, 2:26 AM by Javad Taghia   [ updated May 18, 2014, 1:42 PM ]

source: http://scott.sherrillmix.com/blog/programmer/displaying-code-in-latex/

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.

\begin{verbatim}
for i in range(1, 5):
  print i
else:
  print "The for loop is over"
\end{verbatim}
Code in LaTeX using verbatim

Unfortunately, you can’t use any normal LaTeX commands inside verbatim (since they’re displayedverbatim). 

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:

\newcommand\codeHighlight[1]{\textcolor[rgb]{1,0,0}{\textbf{#1}}}
\begin{Verbatim}[commandchars=\\\{\}]
\codeHighlight{for} i in range(1, 5):
  print i
else:
  print "The for loop is over"
\end{Verbatim}
Code in LaTeX using fancyvrb
Comments