Number equation environments in route-D
This commit is contained in:
1 parent
3cbfdabe03
commit
bb897411d0
5 files changed
+207
-6
No files matched your search
@@ -53,6 +53,10 @@ pub enum MathAtom {
|
||||
vertical: bool,
|
||||
},
|
||||
Strut,
|
||||
Tagged {
|
||||
body: Box<MathAtom>,
|
||||
tag: String,
|
||||
},
|
||||
Limits {
|
||||
base: Box<MathAtom>,
|
||||
sub: Option<Box<MathAtom>>,
|
||||
@@ -584,6 +588,18 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
|
||||
depth: base_box.depth + 2 * 65_536,
|
||||
}
|
||||
}
|
||||
MathAtom::Tagged { body, tag } => {
|
||||
let body_box = layout_math(body, font);
|
||||
let tag_width: i64 = tag
|
||||
.chars()
|
||||
.map(|character| Cmr10Metrics::Roman.width(character))
|
||||
.sum();
|
||||
MathBox {
|
||||
width: body_box.width.max(tag_width),
|
||||
height: body_box.height.max(7 * 65_536),
|
||||
depth: body_box.depth.max(2 * 65_536),
|
||||
}
|
||||
}
|
||||
MathAtom::Script { base, sub, sup } => {
|
||||
let base_box = layout_math(base, font);
|
||||
let sub_box = sub.as_deref().map(|atom| layout_math(atom, font));
|
||||
@@ -2092,3 +2108,32 @@ mod spacing_class_tests {
|
||||
assert_eq!(width(r"\sum x") - sum - font.width('x'), 3 * 65_536 / 18);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tagged_equation_tests {
|
||||
use super::*;
|
||||
use crate::cmr10::Cmr10Metrics;
|
||||
|
||||
fn roman_width(text: &str) -> i64 {
|
||||
text.chars()
|
||||
.map(|character| Cmr10Metrics::Roman.width(character))
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tagged_formula_reserves_room_for_the_tag() {
|
||||
let font = Cmr10Metrics::Math;
|
||||
let body = parse_math("x");
|
||||
let plain = layout_math(&body, &font);
|
||||
let tagged = layout_math(
|
||||
&MathAtom::Tagged {
|
||||
body: Box::new(body),
|
||||
tag: "(12)".to_string(),
|
||||
},
|
||||
&font,
|
||||
);
|
||||
assert_eq!(tagged.width, plain.width.max(roman_width("(12)")));
|
||||
assert_eq!(tagged.height, plain.height.max(7 * 65_536));
|
||||
assert_eq!(tagged.depth, plain.depth.max(2 * 65_536));
|
||||
}
|
||||
}
|
||||
@@ -671,6 +671,26 @@ impl Page {
|
||||
cursor += width;
|
||||
}
|
||||
}
|
||||
MathAtom::Tagged { body, tag } => {
|
||||
let body_box = math::layout_math(body, font);
|
||||
Self::paint_math(body, font, x, baseline, size, list);
|
||||
let tag_width: i64 = tag
|
||||
.chars()
|
||||
.map(|character| Cmr10Metrics::Roman.width(character))
|
||||
.sum();
|
||||
let mut pen = x + body_box.width.max(tag_width) - tag_width;
|
||||
for character in tag.chars() {
|
||||
let width = Cmr10Metrics::Roman.width(character);
|
||||
list.push(DisplayItem::Text {
|
||||
font: FontFace::Roman,
|
||||
x: pen,
|
||||
y: baseline,
|
||||
size,
|
||||
text: character.to_string(),
|
||||
});
|
||||
pen += width;
|
||||
}
|
||||
}
|
||||
MathAtom::Script { base, sub, sup } => {
|
||||
let base_box = math::layout_math(base, font);
|
||||
Self::paint_math(base, font, x, baseline, size, list);
|
||||
|
||||
@@ -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`). 506 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 524 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
|
||||
|
||||
+2
-2
@@ -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<n>{...}` 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<n>`/`\dimen<n>`/`\skip<n>` 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<n>` or `\count<n>` changes the insertion capacity and reservation of later pages); the configured `\skip<n>` also reserves space above its class once per page in the paged builder, and a `\skip<n>` 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 |
|
||||
| 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 |
|
||||
| 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 346 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 506 tests (346 route-D 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 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.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
+139
-3
@@ -10,7 +10,7 @@ use std::fmt::Write as _;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use texrra_tex_core::cmr10::Cmr10Metrics;
|
||||
use texrra_tex_core::math::{parse_math, split_math_lines};
|
||||
use texrra_tex_core::math::{MathAtom, parse_math, split_math_lines};
|
||||
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper};
|
||||
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit};
|
||||
|
||||
@@ -639,6 +639,8 @@ struct SourceParagraph {
|
||||
space_before: i64,
|
||||
space_stretch: i64,
|
||||
space_shrink: i64,
|
||||
/// Number of the equation environment this block came from.
|
||||
equation_number: Option<u32>,
|
||||
}
|
||||
|
||||
/// Recognise an explicit vertical skip command standing alone between
|
||||
@@ -703,6 +705,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||||
space_stretch: pending.1,
|
||||
space_shrink: pending.2,
|
||||
page_break: pending_break,
|
||||
equation_number: None,
|
||||
});
|
||||
pending = (0, 0, 0);
|
||||
pending_break = false;
|
||||
@@ -718,7 +721,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||||
pending.2 += skip.2;
|
||||
continue;
|
||||
}
|
||||
let mut blocks = parse_blocks(chunk);
|
||||
let mut blocks = parse_blocks_raw(chunk);
|
||||
if let Some(first) = blocks.first_mut() {
|
||||
first.space_before += pending.0;
|
||||
first.space_stretch += pending.1;
|
||||
@@ -729,6 +732,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||||
}
|
||||
result.extend(blocks);
|
||||
}
|
||||
resolve_equation_numbers(&mut result);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -738,7 +742,41 @@ fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> {
|
||||
Some(rest.trim())
|
||||
}
|
||||
|
||||
fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
|
||||
/// Assign equation numbers in source order and substitute label references.
|
||||
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() {
|
||||
continue;
|
||||
}
|
||||
number += 1;
|
||||
block.equation_number = Some(number);
|
||||
loop {
|
||||
let Some(start) = block.text.find("\\label{") else {
|
||||
break;
|
||||
};
|
||||
let Some(end) = block.text[start..].find('}') else {
|
||||
break;
|
||||
};
|
||||
let label = block.text[start + 7..start + end].trim().to_string();
|
||||
labels.push((label, number));
|
||||
block.text.replace_range(start..start + end + 1, "");
|
||||
}
|
||||
}
|
||||
for block in blocks.iter_mut() {
|
||||
for (label, value) in labels.iter() {
|
||||
let eqref = format!("\\eqref{{{label}}}");
|
||||
let reference = format!("\\ref{{{label}}}");
|
||||
block.text = block
|
||||
.text
|
||||
.replace(&eqref, &format!("({value})"))
|
||||
.replace(&reference, &value.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
for (environment, numbered) in [("itemize", false), ("enumerate", true)] {
|
||||
let begin = format!("\\begin{{{environment}}}");
|
||||
let finish = format!("\\end{{{environment}}}");
|
||||
@@ -772,6 +810,7 @@ fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -797,6 +836,7 @@ fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -831,6 +871,7 @@ fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -845,6 +886,44 @@ fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
|
||||
/// a full LaTeX reader; it exists so the live endpoint can show headings and
|
||||
/// emphasis while the semantic layer is built out.
|
||||
fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
if let Some(inner) = raw
|
||||
.strip_prefix("\\begin{equation}")
|
||||
.and_then(|text| text.strip_suffix("\\end{equation}"))
|
||||
{
|
||||
return SourceParagraph {
|
||||
text: inner.trim().to_string(),
|
||||
font: ParagraphFont::Roman,
|
||||
line_height: 12,
|
||||
math: true,
|
||||
left_skip: 0,
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
space_before: 0,
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: Some(0),
|
||||
};
|
||||
}
|
||||
if let Some(inner) = raw
|
||||
.strip_prefix("\\begin{equation*}")
|
||||
.and_then(|text| text.strip_suffix("\\end{equation*}"))
|
||||
{
|
||||
return SourceParagraph {
|
||||
text: inner.trim().to_string(),
|
||||
font: ParagraphFont::Roman,
|
||||
line_height: 12,
|
||||
math: true,
|
||||
left_skip: 0,
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
space_before: 0,
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
};
|
||||
}
|
||||
if let Some(math) = raw
|
||||
.strip_prefix("$$")
|
||||
.and_then(|text| text.strip_suffix("$$"))
|
||||
@@ -865,6 +944,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
};
|
||||
}
|
||||
let candidates = [
|
||||
@@ -886,6 +966,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -901,6 +982,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
space_stretch: 0,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,6 +1009,13 @@ 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 {
|
||||
body: Box::new(atom),
|
||||
tag: format!("({number})"),
|
||||
},
|
||||
None => atom,
|
||||
};
|
||||
let lines = split_math_lines(&atom, &font, 480 * SCALE);
|
||||
let mut unit = Unit::math_lines(index as u64, &lines, &font);
|
||||
unit.space_before = paragraph.space_before;
|
||||
@@ -1390,3 +1479,50 @@ mod source_tests {
|
||||
assert!(engine.pages()[0].items.len() >= 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod equation_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equations_are_numbered_and_labels_resolved() {
|
||||
let source = r"\begin{equation}
|
||||
x^2 + y^2
|
||||
\label{eq:sum}
|
||||
\end{equation}
|
||||
|
||||
See \eqref{eq:sum} and \ref{eq:sum}.
|
||||
|
||||
\begin{equation*}
|
||||
z
|
||||
\end{equation*}
|
||||
|
||||
\begin{equation}
|
||||
a + b
|
||||
\end{equation}";
|
||||
let blocks = paragraphs(source).expect("paragraphs");
|
||||
let numbers: Vec<u32> = blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.equation_number)
|
||||
.collect();
|
||||
assert_eq!(numbers, vec![1, 2], "equation numbering");
|
||||
let reference = blocks
|
||||
.iter()
|
||||
.find(|block| block.text.starts_with("See"))
|
||||
.expect("reference paragraph");
|
||||
assert_eq!(reference.text, "See (1) and 1.");
|
||||
assert!(
|
||||
!blocks.iter().any(|block| block.text.contains("\\label")),
|
||||
"labels are stripped from equation bodies"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_equation_renders_its_tag() {
|
||||
let json = preview_json("\\begin{equation}\nx^2\n\\end{equation}").expect("preview");
|
||||
assert!(json.contains(">x</text>"), "formula glyphs in SVG: {json}");
|
||||
assert!(json.contains(">(</text>"), "open tag parenthesis");
|
||||
assert!(json.contains(">1</text>"), "equation number");
|
||||
assert!(json.contains(">)</text>"), "close tag parenthesis");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user