Combine \listoflistings and \listofalgorithms – Creating Unified Lists in LaTeX

algorithmslistingstable of contents

The title said it all…I want to combine the two under one list with the title "Algorithms and program code". Style wise the page should match the usual style of the other lists (\listoffigures, \listoftables, … itd.). Is there a way to do this?

Best Answer

The contents lines and environment counters are added/incremented by \caption. So to change the list that an environment appears on, the caption command can be modified/extended. To keep the two environments in numerical sequence (ie as if they were the same environment) one can be incremented when the other is caption'd.

\documentclass{report}

\usepackage{listings}
\usepackage{algorithm}
\usepackage{etoolbox} % provides AtBeginEnvironment

% make a new caption command for algorithms
\newcommand{\algCaption}[1]{
    \caption{#1}
    \addcontentsline{lol}{lstlisting}{\protect\numberline{\thealgorithm}#1}
    \addtocounter{lstlisting}{1}}
\AtBeginEnvironment{lstlisting}{\addtocounter{algorithm}{1}}

\begin{document}
    \begin{algorithm}
        This is an algorithm
        \algCaption{An algorithm}
    \end{algorithm}
    \begin{lstlisting}[caption=A listing]
        This is a listing
    \end{lstlisting}
    \clearpage%
    \begin{algorithm}
        This is another algorithm
        \algCaption{Another algorithm}
    \end{algorithm}
    \lstlistoflistings%
    \listofalgorithms%
\end{document}

The MWE defines algCaption that adds its argument to the lstlisting and then increments the lstlisting counter. Whenever a lstlisting environment is used, the algorithm counter is incremented with AtBeginEnvironment. One problem that I can see with this solution is that there is still a listofalgorithms being produced by caption.

Related Question