9

The listings package quite nicely formats my pseudo code listings. Is there a way that one can specify that line numbering should be suppressed for empty lines?

doncherry
  • 54,637
user9131
  • 875

2 Answers2

11

You can use numberblanklines=false; a little example:

\documentclass{article} 
\usepackage{listings}

\lstset{numbers=left,numberblanklines=false}

\begin{document}

\begin{lstlisting}
First line.

Second line.
\end{lstlisting}

\end{document}

enter image description here

The above approach will not number blank lines, but will take them into account for increasing the counter controlling the line numbering; you can define a command to decrease the counter manually; something like this:

\documentclass{article} 
\usepackage{listings}

\lstset{numbers=left,numberblanklines=false,escapeinside=||}
\newcommand*\DNumber{\addtocounter{lstnumber}{-1}}

\begin{document}

\begin{lstlisting}
First line.|\DNumber|

Second line.|\DNumber|

Third line.
\end{lstlisting}

\end{document}

enter image description here

Marco Daniel suggested the following automated way of preventing blank lines from increasing the counter, by defining a new key countblanklines and using the macro \lst@AddToHook{<hook>}:

\documentclass{article} 
\usepackage{listings}

\lstset{numbers=left,numberblanklines=false}

\makeatletter
\lst@Key{countblanklines}{true}[t]%
    {\lstKV@SetIf{#1}\lst@ifcountblanklines}

\lst@AddToHook{OnEmptyLine}{%
    \lst@ifnumberblanklines\else%
       \lst@ifcountblanklines\else%
         \advance\c@lstnumber-\@ne\relax%
       \fi%
    \fi}
\makeatother

\begin{document}

\begin{lstlisting}
First line.

Second line.

Third.
\end{lstlisting}


\begin{lstlisting}[countblanklines=false]
First line.

Second line.

Third.
\end{lstlisting}

\end{document}

enter image description here

Gonzalo Medina
  • 505,128
4

You could add the line decrement routine suggested by @Gonzalo using a hook into OnEmptyLines. This is provided by the macro \lst@AddToHook{<hook>}. The convenience, of course, is that one is not required to escape out of the listing in order to decrease the counter. However, this then generalizes the approach for all OnEmptyLines:

enter image description here

\documentclass{article} 
\usepackage{listings}% http://ctan.org/pkg/listings
\makeatletter
\lst@AddToHook{OnEmptyLine}{\addtocounter{lstnumber}{-1}}% Remove line number increment from listings
\makeatother
\lstset{numbers=left,numberblanklines=false}
\begin{document}
\begin{lstlisting}
First line.

Second line.

Third line.
\end{lstlisting}
\end{document}​
Werner
  • 603,163