The (unexpandable) primitive \aftergroup
applies to the next token only; it makes TeX save the token in a FIFO list that will be delivered as soon as the current group ends. So
\begingroup\aftergroup x\aftergroup y\endgroup
is just the same as typing xy
: the list is “first in, first out”. Note that in case of a macro, TeX only saves the macro, not its meaning. Thus
\def\foo{X}
\begingroup\def\foo{Y}\aftergroup\foo\endgroup
will print X
, because the redefinition of \foo
disappears as soon as \endgroup
is executed.
It doesn't matter what group we're in; it can be any of the sixteen different group types. For instance, \hbox{A\aftergroup B}
will box an A
and print B
outside the box; the first example could have been {\aftergroup x\aftergroup y}
.
Leaving aside problems due to the limited size reserved for the FIFO list, what tokens can follow \aftergroup
? Any token, even {
or }
; the definition of the LaTeX environment lrbox
is very instructive in this respect.
If you want to chain tokens in order to reappear after the current group has ended, just precede each one by \aftergroup
:
\begingroup\aftergroup\mbox\aftergroup{\aftergroup X\aftergroup}\endgroup
will make TeX see the tokens \mbox{X}
just after the group has ended (and all settings are restored).
Note that \aftergroup{\mbox{X}}
is not equivalent to the code above: \aftergroup
does not accept arguments in braces, it only applies to the token that immediately follows it.
If you want to defer code when two groups end, it's easy:
\begingroup\begingroup
\aftergroup\aftergroup\aftergroup\foo
\endgroup\endgroup
The meaning should be clear: when the current group (at nesting level 2) ends, TeX will deliver \aftergroup\foo
, which will save back \foo
in the aftergroup list for deliver after the outer group ends. Any group level has its own incarnation of this list.
If you want to climb three levels, just remember that each group consumes one \aftergroup
: so
\begingroup\begingroup\begingroup
\aftergroup\aftergroup
\aftergroup\aftergroup
\aftergroup\aftergroup
\aftergroup\foo
\endgroup\endgroup\endgroup
will do, because when the level 3 group ends, the list will contain
\aftergroup\aftergroup\aftergroup\foo
Do yourself the proof by induction that, in order to climb up n levels, you need 2n - 1 \aftergroup
tokens before \foo
.
\aftergroup
then? – 1010011010 Mar 8 '15 at 11:21\aftergroup
, though I note for example tex.stackexchange.com/q/8136. Probably a more focussed question is not a dupe. – Joseph Wright♦ Mar 8 '15 at 11:24\expandafter
normally accumulates in groups of 2^n-1 rather than 2n+1. For\aftergroup
(if you edit the question just to ask about that) it depends whether you are trying to place n tokens after the current group, or lift one token out of n nested group levels. – David Carlisle Mar 8 '15 at 11:40\aftergroup
that are not in groups of 2^n-1. – David Carlisle Mar 8 '15 at 15:28