engine

package module
v0.311.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: BSD-3-Clause Imports: 33 Imported by: 4 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

engine — go-tex

License Go status

A pure-Go (no cgo) TeX engine aimed at functional parity with a TeX distribution, not a subset. It is a faithful re-implementation of TeX — the category-code tokenizer, the equivalents table (eqtb) with grouping/scoping, macro definition with delimited parameters and the full expansion machinery (the mouth and gullet); a scaled-point box/glue/penalty stomach with Knuth–Plass line breaking and a cost-based page builder; math via go-tex/math; OpenType fonts; and PDF + SVG output — and on top of it, it loads and runs the genuine LaTeX classes: \documentclass{article}, {report} and {book} execute the real, embedded .cls files, in native builds and in the browser (js/wasm), with no TeXLive.

It is developed the way parity is actually reachable — reimplement the engine faithfully, gated by objective oracles — then run the real LaTeX classes and packages on it (they are TeX macros). Two gates hold the line: the conformance ratchet (TestConformance, TeX snippets checked byte-for-byte against real-TeX output) and a fidelity check that compares whole-document prose against a real LaTeX engine (tectonic).

Working today (verified, faithful)

  • Category-code tokenizer — full catcode table, comments, control words/symbols.
  • Macros — \def (undelimited, delimited, and grouped parameters, with backtracking on partial delimiter matches), \edef/\gdef/\xdef, \let (to macros, primitives, undefined, and character tokens), \global.
  • Expansion — \expandafter, \csname/\endcsname, \noexpand, \string, \the, \number, \romannumeral, \meaning, \uppercase/\lowercase.
  • Conditionals — \if, \ifnum, \ifx, \ifcat, \ifodd, \ifcase, \iftrue/\iffalse, with \else/\or/\fi and nesting.
  • Registers & arithmetic — \count, \advance, \multiply, \chardef, \catcode, read via \the/\count; TeX's own number syntaxes in any numeric slot ("FF, '17, `A) and the glyph metrics \fontcharht/\fontchardp/\fontcharwd/\fontcharic, which are internal dimensions wherever one is read. \showthe prints what \the would give, on a diagnostic stream of its own (Diagnostics.Shows, and gotex writes it unconditionally): TeX sends \message to the log and the terminal but \showthe to the terminal, and folding the two together makes a document's own diagnostics indistinguishable from its output. The shape is print_nl("> "); token_show(…) (tex.web 23721-23725) followed by error, and the trailing full stop is error's own first act (print_char("."), 1883-1884) — not part of the value.
  • Grouping — {…}, \begingroup/\endgroup, save/restore of meanings, registers, and catcodes; \global escapes the current group.
  • Registers — \count, \dimen, \skip and \box, 32768 of each kind, which is eTeX's register file and not TeX82's 256. Packages written against eTeX allocate accordingly: the real tikz and calc together leave 86 of 256 \count registers free, and a package-heavy paper spends those before its own \newtheorem counters are declared. The pools are grown on demand, so a document that stays inside TeX82's range costs what it always did. An index no pool can hold — negative, or at least 32768 — is refused rather than allocated, and counted in Diagnostics.RegistersOutOfRange.

Faithfulness is checked on subtleties only real TeX gets right (a control word absorbing its following space; significant spaces in conditional branches).

out, _ := engine.New().Run(`\def\twice#1{#1#1}\message{\twice{\twice A}}`)
// out == "AAAA"

Real-world documents (lenient mode)

