Offset math scripts by the base italic correction

This commit is contained in:
gloamxun committed 2026-10-20 21:34:09 +08:00
1 parent 6a7e79fa03
commit 6dd4f6bf83
3 files changed
+34 -5

No files matched your search

+29 -1
View File
@@ -197,6 +197,22 @@ pub fn delimiter_scale(body: &MathBox) -> f64 {
}
/// Lay out a math atom at the current style size.
/// TeX italic correction of the rightmost glyph of an atom. It is added
/// before a superscript/subscript so italic bases do not collide with scripts.
pub fn italic_correction(atom: &MathAtom, font: &Cmr10Metrics) -> i64 {
match atom {
MathAtom::Symbol(character) => font.italic(*character),
MathAtom::Row(atoms) => atoms
.iter()
.rev()
.map(|atom| italic_correction(atom, font))
.find(|correction| *correction != 0)
.unwrap_or(0),
MathAtom::Script { base, .. } => italic_correction(base, font),
_ => 0,
}
}
pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
match atom {
MathAtom::Symbol(character) => {
@@ -428,8 +444,9 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
.max(sup_box.as_ref().map(|boxed| boxed.width).unwrap_or(0));
let sup_height = sup_box.as_ref().map_or(0, |boxed| boxed.height);
let sub_depth = sub_box.as_ref().map_or(0, |boxed| boxed.depth);
let italic = italic_correction(base, font);
MathBox {
width: base_box.width + scaled(script_width, 0.7),
width: base_box.width + italic + scaled(script_width, 0.7),
height: base_box
.height
.max(scaled(base_box.height, 0.6) + scaled(sup_height, 0.7)),
@@ -1121,6 +1138,17 @@ fn parse_script(chars: &[char], index: usize) -> (MathAtom, usize) {
mod tests {
use super::*;
#[test]
fn italic_base_offsets_scripts() {
let font = Cmr10Metrics::default();
let base = parse_math("f");
let scripted = parse_math("f^2");
let italic = italic_correction(&base, &font);
assert!(italic > 0);
let base_box = layout_math(&base, &font);
let scripted_box = layout_math(&scripted, &font);
assert!(scripted_box.width >= base_box.width + italic);
}
#[test]
fn math_symbol_uses_font_width() {
let font = Cmr10Metrics::default();