Skip to content

pgf/TikZ: the \special graphics seam and a pgfsys driver - #1

Merged
tannevaled merged 5 commits into
mainfrom
feat/pgf-driver
Aug 16, 2026
Merged

tannevaled merged 5 commits into
mainfrom
feat/pgf-driver

Conversation

@tannevaled

Copy link
Copy Markdown
Contributor

Attacks the plan to make the engine load the real pgf/TikZ instead of gobbling a picture and standing a placeholder box in for it.

What lands

1. A graphics-literal seam (\special). TeX draws pictures by letting a package emit driver operators through \special; the engine had no such hook, so a drawing package had nothing to target. \special{...} now expands its text at once into a zero-dimension whatsit that rides in a horizontal or vertical list without disturbing the layout. The engine's driver namespace is gotex: and its payload is an SVG fragment, with {?x}/{?y} substituted at shipout with the node's own reference point — the dvisvgm convention pgf already targets. Foreign namespaces are carried but drawn by nobody.

The SVG driver writes the payload out verbatim, so a scope one special opens brackets the material painted after it. The PDF driver collects a page's literals in paint order and interprets them as real imaging operators (svgpdf.go): <g> scopes, path/rect/line/circle/ellipse/polygon/polyline, fill and stroke colour, stroke width, dash, cap, join, miter, opacity. Stroking is new — the existing SVG→PDF paths only ever filled — so drawSVGPath splits into a path builder plus a paint step, and parseTransform grows rotate/matrix/skewX/skewY.

2. e-TeX expressions. \numexpr/\dimexpr with parentheses and exact 64-bit intermediates (so a*b/c keeps its full product) and e-TeX's round-half-away-from-zero division. A drawing package converts every coordinate with \dimexpr\the\numexpr(2*N+1)*400/803\relax sp\relax, so without them it runs and produces nonsense. Plus \futurelet (every package's \@ifnextchar) and \newread.

3. The pgfsys driver + the primitives package code assumes. texmf/pgfsys-gotex.def, modelled on pgfsys-dvisvgm.def — pgf ships the hard part, since pgfsys-common-svg.def already expresses all ~40 operations as SVG fragments. Getting pgf's sources to run also needed \ifdefined/\ifcsname/\unless, \expanded/\unexpanded/\detokenize/\scantokens/\protected/\eTeXversion, \nullfont (really a font with no characters), and TeX's named parameters as real registers.

Two faithfulness bugs, with reach well beyond pgf

  • \ifx of two undefined control sequences must be true — they share the meaning "undefined". \ifx\foo\undefined is how nearly every package asks whether \foo exists; the engine answered it wrong.
  • \the of a token register inside \edef must insert its tokens without expanding them again. pgfkeys' sentinel (\def\pgfkeys@mainstop{\pgfkeys@mainstop}, equal only to itself) travels through such a register, so re-expanding it looped forever.

\input also now searches where \usepackage looks, since a package splits itself across files and pulls them in with \input.

Status and safety

Loading the real sources is opt-in through GOTEX_PGF: they now load a long way (pgfrcs, pgfkeys, pgfsys, the driver file, pgfmath) but do not yet complete, so the stubs stay the default and an ordinary document renders exactly as before. The remaining work is the TeX-layer debugging the plan always scoped as multi-session.

Verification

  • Full suite green: 729 pass, 0 skip, 0 fail; go vet and gofmt clean.
  • The conformance ratchet and the document corpus pass unchanged.
  • scripts/fidelity.sh --check (the CI gate, gotex vs real LaTeX via tectonic) passes: gotex reproduces the reference prose.
  • New code is at 100% statement coverage; tests assert exact PDF operators and mapped coordinates, not merely that something was painted.

tannevaled and others added 5 commits August 16, 2026 22:05
TeX draws pictures by letting a package emit driver operators through
\special; the engine had no such hook, so a drawing package had nothing to
target and its output could only be gobbled. This adds the seam.

\special{...} expands its text at once (as TeX does when it builds the
whatsit) into a specialNode: a zero-dimension node that rides in a
horizontal or vertical list without disturbing the layout. The engine's own
driver namespace is "gotex:" and its payload is an SVG fragment; a literal's
{?x}/{?y} are substituted at shipout with the node's own reference point on
the page and {?nl} with a newline, the dvisvgm convention pgf already
targets. Specials in another driver's namespace are carried but drawn by
nobody.

The SVG driver writes the payload out verbatim at that point, so a scope one
special opens brackets the material painted after it. The PDF driver
collects a page's literals in paint order and interprets them as real
imaging operators (svgpdf.go): <g> scopes, <path>, <rect>, <line>, <circle>,
<ellipse>, <polygon>, <polyline>, fill and stroke colour, stroke width, dash,
cap, join, miter and opacity. Stroking is new — the existing SVG-to-PDF
paths only ever filled — so drawSVGPath is split into a path builder plus a
paint step the callers choose, and parseTransform grows rotate/matrix/skewX/
skewY beside translate/scale.

Tests assert the exact operators and mapped coordinates, not merely that
something was painted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A package that computes reaches for e-TeX's expressions on every value — a
drawing package converts each coordinate from points to big points with
\dimexpr\the\numexpr(2*N+1)*400/803\relax sp\relax — so without them it
runs and produces nonsense rather than failing loudly. e-TeX has been the
default engine under LaTeX for two decades; real sources assume it.

scanExpr evaluates sum/term/factor with parentheses, terminated by an
optional \relax. Arithmetic is exact: operands accumulate in 64-bit so the
scaling idiom a*b/c keeps its full intermediate product, and division rounds
to nearest with ties away from zero, as e-TeX does. In a \dimexpr a factor
with no unit is an integer coefficient, so 2pt*3 and 3*2pt both read as
expected, and an internal dimension serves as a unit of measure (.5\hsize).
Either result is an internal quantity: assignable to a register of its own
type, usable as a factor in another expression, printable with \the, and
coercing between integers and scaled points the way TeX's do.

\futurelet is how \@ifnextchar peeks at the next token — every package
carries a copy, pgf's \pgfutil@ifnextchar among them — so it is needed for
optional arguments to work at all in package code. \newread allocates an
input stream alongside the existing \newwrite.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pgf and TikZ are written against a *driver*: pgfsys.code.tex defines every
drawing operation as \pgfsys@<op> and a pgfsys-<backend>.def says what those
emit. With no driver the whole edifice loads and defines nothing that draws,
which is why the operators stayed undefined. texmf/pgfsys-gotex.def is that
file for this engine, modelled on pgfsys-dvisvgm.def: pgf already ships the
hard part, since pgfsys-common-svg.def expresses all ~40 operations as SVG
fragments, and this engine's \special namespace carries exactly that. The
driver adds what only a backend can know — how to send a literal, how to
open and close a picture, and how to place a typeset box inside one. That
last needs the picture's origin, so a literal may declare one and later
literals refer back to it, which is how a box is wrapped in the inverse of
the map its picture opened.

Getting pgf's own sources to run took the primitives package code assumes are
simply there, each of which halts a load on its own when missing:

  \ifdefined, \ifcsname, \unless — a package guards its own loading with
  these ("\ifdefined\pgfmathloaded\else\input{pgfmath.code.tex}\fi"), and
  when the conditional is not one the \else/\fi structure is mis-read and a
  whole component silently never loads.

  \expanded, \unexpanded, \detokenize, \scantokens, \protected, \eTeXversion
  — pgfkeys refuses outright: "PGF requires the \expanded primitive".

  \nullfont — really a font with no characters, since a package selects it
  around material it wants measured but not set.

  TeX's named parameters (\tracinglostchars, \hbadness, \spaceskip, …) as
  registers of their own type: assignable, readable with \the, and scoped.

Two faithfulness bugs surfaced on the way, both with reach far beyond pgf:

  \ifx compares meanings, and every undefined control sequence has the same
  one, so two of them are equal whatever they are called. \ifx\foo\undefined
  is how nearly every package asks whether \foo exists; the engine answered
  it wrong.

  \the of a token register inside an \edef must insert its tokens WITHOUT
  expanding them again. That is the whole reason \the\toks exists, and
  pgfkeys' sentinel (\def\pgfkeys@mainstop{\pgfkeys@mainstop}, equal only to
  itself) went through such a register — so re-expanding it looped forever.

\input now searches where \usepackage looks (document directory, TEXINPUTS/
GOTEX_TEXMF, embedded set) instead of the current directory alone: a package
splits itself across files and pulls them in with \input, so one found on the
path whose parts were not would load only its first file.

Loading the real sources is opt-in through GOTEX_PGF while the remaining gaps
are closed — they now load a long way but do not yet complete, and the stubs
must stay the default so an ordinary document renders exactly as before.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A path spliced into TeX source is read as TeX, where a backslash begins a
control sequence — so a Windows temp path arrived as a string of undefined
commands and the file was never found. Forward slashes are accepted by
os.ReadFile on every platform.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
main grew its own \futurelet (with the \global prefix and the truncated-input
case) while this branch was being written; that one is kept, and the duplicate
assignment helper the merge left behind is folded back into assignLetMeaning so
there is one \let assignment, not two. The branch's \futurelet tests that main
does not already cover — that both peeked tokens are still read, that the
meaning is copied, and the end-of-input case — are kept alongside main's.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@tannevaled
tannevaled merged commit 2963ece into main Aug 16, 2026
18 checks passed
tannevaled added a commit that referenced this pull request Aug 17, 2026
…mand\bf

\textbf was \def\textbf#1{{\bf #1}} and \bfseries was \def\bfseries{\bf}, so both
named the deprecated switch \bf. A document that modernises it with

    \renewcommand{\bf}{\textbf}

(common in older sources) then makes \textbf refer to itself —
\textbf→{\bf …}→{\textbf …}→… — an unbounded self-reference that consumes the
rest of the document as arguments. A JHEP paper doing this rendered 1 page / 28
glyphs (whole body gone); now 14 pages / ~46000.

Fix, matching real LaTeX's NFSS layering: aliasFontSwitches makes \bfseries,
\itshape, \ttfamily, \sffamily, \rmfamily, \normalfont direct copies of the bound
\bf/\it/\tt/\sf/\rm switches (not macros that name them), and \textbf/\textit/…
now go through those NFSS names. Redefining the user-facing \bf no longer touches
\textbf.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
tannevaled added a commit that referenced this pull request Aug 17, 2026
…closing brace

