Although the ideas in Mico's comment probably do work, they would be very specific to one environment and subject to break if anything related changes. I was heading for a more general solution.
There are two problems:
- As egreg points out, every line is an implicit group, so that all local definitions get deleted before the next line.
- Every amsmath environment is executed twice, first for measuring its size and then for printing.
Because of 1.,
\global has to be used. Because of 2., every direct
\let followed by a
\def of the same command will lead to an infinite recursion in the second pass, because the
\let then points to itself, so the \gdef reaches towards an infity.
With this knowledge, a fix is simple. The recursion has to be avoided by only executing the commands in the first pass. Thus, this is solution: