Commit Graph
633 Commits
Author SHA1 Message Date
gloamxun e48a64da7a Resolve csname during runtime expansion
\csname only worked inside \edef bodies, so a normal macro such as
\def\a{\csname foo\endcsname} leaked the literal construct. Handle it in the
expand loop: read through \endcsname, expand the inner text with the current
runtime table and scopes, look the resulting control sequence up, and splice
its body (nothing when undefined). Macro arguments are not consumed, so a
parameterized target is left alone for now.

A preview test defines \a through \csname, uses both \a and a direct
\csname foo\endcsname, and checks "Z and Z and ." with no warnings.
2026-10-27 00:49:07 +08:00
gloamxun 34d54d91a4 Honor \catcode`\@ assignments
Class files often set the @ catcode directly instead of calling
\makeatletter. Recognise \catcode assignments in the canonicalisation pass for
the @ target: the target may be written with a backtick, bare, or as a code
point, the value must be numeric (11 letter, 12 other) or \active, and the
assignment is consumed and updates the same state \makeatletter toggles.
Assignments for other characters are left untouched so nothing is silently
dropped.

A preview test sets \catcode`\@=11, defines and uses \@foo, and checks "bar"
with no warnings and no leaked assignment.
2026-10-27 00:46:15 +08:00
gloamxun b056b11ba9 Expand parameterized runtime definitions
runtime_definition only accepted \def\name{body}: if the first token after the
name was not '{' it gave up, leaving a body-embedded \def\foo#1{...} to leak as
text. Parse the parameter text before the body with the same helpers the line
capture uses: definition_argument_count for undelimited #1..#n, otherwise
parameter_placeholders plus the raw parameter text for delimited forms. The
returned MacroDefinition carries args/params, so expand_macro_lookup collects
the arguments during expansion.

A preview test defines \add#1 and \pair#1,#2 mid-body and checks "[x]" and
"(a|b)" with no warnings.
2026-10-27 00:43:51 +08:00
gloamxun 619eb19f72 Map fontspec families to engine faces
fontspec declarations were neither consumed nor mapped, so
\newfontfamily\headingfont{...} leaked into the text. Consume \setmainfont,
\setsansfont and \setmonofont (the engine's Roman/Sans/Mono faces stand in for
those choices) and turn \newfontfamily/\renewfontfamily into an alias macro that
switches to the closest NFSS family by name: mono/typewriter/courier to cmtt,
sans/helvetica/arial to cmss, otherwise cmr. Optional bracket options are
skipped.

A preview test declares all four commands, renders \headingfont Sans words. and
checks no warnings, the sans-serif face and no leaked declaration text. Docs
also record that complex scripts (Devanagari, Thai, emoji) still have no shaping
fallback and render as missing glyphs in the PDF.
2026-10-27 00:41:36 +08:00
gloamxun 81da180ab7 Lay out nested tables inside their cell
Nested tabulars were flattened to a text summary before the outer halign
parsed them, so the inner rows never existed as a table. Keep them instead:
strip_page_geometry replaces each nested block with a \texrranested{index}
token and stores the source on the geometry, and tabular_unit resolves the
token into a recursively built inner table attached to the cell. Cell text is
cleared, column widths and row height take the inner table's metrics, and page
splitting remaps nested row indices when it chunks rows.

Halign gains a nested list, refresh_measurements, nested-aware row_height and a
painting branch that translates the inner display list to the cell position at
the row's alignment. The old flattening pass stays as a dead-code fallback.

The nested-table test now checks one stored source, the placeholder token, one
attached 2x2 table in cell (0, 1), an empty outer cell and inner "a"/"d"
painted in the preview SVG.
2026-10-27 00:38:02 +08:00
gloamxun 371f05baaa Default project previews and PDFs to route-D
uses_route_d still treated v1 as the default unless TEXRRA_ENGINE=route-d was
set, so only the flat /preview endpoint had switched. Make route-D the default
there too: an explicit engine parameter still wins, TEXRRA_ENGINE=v1 forces the
old pipeline, and a route-D error now falls through to the v1 compiler instead
of answering 422 (both preview and PDF).

