参照跳过行号并从特定数字继续我尝试跳过清单中的几个行号,然后继续使用特定编号。但在我的例子中,有一个非常糟糕的副作用:之后的每一行\Reactivatenumber{...}
都有相同的编号。而且新清单的编号与上一个清单中定义的编号相同\Reactivatenumber{...}
我的例子:
\documentclass{article}
\usepackage{listings}
\lstset{numbers=left,numberblanklines=false,escapeinside=||}
\let\origthelstnumber\thelstnumber
\makeatletter
\newcommand*\Suppressnumber{%
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\relax%
\advance\c@lstnumber-\@ne\relax%
}%
}
\newcommand*\Reactivatenumber[1]{%
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\origthelstnumber%
\setcounter{lstnumber}{\numexpr#1-1\relax}%
%\advance\c@lstnumber\@ne\relax%
}%
}
\makeatother
\begin{document}
First listing:
\begin{lstlisting}[firstnumber=1]
var myFunc = function() {|\Suppressnumber|
//my function does many great things
//and it's only 10 lines long!|\Reactivatenumber{12}|
}
var oneMoreFunc = function() {
return myFunc;
}
\end{lstlisting}
One more listing:
\begin{lstlisting}[firstnumber=18]
var something = "bla";
console.log(something);
\end{lstlisting}
\end{document}
有人能帮助我吗?
答案1
将您的定义更改为
\newcommand*\Reactivatenumber[1]{%
\setcounter{lstnumber}{\numexpr#1-1\relax}
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\origthelstnumber%
\refstepcounter{lstnumber}
}%
}
完整代码:
\documentclass{article}
\usepackage{listings}
\lstset{numbers=left,numberblanklines=false,escapeinside=||}
\let\origthelstnumber\thelstnumber
\makeatletter
\newcommand*\Suppressnumber{%
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\relax%
\advance\c@lstnumber-\@ne\relax%
}%
}
\newcommand*\Reactivatenumber[1]{%
\setcounter{lstnumber}{\numexpr#1-1\relax}
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\origthelstnumber%
\refstepcounter{lstnumber}
}%
}
\makeatother
\begin{document}
First listing:
\begin{lstlisting}[firstnumber=1]
var myFunc = function() {|\Suppressnumber|
//my function does many great things
//and it's only 10 lines long!|\Reactivatenumber{12}|
}
var oneMoreFunc = function() {
return myFunc;
}
}
var oneMoreFunc = function() {
return myFunc;
}
\end{lstlisting}
One more listing:
\begin{lstlisting}[firstnumber=18]
var something = "bla";
console.log(something);
}
var oneMoreFunc = function() {
return myFunc;
}
\end{lstlisting}
\end{document}
答案2
对上一个正确答案的一个小补充。在行末:
\refstepcounter{lstnumber}%
应该有一个“%”。省略此符号将导致后续内联列表格式不正确。
重新激活命令如下:
\newcommand*\Reactivatenumber[1]{%
\setcounter{lstnumber}{\numexpr#1-1\relax}
\lst@AddToHook{OnNewLine}{%
\let\thelstnumber\origthelstnumber%
\refstepcounter{lstnumber}%
}%
}