Hyphenate native XeTeX OpenType words during line breaking
This commit is contained in:
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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2175,6 +2175,42 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### XeTeX OpenType 自动断词
|
||||
|
||||
原生断行的容差轮从实际胶、语言节点、字符小写码和字体整数选取
|
||||
OpenType 词。匹配 INITEX 载入的语言规则和任务内的断词例外词。
|
||||
保留 UTF-16 长度限制、最小词段、大小写、原字标点和
|
||||
`\XeTeXhyphenatablelength`。独立塑形普通词段及真实字体的行尾
|
||||
连字符,参与同一个尺寸、断行和绘制流程。分段保留来源范围,新增的
|
||||
连字符记录断词派生关系。现有 XeTeX 镜像可继续使用默认长度。要通过
|
||||
TeX 命令改写此长度,使用包含该原语的新镜像。
|
||||
[上游第二遍断行](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L21497-L21619)
|
||||
[上游词段与离散断点](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L21785-L21835)
|
||||
|
||||
同源 Latin Modern 用例的 12 页逐条对齐 XDV 字形编号及 scaled-point 坐标。
|
||||
用例覆盖同一词在不同语言中的规则、标点、大小写、禁用及自定义
|
||||
连字符、词长、右侧最小词段、预容差时保留未断词形和相同位置的重复
|
||||
例外标记。五项既有 TFM 断词测试通过。三页项目的子文件依次
|
||||
修改小写码映射、撤销修改和覆盖断词例外,均复用 90 步并只发第二页。
|
||||
每次修订的 PDF、SVG 和来源映射与独立全量编译完全一致。
|
||||
回执 `target/p3-xetex-native-hyphenation/receipt.json` 的 SHA-256 为
|
||||
`2aa5dcdbb2a52bcd0bfe69eb5605e7ce2e8089157495104dcc2035be4d6e06d9`。
|
||||
|
||||
复用原 ACL 源码、字体、schema71 和已收敛的 BibTeX 产物。
|
||||
`.aux`、`.out`、`.bbl` 继续与参考逐字节一致。ACL 参考的英语
|
||||
断词在 LuaLaTex、languages 和 argues 处进入相同的行。配对词框
|
||||
最大坐标差为 12.35 bp,前版为 18.69 bp,整页等价尚未通过。
|
||||
|
||||
随后用同一字体文件冻结原样印地语和阿拉伯语文字的三页最小布局。
|
||||
印地语 25 个字形编号一致,使用 Lohit Devanagari 的单行原生基线
|
||||
比参考向下 78080 sp。参考 XeTeX 经 FreeType 取 ascent。Lohit 的
|
||||
OS/2 标有 USE_TYPO_METRICS,typo ascender 999,hhea ascender
|
||||
1121,EM 1024,两个度量按 10 pt 换算的差正是 78080 sp。
|
||||
同一对照中的阿拉伯语独立字盒与显式 RTL 字盒字形坐标一致。后续先接
|
||||
实际字体垂直度量,再比对原样混合段落与 PDF 来源映射。证据在
|
||||
`target/p3-xetex-multilingual-shaping/comparison.json`。
|
||||
[XeTeX FreeType 字体度量](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeXFontInst.cpp#L329-L335)
|
||||
|
||||
### XDV 链接注释与实际矩形
|
||||
|
||||
原生发页以实际字形度量和 DVI 列表层级生成 `pdf:bann`、
|
||||
|
||||
@@ -758,6 +758,16 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
|
||||
`target/p3-xdv-annotation/receipt.json`。
|
||||
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
|
||||
|
||||
#### OpenType 自动断词复编
|
||||
|
||||
同一 schema71 镜像和十份 ACL 源文件原样复编,使用已收敛的实际
|
||||
BibTeX 产物。`.aux`、`.out`、`.bbl` 仍逐字节一致,输出一页。
|
||||
LuaLaTex、languages 和 argues 的断行与冻结参考一致。PDF 提取的
|
||||
119 个参考词中 101 个可与原生顺序配对,前版为 95 个。配对词框
|
||||
最大坐标偏差从 18.69 bp 降到 12.35 bp。印地语基线和混合语言
|
||||
字形提取仍待对照,当前整页版面门禁保持未通过。
|
||||
阶段回执 `target/p3-xetex-native-hyphenation/receipt.json`。
|
||||
|
||||
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
|
||||
|
||||
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。
|
||||
|
||||
Reference in new issue
Block a user