1

I would like to increase a counter whenever the command \item is called.

Of course, the following code

\renewcommand{\item}{\item\stepcounter{counterNbQuestions}}

will not work.

How can I do?


Edit

The following code does work.

\documentclass{article}

\usepackage{etoolbox}
\usepackage{totcount}

\newtotcounter{mycounter}
\preto\item{\refstepcounter{mycounter}}

\begin{document}

Total : \total{mycounter} items

\begin{enumerate}
\item Test
\item Test
\item \begin{enumerate}
\item Test
\item Test
\end{enumerate}
\end{enumerate}

\end{document}
6
  • 2
    etoolbox \prepto\item{\refstepcounter{... (really you should put it before not after, as otherwise you break the optional argument \item[zzz] otherwise use \appto) Commented Nov 14, 2020 at 9:39
  • The above comment is the general case for any command, but for \item it already is configured to increment a counter (so enumerate works) You have given no use case but probably you should just define a standard latex list using the counterNbQuestions counter, either directly or using the enumitem package. Commented Nov 14, 2020 at 9:46
  • Your solution seems not to work. I will create a MWE. I need to stick to enumerate environments and the \item command. Thanks for your help.
    – Colas
    Commented Nov 14, 2020 at 9:51
  • Question edited: I have added a MWE
    – Colas
    Commented Nov 14, 2020 at 10:07
  • 5
    you should of course do what I mean not what I type sorry try \preto (no middle p) Commented Nov 14, 2020 at 10:09

1 Answer 1

2

The following code does work.

\documentclass{article}

\usepackage{etoolbox}
\usepackage{totcount}

\newtotcounter{mycounter}
\preto\item{\refstepcounter{mycounter}}

\begin{document}

Total : \total{mycounter} items

\begin{enumerate}
\item Test
\item Test
\item \begin{enumerate}
\item Test
\item Test
\end{enumerate}
\end{enumerate}

\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .