Model TeX demerit registers and hyphenation exceptions
This commit is contained in:
1 parent
3725cca9d7
commit
24a96d1c7c
5 files changed
+153
-34
No files matched your search
@@ -51,6 +51,22 @@ fn default_ex_hyphen_penalty() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
fn default_double_hyphen_demerits() -> i64 {
|
||||
10_000
|
||||
}
|
||||
|
||||
fn default_final_hyphen_demerits() -> i64 {
|
||||
5_000
|
||||
}
|
||||
|
||||
fn default_line_penalty() -> i64 {
|
||||
10
|
||||
}
|
||||
|
||||
fn default_adj_demerits() -> i64 {
|
||||
10_000
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ParagraphStyle {
|
||||
pub line_width: i64,
|
||||
@@ -83,6 +99,24 @@ pub struct ParagraphStyle {
|
||||
/// (`\exhyphenpenalty`).
|
||||
#[serde(default = "default_ex_hyphen_penalty")]
|
||||
pub ex_hyphen_penalty: i64,
|
||||
/// Additional demerits when two consecutive lines are hyphenated
|
||||
/// (`\doublehyphendemerits`).
|
||||
#[serde(default = "default_double_hyphen_demerits")]
|
||||
pub double_hyphen_demerits: i64,
|
||||
/// Additional demerits when the second-to-last line is hyphenated
|
||||
/// (`\finalhyphendemerits`).
|
||||
#[serde(default = "default_final_hyphen_demerits")]
|
||||
pub final_hyphen_demerits: i64,
|
||||
/// Base demerits charged for every line (`\linepenalty`).
|
||||
#[serde(default = "default_line_penalty")]
|
||||
pub line_penalty: i64,
|
||||
/// Extra demerits when adjacent lines' fitness classes differ by more
|
||||
/// than one (`\adjdemerits`).
|
||||
#[serde(default = "default_adj_demerits")]
|
||||
pub adj_demerits: i64,
|
||||
/// Hyphenation exceptions in TeX syntax (`\hyphenation{hy-phen-a-tion}`).
|
||||
#[serde(default)]
|
||||
pub hyphenation_exceptions: Vec<String>,
|
||||
pub line_height: i64,
|
||||
pub char_width: i64,
|
||||
pub space_width: i64,
|
||||
@@ -104,6 +138,11 @@ impl Default for ParagraphStyle {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: 12,
|
||||
char_width: 10,
|
||||
space_width: 4,
|
||||
@@ -231,10 +270,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
struct Candidate {
|
||||
cost: i64,
|
||||
previous: usize,
|
||||
previous_fitness: usize,
|
||||
previous_state: usize,
|
||||
}
|
||||
const LINE_PENALTY: i64 = 10;
|
||||
const ADJ_DEMERITS: i64 = 10_000;
|
||||
let count = breakpoints.len();
|
||||
let mut solution: Option<Vec<(usize, usize)>> = None;
|
||||
// TeX's emergency pass only exists when \emergencystretch is positive.
|
||||
@@ -248,11 +285,12 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
_ => 10_000,
|
||||
};
|
||||
let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 };
|
||||
let mut best: Vec<[Option<Candidate>; 4]> = vec![[None; 4]; count];
|
||||
best[0][1] = Some(Candidate {
|
||||
// State = fitness * 2 + whether the previous line was hyphenated.
|
||||
let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count];
|
||||
best[0][2] = Some(Candidate {
|
||||
cost: 0,
|
||||
previous: 0,
|
||||
previous_fitness: 1,
|
||||
previous_state: 2,
|
||||
});
|
||||
for end_index in 1..count {
|
||||
let end = breakpoints[end_index];
|
||||
@@ -369,43 +407,53 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
} else {
|
||||
fitness
|
||||
};
|
||||
for previous_fitness in 0..4 {
|
||||
let Some(node) = best[start_index][previous_fitness] else {
|
||||
let state = fitness * 2 + usize::from(hyphen_break);
|
||||
for previous_state in 0..8 {
|
||||
let Some(node) = best[start_index][previous_state] else {
|
||||
continue;
|
||||
};
|
||||
let mut demerits = (LINE_PENALTY + badness).pow(2);
|
||||
let previous_fitness = previous_state / 2;
|
||||
let mut demerits = (style.line_penalty + badness).pow(2);
|
||||
if trailing_penalty >= 0 {
|
||||
demerits = demerits.saturating_add(trailing_penalty.pow(2));
|
||||
} else {
|
||||
demerits = demerits.saturating_sub(trailing_penalty.pow(2));
|
||||
}
|
||||
if (fitness as i64 - previous_fitness as i64).abs() > 1 {
|
||||
demerits = demerits.saturating_add(ADJ_DEMERITS);
|
||||
demerits = demerits.saturating_add(style.adj_demerits);
|
||||
}
|
||||
if hyphen_break {
|
||||
if previous_state % 2 == 1 {
|
||||
demerits = demerits.saturating_add(style.double_hyphen_demerits);
|
||||
}
|
||||
if end_index + 1 == count - 1 {
|
||||
demerits = demerits.saturating_add(style.final_hyphen_demerits);
|
||||
}
|
||||
}
|
||||
let cost = node.cost.saturating_add(demerits);
|
||||
let entry = &mut best[end_index][fitness];
|
||||
let entry = &mut best[end_index][state];
|
||||
if entry.map_or(true, |current| cost < current.cost) {
|
||||
*entry = Some(Candidate {
|
||||
cost,
|
||||
previous: start_index,
|
||||
previous_fitness,
|
||||
previous_state,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let final_index = count - 1;
|
||||
let winner = (0..4)
|
||||
.filter_map(|fitness| best[final_index][fitness].map(|node| (node.cost, fitness)))
|
||||
let winner = (0..8)
|
||||
.filter_map(|state| best[final_index][state].map(|node| (node.cost, state)))
|
||||
.min();
|
||||
if let Some((_, mut fitness)) = winner {
|
||||
if let Some((_, mut state)) = winner {
|
||||
let mut ranges = Vec::new();
|
||||
let mut end_index = final_index;
|
||||
while end_index > 0 {
|
||||
let node = best[end_index][fitness].expect("chosen line");
|
||||
let node = best[end_index][state].expect("chosen line");
|
||||
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
|
||||
end_index = node.previous;
|
||||
fitness = node.previous_fitness;
|
||||
state = node.previous_state;
|
||||
}
|
||||
solution = Some(ranges);
|
||||
break;
|
||||
@@ -668,13 +716,18 @@ const HYPHENATION_EXCEPTIONS: &str = include_str!("../assets/hyph-en-us-exceptio
|
||||
/// Convert text using TFM character widths and fontdimen glue parameters.
|
||||
pub fn text_items_with_font(
|
||||
text: &str,
|
||||
_style: &ParagraphStyle,
|
||||
style: &ParagraphStyle,
|
||||
font: &crate::cmr10::Cmr10Metrics,
|
||||
) -> Vec<HorizontalItem> {
|
||||
let mut items = Vec::new();
|
||||
let mut hyphenator = hyphenate::Hyphenator::default();
|
||||
hyphenator.load_patterns(HYPHENATION_PATTERNS);
|
||||
hyphenator.insert_exceptions(HYPHENATION_EXCEPTIONS);
|
||||
let mut exceptions = String::from(HYPHENATION_EXCEPTIONS);
|
||||
for exception in &style.hyphenation_exceptions {
|
||||
exceptions.push('\n');
|
||||
exceptions.push_str(exception);
|
||||
}
|
||||
hyphenator.insert_exceptions(&exceptions);
|
||||
let caser = hyphenate::AsciiLowerCaser::default();
|
||||
// TeX's text fonts turn runs of hyphens into en/em dashes. cmr10's TFM
|
||||
// does not carry these ligatures, so apply the same mapping before
|
||||
@@ -1096,4 +1149,30 @@ mod tests {
|
||||
fn empty_paragraph_has_no_lines() {
|
||||
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyphenation_exceptions_add_breakpoints() {
|
||||
let font = crate::cmr10::Cmr10Metrics::default();
|
||||
let style = ParagraphStyle {
|
||||
line_width: 20 * 65_536,
|
||||
line_height: 12 * 65_536,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let breaks = |style: &ParagraphStyle| {
|
||||
text_items_with_font("zzzzzz", style, &font)
|
||||
.iter()
|
||||
.filter(|item| matches!(item, HorizontalItem::Discretionary { .. }))
|
||||
.count()
|
||||
};
|
||||
assert_eq!(breaks(&style), 0, "no TeX pattern breaks this word");
|
||||
let with_exception = ParagraphStyle {
|
||||
hyphenation_exceptions: vec!["zzz-zzz".to_string()],
|
||||
..style
|
||||
};
|
||||
assert_eq!(
|
||||
breaks(&with_exception),
|
||||
1,
|
||||
"exceptions insert a discretionary point"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,11 @@ fn body_style() -> ParagraphStyle {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: 12 * 65_536,
|
||||
char_width: font.width('x'),
|
||||
space_width: font.space(),
|
||||
@@ -162,6 +167,11 @@ fn route_d_page_matches_pdftex_raster_geometry() {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -314,6 +324,11 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -596,6 +611,11 @@ fn route_d_multiline_bands_track_pdftex() {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
|
||||
+16
-6
@@ -48,13 +48,16 @@ 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`). 288 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 289 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
|
||||
1. paragraph breaking reproduces TeX's passes and demerits, but not yet
|
||||
`\parshape`, `\looseness`, spacefactor or explicit `\tolerance` overrides;
|
||||
1. paragraph breaking reproduces TeX's passes and demerits (including
|
||||
`\adjdemerits`, `\doublehyphendemerits`, `\finalhyphendemerits`,
|
||||
`\hyphenpenalty`, `\exhyphenpenalty` and `\hyphenation` exceptions), but
|
||||
not yet `\parshape`, `\looseness`, `\hangindent`, spacefactor or
|
||||
`\parfillskip`/fil glue orders;
|
||||
2. the page builder is a scrolling builder with fraction policies, not a TeX
|
||||
page builder with badness and an interpreted `\output`;
|
||||
3. `\insert` classes are data structures, not TeX registers and an output
|
||||
@@ -170,9 +173,16 @@ overfull breaks. Register fixtures pin `\pretolerance=10000` (pass 0 stops
|
||||
before hyphenation) and `\hyphenpenalty=10000` (hyphenation illegal, first-fit
|
||||
overfull lines).
|
||||
|
||||
Still open: explicit `\tolerance`/`\pretolerance` overrides, flagged
|
||||
(hyphenated) demerits, `\parfillskip` variants, `\hangindent`/`\parshape`,
|
||||
spacefactor, and more width fixtures.
|
||||
Flagged demerits are now modelled too: the DP state records whether a line
|
||||
ended in a discretionary break, so `\adjdemerits`, `\doublehyphendemerits`
|
||||
and `\finalhyphendemerits` all affect the chosen solution, and
|
||||
`\hyphenation` exceptions are inserted into the pattern trie (unit-tested by
|
||||
counting the discretionary points they add).
|
||||
|
||||
Still open: `\parfillskip`/fil glue orders, `\hangindent`/`\parshape`/
|
||||
`\looseness`, spacefactor/`\sfcode`, vertical-list skips
|
||||
(`\baselineskip`, `\lineskip`, `\parskip`), double/final hyphen demerit
|
||||
oracle fixtures, and more width fixtures.
|
||||
|
||||
### P2 — Vertical list, page builder, `\output` (L2)
|
||||
|
||||
|
||||
+14
-9
@@ -73,8 +73,10 @@ stretches normal glue past its nominal stretch (badness simply exceeds 100)
|
||||
and clamps shrink at the declared limit, so overfull lines stay overfull
|
||||
exactly as in TeX. The bounds and hyphen demerits are `ParagraphStyle`
|
||||
fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and
|
||||
`\exhyphenpenalty`; `\hyphenpenalty` at 10000 or more disables hyphenation
|
||||
and switches the fallback to a first-fit scan.
|
||||
`\exhyphenpenalty`, `\linepenalty`, `\adjdemerits`,
|
||||
`\doublehyphendemerits`, `\finalhyphendemerits` and `\emergencystretch`,
|
||||
plus document-level `\hyphenation` exceptions; `\hyphenpenalty` at 10000 or
|
||||
more disables hyphenation and switches the fallback to a first-fit scan.
|
||||
|
||||
`tests/oracle.rs` compares a matrix of measures (100, 120, 150, 180, 200 and
|
||||
240pt) against pdfLaTeX: every fixture matches word for word and within 0.05pt
|
||||
@@ -114,10 +116,11 @@ and justification.
|
||||
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
|
||||
italic correction, kern pairs, ligatures), applies TeX Live's en-US
|
||||
hyphenation patterns and runs TeX's tolerance passes with demerits. The
|
||||
tolerance bounds and hyphen penalties are modelled. Remaining gaps are
|
||||
`\looseness`, `\parshape`, `\parfillskip` variants, document-level
|
||||
`\hyphenation` exceptions (the TeX Live exception list is loaded) and the
|
||||
`\adjdemerits`/`\doublehyphendemerits`/`\finalhyphendemerits` registers.
|
||||
tolerance bounds, break penalties and flagged demerits are modelled, and
|
||||
`\hyphenation` exceptions are inserted into the pattern trie. Remaining gaps
|
||||
are `\looseness`, `\parshape`, `\hangindent`, spacefactor/`\sfcode`,
|
||||
`\parfillskip`/fil glue orders, and the vertical-list skips
|
||||
(`\baselineskip`, `\lineskip`, `\parskip`).
|
||||
|
||||
The pdfLaTeX oracle pins six measures (100-240pt) and all match; no oracle
|
||||
fixture is ignored.
|
||||
@@ -289,7 +292,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 179 unit tests plus six route-D integration tests and two oracle fixtures (one ignored). Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 282 tests (179 route-D unit, 6 route-D integration, 2 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), of which one is ignored. v1 remains the live server path.
|
||||
The crate currently has 181 unit tests plus six route-D integration tests and five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 289 tests (181 route-D unit, 6 route-D integration, 5 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
@@ -317,8 +320,10 @@ 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**: explicit `\tolerance`/`\pretolerance` registers, hyphenated-break
|
||||
penalties and more width fixtures are still open.
|
||||
- **M1**: `\parshape`, `\looseness`, `\hangindent`, spacefactor/`\sfcode`,
|
||||
`\parfillskip`/fil glue orders and the vertical-list skips are still open;
|
||||
the tolerance, penalty and demerit registers plus `\hyphenation` exceptions
|
||||
are modelled.
|
||||
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented.
|
||||
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
|
||||
math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `\output` is still Rust code rather than interpreted tokens.
|
||||
|
||||
@@ -339,6 +339,11 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
double_hyphen_demerits: 10_000,
|
||||
final_hyphen_demerits: 5_000,
|
||||
line_penalty: 10,
|
||||
adj_demerits: 10_000,
|
||||
hyphenation_exceptions: Vec::new(),
|
||||
line_height: paragraph.line_height * SCALE,
|
||||
char_width: 10 * SCALE,
|
||||
space_width: 4 * SCALE,
|
||||
|
||||
Reference in new issue
Block a user