Honour explicit sfcode assignments

This commit is contained in:
gloamxun committed 2026-10-23 02:29:40 +08:00
1 parent b5ec36ae2a
commit 4acccaee86
7 files changed
+99 -18

No files matched your search

+1 -1
View File
@@ -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 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 boundaries when they cross a page, and the pdfLaTeX oracle covers the
100-240pt measure matrix plus register, `\hangindent`/`\parshape`, 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 insertion material is split at item boundaries, with the tail held over to the
next page. The production v1 engine remains 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, default until the new core reaches layout parity. See `docs/TEX_CORE.md`. The complete phased plan (P0 oracle harness, TeX-exact paragraphs,
+70 -8
View File
@@ -98,6 +98,10 @@ pub struct ParagraphStyle {
/// punctuation adds no sentence spacing. /// punctuation adds no sentence spacing.
#[serde(default)] #[serde(default)]
pub frenchspacing: bool, 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). /// TeX `\baselineskip` (12pt for 10pt text).
#[serde(default = "default_baselineskip")] #[serde(default = "default_baselineskip")]
pub baselineskip: i64, pub baselineskip: i64,
@@ -228,6 +232,7 @@ impl Default for ParagraphStyle {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536, baselineskip: 12 * 65_536,
lineskip: 65_536, lineskip: 65_536,
lineskiplimit: 0, 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 { .. })) { while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.pop(); items.pop();
@@ -1031,16 +1041,29 @@ pub fn text_items_with_font(
} }
/// TeX's default `\sfcode` values for sentence punctuation (`plain.tex`'s /// TeX's default `\sfcode` values for sentence punctuation (`plain.tex`'s
/// `\nonfrenchspacing`); every other character is 1000. /// `\nonfrenchspacing`); every other character is 1000. Explicit
fn space_factor_after(word: &str, frenchspacing: bool) -> i64 { /// `\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 { if frenchspacing {
return 1000; return 1000;
} }
match word.chars().last() { let Some(last) = word.chars().last() else {
Some('.') | Some('?') | Some('!') => 3000, return previous;
Some(':') => 2000, };
Some(';') => 1500, if let Some((_, code)) = codes.iter().rev().find(|(character, _)| *character == last) {
Some(',') => 1250, return if *code == 0 { previous } else { *code };
}
match last {
'.' | '?' | '!' => 3000,
':' => 2000,
';' => 1500,
',' => 1250,
_ => 1000, _ => 1000,
} }
} }
@@ -1524,6 +1547,45 @@ mod tests {
assert_eq!(shrink, font.shrink() * 1000 / 3000); 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] #[test]
fn baselines_use_baselineskip_then_lineskip() { fn baselines_use_baselineskip_then_lineskip() {
let font = crate::cmr10::Cmr10Metrics::new(); let font = crate::cmr10::Cmr10Metrics::new();
+12
View File
@@ -363,6 +363,18 @@ fn sentence_spacing_matches_pdftex_at_150pt() {
assert_lines_match("sentence spacing 150pt", &ours, &reference); 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] #[test]
fn paragraph_breaks_match_pdftex_at_150pt() { fn paragraph_breaks_match_pdftex_at_150pt() {
compare_fixture(WORDS, 150); compare_fixture(WORDS, 150);
+4
View File
@@ -23,6 +23,7 @@ fn body_style() -> ParagraphStyle {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536, baselineskip: 12 * 65_536,
lineskip: 65_536, lineskip: 65_536,
lineskiplimit: 0, lineskiplimit: 0,
@@ -189,6 +190,7 @@ fn route_d_page_matches_pdftex_raster_geometry() {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536, baselineskip: 12 * 65_536,
lineskip: 65_536, lineskip: 65_536,
lineskiplimit: 0, lineskiplimit: 0,
@@ -364,6 +366,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536, baselineskip: 12 * 65_536,
lineskip: 65_536, lineskip: 65_536,
lineskiplimit: 0, lineskiplimit: 0,
@@ -665,6 +668,7 @@ fn route_d_multiline_bands_track_pdftex() {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536, baselineskip: 12 * 65_536,
lineskip: 65_536, lineskip: 65_536,
lineskiplimit: 0, lineskiplimit: 0,
+3 -3
View File
@@ -59,7 +59,7 @@ Known gaps, in dependency order:
`\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip` `\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip`
with or without `fil`, default `\sfcode` sentence spacing, with or without `fil`, default `\sfcode` sentence spacing,
`\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline `\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`; orders or `\prevgraf`;
2. the default builder is still the scrolling builder with fraction 2. the default builder is still the scrolling builder with fraction
policies, now with line-level paragraph splits; `page::PageBuilder` 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 page without a `\parskip`, and a single unsplittable line may overflow at the
top of a page (see `Paragraph::split_at`). top of a page (see `Paragraph::split_at`).
Still open: generic `fil`/`fill` glue orders, custom `\sfcode` overrides, Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit
`\prevgraf`, explicit `\vskip` classes (`\smallskip` and friends), `\vskip` classes (`\smallskip` and friends),
double/final hyphen demerit oracle fixtures, and more width fixtures. double/final hyphen demerit oracle fixtures, and more width fixtures.
### P2 — Vertical list, page builder, `\output` (L2) ### P2 — Vertical list, page builder, `\output` (L2)
+8 -6
View File
@@ -109,7 +109,7 @@ and justification.
| Milestone | Content | Acceptance | | Milestone | Content | Acceptance |
| --- | --- | --- | | --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | 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 | | 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 | | 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 | | 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: line is justified. Sentence spacing follows TeX's default `\sfcode` values:
interword glue stretch is multiplied by the space factor, shrink is divided interword glue stretch is multiplied by the space factor, shrink is divided
by it, `\fontdimen7` is added from factor 2000, and `\frenchspacing` 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 the requested count lies between one and nine lines away from the natural
count (the adjustment is reverted when no feasible layout exists). count (the adjustment is reverted when no feasible layout exists).
Interline glue follows TeX: each baseline advances by `\baselineskip` when 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 boundaries (`Paragraph::split_at`): the fragment keeps its baseline grid on
the next page, `\parskip` is not charged inside the paragraph, and only a 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. single unsplittable line is allowed to overflow at the top of a page.
Remaining gaps are custom `\sfcode` overrides, generic `fil`/`fill` glue Remaining gaps are generic `fil`/`fill` glue orders outside
orders outside `\parfillskip`, and `\prevgraf`. `\parfillskip` and `\prevgraf`.
The pdfLaTeX oracle pins the 100-240pt measure matrix plus `\hangindent`, The pdfLaTeX oracle pins the 100-240pt measure matrix plus `\hangindent`,
`\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no `\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no
@@ -280,7 +282,7 @@ for a later overlaid slash.
| Milestone | State | Notes | | Milestone | State | Notes |
| --- | --- | --- | | --- | --- | --- |
| M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | 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 | | 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 | | 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 | | 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 Route D currently covers M0-M4/M6 as a working subset. The remaining milestones are
deliberately open rather than approximated: 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, `\prevgraf` are still open; the tolerance, penalty and demerit registers,
`\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with `\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with
or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip`
+1
View File
@@ -397,6 +397,7 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
par_fillskip_stretch: 0, par_fillskip_stretch: 0,
par_fillskip_fil: true, par_fillskip_fil: true,
frenchspacing: false, frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65536, baselineskip: 12 * 65536,
lineskip: 65536, lineskip: 65536,
lineskiplimit: 0, lineskiplimit: 0,