Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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.

share|improve this answer
    
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 '13 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 '13 at 10:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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