Hyphenate CMR10 paragraphs with TeX patterns

This commit is contained in:
gloamxun committed 2026-10-20 12:51:30 +08:00
1 parent c98ec0056f
commit 9a7404c717
4 files changed
+95 -11

No files matched your search

Generated
+1
View File
@@ -965,6 +965,7 @@ dependencies = [
name = "texrra-tex-core"
version = "0.1.0"
dependencies = [
"hyphenate",
"serde",
"serde_json",
]
+1
View File
@@ -8,3 +8,4 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
hyphenate = { path = "../../vendor/hyphenate" }
+89 -11
View File
@@ -21,6 +21,13 @@ pub enum HorizontalItem {
penalty: i64,
flagged: bool,
},
/// A possible hyphenation point. `pre_break_width` is the hyphen width
/// added when the line breaks here; `no_break_width` is the material kept
/// when it does not break.
Discretionary {
pre_break_width: i64,
no_break_width: i64,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -117,6 +124,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
HorizontalItem::Penalty { penalty, .. } if *penalty < 10_000 => {
breakpoints.push(index + 1)
}
HorizontalItem::Discretionary { .. } => breakpoints.push(index + 1),
_ => {}
}
}
@@ -142,7 +150,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
let mut shrink = 0_i64;
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for item in line {
for (offset, item) in line.iter().enumerate() {
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
@@ -160,6 +168,16 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
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 {
@@ -217,7 +235,30 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
for (start, end) in ranges {
let mut line: Vec<HorizontalItem> = items[start..end].to_vec();
let mut line: Vec<HorizontalItem> = Vec::new();
for (index, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + index + 1 == end {
line.push(HorizontalItem::Box(HorizontalBox {
width: *pre_break_width,
height: style.line_height,
depth: 0,
}));
} else if *no_break_width > 0 {
line.push(HorizontalItem::Box(HorizontalBox {
width: *no_break_width,
height: style.line_height,
depth: 0,
}));
}
}
_ => line.push(item.clone()),
}
}
while matches!(
line.last(),
Some(HorizontalItem::Glue { .. } | HorizontalItem::Penalty { .. })
@@ -230,6 +271,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum();
max_width = max_width.max(width);
@@ -249,21 +291,40 @@ pub fn text_items_with_font(
font: &crate::cmr10::Cmr10Metrics,
) -> Vec<HorizontalItem> {
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: font.space(),
stretch: font.stretch(),
shrink: font.shrink(),
});
}
let hyphenator = hyphenate::Hyphenator::plain_tex_en_us();
let caser = hyphenate::AsciiLowerCaser::default();
let words: Vec<&str> = text.split_whitespace().collect();
for (word_index, word) in words.iter().enumerate() {
if word_index > 0 {
items.push(HorizontalItem::Glue {
width: font.space(),
stretch: font.stretch(),
shrink: font.shrink(),
});
}
let points: std::collections::HashSet<usize> = if word.is_ascii()
&& word
.chars()
.all(|character| character.is_ascii_alphabetic())
&& word.len() >= 5
{
hyphenator.calculate_indices(&caser, word).collect()
} else {
std::collections::HashSet::new()
};
for (character_index, character) in word.chars().enumerate() {
items.push(HorizontalItem::Box(HorizontalBox {
width: font.width(character),
height: style.line_height,
depth: 0,
}));
let boundary = character_index + 1;
if points.contains(&boundary) && boundary >= 2 && boundary + 2 <= word.chars().count() {
items.push(HorizontalItem::Discretionary {
pre_break_width: font.width('-'),
no_break_width: 0,
});
}
}
}
while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
@@ -384,6 +445,23 @@ mod tests {
assert_eq!(counts, vec![30, 25]);
}
#[test]
fn hyphenation_inserts_discretionary_breaks() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 3_000_000,
..ParagraphStyle::default()
};
let items = text_items_with_font("hyphenation", &style, &font);
assert!(
items
.iter()
.any(|item| matches!(item, HorizontalItem::Discretionary { .. }))
);
let paragraph = layout_items(&items, &style);
assert!(paragraph.lines.len() > 1);
}
#[test]
fn cmr10_font_drives_character_widths() {
let font = crate::cmr10::Cmr10Metrics::new();
+4
View File
@@ -104,6 +104,10 @@ 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.
- M1 now inserts TeX en-US hyphenation points as `HorizontalItem::
Discretionary`: a break adds the hyphen width, a non-break keeps zero
width. The line breaker scores these breakpoints with the same glue
model as spaces.
- `Unit::halign` lays out natural column widths, multi-column spans and rule
rows as a `VerticalItem::Halign`; `Halign::cell_box` returns each cell's
aligned rectangle for a future painter. It is not yet painted by v2.