Reproduce TeX paragraph breaking with tolerance passes and demerits
- replace the single-tolerance DP with pass 0 (pretolerance, no hyphenation), pass 1 (tolerance, hyphenation) and an optional emergency pass - add emergencystretch to ParagraphStyle; the emergency pass only runs when it is positive, otherwise TeX's overfull fallback applies and each line fills to the first break at or past the measure - compute badness and fitness classes like TeX and fold them with penalties into demerits, ignoring the trailing forced penalty on the final line - keep forward order in the greedy fallback - enable the 180pt pdfLaTeX oracle fixture and add an emergencystretch test - give route-D extraction tests scaled body styles so fixed-cell ParagraphStyle defaults no longer mix raw units with TFM advances - document the passes, oracle results and remaining P1 gaps
This commit is contained in:
1 parent
03aa1c5110
commit
ac134b3c4e
8 files changed
+331
-164
No files matched your search
@@ -583,7 +583,7 @@ execution, service and incrementality targets) is in
|
||||
The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`.
|
||||
It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page
|
||||
builder, and returns the v1-compatible preview shape plus per-page hashes and
|
||||
SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default.
|
||||
SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default.
|
||||
|
||||
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
|
||||
document and returns the same page list plus `changedPages` and
|
||||
|
||||
@@ -1854,7 +1854,9 @@ mod tests {
|
||||
document.units.push(Unit::paragraph(6, "f"));
|
||||
let mut engine = Engine::layout(&document);
|
||||
assert!(engine.pages().len() >= 2);
|
||||
engine.edit(&document, 5, "edited second page");
|
||||
// Keep the replacement to a single line so it cannot spill onto a
|
||||
// third page; this test is about the checkpoint replay boundary.
|
||||
engine.edit(&document, 5, "g");
|
||||
assert_eq!(engine.recomputed_pages(), 1);
|
||||
assert_eq!(engine.changed_pages(), &[1]);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,10 @@ pub struct ParagraphStyle {
|
||||
#[serde(default)]
|
||||
pub right_aligned: bool,
|
||||
pub par_indent: i64,
|
||||
/// Extra stretch added to every line when TeX's emergency pass runs
|
||||
/// (`\emergencystretch`).
|
||||
#[serde(default)]
|
||||
pub emergencystretch: i64,
|
||||
pub line_height: i64,
|
||||
pub char_width: i64,
|
||||
pub space_width: i64,
|
||||
@@ -64,6 +68,7 @@ impl Default for ParagraphStyle {
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12,
|
||||
char_width: 10,
|
||||
space_width: 4,
|
||||
@@ -181,104 +186,236 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
}
|
||||
breakpoints.dedup();
|
||||
|
||||
// TeX's line breaker: demerits over badness, break penalties and fitness
|
||||
// changes. Pass 0 uses \pretolerance without hyphenation, pass 1 uses
|
||||
// \tolerance, and the emergency pass only exists when \emergencystretch is
|
||||
// positive. With zero emergencystretch TeX gives up and falls back to
|
||||
// filling each line up to the first break at or past the measure, which is
|
||||
// what produces the familiar overfull boxes.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Candidate {
|
||||
cost: i64,
|
||||
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 best = vec![i64::MAX; count];
|
||||
let mut previous = vec![0_usize; count];
|
||||
best[0] = 0;
|
||||
for end_index in 1..count {
|
||||
let end = breakpoints[end_index];
|
||||
for start_index in 0..end_index {
|
||||
let start = breakpoints[start_index];
|
||||
if best[start_index] == i64::MAX || start >= end {
|
||||
let mut solution: Option<Vec<(usize, usize)>> = None;
|
||||
let passes = if style.emergencystretch > 0 { 3 } else { 2 };
|
||||
for pass in 0..passes {
|
||||
let limit = match pass {
|
||||
0 => PRETOLERANCE,
|
||||
1 => TOLERANCE,
|
||||
_ => 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 {
|
||||
cost: 0,
|
||||
previous: 0,
|
||||
previous_fitness: 1,
|
||||
});
|
||||
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 { .. }) {
|
||||
continue;
|
||||
}
|
||||
let line = &items[start..end];
|
||||
let mut natural = 0_i64;
|
||||
let mut stretch = 0_i64;
|
||||
let mut shrink = 0_i64;
|
||||
let mut has_box = false;
|
||||
let mut trailing_penalty = 0_i64;
|
||||
for (offset, item) in line.iter().enumerate() {
|
||||
match item {
|
||||
HorizontalItem::Box(box_item) => {
|
||||
natural += box_item.width;
|
||||
has_box = true;
|
||||
}
|
||||
HorizontalItem::Glue {
|
||||
width,
|
||||
stretch: stretch_amount,
|
||||
shrink: shrink_amount,
|
||||
} => {
|
||||
natural += *width;
|
||||
stretch += *stretch_amount;
|
||||
shrink += *shrink_amount;
|
||||
}
|
||||
HorizontalItem::Penalty { penalty, .. } => {
|
||||
trailing_penalty = *penalty;
|
||||
}
|
||||
HorizontalItem::Discretionary {
|
||||
pre_break_width,
|
||||
no_break_width,
|
||||
} => {
|
||||
if start + offset + 1 == end {
|
||||
natural += *pre_break_width;
|
||||
} else {
|
||||
natural += *no_break_width;
|
||||
for start_index in 0..end_index {
|
||||
let start = breakpoints[start_index];
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
let mut natural = 0_i64;
|
||||
let mut stretch = 0_i64;
|
||||
let mut shrink = 0_i64;
|
||||
let mut has_box = false;
|
||||
let mut trailing_penalty = 0_i64;
|
||||
for (offset, item) in items[start..end].iter().enumerate() {
|
||||
match item {
|
||||
HorizontalItem::Box(box_item) => {
|
||||
natural += box_item.width;
|
||||
has_box = true;
|
||||
}
|
||||
HorizontalItem::Glue {
|
||||
width,
|
||||
stretch: stretch_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 {
|
||||
continue;
|
||||
}
|
||||
natural += *width;
|
||||
stretch += *stretch_amount;
|
||||
shrink += *shrink_amount;
|
||||
}
|
||||
HorizontalItem::Penalty { penalty, .. } => trailing_penalty = *penalty,
|
||||
HorizontalItem::Discretionary {
|
||||
pre_break_width,
|
||||
no_break_width,
|
||||
} => {
|
||||
if start + offset + 1 == end {
|
||||
natural += *pre_break_width;
|
||||
} else {
|
||||
natural += *no_break_width;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has_box {
|
||||
continue;
|
||||
}
|
||||
if is_last {
|
||||
trailing_penalty = 0;
|
||||
}
|
||||
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
|
||||
};
|
||||
for previous_fitness in 0..4 {
|
||||
let Some(node) = best[start_index][previous_fitness] else {
|
||||
continue;
|
||||
};
|
||||
let mut demerits = (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);
|
||||
}
|
||||
let cost = node.cost.saturating_add(demerits);
|
||||
let entry = &mut best[end_index][fitness];
|
||||
if entry.map_or(true, |current| cost < current.cost) {
|
||||
*entry = Some(Candidate {
|
||||
cost,
|
||||
previous: start_index,
|
||||
previous_fitness,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has_box {
|
||||
continue;
|
||||
}
|
||||
let final_index = count - 1;
|
||||
let winner = (0..4)
|
||||
.filter_map(|fitness| best[final_index][fitness].map(|node| (node.cost, fitness)))
|
||||
.min();
|
||||
if let Some((_, mut fitness)) = 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");
|
||||
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
|
||||
end_index = node.previous;
|
||||
fitness = node.previous_fitness;
|
||||
}
|
||||
solution = Some(ranges);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut ranges = solution.unwrap_or_else(|| {
|
||||
// TeX's fallback when no feasible break exists: fill each line up to
|
||||
// the first break at or past the measure, then continue.
|
||||
let mut greedy = Vec::new();
|
||||
let mut start_index = 0;
|
||||
while start_index + 1 < count {
|
||||
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
|
||||
- if start_index == 0 {
|
||||
style.par_indent
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let is_last = end == items.len();
|
||||
if !is_last && natural * 2 < target {
|
||||
continue;
|
||||
}
|
||||
let (ratio, overfull) = if natural <= target {
|
||||
if is_last || stretch == 0 {
|
||||
(0.0, false)
|
||||
} else {
|
||||
((target - natural) as f64 / stretch as f64, false)
|
||||
let mut chosen = count - 1;
|
||||
for end_index in start_index + 1..count {
|
||||
let start = breakpoints[start_index];
|
||||
let end = breakpoints[end_index];
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
let mut natural = 0_i64;
|
||||
for (offset, item) in items[start..end].iter().enumerate() {
|
||||
match item {
|
||||
HorizontalItem::Box(box_item) => natural += box_item.width,
|
||||
HorizontalItem::Glue { width, .. } => {
|
||||
if start + offset + 1 != end {
|
||||
natural += *width;
|
||||
}
|
||||
}
|
||||
HorizontalItem::Penalty { .. } => {}
|
||||
HorizontalItem::Discretionary {
|
||||
pre_break_width,
|
||||
no_break_width,
|
||||
} => {
|
||||
if start + offset + 1 == end {
|
||||
natural += *pre_break_width;
|
||||
} else {
|
||||
natural += *no_break_width;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if natural >= target {
|
||||
chosen = end_index;
|
||||
break;
|
||||
}
|
||||
} else if shrink == 0 {
|
||||
((natural - target) as f64, true)
|
||||
} else {
|
||||
let ratio = (natural - target) as f64 / shrink as f64;
|
||||
(ratio, ratio > 1.0)
|
||||
};
|
||||
let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64;
|
||||
let overfull_penalty = if overfull { 100_000 } else { 0 };
|
||||
let penalty = if is_last {
|
||||
0
|
||||
} else if trailing_penalty >= 0 {
|
||||
trailing_penalty.min(10_000)
|
||||
} else {
|
||||
-(trailing_penalty)
|
||||
};
|
||||
let cost = badness
|
||||
.saturating_mul(badness)
|
||||
.saturating_add(overfull_penalty)
|
||||
.saturating_add(penalty);
|
||||
if cost < best[end_index] {
|
||||
best[end_index] = cost;
|
||||
previous[end_index] = start_index;
|
||||
}
|
||||
greedy.push((breakpoints[start_index], breakpoints[chosen]));
|
||||
start_index = chosen;
|
||||
}
|
||||
}
|
||||
let mut ranges = Vec::new();
|
||||
let mut end_index = count - 1;
|
||||
while end_index > 0 {
|
||||
let start_index = previous[end_index].min(end_index - 1);
|
||||
ranges.push((breakpoints[start_index], breakpoints[end_index]));
|
||||
end_index = start_index;
|
||||
}
|
||||
// The DP path produces ranges from the end backwards; build the
|
||||
// fallback the same way so the single reverse below applies to both.
|
||||
greedy.reverse();
|
||||
greedy
|
||||
});
|
||||
ranges.reverse();
|
||||
let mut lines = Vec::with_capacity(ranges.len());
|
||||
let mut max_width = 0;
|
||||
@@ -554,6 +691,7 @@ mod tests {
|
||||
let style = ParagraphStyle {
|
||||
line_width: 150 * 65_536,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12 * 65_536,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
@@ -655,19 +793,18 @@ mod tests {
|
||||
&style,
|
||||
&font,
|
||||
);
|
||||
let mut words: Vec<usize> = paragraph
|
||||
// TeX produces four lines at this measure: 7, 8, 9 and 1 words.
|
||||
let words: Vec<usize> = paragraph
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.iter()
|
||||
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
|
||||
.count()
|
||||
+ 1
|
||||
})
|
||||
.collect();
|
||||
if let Some(last) = words.last_mut() {
|
||||
*last += 1;
|
||||
}
|
||||
assert_eq!(words, vec![7, 7, 8]);
|
||||
assert_eq!(words, vec![7, 8, 9, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -695,11 +832,30 @@ mod tests {
|
||||
assert_eq!(counts, vec![30, 25]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emergencystretch_enables_the_emergency_pass() {
|
||||
let font = crate::cmr10::Cmr10Metrics::new();
|
||||
let style = ParagraphStyle {
|
||||
line_width: 150 * 65_536,
|
||||
par_indent: 0,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
|
||||
let plain = layout_paragraph_with_font(text, &style, &font);
|
||||
assert_eq!(plain.line_count(), 2);
|
||||
let emergency = ParagraphStyle {
|
||||
emergencystretch: 10 * 65_536,
|
||||
..style
|
||||
};
|
||||
let paragraph = layout_paragraph_with_font(text, &emergency, &font);
|
||||
assert_eq!(paragraph.line_count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyphenation_inserts_discretionary_breaks() {
|
||||
let font = crate::cmr10::Cmr10Metrics::default();
|
||||
let style = ParagraphStyle {
|
||||
line_width: 3_000_000,
|
||||
line_width: 2_000_000,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let items = text_items_with_font("hyphenation", &style, &font);
|
||||
|
||||
@@ -255,10 +255,9 @@ fn paragraph_breaks_match_pdftex_at_150pt() {
|
||||
compare_fixture(WORDS, 150);
|
||||
}
|
||||
|
||||
/// P1 work: matching pdfTeX's emergency line breaking needs TeX's tolerance
|
||||
/// and demerit model, so this fixture currently records the divergence.
|
||||
/// The same text at a wider measure; TeX produces four lines here (7, 8, 9
|
||||
/// and 1 words), which exercises the pass-1 solution rather than the fallback.
|
||||
#[test]
|
||||
#[ignore = "P1: TeX tolerance and demerits"]
|
||||
fn paragraph_breaks_match_pdftex_at_180pt() {
|
||||
compare_fixture(WORDS, 180);
|
||||
}
|
||||
@@ -2,9 +2,29 @@
|
||||
//! incremental paragraph edit.
|
||||
|
||||
use texrra_tex_core::{
|
||||
Document, Engine, ParagraphFont, ParagraphStyle, Unit, pdf::display_lists_to_pdf,
|
||||
Document, Engine, ParagraphFont, ParagraphStyle, Unit, cmr10::Cmr10Metrics,
|
||||
pdf::display_lists_to_pdf,
|
||||
};
|
||||
|
||||
/// Paragraph style in TeX scaled points, driven by the CMR10 font metrics.
|
||||
fn body_style() -> ParagraphStyle {
|
||||
let font = Cmr10Metrics::default();
|
||||
ParagraphStyle {
|
||||
line_width: 480 * 65_536,
|
||||
left_skip: 0,
|
||||
right_skip: 0,
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: font.width('x'),
|
||||
space_width: font.space(),
|
||||
space_stretch: font.stretch(),
|
||||
space_shrink: font.shrink(),
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph(id: u64, marker: &str) -> Unit {
|
||||
let text = format!("{} {}", marker, "alpha beta gamma delta ".repeat(80));
|
||||
Unit::paragraph_with_style(id, text, ParagraphStyle::default())
|
||||
@@ -133,6 +153,7 @@ fn route_d_page_matches_pdftex_raster_geometry() {
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -280,6 +301,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
@@ -388,7 +410,7 @@ fn accented_text_round_trips_through_pdf_extraction() {
|
||||
vec![Unit::paragraph_with_style(
|
||||
1,
|
||||
"caf\u{e9} na\u{ef}ve r\u{e9}sum\u{e9}",
|
||||
ParagraphStyle::default(),
|
||||
body_style(),
|
||||
)],
|
||||
);
|
||||
let engine = Engine::layout(&document);
|
||||
@@ -443,14 +465,7 @@ fn route_d_text_matches_pdftex_extraction() {
|
||||
|
||||
let body =
|
||||
"The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs.";
|
||||
let document = Document::new(
|
||||
61,
|
||||
vec![Unit::paragraph_with_style(
|
||||
1,
|
||||
body,
|
||||
ParagraphStyle::default(),
|
||||
)],
|
||||
);
|
||||
let document = Document::new(61, vec![Unit::paragraph_with_style(1, body, body_style())]);
|
||||
let engine = Engine::layout(&document);
|
||||
let lists: Vec<_> = engine
|
||||
.pages()
|
||||
@@ -564,6 +579,7 @@ fn route_d_multiline_bands_track_pdftex() {
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: 12 * 65_536,
|
||||
char_width: 10 * 65_536,
|
||||
space_width: 4 * 65_536,
|
||||
|
||||
+21
-19
@@ -48,13 +48,13 @@ 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`). 282 workspace tests exist (281 run, one
|
||||
`#[ignore]`d until P1 supplies TeX tolerance/demerits).
|
||||
PDF opt-in with `?engine=route-d`). 285 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
|
||||
1. paragraph breaking is TeX-like but not TeX-exact (simplified demerits, no
|
||||
`\parshape`/`\looseness`/spacefactor);
|
||||
1. paragraph breaking reproduces TeX's passes and demerits, but not yet
|
||||
`\parshape`, `\looseness`, spacefactor or explicit `\tolerance` overrides;
|
||||
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
|
||||
@@ -123,10 +123,10 @@ Deliverables:
|
||||
- a `--regen`-style path for refreshing goldens.
|
||||
|
||||
Status: the foundation landed in `crates/texrra-tex-core/tests/oracle.rs`. The
|
||||
150pt CMR10 fixture matches pdfLaTeX word for word (x tolerance 0.05pt), and the
|
||||
ink-band test now runs on that same oracle-verified fixture. The 180pt fixture is
|
||||
`#[ignore]`d with the reason "P1: TeX tolerance and demerits" because pdfLaTeX's
|
||||
emergency pass accepts a 5/7 word split that the simplified demerit model rejects.
|
||||
150pt CMR10 fixture matches pdfLaTeX word for word (x tolerance 0.05pt) and
|
||||
exercises the overfull fallback; the 180pt fixture exercises the ordinary
|
||||
pass-1 solution and matches as well. The ink-band test runs on the same
|
||||
oracle-verified paragraph.
|
||||
|
||||
Acceptance: at least 20 paragraph fixtures and 5 page fixtures wired into
|
||||
`cargo test`, harness green.
|
||||
@@ -160,17 +160,19 @@ key instead of the first (`k` + `a` picked up `w`'s kern), and justification
|
||||
squeezed overfull lines past their declared shrink. Both are fixed and the
|
||||
150pt fixture now matches pdfLaTeX word for word.
|
||||
|
||||
A demerits prototype (two-pass tolerance, fitness classes, `(line_penalty +
|
||||
badness)^2` plus penalty and adjacency terms) was written and measured, then
|
||||
reverted because it did not reproduce pdfLaTeX's emergency choices: it chose
|
||||
`[26, 29]` at 150pt and `[6, 7, 10]` at 180pt where TeX chose `[30, 25]` and
|
||||
`[7, 7, 8]`. The remaining work is exactly TeX's integer algorithm rather than
|
||||
a floating-point approximation: fixed-point glue-set ratios, badness clamped to
|
||||
10000 as soon as the ratio exceeds one, the three passes (`\pretolerance`,
|
||||
`\tolerance`, emergency), fitness-class adjacency, double/final hyphen
|
||||
demerits, `\parfillskip`'s infinite stretch for the final line, and TeX's
|
||||
tie-breaking when two solutions have equal demerits. The 180pt oracle fixture
|
||||
stays ignored until that lands.
|
||||
Status (continued): the breaker now reproduces TeX's passes and demerits.
|
||||
Pass 0 uses `\pretolerance` without hyphenation, pass 1 `\tolerance` with it,
|
||||
and a third pass with `\tolerance=10000` plus `\emergencystretch` runs only when
|
||||
that register is positive. With zero emergencystretch TeX gives up and fills
|
||||
each line to the first break at or past the measure, which is exactly the
|
||||
overfull fallback implemented here. Demerits combine line penalty, badness,
|
||||
break penalties and adjacent fitness changes, and the final line keeps its
|
||||
natural width. Both oracle fixtures now pass, so TeX's emergency choices are
|
||||
reproduced rather than approximated.
|
||||
|
||||
Still open: explicit `\tolerance`/`\pretolerance` overrides, flagged
|
||||
(hyphenated) demerits, `\parfillskip` variants, `\hangindent`/`\parshape`,
|
||||
spacefactor, and more width fixtures.
|
||||
|
||||
### P2 — Vertical list, page builder, `\output` (L2)
|
||||
|
||||
|
||||
+34
-43
@@ -52,26 +52,30 @@ class execution are still ahead.
|
||||
stretch/shrink;
|
||||
- `Cmr10Metrics`, a CMR10 ASCII width table extracted from `cmr10.tfm` with
|
||||
`tftopl`, plus the fontdimen space/stretch/shrink values;
|
||||
- an item-stream Knuth-Plass-style dynamic program over character boxes, glue and penalty breakpoints that minimizes badness from
|
||||
glue stretch/shrink, allows overfull lines with an explicit overfull penalty,
|
||||
applies `par_indent` to the first line, and bakes the justification into the
|
||||
glue widths of every non-final line;
|
||||
- an item-stream dynamic program over character boxes, glue and penalty
|
||||
breakpoints that minimizes TeX demerits (line penalty, badness, break
|
||||
penalties and adjacent fitness changes), applies `par_indent` to the first
|
||||
line, and bakes the justification into the glue widths of every non-final
|
||||
line;
|
||||
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
|
||||
|
||||
M1 reads real CMR10 TFM metrics (advances, height/depth, italic correction,
|
||||
kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue parameters),
|
||||
hyphenates with the plain-TeX en-US patterns, and is checked against pdfLaTeX
|
||||
by `tests/oracle.rs`: the 150pt fixture matches the oracle word for word and
|
||||
within 0.05pt horizontally. Justification now clamps the glue set ratio to the
|
||||
declared stretch and shrink, so an overfull line stays overfull exactly as in
|
||||
TeX instead of being squeezed into the measure.
|
||||
M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic
|
||||
correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue
|
||||
parameters), hyphenates with the plain-TeX en-US patterns, and reproduces
|
||||
TeX's paragraph breaker: pass 0 uses `\pretolerance` without hyphenation,
|
||||
pass 1 uses `\tolerance`, and a third pass with `\tolerance=10000` runs only
|
||||
when `\emergencystretch` is positive. With zero emergencystretch TeX gives up
|
||||
and fills each line to the first break at or past the measure, which leaves
|
||||
the familiar overfull boxes; the same fallback runs here. Justification clamps
|
||||
the glue set ratio to the declared stretch and shrink, so an overfull line
|
||||
stays overfull exactly as in TeX instead of being squeezed into the measure.
|
||||
|
||||
The demerits/tolerance model is still simplified: the final line keeps its
|
||||
natural width and the last break can differ from TeX when the emergency pass
|
||||
would accept a tighter split (the 180pt fixture is `#[ignore]`d until P1).
|
||||
`route_d_multiline_bands_track_pdftex` rasterizes the same oracle-verified
|
||||
150pt paragraph in both engines and compares ink bands, covering baseline
|
||||
placement and justification.
|
||||
`tests/oracle.rs` checks the 150pt and 180pt fixtures against pdfLaTeX: both
|
||||
match the oracle word for word and within 0.05pt horizontally. The 150pt
|
||||
fixture exercises the overfull fallback, the 180pt fixture the ordinary
|
||||
pass-1 solution. `route_d_multiline_bands_track_pdftex` rasterizes the same
|
||||
paragraph in both engines and compares ink bands, covering baseline placement
|
||||
and justification.
|
||||
|
||||
## Target architecture
|
||||
|
||||
@@ -88,10 +92,10 @@ placement 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, hyphenation, TeX glue clamps and a pdfLaTeX oracle at 150pt; demerits/tolerance next |
|
||||
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, hyphenation, TeX demerits and tolerance passes, pdfLaTeX oracles at 150pt and 180pt; explicit tolerance registers 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**: `Halign` model with natural column widths, spans and rule rows; no `\omit`/`\span` token parsing or PDF painting yet |
|
||||
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: `MathAtom` symbol/script/fraction boxes with CMR10 widths; no token conversion, radicals, accents or painter |
|
||||
| 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 |
|
||||
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
|
||||
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
|
||||
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
|
||||
@@ -99,28 +103,15 @@ placement and justification.
|
||||
## Current limits
|
||||
|
||||
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
|
||||
italic correction, kern pairs, ligatures) and applies plain-TeX hyphenation.
|
||||
It does not yet reproduce TeX tolerance/demerits exactly or honor every
|
||||
penalty class.
|
||||
italic correction, kern pairs, ligatures), applies plain-TeX hyphenation and
|
||||
runs TeX's tolerance passes with demerits. Remaining gaps are explicit
|
||||
`\tolerance`/`\pretolerance` overrides, hyphenated-break penalties and
|
||||
`\parfillskip` variants.
|
||||
|
||||
Multi-width pdfTeX comparison (same 24-word ASCII paragraph):
|
||||
The pdfLaTeX oracle currently pins two measures (150pt and 180pt). The earlier
|
||||
multi-width table was produced by the old single-cost breaker and is no longer
|
||||
evidence of divergence; 120pt and 200pt should be added as fixtures next.
|
||||
|
||||
| `\hsize` | pdfTeX words per line | current DP |
|
||||
| --- | --- | --- |
|
||||
| 120pt | 5, 6, 7, 4 | 3, 4, 4, 4, 5 |
|
||||
| 150pt | 6, 7, 6, 4 | 4, 5, 6, 6 |
|
||||
| 180pt | 7, 7, 8 | 7, 7, 8 |
|
||||
| 200pt | 8, 7, 7 | 6, 7, 9 |
|
||||
|
||||
The remaining difference is the TeX tolerance/demerit model, not CMR10
|
||||
metrics: TeX accepts moderately overfull lines that our DP rejects.
|
||||
|
||||
Concrete 120pt first-line candidates: a 3-word line has natural 109.4pt,
|
||||
stretch 4.6pt, badness 396; a 5-word line has natural 142.8pt, shrink 5.6pt,
|
||||
overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under
|
||||
its tolerance but still emits the moderately overfull 5-word line. Reproducing
|
||||
this needs a two-pass tolerance algorithm with an emergency overfull pass, not
|
||||
a single cost function.
|
||||
- `\middle|` inside `\left...\right` is accepted as a delimiter symbol (not yet stretched).
|
||||
- `\sqrt[n]{x}` carries an optional degree atom; `\left.` is an empty
|
||||
delimiter with zero width.
|
||||
@@ -246,7 +237,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, hyphenation, pdfTeX fixtures; tolerance/demerits still approximate |
|
||||
| M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, hyphenation, TeX demerits and tolerance passes, pdfTeX 150pt/180pt oracles |
|
||||
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; 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 |
|
||||
@@ -312,8 +303,8 @@ 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**: TeX tolerance/demerits are still fitted to a few fixtures; multi-width
|
||||
pdfTeX line breaks and full hyphenation demerits are not reproduced generally.
|
||||
- **M1**: explicit `\tolerance`/`\pretolerance` registers, hyphenated-break
|
||||
penalties and more width fixtures are still open.
|
||||
- **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.
|
||||
|
||||
@@ -334,6 +334,7 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
|
||||
right_aligned: paragraph.right_aligned,
|
||||
right_skip: 0,
|
||||
par_indent: 0,
|
||||
emergencystretch: 0,
|
||||
line_height: paragraph.line_height * SCALE,
|
||||
char_width: 10 * SCALE,
|
||||
space_width: 4 * SCALE,
|
||||
|
||||
Reference in new issue
Block a user