Skip to content

tex: the primitives and rules real package code is built on - #2

Merged
tannevaled merged 1 commit into
mainfrom
fix/pgfkeys-parse
Aug 16, 2026
Merged

tannevaled merged 1 commit into
mainfrom
fix/pgfkeys-parse

Conversation

@tannevaled

@tannevaled tannevaled commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Continuation of the pgf/TikZ work: the pgfkeys blocker is lifted, the whole pgf stack loads from its own sources, and a figure draws.

Seven divergences from TeX, each measured before the fix

Each behavior was isolated in a few lines and then compared against a real TeX (tectonic); the expected values in the tests are that engine's, not a guess.

Rule What was breaking
\ifx compares meanings, and a character token has one (category + character) — so \ifx\next/ is true if \next was \let to a slash pgfkeys split every key path wrong, then executed the value as if it were a command
The alphabetic constant `a/`\a was missing \catcode@=11` was changing the category of character 0
Reading a category (\the\catcode@`) files that restore a category would restore emptiness → @ became an escape character
\afterassignment a scanner that restarts after \let never resumed
Dimension → integer coercion (\number\pgf@x) every computed coordinate came out wrong
\newbox handle = register number the contents of a package's boxes disappeared (everything went into box 0)
\global forgets pending saves {…\global\pgf@x=\pgf@x} — the idiom that carries a value out of a group — returned nothing

In addition: a file name is expanded before it is resolved (a package names the file to load through a macro), and the engine's named colors are published in the form a color reader expects, so that a drawing package can ask for the model and the values instead of declaring it unsupported.

Result

  • pgfrcs, pgfkeys, pgfsys, pgfmath, pgfcore and pgf load in full under \documentclass{article}.
  • Milestone (a) reached: \pgfpathmoveto{\pgfpoint{0pt}{0pt}}\pgfpathlineto{\pgfpoint{50pt}{30pt}}\pgfusepath{stroke} reaches the page as <path d="M 0.0 0.0 L 50.0 30.0" fill="none"/>, within the picture's scope, at the right coordinates.
  • Remaining for TikZ: the startup of \begin{tikzpicture} (\draw is installed by that startup) — next step identified.

The actual loading stays opt-in via GOTEX_PGF; by default nothing changes for an ordinary document.

Verification

  • 746 tests pass, 0 skips, 0 failures; go vet and gofmt clean.
  • Conformance ratchet and document corpus unchanged.
  • scripts/fidelity.sh --check (CI gate, gotex vs real LaTeX): OK.
  • New code at 100% coverage; the tests document the real-TeX value in a comment.

Running the real pgf/TikZ sources turned up seven places where the engine
answered differently from TeX. Each was isolated to a few lines, checked
against a real TeX (tectonic) before being implemented, and is a rule that
package code leans on constantly — the failures they caused looked like
anything but their cause.

\ifx compares meanings, and a character token has one: its category and its
character, the same meaning a control sequence \let to that character has.
So \ifx\next/ is true when \next was \let to a slash. Every one-token
lookahead tests what it peeked at this way; without it pgfkeys mis-split
every key path it was given and then ran the key's value as if it were a
command.

