# [Tex/LaTex] Listings numbering doesn’t restart

listingsnumbering

I have problem with listing numbering from this topic. Numbering isn't restarted, it just continues.

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


For subsubsection 4.2.1 it should start from the beginning but it continues so I'm getting 4.2.1.2 (because there is one previous listing).

It's no different from what I already suggested you as answer to Caption and sections, subsections and subsubsections

The only addition is that \AtBeginDocument is necessary, because listings defines there the counter.

\documentclass{article}
\usepackage{listings,chngcntr}

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

\begin{document}
\section{A section}
\begin{lstlisting}[caption=Caption]
\caption{section.lstlisting}
\end{lstlisting}
\subsection{A subsection}
\begin{lstlisting}[caption=Caption]
\caption{subsection.lstlisting}
\end{lstlisting}
\begin{lstlisting}[caption=Caption]
\caption{subsection.lstlisting}
\end{lstlisting}
\subsubsection{A subsubsection}
\begin{lstlisting}[caption=Caption]
\caption{subsubsection.lstlisting}
\end{lstlisting}
\subsection{A subsection}
\begin{lstlisting}[caption=Caption]
\caption{subsection.lstlisting}
\end{lstlisting}
\section{A section}
\begin{lstlisting}[caption=Caption]
\caption{section.lstlisting}
\end{lstlisting}

\end{document}