Support hang indentation and parshape measures

This commit is contained in:
gloamxun committed 2026-10-23 01:18:19 +08:00
1 parent 24a96d1c7c
commit 8993186005
7 files changed
+269 -88

No files matched your search

+171 -62
View File
@@ -74,6 +74,17 @@ pub struct ParagraphStyle {
pub left_skip: i64, pub left_skip: i64,
/// Right skip reserved at the end of every line (`\rightskip`). /// Right skip reserved at the end of every line (`\rightskip`).
pub right_skip: i64, pub right_skip: i64,
/// Extra indentation for hanging lines (`\hangindent`); negative values
/// indent the right margin instead.
#[serde(default)]
pub hang_indent: i64,
/// First hanging line (`\hangafter`): non-negative N applies from line
/// N+1 on, negative -N applies to the first N lines.
#[serde(default)]
pub hang_after: i32,
/// Explicit `(indent, width)` pairs for `\parshape`.
#[serde(default)]
pub par_shape: Vec<(i64, i64)>,
/// Center each line in the measure instead of justifying it. /// Center each line in the measure instead of justifying it.
#[serde(default)] #[serde(default)]
pub centered: bool, pub centered: bool,
@@ -124,12 +135,61 @@ pub struct ParagraphStyle {
pub space_shrink: i64, pub space_shrink: i64,
} }
impl ParagraphStyle {
/// `(indent, measure)` for a zero-based line number, honouring
/// `\parshape` and `\hangindent`/`\hangafter`.
pub fn line_geometry(&self, line: usize) -> (i64, i64) {
if !self.par_shape.is_empty() {
let (indent, width) = if line < self.par_shape.len() {
self.par_shape[line]
} else {
*self.par_shape.last().expect("parshape")
};
return (indent, width.max(1));
}
if self.hang_indent != 0 {
let hangs = if self.hang_after >= 0 {
line >= self.hang_after as usize
} else {
line < (-self.hang_after) as usize
};
if hangs {
return if self.hang_indent > 0 {
(
self.hang_indent,
(self.line_width - self.hang_indent).max(1),
)
} else {
(0, (self.line_width + self.hang_indent).max(1))
};
}
}
(0, self.line_width)
}
fn par_indent_for(&self, line: usize) -> i64 {
if line == 0 && self.par_shape.is_empty() {
self.par_indent
} else {
0
}
}
fn line_target(&self, line: usize) -> i64 {
let (_, width) = self.line_geometry(line);
(width - self.left_skip - self.right_skip).max(1) - self.par_indent_for(line)
}
}
impl Default for ParagraphStyle { impl Default for ParagraphStyle {
fn default() -> Self { fn default() -> Self {
Self { Self {
line_width: 400, line_width: 400,
left_skip: 0, left_skip: 0,
right_skip: 0, right_skip: 0,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
centered: false, centered: false,
right_aligned: false, right_aligned: false,
par_indent: 0, par_indent: 0,
@@ -177,6 +237,9 @@ pub struct Paragraph {
pub font: ParagraphFont, pub font: ParagraphFont,
#[serde(default)] #[serde(default)]
pub left_skip: i64, pub left_skip: i64,
/// Left offset for each line, from `\hangindent`/`\parshape`.
#[serde(default)]
pub line_indents: Vec<i64>,
#[serde(default)] #[serde(default)]
pub centered: bool, pub centered: bool,
#[serde(default)] #[serde(default)]
@@ -240,6 +303,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
width: 0, width: 0,
font: ParagraphFont::Roman, font: ParagraphFont::Roman,
left_skip: style.left_skip, left_skip: style.left_skip,
line_indents: Vec::new(),
centered: style.centered, centered: style.centered,
right_aligned: style.right_aligned, right_aligned: style.right_aligned,
}; };
@@ -271,6 +335,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
cost: i64, cost: i64,
previous: usize, previous: usize,
previous_state: usize, previous_state: usize,
line: usize,
} }
let count = breakpoints.len(); let count = breakpoints.len();
let mut solution: Option<Vec<(usize, usize)>> = None; let mut solution: Option<Vec<(usize, usize)>> = None;
@@ -286,11 +351,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}; };
let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 }; let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 };
// State = fitness * 2 + whether the previous line was hyphenated. // State = fitness * 2 + whether the previous line was hyphenated.
// A candidate also records its zero-based line number so that
// \parshape and \hangindent can give each line its own measure.
let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count]; let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count];
best[0][2] = Some(Candidate { best[0][2] = Some(Candidate {
cost: 0, cost: 0,
previous: 0, previous: 0,
previous_state: 2, previous_state: 2,
line: 0,
}); });
for end_index in 1..count { for end_index in 1..count {
let end = breakpoints[end_index]; let end = breakpoints[end_index];
@@ -320,8 +388,6 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
stretch: stretch_amount, stretch: stretch_amount,
shrink: shrink_amount, shrink: shrink_amount,
} => { } => {
// A break at glue discards that glue: the line ends
// before it, exactly as TeX's line breaker does.
if start + offset + 1 == end { if start + offset + 1 == end {
continue; continue;
} }
@@ -334,11 +400,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
pre_break_width, pre_break_width,
no_break_width, no_break_width,
} => { } => {
if start + offset + 1 == end { natural += if start + offset + 1 == end {
natural += *pre_break_width; *pre_break_width
} else { } else {
natural += *no_break_width; *no_break_width
} };
} }
} }
} }
@@ -360,58 +426,53 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
style.hyphen_penalty style.hyphen_penalty
}; };
} }
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target {
if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else if natural > target {
if shrink > 0 {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else {
(0.0, 0)
};
// TeX's final line has \parfillskip's infinite stretch.
let badness = if is_last && natural <= target {
0
} else {
badness
};
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
3
};
let fitness = if natural < target && stretch == 0 {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
for previous_state in 0..8 { for previous_state in 0..8 {
let Some(node) = best[start_index][previous_state] else { let Some(node) = best[start_index][previous_state] else {
continue; continue;
}; };
let target = style.line_target(node.line);
let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target {
if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else if natural > target {
if shrink > 0 {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else {
(0.0, 0)
};
// TeX's final line has \parfillskip's infinite stretch.
let badness = if is_last && natural <= target {
0
} else {
badness
};
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
3
};
let fitness = if natural < target && stretch == 0 {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
let previous_fitness = previous_state / 2; let previous_fitness = previous_state / 2;
let mut demerits = (style.line_penalty + badness).pow(2); let mut demerits = (style.line_penalty + badness).pow(2);
if trailing_penalty >= 0 { if trailing_penalty >= 0 {
@@ -431,12 +492,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} }
} }
let cost = node.cost.saturating_add(demerits); let cost = node.cost.saturating_add(demerits);
let line = node.line + 1;
let entry = &mut best[end_index][state]; let entry = &mut best[end_index][state];
if entry.map_or(true, |current| cost < current.cost) { if entry.map_or(true, |current| cost < current.cost) {
*entry = Some(Candidate { *entry = Some(Candidate {
cost, cost,
previous: start_index, previous: start_index,
previous_state, previous_state,
line,
}); });
} }
} }
@@ -467,12 +530,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
let mut greedy = Vec::new(); let mut greedy = Vec::new();
let mut start_index = 0; let mut start_index = 0;
while start_index + 1 < count { while start_index + 1 < count {
let target = (style.line_width - style.left_skip - style.right_skip).max(1) let target = style.line_target(greedy.len());
- if start_index == 0 {
style.par_indent
} else {
0
};
let mut feasible = None; let mut feasible = None;
let mut overflow = None; let mut overflow = None;
for end_index in start_index + 1..count { for end_index in start_index + 1..count {
@@ -605,8 +663,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
// Bake the justification into the line: TeX distributes the // Bake the justification into the line: TeX distributes the
// difference between the natural width and the measure across the // difference between the natural width and the measure across the
// glue, so the shipped line (and therefore the PDF) is flush. // glue, so the shipped line (and therefore the PDF) is flush.
let target = (style.line_width - style.left_skip - style.right_skip).max(1) let target = style.line_target(line_index);
- if line_index == 0 { style.par_indent } else { 0 };
let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64); let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64);
for item in &line { for item in &line {
match item { match item {
@@ -695,12 +752,16 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
max_width = max_width.max(width + italic); max_width = max_width.max(width + italic);
lines.push(line); lines.push(line);
} }
let line_indents: Vec<i64> = (0..lines.len())
.map(|line| style.line_geometry(line).0 + style.par_indent_for(line))
.collect();
Paragraph { Paragraph {
height: lines.len() as i64 * style.line_height, height: lines.len() as i64 * style.line_height,
width: max_width, width: max_width,
lines, lines,
font: ParagraphFont::Roman, font: ParagraphFont::Roman,
left_skip: style.left_skip, left_skip: style.left_skip,
line_indents,
centered: style.centered, centered: style.centered,
right_aligned: style.right_aligned, right_aligned: style.right_aligned,
} }
@@ -1145,6 +1206,54 @@ mod tests {
let full_lines = layout_paragraph(text, &full).lines.len(); let full_lines = layout_paragraph(text, &full).lines.len();
assert!(narrow_lines > full_lines); assert!(narrow_lines > full_lines);
} }
#[test]
fn hang_geometry_applies_after_hang_after() {
let positive = ParagraphStyle {
line_width: 100,
hang_indent: 20,
hang_after: 1,
..ParagraphStyle::default()
};
assert_eq!(positive.line_geometry(0), (0, 100));
assert_eq!(positive.line_geometry(1), (20, 80));
assert_eq!(positive.line_target(1), 80);
let negative = ParagraphStyle {
line_width: 100,
hang_indent: 20,
hang_after: -2,
..ParagraphStyle::default()
};
assert_eq!(negative.line_geometry(0), (20, 80));
assert_eq!(negative.line_geometry(1), (20, 80));
assert_eq!(negative.line_geometry(2), (0, 100));
}
#[test]
fn parshape_overrides_the_measure_and_repeats_the_last_pair() {
let style = ParagraphStyle {
line_width: 400,
par_shape: vec![(0, 100), (20, 80)],
..ParagraphStyle::default()
};
assert_eq!(style.line_geometry(0), (0, 100));
assert_eq!(style.line_geometry(1), (20, 80));
assert_eq!(style.line_geometry(2), (20, 80));
assert_eq!(style.line_target(1), 80);
}
#[test]
fn parshape_offsets_paragraph_lines() {
let style = ParagraphStyle {
line_width: 80,
par_shape: vec![(0, 80), (30, 80)],
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("aa bb cc dd ee ff gg hh ii", &style);
assert_eq!(paragraph.line_count(), 3);
assert_eq!(paragraph.line_indents, vec![0, 30, 30]);
}
#[test] #[test]
fn empty_paragraph_has_no_lines() { fn empty_paragraph_has_no_lines() {
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0); assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
+5 -4
View File
@@ -409,7 +409,8 @@ impl Page {
let lines = paragraph.lines.len().max(1) as i64; let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1); let line_height = (paragraph.height / lines).max(1);
let size = 10 * 65_536; let size = 10 * 65_536;
for line in &paragraph.lines { for (line_index, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0);
let baseline = y + ((line_height as f64) * 0.8) as i64; let baseline = y + ((line_height as f64) * 0.8) as i64;
let natural: i64 = line let natural: i64 = line
.iter() .iter()
@@ -421,11 +422,11 @@ impl Page {
}) })
.sum(); .sum();
let mut x = if paragraph.centered { let mut x = if paragraph.centered {
paragraph.left_skip + ((paragraph.width - natural) / 2).max(0) paragraph.left_skip + indent + ((paragraph.width - natural) / 2).max(0)
} else if paragraph.right_aligned { } else if paragraph.right_aligned {
paragraph.left_skip + (paragraph.width - natural).max(0) paragraph.left_skip + indent + (paragraph.width - natural).max(0)
} else { } else {
paragraph.left_skip paragraph.left_skip + indent
}; };
for item in line { for item in line {
match item { match item {
+51 -4
View File
@@ -27,6 +27,9 @@ struct Word {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
struct Line { struct Line {
words: Vec<Word>, words: Vec<Word>,
/// Absolute x of the line's first word in TeX points (page origin).
#[allow(dead_code)]
start: f64,
} }
fn temp_dir(tag: &str) -> PathBuf { fn temp_dir(tag: &str) -> PathBuf {
@@ -112,7 +115,10 @@ fn parse_bbox(xhtml: &str) -> Vec<Line> {
let x_min = attr(tag, "xMin"); let x_min = attr(tag, "xMin");
let y_min = attr(tag, "yMin"); let y_min = attr(tag, "yMin");
if lines.is_empty() || (y_min - current_y).abs() > 2.0 { if lines.is_empty() || (y_min - current_y).abs() > 2.0 {
lines.push(Line { words: Vec::new() }); lines.push(Line {
words: Vec::new(),
start: 0.0,
});
current_y = y_min; current_y = y_min;
} }
lines lines
@@ -124,6 +130,7 @@ fn parse_bbox(xhtml: &str) -> Vec<Line> {
} }
for line in &mut lines { for line in &mut lines {
let origin = line.words.first().map(|word| word.x).unwrap_or(0.0); let origin = line.words.first().map(|word| word.x).unwrap_or(0.0);
line.start = origin * BP_TO_PT;
for word in &mut line.words { for word in &mut line.words {
word.x = (word.x - origin) * BP_TO_PT; word.x = (word.x - origin) * BP_TO_PT;
} }
@@ -155,8 +162,13 @@ fn route_d_lines_with(
other => panic!("expected a paragraph unit, got {other:?}"), other => panic!("expected a paragraph unit, got {other:?}"),
}; };
let mut lines = Vec::new(); let mut lines = Vec::new();
for line in &paragraph.lines { for (line_number, line) in paragraph.lines.iter().enumerate() {
let mut x = paragraph.left_skip as f64 / PT as f64; let indent = paragraph
.line_indents
.get(line_number)
.copied()
.unwrap_or(0);
let mut x = (paragraph.left_skip + indent) as f64 / PT as f64;
let mut words: Vec<Word> = Vec::new(); let mut words: Vec<Word> = Vec::new();
let mut word = String::new(); let mut word = String::new();
let mut word_x = 0.0; let mut word_x = 0.0;
@@ -189,12 +201,13 @@ fn route_d_lines_with(
x: word_x, x: word_x,
}); });
} }
let start = words.first().map(|word| word.x).unwrap_or(0.0);
if let Some(origin) = words.first().map(|word| word.x) { if let Some(origin) = words.first().map(|word| word.x) {
for word in &mut words { for word in &mut words {
word.x -= origin; word.x -= origin;
} }
} }
lines.push(Line { words }); lines.push(Line { words, start });
} }
lines lines
} }
@@ -286,6 +299,40 @@ fn hyphen_penalty_inhibits_hyphenation() {
}); });
} }
/// `\hangindent`/`\hangafter` shift the affected lines and narrow their
/// measure exactly like pdfLaTeX.
#[test]
fn hang_indent_shifts_lines_like_tex() {
let width = 120;
let Some(reference) = pdftex_lines(&paragraph_fixture_with(
WORDS,
width,
"\\hangindent=20pt\\hangafter=1\\relax ",
)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(WORDS, f64::from(width), |style| {
style.hang_indent = 20 * PT;
style.hang_after = 1;
});
assert_lines_match("hangindent 120pt", &ours, &reference);
assert!(ours.len() >= 3, "fixture must span at least three lines");
for index in 1..ours.len() {
let our_step = ours[index].start - ours[index - 1].start;
let tex_step = reference[index].start - reference[index - 1].start;
assert!(
(our_step - tex_step).abs() <= 0.1,
"line {} moved {our_step:.3}pt, pdfLaTeX {tex_step:.3}pt",
index + 1
);
}
assert!(
ours[1].start - ours[0].start > 18.0,
"the second line must start 20pt further right"
);
}
#[test] #[test]
fn paragraph_breaks_match_pdftex_at_150pt() { fn paragraph_breaks_match_pdftex_at_150pt() {
compare_fixture(WORDS, 150); compare_fixture(WORDS, 150);
+12
View File
@@ -15,6 +15,9 @@ fn body_style() -> ParagraphStyle {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,
@@ -161,6 +164,9 @@ fn route_d_page_matches_pdftex_raster_geometry() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,
@@ -318,6 +324,9 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,
@@ -605,6 +614,9 @@ fn route_d_multiline_bands_track_pdftex() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,
+12 -8
View File
@@ -48,16 +48,16 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the 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 route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 289 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 293 workspace tests are green and no oracle
fixture is ignored. fixture is ignored.
Known gaps, in dependency order: Known gaps, in dependency order:
1. paragraph breaking reproduces TeX's passes and demerits (including 1. paragraph breaking reproduces TeX's passes and demerits (including
`\adjdemerits`, `\doublehyphendemerits`, `\finalhyphendemerits`, `\adjdemerits`, `\doublehyphendemerits`, `\finalhyphendemerits`,
`\hyphenpenalty`, `\exhyphenpenalty` and `\hyphenation` exceptions), but `\hyphenpenalty`, `\exhyphenpenalty`, `\hyphenation` exceptions and
not yet `\parshape`, `\looseness`, `\hangindent`, spacefactor or `\hangindent`/`\hangafter`/`\parshape` line geometry), but not yet
`\parfillskip`/fil glue orders; `\looseness`, spacefactor or `\parfillskip`/fil glue orders;
2. the page builder is a scrolling builder with fraction policies, not a TeX 2. the page builder is a scrolling builder with fraction policies, not a TeX
page builder with badness and an interpreted `\output`; page builder with badness and an interpreted `\output`;
3. `\insert` classes are data structures, not TeX registers and an output 3. `\insert` classes are data structures, not TeX registers and an output
@@ -179,10 +179,14 @@ and `\finalhyphendemerits` all affect the chosen solution, and
`\hyphenation` exceptions are inserted into the pattern trie (unit-tested by `\hyphenation` exceptions are inserted into the pattern trie (unit-tested by
counting the discretionary points they add). counting the discretionary points they add).
Still open: `\parfillskip`/fil glue orders, `\hangindent`/`\parshape`/ `\hangindent`/`\hangafter` and `\parshape` now drive each line's measure
`\looseness`, spacefactor/`\sfcode`, vertical-list skips and left offset; the DP remembers a candidate's line number so the geometry can
(`\baselineskip`, `\lineskip`, `\parskip`), double/final hyphen demerit vary per line, and a 120pt oracle fixture checks every line origin against
oracle fixtures, and more width fixtures. pdfLaTeX.
Still open: `\parfillskip`/fil glue orders, `\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) ### P2 — Vertical list, page builder, `\output` (L2)
+15 -10
View File
@@ -71,7 +71,9 @@ the fallback here mirrors that choice by taking the longest prefix within
tolerance and otherwise the first prefix that overflows. Justification tolerance and otherwise the first prefix that overflows. Justification
stretches normal glue past its nominal stretch (badness simply exceeds 100) stretches normal glue past its nominal stretch (badness simply exceeds 100)
and clamps shrink at the declared limit, so overfull lines stay overfull and clamps shrink at the declared limit, so overfull lines stay overfull
exactly as in TeX. The bounds and hyphen demerits are `ParagraphStyle` exactly as in TeX. Each line can take its measure and left offset from
`\hangindent`/`\hangafter` or an explicit `\parshape` list; the display list
honours the same offsets. The bounds and hyphen demerits are `ParagraphStyle`
fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and
`\exhyphenpenalty`, `\linepenalty`, `\adjdemerits`, `\exhyphenpenalty`, `\linepenalty`, `\adjdemerits`,
`\doublehyphendemerits`, `\finalhyphendemerits` and `\emergencystretch`, `\doublehyphendemerits`, `\finalhyphendemerits` and `\emergencystretch`,
@@ -84,7 +86,9 @@ horizontally. The narrow measures exercise hyphenated and overfull breaks,
150pt the final-pass overfull box, and 180-240pt ordinary tolerance 150pt the final-pass overfull box, and 180-240pt ordinary tolerance
solutions. Two further fixtures pin register behaviour at 120pt: solutions. Two further fixtures pin register behaviour at 120pt:
`\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000` `\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 inhibits it, leaving the overfull first-fit lines TeX produces. A 120pt
fixture with `\hangindent=20pt \hangafter=1` checks every line origin
against pdfLaTeX as well as the word positions inside each line. `route_d_multiline_bands_track_pdftex` rasterizes the same
paragraph in both engines and compares ink bands, covering baseline placement paragraph in both engines and compares ink bands, covering baseline placement
and justification. and justification.
@@ -116,9 +120,10 @@ and justification.
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth, - The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
italic correction, kern pairs, ligatures), applies TeX Live's en-US italic correction, kern pairs, ligatures), applies TeX Live's en-US
hyphenation patterns and runs TeX's tolerance passes with demerits. The hyphenation patterns and runs TeX's tolerance passes with demerits. The
tolerance bounds, break penalties and flagged demerits are modelled, and tolerance bounds, break penalties and flagged demerits are modelled,
`\hyphenation` exceptions are inserted into the pattern trie. Remaining gaps `\hyphenation` exceptions are inserted into the pattern trie, and
are `\looseness`, `\parshape`, `\hangindent`, spacefactor/`\sfcode`, `\hangindent`/`\hangafter`/`\parshape` change each line's measure and left
offset. Remaining gaps are `\looseness`, spacefactor/`\sfcode`,
`\parfillskip`/fil glue orders, and the vertical-list skips `\parfillskip`/fil glue orders, and the vertical-list skips
(`\baselineskip`, `\lineskip`, `\parskip`). (`\baselineskip`, `\lineskip`, `\parskip`).
@@ -292,7 +297,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. 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 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. The crate currently has 184 unit tests plus six route-D integration tests and six oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 293 tests (184 route-D unit, 6 route-D integration, 6 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 ### M0 incremental demo
@@ -320,10 +325,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 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**: `\parshape`, `\looseness`, `\hangindent`, spacefactor/`\sfcode`, - **M1**: `\looseness`, spacefactor/`\sfcode`, `\parfillskip`/fil glue orders
`\parfillskip`/fil glue orders and the vertical-list skips are still open; and the vertical-list skips are still open; the tolerance, penalty and demerit
the tolerance, penalty and demerit registers plus `\hyphenation` exceptions registers, `\hyphenation` exceptions, and `\hangindent`/`\parshape` are
are modelled. 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. - **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 - **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. 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.
+3
View File
@@ -333,6 +333,9 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
centered: paragraph.centered, centered: paragraph.centered,
right_aligned: paragraph.right_aligned, right_aligned: paragraph.right_aligned,
right_skip: 0, right_skip: 0,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,