[Tex/LaTex] Customize list of listings

table of contentstocloft

I want to make list of listings a bit different than what it gives by default.
For example for figures, I used package tocloft. It worked ok, I was wondering if tocloft could do the same for list of listings.
I want it for example just like this:

\renewcommand{\cftfigpresnum}{Figure }
\settowidth{\cftfignumwidth}{Figure 20\quad}
\setlength{\cftfignumwidth}{2.5cm}
\listoffigures

I already used the following lines:

 \renewcommand\lstlistlistingname{List of Programs}
 \addcontentsline{toc}{chapter}{List of Programs}
 \lstlistoflistings

But I want, in this case when the list is displayed to be for example Program 1.1 instead of 1.1 alone. How could I do this??

Thanks,
Claude

Best Answer

If the float package is not used, listing 'hi-jacks' the \@starttoc command and 'pretends' to typeset the ToC -- since this is all done in a group, the real ToC is not affected by this.

tocloft itself can't change such list of... that are not provided by the package itself or one of the standard classes.

The following code changes the \l@lstlisting command definition and inserts the word 'Program' before the listing number. \l@lstlisting is doing the same like \l@section etc.

The original definition in listings.sty is

\def\l@lstlisting#1#2{\@dottedtocline{1}{1.5em}{2.3em}{#1}{#2}}

The 1.5em width indicates the indentation, the 2.3em is meant for the width of the number box. Since \l@lstlisting#1#2 is redefined within a \renewcommand, I've to use ##1 and ##2 instead of #1 and #2 only.

enter image description here

\documentclass{book}


\usepackage{tocloft}
\usepackage{listings}


\makeatletter
\AtBeginDocument{%
\renewcommand\lstlistoflistings{\bgroup
  \let\contentsname\lstlistlistingname
  \def\l@lstlisting##1##2{\@dottedtocline{1}{1.5em}{2.3em}{\bfseries Program ##1}{##2}}
  \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{lol}}%
  \tableofcontents \egroup}
}
\makeatother

\begin{document}
\tableofcontents
\lstlistoflistings

\chapter{First}
\begin{lstlisting}[caption={My nice program},language=C]
#include<stdio.h>

int main(int argc,char **argv)
{
  printf("Hello World!\n");
  return(0);
}
\end{lstlisting}

\end{document}
Related Question