Because route-D follows pdfLaTeX's Letter default for geometry-less documents,
the two server tests that asserted the v1 A4 page now ask for ?engine=v1 or
expect 215.9mm. A new test starts a server without the environment variable and
checks a project preview uses route-D's italic math face with no literal $.
2026-10-27 00:32:45 +08:00
gloamxun a56d441513 Make route-D the default flat preview engine
POST /preview served the v1 pipeline while route-D lived behind /api/route-d
and the project engine switch. Try route_d::preview_json first and keep the v1
compiler as the fallback when route-D rejects the source; ?engine=v1 forces the
old path and the project endpoints are unchanged.

Both paths now answer with an X-Preview-Engine header (route-d or v1) so the
choice is observable, and the server test helper compares header names
case-insensitively because tiny-http lowercases them.

A server test posts a document and checks route-d by default plus v1 when the
query asks for it.
2026-10-27 00:27:59 +08:00
gloamxun 621a8abb92 Make @ a letter only inside makeatletter
The scanner treated @ as a letter everywhere, so \makeatletter was a no-op and
\foo@bar parsed as one command even outside it. Canonicalise the source once,
before captures: in the default state a control word stops at @ (and a marker
keeps later scanners from re-joining the split), between \makeatletter and
\makeatother the name is rewritten with a private-use placeholder that
control_sequence and expand_macro_lookup accept as a letter and normalise back
to @. Grouping saves and restores the state, and route-D's own \@... names plus
the internal \p@/\z@/\protected@edef family stay literal so their handlers keep
matching; markers are stripped from text before shaping.

Tests cover \@foo inside makeatletter, \foo@bar splitting to \foo plus "@bar",
\@ifundefined still working, and a group-local \makeatother.
2026-10-27 00:24:28 +08:00
gloamxun d4de3a3f35 Expand body edef definitions when they are read
\edef/\xdef were expanded eagerly only in the preamble: after \begin{document}
the strip pass no longer captured definitions, and capture_body_definitions had
no edef branch, so a body \edef\b{\a} stored the raw body and expanded \a later.
The body branch now calls edef_definition (which also resolves \csname), and the
strip pass leaves body edef/chardef lines to it instead of swallowing them.

A test with \begin{document} defines a=one, \edef b={\a}, redefines a=two and
expects "one and two"; the existing preamble edef/xdef tests still pass.
2026-10-27 00:19:28 +08:00
gloamxun 9aa743b601 Run let/chardef and keep group definitions local
Runtime expansion only understood \def/\gdef. Add \let\alias=\target (a macro
body that expands to the target) and \chardef\name=<code> (a one-character
body), both honoring the current scope, so class-style aliases work and can be
shadowed inside a group.

Line-based capture also still pulled a definition line out of a group and made
it global. Track brace depth across body lines and only capture at depth zero,
and restrict strip_page_geometry's definition capture to the preamble before
\begin{document}; body lines now reach runtime expansion where the scope stack
applies.

Tests preview a group-local \def on its own line as "twoone" and
\let/\chardef as "HiandA".
2026-10-27 00:15:20 +08:00
gloamxun d1b66af251 Scope runtime definitions to their group
Expansion kept a single flat macro table, so a \def inside {...} replaced the
outer definition for the rest of the document. Keep a scope stack in
expand_macros instead: '{' and \begingroup push a scope, '}' and \endgroup pop
it, and lookup walks the scopes newest-first before the document table. A
top-level \def and every \gdef update the document table; a \def inside a group
only shadows until the group closes.

Runtime \def\name{body} is now parsed during expansion (the pre-expansion inline
capture is gone), and grouping braces are dropped after command parsing so the
scope braces do not print: plain pieces, link labels, inline runs and the
fallback face path all strip them at that point.

A test previews \def\a{one}{\def\a{two}\a}\a as "twoone" and the
\begingroup form likewise; the existing inline-definition test still passes.
Catcode state and a real token stream remain open.
2026-10-27 00:10:18 +08:00
gloamxun 7547c0abc4 Capture inline definitions and @ control words
The line-based capture treated any line that began with a definition command as
a definition and dropped the rest of the line, so
\makeatletter\def\@foo{bar}\makeatother\@foo lost everything after the body.
Only consume such a line when the definition actually ends it; otherwise leave
it for a new inline pass that captures simple \def\name{body} forms anywhere in
running text.

\makeatletter/\makeatother are stripped as no-ops and the macro expander now
scans @ as a letter, matching control_sequence, so \@foo expands to its body.

