diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 55596a4..2df7392 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -61,103 +61,174 @@ impl Paragraph { } } -/// M1 word-level Knuth-Plass approximation. +/// Convert text into a horizontal item stream: one box per character, one +/// glue per space, and a final penalty. +pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec { + let mut items = Vec::new(); + for character in text.chars() { + if character.is_whitespace() { + if !matches!(items.last(), Some(HorizontalItem::Glue { .. })) { + items.push(HorizontalItem::Glue { + width: style.space_width, + stretch: style.space_stretch, + shrink: style.space_shrink, + }); + } + } else { + items.push(HorizontalItem::Box(HorizontalBox { + width: style.char_width, + height: style.line_height, + depth: 0, + })); + } + } + while matches!(items.last(), Some(HorizontalItem::Glue { .. })) { + items.pop(); + } + items.push(HorizontalItem::Penalty { + width: 0, + penalty: 10_000, + flagged: false, + }); + items +} + +/// M1 paragraph builder over a horizontal item stream. /// -/// The real TeX paragraph builder will operate on an item stream with -/// discretionary hyphens and penalties. This version keeps the same glue -/// stretch/shrink cost model but only breaks at spaces; it is deliberately -/// isolated so the DP can be replaced without touching the page builder. -pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph { - let words: Vec<&str> = text.split_whitespace().collect(); - if words.is_empty() { +/// Breakpoints are the ends of glue/penalty items. The cost model uses the +/// available glue stretch/shrink; overfull lines are allowed with an explicit +/// penalty so a single long word still produces output. +pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragraph { + if items.is_empty() + || !items + .iter() + .any(|item| matches!(item, HorizontalItem::Box(_))) + { return Paragraph { lines: Vec::new(), height: 0, width: 0, }; } - let widths: Vec = words - .iter() - .map(|word| word.chars().count() as i64 * style.char_width) - .collect(); - let count = words.len(); - let mut best = vec![i64::MAX; count + 1]; - let mut previous = vec![0_usize; count + 1]; + let mut breakpoints = vec![0_usize]; + for (index, item) in items.iter().enumerate() { + match item { + HorizontalItem::Glue { .. } => breakpoints.push(index + 1), + HorizontalItem::Penalty { penalty, .. } if *penalty < 10_000 => { + breakpoints.push(index + 1) + } + _ => {} + } + } + if breakpoints.last().copied() != Some(items.len()) { + breakpoints.push(items.len()); + } + breakpoints.dedup(); + + let count = breakpoints.len(); + let mut best = vec![i64::MAX; count]; + let mut previous = vec![0_usize; count]; best[0] = 0; - for end in 1..=count { - for start in 0..end { - if best[start] == i64::MAX { + 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 { continue; } - let natural: i64 = widths[start..end].iter().sum::() - + style.space_width * (end - start - 1) as i64; - let target = style.line_width - if start == 0 { style.par_indent } else { 0 }; + 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 item in line { + 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; + } + } + } + if !has_box { + continue; + } + let target = style.line_width + - if start_index == 0 { + style.par_indent + } else { + 0 + }; + let is_last = end == items.len(); let (ratio, overfull) = if natural <= target { - let stretch = style.space_stretch * (end - start - 1) as i64; - if stretch == 0 { - // A single word has no interword glue to stretch. Treat it - // as an extremely loose line instead of a free break. - let slack = (target - natural).max(1) as f64; - (slack / style.space_stretch.max(1) as f64, false) + if is_last || stretch == 0 { + (0.0, false) } else { ((target - natural) as f64 / stretch as f64, false) } + } else if shrink == 0 { + ((natural - target) as f64, true) } else { - let shrink = style.space_shrink * (end - start - 1) as i64; - if shrink == 0 { - ((natural - target) as f64, true) - } else { - let ratio = (natural - target) as f64 / shrink as f64; - (ratio, ratio > 1.0) - } + 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); - if cost < best[end] { - best[end] = cost; - previous[end] = start; + .saturating_add(overfull_penalty) + .saturating_add(penalty); + if cost < best[end_index] { + best[end_index] = cost; + previous[end_index] = start_index; } } } let mut ranges = Vec::new(); - let mut end = count; - while end > 0 { - let start = previous[end].min(end - 1); - ranges.push((start, end)); - end = start; + 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; } ranges.reverse(); let mut lines = Vec::with_capacity(ranges.len()); let mut max_width = 0; for (start, end) in ranges { - let mut line = Vec::new(); - let mut width = 0; - for index in start..end { - if index > start { - line.push(HorizontalItem::Glue { - width: style.space_width, - stretch: style.space_stretch, - shrink: style.space_shrink, - }); - width += style.space_width; - } - line.push(HorizontalItem::Box(HorizontalBox { - width: widths[index], - height: style.line_height, - depth: 0, - })); - width += widths[index]; - } - if end == count { - line.push(HorizontalItem::Penalty { - width: 0, - penalty: 10_000, - flagged: false, - }); + let mut line: Vec = items[start..end].to_vec(); + while matches!( + line.last(), + Some(HorizontalItem::Glue { .. } | HorizontalItem::Penalty { .. }) + ) { + line.pop(); } + let width: i64 = line + .iter() + .map(|item| match item { + HorizontalItem::Box(box_item) => box_item.width, + HorizontalItem::Glue { width, .. } => *width, + HorizontalItem::Penalty { width, .. } => *width, + }) + .sum(); max_width = max_width.max(width); lines.push(line); } @@ -168,23 +239,37 @@ pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph { } } +pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph { + let items = text_items(text, style); + layout_items(&items, style) +} + #[cfg(test)] mod tests { use super::*; + fn boxes(line: &[HorizontalItem]) -> usize { + line.iter() + .filter(|item| matches!(item, HorizontalItem::Box(_))) + .count() + } + + fn glues(line: &[HorizontalItem]) -> usize { + line.iter() + .filter(|item| matches!(item, HorizontalItem::Glue { .. })) + .count() + } + #[test] - fn words_break_at_spaces_and_use_glue() { + fn words_break_at_glue_and_lines_are_justified() { let style = ParagraphStyle { - line_width: 100, + line_width: 110, ..ParagraphStyle::default() }; let paragraph = layout_paragraph("alpha beta gamma delta", &style); assert_eq!(paragraph.line_count(), 2); - assert!( - paragraph.lines[0] - .iter() - .any(|item| matches!(item, HorizontalItem::Glue { .. })) - ); + assert!(glues(¶graph.lines[0]) > 0); + assert!(boxes(¶graph.lines[0]) >= 4); } #[test] diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 14cfd7e..e93d761 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -44,12 +44,12 @@ class execution are still ahead. list model; - `ParagraphStyle` with `line_width`, `par_indent`, `line_height`, fixed character/space metrics and glue stretch/shrink; -- a word-level Knuth-Plass-style dynamic program that minimizes badness from +- 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 emits justified glue; - `Paragraph { lines, height, width }` and a paragraph-backed `Unit`. -M1 is deliberately word-level: it does not yet hyphenate, process +M1 still does not hyphenate, process `\discretionary`, use real TFM metrics or compare against pdfTeX. Those are the next paragraph milestones.