[Tex/LaTex] Number listings the same way as figures and tables

listingsnumbering

For numbering figures and tables with 1 depth level like this:

Figure 1.2
Table 3.13

I use the package:

\usepackage{chngcntr}
\counterwithin{figure}{section}
\counterwithin{table}{section}
\numberwithin{equation}{section}

I wanted to get the same effect for code listings usepackage listings but the compiler says that chngcntr doesnt support listings. How can I accomplish this effect? I would appreciate all help.

Best Answer

Here is a solution.

The counter lstlisting is defined using \AtBeginDocument so the change must be done after \begin{document} or using \AtBeginDocument

\documentclass{book}
\usepackage{lipsum}
\usepackage{listings}
\usepackage{chngcntr}
\AtBeginDocument{\counterwithin{lstlisting}{chapter}}
\begin{document}
\chapter{Foo}
\begin{lstlisting}[caption={bla bla},label=list]
for i:=maxint to 0 do
begin
{ do nothing }
end;

Write(’Case insensitive ’);
WritE(’Pascal keywords.’);
\end{lstlisting}
\section{Foo}
\begin{lstlisting}[caption={bla bla},label=list]
for i:=maxint to 0 do
begin
{ do nothing }
end;

Write(’Case insensitive ’);
WritE(’Pascal keywords.’);
\end{lstlisting}
\end{document}