# Shared line counter with \lstinputlisting

Using the listings package, you can name your listings to make them share a line counter:

On the other hand you can use firstnumber=auto and name your listings. Listings with identical names (case sensitive!) share a line counter.

However, this only seems to work when the lstlisting environment is used, not when using \lstinputlisting. After a closer examination of the manual, this seems to be documented:

name=<name>

names a listing. Displayed environment-listings with the same name share a line counter if firstnumber=auto is in effect.

I was wondering if anyone knows some kind of "trick" to share line counters across \lstinputlistings.

Here is a MWE to demonstrate the issue:

\documentclass{article}
\usepackage{listings}
\lstset{numbers=left,firstnumber=auto}

\begin{document}
\begin{lstlisting}[name=bar]
...
\end{lstlisting}
\begin{lstlisting}[name=bar] %first line number is the last of previous listing + 1
...
\end{lstlisting}
\lstinputlisting[name=foo]{foo.c}
\lstinputlisting[name=foo]{foo.c} %first line number is 1
\end{document}

-
I am using the latest version if the listings package (TeXLive 2011) and it seems that the numbering does not resume in any of the cases. –  Peter Grill Apr 8 '12 at 18:08
@Peter: That's weird, I'm using the same version and it works for the environment case. Did you try my MWE verbatim? –  Job Apr 9 '12 at 6:53
Yep, just cut and pasted the given MWE. I also confirmed that I see identical behavior with TeXLive2010. I noticed the message Package Listings Warning: Text dropped after begin of listing on input line 10. in the console though, so perhaps my problem is related to that. –  Peter Grill Apr 9 '12 at 14:25
Related Question: Create a \lstnewenvironment that creates named listings. –  Peter Grill Jun 22 '12 at 20:32
Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count (see How do you accept an answer?). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers. –  Jubobs Mar 1 at 22:01

You can use name=foo, firstnumber=last option to \lstinputlisting to obtain the desired results as shown in the yellow highlighted code:

## Code:

\documentclass{article}

\begin{filecontents*}{foo.c}
#include <stdio.h>
void main()
\end{filecontents*}

\usepackage{listings}
\usepackage{xcolor}
\lstset{numbers=left,firstnumber=auto}

\begin{document}
\begin{lstlisting}[name=bar]
first line
second line
\end{lstlisting}
\begin{lstlisting}[name=bar]
third line (continued)
\end{lstlisting}

\lstinputlisting[name=foo,backgroundcolor=\color{yellow!20}]{foo.c}
\lstinputlisting[name=foo,backgroundcolor=\color{yellow!20}, firstnumber=last]{foo.c} %first line number is now 3
\end{document}

-