[Tex/LaTex] Why \begin{flushleft}…\end{flushleft} doesn’t behave as \flushleft…\endflushleft

environmentsgroupingmacros

The following MWE points out that \begin{flushleft}...\end{flushleft} doesn't behave as its macros counterpart: \flushleft...\endflushleft:

  • flushleft environment's effect stops after \end{flushleft}
  • \flushleft macro's effect continues after \endflushleft.

I wonder why.

\documentclass{article}
\usepackage{mwe}
\begin{document}
\section{Environments}
\begin{flushleft}
  \lipsum[1]
\end{flushleft}
\lipsum[2]
\section{Macros}
\flushleft%
\lipsum[1]
\endflushleft%
\lipsum[2]
\end{document}

Best Answer

First of all let's see \endflushleft:

% latex.ltx, line 3973:
\def\endflushleft{\endtrivlist}

Now \endtrivlist:

% latex.ltx, line 4425:
\def\endtrivlist{%
  \if@inlabel
    \leavevmode
    \global \@inlabelfalse
  \fi
  \if@newlist
    \@noitemerr
    \global \@newlistfalse
  \fi
  \ifhmode\unskip \par
  \else
    \@inmatherr{\end{\@currenvir}}%
  \fi
  \if@noparlist \else
    \ifdim\lastskip >\z@
      \@tempskipa\lastskip \vskip -\lastskip
      \advance\@tempskipa\parskip \advance\@tempskipa -\@outerparskip
      \vskip\@tempskipa
    \fi
    \@endparenv
  \fi
}

OK, nothing very strange. But the problem is in \flushleft:

% latex.ltx, line 3972:
\def\flushleft{\trivlist \raggedright\item\relax}

The \raggedright declaration is not surrounded by a group, so even upon finding \endflushleft it continues forever.

But \end{flushleft} also provides an \endgroup token, which will match the \begingroup issued by \begin{flushleft} (before doing \raggedright), so the \raggedright setting will be undone.

You are not supposed to use \flushright and \endflushright in a document. They can be used in definitions of environments, though.

Related Question