[Tex/LaTex] Errors when trying to define a custom align environment

alignenvironments

I'm currently trying to create a custom environment with its own counter.

\documentclass[a4paper,11pt]{report}
\usepackage[fleqn]{amsmath}
\newcounter{grammarcounter}

\newenvironment{grammar}{
   \refstepcounter{grammarcounter}
   \begin{equation*}
   \tag{$\Gamma_{\thegrammarcounter}$}
   }{\end{equation*}}
\numberwithin{grammarcounter}{chapter}

\begin{document}

\begin{grammar}
\label{gr:label}
E ::= E + E \\
E ::= a
\end{grammar}

\end{document}

This works nicely for simple equations, but the line split \\ does not work inside the equation* environment. Ideally I would like to replace the equation* environment with the align* environment. However, when simply replacing equation* in the example with align*, I get LaTeX errors indicating \begin{align} on input line .. ended by \end{grammar}.

How can I create a custom equation environment with its own counter that respects line breaks?

Best Answer

I'm not sure why but you can't use \begin{align} and \end{align} in the definition of a new environment; you have to use the "lower-level" macros \align and \endalign instead. Edit: as pointed by alexwlchan in his comment, you can find more details about that in section 6 of Technical notes on the amsmath package.

Here I've used the equivalent of an align* environment (see Herbert's answer to Define a custom align, and align* environment).

Note that you will get an error if you try to reset your grammarcounter at each chapter in the article class, because the latter doesn't have chapters; \section is the most high-level sectioning command in the article class. Did you mean

\numberwithin{grammarcounter}{section}

instead?

enter image description here

\documentclass{article}

\usepackage{amsmath}

\newcounter{grammarcounter}[section]

\makeatletter
\newenvironment{grammar}
{%
  \refstepcounter{grammarcounter}
  \start@align\@ne\st@rredtrue\m@ne
  \tag{$\Gamma_{\thegrammarcounter}$}
}{%
  \endalign
}
\makeatother
 
\begin{document}

\section{Foo}

\begin{grammar}
\label{gr:label}
E &::= E + E \\
E &::= a     \\
E &::= b     
\end{grammar}

\begin{grammar}
\label{gr:label2}
E &::= E + E \\
E &::= a     \\
E &::= b     
\end{grammar}

\end{document}