TeX's alphabetic constant — `<character>, or `<single-character control
sequence> — was missing entirely, so \catcode`\@=11 quietly set the category
of character 0 and left @ alone. Reading a category was missing too, so the
files that put a category back (\edef\saved{\the\catcode`\@} … \catcode`\@=
\saved) restored garbage.

\afterassignment holds one token until the next assignment has been carried
out, which is how a scanner resumes itself after \let has swallowed a token.

An internal dimension coerces to an integer, its value in scaled points, so
\number\pgf@x and \ifnum\wd0>0 read it. A box handle from \newbox is a
register *number* (TeX allocates it with \chardef), so \box\mybox reaches
the right register instead of box 0, where a package's boxed material used
to vanish.

A global assignment must outlive every open group, so a local assignment
made earlier in one of them is no longer restored over it at the closing
brace. The idiom that carries a computed value out of a group —
{…\global\pgf@x=\pgf@x} — depended on it entirely.

Alongside those: a file name is expanded before it is looked up (a package
names the file to load through a macro), and the engine's named colours are
published in the form a colour-reading package expects, so a drawing package
can ask which model and values a colour has rather than reporting the model
as unsupported.

With these, the whole pgf stack — pgfrcs, pgfkeys, pgfsys, pgfmath, pgfcore
and pgf itself — loads from its own sources under \documentclass{article},
and a picture draws: \pgfpathmoveto…\pgfusepath{stroke} now reaches the page
as a real stroked path at the right coordinates.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@tannevaled
tannevaled merged commit 3a28ac1 into main Aug 16, 2026
18 checks passed
tannevaled added a commit that referenced this pull request Aug 27, 2026
\usepackage{beamerthemesplit} lost the body of the talk. So did the fifteen other
beamer themes built the same way. The theme was not at fault: the file is 24
lines, and the loss came from \ProcessOptionsBeamer, from the \@for inside it,
and from one control sequence the engine never defined.

\@for over an UNDEFINED control sequence does not iterate over nothing — it
swallows what follows. LaTeX's own \ProcessOptions guards the loop,

	\ifx\@classoptionslist\relax\else
	  \@for\CurrentOption:=\@classoptionslist\do{…}

but beamer's \ProcessOptionsBeamer guards on \@currext instead and runs the loop
unguarded, as does \beamer@filterclassoptions. Both therefore rely on
\documentclass having set the list — and the engine never set it.

ltclass.dtx is followed on all four points: \@classoptionslist and
\@raw@classoptionslist both start at \relax (§547), \documentclass fills them on
the FIRST class load,

	\ifx\@classoptionslist\relax
	  \protected@xdef\@classoptionslist{\zap@space#2 \@empty}%
	  \gdef\@raw@classoptionslist{#2}%

and the \ifx guard means a class that loads another class does not overwrite the
document's own list. A test pins that last part, which is easy to miss.

Measured over 200 real beamer talks: 0 lost, one MORE renders, 12 outputs change
— a narrow change, as it should be — and the page-count error against tectonic on
the 14 talks with a reference falls 11 -> 6, with none moving away and 9 of the
14 landing exactly on it. Over 200 real arXiv papers: 0 lost, two more render, 29
outputs change.

Not fixed here, and pre-existing: a frame TITLE does not render, with or without
a theme, before or after this change.
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 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 Aug 31, 2026
\newcommand{\cmd}[n][default] makes the FIRST of the n parameters optional: \cmd is
\@Protected@testopt, which supplies {default} when no [ follows (latex.ltx:1187-1199,
\@xargdef), and the remaining n-1 are grabbed as usual. The token path already does
this (engine.go's optArg/optDefault); the maths source path read all n as MANDATORY.

That is worse than not expanding at all. With the optional argument written out the
macro still "matched", by taking the brackets themselves as arguments:

	\qbin [p]{N}{k}  ->  \genfrac []{0pt}{}{p}{]}_{[}{N}{k}
	\qbin {N}{k}+1   ->  \genfrac []{0pt}{}{k}{+}_{N}1

so the formula came out silently wrong, the + of an expression becoming an argument.
Without it, nothing matched and the formula was dropped — which is how a paper's own
\newcommand{\qbinom}[3][q]{\genfrac[]{0pt}{}{#2}{#3}_{#1}} lost 12 equations.

Measured over 200 arXiv papers and 200 beamer talks: 5 documents change for +1234
glyphs. One repaginates, 362 -> 363 against tectonic's 333 — a document already 29
pages long of it — and the page error against the 157 renders moves 669 -> 670.
beamer does not move by one glyph.
tannevaled added a commit that referenced this pull request Aug 31, 2026
Three families reached the maths layer as unknown commands, and an unknown command
costs the WHOLE formula:

  - \setlength{\len}{dim} is \def\setlength#1#2{#1 #2\relax} (latex.ltx:7347), an
    assignment with two arguments — \addtolength beside it (:7348);
  - \hfil and its kin are \hskip with a fixed glue:
    primitive("hfil",hskip,fil_code) with fil_glue = 0pt plus 1fil (tex.web:20547,
    §3318), so they take no argument at all. The maths layer cannot stretch, so what
    they contribute here is nothing;
  - \leftskip and the other glue PARAMETERS are assignments that read a <glue>
    (tex.web §224), with TeX's optional equals before it, which scanMathGlue now
    accepts.

Measured over 200 arXiv papers and 200 beamer talks: 11 documents change and 3
repaginate for +1290 glyphs; the page error against the 157 tectonic renders falls
656 -> 655. beamer gains 17 glyphs on one talk.
tannevaled added a commit that referenced this pull request Sep 3, 2026
…#208)

\def\tikzstyle#1=[#2]{} matches its delimiters as CHARACTERS, and real documents
write

	\tikzstyle{thmbox} = [
	  draw=black, fill=white
	]

with spaces around the =. The scan then hunts a literal "=[" that never comes and
takes the rest of the file with it: measured on the 157-paper corpus, 2311.08855
went from 18 pages and 38829 glyphs to ONE page and NOTHING. The stub landed in
#128 without a corpus measurement; this is that measurement, and the fix.

\@ifnextchar skips spaces, so the = and the bracket group are now read however
they are spaced, and a \tikzstyle with neither is left alone. The paper is back
to 17 pages and 38765 glyphs.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
tannevaled added a commit that referenced this pull request Sep 4, 2026
…#222)

amsthm's starred form was unhandled. The star stopped readBraceName dead: no name
was read, the environment stayed undefined, and the star and the heading were left
in the input to be TYPESET. One paper opened on a spurious page of its own carrying

	*theoremTheorem *namedconjectureConjecture

and then set the three bodies of its theorem environment as plain paragraphs.

The star is now read, and a starred \newtheorem defines the same environment with
no counter, no \the<env>, and a heading with no number: \@beginthmnonum, a sibling
of \@BeginTheorem without its "\ #2", so the head reads "Theorem." rather than
"Theorem ." — the optional note ("Theorem (Smith).") goes through the same
continuation as a numbered one.

39 uses across 17 of the 200 arXiv papers. Measured over the 157 with a tectonic
reference: page error 574 → 535, exact 23 → 24, within 1 page 61 → 66, within 2
pages 96 → 103; the signed bias crosses from +36 to −19.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 6, 2026
\@setfontsize is the hook every size command goes through — latex.ltx:10003-10007
reads its three arguments as \fontsize{#2}{#3}\selectfont — and ours threw #2, the
size, away. Every class size option file redefines all ten commands through it:

	\DeclareRobustCommand\large{\@setfontsize\large\@xiipt{14}}   size11.clo:82

so all ten redefinitions landed as no-ops. A document that loaded article.cls came
out with ONE font size in the whole PDF: a probe of \tiny through \Huge at [10pt]
wrote `/F0 10 Tf` and nothing else, \Huge 57% too narrow and \tiny 51% too wide.

\gotex@fontsizeat now puts the font at the size the table states, read against the
size the same table states for \normalsize (\gotex@classnormalsize), so a caller's
Options.Size still picks the body size and the table supplies the ratios. That
matters because the table is NOT a scale factor: size10.clo:82-86 and
size11.clo:82-86 are identical, so \large…\Huge are the same points in a 10pt and
an 11pt class, and size12.clo caps \Huge at \@xxvpt — the same 24.88pt as \huge.
Scaling one ladder by the class base instead would have made every 11pt heading
8-11% too large and \Huge in a 12pt class 21% too large.

The kernel's own number macros were copied rounded (\@xxpt as 20 against 20.74,
\@xxvpt as 25 against 24.88); they are now latex.ltx:7852-7863 verbatim, which is
what the ladder reads.

Measured against tectonic on the same probe, mean |error| over the ten sizes at
[10pt]/[11pt]/[12pt]: 28.8% → 5.5%. What is left is optical design sizes — cmr5
is not cmr10 shrunk — which is a different subject.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 6, 2026
\@setfontsize is the hook every size command goes through — latex.ltx:10003-10007
reads its three arguments as \fontsize{#2}{#3}\selectfont — and ours threw #2, the
size, away. Every class size option file redefines all ten commands through it:

	\DeclareRobustCommand\large{\@setfontsize\large\@xiipt{14}}   size11.clo:82

so all ten redefinitions landed as no-ops. A document that loaded article.cls came
out with ONE font size in the whole PDF: a probe of \tiny through \Huge at [10pt]
wrote `/F0 10 Tf` and nothing else, \Huge 57% too narrow and \tiny 51% too wide.

\gotex@fontsizeat now puts the font at the size the table states, read against the
size the same table states for \normalsize (\gotex@classnormalsize), so a caller's
Options.Size still picks the body size and the table supplies the ratios. That
matters because the table is NOT a scale factor: size10.clo:82-86 and
size11.clo:82-86 are identical, so \large…\Huge are the same points in a 10pt and
an 11pt class, and size12.clo caps \Huge at \@xxvpt — the same 24.88pt as \huge.
Scaling one ladder by the class base instead would have made every 11pt heading
8-11% too large and \Huge in a 12pt class 21% too large.

The kernel's own number macros were copied rounded (\@xxpt as 20 against 20.74,
\@xxvpt as 25 against 24.88); they are now latex.ltx:7852-7863 verbatim, which is
what the ladder reads.

Measured against tectonic on the same probe, mean |error| over the ten sizes at
[10pt]/[11pt]/[12pt]: 28.8% → 5.5%. What is left is optical design sizes — cmr5
is not cmr10 shrunk — which is a different subject.

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

* xcolor: \definecolor takes two optional arguments, and both were typeset

    \def\definecolor{\@testopt{\XC@definecolor}{}}
    \def\XC@definecolor[#1]#2{\@testopt{\XC@definec@lor[#1]{#2}}\colornameprefix}
    \def\XC@definec@lor[#1]#2[#3]#4#5{…}          xcolor.sty:473-476

so the signature is \definecolor[type]{name}[prefix]{model}{spec}. We read only the
three mandatory arguments, so a call carrying either optional one was left whole in
the input and every token of it reached the page.

acmart declares its palette that way (acmart.cls:561-568), so eight lines of

    [named]ACMBluecmyk1,0.1,0,0.1 [named]ACMYellowcmyk0,0.16,1,0 …

came out on page 1 of every acmart paper in the corpus.

The type and the prefix decide which colour STACK a name lands on in xcolor; this
engine keeps one flat table, so they are consumed and dropped. The colour itself is
defined either way, which is what a renderer needs.

Measured over the 157-paper corpus: Sigma 344 -> 343 (-1), glyphs -2357.

Every one of the nine papers the harness flags loses about 260 glyphs, and on each
one those glyphs ARE the palette: on 2301.08336 the words that disappear are exactly
[named]ACMBlue…, [named]ACMYellow…, [named]ACMOrange…, [named]ACMRed…,
[named]ACMLightBlue…, [named]ACMGreen…, [named]ACMPurple…, [named]ACMDarkBlue… —
319 characters of a class's colour declarations that were never text.

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

* gofmt: a stray blank line left by #309

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 7, 2026
…317)

natbib's key=value parser is two DELIMITED macros (natbib.sty:344-345):

    \def\NAT@find@eq#1=#2\@nil{\def\@tempa{#1}\def\@tempc{#2}}
    \def\NAT@rem@eq#1={\def\@tempc{#1}}

Neither takes a braced argument, so an undefined \NAT@find@eq consumes NOTHING and
the key list it was handed is typeset instead. natbib itself is emulated here rather
than loaded, but a class may bring its own \setcitestyle whose body still calls
these: acmart.cls:273 renews \setcitestyle and acmart.cls:347 calls it with

    \setcitestyle{numbers,sortcompress,open={[},close={]},citesep={,},notesep={, }}

so an acmart paper opened with "numbers=sortcompress=open=[=close=]=citesep=,=" on
the page, one "<key>=" per iteration. 20 of the 157 corpus papers use \setcitestyle.

On a two-column paper it costs a whole page: the junk lands in the main vertical
list BEFORE \maketitle's \twocolumn[...], and a \twocolumn starts a new column
region, so the junk takes a page of its own and pushes the title and the first
column of text onto page 2.

Measured over the 157-paper corpus: Sigma 344 -> 344 (+0), glyphs -565.

One paper is flagged, 2407.13726 at -117 glyphs, and those glyphs are the junk: it
sets two of these lists ("numbers=sortcompress=", "authoryear=open="), and after the
fix its real words go UP, not down — "This" 20 -> 21, "Code" 13 -> 14, "purposes"
0 -> 1.

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

xstring's \IfSubStr[<n>]{<string>}{<substring>}{<true>}{<false>} has four mandatory
arguments after an optional occurrence number (xstring.tex:444,
\xs_newmacro*3\IfSubStr{1}{2}{0}). Undefined it consumes nothing, and acmart opens
its \author with

    \IfSubStr{\detokenize{#2}}{,}{\ClassWarning{…}}{}          acmart.cls:1314

so \author{A Name} in the PREAMBLE printed "A Name," as body text — the detokenized
name and the comma it was being tested for. Over the corpus that is 906 glyphs on at
least five papers: on 2407.15192 the words that disappear are Aniruddha, Datta,
Joshua, Khoa, Kricheli, Ozgur, Paulo — its author list, set in the running text.

On a two-column paper it costs a page. The text lands in the main vertical list ahead
of \maketitle's \twocolumn[...], which starts a new column region, so it takes a page
of its own: on a controlled acmart sigconf document page 1 held two lines while the
complete title band sat at the top of page 2. Same shape as #316 and #318.

The test is PERFORMED, not guessed. \in@{<search>}{<in>} is the kernel's own
substring test and sets \ifin@. A stub answering "false" always would drop whichever
branch it did not pick, and a branch is content — the distinction #314 drew between a
configuration command, whose arguments are never text, and a test, whose arguments
are.

Measured over the 157-paper corpus: Sigma 344 -> 345 (+1), glyphs -906.

The +1 is one paper (2304.11274, 10 -> 9 against a reference of 12). It is the same
trade #296 was merged on: a reader seeing an author list in the middle of the running
text is worse than a page of discrepancy, and every glyph removed here is text that
was never the author's to see.

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

* engine: name the macro whose call a \par abandoned (#315)

The runaway alarm counted abandoned calls but never said WHICH macro was
being read, so 198 of them over 22 corpus papers were a sum with no handle
on it — the same fault #262 repaired for the maths layer, where every
dropped formula was filed as "$math$".

parEndsArgument now records e.expandingCS, set immediately before the
argument scan in getXToken's mMacro case, and Diagnostics carries the
tally by name. cmd/gotex prints it under the existing WARNING.

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

* engine: \@hangfrom must be \long, or every heading is dropped

Named by the diagnostic above, \@hangfrom is 179 of the 199 abandoned calls
across the 23 corpus documents that have any — 90%, and not a document's
malformed macro but our own substrate. 44 of them fall on one paper.

Real LaTeX's \@hangfrom takes ONE argument, the label (latex.ltx:12865);
the amsart family's second brace group is ordinary material, so the \par
that ends it is harmless (mathincs.cls:1177):

	\@hangfrom{\hskip #3\relax\@svsec}{\interlinepenalty\@m #8\par}

Ours takes that group as #2 — having no hanging indent, it has nothing
else to do with it — which makes the \par a runaway, and tex.web §392
abandons the call. The whole heading goes: number and title both. Without
the \long prefix the test's page comes out EMPTY.

Measured against a control built from the same base: abandoned calls
44→0 on 2401.13343 and 22→0 on 2408.04846, +4649 glyphs, no text lost.
Section numbers and whole subsection headings return; I diffed the text
layers and every word the diff called lost is still present, reflowed.

Five documents each change by a page, so the barometer moves 345→350 and
≤1pp 83→80. Three of the five were ALREADY longer than the reference while
missing their headings — 2401.13343 set 30 pages against 29, longer with
less content — so restoring the headings adds their height to a body whose
excess was being paid for by the loss. The other two shorten, which is page
breaking rearranging around a heading, not height. The deficit is now
visible instead of cancelled.

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

* engine: \long the emulation stubs whose real commands are \long

The other 20 of the 199 abandoned calls, each checked against the package
that defines the real command:

  \@subfloatopt/\@subfloatnoopt (13)  subfig.sty:350,354 are \long
  \subcaptionbox                      caption.sty:457 \newcommand (unstarred)
                                      and subcaption.sty:270 \long
  \@titlemand (1)                     latex.ltx:12747 \DeclareRobustCommand,
                                      unstarred, so \long (\@star@or@long,
                                      latex.ltx:1173)
  \@gobbleoptarg (2)                  \@footnotetext is \long (latex.ltx:13187);
                                      array.sty:273 rewrites likewise

\@authormand is the deliberate exception and keeps its short form:
latex.ltx:12748 declares \author with \DeclareRobustCommand*, and the STARRED
branch of \@star@or@long is \relax. A \par in an author block is a runaway in
real LaTeX too, so the 3 in the corpus are the documents' error, not ours.
A test pins that. \onlinecite (1) is revtex's, not ours.

The corpus page barometer does not move: 350 both sides, 27 exact, ≤1pp 80.
Five documents change and the raw glyph count falls by 10197 — which is the
FIX, not a regression. What disappears is TikZ source that the abandoned call
had pushed back and typeset AS TEXT:

  [] (end) -- (endbot) node[midway, right] \delta; [] (0,0.5) -- (5,0.5) ...

What appears is real: sub-caption labels ((b) (c) (d), (m) Bending problem),
table rows, and a section counter that was reading 1.1 where the reference has
2.1. A glyph census counts leaked source as content, so stopping a leak reads
as loss; the text-layer diff is what settles it.

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 9, 2026
…331)

Two halves of one mechanism, neither of which existed.

    \def\pagestyle#1{\@ifundefined{ps@#1}\undefinedpagestyle{\@nameuse{ps@#1}}}
                                                        latex.ltx:13326-13329
    \long\def\f@nch@pagestyle#1[#2]#3{… \@namedef{ps@#1}{…#3\relax} …}
                                                        fancyhdr.sty:438-450

\fancypagestyle was undefined, so its arguments were left in the input and
EXECUTED where they landed: a class's \fancyhead/\fancyfoot assignments reached
this engine's fields by ACCIDENT, and the style's name was typeset. acmart.cls:2589
declares standardpagestyle and firstpagestyle, and both names came out as body
text before \maketitle — on a two-column paper that lands ahead of the
\twocolumn[...], which starts a new column region, so it took a page of its own.

Now the definitions are stored under \ps@name and run when the style is SELECTED,
which is what makes a running head appear on the page that asked for it. On
2406.06585 page 2 began with body text and now reads

    ITERATED MAP IDENTIFICATION UCSB RMP AUG 2023

against the reference's

    UCSB RMP ITERATED MAP IDENTIFICATION AUG 2023

— the same content with the left and right fields transposed, which is a separate
question (this engine does not yet swap them by page parity).

I measured three variants of this in #318 and shipped none: giving \ps@name the
definitions changed nothing while the selection never ran them, and executing them
at declaration time bought Sigma by removing a real title block. Running them on
selection is the one the sources describe.

Measured over the 157-paper corpus: Sigma 343 -> 341 (-2), glyphs -5658.
2406.06585 goes 7 -> 6 pages against a reference of 6, so exact; 2408.04846 26 ->
25 against 24.

Eight papers are flagged. Each was checked: the deltas are at most 1% of the
paper's characters, they leave every other page byte-identical (2304.01951 changes
page 1 alone, 5647 -> 4752 characters, and pages 2-10 not at all), and the pages
they touch are the ones acmart fills with its own option junk — which is #306's
subject, not this one — or reflow around a head that now exists.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 20, 2026
Named in #356 and left unfixed there. Our generic \caption hard-coded \small
for every caption in the corpus; article.cls's \@makecaption sets "#1: #2" at
the CURRENT size (l.482) and carries no \small at all.

Measured against tectonic rather than inferred from the class: with the SAME
word in the body and in the caption, the reference gives it width 66.01 in
both, and its caption glyphs have the body's own height (9.96). Ours set the
caption a factor 10/9 narrower — the signature of \small.

A census says the class rule is the corpus rule too. Of the 200 arXiv papers,
149 never redefine \@makecaption (so article.cls's is theirs) and 19 redefine
it at the current size: 168 against the 32 that ask for \small or smaller.

\captionfont is the hook, empty by default. The name is caption.sty's own —
its small/footnotesize/scriptsize options are literally \def\captionfont{\small}
and friends — so a class or document that wants a smaller caption is honoured
for free. The three definitions of \caption in MiniLaTeXKernel are aligned;
only the last takes effect, but leaving two contradictory forms of one macro
misleads the next reader.

Corpus (157 comparable): Σ 326 → 328, exact 38 → 36, ≤1pp 88 → 85, ≤2pp
116 → 117, bias +50 → +58. Eight documents change and EVERY ONE gains exactly
one page, which is what a caption one step larger does: three of them were too
short and improve, five were already too long and worsen. The cost is not this
rule being wrong, it is that more of the corpus leans long than short — see the
population measurement I am posting to #356.

One of the five, 2311.02037, asks for \usepackage[font=footnotesize]{caption}
and we ignore it; \captionfont is where that belongs, and the option parsing is
filed separately.

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

Part of #293.

\algrenewcommand\algorithmicwhile{\textbf{While}} (algorithmicx.sty:622) names
a pseudocode keyword. It was undefined, so the command was skipped and its
braced argument was ordinary material — the keyword landed on the page.
2406.02421 opened on a page carrying nothing but

	While For Do If Then Else End Return

38 characters, and ran a page long.

\algnewcommand was not undefined but WORSE: a \def\algnewcommand#1#2{} taking
exactly two arguments. On \algnewcommand\algorithmiccomment[1]{…} — the form
algorithmicx uses for its own commands — #2 grabbed the "[1]" and the body
leaked instead.

Both are now \newcommand/\renewcommand on the name. The real pair routes
through \ALG@defbasecmd, which binds the name into a per-LANGUAGE slot so
algorithmicx can carry several pseudocode languages at once; no corpus document
uses more than one, so the visible behaviour is exactly this, the [n] form
included. The definition is KEPT rather than gobbled, so a document that writes
\algorithmicwhile itself gets what it asked for. Our own keyword output does
not consult these yet — \@algkw prints its word directly — so a document's
capitalisation is still ours, which is a smaller gap than a page of leaked
keywords.

The pair sits where the old gobbler was, so a later line of the same format
cannot shadow it again — which is exactly what happened when I first put it
500 lines earlier.

Corpus, control and treatment both from ee243ab: Σ 329 → 329, exact 35 → 36,
bias +61 → +59. Two documents move: 2406.02421 goes 10 → 9 against a reference
of 9 and is now exact, its page 1 going from 38 characters to 4304;
2401.13156 goes 23 → 22 against 24 — it carried leaked keywords too, and
removing them uncovers a deficit that was already there.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 23, 2026
Same family as #383, found on the corpus's second-worst "too long" paper.
2408.02845 (wlscirep, Scientific Reports) opened on a page holding

    [2006/08/17]
    main
    adja-page
    adja-page
    #1 #2 (previous page)

with an \hrulefill drawn across the sheet — its own preamble, typeset, pushing
the title to page 2. The commands and their real shapes:

    \DeclareCaptionLabelFormat{<name>}{<code>}    caption3.sty:725  (2)
    \DeclareVoidOption{<name>}{<code>}            kvoptions.sty:370 (2)
    \ProcessKeyvalOptions[*]{<family>}            kvoptions.sty:619
    \define@key{<fam>}{<key>}[<default>]{<code>}  keyval.sty:81
    \contentsmargin[<corr>]{<width>}              titletoc.sty:188
    \titlecontents[*]{…}[…]{…}{…}{…}{…}[…][…]     titletoc.sty:203
    \defaultbibliography / \defaultbibliographystyle
    \phantomsection

Two are worth naming. \contentsmargin's body ENDS with a bare "\def\@pnumwidth",
which swallows the following group as that macro's body — so it really takes an
optional bracket AND a group, and a stub taking only the bracket would leave
"{0cm}" on the page. \titlecontents takes a star, a group, a bracket, FOUR
groups, then up to TWO trailing brackets; wlscirep declares three of them.

MEASURED: Sigma 300 -> 299 over the 154-paper corpus, nothing lost. The paper
itself still runs long (37 against 29) for a different reason — its \@maketitle
draws nothing, which is its own investigation — but its first page no longer
carries the preamble.

Thirteen of the test's cases fail without the change.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 23, 2026
A file spec takes TWO optional arguments, options and a DATE:

    \@onefilewithoptions#1[#2][#3]#4        latex.ltx:13735

The date is how a package states the version it needs. jabbrv.sty writes

    \RequirePackage{kvoptions}[2006/08/17]

and we read only the options, so the date was typeset. Every document that loads
jabbrv opened on a page carrying "[2006/08/17]" and nothing else, its title
pushed to page 2 — visible on the corpus's 2408.02845 (wlscirep), whose class
requires jabbrv.

The lookahead uses getNext, NOT getXToken. LaTeX's own is \@ifnextchar, which is
\futurelet and expands nothing; expanding runs whatever follows the load before
the package is registered, and the first draft of this made

    \usepackage{p}\@ifpackageloaded{p}{…}{…}

answer "not loaded" — two existing tests caught it, which is the whole point of
their being there.

MEASURED: Sigma 299 -> 300 over the 154-paper corpus, inside the +-3 this corpus
can resolve, and a leaked version date leaves page 1.

A bracket that is NOT a date — one opening a paragraph after a blank line —
still survives, in both engines: the \par stops the lookahead. Pinned.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Sep 23, 2026
ifthen.sty:125 is \lowercase{\def\@tempa{#2}} before the value is used, so
\setboolean{b}{True} and {TRUE} both work. Written without it, \csname
bTrue\endcsname is undefined and the assignment silently does NOTHING — a wrong
answer with no diagnostic, which is the worst shape a defect can take.

Against tectonic:

  \setboolean{b}{True} ... \ifthenelse{\boolean{b}}{VRAI}{FAUX}
  reference  B VRAI C FAUX
  before     B FAUX C FAUX
  after      B VRAI C FAUX

No corpus paper writes a capitalised value — all 38 uses are lowercase. This
came from READING ifthen.sty, which I should have done before #390 and did
only when asked whether I had been doing my bibliography. Measurement could
not have found it.

Two further divergences from the source are documented in ifthen.go rather than
fixed, since nothing exercises them: the combinators exist in lowercase too
(or/and/not, rewritten by \TE@repl at :75-81), and \equal compares token lists
with \ifx inside an \xdef (:122) where this compares rendered characters.

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

* \resizebox* printed its own arguments onto the page

The star is the whole difference between the two forms, and it is one word of
graphics.sty:539-541:

    \protected\def\resizebox{%
      \leavevmode
      \@ifstar{\Gscale@@box\totalheight}{\Gscale@@box\height}}

\resizebox sizes the box by its HEIGHT above the baseline, \resizebox* by its
TOTAL height, depth included. Everything else is shared.

The star was never consumed, so neither dimension parsed and the source reached
the page as text. `Y\resizebox*{30mm}{!}{CONTENU}Y` set

    Y*30mm!CONTENUY

with the content unscaled. One corpus paper wraps every one of its four figures
this way and printed "*45mm!", "*100mm!" and "*65mm!" into them, each around a
tikzpicture that then went unscaled.

20 of the 154 corpus papers use \resizebox, 111 times, 4 of them starred.

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

* \rule's lift was added to its height instead of crossing the baseline

The lift of \rule[lift]{width}{height} moves the rule ACROSS the baseline; it does
not make it taller. latex.ltx:11900-11907 says which dimension takes it:

    \def\@rule[#1]#2#3{%
      \leavevmode
      \hbox{%
        \setlength\@tempdima{#1}%   lift
        \setlength\@tempdimb{#2}%   width
        \setlength\@tempdimc{#3}%   height
        \advance\@tempdimc\@tempdima
        \vrule\@width\@tempdimb\@height\@tempdimc\@Depth-\@tempdima}}

so height = #3 + lift and depth = -lift. Both signs were the wrong way round here.

Asked directly, tectonic answers:

    \rule[2pt]{3pt}{6pt}    ht=8.0pt  dp=0.0pt
    \rule[-2pt]{3pt}{6pt}   ht=4.0pt  dp=2.0pt
    \rule{3pt}{6pt}         ht=6.0pt  dp=0.0pt

and this engine now answers the same three. Before, a negative lift — the only
kind that does anything visible — was ADDED to the height and asked for a negative
depth the packer clamped to zero: \rule[-2mm]{3mm}{6mm} packed 8mm tall and 0mm
deep. One corpus paper writes \rule[-\textheight/2]{1ex}{\textheight}, meant to
straddle the baseline by half a page each way; it packed one and a half pages
above it. 4 of the 154 papers use a non-zero lift, 21 times.

A lift of zero, which is what \rule{w}{h} supplies, is unaffected either way, so
nothing else in the corpus moves.

TestRuleLift demanded the inversion outright — height 4pt and depth 2pt for a
+2pt lift — and so pinned it in place. It now asks tectonic's answer, and checks
the enclosing hbox clamps the negative depth the way TeX's hpack does (tex.web
§649).

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 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 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 Oct 3, 2026
…pcounter hook (#527)

Three defects in typed cross-references, all measured on the 154-paper arXiv
corpus against tectonic. 14 papers use \cref/\Cref, 904 times.

1. crefForms disagreed with cleveref. It abbreviated both cases alike
   ("Fig."/"fig.", "Thm."/"thm.") where cleveref abbreviates the LOWERCASE
   equation and figure only and spells every capitalised name out, and it had no
   entry for a section at all — so \Cref{sec:x} printed a bare "1". The table is
   now read from cleveref.sty's own \crefname@preamble/\Crefname@preamble blocks
   (cleveref.sty:3833-3946) under its default options (abbrev on, capitalise
   off, both set at cleveref.sty:3814-3831).

2. The reference TYPE was recorded by \@NSECTION, \equation and \caption only,
   never on the real \@startsection path — which every standard class takes. It
   is now recorded by \refstepcounter, which is LaTeX's own hook for it: whatever
   a class or package numbers gets a type, instead of one command at a time.

3. \crefname and \Crefname discarded their arguments, so a document could not
   name its own types. Four corpus papers name theirs, 35 times, and three of
   the four ask for the SHORT forms ("Sec.", "Fig.", "Tab.", "Eq.") exactly
   where cleveref's default spells the capitalised name out — so without this
   the defaults table is not a fallback, it is an override. The cross-fill is
   cleveref's own (\@crefname, cleveref.sty:1296-1320): naming one case defines
   the other, lowercased or uppercased, but only while that one is unset, so
   whichever call came first wins.

Measured, by CHANNEL — counting cleveref's label words themselves in our text
and in the reference's, because the corpus text census has a 5-letter floor and
would score a change from "Fig." to "Figure" as a gain:

    Σ|deviation|, label words, 14 papers   991 -> 780
    rows moving toward the reference        40
    rows moving away                        11

Corpus pages: Σ|deviation| 338 -> 339, exact pagination 37 unchanged. The one
page is 2406.01525, which sets \crefformat{section}{#2\S#1#3} — its reference
prints "§" 61 times where we now print "Section". \crefformat is unimplemented
and is the whole of that paper's remaining deficit; it is 1 paper and 2 uses in
154, and it is left for its own change.

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
…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
…lias was built anyway (#547)

latex.ltx's \@othm tests \@ifundefined{c@#2} and errors — "No theorem environment #2
defined" — because that counter does not exist yet, so real LaTeX numbers nothing and
carries on. Here the alias was built regardless:

	\the<env> := \the<shared>, which when shared == env is \the<env> again

a self-referential macro the engine then spun 400 times into the runaway guard. The
test's failure message shows it at the token level: [macro:->\thecorollary ].

Two corpus papers write it, one directly and one through a wrapper of its own:

	\newtheorem{corollary}[corollary]{Corollary}        2607.21390   3 ->  11 pages
	\newtheorem{#1vArIAblE}[#1vArIAblE]{#3}             2606.14675   2 ->  37 pages

open groups 3 -> 0 and 4 -> 0, runaway gone in both.

Dropping the self-share leaves the environment a counter of its own, which is what the
code already does when no [shared] is given at all. The second test is there because the
cure must not break what [shared] is FOR: \newtheorem{example}[theorem] must still give
\theexample = \thetheorem, which carries the section (latex.ltx:12728).

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 4, 2026
…n the SEARCH

import.sty does two things at once, and this implementation honoured one of them:

	\newcommand{\import}{\global\let\import@path\@empty \@doimport\input}
	\protected@edef\input@path{{\import@path}#2}   % #2 = \input@path's CURRENT value

The path is reset; the search list ACCUMULATES. Honouring only the reset means a
nested \import looks in the working directory rather than in the file that is doing
the importing — and \import, not \subimport, is what a paper writes when each of its
chapters lives in its own directory:

	main.tex                     \import{chapters/01-intro}{main.tex}
	chapters/01-intro/main.tex   \import{./}{intro.tex}

2601.22691 is that shape: five chapters that each import their own sections, 14 calls
in all. The five at the top level always worked — which is how the nested ones came
to be seen at all — and the nine nested ones were recorded as a skipped command.

	pages 2 -> 27, \import skipped 9 -> 0

The fix tries the enclosing directories, innermost first, when the reset path misses,
before the existing fall-back to the bare name.

⚠ The engine reports this as "\import skipped", not as a missing file, and that is
what made a path bug look like an absent feature: I opened an issue saying \import was
unimplemented when it has been here since #223. A lookup that exhausted its candidates
is a different event from a command with no meaning, and reporting them alike hid the
difference. Worth separating, in its own change.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 4, 2026
…n the SEARCH (#555)

import.sty does two things at once, and this implementation honoured one of them:

	\newcommand{\import}{\global\let\import@path\@empty \@doimport\input}
	\protected@edef\input@path{{\import@path}#2}   % #2 = \input@path's CURRENT value

The path is reset; the search list ACCUMULATES. Honouring only the reset means a
nested \import looks in the working directory rather than in the file that is doing
the importing — and \import, not \subimport, is what a paper writes when each of its
chapters lives in its own directory:

	main.tex                     \import{chapters/01-intro}{main.tex}
	chapters/01-intro/main.tex   \import{./}{intro.tex}

2601.22691 is that shape: five chapters that each import their own sections, 14 calls
in all. The five at the top level always worked — which is how the nested ones came
to be seen at all — and the nine nested ones were recorded as a skipped command.

	pages 2 -> 27, \import skipped 9 -> 0

The fix tries the enclosing directories, innermost first, when the reset path misses,
before the existing fall-back to the bare name.

⚠ The engine reports this as "\import skipped", not as a missing file, and that is
what made a path bug look like an absent feature: I opened an issue saying \import was
unimplemented when it has been here since #223. A lookup that exhausted its candidates
is a different event from a command with no meaning, and reporting them alike hid the
difference. Worth separating, in its own change.

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]>
tannevaled added a commit that referenced this pull request Oct 20, 2026
…#625) (#627)

A class may apply one of its own options by CALLING the macro the declaration
left behind. base/ltclass.dtx stores it there:

	\long\def\@declareoption#1#2{%
	   \xdef\@declaredoptions{\@declaredoptions,#1}%
	   \toks@{#2}%
	   \expandafter\edef\csname ds@#1\endcsname{\the\toks@}}

and \ProcessOptions reaches the same macro through \@use@ption, which ends in
\csname ds@\detokenize\expandafter{\CurrentOption}\endcsname. So \ds@<option> is
the mechanism, not a private spelling. We recorded the code on the load frame and
defined nothing, so aas.cls:5547 — \ds@letterpaper, how that class sets its paper
size between its declarations and its option processing — was an undefined command,
skipped.

\@options is the LaTeX 2.09 spelling of the same step, and the kernel keeps it as
exactly that: "\@options is a synonym for \ProcessOptions* for upward compatibility
with LaTeX 2.09 style files", \def\@options{\ProcessOptions*}. aas.cls:6961 is that
class's ONLY option processing, so skipping it meant no option ran at all.

The definition is local, as the kernel's \edef is: a class file is loaded on a load
FRAME (catcodes saved and restored), not inside a TeX group, so nothing closes
between the declaration and the call.

\@options goes through doProcessOptions, star peek and all. A version that skipped
the peek (\@options carries no star of its own) was written and could not be given a
witness — no real 2.09 style file writes a literal * after it — so the distinction
was dropped rather than shipped.

This does NOT fix 2607.05497, the paper that led here: it still renders one page of
a 56 KB source. Two commands leave its skipped list (14 → 12) and the class's output
routine remains the gap. Measured and said rather than implied.

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

latex.ltx:

	\def\cite{\@ifnextchar[{\@tempswatrue\@citex}{\@tempswafalse\@citex[]}}
	\def\@citex[#1]#2{…\if@tempswa , #1\fi…}

so the note is appended AFTER the key list, separated by ", ": \cite[p. 5]{k}
sets "[1, p. 5]". doCite read the braces straight away, so readBraceName met "["
instead of "{", returned nothing, and the whole

	[etc.]{Zeilberger1990,chyzak98,chyzak00,chyzak09a,raab12,koutschan13,…}

was typeset as text — one unbroken run 2665pt wide on a 478pt measure on arXiv
2311.05246, with the words after it run together for want of interword glue.

6621 papers of the arXiv pool write \cite[, 38 of the measured 154 (measure
population). Both corpus papers whose overfull line was a citation — 2311.05246
at 2665pt and 2405.10478 at 1171pt — now have NONE.

natbib's \citep and \citet take TWO optionals, [pre][post]; with one bracket it is
the post-note, which is what LaTeX's \cite means by its single one. readCiteNotes
reads up to two, so both spellings stay off the page, and the existing
\citep/\citet/\citeauthor/\citenum tests pass unchanged.

Checked against its own mutation: with the optional read removed the test reports
"[][etc.]alphaReferences…" against the expected "[1, etc.]".

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 22, 2026
…sts (#636, #629) (#642)

caption3.sty:237-243:

	\newif\ifcaptionsetup@star
	\newcommand*\captionsetup{\caption@teststar@\@captionsetup\@gobble\@Firstofone}
	\newcommand*\@captionsetup[1]{\captionsetup@startrue#1\captionsetup@starfalse…}

All the star does is raise that flag, and the flag's ONE use is to suppress a
warning: caption.sty:319 reads \ifcaptionsetup@star\else\@nameuse{caption@#1type@
warning}\fi. Nothing it typesets changes, so the star is consumed and nothing else
here does.

Unread, the star WAS the argument: scanBracketList met "*" instead of "[", so the key
list was never read and the whole lot went on the page.

caption3.sty:696-706 for the second half:

	\newcommand*\DeclareCaptionFormat{\caption@teststar\caption@declareformat…}
	\newcommand*\caption@declareformat[2]{\@dblarg{\caption@@declareformat#1{#2}}}
	\long\def\caption@@declareformat#1#2[#3]#4{…}

— an optional star, the name, an OPTIONAL single-line variant that \@dblarg defaults
to the mandatory one, and the body. Undefined, it left all of that behind.

paper.cls (PNAS) writes both, four lines apart:

	\DeclareCaptionFormat{pnasformat}{\normalfont\sffamily…#1#2#3}   % :154
	\captionsetup*{format=pnasformat}                                % :155

and page 1 of 2310.11517 read "*format=pnasformat" in its body text. 29 corpus papers
write \captionsetup* (#636).

Caption FORMATS are not modelled here — the caption head goes through \fnum@<type>,
see doCaptionsetup — so the declaration is consumed and nothing is kept. What matters
is that it stops reaching the page.

⛔ The test reads through captionHead, not pageOf: a float's content is DEFERRED and
never reaches the main vertical list, so pageOf comes back empty for BOTH forms — a
comparison of nothing with nothing, which is how this test first "passed". And all
four spellings of \DeclareCaptionFormat's grammar are exercised, because a dispatcher
that reads three and leaks the fourth looks exactly like one that works. Run against
the unfixed files, both tests fail and print the leaked text.

⚠ This does NOT fix 2310.11517's author line, which is still 1787.88pt wide. That is a
separate cause and stays open on #629.

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

mdframed.sty:

	\newrobustcmd*\mdfdefinestyle[2]{\csdef{mdf@definestyle@#1}{#2}}          % :564
	\newrobustcmd*\mdfapptodefinestyle[2]{…\csappto{mdf@definestyle@#1}{,#2}} % :567
	\newrobustcmd*{\mdfsetup}{\kvsetkeys{mdf}}                                % :386

All three STORE a key list and typeset nothing. Undefined, all three left their
arguments behind. researchpaper.sty (PNAS) writes

	\mdfdefinestyle{pnassigstyle}{linewidth=0.7pt,backgroundcolor=pnasblueback,…}

at :23, and page 1 of 2310.11517 carried that as a 797pt line on a 612pt sheet — the
leak that #643 uncovered underneath the one it fixed. 144 papers of the arXiv pool
write one of the three.

The environment is defined too, as \newenvironment{mdframed}[1][]{}{}: its BODY is
document content and must be set — the PNAS significance statement lives in one — so
only the optional key list is consumed and the frame itself is not drawn. Undefined,
"[style=pnassigstyle]" stood on the page as ordinary text.

⛔ A gobbler that ate the body would pass a leak test and silently delete a paragraph,
which is the worse defect of the two, so the test asserts the body IS there as well as
that the keys are not. Measured on 2310.11517, pages 1-2: 1154 words before, 1386
after, against the reference's 2080 — the change ADDS content, it does not remove any.

Run against the unfixed file all four cases fail, printing what leaked:
"gotexstylinewidth=0.7pt,backgroundcolor=gotexcolourAPRES" and
"[style=gotexsty]GOTEXCORPS".

⚠ \newmdenv / \renewmdenv / \newmdtheoremenv (mdframed.sty:578, :586, :591) are NOT
done here: no witness in the corpus produces a leak from them, and a definition
written without one is a guess.

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

Two things: GOTEX_FLTRACE, which makes the placer report its decisions the way
LaTeX's `fltrace` package does, and the defect that trace located.

⭐ THE REFERENCE CAN BE ASKED WHY, not just where. LaTeX ships `fltrace`;
\usepackage{fltrace}\tracefloats makes the output routine print \@fpstype,
\@textmin, \@reqcolroom, \@colroom, \@toproom, \@colnum and the verdict for every
float (ltoutput.dtx:4127-4323, 6010-6049), and tectonic's bundle has it. A PDF
shows where a float LANDED and never why; this is the one channel that does. So
the same trace exists here now, with fltrace's own wording -- "Space OK",
"Fail---no room", "toproom", "float size" -- so the two logs read side by side
without a translation table.

THE DEFECT. ltoutput.dtx:6016-6018 refuses a top float unless the room left
STRICTLY exceeds its height:

  \ifdim \@colroom>\@reqcolroom
    \ifdim #1>\ht\@currbox  \@tempswatrue

with #1 = \@toproom, which starts at \topfraction\@ColhT and is decremented by
the float's height PLUS, from ltoutput.dtx:6009,

  \ifx #2\@empty \textfloatsep \else \floatsep \fi

-- \textfloatsep (20pt) while the top list is still empty, \floatsep (12pt)
after. This engine charged \floatsep BETWEEN floats and nothing for the first, so
its top budget was 8pt more generous than LaTeX's on every page carrying floats.

The reference's own trace on a three-figure witness is what located it:

  Space OK: \@toproom = 384.99832pt > 144.05998pt
  Fail---no room: \@toproom = 220.93834pt. Ht float: 224.05998pt

384.998 − 220.938 = 164.06 = 144.06 + 20pt. Ours reached 144.06 + 12 + 224.06 =
380.12 against a 385pt cap and accepted the second figure with 4.88pt to spare;
LaTeX, charging 20pt instead of 12, reaches 388.12 and defers it.

⛔ THE FIX WENT INTO DEAD CODE FIRST. The same arithmetic appears twice in
pagesWithFloats: a top/bottom selection over the deferred queue, and a second
pass over the floats anchored INSIDE the page being built. The first was corrected
and the witness did not move -- because the trace then showed "0 flottant(s) en
attente" on every page and no per-float line at all: on this document the
deferred queue is always empty and the live path is the second one. The trace
found that in one run; reading the code had not.

⛔ AND A PREDICTION THAT FAILED, which is why the trace exists. The arithmetic was
written, predicted to move the figure to page 2, and did not. The prediction was
about OUR numbers and nothing had measured them. It turns out our float boxes are
4.54pt SHORTER than LaTeX's -- 139.52 against 144.05998, 219.52 against 224.05998,
the same 4.54pt on both -- which is a second defect, filed separately, and it is
what still holds that witness back.

TestTopRoomChargesTextfloatsepForTheFirstFloat is built so the two rules
DISAGREE, which is the only thing that makes it a test: captionless floats of
200pt and 170pt against a 385pt cap. LaTeX leaves 165pt and 165 > 170 is false,
so the second defers; the old rule reached 200 + 12 + 170 = 382 <= 385 and kept it
on page 1. 8pt decides it, exactly \textfloatsep − \floatsep. Charging nothing for
the first float again turns it red.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Oct 31, 2026
…\samepage; \stretch to order 2 (#664)

* \hspace and \vspace take a GLUE, not a dimen

The reference reads that argument into a SKIP register, which is the whole point
(ltspace.dtx:450, 1412-1413, 1423, 1152-1183):

	\newskip\sp@ce@skip
	\def\@hspace#1{\setlength\sp@ce@skip{#1}\hskip\sp@ce@skip}
	\def\@Vspace@calcify#1{\setlength\sp@ce@skip{#1}\vskip\sp@ce@skip}

Both primitives here read a rigid dimen and dropped everything after the natural
width. Silently: \hspace{\fill} became a 0pt space. Measured against tectonic on
three lines each anchored at BOTH ends, so the x of the second word says whether
the glue stretched:

	                 oracle    before    after
	\hspace{\fill}   477.48    188.50    477.50   (188.50 = "gauchedroite", accolés)
	\hfill           477.48    477.50    477.50   (témoin planté: déjà juste)
	\enskip          193.85    188.50    193.48

readBraceGlue is what \setlength itself reads with, so this is the reference's own
route rather than a parallel one.

Four names ltspace.dtx documents and this format did not define — all four
DOCUMENT commands, so strict mode aborted the compilation on each and -lenient
dropped them, which for \fill and \enskip glues the surrounding words together:

	\newskip\fill  \fill = 0pt plus 1fill		l.1445-1446
	\def\enskip{\hskip.5em\relax}			l.1501
	\DeclareRobustCommand\samepage{…nine penalties}	l.314-322
	\relax on \quad and \qquad			l.1502-1503

⛔ \stretch was order ONE and the reference's is order TWO.

	\def\stretch#1{\z@ \@plus #1fill\relax}		l.1454

Not a detail, and not visible as a failure: against any \vfil or \hfil on the same
list, order 2 takes ALL the leftover space and order 1 only shares it, so the box
lands elsewhere with nothing going wrong. Two tests ASSERTED "fil" and pinned it
there; both are updated with the reference line, and TestStretch now carries a
control that an order-1 glue must not read as fill.

⛔ The trailing \relax had to be absorbed. \stretch ends in one by construction,
and in the reference there is no brace to meet — \setlength\sp@ce@skip{#1} is a
MACRO, so #1's braces are gone before the assignment scans. Keeping them as real
tokens left the \relax in front of the brace and \vspace{\stretch{1}} ABORTED with
"Extra }, or forgotten \endgroup" — a message that names braces for a defect in a
glue scan, which is why this was probed with \ifx and not read off the error.

⛔⛔ THE MUTATION ON THE PRIMITIVE SURVIVED THE WHOLE SUITE. There are three call
sites — the \hspace primitive, the \vspace primitive, boxNodeFor — and they were
mutated one at a time. boxNodeFor failed four cases; \vspace failed three; the
\hspace PRIMITIVE, the paragraph route the witness measured, passed 12.7s of tests
with nothing to say. TestHspaceInRunningTextKeepsTheRubber exists for that
mutation alone.

⛔ And its first version searched the line for "an infinite glue", which found the
PARAGRAPH'S OWN \parfillskip (0pt plus 1fil) and reported order 1 against the
defect with a straight face. The subject is order TWO, which nothing else on the
line produces.

⛔ \@m and all four \@…penalty registers \samepage sets were ALREADY here. grep
found them only inside comments, which reads as "not implemented"; a probe that
SET each one compiled clean. Code shape and behaviour disagreed and behaviour won.

Not in this change, measured and left open:

- The VERTICAL half does not stretch. \vfil, \vfill and \vss have empty bodies in
  this engine, so the page is packed at its natural height: the glue now reaches
  the list and the page builder ignores it. Witness vfill.tex, oracle against ours
  — "bas" at y=664.72 there and 139.10 here, and a \stretch 1:2:1 page the oracle
  sets at 126.73 / 267.21 / 536.20 while ours stays flat. That is the output
  routine, not \vspace; filed with the witness.
- \enspace is a KERN in the reference (l.1469, l.1489) and glue here, so it can be
  broken at and could stretch. Left as glue with the divergence named in place:
  every list item in this format goes through \llap{#2\enspace}, so its
  breakability is a corpus question.

Corpus A/B pending: the machine has been at load 27-30 all evening and the rule
here is not to measure ratios under load. This rests on the witness and the suite.

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

* README: the glue scan, the four definitions, and the vertical gap

Stage 2 (Stomach) is where the page-builder defect of #622/#648 is recorded, so the
glue-scan one belongs beside it: \hspace and \vspace read a rigid dimen where the
reference puts the argument through a skip register (ltspace.dtx:1412-1413, 450),
which dropped the stretch and set the words on either side of \hspace{\fill}
adjoining — 188.50 against the oracle's 477.48.

Also named: \fill, \enskip and \samepage now defined, and \stretch moved to the
reference's SECOND order of infinity (l.1454), which is what decides who wins the
leftover space on a list that also holds an \hfil.

⛔ And the gap this does NOT close, with its issue number READ BACK from
`gh issue create` rather than assumed: vertical infinite glue still does not
stretch (\vfil/\vfill/\vss are empty no-ops, a page is packed at its natural
height), so \vspace{\fill} puts nothing between its neighbours — #663.
A README that claimed the fix without that line would read as parity on a channel
that is still flat.

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 Nov 1, 2026
⛔⛔ NOT A MISSING MARGINAL NOTE — CORRUPTED BODY TEXT, on 52 of the 154 measured corpus
papers (5985 in the archive). \marginpar was undefined, so strict mode aborted and
-lenient skipped the command name and then SET ITS ARGUMENT AS ORDINARY TEXT.

Measured against tectonic, with a control line that uses no \marginpar at all:

	source                                  oracle                 avant            après
	AVANTUN\marginpar{NOTEUN}APRESUN        AVANTUNAPRESUN         AVANTUNNOTEUN-   AVANTUNAPRESUN
	                                        + NOTEUN marge 488.44  APRESUN
	AVANTDEUX APRESDEUX (témoin)            idem                   idem             idem
	AVANTTROIS\marginpar[GAUCHE]{DROITE}…   AVANTTROISAPRESTROIS   AVANTTROIS-      AVANTTROISAPRESTROIS
	                                        + DROITE en marge      [GAUCHE]DROITE-
	                                                               APRESTROIS

The optional row is the one that shows what was happening: BOTH arguments reached the
page, the first with its literal brackets. And the body is what the corpus measures.

Bibliography, ltfloat.dtx:951-967 and 973-985:

	\def\marginpar{\ifhmode \@bsphack \@floatpenalty -\@mii
	  \else \@floatpenalty-\@miii \fi
	  \ifinner \@parmoderr \@floatpenalty\z@ \else …\@next… \fi
	  \@ifnextchar [\@xmpar\@ympar}
	\long\def\@xmpar[#1]#2{\@savemarbox\@MARBOX{#1}\@savemarbox\@currbox{#2}\@xympar}
	\long\def\@ympar#1{\@savemarbox\@MARBOX{#1}\global\setbox\@currbox\copy\@MARBOX
	  \@xympar}

\@savemarbox (1013-1025) sets the note in a \vtop at \hsize=\marginparwidth, and
\@xympar (1098-1106) conses it onto \@currlist for the float machinery to place. On the
normal side the box shown is the SECOND argument; \if@reversemargin shows the first.
\marginparwidth, \marginparsep, \marginparpush, \if@reversemargin, \reversemarginpar
and \normalmarginpar were all already here — only \marginpar itself was missing.

⛔ THE NOTE IS NOT PLACED, AND THAT IS NAMED RATHER THAN HIDDEN. Putting a box in the
margin from inside a paragraph needs \vadjust, which this engine does not have (#665);
the alternative is the float machinery, its own piece of work. What this does is read
both arguments and emit NOTHING, which makes the body text EXACTLY the reference's.
A note in the margin is a note; a note in the middle of a sentence is a wrong sentence.

\@bsphack…\@esphack keeps the spacing around an invisible command right, as the
reference does for the horizontal-mode case.

⭐ HOW IT WAS FOUND. `measure refmacros` on ltfloat.dtx — the channel that asks what the
REFERENCE defines and we do not, and that needs no rendering, so it answers while the
machine is too loaded to measure. 39 of its 54 documented macros are absent; \marginpar
was the only DOCUMENT-level command among them with a real corpus population, which
`measure population` then put at 52/154 before a line of code was written.

Tests: the three forms plus a control with no \marginpar, in STRICT mode (an undefined
\marginpar aborted there, so compiling is itself part of the assertion). The mutation —
removing the three definitions — fails every row.

README updated, and it says the general lesson rather than just this case: in lenient
mode an undefined command is skipped "along with its LIKELY [opt]{arg} block", and
"likely" is why a command that takes an argument is worth defining even when its effect
is not.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 3, 2026
…s built in Go (#682)

* \@biblabel and \@cite are macros the citation path calls, not brackets built in Go

The marker's brackets were written into \@bibitemopt/\@bibitemnoopt and into doCite,
so no class could change either. The reference makes both a macro:

    \def\@biblabel#1{[#1]}                        (latex.ltx:13324)
    \def\@cite#1#2{[{#1\if@tempswa , #2\fi}]}     (latex.ltx:13322)

and article.cls:568 builds the bibliography list's label by calling \@biblabel.

This engine EXECUTES real .cls files, so those redefinitions were already reaching the
eqtb and were dropped at the one point that mattered. Measured on the corpus, split by
where the redefinition lives — because the first count did not separate a paper's own
source from the files it ships:

    dans le .tex du papier     56 papiers,     0 des 154
    dans un .cls embarque    3093 papiers,    22 des 154
      dont \@biblabel        2961 papiers,    19 des 154
      dont \@cite            1450 papiers,    12 des 154

Only 50 of the 154 ship a class at all, so 22 of 50 — 44% — of the papers that bring
their own class bring one that redefines these hooks. Exactly one of the 154 ships
natbib.sty, so this is about classes, not about natbib.

Measured before and after on a four-line document: \def\@biblabel#1{<<#1>>} and
\def\@cite#1#2{(((#1#2)))} rendered BYTE-IDENTICALLY to a document without them, and
now produce <<1>> and (((1))).

\if@tempswa is SET here rather than inherited. The reference's \cite makes it true when
it read a bracket and false when it did not (latex.ltx:13283-13284), and a redefined
\@cite reads it to decide whether to print the note; leaving it alone would make the
note's fate depend on whatever last touched the switch — a defect visible only on a
document that cites twice, with and without a note, in that order.

NOT DONE HERE: \@citex, the iteration itself. natbib works by \letting it
(natbib.sty:658,666), so executing it would mean running real natbib instead of the Go
emulation — and no number here calls for that: one paper in 154 ships natbib.sty.

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

* README: a citation's brackets are the class's, with the measured footprint

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 Nov 6, 2026
…fore the group

ltlists.dtx:552-573 is the whole macro, and the second argument is where the class
puts the list's geometry:

    \def\list#1#2{%
      \ifnum \@listdepth >5\relax \@toodeep \else \global\advance\@listdepth\@ne \fi
      \rightmargin\z@ \listparindent\z@ \itemindent\z@
      \csname @list\romannumeral\the\@listdepth\endcsname
      \def\@itemLabel{#1}\let\makelabel\@mklab \@nmbrlistfalse
      #2\relax
      \@trivlist
      \parskip\parsep \parindent\listparindent
      \advance\linewidth -\rightmargin \advance\linewidth -\leftmargin
      \advance\@totalleftmargin \leftmargin
      \parshape \@ne \@totalleftmargin \linewidth
      \ignorespaces}

A two-argument stub expanding to \@trivlist threw BOTH arguments away. For every
list in every real class the label vanished and so did \leftmargin, \labelwidth,
\usecounter and whatever else the class wrote there. article.cls:568-573 computes a
bibliography's measure in that block.

⚠ \leftskip and \rightskip in place of \parshape, stated rather than hidden: this
engine has neither \parshape nor \@totalleftmargin. For a list, \parshape \@ne
<indent> <width> sets ONE shape for every line, which is what a pair of skips does;
they differ only for a shape that changes line by line, which \list never asks for.
\leftskip is already how \itemize, \enumerate and \description indent here and it is
measurably right — our itemize continuation lands at 157.68 against 158.67.

⛔ AND \endtrivlist HAD \endgroup BEFORE \par, so a list's LAST item was typeset
after its group had closed, under the enclosing \leftskip and \parindent rather than
the list's. latex.ltx ends the paragraph first. This was invisible until \list
started doing its job: with \list a stub no list ever set \leftskip, so the early
\endgroup had nothing to lose. It showed up the same hour, as entry one on the
margin and entry two 16.86pt left of it.

⛔ AND A BIBLIOGRAPHY ENTRY CARRIES \itemsep — \itemsep ALONE, now that \list sets
\parskip to \parsep. \@item adds \itemsep (latex.ltx:11567); the other half of the
gap is \parskip, which the paragraph break between entries carries by itself.
\@iteminterspace adds BOTH, correctly, because \itemize and \enumerate here never go
through \list; using it for \bibitem would overshoot by 4pt an entry. The two
changes cannot be measured apart, which is why they are one branch.

Measured against tectonic on a two-entry bibliography:

                              entry 1    continuation   entry 2    inter-entry gap
    reference                  133.77        149.27      133.77        19.93
    before                     116.91        133.77      116.91        11.96
    \list alone                133.77        150.64      116.91        15.94
    this branch                133.77        150.64      133.77        19.92

The residual 1.37pt on the continuation is \settowidth measuring [9] in a different
face (11.93pt here, 10.56pt there), not a defect.

\@listdepth, \@mklab, \@toodeep and \makelabel were undefined and are added;
\@listi/\@Listi and \@trivlist were already there with the reference's values.

This supersedes the half-fix on bibliography-is-a-list (#705), which raised the
corpus bias from -5 to +40 by correcting the spacing while leaving the measure 32pt
too wide.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 6, 2026
…fore the group

ltlists.dtx:552-573 is the whole macro, and the second argument is where the class
puts the list's geometry:

    \def\list#1#2{%
      \ifnum \@listdepth >5\relax \@toodeep \else \global\advance\@listdepth\@ne \fi
      \rightmargin\z@ \listparindent\z@ \itemindent\z@
      \csname @list\romannumeral\the\@listdepth\endcsname
      \def\@itemLabel{#1}\let\makelabel\@mklab \@nmbrlistfalse
      #2\relax
      \@trivlist
      \parskip\parsep \parindent\listparindent
      \advance\linewidth -\rightmargin \advance\linewidth -\leftmargin
      \advance\@totalleftmargin \leftmargin
      \parshape \@ne \@totalleftmargin \linewidth
      \ignorespaces}

A two-argument stub expanding to \@trivlist threw BOTH arguments away. For every
list in every real class the label vanished and so did \leftmargin, \labelwidth,
\usecounter and whatever else the class wrote there. article.cls:568-573 computes a
bibliography's measure in that block.

⚠ \leftskip and \rightskip in place of \parshape, stated rather than hidden: this
engine has neither \parshape nor \@totalleftmargin. For a list, \parshape \@ne
<indent> <width> sets ONE shape for every line, which is what a pair of skips does;
they differ only for a shape that changes line by line, which \list never asks for.
\leftskip is already how \itemize, \enumerate and \description indent here and it is
measurably right — our itemize continuation lands at 157.68 against 158.67.

⛔ AND \endtrivlist HAD \endgroup BEFORE \par, so a list's LAST item was typeset
after its group had closed, under the enclosing \leftskip and \parindent rather than
the list's. latex.ltx ends the paragraph first. This was invisible until \list
started doing its job: with \list a stub no list ever set \leftskip, so the early
\endgroup had nothing to lose. It showed up the same hour, as entry one on the
margin and entry two 16.86pt left of it.

⛔ AND A BIBLIOGRAPHY ENTRY CARRIES \itemsep — \itemsep ALONE, now that \list sets
\parskip to \parsep. \@item adds \itemsep (latex.ltx:11567); the other half of the
gap is \parskip, which the paragraph break between entries carries by itself.
\@iteminterspace adds BOTH, correctly, because \itemize and \enumerate here never go
through \list; using it for \bibitem would overshoot by 4pt an entry. The two
changes cannot be measured apart, which is why they are one branch.

Measured against tectonic on a two-entry bibliography:

                              entry 1    continuation   entry 2    inter-entry gap
    reference                  133.77        149.27      133.77        19.93
    before                     116.91        133.77      116.91        11.96
    \list alone                133.77        150.64      116.91        15.94
    this branch                133.77        150.64      133.77        19.92

The residual 1.37pt on the continuation is \settowidth measuring [9] in a different
face (11.93pt here, 10.56pt there), not a defect.

\@listdepth, \@mklab, \@toodeep and \makelabel were undefined and are added;
\@listi/\@Listi and \@trivlist were already there with the reference's values.

This supersedes the half-fix on bibliography-is-a-list (#705), which raised the
corpus bias from -5 to +40 by correcting the spacing while leaving the measure 32pt
too wide.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 7, 2026
#726 gave \pagestyle{headings} its band, its folio and its rule, and #426's own
witness still came out with an EMPTY head. The cause is the last link, and it is
a name:

  \leftmark / \rightmark read \gotex@leftmark / \gotex@rightmark, a PRIVATE pair
  that only this engine's own \markboth ever wrote.

A class may bring its own \markboth, and amsart.cls does — one of the four
classes this engine advertises running (texmf/amsart.cls:335-340):

  \def\markboth#1#2{\begingroup
    \@temptokena{{#1}{#2}}\xdef\@theMark{\the\@temptokena}%
    \mark{\the\@temptokena}\endgroup …}

It writes \@theMark, the kernel's name (ltpage.dtx:355 \def\@theMark{{}{}}), and
touches no private pair. Every other link already worked: \ps@headings does
\let\@mkboth\markboth (amsart.cls:318), amsart calls
\@mkboth{\@nx\shortauthors}{\@nx\shorttitle} (:622), the mark was set. Only the
read was looking elsewhere.

So the pair moves to \@theMark and the accessors become the kernel's own
(ltpage.dtx:167-174, 341-342, 356-357):

  \let\@leftmark\@FirstOfTwo              \let\@rightmark\@secondoftwo
  \def\@theMark{{}{}}
  \def\markboth#1#2{\protected@xdef\@theMark{{#1}{#2}}}
  \def\@markright#1#2#3{\@temptokena{#1}%
    \protected@xdef\@theMark{{\the\@temptokena}{#3}}}
  \def\markright#1{\expandafter\@markright\@theMark{#1}}
  \def\leftmark{\expandafter\@leftmark\@theMark\@empty\@empty}
  \def\rightmark{\expandafter\@rightmark\@theMark\@empty\@empty}

\markright keeps the LEFT half, which is why the kernel routes it through
\@markright rather than assigning both — and \ps@headings's \sectionmark IS a
\markright, so the wrong shape would wipe half the head at every section. The
two \@empty are the kernel's guard for a pair never set.

⛔ WHAT WAS WRONG WITH THE TESTS, not just with the code. Two tests probed
\gotex@rightmark — the STORAGE — so they were green for every document whose
class brings its own \markboth, which is the only case that was broken. They now
probe \rightmark, the name a page style reads. Two tests added:

  - a class's own \markboth (amsart's idiom verbatim in shape) must reach
    \leftmark/\rightmark — the test #426 needed;
  - \markright keeps the left half.

Run against the previous commit, which is the control a new test needs or it
proves nothing, they do NOT both fail — and the difference matters:

  class's own \markboth   FAILS, "[|]" — both halves empty. #426 reproduced.
  \markright keeps left   PASSES. The old private pair kept the left too,
                          since \markright wrote only \gotex@rightmark.

So the second one is not a regression test for this change; it is a guard that
the new \@markright shape — which destructures the pair and rebuilds it — did
not lose what the simpler assignment got right. Keeping it, labelled for what it
is, rather than letting it be counted as evidence.

Still NOT done, and unchanged by this: the pair is the single live one, where
the kernel reads \botmark and \firstmark so a head shows the mark of THAT page
(#727). amsart is immune to that difference by construction — it \@Gobbles
\sectionmark and friends (amsart.cls:344-346), so its head is set once from the
authors and the short title.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 7, 2026
#726 gave \pagestyle{headings} its band, its folio and its rule, and #426's own
witness still came out with an EMPTY head. The cause is the last link, and it is
a name:

  \leftmark / \rightmark read \gotex@leftmark / \gotex@rightmark, a PRIVATE pair
  that only this engine's own \markboth ever wrote.

A class may bring its own \markboth, and amsart.cls does — one of the four
classes this engine advertises running (texmf/amsart.cls:335-340):

  \def\markboth#1#2{\begingroup
    \@temptokena{{#1}{#2}}\xdef\@theMark{\the\@temptokena}%
    \mark{\the\@temptokena}\endgroup …}

It writes \@theMark, the kernel's name (ltpage.dtx:355 \def\@theMark{{}{}}), and
touches no private pair. Every other link already worked: \ps@headings does
\let\@mkboth\markboth (amsart.cls:318), amsart calls
\@mkboth{\@nx\shortauthors}{\@nx\shorttitle} (:622), the mark was set. Only the
read was looking elsewhere.

So the pair moves to \@theMark and the accessors become the kernel's own
(ltpage.dtx:167-174, 341-342, 356-357):

  \let\@leftmark\@FirstOfTwo              \let\@rightmark\@secondoftwo
  \def\@theMark{{}{}}
  \def\markboth#1#2{\protected@xdef\@theMark{{#1}{#2}}}
  \def\@markright#1#2#3{\@temptokena{#1}%
    \protected@xdef\@theMark{{\the\@temptokena}{#3}}}
  \def\markright#1{\expandafter\@markright\@theMark{#1}}
  \def\leftmark{\expandafter\@leftmark\@theMark\@empty\@empty}
  \def\rightmark{\expandafter\@rightmark\@theMark\@empty\@empty}

\markright keeps the LEFT half, which is why the kernel routes it through
\@markright rather than assigning both — and \ps@headings's \sectionmark IS a
\markright, so the wrong shape would wipe half the head at every section. The
two \@empty are the kernel's guard for a pair never set.

⛔ WHAT WAS WRONG WITH THE TESTS, not just with the code. Two tests probed
\gotex@rightmark — the STORAGE — so they were green for every document whose
class brings its own \markboth, which is the only case that was broken. They now
probe \rightmark, the name a page style reads. Two tests added:

  - a class's own \markboth (amsart's idiom verbatim in shape) must reach
    \leftmark/\rightmark — the test #426 needed;
  - \markright keeps the left half.

Run against the previous commit, which is the control a new test needs or it
proves nothing, they do NOT both fail — and the difference matters:

  class's own \markboth   FAILS, "[|]" — both halves empty. #426 reproduced.
  \markright keeps left   PASSES. The old private pair kept the left too,
                          since \markright wrote only \gotex@rightmark.

So the second one is not a regression test for this change; it is a guard that
the new \@markright shape — which destructures the pair and rebuilds it — did
not lose what the simpler assignment got right. Keeping it, labelled for what it
is, rather than letting it be counted as evidence.

Still NOT done, and unchanged by this: the pair is the single live one, where
the kernel reads \botmark and \firstmark so a head shows the mark of THAT page
(#727). amsart is immune to that difference by construction — it \@Gobbles
\sectionmark and friends (amsart.cls:344-346), so its head is set once from the
authors and the short title.

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

#726 gave \pagestyle{headings} its band, its folio and its rule, and #426's own
witness still came out with an EMPTY head. The cause is the last link, and it is
a name:

  \leftmark / \rightmark read \gotex@leftmark / \gotex@rightmark, a PRIVATE pair
  that only this engine's own \markboth ever wrote.

A class may bring its own \markboth, and amsart.cls does — one of the four
classes this engine advertises running (texmf/amsart.cls:335-340):

  \def\markboth#1#2{\begingroup
    \@temptokena{{#1}{#2}}\xdef\@theMark{\the\@temptokena}%
    \mark{\the\@temptokena}\endgroup …}

It writes \@theMark, the kernel's name (ltpage.dtx:355 \def\@theMark{{}{}}), and
touches no private pair. Every other link already worked: \ps@headings does
\let\@mkboth\markboth (amsart.cls:318), amsart calls
\@mkboth{\@nx\shortauthors}{\@nx\shorttitle} (:622), the mark was set. Only the
read was looking elsewhere.

So the pair moves to \@theMark and the accessors become the kernel's own
(ltpage.dtx:167-174, 341-342, 356-357):

  \let\@leftmark\@FirstOfTwo              \let\@rightmark\@secondoftwo
  \def\@theMark{{}{}}
  \def\markboth#1#2{\protected@xdef\@theMark{{#1}{#2}}}
  \def\@markright#1#2#3{\@temptokena{#1}%
    \protected@xdef\@theMark{{\the\@temptokena}{#3}}}
  \def\markright#1{\expandafter\@markright\@theMark{#1}}
  \def\leftmark{\expandafter\@leftmark\@theMark\@empty\@empty}
  \def\rightmark{\expandafter\@rightmark\@theMark\@empty\@empty}

\markright keeps the LEFT half, which is why the kernel routes it through
\@markright rather than assigning both — and \ps@headings's \sectionmark IS a
\markright, so the wrong shape would wipe half the head at every section. The
two \@empty are the kernel's guard for a pair never set.

⛔ WHAT WAS WRONG WITH THE TESTS, not just with the code. Two tests probed
\gotex@rightmark — the STORAGE — so they were green for every document whose
class brings its own \markboth, which is the only case that was broken. They now
probe \rightmark, the name a page style reads. Two tests added:

  - a class's own \markboth (amsart's idiom verbatim in shape) must reach
    \leftmark/\rightmark — the test #426 needed;
  - \markright keeps the left half.

Run against the previous commit, which is the control a new test needs or it
proves nothing, they do NOT both fail — and the difference matters:

  class's own \markboth   FAILS, "[|]" — both halves empty. #426 reproduced.
  \markright keeps left   PASSES. The old private pair kept the left too,
                          since \markright wrote only \gotex@rightmark.

So the second one is not a regression test for this change; it is a guard that
the new \@markright shape — which destructures the pair and rebuilds it — did
not lose what the simpler assignment got right. Keeping it, labelled for what it
is, rather than letting it be counted as evidence.

Still NOT done, and unchanged by this: the pair is the single live one, where
the kernel reads \botmark and \firstmark so a head shows the mark of THAT page
(#727). amsart is immune to that difference by construction — it \@Gobbles
\sectionmark and friends (amsart.cls:344-346), so its head is set once from the
authors and the short title.

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

* the running mark pair lives under the name the classes write, \@theMark

#726 gave \pagestyle{headings} its band, its folio and its rule, and #426's own
witness still came out with an EMPTY head. The cause is the last link, and it is
a name:

  \leftmark / \rightmark read \gotex@leftmark / \gotex@rightmark, a PRIVATE pair
  that only this engine's own \markboth ever wrote.

A class may bring its own \markboth, and amsart.cls does — one of the four
classes this engine advertises running (texmf/amsart.cls:335-340):

  \def\markboth#1#2{\begingroup
    \@temptokena{{#1}{#2}}\xdef\@theMark{\the\@temptokena}%
    \mark{\the\@temptokena}\endgroup …}

It writes \@theMark, the kernel's name (ltpage.dtx:355 \def\@theMark{{}{}}), and
touches no private pair. Every other link already worked: \ps@headings does
\let\@mkboth\markboth (amsart.cls:318), amsart calls
\@mkboth{\@nx\shortauthors}{\@nx\shorttitle} (:622), the mark was set. Only the
read was looking elsewhere.

So the pair moves to \@theMark and the accessors become the kernel's own
(ltpage.dtx:167-174, 341-342, 356-357):

  \let\@leftmark\@FirstOfTwo              \let\@rightmark\@secondoftwo
  \def\@theMark{{}{}}
  \def\markboth#1#2{\protected@xdef\@theMark{{#1}{#2}}}
  \def\@markright#1#2#3{\@temptokena{#1}%
    \protected@xdef\@theMark{{\the\@temptokena}{#3}}}
  \def\markright#1{\expandafter\@markright\@theMark{#1}}
  \def\leftmark{\expandafter\@leftmark\@theMark\@empty\@empty}
  \def\rightmark{\expandafter\@rightmark\@theMark\@empty\@empty}

\markright keeps the LEFT half, which is why the kernel routes it through
\@markright rather than assigning both — and \ps@headings's \sectionmark IS a
\markright, so the wrong shape would wipe half the head at every section. The
two \@empty are the kernel's guard for a pair never set.

⛔ WHAT WAS WRONG WITH THE TESTS, not just with the code. Two tests probed
\gotex@rightmark — the STORAGE — so they were green for every document whose
class brings its own \markboth, which is the only case that was broken. They now
probe \rightmark, the name a page style reads. Two tests added:

  - a class's own \markboth (amsart's idiom verbatim in shape) must reach
    \leftmark/\rightmark — the test #426 needed;
  - \markright keeps the left half.

Run against the previous commit, which is the control a new test needs or it
proves nothing, they do NOT both fail — and the difference matters:

  class's own \markboth   FAILS, "[|]" — both halves empty. #426 reproduced.
  \markright keeps left   PASSES. The old private pair kept the left too,
                          since \markright wrote only \gotex@rightmark.

So the second one is not a regression test for this change; it is a guard that
the new \@markright shape — which destructures the pair and rebuilds it — did
not lose what the simpler assignment got right. Keeping it, labelled for what it
is, rather than letting it be counted as evidence.

Still NOT done, and unchanged by this: the pair is the single live one, where
the kernel reads \botmark and \firstmark so a head shows the mark of THAT page
(#727). amsart is immune to that difference by construction — it \@Gobbles
\sectionmark and friends (amsart.cls:344-346), so its head is set once from the
authors and the short title.

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

* marks travel with page breaking: \mark, \topmark, \firstmark, \botmark

#426's witness has its running head. It took four fixes, three of which were
right and insufficient, and the fourth is one line that threw the mark away.

  2111.13456 page 2, before:  y=98.99  "2"
                      after:  y=99.17  "A POSTERIORI ESTIMATION FOR
                                        MULTIPLE-NETWORK POROELASTICITY"  "2"

⛔⛔ THE LINE. amssubstrate.go carried `\def\mark#1{}` — a stub that DISCARDS its
argument — with the reason it stated: "page marks feed running heads the engine
does not build; drop the mark". True when written. It then survived every fix to
the chain above it: the band and the folio (#726), the page-style dispatch, and
the pair's name (#728). Each of those was correct, and each left the head empty,
because the mark was being dropped one layer below all of them.

A stub that discards its argument is the one shape no channel can see: the
document says what it wants, the engine says nothing, the suite stays green, and
the loss appears only as ink that is not on the page. The measurement harness has
a section about exactly this trap ("the blind spot no channel has"), and it still
cost 27 of the 128 corpus papers with a reference their head, through three
rounds of fixing the wrong layer.

WHAT IS IMPLEMENTED, from tex.web:

  \mark{…}  a node on the vertical list (markNode), the argument EXPANDED at
            mark time — scan_toks(false,true). Not a detail: amsart writes
            \@temptokena{{#1}{#2}}…\mark{\the\@temptokena}, so an unexpanded
            mark would store "\the\@temptokena" and the head would read \the.
            It travels like pageStyleNode, for the same reason: at mark time
            nothing knows which page it lands on.

  \topmark / \firstmark / \botmark  republished before each page's head is
            built, from §1012's arithmetic (:19718-19729, :19782-19789):

              if bot<>null then top:=bot; first:=null
              walking the page: if first=null then first:=p;  bot:=p
              if top<>null and first=null then first:=top

            Two consequences a plainer reading misses, and both are what a head
            depends on: bot is NOT cleared for a page with no marks, so a head
            set once at \maketitle stays on every later page; and first falls
            back to top, so a page broken mid-section reports the mark in force
            at its own top.

            They are published in assemblePage, which every page passes through,
            BEFORE anything draws a head — a head expands \topmark/\botmark
            while the page is assembled (amsart.cls:325-326), so values set
            after it would be one page late. tex.web updates them at the top of
            fire_up for the same reason.

\splitfirstmark / \splitbotmark belong to \vsplit and are not here.

Tests: the node reaches the vertical list (it did not, and that is how the stub
was found — the arithmetic was already right while the node never arrived); and
the three-page arithmetic above, including the markless page that keeps the
previous bot.

⛔ THE CORPUS SWEEP IS DEFERRED, NOT RUN: 1-minute load average 20.05 against a
ceiling of ~8. This change adds ink to pages without changing their count, so
the channel that can see it is `hashdiff`, not Σ — and a render that times out
under load would report a page count that is simply wrong. It runs behind
`loadwait` and the numbers go on the pull request.

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

* a mark is type 4, so a break may be taken after it (tex.web:3109)

2405.05720 went 9 pages -> 10 with the ink IDENTICAL on both sides (23282), against a reference of 9: the one paper the engine had exactly right, lost. Same content, one more page, because the glue after a mark had stopped being a legal breakpoint -- precedesBreak answered false for markNode, while precedes_break(#) == (type(#) < math_node) is true for mark 4, which the comment above that very function already listed.

Sigma 272 -> 273 and exact 47 -> 46 for that one paper. 'A mark carries no dimension, so no page can change height' was written on #729 before the sweep ran: true, and beside the point. Having no dimension is a different claim from having no effect on where a page MAY break.

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

* a \mark in the PREAMBLE is read and dropped (2405.05720: 10 pages -> 9)

The paper the marks cost its exact match, found by the corpus and fixed by experiment rather than by the mechanism I first proposed. ws-fnl.cls:804 carries a bare \mark{{}{}} at class level, OUTSIDE the document body, and 2405.05720 uses that class. Contributed there, it is material on a page that does not exist yet: 9 pages became 10 with the ink IDENTICAL on both sides (23282 glyph units) against a reference of 9. Dropping the preamble's mark returns it to 9, measured on that paper.

The argument is still SCANNED, so its tokens are consumed exactly as they would be inside the body; only the node is withheld. Nothing in the preamble is typeset (see inBody).

⛔ And the previous commit, which made precedesBreak answer true for a markNode, FIXED NOTHING: the re-sweep came back 273 and 46, byte-for-byte what it was. It is kept because tex.web:3109 says a mark precedes a break (type 4 < 9) and the engine should agree -- not because it repaired that paper. Its comment now says so where the line is, instead of claiming the measurement that refuted it.

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 Nov 16, 2026
… its text

The other half of #691's measured list. ltsect.dtx:483-493, \@xsect's
display-heading branch, verbatim:

	\ifdim \@tempskipa>\z@
	    \par \nobreak
	    \vskip \@tempskipa
	    \@afterheading

That \nobreak is a \penalty 10000 on the VERTICAL list, between the heading's
\par and its afterskip, and it is what forbids a page break between a heading
and the first line of its text. The reference's list is hbox(heading),
\penalty 10000, \glue 9.913(afterskip); ours had the box and the glue with
nothing between them.

Measured, same witness as the \@secpenalty half:

	before   [-300 -10000]
	after    [-300 10000 -10000]

⚠ The POSITIVE branch only. When the afterskip is negative the heading runs in
beside its text and the reference takes the else branch, which sets
\@nobreakfalse — there is no vertical break to forbid because there is no
vertical space.

⚠ The test asserts 10000 and not merely "some positive penalty": 10000 is \@m,
TeX's never-break-here, and a smaller positive number would only discourage the
break, which is not what the reference says.

⛔ AND IT TURNED AN EXISTING TEST RED, WHICH WAS RIGHT OF IT.
TestGxheadEndsTheHeadingParagraphInsideTheGroup compared the WHOLE line
(\noindent{#1 #2\par}\vskip\@tempskipa) to protect one invariant: the \par
belongs INSIDE the style group, worth 5.978pt per heading. Inserting \nobreak
between the group and the \vskip respects that invariant exactly and still broke
the literal match. The two patterns now cover the group and its \par alone, so
what follows is free; MUTATED to prove the relaxation did not gut it — moving
the brace to \noindent{#1 #2}\par reddens BOTH of its assertions.

Co-Authored-By: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 16, 2026
…after it (#802)

* a heading carries \@secpenalty, so a page can break where a reader would break it

#691 measured it with \showlists on `Avant.\section{Titre}Texte.`: the reference
opens with \penalty -300 and we opened with the beforeskip glue. A heading
contributed NO penalty node at all, so the page builder had no reason to prefer
the break a reader would choose — above the heading — over one two lines into
its text.

THREE PIECES, each from the source, and any one of them alone would have been
silent:

  1. \addpenalty was `\def\addpenalty#1{}`, an empty no-op. Ported whole from
     ltspace.dtx:992-1051, including the \prevdepth adjustment of its second
     branch, rather than reduced to the branch a \section happens to take.
  2. \@secpenalty was DECLARED and never assigned, so it held 0.
     ltsect.dtx:229-230 assigns -300. ⛔ A \penalty 0 is not a weaker version of
     the reference's: 0 means "no preference", which is what a list with no
     penalty node already said.
  3. \@startsection never called it. ltsect.dtx:331 is
     \addpenalty\@secpenalty\addvspace\@tempskipa, and the penalty goes BEFORE
     the space — the order the reference's own list shows.

\@SecT and \@ssect get the same line. They are NOT reached through
\@startsection here (it goes via \@GXSEC), so a class calling LaTeX's
continuations directly would otherwise keep the old silence, and adding it in
both places cannot double the penalty.

⭐ THE SECOND BRANCH OF \addpenalty IS NOT THE ONE A \section TAKES, and knowing
that is why this was worth porting whole: \addpenalty runs BEFORE \addvspace, so
the list carries no skip yet, \lastskip is 0, and the plain `\penalty#1\relax`
is what fires. The glue-reinsertion branch exists for a penalty added AFTER a
skip, where TeX must place it before the glue without the \prevdepth correction
leaking into the skip the list keeps.

⚠ THE SPACE IS DELIBERATELY STILL A \vskip, not the reference's \addvspace.
\addvspace takes the MAXIMUM of adjacent skips where \vskip adds them; that
moves the corpus on its own and it is #690, which has its own pull request and
its own measured regression. One defect per change.

⚠ And one stated difference in \addpenalty itself: \@LRmoderr does not exist
here, so restricted horizontal mode takes the same \par as outer horizontal
mode instead of an error — more permissive than the reference, never less.

MUTATION, on the piece that would have been invisible: removing the -300
assignment leaves the test reporting `[0 -10000]` instead of `[-300 -10000]` —
a penalty that is present and says nothing. The witness asserts the NODE rather
than a page count, because -300 moves pagination only when it competes with
another candidate, so a count-based witness would pass on a document that never
breaks.

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

* and \nobreak after the heading, so a page cannot break between it and its text

The other half of #691's measured list. ltsect.dtx:483-493, \@xsect's
display-heading branch, verbatim:

	\ifdim \@tempskipa>\z@
	    \par \nobreak
	    \vskip \@tempskipa
	    \@afterheading

That \nobreak is a \penalty 10000 on the VERTICAL list, between the heading's
\par and its afterskip, and it is what forbids a page break between a heading
and the first line of its text. The reference's list is hbox(heading),
\penalty 10000, \glue 9.913(afterskip); ours had the box and the glue with
nothing between them.

Measured, same witness as the \@secpenalty half:

	before   [-300 -10000]
	after    [-300 10000 -10000]

⚠ The POSITIVE branch only. When the afterskip is negative the heading runs in
beside its text and the reference takes the else branch, which sets
\@nobreakfalse — there is no vertical break to forbid because there is no
vertical space.

⚠ The test asserts 10000 and not merely "some positive penalty": 10000 is \@m,
TeX's never-break-here, and a smaller positive number would only discourage the
break, which is not what the reference says.

⛔ AND IT TURNED AN EXISTING TEST RED, WHICH WAS RIGHT OF IT.
TestGxheadEndsTheHeadingParagraphInsideTheGroup compared the WHOLE line
(\noindent{#1 #2\par}\vskip\@tempskipa) to protect one invariant: the \par
belongs INSIDE the style group, worth 5.978pt per heading. Inserting \nobreak
between the group and the \vskip respects that invariant exactly and still broke
the literal match. The two patterns now cover the group and its \par alone, so
what follows is free; MUTATED to prove the relaxation did not gut it — moving
the brace to \noindent{#1 #2}\par reddens BOTH of its assertions.

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 Nov 18, 2026
…em (#837)

\@gxhead's body read

	\noindent{#1 #2}\hskip-\@tempskipa
	\noindent{#1 #2\par}\nobreak\vskip\@tempskipa

and the space between #1 and #2 is a real space TOKEN: #1 is a parameter,
not a control word, so nothing absorbs it. Expanded in horizontal mode at
the very start of the heading it became interword glue, and every
sectioning heading in every document began that far right of the margin.

LaTeX has no such space — ltsect.dtx:418 is
\@hangfrom{\hskip #3\relax\@svsec}.

Measured against tectonic, leftmost glyph in points from the page edge:

	heading           font    reference   before   after
	\section          14.35   133.77      140.95   133.77
	\subsection       11.96   133.77      139.75   133.77
	\subsubsection     9.96   133.77      138.86   133.77
	body lines         9.96   133.77      133.77   133.77

The right edges land with them — 185.66/185.67, 190.40/190.41,
206.51/206.51 — so the whole line is in place and not merely its start.
The offset scaled with the heading's font, which is what a stray
interword space does and what a fixed indent would not.

⛔ TestGxheadEndsTheHeadingParagraphInsideTheGroup went red on this, and
it was the TEST that was wrong: it matched the literal
`\noindent{#1 #2\par}`, so it pinned the stray space as if it were part
of the invariant. That invariant is the PLACE OF THE BRACE — the \par
inside the style group — and its patterns now name only that. This is the
second drift of that literal; the first was when \nobreak was inserted
between the group and the \vskip, which its own comment records.

The new test guards both branches of \@gxhead and carries a control: a
"fix" that deleted the braces rather than the space would pass the two
refusing rows and set every heading in body type.

⚠ Still missing and deliberately not fixed here: \@startsection's INDENT
argument. LaTeX passes it (\hskip #3 above); \@gxhead is handed only
{style}{title}{afterskip} and never sees it. It is \z@ in every standard
class, so nothing in the corpus moves, but a class that indents its
headings is unobeyed.

Refs #833, Refs #716.

Co-authored-by: Claude Opus 5 <[email protected]>
tannevaled added a commit that referenced this pull request Nov 21, 2026
* \/ is the glyph's italic correction, and \textXX ends with one

\/ was \def\/{} ("a zero-width adjustment the engine does not need") and the
\text… commands were {#2#1}, so every italic word followed by upright text was
set short of the reference: tectonic sets \textit{f} 4.52pt wide, this engine
3.07pt.

\/ is now a primitive, tex.web §1113 append_italic_correction: when the current
list ends in a character, append a kern of that character's correction in its
own font. For an OpenType face the correction is XeTeX's —
XeTeXFontInst::getGlyphItalCorr, rval = bbox.xMax - width when the glyph box
reaches past the advance, else 0 — since such a font carries none outside its
MATH table.

The text commands are the kernel's \DeclareTextFontCommand (LaTeX 2021-11-15,
the meanings tectonic prints): \text@command, \check@nocorr@, \maybe@ic,
\t@st@ic, \sw@slant, \fix@penalty, \nocorrlist, \nocorr. \check@icr runs
\maybe@ic after the group, so a following "," or "." suppresses it and a skip or
penalty at the end of the text is lifted off and put back. \lastpenalty
(tex.web §424) is added for \fix@penalty. \textup, \textmd and \textnormal,
identities in the amsart layer, are declared the same way — \textup{\itshape f}
was set upright.

The kernel's text commands branch on \ifmmode, which was false everywhere,
including while flattenMathBody expands a macro body for the maths layer. A
formula reaching \codefontify{…} through \codify took the text branch, and
\text@command's \edef cost it the formula
(TestMathKeepsAFormulaWhoseMacroHidesAFontSwitch went red). \ifmmode is now
true during that flattening: the body is maths-mode material, and the maths
branch {#2##1} is what this engine had before. The same line is its own fix on
main, for \ensuremath (a separate pull request); the hunk is identical in both.

The text commands are \protected. LaTeX declares them robust, and
\protected@edef is a plain \edef in this engine, so without the prefix
\textit{…} expanded inside a mark's \edef into \text@command's own \edef and
\futurelet. sn-jnl.cls:486 writes \markboth{\textit{\s@title}}{…}: the corpus
comparison showed 2209.13768 losing its running head and page number on all
24 pages. With \protected its text is word-for-word main's again, and
TestATextCommandInARunningHeadReachesTheHead pins it.

\fontcharic answers the same correction (it was 0, "so the two agree" —
true only while \/ was also 0): tectonic gives 0.50998pt for an upright f,
1.44998pt for an italic one. And \the\fontcharht/wd/dp/ic expands inside
\typeout, \edef and \write; \the had no case for them and passed the tokens
through unexpanded.

testdata/parity/italcorr.tex, 34 rows, each tectonic's value to 0.005pt.
Before, \nocorr was undefined and the file aborted at its first use; without
those 3 rows, 18 of the other 27 differed. Among them (before = measured with
the parent commit's build):

  row                     tectonic   before
  {\itshape f\/}          4.52       3.07
  f\/                     3.57       3.06
  \textit{f}              4.52       3.07
  \textit{f}.             5.85       5.85   (\nocorrlist)
  \textit{f} x            13.13      11.68
  \textit{f\hskip2pt}x    11.80      10.35  (\sw@slant)
  \textit{f\nocorr}       3.07       undefined \nocorr
  \textbf{f}              4.37       3.51
  \textup{\itshape f}     4.52       3.07

FreeType's box is the CONTROL box, and a slanted glyph's control points reach
past its curve: read from the flattened outline \textsl{f} was 4.64pt against
tectonic's 4.69. The box comes from Face.GlyphControlBox (go-opentype v0.24.0,
go-opentype/opentype#80, exact against \XeTeXglyphbounds), and \textsl{f} is
now 4.69. Not reached: \textsf{f} is set in the roman — the missing sans
family, not this.

Break-checked with mutate, 9 of 9 caught: the correction zero, \/ appending
nothing, \lastpenalty reading 0, no correction after the group, \nocorrlist
empty, the skip not lifted, a trailing \nocorr ignored, \fontcharic zero,
\the skipping the glyph metrics.

Stacked on the \fontsize branch.

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

* Test the guards of the italic correction

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Report a missing guard as a failure, not a panic

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Drop the go.sum entries of opentype v0.22.0

go mod tidy: go.mod requires v0.24.0.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.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