A test defines \@foo and \greet in one body line and checks the previewed text
"bar and Hello." with no warnings. Group scoping, catcode state and a token
stream remain open.
2026-10-27 00:02:54 +08:00
gloamxun def93b6cf5 Keep nested tabulars inside their outer table
The table capture ended at the first \end{tabular}, so a nested table inside a
cell closed the outer table early and the remaining inner rows leaked into the
document. Track the nesting depth of \begin{tabular}/\end{tabular} and only
close the outer environment at depth zero.

Nested blocks are flattened before the outer halign parses them: inner rows are
split on \\ and cells on &, rule commands and \multicolumn/\multirow wrappers
are stripped, and the text is joined as "a b ; c d" inside the outer cell. The
outer structure, column count and row count survive; true nested-table layout
and \valign remain open.

A regression test wraps a 2x2 tabular in a 2-column outer table and checks one
captured table, two columns, two rows and the flattened inner text.
2026-10-26 23:56:43 +08:00
gloamxun 4b28d65006 Render Greek math commands as their letters
\alpha through \omega, the uppercase Greek commands and the varepsilon /
vartheta / varrho / varsigma / varphi / varpi / varkappa variants were not in
the math command table, so a formula such as $\alpha+\beta$ painted "?" glyphs.

Map them to their Unicode code points. The math renderer already treats the
Greek ranges as math letters and sends them through the math-italic fallback,
so the formula now previews as α+β=γ with no warnings; the widths still use the
TFM fallback constant rather than per-letter cmmi metrics.

A core test pins the parsed symbols and a route-D test checks the previewed
characters.
2026-10-26 23:52:44 +08:00
gloamxun 5a1a04d029 Freeze savebox metrics and expand wd/ht/dp
\sbox/\savebox now measure their content at definition with the Roman metrics
at the class base size and store width/height/depth. \usebox carries that size
into the no-break segment, which scales the box back to its definition size
inside a differently sized paragraph, and \wd/\ht/\dp\boxname expand to the
frozen metrics before paragraph parsing.

\mbox/\hbox/\makebox keep following the surrounding size (their marker carries
size 0). A core test checks that a box frozen at 20pt is twice as wide as the
10pt one, and a route-D test checks the measured dimensions and a
\hspace{\wd\box} expansion. Image-only boxes still measure as empty text.

Three savebox tests strip the internal markers (now with their size prefix)
before comparing visible text.
2026-10-26 23:48:42 +08:00
gloamxun 95a6a1291a Keep mbox and savebox content on one line
Add InlineSegment::NoBreak: it shapes each word and replaces the interword
glue with fixed-width boxes, so the run has no breakpoints and behaves like
TeX's unbreakable hbox rather than reflowing at the use site.

Route-D wraps \usebox bodies and \mbox/\hbox/\makebox arguments in private-use
markers; the paragraph text builder splits on them and emits NoBreak runs,
leaving ordinary text and styling on the existing path. \underline keeps its
old inline behaviour.

A 60pt measure now keeps \mbox{alpha beta gamma} and a stored
\sbox{alpha beta gamma} on one line, covered by a core segment test and a
route-D test. Savebox dimensions are still measured at the use site instead of
being frozen at definition, and \wd/\ht/\dp accessors remain open.
2026-10-26 23:43:53 +08:00
gloamxun 56faec6046 Split colour, link and sized runs at any base size
inline_math_segments returned None for every paragraph whose base size was not
10pt, so a 12pt or \Large paragraph kept \textcolor/\href/\textsuperscript
delimiters as literal text. Only inline math actually depends on the 10pt
metric baseline: build the segments at any size and fall back to literal
delimiters only when a math segment is present and the size differs.

The existing sized-href test moves from "href is stripped but not linked" to
"the sized run keeps its link", and a new 12pt test covers a red run, a link
and a superscript in one paragraph with no warnings.
2026-10-26 23:37:14 +08:00
gloamxun 15b5437987 Paint fancyhdr running heads and feet
Parse \pagestyle{fancy}, \fancyhf, \fancyhead/\fancyfoot with L/C/R positions,
the \lhead/\chead/\rhead/\lfoot/\cfoot/\rfoot shorthands and
\renewcommand{\headrulewidth}, and paint them on every page. Head fields are
placed at top margin - \headsep and feet at text height + \footskip, both in
content coordinates so the page origin shifts them with the body; left, centre
and right align against the text measure, \thepage is expanded per page, and
the head rule uses the requested width.

