My question is exactly the same as this one, but in my case some of the lines for which I would like to suppress line numbering are blank, and the accepted answer for that question produces an incorrect line count when there are blank lines between the suppress and reactivate commands (see screenshots below).
Note that my problem is not simply suppressing line numbers for blank lines, I know I can use numberblanklines=false for that. My problem is suppressing line numbers for specific lines that happen to be blank.
Here's the code I'm using:
\lstset{
basicstyle=\tiny\ttfamily,
numbers=left,
showlines=true,
tabsize=2,
escapeinside=??
}
\let\origthelstnumber\thelstnumber
\makeatletter
\newcommand*\Suppressnumber{%
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\relax%
\advance\c@lstnumber-\@ne\relax%
}%
}
\newcommand*\Reactivatenumber{%
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\origthelstnumber%
\advance\c@lstnumber\@ne\relax}%
}
\makeatother
Example 1 (no problem)
\begin{lstlisting}[
caption=Listing,
language=Scala,
frame=tlrb,
linewidth=\textwidth,
xleftmargin=0.25\textwidth,
xrightmargin=0.25\textwidth
]
// No blank lines between suppress and
// reactivate commands, no problem
def fib(n: Int): Int = n match {
case 0 | 1 => n
case _ => {
val fibNMinusOne = fib(n - 1)?\Suppressnumber?
?\Reactivatenumber?
val fibNMinusTwo = fib(n - 2)
fibNMinusOne + fibNMinusTwo
}
}
\end{lstlisting}
Result:
Example 2 (incorrect line count)
\begin{lstlisting}[
caption=Listing,
language=Scala,
frame=tlrb,
linewidth=\textwidth,
xleftmargin=0.25\textwidth,
xrightmargin=0.25\textwidth
]
// One blank line between suppress and
// reactivate commands, line count is incorrect
def fib(n: Int): Int = n match {
case 0 | 1 => n
case _ => {
val fibNMinusOne = fib(n - 1)?\Suppressnumber?
?\Reactivatenumber?
val fibNMinusTwo = fib(n - 2)
fibNMinusOne + fibNMinusTwo
}
}
\end{lstlisting}
Result:
Example 3 (no problem)
\begin{lstlisting}[
caption=Listing,
language=Scala,
frame=tlrb,
linewidth=\textwidth,
xleftmargin=0.25\textwidth,
xrightmargin=0.25\textwidth
]
// Non-blank line between suppress and
// reactivate commands, no problem
def fib(n: Int): Int = n match {
case 0 | 1 => n
case _ => {
val fibNMinusOne = fib(n - 1)?\Suppressnumber?
// Some comment, line is not blank anymore
?\Reactivatenumber?
val fibNMinusTwo = fib(n - 2)
fibNMinusOne + fibNMinusTwo
}
}
\end{lstlisting}
Result:
How can I suppress line numbers consistently for both blank and non-blank lines?


