[Tex/LaTex] Shared line counter with \lstinputlisting

line-numberinglistings

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}

Best Answer

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

enter image description here

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}