"Jonathan Sauer"
While writing unit tests for some of my macros, I stumbled on the following weird behaviour when expanding \toks registers inside \edef using \the (PlainTeX):
There is nothing strange here.
\catcode`\@=11 \def\log#1{\immediate\write\sixt@@n{#1}}
\toks@{|##|}
% Obvious result: Doubled \edef\foo{\the\toks@}
\log{1: \meaning\foo}
% Obvious as well: Doubled \edef\foo{\the\toks@\the\toks@}
\log{2: \meaning\foo}
% Now this is weird: First doubled, then not \edef\foo{\the\expandafter\toks@\the\toks@}
\the\toks@ passes # unmolested into \edef. In every other case (apart from the equivalent use of \unexpanded), a doubled ## is required for producing a single # in the result, because then # is a parameter delimiting token for the \edef. The \expandafter takes the ## out of the token register and into the regular input stream, so the #-preserving character of \the inside of \edef is no longer in action.
So when jumping out of the first expansion of the \toks register and into the second expansion, TeX seems to forget that it is inside an \edef and thus does not double the ##.
TeX _never_ doubles the # in \edef: you are confusing this with a printing artifact.
I do not know what to make of this. I could not find any place in the TeXbook where it is stated that # is doubled when expanding a \toks register inside \edef, so this might not be a bug, but simply some weird undocumented phenomenon.
It is not doubled, but simply left uninterpreted.
And it might be useful too, to build up the body of a complicated macro inside a \toks register before finally creating the macro using \edef:
What do you think?
You are about 20 years late. Please check LaTeX's definition (and usage) of \g@addto@macro: \long\def\g@addto@macro#1#2{% \begingroup \toks@\expandafter{#1#2}% \xdef#1{\the\toks@}% \endgroup} \def\AtEndOfPackage{% \expandafter\g@addto@macro\csname\@currname.\@currext-h@@k\endcsname} \let\AtEndOfClass\AtEndOfPackage \@onlypreamble\AtEndOfPackage \@onlypreamble\AtEndOfClass \def\AtBeginDocument{\g@addto@macro\@begindocumenthook} \def\AtEndDocument{\g@addto@macro\@enddocumenthook} -- David Kastrup