[Tex/LaTex] Create a \lstnewenvironment that creates named listings

environmentslistings

I am using the \lstnewenvironment to format a set of code listings in my document.

\lstnewenvironment{code}
    {\lstset{language=haskell,
    basicstyle=\small\ttfamily,
    numbers=left,
    numberstyle=\tiny\color{gray},
    backgroundcolor=\color{lightgray},
    firstnumber=auto
    }}
    {}

I would like to be able to give all these listings the same name, so that they will be continuously numbered, even if other listings (not using the code environment) are scattered in between them.

However I cannot add the name property using \lstset. The top of page 11 of the listings manual indicates that there are certain properties that can only be set as options directly on the listing (and not in \lstset). I suspect this is one of those properties. So I would have to do

\begin{code}[name=main]
...
\end{code}

on every listing. Is there some other way I can indicate that the code environment should always carry that name option?

Best Answer

Thanks to egreg, you can use a custom counter to keep track of the last line number and resume from there:

enter image description here

Code:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}

\newcounter{main}
\setcounter{main}{1}

\lstnewenvironment{code}[1][firstnumber=\themain,name=main]
  {\lstset{language=haskell,
           basicstyle=\small\ttfamily,
           numbers=left,
           numberstyle=\tiny\color{gray},
           backgroundcolor=\color{lightgray},
           #1
          }
}
{\setcounter{main}{\value{lstnumber}}}


\begin{document}
\begin{code}
 foo bar first line
 foo bar second line
 foo bar third line
\end{code}

some text

\begin{lstlisting}[backgroundcolor=\color{lightgray!20}]
  some other non-code listing
\end{lstlisting}


\begin{code}
 listing continued
\end{code}
\end{document}