The TeX primitive \output behaves almost like a toks register, except in the fact that it is always surrounded by braces. For instance, after \output={\plainoutput}, the result of \showthe\output is {\plainoutput}, instead of what we could naively expect (no braces).
The status of the surrounded braces is a little odd. My specific problem happens when replacing the closing brace with an explicit or implicit end-group character which does not directly come from TeX's internal mechanisms.
Specifically, compiling the following example in plain TeX triggers the ! Unbalanced output routine. error at line 6: the first case works, but not the second.
\output{\plainoutput \afterassignment\next \let\next}
\hbox{} \vfill \penalty -10000
\def\Next{\next}
\output{\plainoutput \afterassignment\Next \let\next}
\hbox{} \vfill \penalty -10000
In both cases, I redefine the output routine, then force TeX to call it (with \penalty-10000). I keep the normal \plainoutput routine, and afterwards grab the closing brace in \next, and put it back, either directly (\next), or indirectly (\Next). In the first, direct, case, TeX recognizes the closing brace as being from the \output routine, while in the second case, TeX doesn't, and gets into a state where nothing I type has any effect.
Why are the two situations different?
Assuming that I have typed the code above in the command line, is there any way to recover?
\futureletto try and grab the internal\outer endtemplate:token (see discussions on this topic). Similar investigations in the case of\writewere discussed in the comp.text.tex newsgroup. – Bruno Le Floch Dec 25 '11 at 05:19\relaxadded by TeX when it finds\elsewhile expanding tokens for a conditional, is different from the normal\relax. – Martin Scharrer Dec 25 '11 at 09:06