From 09c831d3b32935fe162f198e3512e1e7cd6647db Mon Sep 17 00:00:00 2001 From: Malo <57839069+MDLC01@users.noreply.github.com> Date: Wed, 2 Jul 2025 09:00:45 +0100 Subject: [PATCH] Use "subs" and "sups" font features for typographic scripts (#5777) --- crates/typst-layout/src/inline/collect.rs | 4 +- crates/typst-layout/src/inline/line.rs | 43 ++- crates/typst-layout/src/inline/linebreak.rs | 6 +- crates/typst-layout/src/inline/mod.rs | 2 +- crates/typst-layout/src/inline/prepare.rs | 4 +- crates/typst-layout/src/inline/shaping.rs | 143 +++++++-- crates/typst-layout/src/math/fragment.rs | 6 +- crates/typst-library/src/layout/em.rs | 17 +- crates/typst-library/src/text/font/mod.rs | 39 +++ crates/typst-library/src/text/mod.rs | 6 + crates/typst-library/src/text/shift.rs | 298 ++++++++++-------- .../ref/issue-4454-footnote-ref-numbering.png | Bin 841 -> 903 bytes tests/ref/long-scripts.png | Bin 0 -> 956 bytes tests/ref/script-metrics-bundeled-fonts.png | Bin 0 -> 3110 bytes tests/ref/sub-super-italic-compensation.png | Bin 0 -> 1281 bytes tests/ref/sub-super-non-typographic.png | Bin 311 -> 318 bytes tests/ref/sub-super-typographic.png | Bin 0 -> 1337 bytes tests/ref/sub-super.png | Bin 1114 -> 1189 bytes tests/ref/super-highlight.png | Bin 0 -> 1353 bytes tests/ref/super-underline.png | Bin 1833 -> 835 bytes tests/suite/text/shift.typ | 79 ++++- 21 files changed, 450 insertions(+), 197 deletions(-) create mode 100644 tests/ref/long-scripts.png create mode 100644 tests/ref/script-metrics-bundeled-fonts.png create mode 100644 tests/ref/sub-super-italic-compensation.png create mode 100644 tests/ref/sub-super-typographic.png create mode 100644 tests/ref/super-highlight.png diff --git a/crates/typst-layout/src/inline/collect.rs b/crates/typst-layout/src/inline/collect.rs index 5a1b7b4fc..829f64b66 100644 --- a/crates/typst-layout/src/inline/collect.rs +++ b/crates/typst-layout/src/inline/collect.rs @@ -206,7 +206,7 @@ pub fn collect<'a>( } InlineItem::Frame(mut frame) => { frame.modify(&FrameModifiers::get_in(styles)); - apply_baseline_shift(&mut frame, styles); + apply_shift(&engine.world, &mut frame, styles); collector.push_item(Item::Frame(frame)); } } @@ -221,7 +221,7 @@ pub fn collect<'a>( let mut frame = layout_and_modify(styles, |styles| { layout_box(elem, engine, loc, styles, region) })?; - apply_baseline_shift(&mut frame, styles); + apply_shift(&engine.world, &mut frame, styles); collector.push_item(Item::Frame(frame)); } } else if let Some(elem) = child.to_packed::() { diff --git a/crates/typst-layout/src/inline/line.rs b/crates/typst-layout/src/inline/line.rs index 7bf4d4c73..b850e50ee 100644 --- a/crates/typst-layout/src/inline/line.rs +++ b/crates/typst-layout/src/inline/line.rs @@ -5,7 +5,7 @@ use typst_library::engine::Engine; use typst_library::introspection::{SplitLocator, Tag}; use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point}; use typst_library::model::ParLineMarker; -use typst_library::text::{Lang, TextElem}; +use typst_library::text::{variant, Lang, TextElem}; use typst_utils::Numeric; use super::*; @@ -330,7 +330,7 @@ fn adjust_cj_at_line_start(p: &Preparation, items: &mut Items) { let glyph = shaped.glyphs.to_mut().first_mut().unwrap(); let shrink = glyph.shrinkability().0; glyph.shrink_left(shrink); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } else if p.config.cjk_latin_spacing && glyph.is_cj_script() && glyph.x_offset > Em::zero() @@ -342,7 +342,7 @@ fn adjust_cj_at_line_start(p: &Preparation, items: &mut Items) { glyph.x_advance -= shrink; glyph.x_offset = Em::zero(); glyph.adjustability.shrinkability.0 = Em::zero(); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } } @@ -360,7 +360,7 @@ fn adjust_cj_at_line_end(p: &Preparation, items: &mut Items) { let shrink = glyph.shrinkability().1; let punct = shaped.glyphs.to_mut().last_mut().unwrap(); punct.shrink_right(shrink); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(punct.size); } else if p.config.cjk_latin_spacing && glyph.is_cj_script() && (glyph.x_advance - glyph.x_offset) > Em::one() @@ -371,7 +371,7 @@ fn adjust_cj_at_line_end(p: &Preparation, items: &mut Items) { let glyph = shaped.glyphs.to_mut().last_mut().unwrap(); glyph.x_advance -= shrink; glyph.adjustability.shrinkability.1 = Em::zero(); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } } @@ -412,9 +412,30 @@ fn should_repeat_hyphen(pred_line: &Line, text: &str) -> bool { } } -/// Apply the current baseline shift to a frame. -pub fn apply_baseline_shift(frame: &mut Frame, styles: StyleChain) { - frame.translate(Point::with_y(TextElem::baseline_in(styles))); +/// Apply the current baseline shift and italic compensation to a frame. +pub fn apply_shift<'a>( + world: &Tracked<'a, dyn World + 'a>, + frame: &mut Frame, + styles: StyleChain, +) { + let mut baseline = TextElem::baseline_in(styles); + let mut compensation = Abs::zero(); + if let Some(scripts) = TextElem::shift_settings_in(styles) { + let font_metrics = TextElem::font_in(styles) + .into_iter() + .find_map(|family| { + world + .book() + .select(family.as_str(), variant(styles)) + .and_then(|id| world.font(id)) + }) + .map_or(*scripts.kind.default_metrics(), |f| { + *scripts.kind.read_metrics(f.metrics()) + }); + baseline -= scripts.shift.unwrap_or(font_metrics.vertical_offset).resolve(styles); + compensation += font_metrics.horizontal_offset.resolve(styles); + } + frame.translate(Point::new(compensation, baseline)); } /// Commit to a line and build its frame. @@ -444,7 +465,7 @@ pub fn commit( && TextElem::overhang_in(text.styles) && (line.items.len() > 1 || text.glyphs.len() > 1) { - let amount = overhang(glyph.c) * glyph.x_advance.at(text.size); + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); offset -= amount; remaining += amount; } @@ -458,7 +479,7 @@ pub fn commit( && TextElem::overhang_in(text.styles) && (line.items.len() > 1 || text.glyphs.len() > 1) { - let amount = overhang(glyph.c) * glyph.x_advance.at(text.size); + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); remaining += amount; } } @@ -519,7 +540,7 @@ pub fn commit( let mut frame = layout_and_modify(*styles, |styles| { layout_box(elem, engine, loc.relayout(), styles, region) })?; - apply_baseline_shift(&mut frame, *styles); + apply_shift(&engine.world, &mut frame, *styles); push(&mut offset, frame, idx); } else { offset += amount; diff --git a/crates/typst-layout/src/inline/linebreak.rs b/crates/typst-layout/src/inline/linebreak.rs index ada048c7d..709745edc 100644 --- a/crates/typst-layout/src/inline/linebreak.rs +++ b/crates/typst-layout/src/inline/linebreak.rs @@ -927,9 +927,9 @@ impl Estimates { let byte_len = g.range.len(); let stretch = g.stretchability().0 + g.stretchability().1; let shrink = g.shrinkability().0 + g.shrinkability().1; - widths.push(byte_len, g.x_advance.at(shaped.size)); - stretchability.push(byte_len, stretch.at(shaped.size)); - shrinkability.push(byte_len, shrink.at(shaped.size)); + widths.push(byte_len, g.x_advance.at(g.size)); + stretchability.push(byte_len, stretch.at(g.size)); + shrinkability.push(byte_len, shrink.at(g.size)); justifiables.push(byte_len, g.is_justifiable() as usize); } } else { diff --git a/crates/typst-layout/src/inline/mod.rs b/crates/typst-layout/src/inline/mod.rs index 6cafb9b00..506fa5eac 100644 --- a/crates/typst-layout/src/inline/mod.rs +++ b/crates/typst-layout/src/inline/mod.rs @@ -29,7 +29,7 @@ use typst_utils::{Numeric, SliceExt}; use self::collect::{collect, Item, Segment, SpanMapper}; use self::deco::decorate; use self::finalize::finalize; -use self::line::{apply_baseline_shift, commit, line, Line}; +use self::line::{apply_shift, commit, line, Line}; use self::linebreak::{linebreak, Breakpoint}; use self::prepare::{prepare, Preparation}; use self::shaping::{ diff --git a/crates/typst-layout/src/inline/prepare.rs b/crates/typst-layout/src/inline/prepare.rs index 5d7fcd7cb..ab39bdb14 100644 --- a/crates/typst-layout/src/inline/prepare.rs +++ b/crates/typst-layout/src/inline/prepare.rs @@ -144,7 +144,7 @@ fn add_cjk_latin_spacing(items: &mut [(Range, Item)]) { // The spacing is default to 1/4 em, and can be shrunk to 1/8 em. glyph.x_advance += Em::new(0.25); glyph.adjustability.shrinkability.1 += Em::new(0.125); - text.width += Em::new(0.25).at(text.size); + text.width += Em::new(0.25).at(glyph.size); } // Case 2: Latin followed by a CJ character @@ -152,7 +152,7 @@ fn add_cjk_latin_spacing(items: &mut [(Range, Item)]) { glyph.x_advance += Em::new(0.25); glyph.x_offset += Em::new(0.25); glyph.adjustability.shrinkability.0 += Em::new(0.125); - text.width += Em::new(0.25).at(text.size); + text.width += Em::new(0.25).at(glyph.size); } prev = Some(glyph); diff --git a/crates/typst-layout/src/inline/shaping.rs b/crates/typst-layout/src/inline/shaping.rs index 935a86b38..48747cd50 100644 --- a/crates/typst-layout/src/inline/shaping.rs +++ b/crates/typst-layout/src/inline/shaping.rs @@ -3,14 +3,15 @@ use std::fmt::{self, Debug, Formatter}; use std::sync::Arc; use az::SaturatingAs; -use rustybuzz::{BufferFlags, ShapePlan, UnicodeBuffer}; +use rustybuzz::{BufferFlags, Feature, ShapePlan, UnicodeBuffer}; +use ttf_parser::gsub::SubstitutionSubtable; use ttf_parser::Tag; use typst_library::engine::Engine; use typst_library::foundations::{Smart, StyleChain}; use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Size}; use typst_library::text::{ families, features, is_default_ignorable, language, variant, Font, FontFamily, - FontVariant, Glyph, Lang, Region, TextEdgeBounds, TextElem, TextItem, + FontVariant, Glyph, Lang, Region, ShiftSettings, TextEdgeBounds, TextElem, TextItem, }; use typst_library::World; use typst_utils::SliceExt; @@ -41,8 +42,6 @@ pub struct ShapedText<'a> { pub styles: StyleChain<'a>, /// The font variant. pub variant: FontVariant, - /// The font size. - pub size: Abs, /// The width of the text's bounding box. pub width: Abs, /// The shaped glyphs. @@ -62,6 +61,8 @@ pub struct ShapedGlyph { pub x_offset: Em, /// The vertical offset of the glyph. pub y_offset: Em, + /// The font size for the glyph. + pub size: Abs, /// The adjustability of the glyph. pub adjustability: Adjustability, /// The byte range of this glyph's cluster in the full inline layout. A @@ -222,14 +223,17 @@ impl<'a> ShapedText<'a> { let mut frame = Frame::soft(size); frame.set_baseline(top); + let size = TextElem::size_in(self.styles); let shift = TextElem::baseline_in(self.styles); let decos = TextElem::deco_in(self.styles); let fill = TextElem::fill_in(self.styles); let stroke = TextElem::stroke_in(self.styles); let span_offset = TextElem::span_offset_in(self.styles); - for ((font, y_offset), group) in - self.glyphs.as_ref().group_by_key(|g| (g.font.clone(), g.y_offset)) + for ((font, y_offset, glyph_size), group) in self + .glyphs + .as_ref() + .group_by_key(|g| (g.font.clone(), g.y_offset, g.size)) { let mut range = group[0].range.clone(); for glyph in group { @@ -237,7 +241,7 @@ impl<'a> ShapedText<'a> { range.end = range.end.max(glyph.range.end); } - let pos = Point::new(offset, top + shift - y_offset.at(self.size)); + let pos = Point::new(offset, top + shift - y_offset.at(size)); let glyphs: Vec = group .iter() .map(|shaped: &ShapedGlyph| { @@ -257,11 +261,11 @@ impl<'a> ShapedText<'a> { adjustability_right * justification_ratio; if shaped.is_justifiable() { justification_right += - Em::from_length(extra_justification, self.size) + Em::from_abs(extra_justification, glyph_size) } - frame.size_mut().x += justification_left.at(self.size) - + justification_right.at(self.size); + frame.size_mut().x += justification_left.at(glyph_size) + + justification_right.at(glyph_size); // We may not be able to reach the offset completely if // it exceeds u16, but better to have a roughly correct @@ -304,7 +308,7 @@ impl<'a> ShapedText<'a> { let item = TextItem { font, - size: self.size, + size: glyph_size, lang: self.lang, region: self.region, fill: fill.clone(), @@ -336,12 +340,13 @@ impl<'a> ShapedText<'a> { let mut top = Abs::zero(); let mut bottom = Abs::zero(); + let size = TextElem::size_in(self.styles); let top_edge = TextElem::top_edge_in(self.styles); let bottom_edge = TextElem::bottom_edge_in(self.styles); // Expand top and bottom by reading the font's vertical metrics. let mut expand = |font: &Font, bounds: TextEdgeBounds| { - let (t, b) = font.edges(top_edge, bottom_edge, self.size, bounds); + let (t, b) = font.edges(top_edge, bottom_edge, size, bounds); top.set_max(t); bottom.set_max(b); }; @@ -388,18 +393,16 @@ impl<'a> ShapedText<'a> { pub fn stretchability(&self) -> Abs { self.glyphs .iter() - .map(|g| g.stretchability().0 + g.stretchability().1) - .sum::() - .at(self.size) + .map(|g| (g.stretchability().0 + g.stretchability().1).at(g.size)) + .sum() } /// The shrinkability of the text pub fn shrinkability(&self) -> Abs { self.glyphs .iter() - .map(|g| g.shrinkability().0 + g.shrinkability().1) - .sum::() - .at(self.size) + .map(|g| (g.shrinkability().0 + g.shrinkability().1).at(g.size)) + .sum() } /// Reshape a range of the shaped text, reusing information from this @@ -418,9 +421,8 @@ impl<'a> ShapedText<'a> { lang: self.lang, region: self.region, styles: self.styles, - size: self.size, variant: self.variant, - width: glyphs.iter().map(|g| g.x_advance).sum::().at(self.size), + width: glyphs_width(glyphs), glyphs: Cow::Borrowed(glyphs), } } else { @@ -484,13 +486,15 @@ impl<'a> ShapedText<'a> { // that subtracting either of the endpoints by self.base doesn't // underflow. See . .unwrap_or_else(|| self.base..self.base); - self.width += x_advance.at(self.size); + let size = TextElem::size_in(self.styles); + self.width += x_advance.at(size); let glyph = ShapedGlyph { font, glyph_id: glyph_id.0, x_advance, x_offset: Em::zero(), y_offset: Em::zero(), + size, adjustability: Adjustability::default(), range, safe_to_break: true, @@ -666,6 +670,7 @@ fn shape<'a>( region: Option, ) -> ShapedText<'a> { let size = TextElem::size_in(styles); + let shift_settings = TextElem::shift_settings_in(styles); let mut ctx = ShapingContext { engine, size, @@ -676,6 +681,7 @@ fn shape<'a>( features: features(styles), fallback: TextElem::fallback_in(styles), dir, + shift_settings, }; if !text.is_empty() { @@ -698,12 +704,17 @@ fn shape<'a>( region, styles, variant: ctx.variant, - size, - width: ctx.glyphs.iter().map(|g| g.x_advance).sum::().at(size), + width: glyphs_width(&ctx.glyphs), glyphs: Cow::Owned(ctx.glyphs), } } +/// Computes the width of a run of glyphs relative to the font size, accounting +/// for their individual scaling factors and other font metrics. +fn glyphs_width(glyphs: &[ShapedGlyph]) -> Abs { + glyphs.iter().map(|g| g.x_advance.at(g.size)).sum() +} + /// Holds shaping results and metadata common to all shaped segments. struct ShapingContext<'a, 'v> { engine: &'a Engine<'v>, @@ -715,6 +726,7 @@ struct ShapingContext<'a, 'v> { features: Vec, fallback: bool, dir: Dir, + shift_settings: Option, } /// Shape text with font fallback using the `families` iterator. @@ -789,6 +801,18 @@ fn shape_segment<'a>( // text extraction. buffer.set_flags(BufferFlags::REMOVE_DEFAULT_IGNORABLES); + let (script_shift, script_compensation, scale, shift_feature) = ctx + .shift_settings + .map_or((Em::zero(), Em::zero(), Em::one(), None), |settings| { + determine_shift(text, &font, settings) + }); + + let has_shift_feature = shift_feature.is_some(); + if let Some(feat) = shift_feature { + // Temporarily push the feature. + ctx.features.push(feat) + } + // Prepare the shape plan. This plan depends on direction, script, language, // and features, but is independent from the text and can thus be memoized. let plan = create_shape_plan( @@ -799,6 +823,10 @@ fn shape_segment<'a>( &ctx.features, ); + if has_shift_feature { + ctx.features.pop(); + } + // Shape! let buffer = rustybuzz::shape_with_plan(font.rusty(), &plan, buffer); let infos = buffer.glyph_infos(); @@ -869,8 +897,9 @@ fn shape_segment<'a>( glyph_id: info.glyph_id as u16, // TODO: Don't ignore y_advance. x_advance, - x_offset: font.to_em(pos[i].x_offset), - y_offset: font.to_em(pos[i].y_offset), + x_offset: font.to_em(pos[i].x_offset) + script_compensation, + y_offset: font.to_em(pos[i].y_offset) + script_shift, + size: scale.at(ctx.size), adjustability: Adjustability::default(), range: start..end, safe_to_break: !info.unsafe_to_break(), @@ -932,6 +961,64 @@ fn shape_segment<'a>( ctx.used.pop(); } +/// Returns a `(script_shift, script_compensation, scale, feature)` quadruplet +/// describing how to produce scripts. +/// +/// Those values determine how the rendered text should be transformed to +/// display sub-/super-scripts. If the OpenType feature can be used, the +/// rendered text should not be transformed in any way, and so those values are +/// neutral (`(0, 0, 1, None)`). If scripts should be synthesized, those values +/// determine how to transform the rendered text to display scripts as expected. +fn determine_shift( + text: &str, + font: &Font, + settings: ShiftSettings, +) -> (Em, Em, Em, Option) { + settings + .typographic + .then(|| { + // If typographic scripts are enabled (i.e., we want to use the + // OpenType feature instead of synthesizing if possible), we add + // "subs"/"sups" to the feature list if supported by the font. + // In case of a problem, we just early exit + let gsub = font.rusty().tables().gsub?; + let subtable_index = + gsub.features.find(settings.kind.feature())?.lookup_indices.get(0)?; + let coverage = gsub + .lookups + .get(subtable_index)? + .subtables + .get::(0)? + .coverage(); + text.chars() + .all(|c| { + font.rusty().glyph_index(c).is_some_and(|i| coverage.contains(i)) + }) + .then(|| { + // If we can use the OpenType feature, we can keep the text + // as is. + ( + Em::zero(), + Em::zero(), + Em::one(), + Some(Feature::new(settings.kind.feature(), 1, ..)), + ) + }) + }) + // Reunite the cases where `typographic` is `false` or where using the + // OpenType feature would not work. + .flatten() + .unwrap_or_else(|| { + let script_metrics = settings.kind.read_metrics(font.metrics()); + ( + settings.shift.unwrap_or(script_metrics.vertical_offset), + script_metrics.horizontal_offset, + settings.size.unwrap_or(script_metrics.height), + None, + ) + }) +} + /// Create a shape plan. #[comemo::memoize] pub fn create_shape_plan( @@ -963,6 +1050,7 @@ fn shape_tofus(ctx: &mut ShapingContext, base: usize, text: &str, font: Font) { x_advance, x_offset: Em::zero(), y_offset: Em::zero(), + size: ctx.size, adjustability: Adjustability::default(), range: start..end, safe_to_break: true, @@ -985,9 +1073,8 @@ fn shape_tofus(ctx: &mut ShapingContext, base: usize, text: &str, font: Font) { /// Apply tracking and spacing to the shaped glyphs. fn track_and_space(ctx: &mut ShapingContext) { - let tracking = Em::from_length(TextElem::tracking_in(ctx.styles), ctx.size); - let spacing = - TextElem::spacing_in(ctx.styles).map(|abs| Em::from_length(abs, ctx.size)); + let tracking = Em::from_abs(TextElem::tracking_in(ctx.styles), ctx.size); + let spacing = TextElem::spacing_in(ctx.styles).map(|abs| Em::from_abs(abs, ctx.size)); let mut glyphs = ctx.glyphs.iter_mut().peekable(); while let Some(glyph) = glyphs.next() { diff --git a/crates/typst-layout/src/math/fragment.rs b/crates/typst-layout/src/math/fragment.rs index eb85eeb5d..c5891f7d5 100644 --- a/crates/typst-layout/src/math/fragment.rs +++ b/crates/typst-layout/src/math/fragment.rs @@ -215,7 +215,7 @@ impl MathFragment { &glyph.item.font, GlyphId(glyph.item.glyphs[glyph_index].id), corner, - Em::from_length(height, glyph.item.size), + Em::from_abs(height, glyph.item.size), ) .unwrap_or_default() .at(glyph.item.size) @@ -767,8 +767,8 @@ fn assemble( advance += ratio * (max_overlap - min_overlap); } let (x, y) = match axis { - Axis::X => (Em::from_length(advance, base.item.size), Em::zero()), - Axis::Y => (Em::zero(), Em::from_length(advance, base.item.size)), + Axis::X => (Em::from_abs(advance, base.item.size), Em::zero()), + Axis::Y => (Em::zero(), Em::from_abs(advance, base.item.size)), }; glyphs.push(Glyph { id: part.glyph_id.0, diff --git a/crates/typst-library/src/layout/em.rs b/crates/typst-library/src/layout/em.rs index e2d8b120f..746e17692 100644 --- a/crates/typst-library/src/layout/em.rs +++ b/crates/typst-library/src/layout/em.rs @@ -6,7 +6,7 @@ use ecow::EcoString; use typst_utils::{Numeric, Scalar}; use crate::foundations::{cast, repr, Repr, Resolve, StyleChain, Value}; -use crate::layout::Abs; +use crate::layout::{Abs, Length}; use crate::text::TextElem; /// A length that is relative to the font size. @@ -26,18 +26,18 @@ impl Em { Self(Scalar::ONE) } - /// Create a font-relative length. + /// Creates a font-relative length. pub const fn new(em: f64) -> Self { Self(Scalar::new(em)) } - /// Create an em length from font units at the given units per em. + /// Creates an em length from font units at the given units per em. pub fn from_units(units: impl Into, units_per_em: f64) -> Self { Self(Scalar::new(units.into() / units_per_em)) } - /// Create an em length from a length at the given font size. - pub fn from_length(length: Abs, font_size: Abs) -> Self { + /// Creates an em length from an absolute length at the given font size. + pub fn from_abs(length: Abs, font_size: Abs) -> Self { let result = length / font_size; if result.is_finite() { Self(Scalar::new(result)) @@ -46,6 +46,11 @@ impl Em { } } + /// Creates an em length from a length at the given font size. + pub fn from_length(length: Length, font_size: Abs) -> Em { + length.em + Self::from_abs(length.abs, font_size) + } + /// The number of em units. pub const fn get(self) -> f64 { (self.0).get() @@ -56,7 +61,7 @@ impl Em { Self::new(self.get().abs()) } - /// Convert to an absolute length at the given font size. + /// Converts to an absolute length at the given font size. pub fn at(self, font_size: Abs) -> Abs { let resolved = font_size * self.get(); if resolved.is_finite() { diff --git a/crates/typst-library/src/text/font/mod.rs b/crates/typst-library/src/text/font/mod.rs index 0383bfe15..3f5e71204 100644 --- a/crates/typst-library/src/text/font/mod.rs +++ b/crates/typst-library/src/text/font/mod.rs @@ -228,6 +228,10 @@ pub struct FontMetrics { pub underline: LineMetrics, /// Recommended metrics for an overline. pub overline: LineMetrics, + /// Metrics for subscripts, if provided by the font. + pub subscript: Option, + /// Metrics for superscripts, if provided by the font. + pub superscript: Option, } impl FontMetrics { @@ -240,6 +244,7 @@ impl FontMetrics { let cap_height = ttf.capital_height().filter(|&h| h > 0).map_or(ascender, to_em); let x_height = ttf.x_height().filter(|&h| h > 0).map_or(ascender, to_em); let descender = to_em(ttf.typographic_descender().unwrap_or(ttf.descender())); + let strikeout = ttf.strikeout_metrics(); let underline = ttf.underline_metrics(); @@ -262,6 +267,20 @@ impl FontMetrics { thickness: underline.thickness, }; + let subscript = ttf.subscript_metrics().map(|metrics| ScriptMetrics { + width: to_em(metrics.x_size), + height: to_em(metrics.y_size), + horizontal_offset: to_em(metrics.x_offset), + vertical_offset: -to_em(metrics.y_offset), + }); + + let superscript = ttf.superscript_metrics().map(|metrics| ScriptMetrics { + width: to_em(metrics.x_size), + height: to_em(metrics.y_size), + horizontal_offset: to_em(metrics.x_offset), + vertical_offset: to_em(metrics.y_offset), + }); + Self { units_per_em, ascender, @@ -271,6 +290,8 @@ impl FontMetrics { strikethrough, underline, overline, + superscript, + subscript, } } @@ -296,6 +317,24 @@ pub struct LineMetrics { pub thickness: Em, } +/// Metrics for subscripts or superscripts. +#[derive(Debug, Copy, Clone)] +pub struct ScriptMetrics { + /// The width of those scripts, relative to the outer font size. + pub width: Em, + /// The height of those scripts, relative to the outer font size. + pub height: Em, + /// The horizontal (to the right) offset of those scripts, relative to the + /// outer font size. + /// + /// This is used for italic correction. + pub horizontal_offset: Em, + /// The vertical (to the top) offset of those scripts, relative to the outer font size. + /// + /// For superscripts, this is positive. For subscripts, this is negative. + pub vertical_offset: Em, +} + /// Identifies a vertical metric of a font. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)] pub enum VerticalFontMetric { diff --git a/crates/typst-library/src/text/mod.rs b/crates/typst-library/src/text/mod.rs index 563adbbd4..b1e381cb2 100644 --- a/crates/typst-library/src/text/mod.rs +++ b/crates/typst-library/src/text/mod.rs @@ -755,6 +755,12 @@ pub struct TextElem { #[internal] #[ghost] pub smallcaps: Option, + + /// The configuration for superscripts or subscripts, if one of them is + /// enabled. + #[internal] + #[ghost] + pub shift_settings: Option, } impl TextElem { diff --git a/crates/typst-library/src/text/shift.rs b/crates/typst-library/src/text/shift.rs index 7b35dfd38..b7f3ed926 100644 --- a/crates/typst-library/src/text/shift.rs +++ b/crates/typst-library/src/text/shift.rs @@ -1,14 +1,13 @@ -use ecow::EcoString; - use crate::diag::SourceResult; use crate::engine::Engine; use crate::foundations::{ - elem, Content, NativeElement, Packed, SequenceElem, Show, StyleChain, TargetElem, + elem, Content, NativeElement, Packed, Show, Smart, StyleChain, TargetElem, }; use crate::html::{tag, HtmlElem}; use crate::layout::{Em, Length}; -use crate::text::{variant, SpaceElem, TextElem, TextSize}; -use crate::World; +use crate::text::{FontMetrics, TextElem, TextSize}; +use ttf_parser::Tag; +use typst_library::text::ScriptMetrics; /// Renders text in subscript. /// @@ -20,11 +19,16 @@ use crate::World; /// ``` #[elem(title = "Subscript", Show)] pub struct SubElem { - /// Whether to prefer the dedicated subscript characters of the font. + /// Whether to create artificial subscripts by lowering and scaling down + /// regular glyphs. /// - /// If this is enabled, Typst first tries to transform the text to subscript - /// codepoints. If that fails, it falls back to rendering lowered and shrunk - /// normal letters. + /// Ideally, subscripts glyphs are provided by the font (using the `subs` + /// OpenType feature). Otherwise, Typst is able to synthesize subscripts. + /// + /// When this is set to `{false}`, synthesized glyphs will be used + /// regardless of whether the font provides dedicated subscript glyphs. When + /// `{true}`, synthesized glyphs may still be used in case the font does not + /// provide the necessary subscript glyphs. /// /// ```example /// N#sub(typographic: true)[1] @@ -33,17 +37,27 @@ pub struct SubElem { #[default(true)] pub typographic: bool, - /// The baseline shift for synthetic subscripts. Does not apply if - /// `typographic` is true and the font has subscript codepoints for the - /// given `body`. - #[default(Em::new(0.2).into())] - pub baseline: Length, + /// The downward baseline shift for synthesized subscripts. + /// + /// This only applies to synthesized subscripts. In other words, this has no + /// effect if `typographic` is `{true}` and the font provides the necessary + /// subscript glyphs. + /// + /// If set to `{auto}`, the baseline is shifted according to the metrics + /// provided by the font, with a fallback to `{0.2em}` in case the font does + /// not define the necessary metrics. + pub baseline: Smart, - /// The font size for synthetic subscripts. Does not apply if - /// `typographic` is true and the font has subscript codepoints for the - /// given `body`. - #[default(TextSize(Em::new(0.6).into()))] - pub size: TextSize, + /// The font size for synthesized subscripts. + /// + /// This only applies to synthesized subscripts. In other words, this has no + /// effect if `typographic` is `{true}` and the font provides the necessary + /// subscript glyphs. + /// + /// If set to `{auto}`, the size is scaled according to the metrics provided + /// by the font, with a fallback to `{0.6em}` in case the font does not + /// define the necessary metrics. + pub size: Smart, /// The text to display in subscript. #[required] @@ -52,7 +66,7 @@ pub struct SubElem { impl Show for Packed { #[typst_macros::time(name = "sub", span = self.span())] - fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult { + fn show(&self, _: &mut Engine, styles: StyleChain) -> SourceResult { let body = self.body.clone(); if TargetElem::target_in(styles).is_html() { @@ -62,17 +76,14 @@ impl Show for Packed { .spanned(self.span())); } - if self.typographic(styles) { - if let Some(text) = convert_script(&body, true) { - if is_shapable(engine, &text, styles) { - return Ok(TextElem::packed(text)); - } - } - }; - - Ok(body - .styled(TextElem::set_baseline(self.baseline(styles))) - .styled(TextElem::set_size(self.size(styles)))) + show_script( + styles, + body, + self.typographic(styles), + self.baseline(styles), + self.size(styles), + ScriptKind::Sub, + ) } } @@ -86,11 +97,16 @@ impl Show for Packed { /// ``` #[elem(title = "Superscript", Show)] pub struct SuperElem { - /// Whether to prefer the dedicated superscript characters of the font. + /// Whether to create artificial superscripts by raising and scaling down + /// regular glyphs. /// - /// If this is enabled, Typst first tries to transform the text to - /// superscript codepoints. If that fails, it falls back to rendering - /// raised and shrunk normal letters. + /// Ideally, superscripts glyphs are provided by the font (using the `sups` + /// OpenType feature). Otherwise, Typst is able to synthesize superscripts. + /// + /// When this is set to `{false}`, synthesized glyphs will be used + /// regardless of whether the font provides dedicated superscript glyphs. + /// When `{true}`, synthesized glyphs may still be used in case the font + /// does not provide the necessary superscript glyphs. /// /// ```example /// N#super(typographic: true)[1] @@ -99,17 +115,31 @@ pub struct SuperElem { #[default(true)] pub typographic: bool, - /// The baseline shift for synthetic superscripts. Does not apply if - /// `typographic` is true and the font has superscript codepoints for the - /// given `body`. - #[default(Em::new(-0.5).into())] - pub baseline: Length, + /// The downward baseline shift for synthesized superscripts. + /// + /// This only applies to synthesized superscripts. In other words, this has + /// no effect if `typographic` is `{true}` and the font provides the + /// necessary superscript glyphs. + /// + /// If set to `{auto}`, the baseline is shifted according to the metrics + /// provided by the font, with a fallback to `{-0.5em}` in case the font + /// does not define the necessary metrics. + /// + /// Note that, since the baseline shift is applied downward, you will need + /// to provide a negative value for the content to appear as raised above + /// the normal baseline. + pub baseline: Smart, - /// The font size for synthetic superscripts. Does not apply if - /// `typographic` is true and the font has superscript codepoints for the - /// given `body`. - #[default(TextSize(Em::new(0.6).into()))] - pub size: TextSize, + /// The font size for synthesized superscripts. + /// + /// This only applies to synthesized superscripts. In other words, this has + /// no effect if `typographic` is `{true}` and the font provides the + /// necessary superscript glyphs. + /// + /// If set to `{auto}`, the size is scaled according to the metrics provided + /// by the font, with a fallback to `{0.6em}` in case the font does not + /// define the necessary metrics. + pub size: Smart, /// The text to display in superscript. #[required] @@ -118,7 +148,7 @@ pub struct SuperElem { impl Show for Packed { #[typst_macros::time(name = "super", span = self.span())] - fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult { + fn show(&self, _: &mut Engine, styles: StyleChain) -> SourceResult { let body = self.body.clone(); if TargetElem::target_in(styles).is_html() { @@ -128,104 +158,102 @@ impl Show for Packed { .spanned(self.span())); } - if self.typographic(styles) { - if let Some(text) = convert_script(&body, false) { - if is_shapable(engine, &text, styles) { - return Ok(TextElem::packed(text)); - } - } - }; - - Ok(body - .styled(TextElem::set_baseline(self.baseline(styles))) - .styled(TextElem::set_size(self.size(styles)))) + show_script( + styles, + body, + self.typographic(styles), + self.baseline(styles), + self.size(styles), + ScriptKind::Super, + ) } } -/// Find and transform the text contained in `content` to the given script kind -/// if and only if it only consists of `Text`, `Space`, and `Empty` leaves. -fn convert_script(content: &Content, sub: bool) -> Option { - if content.is::() { - Some(' '.into()) - } else if let Some(elem) = content.to_packed::() { - if sub { - elem.text.chars().map(to_subscript_codepoint).collect() - } else { - elem.text.chars().map(to_superscript_codepoint).collect() - } - } else if let Some(sequence) = content.to_packed::() { - sequence - .children - .iter() - .map(|item| convert_script(item, sub)) - .collect() - } else { - None - } +fn show_script( + styles: StyleChain, + body: Content, + typographic: bool, + baseline: Smart, + size: Smart, + kind: ScriptKind, +) -> SourceResult { + let font_size = TextElem::size_in(styles); + Ok(body.styled(TextElem::set_shift_settings(Some(ShiftSettings { + typographic, + shift: baseline.map(|l| -Em::from_length(l, font_size)), + size: size.map(|t| Em::from_length(t.0, font_size)), + kind, + })))) } -/// Checks whether the first retrievable family contains all code points of the -/// given string. -fn is_shapable(engine: &Engine, text: &str, styles: StyleChain) -> bool { - let world = engine.world; - for family in TextElem::font_in(styles) { - if let Some(font) = world - .book() - .select(family.as_str(), variant(styles)) - .and_then(|id| world.font(id)) - { - let covers = family.covers(); - return text.chars().all(|c| { - covers.is_none_or(|cov| cov.is_match(c.encode_utf8(&mut [0; 4]))) - && font.ttf().glyph_index(c).is_some() - }); +/// Configuration values for sub- or superscript text. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub struct ShiftSettings { + /// Whether the OpenType feature should be used if possible. + pub typographic: bool, + /// The baseline shift of the script, relative to the outer text size. + /// + /// For superscripts, this is positive. For subscripts, this is negative. A + /// value of [`Smart::Auto`] indicates that the value should be obtained + /// from font metrics. + pub shift: Smart, + /// The size of the script, relative to the outer text size. + /// + /// A value of [`Smart::Auto`] indicates that the value should be obtained + /// from font metrics. + pub size: Smart, + /// The kind of script (either a subscript, or a superscript). + /// + /// This is used to know which OpenType table to use to resolve + /// [`Smart::Auto`] values. + pub kind: ScriptKind, +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum ScriptKind { + Sub, + Super, +} + +impl ScriptKind { + /// Returns the default metrics for this script kind. + /// + /// This can be used as a last resort if neither the user nor the font + /// provided those metrics. + pub fn default_metrics(self) -> &'static ScriptMetrics { + match self { + Self::Sub => &DEFAULT_SUBSCRIPT_METRICS, + Self::Super => &DEFAULT_SUPERSCRIPT_METRICS, } } - false -} + /// Reads the script metrics from the font table for to this script kind. + pub fn read_metrics(self, font_metrics: &FontMetrics) -> &ScriptMetrics { + match self { + Self::Sub => font_metrics.subscript.as_ref(), + Self::Super => font_metrics.superscript.as_ref(), + } + .unwrap_or(self.default_metrics()) + } -/// Convert a character to its corresponding Unicode superscript. -fn to_superscript_codepoint(c: char) -> Option { - match c { - '1' => Some('¹'), - '2' => Some('²'), - '3' => Some('³'), - '0' | '4'..='9' => char::from_u32(c as u32 - '0' as u32 + '⁰' as u32), - '+' => Some('⁺'), - '−' => Some('⁻'), - '=' => Some('⁼'), - '(' => Some('⁽'), - ')' => Some('⁾'), - 'n' => Some('ⁿ'), - 'i' => Some('ⁱ'), - ' ' => Some(' '), - _ => None, + /// The corresponding OpenType feature. + pub const fn feature(self) -> Tag { + match self { + Self::Sub => Tag::from_bytes(b"subs"), + Self::Super => Tag::from_bytes(b"sups"), + } } } +static DEFAULT_SUBSCRIPT_METRICS: ScriptMetrics = ScriptMetrics { + width: Em::new(0.6), + height: Em::new(0.6), + horizontal_offset: Em::zero(), + vertical_offset: Em::new(-0.2), +}; -/// Convert a character to its corresponding Unicode subscript. -fn to_subscript_codepoint(c: char) -> Option { - match c { - '0'..='9' => char::from_u32(c as u32 - '0' as u32 + '₀' as u32), - '+' => Some('₊'), - '−' => Some('₋'), - '=' => Some('₌'), - '(' => Some('₍'), - ')' => Some('₎'), - 'a' => Some('ₐ'), - 'e' => Some('ₑ'), - 'o' => Some('ₒ'), - 'x' => Some('ₓ'), - 'h' => Some('ₕ'), - 'k' => Some('ₖ'), - 'l' => Some('ₗ'), - 'm' => Some('ₘ'), - 'n' => Some('ₙ'), - 'p' => Some('ₚ'), - 's' => Some('ₛ'), - 't' => Some('ₜ'), - ' ' => Some(' '), - _ => None, - } -} +static DEFAULT_SUPERSCRIPT_METRICS: ScriptMetrics = ScriptMetrics { + width: Em::new(0.6), + height: Em::new(0.6), + horizontal_offset: Em::zero(), + vertical_offset: Em::new(0.5), +}; diff --git a/tests/ref/issue-4454-footnote-ref-numbering.png b/tests/ref/issue-4454-footnote-ref-numbering.png index bf23221aeeeb719e4e276cb3f92e15fbce353363..bc19d46c531ca73d46feb7e883c46af7fce88d44 100644 GIT binary patch delta 880 zcmV-$1CRX428RcbB!8z+OjJex|Nr&%_4oJr-QVZ#@AKy8?fLoo+}`H%^Y-lR@#Ey^ z+uPesO-=s({z^(pG&D4QeSM3Ii#RwqEG#VX@$t>g&6k&#+}zxBbacqd(zdp?larHa zX=!h7Z}9N&>FMdq%gddeoui|pb8~YmD=UG4fvc^xm6xBeuz#?LiHXF-#Psy^NJvQP z>gqEyGv?;z>g(@d2PK0ZD+Ha6PY+T!BkS65f5sj1M= z&_qN;(bCv{fQZ`L;l9AgxVpmN;pf%X+<$?Igocj1zQ)PR)5pottgNg-K|y+Ydf(sQ zg@uKDe0-FYlz(SuXJTSv^78VcqN3K;)@*ES>FVy{;^f}m;NITehlhu|ySrs&WzWyg zYHD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Xx{Lb?K;S><#^ba86ck{pIzsuXU-FO4!9RKs{#Q(cbfvlR<{{yd5IaRMIxI3rp zC6F;?>;M0Ei&tLC-ScF|i@iNSk@oj*y8drI{Qv)l>b_?s3u%>)w|s`Nrp(=Y=JsgG jHEQvw#iJGvG8T&g%vEnNuDA|p00000NkvXXu0mjfgY2Q~ diff --git a/tests/ref/sub-super-typographic.png b/tests/ref/sub-super-typographic.png new file mode 100644 index 0000000000000000000000000000000000000000..a0c53d5002b540dadc26f36160e9aaf511a90d3b GIT binary patch literal 1337 zcmV-91;+Y`P)CJDl2m~roMa*mMdW2zl z3L4im^KOVs>Eomr6lq*|4`{QGp^q#Ps?gBTa8kHuAu}l4=_mzI9(VAhj}S3{+~z8< zdy+kUp+}@;M)g8fS_%p0zq`p(ZkBtfMWq_@SF`SOlDoP>LK?BR3NzZWJ)E$M+2)N za!{ux?7N@fIIZEkD@>NP^V9Hi9o%?hVe#}8VW-AvY=*YUdEvDmUv`FR0Q zT3FCVTx?5WaZx3;{xqbu(4&3&Y*oWN8QQHJQLDDUgGTjI7nkKS1UkYp%N0HndMGcd zK@ii(^KvZqy5^xn>o~`~7YsZ=u9}K@AwQGd=#*?`i-F;sk%NnQk&DCMZb6q~ON$)C z!p#fntgO1xt;DW+lp8vo!8w~eR7Vlz6`%`7Lza6TI^Hsecysf0we&A;j=6-Qai+HEdWWkD@@tUg7UnggU0GpX6V-Wzxt;W{ zrXatHrYBPxjDH};urX{58^gx1G5kLY-;Ga)6O!+IGApr=gDiL%=o|Xf&MIUdaM}q13?-S6WYS`xA_hC?&V6!Cv z-TtGK5$<1h2CV^_Kj{qF!c$uY?m(yWrVBAJTs3f19RlYRfTrKbn+!Zo=cp%7#hK6S z29SDw1uFlo^RGbQS{n&ZJsSLa6+ma8H5y@C7a!0S?p~Zd&i?PKh@f2nsx32Q&&Gb1 zIoKP(-9Zfb3pqcI)?NH8riW_D?Ma`ifxrzS9@siLIZDTAW#jh1|cwaYz0~7L;Rb2!sOdj0g3B}wj#)0X`V{;B-3rB&#xky>~5kp zoEZ_GP5Gs$uyU}u0$J)V2PHm~v{OatR1hRZhE;GUEb>w#1b-ofoLUPz0L75&ns7vT zCY6^W!|papGoMxP{J6G$LuJ>6TQw)N8k@PEYr_TxQySuv|grJRktLZIjr;oQv vB9X)>w?BDGu5VabghsCMvuF$(!+QA(zLpk~LW$FI00000NkvXXu0mjf&n|^o literal 0 HcmV?d00001 diff --git a/tests/ref/sub-super.png b/tests/ref/sub-super.png index 10fe77b07b5a1d65ec87de08f54bc8d13db6ee8d..fafdf5594dfb65df0e515779572353f0c380d42f 100644 GIT binary patch delta 1169 zcmV;C1aAA<2&D;-B!6s4L_t(|+U?nCOcZAv$8i(-qNPcbCZsRgas+D`D86b_r6JVN zn2JOR4X06#7$xN>Vz~rmLC(~284Bg9C{Vyc$cl)S!*IAO6o?YL8=}Aha%-SmdoVk{ z4vi7m%s#WbeNj{An|=3xvY%vUp2@SBUHFgMCBOnK!2csSFMlYRTyP+HemFLnub?~* zIOu?goU03YZV@Kp>p&m}oGb#lv_uf2|f6Db!izS9Zd7s^+Dcy12;~aLmQ)JK)S?PoeM;Yr^h* zUwJ-&>9DI{oN7-s7zX1)6^amAjiW=C#Q0Xc1GcRRo^PMMmHGm1fb-&Z7?ln`A-xPm zD2-rF$<<#1_G7Du41{M~I-el&J~AqfNl~7;1Ev5d@_%zeU;fkqL)&2umMzuKoTM^T z{EX=CO?V&sF#s-!25>wQh-_zk6$SB#>V7=C1vBqyfuP}z(+H4i?U5>0d7x_x)bOp1F1RNZ0W=pVX)tCt(mDBXg83%?HZWZjDCjV)-2 z=xxf&oqs?A{Srp@kJl#HRX3nXNm)FXkECCE!v1Lc?qTi>0p6+w+hc{0({Wig529Y3*LCwf-m!f9B^XH0=a}J@_dhEfv?yE;Tr40{k9Zk zCnLj&b`<5kst>OJh@!q2Hxiyc7k^eRKb@%;u759{1FYKQa?3F;n5oHxPqtisq{c{C z6BW;*@%rKBisb>=u&50u3?>_XEb3xnQx~`bk+^vuXhDdnoF&c^!BoBwT)GL6ifLHAQ_QF&xHKpQivA zxqn<uI(FRWg=i_I8z4WkPyTBbctp|h(6jDF(J6H zEQ)R#9HYZIgc&8{Z`t^xs4Y+^WKIF+?1Xm0Kq%VAlp>G;8Y!cIKw8F*m`W)W5JZGk zptR6_RuW^uw7)x=g>B~EY5L@Q$t%74^_RQcI{ZtmV__C%;eQthE{Mz^7j=X@-z_ay_4E5HgL0Wi3$pj9` z3Ez_yOn|Gl6sDxY(UYKVYMV8@`Z>5mlFh@iCScsm1a3mvY1}5j*a9?Ssb~#$AiL%{ zm^0@XJ2M9Y{(nqhpfVHvp>^h%hQsCQ#jxZ_uB?Q8=5J0vs7f$B_vdC^Myb$e*n!+ z*cK1$298Dpq5{M7`Cr@Trsua_LFr`8%x>G;J7MgHvsiE>*ks z*El+mHKC4kDjD~sfzoP^W*MeN`LJcY)ztpo28={Dw5s8c8y@w@JRon zegg6C;nDtufrl9Tv05u|1>5>ZX7%Qw`c=a+Kg*GOqryMk!U~_cqm))TUDYPmxqug< zFnMuR9W)RZSC|lseL8e~#&LAq#2D@f>LSD4AE}A(rC_Tk zdw+FX>X;uzf;+#R^zCsEFBH^>qNY87^#k+N5D7NuEz}?ZrY6U!zt~5Z|0Wz0DkaAW zAKk|J2UJgxOf3Vk>h5yg+KmylMmX#@dg>TMnA;D#5X3pMr z51UV1HS)#*9E`|!Bg8@fHZ+0$*Z0j=&~3~sREu}tp{ zMh+KfmaQHx5(!}lA;1zb4>cY3%ko^8@a(1VUb``8)o?}LRB#>A+`}?~X`j-3x2UE^ z=n9@qYFB<`=+b(4U%kJVysEWQ&AB?R&fTguf6d32pKu+0AYb#p)8qW5O4*&u1wMRW zQvkWQHD!oG!JVHRfLf1tks?=69MA@eAY00000 LNkvXXu0mjf+=n3e diff --git a/tests/ref/super-highlight.png b/tests/ref/super-highlight.png new file mode 100644 index 0000000000000000000000000000000000000000..c0cf612b95278ebef939f33cd1ed42c079079a3b GIT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f(1NCl literal 0 HcmV?d00001 diff --git a/tests/ref/super-underline.png b/tests/ref/super-underline.png index 4608d1a8308c5729a6b0b10905ebe2683019e2fc..cef0d2a108341211983a8db7815725d82d202448 100644 GIT binary patch delta 825 zcmV-91IGNR4#NhJ7k^v`00000fHE#F0009DNklIK z)H=*~=9@DJUUnmoVCM(##e4PPxp;oh0_G?S4A_7Tcs{}nL4SET)(7fo4U{!E3v=Y) z)^mCA#(z_%9NclJ07}w-0^8gy9~Ofj4sM2l^PWg$emRH~>`(5D_JDgR3}>77 zd8FXHs``vOn$1=fnHX215FEG!Jf&bp|gBs>E^Ic9!U8Zw&8faekX zSsK1L20&9L1k#Q=^87;Zx42?}-Uf46KS)WE5S;xh7Jp#;!?_T&C4@4oW#I92pUDf* z*9^36u*ErK;DTpmDONx!D(VkUjJ{$>0@g2se;qK~)1yIiJVXyjzzvpG>F2IqF~0-re(u;+26OA6L3 zp-n1yJb!@wczSGy6kL4w@hKYsk%_z4NWsZ4XaWFovIs^A!FLa+DC-IV@Fwhc+Pj3{ zzDW9~p70*$M^Z5Lbfc>cc-CQC0I=7A_r`5UtsLART?uuMD*;Ou2i}Omk2>Swd)oAo zNNksagAXwIp}jqFB+|D0kb+&Q_9IVcjzq_LDS!A1cw+#7+#EtngkZ}~6(wr=NbHGo z=Cp|JacFdObWRFHvs$gjkuc!dhn+eAgV%s^OHt*75InT%9RL-nz~o|DO+xUK*29F! z(iktW4Bu`USiev7IDoI*2P`cy70bX?$@X~1%y$|3_C^sn1$tsY6iCgjTeU`I8n6Ky@IUhx_1Q)K?Nxld00000NkvXXu0mjf Dy!wGc delta 1831 zcmV+?2iW+-2B{8^7k^I(000001#n&)000K?NklV`b=Pk8 z)K;tYOX{j!553jd;@1@rOK?(j%CIw{50V z<$DWRXSTO-6n}P!5Z>dG@;LgKgZ02Xxu}`a^eD4cb|$}dW4=$c9q@bo7b1t3UvpJJ z|5^%rC91w0{!G<2L_Mk|7XKh>SAl&dAd)2Y>`P|*cfg1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