10

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!

lockstep
  • 250,273
  • Welcome to TeX.sx! Your question was migrated here from [so]. Please register on this site, too, and make sure that both accounts are associated with each other, otherwise you won't be able to comment on or accept answers or edit your question. – N.N. Mar 02 '12 at 08:08
  • 1
    See also http://tex.stackexchange.com/questions/28333/continuous-v-per-chapter-section-numbering-of-figures-tables-and-other-docume – lockstep Mar 02 '12 at 08:15

2 Answers2

6

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.

Thilo
  • 193
6

Listings are printed with the counter lstlisting. You can modify the way it prints and prepend the section number \thesection using

\renewcommand{\thelstlisting}{\thesection-\arabic{lstlisting}}

Here's a minimal example showing the same listing using two different numbering styles. Add the above code to your document preamble after loading the listings package.

enter image description here

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\begin{document}
\section{My section}
\begin{lstlisting}[
   language=Python,
   caption={Simple Python Program}
]
print "Hello, World!"
\end{lstlisting}

\renewcommand{\thelstlisting}{\thesection-\arabic{lstlisting}}

\begin{lstlisting}[
   language=Python,
   caption={Simple Python Program}
]
print "Hello, World!"
\end{lstlisting}
\end{document}

If all your listings use language=Python, you can perform a global setting via

\lstset{language=Python}
Werner
  • 603,163