It should figure out which environment has to be closed now.
Since it is always the latest opened and not closed, this should be a simple thing.

As an alternative, implement automatic \end{.} insertion when \begin{.}\n is entered.