As question Count and use the number of items in advance mentioned, I have the same demand, but mine is more advanced.
Here I have some enumerates, some of them begin with [resume]
paramater, some of them have nested enumerate. I want to compute the number of the first level items of each enumerate. For example
I wrote codes below:
\documentclass{article}
\usepackage{enumitem}
\makeatletter
\newcounter{totalitems}
\newcounter{beginitems}
\newcounter{enditems}
\let\@numerate\enumerate
\def\enumerate{%
\setcounter{beginitems}{\arabic{enumi}}
\@numerate
}
\let\end@numerate\endenumerate
\def\endenumerate{
\end@numerate%
\setcounter{enditems}{\arabic{enumi}}
\setcounter{totalitems}{\numexpr \c@enditems - \c@beginitems \relax}
}
\makeatother
\begin{document}
\begin{enumerate}
\item one
\item two
\end{enumerate}
total = \thetotalitems, begin = \thebeginitems, end = \theenditems
\begin{enumerate}[resume]
\item three
\begin{enumerate}
\item a nested enumerate
\end{enumerate}
\end{enumerate}
total = \thetotalitems, begin = \thebeginitems, end = \theenditems
\begin{enumerate}
\item one
\item two
\end{enumerate}
total = \thetotalitems, begin = \thebeginitems, end = \theenditems
\end{document}
it produced:
As we can see there are some things goes wrong
- When there is nested enumerate, the
beginitems
counter is wrong - When there is no
[resume]
paramater, thebeginitems
counter didn't been reset to 0.
Where should I change to reach my demand?
Best Answer
You need to postpone
\setcounter{beginitems}{\arabic{enumi}}
to after theenumerate
environment was initiated, so essentially after\begin{enumerate}
or\begin{enumerate}[resume]
respectively. You need to take into account that\begin{environment}
may have one optional argument.I am not totally sure, but I think, using
\LetLtxMacro
instead of a plain\let
and\renewcommand
instead of\def
is a bit more secure here:Now, you still may have the problem that the counters are affected every time, an
enumerate
environment starts, which may cause wrong results whenenumerate
environments are nested. I did not test this thouroughly.