[Tex/LaTex] Numbering of listings

listingsnumbering

I would like to numerate listings according to sections. If the listing is in subsection then it should have subsection numbers.

This example is very good and I'm using it for some other numbering, but it gives me error because I can't seem to guess the parameter for renewcommand

\renewcommand{\thelstlistingname}{%
  \ifnum\value{subsection}=0
    \thesection.\arabic{lstlistingname}%
  \else
    \ifnum\value{subsubsection}=0
      \thesubsection.\arabic{lstlistingname}%
    \else
      \thesubsubsection.\arabic{lstlistingname}%
    \fi
  \fi
}

This is the MWE

\documentclass[11pt]{article}
\usepackage{listings}
\renewcommand{\lstlistingname}{Pseudokod} 

\begin{document}
\section{Section}
\subsection{Subsection}

\begin{lstlisting}
  ...
  ucitaj sliku
  ucitaj zeljeni prag ili pragove za segmentaciju
  podijeli sliku na kanale //ako je u pitanju RGB slika podijela je na R, G i B kanal boje
  primjeni prag na svakom kanalu
  AND operacija na kanalima
  prikazi sliku
  ...
\end{lstlisting}
\end{document}  

Since the listing is in section 1.1 I would like it to be numbered like 1.1.1. Next listing in that section would be 1.1.2, etc.

Best Answer

I'm not sure to understand exactly what you want to achieve.

In any case, the right counter is lstlisting and gets defined only after the document has begun.

So, you can either put the following code after \begin{document}

\renewcommand{\thelstlisting}{%
  \ifnum\value{subsection}=0
    \thesection.\arabic{lstlisting}%
  \else
    \ifnum\value{subsubsection}=0
      \thesubsection.\arabic{lstlisting}%
    \else
      \thesubsubsection.\arabic{lstlisting}%
    \fi
  \fi
}

or the following in the preamble

\AtBeginDocument{%
  \renewcommand{\thelstlisting}{%
    \ifnum\value{subsection}=0
      \thesection.\arabic{lstlisting}%
    \else
      \ifnum\value{subsubsection}=0
        \thesubsection.\arabic{lstlisting}%
      \else
        \thesubsubsection.\arabic{lstlisting}%
      \fi
    \fi
  }
}

The result is the same, but I would suggest the latter.