# Creating a new environment that combines samepage with align

I want to avoid pagebreaks within an align environment. I can accomplish this with both the samepage and the minipage environments. However, when I try to create a new environment that combines align with either one I get errors. The following illustrates; as far as I can see, my use of the newenvironment command is completely standard. Yet both my new environments SPalignOne and SPalignTwo throw the ame error, i.e., LaTeX Error: \begin{align} on input line 26 ended by \end{SPalignTwo} Could somebody please explain what I'm doing wrong? Thanks very much, Leo

\documentclass{minimal}
\usepackage{amsmath}
\newenvironment{SPalignOne}
{\begin{samepage}\begin{align}}
{\end{align}\end{samepage}}
\newenvironment{SPalignTwo}
{\begin{minipage}{\textwidth}\begin{align}}
{\end{align} \end{minipage} }
\begin{document}
\begin{samepage}
\begin{align}
x
\end{align}
\end{samepage}
\begin{minipage}{\textwidth}
\begin{align}
x
\end{align}
\end{minipage}
\begin{SPalignOne}
x
\end{SPalignOne}
\begin{SPalignTwo}
x
\end{SPalignTwo}
\end{document}


The error occurs because of the way that the align environment processes the material in its scope: LaTeX is set to look ahead for the hard-coded string \end{align}, at which point processing of the material in the align environment begins in earnest.
With your definitions of the SPalignX environments, after \begin{align} LaTeX will eventually come across \end{SPalignX}; however, it isn't set to evaluate immediately what goes on at the end of an SPalignX environment -- and thereby notice that the first instruction to be executed would be \end{align}. Hence the error message: LaTeX has encountered the end of an environment (SPalignX) before the one it's currently in (align) is closed.
Incidentally, by default no page breaks should occur inside an align environment, unless an instruction such as \allowdisplaybreaks was provided. You may want to check the code in your document to discover if such a command is lurking somewhere. It should be easier to cure the problem at its root rather than to provide a treatment of the symptoms, right?