Reserve display skips around math
TeX surrounds each display with \abovedisplayskip above and \belowdisplayskip below, but route-D only reserved the paragraph's own spacing, so displays sat directly against the surrounding text. Parse the four registers (including the short forms), default to the article-class 10/11/12pt values, and add them to the math unit and the unit that follows it. The glue parser now also accepts the class-file spelling (`\abovedisplayskip 7\p@ \@plus 2\p@ \@minus 5\p@`), register copies such as `\belowdisplayskip \abovedisplayskip`, `\z@`/`\p@` dimensions and space-separated assignments, which clears the display-skip warnings the arXiv template produced. A page oracle sets a 45pt above skip and pins the display moving to the second page exactly as pdfLaTeX lays it out; unit tests cover the defaults, overrides and the class-file spelling.
This commit is contained in:
1 parent
8ac2e828df
commit
2f9b18c95c
4 files changed
+265
-21
No files matched your search
@@ -293,23 +293,61 @@ fn pdftex_pages(source: &str) -> Option<Vec<String>> {
|
||||
fn page_alnum_text(page: &texrra_tex_core::Page) -> String {
|
||||
let mut text = String::new();
|
||||
for item in &page.items {
|
||||
let VerticalItem::Paragraph(paragraph) = item else {
|
||||
continue;
|
||||
};
|
||||
for line in ¶graph.lines {
|
||||
for item in line {
|
||||
if let HorizontalItem::Box(box_) = item
|
||||
&& let Some(character) = box_.character
|
||||
&& character.is_ascii_alphanumeric()
|
||||
{
|
||||
text.push(character);
|
||||
match item {
|
||||
VerticalItem::Paragraph(paragraph) => {
|
||||
for line in ¶graph.lines {
|
||||
for item in line {
|
||||
if let HorizontalItem::Box(box_) = item
|
||||
&& let Some(character) = box_.character
|
||||
&& character.is_ascii_alphanumeric()
|
||||
{
|
||||
text.push(character);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
VerticalItem::Math { atom, .. } => math_alnum_text(atom, &mut text),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn math_alnum_text(atom: &texrra_tex_core::math::MathAtom, text: &mut String) {
|
||||
use texrra_tex_core::math::MathAtom;
|
||||
match atom {
|
||||
MathAtom::Symbol(character) if character.is_ascii_alphanumeric() => text.push(*character),
|
||||
MathAtom::Text(value) => {
|
||||
text.extend(value.chars().filter(char::is_ascii_alphanumeric));
|
||||
}
|
||||
MathAtom::Row(atoms) => {
|
||||
for atom in atoms {
|
||||
math_alnum_text(atom, text);
|
||||
}
|
||||
}
|
||||
MathAtom::Classed { body, .. } => math_alnum_text(body, text),
|
||||
MathAtom::Script { base, sub, sup } => {
|
||||
math_alnum_text(base, text);
|
||||
if let Some(sub) = sub {
|
||||
math_alnum_text(sub, text);
|
||||
}
|
||||
if let Some(sup) = sup {
|
||||
math_alnum_text(sup, text);
|
||||
}
|
||||
}
|
||||
MathAtom::Limits { base, sub, sup } => {
|
||||
math_alnum_text(base, text);
|
||||
if let Some(sub) = sub {
|
||||
math_alnum_text(sub, text);
|
||||
}
|
||||
if let Some(sup) = sup {
|
||||
math_alnum_text(sup, text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay `paragraphs` out with the route-D scrolling builder using article
|
||||
/// metrics that match the pdfTeX fixtures (`\hsize` 345pt, `\topskip` 12pt,
|
||||
/// `\vsize` 550pt, `\parskip` 0).
|
||||
@@ -874,6 +912,47 @@ fn widow_penalty_forces_a_break_before_the_last_line() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_skips_push_a_display_to_the_next_page() {
|
||||
let source = "\\documentclass[10pt]{article}\n\
|
||||
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
|
||||
\\pagestyle{empty}\n\
|
||||
\\begin{document}\n\
|
||||
\\hsize=345pt \\parindent=0pt \\topskip=12pt \\vsize=60pt \\abovedisplayskip=45pt \\belowdisplayskip=20pt\n\
|
||||
Before text.\\par\n\\[ x \\]\nAfter text.\\par\n\\end{document}\n";
|
||||
let Some(reference) = pdftex_pages(&source) else {
|
||||
eprintln!("skipping: pdflatex/pdftotext are not installed");
|
||||
return;
|
||||
};
|
||||
let style = ParagraphStyle {
|
||||
line_width: 345 * PT,
|
||||
par_indent: 0,
|
||||
line_height: 12 * PT,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let before = Unit::paragraph_with_style(1, "Before text.", style.clone());
|
||||
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
|
||||
let mut display = Unit::math(2, texrra_tex_core::math::parse_math("x"), &font);
|
||||
display.space_before = 45 * PT;
|
||||
let mut after = Unit::paragraph_with_style(3, "After text.", style);
|
||||
after.space_before = 20 * PT;
|
||||
let mut document = Document::new(60 * PT, vec![before, display, after]);
|
||||
document.top_skip = 12 * PT;
|
||||
document.max_depth = 5 * PT;
|
||||
let engine = Engine::layout_paged(&document).expect("paged layout");
|
||||
let ours: Vec<String> = engine.pages().iter().map(page_alnum_text).collect();
|
||||
assert_eq!(
|
||||
ours.len(),
|
||||
reference.len(),
|
||||
"route-D produced {} pages, pdfLaTeX {}",
|
||||
ours.len(),
|
||||
reference.len()
|
||||
);
|
||||
for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() {
|
||||
assert_eq!(ours, reference, "text on page {}", index + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_break_like_pdftex_for_single_line_paragraphs() {
|
||||
let paragraphs: Vec<String> = (0..100)
|
||||
|
||||
@@ -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`). 963 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 967 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.
|
||||
@@ -308,7 +308,10 @@ Two more fixtures pin TeX's orphan and widow controls: `\clubpenalty=-10000`
|
||||
forces a break after a paragraph's first line and `\widowpenalty=-10000` forces
|
||||
one before its last, page for page against pdfLaTeX. The paged builder inserts
|
||||
both penalties between line nodes (150 by default) and refuses any penalty of
|
||||
10000 or more as a breakpoint.
|
||||
10000 or more as a breakpoint. Display math units reserve `\abovedisplayskip`
|
||||
above and `\belowdisplayskip` below (the 10/11/12pt class defaults, overridable
|
||||
from the source in TeX's `7\p@ \@plus 2\p@` spelling too), and a page fixture
|
||||
shows a display near the page goal moving to the next page with pdfLaTeX.
|
||||
|
||||
### P3 — `\halign` / `\valign` (L2)
|
||||
|
||||
|
||||
+2
-2
@@ -360,7 +360,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. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `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, and `Document::split_max_depth` (TeX `\splitmaxdepth`, `\maxdimen` by default) clamps the first held box's depth while moving the excess into its height); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the later candidate wins, matching the page builder's `least_page_cost` update with `<=`, so a page can take a later break even when it overfills the goal slightly; when no break fits within the glue shrink, the least overfull break is used instead. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. Each multi-line paragraph inserts TeX's `\clubpenalty` after its first line and `\widowpenalty` before its last (150 in LaTeX, overridable through `\clubpenalty`/`\widowpenalty`); a page penalty of 10000 or more is not a legal breakpoint, and forcing either register to -10000 breaks exactly where pdfLaTeX does (two page oracle fixtures). Paragraph boxes carry TeX depth: each node reports its last line's descent, so `\pagedepth` sees it, and the builder adds every box descent beyond `\maxdepth` to the page height while keeping the rest as page depth (TeX's per-box rule); route-D sources default `\maxdepth` to LaTeX's 5pt (0.5\topskip), and the page fixtures set it explicitly. A standalone `\smallskip`, `\medskip`, `\bigskip`, `\vskip` or `\vspace{...}` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpoint with the glue's stretch and shrink, and edits preserve all three components; the command no longer leaks into the paragraph text. `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`, and
|
||||
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. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `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, and `Document::split_max_depth` (TeX `\splitmaxdepth`, `\maxdimen` by default) clamps the first held box's depth while moving the excess into its height); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the later candidate wins, matching the page builder's `least_page_cost` update with `<=`, so a page can take a later break even when it overfills the goal slightly; when no break fits within the glue shrink, the least overfull break is used instead. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. Each multi-line paragraph inserts TeX's `\clubpenalty` after its first line and `\widowpenalty` before its last (150 in LaTeX, overridable through `\clubpenalty`/`\widowpenalty`); a page penalty of 10000 or more is not a legal breakpoint, and forcing either register to -10000 breaks exactly where pdfLaTeX does (two page oracle fixtures). Display math units also reserve LaTeX's `\abovedisplayskip` above and `\belowdisplayskip` below (10pt plus 2pt minus 5pt at 10pt, 11pt/12pt class values otherwise); the four registers, including the short forms, are read from the source in both `\abovedisplayskip=10pt plus 2pt` and class-file `\abovedisplayskip 7\p@ \@plus 2\p@` spelling, `\belowdisplayskip \abovedisplayskip` copies resolve, and a page oracle pins a display that no longer fits moving to the next page exactly as pdfLaTeX does. Paragraph boxes carry TeX depth: each node reports its last line's descent, so `\pagedepth` sees it, and the builder adds every box descent beyond `\maxdepth` to the page height while keeping the rest as page depth (TeX's per-box rule); route-D sources default `\maxdepth` to LaTeX's 5pt (0.5\topskip), and the page fixtures set it explicitly. A standalone `\smallskip`, `\medskip`, `\bigskip`, `\vskip` or `\vspace{...}` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpointLine truncated
|
||||
preview pages apply the same offsets to their display list so the editor and
|
||||
PDF agree. `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; `\textwidth`/`\hsize` (including `\setlength{\textwidth}{...}`) set the paragraph measure, and `\setlength` also applies to the supported layout lengths with `\parskip` keeping its plus/minus glue; 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`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. A `\mark{...}` or classed `\marks<n>{...}` write inside the routine is recorded by the interpreter and placed at the front of the next page's marks, so the carried marks TeX exposes to the following page are reproduced. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\advance`, `\multiply` and `\divide` adjust those registers in place (`\advance\pageno by 2`, `\divide\deadcycles by 2`, `\advance\dimen2 by 5pt`), and an arithmetic `\vsize` change retargets later pages exactly like an assignment; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); 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 remaining fragments are rebuilt from the next node index with the new goal, which works with insertion material because class limits apply while the page is assembled; a deferred bottom float disables the retarget because the carried queue cannot be rebuilt. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. `\vbadness` carries the page's break badness and `\insertpenalties` counts insertion items the class limits held over, so an output routine can react to overfull breaks or split insertions. 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 interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. A document that contains a bottom float likewise rebuilds in full: a deferred float is carried on the page fragment, and a suffix replay starting at a page boundary cannot recover that queue. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: ten page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears, and `[b]` floats that fit or defer to the next page) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`.
|
||||
|
||||
@@ -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-one oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 963 tests (434 route-D unit, 342 engine binary unit, 10 route-D integration, 41 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 967 tests (434 route-D unit, 345 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
|
||||
|
||||
|
||||
+169
-7
@@ -231,6 +231,11 @@ struct PageGeometry {
|
||||
max_depth: Option<i64>,
|
||||
club_penalty: Option<i64>,
|
||||
widow_penalty: Option<i64>,
|
||||
/// `\abovedisplayskip` and friends, as width/stretch/shrink.
|
||||
above_display_skip: Option<(i64, i64, i64)>,
|
||||
below_display_skip: Option<(i64, i64, i64)>,
|
||||
above_display_short_skip: Option<(i64, i64, i64)>,
|
||||
below_display_short_skip: Option<(i64, i64, i64)>,
|
||||
split_top_skip: Option<i64>,
|
||||
split_max_depth: Option<i64>,
|
||||
hyphen_penalty: Option<i64>,
|
||||
@@ -2621,6 +2626,20 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
geometry.par_skip = Some(width);
|
||||
geometry.par_skip_stretch = Some(stretch);
|
||||
geometry.par_skip_shrink = Some(shrink);
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "abovedisplayskip") {
|
||||
geometry.above_display_skip = Some(spacing);
|
||||
} else if glue_copy(trimmed, "belowdisplayskip", "abovedisplayskip") {
|
||||
geometry.below_display_skip = geometry.above_display_skip;
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "belowdisplayskip") {
|
||||
geometry.below_display_skip = Some(spacing);
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "abovedisplayshortskip") {
|
||||
geometry.above_display_short_skip = Some(spacing);
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "belowdisplayshortskip") {
|
||||
geometry.below_display_short_skip = Some(spacing);
|
||||
} else if let Some(spacing) = setlength_glue(trimmed, "abovedisplayskip") {
|
||||
geometry.above_display_skip = Some(spacing);
|
||||
} else if let Some(spacing) = setlength_glue(trimmed, "belowdisplayskip") {
|
||||
geometry.below_display_skip = Some(spacing);
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "itemsep") {
|
||||
geometry.item_sep = Some(spacing);
|
||||
} else if let Some(spacing) = glue_assignment(trimmed, "topsep") {
|
||||
@@ -4628,21 +4647,49 @@ fn sfcode_assignment(line: &str) -> Option<(char, i64)> {
|
||||
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 rest = rest.trim_start();
|
||||
// TeX accepts both `\parskip=6pt` and `\abovedisplayskip 10pt`; class
|
||||
// files use the space-separated form.
|
||||
let rest = rest.strip_prefix('=').unwrap_or(rest).trim();
|
||||
let (width, rest) = split_glue_part(rest)?;
|
||||
let (stretch, rest) = match rest.trim_start().strip_prefix("plus") {
|
||||
let rest = rest.trim_start();
|
||||
let (stretch, rest) = match rest
|
||||
.strip_prefix("plus")
|
||||
.or_else(|| rest.strip_prefix("\\@plus"))
|
||||
{
|
||||
Some(rest) => split_glue_part(rest.trim_start())?,
|
||||
None => (0, rest),
|
||||
};
|
||||
let shrink = match rest.trim_start().strip_prefix("minus") {
|
||||
let rest = rest.trim_start();
|
||||
let shrink = match rest
|
||||
.strip_prefix("minus")
|
||||
.or_else(|| rest.strip_prefix("\\@minus"))
|
||||
{
|
||||
Some(rest) => split_glue_part(rest.trim_start())?.0,
|
||||
None => 0,
|
||||
};
|
||||
Some((width, stretch, shrink))
|
||||
}
|
||||
|
||||
/// Match a register copy such as `\belowdisplayskip \abovedisplayskip`.
|
||||
fn glue_copy(line: &str, name: &str, source: &str) -> bool {
|
||||
let Some(rest) = line.strip_prefix('\\') else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = rest.strip_prefix(name) else {
|
||||
return false;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
let rest = rest.strip_prefix('=').unwrap_or(rest).trim();
|
||||
rest == format!("\\{source}")
|
||||
}
|
||||
|
||||
fn split_glue_part(text: &str) -> Option<(i64, &str)> {
|
||||
let text = text.trim_start();
|
||||
// TeX's internal dimension macros: \z@ is 0pt and \p@ is 1pt.
|
||||
if let Some(rest) = text.strip_prefix("\\z@") {
|
||||
return Some((0, rest));
|
||||
}
|
||||
let end = text
|
||||
.find(|character: char| {
|
||||
!(character.is_ascii_digit() || character == '.' || character == '-')
|
||||
@@ -4650,11 +4697,11 @@ fn split_glue_part(text: &str) -> Option<(i64, &str)> {
|
||||
.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"]
|
||||
let (unit, rest) = ["pt", "bp", "in", "cm", "mm", "pc", "\\p@"]
|
||||
.iter()
|
||||
.find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?;
|
||||
let factor = match unit {
|
||||
"pt" => 65_536.0,
|
||||
"pt" | "\\p@" => 65_536.0,
|
||||
"bp" => 65_782.0,
|
||||
"in" => 4_736_286.0,
|
||||
"cm" => 1_864_680.0,
|
||||
@@ -9516,6 +9563,18 @@ fn color_switch(text: &str) -> Option<(String, String)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// LaTeX's article-class display skips for 10pt, 11pt and 12pt.
|
||||
fn display_skip_defaults(base_font_size: i64) -> ((i64, i64, i64), (i64, i64, i64)) {
|
||||
const PT: i64 = 65_536;
|
||||
if base_font_size >= 12 * PT {
|
||||
((12 * PT, 3 * PT, 7 * PT), (12 * PT, 3 * PT, 7 * PT))
|
||||
} else if base_font_size >= 11 * PT {
|
||||
((11 * PT, 3 * PT, 6 * PT), (11 * PT, 3 * PT, 6 * PT))
|
||||
} else {
|
||||
((10 * PT, 2 * PT, 5 * PT), (10 * PT, 2 * PT, 5 * PT))
|
||||
}
|
||||
}
|
||||
|
||||
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
|
||||
build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new())
|
||||
}
|
||||
@@ -9603,7 +9662,7 @@ fn build_document_with_labels(
|
||||
}
|
||||
}
|
||||
let line_width = geometry.line_width.unwrap_or(480 * SCALE);
|
||||
let base_units: Vec<Unit> = paragraphs
|
||||
let mut base_units: Vec<Unit> = paragraphs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, paragraph)| {
|
||||
@@ -9949,6 +10008,22 @@ fn build_document_with_labels(
|
||||
.collect();
|
||||
// Footnotes follow their anchor paragraph as insertion units, so the page
|
||||
// builder reserves room for them on the page that mentions them.
|
||||
let (default_above_display, default_below_display) =
|
||||
display_skip_defaults(geometry.base_font_size.unwrap_or(655_360));
|
||||
let above_display = geometry.above_display_skip.unwrap_or(default_above_display);
|
||||
let below_display = geometry.below_display_skip.unwrap_or(default_below_display);
|
||||
for index in 0..base_units.len().min(paragraphs.len()) {
|
||||
if paragraphs[index].math {
|
||||
base_units[index].space_before += above_display.0;
|
||||
base_units[index].space_stretch += above_display.1;
|
||||
base_units[index].space_shrink += above_display.2;
|
||||
}
|
||||
if index > 0 && paragraphs[index - 1].math {
|
||||
base_units[index].space_before += below_display.0;
|
||||
base_units[index].space_stretch += below_display.1;
|
||||
base_units[index].space_shrink += below_display.2;
|
||||
}
|
||||
}
|
||||
let mut units: Vec<Unit> = Vec::with_capacity(base_units.len());
|
||||
let mut unit_for_paragraph = Vec::with_capacity(paragraphs.len());
|
||||
let mut footnote_count = 0usize;
|
||||
@@ -13451,6 +13526,93 @@ A definition.
|
||||
assert_eq!(document.widow_penalty, 88);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_math_uses_article_display_skips() {
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||||
let document = build_document(¶graphs, &geometry);
|
||||
let math_index = document
|
||||
.units
|
||||
.iter()
|
||||
.position(|unit| {
|
||||
unit.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, VerticalItem::Math { .. }))
|
||||
})
|
||||
.expect("display math unit");
|
||||
let math = &document.units[math_index];
|
||||
assert_eq!(math.space_before, 10 * SCALE);
|
||||
assert_eq!(math.space_stretch, 2 * SCALE);
|
||||
assert_eq!(math.space_shrink, 5 * SCALE);
|
||||
let after = &document.units[math_index + 1];
|
||||
assert_eq!(after.space_before, 10 * SCALE);
|
||||
assert_eq!(after.space_stretch, 2 * SCALE);
|
||||
assert_eq!(after.space_shrink, 5 * SCALE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_skips_accept_class_file_spelling() {
|
||||
let source = "\\documentclass{article}\n\\abovedisplayskip 7\\p@ \\@plus 2\\p@ \\@minus 5\\p@\n\\abovedisplayshortskip \\z@ \\@plus 3\\p@\n\\belowdisplayskip \\abovedisplayskip\n\\belowdisplayshortskip 4\\p@ \\@plus 3\\p@ \\@minus 3\\p@\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n";
|
||||
let (_body, geometry) = geometry_and_body(source);
|
||||
assert_eq!(
|
||||
geometry.above_display_skip,
|
||||
Some((7 * SCALE, 2 * SCALE, 5 * SCALE))
|
||||
);
|
||||
assert_eq!(geometry.above_display_short_skip, Some((0, 3 * SCALE, 0)));
|
||||
assert_eq!(
|
||||
geometry.below_display_skip,
|
||||
Some((7 * SCALE, 2 * SCALE, 5 * SCALE))
|
||||
);
|
||||
assert_eq!(
|
||||
geometry.below_display_short_skip,
|
||||
Some((4 * SCALE, 3 * SCALE, 3 * SCALE))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_skip_registers_override_the_class_defaults() {
|
||||
let source = "\\documentclass{article}\n\\abovedisplayskip=30pt plus 1pt minus 2pt\n\\belowdisplayskip=40pt plus 3pt minus 4pt\n\\abovedisplayshortskip=1pt plus 2pt\n\\belowdisplayshortskip=3pt minus 1pt\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
assert_eq!(
|
||||
geometry.above_display_skip,
|
||||
Some((30 * SCALE, SCALE, 2 * SCALE))
|
||||
);
|
||||
assert_eq!(
|
||||
geometry.below_display_skip,
|
||||
Some((40 * SCALE, 3 * SCALE, 4 * SCALE))
|
||||
);
|
||||
assert_eq!(
|
||||
geometry.above_display_short_skip,
|
||||
Some((SCALE, 2 * SCALE, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
geometry.below_display_short_skip,
|
||||
Some((3 * SCALE, 0, SCALE))
|
||||
);
|
||||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||||
let document = build_document(¶graphs, &geometry);
|
||||
let math_index = document
|
||||
.units
|
||||
.iter()
|
||||
.position(|unit| {
|
||||
unit.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, VerticalItem::Math { .. }))
|
||||
})
|
||||
.expect("display math unit");
|
||||
let math = &document.units[math_index];
|
||||
assert_eq!(
|
||||
(math.space_before, math.space_stretch, math.space_shrink),
|
||||
(30 * SCALE, SCALE, 2 * SCALE)
|
||||
);
|
||||
let after = &document.units[math_index + 1];
|
||||
assert_eq!(
|
||||
(after.space_before, after.space_stretch, after.space_shrink),
|
||||
(40 * SCALE, 3 * SCALE, 4 * SCALE)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometry_reads_demerit_registers() {
|
||||
let source = "\\documentclass{article}\n\\hyphenpenalty=77\n\\exhyphenpenalty=88\n\\doublehyphendemerits=1234\n\\finalhyphendemerits=4321\n\\linepenalty=20\n\\adjdemerits=999\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||||
|
||||
Reference in new issue
Block a user