# How do I define a counter which resets whenever a display equation environment is entered?

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}
$$x\themycounter$$

\setcounter{mycounter}{23}
$y\themycounter$

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

$$z\themycounter$$
Counter mycounter should reset in any equation--like environment, numbered or not.
\end{document}

• 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
• 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

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}
$$x\themycounter$$

\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}