[Tex/LaTex] listings caption number

listingsnumbering

I'm using the listings package with this \begin command:

\begin{lstlisting}[
   language=Python,
   caption={Simple Python Program},
]

This yields a nice code listing with a caption like "Listing 1 Simple Python Program".
Is there a way to change the caption and have something like "Listing 1-1 Simple Python Program" in which the 1-1 is the combination of the section number and the subsection number?

Any hint will be greatly appreciated!

Best Answer

You could also use something like this in your document preamble:

\usepackage{chngcntr}
\AtBeginDocument{\counterwithin{lstlisting}{section}}

This would resemble the same behaviour as:

\renewcommand{\thelstlisting}{\thechapter.\thesection.\arabic{lstlisting}}

But I think the first variant is much cleaner and more flexible. You could specify \AtBeginDocument{\counterwithin{lstlisting}{subsection}} just as well.

Or \AtBeginDocument{\counterwithin{lstlisting}{chapter}} if you like.

I hope this helps.

Related Question