per-section figures in un-numbered sections

I'm trying to write a document with un-numbered sections (i.e., \setcounter{secnumdepth}{0}) and numbered figures, with the figures numbered within section. I can't get secnumdepth and chngcntr to work together. The best I can get is:

\documentclass{article}

\usepackage{chngcntr}
\counterwithin*{figure}{section}
%\setcounter{secnumdepth}{0}

\begin{document}

\section{Section the First }

\begin{figure}[h]
\centering
\caption{Figure A}
\end{figure}

\begin{figure}[h]
\centering
\caption{Figure B}
\end{figure}

\section{Section the Second}

\begin{figure}[h]
\centering
\caption{Figure C}
\end{figure}

\end{document}


This gets the figure numbers right, but I have section numbers:

If I uncomment the line \setcounter{secnumdepth}{0}, the sections are unnumbered, as I want, but the figures are now 'counterwithout' again:

How do I achieve per-section figure numbering in unnumbered sections?

The reason why the counters are not reset is in the common \@sect code (see latex.ltx)

\def\@sect#1#2#3#4#5#6[#7]#8{%
\ifnum #2>\c@secnumdepth
\let\@svsec\@empty
\else
\refstepcounter{#1}%
\protected@edef\@svsec{\@seccntformat{#1}\relax}%
\fi
....


The code tests if the section level (#2) is greater than the value of secnumdepth. If this is not the case, the section counter is refstepped and all other counters in the reset list of the counter as well are reset.

However, if the counter is not reset, \counterwithout is useless here anyway (regardless whether \counterwithout* or \counterwithout is used)

One possibility could be to force \section to set the figure counter to zero automatically, however, this would be used with \section* too. I think this is not really a problem, however.

\documentclass{article}

%\usepackage{chngcntr}
\usepackage{xpatch}
\setcounter{secnumdepth}{0}
%\counterwithin*{figure}{section} Not needed any longer

\xpretocmd{\section}{\setcounter{figure}{0}}{}{} % Prepend the \section code with a figure counter reset.

\begin{document}

\section{Section the First }

\begin{figure}[h]
\centering
\caption{Figure A}
\end{figure}

\begin{figure}[h]
\centering
\caption{Figure B}
\end{figure}

\section{Section the Second}

\begin{figure}[h]
\centering
\caption{Figure C}
\end{figure}

\end{document}


• That works. If I do that, do I still need chngctr, or can I drop it? – Tyler Feb 18 '16 at 22:14
• @Tyler: Good point -- you can drop it, since there's nothing to hook into here (that's precisely the point why \counterwithout has no effect here) – user31729 Feb 18 '16 at 22:16