beginEnvironment :: HandleTeXIO m => LexerT m [Token]
beginEnvironment = do
  name <- envName
  -- Note: expansion must be enabled because we are expanding 'begin'
  st <- getState
  case lookupMacroEnv (stripBraces name) st of
    Nothing -> let grp = NamedGroup (stripBraces name)
               in modifyState (pushGroup grp) *>
                  return (mkCtrlSeq "begin": name)
    Just envdef -> do
      (startCode, endCode) <- expandEnvironment envdef
      modifyState . pushGroup $
        DefinedGroup (stripBraces name) startCode endCode
      prependTokens startCode
      return []

-- Close matching TeX group and inject end code for user-defined environments.
beginEnvironment :: HandleTeXIO m => LexerT m [Token]
beginEnvironment = do
  name <- envName
  -- Note: expansion must be enabled because we are expanding 'begin'
  st <- getState
  case lookupMacroEnv (stripBraces name) st of
    Nothing -> let grp = NamedGroup (stripBraces name)
               in modifyState (pushGroup grp) *>
                  return (mkCtrlSeq "begin": name)
    Just envdef -> do
      (startCode, endCode) <- expandEnvironment envdef
      modifyState . pushGroup $
        DefinedGroup (stripBraces name) startCode endCode
      prependTokens startCode
      return []

-- Close matching TeX group and inject end code for user-defined environments.
beginEnvironment = do
  name <- envName
  -- Note: expansion must be enabled because we are expanding 'begin'
  st <- getState
  case lookupMacroEnv (stripBraces name) st of
    Nothing -> let grp = NamedGroup (stripBraces name)
               in modifyState (pushGroup grp) *>
                  return (mkCtrlSeq "begin": name)
    Just envdef -> do
      (startCode, endCode) <- expandEnvironment envdef
      modifyState . pushGroup $
        DefinedGroup (stripBraces name) startCode endCode
      prependTokens startCode
      return []

-- Close matching TeX group and inject end code for user-defined environments.