diff --git a/crates/typst-layout/src/inline/shaping.rs b/crates/typst-layout/src/inline/shaping.rs index 6e77a80e7..2a1fc8586 100644 --- a/crates/typst-layout/src/inline/shaping.rs +++ b/crates/typst-layout/src/inline/shaping.rs @@ -1044,9 +1044,8 @@ fn calculate_adjustability(ctx: &mut ShapingContext, lang: Lang, region: Option< /// Difference between non-breaking and normal space. fn nbsp_delta(font: &Font) -> Option { - let space = font.ttf().glyph_index(' ')?.0; let nbsp = font.ttf().glyph_index('\u{00A0}')?.0; - Some(font.advance(nbsp)? - font.advance(space)?) + Some(font.advance(nbsp)? - font.space_width()?) } /// Returns true if all glyphs in `glyphs` have ranges within the range `range`. diff --git a/crates/typst-layout/src/math/mod.rs b/crates/typst-layout/src/math/mod.rs index b18bd98d0..5fd22e578 100644 --- a/crates/typst-layout/src/math/mod.rs +++ b/crates/typst-layout/src/math/mod.rs @@ -373,7 +373,6 @@ struct MathContext<'a, 'v, 'e> { // Font-related. font: &'a Font, constants: ttf_parser::math::Constants<'a>, - space_width: Em, // Mutable. fragments: Vec, } @@ -386,15 +385,10 @@ impl<'a, 'v, 'e> MathContext<'a, 'v, 'e> { base: Size, font: &'a Font, ) -> Self { - let math_table = font.ttf().tables().math.unwrap(); - let constants = math_table.constants.unwrap(); - - let ttf = font.ttf(); - let space_width = ttf - .glyph_index(' ') - .and_then(|id| ttf.glyph_hor_advance(id)) - .map(|advance| font.to_em(advance)) - .unwrap_or(THICK); + // These unwraps are safe as the font given is one returned by the + // find_math_font function, which only returns fonts that have a math + // constants table. + let constants = font.ttf().tables().math.unwrap().constants.unwrap(); Self { engine, @@ -402,7 +396,6 @@ impl<'a, 'v, 'e> MathContext<'a, 'v, 'e> { region: Region::new(base, Axes::splat(false)), font, constants, - space_width, fragments: vec![], } } @@ -501,7 +494,8 @@ fn layout_realized( if let Some(elem) = elem.to_packed::() { ctx.push(MathFragment::Tag(elem.tag.clone())); } else if elem.is::() { - ctx.push(MathFragment::Space(ctx.space_width.resolve(styles))); + let space_width = ctx.font.space_width().unwrap_or(THICK); + ctx.push(MathFragment::Space(space_width.resolve(styles))); } else if elem.is::() { ctx.push(MathFragment::Linebreak); } else if let Some(elem) = elem.to_packed::() { diff --git a/crates/typst-library/src/text/font/mod.rs b/crates/typst-library/src/text/font/mod.rs index afa92e778..b2afb0466 100644 --- a/crates/typst-library/src/text/font/mod.rs +++ b/crates/typst-library/src/text/font/mod.rs @@ -113,6 +113,11 @@ impl Font { .map(|units| self.to_em(units)) } + /// Look up the width of a space. + pub fn space_width(&self) -> Option { + self.0.ttf.glyph_index(' ').and_then(|id| self.advance(id.0)) + } + /// Lookup a name by id. pub fn find_name(&self, id: u16) -> Option { find_name(&self.0.ttf, id)