Two more pieces of TeX and of the LaTeX kernel, both found the same way: by
pointing the real beamer.cls at the engine and asking what it put on the page.

  * \@currname / \@currext name the file being loaded, and LaTeX keeps them on a
    STACK. A class that requires a package in the middle of its own work must
    still be "the current file" afterwards. The engine left them naming the last
    file loaded, so beamer declared its options into the family named by whatever
    package it happened to require last, and its own \ExecuteOptionsBeamer{c}
    then answered "Package keyval Error: c undefined" — onto the page. They are
    now saved on the load frame and handed back when the file ends, and outside
    any file they are EMPTY rather than undefined, which is what real LaTeX
    leaves behind (it prints "." for \@currname.\@currext there).

  * TeX strips the braces of an argument that is ENTIRELY one group (§399):
    \def\d[#1]{} called as \d[{g}] sees "g", while \d[{a}{b}] — two groups, with
    nothing enclosing both — keeps them. The engine reads [optional arguments] in
    Go rather than through a delimited macro, so the rule had to be applied
    there, and it is applied to the argument COUNT too, which may arrive braced.

    That one is what put beamer's templates on the page. beamer builds each
    template as \newcommand\foo[{1}][{}]{…} through a chain of \expandafter; with
    the braces left on, the argument count was not a number and \foo came out as
    a macro with NO arguments, so the template BODY was typeset at definition
    time instead of being stored.

Where the beamer bring-up stands: the class loads, its modes resolve, its options
execute, and its templates define. The page furniture is still wrong (beamer's
navigation bar reaches the page as running text) — with, again, no undefined
control sequence anywhere. That is the next thread.

Proof: all tests pass under -race; the conformance ratchet gains two rows;
scripts/fidelity.sh --check is OK. The ten TikZ documents and all ten pages of
the arXiv paper (2608.14117) still render PIXEL-IDENTICAL to the binary built
before this beamer work started.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
tannevaled added a commit that referenced this pull request Aug 17, 2026
…closing brace (#20)

Two more pieces of TeX and of the LaTeX kernel, both found the same way: by
pointing the real beamer.cls at the engine and asking what it put on the page.

  * \@currname / \@currext name the file being loaded, and LaTeX keeps them on a
    STACK. A class that requires a package in the middle of its own work must
    still be "the current file" afterwards. The engine left them naming the last
    file loaded, so beamer declared its options into the family named by whatever
    package it happened to require last, and its own \ExecuteOptionsBeamer{c}
    then answered "Package keyval Error: c undefined" — onto the page. They are
    now saved on the load frame and handed back when the file ends, and outside
    any file they are EMPTY rather than undefined, which is what real LaTeX
    leaves behind (it prints "." for \@currname.\@currext there).

  * TeX strips the braces of an argument that is ENTIRELY one group (§399):
    \def\d[#1]{} called as \d[{g}] sees "g", while \d[{a}{b}] — two groups, with
    nothing enclosing both — keeps them. The engine reads [optional arguments] in
    Go rather than through a delimited macro, so the rule had to be applied
    there, and it is applied to the argument COUNT too, which may arrive braced.

    That one is what put beamer's templates on the page. beamer builds each
    template as \newcommand\foo[{1}][{}]{…} through a chain of \expandafter; with
    the braces left on, the argument count was not a number and \foo came out as
    a macro with NO arguments, so the template BODY was typeset at definition
    time instead of being stored.

Where the beamer bring-up stands: the class loads, its modes resolve, its options
execute, and its templates define. The page furniture is still wrong (beamer's
navigation bar reaches the page as running text) — with, again, no undefined
control sequence anywhere. That is the next thread.

Proof: all tests pass under -race; the conformance ratchet gains two rows;
scripts/fidelity.sh --check is OK. The ten TikZ documents and all ten pages of
the arXiv paper (2608.14117) still render PIXEL-IDENTICAL to the binary built
before this beamer work started.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
tannevaled added a commit that referenced this pull request Aug 18, 2026
An UNDELIMITED macro argument takes exactly one token and cannot run away, so the
splicer's file-end sentinels (\gotexendinput, \@endofpackagehook,
\@endofclasshook, \@Gotex@endload) must not be refused there. The guard belongs to
grabDelimited, where a scan really can run past the end of its file; in
grabUndelimited it broke the LaTeX kernel's own

    \AtEndOfPackage#1{\g@addto@macro\@endofpackagehook{#1}}

whose FIRST argument IS \@endofpackagehook. The call was abandoned, so the {code}
that followed executed on the spot instead of being stored, and the hook stayed
empty — measurable in one line:

    \AtEndOfPackage{\message{HOOK}}\message{[\meaning\@endofpackagehook]}
    before:  HOOK [h=macro:->]          (ran immediately, hook empty)
    after:        [h=macro:->\message {HOOK}]

The consequence went all the way to the page, and this is the fault that has been
keeping the real beamer class from rendering anything:

  * etoolbox registers its catcode restore as
    \AtEndOfPackage{\etb@catcodes\undef\etb@catcodes};
  * the restore never ran, so "|" kept the catcode 3 etoolbox gives it;
  * beamerbasedecode's \beamer@@decodefind#1| then had a catcode-3 delimiter while
    \beamer@@@temp carried a catcode-12 bar, so the argument scan never matched;
  * it ran away, raised the single "Argument has an extra }", left the group open,
    and beamer's comment skipper swallowed the rest of the file and the document.

Measured, on the real class:

    \usepackage{etoolbox}        catcode | : 3 → 12,  0 skipped commands
    \usepackage{beamerbasemodes} swallowed everything → returns, 0 groups, 0 skipped
    \documentclass{beamer} + one frame   mvl 0 → 123,  pages 0 → 1

What is left there is ordinary content work (keyval keys, undefined shadings and
images), not a collapse.

Proof: all tests pass, scripts/fidelity.sh --check is OK, and the ten TikZ
documents and all ten pages of the arXiv paper (2608.14117) are pixel-identical to
main.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
tannevaled added a commit that referenced this pull request Aug 26, 2026
…e page \vsize (#71)

The layout-diff harness's #1 fidelity divergence was under-pagination: gotex
fit more content per page than real LaTeX and emitted fewer pages. On a minimal
120-line \documentclass{article} document tectonic produces 3 pages (46/46/28
lines) while gotex produced 2, at a 10.48pt line pitch against tectonic's 12pt.

Two vertical-metric defects, both measured:

1. scanDimenValue coerced the internal DIMEN parameters (\hsize, \vsize,
   \parindent) but not the internal GLUE parameters (\baselineskip, \leftskip,
   \rightskip). A bare \baselineskip where a rigid <dimen> was wanted therefore
   read as zero and was left in the input, where the standard classes'
   \divide\@tempdima\baselineskip then ran it as a spurious \baselineskip=0
   assignment. That zeroed the leading — collapsing interline glue to \lineskip
   (10.48pt instead of 12pt) — and broke the \textheight line-count arithmetic.

2. \textheight was an independent \newdimen, disconnected from the page
   builder's \vsize, so the classes' \setlength\textheight{...} never changed
   the page-break budget and \vsize stayed at the plain-TeX 8.9in (643pt)
   default. Aliasing \textheight to \vsize — the vertical twin of the existing
   \let\textwidth\hsize — lets a class size the text block, exactly as LaTeX's
   output routine sets \vsize from \textheight.

With both fixed, \the\baselineskip is 12pt and \the\vsize is 550pt for
article/letterpaper, and the minimal document paginates 46/46/28 like tectonic.

Measured on cmd/gotex-refdiff -layout (corpus /Users/Shared/axc/work, -n 30
-seed 1), before -> after: total missing pages 127 -> 109 (18 recovered), total
|page-delta| 132 -> 115, mean divergence 10.901 -> 9.525. Every standard
article-class paper improved (e.g. 2508.20008 -27 -> -16, 2608.10560 -7 -> -4);
classes with their own \output geometry (amsart, revtex, eptcs) are unchanged
and are a separate target. Prose fidelity gate and the conformance suite stay
green.

Co-authored-by: Claude Opus 4.8 <[email protected]>
tannevaled added a commit that referenced this pull request Aug 26, 2026
\newcommand\foo[\somecount]{…} defined a command of ZERO arguments. The reader
walked the bracket's tokens, kept the digits and skipped everything else, so a
count that arrived as a register — or as \the<register> — read as nothing.

That is not a missing feature, it is silent damage: the command then consumed
none of the arguments its caller passed, and each one was left in the input and
TYPESET. beamer generates its whole overlay layer this way,

	\newcommand\csname beamerx@…\endcsname[\beamer@argscount]{#3}

so every \defbeamertemplate printed its template body onto the page instead of
storing it. An empty beamer document came out 5 pages of that debris; it is now
2. The same shift also mis-bound the arguments further down the chain — the
overlay specification \beamer@sortzero passes as {} was picked up as the first
real argument, so \defbeamertemplate{tst}{fam}{…} built its key as
\beamer@@Tmpop@@tst instead of \beamer@@Tmpop@tst@fam.

A bracket holding a control sequence now goes to the engine's own integer
scanner, on an isolated input stack so nothing it leaves unread escapes into the
document. A bracket of plain digits keeps the old path.

One test expectation moves. It asserted that \newcommand\c[\relax 1]{…} takes
ONE argument — digits kept, control sequences ignored. Real LaTeX does not do
that: it scans a number, raises "Missing number, treated as zero", and defines a
command of no arguments. Checked with tectonic, which also confirms the register
form: \newcount\nn \nn=1 \newcommand\ca[\nn]{<#1>} makes \ca{X} give <X>.
tannevaled added a commit that referenced this pull request Aug 27, 2026
\global\setlength\xx{5pt} inside a group was a LOCAL assignment: it took effect
inside the group and was undone on the way out, in silence. \global\xx=5pt and
\global\advance\xx by4pt both worked, which is what kept the hole out of sight.

In TeX a prefix applies to the assignment it finds after EXPANDING what follows —
tex.web §1211 takes "the next non-blank non-relax NON-CALL token", so a macro is
expanded away. \setlength is a macro there (ltlength.dtx: \def\setlength#1#2{#1
#2\relax}), so \global reaches the register assignment by itself. Here it is a
primitive, which getXToken does not expand, and doGlobal's switch had no case for
it: the default branch put the token back and ran it locally.

The machinery was already in place — assignLength takes a global flag that nothing
ever passed as true. \setlength, \addtolength, \settowidth, \settoheight and
\settodepth now receive the prefix, so they reach both a \newlength register and
one of the engine's dimension parameters (\textwidth is \let to \hsize, a
different path, same rule).

Measured over 200 real beamer talks: 0 documents lost, 0 outputs changed, page
count identical — the change is inert on that corpus, which is what a fix this
narrow should look like.

One test case of mine was wrong before the engine was: I asserted \the\xx after
setting \textwidth. Removed; the parameter path has its own test.
tannevaled added a commit that referenced this pull request Aug 27, 2026
…mes expand (#99)

Two defects that turn out to be one story: no beamer theme had ever been loaded,
and every keyval value was silently lost.

1. \@ifnextchar does not INSERT the branch it picks — it stores it first.
   ltdefns.dtx:

	\long\def\@ifnextchar#1#2#3{\let\reserved@d=#1
	  \def\reserved@a{#2}\def\reserved@b{#3}\futurelet\@let@token\@ifnch}

   and \def\reserved@b{#3} SCANS the branch as a macro body, which halves ## a
   second time (tex.web §479: a # followed by a # stores one #). This engine's
   \@ifnextchar is a primitive that inserted the branch verbatim, skipping it.

   keyval is built on exactly that:

	\def\define@key#1#2{\@ifnextchar[{\KV@def{#1}{#2}}{\long\@namedef{KV@#1@#2}####1}}

   The #### is halved once into \define@key's own body and a second time by
   \@ifnextchar, leaving the one # that \def reads as the parameter text #1.
   Without it the generated macro's parameter text was ##1 and bound nothing:
   \setkeys{fam}{k=VAL} gave <<>>. Real LaTeX gives \long macro:#1-><<#1>> where
   this engine gave macro:##1-><<#1>>. \@ifstar and \@ifnextbracket pick their
   branch the same way and are halved for the same reason.

2. \usepackage, \documentclass and \LoadClass now EXPAND their {name}. Checked in
   one line: \def\nm{marker}\usepackage{zz\nm} loads zzmarker.sty in real LaTeX
   and loaded nothing here. beamer builds every theme file name that way —
   \beamer@calltheme does \usepackage[{#1}]{beamertheme\beamer@themename} — so
   \usetheme{default} asked for a package literally named
   "beamertheme\beamer@themename".

Together: the frametitle template (beamerouterthemedefault.sty) finally exists, so
a FRAME TITLE renders; and because key values no longer leak, the theme files stop
contributing four pages of debris. On the minimal document that is exactly the
reference — n frames make n pages, title and body both present, page 364.2x273.15.

Measured over 200 real beamer talks: 0 content lost, pages 1061 -> 1095, vector
paths 155106 -> 174863. Eight documents stop producing a sized page and each was
checked by hand: four are corpus FRAGMENTS with no \begin{document} (0 pages is
what real LaTeX gives them), one is a talk with no frame at all, one is a fragile
frame whose verbatim body this engine cannot render either way, one is unchanged
when re-run cold, and one (039a234b02c5…) trips the runaway guard on main TOO —
the guard now fires sooner, so 40KB of debris becomes none. Over 200 arXiv papers:
the single apparent loss renders 2.46MB in both binaries when re-run cold; it had
exceeded the sweep's time cap.
tannevaled added a commit that referenced this pull request Aug 28, 2026
\url, \nolinkurl, \href and \hypertarget read their argument literally out of the
base input, so ~, % , #, _ and & keep the value they have in the file. Only the
SOURCE can be read that way. When something is already pending on the input stack
the argument is coming from an EXPANSION, and the base text at the mouth's
position is whatever follows the macro that produced it — so the scan skipped the
argument and ate the next braced group in the document.

Two ways that shows up, both measured:

  - A link whose target a macro builds. This paper defines
    \newcommand{\pyref}[2]{\href{https://…/discopy.#1.html}{\py{#2}}}, and the URL
    was typeset in the running text ("The class https://… is defined by:")
    because \href never consumed it.
  - beamer's navigation lays a \hypertarget per frame whose name it composes.
    With an outer theme that draws a head or foot line (split, infolines — so
    \usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the target is emitted while a
    [fragile] frame's body is being copied out verbatim, and the group eaten was
    the frame's own: \textbf{gras} reached \jobname.vrb as \textbf, and the frame
    lost everything after its first control sequence. Issue #103.

With a token list pending, the argument is read as tokens instead. Reading the
source raw is kept for the case it is meant for — a \url written in the document —
where % must not start a comment.

Measured over 200 real talks and 200 arXiv papers:

	beamer  1121 → 1131 pages   5 talks up, none down
	arXiv   4052 → 4051 pages   one paper, and it is a correction: three
	                            \href targets it used to typeset in the page
	                            are gone, no text lost (word counts unchanged)

The glyph count falls in 61 documents for that same reason — a URL that was
never meant to be on the page.
tannevaled added a commit that referenced this pull request Aug 28, 2026
Two things this engine did not model, both straight from the reference, and
both reached through the same document: a beamer talk with a [fragile] frame.

## A file is a level of input (tex.web §537)

start_input does begin_file_reading — "set up cur_file and new level of input" —
and the file is read to its end before the level underneath resumes; §329
end_file_reading pops back.

This mouth merged a file into ONE character buffer at the mouth's position, and
it reads pending token lists before that buffer, so a file \input from inside a
macro arrived AFTER the rest of that macro's body. It is not a corner case:

	\frame<*>[…][{…,fragile=false}]{\begingroup\input{\jobname.vrb}\endgroup}

is how beamer re-reads a fragile frame's body, and the body arrived after the
frame had closed — into a box nothing places.

pushInputLevel/popInputLevel make the file a level of its own, carrying the
buffer, the mouth's position, the line table, the pending lists and the
no-progress guard's baseline (which watches e.bpos, and a new buffer starts at 0
again). \input, \InputIfFileExists, the .bbl reader and class/package loading all
go through it, so the line-number bookkeeping that discounted a loaded file's
lines from the document's own (inputNL/loadedNL/nlCount) is gone: a file no
longer shifts the document's lines because it is no longer in its buffer.

\InputIfFileExists now runs its then-code BEFORE the file, which is what
ltfiles.dtx does: \IfFileExists{#1}{#2\@addtofilelist{#1}\@@input\@FilEf@und}.

## \begin{env} … \end{env} is a group (ltmiscen.dtx)

	\protected\def\begin#1{… \begingroup\@endpefalse\reserved@a}
	  where \reserved@a is \def\@Currenvir{#1}… \csname #1\endcsname
	\def\end#1{\csname end#1\endcsname\@Checkend{#1}\expandafter\endgroup …}

\begingroup comes first and \@Currenvir is defined inside it. Without the group
\@Currenvir was never restored, so a class that leaves an environment early by
closing its group could not — and beamer's fragile frame does exactly that:

	\def\beamer@checkforfragile#1fragile#2\relax{… \endgroup% end environment
	  \expandafter\beamer@framecommand\beamer@frameoptions\bgroup}

then calls \frame, which picks its syntax with \ifx\@Currenvir\beamer@frametext.
With \@Currenvir still "frame" the command form took the ENVIRONMENT path a
second time and \beamer@doseveralframes was handed the bare \bgroup instead of
the frame's body — measured, the frame went on the page empty.

The group is opened and closed by the Go-side probes \gotex@checkenv and
\gotex@endenv, not by \begingroup/\endgroup tokens, because \begin and \end must
stay expandable here: as tokens they would print as literal text wherever \begin
is only expanded (inside \message or \edef).

Four consequences, each from the reference:

  - Allocation is GLOBAL. ltplain.dtx's \e@alloc ends with
    `\global#2#6\allocationnumber`; ltcounts.dtx's \@definecounter makes \cl@<c>,
    \p@<c> and \the<c> global; ltthm.dtx's \@xnthm/\@ynthm use \xdef and
    \global\@namedef. So \newcount, \newdimen, \newskip, \newlength, \newcounter
    and \newtheorem now define globally — otherwise a counter declared inside
    \begin{document} (which is an environment) vanished with it.
  - Every alignment entry is a group (tex.web §791: a template's u-part and
    v-part are inserted inside braces), so a font switch in a cell stops there.
    buildCellHList terminated the cell with a bare } sentinel and no group; that
    stray brace was silently swallowed until a \begingroup was open.
  - An environment the engine implements in Go swallows its own \end, so \end —
    and the \endgroup with it — never runs: tabular, tabularx, verbatim,
    lstlisting, equation, align, minipage and the gobbled comment environments
    each close the group themselves.
  - setSrcPos no longer discounts loaded lines: a level reports its own file's
    line, which is where a diagnostic about that file belongs.

## Measured

200 real beamer talks and 200 arXiv papers, against main:

	beamer   1121 → 1031 pages   182 743 → 171 499 glyphs   16 up, 14 down
	arXiv    4052 → 4057 pages     9 485 942 → 9 234 865    14 up,  7 down

NOT a net win yet, and the reason is a defect that predates this branch and is
reproducible on main: with an outer theme of the split/infolines family
(\usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the verbatim capture of a
fragile frame's FIRST line loses everything after its first control sequence —
\textbf{gras} is written to the .vrb as \textbf. Reading that back where it
belongs (inside the frame) then swallows the next line, which is why correcting
the ORDER makes those talks worse. See the issue.
tannevaled added a commit that referenced this pull request Aug 28, 2026
Two things this engine did not model, both straight from the reference, and
both reached through the same document: a beamer talk with a [fragile] frame.

## A file is a level of input (tex.web §537)

start_input does begin_file_reading — "set up cur_file and new level of input" —
and the file is read to its end before the level underneath resumes; §329
end_file_reading pops back.

This mouth merged a file into ONE character buffer at the mouth's position, and
it reads pending token lists before that buffer, so a file \input from inside a
macro arrived AFTER the rest of that macro's body. It is not a corner case:

	\frame<*>[…][{…,fragile=false}]{\begingroup\input{\jobname.vrb}\endgroup}

is how beamer re-reads a fragile frame's body, and the body arrived after the
frame had closed — into a box nothing places.

pushInputLevel/popInputLevel make the file a level of its own, carrying the
buffer, the mouth's position, the line table, the pending lists and the
no-progress guard's baseline (which watches e.bpos, and a new buffer starts at 0
again). \input, \InputIfFileExists, the .bbl reader and class/package loading all
go through it, so the line-number bookkeeping that discounted a loaded file's
lines from the document's own (inputNL/loadedNL/nlCount) is gone: a file no
longer shifts the document's lines because it is no longer in its buffer.

\InputIfFileExists now runs its then-code BEFORE the file, which is what
ltfiles.dtx does: \IfFileExists{#1}{#2\@addtofilelist{#1}\@@input\@FilEf@und}.

## \begin{env} … \end{env} is a group (ltmiscen.dtx)

	\protected\def\begin#1{… \begingroup\@endpefalse\reserved@a}
	  where \reserved@a is \def\@Currenvir{#1}… \csname #1\endcsname
	\def\end#1{\csname end#1\endcsname\@Checkend{#1}\expandafter\endgroup …}

\begingroup comes first and \@Currenvir is defined inside it. Without the group
\@Currenvir was never restored, so a class that leaves an environment early by
closing its group could not — and beamer's fragile frame does exactly that:

	\def\beamer@checkforfragile#1fragile#2\relax{… \endgroup% end environment
	  \expandafter\beamer@framecommand\beamer@frameoptions\bgroup}

then calls \frame, which picks its syntax with \ifx\@Currenvir\beamer@frametext.
With \@Currenvir still "frame" the command form took the ENVIRONMENT path a
second time and \beamer@doseveralframes was handed the bare \bgroup instead of
the frame's body — measured, the frame went on the page empty.

The group is opened and closed by the Go-side probes \gotex@checkenv and
\gotex@endenv, not by \begingroup/\endgroup tokens, because \begin and \end must
stay expandable here: as tokens they would print as literal text wherever \begin
is only expanded (inside \message or \edef).

Four consequences, each from the reference:

  - Allocation is GLOBAL. ltplain.dtx's \e@alloc ends with
    `\global#2#6\allocationnumber`; ltcounts.dtx's \@definecounter makes \cl@<c>,
    \p@<c> and \the<c> global; ltthm.dtx's \@xnthm/\@ynthm use \xdef and
    \global\@namedef. So \newcount, \newdimen, \newskip, \newlength, \newcounter
    and \newtheorem now define globally — otherwise a counter declared inside
    \begin{document} (which is an environment) vanished with it.
  - Every alignment entry is a group (tex.web §791: a template's u-part and
    v-part are inserted inside braces), so a font switch in a cell stops there.
    buildCellHList terminated the cell with a bare } sentinel and no group; that
    stray brace was silently swallowed until a \begingroup was open.
  - An environment the engine implements in Go swallows its own \end, so \end —
    and the \endgroup with it — never runs: tabular, tabularx, verbatim,
    lstlisting, equation, align, minipage and the gobbled comment environments
    each close the group themselves.
  - setSrcPos no longer discounts loaded lines: a level reports its own file's
    line, which is where a diagnostic about that file belongs.

## Measured

200 real beamer talks and 200 arXiv papers, against main:

	beamer   1121 → 1031 pages   182 743 → 171 499 glyphs   16 up, 14 down
	arXiv    4052 → 4057 pages     9 485 942 → 9 234 865    14 up,  7 down

NOT a net win yet, and the reason is a defect that predates this branch and is
reproducible on main: with an outer theme of the split/infolines family
(\usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the verbatim capture of a
fragile frame's FIRST line loses everything after its first control sequence —
\textbf{gras} is written to the .vrb as \textbf. Reading that back where it
belongs (inside the frame) then swallows the next line, which is why correcting
the ORDER makes those talks worse. See the issue.
tannevaled added a commit that referenced this pull request Aug 29, 2026
Two things this engine did not model, both straight from the reference, and
both reached through the same document: a beamer talk with a [fragile] frame.

## A file is a level of input (tex.web §537)

start_input does begin_file_reading — "set up cur_file and new level of input" —
and the file is read to its end before the level underneath resumes; §329
end_file_reading pops back.

This mouth merged a file into ONE character buffer at the mouth's position, and
it reads pending token lists before that buffer, so a file \input from inside a
macro arrived AFTER the rest of that macro's body. It is not a corner case:

	\frame<*>[…][{…,fragile=false}]{\begingroup\input{\jobname.vrb}\endgroup}

is how beamer re-reads a fragile frame's body, and the body arrived after the
frame had closed — into a box nothing places.

pushInputLevel/popInputLevel make the file a level of its own, carrying the
buffer, the mouth's position, the line table, the pending lists and the
no-progress guard's baseline (which watches e.bpos, and a new buffer starts at 0
again). \input, \InputIfFileExists, the .bbl reader and class/package loading all
go through it, so the line-number bookkeeping that discounted a loaded file's
lines from the document's own (inputNL/loadedNL/nlCount) is gone: a file no
longer shifts the document's lines because it is no longer in its buffer.

\InputIfFileExists now runs its then-code BEFORE the file, which is what
ltfiles.dtx does: \IfFileExists{#1}{#2\@addtofilelist{#1}\@@input\@FilEf@und}.

## \begin{env} … \end{env} is a group (ltmiscen.dtx)

	\protected\def\begin#1{… \begingroup\@endpefalse\reserved@a}
	  where \reserved@a is \def\@Currenvir{#1}… \csname #1\endcsname
	\def\end#1{\csname end#1\endcsname\@Checkend{#1}\expandafter\endgroup …}

\begingroup comes first and \@Currenvir is defined inside it. Without the group
\@Currenvir was never restored, so a class that leaves an environment early by
closing its group could not — and beamer's fragile frame does exactly that:

	\def\beamer@checkforfragile#1fragile#2\relax{… \endgroup% end environment
	  \expandafter\beamer@framecommand\beamer@frameoptions\bgroup}

then calls \frame, which picks its syntax with \ifx\@Currenvir\beamer@frametext.
With \@Currenvir still "frame" the command form took the ENVIRONMENT path a
second time and \beamer@doseveralframes was handed the bare \bgroup instead of
the frame's body — measured, the frame went on the page empty.

The group is opened and closed by the Go-side probes \gotex@checkenv and
\gotex@endenv, not by \begingroup/\endgroup tokens, because \begin and \end must
stay expandable here: as tokens they would print as literal text wherever \begin
is only expanded (inside \message or \edef).

Four consequences, each from the reference:

  - Allocation is GLOBAL. ltplain.dtx's \e@alloc ends with
    `\global#2#6\allocationnumber`; ltcounts.dtx's \@definecounter makes \cl@<c>,
    \p@<c> and \the<c> global; ltthm.dtx's \@xnthm/\@ynthm use \xdef and
    \global\@namedef. So \newcount, \newdimen, \newskip, \newlength, \newcounter
    and \newtheorem now define globally — otherwise a counter declared inside
    \begin{document} (which is an environment) vanished with it.
  - Every alignment entry is a group (tex.web §791: a template's u-part and
    v-part are inserted inside braces), so a font switch in a cell stops there.
    buildCellHList terminated the cell with a bare } sentinel and no group; that
    stray brace was silently swallowed until a \begingroup was open.
  - An environment the engine implements in Go swallows its own \end, so \end —
    and the \endgroup with it — never runs: tabular, tabularx, verbatim,
    lstlisting, equation, align, minipage and the gobbled comment environments
    each close the group themselves.
  - setSrcPos no longer discounts loaded lines: a level reports its own file's
    line, which is where a diagnostic about that file belongs.

## Measured

200 real beamer talks and 200 arXiv papers, against main:

	beamer   1121 → 1031 pages   182 743 → 171 499 glyphs   16 up, 14 down
	arXiv    4052 → 4057 pages     9 485 942 → 9 234 865    14 up,  7 down

NOT a net win yet, and the reason is a defect that predates this branch and is
reproducible on main: with an outer theme of the split/infolines family
(\usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the verbatim capture of a
fragile frame's FIRST line loses everything after its first control sequence —
\textbf{gras} is written to the .vrb as \textbf. Reading that back where it
belongs (inside the frame) then swallows the next line, which is why correcting
the ORDER makes those talks worse. See the issue.
tannevaled added a commit that referenced this pull request Aug 29, 2026
Two things this engine did not model, both straight from the reference, and
both reached through the same document: a beamer talk with a [fragile] frame.

## A file is a level of input (tex.web §537)

start_input does begin_file_reading — "set up cur_file and new level of input" —
and the file is read to its end before the level underneath resumes; §329
end_file_reading pops back.

This mouth merged a file into ONE character buffer at the mouth's position, and
it reads pending token lists before that buffer, so a file \input from inside a
macro arrived AFTER the rest of that macro's body. It is not a corner case:

	\frame<*>[…][{…,fragile=false}]{\begingroup\input{\jobname.vrb}\endgroup}

is how beamer re-reads a fragile frame's body, and the body arrived after the
frame had closed — into a box nothing places.

pushInputLevel/popInputLevel make the file a level of its own, carrying the
buffer, the mouth's position, the line table, the pending lists and the
no-progress guard's baseline (which watches e.bpos, and a new buffer starts at 0
again). \input, \InputIfFileExists, the .bbl reader and class/package loading all
go through it, so the line-number bookkeeping that discounted a loaded file's
lines from the document's own (inputNL/loadedNL/nlCount) is gone: a file no
longer shifts the document's lines because it is no longer in its buffer.

\InputIfFileExists now runs its then-code BEFORE the file, which is what
ltfiles.dtx does: \IfFileExists{#1}{#2\@addtofilelist{#1}\@@input\@FilEf@und}.

## \begin{env} … \end{env} is a group (ltmiscen.dtx)

	\protected\def\begin#1{… \begingroup\@endpefalse\reserved@a}
	  where \reserved@a is \def\@Currenvir{#1}… \csname #1\endcsname
	\def\end#1{\csname end#1\endcsname\@Checkend{#1}\expandafter\endgroup …}

\begingroup comes first and \@Currenvir is defined inside it. Without the group
\@Currenvir was never restored, so a class that leaves an environment early by
closing its group could not — and beamer's fragile frame does exactly that:

	\def\beamer@checkforfragile#1fragile#2\relax{… \endgroup% end environment
	  \expandafter\beamer@framecommand\beamer@frameoptions\bgroup}

then calls \frame, which picks its syntax with \ifx\@Currenvir\beamer@frametext.
With \@Currenvir still "frame" the command form took the ENVIRONMENT path a
second time and \beamer@doseveralframes was handed the bare \bgroup instead of
the frame's body — measured, the frame went on the page empty.

The group is opened and closed by the Go-side probes \gotex@checkenv and
\gotex@endenv, not by \begingroup/\endgroup tokens, because \begin and \end must
stay expandable here: as tokens they would print as literal text wherever \begin
is only expanded (inside \message or \edef).

Four consequences, each from the reference:

  - Allocation is GLOBAL. ltplain.dtx's \e@alloc ends with
    `\global#2#6\allocationnumber`; ltcounts.dtx's \@definecounter makes \cl@<c>,
    \p@<c> and \the<c> global; ltthm.dtx's \@xnthm/\@ynthm use \xdef and
    \global\@namedef. So \newcount, \newdimen, \newskip, \newlength, \newcounter
    and \newtheorem now define globally — otherwise a counter declared inside
    \begin{document} (which is an environment) vanished with it.
  - Every alignment entry is a group (tex.web §791: a template's u-part and
    v-part are inserted inside braces), so a font switch in a cell stops there.
    buildCellHList terminated the cell with a bare } sentinel and no group; that
    stray brace was silently swallowed until a \begingroup was open.
  - An environment the engine implements in Go swallows its own \end, so \end —
    and the \endgroup with it — never runs: tabular, tabularx, verbatim,
    lstlisting, equation, align, minipage and the gobbled comment environments
    each close the group themselves.
  - setSrcPos no longer discounts loaded lines: a level reports its own file's
    line, which is where a diagnostic about that file belongs.

## Measured

200 real beamer talks and 200 arXiv papers, against main:

	beamer   1121 → 1031 pages   182 743 → 171 499 glyphs   16 up, 14 down
	arXiv    4052 → 4057 pages     9 485 942 → 9 234 865    14 up,  7 down

NOT a net win yet, and the reason is a defect that predates this branch and is
reproducible on main: with an outer theme of the split/infolines family
(\usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the verbatim capture of a
fragile frame's FIRST line loses everything after its first control sequence —
\textbf{gras} is written to the .vrb as \textbf. Reading that back where it
belongs (inside the frame) then swallows the next line, which is why correcting
the ORDER makes those talks worse. See the issue.
tannevaled added a commit that referenced this pull request Aug 29, 2026
Two things this engine did not model, both straight from the reference, and
both reached through the same document: a beamer talk with a [fragile] frame.

## A file is a level of input (tex.web §537)

start_input does begin_file_reading — "set up cur_file and new level of input" —
and the file is read to its end before the level underneath resumes; §329
end_file_reading pops back.

This mouth merged a file into ONE character buffer at the mouth's position, and
it reads pending token lists before that buffer, so a file \input from inside a
macro arrived AFTER the rest of that macro's body. It is not a corner case:

	\frame<*>[…][{…,fragile=false}]{\begingroup\input{\jobname.vrb}\endgroup}

is how beamer re-reads a fragile frame's body, and the body arrived after the
frame had closed — into a box nothing places.

pushInputLevel/popInputLevel make the file a level of its own, carrying the
buffer, the mouth's position, the line table, the pending lists and the
no-progress guard's baseline (which watches e.bpos, and a new buffer starts at 0
again). \input, \InputIfFileExists, the .bbl reader and class/package loading all
go through it, so the line-number bookkeeping that discounted a loaded file's
lines from the document's own (inputNL/loadedNL/nlCount) is gone: a file no
longer shifts the document's lines because it is no longer in its buffer.

\InputIfFileExists now runs its then-code BEFORE the file, which is what
ltfiles.dtx does: \IfFileExists{#1}{#2\@addtofilelist{#1}\@@input\@FilEf@und}.

## \begin{env} … \end{env} is a group (ltmiscen.dtx)

	\protected\def\begin#1{… \begingroup\@endpefalse\reserved@a}
	  where \reserved@a is \def\@Currenvir{#1}… \csname #1\endcsname
	\def\end#1{\csname end#1\endcsname\@Checkend{#1}\expandafter\endgroup …}

\begingroup comes first and \@Currenvir is defined inside it. Without the group
\@Currenvir was never restored, so a class that leaves an environment early by
closing its group could not — and beamer's fragile frame does exactly that:

	\def\beamer@checkforfragile#1fragile#2\relax{… \endgroup% end environment
	  \expandafter\beamer@framecommand\beamer@frameoptions\bgroup}

then calls \frame, which picks its syntax with \ifx\@Currenvir\beamer@frametext.
With \@Currenvir still "frame" the command form took the ENVIRONMENT path a
second time and \beamer@doseveralframes was handed the bare \bgroup instead of
the frame's body — measured, the frame went on the page empty.

The group is opened and closed by the Go-side probes \gotex@checkenv and
\gotex@endenv, not by \begingroup/\endgroup tokens, because \begin and \end must
stay expandable here: as tokens they would print as literal text wherever \begin
is only expanded (inside \message or \edef).

Four consequences, each from the reference:

  - Allocation is GLOBAL. ltplain.dtx's \e@alloc ends with
    `\global#2#6\allocationnumber`; ltcounts.dtx's \@definecounter makes \cl@<c>,
    \p@<c> and \the<c> global; ltthm.dtx's \@xnthm/\@ynthm use \xdef and
    \global\@namedef. So \newcount, \newdimen, \newskip, \newlength, \newcounter
    and \newtheorem now define globally — otherwise a counter declared inside
    \begin{document} (which is an environment) vanished with it.
  - Every alignment entry is a group (tex.web §791: a template's u-part and
    v-part are inserted inside braces), so a font switch in a cell stops there.
    buildCellHList terminated the cell with a bare } sentinel and no group; that
    stray brace was silently swallowed until a \begingroup was open.
  - An environment the engine implements in Go swallows its own \end, so \end —
    and the \endgroup with it — never runs: tabular, tabularx, verbatim,
    lstlisting, equation, align, minipage and the gobbled comment environments
    each close the group themselves.
  - setSrcPos no longer discounts loaded lines: a level reports its own file's
    line, which is where a diagnostic about that file belongs.

## Measured

200 real beamer talks and 200 arXiv papers, against main:

	beamer   1121 → 1031 pages   182 743 → 171 499 glyphs   16 up, 14 down
	arXiv    4052 → 4057 pages     9 485 942 → 9 234 865    14 up,  7 down

NOT a net win yet, and the reason is a defect that predates this branch and is
reproducible on main: with an outer theme of the split/infolines family
(\usetheme{Berlin}, Madrid, Warsaw, Copenhagen) the verbatim capture of a
fragile frame's FIRST line loses everything after its first control sequence —
\textbf{gras} is written to the .vrb as \textbf. Reading that back where it
belongs (inside the frame) then swallows the next line, which is why correcting
the ORDER makes those talks worse. See the issue.
tannevaled added a commit that referenced this pull request Aug 29, 2026
The environments the engine collects in Go — minipage, tabular, equation, align,
and the gobbled picture/comment environments — scan their body as RAW tokens,
looking for \end{name}. \csname was stored raw like anything else, and it must
not be: it can only produce a CONTROL SEQUENCE, and that sequence may be the
\end the scanner is hunting.

beamer reaches every one of its templates that way:

	\def\beamer@usebeamertemplatedo#1{\csname beamer@@tmpl@#1\endcsname}

and the rounded block's closing template is \end{beamerboxesrounded}, whose own
first move is \end{minipage}. Stored raw, that \end never surfaced: the minipage
scanner ran to the end of the document and took the talk with it.

Reduced to three lines, without beamer:

	\def\mf{\end{minipage}}
	\setbox0=\hbox{\begin{minipage}{100pt}X\csname mf\endcsname}  % 0.0pt
	\setbox0=\hbox{\begin{minipage}{100pt}X\end{minipage}}        % 100.0pt

Running \csname where the scanner already expands a macro that leads to \end
(expandsToEnd, hidesTabularEnd) is the same rule one step further: the token that
carries the environment's end may be BUILT rather than written.

Measured over 200 talks and 200 arXiv papers: not one document changes — 1121
pages and 188 933 glyphs on one side, 4184 and 9 493 784 on the other, identical
before and after. It closes a hole rather than moving anything.

Part of #115: the rounded block still renders nothing, so the \begin{block} path
has another obstacle above this one, but the layer this commit fixes is now
provably right — \begin{beamerboxesrounded}…\end{beamerboxesrounded} reached
through \csname renders where it did not.
tannevaled added a commit that referenced this pull request Aug 30, 2026
This engine renders no speaker notes, and beamer's note machinery emits PAGES.

\setbeameroption{show notes on second screen} (beamerbasenotes.sty) sets
\beamer@notes and \beamer@twoscreensnotes, and every frame is then typeset a
second time for the notes screen:

	\ifbeamer@twoscreenstext \beamer@dosecondscreennow{#1}\fi

LaTeX hands slide and note to pgfpages, which merges them onto ONE physical page.
With no merging the second pass came out as extra pages: each frame rendered
THREE, so five lines rendered six pages where LaTeX renders two.

	\documentclass{beamer}
	\setbeameroption{show notes on second screen}
	\begin{document}
	\begin{frame}{A}un\end{frame}
	\begin{frame}{B}deux\end{frame}
	\end{document}

The switch goes off at \begin{document}, after the preamble's \setbeameroption
has had its say — appended to the class load's post-amble, which is where @ is a
letter. \beamer@dosecondscreennow was the obvious target and is the wrong one:
neutralising it changes nothing (measured), because the pages come from the note
machinery itself.

Measured over 200 talks and 200 arXiv papers:

	beamer   1197 → 1175 pages   3 talks, all of them over-producers converging
	arXiv    unchanged, not one document moves

Against the 80 talks that now have a tectonic PDF beside them — ground truth —
the absolute page error falls from 70 to 48 and exact matches rise from 59 to 61.
The worst over-producer in the set goes from 21 pages to 7, which is exactly what
tectonic renders; another goes from 6 to 2, likewise exact.
tannevaled added a commit that referenced this pull request Aug 30, 2026
Two defects in report/book numbering, both measured against the real embedded
report.cls rather than a reconstruction of it.

\@addtoreset was undefined. report.cls ties the equation counter to chapter with
it, not with \newcounter{equation}[chapter] — the counter already exists, so
there is nothing to declare:

    \@addtoreset {equation}{chapter}
    \renewcommand\theequation
      {\ifnum \c@chapter>\z@ \thechapter.\fi \@Arabic\c@equation}

With the command undefined that line did nothing, so the chapter part of an
equation number advanced while the equation part kept counting across the whole
document: the second chapter's first equation printed (2.2).

A reset also has to CASCADE, and did not. The kernel zeroes a counter by
stepping it out of −1,

    \def\@stpelt#1{\global\csname c@#1\endcsname \m@ne\stepcounter{#1}}

so zeroing a counter runs THAT counter's own reset list too. addToReset appended
a flat "\global\count<code>=0", which stops at the first level. With section
registered within chapter and subsection within section, a \chapter therefore
left the subsection counter untouched: \thesubsection after the second chapter
read 2.0.2 where LaTeX gives 2.0.0. The reset list now holds \@stpelt{name}, and
\@stpelt is a primitive that zeroes and re-runs the list.

Both negative controls were run: with \@addtoreset removed the first test fails;
with the cascade replaced by the old flat assignment the other two fail, naming
2.0.2 and the grandchild that survived. Per-chapter section, figure, table and
theorem numbering were already correct and stay so.
tannevaled added a commit that referenced this pull request Aug 31, 2026
#153 said "a matrix is not braced". That is true of this engine and FALSE of TeX,
and the difference is worth stating where the code is read. tex.web §6738-6742:
align_state is increased by 1 for a { and decreased by 1 for a }, and §7259-7264: an
alignment entry ends at a tab or \cr only when align_state is back where it started.
A nested matrix is protected by a real brace, an implicit one:

	\newenvironment{bmatrix}{\left[\env@matrix}{\endmatrix\right]}   amsmath.sty:1082
	\def\env@matrix{…\array{*\c@MaxMatrixCols c}}                    amsmath.sty:1058
	\def\@array[#1]#2{…\bgroup …}                                    latex.ltx:12101

This engine never expands \bmatrix — the maths layer parses the source text itself —
so that \bgroup never arrives and the counter cannot see it. Counting the
environment is the same protection by another road, and the comment now says so.

The reading also turned up something the code did not do: tex.web §7492-7493 counts
IMPLICIT braces, \bgroup and \egroup, in align_state. The cell scanner looked only
at category-1 and -2 characters, so a & inside \bgroup…\egroup cut a cell that TeX
would not have cut. implicitChar is what the box scanner already uses for \bgroup;
the cell scanner now uses it too.

Measured over 200 arXiv papers and 200 beamer talks: not one document changes — the
corpus does not exercise it. The unit test does, on the scanner directly: with
\bgroup x & y\egroup a row has two cells, and had three.
tannevaled added a commit that referenced this pull request Aug 31, 2026
#155)

\pmb does not switch font. It typesets its argument THREE times, offset by a
fraction of an ex, so the ink looks heavier:

	\def\pmb@#1#2{\setbox8\hbox{$\m@th#1{#2}$}…
	  \mkern-.8mu\copy8 \kern\dimen@\mkern.4mu\raise\pmbraise@\copy8 …}
	                                                    (amsbsy.sty:40-57)

It is the fallback the package offers when no bold math version exists. One exists
here: the maths layer renders \boldsymbol, which is amsbsy's own real bold
(\mathversion{bold}, amsbsy.sty:28). Aliasing \pmb to it gives the formula the thing
\pmb was imitating instead of dropping it — 348 of the 4172 formulas the arXiv
corpus drops are this one command.

Measured over 200 arXiv papers and 200 beamer talks: 4 documents change and 2
repaginate (one closer to tectonic, one further) for +3373 glyphs of formulas that
were absent. The page error against the 157 tectonic renders is 670 → 669. beamer
does not move.
tannevaled added a commit that referenced this pull request Sep 25, 2026
fancyhdr's six fields were the only head this engine could draw. Every standard
class declares one the other way — article.cls:

    \def\ps@headings{%
      \let\@oddfoot\@empty
      \def\@oddhead{{\slshape\rightmark}\hfil\thepage}%
      \let\@mkboth\markboth
      \def\sectionmark##1{\markright{\MakeUppercase{…##1}}}}

and doPagestyle already RAN \ps@name, so those \def's took effect and nothing read
them back. Four links were missing, each one measured on its own:

  - \ps@headings and \ps@myheadings were never defined (and \ps@plain/\ps@empty
    did not CLEAR a head an earlier style set);
  - \@oddhead was never read: latexHead typesets it as one hbox to \hsize, the
    \hfil's inside placing the pieces, which is how LaTeX sets it;
  - \@startsection never called the mark. latex.ltx:12796 runs
    \csname #1mark\endcsname{#7} in BOTH branches of the secnumdepth test, and in
    the numbered one AFTER \refstepcounter so the mark carries the section it
    names. The starred form does not mark, and \@Gxstar leaves it alone;
  - \MakeUppercase was not \protected, so \markright{\MakeUppercase{…}} — which
    \ps@headings writes and \protected@xdef stores — broke the expansion and
    swallowed the rest of the paragraph. latex.ltx declares it
    \DeclareRobustCommand for exactly this.

Beside tectonic on \pagestyle{headings}, page 2 of a two-section document:

    tectonic   2   DEUXIEME SECTION    2
    before     2
    after      2   DEUXIEME SECTION    2

Measured over the 154-paper corpus, against origin/main = 3d7c481 rebuilt at
measurement time:

    Sigma|page error|   288 -> 292      no paper loses content
    glyphs              +63940

and papers drawing a running head at all go from 6 to 13 of the 28 whose
reference has one. The glyphs are the heads: on 2205.03780 the added words are its
section titles, one per page.

The +4 is the honest cost — a head occupies its band, and a few papers that were
fitting more text now paginate a page longer. It buys a line of text on every page
of seven more papers.

Part of #426.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 25, 2026
\@setfontsize#1#2#3 states a size (#2) and a leading (#3). The leading reached
\gotex@notefontsize only inside the \ifx#1\normalsize guard, so nine of the ten
size commands stated a skip that went nowhere.

latex.ltx:8533 \set@fontsize sets both from the one call; only
\gotex@classnormalsize, which records what the class calls normal and is the
denominator every other size is scaled against, belongs under that guard.

\the\baselineskip, tectonic against this engine:

                    tectonic   before    after
  \normalsize          12.0     12.0     12.0
  \small               11.0     12.0     11.0
  \footnotesize         9.5     12.0      9.5
  \Large               18.0     12.0     18.0

Each reference value is exactly the third argument of that size's \@setfontsize
call in the class size file, which is what makes the locus certain.

It is not only the register — the engine acts on \baselineskip, so a frozen
register was a frozen leading. Distance between two consecutive lines:

                       tectonic   before    after
  \normalsize             11.96    12.00    12.00
  \footnotesize            9.46    12.00     9.50
  \Large                  17.93    12.00    18.00
  back to \normalsize     11.96    12.00    12.00

\normalsize is the CONTROL and was already right, which is why this never looked
like a defect: body text was correct and only the size-switched blocks —
captions, abstracts, table bodies, and in several classes the whole bibliography
— were not. The residual +0.04pt is this engine's sp rounding and the control
carries it too.

\f@baselineskip had to become scoped with it. It is scoped in LaTeX (\set@fontsize
\edef's it inside whatever group is open), and baselineStretchFactor recovers the
line-spacing factor as the RATIO baselineskip/baseBaselineskip, so a
baseBaselineskip left behind by a closing brace reads as a \linespread the
document never asked for. Measured with the fix in and the scoping out, \Large
after a \footnotesize group comes out 22.73pt instead of 17.93 — 18 x (12/9.5),
compounding at every later switch. \linespread{1.5} is right in all three places
it is read: 18.00, 14.25 inside \footnotesize, 18.00 again on the way out.

One existing assertion changed rather than being accommodated. "another size
command is ignored" pinned \baselineskip NOT moving for a non-\normalsize switch,
which is the defect and not a requirement — the reference gives \small an 11pt
skip. What the \ifx guard legitimately protects went unasserted while it also
held the leading back, so TestSetfontsizeOnlyNormalsizeRestatesTheClassSize now
covers it, verified by removing the guard: a \small then moves the class size
reference from 10 to 9 and puts the whole ladder on a 9pt base.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 25, 2026
\@setfontsize#1#2#3 states a size (#2) and a leading (#3). The leading reached
\gotex@notefontsize only inside the \ifx#1\normalsize guard, so nine of the ten
size commands stated a skip that went nowhere.

latex.ltx:8533 \set@fontsize sets both from the one call; only
\gotex@classnormalsize, which records what the class calls normal and is the
denominator every other size is scaled against, belongs under that guard.

\the\baselineskip, tectonic against this engine:

                    tectonic   before    after
  \normalsize          12.0     12.0     12.0
  \small               11.0     12.0     11.0
  \footnotesize         9.5     12.0      9.5
  \Large               18.0     12.0     18.0

Each reference value is exactly the third argument of that size's \@setfontsize
call in the class size file, which is what makes the locus certain.

It is not only the register — the engine acts on \baselineskip, so a frozen
register was a frozen leading. Distance between two consecutive lines:

                       tectonic   before    after
  \normalsize             11.96    12.00    12.00
  \footnotesize            9.46    12.00     9.50
  \Large                  17.93    12.00    18.00
  back to \normalsize     11.96    12.00    12.00

\normalsize is the CONTROL and was already right, which is why this never looked
like a defect: body text was correct and only the size-switched blocks —
captions, abstracts, table bodies, and in several classes the whole bibliography
— were not. The residual +0.04pt is this engine's sp rounding and the control
carries it too.

\f@baselineskip had to become scoped with it. It is scoped in LaTeX (\set@fontsize
\edef's it inside whatever group is open), and baselineStretchFactor recovers the
line-spacing factor as the RATIO baselineskip/baseBaselineskip, so a
baseBaselineskip left behind by a closing brace reads as a \linespread the
document never asked for. Measured with the fix in and the scoping out, \Large
after a \footnotesize group comes out 22.73pt instead of 17.93 — 18 x (12/9.5),
compounding at every later switch. \linespread{1.5} is right in all three places
it is read: 18.00, 14.25 inside \footnotesize, 18.00 again on the way out.

One existing assertion changed rather than being accommodated. "another size
command is ignored" pinned \baselineskip NOT moving for a non-\normalsize switch,
which is the defect and not a requirement — the reference gives \small an 11pt
skip. What the \ifx guard legitimately protects went unasserted while it also
held the leading back, so TestSetfontsizeOnlyNormalsizeRestatesTheClassSize now
covers it, verified by removing the guard: a \small then moves the class size
reference from 10 to 9 and puts the whole ladder on a 9pt base.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
…ey (#448)

latex.ltx:1619 —

	\def\:{\let\@SPtoken= } \:  % this makes \@SPtoken a space token

and LaTeX's own look-ahead tests against it (latex.ltx:1609, \@ifnch's
\ifx\@let@token\@SPtoken). Left UNDEFINED, every such \ifx compares a space token
against an undefined control sequence and takes the wrong branch, in silence.

keyval's space trimmer is built on exactly that test (keyval.sty:47-52), so

	\setkeys{fam}{ key = value }

looked the key up as "\KV@fam@ key" and dropped the call -- and a preamble writes
its options with spaces. The engine already embeds the real keyval.sty (texmf.go),
so nothing was missing but this one token.

Witness, against tectonic 0.17.0, which renders both lines:

	\define@key{fam}{name}{[got #1]}
	\setkeys{fam}{name=TIGHT}      -> [got TIGHT]  both
	\setkeys{fam}{ name = SPACED } -> [got SPACED] reference only, before this

Measured against the parent a886b8b on the clean list of 154:

    Sigma|err| 331 -> 328 (-3)

⚠ abpair flags TWO papers as losing content (-82993 glyph paths). Read the
characters before believing it -- both are printed GARBAGE going away, and both
papers come out with MORE WORDS:

  2408.02845  ref 30 pages, 15783 words
              ctl 35 pages, 13600 words   sp 32 pages, 13733 words
    The control's densest pages (20518 and 16291 glyph paths) are the bibliography,
    printing "NatureMachineIntelligenceNatureMed.NatureReviewsGenetics…" -- an
    accumulating journal-name list re-emitted on every entry. Closer to the
    reference on BOTH counts now.

  2310.11517  ctl 7439 words, 84 glued runs over 40 characters
              sp  7470 words, 14
    The garbage is visible: "[table]labelfont+=small,textfont+=small,sf,bf,
    skip=10pt,position=above" -- a \captionsetup option list TYPESET as body text.
    With the keys found, it is consumed as options instead of printed.

A glyph-path delta is not a verdict (measure/TOOLS.md), and <path> is not one
element per character in this engine's SVG -- counting them gave me a wrong answer
about this very witness before pdftotext corrected it.

TestSptokenIsASpaceSoKeyvalTrims reads the engine's table rather than the render,
and fails on the parent with "\ranSPACED undefined: \setkeys never ran that key"
while \ranTIGHT still passes -- the tight form always worked.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
ltdefns.dtx:

	\long\def\@ifnextchar#1#2#3{\let\reserved@d=#1
	  \def\reserved@a{#2}\def\reserved@b{#3}\futurelet\@let@token\@ifnch}

\let\reserved@d=#1 takes #1 as an UNDELIMITED ARGUMENT, so a brace group around the
target is stripped and \@ifnextchar{*}{A}{B} tests for a star exactly as
\@ifnextchar*{A}{B} does. This primitive read it with one getNext, which took the
BRACE as the target — after which the two branches were read one token late, BOTH
were emitted, and the star was typeset.

Judged against tectonic 0.17.0:

	\def\tb{\@ifnextchar{*}{YES}{NO}}   A\tb* B\tb x C
	\def\tn{\@ifnextchar*{YES}{NO}}     D\tn* E\tn y F

	reference   braced: AYES* BNOx C          bare: DYES* ENOy F
	before      braced: A*YESNO* B*YESNOx C   bare: DYES* ENOy F
	after       braced: AYES* BNOx C          bare: DYES* ENOy F

Only the braced form was wrong, and every earlier witness used a bare target — which
is how it survived. A bare control sequence (\@ifnextchar\bgroup) and a bare
character (\@ifnextchar[) both arrive as a one-token argument and are unchanged.

It is not a corner case. xkeyval reaches it through xkvutils' \@ifnextcharacter,
whose FIRST branch has a braced target and is taken whenever the next token is a
brace — \setkeys{fam}{…}, the common case. Every \setkeys printed "*+" and left two
groups open. On the 8-line witness of #306:

	\usepackage{xkeyval}
	\define@key{fam}{name}{[got #1]}
	\setkeys{fam}{name=VALUE}

	before  *+            after  [got VALUE]    reference  [got VALUE]

and on corpus paper 2407.13726 (acmart [acmsmall,authorversion,nonacm,screen],
reference 27 pages), with the real xkeyval on GOTEX_TEXMF:

	before  1 page,  9 undefined, 41 argument grabs abandoned, 4 groups open
	after   26 pages, 21 undefined, none abandoned, no group left open

Measured on the DEFAULT configuration, clean list of 154, against deb1e54:

	Sigma|err| 328 -> 328 (+0), glyphs +0, 0 papers moved

Neutral by default because nothing in the default path writes a braced target — the
xkeyval that does is not embedded yet (see #306, and branch fix/filelist for the
three kernel names it also needs).

TestIfnextcharTargetIsAnArgumentNotAToken pins all four combinations and fails on
the parent with "ranNO branch ALSO ran — both were emitted", on the braced cases
only.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
Both read straight past it. color.sty:88-90 and 103-104 (xcolor.sty:711 and 758-759
are the same):

	\DeclareRobustCommand\color{\@ifnextchar[\@undeclaredcolor\@declaredcolor}
	\def\@undeclaredcolor[#1]#2{…\csname color@#1\endcsname\current@color{#2}…}
	\protected\def\textcolor#1#{\@textcolor{#1}}
	\def\@textcolor#1#2#3{\protect\leavevmode{\color#1{#2}#3}}

\textcolor's parameter text is "#1#" — delimited by the next brace — so the bracket,
if any, lands in #1 and the name in #2. Taking two plain arguments bound #1=[HTML]
and #2={FF0000} and left the TEXT unconsumed. For \color, readBraceName saw "["
where it wanted "{", backed the token up and returned empty: the colour was not set
AND the spec was typeset.

parseColorSpec already knew every model the reference does (rgb, RGB, gray, HTML,
cmyk) — it was reachable only through \definecolor.

Judged against tectonic 0.17.0, which renders "A ROUGEB C VERT D E BLEU F G RGBH":

	before  A [HTML]FF0000ROUGE B C HTML]00FF00VERT D E BLEU F G [rgb]1,0,0RGB H
	after   A ROUGE B C VERT D E BLEU F G RGB H

Measured, clean list of 154, against 6953499:

	Sigma|err| 328 -> 324 (-4), glyphs -14243, 9 papers moved

and THREE of them land exactly: 2304.05592 (21->20 of 20), 2402.04392 (9->8 of 8),
2402.04684 (10->9 of 9). 2405.18549 goes 42->41 of 37 and 2407.09954 28->30 of 31.

abpair flags six as losing content; every one is the SPEC no longer being typeset.
Judged the only way that answers it — are the lost WORDS in the paper's reference PDF:

	paper        words lost  of them in the reference   sample
	2304.05592          284                        4    rgb]0.37,0.37,0.37#
	2407.13726          181                        3    [HTML]000000sparsity
	2405.18549          111                        3    ${w_R}$
	2402.04711          113                        -    (no reference PDF)
	2111.13456           38                        0    c(\partial_{t}p…
	2311.09365           17                        0    [rgb]0,0,0

2304.05592's four are "11", "13", "14" and "high-dimensional" — page numbers, and one
word that was GLUED to a spec ("rgb]…high-dimensional") and now stands on its own. Its
word count moves only 8217 -> 8197 while its glyphs move -8292: the specs were inside
words, and removing them shortens words without removing text.

Known and deliberately NOT in this change: the reference's \@undeclaredcolor and
\@declaredcolor both end with \ignorespaces and ours do not, so "\color{black} B"
keeps a space the reference eats ("ROUGE B" against "ROUGEB"). That predates this and
touches every \color in the corpus, so it wants its own measurement. \leavevmode is
left out of \textcolor for the same reason.

TestColorTakesAnOptionalModel pins all four forms and fails on the parent with five
specs on the page.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
color.sty ends BOTH of \color's branches with \ignorespaces —

	\def\@undeclaredcolor[#1]#2{… \set@color}\ignorespaces}   % l.90-95
	\def\@declaredcolor#1{… \set@color}\ignorespaces}         % l.96-102

and xcolor's \color (xcolor.sty:711) delegates to the same two. We kept the space, so
"\color{red} X" typeset " X" where the reference typesets "X". On #452's witness the
reference renders

	A ROUGEB C VERT D E BLEU F G RGBH

and we rendered "A ROUGE B … RGB H". After this the two are identical character for
character.

The \ignorespaces loop is lifted out of its primitive (amssubstrate.go) into
e.ignoreSpaces rather than copied, because a second copy of a rule is a second thing
to keep in step.

Measured, clean list of 154, against 19b1b3e:

	Sigma|err| 324 -> 324 (+0), glyphs +2, 0 papers moved

Neutral on the corpus. It ships on being right, not on Sigma — and on Sigma alone there
would be no reason to look at it, which is the point: the spacing was wrong in every
document that colours a word, and the metric could not see one space.

TestColorIgnoresFollowingSpaces asserts RELATIONALLY: the SVG's source layer spells the
SOURCE, not the output, so asserting on the string "AB" fails even with the fix — that
is how this test first came out red. What the rule says is that the space makes no
difference, so "A \color{red} B" must render what "A \color{red}B" renders. It carries
its own control ("A B" against "AB"), because a measure that cannot see a space at all
would pass either way.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
… from #452 (#454)

#452 gave \textcolor the reference's own parameter text,
\protected\def\textcolor#1#{\@textcolor{#1}} (color.sty:103, xcolor.sty:758), whose
first argument is delimited by the next BRACE. That is right for TeX and wrong here: the
maths layer works on a SOURCE STRING, and renderMathResolvingMacros expands a macro by
matching its parameter text against TEXT. It cannot match a brace-delimited parameter.

	\newcommand{\W}{\ensuremath{\textcolor{darkgreen}{\boldsymbol{w}_R}}}

expanded to "{arkgreen{" — the backslash and the colour name's first letter eaten — and
go-tex/math refused it with "missing }". 52 equations on corpus paper 2405.18549 and 86
over five papers, NONE of them dropped before #452.

An \@ifnextbracket dispatcher fails the same way for the same reason: it has to LOOK at
the next token, which a string expander cannot do. It reached the maths layer as
\@ifnextbracket and dropped the equation under that name instead. Both were tried.

A PRIMITIVE is the answer, and not by accident: expandMacroInMathSource declines a
primitive, so the source falls through to stripMathColor, which already knows the
command and its optional model (math.go, "textcolor": {2, 1}) and strips it while
KEEPING the content — an equation set in the surrounding colour rather than dropped.

In text it rebuilds the reference's own body, {\color#1{#2}#3} (color.sty:104), and
pushes it for the mouth to read: the group is TeX's. Opening it with e.beginGroup and
closing it by pushing \endgroup instead left the brace bookkeeping one deep and every
\textcolor raised "Missing } inserted" — four tests caught that.

Measured, clean list of 154, against 7c6e838:

	Sigma|err| 324 -> 325 (+1), glyphs +3539, 0 papers losing content

	2111.13456  ref 29   35 -> 34
	2402.04711  ref 198  180 -> 181
	2405.18549  ref 37   41 -> 42
	2407.09954  ref 31   30 -> 28

+1 on Sigma for 3539 glyphs of mathematics that the reference has and we were dropping.
A restored equation moves a page count in EITHER direction (measure/TOOLS.md); the four
papers are back exactly where they stood before #452.

## What let a merged change lose 86 equations

The A/B did not see it. Sigma went DOWN by 4 and the glyph delta showed 2416 fewer on
2405.18549, which I read as the colour specs #452 stops typesetting — and part of it
was. The rest was the equations. One of the "garbage" words I cleared it on was
"${w_R}$", which is the SYMBOL.

What saw it was the per-channel census (campaign.py): "$math$ texmath: missing }" went
from absent to 86 in five papers. A page count cannot see an equation, so a change to a
colour command has to be measured on the equation channel too.

TestTextcolorInMathsKeepsTheEquation pins all three shapes — direct, through a macro as
the corpus writes it, and with a model — and is the test that should have existed before
#452.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 26, 2026
wrapfig.sty:40-43:

	\def\wrapfloat#1{\def\@CapType{#1}\@ifnextchar[\WF@wr{\WF@wr[]}}
	\def\wrapfigure{\wrapfloat{figure}}
	\def\wraptable{\wrapfloat{table}}

so \begin{wrapfigure}[<lines>]{<position>}{<width>}. Undefined, \begin{wrapfigure}
resolved to \relax through \csname: the POSITION and the WIDTH were typeset on the page,
the body was set as running prose — a figure and its caption in the middle of a sentence —
and \caption, with no \@CapType, came out as "by1:" instead of "Figure 1:".

	main   AVANT texte. r0.4 FIGCONTENT by1: LALEGENDE Du texte qui…
	this   AVANT texte. FIGCONTENT Figure 1: LALEGENDE Du texte qui…

Eight corpus papers use wrapfigure, seventeen times; two use wraptable.

This engine cannot reshape a paragraph, so the text does NOT wrap: the body becomes an
ordinary centred float of the stated width. The width is honoured through a \parbox rather
than dropped, because a wrapfigure is narrow by construction (0.3-0.5\textwidth is the
norm) and a full-width float would cost more vertical space than the real one does. The
reference also DEFERS the float to a later position, which this does not.

Measured against its parent 10073fb, clean list of 154:

	Sigma|err| 323 -> 324 (+1), glyphs -82, 0 papers losing content
	2406.13839  ref 23  28 -> 29

and on that one paper the ONLY words lost are "R0.3" and "r0.5" — the arguments, which
the reference does not print. Sigma pays one page for a figure that is now a float with a
correctly numbered caption instead of prose with its own argument in front of it.

The equation channel is identical before and after (campaign.py), per engine#454.

TestWrapfigureConsumesItsArgumentsAndFloats pins all three shapes. Two notes on it, both
learned the hard way here:

  - the width in the witness is 0.4321\textwidth, not 0.4\textwidth, because searching the
    SVG for "0.4" hits its own numeric attributes and the assertion came out red against a
    fix that works;
  - the break check must run with -count=1. Without it "go test" served a CACHED pass and
    reported ok for a tree with the fix stashed out — and the stash push of an
    already-committed file is a no-op, so the second attempt popped an unrelated stash
    instead. Build the parent from git archive and drop the test file in.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
Nothing between \documentclass and \begin{document} is typeset — LaTeX refuses text there
outright ("Missing \begin{document}") — so lenient recovery may discard an undefined
command's arguments in the preamble exactly as it does inside a package. skipUndefined's own
comment already states the rule it missed: "only where nothing is typeset".

Left standing, the leaked text OPENED A PAGE. Corpus paper 2304.01951 \inputs macros.tex
from its preamble, and macros.tex carries

	\pgfdeclarelayer{background}
	\pgfsetlayers{background,main}

both undefined with GOTEX_PGF off. Their arguments were typeset, that text began a page, and
the paper's real title page became page 2 — a page 1 holding the words "background" and
"background,main" and nothing else of the document.

The e.hasClass guard keeps a FRAGMENT safe: a file with no \documentclass has no preamble,
so nothing in it may be discarded — that mistake reads as a smaller corpus (measure/TOOLS.md,
#395). TestAFragmentHasNoPreambleToDiscardIn pins it.

## Measured, clean list of 154, against its parent 188f276

	Sigma|err| 326 -> 330 (+4)
	glyphs     -1266

	channel                     main    branch
	undefined commands          1010    1013      +3
	DROPPED EQUATIONS            289     271     -18
	undefined environments       357     357       0
	figures as an empty box      997     997       0

18 equations recovered: a preamble that stops typesetting stops leaving the maths layer
material it cannot read.

Sigma pays 4, and four of the papers that pay it were EXACT — 2201.04865, 2304.05592,
2311.00084 and 2403.16666 each lose the page of preamble garbage that made them exact.

## No distinctive content is lost, and the first answer said otherwise

Twelve papers move. Asked whether the lost WORDS appear in each paper's reference PDF, three
came out "content" — and that verdict was WRONG, from a test whose vocabulary was too coarse.
On 2407.18384 it reported 74 of 78 lost words present in the reference; the 74 were

	29  35  37  44  52  55  61  64  66  71  73  75  82  84  86  89  98 …

table-of-contents PAGE NUMBERS, and every two-digit number appears somewhere in a 333-page
document. Counting only DISTINCTIVE tokens — five characters or more, not purely numeric —
all three come out with ZERO lost words in their references, and the lost tokens read as what
they are:

	Scale=MatchLowercase    genTri3and(#1    dbluecolorrgb0.01,0.02,0.7
	ShowDetailedProofs      yhlargesymbols"F3    [auto

The sharpening does not overturn a real finding: "Gaithersburg", "(NIST)" and "Measurement"
on 2209.13121 (engine#451) pass it. It removes the coincidences. measure/TOOLS.md now states
the rule with the threshold.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
…le (#462)

Nothing between \documentclass and \begin{document} is typeset — LaTeX refuses text there
outright ("Missing \begin{document}") — so lenient recovery may discard an undefined
command's arguments in the preamble exactly as it does inside a package. skipUndefined's own
comment already states the rule it missed: "only where nothing is typeset".

Left standing, the leaked text OPENED A PAGE. Corpus paper 2304.01951 \inputs macros.tex
from its preamble, and macros.tex carries

	\pgfdeclarelayer{background}
	\pgfsetlayers{background,main}

both undefined with GOTEX_PGF off. Their arguments were typeset, that text began a page, and
the paper's real title page became page 2 — a page 1 holding the words "background" and
"background,main" and nothing else of the document.

The e.hasClass guard keeps a FRAGMENT safe: a file with no \documentclass has no preamble,
so nothing in it may be discarded — that mistake reads as a smaller corpus (measure/TOOLS.md,
#395). TestAFragmentHasNoPreambleToDiscardIn pins it.

## Measured, clean list of 154, against its parent 188f276

	Sigma|err| 326 -> 330 (+4)
	glyphs     -1266

	channel                     main    branch
	undefined commands          1010    1013      +3
	DROPPED EQUATIONS            289     271     -18
	undefined environments       357     357       0
	figures as an empty box      997     997       0

18 equations recovered: a preamble that stops typesetting stops leaving the maths layer
material it cannot read.

Sigma pays 4, and four of the papers that pay it were EXACT — 2201.04865, 2304.05592,
2311.00084 and 2403.16666 each lose the page of preamble garbage that made them exact.

## No distinctive content is lost, and the first answer said otherwise

Twelve papers move. Asked whether the lost WORDS appear in each paper's reference PDF, three
came out "content" — and that verdict was WRONG, from a test whose vocabulary was too coarse.
On 2407.18384 it reported 74 of 78 lost words present in the reference; the 74 were

	29  35  37  44  52  55  61  64  66  71  73  75  82  84  86  89  98 …

table-of-contents PAGE NUMBERS, and every two-digit number appears somewhere in a 333-page
document. Counting only DISTINCTIVE tokens — five characters or more, not purely numeric —
all three come out with ZERO lost words in their references, and the lost tokens read as what
they are:

	Scale=MatchLowercase    genTri3and(#1    dbluecolorrgb0.01,0.02,0.7
	ShowDetailedProofs      yhlargesymbols"F3    [auto

The sharpening does not overturn a real finding: "Gaithersburg", "(NIST)" and "Measurement"
on 2209.13121 (engine#451) pass it. It removes the coincidences. measure/TOOLS.md now states
the rule with the threshold.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
\newcommand{\code}[1]{\mathtt{#1}} rendered its argument in the SURROUNDING face, not
typewriter, and nothing reported it. Written directly, $\mathtt{A}$ was always right;
only a macro lost it, which is what kept this invisible.

classkernel.go:427-439 defines the \math… alphabets as identity wrappers —
\def\mathtt#1{#1} — which is correct in TEXT mode, where the engine has one face. Its
comment says the identity is "harmless, user math is handled wholesale by the math
layer", and a substituted macro body is exactly what breaks that premise:
flattenMathBody runs the body through the gullet, so the alphabet expands away before
go-tex/math, which knows \mathtt perfectly well, ever sees it. \boldsymbol survives
only because the engine does not define it.

flattenMathBody already protects this class of name — \begin, \end, and the char
stand-ins whose comment states the principle: "In a formula those names are the maths
layer's own — \cdot is ⋅ and it renders it — so flattening one into \char costs the
formula." mathFontSwitch holds only TEXT-mode switches (\ttfamily, \bf …), not the
alphabets.

The eight names are the intersection of two sets: what the engine defines as an
identity and what go-tex/math's alphabetFor answers for. \mathnormal is out because
the layer has no mapping for it, so the identity is the right fallback; \mathds is out
because classkernel defines it as an ALIAS to \mathbb, and expanding it is the point.
Both exclusions are asserted, so a later edit does not add them by symmetry.

  mathAlphabet is a LIST, which go-tex/math could drift from, so every entry is
  rendered against a control and must differ. That test is what makes hard-coding it
  defensible, and writing it found something: \mathit is byte-identical to no alphabet
  at all, because maths sets letters, digits and words in italic ALREADY. Its effect is
  only observable NESTED — \mathbf{a\mathit{b}} is 655360 wide against \mathbf{ab}'s
  720896 — so it has its own subject in the table. A flat subject would have "passed"
  while proving nothing.

The witness is the SOURCE handed to the maths layer, not the rendered box: an identity
wrapper keeps the glyph count and very nearly the width, so neither the
dropped-equation census nor the page barometer nor the ink ratio can see this. That is
also why it survived.

Population: 68 of the 200 papers on the sweep list define a macro wrapping one of
these alphabets, and 7537 of the 22127 papers harvested do — a third of them.

Removing the protection breaks 16 assertions.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
Two instances of one defect: a name the MATHS LAYER renders itself, overridden by the
engine's own text-mode definition when flattenMathBody runs a substituted macro body
through the gullet.

  \newcommand{\code}[1]{\mathtt{#1}}   $\code{A}$    handed the layer  "A"
  \newcommand{\w}[1]{a\;#1}            $\w{b}$       handed the layer  "a b"

Written directly, $\mathtt{A}$ and $a\;b$ were always right. Only a macro lost them,
which is what kept both invisible.

classkernel.go:427-439 defines the \math… alphabets as identity wrappers
(\def\mathtt#1{#1}) and format.go:47-56 defines the spacing commands as ordinary
horizontal space (\let\,\thinspace, \def\;{\hskip.27778em}, \def\quad{\hskip1em}).
Both are correct in TEXT mode, and both carry a comment saying so — "harmless, user
math is handled wholesale by the math layer" and "what a real LaTeX produces in text".
A substituted macro body is exactly what breaks that shared premise.

  \! is the one that was not merely lost. It is a NEGATIVE thin space, −3mu, and it
  came out as a positive space: a formula written to pull two atoms together pushed
  them apart. Asserted as an ORDER rather than a width — a\!b < ab < a\,b — because a
  width pins today's font while the order is what −3mu, 0 and +3mu mean.

flattenMathBody already protects this class: \begin, \end and the char stand-ins, whose
comment states the principle — "In a formula those names are the maths layer's own —
\cdot is ⋅ and it renders it — so flattening one into \char costs the formula."
mathFontSwitch holds only TEXT-mode switches (\ttfamily, \bf …).

The eight alphabets are the intersection of what the engine defines as an identity and
what go-tex/math's alphabetFor answers for. \mathnormal is out because the layer has no
mapping, so the identity is the right fallback; \mathds is out because classkernel
defines it as an ALIAS to \mathbb and expanding it is the point. Both exclusions are
asserted so a later edit does not add them by symmetry.

  Both lists get a drift guard: every entry must be observable against a control. That
  is what makes hard-coding them defensible, and writing the first one found something
  — \mathit is byte-identical to no alphabet at all, because maths sets letters, digits
  and words in italic ALREADY. Its effect is only observable NESTED:
  \mathbf{a\mathit{b}} is 655360 wide against \mathbf{ab}'s 720896. It has its own
  subject in the table; a flat subject would have "passed" while proving nothing.

  The second guard caught a defect in its own test: $a\qquadb$ is an unknown command,
  not a spacing test. The subjects carry an explicit separator now, and the control
  carries the same space so the comparison is of the spacing command alone.

The witness is the SOURCE handed to the maths layer, not the rendered box: an identity
wrapper keeps the glyph count and very nearly the width, so neither the
dropped-equation census nor the page barometer nor the ink ratio can see any of this.
That is also why it survived.

Population: 68 of the 200 papers on the sweep list define a macro wrapping one of these
alphabets, and 7537 of the 22127 papers harvested do.

Removing the alphabet protection breaks 16 assertions; removing the spacing protection
breaks 7.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
A string-comparison switch — a test string and a list of {case}{code} pairs, expanding
to the first match. 33 equations on one arXiv paper were dropped by one, the largest
single item in the dropped-equation census.

The bibliography decided the approach. The real machinery cannot be expanded textually
— \xs_testcase recursing over \_nil delimiters, \xs_ifstar, \xs_testopt
(xstring.tex:626-645) — but the switch's DECISION can, and that is all the reader
needs. What the sources gave that guesswork would not:

  xstring.tex:588-596  the comparison is exact string equality FIRST (\xs_ifx), then
                       numeric equality if BOTH sides are decimals (\ifdim#1pt=#2pt),
                       otherwise false.

  So \IfEqCase falls back to numbers and \IfStrEqCase does not (\xs_IfStrEqFalse_ii
  versus _i). Folding the two together would have made the second wrong, and a test
  pins the difference on "1.0" against the case "1" — equal as numbers, different as
  strings.

  xstring.tex:235-256  the star swaps \xs_expand_and_assign for
                       \xs_expand_and_detokenize, so the starred form compares the
                       arguments' printed characters. A go-tex/math source string is
                       already scanned text, so the starred behaviour is what this
                       reproduces, and the unstarred form's token-level comparison is
                       not available here.

Rewritten in the engine and gated on \usepackage{xstring}, following resolvePhysics
and resolveLeftIndex: the names could be a document's own.

Measured on the corpus: 224 dropped equations become 191. Exactly -33, one trigger
gone, NO trigger appeared and no other count moved.

  Each branch is tested against that branch WRITTEN OUT, not against a number:
  "the switch chose case 1" only means something as "it produced what case 1 says",
  and a test that merely checked the equation survived would pass on a switch that
  always took the first case. The else branch is tested too, since dropping it
  silently would leave the symbol off the page.

  The branches are distinguished by their CONTENT and not by a face. A document macro
  wrapping \mathtt loses it before the maths layer sees the formula —
  classkernel.go:431 defines \def\mathtt#1{#1} as a text-mode fallback and
  flattenMathBody expands it, while go-tex/math knows \mathtt perfectly well. That is
  a separate defect, found while writing these tests and reported separately; using a
  face as the witness here would have tested it instead of this.

A malformed switch is left for go-tex/math to report rather than silently swallowed,
and an odd trailing group falls to the else branch instead of being paired with the
next case's code — guessing which half it is would put the wrong material on the page.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
Two instances of one defect: a name the MATHS LAYER renders itself, overridden by the
engine's own text-mode definition when flattenMathBody runs a substituted macro body
through the gullet.

  \newcommand{\code}[1]{\mathtt{#1}}   $\code{A}$    handed the layer  "A"
  \newcommand{\w}[1]{a\;#1}            $\w{b}$       handed the layer  "a b"

Written directly, $\mathtt{A}$ and $a\;b$ were always right. Only a macro lost them,
which is what kept both invisible.

classkernel.go:427-439 defines the \math… alphabets as identity wrappers
(\def\mathtt#1{#1}) and format.go:47-56 defines the spacing commands as ordinary
horizontal space (\let\,\thinspace, \def\;{\hskip.27778em}, \def\quad{\hskip1em}).
Both are correct in TEXT mode, and both carry a comment saying so — "harmless, user
math is handled wholesale by the math layer" and "what a real LaTeX produces in text".
A substituted macro body is exactly what breaks that shared premise.

  \! is the one that was not merely lost. It is a NEGATIVE thin space, −3mu, and it
  came out as a positive space: a formula written to pull two atoms together pushed
  them apart. Asserted as an ORDER rather than a width — a\!b < ab < a\,b — because a
  width pins today's font while the order is what −3mu, 0 and +3mu mean.

flattenMathBody already protects this class: \begin, \end and the char stand-ins, whose
comment states the principle — "In a formula those names are the maths layer's own —
\cdot is ⋅ and it renders it — so flattening one into \char costs the formula."
mathFontSwitch holds only TEXT-mode switches (\ttfamily, \bf …).

The eight alphabets are the intersection of what the engine defines as an identity and
what go-tex/math's alphabetFor answers for. \mathnormal is out because the layer has no
mapping, so the identity is the right fallback; \mathds is out because classkernel
defines it as an ALIAS to \mathbb and expanding it is the point. Both exclusions are
asserted so a later edit does not add them by symmetry.

  Both lists get a drift guard: every entry must be observable against a control. That
  is what makes hard-coding them defensible, and writing the first one found something
  — \mathit is byte-identical to no alphabet at all, because maths sets letters, digits
  and words in italic ALREADY. Its effect is only observable NESTED:
  \mathbf{a\mathit{b}} is 655360 wide against \mathbf{ab}'s 720896. It has its own
  subject in the table; a flat subject would have "passed" while proving nothing.

  The second guard caught a defect in its own test: $a\qquadb$ is an unknown command,
  not a spacing test. The subjects carry an explicit separator now, and the control
  carries the same space so the comparison is of the spacing command alone.

The witness is the SOURCE handed to the maths layer, not the rendered box: an identity
wrapper keeps the glyph count and very nearly the width, so neither the
dropped-equation census nor the page barometer nor the ink ratio can see any of this.
That is also why it survived.

Population: 68 of the 200 papers on the sweep list define a macro wrapping one of these
alphabets, and 7537 of the 22127 papers harvested do.

Removing the alphabet protection breaks 16 assertions; removing the spacing protection
breaks 7.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
Two instances of one defect: a name the MATHS LAYER renders itself, overridden by the
engine's own text-mode definition when flattenMathBody runs a substituted macro body
through the gullet.

  \newcommand{\code}[1]{\mathtt{#1}}   $\code{A}$    handed the layer  "A"
  \newcommand{\w}[1]{a\;#1}            $\w{b}$       handed the layer  "a b"

Written directly, $\mathtt{A}$ and $a\;b$ were always right. Only a macro lost them,
which is what kept both invisible.

classkernel.go:427-439 defines the \math… alphabets as identity wrappers
(\def\mathtt#1{#1}) and format.go:47-56 defines the spacing commands as ordinary
horizontal space (\let\,\thinspace, \def\;{\hskip.27778em}, \def\quad{\hskip1em}).
Both are correct in TEXT mode, and both carry a comment saying so — "harmless, user
math is handled wholesale by the math layer" and "what a real LaTeX produces in text".
A substituted macro body is exactly what breaks that shared premise.

  \! is the one that was not merely lost. It is a NEGATIVE thin space, −3mu, and it
  came out as a positive space: a formula written to pull two atoms together pushed
  them apart. Asserted as an ORDER rather than a width — a\!b < ab < a\,b — because a
  width pins today's font while the order is what −3mu, 0 and +3mu mean.

flattenMathBody already protects this class: \begin, \end and the char stand-ins, whose
comment states the principle — "In a formula those names are the maths layer's own —
\cdot is ⋅ and it renders it — so flattening one into \char costs the formula."
mathFontSwitch holds only TEXT-mode switches (\ttfamily, \bf …).

The eight alphabets are the intersection of what the engine defines as an identity and
what go-tex/math's alphabetFor answers for. \mathnormal is out because the layer has no
mapping, so the identity is the right fallback; \mathds is out because classkernel
defines it as an ALIAS to \mathbb and expanding it is the point. Both exclusions are
asserted so a later edit does not add them by symmetry.

  Both lists get a drift guard: every entry must be observable against a control. That
  is what makes hard-coding them defensible, and writing the first one found something
  — \mathit is byte-identical to no alphabet at all, because maths sets letters, digits
  and words in italic ALREADY. Its effect is only observable NESTED:
  \mathbf{a\mathit{b}} is 655360 wide against \mathbf{ab}'s 720896. It has its own
  subject in the table; a flat subject would have "passed" while proving nothing.

  The second guard caught a defect in its own test: $a\qquadb$ is an unknown command,
  not a spacing test. The subjects carry an explicit separator now, and the control
  carries the same space so the comparison is of the spacing command alone.

The witness is the SOURCE handed to the maths layer, not the rendered box: an identity
wrapper keeps the glyph count and very nearly the width, so neither the
dropped-equation census nor the page barometer nor the ink ratio can see any of this.
That is also why it survived.

Population: 68 of the 200 papers on the sweep list define a macro wrapping one of these
alphabets, and 7537 of the 22127 papers harvested do.

Removing the alphabet protection breaks 16 assertions; removing the spacing protection
breaks 7.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
Found by looking at the page after the spanning title block landed: 2405.05734's
author line came out as

    Daanish Mahajan
          ,
     Chirag Jain
          ,
    Navin Kashyap

where the reference reads "Daanish Mahajan, Chirag Jain, Navin Kashyap".

IEEEtran defines the author blocks TWO WAYS, and the distinction is the whole point.
In conference, peerreviewca and transmag mode they are ROWS of \@IEEEauthorhalign,
each ended by its own \crcr (IEEEtran.cls:4632, :4649). Outside those modes the class
defines plain pass-throughs (:4676-4677):

    \def\IEEEauthorblockN#1{#1}
    \def\IEEEauthorblockA#1{#1}

because a journal paper writes the blocks INLINE with its own punctuation between
them — which is exactly what 2405.05734 does, and breaking there strands every comma
alone on a line.

The halign is still not implemented, so the conference rows are a vertical stack
rather than side-by-side columns. But the mode distinction costs nothing to keep and
is visible on the page both ways: with rows everywhere, a journal author line is shot
through with orphan commas; with pass-throughs everywhere, 2408.02112's conference
author ran together on one line off the right edge of the page.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 27, 2026
…481)

* engine: IEEEtran's author blocks, and the lockout override that must exist

\IEEEauthorblockN and \IEEEauthorblockA were undefined, so a conference paper's
names and affiliations were skipped as commands and their arguments ran into ONE
paragraph. On 2408.02112 the reference reads "Stephen M. Watt" and "D. J. Jeffrey"
above their affiliations; we produced "Stephen M. Watt Ontario Research Centre for
Computer Algebra and Cheriton School of …".

IEEEtran.cls:4676-4677 defines both as pass-throughs outside conference,
peerreviewca and transmag mode, and inside those modes sets them through
\@IEEEauthorhalign (:4683), which places the name rows and the affiliation rows
side by side in COLUMNS. That halign is not implemented, so every mode gets the
pass-through — but not a bare #1: the halign's \crcr is what ends each block, and
without it the run-together is exactly what we had. A paragraph per block keeps the
content and its reading order and loses only the column arrangement.

\IEEEoverridecommandlockouts restores \thanks, \IEEEPARstart, \IEEEbiography,
\IEEEpubid and \IEEEmembership from their saved meanings, which conference mode
locked out (IEEEtran.cls:6274-6285). Nothing is locked out here, so there is nothing
to restore — but the command has to EXIST, because a paper that calls it is stopped
by an undefined control sequence before its preamble is finished. Two corpus papers
do (2304.04876, 2311.16571).

Census: 5 papers, 13 uses, and it was only visible at all after #480 — the command
sits inside \author{…} after a blank line, so the engine never reached it while the
call was being abandoned.

⛔ Not fixed here, and larger: the IEEEtran title block does not SPAN the columns.
The class sets two columns from \documentclass, and the generic \maketitle
(latex.go:193) emits the title into column one, where it overlaps the body — the
affiliation on 2408.02112 runs off the right edge. The machinery exists
(colRegion.span, \@topnewpage, and \gotex@revtexbodytwocol as the model); it is its
own change.

Co-Authored-By: Claude Opus 5 <[email protected]>

* engine: IEEEtran's title block is a vertical, column-spanning block

The author-block commands alone changed the corpus by ZERO — Σ +0, glyphs +0, and
byte-identical page hashes on every paper. That measurement is what found the real
defect, which is in \maketitle.

⛔ \centerline{\@author} is an \hbox, and an IEEEtran author is a VERTICAL list:
\IEEEauthorblockN{name} over \IEEEauthorblockA{affiliation}, repeated per author. An
hbox flattens it into one line that does not wrap, so a \par inside it does nothing —
which is exactly why defining \IEEEauthorblockN with one had no effect. On 2408.02112
the reference sets two authors side by side over four affiliation lines each; we set
one line that ran off the right edge of the page.

⛔ And the block did not SPAN the columns. IEEEtran sets two from \documentclass, and
applyTwoColumnMeasure defers halving the measure to the first BODY paragraph — so the
title block was typeset at FULL width and then sliced by paginateTwoColList as if it
were column material. That is what put the title through the introduction.

\twocolumn[…] is the construct for this: its bracket material is typeset full width
and placed across the top of the region's first page (typesetSpanFullWidth,
colRegion.span), which is how the revtex emulation already does it. On 2408.02112 the
title now sits across the page, each name over its own affiliation lines, with the
abstract and the body in two columns below it — the reference's structure, minus the
\@IEEEauthorhalign that would set the two authors side by side rather than stacked.

[onecolumn] gets a non-spanning form, because \twocolumn[…] GOBBLES its span when the
engine is not in two-column mode and would drop the whole title block. It still
replaces \centerline with a center environment: the hbox defect is not about columns.

Font sizes are deliberately unchanged. This is structural; the title's real size is a
separate fidelity question with its own effect on Σ.

⛔ Both tests had to be rewritten after failing the way they were first written:
- the \par check asserted on rendered TEXT, where stripSVGTags joins lines with a
  space, so two separate lines read as one run. It now compares the y of each
  token's <tspan>.
- the span check asserted only that the words were on the page, and PASSED against
  the unfixed engine — the words are there either way, wrongly placed. It now asserts
  colRegions[0].span exists and is wider than the column measure.

Co-Authored-By: Claude Opus 5 <[email protected]>

* engine: the author blocks follow the class's MODE, as the class does

Found by looking at the page after the spanning title block landed: 2405.05734's
author line came out as

    Daanish Mahajan
          ,
     Chirag Jain
          ,
    Navin Kashyap

where the reference reads "Daanish Mahajan, Chirag Jain, Navin Kashyap".

IEEEtran defines the author blocks TWO WAYS, and the distinction is the whole point.
In conference, peerreviewca and transmag mode they are ROWS of \@IEEEauthorhalign,
each ended by its own \crcr (IEEEtran.cls:4632, :4649). Outside those modes the class
defines plain pass-throughs (:4676-4677):

    \def\IEEEauthorblockN#1{#1}
    \def\IEEEauthorblockA#1{#1}

because a journal paper writes the blocks INLINE with its own punctuation between
them — which is exactly what 2405.05734 does, and breaking there strands every comma
alone on a line.

The halign is still not implemented, so the conference rows are a vertical stack
rather than side-by-side columns. But the mode distinction costs nothing to keep and
is visible on the page both ways: with rows everywhere, a journal author line is shot
through with orphan commas; with pass-throughs everywhere, 2408.02112's conference
author ran together on one line off the right edge of the page.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 28, 2026
⛔ My premise in #496 was WRONG, and the correction is the useful part. I filed that issue
saying \NewDocumentCommand "is not honoured". It is: xparse.go has implemented the whole
family — m, o/O{def}, s, r/R/d/D, t, with \IfNoValueTF and the -NoValue- marker — for a long
time, and the commands work in text mode. Writing a second implementation is what found the
existing one, which is the cheapest way to learn it and not the way I should have looked.

The real defect is narrow. xparse binds a document command to a STOMACH primitive, and says
why where it does: a real \NewDocumentCommand is \protected and must not expand inside an
\edef. But the maths layer is fed a STRING, and expandMacroInMathSource — the pass that
resolves the names go-tex/math cannot know — only ever looked at kind mMacro. So every
\NewDocumentCommand macro reached a formula as a bare NAME and dropped it.

Measured on 999 papers of the arXiv corpus: 99 census triggers worth 1193 equations, the
largest single group in the dropped-equation census (#496).

Served here, and only what can be served EXACTLY:

  {}       no arguments — replace each occurrence with the body.  37 triggers, 293 eq
  m … m    mandatory only — the same parameter text \newcommand   18 triggers, 200 eq
           produces, so the existing string-level substitution
           is reused verbatim through a shim meaning

Refused, each because it is NOT \newcommand's machinery:

  o O d D  an ABSENT optional argument yields -NoValue- (latex.ltx:2121 normalises o to
           D[]{-NoValue-}) and the body tests it with \IfNoValueTF; \newcommand substitutes
           a DEFAULT, so \IfNoValueF{#1}{…} would take the wrong branch. 24 triggers, 324 eq
           — the next thing to do, and it needs the marker, not a default.
  s t      a star or token test yielding \BooleanTrue/\BooleanFalse.  14 triggers, 234 eq
  r R e E v  delimited, embellished, verbatim.                         6 triggers, 142 eq

Refusing is the design: a half-understood specification substitutes with the wrong arity and
mangles the formula silently, where a name left standing is reported and the census counts it.

  ⛔ Two mistakes of mine, both the same shape — an empty value read as an absent one:

  the guard was "m.xpSpecs != nil", and an EMPTY specification gives a NIL slice. So the
  case worth most — 37 of the 99 triggers — was indistinguishable from "not an xparse
  command", and the fix did nothing at all until an explicit xpDoc flag replaced the test.
  Earlier the same day I had mis-tiered those same 37 specifications as "unparsed" for the
  same reason.

  and my refusal test was a BLIND WITNESS. Its three inputs were $\Opt$, $\Str{x}$ and
  $\Dfl{y}$, all of which drop with the guard removed too — reading "o" as one mandatory
  argument then finds nothing to grab and leaves the occurrence standing anyway. The
  ablation broke 0 tests. The inputs now SUPPLY what a wrong reading would consume
  ($\Opt[x]$, $\Str*{x}$, $\Dfl{a}{b}$), so accepting the specification renders something
  wrong instead of failing, and the ablation breaks 1.

  Five ablations: removing the branch breaks 5; restoring the nil-slice test breaks 3;
  lifting the refusal breaks 1; counting the arity as zero breaks 1; never setting xpDoc
  breaks 5.

  A test also pins that an xparse ENVIRONMENT stays stomach-only: \begin/\end are already
  noexp for the maths layer and flattening one would hand it a half-run environment.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 28, 2026
…ace (#498)

Follows the previous commit, which served {} and m…m. This adds the optional kinds — 24
census triggers and 324 equations (#496) — and they could not go through \newcommand's
machinery for two reasons, both of which the tests pin:

  the ORDER. \newcommand can only make the FIRST parameter optional; "m o m" is
  inexpressible for it, and a corpus paper writes "s O{\lambda} m m". parseXparseMathArgs
  grabs one argument per specifier IN ITS PLACE, which parseMathArgsOpt cannot.

  the ABSENCE. The kernel normalises o to D[]{-NoValue-} (latex.ltx:2121), so an absent
  optional argument carries the -NoValue- MARKER and the body tests it with \IfNoValueTF;
  \newcommand substitutes a DEFAULT, and a body written \IfNoValueF{#1}{…} would take the
  wrong branch. O{d} is the other half: absent means d, and the two must not be confused.

\IfNoValueTF and its eight siblings are already expandable — primitives.go's expandableSet
literal lists all nine, with a comment pointing at xparse.go — so flattenMathBody resolves
the branch after substitution and the maths layer never sees the test.

  ⛔ I nearly committed a false accusation about that. xparse.go's comment says "these are
  expandable (registered in expandableSet)"; my grep looked for `expandableSet["IfNoValue`
  and found nothing, because the registration is an entry in a map LITERAL and not an
  assignment. I wrote a comment saying the claim was false and the tests were stomach
  primitives, and added a duplicate registration loop. Both are reverted. A grep that
  matches one of two spellings answers about the spelling, not about the fact — the fourth
  time this session a too-strict pattern read as an absence.

  Five ablations. An absent optional taking "" instead of its default breaks 2; reading the
  optional from the start of the string instead of the current position breaks 1; lifting
  the nine-parameter bound breaks 1; removing the whole branch breaks 9. The fifth —
  letting parseXparseMathArgs's default clause accept an unknown kind — breaks NOTHING,
  because the caller's guard already refused those kinds. It is kept and documented as
  unreachable-by-construction: without it a new specifier kind would leave the argument
  list SHORT and substitute the wrong text silently.

  A test also pins the nine-parameter bound, which is the one clause only the outer guard
  can enforce, so the layering is not two untested halves.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 28, 2026
## math v0.46.0 (go-tex/math#49): \mathchoice and the style level

  control    math v0.45.0   7264 equations dropped, 310 triggers
  treatment  math v0.46.0   7086 equations dropped, 309 triggers
  delta                      -178 equations,          -1 trigger

\mathchoice 183 (7 papers) and \mskip 11 gone, 16 unmasked — 92% conversion. A SELECTOR is a
better candidate than a wrapper of the same count: it discards three quarters of its content,
so only the branch it keeps has to render.

## \mathpalette, which that release makes worth defining

latex.ltx:11179-11184, used VERBATIM in classkernel.go:

    \def\mathpalette#1#2{%
      \mathchoice{#1\displaystyle{#2}}{#1\textstyle{#2}}
                 {#1\scriptstyle{#2}}{#1\scriptscriptstyle{#2}}}

336 equations over 6 papers (#466), and all six use it the same way: to build a CUSTOM SYMBOL
whose parts must be sized by hand — \mathbin{\mathpalette\shuffle@{}} or \mathpalette\@cupdot{}.

⛔ It belongs HERE and not in go-tex/math, and the EXPANSION ORDER is the reason. Those papers'
\shuffle@ and \@cupdot are their own \newcommand*[2] macros, which this engine substitutes into
the maths SOURCE STRING. Expanding \mathpalette inside the maths layer instead would leave the
source reading \mathpalette\shuffle@{} while the layer asked for \shuffle@ — and the retry would
then try to grab TWO arguments after \shuffle@ in a source that has one. Expanded here, the
source becomes \mathchoice{\shuffle@\displaystyle{}}{…} and the same pass expands \shuffle@ with
the arguments actually standing beside it.

Without v0.46.0's \mathchoice this definition would only trade one unknown command for another,
which is why the two go together.

  ⛔ An ablation that dropped the SECOND argument broke nothing at first. Every corpus use
  passes {} for it — \mathpalette\shuffle@{} builds its symbol out of the style alone — so the
  tests could not see it. A test now passes a real #2 and asserts it reaches the body, because
  the definition is latex.ltx's and has to be complete, not complete enough for six papers.

  Three ablations: removing the definition breaks 3; dropping #1, the style, breaks 1; dropping
  #2 breaks 1.

  The tests assert through Diagnostics().MathDropped, plus one that a macro body whose content
  is itself unknown drops under THAT name — the only observation that separates "expanded" from
  "silently swallowed".

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 30, 2026
harvard.sty:28, the branch taken without hyperref:

    \newcommand{\harvardurl}[1]{\textbf{URL:} \textit{#1}}

Its hyperref branch only adds a link around the same words. The kernel already
carried \harvarditem, \harvardand and \harvardyearleft/right — added when a
harvard-style bibliography was found to lose every ENTRY — and this was the one
still missing, so each entry lost the line that says where the work is. The
census counts 25 of them in 2304.12934, one per reference.

WHAT IT CHANGES TODAY: nothing measurable on the corpus, and that is worth
stating rather than implying otherwise. 2304.12934 is the only paper that
writes \harvardurl, and its whole reference list is swallowed before it can be
set — by a separate defect, reduced but not yet understood: \input{tomobank_25}
eats everything after it, while the SAME file inlined sets fine, and changing
one minipage's width from {\linewidth} to {0.33\linewidth} inside it is enough
to stop the swallow. That is the next thing to chase, and this line is one of
the things that will be missing when it is fixed.

The break check is the entry in place: a \harvarditem entry followed by its
\harvardurl keeps both, and against this file at HEAD the run stops with
"Undefined control sequence \harvardurl".

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 3, 2026
…t the name (#530)

cleveref's other interface: \crefformat{type}{template} replaces the whole
rendering, name included, with a three-parameter template — #1 the number, #2 a
prefix and #3 a suffix, which are its hyperlink wrappers and are empty here. It
is applied through cref@<type>@Format and never consults the name
(cleveref.sty:543-549), so a format wins over every naming tier.

One corpus paper in 154 uses it, twice: 2406.01525 writes

	\crefformat{section}{#2\S#1#3}
	\Crefformat{section}{#2\S#1#3}

and its reference prints "§" 73 times where the engine printed "Section" 52
times and "§" none. Measured on that paper directly, after: § 74 against 73,
"Section" 0 against 0.

Three things the oracle decided rather than the source, each of which had been
guessed wrong first:

  - a template read with grabGroup keeps "#1" as TWO tokens, a catParam '#' and
    the digit, where a \def body folds them into one. The first substitution
    looked only for the folded form and printed "#2§#1#3" on the page.
  - a one-sided \crefformat cross-fills the other case by shifting the FIRST
    LETTER only: {fig.~#2#1#3} makes \Cref print "Fig. 1", not "FIG. 1" from a
    whole-word \MakeUppercase and not the default "Figure 1". cleveref's
    \@crefformat (cleveref.sty:1886-1910) wraps the copy in \MakeUppercase with
    an UNBRACED argument, which is the same first-letter trick \@crefname uses.
  - a subsection with no format of its own follows the SECTION's — the same
    fallback that makes cleveref's default NAME for a subsection "section".
    Asked both ways: \crefname{subsection}{subsec.} IS honoured, so the type
    really is `subsection` and this is a fallback, not an alias.

Several keys still go through the naming path: that is \crefmultiformat in
cleveref, which no corpus paper uses.

Measured by channel over the 16 papers that use \cref:

	Σ|deviation|   581 -> 528    3 rows toward the reference, 1 away

The one row away is "Definition" 32 -> 31 against a reference 41, a drift of one
from reflow.

⛔ AND IT DOES NOT RECOVER THE PAGE. #527 and #528 both said this was "the whole
of 2406.01525's remaining deficit"; that prediction is measured false. The paper
stays at 37 pages against a reference 35 — Σ|deviation| 339 and exact pagination
37 are unchanged corpus-wide. Its text ratio falls 98.4% -> 97.5% because "§" is
three characters and the corpus text census counts words of five or more, so
replacing 52 wrong "Section"s with the right symbol reads there as a loss. What
keeps that paper two pages long is something else, still unidentified.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
… knew one (#536)

\begin{X} and \end{X} EXPAND to \X and \endX. So an \edef over a macro that
contains an environment leaves the ONE-TOKEN form — measured on the macro itself:

    \def\zzs{Author\begin{tikzpicture}\end{tikzpicture}}
    \edef\zzx{\zzs}   ->   macro:->Author\tikzpicture \endtikzpicture

Executing that runs \tikzpicture, which reaches gobbleEnvBody looking for a \end
followed by a braced name, finds none, and reads to the end of the document.

\MakeUppercase is exactly that shape — \edef\@makecase@a{#1} then
\uppercase\expandafter{…} (classkernel.go:567) — so \MakeUppercase of a macro
holding an environment swallowed everything after it and left a group open
(#535). Through lmcs's \maketitle it is also what truncated 2603.18955 to ONE
page out of 139KB of source (#517).

Measured over the 71 corpus papers that render truncated or leak groups,
control c96d0a5:

    paper        pages      glyph paths
    2603.18955   1 -> 49       +84102
    2603.13142   1 ->  2        +4698
    total        +49 pages     +88800

No other paper of the 71 changes.

⛔ Three hypotheses were refuted before this one, and the third is what pointed
here:

  the environment NAME is case-shifted so the gobbler cannot match it — no,
  \MakeLowercase fails identically and the name is already lowercase;

  \protected@edef instead of \edef — no, it only protects what carries \protect,
  and \begin does not;

  the gobbler runs during the \edef, so guard it on expandDepth — NO. The guard
  measured as having no effect, and instrumenting the gobbler showed why: it runs
  at expandDepth=0, during the EXECUTION of \uppercase\expandafter{…}, not during
  the expansion. That observation is what led to reading what the \edef had
  actually left behind.

⛔ And a correction to #535, where I wrote that the lmcs chain did not close
because \@setauthors on its own does not reproduce it. The observation was right
and the conclusion was wrong: the full \maketitle path does reach the one-token
form.

2603.13142 is still short at 2 pages from 46KB, so it has a second cause as well.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
…title := \@title (#541)

amsart switches \uppercasenonmath to \altucnm as soon as \MakeTextUppercase is
defined (amsart.cls:429), and \altucnm hands it an ASSIGNMENT rather than text:

	\def\altucnm#1{\MakeTextUppercase{\toks@{#1}}\edef#1{\the\toks@}}

\the inside an \edef contributes its tokens unexpanded, so \MakeTextUppercase has
to expand \@title BEFORE \uppercase hands the list back to the mouth. Defined as
a bare indirection to \MakeUppercase it did not: a document's own
\let\MakeUppercase\relax (15 of 999 corpus papers, 7 of them amsart) left the
\toks@ assignment undone, \toks@ kept the token \@title, and \edef\@title{\the\toks@}
closed a self-reference the engine then spun 400 times into the runaway guard.

Measured, pages before -> after, with the loop gone in both:

	2511.23047     1 -> 10
	2604.01571     1 -> 48

Two refuted forms are recorded in the test file, because each one shows what the
witness has to be:

  - \let\MakeTextUppercase\MakeUppercase binds the undefined — nothing defines
    \MakeUppercase when the ams substrate runs; only amsart.cls:431 does, later.
  - \def\MakeTextUppercase#1{\uppercase{#1}} performs the assignment but does not
    expand a control sequence, so \toks@ still receives \@title. Measured: no change,
    which is a refuted hypothesis and not a near miss.

No regression on the disjoint population that calls \MakeTextUppercase itself
(22 papers): 18 identical, 0 changed, 4 unreadable on both sides.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
…pands it one step (#544)

lineno.sty installs its hooks with (lineno.sty:3029-3035)

	\def\@tempa#1#2{\expandafter\def\expandafter#2\expandafter{\expandafter
	  \ifLineNumbers\expandafter#1\expandafter\fi#2}}
	\@tempa\@ln@changevadjust\vspace

whose \expandafter chain expands #2 ONE step while the new body is being formed, so
the body holds the command's old MEANING rather than its name. A primitive cannot be
expanded: the body kept the token \vspace and the wrapper called itself, 400 turns
into the runaway guard.

LaTeX's \vspace is a macro — \def\vspace{\@ifstar\@Vspacer\@Vspace} — so one step
gives \@ifstar and the idiom works. Here it was a Go primitive, and \meaning\vspace
said so. A \let-captured internal name with a macro in front restores the shape
without touching the primitive, which keeps reading its own star.

Measured, pages before -> after, with the runaway gone in all three (class aa with
lineno, all three stopping at ONE page before):

	2607.18707     1 -> 21
	2607.28723     1 -> 15
	2607.29488     1 -> 15

\pagebreak and \nopagebreak, which lineno wraps identically, were already macros
here. That is why only \vspace looped, and why the first test asserts the SHAPE of
the definition rather than anything about vertical space. The second test is there
because a macro that swallowed its argument would pass the first while silently
losing the glue: a 600pt skip has to push the next paragraph onto a second page.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
…ays a token (1 page → 8) (#545)

* maths: flattening resolves notation, so a macro whose body is an ASSIGNMENT stays a token

flattenMathBody expands the formula's own source so go-tex/math sees notation rather
than macro names. A macro whose replacement text IS an assignment must be left for the
stomach: expanding it hands back the assignment's tokens, and the engine then expands
the very name the assignment was about to redefine.

The self-redefining idiom makes that non-terminating. quantumarticle.cls:1108-1109 is
the textbook form — nothing the first time, a separator after that:

	\def\@@@comma{\def\@@@comma{,}}
	\def\@@commaspacebefore#1{\@@@comma{}#1}

Reached through \ensuremath in an author block, 2607.22466 spun \@@@comma 400 times and
pushed {,} to 200 001 frames deep. Measured:

	pages 1 -> 8, groups still open 4 -> 0, runaway gone

The Go stack named the context rather than a guess: doMath -> makeMath ->
renderMathResolvingMacros -> expandMacroInMathSource -> flattenMathBody -> expandList.

The guard is in the expansion path, NOT in flattenMathBody's noexp pre-pass, because
the macro is not in the source being flattened — it arrives mid-expansion through
etoolbox's \forlistloop, so marking names up front cannot reach it. That version was
written first and measured: it changed nothing at all.

Two tests, and only the first is a witness for this change: without the fix it reports
the runaway. The second asserts the macro still TAKES EFFECT, because a guard that
dropped the token instead of deferring it would pass the first while silently losing
every separator the idiom exists to produce.

Co-Authored-By: Claude Opus 5 <[email protected]>

* maths: narrow the guard to SELF-redefinition, which the equation census demanded

The first version refused to expand every macro whose body began with an assignment.
The page channel liked it — 4 papers up, none down over the 154-paper list — and the
equation census showed what pages cannot see:

	Σ dropped equations 138 -> 158 (+20)
	\def     disappeared as a trigger   (-2)
	\unskip  disappeared                (-1)
	\@forloop APPEARED                 (+23)

A loop macro assigns to OTHER names and must keep expanding; only a macro that
redefines ITSELF cannot be flattened. With the guard narrowed to that:

	Σ dropped equations 138 -> 138 (+0), no trigger gone, appeared, risen or fallen
	2607.22466 still 1 page -> 8, groups 4 -> 0, runaway gone

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
…hat the engine cannot exec or write (#554)

* thmtools: \declaretheorem, read from thm-kv.sty rather than guessed

\declaretheorem is thmtools' key-value front end onto \newtheorem, and the engine
skipped it: 219 corpus papers use it, 1735 times, and the environments it was to
declare arrived undefined. The body of an undefined environment still reaches the
page, so what was lost is the heading and its number.

Three details come from thm-kv.sty and are not guessable:

  - {<names>} is a COMMA LIST (:337, \@for\thmt@tmp:=#2\do), so
    \declaretheorem{theorem,lemma} declares both. Declaring one would leave the other
    undefined, which loses only a heading — invisible in a page count.
  - the two counter keys map to the two DIFFERENT optional arguments of \newtheorem
    (:362): sibling/numberlike/sharenumber is the SHARED counter, before the heading,
    and parent/numberwithin/within is the WITHIN counter, after it. Swapping them gives
    numbering that looks plausible and is wrong.
  - the default heading uppercases the FIRST LETTER only: :354 is
    \thmt@setthmname{\thmt@modifycase #1} with no braces, and \thmt@modifycase defaults
    to \MakeUppercase (:42), which takes one token as an undelimited argument.

style, qed and the hook keys are formatting the engine has no model for; they are read
and dropped rather than refused, so a declaration carrying them still numbers.

Measured on two DISJOINT populations (219 subjects, 154 control, overlap zero):

	subjects, glyph paths   132 up, 13 down, 74 identical, Σ +262585
	subjects, pages          85 up, 0 down
	control, pages           0 up, 0 down, 154 identical
	control, equations       Σ 138 -> 138, no trigger gone, appeared, risen or fallen

The 13 glyph decreases are reflow, not loss, and the evidence is that none of them
loses a PAGE while several gain one: content cannot be vanishing from a document that
grows. All are at or below 0.41% (median 0.17%), and one is a single glyph — the
signature of hyphenation and line breaks moving when a heading is inserted.

Co-Authored-By: Claude Opus 5 <[email protected]>

* security: assert in a test that a document can neither run a process nor write a file

This package compiles untrusted input — a .tex is a program and this is its interpreter.
An audit of what such a program can reach (engine#553) found two properties already true
and worth holding on purpose rather than by accident: nothing in the package runs a
process, and nothing writes a file.

Neither is expressible through an API, so the test reads the package's own source. A
plausible commit that reaches for os/exec to shell out to a rasteriser, or os.WriteFile
to cache something, now fails here and has to argue the case in the diff. cmd/ is out of
scope: the CLI writes the PDF it was asked for.

Both halves of the guard are asserted, because a scanner that read nothing would pass:
the test fails if it saw fewer than 50 source files, and it fails if its own matcher
cannot find a planted os.Create. Verified in both directions — planting
os.Create in io.go makes it report "io.go:295 uses os.Create", and removing it passes.

What the audit found that this test does NOT cover, and that needs a decision rather
than a test, is in #553: \input and \openin reach any readable path with no way for a
host to confine them, and an expansion bomb of twelve lines reaches 6.3 GB because the
step ceiling bounds loops and not size.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 7, 2026
…tonic (#582)

* toc: a contents list shaped like article.cls's, not like \dotfill

Measured against tectonic on an 11pt article with two sections, two
subsections and one subsubsection, four things were wrong at once:

  - every level carried a dot leader. article.cls:528-543 sets \l@section
    as "#1\nobreak\hfil\nobreak\hb@xt@\@pnumwidth{\hss #2}" — no leader at
    all — and only reaches for \@dottedtocline from \l@subsection down.
  - the dots were twice too dense: 4.82pt apart against the reference's
    8.49. \dotfill tiles plain TeX's .44em box; \@dottedtocline tiles
    \hbox{$\mkern\@dotsep mu.\mkern\@dotsep mu$}, the dot plus half an em.
  - the indent ladder was a flat 18pt per level, not article's
    {1.5em}{2.3em} / {3.8em}{3.2em} / {7em}{4.1em} / {10em}{5em}, and the
    number was set inline rather than in a box of the level's width, so
    titles did not line up.
  - section entries were missing \l@section's \addvspace{1.0em}, which is
    the blank line a reader uses to find the sections in a contents list.

Each of the four is now within a fraction of a point of tectonic:
number x 142.24 against 142.16, title x 167.45 against 167.25, deeper
title 202.52 against 202.15, page number right-flushed at the margin in
both, section gap 24.51pt against 24.46. The residual dot pitch (8.16
against 8.49) is the width of STIX's period, not arithmetic.

The page number needs \hfill where LaTeX writes \hfil: LaTeX also sets
\parfillskip -\@pnumwidth so its \hfil is the only stretch on the line.
Ours is not, and an \hfil there shared the space with \parfillskip and
stranded the number 134pt short of the margin.

Counted in tectonic: a document of 30 one-page sections is 32 pages, two
of them contents. We produced 31 before this and produce 32 now. The test
that covered it said "contents on one page" for those 30 sections — an
expectation written by hand, which had pinned our own too-tight list; it
is now three rows whose page counts were all counted in tectonic.

24-sommaire's glyph floor drops from 301 to 173. The 108 glyphs it stops
drawing are dots: with '.' and spaces removed, the text of its PDF is
byte-identical before and after.

Co-Authored-By: Claude Opus 5 <[email protected]>

* toc: a list of figures is \@dottedtocline too, whatever its level

\caption records a figure or table entry at LEVEL 1 (latex.go:779), the
same level a \section entry carries. The ladder added in the previous
commit read that level alone, so \listoffigures and \listoftables came
out in the \l@section shape: bold, flush left, no dot leader.

article.cls does not key on the level. \l@figure is
\@dottedtocline{1}{1.5em}{2.3em} and \l@table is \let to it (lines 554
and 562) — the \l@subsection shape. Only a CONTENTS entry at level 1 is
\l@section's.

Measured against tectonic on an 11pt article with two captioned figures:
entry number at x 142.24 against 142.16, title at 167.45 against 167.25,
dotted at 8.16pt against 8.49, page number right-flushed at the margin in
both.

Co-Authored-By: Claude Opus 5 <[email protected]>

* toc: read the entry's shape from the loaded class, not from one table

The ladder added in 5f64edb was article.cls's, applied to every class. It
is not every class's. article's \l@section is hand-written — bold, \hfil,
no leader — while book's and report's \l@section, at the very same level
1, is \@dottedtocline{1}{1.5em}{2.3em} (book.cls:635, report.cls:629),
and their \l@subsection indents 3.8em where article's indents 1.5em.

Measured: that cost three pages on 2402.04711, a \documentclass{book}
thesis in the corpus, and the whole of the +3 the A/B reported
(Sigma|page deviation| 278 -> 281 against origin/main 5c7c16a).

So stop restating any class's numbers. The level names the sectioning
command that recorded the entry — \@startsection numbers them identically
in article, report and book — and the class's own \l@<name> decides the
rest: a \@dottedtocline means a leader, and its second and third arguments
ARE the indent and the number-box width, read out of the macro body. A
hand-written \l@… means the bold leaderless shape. article's table stays
only as the fallback for the engine's own LaTeX emulation, which has no
class file to read.

\l@figure and \l@table are reached by name for the same reason: every
class writes them as \@dottedtocline even though \caption records them at
level 1.

Four mutations caught: naming a \l@ macro that does not exist, ignoring
the lengths read from it, accepting a unit other than em, and dropping the
\addvspace before a top-level entry.

Co-Authored-By: Claude Opus 5 <[email protected]>

* gotex-linediff: read two PDFs line by line, in Go, with no outside tool

The corpus instruments answer a different question. gotex-abdiff counts
pages and gotex-refdiff scores a paper; neither can say "our contents
entry starts 1.58pt to the right of the reference's and its dots are
twice as dense", which is the sentence the three contents-list defects
in this branch were actually fixed from. That sentence was reached with a
throwaway Python script over `mutool draw -F stext` — written three
times, never kept, and impossible to put in CI.

gotex-linediff is that measurement as a program: one page of two PDFs
side by side, per line the start, the end, the baseline, the face, the
size, and — when the line holds a leader — how many tiles it draws and
how far apart. The leader is the case that justifies it: "Title. . . . 7"
reads the same whether the tiles are 4.8pt apart or 8.5, so no comparison
of the TEXT can see the difference the drawn positions show plainly.

It reads the PDFs with github.com/go-pdfkit/reader, which the repository
already depends on: no qpdf, no poppler, no MuPDF, nothing but Go, so it
runs wherever the engine's own tests run. It supersedes tools/pdfprobe's
pdfitems.py, which read `qpdf --qdf` output with regular expressions.

Text comes through each font's ToUnicode CMap and widths through /Widths
or /W. A font that carries neither yields runs with no text and a line
whose end is reported as "?" — never a made-up width. Word breaks are put
back from the gaps between show operators, since neither engine draws a
space glyph.

Verified against the reference on the branch's own witness: it reproduces
every number the Python script had produced — pitch 8.49 against 8.16,
first-glyph x 142.16 against 142.24, and no leader on a section line on
either side.

Co-Authored-By: Claude Opus 5 <[email protected]>

* gotex-linediff: cover the operators neither engine emits, and fix q/Q

The reference side of every comparison is a PDF this tool did not
produce, so the paths go-tex and tectonic never take are exactly the ones
that must be right. A one-page PDF assembled byte by byte in the test —
with a SIMPLE font (/FirstChar + /Widths, one byte per glyph) and the
operators neither engine writes — covers them, and it found a real one:

q and Q save the whole graphics state, and the character, word and
horizontal spacing are part of it. Saving only the matrix leaked a Tc set
inside a q out past its Q and widened every run after it.

Four mutations caught: saving only the matrix at q, reading TJ's numbers
as forward motion (which mirrors every kern on the line), reading a
composite font one byte at a time (which halves every position), and
dropping the word breaks rebuilt from the gaps between show operators.

Coverage 81.0%, above the 80% floor CI enforces on the whole module; the
report still reproduces the reference numbers it was verified against.

Co-Authored-By: Claude Opus 5 <[email protected]>

* build: stop tracking the built binaries, and guard it in code

Two Mach-O executables were in the tree. `gotex`, 5.8MB, has been there
since the CLI landed; `gotex-linediff`, 3.5MB, I added myself four
commits ago — `go build ./cmd/gotex-linediff` with no -o drops the binary
at the repository ROOT, named after the directory, and `git add -A` swept
it up. Every clone paid for both, on every platform.

The .gitignore said `/gotex` already and did nothing, because a rule
cannot untrack a file that is already tracked, and because a rule that
names one binary stops working the moment a command is renamed or a new
one is added. So the control is a test, not a convention:

  TestNoBinaryIsTracked reads the first bytes of everything `git
  ls-files` names and fails on a Mach-O, ELF, PE or wasm header. It
  refuses to pass on an empty listing, so it cannot silently test
  nothing; outside a checkout it skips and says why.

  TestEveryCommandIsIgnoredAtTheRoot derives the list from cmd/ itself,
  so a command added without its .gitignore line fails the build instead
  of waiting for someone's `git add -A`.

Both break-checked: staging the binary again fails the first by name and
size, commenting out one ignore line fails the second.

The history still carries both blobs; this only stops them being checked
out. Purging them is a separate operation on a separate day.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant