From 1b7baa02572d5f460a7607e7f3f46f22fc3fb56f Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 26 Oct 2026 23:08:35 +0800 Subject: [PATCH] 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. --- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 8 ++- src/route_d.rs | 142 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 2 deletions(-) diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 8873e56..b8945c8 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and 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`). 969 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 971 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 36e9f0f..2a926c7 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 434 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 969 tests (434 route-D unit, 347 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 434 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 971 tests (434 route-D unit, 349 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -482,6 +482,12 @@ deliberately open rather than approximated: `OutputRoutine::wants_break` remains a Rust hook for forcing a page break between units, insertion material is stacked by class from the page bottom, and the page box (`\box255`) exposes width/height/depth but not its content. + Class files contribute multi-line `\newcommand`/`\def`/`\newenvironment` + bodies: the source is joined at balanced braces and the whole definition is + captured, while `\ifhmode`/`\ifvmode`/`\ifmmode` resolve as the + horizontal/vertical/math approximations. The arXiv class preamble no longer + leaks into the body: the template now previews as four pages instead of one + page of `\NeedsTeXFormat`/`\fancyhf` text. - Page hashes cover rendered items/insertions/marks/floats, not source-dependency metadata, so replaying an earlier page cannot change its hash merely by re-attaching source hashes. diff --git a/src/route_d.rs b/src/route_d.rs index cffc19e..3223f95 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -1656,6 +1656,14 @@ fn conditional_at( if word == "iffalse" { return Some((false, consumed)); } + // Route-D expands macros while building paragraph text, which is + // horizontal mode; vertical and math mode are not modelled here. + if word == "ifhmode" { + return Some((true, consumed)); + } + if word == "ifvmode" || word == "ifmmode" { + return Some((false, consumed)); + } if word == "ifdefined" { let after = text.get(index + consumed..)?; let trimmed = after.trim_start(); @@ -4376,6 +4384,111 @@ fn capture_body_definitions( } } +/// Join multi-line `\newcommand`/`\def`/`\newenvironment` definitions into +/// one line so the line-oriented preamble parser can capture the whole body. +fn collapse_definition_bodies(source: &str) -> String { + const COMMANDS: [&str; 9] = [ + "\\newcommand", + "\\renewcommand", + "\\providecommand", + "\\def", + "\\gdef", + "\\edef", + "\\xdef", + "\\newenvironment", + "\\renewenvironment", + ]; + let starts_definition = |line: &str| { + COMMANDS.iter().any(|command| { + line.strip_prefix(command) + .is_some_and(|rest| !rest.starts_with(|c: char| c.is_ascii_alphabetic())) + }) + }; + let mut out = String::new(); + let mut pending: Option = None; + let mut depth = 0_i64; + for line in source.lines() { + if let Some(buffer) = pending.as_mut() { + let continues = line.trim_end().ends_with('%'); + let code = strip_tex_comment(line); + if code.trim().is_empty() { + buffer.push_str(" \\par "); + } else if continues { + buffer.push_str(code.trim()); + } else { + buffer.push(' '); + buffer.push_str(code.trim()); + } + depth += brace_delta(&code); + if depth <= 0 { + out.push_str(buffer); + out.push('\n'); + pending = None; + depth = 0; + } + continue; + } + let code = strip_tex_comment(line); + let trimmed = code.trim_start(); + if starts_definition(trimmed) { + let delta = brace_delta(&code); + if delta > 0 { + pending = Some(code.trim_end().to_string()); + depth = delta; + continue; + } + } + out.push_str(line); + out.push('\n'); + } + if let Some(buffer) = pending { + out.push_str(&buffer); + out.push('\n'); + } + out +} + +/// Drop an unescaped `%` comment from the end of a source line. +fn strip_tex_comment(line: &str) -> String { + let mut out = String::with_capacity(line.len()); + let mut escaped = false; + for character in line.chars() { + if escaped { + escaped = false; + out.push(character); + continue; + } + if character == '\\' { + escaped = true; + out.push(character); + continue; + } + if character == '%' { + break; + } + out.push(character); + } + out +} + +fn brace_delta(text: &str) -> i64 { + let mut depth = 0_i64; + let mut escaped = false; + for character in text.chars() { + if escaped { + escaped = false; + continue; + } + match character { + '\\' => escaped = true, + '{' => depth += 1, + '}' => depth -= 1, + _ => {} + } + } + depth +} + /// Move `\AtBeginDocument{...}` bodies in front of `\begin{document}`. fn lift_at_begin_document(source: &str) -> String { let mut hooks = String::new(); @@ -4441,6 +4554,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) { // body before `\begin{document}` so its commands are consumed as setup // instead of being typeset as text at the top of page one. let source = lift_at_begin_document(source); + let source = collapse_definition_bodies(&source); let source = collapse_braced_command(&source, "\\newgeometry"); let (stripped, mut geometry) = strip_page_geometry(&source); dedupe_macros(&mut geometry.macros); @@ -13629,6 +13743,34 @@ A definition. assert_eq!(after.space_shrink, 5 * SCALE); } + #[test] + fn multiline_macro_definitions_do_not_leak_into_the_body() { + let source = "\\documentclass{article}\n\\newcommand{\\kw}[1]{%\n \\textbf{#1}%\n}\n\\def\\and{\\ifhmode\n\\fi}\n\\begin{document}\n\nSee \\kw{Hi} and \\and there.\n\n\\end{document}\n"; + let (body, _) = geometry_and_body(source); + assert!(!body.contains("newcommand"), "{body}"); + assert!(!body.contains("ifhmode"), "{body}"); + assert!(body.contains("Hi"), "{body}"); + } + + #[test] + fn arxiv_class_preamble_does_not_reach_the_body() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let template = std::fs::read_to_string(root.join("fixtures/arxiv-template/template.tex")) + .expect("template"); + let sty = + std::fs::read_to_string(root.join("fixtures/arxiv-template/arxiv.sty")).expect("sty"); + let assembled = template.replace("\\usepackage{arxiv}", &sty); + let (body, _) = geometry_and_body(&assembled); + for needle in ["NeedsTeXFormat", "fancyhf", "ifhmode"] { + assert!(!body.contains(needle), "`{needle}` leaked into the body"); + } + assert!( + body.contains("Introduction"), + "body lost the document text: {}", + body.chars().take(200).collect::() + ); + } + #[test] fn at_begin_document_newgeometry_sets_the_text_block() { let source = "\\documentclass{article}\n\\usepackage{geometry}\n\\AtBeginDocument{\n \\newgeometry{\n textheight=9in,\n textwidth=6.5in,\n top=1in,\n headheight=14pt,\n headsep=25pt,\n footskip=30pt\n }\n}\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";