# Using pgffor and line breaks inside math environments

Today I decided to try to typeset a humorous list enumerating all 7! valid iterated integrals for a 7-dimensional integral (It takes 361 pages in the version that does compile) but I'm running into very unhelpful errors when I try to add the last bit of polish. I learned how to use pgffor to generate the permutations, but trying to run my code with nice alignments breaks it.

Since the 7 variable code is a bit unwieldy, I've reproduced the two-variable case here. This works:

\documentclass{article}
\usepackage{pgffor}
\usepackage{amsmath}

\newcommand*\diff{\mathop{}\!d}
\begin{document}
$$\iint_B f(x, y) \foreach \a/\b/\x in {a/b/x, c/d/y} \foreach \c/\d/\y in {a/b/x, c/d/y} { \ifx \y \x \else = \int_\a^\b \int_\c^\d f(x, y) \diff\x \diff\y \fi }$$
\end{document}


But of course it's all on one line. If I add \\ to the end of \int_\a^\b \int_\c^\d f(x, y) \diff\x \diff\y, it doesn't actually break the lines since equation doesn't support multiline equations. Here's where things get confusing for me:

If I change the environment to multline I get a pile of errors starting with

! Missing \endgroup inserted.


If I change the environment to AMSMath's align then I get the rather similar looking

! Extra }, or forgotten \endgroup.


If I add a & for alignment without the line breaks (to prevent the other error) then I get the following error:

! Incomplete \ifx; all text was ignored after line 16.


How can I use the combination of pgffor, amsmath's align environment, and alignment/linebreak commands? More generally, why doesn't pgffor play nice with these macros?

• It is not really anything to do with pgffor. Try, for example, \begin{gather*} {% ij kl\\ } \end{gather*}. – cfr Oct 27 '15 at 0:41
• I think what you are trying to do is the structural equivalent of something like \begin{tabular}{c} {some stuff\\}\end{tabular}. These environments are essentially like sophisticated array or tabular environments: the TeX code is using the stuff used to set out tab-separated material. And you can't start a group on one row and end it on a later one, which is what you are trying to do here. As I say, I think the pgffor is a red herring. – cfr Oct 27 '15 at 1:21

It is pretty hard to control the expanding order while there are table-like environment and for-structure involved. However, one can first write the contents to a separated file and then input it immediately. By doing so the expanding order is clear.

\documentclass{article}
\usepackage{pgffor,newfile}
\usepackage{amsmath}
\begin{document}

\newcommand*\diff{\mathop{}\!d}
\newoutputstream{factorial}
\openoutputfile{\jobname.factorial}{factorial}
\iint_B f(x, y)
}
\foreach \a/\b/\x in {a/b/x, c/d/y}{
\foreach \c/\d/\y in {a/b/x, c/d/y}{
\ifx \y \x \else