A real third-party paper pulls in classes, packages, fonts, figures and .bib files that a from-scratch engine does not carry. Strict mode aborts on the first such gap (as TeX does). Lenient mode (gotex -lenient, or Options{Lenient: true}) turns those gaps into best-effort no-ops so an editor preview shows the typesettable content instead of one hard error:

  • an undefined command is skipped, along with its likely [opt]{arg} block; ⛔ "likely" is the catch, and it is why a command that takes an argument is worth defining even when its effect is not implemented: \marginpar was undefined, and in lenient mode its argument reached the page as ordinary text — AVANTUN\marginpar{NOTEUN}APRESUN set AVANTUNNOTEUNAPRESUN, and the optional form set the first argument with its brackets, where tectonic puts AVANTUNAPRESUN and the note out in the margin. It is now defined and reads both arguments (ltfloat.dtx 951-967, 973-985), so the body text matches the reference exactly; placing the note in the margin needs \vadjust (#665) and is still missing;

  • an unloadable figure becomes a framed placeholder of the requested size (this includes a raster figure above 40 megapixels, see below);

  • a math macro go-tex/math doesn't know drops that one equation;

  • a \setlength on an unmodelled length, and a missing \input/\bibliography/ \font file, are ignored.

Raster figures above 40 megapixels. \includegraphics decodes a PNG, JPEG, GIF, WEBP, TIFF, BMP, ICNS or ICO figure through go-gfx/gfx, which since v0.37.0 refuses an image of more than codec.DefaultMaxPixels (40 million pixels, width times height) from its header, before allocating anything: the size is read from the file, and a compressed format describes a huge image in a few bytes. Such a figure fails with an error wrapping codec.ErrTooLarge: in strict mode the compile stops (includegraphics <name>: …), in lenient mode it becomes the framed placeholder above and is recorded as a dropped figure. There is no option to raise the ceiling; downscale the figure.

PDF figures. \includegraphics of a .pdf (with page=N for a later page) is embedded in the PDF output as a Form XObject through go-pdfkit/pdfkit, as pdfTeX and XeTeX do, so it stays vector and its text stays selectable; a page past the end is an error in strict mode and an empty box in lenient mode.

Every skipped construct is tallied ((*Engine).SkippedCommands) so a caller can report what was dropped. Diagnostics also records the paths the document read from outside its own directory — an absolute path, or one that walked out with ../, excluding the search directories the host itself configured. Reading a named file is what \input is for and it is not an error, but a service compiling a document it did not write is the one who can judge it, and nothing else in this package will tell it.

Two register tallies sit beside those, and they are different facts. Diagnostics.RegistersExhausted counts allocations this engine refused because that pool is full — the name a \newcount could not satisfy stays undefined, whatever used it reads 0 or vanishes, and the run completes normally, where TeX stops with "No room for a new \count". Diagnostics.RegistersOutOfRange counts a document naming a register number that cannot exist, which TeX answers with "Bad register code"; a read gives the zero value and a write is dropped. A register inside the pool that nothing has written is neither: it legitimately holds 0, 0pt, zero glue or a void box.

Diagnostics.KerningIsAFloor says a face was used whose kerning this engine cannot fully read, so the compile's kern figures are a floor and not a measurement. The kern is asked for a pair of glyphs, and GPOS lookup types 7 and 8 position pairs contextually — matched against the glyphs around a position, which a pair cannot carry — so those adjustments come back as 0, the same 0 a font gives for a pair it deliberately leaves alone. Measured over the 81 fonts go-opentype/fonts bundles, 8 carry such lookups (seven complex-script Noto faces and notosans.ttf, a general Latin sans), so this is neither rare nor exotic. It does not claim any kern was wrong; it says the figure is a floor, which is the distinction a fidelity measurement needs and did not have (#716).

On a 1000-source arXiv sweep (measure trunc, re-measured 2026-10-19), strict mode compiles almost none end-to-end — each hits a package command in the preamble — while lenient mode flags 64 sources, and the engine's two alarms do not say the same thing:

sources
runaway guard tripped, alone 2
groups still open at end of document, alone 58
both 4
either 64
rendered as a SINGLE page 1

An aborted loop has lost content; groups left open may be only a leak — seven papers measured the same day carry that alarm and render 14 to 42 pages, and one leaves 20 groups open over 17 pages. The number that is not a suspicion is the last row, and it is one source in a thousand (2607.05497, aas.cls, tracked in #625). The same sweep counted twelve when the series began, and #517 records each one's diagnosis.

It is a preview aid, not a fidelity claim — the roadmap below is how the gaps close for real.

Loading real classes and packages

\documentclass and \usepackage (and \RequirePackage, \LoadClass, \LoadClassWithOptions) do more than emulate: they resolve and load the real .cls/.sty — from the document's own directory (an arXiv paper's bundled class/package), a TEXINPUTS/GOTEX_TEXMF search path, or an embedded base set — making @ a letter and running the file's own \newcommand/\def/… on the engine. The LaTeX2e option mechanism runs too: \DeclareOption, \DeclareOption*, \ProcessOptions, \ExecuteOptions, \CurrentOption, \PassOptionsToPackage/\PassOptionsToClass, plus \IfFileExists/ \InputIfFileExists. A file loads tolerantly — a command the engine lacks is skipped, so a real class contributes what it can — and a runaway-expansion guard bounds macro expansion so a pathological or partially-supported file can never hang (it stops with partial output in lenient mode, an error in strict).

⛔ That guard has two ceilings, and which one stops a document says something different about it. The no-progress ceiling measures TeX-style forward progress — expansion steps taken while the mouth reads no new input — and a self-referential macro crosses it in under half a second. The absolute one is a coarse backstop on total steps, and its old comment, "a large real document stays well under it", is false for a figure-heavy paper: one tikzDevice picture (R's output — 489 KB, thousands of coordinates, each through pgfmath) spends tens of millions of steps inside a single \path, with the input advancing the whole way. Measured on arXiv 2405.11065 with the real pgf sources: it takes 106 315 622 expansion steps — against a 60M ceiling, so 7 pages of 18 and a report of a possible loop; with Options.StepLimit: engine.StepLimitHeavy (600M), which gotex now passes beside NoProgressLimitHeavy, all 18 and no trip. Its longest run reading no new input is 3 117 166, six times under the no-progress ceiling, which it never approached — the document advanced the whole way and simply needed more budget. Raising the no-progress ceiling twentyfold changes nothing on that paper — it stops at the same byte with the same seven pages, which is the wrong turn #360 recorded for seven weeks.

So the report carries its evidence instead of a verdict: both counters, the ceiling reached, and the two readings of it, because the engine cannot tell them apart — a legitimate \path and a loop both spend millions of steps reading no input. What does tell them apart is raising the ceilings: a loop stops at the same place however high they go. GOTEX_TRACE=1 prints the margin to each ceiling on every compile, including one that succeeds, since a margin is only useful before it is crossed. Raising the absolute ceiling does not slow a loop down: the no-progress ceiling still catches one first, which TestALoopIsStillCaughtByTheNoProgressCeilingAtShippedLimits holds. Distribution-heavy packages the engine emulates natively or better as stubs (geometry, tikz, hyperref, graphicx, encodings, …) are not loaded from disk.

The standard base classes run for real. \documentclass{article}, {report} and {book} load and execute the genuine, embedded LaTeX classes (article.cls/report.cls/book.cls + their size option files, LPPL, verbatim) — not an emulation. Everything they need is in place: the LaTeX2e kernel helpers, a class-kernel substrate (constants, registers, \if@ flags, NFSS font-switch aliases), \newcommand*/\DeclareOldFontCommand, the rubber-glue and <factor><internal-dimen> length scanner, numbered \@startsection with \@tocentry, \secdef via \@dblarg (so \chapter works), \@float figure/table captions, \@starttoc bridged to the engine's two-pass contents table, \addcontentsline bridged to it as well — \chapter and \part are the two entries no \@startsection records, which is why a book's contents list used to have no chapters in it — and — the keystone — stable source lines (loading a 644-line class no longer shifts the line numbers the editor maps glyphs back to). A real \documentclass{article} document typesets a numbered title, a \tableofcontents shaped by the loaded class's own \l@… macros — the indent and number-box widths are read out of its \@dottedtocline calls, so article's leaderless bold \l@section and book's dotted one at the very same level come out differently, and the leader tiles \@dotsep rather than \dotfill's narrower box — numbered sections, and numbered figure/table captions, and it reproduces the reference engine's prose on the fidelity gate. Because the class files are go:embeded and the resolver needs no filesystem, the real classes also run in the js/wasm build — genuine LaTeX class rendering in the browser, with no TeXLive and no server. amsart now joins them: \documentclass{amsart} loads the real embedded amsart.cls and typesets its own title, sections and theorem heads (its \maketitle drove real token-register support — \toks/ \newtoks — into the engine, and its \newtheorem…[section] machinery, which used to loop, runs through the class-kernel substrate's counter hooks). GOTEX_AMSART=0 forces the old emulation back, for comparing the two paths.

Supported classes & packages, at a glance

The full, honest matrix — every supported class, package, primitive, output format and image type, with its status, plus every remaining gap — lives at go-tex.github.io/docs. In short:

  • Classes (real embedded): article, report, book, amsart. beamer runs its real class when resolvable, and its headline and footline (like any fancyhdr/class running head or foot) now carry their text — section names, author, title, frame numbers — typeset in the body's local state at shipout (v0.306.0); still open: per-page counters in heads (see #973), errors in a head swallowed in strict mode (see #974), navigation symbols and mini-frame dots not drawn (see #975), head text about 1.2× wider than tectonic (see #976). revtex4-x, acmart, IEEEtran, elsarticle and the aastex6x family fall back to content-preserving emulation. Any other resolvable .cls is loaded and run as real TeX.

  • Packages with native handling: amsmath (equation/align/gather/multline/…), amssymb, amsthm, thmtools (\declaretheorem, including its comma list of names and both of its counter keys), graphicx, xcolor, hyperref, geometry, fancyhdr (and the class page styles beside it: a \thispagestyle{plain} page — every chapter opening in a book or report, and the first page of its contents list — keeps its folio centred at the foot even though the class declared a running head for the whole document; and the running head itself now carries its own page's mark, because \mark travels with page breaking and \topmark/\firstmark/\botmark are maintained per page as tex.web §1012 maintains them, so a head that tracks sections names the section the reader is in rather than the document's last one), setspace, enumitem, multicols, booktabs/multirow/tabularx, subcaption, algorithm/algorithmic, listings (caption=, label= and captionpos=, so a listing is numbered, captioned and referable; and basicstyle= through \lstset, \lstdefinestyle and style=, so code set at \footnotesize or \scriptsize takes the room it takes in the reference), minted, siunitx, cleveref (\cref/\Cref with cleveref's own default naming, its capitalise and noabbrev options, \crefname/\Crefname and \crefformat), caption's \captionsetup{name=}, longtable, url, paragraph columns (p{}, with m/b treated as p), numprint, makeidx, verbatim, BibTeX. Any other resolvable .sty runs as real TeX macros through the full LaTeX2e option mechanism.

  • Opt-in and working: PDF-figure rasterization. GOTEX_PDFRENDER=1 wires go-tex/pdfrender into the CLI and a vector .pdf figure typesets as a real raster instead of a framed placeholder — measured on one corpus paper, 21 figures reported as empty boxes become 0. It is off by default so the engine core, and the js/wasm build with it, carries no PDF renderer.

  • Partly: biblatex. Biber's data .bbl is parsed and its entries are typeset — on the two corpus papers that ship one, 30 of 30 and 15 of 17 titles are present and no raw field data reaches the page. Its citation commands are not there: \textcite, \parencite, \autocite, \footcite and \smartcite are undefined and print the bare key, and the citation and bibliography styles are not modelled.

  • The front matter stays on the sheet. A vertical block that should fill a title page — an author/affiliation list, an abstract — used to be emitted as one horizontal list that was never line-broken, so everything past the right margin was drawn off the paper: measured at up to x=6619pt on a 612pt sheet, with author names, affiliations and e-mails outside it. No other channel can see that — the page count cannot (the clearest witness is 15 pages against 15), the ink count cannot (every glyph is emitted), -report-skipped cannot (nothing is skipped) and the text layer carries the words. Seven distinct causes, each with its own witness: a macro standing for several tabular rows (article.cls sets the author block as \begin{tabular}[t]{c}\@author\end{tabular} and authblk builds \@author with \\), a bare \endX closing what \X opened (sagej.cls writes \def\endabstract{\endminipage\endlrbox}), calc expressions in a length argument ({\textwidth-57.625mm}), \cite's optional note, \unvbox inside a paragraph — a vbox holds finished lines, and handing them to the line breaker glues them end to end and re-breaks the lot as one paragraph (acmart writes \noindent\unvbox\mktitle@bx, so its title and every author block came out as a single line) — \maketitle never running the class's own \@maketitle, which left \@author in a \centerline no line breaker touches, and a package whose key-list commands were undefined and left their keys behind (mdframed, caption).

    Over the 154-paper corpus 21 papers still draw text past their own page edge in their first two pages, the widest line at 1281pt, against a floor of 0 on the reference PDFs themselves. ⚠ That floor is 0 and not 2 because the instrument changed: it lives in the measure harness now (measure offpage) and filters text the PDF reader surfaces but that was never typeset — a /Title string's octal escapes, hyperref's PostScript specials, pdfmark attributes, burl's PostScript definitions. Unfiltered the reference itself reports 12, one of them at x=5135. The earlier series — 49 at v0.260.0, 23 at v0.261.0 — was taken with a filter that left 2 there, so it is not directly comparable to these. ⚠ Not closed: 21 remain, and the top of that list is a different population again (see #629).

  • Float placement takes its seven parameters from the class, not from article's: \topnumber, \bottomnumber and \totalnumber are counters the class kernel declares so a \setcounter of them takes (amsart's \setcounter{topnumber}{4} used to be a no-op on an undeclared counter), and \topfraction, \bottomfraction, \textfraction and \floatpagefraction are read from their macros. Measured against the reference on forty figures in amsart prose: four floats to a page on both sides, 11 pages each, where article's hardcoded values gave three and 14.

  • Primitives and registers (v0.290.0–v0.291.0). \halign copies its preamble unexpanded and runs its entries live, as tex.web §782-791 does: \def\a{OLD}\halign{#\cr \def\a{NEW}\a\cr} typesets NEW (it used to print OLD, #602), a \gdef in a cell reaches the next one, IEEEtran's {\ifnum0=}\fi … \ifnum0={\fi}\cr brace trick ends an entry from inside a group, and \halign\bgroup opens an alignment. tabular and the maths alignments keep their own collect-then-build shape. \leaders, \cleaders and \xleaders are real primitives with a box or rule tile in the aligned, centred and expanded modes of §626-628, in both the SVG and the PDF painter (vertical leaders keep the glue's space and paint nothing). \c@page is a real count register, \count0: \the\c@page and \advance\c@page work, \stepcounter{page} works, and a header or footer can ask \ifodd\c@page. \DeclareUnicodeCharacter makes the character active with the text as its meaning, and the catcode table is sparse past 255 so a character beyond the old 256 entries can be made active.

  • Page geometry (v0.290.0–v0.291.0). \restoregeometry returns to the layout \begin{document} found and, like \newgeometry, starts with a \clearpage (mdpi.cls stayed on its title-page geometry for the whole body before). The twocolumn and onecolumn keys set \@twocolumn, so sn-jnl's iicol option takes the two-column \maketitle branch. With none of margin, body, margin fixed in a direction, geometry takes its default body, 0.7 of the paper, and splits the margins 1:1 horizontally and 2:3 vertically, and \oddsidemargin, \evensidemargin and \topmargin follow. a4 is emulated (the text block per base size, the two-side even margin and widemargins) because its licence only allows distribution with the NTG classes; a4wide is bundled and reaches it through \RequirePackage{a4}. ⚠ The page grid is still one layout per run, so pages before a \restoregeometry take the restored height and margins; the measure after it, and the pages that follow, are exact.

  • Packages (v0.290.0–v0.291.0). eso-pic's \AddToShipoutPicture family draws at the paper's lower-left corner, behind (BG) or over (FG, plain) the body, on every later page, or on that page only for the starred form; \ClearShipoutPicture empties the list. setspace single-spaces floats and footnotes as setspace.sty does, so \baselinestretch reaches the body and not the rows of a table or the lines of a note. titlesec's \titleformat and \titlespacing are recorded and read by \@startsection, instead of being gobbled. manyfoot's \DeclareNewFootnote declares each class with its counter, numbering style and \footnoteA, \footnotemarkA, \footnotetextA. algorithm2e keeps its block commands (\If, \For, \While, …) and numbers its lines under linesnumbered. \tableofcontents honours tocdepth. comment's \specialcomment declares an environment (comment.sty itself is not embedded: GPL). xstring's \IfInteger and \IfDecimal pick one branch. -report-skipped now lists the packages that had no .sty to load.

  • Classes and fonts (v0.290.0–v0.291.0). elsarticle is still an emulation, but its front matter is placed: \ead, \journal, \cortext, \fntext, \tnotetext, \tnoteref, \fnref, \corref, \cormark, \address and \affiliation no longer leak into the body, and \maketitle sets title, authors, affiliations, abstract, keywords, the footnote block and the preprint footer. acmart titles are Linux Biolinum (the sans family follows series and shape) and \texttt is Inconsolata through zi4/inconsolata (0.5em per character, where Latin Modern Mono is 0.525em).

  • Font sizes and classes (v0.299.0–v0.300.0). \fontsize and \@setfontsize read any TeX unit (pt, bp, mm, cm, in, pc, dd, cc, sp), as \set@fontsize does by scanning a whole <dimen>; em and ex stay refused because they depend on the font. A class that restates \@setfontsize\normalsize{10bp}{12bp} makes that the body size and the size table is rebased on it (springer's sn-jnl over \LoadClass[11pt]{article} used to keep the 11pt body). \PassOptionsToClass and \PassOptionsToPackage expand their option argument, so elsarticle's \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}} forwards 12pt and a 12pt document stays 12pt. authblk's \author[marks]{name} accumulates (“A, B, and C”, marks as superscripts) and \affil is set in \Affilfont (before, the last author replaced the others). elsarticle's \tnotemark and title-note footnotes print the class's star ($\star$, $\star\star$) and no longer U+2217. The sans bold, oblique and bold oblique of Latin Modern are bound (\textsf{\textbf{x}}, \textsf{\textit{x}}), with the optical sizes of tulmss.fd.

  • Pages and geometry (v0.299.0–v0.300.0). \setcounter{page}{n} and \pagenumbering{style} change the printed folio: \setcounter{page}{5} then \pagenumbering{roman} and \pagenumbering{arabic} print 1 5 6 i ii 1 2, as tectonic does (they used to count 1 2 3 …). geometry takes the options \PassOptionsToPackage queued for it (acl.sty's a4paper,margin=2.5cm,heightrounded=true), reads heightrounded=true|false in key form, and one margin beside a body no longer cancels the body, so \newgeometry{textheight=9in,top=1in,…} keeps its 9in. eso-pic's \AtText… family uses \evensidemargin on the even pages of a twoside document, and \AtText…, \AtPageUpperLeft and \AtPageCenter pictures no longer sit at x = 0.

  • Mathematics: align and \text (v0.299.0–v0.300.0). align and align* follow amsmath for the \tag: the block is placed from \measure@'s shift and gap, and a tag that cannot fit (row + tag + \minalignsep × pairs + 2\mintagsep wider than \displaywidth) goes on a line of its own, flush right, instead of running off the page. A relation opening a right-aligned column (x &\sim y, &\iff …) gets the {} amsmath puts there, so it has its space. \text, \mbox, \hbox, \textrm and \textnormal keep their interword spaces (go-tex/math v0.51.0: \text{gene } i \text{ is …} used to print as one word). ⚠ flalign, alignat, eqnarray and gather keep their earlier tag rule, and \text does not yet inherit the surrounding text font (it stays upright).

  • Corpus, v0.288.0 → v0.299.0 (140 scored papers, the A/B harness, measured on v0.299.0; v0.300.0 is not measured yet): Σ|page deviation| from the reference 258 → 219, exact pagination 29 → 42 papers (38 moved: 32 toward the reference, 5 away, 1 sideways). 13 references are left out as unusable (a pdfTeX-driver leak or a junk first page).

  • Tables and front matter (v0.301.0–v0.303.0). tabularray's tblr, longtblr and talltblr are environments (#955): outer [..], inner spec (colspec, width, hlines, vlines, rowhead, rowfoot, or a bare colspec; a key=value spec with a bare colspec keeps its cells), tabularray's row padding, caption= and label= (the table counter steps). A table taller than a page is split row by row (longtable too); a longtblr repeats its rowhead rows on every page and ends all but the last page with the right-aligned "Continued on next page" foot. \SetCell, \SetTblrInner and the other styling commands are read and dropped; caption-lot, entry= and the booktabs themes are not modelled. titlesec's explicit option makes the \titleformat before-code take the title as #1, so {\MakeUppercase{#1}} works (#954). elsarticle's \cormark, \corref and \cortext print $\ast$ (#951), \textsuperscript follows the current size (\sf@size, #951), and 5p is two columns under a title block that spans both (#953).

  • Corpus, v0.302.0 → v0.303.0: Σ|page deviation| 245 → 239; one witness, 2407.19892, goes 28 → 31 pages (reference 34).

  • Command coverage (v0.307.0). How many TeX primitives, latex.ltx kernel commands and package commands the engine accepts, tests, and holds to the reference engine, raw and weighted by corpus usage (the package scope counts only the names a package's own files define; kernel names stay in the kernel scope), with the definition and limits of each state: go-tex.github.io/docs/main/coverage.

  • Not yet: TikZ/pgf drawing (gated behind GOTEX_PGF, in bring-up), full float pagination (GOTEX_FLOATS), two-column reprint layouts (GOTEX_TWOCOLUMN), EPS graphics (an .eps is measured from its %%BoundingBox, so its placeholder has the right shape, but it is not drawn), rotating's sideways floats (sidewaystable/sidewaysfigure are undefined, so the body sets inline and its caption carries no number), and the XeTeX/LuaTeX Unicode engines / fontspec.

Compiling a document you did not write

A .tex is a program and this package is its interpreter. Lenient mode is offered above as a preview for "a real third-party paper", the fidelity work runs the engine over arXiv sources in bulk, and the playground runs it on whatever a visitor pastes. Four properties are therefore held on purpose rather than by accident, each with a test that fails if it stops being true:

  • A document cannot run a process. No os/exec, no syscall.Exec — TeX's \write18 shell escape has no implementation here. Asserted by a scan of the package's own source, since there is no API that could express the property.
  • A document cannot write a file. No os.Create, os.WriteFile, os.Remove, os.Rename… in the engine package. (cmd/ is deliberately out of scope: the CLI writes the PDF it was asked for.)
  • A document cannot read a file outside the search roots. \input, \include, \usepackage, \documentclass and \bibliography resolve only under the working directory and the TEXINPUTS/GOTEX_TEXMF entries — the same search path the engine already looked in. This is TeX Live's openin_any=p policy. GOTEX_READ_ANY=1 is a named opt-out for a macro tree deliberately kept outside the document.
  • A document cannot exhaust memory or run forever. A macro that expands exponentially — ten macros, each ten copies of the next — asks for 10¹⁰ characters while taking few expansion steps and keeping a shallow input stack, so the step and depth ceilings could not see it: it reached 15.96 GB and was still growing. One paragraph is now bounded (200 000 nodes, against a largest-real-paragraph of 8 881 measured over the fidelity corpus) and the run ends rather than recovering, as TeX's capacity error does. The rest was the hyphenator: a document with no space in it is one enormous word and Liang's algorithm is quadratic in a word's length, so TeX's own limit applies — no word longer than 63 letters is hyphenated (tex.web §891). The same file now fails in 0.06 s at ~90 MB. The same expansion routed into a macro rather than onto a page took a second ceiling: \edef\boom{…} never builds a paragraph, so it passed the first one untouched at 6.3 GB while the typeset form stopped at 97 MB. One replacement text is now bounded too (1 000 000 tokens, against a largest-real-replacement-text of 2 999 measured over the same corpus), and that file returns in 0.38 s at 99 MB — against tectonic's 236 MB, where TeX's main_memory answers the same shape.

What that does not cover, stated rather than glossed over:

  • \font and \includegraphics read by absolute path, because each decodes its file and the engine loads system fonts from /System/Library/Fonts. A file that is neither a font nor an image yields an error and no content, so nothing is spliced into the page — but the shape of that error still tells a document whether a path exists.
  • The first two properties are read off the source, not enforced at runtime: they say the package contains no such call, which is what makes a commit that adds one fail the test and have to argue the case.
  • The CLI may use the network. gotex fetches the TeXMF bundles a document asks for (\usepackage{pgf} and friends) unless -offline is given, so the document influences what is downloaded — but only names a closed registry knows become bundles, so it cannot aim the fetch somewhere of its own choosing. To decide which bundles are needed the CLI also reads the document's class file, one level deep and by NAME only: a \documentclass argument carrying a path separator is not read, because that read happens a layer above the engine's own policy. The engine package itself opens no connection.

govulncheck reports no called vulnerability under the pinned toolchain (go 1.27.1); a 1.26.4 build of the same code called six, among them an encoding/xml recursion bomb reachable from an SVG figure.

Status & roadmap to parity

Each stage is gated by an objective oracle:

  1. ✅ Mouth + gullet — tokenizer, eqtb, macros, expansion.
  2. ✅ Stomach — box/glue/penalty model in scaled points, h/v lists, Knuth–Plass line breaking with an emergency pass, cost-based page builder, \halign. The page builder keeps TeX's two page measurements apart: page_total, which is what the break is decided on, and page_depth, which is not charged against the goal and is capped at \maxdepth (tex.web 19519-19529, 19594-19599). Summing the two, as this did, refused a page that filled to exactly \textheight over the descender of its own last line and cost it a line (#622, #648). The page also carries its glue: page_so_far is eight numbers in TeX (tex.web 19226-19232) — the goal, the total, the depth, three orders of infinite stretch, the finite one and the shrink — and the badness that decides a break is a function of the shortfall over the glue available to absorb it (19593-19599), not of two heights. A page ending in \vfill is badness 0 to TeX and was ~10000 here. That badness is now TeX's own integer function (§108, with its three overflow branches and the octal rounding constants) rather than a float 100·(t/s)³: the two agree on ordinary values and diverge exactly where TeX's rounding decides a close break. Since a breakpoint's cost is badness + penalty, every penalty was until then being compared against numbers on the wrong scale. \hspace and \vspace read a glue, as the reference does by putting their argument through a skip register (ltspace.dtx 1412-1413, 450): reading a rigid dimen kept the natural width and dropped the stretch, so \hspace{\fill} became a 0pt space and the words on either side were set adjoining — 188.50 where tectonic puts the second one at the right margin, 477.48. \fill, \enskip and \samepage are defined, and \stretch is the reference's second order of infinity (0pt plus n fill, l.1454) rather than the first, which decides who wins the leftover space on a list that also holds a \hfil. \vfil/\vfill/\vss contribute their glue at the reference's orders (tex.web §20557-20559, §20600-20601, §3318-3320), and \vfill is the second order where a macro in the format used to shadow the primitive with the first (#674). A footnote's mark is whatever \thefootnote expands to, not digits built in Go: the counter is the TeX counter \c@footnote (latex.ltx:13164-13165), so \renewcommand\thefootnote{\fnsymbol{footnote}} works, and \maketitle scopes it to \@fnsymbol as article.cls:205 does — a title block's \thanks comes out ∗, not 1, as it does in the reference. The foot label carries no full stop (\@makefnmark has none); this engine wrote 1. and a space. And a note's layout is \@makefntext, called, not a row built in Go: the three base classes right-align the mark in a 1.8em box (\hb@xt@1.8em{\hss\@makefnmark}#1, article.cls:609-612, report.cls:708, book.cls:714), so every note's text used to begin one box-width to the left of the reference's — measured as no box of 14.400pt anywhere on the page before and one now, with 72 of the 154 corpus papers rendering differently and Σ|deviation| 277 → 276. The mark reaches it through \@thefnmark and \@makefnmark (latex.ltx:13168, :13179), both replaceable by a document. \@textsuperscript is still the identity here, so the mark is set at text size on the baseline where the reference raises it — a separate divergence, unchanged. \footnoterule is a macro the page builder executes, not three nodes built in Go: 60 of the 154 measured papers redefine it, and what this engine drew was article.cls:605-608's .4\columnwidth — right for article and its relatives by coincidence, where the kernel's own rule is a fixed 2in (latex.ltx:13162-13163). \let\footnoterule\relax now draws nothing, which is what article.cls:172 asks for on a title page. A citation's brackets are \@biblabel and \@cite, called, not brackets built in Go: the reference makes both a macro (latex.ltx:13324, :13322) and article.cls:568 builds the bibliography list's label by calling \@biblabel. This engine runs real .cls files, so a class's redefinition was already in the eqtb and was dropped at the point of use — a document writing \def\@biblabel#1{<<#1>>} rendered byte-identically to one that did not. 22 of the 154 measured papers carry a class that redefines one of the two (19 for \@biblabel, 12 for \@cite), and only 50 of the 154 ship a class at all, so that is 44 % of the papers that bring their own; 18 of 154 render differently. \if@tempswa is set rather than inherited, as latex.ltx:13283-13284 sets it, so a redefined \@cite can decide whether to print the note. \@citex — the iteration natbib replaces — is not executed; one paper in 154 ships natbib.sty (#681). A package can talk to itself across passes, so the real natbib runs. \@auxout was \def\@auxout{-1}, a number no \openout ever opens, so everything a package wrote to the .aux went nowhere; it is a real stream now, carried to the next pass beside the label tables. Given the genuine natbib.sty, \citep/\citet in authoryear mode produce word for word what tectonic produces, with no undefined commands skipped (#712). What is left is reaching the file rather than running it: 20 of the 154 measured papers \usepackage{natbib} and none of those twenty ships it, so all twenty fall back to the built-in emulation, where \citet loses the author name outright — "obtained by [27]" where LaTeX writes "obtained by Nordbotten et al. [27]" (#703). A display chooses between the long and the short skips. tex.web:22578-22585 takes \abovedisplayshortskip/\belowdisplayshortskip when the previous line ends to the left of where the display begins — they do not collide, so little space is needed — and this engine always took the long pair. Measured baseline to baseline across one display between two text lines: 11.96/17.93 in the reference against our 21.92/21.92, now 11.96/17.93 exactly. A document of 40 displays went from 6 pages to the reference's 5. On the corpus the signed page bias falls from +50 to +35 and the median absolute deviation reaches 0 — but Σ|deviation| moves only 276 → 275: every mover got shorter, which rights the papers we set too long and worsens six we already set too short, two of them from exact. That surplus glue was cancelling a second, opposite error, now measurable on its own (#683). \predisplaysize follows tex.web:21781-21813, two ems and all, but is not exposed as a register. Every page is packed exactly to \vsize, whatever its page style (tex.web §19321 page_goal:=vsize, §19564 best_size:=page_goal, §19813 vpackage(…,best_size,exactly,…)): TeX has no page-style branch in the packer, because styles are the output routine's business. \pagestyle{empty} — which this engine takes as its default — was packed at its natural height, so the page was exactly as tall as its material and every vertical glue on it stretched by nothing: \vspace{\fill} under that style put its word at 143.91 where tectonic puts it at 664.72. §19811-19814 sets vbadness:=inf_bad and vfuzz:=max_dimen around that call "to inhibit error messages", so a page that cannot fill itself is packed short in silence — it is not a warning. A running head was four mechanisms, and three correct fixes left it empty. The band and the folio were right (#726), the page-style dispatch was right, the mark pair moved to \@themark — the name the kernel and every class use (#728) — and the head stayed blank, because amssubstrate.go carried \def\mark#1{}: a stub that discarded its argument, one layer below all three. A stub like that is the one shape no channel sees — the document asks, the engine says nothing, the suite stays green, and the loss exists only as ink that is not on the page. It cost 27 of the 128 corpus papers with a reference their head. What found it was a test asking not is this layer right but does the node arrive (#729). Marks now travel as nodes on the vertical list, their argument expanded at mark time (scan_toks(false,true), so amsart's \mark{\the\@temptokena} stores the pair and not the three tokens that would fetch it), and \topmark/\firstmark/\botmark follow §1012's arithmetic (:19718-19729, :19782-19789) — including the two consequences a plainer reading misses and a head depends on: \botmark is not cleared on a page with no marks, so a head set once at \maketitle stays; and \firstmark falls back to \topmark, so a page broken mid-section reports the mark in force at its own top. Measured: 6 corpus papers gain ink at identical page counts, invisible to Σ and visible only to hashdiff, and Σ/bias/exact do not move. A \mark in a class preamble is read and dropped: ws-fnl.cls carries one, and contributing it to a page that does not exist yet turned 9 pages into 10 with the ink identical. \\ is a Go primitive that scans its own star and optional length: as a macro built on \@ifstar it put \@ifstar into the maths source and every formula holding a matrix row separator was refused, because the maths capture writes a control sequence verbatim and never consults its meaning — measured four ways, including a primitive that calls fail and is never run during a capture. \\[20pt] used to typeset the five characters [20pt] and \\* a *, on 38 and 9 of the 154 measured papers; the length now rides on the forced penalty and the line loop emits it after the line, giving the reference's 31.88pt step where a bare \\ gives 11.96 (#662). \vadjust is implemented (tex.web §2994-3001, §12900-12903, §17413-17418, §21195, §21199-21231): vertical material written inside a paragraph rides along in an adjust node that contributes no width, and comes out into the enclosing vertical list after the line it was written on — measured against tectonic as a 41.84pt baseline step where a normal one is 11.96, with the control paragraph unchanged. It is an error in vertical mode, as §21195 requires. Three commands were waiting on it and now work: \pagebreak/\nopagebreak in horizontal mode (the reference makes two pages on a short first paragraph and so do we, where we made one), \\*'s page-break suppression (the \nobreak goes inside the \vadjust, so it reaches the vertical list where 10000 refuses a page rather than a line), and \\[len]'s space, which now uses the same mechanism instead of the stopgap field it shipped with (#665). \pagebreak, \nopagebreak, \linebreak and \nolinebreak are penalties rather than no-ops (ltspace.dtx 294-306, 344-375, 527-531): the optional degree goes through \@getpen (0, 51, 151, 301, 10000) and the sign is what separates forcing from forbidding. All four did nothing at all before, on 18 of the 154 measured corpus papers; \pagebreak between two paragraphs made one page where tectonic makes two. Two gaps are left and named: in horizontal mode \pagebreak needs \vadjust, which is not implemented (#665), and a line ended by a forced break is not justified here — \parfillskip is appended to every forced-break fragment instead of once per paragraph, so the slack it should give the interword glue is absorbed (#666). The second pass is the final pass, as tex.web §863 says in one line: final_pass:=(emergency_stretch<=0), set on entering it. \emergencystretch is accept-and-ignore here, so there is no third pass and TeX's artificial_demerits — a break taken at zero cost where the line is hopeless, nothing feasible was recorded and one node is active — belongs to the second. It could not be armed while go-typeset/linebreak recorded every forced break whatever its badness and ran that clause outside §16769's branch; both are fixed in its v1.4.0. ⭐ And the passes are now only TeX's, which closed #768's second finding. A fourth pass used to run at an effectively infinite tolerance whenever the others left a bad line; tex.web has no such pass — §863 has three and none of them raises the tolerance — and it would rather leave a line overfull than take more hyphens. On #768's witness (\hsize=45pt, \fussy) the reference sets 5 lines with four overfull boxes; with that pass we set 7 that all fit, and we now set the reference's 5, its first three lines matching to 0.02pt. It could not go until \leftskip/\rightskip became the background of every line and a fil stopped being flattened into the finite stretch column (go-typeset/linebreak v1.5.0, its #12 item 1): §16790-16793 gives a line carrying any fil badness 0, so under \raggedright the first pass — which has no hyphens — succeeds outright, where before every such line was merely loose and four tests stopped hyphenating when the fourth pass was taken away. ⚠ The corpus says faithful, not better. Over 40 papers scored both sides: line agreement 91.23 → 91.34%, papers whose page count is exactly the reference's 12 → 13/40, one paper that did not render now rendering and landing exactly right — against Σ|page error| 123 → 125 and mean divergence 3.884 → 3.935. Three papers moved one page, two of them missing pages, which is #381 (our lines hold more than the reference's) exposed a little further now that lines are no longer padded out with extra hyphens. A paragraph is broken on its own SHAPE, not only on \hsize. TeX's shape parameters reach the line breaker rather than being accepted and ignored: \hangindent/\hangafter (tex.web §847-850, :16676-16748) and \parshape (:23275-23286, whose last pair repeats for every later line, :16680-16681). \parshape wins over \hangindent, which is not obvious and is settled at :16706 — it tests par_shape_ptr first and consults hang_indent only in the else branch. All of them last one paragraph: normal_paragraph clears them at every \par (:20756-20761), which became a defect here only once \hangindent started working at all. ⚠ A no-regression check, not a win, and the census says why. \parshape is set by 0 of the 154 measured papers and \hangindent by 3, so the corpus A/B moves Σ|page deviation| 306 → 306 with 0 papers moved — the predicted result, where anything else would have meant a bug. The witnesses are unit-level, and each was confirmed by removing the line it tests: reading \hangindent first makes the precedence test, and only that test, fail. Hyphenation is Liang's algorithm on the embedded US-English patterns (go-typeset/hyphenation), with \lefthyphenmin/\righthyphenmin, \hyphenchar — a face that files it negative is never broken, which is how \texttt keeps code whole (tex.web §896) — and the document's own \hyphenation{…} exception list. Two defects there were invisible to every test: an accented word broke at an offset, because the library built its value array over the word by BYTE index and read it back by RUNE index — the two agree for exactly as long as every letter is one byte, which is every English word and no French one. élémentaires broke as éléme-ntaires, between the m and the n of a syllable, where no pattern can put a break; with the fix it is whole and présentation breaks présenta-tion, which is where tectonic breaks it (go-typeset/hyphenation#8, #774). And \hyphenation{…} was a stub that discarded its argument — a document writes it for the words the patterns get wrong, so the silence fell exactly on the words it was asked about. An entry now replaces the patterns for its word (tex.web §937), including an entry with no hyphen at all, which says the word may never be broken (#775). And the engine loaded MORE patterns than the reference has. The embedded file is ushyphmax.tex: hyphen.tex's patterns, a marker line, then 492 additions. LaTeX's language.dat loads hyph-en-us.tex, which is the first half only, so every addition that applied changed a word's break points — including when it forbade a break, since Liang takes the highest value and an even one is a refusal. .ev2 is one, and it outranks hyphen.tex's ev1er: every could not be broken at all. tectonic 0.17.0 at \hsize=18pt sets ev-/ery. Loading stops at the marker now, and incomprehensibilities, overwhelm, paragraph, photography and typographical break exactly where they did — which is why nothing noticed for as long as the whole file was read. ⚠ Only English patterns are embedded. A paper in another language is set unhyphenated where a real TeX hyphenates it; that gap is tracked in #754. The line straight after a list is not indented, as in LaTeX: after an itemize, enumerate, description, center, quote, quotation or verse with no blank line before the text, the paragraph continues flush left; a blank line indents it as usual. Measured against tectonic, such a line used to start one \parindent (14.94bp) in. The mechanism is \@doendpe from the 2021-11-15 kernel the reference runs, read from it with \meaning: its flag is local, so a list closed inside {…} leaves the next line indented there, as it does here — the 2024 kernel would not (#857).
  3. ✅ Math — $…$ and the display environments delegated to go-tex/math (vector output).
  4. ✅ Fonts — OpenType via go-opentype; a built-in font so it runs with no assets, with kerning and ligatures. A family when one is given: roman, bold, italic, slanted (NFSS's own substitution onto the italic), typewriter and sans are each bound to a file, and a glyph is drawn with the face it was measured with — \textbf, \texttt and \verb reach the page in their own face, not only in their own widths. The size ladder is the class's table, to the point. \tiny through \Huge are ten sizes a size1x.clo states, and three of them are not whole — \Large is 14.4, \LARGE 17.28, \huge 20.74. A face held its size as an integer, so \Large landed on 14: 2.8 % narrow on every section heading in every document. Reading each line's Tf out of the PDF, all ten now agree with tectonic (\Large 13.95 → 14.35, \huge 21 → 20.66, \Huge 25 → 24.79), and an [11pt] class sets its body at the 10.95 its \@xipt states rather than at 11 (#718, #719). Kerning comes from every lookup, not the first. OpenType applies GPOS lookups in LookupList order and their adjustments add; stopping at the first one that covers a pair returned a deliberate zero and never reached the real value. Libertinus Serif files A/V with 0 in one kern lookup and −112 in a later one, so \hbox{AV} at 10pt measured 13.47pt against XeTeX's 12.35pt, and now measures 12.35pt (go-opentype/opentype#63). Neither of these shows in the page-count barometer below: a kern, or a heading a third of a point wider, costs a page only when it tips one. The witness is the oracle comparison.
  5. ✅ Output — PDF (via go-pdfkit, embedded subset fonts, selectable text, and clickable /Link annotations for \href URIs and \hyperlink in-document jumps) and self-contained SVG pages; the SVG carries a source map for click-to-line.
  6. ✅ Real classes — \documentclass{article|report|book|amsart} loads and runs the genuine embedded LaTeX class (see above), reproducing the reference engine's prose on the fidelity gate — in native builds and in js/wasm.

Next: real TikZ/pgf (behind GOTEX_PGF today), float pagination and two-column reprint layouts out of their env flags, PDF-figure rasterization and clickable PDF links, a broader real-document conformance corpus (PDF-diff vs pdftex/xetex), and the TRIP test — see the capability reference for the complete list of gaps. the meaningful gate is the conformance ratchet plus the fidelity check against a real LaTeX engine, not a fixed coverage figure — CI enforces an 80% floor and measures 91.0% today. Pure Go, CGO=0, go vet clean, green on the host plus four cross arches under qemu — s390x (big-endian), ppc64le, riscv64 and loong64 — and on js/wasm and wasip1/wasm.

The instruments

Fidelity work here is measured, not asserted, and each of these answers one question the others cannot. They are ordinary go run ./cmd/… programs.

gotex-abdiff compiles a corpus of real papers at two revisions and reports Σ|page deviation| against the reference counts, naming every paper that moved. It builds each side in its own git worktree, checks that the head really descends from the base, and prints whether GOTEX_PDFRENDER was set — three measurements had been read the wrong way before it did. It also reports Σ glyphs per side, because a page count cannot tell "the same text, broken differently" from "text that appeared or vanished": pages moving while the ink holds still is a breaking change, ink moving is a content change, and the xkeyval precedent — a package that stopped erroring, same page count, text on the page that had not been there before — was called "nothing moved" by a page-only A/B. ⛔ The ink is a witness, not a score, and the line says so: the reference file carries page counts only, so there is no reference ink to be near or far from. Pages that parse but whose text does not decode are counted in their own field and make the report disown its own glyph delta, because two incomplete sums differ by an amount that looks exactly like ink that moved. Both tools refuse to measure above a 1-minute or 5-minute load average of 8 (cmd/internal/loadguard, shared with gotex-refdiff), and refuse when they cannot read the load at all — an unreadable machine is not an idle one; -under-load '<why>' measures anyway and stamps the reason into the report.
gotex-refdiff compiles a sample of papers with tectonic and with the engine and scores each one: word recall (what text came out) or, with -layout, word displacement (where it landed). -gotex names the binary to measure, so two revisions can be put side by side over the same sample; -list draws that sample from a named corpus list instead of walking a raw arXiv directory, where the papers the REFERENCE cannot compile score "ref-unavailable" — a 30-paper run came back 30 of 30 unavailable on both sides of a change, which reads exactly like "no difference". A compile that merely exhausts -timeout is timed-out and leaves the score on either side, with a banner on stderr: it used to be scored 0 on ours and merely dropped on the reference's, so a slow paper — or a loaded machine — moved the mean one way only.
gotex-linediff puts one page of two PDFs side by side line by line — where each line starts and ends, its baseline, face and size, and, when it holds a dot leader, how many tiles it draws and how far apart. This is the rung below a per-paper score: the sentence a defect is fixed from reads "our entry starts 1.58pt right of the reference's and its dots are twice as dense". It reads the PDFs with go-pdfkit/reader — no qpdf, no poppler, no MuPDF. That extractor now lives in cmd/internal/pdfruns rather than inside this command, so gotex-abdiff can count ink with it instead of a second protocol being written to answer the same question.
gotex-worddiff which words one PDF holds that the other does not, as a multiset, for two builds of this engine and no reference. It answers the question a moved score leaves open — gotex-refdiff says a paper fell 0.1 points, this says which words that was. It reads both files through internal/pdftext, the extractor the score itself uses: a word-diff on a different extractor reports the two extractors' disagreement in the engine's units, which is how a fused CenterforTheoretical got published twice as an engine defect before the line dump showed the spaces were in both files. -layout keeps columns apart — without it a two-column page is read as one stream and the end of one column's line fuses onto the start of another's (disFigure, participaentire), and which boundaries fuse moves when the lines do. On #772's two papers, scoring with -layout extraction made one of two apparent regressions vanish outright and reduced the other to a single word.
gotex-paramcensus which measured papers set a given TeX parameter, which is how a divergence is sized before anyone spends a corpus run on it: \looseness turned out to be set by 0 of the 154 (so implementing it is bit-identical and owes no A/B), \emergencystretch by 4, and only 1 paper has a non-English main language — deflating "English-only hyphenation explains the page-count gap". The obvious grep -rl is wrong five ways, each of which reads as a clean answer: it counts the whole paper tree instead of the measured list; the list names each paper's main.tex, not its directory, so walking its entries reads 154 files where the papers hold 679 and every \inputed chapter is skipped; a commented-out setting is not a setting; a bare substring matches prose; and ⛔ a control word is a prefix of longer control words — asked for \font, a substring scan answered 14 of 154, every hit being \fontsize{13}{16} or \Affilfont and not one a use of the primitive. TeX ends a control word at the first non-letter, so a term that is one is matched to that boundary and \font now answers 2, both of them the current-font token in \fontdimen2\font and \hyphenchar\font. The fix moved only \font: \looseness 0, \emergencystretch 4 and \hangindent 3 are unchanged, so no figure published here had to be revisited. It refuses rather than printing a zero it cannot stand behind — every run must find its -control term (default \documentclass) and must have read a file, because a scan that could not read reports zero exactly like a corpus that holds nothing.
gotex-coverage the coverage floor CI enforces.

A dot leader is the case that makes the last one worth having: Title. . . . 7 reads the same whether the tiles are 4.8pt apart or 8.5, so no text-level comparison can see the difference. The drawn positions can.

License

BSD-3-Clause — see LICENSE. Copyright the go-tex/engine authors.

Documentation

Overview

Package engine is the core of a pure-Go (CGO=0) TeX engine: a faithful re-implementation of TeX's mouth and gullet — category-code tokenization, the equivalents table (eqtb) with grouping/scoping, macro definition with delimited parameters, and the expansion machinery (\def, \edef, \let, \expandafter, \csname, \noexpand, \string, \the, \number, conditionals, integer registers). It is the foundation on which the real LaTeX kernel and packages will run, gated by TeX's own conformance suite (the TRIP test) — the path to functional parity with a TeX distribution, not a subset.

Index

Constants

View Source
const AMSClassSubstrate = `` /* 27489-byte string literal not displayed */

AMSClassSubstrate is the register-and-macro layer amsart builds on beyond the article substrate: plain-TeX scratch registers, the penalty/spacing parameters a class assigns, and best-effort no-ops for NFSS font selection and a few text commands. Loaded last by LoadLaTeX.

View Source
const AcmartMetadata = `` /* 5480-byte string literal not displayed */

AcmartMetadata stubs acmart's top-matter METADATA commands, loaded for \documentclass{acmart} when the real acmart.cls is not bundled (it is not embedded, so acmart otherwise runs the amsart-shaped emulation). These commands carry bibliographic metadata — copyright, DOI, conference, CCS concepts — that acmart records and typesets in its own strip; the emulation has none of that, so left undefined they strict-fail and, lenient, typeset their arguments as body text (\setcopyright is the corpus's 3rd most common undefined control sequence, and the CCSXML block dumps a wall of raw XML). Gobbling them keeps the document's real content clean. A bundled acmart.cls defines them itself.

Loaded with @ already an "other" character (document time), so it opens with \makeatletter for its @-helpers.

View Source
const ApaciteStubs = `` /* 6184-byte string literal not displayed */

ApaciteStubs recovers the apacite package's reference-list macros, loaded for \usepackage{apacite} / \RequirePackage{apacite} (many APA journal classes — agujournal, sn-jnl — require it) when the real apacite.sty is NOT bundled with the paper. When it IS bundled the real file resolves and loads and these stubs are not used.

apacite drives an APA-style .bbl. Each reference is a \bibitem whose body is built from an APACrefauthors environment (the author names) followed by content-bearing macros: \APACrefYearMonthDay{year}{month}{day}, the title (\APACrefatitle{Title}{title} — apacite typesets the sentence-case SECOND arg), \APACjournalVolNumPages{journal}{vol}{num}{pages}, plus a run of short string producers (\BBA -> "&", \BCBL -> ",", \BPBI -> ". ", \BOthers -> "et al.").

Left undefined these do not merely vanish: the engine's lenient path GOBBLES an undefined control sequence's braced arguments (see skipUndefined), so \APACrefYearMonthDay{2022}{}{} takes "2022" with it and \APACrefatitle{T}{t} takes the whole title. The reference list then shows the author names alone and drops the year, title, journal and pages — the defect these stubs repair.

The definitions are apacite's own (from apacite.sty), pared to the macros that appear in real .bbl files, so the recovered text matches what apacite renders. The goal is CONTENT recovery, not pixel-perfect APA punctuation: the words (authors, year, title, journal, volume/pages, URL, DOI) appear instead of being dropped or leaking macro names. It opens with \makeatletter for apacite's @-helpers (\@empty tests, \@connect@with@commas) and closes with \makeatother.

View Source
const BeamerClassKernel = `` /* 5548-byte string literal not displayed */

BeamerClassKernel is the built-in emulation of the beamer presentation class. The engine EMULATES beamer's document structure rather than running the real class: every frame becomes a page, frame titles become headings, blocks render as titled paragraphs, and overlay specifications (\pause, <1->, \only, \uncover, …) are shown STATICALLY — all the material of a frame at once. Themes and pgf styling are gobbled. The goal is that a beamer talk RENDERS its content as a sequence of pages, not pixel-fidelity to a themed slide. Loaded by doDocumentClass when \documentclass{beamer} is seen.

The real beamer.cls is being brought up alongside this; it now LOADS in full, and GOTEX_BEAMER switches to it — see realBeamer in packages.go for exactly how far that has got and why the emulation is still the default.

View Source
const ElsarticleFrontMatter = `` /* 11796-byte string literal not displayed */

ElsarticleFrontMatter emulates the front matter of elsarticle.cls (3.3, 2020/11/20) for a paper that does not bundle the class — which is nearly all of them.

Without it the article fallback leaves \ead, \cortext, \fntext, \tnotetext, \tnoteref, \fnref, \corref, \address, \affiliation and \journal undefined: in lenient mode their arguments were typeset raw, as "[c1]Corresponding author" in the body, and the title block carried no author marks, no footnotes at the foot of page one, no e-mail line and no "Preprint submitted to" footer. The line numbers below are elsarticle.cls's own.

What is ported, nearly verbatim:

\title                       :120      \tnotetext/\tnoteref/\tnotemark  :130-148, :1355
\fntext/\fnref/\fnmark       :154-169  \cortext/\corref/\cormark          :171-190
\ead, \emailauthor, \urlauthor :192-233  \author                          :235-282
\address                     :636-648  \affiliation (key=value)           :564-633
abstract and keyword boxes   :650-723  \printFirstPageNotes               :728-751
\pprintMaketitle             :760-790  \finalMaketitle, \MaketitleBox     :801-826
\maketitle                   :887-984  \ps@pprintTitle                    :998-1022
\journal                     :1277     \nonumnote                         :150

What differs, on purpose:

  • The class defers a label to the NEXT run through the .aux file (\elsLabel writes \Newlabel, \ead writes \emailauthor), so a first run prints the default mark. The engine renders once, so a label is defined when its \tnotetext / \fntext / \cortext / \address is READ, counting the same way the class does, and \ead calls \emailauthor directly. The result is the second-run output, which is what the reference (tectonic) prints.
  • \affiliation's keys are read here by a comma/equals splitter, not keyval, because the kernel gobbles \setkeys. Keys that set punctuation (op, ap, cp, ...) are ignored; the default ", " after each value is used. An unknown key is dropped.
  • 1p/3p (the CRC "final" layouts) use \finalMaketitle in one column; 5p runs it as \twocolumn[\finalMaketitle] (:353-364), the title box spanning both columns. The \vsplit of the long-title option and the highlights / graphical-abstract pages are not reproduced.
  • \usepackage{hyperref}'s title/author hooks (:284-289) are not needed here.
View Source
const FloatPlacementSubstrate = `` /* 942-byte string literal not displayed */

FloatPlacementSubstrate routes the figure/table environments through the placer. It is loaded by LoadLaTeX ONLY when floatsEnabled(), so with the flag off the environments keep their untouched LaTeX2eClassLead definitions and the default output is unchanged. It redefines only \@float (not \@dblfloat, which keeps its two-column band path, nor \end@float, whose group would leak): \@float is the class float mechanism every figure/table funnels through and the point that SURVIVES \documentclass — a class redefines \figure to \@float{figure} at \documentclass time but leaves \@float itself the base one. \gotex@inlinefloat reproduces the classic inline begin-code for the two-column / [h] fall-back path (@ a letter, so \@captype / \@ifnextchar are real control sequences).

@ is already a letter here (this loads after AMSClassSubstrate, which — like this substrate — defines @-names with no \makeatletter), and LoadFormat does NOT save and restore catcodes, so this must NOT emit a \makeatother: doing so would flip @ to catother for everything loaded afterwards and for a bare New()+LoadLaTeX() document, breaking later \@-name control sequences. It leaves @ a letter, exactly as the default (substrate-free) end of LoadLaTeX does.

View Source
const IEEEtranAuthorBlocksInline = `
\long\def\IEEEauthorblockN#1{#1}
\long\def\IEEEauthorblockA#1{#1}
`

IEEEtranAuthorBlocksInline is the class's own definition outside the three row modes.

View Source
const IEEEtranAuthorBlocksRows = `
\long\def\IEEEauthorblockN#1{\par#1\par}
\long\def\IEEEauthorblockA#1{\par#1\par}
`

IEEEtranAuthorBlocksRows and IEEEtranAuthorBlocksInline are IEEEtran's author blocks, and the class defines them TWO WAYS.

In conference, peerreviewca and transmag mode it sets them through \@IEEEauthorhalign (IEEEtran.cls:4632, :4649, :4683): each block is a ROW, ended by the macro's own \crcr, and the halign puts the authors side by side in columns. Outside those modes it defines them as plain pass-throughs (:4676-4677):

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

The halign is not implemented here, so the rows become a vertical stack — but the DISTINCTION has to be kept, and getting it wrong is visible on the page both ways.

⛔ A conference paper writes one block per line and needs the break: without it 2408.02112 came out as "Stephen M. Watt Ontario Research Centre for Computer Algebra and Cheriton School of …" on one line that ran off the right edge.

⛔ A journal paper writes them INLINE, with its own punctuation between: "\IEEEauthorblockN{Daanish Mahajan}, \IEEEauthorblockN{Chirag Jain}, …" (2405.05734). Breaking there strands each comma alone on a line, where the reference reads "Daanish Mahajan, Chirag Jain, Navin Kashyap" — which is exactly what the class's pass-through gives.

View Source
const IEEEtranNames = `` /* 1124-byte string literal not displayed */

IEEEtranNames is what IEEEtran calls its floats and its keyword block, plus the two commands the class makes \long. Every line is cited, and every one is visible on the page:

IEEEtran.cls:2607  \def\figurename{Fig.}          — not "Figure"
IEEEtran.cls:2608  \def\tablename{TABLE}          — in CAPITALS
IEEEtran.cls:2830  \def\thetable{\@Roman\c@table} — ROMAN numerals
IEEEtran.cls:2614  \def\IEEEkeywordsname{Index Terms}
IEEEtran.cls:5286  \def\IEEEkeywords{… \textit{\IEEEkeywordsname}---\relax …}
IEEEtran.cls:4882  \long\def\author#1{\gdef\@author{#1}}
IEEEtran.cls:4874  \long\def\thanks#1{…}

Checked against the reference PDFs rather than taken on trust: five IEEEtran papers of the corpus print "Fig. N" and never "Figure N", "TABLE I/II/III" and never "Table 1", and four of the five print "Index Terms". Eleven corpus papers use the class.

compsoc is the exception on three of these — IEEEtran.cls:2609 restores "Figure" and :2828 arabic table numbers for it — and NO corpus paper asks for compsoc, so the option is not branched on here. A paper that did would get the non-compsoc names, which is the same kind of approximation the geometry above already makes.

View Source
const IEEEtranTitlePlain = `` /* 192-byte string literal not displayed */

IEEEtranTitlePlain is the same block without the span, for [onecolumn]. It still replaces \centerline with a center environment, because the hbox defect above is not about columns.

View Source
const IEEEtranTitleSpan = `` /* 194-byte string literal not displayed */

IEEEtranTitleSpan and IEEEtranTitlePlain replace the generic \maketitle (latex.go) for an emulated IEEEtran. Two things were wrong with the generic one on this class.

⛔ \centerline{\@author} is an \hbox. A multi-block IEEEtran author is a VERTICAL list — \IEEEauthorblockN{name} over \IEEEauthorblockA{affiliation}, repeated per author — and an hbox flattens it into one line that does not wrap. On 2408.02112 the reference sets two authors side by side over four lines of affiliation each; we set one line that ran off the right edge of the page. A \par inside that hbox does nothing at all, which is why defining \IEEEauthorblockN with one changed the corpus by exactly zero glyphs before this.

⛔ And the block did not SPAN the columns. IEEEtran sets two columns from \documentclass, so the generic \maketitle emitted the title into column one, where it overlapped the body. \twocolumn[…] is precisely the construct for this: its bracket material is typeset at full width and placed across the top of the region's first page (twocolumn.go, typesetSpanFullWidth / colRegion.span), which is how the revtex emulation already does it.

⛔ The TITLE is set in the class's \Huge, not at \normalsize. IEEEtran.cls:4808-4809 sets {\Huge … \@title\par} and its 10pt \Huge is \@setfontsize\Huge{24}{28pt} (l.667; the 11pt and 12pt branches, l.690 and l.713, are the same 24/28). Measured with tectonic (pdftotext -bbox) on a minimal \documentclass[conference]{IEEEtran} witness: the title words "ZZZ" and "Title" are 40.385pt and 46.10pt wide, 23.91pt high; this emulation set them at body size, and now sets the same widths to the 0.01pt. The author block keeps the size of the running text, as in the class.

View Source
const (
	InfPenalty = linebreak.InfPenalty
)
View Source
const LaTeX2eClassKernel = `` /* 68873-byte string literal not displayed */

LaTeX2eClassKernel is the LaTeX2e class-kernel substrate, loaded by LoadLaTeX right after LaTeX2eKernelHelpers.

View Source
const LaTeX2eClassLead = `` /* 30561-byte string literal not displayed */

LaTeX2eClassLead is the best-effort high-level class machinery a real class builds on top of the kernel: sectioning (\@startsection and its helpers), the generic \list, and small no-ops. It is intentionally simplified — headings are typeset in their requested style without the exact spacing/numbering of real LaTeX — so that loading a real class produces readable structured output rather than aborting. It is loaded after LaTeX2eClassKernel.

View Source
const LaTeX2eKernelHelpers = `
\catcode64=11
% ── expansion primitives / gobblers / selectors ─────────────────────────────
\def\@empty{}
\long\def\@iden#1{#1}
\long\def\@firstofone#1{#1}
\long\def\@gobble#1{}
\long\def\@gobbletwo#1#2{}
\long\def\@gobblethree#1#2#3{}
\long\def\@gobblefour#1#2#3#4{}
\long\def\@firstoftwo#1#2{#1}
\long\def\@secondoftwo#1#2{#2}
% amsgen's emptiness test, verbatim (amsgen.sty:43-46). amsthm's theorem head is
% built out of it — \@ifempty{#3}{\let\thmnote\@gobble}{\let\thmnote\@iden} is how
% a theorem with no note drops the parentheses — and a class that styles its own
% theorems calls it directly. Undefined, the calls were skipped and their
% arguments typeset, so the head came out twice.
\long\def\@ifempty#1{\@xifempty#1@@..\@nil}
\long\def\@xifempty#1#2@#3#4#5\@nil{\ifx#3#4\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
\long\def\@ifnotempty#1{\@ifempty{#1}{}}
% LaTeX kernel while-loops. \@whilenum <test> \do {<body>} repeats <body> while
% the \ifnum test holds; \@whiledim is the \ifdim analogue; \@whilesw <switch>\fi
% {<body>} loops on a boolean switch. Classes drive frontmatter box splitting and
% list machinery with these (e.g. imsart's \close@fm \@whiledim…\vsplit loop);
% defined exactly as latex.ltx so the delimited \do argument parses correctly.
\long\def\@whilenum#1\do #2{\ifnum #1\relax #2\relax\@iwhilenum{#1\relax #2\relax}\fi}
\long\def\@iwhilenum#1{\ifnum #1\expandafter\@iwhilenum\else\expandafter\@gobble\fi{#1}}
\long\def\@whiledim#1\do #2{\ifdim #1\relax#2\@iwhiledim{#1\relax#2}\fi}
\long\def\@iwhiledim#1{\ifdim #1\expandafter\@iwhiledim\else\expandafter\@gobble\fi{#1}}
\long\def\@whilesw#1\fi#2{#1#2\@iwhilesw{#1#2}\fi}
\long\def\@iwhilesw#1\fi{#1\expandafter\@iwhilesw\else\@gobbletwo\fi{#1}\fi}
% \@nil / \@nnil : pure delimiter tokens for list-scanning macros. Their meaning
% is never executed; \@nnil's body is the single token \@nil so that a loop macro
% \def'd to \@nil compares \ifx-equal to \@nnil (meaning-equality of bodies).
\def\@nil{}
\def\@nnil{\@nil}
% ── \csname-based (re)naming ────────────────────────────────────────────────
\def\@namedef#1{\expandafter\def\csname #1\endcsname}
\def\@nameuse#1{\csname #1\endcsname}
% ── numeric / length constants used pervasively by the kernel ───────────────
% Plain-TeX register constants. \z@ is BOTH the number 0 and the dimen 0pt (as in
% plain.tex it is a \dimen); \@ne/\tw@/\thr@@ are \chardef'd small integers.
\newcount\m@ne \m@ne=-1
\chardef\@ne=1
\chardef\tw@=2
\chardef\thr@@=3
\newdimen\z@ \z@=0pt
\newskip\z@skip \z@skip=0pt plus0pt minus0pt
\newskip\@tempskipa
\newskip\@tempskipb
\newdimen\@tempdima
\newdimen\@tempdimb
\newcount\@tempcnta
\newcount\@tempcntb
% ── \newif (the engine has no \newif primitive) ─────────────────────────────
% \@stripif\iffoo expands to the letters "foo": \string\iffoo gives the six
% catcode-12 chars \ i f f o o (the engine has no \escapechar, so \string always
% keeps the leading backslash), and \@gobblethree drops the "\if" prefix. \newif
% then \let's the switch false and builds \footrue / \foofalse via \csname.
\def\@stripif#1{\expandafter\@gobblethree\string#1}
\def\newif#1{%
  \let#1\iffalse
  \expandafter\def\csname\@stripif#1true\endcsname{\let#1\iftrue}%
  \expandafter\def\csname\@stripif#1false\endcsname{\let#1\iffalse}}
\newif\if@tempswa
\newif\ifin@
% xcolor's own switches, which packages built on it read: xxcolor — beamer's
% colour layer — toggles \ifglobalcolors around every colour it sets.
\newif\ifglobalcolors
\newif\ifXC@keepwhite
% …and the two that say WHEN xcolor converts a colour to the target model — at
% definition time or at use time (xcolor.sty:73-74). Both are false unless xcolor
% is given a target model, which this engine never is: it keeps every colour in
% RGB and converts nothing, so false is the truthful answer as well as the one
% \newif gives.
%
% They matter because a package loaded FOR REAL reads them. pgfplots.sty:110-121
% tests them nested —
%
%	\ifconvertcolorsD … \else \ifconvertcolorsU … \fi \fi
%
% and an UNDEFINED conditional is the one thing a TeX engine cannot skip past: the
% \else and both \fi are lost with it and the groups never close.
\newif\ifconvertcolorsD
\newif\ifconvertcolorsU
% ── ifthen's booleans ───────────────────────────────────────────────────────
% \newboolean{b} is \newif\ifb, and \setboolean{b}{true} is \btrue. ifthen.sty
% writes exactly this; \ifthenelse{\boolean{b}} then reads the switch's meaning.
\def\newboolean#1{\expandafter\newif\csname if#1\endcsname}
\def\provideboolean#1{\@ifundefined{if#1}{\newboolean{#1}}{}}
% \setboolean LOWERCASES its value before using it (ifthen.sty:125,
% \lowercase{\def\@tempa{#2}}), so \setboolean{b}{True} and {TRUE} work. Written
% without it, \csname bTrue\endcsname is undefined and the assignment silently
% does nothing — a wrong answer with no diagnostic. Read from the package; the
% corpus writes only lowercase, so no measurement could have shown this.
\def\setboolean#1#2{\lowercase{\def\gotex@bv{#2}}\csname #1\gotex@bv\endcsname}
% ── definability / undefined tests ──────────────────────────────────────────
% \@ifundefined{name}{then}{else}: \csname name\endcsname is \relax when the name
% is undefined (doCsname), so \ifx…\relax selects the branch. NOTE the standard
% LaTeX side effect: after the test an undefined name becomes \relax (no longer
% "undefined") — matching real latex.ltx.
% (One line: any space/newline in the body would leak into the branch that runs
% inside a \message, so it is written without stray space tokens.)
\def\@ifundefined#1{\expandafter\ifx\csname #1\endcsname\relax\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
% \@ifdefinable\name{def}: run {def} if \name is currently undefinable-safe (i.e.
% \relax/undefined); otherwise a no-op (LIMITATION: real LaTeX raises an error and
% also rejects a handful of reserved names — the engine's \newcommand path is a Go
% primitive and does its own checking, so this is only a best-effort fallback).
\long\def\@ifdefinable#1#2{%
  \expandafter\ifx\csname\expandafter\@gobble\string#1\endcsname\relax
    #2%
  \fi}
% ── list / string dissection ────────────────────────────────────────────────
\def\@car#1#2\@nil{#1}
\def\@cdr#1#2\@nil{#2}
% \zap@space<text> \@empty strips ALL spaces from <text>; the trailing \@empty is
% the sentinel (\zap@space a b c\@empty -> abc).
\def\zap@space#1 #2{#1\ifx#2\@empty\else\expandafter\zap@space\fi#2}
% \@backslashchar / \@percentchar : a single catcode-12 "\" / "%" usable inside
% \edef (\string keeps the backslash, \@gobble removes it).
\edef\@backslashchar{\expandafter\@gobble\string\\}
\edef\@percentchar{\expandafter\@gobble\string\%}
% ── two-argument expansion + substring membership (\in@) ─────────────────────
\def\@expandtwoargs#1#2#3{\edef\reserved@a{\noexpand#1{#2}{#3}}\reserved@a}
\def\reserved@a{}
% \@ifinlist{item}{comma-list} sets \ifin@ true iff <item> (after \edef expansion)
% equals one of the comma-separated entries of <comma-list> (also \edef-expanded
% first, so a macro like \opt@foo.sty is spread into its entries). A self-contained
% scanner terminated by the \@inliststop sentinel — it always halts.
%
% LIMITATION: the classic substring \in@ from latex.ltx is NOT provided. Its
% definition builds a macro whose parameter text is self-delimited by its own name
% (\def\in@@#1<sub>#2#3\in@@{…}); this engine's delimited-parameter matcher loops
% on that construction. \@ifinlist covers the comma-option-list case that
% \@ifpackagewith needs; packages that call \in@ directly are the option-processing
% layer's concern (handled in Go by the lead).
\def\@inliststop{\@inliststop}
\def\@ifinlist#1#2{\in@false\edef\@inlistwant{#1}\edef\@inlisttmp{#2}\expandafter\@inlist@scan\@inlisttmp,\@inliststop,}
\def\@inlist@scan#1,{\def\@inlistcur{#1}\ifx\@inlistcur\@inliststop\else\ifx\@inlistcur\@inlistwant\in@true\fi\expandafter\@inlist@scan\fi}
% ── appending tokens to a macro ─────────────────────────────────────────────
% \g@addto@macro (global) / \@addto@macro (local): append #2 to the body of the
% macro #1. Uses an \expandafter chain instead of \toks@ (the engine has no toks
% registers): \expandafter…\def\expandafter#1\expandafter{#1#2} redefines #1 to be
% its old body followed by #2.
\def\@addto@macro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}
\long\def\g@addto@macro#1#2{\expandafter\gdef\expandafter#1\expandafter{#1#2}}
% ── list iteration (\@for over a comma list, \@tfor over tokens) ─────────────
% Authentic latex.ltx definitions (they need only \ifx, \def, \expandafter, the
% \@nil/\@nnil/\@empty sentinels and delimited parameters — all available).
\long\def\@fornoop#1\@@#2#3{}
\long\def\@for#1:=#2\do#3{%
  \expandafter\def\expandafter\@fortmp\expandafter{#2}%
  \ifx\@fortmp\@empty \else
    \expandafter\@forloop#2,\@nil,\@nil\@@#1{#3}\fi}
\long\def\@forloop#1,#2,#3\@@#4#5{\def#4{#1}\ifx #4\@nnil \else
       #5\def#4{#2}\ifx #4\@nnil \else#5\@iforloop #3\@@#4{#5}\fi\fi}
\long\def\@iforloop#1,#2\@@#3#4{\def#3{#1}\ifx #3\@nnil
       \expandafter\@fornoop \else
    #4\relax\expandafter\@iforloop\fi#2\@@#3{#4}}
\def\@tfor#1:=#2\do#3{%
  \def\@fortmp{#2}\ifx\@fortmp\@empty \else
    \expandafter\@tforloop#2\@nil\@nil\@@#1{#3}\fi}
\long\def\@tforloop#1#2\@@#3#4{\def#3{#1}\ifx #3\@nnil
       \expandafter\@fornoop \else
    #4\relax\expandafter\@tforloop\fi#2\@@#3{#4}}
\long\def\@break@tfor#1\@@#2#3{\fi\fi}
% ── star/long dispatch ──────────────────────────────────────────────────────
% \@star@or@long\cmd peeks for a '*' (via \@ifstar) and runs \cmd either way, and
% sets \l@ngrel@x to the prefix the definition should carry — \relax after a star,
% \long without one, exactly as the LaTeX kernel does. \long is an accepted no-op
% prefix here (the engine does not model the \par-in-argument restriction), but the
% MEANING of \l@ngrel@x is read: etoolbox's \newrobustcmd branches on
% \ifx\l@ngrel@x\relax to decide between \protected and \protected\long, so a
% \l@ngrel@x that is neither sends every starred command down the long branch.
\let\l@ngrel@x\relax
\def\@star@or@long#1{\@ifstar{\let\l@ngrel@x\relax#1}{\let\l@ngrel@x\long#1}}
% \@ifnextchar is a native primitive (real \ifx-based look-ahead over any target
% token, including control sequences) — see the engine's primitive table.
% \@testopt{<cmd>}{<default>} runs <cmd> on a following [optional argument], or on
% [<default>] when there is none — the kernel's optional-argument dispatcher, which
% every \newcommand-with-a-default and etoolbox's \newrobustcmd are built on. The
% default is BRACED so a multi-token default arrives as one argument.
\long\def\@testopt#1#2{\@ifnextchar[{#1}{#1[{#2}]}}
% \@protected@testopt\cmd is the same dispatcher guarded by \protect: in the real
% kernel the guard chooses between typesetting and writing the command to a file.
% This engine has one \protect meaning (typesetting — nothing is written to .aux
% for a later run), so the guard is always true and the argument, which only the
% write branch uses, is dropped.
\def\@typeset@protect{}
\def\@protected@testopt#1{\@testopt}
% ── the file list and the file-name parser ──────────────────────────────────
% Three kernel names a package may call, all three missing. Their meanings are not
% guessed: they were read out of a compiled document with \meaning, under
% tectonic 0.17.0.
%
%   \@filelist        \relax
%   \@addtofilelist   \long macro:#1->        (a no-op, unless \listfiles)
%
% A no-op looks like something worth skipping, and it is not: xkeyval.sty WALKS
% \@filelist at load time to find the document class —
%
%   \XKV@whilist\@filelist\XKV@tempa\ifx\XKV@documentclass\@undefined\fi{…}
%
% and with \@filelist undefined that walk left THREE GROUPS OPEN. Everything the
% package defined afterwards was then group-local and rolled back at the end, so
% \XKV@fams came out empty and \setkeys reported every key undefined
% (go-tex/engine#306). An undefined name that a loop walks is not a missing
% feature, it is an unbalanced loop.
\let\@filelist\relax
\long\def\@addtofilelist#1{}
% \filename@parse{<name>} splits a file name into \filename@area, \filename@base
% and \filename@ext, the Unix flavour (latex.ltx:223-233 and 264-280; the VMS, Mac
% and generic flavours differ only in the directory separator, and this engine
% resolves paths with /). \filename@ext is \relax — not empty — when the name
% carries no dot, which is the test callers make.
\def\filename@parse#1{%
  \let\filename@area\@empty
  \expandafter\filename@path#1/\\}
\def\filename@path#1/#2\\{%
  \ifx\\#2\\%
     \def\reserved@a{\filename@simple#1.\\}%
  \else
     \edef\filename@area{\filename@area#1/}%
     \def\reserved@a{\filename@path#2\\}%
  \fi
  \reserved@a}
\def\filename@simple#1.#2\\{%
  \ifx\\#2\\%
    \let\filename@ext\relax
    \edef\filename@base{#1}%
  \else
    \filename@dots{#1}#2\\%
  \fi}
\def\filename@dots#1#2.#3\\{%
  \ifx\\#3\\%
    \def\filename@ext{#2}%
    \edef\filename@base{#1}%
  \else
    \filename@dots{#1.#2}#3\\%
  \fi}
\def\filename@dot#1.\\{#1}
% ── \@argdef / \@yargdef: build an n-argument definition ─────────────────────
% These are the kernel's own definition builders, and packages call them directly
% — etoolbox's \newrobustcmd routes every command it defines through \@argdef (no
% optional argument) or \@yargdef (with one). They were missing, so etoolbox
% defined NOTHING: \mode, on which every line of beamer stands, simply did not
% exist, and the class's own \mode<all> printed "<all>" onto the page.
%
% Written exactly as the LaTeX kernel writes them (read back from a real TeX with
% \meaning). \@yargd@f assembles the parameter text #1#2…#n by matching against a
% ready-made run of nine parameters, and stops at the requested count using a
% parameter text that ends in "#{" — the argument runs up to the opening brace,
% which stays behind to open the body.
\long\def\@argdef#1[#2]#3{\@ifdefinable#1{\@yargdef#1\@ne{#2}{#3}}}
\long\def\@reargdef#1[#2]{\@yargdef#1\@ne{#2}}
\long\def\@yargdef#1#2#3{%
  \ifx#2\tw@
    \def\reserved@b##11{[####1]}%
  \else
    \let\reserved@b\@gobble
  \fi
  \expandafter\@yargd@f\expandafter{\number#3}#1}
\long\def\@yargd@f#1#2{%
  \def\reserved@a##1#1##2##{\expandafter\def\expandafter#2\reserved@b##1#1}%
  \l@ngrel@x\reserved@a 0##1##2##3##4##5##6##7##8##9###1}
% \kernel@ifnextchar is the kernel's own name for \@ifnextchar (the kernel keeps a
% private copy so a package that redefines \@ifnextchar cannot break the kernel).
% beamer's overlay decoder calls it by that name.
% \maxdimen is plain TeX's largest dimension. Package code uses it as "no limit"
% (\vbox to\maxdimen, \dimen0=\maxdimen), so its absence is not a rounding matter:
% the assignment simply does not happen.
\newdimen\maxdimen \maxdimen=16383.99998pt
% \@cons\list{\item} appends an \@elt-separated item to a LaTeX list macro, with
% \@elt made harmless while the list is rebuilt.
\def\@cons#1#2{\begingroup\let\@elt\relax\xdef#1{#1\@elt #2}\endgroup}
% \@onelevel@sanitize\cs rewrites \cs's content as ordinary characters, which is
% how the kernel makes a name safe to compare or write out. \strip@prefix drops
% the "macro:->" that \meaning prints in front of the body.
\def\strip@prefix#1>{}
\def\@onelevel@sanitize#1{\edef#1{\expandafter\strip@prefix\meaning#1}}
\let\kernel@ifnextchar\@ifnextchar
% \in@{<a>}{<b>} sets \ifin@ true iff the token list <a> occurs inside <b>. The
% kernel builds it as a delimited-match macro; keyval and beamer's option handling
% both ask it.
\def\in@#1#2{%
  \def\in@@##1#1##2##3\in@@{%
    \ifx\in@##2\in@false\else\in@true\fi}%
  \in@@#2#1\in@\in@@}
% \@makeother makes a character ordinary — how a package reads text verbatim — and
% \dospecials is plain TeX's list of the characters that need it.
\def\@makeother#1{\catcode` + "`" + `#1=12\relax}
\def\dospecials{\do\ \do\\\do\{\do\}\do\$\do\&\do\#\do\^\do\_\do\%\do\~}
% \@onlypreamble{\cmd} records a command as preamble-only. The list is kept, so
% code that walks \@preamblecmds finds what it expects; the engine does not
% disable the commands at \begin{document}, which only costs a worse error message
% for a document that misuses one.
\def\@preamblecmds{}
\def\@onlypreamble#1{%
  \expandafter\gdef\expandafter\@preamblecmds\expandafter{\@preamblecmds\do#1}}
\long\def\@xargdef#1[#2][#3]#4{%
  \@ifdefinable#1{%
    \expandafter\def\expandafter#1\expandafter{%
      \expandafter\@protected@testopt\expandafter#1%
      \csname\string#1\endcsname{#3}}%
    \expandafter\@yargdef\csname\string#1\endcsname\tw@{#2}{#4}}}
% ── logging / diagnostics: never abort a .sty, route everything to \message ──
% \MessageBreak/\protect/\on@line/\@spaces are the tokens warnings interpolate;
% keep them harmless inside the \message expansion. \@ehc/\@ehd are the "error
% help" tokens callers pass as the last argument of \PackageError/\ClassError.
\def\MessageBreak{ }
\def\protect{}
\def\on@line{}
\def\@spaces{}
\def\@ehc{}
\def\@ehd{}
% \restorecr puts the end-of-line character back to catcode 5, which is what
% latex.ltx:6648 does and the whole of what it does. It writes the character with
% TeX's backtick notation; 13 is the same character and is what this format can
% carry, since a backtick would close the Go string this text lives in (the same
% reason \catcode64=11 is written that way above).
%
% It is the undo for \obeycr, and packages call it DEFENSIVELY before reading
% something whose line endings matter — fancyhdr's \fancy@reset opens with
% \restorecr\endlinechar=13 (fancyhdr.sty:322), once per head or foot built. That
% is why the census of undefined commands counts 111 of them over 5 papers, and
% the five are the same five that ship fancyhdr.
%
% \obeycr, its pair, is NOT defined here: nothing in the corpus calls it, and a
% document that does gets the end of line at catcode 5 either way — which is the
% state \restorecr exists to return to.
\def\restorecr{\catcode13=5 }
\def\wlog#1{\message{#1}}
\long\def\typeout#1{\message{#1}}
\def\PackageWarning#1#2{\message{Package #1 Warning: #2}}
\def\PackageWarningNoLine#1#2{\message{Package #1 Warning: #2}}
\def\PackageInfo#1#2{\message{Package #1 Info: #2}}
\def\PackageError#1#2#3{\message{Package #1 Error: #2}}
\def\ClassWarning#1#2{\message{Class #1 Warning: #2}}
\def\ClassWarningNoLine#1#2{\message{Class #1 Warning: #2}}
\def\ClassInfo#1#2{\message{Class #1 Info: #2}}
\def\ClassError#1#2#3{\message{Class #1 Error: #2}}
% \aftermaketitle@chk{<name>} is revtex's guard against a front-matter construct used
% AFTER \maketitle: the argument is only the construct's name, for the error message,
% and the macro never typesets it. aastex inherits it and calls it once, from the
% BEGIN code of an environment it renews:
%
%	\renewenvironment{frontmatter@abstract}{%
%	  \aftermaketitle@chk{\begin{abstract}}%
%
% ⛔ Undefined, it is SKIPPED — and skipping releases its argument, so \begin{abstract}
% runs, which enters frontmatter@abstract, which reaches \aftermaketitle@chk again.
% Unbounded recursion out of a name that was never meant to be typeset. Measured on
% 2607.24141 (aastex631, 123KB of source): \aftermaketitle@chk skipped 100000 times —
% the runaway guard's own limit — 200005 groups left open, and the document came out as
% ONE page. A missing no-op cost the whole paper.
%
% Defined to discard its argument, which is what the real one does with it whenever the
% construct is in the right place: this engine does not enforce front-matter ordering,
% so the check is always the silent branch.
\long\def\aftermaketitle@chk#1{}
\def\@latex@warning#1{\message{LaTeX Warning: #1}}
\def\@latex@warning@no@line#1{\message{LaTeX Warning: #1}}
\def\@latex@info#1{\message{LaTeX Info: #1}}
\def\@latex@info@no@line#1{\message{LaTeX Info: #1}}
\def\@latex@error#1#2{\message{LaTeX Error: #1}}
\def\@warning#1{\message{Warning: #1}}
% ── begin/end-document and package/class hooks ──────────────────────────────
% \AtBeginDocument / \AtEndDocument accumulate tokens fired by \document /
% \enddocument (redefined here to run the hook; the originals in MiniLaTeXKernel
% only toggled the @ catcode / added \vfill). \AtEndOfPackage / \AtEndOfClass
% accumulate into hooks the Go loader runs+resets after each load (see CONTRACT).
% \appendix retargets the section family's cleveref reference TYPE as well as its
% numbering: after it, a \section is an "appendix" and \Cref prints "Appendix A"
% where it printed "Section A" (cleveref.sty:185-215, checked against tectonic).
%
% It is wrapped HERE, at \begin{document}, around whatever \appendix is by then —
% not defined in the kernel. The kernel's own \appendix is overridden by every
% real class: with article.cls resolvable, \meaning\appendix is the CLASS's
% \par\setcounter{section}{0}…, so a \gotex@appendixreftypes written into the
% kernel definition was never reached. 9 of the 16 corpus papers that use \cref
% open an appendix.
\def\gotex@wrapappendix{\@ifundefined{appendix}{}{%
  \let\gotex@origappendix\appendix
  \def\appendix{\gotex@origappendix\gotex@appendixreftypes}}}
\def\@begindocumenthook{}
\def\@enddocumenthook{}
\def\@endofpackagehook{}
\def\@endofclasshook{}
% These take NO argument of their own, exactly as latex.ltx writes them:
% \def\AtBeginDocument{\g@addto@macro\@begindocumenthook}. The braced code is
% grabbed by \g@addto@macro, which is \long (checked against real LaTeX:
% "\long macro:#1#2->\begingroup\toks@\expandafter{#1#2}\xdef#1{\the\toks@}…").
% Taking the argument here instead made a NON-long macro read it, so a hook whose
% code spans a blank line tripped the \par check of tex.web §392.
\def\AtBeginDocument{\g@addto@macro\@begindocumenthook}
\def\AtEndDocument{\g@addto@macro\@enddocumenthook}
\def\AtEndOfPackage{\g@addto@macro\@endofpackagehook}
\def\AtEndOfClass{\g@addto@macro\@endofclasshook}
% \document / \enddocument run BOTH the classic \AtBeginDocument / \AtEndDocument
% accumulators and the named hooks of the 2020 format (see hooks.go), in the order
% the real format uses: begindocument/before, the \AtBeginDocument code, then
% begindocument/end, then the document environment's own env/document/begin.
%
% ⛔⛔ THE .aux IS READ FIRST AND REOPENED SECOND, which is the order latex.ltx uses
% and the only one that works: \openout truncates, so opening before reading would
% destroy the previous pass's answers. \@newl@bel and the two names built on it —
% \bibcite for citations, \newlabel for references — are what the replayed lines
% call; without them the file would be read and ignored.
%
% The reading is unconditional rather than guarded by \IfFileExists because a first
% pass simply has no such file and \@input is already a no-op then.
\def\@newl@bel#1#2#3{\global\@namedef{#1@#2}{#3}}
\def\bibcite{\@newl@bel b}
\def\newlabel{\@newl@bel r}
% ⛔⛔ AND THE LINES THAT DO NOTHING MUST SAY SO. An .aux carries more than answers:
% \citation{key}, \bibdata{file}, \bibstyle{style} are notes for BibTeX and
% \@writefile{toc}{…} is a note for the contents file, and LaTeX gobbles all of them
% on the way back in (\let\citation\@gobble, latex.ltx:13282; \bibdata and \bibstyle
% :13296-13297). Undefined, each one met its argument and lenient mode set that
% argument as text: the first line of the witness read "alpha alpha Texte (Author et
% al., 2021)…" — the citation keys, twice, in the body.
%
% That is the same shape as the \sectionmark defect (#708), and it is what makes an
% .aux round-trip dangerous to open halfway: every name the file can carry has to be
% defined before the file is read, or the replay prints its own bookkeeping.
%
% \def and not \let\…\@gobble: \@gobble exists by this point in this file, but a \let
% from a name that does not yet exist copies "undefined" silently, and this kernel
% has already paid for that once.
\def\citation#1{}
\def\bibdata#1{}
\def\bibstyle#1{}
\def\@writefile#1#2{}
% ⛔⛔ AND @ IS STILL A LETTER WHILE THE .aux IS READ. The catcode change used to
% come FIRST on this line, so the replay tokenised \NAT@force@numbers as \NAT
% (undefined, skipped) followed by the CHARACTERS @force@numbers, which reached
% the page as ordinary text — twice, on corpus paper 2201.04865, the moment the
% real natbib.sty was embedded. natbib writes it to \@auxout from \AtEndDocument
% (natbib.sty:966-973, \string\providecommand\string\NAT@force@numbers{} then
% \string\NAT@force@numbers), and real LaTeX reads the file inside \document
% while @ is still of category letter, switching it only afterwards.
%
% ⭐ The defect belongs to the KERNEL, not to natbib: EVERY package that
% round-trips a @-bearing control sequence through the .aux hits it, and natbib
% is merely the first one embedded here that does. It was invisible for as long
% as nothing wrote such a name — #712 made \@auxout a real stream, which is what
% made the file carry anything at all.
%
% ⚠ Not the same thing as #500, which is about a DOCUMENT's own \makeatletter
% surviving \begin{document} and is what \gotexatasked below records. This is the
% kernel's own read, which needs @ to be a letter whatever the document asked.
%
% The body starts at \normalsize, whatever size the preamble left (ltfiles.dtx:302).
% beamer's sidebar outer theme selects the \Large frame-title font in the preamble
% to measure its head band (beamerouterthemesidebar.sty:18-21), and only its font,
% not its size, is reset there; without this, every frame of a Rochester talk was
% set at 14.4pt on 18pt lines. \normalsize also installs \@listI as \@listi
% (size10.clo:47-53), over a style's preamble \def\@listi like tmlr.sty's.
\def\document{\gotex@bodybegins\gotex@wrapappendix\gotex@applybaselinestretch\gotex@setmeasure
  \catcode64=11 \@input{\jobname.aux}\if1\gotexatasked\else\catcode64=12 \fi\immediate\openout\@auxout=\jobname.aux
  \ifx\normalsize\@undefined\else\normalsize\fi
  \UseHook{begindocument/before}\@begindocumenthook
  \UseHook{begindocument}\UseHook{begindocument/end}\UseHook{env/document/begin}}
% \enddocument also plants the LastPage label the lastpage package is loaded for,
% so \pageref{LastPage} — the "page 1 of N" every report and CV wants — names the
% final page. It is placed before the closing \vfill so it falls ON that page, and
% after the closing \par, so the last paragraph has been contributed to the page
% before the marker is taken. Planting it unconditionally rather than behind
% \usepackage{lastpage} costs one unused label and covers the documents that
% inherit it from a class.
%
% Only the PAGE half is used. Real lastpage writes \newlabel{LastPage}{{}{\thepage}},
% so a \ref{LastPage} there is empty where ours gives the last section number;
% emptying \@currentlabel to match cost 348 glyphs off the last page of corpus
% paper 2401.17012 — content that, it turns out, only survives BY passing through
% \@currentlabel. Reported separately; a label nobody \refs is not worth it.
\def\enddocument{\UseHook{env/document/end}\@enddocumenthook\UseHook{enddocument}%
  \UseHook{enddocument/afterlastpage}\UseHook{enddocument/afteraux}%
  \UseHook{enddocument/info}\UseHook{enddocument/end}%
  % The stream becomes a readable file only at \closeout, and the NEXT pass is what
  % reads it — it is carried across by carryCrossRefs, beside the label tables.
  \immediate\closeout\@auxout
  \gotex@rereadaux
  \par\gotex@shipbands\gotex@begindvi\label{LastPage}\vfill\penalty-10000 }
% ── the .aux read a second time, at the end ─────────────────────────────────
% latex.ltx:10879-10886 closes the .aux and reads it straight back, in a group,
% with \@newl@bel bound to \@testdef (which only notes that a label changed). That
% second reading is when the \@writefile lines take effect: \@writefile{ext}{…}
% writes its text to \tf@ext if a package opened that stream, and is silent
% otherwise (latex.ltx:10941-10949). beamer opens \tf@nav in its \AtEndDocument
% (beamerbasemisc.sty:176-177), and every \section, \subsection and frame has put
% an \@writefile{nav}{\headcommand{…}} line in the .aux; the .nav they make is what
% the next run reads at \begin{document} to size and fill the navigation bars
% (beamerbasemisc.sty:87-103, beamerouterthemesplit.sty:45-59). With the
% \@writefile of the reading at \begin{document} (above, a no-op) used here as
% well, no talk ever had a .nav, and a split headline measured 0 sections.
%
% The reading is put in a box that is thrown away: the engine paginates after the
% document is read, so anything a line of the file typesets would otherwise reach
% the last page, where LaTeX has already shipped every page out.
\def\@testdef#1#2#3{\def\reserved@a{#3}\expandafter\ifx\csname #1@#2\endcsname
  \reserved@a\else\@tempswatrue\fi}
\long\def\gotex@writefile#1#2{\@ifundefined{tf@#1}\relax
  {\@temptokena{#2}\immediate\write\csname tf@#1\endcsname{\the\@temptokena}}}
\def\gotex@rereadaux{\begingroup\let\@setckpt\@gobbletwo\let\@newl@bel\@testdef
  \let\@writefile\gotex@writefile\catcode64=11
  \setbox\z@\vbox{\@input{\jobname.aux}}\endgroup}
% ── \AtBeginDvi ─────────────────────────────────────────────────────────────
% latex.ltx:15427 runs \@begindvi INSIDE the first page's shipout box, once
% (\unvbox\@begindvibox, then \global\let\@begindvi\@empty); \AtBeginDvi{code} adds
% to it (latex.ltx:14935, via \__shipout_add_firstpage_material:Nn). IEEEtran, for
% one, uses it for \special{papersize=…} (IEEEtran.cls:546,554). The material of a
% first page is typeset with \baselineskip, \lineskip and \lineskiplimit all zero
% (latex.ltx:15400), which is what a \special or a \message asks of it.
%
% This engine paginates after the document has been read and has no shipout to hang
% the hook on, so the code runs ONCE, at \end{document}, in a box that is thrown
% away: its side effects (\message, \special, \write) happen exactly once, as on
% the first shipout, and it puts nothing on any page. A real document whose
% \AtBeginDvi typeset visible material would differ; none in the corpora does.
\def\@begindvi{}
\def\AtBeginDvi#1{\g@addto@macro\@begindvi{#1}}
\def\gotex@begindvi{\begingroup\baselineskip\z@skip\lineskip\z@skip\lineskiplimit\z@
  \setbox\z@\vbox{\@begindvi}\endgroup\global\let\@begindvi\@empty}
% ── loaded-package / loaded-class registry (see CONTRACT above) ─────────────
\def\@ifl@aded#1#2{\@ifundefined{ver@#2.#1}\@secondoftwo\@firstoftwo}
% \@ptionlist{<file>} expands to the options that <file> was loaded with (the Go
% loader records them in opt@<file>, see the CONTRACT above); empty if it was not.
\def\@ptionlist#1{\@ifundefined{opt@#1}\@empty{\csname opt@#1\endcsname}}
\def\@ifpackageloaded#1{\@ifl@aded{sty}{#1}}
\def\@ifclassloaded#1{\@ifl@aded{cls}{#1}}
% \@ifpackagewith{pkg}{opts}{then}{else}: true iff every option in {opts} is in
% the recorded option list opt@pkg.sty. If that list was never recorded (Go side
% did not populate it), fall back to the else-branch.
% \@ifpackagewith{pkg}{opt}: true iff <opt> is one of the options recorded for the
% package in opt@pkg.sty. LIMITATION: checks a SINGLE option (the dominant real
% use); a multi-option {opt} is compared as one string and will not match.
\def\@ifpackagewith#1#2{\@ifundefined{opt@#1.sty}{\@secondoftwo}{\@ifinlist{#2}{\@nameuse{opt@#1.sty}}\ifin@\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}}
\catcode64=11
`

LaTeX2eKernelHelpers is the LaTeX2e low-level kernel helper layer, loaded by LoadLaTeX right after MiniLaTeXKernel.

View Source
const LaTeXHooks = `` /* 4286-byte string literal not displayed */

This file holds two things a package written after 2020 asks about before it does anything else: HOW OLD THE FORMAT IS, and the HOOK system that a modern format offers instead of patching kernel macros.

The question is not academic. etoolbox ends with

\IfFormatAtLeastTF{2020-10-01}
  {\newrobustcmd*{\AtEndPreamble}{\AddToHook{begindocument/before}}%
   … \endinput}
  {}

and then, in the branch for an OLD format, prepends code to \document and \patchcm ds \enddocument. With no \IfFormatAtLeastTF at all the engine fell through to that old branch, whose \patchcmd cannot match this kernel's macros: the patches failed, their code leaked into the page, and the rest of the document was swallowed. beamer's compatibility layer branches the same way.

Answering "yes, at least 2020-10-01" is both the truthful answer — the hook interface below is exactly what that release introduced — and the one that puts packages on the code path that asks the format for a service rather than rewriting the format's internals.

── What the hook layer models, and what it does not ─────────────────────────

A hook is a named token list that the format executes at a defined moment. The engine stores one macro per hook (gotex@hook@<name>) and runs it at that moment. Modelled:

  • \NewHook / \NewReversedHook / \ProvideHook / \NewMirroredHookPair — declare.
  • \AddToHook{<name>}[<label>]{<code>} — append; the hook need not exist yet.
  • \AddToHookNext{<name>}{<code>} — code that fires at the NEXT use only.
  • \UseHook / \UseOneTimeHook — run (and clear the next-use list).
  • \RemoveFromHook, \IfHookEmptyTF, \ShowHook / \LogHook, \ActivateGenericHook.
  • The document hooks are WIRED: begindocument/before, begindocument, begindocument/end and env/document/begin all fire at \begin{document}; enddocument and its four sub-hooks fire at \end{document}.
  • package/<name>/after and file/<name>/after fire from the package loader when that package or file finishes loading (see loadTeXFile).

NOT modelled, deliberately:

  • ORDERING. \DeclareHookRule and the [<label>] argument are accepted and ignored; code runs in the order it was added. \RemoveFromHook therefore empties the whole hook rather than one label's contribution.
  • cmd/<name>/before and cmd/<name>/after. Those ask the format to inject code into the BODY of an existing command, which needs the command's argument count to place the "after" part. The engine records such a hook and never fires it. The one caller that reaches this in a beamer talk is the pdfpages integration, which needs pdfpages itself.
  • Reversed hooks run in the order added, like ordinary ones (ordering again).
View Source
const MiniLaTeX = `` /* 167-byte string literal not displayed */

MiniLaTeX is a small LaTeX-flavoured kernel written *in TeX* — the engine runs these macro definitions through its gullet exactly as a real format does; they are not reimplemented in Go. It is deliberately tiny (the road to parity is to grow this by loading the real latex.ltx, not to hand-code commands).

View Source
const MiniLaTeXKernel = `` /* 152824-byte string literal not displayed */

MiniLaTeXKernel is the LaTeX-flavoured macro layer loaded by LoadLaTeX (after the Plain macros).

View Source
const NoProgressLimitHeavy = tightLoopStepsHeavy

NoProgressLimitHeavy is the ceiling a program that renders whole documents should put in Options.NoProgressLimit. See tightLoopStepsHeavy for what it costs and what it buys.

View Source
const Plain = `` /* 3987-byte string literal not displayed */

Plain is a small set of plain-TeX structural macros, written *in TeX* on top of the box/glue primitives (\hbox to, \hfil, \vskip). Loaded with LoadPlain, they let a document use the familiar commands without any Go-side support — the same growth path as the kernel: add macros, do not hand-code commands.

View Source
const RevtexAuthorBlock = `` /* 1238-byte string literal not displayed */

RevtexAuthorBlock is a pragmatic revtex4 / revtex4-1 / revtex4-2 title-block emulation, loaded for a revtex document class when the real revtex .cls is not bundled with the paper (the common case — revtex is not embedded).

The article-shaped fallback leaves \affiliation and revtex's other author-list commands undefined. That is the single most frequent "undefined control sequence" across the arXiv corpus (~11% of papers): it strict-fails, and in lenient mode it silently DROPS the whole author / affiliation block — the names, affiliations and contact lines vanish, because each undefined command swallows nothing while its braced argument lands in a discarded preamble area.

This accumulates those commands into a centred block that \maketitle emits, so the content survives. It does NOT reproduce revtex's superscript-address layout (authors grouped under shared, numbered affiliations); the goal is faithful CONTENT, not that geometry. But the block is kept COMPACT — all authors on one wrapped paragraph (comma-joined), all affiliations/contacts on one wrapped italic paragraph (semicolon-joined) — rather than one line per command. A one-line-per-command block is far TALLER than real revtex's grouped format for a many-author paper, which pushes the whole body down and wrecks the word-POSITION match against the reference even though every word is present (measured: 2605.12538, 7 authors, went to 5.8 layout-divergence at 94.5% recall). Comma/semicolon joining keeps the block height near revtex's, recovering that layout without losing content. revtex prints NO "Abstract" heading — checked against the real class through tectonic, on the minimal document and on a corpus paper: page one goes straight from the affiliations to the abstract's own text. The generic \abstract (latex.go) centres one, which is right for article and wrong here, so this does not carry it over.

The ABSTRACT is captured, not typeset where it stands. In revtex the abstract is written BEFORE \maketitle and emitted BY it, after the authors; the generic \abstract (latex.go) sets it in place, so the playground and every rendered revtex paper carried its abstract ABOVE its own title. It is collected into a box with \global\setbox — local would be restored by the \endgroup that \end{abstract} runs, and the abstract would vanish — and \maketitle places it. An abstract that comes AFTER \maketitle (some papers do) is emitted as soon as it closes, so the order is right either way and nothing is ever dropped.

\author accumulates here — revtex allows several, each followed by its own \affiliation — rather than overwriting as the base article \author does. It runs at document time (from \documentclass), where @ is an "other" character, so it opens with \makeatletter for its @-commands.

View Source
const StepLimitHeavy = maxExpandStepsHeavy

StepLimitHeavy is the absolute ceiling a program that renders whole documents should put in Options.StepLimit. See maxExpandStepsHeavy for the measurement that sets it.

Variables

View Source
var (
	Box            = linebreak.Box
	Glue           = linebreak.Glue
	GlueOrder      = linebreak.GlueOrder
	Glyph          = linebreak.Glyph
	Penalty        = linebreak.Penalty
	KnuthPlass     = linebreak.KnuthPlass
	KnuthPlassWith = linebreak.KnuthPlassWith

	// The SHAPED breaker, for a paragraph whose lines are not all the same
	// width: \hangindent with \hangafter, and \parshape when this engine grows
	// the primitive. tex.web §847-850 takes one measure per line, and the width
	// is an input to every candidate break's badness — so a shape is a
	// line-breaking parameter and not a placement one.
	KnuthPlassShaped = linebreak.KnuthPlassShaped
	Uniform          = linebreak.Uniform
	HangIndent       = linebreak.HangIndent
	ParShape         = linebreak.ParShape
)
View Source
var PDFPageCount func(data []byte) int

PDFPageCount reports how many pages a PDF holds. Wired by the same consumer that wires the rasteriser; nil leaves \includepdf to its byte heuristic.

View Source
var RasterizePDF func(data []byte, dpi float64) (image.Image, error)

RasterizePDF, when set by a consumer, rasterises a PDF figure (the bytes of an included .pdf) to an image at the given DPI. It is the seam for \includegraphics of vector PDFs: a pure-Go PDF renderer is a heavy dependency, so the engine core stays free of it — the CLI and loom inject one (see go-tex/pdfrender), while the browser/wasm build leaves it nil and shows a placeholder. EPS is not handled here.

View Source
var RasterizePDFPage func(data []byte, page int, dpi float64) (image.Image, error)

RasterizePDFPage rasterises one page of a PDF, the way RasterizePDF does the first. A consumer wires both together (cmd/gotex/pdffigures.go); the engine core leaves them nil so the browser build carries no renderer.

Functions

func CompileToPDF added in v0.36.0

func CompileToPDF(src []byte, opt Options, w io.Writer) (int, error)

CompileToPDF processes TeX source and writes a PDF to w, returning the page count. A document's own \font/\hsize/… override the option defaults.

func CompileToPDFReport added in v0.158.0

func CompileToPDFReport(src []byte, opt Options, w io.Writer) (int, map[string]int, error)

CompileToPDFReport is CompileToPDF that also returns the skipped-command tally (see CompileToSVGPagesReport / SkippedCommands).

func CompileToSVGPages added in v0.36.0

func CompileToSVGPages(src []byte, opt Options) ([]string, error)

CompileToSVGPages processes TeX source and returns one SVG string per page — the form an editor preview pane consumes directly.

func CompileToSVGPagesReport added in v0.158.0

func CompileToSVGPagesReport(src []byte, opt Options) ([]string, map[string]int, error)

CompileToSVGPagesReport is CompileToSVGPages that also returns the tally of undefined control sequences the (lenient) compile skipped — see SkippedCommands. It lets a caller surface the feature gaps a best-effort render would otherwise hide: an unimplemented command silently dropped can take a document's whole body with it (a class's frontmatter macro, \subfile, …) while the page still looks plausible. Ranked over a corpus, the tally points straight at what is worth implementing.

func LineAt added in v0.65.0

func LineAt(spans []SourceSpan, x, y float64) int

LineAt returns the source line of the last glyph span whose box contains (x, y), or 0 when the point is over no glyph. Last-wins so nested/overlapping content (a table cell over its row) resolves to the innermost glyph painted there.

Types

type Diagnostics added in v0.158.0

type Diagnostics struct {
	Skipped    map[string]int // undefined control sequences, by count (internal markers removed)
	Runaway    bool           // the expansion/argument runaway guard tripped
	OpenGroups int            // groups still open at end of the document (a likely swallow)
	PageCapHit bool           // pagination hit the maxPages backstop (a page-count explosion)
	// OverfullLines and UnderfullLines count the lines the breaker itself judged
	// bad in the paragraphs the document ACTUALLY GOT, and WorstOverfull is the
	// largest overflow among them, as a fraction of the line's shrink.
	//
	// ⛔ THE ENGINE KNEW THIS ALL ALONG AND SAID NOTHING. hasBadLine decides
	// which line-breaking pass to run and reached no caller — the same shape as
	// the \hangindent defect of #760, and worse, because an overfull line is the
	// single most common thing a real TeX complains about. See badbox.go for why
	// the thresholds are the breaker's own and not \hbadness/\hfuzz.
	OverfullLines  int
	UnderfullLines int
	WorstOverfull  float64
	// Messages is what the document itself said: the text of every \message and
	// \typeout, in order. A real TeX prints this to the terminal and the log, and
	// it is how a document (or a package) reports what it decided — which branch of
	// an \ifx it took, which driver it picked, what \the of a length says. The
	// engine collected it and no caller could see it, so a probe written the way TeX
	// documents it prints nothing, and a diagnosis has to typeset its answers onto a
	// page instead. Empty unless the document said something.
	Messages string
	// Shows is what \showthe asked to be shown, one "> value." per line.
	//
	// ⛔ IT IS SEPARATE FROM Messages BECAUSE TeX TREATS IT DIFFERENTLY. \message is
	// the document talking, and a caller may reasonably not want it; \showthe is a
	// DIAGNOSTIC the user asked for by name, and tex.web:23721-23726 writes it to the
	// log and the terminal whatever the interaction mode. Folding it into Messages put
	// it behind -messages, where our own measurement tooling could not see it: measure
	// dimens writes one \showthe per dimension and read ZERO of them, because the flag
	// it would have to pass is this engine's and not a real TeX's. (#686)
	Shows string
	// RunawayArgs counts the macro calls abandoned because a \par ended an argument
	// (tex.web §392/§396, parEndsArgument). It is an ALARM, not a feature gap: the
	// call is dropped, so whatever it would have set is gone. It used to be tallied
	// in Skipped under the error message itself, which the report then printed as a
	// command NAME — "\Paragraph ended before argument was complete", 44 of them on
	// one paper — so a corpus census read an error as the fifth most missing macro.
	RunawayArgs int
	// RunawayMacros counts those abandoned calls BY MACRO. The total alone says a
	// document lost something; the name says what, which is what makes the alarm
	// worth acting on.
	RunawayMacros map[string]int
	// UndefinedEnvs counts \begin{env} whose environment was undefined — a silent
	// no-op that never appears in Skipped (\csname coerces the missing \env to
	// \relax). Aggregated over a corpus it surfaces unimplemented environments
	// (math/float/theorem) whose bodies were then typeset in the wrong mode.
	UndefinedEnvs map[string]int

	// MathDropped tallies whole equations the go-tex/math layer refused and the engine
	// dropped, keyed by the unknown math command that triggered it ("\X") or "$math$"
	// for a non-command math error. This is invisible content loss INSIDE a formula:
	// one unrecognised token drops the entire equation. These are lifted out of Skipped
	// (which stays text-mode undefined commands) so a math feature gap is not conflated
	// with a missing text macro. nil/empty when no equation was dropped.
	MathDropped map[string]int

	// FontsSubstituted names the text-font packages the document asked for, mapped to
	// the face it wanted. The engine sets ONE built-in face, so every entry here is a
	// silent substitution of a different WIDTH — and width is what decides how many
	// words fit on a line, hence how long the document is. acmart's Linux Libertine
	// against our substitute measured 15.8% narrower per character, which is two
	// pages in eight (go-tex/engine#310). Reported because nothing else reveals it:
	// the package's macros are all defined, so it never appears in Skipped.
	FontsSubstituted map[string]string

	// FiguresDropped tallies figures whose file could not be loaded, keyed by cause
	// ("PDF figure, no rasteriser wired", "file not found", "unreadable or
	// unsupported format"). The engine still reserves a placeholder box, so this is
	// not lost layout — it is lost PICTURE, and the cause says whether the document
	// is at fault or the engine is. nil/empty when every figure loaded.
	FiguresDropped map[string]int

	// PackagesWithoutSty names the packages \usepackage asked for and for which no
	// .sty file could be resolved — not on the document's path, not in a support
	// tree, not embedded — so that nothing of them ran but what the engine itself
	// emulates. A package here that the document depends on is the cause behind its
	// skipped commands: the file was never read. Sorted. nil when every package
	// that is not emulated wholesale was found.
	PackagesWithoutSty []string

	// FilesMissing tallies files the document names and that are not there, keyed
	// by the command that asked: "\\input", "\\bibliography", "\\putbib". It is NOT
	// a missing command — every one of those is defined and RAN; what failed is
	// that the file is not in the submission. Tallied in Skipped, as they were,
	// the report printed "undefined command(s) skipped: \\input" over a corpus
	// where \\input works, and a census read that as an engine gap. nil/empty when
	// every named file was found.
	FilesMissing map[string]int

	// ExtraBrace tallies TeX's "Argument of \x has an extra }" recoveries, keyed by
	// the macro and the line, e.g. "\\use@pgfmodule (line 661)". It is a RECOVERY,
	// not a missing command, and it has its own field for the reason RunawayArgs
	// does: tallied in Skipped it was printed as a command NAME, so the report
	// offered "\Argument of \@authoropt has an extra }" as an undefined command and
	// a corpus census read a sentence as a macro. Same mistake, same fix.
	ExtraBrace map[string]int
	// ReadsOutsideTree counts the paths the DOCUMENT named that resolved outside the
	// directory the engine started in — an absolute path, or one that walked out with
	// ../ — by path. Reading a named file is what \input is for and this is not an
	// error; it is the fact a host compiling third-party documents needs in order to
	// refuse a result. Empty for every document that stays where it lives.
	ReadsOutsideTree map[string]int
	// AlignmentsAbandoned counts alignments dropped WHOLE because the mandatory
	// left brace was not found, keyed by the primitive ("\\halign"). It has its own
	// field for the reason every other alarm here does: nothing else could show it.
	// The primitive is defined and the preamble's commands are defined, so Skipped
	// stays empty; what reaches the page is the alignment's own source, preamble
	// included. \halign\bgroup — IEEEtran.cls writes exactly that for its author
	// block — put a stray "#" on a real paper's title page and made \noalign and
	// \everycr look undefined (#602). nil/empty when every alignment was entered.
	AlignmentsAbandoned map[string]int
	// ExpansionSteps is how many expansion steps the compile took, and
	// NoProgressPeak the longest run of them that read no new base input. The
	// guard that stops a runaway has TWO ceilings, and without these a reader
	// cannot tell which one a document is near — nor that it is near one at all
	// until it is over. A loop pins NoProgressPeak to the tight ceiling while
	// ExpansionSteps stays small; a document that is merely enormous does the
	// opposite. Reported for every compile, so the margin is visible BEFORE a
	// document crosses it.
	ExpansionSteps int
	NoProgressPeak int
	// KerningIsAFloor says a face was used whose kerning this engine CANNOT FULLY
	// READ, so every kern figure in this compile is a floor and not a measurement.
	//
	// ⛔ IT BELONGS WITH THE SILENT-SWALLOW FLAGS ABOVE AND FOR THE SAME REASON.
	// kernSP asks go-opentype for the kern between two glyphs, and that is a PAIR
	// query: GPOS lookup types 7 (Contextual) and 8 (Chained Contextual) position
	// pairs too, and a pair query cannot evaluate them, because such a rule is
	// matched against the glyphs AROUND a position. The library skips those
	// subtables and answers 0 — the same 0 it gives for a pair the font
	// deliberately leaves alone. Nothing distinguished the two, which is #716: a
	// kerning defect of 1.12pt per "AV" invisible to every number this engine's
	// fidelity measurement steers by.
	//
	// ⚠ IT IS NOT A CLAIM THAT ANY KERN WAS WRONG. It says the figures are a
	// floor. Measured over the 81 fonts go-opentype/fonts bundles, 8 carry such
	// lookups — seven complex-script Noto faces and notosans.ttf, a general Latin
	// sans — so it is neither rare nor exotic. Whether it fires on a given
	// document's text, and by how much, this flag does not say.
	//
	// False for every font whose kerning is pair adjustment, which is the ordinary
	// case, and false for a face that cannot be asked at all (a test mock).
	KerningIsAFloor bool

	// RegistersExhausted counts allocations refused because that pool of
	// registers is full, keyed by kind (`\count`, `\dimen`, `\skip`, `\box`,
	// `\toks`).
	//
	// ⛔ A NON-EMPTY MAP MEANS THE DOCUMENT IS WRONG IN A WAY NOTHING ELSE
	// REPORTS. The name a \newcount could not satisfy stays UNDEFINED; whatever
	// used it reads 0 or vanishes, and the run completes normally. TeX stops at
	// this point with "No room for a new \count"; this engine carries on, which
	// is a deliberate choice (TestNewcounterExhaustion) — but a choice whose cost
	// was invisible until now.
	//
	// Measured 2026-11-15: loading the real tikz and calc leaves 86 of 256
	// `\count` registers and 230 of 256 `\box` (#788). A package-heavy paper
	// spends 86 quickly, so this is reached by real documents and not only by a
	// probe.
	RegistersExhausted map[string]int

	// RegistersOutOfRange counts register accesses whose index cannot exist in
	// any pool — negative, or at least registerPoolSize (eTeX's 32768) — keyed
	// by kind (`\count`, `\dimen`, `\skip`, `\box`).
	//
	// ⛔ EACH OF THESE USED TO BE A PANIC, NOT A TALLY. Measured at 39da8fe,
	// `\the\count300` took the process down with "index out of range [300] with
	// length 256": the bound lived as a literal at the write sites and was simply
	// absent from the reads. 300 is now an ordinary register, so what remains
	// here is a genuinely impossible index, which TeX answers with "Bad register
	// code" and refuses outright.
	//
	// A register inside the pool that nothing has written is not counted: it
	// holds its zero value legitimately, and counting it would report every
	// `\the\count` of a fresh register.
	RegistersOutOfRange map[string]int
}

Diagnostics summarises what a lenient compile may have quietly lost. Beyond the undefined commands it skipped, it flags the signals of a SILENT swallow — content dropped with no undefined command at all: a runaway loop or exponential scan that tripped the guard, groups left open at the end of the document (an unbalanced { or \begingroup, the fingerprint of an eager-box or delimited-scan swallow), and a pagination explosion capped at maxPages. Aggregated over a corpus these surface problems SkippedCommands cannot see.

func CompileToPDFDiag added in v0.158.0

func CompileToPDFDiag(src []byte, opt Options, w io.Writer) (int, Diagnostics, error)

CompileToPDFDiag is CompileToPDF that also returns the compile's Diagnostics.

func CompileToSVGPagesDiag added in v0.158.0

func CompileToSVGPagesDiag(src []byte, opt Options) ([]string, Diagnostics, error)

CompileToSVGPagesDiag is CompileToSVGPages that also returns the compile's Diagnostics (undefined commands plus the silent-swallow flags — see Diagnostics), for a preview UI's log panel or a corpus report.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine holds all TeX state: the input stack, the eqtb (control-sequence meanings), integer registers, category codes, the grouping save stack, and the \message output buffer.

func New

func New() *Engine

New builds an engine with TeX's default category codes and primitives loaded.

func NewDocument added in v0.36.0

func NewDocument(opt Options) (*Engine, error)

NewDocument builds an engine configured from opts: the Plain macros loaded (unless NoPlain) and the text font family set. It is the starting point for programmatic use when callers want to Run source incrementally before rendering.

func (*Engine) Diagnostics added in v0.158.0

func (e *Engine) Diagnostics() Diagnostics

Diagnostics returns the compile's Diagnostics (see the type). Internal markers (the page-cap tally and the like) are lifted out of Skipped into their own flags.

func (*Engine) LoadFormat added in v0.6.0

func (e *Engine) LoadFormat(src string) error

LoadFormat executes a string of TeX definitions (a format/preamble) through the gullet, defining its macros in the engine's eqtb without typesetting.

func (*Engine) LoadLaTeX added in v0.37.0

func (e *Engine) LoadLaTeX() error

LoadLaTeX loads the Plain macros (if not already) and the minimal LaTeX kernel.

func (*Engine) LoadPlain added in v0.24.0

func (e *Engine) LoadPlain() error

LoadPlain defines the Plain structural macros in the engine.

func (*Engine) Page added in v0.13.0

func (e *Engine) Page() *boxNode

Page vpacks the main vertical list (everything contributed at top level) into a single vbox at natural height. Empty (nil) if nothing was contributed.

func (*Engine) Pages added in v0.17.0

func (e *Engine) Pages() []*boxNode

func (*Engine) Position added in v0.64.0

func (e *Engine) Position() (line, col int)

Position returns the 1-based line and 0-based column of the input the engine is currently reading — the location a diagnostic should point at.

func (*Engine) RenderBox added in v0.12.0

func (e *Engine) RenderBox(i int, margin float64) string

RenderBox renders box register i to an SVG string with a uniform margin (pt). Empty if the register is void.

func (*Engine) RenderPDF added in v0.27.0

func (e *Engine) RenderPDF(w io.Writer, margin float64) error

RenderPDF writes the main vertical list, split into \vsize pages, as a PDF to w. Each page is (content width + 2·margin) × (content height + 2·margin) points. A current OpenType font (with embeddable bytes) is required to draw text.

func (*Engine) RenderPage added in v0.13.0

func (e *Engine) RenderPage(margin float64) string

RenderPage renders the main vertical list to an SVG page with the given margin.

func (*Engine) RenderPages added in v0.17.0

func (e *Engine) RenderPages(margin float64) []string

RenderPages renders each page of the main vertical list to its own SVG string.

func (*Engine) Run

func (e *Engine) Run(src string) (string, error)

Run tokenizes src as the base input and processes it to completion, returning the accumulated \message output.

func (*Engine) SetFont added in v0.14.0

func (e *Engine) SetFont(f fontFace)

SetFont sets the current font used to measure and render characters in horizontal mode. Passing an *OpenTypeFont (or any fontFace) is the Go-level stand-in for TeX's \font primitive until font-file loading via \font lands.

func (*Engine) SkippedCommands added in v0.86.0

func (e *Engine) SkippedCommands() map[string]int

SkippedCommands returns, for a lenient compile, how many times each undefined control sequence was skipped (empty when strict or when none were undefined). It lets a caller surface "these commands were dropped" after a preview compile.

func (*Engine) SourceSpans added in v0.65.0

func (e *Engine) SourceSpans(margin float64) [][]SourceSpan

SourceSpans returns, for each page of the built document, the glyph spans that tie output back to source — the data behind click-to-source and jump-to-line. margin matches the value passed to the SVG/PDF renderers so coordinates align.

type Item added in v0.2.0

type Item = linebreak.Item

Two pieces of this engine are algorithms in their own right, useful to anyone laying out text and not only to a TeX engine, so they now live in their own repositories and this file is the seam:

  • github.com/go-typeset/linebreak — Knuth–Plass optimal line breaking: the box/glue/penalty model and the paragraph builder.
  • github.com/go-typeset/hyphenation — Liang's algorithm: where a hyphen may fall in a word, reading TeX's own pattern files.

The aliases below keep the engine's own code reading as it did (Item, Line, KnuthPlass, …) while the definitions live upstream. What stays HERE is what is genuinely TeX's rather than the algorithm's: the \patterns primitive that loads a pattern file, and the walk that turns a node list into discretionary breaks.

type Line added in v0.2.0

type Line = linebreak.Line

Two pieces of this engine are algorithms in their own right, useful to anyone laying out text and not only to a TeX engine, so they now live in their own repositories and this file is the seam:

  • github.com/go-typeset/linebreak — Knuth–Plass optimal line breaking: the box/glue/penalty model and the paragraph builder.
  • github.com/go-typeset/hyphenation — Liang's algorithm: where a hyphen may fall in a word, reading TeX's own pattern files.

The aliases below keep the engine's own code reading as it did (Item, Line, KnuthPlass, …) while the definitions live upstream. What stays HERE is what is genuinely TeX's rather than the algorithm's: the \patterns primitive that loads a pattern file, and the walk that turns a node list into discretionary breaks.

type LineBackground added in v0.276.0

type LineBackground = linebreak.Background

LineBackground is \leftskip + \rightskip as the breaker sees them: the glue every line carries before its own material (tex.web §16307-16315).

type LineBreakParams added in v0.208.0

type LineBreakParams = linebreak.Params

LineBreakParams carries TeX's demerit parameters to the optimiser.

type Measure added in v0.276.0

type Measure = linebreak.Measure

Measure is the per-line width source a shaped paragraph is broken on.

type OpenTypeFont added in v0.4.0

type OpenTypeFont struct {
	// contains filtered or unexported fields
}

OpenTypeFont adapts a go-opentype face for the engine: it measures glyphs (in points via CharDims and in scaled points via charDimsSP), supplies the interword glue, and returns glyph outline paths for the SVG driver.

func NewOpenTypeFont added in v0.4.0

func NewOpenTypeFont(fontBytes []byte, sizePt float64) (*OpenTypeFont, error)

NewOpenTypeFont builds a metrics source from a font and a size in points.

func (*OpenTypeFont) CharDims added in v0.4.0

func (o *OpenTypeFont) CharDims(r rune) (float64, float64, float64)

CharDims returns a glyph's advance width and its ink height above and depth below the baseline, in pixels.

func (*OpenTypeFont) KerningIsAFloor added in v0.277.0

func (o *OpenTypeFont) KerningIsAFloor() bool

KerningIsAFloor reports whether this face's kerning is one this engine cannot fully read: the font puts part of its `kern` feature in GPOS lookups a pair query cannot evaluate.

⛔ IT IS ASKED ONCE PER FACE AND NOT PER PAIR, because the condition is a property of the font's lookup list. The library genuinely does not know whether the contextual lookup it skipped would have matched at some position, so a per-pair answer could only ever be "maybe".

func (*OpenTypeFont) Space added in v0.4.0

func (o *OpenTypeFont) Space() (float64, float64, float64)

Space returns TeX-like interword glue derived from the space advance.

⛔ AdvanceUnits and NOT Advance: Advance rounds to a whole pixel, and the space is the one glyph whose advance is most often a half — 235 units at 10pt is 2.35pt, 250 units is 2.5pt — so the rounded form answered 2 or 3 and was wrong on both. That is up to half a point on EVERY interword space in the document, about 20% of the space itself, and ~3.9pt per 66-character line.

Measured against XeTeX on the same file, \hbox{A B} minus \hbox{AB}:

                   ours (rounded)   ours (here)   XeTeX
LibertinusSerif        3.00            2.50        2.50
TeXGyreTermesX         3.00            2.50        2.50

and XeTeX's own \fontdimen2 is 2.5pt for both — the glyph's advance exactly, so the quantity was never in doubt, only the rounding.

The unrounded accessor is go-opentype's (v0.19.0), added there rather than spelled out here as AdvanceIndexUnits × Scale, so that every consumer of that library gets the exact path as cheaply as the lossy one.

type Options added in v0.36.0

type Options struct {
	Font       []byte  // roman text font (.ttf/.otf); nil ⇒ the built-in default
	BoldFont   []byte  // optional bold face, bound to \bf (so \textbf really bolds)
	ItalicFont []byte  // optional italic face, bound to \it (so \textit/\emph slant)
	MonoFont   []byte  // optional monospace face, bound to \tt (so \texttt is fixed-width)
	SansFont   []byte  // optional sans-serif face, bound to \sf (so \textsf is sans)
	Size       int     // font size in points (0 ⇒ 10)
	Margin     float64 // page margin in points (0 ⇒ 72)
	NoPlain    bool    // set to omit the Plain macros
	Date       string  // \today text (a pure-Go wasm build has no clock; supply it here)

	// Lenient turns an undefined control sequence from a fatal error into a
	// skipped command: the engine drops the unknown \cs (and its likely
	// [optional]/{mandatory} argument block) and carries on, recording the name
	// for reporting. This is best-effort "produce something" behaviour for real
	// third-party documents that pull in packages/classes gotex does not load —
	// an editor preview shows the typesettable content instead of one hard error.
	// The default (false) is strict: an undefined cs aborts, as TeX does.
	Lenient bool

	// NoProgressLimit raises the ceiling on expansion steps taken with no new
	// base input consumed — the guard that stops a non-terminating expansion.
	// Zero keeps the engine's own, which is tight enough that a loop aborts in a
	// tenth of a second.
	//
	// A program that renders whole documents should ask for
	// NoProgressLimitHeavy: two million steps is too tight for a real
	// package, and pgfplots — which needs three to four million both to load and
	// to draw — stops the document dead without the headroom. It is not the
	// default because a genuine loop then takes ten times as long to abort, and a
	// caller exercising the guard wants it tight.
	NoProgressLimit int

	// StepLimit raises the ABSOLUTE ceiling on expansion steps — the coarse
	// backstop that stops a compile however well the input is advancing. Zero
	// keeps the engine's own.
	//
	// ⛔ A program that renders whole documents should ask for StepLimitHeavy.
	// The engine's own ceiling carries the comment "a large real document stays
	// well under it", and that is false for a figure-heavy paper: one tikzDevice
	// picture of 489 KB — R's output, thousands of coordinates, every one of them
	// through pgfmath — spends tens of millions of steps inside a single \path.
	// Measured on arXiv 2405.11065 with the real pgf sources: at the engine's own
	// ceiling it renders 7 pages of 18 and reports a runaway; with this raised it
	// renders all 18 and reports none. The no-progress ceiling is NOT what was
	// stopping it — raised twentyfold it changes nothing, which is the mistake
	// go-tex/engine#360 recorded for seven weeks.
	//
	// It is not the default for the same reason NoProgressLimit is not: a caller
	// exercising the guard wants it tight, and a genuine loop that also fails to
	// trip the no-progress guard would run far longer before this one caught it.
	StepLimit int

	// Resolve supplies class, package and \input files that the process cannot
	// read from disk, so a host can hand the engine a texmf tree it holds in
	// memory. It is given the file name the document asked for, already carrying
	// an extension (article.cls, beamerbasetitle.sty, pgfcore.code.tex), and
	// returns the file's bytes.
	//
	// It is consulted AFTER the document's own directory and TEXINPUTS/
	// GOTEX_TEXMF — a file next to the document still overrides — and BEFORE the
	// small base set embedded in the binary, so a host that supplies a real
	// article.cls gets its own rather than the built-in one.
	//
	// This is what a build with no filesystem needs: in js/wasm every os.ReadFile
	// fails, so without it a browser host can compile nothing beyond the embedded
	// set. Such a host fetches the files it needs (driven by a scan of the source
	// for \usepackage and friends), keeps them in a map, and answers from it —
	// the engine's own reading stays synchronous.
	//
	// nil (the default) means no host resolver: disk and the embedded set only.
	Resolve func(name string) ([]byte, bool)

	// JobName is TeX's \jobname: the main input file's name without its
	// extension. A document reads and writes files named after it — \jobname.bbl
	// is where LaTeX's own \bibliography looks first, and .aux/.toc/.nav are the
	// same family. Empty keeps TeX's own default for a nameless job, "texput".
	JobName string
}

Options configures a compile. The zero value is valid: a built-in font at 10pt with a 72pt (1 inch) margin.

type Shape added in v0.276.0

type Shape = linebreak.Shape

Shape is one \parshape pair: a left margin and a width.

type SourceError added in v0.64.0

type SourceError struct {
	Line, Col int // 1-based line, 0-based column (0/0 = unknown)
	Msg       string
}

SourceError is an engine error carrying the source location it occurred at, so a caller (a CLI, loom's compile panel) can point the user at the exact line.

func (SourceError) Error added in v0.64.0

func (s SourceError) Error() string

type SourceSpan added in v0.65.0

type SourceSpan struct {
	Line       int
	X, Y, W, H float64
}

SourceSpan is one rendered glyph's bounding box on a page (points, SVG coordinates: origin top-left, Y is the box top) tagged with the source line it came from. It is the programmatic form of the SVG's data-l groups: a caller maps a click (x, y) → line, or a line → its output rectangles.

func RectsForLine added in v0.65.0

func RectsForLine(spans []SourceSpan, line int) []SourceSpan

RectsForLine returns every glyph span originating from the given source line — the boxes an editor highlights when the cursor sits on that line.

Source Files

Directories

Path Synopsis
cmd
gotex command
Command gotex is a pure-Go TeX compiler: it processes a .tex document and writes a PDF (or SVG pages), a drop-in for pdftex/xetex in a loom-style preview/build pipeline.
Command gotex is a pure-Go TeX compiler: it processes a .tex document and writes a PDF (or SVG pages), a drop-in for pdftex/xetex in a loom-style preview/build pipeline.
gotex-abdiff command
Command gotex-abdiff compares TWO REVISIONS OF THIS ENGINE over a fixed corpus of real papers, and says what a change did to pagination.
Command gotex-abdiff compares TWO REVISIONS OF THIS ENGINE over a fixed corpus of real papers, and says what a change did to pagination.
gotex-coverage command
Command gotex-coverage is a corpus content-coverage detector: it renders a directory of real LaTeX papers through the pure-Go engine and flags the SILENT swallows — papers that typeset far less than their source implies.
Command gotex-coverage is a corpus content-coverage detector: it renders a directory of real LaTeX papers through the pure-Go engine and flags the SILENT swallows — papers that typeset far less than their source implies.
gotex-linediff command
Command gotex-linediff puts one page of two PDFs side by side, LINE BY LINE, with the geometry of each line: where it starts, where it ends, its baseline, the face and size it is set in, and — when it holds a leader — how many dots it draws and how far apart.
Command gotex-linediff puts one page of two PDFs side by side, LINE BY LINE, with the geometry of each line: where it starts, where it ends, its baseline, the face and size it is set in, and — when it holds a leader — how many dots it draws and how far apart.
gotex-paramcensus command
Command gotex-paramcensus answers one question about the fidelity corpus: WHICH MEASURED PAPERS SET A GIVEN TeX PARAMETER?
Command gotex-paramcensus answers one question about the fidelity corpus: WHICH MEASURED PAPERS SET A GIVEN TeX PARAMETER?
gotex-refdiff command
Command gotex-refdiff is a reference-diff corpus sampler: the highest-signal fidelity detector for gotex.
Command gotex-refdiff is a reference-diff corpus sampler: the highest-signal fidelity detector for gotex.
gotex-wasm command
Command gotex-wasm compiles the engine to GOOS=js/wasm and exposes LaTeX compilation to JavaScript, so an editor like loom can render LaTeX to SVG *directly in the browser* — no server round-trip, no microVM, no TeX Live.
Command gotex-wasm compiles the engine to GOOS=js/wasm and exposes LaTeX compilation to JavaScript, so an editor like loom can render LaTeX to SVG *directly in the browser* — no server round-trip, no microVM, no TeX Live.
gotex-worddiff command
gotex-worddiff says which words one PDF has that the other lacks.
gotex-worddiff says which words one PDF has that the other lacks.
internal/loadguard
Package loadguard reads the machine's load averages and refuses a measurement taken on a busy machine.
Package loadguard reads the machine's load averages and refuses a measurement taken on a busy machine.
internal/pdfruns
Package pdfruns reads the text a PDF shows — the positioned runs, their fonts and their widths — with nothing outside the standard library and github.com/go-pdfkit/reader.
Package pdfruns reads the text a PDF shows — the positioned runs, their fonts and their widths — with nothing outside the standard library and github.com/go-pdfkit/reader.
internal/refaudit
Package refaudit decides whether a REFERENCE PDF can stand as a reference.
Package refaudit decides whether a REFERENCE PDF can stand as a reference.
internal
pdftext
Package pdftext finds and runs the text extractor the measuring tools share.
Package pdftext finds and runs the text extractor the measuring tools share.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址