[Tex/LaTex] Caption and sections, subsections and subsubsections

captionsgraphics

I'm writing my thesis in Latex and this is the first time ever for me to use it. I've figured out a lot of things except this one – I need custom captions for pictures that are connected with sections, subsections, etc. I've put this lines in my preamble

\usepackage{chngcntr}
\counterwithin{figure}{section}
\counterwithin{figure}{subsection}
\counterwithin{figure}{subsubsection}

but when I'm using images in section it looks like this: Image with subsubsection that doesn't match
And it should look like this:
The way it should look like

What I need is a way to keep this look in subsections and subsubsections, but not in sections.

Best Answer

We add the figure counter to the reset list of every relevant sectioning command; then we redefine \thefigure to check (from top to bottom) which is the lowest level non zero sectional counter. Finally, with the help of tocloft, we increase the space reserved for the figure numbers in the list of figures.

\documentclass{article}
\usepackage{chngcntr,tocloft}
\counterwithin*{figure}{section}
\counterwithin*{figure}{subsection}
\counterwithin*{figure}{subsubsection}

\addtolength{\cftfignumwidth}{2em}


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

\begin{document}
\listoffigures
\section{A section}
\begin{figure}[!htp]
\caption{section.figure}
\end{figure}
\subsection{A subsection}
\begin{figure}[!htp]
\caption{subsection.figure}
\end{figure}
\begin{figure}[!htp]
\caption{subsection.figure}
\end{figure}
\subsubsection{A subsubsection}
\begin{figure}[!htp]
\caption{subsubsection.figure}
\end{figure}
\subsection{A subsection}
\begin{figure}[!htp]
\caption{subsection.figure}
\end{figure}
\section{A section}
\begin{figure}[!htp]
\caption{section.figure}
\end{figure}

\end{document}

enter image description here