17 May 2010

Painless Code Listings

Even though LaTeX is a tool of, by, and for computer scientists, it sure doesn't make it easy for you to include code samples in your papers. Sure, there is the verbatim package, but what if your code listing is too big, and the next font size down is too small? Also, how the heck do you draw a frame around the text?

Let's talk about it. Here's my solution:
  • You should put line numbers in your code listings. This makes it easier to refer to particular parts of the code; easier for you in your exposition, or easier for your reviewers. It also seems to give the listing a clean, scientific look.
  • Putting a box around the figure helps set it apart from the rest of the text, and avoids "bumping." However, LaTeX is surprisingly bad at letting you compose different commands; you can't just put an "fbox" around your verbatim and leave it at that. Instead, you need to construct it in an lrbox first, and then put the fbox around the lrbox.
  • Actually, this box trick works well for the other problem: Finding the right font size. If you use a minipage, you can make it as exactly the number of columns wide as you need.
Here's it all put together:
\newsavebox{\savelisting}
\newenvironment{listing}
{\begin{lrbox}{\savelisting}
\begin{minipage}{4.5in}
\begin{flushleft}}
{\end{flushleft}
\end{minipage}
\end{lrbox}
\begin{center}
\resizebox{\columnwidth}{!}{\setlength\fboxsep{6pt}\fbox{\usebox{\savelisting}}}
\end{center}}
Then, use it in a figure like this:
\begin{figure}
\begin{listing}
\begin{verbatim}
01 void sort(int[] arr, int start, int end) { ... }
\end{verbatim}
\end{listing}
\caption{A code listing}
\end{figure}
Using the "times" package for the fonts, and the 4.5in minipage width, gives you 60 columns of code. (You could have different widths for different code listings, making each exactly what you need and no more, but then that would cause an inconsistency in size across your listings.)

Here's the result:

No comments:

Post a Comment