From 254fd4a9a1bd74fbacca32360178f15a59ba59b8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 27 Oct 2026 12:46:48 +0800 Subject: [PATCH] Fix heading/float block boundaries and record the web trial The curated trial exposed two parser losses: a heading followed on the next line by body text dropped the body, and consecutive figure/table/equation blocks without blank lines swallowed each other. Headings are now separated from following text and later headings, and the block splitter understands display environments plus headings, so article-basic keeps its body, figure, table and equation while arxiv-template moves from 2 to the expected 3 pages. WEB_ROUTE_D_EXPERIMENT.md now records the three-project results (article-basic, unicode-mixed, arxiv-template), the Edge smoke test, the go/no-go and the updated P0 backlog: SVG preview image embedding, .bib data, vector figures and table-cell math. Test counts move to 1065 (431 engine, 442 core, 64 server). --- docs/ROUTE_D_PLAN.md | 2 +- docs/ROUTE_D_STATUS.md | 8 +- docs/TEX_CORE.md | 4 +- docs/WEB_ROUTE_D_EXPERIMENT.md | 57 ++++++--- src/route_d.rs | 209 +++++++++++++++++++++++++++++++-- 5 files changed, 250 insertions(+), 30 deletions(-) diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 2481222..8ffe413 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -51,7 +51,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). 1063 workspace tests are green and no oracle +prefer route-D with a v1 fallback). 1065 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/ROUTE_D_STATUS.md b/docs/ROUTE_D_STATUS.md index c18cdae..60a3d7f 100755 --- a/docs/ROUTE_D_STATUS.md +++ b/docs/ROUTE_D_STATUS.md @@ -16,20 +16,20 @@ cargo test --workspace --offline or run `./scripts/verify-route-d.sh`, which executes both. -The workspace currently passes **1063 tests**: +The workspace currently passes **1065 tests**: | Suite | Tests | | --- | --- | | route-D unit (engine) | 442 | -| engine binary unit | 429 | +| engine binary unit | 431 | | server integration | 64 | | v1 integration | 71 | | pdfLaTeX oracle | 42 | | route-D integration | 10 | | engine/core unit | 4 + 1 | -Latest full run (commit `1058122`): `./scripts/verify-route-d.sh` passes with -fmt clean and **1063 tests** green. +Latest full run (web trial increment): `./scripts/verify-route-d.sh` passes +with fmt clean and **1065 tests** green. Latest live check (2026-10-27): the debug server served `examples/hello.tex` from `target/debug/texrra serve`; `POST /preview` answered 200 with diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 4807704..6ddd0ba 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 442 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1063 tests (442 route-D unit, 429 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 64 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; flat and project responses carry `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 442 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1065 tests (442 route-D unit, 431 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 64 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; flat and project responses carry `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 @@ -524,7 +524,7 @@ deliberately open rather than approximated: ## Limits and remaining gaps -The suite currently stands at 1063 passing tests, with the workspace clean. +The suite currently stands at 1065 passing tests, with the workspace clean. Route-D serves both flat `/preview` and project preview/PDF requests by default (automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The objective's areas are implemented to the limits below; complex-script shaping is diff --git a/docs/WEB_ROUTE_D_EXPERIMENT.md b/docs/WEB_ROUTE_D_EXPERIMENT.md index 6007ed7..04c2c65 100644 --- a/docs/WEB_ROUTE_D_EXPERIMENT.md +++ b/docs/WEB_ROUTE_D_EXPERIMENT.md @@ -1,7 +1,8 @@ # Route-D web experiment -Status: contract fixes landed (engine `1058122` + `2194341`, web `cecad51`), -curated trial pending. +Status: contract fixes and the curated three-project trial are complete +(engine contract `1058122`, web `cecad51`); the go/no-go and P0 backlog are +recorded below. Audit baseline: engine `c49afbd`, web `24c9593`; 2026-10-27. ## Verdict @@ -45,7 +46,7 @@ now means route-D. | Area | Route-D | Evidence / impact | | --- | --- | --- | -| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1063-test suite | +| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1065-test suite | | Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures | | Floats, captions, tables, booktabs | Supported | table/math tests, corpus | | PNG/JPEG/BMP `\includegraphics` | Supported | project image tests | @@ -59,25 +60,53 @@ now means route-D. | Complex scripts | **Not supported** | no shaping fallback; outside pdfLaTeX's own scope | | Footnotes, marks, running heads | Partial | marks are document-level, not per-page | | `\parbox` wrapping | Partial | width argument does not wrap | +| Raster images in the SVG preview | Placeholder | the SVG painter draws a grey rectangle; the PDF embeds the real image | +| Inline math in table cells | **Not supported** | trial table shows literal `$\mu$m`, `$\sim$`, `$10^6$` | | Nested-table images, `\valign` alignments | Not supported/partial | documented engine limits | | Token stream/catcodes beyond `@`/`%` | Partial | textual expander, not a TeX token stream | -## Curated trial (next) +## Curated trial results -1. `article-basic`: title, sections, PNG figure, table, math, references, - inline bibliography. -2. `arxiv-template`: the checked-in `fixtures/arxiv-template` with local - class/style/input files, images and inline bibliography. -3. `unicode-mixed`: accents, Greek math, colors, TOC + footnotes. +All three projects were created through the project API and rendered with both +engines. Durations are the server's `durationMs` (client HTTP elapsed in +parentheses); PDFs were checked for `%PDF-`. -For each project record page count, warnings, preview/PDF duration, PDF magic -and any fallback. Any project that needs `.bib`, vector figures or arbitrary -packages must be marked as a v1 fallback case, not a silent failure. +| Project | Route-D | v1 | Notes | +| --- | --- | --- | --- | +| `article-basic` | 1 page, 0 warnings, 502 ms (624 ms), PDF 633 ms / 466 KB | 1 page, 1449 ms (1456 ms), PDF 2701 ms / 488 KB | TOC, figure, table, equation and inline bibliography all present; figure raster is a grey placeholder in SVG | +| `unicode-mixed` | 1 page, 0 warnings, 442 ms (510 ms), PDF 656 ms / 174 KB | **422**, `undefined control sequence \'` | Route-D handles accents, Greek math, colours and footnotes; v1 cannot compile the source | +| `arxiv-template` | 3 pages, 0 warnings, 1448 ms (1514 ms), PDF 1572 ms / 448 KB | 3 pages, 4280 ms (4308 ms), PDF 4677 ms / 5.2 MB | Route-D is faster, but `.bib` citations render `[?]`, `References` is absent, table-cell math is literal and `orcid.pdf` is a placeholder | + +The first pass of this trial also exposed a parser bug: a heading followed on the +next line by body text (no blank line) dropped the body, and consecutive +display blocks without blank lines swallowed each other. Both were fixed before +the table above was recorded: + +- headings are separated from following text and from later headings; +- `figure`, `table`, `equation`, `align`, `gather` and `multline` blocks split + from surrounding text and from each other. + +A headless Edge smoke test of `article-basic` confirmed the editor loads, the +toolbar shows **Route-D (实验)**, and the preview contains the body, table, +equation and captions. It also confirmed the remaining visual gap: the PNG +figure is a grey rectangle in the SVG preview (the exported PDF embeds it). + +## Go/no-go + +- **Go**, limited to text/table/math documents: Route-D is the faster default + and handles accents that v1 rejects. +- **Conditional no-go** for image-heavy or BibTeX-based papers: the SVG preview + does not draw raster images, `.bib` data is not resolved, PDF/vector figures + are unsupported, and table-cell math is literal. +- Keep the explicit v1 escape hatch: v1 is not a universal fallback (it failed + the Unicode trial), so the UI must continue to show the actual engine and + warnings/fallbacks instead of assuming v1 always recovers. ## Backlog after the trial -- **P0**: `.bib`/BibTeX citation data; PDF/vector figure support; capability and - warning UI; project-level trial coverage. +- **P0**: SVG preview raster-image embedding; `.bib`/BibTeX citation data; + PDF/vector figure support; inline math/formatting in table cells; visible + capability warnings for unsupported content. - **P1**: two-column/multicols layout; fontspec/system-font loading; common TikZ/package execution; longtable page splitting. - **P2**: full catcode/token stream; nested-table images; per-page marks; diff --git a/src/route_d.rs b/src/route_d.rs index dd9ed88..1986544 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -6756,12 +6756,27 @@ fn expand_par_breaks(body: &str) -> String { /// Remove a `thebibliography` environment from the body and return its /// `\bibitem{key}` entries in order. /// Start a new block when a display environment follows text on the same -/// chunk, e.g. "The documentation is at\n\begin{center}...". +/// chunk, or when display blocks follow each other without a blank line. fn split_block_environments(chunk: &str) -> Vec<&str> { - const OPENINGS: [&str; 3] = [ + const OPENINGS: [&str; 18] = [ "\\begin{center}", "\\begin{flushleft}", "\\begin{flushright}", + "\\begin{figure}", + "\\begin{figure*}", + "\\begin{table}", + "\\begin{table*}", + "\\begin{equation}", + "\\begin{equation*}", + "\\begin{align}", + "\\begin{gather}", + "\\begin{multline}", + "\\chapter", + "\\section", + "\\subsection", + "\\subsubsection", + "\\paragraph", + "\\subparagraph", ]; let mut pieces = Vec::new(); let mut rest = chunk; @@ -6770,15 +6785,50 @@ fn split_block_environments(chunk: &str) -> Vec<&str> { .iter() .filter_map(|opening| rest.find(opening).map(|position| (position, *opening))) .min_by_key(|(position, _)| *position); - match next { - Some((position, _)) if position > 0 && !rest[..position].trim().is_empty() => { - pieces.push(&rest[..position]); - rest = &rest[position..]; + let Some((position, opening)) = next else { + if !rest.trim().is_empty() { + pieces.push(rest); } - _ => break, + break; + }; + if position > 0 { + pieces.push(&rest[..position]); + rest = &rest[position..]; + continue; + } + if !opening.starts_with("\\begin") { + // A heading has no closing delimiter: split before the next + // heading or display environment, keeping the body with it. + let after = &rest[opening.len()..]; + let next = OPENINGS + .iter() + .filter_map(|candidate| { + after + .find(candidate) + .map(|position| (position + opening.len(), *candidate)) + }) + .min_by_key(|(position, _)| *position); + if let Some((cut, _)) = next { + pieces.push(&rest[..cut]); + rest = rest[cut..].trim_start(); + } else { + pieces.push(rest); + break; + } + continue; + } + let closing = opening.replacen("\\begin", "\\end", 1); + let Some(close) = rest.find(&closing) else { + pieces.push(rest); + break; + }; + let end = close + closing.len(); + pieces.push(&rest[..end]); + rest = rest[end..].trim_start(); + while rest.starts_with('\n') { + rest = rest[1..].trim_start(); } } - pieces.push(rest); pieces } @@ -7939,8 +7989,9 @@ fn paragraphs_with_spacing( equation_start: u32, spacing: ListSpacing, ) -> Result, String> { + let source = separate_heading_lines(source); let mut paragraphs: Vec<&str> = Vec::new(); - for chunk in split_display_chunks(source) { + for chunk in split_display_chunks(&source) { for piece in split_block_environments(chunk) { let piece = piece.trim(); if !piece.is_empty() { @@ -11498,6 +11549,89 @@ fn parse_runs( } /// Recognize a `\section`-family command: level, starred, and title. +/// Byte span of a heading command at the start of a line, including any +/// immediately following `\label{...}` groups. +fn heading_span(raw: &str) -> Option { + let trimmed = raw.trim_start(); + for command in [ + "\\chapter", + "\\section", + "\\subsection", + "\\subsubsection", + "\\paragraph", + "\\subparagraph", + ] { + if !trimmed.starts_with(command) { + continue; + } + let mut position = command.len(); + if trimmed[position..].starts_with('*') { + position += 1; + } + while trimmed[position..] + .chars() + .next() + .is_some_and(|character| character.is_whitespace()) + { + position += 1; + } + if trimmed[position..].starts_with('[') { + let close = trimmed[position..].find(']')?; + position += close + 1; + } + let rest = &trimmed[position..]; + let trimmed_rest = rest.trim_start(); + let skipped = rest.len() - trimmed_rest.len(); + position += skipped; + let (_, used) = braced_group(&trimmed[position..])?; + position += used; + loop { + let tail = &trimmed[position..]; + let trimmed_tail = tail.trim_start(); + let Some(after) = trimmed_tail.strip_prefix("\\label") else { + break; + }; + let after = after.trim_start(); + let Some((_, label_used)) = braced_group(after) else { + break; + }; + position += tail.len() - after.len() + label_used; + } + return Some(position + (raw.len() - trimmed.len())); + } + None +} + +/// Put each heading on its own paragraph by ensuring a blank line after the +/// heading (and moving any same-line text after it onto the next line). +fn separate_heading_lines(source: &str) -> String { + let mut output = String::with_capacity(source.len() + 16); + let mut in_verbatim = false; + for line in source.lines() { + let trimmed = line.trim_start(); + if trimmed.starts_with("\\begin{verbatim}") { + in_verbatim = true; + } + if trimmed.starts_with("\\end{verbatim}") { + in_verbatim = false; + } + if !in_verbatim && let Some(span) = heading_span(line) { + let head = line[..span].trim_end(); + let rest = line[span..].trim(); + output.push_str(head); + output.push_str("\n\n"); + if !rest.is_empty() { + output.push_str(rest); + output.push_str("\n\n"); + } + continue; + } + output.push_str(line); + output.push('\n'); + } + output +} + fn heading_command(raw: &str) -> Option<(u8, bool, String, Option)> { let raw = raw.trim(); for (command, level) in [ @@ -17522,6 +17656,63 @@ A definition. assert!(text.contains("D"), "{text}"); } + #[test] + fn heading_text_without_blank_lines_is_kept() { + let source = "\\documentclass{article}\n\\begin{document}\n\n\\section{One}\nFirst body.\n\\section{Two}\nSecond body.\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 pages = value["pages"].as_array().expect("pages"); + let mut text = String::new(); + for page in pages { + if let Some(svg) = page["svg"].as_str() { + text.push_str( + &svg.split('>') + .filter_map(|piece| piece.split('<').next()) + .collect::(), + ); + } + } + let text: String = text.split_whitespace().collect(); + assert!(text.contains("Firstbody."), "{text}"); + assert!(text.contains("Secondbody."), "{text}"); + assert!(text.contains("2Two"), "{text}"); + } + + #[test] + fn floats_after_text_without_blank_lines_are_kept() { + let source = "\\documentclass{article}\n\\begin{document}\n\nBefore.\n\\begin{figure}[h]\n\\rule{10pt}{10pt}\n\\caption{Cap}\\label{fig:cap}\n\\end{figure}\n\\begin{table}[h]\n\\begin{tabular}{ll}\nA & B \\\\\n\\end{tabular}\n\\caption{Tab}\\label{tab:cap}\n\\end{table}\n\\begin{equation}\nx = 1\n\\end{equation}\nAfter.\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 pages = value["pages"].as_array().expect("pages"); + let mut text = String::new(); + for page in pages { + if let Some(svg) = page["svg"].as_str() { + text.push_str( + &svg.split('>') + .filter_map(|piece| piece.split('<').next()) + .collect::(), + ); + } + } + let text: String = text.split_whitespace().collect(); + assert!(text.contains("Before."), "{text}"); + assert!(text.contains("Figure1:Cap"), "{text}"); + assert!(text.contains("Table1:Tab"), "{text}"); + assert!(text.contains("After."), "{text}"); + } + #[test] fn eqref_wraps_non_equation_labels() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\section{Intro\\label{sec:a}}\n\nSee \\eqref{sec:a}.\n\n\\end{document}\n";