Friday, March 30, 2007

Suppressing a line number with the listings LaTeX package

Don't bother reading this post unless you are using the LaTeX listings package, have a code listing with line numbers, and want to suppress a line number in the listing.

By suppressing a line number, I mean something like the following:

Line 16 is split across two lines in the figure, but it's really one code statement, and I didn't want to have to refer to the statement using multiple line numbers in the text. Here is the LaTeX source for the key line:

String firstName = /*@\\@*/ /*@\underline{fullName.substring(0,spaceInd-1)};@*/

Note that since this snippet is used within the listings environment, the whitespace and the lack of a newline are significant. I used \lstset{escapeinside={/*@}{@*/}} before this listing to declare the escape sequence for adding other formatting. The {\*@\\@*/} inserts a linebreak, and then the spaces before the next characters appear as indentation in the figure.

Anyway, I googled around and couldn't find this trick, so hopefully this writeup will be useful to someone.

UPDATE (10/27/2008): In response to a request in a comment below, here is a minimal-ish full example that uses the technique. I've confirmed that this example works with the MacTex 2008 distribution (pdfTeXk, Version 3.1415926-1.40.9 and version 1.4 of the listings package).


\documentclass{article}
\usepackage{listings}

\lstset{escapeinside={/*@}{@*/}}

\begin{document}

\begin{figure}[t]
\begin{lstlisting}[numbers=left]
String firstName = /*@\\@*/ /*@\underline{fullName.substring(0,spaceInd-1)};@*/
\end{lstlisting}
\caption{Example illustrating suppression of line numbers.}
\end{figure}

\end{document}
Post a Comment