[Tex/LaTex] Continue line numbers in listings package

line-numberinglistings

I have been using the listings package to present my source code in LaTeX. However, I can't get the line numbers to continue between two separate user-defined listings that have been given the same name. For example, the following code just seems to start the line number at 1 for each listing block rather than sequentially numbering them:

\usepackage{listings}

\lstnewenvironment{bash}[1][]{
#1,
language = bash,
numbers = left,
firstnumber = auto}

\begin{document}

\begin{bash}[name=Test]
echo xyz
\end{bash}
\begin{bash}[name=Test]
echo xyz
\end{bash}

\end{document}

I'm aware I can set the number manually each time with \firstnumber = last, but this kind of defeats the object of naming your listing. I presume I'm missing something here. Any help would be greatly appreciated.

Best Answer

A slightly different approach from Heiko's fine answer:

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

\lstnewenvironment{bash}[1][]
  {\lstset{language=C}\lstset{%
   numbers=left,numberstyle=\normalsize,stepnumber=1,numbersep=5pt,
   framesep=5pt,
   basicstyle=\normalsize\ttfamily,
   showstringspaces=false,
   keywordstyle=\itshape\color{blue},
   stringstyle=\color{maroon},
   commentstyle=\color{black},
   xleftmargin=5pt,
   xrightmargin=5pt,
   aboveskip=\bigskipamount,
   belowskip=\bigskipamount,
   backgroundcolor=\color{gray!20}, #1
}}
{}


%
%%% Always I forget this so I created some aliases
\def\ContinueLineNumber{\lstset{firstnumber=last}}
\def\StartLineAt#1{\lstset{firstnumber=#1}}
\let\numberLineAt\StartLineAt



\begin{document}

\begin{bash}[name=Test]
echo xyz
\end{bash}

\StartLineAt{30}
\begin{bash}[name=Test]
echo xyz
\end{bash}

\ContinueLineNumber


\begin{bash}[name=Test]
echo xyz
\end{bash}

\end{document}

The code offers two macros that I personally find convenient

 \ContinueLineNumber

and

 \StartLineAt

If you wouldn't like all your code to have consecutive numbering you might find it useful.

Related Question