diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index d2d299e..91c09e5 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -246,6 +246,12 @@ pub struct Unit { /// Extra vertical glue before this unit (TeX `\vskip`/`\smallskip`). #[serde(default)] pub space_before: i64, + /// Stretch of the glue before this unit. + #[serde(default)] + pub space_stretch: i64, + /// Shrink of the glue before this unit. + #[serde(default)] + pub space_shrink: i64, } impl Unit { @@ -309,6 +315,8 @@ impl Unit { source: "halign".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![VerticalItem::Halign(Halign { rows, column_widths, @@ -515,6 +523,8 @@ impl Unit { items: vec![VerticalItem::Paragraph(paragraph)], paragraph_style: Some(style), space_before: 0, + space_stretch: 0, + space_shrink: 0, } } @@ -544,6 +554,8 @@ impl Unit { items, paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, } } @@ -847,8 +859,8 @@ fn document_nodes( if unit.space_before > 0 { nodes.push(VerticalNode::Glue(VerticalGlue::new( unit.space_before, - 0, - 0, + unit.space_stretch, + unit.space_shrink, ))); owners.push(index); items.push(VerticalItem::Glue(unit.space_before)); @@ -2310,8 +2322,12 @@ impl Engine { }) .unwrap_or(ParagraphFont::Roman); let space_before = next.units[unit_index].space_before; + let space_stretch = next.units[unit_index].space_stretch; + let space_shrink = next.units[unit_index].space_shrink; next.units[unit_index] = Unit::paragraph_with_style_and_face(unit_id, source, style, font); next.units[unit_index].space_before = space_before; + next.units[unit_index].space_stretch = space_stretch; + next.units[unit_index].space_shrink = space_shrink; if self.layout.checkpoints.is_empty() { if !self.relayout_paged_incremental(&next, unit_index) { self.replace_with_paged(&next); @@ -2865,6 +2881,8 @@ mod tests { source: "footnote layout".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Insertion(Insertion { class: 0, @@ -2993,6 +3011,8 @@ mod tests { source: String::new(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, @@ -3015,6 +3035,8 @@ mod tests { source: "boxes".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3065,6 +3087,8 @@ mod tests { source: "penalty".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3129,6 +3153,8 @@ mod tests { source: text.to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3188,6 +3214,8 @@ mod tests { source: "float".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3222,6 +3250,8 @@ mod tests { source: "float".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3825,6 +3855,8 @@ mod tests { source: "bottom float".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3861,6 +3893,8 @@ mod tests { source: "tall bottom float".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Box(VerticalBox { width: 10, @@ -3894,6 +3928,8 @@ mod tests { source: "top fraction".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Float(Float { gap_before: 0, @@ -5477,6 +5513,8 @@ mod tests { source: "top float".to_owned(), paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, items: vec![ VerticalItem::Float(Float { placement: FloatPlacement::Top, @@ -5916,6 +5954,8 @@ mod tests { }], paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, }; let mut document = Document::new(100, vec![math, Unit::vskip(2, 0), Unit::rule(3, 100, 20)]); @@ -6006,6 +6046,8 @@ mod tests { }], paragraph_style: None, space_before: 0, + space_stretch: 0, + space_shrink: 0, }; let mut document = Document::new(800_000, vec![math]); document.max_depth = 400_000; diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 0d7803e..b07b7f1 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -345,7 +345,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. A standalone `\smallskip`, `\medskip`, `\bigskip` or `\vskip` line between paragraphs becomes the following unit's `space_before` glue, which both page builders reserve and edits preserve; 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. `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. A standalone `\smallskip`, `\medskip`, `\bigskip` or `\vskip` 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 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; 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 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. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. diff --git a/src/route_d.rs b/src/route_d.rs index 3b903c5..df18583 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -511,21 +511,46 @@ struct SourceParagraph { math: bool, left_skip: i64, space_before: i64, + space_stretch: i64, + space_shrink: i64, } /// Recognise an explicit vertical skip command standing alone between /// paragraphs. -fn vertical_skip(text: &str) -> Option { +fn vertical_skip(text: &str) -> Option<(i64, i64, i64)> { match text.trim() { - "\\smallskip" => Some(3 * SCALE), - "\\medskip" => Some(6 * SCALE), - "\\bigskip" => Some(12 * SCALE), + "\\smallskip" => Some((3 * SCALE, SCALE, SCALE)), + "\\medskip" => Some((6 * SCALE, 2 * SCALE, 2 * SCALE)), + "\\bigskip" => Some((12 * SCALE, 4 * SCALE, 4 * SCALE)), other => other .strip_prefix("\\vskip") - .and_then(|rest| parse_dimension(rest.trim_start())), + .and_then(|rest| skip_glue(rest.trim_start())), } } +/// Parse `\vskip` glue: a width with optional `plus` and `minus` parts. +fn skip_glue(rest: &str) -> Option<(i64, i64, i64)> { + let mut width = None; + let mut stretch = 0_i64; + let mut shrink = 0_i64; + let mut mode = 0_u8; + for token in rest.split_whitespace() { + match token { + "plus" => mode = 1, + "minus" => mode = 2, + _ => { + let value = parse_dimension(token)?; + match mode { + 0 => width = Some(value), + 1 => stretch = value, + _ => shrink = value, + } + } + } + } + Some((width?, stretch, shrink)) +} + fn paragraphs(source: &str) -> Result, String> { let paragraphs: Vec<&str> = source .split("\n\n") @@ -536,16 +561,20 @@ fn paragraphs(source: &str) -> Result, String> { return Err("route-D preview needs at least one paragraph".to_string()); } let mut result = Vec::new(); - let mut pending = 0_i64; + let mut pending = (0_i64, 0_i64, 0_i64); for chunk in paragraphs { if let Some(skip) = vertical_skip(chunk) { - pending += skip; + pending.0 += skip.0; + pending.1 += skip.1; + pending.2 += skip.2; continue; } let mut blocks = parse_blocks(chunk); if let Some(first) = blocks.first_mut() { - first.space_before += pending; - pending = 0; + first.space_before += pending.0; + first.space_stretch += pending.1; + first.space_shrink += pending.2; + pending = (0, 0, 0); } result.extend(blocks); } @@ -589,6 +618,8 @@ fn parse_blocks(raw: &str) -> Vec { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, } }) .collect(); @@ -611,6 +642,8 @@ fn parse_blocks(raw: &str) -> Vec { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, }]; } } @@ -642,6 +675,8 @@ fn parse_blocks(raw: &str) -> Vec { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, } }) .collect(); @@ -673,6 +708,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, }; } let candidates = [ @@ -691,6 +728,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, }; } } @@ -703,6 +742,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { centered: false, right_aligned: false, space_before: 0, + space_stretch: 0, + space_shrink: 0, } } @@ -718,6 +759,8 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do &Cmr10Metrics::default(), ); unit.space_before = paragraph.space_before; + unit.space_stretch = paragraph.space_stretch; + unit.space_shrink = paragraph.space_shrink; return unit; } let style = ParagraphStyle { @@ -775,6 +818,8 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do paragraph.font, ); unit.space_before = paragraph.space_before; + unit.space_stretch = paragraph.space_stretch; + unit.space_shrink = paragraph.space_shrink; unit }) .collect(); @@ -1086,12 +1131,19 @@ mod source_tests { } #[test] fn paragraphs_read_vertical_skip_commands() { - let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma."; + let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma.\n\n\\vskip 5pt plus 2pt minus 1pt\n\nDelta."; let parsed = paragraphs(source).expect("paragraphs"); - assert_eq!(parsed.len(), 3); + assert_eq!(parsed.len(), 4); assert_eq!(parsed[0].space_before, 0); assert_eq!(parsed[1].space_before, 6 * SCALE); + assert_eq!(parsed[1].space_stretch, 2 * SCALE); + assert_eq!(parsed[1].space_shrink, 2 * SCALE); assert_eq!(parsed[2].space_before, 12 * SCALE); + assert_eq!(parsed[2].space_stretch, 4 * SCALE); + assert_eq!(parsed[2].space_shrink, 4 * SCALE); + assert_eq!(parsed[3].space_before, 5 * SCALE); + assert_eq!(parsed[3].space_stretch, 2 * SCALE); + assert_eq!(parsed[3].space_shrink, SCALE); assert!( !parsed .iter() @@ -1099,6 +1151,11 @@ mod source_tests { ); let document = build_document(&parsed, &PageGeometry::default()); assert_eq!(document.units[1].space_before, 6 * SCALE); + assert_eq!(document.units[1].space_stretch, 2 * SCALE); + assert_eq!(document.units[1].space_shrink, 2 * SCALE); assert_eq!(document.units[2].space_before, 12 * SCALE); + assert_eq!(document.units[3].space_before, 5 * SCALE); + assert_eq!(document.units[3].space_stretch, 2 * SCALE); + assert_eq!(document.units[3].space_shrink, SCALE); } }