开发者

Using listings, how do I maintain grouping of listing numbers?

I'm using the listings package for showing code, as well as algorithms in pseudocode.

This is what I would like happen:

Algorithm 1.1: myFirstAlgorithm()
    ... content ...
Algorithm 1.2: mySecondAlgorithm()
    ... content ...
Code 1.1: My Fi开发者_如何学编程rst Code Block
    ... content ...
Algorithm 1.3: myThirdAlgorithm()
    ... content ...

While this is what I get:

Algorithm 1.1: myFirstAlgorithm()
    ... content ...
Algorithm 1.2: mySecondAlgorithm()
    ... content ...
Code 1.3: My First Code Block
    ... content ...
Algorithm 1.4: myThirdAlgorithm()
    ... content ...

To change the caption name, I'm using \renewcommand*{\lstlistingname}{Code} and \renewcommand*{\lstlistingname}{Algorithm}.

There might be a better way to do this, but in any case I'm still clueless as to how to reset the numbering, or how to keep track of grouping. Any help would be greatly appreciated.


In spite of my comment above, here's some code to create two new environments, algorithm and code, that do what you ask for.

\newcounter{oldlstlisting}
\newcounter{algorithm}[chapter]
\newcounter{code}[chapter]

\lstnewenvironment{algorithm}[1][]{
    \setcounter{oldlstlisting}{\value{lstlisting}}
    \setcounter{lstlisting}{\value{algorithm}}
    \renewcommand*{\lstlistingname}{Algorithm}
    \lstset{#1}
}{
    \stepcounter{algorithm}
    \setcounter{lstlisting}{\value{oldlstlisting}}
}
\lstnewenvironment{code}[1][]{
    \setcounter{oldlstlisting}{\value{lstlisting}}
    \setcounter{lstlisting}{\value{code}}
    \renewcommand*{\lstlistingname}{Code}
    \lstset{#1}
}{
    \stepcounter{code}
    \setcounter{lstlisting}{\value{oldlstlisting}}
}

Usage:

\begin{algorithm}[caption={myFirstAlgorithm()}]
    ... content ...
\end{algorithm}

\begin{algorithm}[caption={mySecondAlgorithm()}]
    ... content ...
\end{algorithm}

\begin{code}[caption={My First Code Block}]
    ... content ...
\end{code}

\begin{algorithm}[caption={myThirdAlgorithm()}]
    ... content ...
\end{algorithm}

These number by chapter, as you probably intended, and are numbered independently of "regular" lstlisting environments. Furthermore, you can specify additional \lstset arguments (e.g. language=...) in the environment definition, if you want.


Update: To use the same numbering for all of them, just remove all counter-related code:

\lstnewenvironment{algorithm}[1][]{
    \renewcommand*{\lstlistingname}{Algorithm}
    \lstset{#1}
}{
}
\lstnewenvironment{code}[1][]{
    \renewcommand*{\lstlistingname}{Code}
    \lstset{#1}
}{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