Search code examples
latexlistingslstlisting

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 First 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.


Solution

  • 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}
    }{
    }