From f6726439edcc6355ef114ddf688a1eb84593b5ce Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 02:00:47 +0800 Subject: [PATCH] Support tag and notag on numbered equations --- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/route_d.rs | 100 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 341e459..5f54f02 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`). 524 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 525 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 1241519..53bba1c 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -131,7 +131,7 @@ and justification. | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | | M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open | -| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels | +| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | @@ -367,7 +367,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`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 524 tests (347 route-D unit, 17 engine binary unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 525 tests (347 route-D unit, 18 engine binary unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/route_d.rs b/src/route_d.rs index 1812f18..f7cb2fa 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -641,6 +641,7 @@ struct SourceParagraph { space_shrink: i64, /// Number of the equation environment this block came from. equation_number: Option, + equation_tag: Option, } /// Recognise an explicit vertical skip command standing alone between @@ -706,6 +707,7 @@ fn paragraphs(source: &str) -> Result, String> { space_shrink: pending.2, page_break: pending_break, equation_number: None, + equation_tag: None, }); pending = (0, 0, 0); pending_break = false; @@ -747,7 +749,18 @@ fn resolve_equation_numbers(blocks: &mut [SourceParagraph]) { let mut number = 0; let mut labels: Vec<(String, u32)> = Vec::new(); for block in blocks.iter_mut() { - if !block.math || block.equation_number.is_none() { + if !block.math { + continue; + } + if let Some(tag) = take_braced_argument(&mut block.text, "\\tag") { + block.equation_tag = Some(tag); + block.equation_number = None; + } + if block.text.contains("\\notag") || block.text.contains("\\nonumber") { + block.equation_number = None; + } + block.text = block.text.replace("\\notag", "").replace("\\nonumber", ""); + if block.equation_number.is_none() || block.equation_tag.is_some() { continue; } number += 1; @@ -811,6 +824,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, } }) .collect(); @@ -837,6 +851,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, }]; } } @@ -872,6 +887,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, } }) .collect(); @@ -885,6 +901,30 @@ fn parse_blocks_raw(raw: &str) -> Vec { /// Map a small, general LaTeX subset onto route-D paragraph faces. This is not /// a full LaTeX reader; it exists so the live endpoint can show headings and /// emphasis while the semantic layer is built out. +fn take_braced_argument(text: &mut String, command: &str) -> Option { + let start = text.find(command)?; + let after = start + command.len(); + if !text[after..].starts_with('{') { + return None; + } + let mut depth = 0_usize; + for (offset, character) in text[after..].char_indices() { + match character { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + let inner = text[after + 1..after + offset].to_string(); + text.replace_range(start..after + offset + 1, ""); + return Some(inner); + } + } + _ => {} + } + } + None +} + fn parse_paragraph(raw: &str) -> SourceParagraph { if let Some(inner) = raw .strip_prefix("\\begin{equation}") @@ -903,6 +943,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_shrink: 0, page_break: false, equation_number: Some(0), + equation_tag: None, }; } if let Some(inner) = raw @@ -922,6 +963,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, }; } if let Some(math) = raw @@ -945,6 +987,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, }; } let candidates = [ @@ -967,6 +1010,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, }; } } @@ -983,6 +1027,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_shrink: 0, page_break: false, equation_number: None, + equation_tag: None, } } @@ -1009,10 +1054,15 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do if paragraph.math { let font = Cmr10Metrics::Math; let atom = parse_math(¶graph.text); - let atom = match paragraph.equation_number { - Some(number) => MathAtom::Tagged { + let tag = paragraph.equation_tag.clone().or_else(|| { + paragraph + .equation_number + .map(|number| format!("({number})")) + }); + let atom = match tag { + Some(tag) => MathAtom::Tagged { body: Box::new(atom), - tag: format!("({number})"), + tag, }, None => atom, }; @@ -1517,6 +1567,48 @@ a + b ); } + #[test] + fn equation_tags_override_and_suppress_numbers() { + let source = r"\begin{equation} +a +\end{equation} + +\begin{equation} +b +\tag{B} +\end{equation} + +\begin{equation} +c +\notag +\end{equation} + +\begin{equation} +d +\end{equation}"; + let blocks = paragraphs(source).expect("paragraphs"); + let tags: Vec<(Option, Option)> = blocks + .iter() + .filter(|block| block.math) + .map(|block| (block.equation_number, block.equation_tag.clone())) + .collect(); + assert_eq!( + tags, + vec![ + (Some(1), None), + (None, Some("B".to_string())), + (None, None), + (Some(2), None) + ] + ); + assert!( + !blocks + .iter() + .any(|block| block.text.contains("\\tag") || block.text.contains("\\notag")), + "tagging commands are stripped from the formula" + ); + } + #[test] fn numbered_equation_renders_its_tag() { let json = preview_json("\\begin{equation}\nx^2\n\\end{equation}").expect("preview");