示例 1(没有问题)

示例 1(没有问题)

我的问题与这个但是就我而言,我想抑制行号的某些行是空白的,并且当抑制和重新激活命令之间存在空白行时,该问题的接受答案会产生不正确的行数(参见下面的屏幕截图)。

请注意,我的问题不仅仅是抑制空白行的行号,我知道我可以用numberblanklines=false它。我的问题是隐藏恰好为空白的特定行的行号。

这是我正在使用的代码:

\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

示例 1(没有问题)

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

结果:

示例 1 结果

示例 2(行数不正确)

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

结果:

示例 2 结果

示例 3(没问题)

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

结果:

示例 3 结果

如何才能一致地抑制空白行和非空白行的行号?

相关内容