Size and shape declarations are stripped before macro expansion because class
files define \footnotesize in terms of itself; expanding it repeated
\@setfontsize internals on every pass. A title page with fancy style is treated
as \thispagestyle{empty}, matching class \maketitle definitions.

The arXiv template now shows "A Preprint" on the right and its short title in
the centre after the title page, with the page number in the footer; tests
cover field parsing, painted positions/alignment and the title-page
suppression.
2026-10-26 23:32:52 +08:00
gloamxun 7a615a8639 Place the page body below geometry's top margin
The geometry package's top/bottom margins were only used to derive a text
height; the laid-out body still started at the very top of the sheet, so the
arXiv template's 1in top margin was ignored and text sat on the paper edge.

Record top/bottom margins on PageGeometry and add the top margin to the page
body's vertical offset, which both the SVG preview and the PDF writer honour;
the page number and footer baseline move with the body. An explicit textheight
still wins over the margin-derived one.

The arXiv template's first baseline now sits at 1in + 12pt, still with zero
warnings in two pages. Unit tests cover the margin parse/derive and a preview
whose first baseline shifts by exactly one inch.
2026-10-26 23:25:20 +08:00
gloamxun 21d48866de Preview the arXiv template without warnings
The archived class file expands \maketitle, \section and \keywords into LaTeX
internals that route-D does not model, so the template's title block, headings
and keywords were replaced by LaTeX machinery and 20+ control words reached
layout.

Keep \maketitle, \thanks and the heading commands out of generic macro
expansion so the native title block and section parser see them; scrub the
author metadata (\href labels, ORCID \includegraphics, text-style wrappers,
line breaks and \And) into plain text; turn \keywords into a "Keywords: ..."
paragraph; expand \lipsum[n]/[a-b] to filler paragraphs; drop `%` comments and
external \bibliography/\bibliographystyle commands (an inline thebibliography
still supplies References); and start a new block when center/flushleft/
flushright follows text on the same chunk.

The arXiv fixture now previews with zero warnings in two pages, covered by a
JSON-level regression test. Remaining class support is still semantic rather
than a TeX VM.
2026-10-26 23:20:58 +08:00
gloamxun 1b7baa0257 Capture multi-line macro definitions and mode conditionals
The preamble parser is line-oriented, so a multi-line \newcommand, \def or
\newenvironment contributed only its first line to the macro table while the
remaining body lines fell through to the document text. In the assembled arXiv
source that also swallowed the \begin{document} marker, so the whole class
preamble was laid out as one page of \NeedsTeXFormat/\fancyhf text.

Join definition bodies at balanced braces before stripping: comments are
removed, a `%` line continuation joins without adding a space, and a blank line
becomes \par. Definitions now reach the existing single-line capture whole.

Resolve \ifhmode as true and \ifvmode/\ifmmode as false for the text expansion
path, so class macros such as \and expand.

The arXiv fixture body no longer contains NeedsTeXFormat, fancyhf or ifhmode and
the project preview lays out four pages instead of one; unit tests cover a
multi-line \newcommand/\def and the arXiv preamble containment. Remaining
warnings are now body commands (\maketitle, \thanks, \lipsum, \addvspace and the
footnote machinery), which are separate work.
2026-10-26 23:08:35 +08:00
gloamxun ebf2070295 Run AtBeginDocument setup and newgeometry as preamble
Class files such as the arXiv template set the page block inside
\AtBeginDocument{\newgeometry{...}}. Route-D treated the hook body as document
text, so the setup commands were typeset at the top of page one and the page
measure stayed at its default.

Lift \AtBeginDocument bodies in front of \begin{document}, join a multi-line
\newgeometry argument into one line, and read it through the geometry option
parser. Explicit textheight/textwidth options now win over margins, so
textheight=9in with top=1in keeps 9in instead of recomputing it from the
paper height.

The arXiv project now applies its 6.5in/9in block and no longer reports a
\newgeometry warning; unit tests cover the multi-line hook, the option
precedence, and the no-leak case. A remaining leak from multi-line macro
definitions in the same class file is separate work.
2026-10-26 23:03:37 +08:00
gloamxun 2f9b18c95c Reserve display skips around math
TeX surrounds each display with \abovedisplayskip above and \belowdisplayskip
below, but route-D only reserved the paragraph's own spacing, so displays sat
directly against the surrounding text. Parse the four registers (including the
short forms), default to the article-class 10/11/12pt values, and add them to
the math unit and the unit that follows it.

