How many times is “align” processed?

Consider the following MWE which writes the word "Cat" to a file.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
\newwrite\datei
\immediate\openout\datei=Beispiel.txt
\begin{align*}
a+b &=c \\ \immediate\write\datei{Cat}
c+d &= 88+ 9
\end{align*}
\end{document}


Actually, this writes the word "Cat" twice (I have more complicated examples, where it is written four times).

1. Can I determine how many times is an align processed?

2. Can I somehow ensure that the writing command is only called once?

-

amsmath uses the conditional \ifmeasuring@ which is true in the first steps when things are measured and false during the "typesetting step". So you can say

\makeatletter
\newcommand{\alignwrite}[2]{%
\ifmeasuring@\else
\write#1{#2}%
\fi}
\makeatother


and \immediate\alignwrite\datei{Cat} will be executed only on the "typesetting step".

Here's the complete example:

\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand{\alignwrite}[2]{%
\ifmeasuring@\else
\write#1{#2}%
\fi}
\makeatother

\begin{document}
\newwrite\datei
\immediate\openout\datei=Beispiel.txt
\begin{align*}
a+b &=c \\ \immediate\write\datei{Cat}
c+d &= 88+ 9
\end{align*}

\begin{align*}
a+b &=c \\ \immediate\alignwrite\datei{Dog}
c+d &= 88+ 9
\end{align*}
\end{document}


The contents of Beispiel.txt is

Cat
Cat
Dog


This uses the fact that \immediate which is not followed by \write or \closeout is ignored, but it expands the following token to see what really follows.

-
Can I rely on \ifmeasuring@ being false everywhere OUTSIDE a math environment? Then I could include your \alignwrite in commands which can be used everywhere in the document. –  JF Meier Mar 30 at 9:19
@JFMeier amsmath always does \begingroup\measuring@true, so the conditional is set to true inside a group (and no \global is used in this context). So you should be safe. –  egreg Mar 30 at 10:28