From b16e5a53e8e1e484ea60d8c52aa5a8184cf538a8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 27 Oct 2026 01:01:28 +0800 Subject: [PATCH] Run afterassignment tokens after their assignment \afterassignment leaked because assignment processing happens in later passes. Add a rewrite after the body is extracted: find \afterassignment, read its token, locate the following assignment (a \def/\gdef through runtime_definition, or the next top-level '=' plus its value token), and move the command before the assignment's follower so the assignment passes run first. The queued token stays in the stream for normal expansion. A preview test queues \hello before \a=5 and checks H appears, Text. still renders and no \afterassignment leaks. --- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 10 ++++--- src/route_d.rs | 71 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 56cebd3..e759a28 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -49,7 +49,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now -prefer route-D with a v1 fallback). 1000 workspace tests are green and no oracle +prefer route-D with a v1 fallback). 1001 workspace tests are green and no oracle fixture is ignored. Preview JSON also carries a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported instead of being silently typeset. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 3539d7f..afdc6c7 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1000 tests (437 route-D unit, 373 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. +The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1001 tests (437 route-D unit, 374 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. ### M0 incremental demo @@ -553,9 +553,11 @@ are: `\futurelet\alias\command ` binds the looked-ahead token to the alias without consuming it, and `\aftergroup` (or `\aftergroup{...}`) queues its token until the enclosing `{}` or - `\begingroup` closes, then injects it after the group. Conditionals are - evaluated after macro expansion with their operand tokens protected from - expansion, then before register expansion. + `\begingroup` closes, then injects it after the group. + `\afterassignment` moves the token behind the following register or + `\def` assignment so it runs once the assignment has been processed. + Conditionals are evaluated after macro expansion with their operand tokens + protected from expansion, then before register expansion. - **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox` bodies are inserted as one unbreakable inline box (interword spaces become fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox diff --git a/src/route_d.rs b/src/route_d.rs index ee6dfa4..b757071 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -5175,6 +5175,53 @@ fn measure_savebox(content: &str, base_size: i64) -> (i64, i64, i64) { /// Capture `\def` lines written in the document body, before macro expansion. /// Reserve `\newcount`/`\newdimen`/`\newskip` registers declared in the body. +/// Move the token queued by `\afterassignment` behind the assignment it +/// follows, so the normal assignment passes run first. +fn apply_afterassignment(body: &str) -> String { + let mut text = body.to_string(); + loop { + let Some(position) = text.find("\\afterassignment") else { + break; + }; + let after = &text[position + "\\afterassignment".len()..]; + let Some((token, token_used)) = next_token(after) else { + break; + }; + let rest = &after[token_used..]; + let Some(end) = assignment_end(rest) else { + break; + }; + text = format!( + "{}{}{}{}", + &text[..position], + &rest[..end], + token, + &rest[end..] + ); + } + text +} + +fn assignment_end(text: &str) -> Option { + if let Some((_, used, _)) = runtime_definition(text) { + return Some(used); + } + let mut depth = 0_i32; + for (index, character) in text.char_indices() { + match character { + '{' => depth += 1, + '}' => depth -= 1, + '=' if depth == 0 => { + let after = &text[index + 1..]; + let (_, used) = next_token(after)?; + return Some(index + 1 + used); + } + _ => {} + } + } + None +} + fn capture_body_registers( body: &mut String, counts: &mut Vec<(String, i64)>, @@ -5811,6 +5858,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) { // paragraphs of their own. let mut body = latex_body(&stripped).trim_matches('\n').to_string(); geometry.bibliography = extract_bibliography(&mut body); + body = apply_afterassignment(&body); capture_body_registers( &mut body, &mut geometry.count_registers, @@ -15719,6 +15767,29 @@ A definition. assert!(!text.contains("makeatletter"), "{text}"); } + #[test] + fn afterassignment_runs_after_the_assignment() { + let source = "\\documentclass{article}\n\\begin{document}\n\n\\newcount\\a\n\\def\\hello{H}\n\\afterassignment\\hello\\a=5\n\nText.\n\n\\end{document}\n"; + let json = preview_json(source).expect("preview"); + let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); + assert_eq!( + value["warnings"].as_array().map(Vec::len), + Some(0), + "{}", + value["warnings"] + ); + let svg = value["pages"][0]["svg"].as_str().expect("svg"); + let text: String = svg + .split('>') + .filter_map(|piece| piece.split('<').next()) + .collect::() + .split_whitespace() + .collect(); + assert!(text.contains('H'), "{text}"); + assert!(text.contains("Text."), "{text}"); + assert!(!text.contains("afterassignment"), "{text}"); + } + #[test] fn aftergroup_runs_tokens_at_group_end() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{A}{\\def\\a{B}\\aftergroup\\a}\\a and {\\aftergroup{!}}X\n\n\\end{document}\n";