The glue parser now also accepts the class-file spelling
(`\abovedisplayskip 7\p@ \@plus 2\p@ \@minus 5\p@`), register copies such as
`\belowdisplayskip \abovedisplayskip`, `\z@`/`\p@` dimensions and
space-separated assignments, which clears the display-skip warnings the arXiv
template produced.

A page oracle sets a 45pt above skip and pins the display moving to the second
page exactly as pdfLaTeX lays it out; unit tests cover the defaults, overrides
and the class-file spelling.
2026-10-26 22:49:41 +08:00
gloamxun 8ac2e828df Honour club and widow penalties on paragraph lines
Route-D expanded a paragraph into one node per line without TeX's
\clubpenalty/\widowpenalty, so a page break could orphan the first line or
widow the last. Insert the penalties between line nodes (150 by default, read
from the source registers) and make the page builder reject any penalty of
10000 or more as a breakpoint. Forced -10000 values now break exactly where
pdfLaTeX does; two page oracle fixtures compare per-page text, and unit tests
cover the node order and the forbidden breakpoint.
2026-10-26 22:14:01 +08:00
gloamxun e09e413892 Break long paragraphs with prefix sums
The line-breaker rescanned items[start..end] for every break pair, so a 900-word paragraph took seconds and the 2,700-word edit fixture took about 30 s. Prefix sums over natural width, stretch, shrink, glue order, box count and the last penalty give each candidate its metrics in O(1); the search now costs O(breakpoints^2) and the same document lays out in about 0.3 s. Add a 900-word regression test and note the change in TEX_CORE.
2026-10-26 22:03:19 +08:00
gloamxun 41c68baa5d Ignore display break hints 2026-10-26 20:37:24 +08:00
gloamxun 7271e2ee12 End table rows with tabularnewline 2026-10-26 20:36:57 +08:00
gloamxun 80a5e8272d Stretch tabular* tables to their target width 2026-10-26 20:36:49 +08:00
gloamxun 3770de0804 Render tabular* by its declared column template 2026-10-26 20:36:43 +08:00
gloamxun 40abb7bef3 Reserve environment definitions declared in the body 2026-10-26 20:36:30 +08:00
gloamxun 0d9ed56a55 Reserve theorem definitions declared in the body 2026-10-26 20:36:21 +08:00
gloamxun 3087a9a116 Reserve saveboxes declared in the body 2026-10-26 20:35:58 +08:00
gloamxun eaebb1edbf Reserve registers declared in the body 2026-10-26 20:35:42 +08:00
gloamxun 13de893c46 Capture body-level newif definitions 2026-10-26 20:35:34 +08:00
gloamxun dc49b92a47 Capture body-level chardef definitions 2026-10-26 20:35:09 +08:00
gloamxun 2408736c5e Capture body-level let aliases 2026-10-26 20:34:44 +08:00
gloamxun 6efb210781 Capture definitions written in the body 2026-10-26 20:34:33 +08:00
gloamxun 7c98c61b7a Ignore preamble-only guards 2026-10-26 20:34:06 +08:00
gloamxun 991498b0e1 Guard definitions with @ifdefinable 2026-10-26 20:33:57 +08:00
gloamxun f6a41c9f59 Expand the checkmark symbol in text 2026-10-26 20:33:49 +08:00
gloamxun 8e884e6db1 Expand parameterised newcolumntype letters 2026-10-26 20:33:43 +08:00
gloamxun 9d57ca604e Expand newcolumntype letters in table specs 2026-10-26 20:33:14 +08:00
gloamxun 97e883f51d Branch on @ifclassloaded for supported classes 2026-10-26 20:33:02 +08:00
gloamxun c9982a7675 Branch on @ifpackageloaded for known packages 2026-10-26 20:32:51 +08:00
gloamxun fce3a3b0a0 Honour optional newenvironment defaults 2026-10-26 20:32:41 +08:00
gloamxun b7d18dff37 Expand punctuation and symbol commands 2026-10-26 20:32:18 +08:00
gloamxun 3a089c6175 Number standalone captionof captions 2026-10-26 20:32:01 +08:00
gloamxun 7d05268983 Keep underline text without the rule 2026-10-26 20:31:45 +08:00
gloamxun f147ccc8c5 Parse array column modifiers and their alignment 2026-10-26 20:31:33 +08:00
gloamxun 71dc8ca59b Treat starred floats as their single-column forms 2026-10-26 20:31:18 +08:00