Model TeX tolerance and hyphen penalty registers
This commit is contained in:
1 parent
4fbc43f5ff
commit
3725cca9d7
6 files changed
+148
-23
No files matched your search
@@ -35,6 +35,22 @@ pub enum HorizontalItem {
|
||||
},
|
||||
}
|
||||
|
||||
fn default_pretolerance() -> i64 {
|
||||
100
|
||||
}
|
||||
|
||||
fn default_tolerance() -> i64 {
|
||||
200
|
||||
}
|
||||
|
||||
fn default_hyphen_penalty() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
fn default_ex_hyphen_penalty() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ParagraphStyle {
|
||||
pub line_width: i64,
|
||||
@@ -52,6 +68,21 @@ pub struct ParagraphStyle {
|
||||
/// (`\emergencystretch`).
|
||||
#[serde(default)]
|
||||
pub emergencystretch: i64,
|
||||
/// Badness bound for the first pass, which never hyphenates
|
||||
/// (`\pretolerance`).
|
||||
#[serde(default = "default_pretolerance")]
|
||||
pub pretolerance: i64,
|
||||
/// Badness bound for the second pass (`\tolerance`).
|
||||
#[serde(default = "default_tolerance")]
|
||||
pub tolerance: i64,
|
||||
/// Demerits charged when a line breaks at a hyphenation point
|
||||
/// (`\hyphenpenalty`); values of 10000 or more disable hyphenation.
|
||||
#[serde(default = "default_hyphen_penalty")]
|
||||
pub hyphen_penalty: i64,
|
||||
/// Demerits charged when a line breaks after an explicit hyphen
|
||||
/// (`\exhyphenpenalty`).
|
||||
#[serde(default = "default_ex_hyphen_penalty")]
|
||||
pub ex_hyphen_penalty: i64,
|
||||
pub line_height: i64,
|
||||
pub char_width: i64,
|
||||
pub space_width: i64,
|
||||
@@ -69,6 +100,10 @@ impl Default for ParagraphStyle {
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: 12,
|
||||
char_width: 10,
|
||||
space_width: 4,
|
||||
@@ -198,17 +233,18 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
previous: usize,
|
||||
previous_fitness: usize,
|
||||
}
|
||||
const PRETOLERANCE: i64 = 100;
|
||||
const TOLERANCE: i64 = 200;
|
||||
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.
|
||||
// With zero emergencystretch TeX gives up and falls back to a first-fit
|
||||
// scan, which is what produces the familiar overfull boxes.
|
||||
let passes = if style.emergencystretch > 0 { 3 } else { 2 };
|
||||
for pass in 0..passes {
|
||||
let limit = match pass {
|
||||
0 => PRETOLERANCE,
|
||||
1 => TOLERANCE,
|
||||
0 => style.pretolerance,
|
||||
1 => style.tolerance,
|
||||
_ => 10_000,
|
||||
};
|
||||
let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 };
|
||||
@@ -221,7 +257,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
for end_index in 1..count {
|
||||
let end = breakpoints[end_index];
|
||||
let is_last = end == items.len();
|
||||
if pass == 0 && matches!(items[end - 1], HorizontalItem::Discretionary { .. }) {
|
||||
let hyphen_break = matches!(items[end - 1], HorizontalItem::Discretionary { .. });
|
||||
if hyphen_break && (pass == 0 || style.hyphen_penalty >= 10_000) {
|
||||
continue;
|
||||
}
|
||||
for start_index in 0..end_index {
|
||||
@@ -272,6 +309,18 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
}
|
||||
if is_last {
|
||||
trailing_penalty = 0;
|
||||
} else if hyphen_break {
|
||||
// TeX charges \exhyphenpenalty after an explicit hyphen
|
||||
// and \hyphenpenalty at an inserted hyphenation point.
|
||||
trailing_penalty = if end >= 2
|
||||
&& matches!(
|
||||
&items[end - 2],
|
||||
HorizontalItem::Box(box_item) if box_item.character == Some('-')
|
||||
) {
|
||||
style.ex_hyphen_penalty
|
||||
} else {
|
||||
style.hyphen_penalty
|
||||
};
|
||||
}
|
||||
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
|
||||
- if start_index == 0 {
|
||||
@@ -384,6 +433,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
if style.hyphen_penalty >= 10_000
|
||||
&& matches!(items[end - 1], HorizontalItem::Discretionary { .. })
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut natural = 0_i64;
|
||||
let mut stretch = 0_i64;
|
||||
let mut shrink = 0_i64;
|
||||
@@ -443,11 +497,18 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
} else {
|
||||
10_000
|
||||
};
|
||||
if badness <= TOLERANCE {
|
||||
if badness <= style.tolerance {
|
||||
feasible = Some(end_index);
|
||||
}
|
||||
}
|
||||
let chosen = feasible.or(overflow).unwrap_or(count - 1);
|
||||
// When hyphenation is forbidden TeX's fallback keeps filling to
|
||||
// the first break at or past the measure instead of stopping at a
|
||||
// loose-but-feasible line.
|
||||
let chosen = if style.hyphen_penalty >= 10_000 {
|
||||
overflow.or(feasible).unwrap_or(count - 1)
|
||||
} else {
|
||||
feasible.or(overflow).unwrap_or(count - 1)
|
||||
};
|
||||
greedy.push((breakpoints[start_index], breakpoints[chosen]));
|
||||
start_index = chosen;
|
||||
}
|
||||
|
||||
@@ -131,10 +131,14 @@ fn parse_bbox(xhtml: &str) -> Vec<Line> {
|
||||
lines
|
||||
}
|
||||
|
||||
/// Lay out one paragraph with route-D and return its per-line words.
|
||||
fn route_d_lines(text: &str, width_pt: f64) -> Vec<Line> {
|
||||
/// Lay out a paragraph after applying paragraph-register overrides.
|
||||
fn route_d_lines_with(
|
||||
text: &str,
|
||||
width_pt: f64,
|
||||
configure: impl FnOnce(&mut ParagraphStyle),
|
||||
) -> Vec<Line> {
|
||||
let width = (width_pt * PT as f64).round() as i64;
|
||||
let style = ParagraphStyle {
|
||||
let mut style = ParagraphStyle {
|
||||
line_width: width,
|
||||
left_skip: 0,
|
||||
right_skip: 0,
|
||||
@@ -144,6 +148,7 @@ fn route_d_lines(text: &str, width_pt: f64) -> Vec<Line> {
|
||||
line_height: 12 * PT,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
configure(&mut style);
|
||||
let unit = Unit::paragraph_with_style(0, text, style);
|
||||
let paragraph = match unit.items.first() {
|
||||
Some(VerticalItem::Paragraph(paragraph)) => paragraph,
|
||||
@@ -229,12 +234,16 @@ fn assert_lines_match(label: &str, ours: &[Line], reference: &[Line]) {
|
||||
}
|
||||
|
||||
fn paragraph_fixture(text: &str, width_pt: u32) -> String {
|
||||
paragraph_fixture_with(text, width_pt, "")
|
||||
}
|
||||
|
||||
fn paragraph_fixture_with(text: &str, width_pt: u32, prefix: &str) -> String {
|
||||
format!(
|
||||
"\\documentclass[10pt]{{article}}\n\
|
||||
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
|
||||
\\pagestyle{{empty}}\n\
|
||||
\\begin{{document}}\n\
|
||||
\\hsize={width_pt}pt \\parindent=0pt \\noindent {text}\\par\n\
|
||||
\\hsize={width_pt}pt \\parindent=0pt {prefix}\\noindent {text}\\par\n\
|
||||
\\end{{document}}\n"
|
||||
)
|
||||
}
|
||||
@@ -242,12 +251,39 @@ fn paragraph_fixture(text: &str, width_pt: u32) -> String {
|
||||
const WORDS: &str = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
|
||||
|
||||
fn compare_fixture(text: &str, width_pt: u32) {
|
||||
let Some(reference) = pdftex_lines(¶graph_fixture(text, width_pt)) else {
|
||||
compare_fixture_with(text, width_pt, "", |_| {});
|
||||
}
|
||||
|
||||
fn compare_fixture_with(
|
||||
text: &str,
|
||||
width_pt: u32,
|
||||
tex_prefix: &str,
|
||||
configure: impl FnOnce(&mut ParagraphStyle),
|
||||
) {
|
||||
let Some(reference) = pdftex_lines(¶graph_fixture_with(text, width_pt, tex_prefix)) else {
|
||||
eprintln!("skipping: pdflatex/pdftotext are not installed");
|
||||
return;
|
||||
};
|
||||
let ours = route_d_lines(text, f64::from(width_pt));
|
||||
assert_lines_match(&format!("{width_pt}pt"), &ours, &reference);
|
||||
let ours = route_d_lines_with(text, f64::from(width_pt), configure);
|
||||
assert_lines_match(&format!("{width_pt}pt {tex_prefix}"), &ours, &reference);
|
||||
}
|
||||
|
||||
/// `\pretolerance` lets pass 0 accept very loose lines and stops the breaker
|
||||
/// before hyphenation is enabled.
|
||||
#[test]
|
||||
fn pretolerance_skips_hyphenation_like_tex() {
|
||||
compare_fixture_with(WORDS, 120, "\\pretolerance=10000 ", |style| {
|
||||
style.pretolerance = 10_000;
|
||||
});
|
||||
}
|
||||
|
||||
/// `\hyphenpenalty=10000` makes hyphenation illegal, so the final pass keeps
|
||||
/// overfull lines instead.
|
||||
#[test]
|
||||
fn hyphen_penalty_inhibits_hyphenation() {
|
||||
compare_fixture_with(WORDS, 120, "\\hyphenpenalty=10000 ", |style| {
|
||||
style.hyphen_penalty = 10_000;
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,6 +17,10 @@ fn body_style() -> ParagraphStyle {
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: font.width('x'),
|
||||
space_width: font.space(),
|
||||
@@ -154,6 +158,10 @@ fn route_d_page_matches_pdftex_raster_geometry() {
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -302,6 +310,10 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -580,6 +592,10 @@ fn route_d_multiline_bands_track_pdftex() {
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
|
||||
@@ -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`). 286 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 288 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
@@ -166,7 +166,9 @@ nominal stretch while clamping shrink at the declared limit, and falls back to
|
||||
the longest prefix within `\tolerance` or the first overflowing prefix. The
|
||||
oracle compares 100, 120, 150, 180, 200 and 240pt and all six match pdfLaTeX
|
||||
word for word within 0.05pt; the narrow measures exercise hyphenated and
|
||||
overfull breaks.
|
||||
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`,
|
||||
|
||||
+13
-7
@@ -71,13 +71,18 @@ the fallback here mirrors that choice by taking the longest prefix within
|
||||
tolerance and otherwise the first prefix that overflows. Justification
|
||||
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.
|
||||
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.
|
||||
|
||||
`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
|
||||
horizontally. The narrow measures exercise hyphenated and overfull breaks,
|
||||
150pt the final-pass overfull box, and 180-240pt ordinary tolerance
|
||||
solutions. `route_d_multiline_bands_track_pdftex` rasterizes the same
|
||||
solutions. Two further fixtures pin register behaviour at 120pt:
|
||||
`\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000`
|
||||
inhibits it, leaving the overfull first-fit lines TeX produces. `route_d_multiline_bands_track_pdftex` rasterizes the same
|
||||
paragraph in both engines and compares ink bands, covering baseline placement
|
||||
and justification.
|
||||
|
||||
@@ -96,7 +101,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, pdfLaTeX oracle matrix 100-240pt; explicit tolerance registers, `\looseness`, `\parshape` and more fixtures 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, pdfLaTeX oracle matrix 100-240pt plus register fixtures; `\looseness`, `\parshape` and more fixtures 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; interpreted `\output`, float pages 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 |
|
||||
@@ -108,10 +113,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. Remaining
|
||||
gaps are explicit `\tolerance`/`\pretolerance` overrides (the defaults and
|
||||
`\emergencystretch` are modelled), `\hyphenpenalty`/`\exhyphenpenalty`,
|
||||
`\looseness`, `\parshape` and `\parfillskip` variants.
|
||||
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.
|
||||
|
||||
The pdfLaTeX oracle pins six measures (100-240pt) and all match; no oracle
|
||||
fixture is ignored.
|
||||
|
||||
@@ -335,6 +335,10 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
|
||||
right_skip: 0,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
pretolerance: 100,
|
||||
tolerance: 200,
|
||||
hyphen_penalty: 50,
|
||||
ex_hyphen_penalty: 50,
|
||||
line_height: paragraph.line_height * SCALE,
|
||||
char_width: 10 * SCALE,
|
||||
space_width: 4 * SCALE,
|
||||
|
||||
Reference in new issue
Block a user