I'm trying to understand how exactly TeX parses documents, and with respect to that, the definition of \newif
confuses me quite a lot (in latex.ltx
, line 929ff):
\def\newif#1{%
\count@\escapechar \escapechar\m@ne
\let#1\iffalse
\@if#1\iftrue
\@if#1\iffalse
\escapechar\count@}
\def\@if#1#2{%
\expandafter\def\csname\expandafter\@gobbletwo\string#1%
\expandafter\@gobbletwo\string#2\endcsname
{\let#1#2}}
I understand what this definition does (i.e. \newif\iffoo
introduces three macros \iffoo
, \foofalse
and \footrue
), but I don't understand why it works. Here's how I understand this code:
\newif\iffoo
first stores the current escape character in\count@
and temporarily redefines it to-1
. This is probably the crux of the issue, but it's unclear to me how exactly that affects further parsing.- We define
\iffoo
to be\iffalse
. Apparently the redefining of\escapechar
has no effect here yet. So far this makes sense, since (I guess) the "definition" of\newif
and the argument\iffoo
have already been tokenized before the\escapechar
-stuff is expanded(?). - Now the weird stuff that
\@if
does comes into play. We do\@if\iffoo\iftrue
, which does the\csname
-stuff. And here's where I don't understand how this works. I read this as:\expandafter\def\csname\expandafter\@gobbletwo\string#1\expandafter\@gobbletwo\string#2\endcsname
expands to\def[\csname\@gobbletwo[\string\iffoo]\@gobbletwo[\string\iftrue]\endcsname]
(where by the square brackets I mean the evaluation of).- According to the TeXbook,
\string
turns a control sequence into its constituent characters as individual tokens, including the escape character, all with category code 12. So\string\iffoo
should turn into $\backslash_{12}i_{12}f_{12}f_{12}o_{12}o_{12}$. But this would result in\csname ffooftrue\endcsname
rather than\csname footrue\endcsname
.
Quote TeX book:
Although control sequences are treated as single objects, TEX does provide a way to break them into lists of character tokens: If you write
\string\cs
, where\cs
is any control sequence, you get the list of characters for that control sequence’s name. For example,\string\TeX
produces four tokens: $\backslash_{12},T_{12},e_{12},X_{12}$. Each character in this token list automatically gets category code 12 (“other”), including the backslash that\string
inserts to represent an escape character. However, category 10 will be assigned to the character ‘ ’ (blank space) if a space character somehow sneaks into the name of a control sequence.
So I guess my question is: Is the claim from the TeX book quote above simplified? Then how exactly does the current value of \escapechar
impact the expansion of \string
?