5

I have a listing that I want to restate at some later point. How can I do this, without creating a new index for the restated listing?

My best approach so far has been to put the listing twice, which creates a new index for the second occurrence. If the label of the two duplicated listing is not changed, this in addition lead to a naming conflict.

\documentclass{article}
\usepackage{listings}
\begin{document}
\section{One}
\begin{lstlisting}[caption=Code,label=lst:code]
    x:=1;
\end{lstlisting}
Here, we introduce Listing~\ref{lst:code}.
\section{Two}
For convenience, we restate Listing~\ref{lst:code} here.
\begin{lstlisting}[caption=Code,label=lst:code]
    x:=1;
\end{lstlisting}
\end{document}

Picture

How do I avoid this?

Ideally, I would like to restate the listing without having to repeat its contents explicitly (this is possible for e.g. Lemmas using thm-restate). Essentially, I would like to obtain the same result as in this question, but for listings.

Peter
  • 485
  • Remove the caption of the 2nd listing and there will no 'index', i.e. a number. By the way, you're using the same label twice, which is a logical error –  Oct 18 '17 at 12:21
  • This still requires to duplicate the Listing. Ideally, I would like to avoid that. Also, I do want a caption for the 2nd listing. Essentially, the second listing should be a duplication of the first one. – Peter Oct 18 '17 at 12:26
  • \lstinputlisting could help to avoid the duplication of the content. – Daniel Oct 18 '17 at 14:12
  • Using title= instead of caption= for the second occurrence should prevent the additional label and index entry. Alternatively, try the nolol option to prevent inclusion of the second listing into the list of listings. – Daniel Oct 18 '17 at 14:14

1 Answers1

4

One option would be to externalise the listings's content as an extra file inserted with \lstinputlisting and construct the caption of the second instance from the label set in the first instance:

\documentclass{article}
\usepackage{listings,hyperref,filecontents}
\begin{document}

% only for MWE purposes (to create a file we can load with \lstinputlisting)
\begin{filecontents*}{mycode.pas}
  x:=1;
\end{filecontents*}


\section{One}
\lstinputlisting[caption=Code,label=lst:code]{mycode.pas}
Here, we introduce Listing~\ref{lst:code}.

\section{Two}
For convenience, we restate Listing~\ref{lst:code} here.
\lstinputlisting[title=\lstlistingname~\ref{lst:code}: \nameref{lst:code}]{mycode.pas}
\end{document}

enter image description here

Daniel
  • 37,517