Read hang indent, spacing and tolerance registers from route-D sources
This commit is contained in:
1 parent
53436f8177
commit
96cd98f833
4 files changed
+160
-10
No files matched your search
@@ -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`). 422 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 424 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
|
||||
+2
-2
@@ -338,7 +338,7 @@ M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic
|
||||
|
||||
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
|
||||
|
||||
M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance` and `\pretolerance` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interLine truncated
|
||||
M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the seLine truncated
|
||||
|
||||
M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved.
|
||||
|
||||
@@ -346,7 +346,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 288 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 422 tests (288 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 25 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
|
||||
The crate currently has 288 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 424 tests (288 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 3 binary units), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
+95
-7
@@ -115,6 +115,11 @@ struct PageGeometry {
|
||||
tolerance: Option<i64>,
|
||||
pretolerance: Option<i64>,
|
||||
emergency_stretch: Option<i64>,
|
||||
hang_indent: Option<i64>,
|
||||
hang_after: Option<i64>,
|
||||
french_spacing: Option<bool>,
|
||||
space_skip: Option<(i64, i64, i64)>,
|
||||
xspace_skip: Option<(i64, i64, i64)>,
|
||||
}
|
||||
|
||||
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/
|
||||
@@ -154,6 +159,18 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
geometry.tolerance = Some(value);
|
||||
} else if let Some(value) = integer_assignment(trimmed, "pretolerance") {
|
||||
geometry.pretolerance = Some(value);
|
||||
} else if let Some(value) = dimension_assignment(trimmed, "hangindent") {
|
||||
geometry.hang_indent = Some(value);
|
||||
} else if let Some(value) = integer_assignment(trimmed, "hangafter") {
|
||||
geometry.hang_after = Some(value);
|
||||
} else if let Some(value) = glue_assignment(trimmed, "spaceskip") {
|
||||
geometry.space_skip = Some(value);
|
||||
} else if let Some(value) = glue_assignment(trimmed, "xspaceskip") {
|
||||
geometry.xspace_skip = Some(value);
|
||||
} else if trimmed == "\\frenchspacing" {
|
||||
geometry.french_spacing = Some(true);
|
||||
} else if trimmed == "\\nonfrenchspacing" {
|
||||
geometry.french_spacing = Some(false);
|
||||
} else {
|
||||
body.push_str(line);
|
||||
body.push('\n');
|
||||
@@ -166,7 +183,10 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
/// return the LaTeX body with them removed.
|
||||
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||||
let (stripped, geometry) = strip_page_geometry(source);
|
||||
(latex_body(&stripped).to_string(), geometry)
|
||||
// Removed assignments can leave blank lines at the edges; they are not
|
||||
// paragraphs of their own.
|
||||
let body = latex_body(&stripped).trim_matches('\n').to_string();
|
||||
(body, geometry)
|
||||
}
|
||||
|
||||
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
|
||||
@@ -187,10 +207,49 @@ fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
|
||||
}
|
||||
|
||||
/// Read a plain integer assignment such as `\tolerance=1000`.
|
||||
fn glue_assignment(line: &str, name: &str) -> Option<(i64, i64, i64)> {
|
||||
let rest = line.strip_prefix('\\')?;
|
||||
let rest = rest.strip_prefix(name)?;
|
||||
let rest = rest.trim_start().strip_prefix('=')?;
|
||||
let rest = rest.trim();
|
||||
let (width, rest) = split_glue_part(rest)?;
|
||||
let (stretch, rest) = match rest.trim_start().strip_prefix("plus") {
|
||||
Some(rest) => split_glue_part(rest.trim_start())?,
|
||||
None => (0, rest),
|
||||
};
|
||||
let shrink = match rest.trim_start().strip_prefix("minus") {
|
||||
Some(rest) => split_glue_part(rest.trim_start())?.0,
|
||||
None => 0,
|
||||
};
|
||||
Some((width, stretch, shrink))
|
||||
}
|
||||
|
||||
fn split_glue_part(text: &str) -> Option<(i64, &str)> {
|
||||
let end = text
|
||||
.find(|character: char| {
|
||||
!(character.is_ascii_digit() || character == '.' || character == '-')
|
||||
})
|
||||
.unwrap_or(text.len());
|
||||
let number: f64 = text[..end].parse().ok()?;
|
||||
let unit_text = &text[end..];
|
||||
let (unit, rest) = ["pt", "bp", "in", "cm", "mm", "pc"]
|
||||
.iter()
|
||||
.find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?;
|
||||
let factor = match unit {
|
||||
"pt" => 65_536.0,
|
||||
"bp" => 65_782.0,
|
||||
"in" => 4_736_286.0,
|
||||
"cm" => 1_864_680.0,
|
||||
"mm" => 186_468.0,
|
||||
_ => 786_432.0,
|
||||
};
|
||||
Some(((number * factor).round() as i64, rest))
|
||||
}
|
||||
|
||||
fn integer_assignment(line: &str, name: &str) -> Option<i64> {
|
||||
let rest = line.strip_prefix('\\')?;
|
||||
let rest = rest.strip_prefix(name)?;
|
||||
rest.trim_start().strip_prefix('=')?;
|
||||
let rest = rest.trim_start().strip_prefix('=')?;
|
||||
rest.trim()
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
@@ -484,13 +543,13 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
|
||||
right_aligned: paragraph.right_aligned,
|
||||
ragged_right: false,
|
||||
right_skip: geometry.right_skip.unwrap_or(0),
|
||||
hang_indent: 0,
|
||||
hang_after: 1,
|
||||
hang_indent: geometry.hang_indent.unwrap_or(0),
|
||||
hang_after: geometry.hang_after.unwrap_or(1) as i32,
|
||||
par_shape: Vec::new(),
|
||||
par_fillskip: 0,
|
||||
par_fillskip_stretch: 0,
|
||||
par_fillskip_fil: true,
|
||||
frenchspacing: false,
|
||||
frenchspacing: geometry.french_spacing.unwrap_or(false),
|
||||
space_factor_codes: Vec::new(),
|
||||
baselineskip: geometry.baseline_skip.unwrap_or(12 * 65536),
|
||||
lineskip: 65536,
|
||||
@@ -515,8 +574,8 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
|
||||
space_width: 4 * SCALE,
|
||||
space_stretch: 6 * SCALE,
|
||||
space_shrink: 2 * SCALE,
|
||||
space_skip: None,
|
||||
xspace_skip: None,
|
||||
space_skip: geometry.space_skip,
|
||||
xspace_skip: geometry.xspace_skip,
|
||||
};
|
||||
Unit::paragraph_with_style_and_face(
|
||||
index as u64,
|
||||
@@ -658,3 +717,32 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_hang_registers_from_the_preamble() {
|
||||
let (body, geometry) = geometry_and_body(
|
||||
"\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word",
|
||||
);
|
||||
assert_eq!(geometry.hang_indent, Some(20 * 65_536));
|
||||
assert_eq!(geometry.hang_after, Some(1));
|
||||
let pt = 65_536;
|
||||
assert_eq!(geometry.tolerance, Some(1000));
|
||||
assert_eq!(geometry.pretolerance, Some(50));
|
||||
assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2)));
|
||||
assert_eq!(geometry.french_spacing, Some(true));
|
||||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||||
assert_eq!(paragraphs.len(), 1, "{body:?}");
|
||||
let document = build_document(¶graphs, &geometry);
|
||||
let style = document.units[0].paragraph_style.clone().expect("style");
|
||||
assert_eq!(style.hang_indent, 20 * 65_536);
|
||||
assert_eq!(style.hang_after, 1);
|
||||
assert_eq!(style.tolerance, 1000);
|
||||
assert_eq!(style.pretolerance, 50);
|
||||
assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2)));
|
||||
assert!(style.frenchspacing);
|
||||
}
|
||||
}
|
||||
@@ -781,6 +781,68 @@ fn route_d_renders_flushright_blocks() {
|
||||
assert!(x > 50.0, "{x}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_d_applies_hang_indent_from_source() {
|
||||
let server = TestServer::start("route-d-hangindent");
|
||||
let body = "word ".repeat(120);
|
||||
let source = format!("\\hangindent=20pt\n\\hangafter=1\n\n{body}");
|
||||
|
||||
let plain = server.request(
|
||||
"POST",
|
||||
"/api/route-d/preview",
|
||||
body.as_bytes(),
|
||||
"text/plain",
|
||||
);
|
||||
assert_eq!(plain.status, 200, "{}", plain.text());
|
||||
let plain: Value = serde_json::from_slice(&plain.body).expect("route-D JSON");
|
||||
let plain_starts = line_starts(plain["pages"][0]["svg"].as_str().unwrap());
|
||||
assert!(
|
||||
plain_starts.len() >= 3,
|
||||
"need several lines: {plain_starts:?}"
|
||||
);
|
||||
assert!(plain_starts[1].1 < 3.0, "plain lines start at zero");
|
||||
|
||||
let hung = server.request(
|
||||
"POST",
|
||||
"/api/route-d/preview",
|
||||
source.as_bytes(),
|
||||
"text/plain",
|
||||
);
|
||||
assert_eq!(hung.status, 200, "{}", hung.text());
|
||||
let hung: Value = serde_json::from_slice(&hung.body).expect("route-D JSON");
|
||||
let hung_starts = line_starts(hung["pages"][0]["svg"].as_str().unwrap());
|
||||
assert!(hung_starts[0].1 < 3.0, "first line is not hung");
|
||||
assert!(
|
||||
hung_starts[1].1 > 15.0,
|
||||
"hangindent should shift later lines: {hung_starts:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// (y, x) of the leftmost glyph on each distinct text baseline.
|
||||
fn line_starts(svg: &str) -> Vec<(f64, f64)> {
|
||||
let mut lines: Vec<(f64, f64)> = Vec::new();
|
||||
let mut rest = svg;
|
||||
while let Some(start) = rest.find("<text x=\"") {
|
||||
let after = &rest[start + 9..];
|
||||
let x: f64 = after.split('"').next().unwrap().parse().unwrap();
|
||||
let y_start = after.find(" y=\"").expect("text y");
|
||||
let y: f64 = after[y_start + 4..]
|
||||
.split('"')
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
let key = (y * 100.0).round() / 100.0;
|
||||
match lines.iter_mut().find(|(line_y, _)| *line_y == key) {
|
||||
Some((_, line_x)) => *line_x = line_x.min(x),
|
||||
None => lines.push((key, x)),
|
||||
}
|
||||
rest = &after[y_start..];
|
||||
}
|
||||
lines.sort_by(|left, right| left.0.total_cmp(&right.0));
|
||||
lines
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_d_applies_source_paragraph_registers() {
|
||||
let server = TestServer::start("route-d-parregisters");
|
||||
|
||||
Reference in new issue
Block a user