diff --git a/README.md b/README.md index a32ac17..6beef93 100644 --- a/README.md +++ b/README.md @@ -577,7 +577,7 @@ edit demo. M1 adds the horizontal box/glue/penalty model, an item-stream Knuth-P paragraph builder, CMR10 metrics extracted from `cmr10.tfm`, and a matching pdfTeX line-break fixture. Paragraphs are split at line boundaries when they cross a page, and the pdfLaTeX oracle covers the 100-240pt measure matrix plus register, `\hangindent`/`\parshape`, -`\parfillskip`, sentence-spacing, `\looseness` and vertical-glue fixtures. Overflowing +`\parfillskip`, sentence-spacing with custom `\sfcode`, `\looseness` and vertical-glue fixtures. Overflowing insertion material is split at item boundaries, with the tail held over to the next page. The production v1 engine remains the default until the new core reaches layout parity. See `docs/TEX_CORE.md`. The complete phased plan (P0 oracle harness, TeX-exact paragraphs, diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 4618528..062de64 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -98,6 +98,10 @@ pub struct ParagraphStyle { /// punctuation adds no sentence spacing. #[serde(default)] pub frenchspacing: bool, + /// Per-character `\sfcode` overrides (the last matching assignment wins). + /// A code of zero leaves the previous space factor unchanged, as in TeX. + #[serde(default)] + pub space_factor_codes: Vec<(char, i64)>, /// TeX `\baselineskip` (12pt for 10pt text). #[serde(default = "default_baselineskip")] pub baselineskip: i64, @@ -228,6 +232,7 @@ impl Default for ParagraphStyle { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, @@ -1017,7 +1022,12 @@ pub fn text_items_with_font( }); } } - space_factor = space_factor_after(word, style.frenchspacing); + space_factor = space_factor_after( + word, + space_factor, + style.frenchspacing, + &style.space_factor_codes, + ); } while matches!(items.last(), Some(HorizontalItem::Glue { .. })) { items.pop(); @@ -1031,16 +1041,29 @@ pub fn text_items_with_font( } /// TeX's default `\sfcode` values for sentence punctuation (`plain.tex`'s -/// `\nonfrenchspacing`); every other character is 1000. -fn space_factor_after(word: &str, frenchspacing: bool) -> i64 { +/// `\nonfrenchspacing`); every other character is 1000. Explicit +/// `\sfcode` assignments in `space_factor_codes` override the defaults, and a +/// zero code leaves the running factor unchanged. +fn space_factor_after( + word: &str, + previous: i64, + frenchspacing: bool, + codes: &[(char, i64)], +) -> i64 { if frenchspacing { return 1000; } - match word.chars().last() { - Some('.') | Some('?') | Some('!') => 3000, - Some(':') => 2000, - Some(';') => 1500, - Some(',') => 1250, + let Some(last) = word.chars().last() else { + return previous; + }; + if let Some((_, code)) = codes.iter().rev().find(|(character, _)| *character == last) { + return if *code == 0 { previous } else { *code }; + } + match last { + '.' | '?' | '!' => 3000, + ':' => 2000, + ';' => 1500, + ',' => 1250, _ => 1000, } } @@ -1524,6 +1547,45 @@ mod tests { assert_eq!(shrink, font.shrink() * 1000 / 3000); } + #[test] + fn explicit_space_factor_code_overrides_sentence_spacing() { + let font = crate::cmr10::Cmr10Metrics::Roman; + let glue_width = |style: &ParagraphStyle| { + text_items_with_font("alpha. beta", style, &font) + .iter() + .find_map(|item| match item { + HorizontalItem::Glue { width, .. } => Some(*width), + _ => None, + }) + .expect("interword glue") + }; + let default = glue_width(&ParagraphStyle::default()); + let style = ParagraphStyle { + space_factor_codes: vec![('.', 1000)], + ..ParagraphStyle::default() + }; + assert_eq!(glue_width(&style), font.space()); + assert!(glue_width(&style) < default); + } + + #[test] + fn zero_space_factor_code_keeps_the_previous_factor() { + let font = crate::cmr10::Cmr10Metrics::Roman; + let style = ParagraphStyle { + space_factor_codes: vec![('.', 0)], + ..ParagraphStyle::default() + }; + let width = text_items_with_font("alpha. beta", &style, &font) + .iter() + .find_map(|item| match item { + HorizontalItem::Glue { width, .. } => Some(*width), + _ => None, + }) + .expect("interword glue"); + // "alpha" leaves the factor at 1000, and a zero `\sfcode` keeps it. + assert_eq!(width, font.space()); + } + #[test] fn baselines_use_baselineskip_then_lineskip() { let font = crate::cmr10::Cmr10Metrics::new(); diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 5257753..c73e119 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -363,6 +363,18 @@ fn sentence_spacing_matches_pdftex_at_150pt() { assert_lines_match("sentence spacing 150pt", &ours, &reference); } +#[test] +fn explicit_sfcode_matches_pdftex() { + let width = 150; + let text = "alpha. beta gamma, delta; epsilon: zeta eta theta iota kappa lambda mu"; + // `\sfcode`.=1000` makes the period behave like an ordinary character for + // the following interword glue, so the sentence space shrinks. + let prefix = "\\sfcode`.=1000\\relax "; + compare_fixture_with(text, width, prefix, |style| { + style.space_factor_codes = vec![('.', 1000)]; + }); +} + #[test] fn paragraph_breaks_match_pdftex_at_150pt() { compare_fixture(WORDS, 150); diff --git a/crates/texrra-tex-core/tests/route_d.rs b/crates/texrra-tex-core/tests/route_d.rs index 9141e8e..3184d30 100755 --- a/crates/texrra-tex-core/tests/route_d.rs +++ b/crates/texrra-tex-core/tests/route_d.rs @@ -23,6 +23,7 @@ fn body_style() -> ParagraphStyle { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, @@ -189,6 +190,7 @@ fn route_d_page_matches_pdftex_raster_geometry() { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, @@ -364,6 +366,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, @@ -665,6 +668,7 @@ fn route_d_multiline_bands_track_pdftex() { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index a6f8c0c..b1ac233 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -59,7 +59,7 @@ Known gaps, in dependency order: `\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip` with or without `fil`, default `\sfcode` sentence spacing, `\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline - glue), but not yet custom `\sfcode` overrides, generic `fil`/`fill` glue + glue), custom `\sfcode` overrides, but not yet generic `fil`/`fill` glue orders or `\prevgraf`; 2. the default builder is still the scrolling builder with fraction policies, now with line-level paragraph splits; `page::PageBuilder` @@ -215,8 +215,8 @@ not fit is split at line boundaries: the next fragment continues on the next page without a `\parskip`, and a single unsplittable line may overflow at the top of a page (see `Paragraph::split_at`). -Still open: generic `fil`/`fill` glue orders, custom `\sfcode` overrides, -`\prevgraf`, explicit `\vskip` classes (`\smallskip` and friends), +Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit +`\vskip` classes (`\smallskip` and friends), double/final hyphen demerit oracle fixtures, and more width fixtures. ### P2 — Vertical list, page builder, `\output` (L2) diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 1460c0a..1518204 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -109,7 +109,7 @@ and justification. | Milestone | Content | Acceptance | | --- | --- | --- | | M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | -| 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, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 100-240pt plus register, geometry and vertical-glue fixtures; custom `\sfcode`, generic fil glue and `\prevgraf` next | +| 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, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 100-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next | | 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, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; interpreted `\output` next | | 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; no booktabs/longtable parity yet | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet | @@ -129,7 +129,9 @@ and justification. line is justified. Sentence spacing follows TeX's default `\sfcode` values: interword glue stretch is multiplied by the space factor, shrink is divided by it, `\fontdimen7` is added from factor 2000, and `\frenchspacing` - disables the effect. `\looseness` shifts the paragraph by whole lines when + disables the effect. `ParagraphStyle::space_factor_codes` carries explicit + `\sfcode` assignments, which replace the built-in table for that character; + a zero code leaves the running factor unchanged, as in TeX. `\looseness` shifts the paragraph by whole lines when the requested count lies between one and nine lines away from the natural count (the adjustment is reverted when no feasible layout exists). Interline glue follows TeX: each baseline advances by `\baselineskip` when @@ -139,8 +141,8 @@ and justification. boundaries (`Paragraph::split_at`): the fragment keeps its baseline grid on the next page, `\parskip` is not charged inside the paragraph, and only a single unsplittable line is allowed to overflow at the top of a page. - Remaining gaps are custom `\sfcode` overrides, generic `fil`/`fill` glue - orders outside `\parfillskip`, and `\prevgraf`. + Remaining gaps are generic `fil`/`fill` glue orders outside + `\parfillskip` and `\prevgraf`. The pdfLaTeX oracle pins the 100-240pt measure matrix plus `\hangindent`, `\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no @@ -280,7 +282,7 @@ for a later overlaid slash. | Milestone | State | Notes | | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | -| M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing (`\sfcode`/`\frenchspacing`), `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 100-240pt plus register, geometry and vertical-glue fixtures | +| M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing with default and custom `\sfcode`/`\frenchspacing`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 100-240pt plus register, geometry and vertical-glue fixtures | | M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for single-item documents, while floats, insertions and incremental replay still use the scrolling path; interpreted `\output` absent | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping | @@ -346,7 +348,7 @@ The staged program that closes these milestones is described in Route D currently covers M0-M4/M6 as a working subset. The remaining milestones are deliberately open rather than approximated: -- **M1**: custom `\sfcode` overrides, generic `fil`/`fill` glue orders and +- **M1**: generic `fil`/`fill` glue orders and `\prevgraf` are still open; the tolerance, penalty and demerit registers, `\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` diff --git a/src/route_d.rs b/src/route_d.rs index 0c193a4..27d5388 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -397,6 +397,7 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document { par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, + space_factor_codes: Vec::new(), baselineskip: 12 * 65536, lineskip: 65536, lineskiplimit: 0,