7

I want to include several listings in my document with sections. I also want each listing to have labels like Listing 2.1 where 2 is section number and 1 is number of given listing within that section. So far I was able to produce this code:

\documentclass[a4paper]{article}
\usepackage{listings}
\lstset{frame=Trbl,numbers=left}

\begin{document}
\renewcommand{\thelstlisting}{\thesection.\arabic{lstlisting}}

\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}

But this produces the following result: Produced result

How can I reset the counter after the beginning of each section?

  • This TEX.SE should solve this http://tex.stackexchange.com/questions/203790/per-section-figure-numbering-reset-counter-each-section – R. Schumacher Apr 16 '15 at 03:16
  • \numberwithin{lstlisting}{section} produces error No counter 'lstlisting' defined. \numberwithin{lstlisting}{section} – programagor Apr 16 '15 at 03:19

1 Answers1

7

Solution is to include package chngcntr and to place \counterwithin{lstlisting}{section} after \begin{document}. The complete code is then

\documentclass[a4paper]{article}
\usepackage{listings,chngcntr}
\lstset{frame=Trbl,numbers=left}
\usepackage{amsmath}

\begin{document}
\counterwithin{lstlisting}{section}

\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}

which produces the desired output: Correct output