Hyphenate native XeTeX OpenType words during line breaking

This commit is contained in:
gloamxun committed 2026-11-25 21:37:05 +08:00
1 parent 20986b2fd5
commit c97e0e7279
8 files changed
+321 -16

No files matched your search

@@ -19,6 +19,10 @@ impl Executor {
) {
return self.fail("patterns requires a begin-group token");
}
if self.state.input_profile() == InputProfile::XeTeX {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXhyphenatablelength));
}
let max_length = super::super::hyphenation::max_word_length(&self.state);
let (mut letters, mut weights, mut digit) = (Vec::new(), vec![0], false);
loop {
let t = self.required_expanded(files)?.token;
@@ -50,7 +54,7 @@ impl Executor {
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
if !digit && c.is_ascii_digit() {
if letters.len() < 63 {
if letters.len() < max_length {
*weights.last_mut().unwrap() = c as u8 - b'0';
digit = true;
}
@@ -65,7 +69,7 @@ impl Executor {
}
n
};
if letters.len() < 63 {
if letters.len() < max_length {
letters.push(c);
weights.push(0);
digit = false;
@@ -447,10 +447,15 @@ impl Executor {
self.reads.insert(Dependency::ParagraphShape);
self.reads.insert(Dependency::Hyphenation);
for n in &b.nodes {
if let super::super::paragraph::TextNode::Glyph { original, .. } = n {
for c in original.chars() {
self.reads.insert(Dependency::CaseCode(CaseCode::Lower, c));
let text = match n {
TextNode::Glyph { original, .. } => original,
TextNode::OpenType(run) if self.state.input_profile() == InputProfile::XeTeX => {
&run.text
}
_ => continue,
};
for c in text.chars() {
self.reads.insert(Dependency::CaseCode(CaseCode::Lower, c));
}
}
self.reads.insert(Dependency::FontResources);
@@ -727,7 +732,12 @@ impl Executor {
);
self.reads
.insert(Dependency::Parameter(Parameter::Language));
let (mut word, mut points, mut count) = (String::new(), Vec::new(), 0);
let xetex = self.state.input_profile() == InputProfile::XeTeX;
if xetex {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXhyphenatablelength));
}
let max_length = super::super::hyphenation::max_word_length(&self.state);
let (mut word, mut points, mut count, mut units) = (String::new(), Vec::new(), 0, 0);
loop {
let t = self.required_expanded(files)?.token;
let meaning = self.meaning(&t);
@@ -750,20 +760,20 @@ impl Executor {
word.clear();
points.clear();
count = 0;
units = 0;
continue;
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => c,
Meaning::CharGiven(c) => self.scalar_character(c, t.span)?,
Meaning::Primitive(Primitive::Char) => {
let n = self.integer(files)?;
char::from(u8::try_from(n).map_err(|_| {
self.error("hyphenation character must be in 0..255", self.current)
})?)
let maximum = if xetex { 0x10FFFF } else { 255 };
let n = self.character_number("hyphenation character", maximum, files)?;
self.scalar_character(n, t.span)?
}
_ => return self.fail("improper token in hyphenation exceptions"),
};
if c == '-' {
if count < 63 {
if units < max_length {
points.push(count);
}
continue;
@@ -773,9 +783,12 @@ impl Executor {
if lower == 0 {
return self.fail("hyphenation character must have nonzero lccode");
}
if count < 63 {
word.push(char::from_u32(lower).expect("validated case code"));
let lower = char::from_u32(lower).expect("validated case code");
let size = if xetex { lower.len_utf16() } else { 1 };
if units + size <= max_length {
word.push(lower);
count += 1;
units += size;
}
}
Ok(())
@@ -35,6 +35,14 @@ impl HyphenationLanguage {
}
}
}
pub(super) fn max_word_length(state: &State) -> usize {
if state.input_profile() == InputProfile::XeTeX {
state.parameter(Parameter::XeTeXhyphenatablelength).width().clamp(0, 4095) as usize
} else {
63
}
}
pub(super) fn normalize_language(n: i32) -> u8 {
if (1..=255).contains(&n) { n as u8 } else { 0 }
}
@@ -6,6 +6,7 @@ use crate::opentype::{OpenTypeFont, OpenTypeRun};
mod break_cache;
mod expansion;
mod native_hyphenation;
mod protrusion;
pub(super) use protrusion::stored_margin_kern;
use break_cache::BreakNode;
@@ -1262,6 +1263,11 @@ pub(super) fn finish(
steps,
step_limit,
)?;
if state.input_profile() == InputProfile::XeTeX {
native_hyphenation::add_hyphens(
&mut b.nodes, state, b.initial_language, steps, step_limit,
)?;
}
}
trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?;
if let Some(path) = break_cache::solve(
@@ -1425,6 +1431,7 @@ fn add_hyphens(
steps: &mut usize,
step_limit: usize,
) -> Result<(), String> {
let max_length = super::hyphenation::max_word_length(state);
let (mut start, mut i) = (0, 0);
let mut edits = Vec::new();
let mut word_font = None;
@@ -1454,7 +1461,7 @@ fn add_hyphens(
})
.take_while(|s| {
let n = s.chars().count();
if letters + n > 63 {
if letters + n > max_length {
false
} else {
letters += n;
@@ -1551,7 +1558,7 @@ fn add_hyphens(
component_sources,
..
} => {
if components.len() + original.chars().count() > 63 {
if components.len() + original.chars().count() > max_length {
break;
}
components.extend(original.chars().enumerate().map(|(k, c)| {
@@ -0,0 +1,222 @@
//! Second-pass hyphenation of XeTeX native word nodes.
use super::*;
use crate::provenance::Derivation;
pub(super) fn add_hyphens(
nodes: &mut Vec<TextNode>,
state: &State,
mut language: HyphenationLanguage,
steps: &mut usize,
step_limit: usize,
) -> Result<(), String> {
let max_length = super::super::hyphenation::max_word_length(state);
let uppercase = state.parameter(Parameter::Uchyph).width() > 0;
let use_glyph_metrics = state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
let mut after_glue = false;
let mut auto_breaking = true;
let mut edits = Vec::new();
for (index, node) in nodes.iter().enumerate() {
match node {
TextNode::Language(next) => language = *next,
TextNode::Direction(_)
| TextNode::Output(_)
| TextNode::Kern {
explicit: false, ..
} => {}
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) => {
after_glue = auto_breaking;
}
TextNode::MathBoundary { after, .. } => {
auto_breaking = *after;
after_glue = false;
}
TextNode::Glyph { original, .. }
if after_glue
&& original
.chars()
.next()
.is_none_or(|c| state.case_code(CaseCode::Lower, c) == 0) => {}
TextNode::OpenType(run) if after_glue => {
let lower =
|c| char::from_u32(state.case_code(CaseCode::Lower, c)).filter(|c| *c != '\0');
let Some((start, first, first_lower)) = run
.text
.char_indices()
.find_map(|(at, c)| lower(c).map(|value| (at, c, value)))
else {
// A punctuation-only native node does not end the search.
continue;
};
after_glue = false;
let left = usize::from(language.left_min);
let right = usize::from(language.right_min);
if (!uppercase && first != first_lower)
|| left + right > max_length
|| !following_nodes_allow_hyphenation(&nodes[index + 1..])
{
continue;
}
let Some(hyphen) = u32::try_from(state.font_integers(run.font.id).hyphen)
.ok()
.and_then(char::from_u32)
else {
continue;
};
// Match normalized letters in the language trie but preserve UTF-16
// lengths for XeTeX's limits and byte offsets for shaping/provenance.
let mut word = String::new();
let mut boundaries = vec![(start, 0)];
let mut end = run.text.len();
let mut units = 0;
for (offset, c) in run.text[start..].char_indices() {
let at = start + offset;
let Some(value) = lower(c) else {
end = at;
break;
};
if units + c.len_utf16() > max_length {
break;
}
units += c.len_utf16();
word.push(value);
boundaries.push((at + c.len_utf8(), units));
}
let mut points = if units >= left + right {
state.hyphenation.points(language.language, &word)
} else {
Vec::new()
};
points.dedup();
let mut breaks = points
.into_iter()
.filter_map(|point| {
let &(at, before) = boundaries.get(point)?;
(before >= left && units - before >= right).then_some(at)
})
.peekable();
if start == 0 && end == run.text.len() && breaks.peek().is_none() {
continue;
}
let mut fragments = Vec::new();
let mut from = 0;
let mut sources = run.sources.iter().peekable();
let mut last_source = None;
// Isolated punctuation and the ordinary fragments are measured
// independently, even if the chosen line never breaks at a hyphen.
for (to, discretionary) in (start != 0)
.then_some((start, false))
.into_iter()
.chain(breaks.map(|at| (at, true)))
.chain((end != run.text.len()).then_some((end, false)))
.chain([(run.text.len(), false)])
{
let mut fragment_sources = Vec::new();
while let Some((at, source)) = sources.next_if(|(at, _)| *at < to) {
fragment_sources.push((*at - from, source.clone()));
last_source = Some(source);
}
fragments.push(shape(
run,
run.text[from..to].to_owned(),
fragment_sources,
use_glyph_metrics,
steps,
step_limit,
)?);
from = to;
if discretionary {
let mut source = last_source.cloned().unwrap_or_default();
if let Some((_, next)) = sources.peek() {
source.merge(next);
}
let (text, sources) = run.font.map_text(
hyphen.to_string(),
vec![(0, source.derived(Derivation::Hyphenation))],
)?;
fragments.push(TextNode::Discretionary {
font: run.font.id,
automatic: true,
hyphen_char: Some(hyphen),
pre_break: vec![shape(
run,
text,
sources,
use_glyph_metrics,
steps,
step_limit,
)?],
post_break: Vec::new(),
replacement_count: 0,
});
}
}
edits.push((index, fragments));
}
_ => after_glue = false,
}
}
if !edits.is_empty() {
let mut edits = edits.into_iter().peekable();
let mut original = std::mem::take(nodes);
for (index, node) in original.drain(..).enumerate() {
if let Some((_, replacement)) = edits.next_if(|(at, _)| *at == index) {
nodes.extend(replacement);
} else {
nodes.push(node);
}
}
}
Ok(())
}
fn following_nodes_allow_hyphenation(nodes: &[TextNode]) -> bool {
nodes
.iter()
.find(|node| {
!matches!(
node,
TextNode::Glyph { .. }
| TextNode::Kern {
explicit: false,
..
}
)
})
.is_none_or(|node| {
matches!(
node,
TextNode::OpenType(_)
| TextNode::Language(_)
| TextNode::Adjustment(_)
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Output(_)
| TextNode::Glue(_)
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
| TextNode::Kern { explicit: true, .. }
)
})
}
fn shape(
run: &OpenTypeRun,
text: String,
sources: Vec<(usize, PaintSource)>,
use_glyph_metrics: bool,
steps: &mut usize,
step_limit: usize,
) -> Result<TextNode, String> {
let run = run.font.shape_mapped(text, sources, use_glyph_metrics)?;
*steps = steps
.checked_add(run.glyphs.len())
.filter(|steps| *steps <= step_limit)
.ok_or("native OpenType hyphenation shaping step limit exceeded")?;
Ok(TextNode::OpenType(Arc::new(run)))
}
@@ -125,6 +125,7 @@ pub enum Parameter {
TeXXeTstate,
XeTeXinterchartokenstate,
XeTeXprotrudechars,
XeTeXhyphenatablelength,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -157,12 +158,13 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 5] = [
pub(super) const XETEX: [Self; 6] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
Self::XeTeXhyphenatablelength,
];
pub const ALL: &'static [Self] = &[
@@ -286,6 +288,7 @@ impl Parameter {
Self::TeXXeTstate,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
Self::XeTeXhyphenatablelength,
];
pub fn name(self) -> String {
match self {
@@ -294,6 +297,7 @@ impl Parameter {
Self::TeXXeTstate => "TeXXeTstate".into(),
Self::XeTeXinterchartokenstate => "XeTeXinterchartokenstate".into(),
Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(),
Self::XeTeXhyphenatablelength => "XeTeXhyphenatablelength".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
@@ -367,6 +371,7 @@ impl Parameter {
Self::Hangafter => 1,
Self::Maxdeadcycles => 25,
Self::Showstream => -1,
Self::XeTeXhyphenatablelength => 63,
_ => 0,
})
}