24

I'm using the listings package to put a box around some source code in a document and also to provide some syntax hilighting. Is there an easy way that I could create a table of contents which just listed the code listings? I have already used the figure listing for actual figures and I would rather not mix figures and code listings. Is there perhaps a way I could build two distinct figures collections?

stimms
  • 483

3 Answers3

44

One could use the \lstlistoflistings macro that is part of the listings package.

\documentclass{article}

\usepackage{listings}

\begin{document}

\lstlistoflistings

\section{foo}

\begin{lstlisting}[caption={A listing}]
    Some source code
\end{lstlisting}

\end{document}
lockstep
  • 250,273
  • Compared to the solution of stimms, could you say which one would be nicer? Defining this code environment looks more consistent to table and figure. – Albert Jul 07 '20 at 21:37
14

I figured this out. What I did was

\usepackage{caption}
\DeclareCaptionType{code}[Code Listing][List of Code Listings] 
\begin{document}
...
\listofcodes
...
\begin{code}
\begin{lstlisting}
    Some source code
\end{lstlisting}
\caption[This here is a caption]{caption}
\end{code}

This creates a table of blocks of code. Super nifty.

stimms
  • 483
-1

combining stimms's and lockstep's solution I did this:

  • use no extra environment
  • call lstlistings "Code"
  • call lstlistoflistings "List of Code Snippets"
\documentclass{article}

\usepackage{listings} \renewcommand{\lstlistingname}{Code} % adjusts Listings caption and reference lst \renewcommand{\lstlistlistingname}{List of Code Snippets} \begin{document}

\lstlistoflistings

\section{foo}

\begin{lstlisting}[caption={A code snippet}] Some source code \end{lstlisting}

\end{document}

A code snippet lstlistings

The list of all code snippets enter image description here