[Dev-luatex] # or ##, that is the question

David Kastrup dak at gnu.org
Wed Oct 17 13:56:12 CEST 2007

"Jonathan Sauer" <Jonathan.Sauer at silverstroke.com> writes:

> 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 at addto@macro:

\long\def\g at addto@macro#1#2{%
  \expandafter\g at addto@macro\csname\@currname.\@currext-h@@k\endcsname}
\def\AtBeginDocument{\g at addto@macro\@begindocumenthook}
\def\AtEndDocument{\g at addto@macro\@enddocumenthook}

David Kastrup

More information about the dev-luatex mailing list