Suppress line numbering for empty lines in listings package

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?

-

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}


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=||}

\begin{document}

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

Second line.|\DNumber|

Third line.
\end{lstlisting}

\end{document}


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@ifnumberblanklines\else%
\lst@ifcountblanklines\else%
\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}


-
I understand that this suppresses the printing of the line numbers howver still increases the line counter. Is there a way to specify that an empty line does not increase the line counter? –  user9131 Nov 7 '11 at 17:40
@user9131: see my updated answer. –  Gonzalo Medina Nov 7 '11 at 17:48

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:

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\makeatletter
\makeatother
\lstset{numbers=left,numberblanklines=false}
\begin{document}
\begin{lstlisting}
First line.

Second line.

Third line.
\end{lstlisting}
\end{document}​

-
Yes, this is the way to go. –  Gonzalo Medina Nov 7 '11 at 18:08