Split wide display formulas into lines

This commit is contained in:
gloamxun committed 2026-10-24 01:26:29 +08:00
1 parent 95e677b5c7
commit c9ad1e209a
6 files changed
+103 -10

No files matched your search

+43
View File
@@ -1267,6 +1267,27 @@ impl Unit {
}
/// Build a unit from a math atom using CMR10 metrics.
/// One vertical unit holding a display formula split into lines.
pub fn math_lines(
id: UnitId,
lines: &[crate::math::MathAtom],
font: &crate::cmr10::Cmr10Metrics,
) -> Self {
let items = lines
.iter()
.map(|atom| {
let math_box = crate::math::layout_math(atom, font);
VerticalItem::Math {
atom: atom.clone(),
width: math_box.width,
height: math_box.height,
depth: math_box.depth,
}
})
.collect();
Self::vertical(id, items)
}
pub fn math(
id: UnitId,
atom: crate::math::MathAtom,
@@ -7325,6 +7346,28 @@ b & 2 \\
assert!(!chunk_text[0].iter().any(|text| text == "F1"));
}
#[test]
fn display_math_splits_at_operators() {
let atom = crate::math::parse_math("a + b + c + d + e + f + g + h + i + j");
let font = Cmr10Metrics::default();
let lines = crate::math::split_math_lines(&atom, &font, 60 * 65_536);
assert!(lines.len() > 1, "lines={}", lines.len());
let atoms = |atom: &crate::math::MathAtom| match atom {
crate::math::MathAtom::Row(items) => items.len(),
_ => 1,
};
let total: usize = lines.iter().map(atoms).sum();
assert_eq!(total, atoms(&atom));
for line in &lines {
let width = crate::math::layout_math(line, &font).width;
let single = match line {
crate::math::MathAtom::Row(items) => items.len() <= 1,
_ => true,
};
assert!(single || width <= 60 * 65_536, "width={width}");
}
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
+30
View File
@@ -170,6 +170,36 @@ fn scaled(value: i64, factor: f64) -> i64 {
(value as f64 * factor).round() as i64
}
/// Split a display formula into lines that fit `max_width`.
///
/// TeX itself never breaks display math automatically; this mirrors the
/// explicit `\\split`/`align` behaviour by breaking after a top-level
/// binary or relation operator once the line would overflow.
pub fn split_math_lines(atom: &MathAtom, font: &Cmr10Metrics, max_width: i64) -> Vec<MathAtom> {
let atoms = match atom {
MathAtom::Row(items) => items.clone(),
other => vec![other.clone()],
};
if layout_math(atom, font).width <= max_width {
return vec![atom.clone()];
}
let mut lines: Vec<Vec<MathAtom>> = Vec::new();
let mut current: Vec<MathAtom> = Vec::new();
for item in atoms {
let mut candidate = current.clone();
candidate.push(item.clone());
let candidate_width = layout_math(&MathAtom::Row(candidate.clone()), font).width;
if !current.is_empty() && candidate_width > max_width {
lines.push(std::mem::take(&mut current));
}
current.push(item);
}
if !current.is_empty() {
lines.push(current);
}
lines.into_iter().map(MathAtom::Row).collect()
}
fn atom_class(atom: &MathAtom) -> MathClass {
match atom {
MathAtom::Symbol(character) => math_class(*character),