When should one use \begingroup instead of \bgroup?
\bgroup
is a synonym for {
, which is defined in Plain TeX using \let\bgroup={
.
It interacts with TeX's "digestive system" in hairy ways: {
s and \bgroup
s start the same sort of groups, called simple groups, and each can be terminated with either }
s or \egroup
s, since they are the same. But when the TeX digestive system encounters them, they are of different catcodes, so commands that look ahead, e.g., in LaTeX with \section\bgroup Title}
, can break this matching.
\begingroup
is different. It is a TeX primitive, and it matches a different sort of group that TeX accounts for separately, called "semi-simple groups" (a Knuth joke, I assume). Thus a \begingroup
must be terminated by an \endgroup
, not a }
, and vice versa for \endgroup
.
I generally avoid \bgroup
, and use \begingroup
, but \bgroup
could be useful if you are messing about with a nested token list.
I have a little bit different opinion about \bgroup
versus \begingroup
than the previous answer. First, I give a short explanation about TeX internals:
The {
and }
(more exactly the tokens with catcode 1 and 2) have four different meanings in TeX:
they are the syntactic part of macro definitions:
\def\foo...{...}
each sequence of tokens scanned as single token list in TeX (i.e. in the parameter of a macro, inside macro definitions...) have to be balanced text by these tokens:
\macro{param{e}ter}
.they are a part of several TeX primitive constructions, for example
\hbox...{...}
,$e^{...}$
,\write...{...}
.when they are used without any context mentioned above they open and close the group.
The \bgroup
and \egroup
are declared by \let\bgroup={ \let\egroup=}
and you can replace {
and }
by \bgroup
and \egroup
only in the third and fourth meaning mentioned above. For example:
\hbox ... \bgroup ...}
\hbox ... {...\egroup
\hbox ... \bgroup ...\egroup
$e^\bgroup ...}$, $e^\bgroup...\egroup$
\write ...\bgroup ...}
The last line in the example is another exception: you canot replace the closing brace by \egroup
if the syntactic rule <general text>
(like in \write
parameter) is applied.
The \bgroup
and \egroup
without the context mentioned in the third meaning above open and close a group. The same work do primitive commands \begingroup
and \endgroup
but only this work. They cannot be used instead of {
and }
in the first to third meaning mentioned above.
This means that always you can use \begingroup
and \endgroup
, it is possible to use \bgroup
and \egroup
with the same effect. But the nested groups have to be terminated by the appropriate counterpart, they cannot be crossed. And in math mode, there is a little bit different behavior, see comments.
I am preferring \bgroup
and \egroup
instead \begingroup
and \endgroup
. Only, if I see that the nested group crossing error would be usable for users of my macros then I use \begingroup
and \endgroup
.