1

I'd like to have a counter that resets whenever a display math environment is entered, numbered or not. How do I accomplish that?

The code below produces zeros only for the actual equation environments.

\documentclass{article}


\usepackage{amsmath}
\newcounter{mycounter}[equation]

\begin{document}

\setcounter{mycounter}{23}  
\begin{equation}
x\themycounter
\end{equation}

\setcounter{mycounter}{23}
\[
y\themycounter
\]

\setcounter{mycounter}{23}
\begin{multline}
a\\=b\themycounter
\end{multline}


\begin{equation}
z\themycounter
\end{equation}
Counter mycounter should reset in any equation--like environment, numbered or not.
\end{document}
  • 1
    A bit risky, but \everydisplay\expandafter{\the\everydisplay\setcounter{mycounter}{0}} might work. – Phelype Oleinik Sep 9 '19 at 21:24
  • What's risky about it? – JPi Sep 10 '19 at 0:25
  • 1
    Not risky in the strict sense of the word, but there might be some code which carelessly changes the contents of \everydisplay, or some code which relies on the contents of \everydisplay. In the former case, your setting will be lost and your code won't work. In the latter case something might break badly. You just need to have in mind that it may break something, somewhere. If it doesn't, go for it :-) – Phelype Oleinik Sep 10 '19 at 0:36
  • Thank you @PhelypeOleinik – JPi Sep 11 '19 at 21:54
4

Use \AtBeginEnvironment from etoolbox.

\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}

\newcounter{mycounter}
\AtBeginEnvironment{equation}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{equation*}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{align}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{align*}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{gather}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{gather*}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{multline}{\setcounter{mycounter}{0}}
\AtBeginEnvironment{multline*}{\setcounter{mycounter}{0}}

\begin{document}

\setcounter{mycounter}{23}  
\begin{equation}
x\themycounter
\end{equation}

\setcounter{mycounter}{23}
\[
y\themycounter
\]

\setcounter{mycounter}{23}
\begin{multline}
a\\=b\themycounter
\end{multline}

\begin{align}
z\themycounter&=y\\
t\themycounter&=u
\end{align}

\begin{align*}
z\themycounter&=y\\
t\themycounter&=u
\end{align*}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.