diff options
| author | Malo <57839069+MDLC01@users.noreply.github.com> | 2025-07-02 09:00:45 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-07-02 08:00:45 +0000 |
| commit | 09c831d3b32935fe162f198e3512e1e7cd6647db (patch) | |
| tree | a80a3e60381c2ac162034c45661d4070443563a7 /crates/typst-library/src/text | |
| parent | 30ddc4a7ca38ea41d9184cec6eee732307c80b33 (diff) | |
Use "subs" and "sups" font features for typographic scripts (#5777)
Diffstat (limited to 'crates/typst-library/src/text')
| -rw-r--r-- | crates/typst-library/src/text/font/mod.rs | 39 | ||||
| -rw-r--r-- | crates/typst-library/src/text/mod.rs | 6 | ||||
| -rw-r--r-- | crates/typst-library/src/text/shift.rs | 298 |
3 files changed, 208 insertions, 135 deletions
diff --git a/crates/typst-library/src/text/font/mod.rs b/crates/typst-library/src/text/font/mod.rs index 0383bfe1..3f5e7120 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<ScriptMetrics>, + /// Metrics for superscripts, if provided by the font. + pub superscript: Option<ScriptMetrics>, } 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 563adbbd..b1e381cb 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<Smallcaps>, + + /// The configuration for superscripts or subscripts, if one of them is + /// enabled. + #[internal] + #[ghost] + pub shift_settings: Option<ShiftSettings>, } impl TextElem { diff --git a/crates/typst-library/src/text/shift.rs b/crates/typst-library/src/text/shift.rs index 7b35dfd3..b7f3ed92 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. + /// + /// Ideally, subscripts glyphs are provided by the font (using the `subs` + /// OpenType feature). Otherwise, Typst is able to synthesize subscripts. /// - /// 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. + /// 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<Length>, - /// 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<TextSize>, /// The text to display in subscript. #[required] @@ -52,7 +66,7 @@ pub struct SubElem { impl Show for Packed<SubElem> { #[typst_macros::time(name = "sub", span = self.span())] - fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> { + fn show(&self, _: &mut Engine, styles: StyleChain) -> SourceResult<Content> { let body = self.body.clone(); if TargetElem::target_in(styles).is_html() { @@ -62,17 +76,14 @@ impl Show for Packed<SubElem> { .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<SubElem> { /// ``` #[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<Length>, - /// 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<TextSize>, /// The text to display in superscript. #[required] @@ -118,7 +148,7 @@ pub struct SuperElem { impl Show for Packed<SuperElem> { #[typst_macros::time(name = "super", span = self.span())] - fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> { + fn show(&self, _: &mut Engine, styles: StyleChain) -> SourceResult<Content> { let body = self.body.clone(); if TargetElem::target_in(styles).is_html() { @@ -128,104 +158,102 @@ impl Show for Packed<SuperElem> { .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<EcoString> { - if content.is::<SpaceElem>() { - Some(' '.into()) - } else if let Some(elem) = content.to_packed::<TextElem>() { - 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::<SequenceElem>() { - sequence - .children - .iter() - .map(|item| convert_script(item, sub)) - .collect() - } else { - None - } +fn show_script( + styles: StyleChain, + body: Content, + typographic: bool, + baseline: Smart<Length>, + size: Smart<TextSize>, + kind: ScriptKind, +) -> SourceResult<Content> { + 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<Em>, + /// 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<Em>, + /// 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, +} - false +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum ScriptKind { + Sub, + Super, } -/// Convert a character to its corresponding Unicode superscript. -fn to_superscript_codepoint(c: char) -> Option<char> { - 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, +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, + } } -} -/// Convert a character to its corresponding Unicode subscript. -fn to_subscript_codepoint(c: char) -> Option<char> { - 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, + /// 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()) + } + + /// 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), +}; + +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), +}; |
