如果我把所有代码都写在一个框里codebox
,页面就会满满的。如果我把代码写在两个框里,行数计数器就会从 1 重新开始。
我怎样才能保存行计数器?
答案1
这是一个初步版本,至少用于手动换行,使用\codeboxcontinuedtrue
和\codeboxcontinuedfalse
最后一行号始终存储在 a 的末尾,如果计算结果为 ,则codebox
可能会重新注入到计数器中。codelinenumber
\ifcodeboxcontinued
true
\documentclass{article}
\usepackage{clrscode3e}
\usepackage{xpatch}
\newcounter{lastcodelinenumber}
\newif\ifcodeboxcontinued
\xapptocmd{\endcodebox}{%
\setcounter{lastcodelinenumber}{\value{codelinenumber}}%
\global\codeboxcontinuedfalse
}{}{}
\xapptocmd{\codebox}{%
\ifcodeboxcontinued
\setcounter{codelinenumber}{\value{lastcodelinenumber}}%
\fi
}{}{}
\newcommand\continuecodebox{\global\codeboxcontinuedtrue}
\begin{document}
\begin{codebox}
\Procname{$\proc{Insertion-Sort}(A)$}
\li \For $j \gets 2$ \To $\attrib{A}{length}$
\li \Do
$\id{key} \gets A[j]$
\li \Comment Insert $A[j]$ into the sorted sequence
$A[1 \twodots j-1]$.
\li $i \gets j-1$
\li \While $i > 0$ and $A[i] > \id{key}$
\li \Do
$A[i+1] \gets A[i]$
\li $i \gets i-1$
\End
\li $A[i+1] \gets \id{key}$
\End
\end{codebox}
\clearpage % a manual break that would be necessary
\continuecodebox
\begin{codebox}
\li \For $j \gets 2$ \To $\attrib{A}{length}$
\li \Do
$\id{key} \gets A[j]$
\li \Comment Insert $A[j]$ into the sorted sequence
$A[1 \twodots j-1]$.
\li $i \gets j-1$
\li \While $i > 0$ and $A[i] > \id{key}$
\li \Do
$A[i+1] \gets A[i]$
\li $i \gets i-1$
\End
\li $A[i+1] \gets \id{key}$
\End
\li \For $j \gets 2$ \To $\attrib{A}{length}$
\li \Do
$\id{key} \gets A[j]$
\li \Comment Insert $A[j]$ into the sorted sequence
$A[1 \twodots j-1]$.
\li $i \gets j-1$
\li \While $i > 0$ and $A[i] > \id{key}$
\li \Do
$A[i+1] \gets A[i]$
\li $i \gets i-1$
\End
\li $A[i+1] \gets \id{key}$
\End
\li \For $j \gets 2$ \To $\attrib{A}{length}$
\li \Do
$\id{key} \gets A[j]$
\li \Comment Insert $A[j]$ into the sorted sequence
$A[1 \twodots j-1]$.
\li $i \gets j-1$
\li \While $i > 0$ and $A[i] > \id{key}$
\li \Do
$A[i+1] \gets A[i]$
\li $i \gets i-1$
\End
\li $A[i+1] \gets \id{key}$
\End
\end{codebox}
\end{document}