Compare commits

...

11 Commits

Author SHA1 Message Date
mkorje
0e5896671e
Add delim-size parameter to mat, vec, and cases
Takes either a function or a relative length, just like with `lr`,
`stretch`, and `accent` which was changed in the previous two commits.
The default is now much clearer to the user: `x => x * 1.1 - 0.1em`.
2025-07-07 13:01:26 +10:00
mkorje
a5170e5fcf
Allow a function as an argument to size in accent
The short fall is now only applied in the default for `accent`
(`x => x - 0.5em`).
2025-07-07 13:01:23 +10:00
mkorje
d62d249355
Allow a function as an argument to size in stretch and lr
Previously there was always a short fall when scaling delimiters, even if
the user requested a specific size. This is no longer the case; the short
fall is only present in the default for `lr` (`x => x - 0.1em`) - the
size of the delimiters is now actually what was specified in the size
argument. This also makes the default for `lr` much clearer to the user.

A slight hack was used by exploiting the `name` property in the `func`
attribute macro so that the default value in the docs for `lr.size` would
clearly show what the default function was (instead of just its name
`default_lr_size` which is meaningless and inaccessible to the user).
2025-07-07 13:01:21 +10:00
Laurenz
d1deb80bb8
Fix nightly warnings (#6558) 2025-07-05 12:23:48 +00:00
Andrew Voynov
88e451b3dc
Fix typo in PackageStorage (#6556) 2025-07-04 17:02:02 +00:00
Tobias Schmitz
cc3a68ecb1
Remove duplicate language computation (#6557) 2025-07-04 17:00:45 +00:00
Max
22a57fcf5c
Use punctuation math class for Arabic comma (#6537) 2025-07-02 08:01:44 +00:00
Malo
09c831d3b3
Use "subs" and "sups" font features for typographic scripts (#5777) 2025-07-02 08:00:45 +00:00
Robin
30ddc4a7ca
Fix typos in calc module docs (#6535) 2025-07-01 11:04:31 +00:00
Robin
d978f8c33a
Fix minor typo in array.product docs (#6532) 2025-07-01 11:04:11 +00:00
Adrián Delgado
c99f3ffc7d
Fix typo in PDF standard CLI help part 2 (#6531) 2025-06-30 16:51:36 +00:00
56 changed files with 856 additions and 345 deletions

View File

@ -491,7 +491,7 @@ pub enum PdfStandard {
/// PDF/A-2u. /// PDF/A-2u.
#[value(name = "a-2u")] #[value(name = "a-2u")]
A_2u, A_2u,
/// PDF/A-3u. /// PDF/A-3b.
#[value(name = "a-3b")] #[value(name = "a-3b")]
A_3b, A_3b,
/// PDF/A-3u. /// PDF/A-3u.

View File

@ -199,7 +199,7 @@ impl PackageStorage {
// The place at which the specific package version will live in the end. // The place at which the specific package version will live in the end.
let package_dir = base_dir.join(format!("{}", spec.version)); let package_dir = base_dir.join(format!("{}", spec.version));
// To prevent multiple Typst instances from interferring, we download // To prevent multiple Typst instances from interfering, we download
// into a temporary directory first and then move this directory to // into a temporary directory first and then move this directory to
// its final destination. // its final destination.
// //

View File

@ -206,7 +206,7 @@ pub fn collect<'a>(
} }
InlineItem::Frame(mut frame) => { InlineItem::Frame(mut frame) => {
frame.modify(&FrameModifiers::get_in(styles)); 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)); collector.push_item(Item::Frame(frame));
} }
} }
@ -221,7 +221,7 @@ pub fn collect<'a>(
let mut frame = layout_and_modify(styles, |styles| { let mut frame = layout_and_modify(styles, |styles| {
layout_box(elem, engine, loc, styles, region) 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)); collector.push_item(Item::Frame(frame));
} }
} else if let Some(elem) = child.to_packed::<TagElem>() { } else if let Some(elem) = child.to_packed::<TagElem>() {

View File

@ -5,7 +5,7 @@ use typst_library::engine::Engine;
use typst_library::introspection::{SplitLocator, Tag}; use typst_library::introspection::{SplitLocator, Tag};
use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point}; use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point};
use typst_library::model::ParLineMarker; use typst_library::model::ParLineMarker;
use typst_library::text::{Lang, TextElem}; use typst_library::text::{variant, Lang, TextElem};
use typst_utils::Numeric; use typst_utils::Numeric;
use super::*; 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 glyph = shaped.glyphs.to_mut().first_mut().unwrap();
let shrink = glyph.shrinkability().0; let shrink = glyph.shrinkability().0;
glyph.shrink_left(shrink); glyph.shrink_left(shrink);
shaped.width -= shrink.at(shaped.size); shaped.width -= shrink.at(glyph.size);
} else if p.config.cjk_latin_spacing } else if p.config.cjk_latin_spacing
&& glyph.is_cj_script() && glyph.is_cj_script()
&& glyph.x_offset > Em::zero() && 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_advance -= shrink;
glyph.x_offset = Em::zero(); glyph.x_offset = Em::zero();
glyph.adjustability.shrinkability.0 = 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 shrink = glyph.shrinkability().1;
let punct = shaped.glyphs.to_mut().last_mut().unwrap(); let punct = shaped.glyphs.to_mut().last_mut().unwrap();
punct.shrink_right(shrink); punct.shrink_right(shrink);
shaped.width -= shrink.at(shaped.size); shaped.width -= shrink.at(punct.size);
} else if p.config.cjk_latin_spacing } else if p.config.cjk_latin_spacing
&& glyph.is_cj_script() && glyph.is_cj_script()
&& (glyph.x_advance - glyph.x_offset) > Em::one() && (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(); let glyph = shaped.glyphs.to_mut().last_mut().unwrap();
glyph.x_advance -= shrink; glyph.x_advance -= shrink;
glyph.adjustability.shrinkability.1 = Em::zero(); 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. /// Apply the current baseline shift and italic compensation to a frame.
pub fn apply_baseline_shift(frame: &mut Frame, styles: StyleChain) { pub fn apply_shift<'a>(
frame.translate(Point::with_y(TextElem::baseline_in(styles))); 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. /// Commit to a line and build its frame.
@ -444,7 +465,7 @@ pub fn commit(
&& TextElem::overhang_in(text.styles) && TextElem::overhang_in(text.styles)
&& (line.items.len() > 1 || text.glyphs.len() > 1) && (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; offset -= amount;
remaining += amount; remaining += amount;
} }
@ -458,7 +479,7 @@ pub fn commit(
&& TextElem::overhang_in(text.styles) && TextElem::overhang_in(text.styles)
&& (line.items.len() > 1 || text.glyphs.len() > 1) && (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; remaining += amount;
} }
} }
@ -519,7 +540,7 @@ pub fn commit(
let mut frame = layout_and_modify(*styles, |styles| { let mut frame = layout_and_modify(*styles, |styles| {
layout_box(elem, engine, loc.relayout(), styles, region) 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); push(&mut offset, frame, idx);
} else { } else {
offset += amount; offset += amount;

View File

@ -927,9 +927,9 @@ impl Estimates {
let byte_len = g.range.len(); let byte_len = g.range.len();
let stretch = g.stretchability().0 + g.stretchability().1; let stretch = g.stretchability().0 + g.stretchability().1;
let shrink = g.shrinkability().0 + g.shrinkability().1; let shrink = g.shrinkability().0 + g.shrinkability().1;
widths.push(byte_len, g.x_advance.at(shaped.size)); widths.push(byte_len, g.x_advance.at(g.size));
stretchability.push(byte_len, stretch.at(shaped.size)); stretchability.push(byte_len, stretch.at(g.size));
shrinkability.push(byte_len, shrink.at(shaped.size)); shrinkability.push(byte_len, shrink.at(g.size));
justifiables.push(byte_len, g.is_justifiable() as usize); justifiables.push(byte_len, g.is_justifiable() as usize);
} }
} else { } else {

View File

@ -29,7 +29,7 @@ use typst_utils::{Numeric, SliceExt};
use self::collect::{collect, Item, Segment, SpanMapper}; use self::collect::{collect, Item, Segment, SpanMapper};
use self::deco::decorate; use self::deco::decorate;
use self::finalize::finalize; 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::linebreak::{linebreak, Breakpoint};
use self::prepare::{prepare, Preparation}; use self::prepare::{prepare, Preparation};
use self::shaping::{ use self::shaping::{

View File

@ -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. // The spacing is default to 1/4 em, and can be shrunk to 1/8 em.
glyph.x_advance += Em::new(0.25); glyph.x_advance += Em::new(0.25);
glyph.adjustability.shrinkability.1 += Em::new(0.125); 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 // 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_advance += Em::new(0.25);
glyph.x_offset += Em::new(0.25); glyph.x_offset += Em::new(0.25);
glyph.adjustability.shrinkability.0 += Em::new(0.125); 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); prev = Some(glyph);

View File

@ -3,14 +3,15 @@ use std::fmt::{self, Debug, Formatter};
use std::sync::Arc; use std::sync::Arc;
use az::SaturatingAs; use az::SaturatingAs;
use rustybuzz::{BufferFlags, ShapePlan, UnicodeBuffer}; use rustybuzz::{BufferFlags, Feature, ShapePlan, UnicodeBuffer};
use ttf_parser::gsub::SubstitutionSubtable;
use ttf_parser::Tag; use ttf_parser::Tag;
use typst_library::engine::Engine; use typst_library::engine::Engine;
use typst_library::foundations::{Smart, StyleChain}; use typst_library::foundations::{Smart, StyleChain};
use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Size}; use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Size};
use typst_library::text::{ use typst_library::text::{
families, features, is_default_ignorable, language, variant, Font, FontFamily, 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_library::World;
use typst_utils::SliceExt; use typst_utils::SliceExt;
@ -41,8 +42,6 @@ pub struct ShapedText<'a> {
pub styles: StyleChain<'a>, pub styles: StyleChain<'a>,
/// The font variant. /// The font variant.
pub variant: FontVariant, pub variant: FontVariant,
/// The font size.
pub size: Abs,
/// The width of the text's bounding box. /// The width of the text's bounding box.
pub width: Abs, pub width: Abs,
/// The shaped glyphs. /// The shaped glyphs.
@ -62,6 +61,8 @@ pub struct ShapedGlyph {
pub x_offset: Em, pub x_offset: Em,
/// The vertical offset of the glyph. /// The vertical offset of the glyph.
pub y_offset: Em, pub y_offset: Em,
/// The font size for the glyph.
pub size: Abs,
/// The adjustability of the glyph. /// The adjustability of the glyph.
pub adjustability: Adjustability, pub adjustability: Adjustability,
/// The byte range of this glyph's cluster in the full inline layout. A /// 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); let mut frame = Frame::soft(size);
frame.set_baseline(top); frame.set_baseline(top);
let size = TextElem::size_in(self.styles);
let shift = TextElem::baseline_in(self.styles); let shift = TextElem::baseline_in(self.styles);
let decos = TextElem::deco_in(self.styles); let decos = TextElem::deco_in(self.styles);
let fill = TextElem::fill_in(self.styles); let fill = TextElem::fill_in(self.styles);
let stroke = TextElem::stroke_in(self.styles); let stroke = TextElem::stroke_in(self.styles);
let span_offset = TextElem::span_offset_in(self.styles); let span_offset = TextElem::span_offset_in(self.styles);
for ((font, y_offset), group) in for ((font, y_offset, glyph_size), group) in self
self.glyphs.as_ref().group_by_key(|g| (g.font.clone(), g.y_offset)) .glyphs
.as_ref()
.group_by_key(|g| (g.font.clone(), g.y_offset, g.size))
{ {
let mut range = group[0].range.clone(); let mut range = group[0].range.clone();
for glyph in group { for glyph in group {
@ -237,7 +241,7 @@ impl<'a> ShapedText<'a> {
range.end = range.end.max(glyph.range.end); 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<Glyph> = group let glyphs: Vec<Glyph> = group
.iter() .iter()
.map(|shaped: &ShapedGlyph| { .map(|shaped: &ShapedGlyph| {
@ -257,11 +261,11 @@ impl<'a> ShapedText<'a> {
adjustability_right * justification_ratio; adjustability_right * justification_ratio;
if shaped.is_justifiable() { if shaped.is_justifiable() {
justification_right += 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) frame.size_mut().x += justification_left.at(glyph_size)
+ justification_right.at(self.size); + justification_right.at(glyph_size);
// We may not be able to reach the offset completely if // We may not be able to reach the offset completely if
// it exceeds u16, but better to have a roughly correct // it exceeds u16, but better to have a roughly correct
@ -304,7 +308,7 @@ impl<'a> ShapedText<'a> {
let item = TextItem { let item = TextItem {
font, font,
size: self.size, size: glyph_size,
lang: self.lang, lang: self.lang,
region: self.region, region: self.region,
fill: fill.clone(), fill: fill.clone(),
@ -336,12 +340,13 @@ impl<'a> ShapedText<'a> {
let mut top = Abs::zero(); let mut top = Abs::zero();
let mut bottom = Abs::zero(); let mut bottom = Abs::zero();
let size = TextElem::size_in(self.styles);
let top_edge = TextElem::top_edge_in(self.styles); let top_edge = TextElem::top_edge_in(self.styles);
let bottom_edge = TextElem::bottom_edge_in(self.styles); let bottom_edge = TextElem::bottom_edge_in(self.styles);
// Expand top and bottom by reading the font's vertical metrics. // Expand top and bottom by reading the font's vertical metrics.
let mut expand = |font: &Font, bounds: TextEdgeBounds| { 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); top.set_max(t);
bottom.set_max(b); bottom.set_max(b);
}; };
@ -388,18 +393,16 @@ impl<'a> ShapedText<'a> {
pub fn stretchability(&self) -> Abs { pub fn stretchability(&self) -> Abs {
self.glyphs self.glyphs
.iter() .iter()
.map(|g| g.stretchability().0 + g.stretchability().1) .map(|g| (g.stretchability().0 + g.stretchability().1).at(g.size))
.sum::<Em>() .sum()
.at(self.size)
} }
/// The shrinkability of the text /// The shrinkability of the text
pub fn shrinkability(&self) -> Abs { pub fn shrinkability(&self) -> Abs {
self.glyphs self.glyphs
.iter() .iter()
.map(|g| g.shrinkability().0 + g.shrinkability().1) .map(|g| (g.shrinkability().0 + g.shrinkability().1).at(g.size))
.sum::<Em>() .sum()
.at(self.size)
} }
/// Reshape a range of the shaped text, reusing information from this /// Reshape a range of the shaped text, reusing information from this
@ -418,9 +421,8 @@ impl<'a> ShapedText<'a> {
lang: self.lang, lang: self.lang,
region: self.region, region: self.region,
styles: self.styles, styles: self.styles,
size: self.size,
variant: self.variant, variant: self.variant,
width: glyphs.iter().map(|g| g.x_advance).sum::<Em>().at(self.size), width: glyphs_width(glyphs),
glyphs: Cow::Borrowed(glyphs), glyphs: Cow::Borrowed(glyphs),
} }
} else { } else {
@ -484,13 +486,15 @@ impl<'a> ShapedText<'a> {
// that subtracting either of the endpoints by self.base doesn't // that subtracting either of the endpoints by self.base doesn't
// underflow. See <https://github.com/typst/typst/issues/2283>. // underflow. See <https://github.com/typst/typst/issues/2283>.
.unwrap_or_else(|| self.base..self.base); .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 { let glyph = ShapedGlyph {
font, font,
glyph_id: glyph_id.0, glyph_id: glyph_id.0,
x_advance, x_advance,
x_offset: Em::zero(), x_offset: Em::zero(),
y_offset: Em::zero(), y_offset: Em::zero(),
size,
adjustability: Adjustability::default(), adjustability: Adjustability::default(),
range, range,
safe_to_break: true, safe_to_break: true,
@ -666,6 +670,7 @@ fn shape<'a>(
region: Option<Region>, region: Option<Region>,
) -> ShapedText<'a> { ) -> ShapedText<'a> {
let size = TextElem::size_in(styles); let size = TextElem::size_in(styles);
let shift_settings = TextElem::shift_settings_in(styles);
let mut ctx = ShapingContext { let mut ctx = ShapingContext {
engine, engine,
size, size,
@ -676,6 +681,7 @@ fn shape<'a>(
features: features(styles), features: features(styles),
fallback: TextElem::fallback_in(styles), fallback: TextElem::fallback_in(styles),
dir, dir,
shift_settings,
}; };
if !text.is_empty() { if !text.is_empty() {
@ -698,12 +704,17 @@ fn shape<'a>(
region, region,
styles, styles,
variant: ctx.variant, variant: ctx.variant,
size, width: glyphs_width(&ctx.glyphs),
width: ctx.glyphs.iter().map(|g| g.x_advance).sum::<Em>().at(size),
glyphs: Cow::Owned(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. /// Holds shaping results and metadata common to all shaped segments.
struct ShapingContext<'a, 'v> { struct ShapingContext<'a, 'v> {
engine: &'a Engine<'v>, engine: &'a Engine<'v>,
@ -715,6 +726,7 @@ struct ShapingContext<'a, 'v> {
features: Vec<rustybuzz::Feature>, features: Vec<rustybuzz::Feature>,
fallback: bool, fallback: bool,
dir: Dir, dir: Dir,
shift_settings: Option<ShiftSettings>,
} }
/// Shape text with font fallback using the `families` iterator. /// Shape text with font fallback using the `families` iterator.
@ -789,6 +801,18 @@ fn shape_segment<'a>(
// text extraction. // text extraction.
buffer.set_flags(BufferFlags::REMOVE_DEFAULT_IGNORABLES); 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, // Prepare the shape plan. This plan depends on direction, script, language,
// and features, but is independent from the text and can thus be memoized. // and features, but is independent from the text and can thus be memoized.
let plan = create_shape_plan( let plan = create_shape_plan(
@ -799,6 +823,10 @@ fn shape_segment<'a>(
&ctx.features, &ctx.features,
); );
if has_shift_feature {
ctx.features.pop();
}
// Shape! // Shape!
let buffer = rustybuzz::shape_with_plan(font.rusty(), &plan, buffer); let buffer = rustybuzz::shape_with_plan(font.rusty(), &plan, buffer);
let infos = buffer.glyph_infos(); let infos = buffer.glyph_infos();
@ -869,8 +897,9 @@ fn shape_segment<'a>(
glyph_id: info.glyph_id as u16, glyph_id: info.glyph_id as u16,
// TODO: Don't ignore y_advance. // TODO: Don't ignore y_advance.
x_advance, x_advance,
x_offset: font.to_em(pos[i].x_offset), x_offset: font.to_em(pos[i].x_offset) + script_compensation,
y_offset: font.to_em(pos[i].y_offset), y_offset: font.to_em(pos[i].y_offset) + script_shift,
size: scale.at(ctx.size),
adjustability: Adjustability::default(), adjustability: Adjustability::default(),
range: start..end, range: start..end,
safe_to_break: !info.unsafe_to_break(), safe_to_break: !info.unsafe_to_break(),
@ -932,6 +961,64 @@ fn shape_segment<'a>(
ctx.used.pop(); 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<Feature>) {
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::<SubstitutionSubtable>(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. /// Create a shape plan.
#[comemo::memoize] #[comemo::memoize]
pub fn create_shape_plan( pub fn create_shape_plan(
@ -963,6 +1050,7 @@ fn shape_tofus(ctx: &mut ShapingContext, base: usize, text: &str, font: Font) {
x_advance, x_advance,
x_offset: Em::zero(), x_offset: Em::zero(),
y_offset: Em::zero(), y_offset: Em::zero(),
size: ctx.size,
adjustability: Adjustability::default(), adjustability: Adjustability::default(),
range: start..end, range: start..end,
safe_to_break: true, 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. /// Apply tracking and spacing to the shaped glyphs.
fn track_and_space(ctx: &mut ShapingContext) { fn track_and_space(ctx: &mut ShapingContext) {
let tracking = Em::from_length(TextElem::tracking_in(ctx.styles), ctx.size); let tracking = Em::from_abs(TextElem::tracking_in(ctx.styles), ctx.size);
let spacing = let spacing = TextElem::spacing_in(ctx.styles).map(|abs| Em::from_abs(abs, ctx.size));
TextElem::spacing_in(ctx.styles).map(|abs| Em::from_length(abs, ctx.size));
let mut glyphs = ctx.glyphs.iter_mut().peekable(); let mut glyphs = ctx.glyphs.iter_mut().peekable();
while let Some(glyph) = glyphs.next() { while let Some(glyph) = glyphs.next() {

View File

@ -1,6 +1,6 @@
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::foundations::{Packed, StyleChain}; use typst_library::foundations::{Packed, StyleChain};
use typst_library::layout::{Em, Frame, Point, Size}; use typst_library::layout::{Frame, Point, Size};
use typst_library::math::AccentElem; use typst_library::math::AccentElem;
use super::{ use super::{
@ -8,9 +8,6 @@ use super::{
MathFragment, MathFragment,
}; };
/// How much the accent can be shorter than the base.
const ACCENT_SHORT_FALL: Em = Em::new(0.5);
/// Lays out an [`AccentElem`]. /// Lays out an [`AccentElem`].
#[typst_macros::time(name = "math.accent", span = elem.span())] #[typst_macros::time(name = "math.accent", span = elem.span())]
pub fn layout_accent( pub fn layout_accent(
@ -45,11 +42,8 @@ pub fn layout_accent(
let mut glyph = let mut glyph =
GlyphFragment::new_char(ctx.font, accent_styles, accent.0, elem.span())?; GlyphFragment::new_char(ctx.font, accent_styles, accent.0, elem.span())?;
// Forcing the accent to be at least as large as the base makes it too wide let width = elem.size(styles).resolve(ctx.engine, styles, base.width())?;
// in many cases. glyph.stretch_horizontal(ctx, width);
let width = elem.size(styles).relative_to(base.width());
let short_fall = ACCENT_SHORT_FALL.at(glyph.item.size);
glyph.stretch_horizontal(ctx, width - short_fall);
let accent_attach = glyph.accent_attach.0; let accent_attach = glyph.accent_attach.0;
let accent = glyph.into_frame(); let accent = glyph.into_frame();

View File

@ -1,8 +1,9 @@
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::foundations::{Packed, StyleChain, SymbolElem}; use typst_library::foundations::{Packed, StyleChain, SymbolElem};
use typst_library::layout::{Abs, Axis, Corner, Frame, Point, Rel, Size}; use typst_library::layout::{Abs, Axis, Corner, Frame, Point, Size};
use typst_library::math::{ use typst_library::math::{
AttachElem, EquationElem, LimitsElem, PrimesElem, ScriptsElem, StretchElem, AttachElem, EquationElem, LimitsElem, PrimesElem, ScriptsElem, StretchElem,
StretchSize,
}; };
use typst_utils::OptionExt; use typst_utils::OptionExt;
@ -66,12 +67,12 @@ pub fn layout_attach(
let relative_to_width = measure!(t, width).max(measure!(b, width)); let relative_to_width = measure!(t, width).max(measure!(b, width));
stretch_fragment( stretch_fragment(
ctx, ctx,
styles,
&mut base, &mut base,
Some(Axis::X), Some(Axis::X),
Some(relative_to_width), Some(relative_to_width),
stretch, &stretch,
Abs::zero(), )?;
);
} }
let fragments = [ let fragments = [
@ -154,7 +155,7 @@ pub fn layout_limits(
} }
/// Get the size to stretch the base to. /// Get the size to stretch the base to.
fn stretch_size(styles: StyleChain, elem: &Packed<AttachElem>) -> Option<Rel<Abs>> { fn stretch_size(styles: StyleChain, elem: &Packed<AttachElem>) -> Option<StretchSize> {
// Extract from an EquationElem. // Extract from an EquationElem.
let mut base = &elem.base; let mut base = &elem.base;
while let Some(equation) = base.to_packed::<EquationElem>() { while let Some(equation) = base.to_packed::<EquationElem>() {

View File

@ -1,14 +1,13 @@
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::foundations::{Content, Packed, Resolve, StyleChain, SymbolElem}; use typst_library::foundations::{Content, Packed, Resolve, StyleChain, SymbolElem};
use typst_library::layout::{Em, Frame, FrameItem, Point, Size}; use typst_library::layout::{Em, Frame, FrameItem, Point, Size};
use typst_library::math::{BinomElem, FracElem}; use typst_library::math::{BinomElem, FracElem, DELIM_SHORT_FALL};
use typst_library::text::TextElem; use typst_library::text::TextElem;
use typst_library::visualize::{FixedStroke, Geometry}; use typst_library::visualize::{FixedStroke, Geometry};
use typst_syntax::Span; use typst_syntax::Span;
use super::{ use super::{
style_for_denominator, style_for_numerator, FrameFragment, GlyphFragment, style_for_denominator, style_for_numerator, FrameFragment, GlyphFragment, MathContext,
MathContext, DELIM_SHORT_FALL,
}; };
const FRAC_AROUND: Em = Em::new(0.1); const FRAC_AROUND: Em = Em::new(0.1);
@ -49,7 +48,7 @@ fn layout_frac_like(
binom: bool, binom: bool,
span: Span, span: Span,
) -> SourceResult<()> { ) -> SourceResult<()> {
let short_fall = DELIM_SHORT_FALL.resolve(styles); let short_fall = DELIM_SHORT_FALL.abs().resolve(styles);
let axis = scaled!(ctx, styles, axis_height); let axis = scaled!(ctx, styles, axis_height);
let thickness = scaled!(ctx, styles, fraction_rule_thickness); let thickness = scaled!(ctx, styles, fraction_rule_thickness);
let shift_up = scaled!( let shift_up = scaled!(

View File

@ -215,7 +215,7 @@ impl MathFragment {
&glyph.item.font, &glyph.item.font,
GlyphId(glyph.item.glyphs[glyph_index].id), GlyphId(glyph.item.glyphs[glyph_index].id),
corner, corner,
Em::from_length(height, glyph.item.size), Em::from_abs(height, glyph.item.size),
) )
.unwrap_or_default() .unwrap_or_default()
.at(glyph.item.size) .at(glyph.item.size)
@ -767,8 +767,8 @@ fn assemble(
advance += ratio * (max_overlap - min_overlap); advance += ratio * (max_overlap - min_overlap);
} }
let (x, y) = match axis { let (x, y) = match axis {
Axis::X => (Em::from_length(advance, base.item.size), Em::zero()), Axis::X => (Em::from_abs(advance, base.item.size), Em::zero()),
Axis::Y => (Em::zero(), Em::from_length(advance, base.item.size)), Axis::Y => (Em::zero(), Em::from_abs(advance, base.item.size)),
}; };
glyphs.push(Glyph { glyphs.push(Glyph {
id: part.glyph_id.0, id: part.glyph_id.0,

View File

@ -1,11 +1,11 @@
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::foundations::{Packed, StyleChain}; use typst_library::foundations::{Packed, StyleChain};
use typst_library::layout::{Abs, Axis, Rel}; use typst_library::layout::{Abs, Axis};
use typst_library::math::{EquationElem, LrElem, MidElem}; use typst_library::math::{EquationElem, LrElem, MidElem, StretchSize};
use typst_utils::SliceExt; use typst_utils::SliceExt;
use unicode_math_class::MathClass; use unicode_math_class::MathClass;
use super::{stretch_fragment, MathContext, MathFragment, DELIM_SHORT_FALL}; use super::{stretch_fragment, MathContext, MathFragment};
/// Lays out an [`LrElem`]. /// Lays out an [`LrElem`].
#[typst_macros::time(name = "math.lr", span = elem.span())] #[typst_macros::time(name = "math.lr", span = elem.span())]
@ -22,7 +22,7 @@ pub fn layout_lr(
// Extract implicit LrElem. // Extract implicit LrElem.
if let Some(lr) = body.to_packed::<LrElem>() { if let Some(lr) = body.to_packed::<LrElem>() {
if lr.size(styles).is_one() { if lr.size(styles).is_lr_default() {
body = &lr.body; body = &lr.body;
} }
} }
@ -45,10 +45,24 @@ pub fn layout_lr(
// Scale up fragments at both ends. // Scale up fragments at both ends.
match inner_fragments { match inner_fragments {
[one] => scale_if_delimiter(ctx, one, relative_to, height, None), [one] => scale_if_delimiter(ctx, styles, one, relative_to, &height, None)?,
[first, .., last] => { [first, .., last] => {
scale_if_delimiter(ctx, first, relative_to, height, Some(MathClass::Opening)); scale_if_delimiter(
scale_if_delimiter(ctx, last, relative_to, height, Some(MathClass::Closing)); ctx,
styles,
first,
relative_to,
&height,
Some(MathClass::Opening),
)?;
scale_if_delimiter(
ctx,
styles,
last,
relative_to,
&height,
Some(MathClass::Closing),
)?;
} }
[] => {} [] => {}
} }
@ -58,7 +72,7 @@ pub fn layout_lr(
if let MathFragment::Glyph(ref mut glyph) = fragment { if let MathFragment::Glyph(ref mut glyph) = fragment {
if glyph.mid_stretched == Some(false) { if glyph.mid_stretched == Some(false) {
glyph.mid_stretched = Some(true); glyph.mid_stretched = Some(true);
scale(ctx, fragment, relative_to, height); scale(ctx, styles, fragment, relative_to, &height)?;
} }
} }
} }
@ -112,32 +126,32 @@ pub fn layout_mid(
/// it is a delimiter, in a way that cannot be overridden by the user. /// it is a delimiter, in a way that cannot be overridden by the user.
fn scale_if_delimiter( fn scale_if_delimiter(
ctx: &mut MathContext, ctx: &mut MathContext,
styles: StyleChain,
fragment: &mut MathFragment, fragment: &mut MathFragment,
relative_to: Abs, relative_to: Abs,
height: Rel<Abs>, height: &StretchSize,
apply: Option<MathClass>, apply: Option<MathClass>,
) { ) -> SourceResult<()> {
if matches!( if matches!(
fragment.class(), fragment.class(),
MathClass::Opening | MathClass::Closing | MathClass::Fence MathClass::Opening | MathClass::Closing | MathClass::Fence
) { ) {
scale(ctx, fragment, relative_to, height); scale(ctx, styles, fragment, relative_to, height)?;
if let Some(class) = apply { if let Some(class) = apply {
fragment.set_class(class); fragment.set_class(class);
} }
} }
Ok(())
} }
/// Scales a math fragment to a height. /// Scales a math fragment to a height.
fn scale( fn scale(
ctx: &mut MathContext, ctx: &mut MathContext,
styles: StyleChain,
fragment: &mut MathFragment, fragment: &mut MathFragment,
relative_to: Abs, relative_to: Abs,
height: Rel<Abs>, height: &StretchSize,
) { ) -> SourceResult<()> {
// This unwrap doesn't really matter. If it is None, then the fragment stretch_fragment(ctx, styles, fragment, Some(Axis::Y), Some(relative_to), height)
// won't be stretchable anyways.
let short_fall = DELIM_SHORT_FALL.at(fragment.font_size().unwrap_or_default());
stretch_fragment(ctx, fragment, Some(Axis::Y), Some(relative_to), height, short_fall);
} }

View File

@ -1,19 +1,20 @@
use typst_library::diag::{bail, warning, SourceResult}; use typst_library::diag::{bail, warning, SourceResult};
use typst_library::foundations::{Content, Packed, Resolve, StyleChain}; use typst_library::foundations::{Content, Packed, Resolve, StyleChain};
use typst_library::layout::{ use typst_library::layout::{
Abs, Axes, Em, FixedAlignment, Frame, FrameItem, Point, Ratio, Rel, Size, Abs, Axes, Em, FixedAlignment, Frame, FrameItem, Point, Rel, Size,
};
use typst_library::math::{
Augment, AugmentOffsets, CasesElem, MatElem, StretchSize, VecElem,
}; };
use typst_library::math::{Augment, AugmentOffsets, CasesElem, MatElem, VecElem};
use typst_library::text::TextElem; use typst_library::text::TextElem;
use typst_library::visualize::{FillRule, FixedStroke, Geometry, LineCap, Shape}; use typst_library::visualize::{FillRule, FixedStroke, Geometry, LineCap, Shape};
use typst_syntax::Span; use typst_syntax::Span;
use super::{ use super::{
alignments, style_for_denominator, AlignmentResult, FrameFragment, GlyphFragment, alignments, style_for_denominator, AlignmentResult, FrameFragment, GlyphFragment,
LeftRightAlternator, MathContext, DELIM_SHORT_FALL, LeftRightAlternator, MathContext,
}; };
const VERTICAL_PADDING: Ratio = Ratio::new(0.1);
const DEFAULT_STROKE_THICKNESS: Em = Em::new(0.05); const DEFAULT_STROKE_THICKNESS: Em = Em::new(0.05);
/// Lays out a [`VecElem`]. /// Lays out a [`VecElem`].
@ -39,7 +40,15 @@ pub fn layout_vec(
)?; )?;
let delim = elem.delim(styles); let delim = elem.delim(styles);
layout_delimiters(ctx, styles, frame, delim.open(), delim.close(), span) layout_delimiters(
ctx,
styles,
frame,
&elem.delim_size(styles),
delim.open(),
delim.close(),
span,
)
} }
/// Lays out a [`CasesElem`]. /// Lays out a [`CasesElem`].
@ -67,7 +76,7 @@ pub fn layout_cases(
let delim = elem.delim(styles); let delim = elem.delim(styles);
let (open, close) = let (open, close) =
if elem.reverse(styles) { (None, delim.close()) } else { (delim.open(), None) }; if elem.reverse(styles) { (None, delim.close()) } else { (delim.open(), None) };
layout_delimiters(ctx, styles, frame, open, close, span) layout_delimiters(ctx, styles, frame, &elem.delim_size(styles), open, close, span)
} }
/// Lays out a [`MatElem`]. /// Lays out a [`MatElem`].
@ -125,7 +134,15 @@ pub fn layout_mat(
)?; )?;
let delim = elem.delim(styles); let delim = elem.delim(styles);
layout_delimiters(ctx, styles, frame, delim.open(), delim.close(), span) layout_delimiters(
ctx,
styles,
frame,
&elem.delim_size(styles),
delim.open(),
delim.close(),
span,
)
} }
/// Layout the inner contents of a matrix, vector, or cases. /// Layout the inner contents of a matrix, vector, or cases.
@ -306,19 +323,20 @@ fn layout_delimiters(
ctx: &mut MathContext, ctx: &mut MathContext,
styles: StyleChain, styles: StyleChain,
mut frame: Frame, mut frame: Frame,
size: &StretchSize,
left: Option<char>, left: Option<char>,
right: Option<char>, right: Option<char>,
span: Span, span: Span,
) -> SourceResult<()> { ) -> SourceResult<()> {
let short_fall = DELIM_SHORT_FALL.resolve(styles);
let axis = scaled!(ctx, styles, axis_height); let axis = scaled!(ctx, styles, axis_height);
let height = frame.height(); let height = frame.height();
let target = height + VERTICAL_PADDING.of(height);
frame.set_baseline(height / 2.0 + axis); frame.set_baseline(height / 2.0 + axis);
let target = size.resolve(ctx.engine, styles, height)?;
if let Some(left_c) = left { if let Some(left_c) = left {
let mut left = GlyphFragment::new_char(ctx.font, styles, left_c, span)?; let mut left = GlyphFragment::new_char(ctx.font, styles, left_c, span)?;
left.stretch_vertical(ctx, target - short_fall); left.stretch_vertical(ctx, target);
left.center_on_axis(); left.center_on_axis();
ctx.push(left); ctx.push(left);
} }
@ -327,7 +345,7 @@ fn layout_delimiters(
if let Some(right_c) = right { if let Some(right_c) = right {
let mut right = GlyphFragment::new_char(ctx.font, styles, right_c, span)?; let mut right = GlyphFragment::new_char(ctx.font, styles, right_c, span)?;
right.stretch_vertical(ctx, target - short_fall); right.stretch_vertical(ctx, target);
right.center_on_axis(); right.center_on_axis();
ctx.push(right); ctx.push(right);
} }

View File

@ -1,7 +1,7 @@
use ttf_parser::math::MathValue; use ttf_parser::math::MathValue;
use ttf_parser::Tag; use ttf_parser::Tag;
use typst_library::foundations::{Style, StyleChain}; use typst_library::foundations::{Style, StyleChain};
use typst_library::layout::{Abs, Em, FixedAlignment, Frame, Point, Size}; use typst_library::layout::{Abs, FixedAlignment, Frame, Point, Size};
use typst_library::math::{EquationElem, MathSize}; use typst_library::math::{EquationElem, MathSize};
use typst_library::text::{FontFeatures, TextElem}; use typst_library::text::{FontFeatures, TextElem};
use typst_utils::LazyHash; use typst_utils::LazyHash;
@ -30,9 +30,6 @@ macro_rules! percent {
}; };
} }
/// How much less high scaled delimiters can be than what they wrap.
pub const DELIM_SHORT_FALL: Em = Em::new(0.1);
/// Converts some unit to an absolute length with the current font & font size. /// Converts some unit to an absolute length with the current font & font size.
pub trait Scaled { pub trait Scaled {
fn scaled(self, ctx: &MathContext, font_size: Abs) -> Abs; fn scaled(self, ctx: &MathContext, font_size: Abs) -> Abs;

View File

@ -1,7 +1,7 @@
use typst_library::diag::{warning, SourceResult}; use typst_library::diag::{warning, SourceResult};
use typst_library::foundations::{Packed, StyleChain}; use typst_library::foundations::{Packed, StyleChain};
use typst_library::layout::{Abs, Axis, Rel}; use typst_library::layout::{Abs, Axis};
use typst_library::math::StretchElem; use typst_library::math::{StretchElem, StretchSize};
use typst_utils::Get; use typst_utils::Get;
use super::{stretch_axes, MathContext, MathFragment}; use super::{stretch_axes, MathContext, MathFragment};
@ -14,7 +14,7 @@ pub fn layout_stretch(
styles: StyleChain, styles: StyleChain,
) -> SourceResult<()> { ) -> SourceResult<()> {
let mut fragment = ctx.layout_into_fragment(&elem.body, styles)?; let mut fragment = ctx.layout_into_fragment(&elem.body, styles)?;
stretch_fragment(ctx, &mut fragment, None, None, elem.size(styles), Abs::zero()); stretch_fragment(ctx, styles, &mut fragment, None, None, &elem.size(styles))?;
ctx.push(fragment); ctx.push(fragment);
Ok(()) Ok(())
} }
@ -22,29 +22,29 @@ pub fn layout_stretch(
/// Attempts to stretch the given fragment by/to the amount given in stretch. /// Attempts to stretch the given fragment by/to the amount given in stretch.
pub fn stretch_fragment( pub fn stretch_fragment(
ctx: &mut MathContext, ctx: &mut MathContext,
styles: StyleChain,
fragment: &mut MathFragment, fragment: &mut MathFragment,
axis: Option<Axis>, axis: Option<Axis>,
relative_to: Option<Abs>, relative_to: Option<Abs>,
stretch: Rel<Abs>, stretch: &StretchSize,
short_fall: Abs, ) -> SourceResult<()> {
) {
let size = fragment.size(); let size = fragment.size();
let MathFragment::Glyph(ref mut glyph) = fragment else { return }; let MathFragment::Glyph(ref mut glyph) = fragment else { return Ok(()) };
// Return if we attempt to stretch along an axis which isn't stretchable, // Return if we attempt to stretch along an axis which isn't stretchable,
// so that the original fragment isn't modified. // so that the original fragment isn't modified.
let axes = stretch_axes(&glyph.item.font, glyph.base_glyph.id); let axes = stretch_axes(&glyph.item.font, glyph.base_glyph.id);
let stretch_axis = if let Some(axis) = axis { let stretch_axis = if let Some(axis) = axis {
if !axes.get(axis) { if !axes.get(axis) {
return; return Ok(());
} }
axis axis
} else { } else {
match (axes.x, axes.y) { match (axes.x, axes.y) {
(true, false) => Axis::X, (true, false) => Axis::X,
(false, true) => Axis::Y, (false, true) => Axis::Y,
(false, false) => return, (false, false) => return Ok(()),
(true, true) => { (true, true) => {
// As far as we know, there aren't any glyphs that have both // As far as we know, there aren't any glyphs that have both
// vertical and horizontal constructions. So for the time being, we // vertical and horizontal constructions. So for the time being, we
@ -55,16 +55,19 @@ pub fn stretch_fragment(
hint: "this is probably a font bug"; hint: "this is probably a font bug";
hint: "please file an issue at https://github.com/typst/typst/issues" hint: "please file an issue at https://github.com/typst/typst/issues"
)); ));
return; return Ok(());
} }
} }
}; };
let relative_to_size = relative_to.unwrap_or_else(|| size.get(stretch_axis)); let relative_to_size = relative_to.unwrap_or_else(|| size.get(stretch_axis));
let target = stretch.resolve(ctx.engine, styles, relative_to_size)?;
glyph.stretch(ctx, stretch.relative_to(relative_to_size) - short_fall, stretch_axis); glyph.stretch(ctx, target, stretch_axis);
if stretch_axis == Axis::Y { if stretch_axis == Axis::Y {
glyph.center_on_axis(); glyph.center_on_axis();
} }
Ok(())
} }

View File

@ -94,7 +94,7 @@ impl Array {
} }
/// Iterate over references to the contained values. /// Iterate over references to the contained values.
pub fn iter(&self) -> std::slice::Iter<Value> { pub fn iter(&self) -> std::slice::Iter<'_, Value> {
self.0.iter() self.0.iter()
} }
@ -604,7 +604,7 @@ impl Array {
Ok(acc) Ok(acc)
} }
/// Calculates the product all items (works for all types that can be /// Calculates the product of all items (works for all types that can be
/// multiplied). /// multiplied).
#[func] #[func]
pub fn product( pub fn product(

View File

@ -207,9 +207,9 @@ pub fn sqrt(
/// ``` /// ```
#[func] #[func]
pub fn root( pub fn root(
/// The expression to take the root of /// The expression to take the root of.
radicand: f64, radicand: f64,
/// Which root of the radicand to take /// Which root of the radicand to take.
index: Spanned<i64>, index: Spanned<i64>,
) -> SourceResult<f64> { ) -> SourceResult<f64> {
if index.v == 0 { if index.v == 0 {
@ -317,7 +317,7 @@ pub fn asin(
/// ``` /// ```
#[func(title = "Arccosine")] #[func(title = "Arccosine")]
pub fn acos( pub fn acos(
/// The number whose arcsine to calculate. Must be between -1 and 1. /// The number whose arccosine to calculate. Must be between -1 and 1.
value: Spanned<Num>, value: Spanned<Num>,
) -> SourceResult<Angle> { ) -> SourceResult<Angle> {
let val = value.v.float(); let val = value.v.float();
@ -387,7 +387,7 @@ pub fn cosh(
value.cosh() value.cosh()
} }
/// Calculates the hyperbolic tangent of an hyperbolic angle. /// Calculates the hyperbolic tangent of a hyperbolic angle.
/// ///
/// ```example /// ```example
/// #calc.tanh(0) \ /// #calc.tanh(0) \

View File

@ -114,7 +114,7 @@ impl Dict {
} }
/// Iterate over pairs of references to the contained keys and values. /// Iterate over pairs of references to the contained keys and values.
pub fn iter(&self) -> indexmap::map::Iter<Str, Value> { pub fn iter(&self) -> indexmap::map::Iter<'_, Str, Value> {
self.0.iter() self.0.iter()
} }

View File

@ -497,7 +497,8 @@ mod callbacks {
macro_rules! callback { macro_rules! callback {
($name:ident = ($($param:ident: $param_ty:ty),* $(,)?) -> $ret:ty) => { ($name:ident = ($($param:ident: $param_ty:ty),* $(,)?) -> $ret:ty) => {
#[derive(Debug, Clone, PartialEq, Hash)] #[derive(Debug, Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)]
pub struct $name { pub struct $name {
captured: Content, captured: Content,
f: fn(&Content, $($param_ty),*) -> $ret, f: fn(&Content, $($param_ty),*) -> $ret,
@ -535,6 +536,19 @@ mod callbacks {
(self.f)(&self.captured, $($param),*) (self.f)(&self.captured, $($param),*)
} }
} }
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
// Comparing function pointers is problematic. Since for
// each type of content, there is typically just one
// callback, we skip it. It barely matters anyway since
// getting into a comparison codepath for inline & block
// elements containing callback bodies is close to
// impossible (as these are generally generated in show
// rules).
self.captured.eq(&other.captured)
}
}
}; };
} }

View File

@ -6,7 +6,7 @@ use ecow::EcoString;
use typst_utils::{Numeric, Scalar}; use typst_utils::{Numeric, Scalar};
use crate::foundations::{cast, repr, Repr, Resolve, StyleChain, Value}; use crate::foundations::{cast, repr, Repr, Resolve, StyleChain, Value};
use crate::layout::Abs; use crate::layout::{Abs, Length};
use crate::text::TextElem; use crate::text::TextElem;
/// A length that is relative to the font size. /// A length that is relative to the font size.
@ -26,18 +26,18 @@ impl Em {
Self(Scalar::ONE) Self(Scalar::ONE)
} }
/// Create a font-relative length. /// Creates a font-relative length.
pub const fn new(em: f64) -> Self { pub const fn new(em: f64) -> Self {
Self(Scalar::new(em)) 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<f64>, units_per_em: f64) -> Self { pub fn from_units(units: impl Into<f64>, units_per_em: f64) -> Self {
Self(Scalar::new(units.into() / units_per_em)) Self(Scalar::new(units.into() / units_per_em))
} }
/// Create an em length from a length at the given font size. /// Creates an em length from an absolute length at the given font size.
pub fn from_length(length: Abs, font_size: Abs) -> Self { pub fn from_abs(length: Abs, font_size: Abs) -> Self {
let result = length / font_size; let result = length / font_size;
if result.is_finite() { if result.is_finite() {
Self(Scalar::new(result)) 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. /// The number of em units.
pub const fn get(self) -> f64 { pub const fn get(self) -> f64 {
(self.0).get() (self.0).get()
@ -56,7 +61,7 @@ impl Em {
Self::new(self.get().abs()) 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 { pub fn at(self, font_size: Abs) -> Abs {
let resolved = font_size * self.get(); let resolved = font_size * self.get();
if resolved.is_finite() { if resolved.is_finite() {

View File

@ -47,12 +47,12 @@ impl Fragment {
} }
/// Iterate over the contained frames. /// Iterate over the contained frames.
pub fn iter(&self) -> std::slice::Iter<Frame> { pub fn iter(&self) -> std::slice::Iter<'_, Frame> {
self.0.iter() self.0.iter()
} }
/// Iterate over the contained frames. /// Iterate over the contained frames.
pub fn iter_mut(&mut self) -> std::slice::IterMut<Frame> { pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Frame> {
self.0.iter_mut() self.0.iter_mut()
} }
} }

View File

@ -6,9 +6,21 @@ use icu_provider::AsDeserializingBufferProvider;
use icu_provider_blob::BlobDataProvider; use icu_provider_blob::BlobDataProvider;
use crate::diag::bail; use crate::diag::bail;
use crate::foundations::{cast, elem, func, Content, NativeElement, SymbolElem}; use crate::foundations::{
use crate::layout::{Length, Rel}; cast, elem, func, Content, NativeElement, NativeFunc, SymbolElem,
use crate::math::Mathy; };
use crate::layout::{Em, Length, Ratio, Rel};
use crate::math::{Mathy, StretchSize};
const ACCENT_SHORT_FALL: Em = Em::new(-0.5);
#[func(name = "x => x - 0.5em")]
const fn default_accent_size(base: Length) -> Rel {
Rel {
rel: Ratio::zero(),
abs: Length { abs: base.abs, em: ACCENT_SHORT_FALL },
}
}
/// Attaches an accent to a base. /// Attaches an accent to a base.
/// ///
@ -59,12 +71,14 @@ pub struct AccentElem {
/// The size of the accent, relative to the width of the base. /// The size of the accent, relative to the width of the base.
/// ///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
///
/// ```example /// ```example
/// $dash(A, size: #150%)$ /// $dash(A, size: #150%)$
/// ``` /// ```
#[resolve] #[default(<default_accent_size>::data().into())]
#[default(Rel::one())] pub size: StretchSize,
pub size: Rel<Length>,
/// Whether to remove the dot on top of lowercase i and j when adding a top /// Whether to remove the dot on top of lowercase i and j when adding a top
/// accent. /// accent.
@ -141,8 +155,11 @@ macro_rules! accents {
/// The base to which the accent is applied. /// The base to which the accent is applied.
base: Content, base: Content,
/// The size of the accent, relative to the width of the base. /// The size of the accent, relative to the width of the base.
///
/// See the [stretch documentation]($math.stretch.size) for
/// more information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// Whether to remove the dot on top of lowercase i and j when /// Whether to remove the dot on top of lowercase i and j when
/// adding a top accent. /// adding a top accent.
#[named] #[named]

View File

@ -1,5 +1,4 @@
use crate::foundations::{elem, Content, Packed}; use crate::foundations::{elem, Content, Packed};
use crate::layout::{Length, Rel};
use crate::math::{EquationElem, Mathy}; use crate::math::{EquationElem, Mathy};
/// A base with optional attachments. /// A base with optional attachments.
@ -128,31 +127,3 @@ pub struct LimitsElem {
#[default(true)] #[default(true)]
pub inline: bool, pub inline: bool,
} }
/// Stretches a glyph.
///
/// This function can also be used to automatically stretch the base of an
/// attachment, so that it fits the top and bottom attachments.
///
/// Note that only some glyphs can be stretched, and which ones can depend on
/// the math font being used. However, most math fonts are the same in this
/// regard.
///
/// ```example
/// $ H stretch(=)^"define" U + p V $
/// $ f : X stretch(->>, size: #150%)_"surjective" Y $
/// $ x stretch(harpoons.ltrb, size: #3em) y
/// stretch(\[, size: #150%) z $
/// ```
#[elem(Mathy)]
pub struct StretchElem {
/// The glyph to stretch.
#[required]
pub body: Content,
/// The size to stretch to, relative to the maximum size of the glyph and
/// its attachments.
#[resolve]
#[default(Rel::one())]
pub size: Rel<Length>,
}

View File

@ -1,6 +1,16 @@
use crate::foundations::{elem, func, Content, NativeElement, SymbolElem}; use crate::foundations::{elem, func, Content, NativeElement, NativeFunc, SymbolElem};
use crate::layout::{Length, Rel}; use crate::layout::{Em, Length, Ratio, Rel};
use crate::math::Mathy; use crate::math::{Mathy, StretchSize};
pub const DELIM_SHORT_FALL: Em = Em::new(-0.1);
#[func(name = "x => x - 0.1em")]
pub const fn default_lr_size(base: Length) -> Rel {
Rel {
rel: Ratio::zero(),
abs: Length { abs: base.abs, em: DELIM_SHORT_FALL },
}
}
/// Scales delimiters. /// Scales delimiters.
/// ///
@ -8,10 +18,13 @@ use crate::math::Mathy;
/// unmatched delimiters and to control the delimiter scaling more precisely. /// unmatched delimiters and to control the delimiter scaling more precisely.
#[elem(title = "Left/Right", Mathy)] #[elem(title = "Left/Right", Mathy)]
pub struct LrElem { pub struct LrElem {
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
#[resolve] /// content.
#[default(Rel::one())] ///
pub size: Rel<Length>, /// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[default(<default_lr_size>::data().into())]
pub size: StretchSize,
/// The delimited content, including the delimiters. /// The delimited content, including the delimiters.
#[required] #[required]
@ -43,9 +56,13 @@ pub struct MidElem {
/// ``` /// ```
#[func] #[func]
pub fn floor( pub fn floor(
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
/// content.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// The expression to floor. /// The expression to floor.
body: Content, body: Content,
) -> Content { ) -> Content {
@ -59,9 +76,13 @@ pub fn floor(
/// ``` /// ```
#[func] #[func]
pub fn ceil( pub fn ceil(
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
/// content.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// The expression to ceil. /// The expression to ceil.
body: Content, body: Content,
) -> Content { ) -> Content {
@ -75,9 +96,13 @@ pub fn ceil(
/// ``` /// ```
#[func] #[func]
pub fn round( pub fn round(
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
/// content.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// The expression to round. /// The expression to round.
body: Content, body: Content,
) -> Content { ) -> Content {
@ -91,9 +116,13 @@ pub fn round(
/// ``` /// ```
#[func] #[func]
pub fn abs( pub fn abs(
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
/// content.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// The expression to take the absolute value of. /// The expression to take the absolute value of.
body: Content, body: Content,
) -> Content { ) -> Content {
@ -107,9 +136,13 @@ pub fn abs(
/// ``` /// ```
#[func] #[func]
pub fn norm( pub fn norm(
/// The size of the brackets, relative to the height of the wrapped content. /// The size of the delimiters, relative to the height of the wrapped
/// content.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[named] #[named]
size: Option<Rel<Length>>, size: Option<StretchSize>,
/// The expression to take the norm of. /// The expression to take the norm of.
body: Content, body: Content,
) -> Content { ) -> Content {
@ -120,7 +153,7 @@ fn delimited(
body: Content, body: Content,
left: char, left: char,
right: char, right: char,
size: Option<Rel<Length>>, size: Option<StretchSize>,
) -> Content { ) -> Content {
let span = body.span(); let span = body.span();
let mut elem = LrElem::new(Content::sequence([ let mut elem = LrElem::new(Content::sequence([

View File

@ -5,15 +5,27 @@ use unicode_math_class::MathClass;
use crate::diag::{bail, At, HintedStrResult, StrResult}; use crate::diag::{bail, At, HintedStrResult, StrResult};
use crate::foundations::{ use crate::foundations::{
array, cast, dict, elem, Array, Content, Dict, Fold, NoneValue, Resolve, Smart, array, cast, dict, elem, func, Array, Content, Dict, Fold, NativeFunc, NoneValue,
StyleChain, Symbol, Value, Resolve, Smart, StyleChain, Symbol, Value,
}; };
use crate::layout::{Abs, Em, HAlignment, Length, Rel}; use crate::layout::{Abs, Em, HAlignment, Length, Ratio, Rel};
use crate::math::Mathy; use crate::math::{Mathy, StretchSize, DELIM_SHORT_FALL};
use crate::visualize::Stroke; use crate::visualize::Stroke;
const DEFAULT_ROW_GAP: Em = Em::new(0.2); const DEFAULT_ROW_GAP: Em = Em::new(0.2);
const DEFAULT_COL_GAP: Em = Em::new(0.5); const DEFAULT_COL_GAP: Em = Em::new(0.5);
const VERTICAL_PADDING: Ratio = Ratio::new(1.1);
#[func(name = "x => x * 1.1 - 0.1em")]
const fn default_mat_size(base: Length) -> Rel {
Rel {
rel: Ratio::zero(),
abs: Length {
abs: Abs::raw(base.abs.to_raw() * VERTICAL_PADDING.get()),
em: DELIM_SHORT_FALL,
},
}
}
/// A column vector. /// A column vector.
/// ///
@ -40,6 +52,13 @@ pub struct VecElem {
#[default(DelimiterPair::PAREN)] #[default(DelimiterPair::PAREN)]
pub delim: DelimiterPair, pub delim: DelimiterPair,
/// The size of the delimiters, relative to the elements' total height.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[default(<default_mat_size>::data().into())]
pub delim_size: StretchSize,
/// The horizontal alignment that each element should have. /// The horizontal alignment that each element should have.
/// ///
/// ```example /// ```example
@ -101,6 +120,13 @@ pub struct MatElem {
#[default(DelimiterPair::PAREN)] #[default(DelimiterPair::PAREN)]
pub delim: DelimiterPair, pub delim: DelimiterPair,
/// The size of the delimiters, relative to the cells' total height.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[default(<default_mat_size>::data().into())]
pub delim_size: StretchSize,
/// The horizontal alignment that each cell should have. /// The horizontal alignment that each cell should have.
/// ///
/// ```example /// ```example
@ -244,6 +270,13 @@ pub struct CasesElem {
#[default(DelimiterPair::BRACE)] #[default(DelimiterPair::BRACE)]
pub delim: DelimiterPair, pub delim: DelimiterPair,
/// The size of the delimiters, relative to the branches' total height.
///
/// See the [stretch documentation]($math.stretch.size) for more
/// information on sizes.
#[default(<default_mat_size>::data().into())]
pub delim_size: StretchSize,
/// Whether the direction of cases should be reversed. /// Whether the direction of cases should be reversed.
/// ///
/// ```example /// ```example

View File

@ -9,6 +9,7 @@ mod lr;
mod matrix; mod matrix;
mod op; mod op;
mod root; mod root;
mod stretch;
mod style; mod style;
mod underover; mod underover;
@ -21,6 +22,7 @@ pub use self::lr::*;
pub use self::matrix::*; pub use self::matrix::*;
pub use self::op::*; pub use self::op::*;
pub use self::root::*; pub use self::root::*;
pub use self::stretch::*;
pub use self::style::*; pub use self::style::*;
pub use self::underover::*; pub use self::underover::*;

View File

@ -0,0 +1,125 @@
use comemo::Track;
use crate::diag::{At, SourceResult};
use crate::engine::Engine;
use crate::foundations::{
cast, elem, Content, Context, Func, NativeFunc, NativeFuncData, Resolve, StyleChain,
};
use crate::layout::{Abs, Rel};
use crate::math::{default_lr_size, Mathy};
/// Stretches a glyph.
///
/// This function can also be used to automatically stretch the base of an
/// attachment, so that it fits the top and bottom attachments.
///
/// Note that only some glyphs can be stretched, and which ones can depend on
/// the math font being used. However, most math fonts are the same in this
/// regard.
///
/// ```example
/// $ H stretch(=)^"define" U + p V $
/// $ f : X stretch(->>, size: #150%)_"surjective" Y $
/// $ x stretch(harpoons.ltrb, size: #3em) y
/// stretch(\[, size: #150%) z $
/// ```
#[elem(Mathy)]
pub struct StretchElem {
/// The glyph to stretch.
#[required]
pub body: Content,
/// The size to stretch to, relative to the maximum size of the glyph and
/// its attachments.
///
/// This value can be given as a [relative length]($relative), or a
/// [function]($function) that receives the size of the glyph as a
/// parameter (an absolute length) and should return a (relative) length.
/// For example, `{x => x * 80%}` would be equivalent to just specifying `{80%}`.
///
/// Note that the sizes of glyphs in math fonts come about in two ways:
///
/// - First, there are pre-made variants at specific sizes. This means you
/// will see discrete jumps in the stretched glyph's size as you increase
/// the size parameter. It is up to the font how many pre-made variants
/// there are and what their sizes are.
///
/// - Then, if the pre-made variants are all too small, a glyph of the
/// desired size is assembled from parts. The stretched glyph's size will
/// now be the exact size requested.
///
/// It could be the case that only one of the above exist for a glyph in
/// the font.
///
/// The value given here is really a minimum (but if there is no assembly
/// for the glyph, this minimum may not be reached), so the actual size of
/// the stretched glyph may not match what you specified.
///
/// ```example
/// #for i in range(0, 15) {
/// $stretch(\[, size: #(10pt + i * 2pt))$
/// }
///
/// #set math.stretch(size: x => x + 0.5em)
/// $x stretch(=)^"def" y$
/// ```
#[default(Rel::one().into())]
pub size: StretchSize,
}
/// How to size a stretched glyph.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum StretchSize {
/// Sized by the specified length.
Rel(Rel),
/// Resolve the size for the given base size through the specified
/// function.
Func(Func),
}
impl StretchSize {
/// Resolve the stretch size given the base size.
pub fn resolve(
&self,
engine: &mut Engine,
styles: StyleChain,
base: Abs,
) -> SourceResult<Abs> {
Ok(match self {
Self::Rel(rel) => *rel,
Self::Func(func) => func
.call(engine, Context::new(None, Some(styles)).track(), [base])?
.cast()
.at(func.span())?,
}
.resolve(styles)
.relative_to(base))
}
/// Whether the size is the default used by `LrElem`.
pub fn is_lr_default(self) -> bool {
self == <default_lr_size>::data().into()
}
}
impl From<Rel> for StretchSize {
fn from(rel: Rel) -> Self {
Self::Rel(rel)
}
}
impl From<&'static NativeFuncData> for StretchSize {
fn from(data: &'static NativeFuncData) -> Self {
Self::Func(Func::from(data))
}
}
cast! {
StretchSize,
self => match self {
Self::Rel(v) => v.into_value(),
Self::Func(v) => v.into_value(),
},
v: Rel => Self::Rel(v),
v: Func => Self::Func(v),
}

View File

@ -228,6 +228,10 @@ pub struct FontMetrics {
pub underline: LineMetrics, pub underline: LineMetrics,
/// Recommended metrics for an overline. /// Recommended metrics for an overline.
pub overline: LineMetrics, 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 { impl FontMetrics {
@ -240,6 +244,7 @@ impl FontMetrics {
let cap_height = ttf.capital_height().filter(|&h| h > 0).map_or(ascender, to_em); 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 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 descender = to_em(ttf.typographic_descender().unwrap_or(ttf.descender()));
let strikeout = ttf.strikeout_metrics(); let strikeout = ttf.strikeout_metrics();
let underline = ttf.underline_metrics(); let underline = ttf.underline_metrics();
@ -262,6 +267,20 @@ impl FontMetrics {
thickness: underline.thickness, 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 { Self {
units_per_em, units_per_em,
ascender, ascender,
@ -271,6 +290,8 @@ impl FontMetrics {
strikethrough, strikethrough,
underline, underline,
overline, overline,
superscript,
subscript,
} }
} }
@ -296,6 +317,24 @@ pub struct LineMetrics {
pub thickness: Em, 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. /// Identifies a vertical metric of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum VerticalFontMetric { pub enum VerticalFontMetric {

View File

@ -755,6 +755,12 @@ pub struct TextElem {
#[internal] #[internal]
#[ghost] #[ghost]
pub smallcaps: Option<Smallcaps>, 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 { impl TextElem {
@ -930,7 +936,7 @@ cast! {
} }
/// Resolve a prioritized iterator over the font families. /// Resolve a prioritized iterator over the font families.
pub fn families(styles: StyleChain) -> impl Iterator<Item = &FontFamily> + Clone { pub fn families(styles: StyleChain<'_>) -> impl Iterator<Item = &'_ FontFamily> + Clone {
let fallbacks = singleton!(Vec<FontFamily>, { let fallbacks = singleton!(Vec<FontFamily>, {
[ [
"libertinus serif", "libertinus serif",

View File

@ -1,14 +1,13 @@
use ecow::EcoString;
use crate::diag::SourceResult; use crate::diag::SourceResult;
use crate::engine::Engine; use crate::engine::Engine;
use crate::foundations::{ 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::html::{tag, HtmlElem};
use crate::layout::{Em, Length}; use crate::layout::{Em, Length};
use crate::text::{variant, SpaceElem, TextElem, TextSize}; use crate::text::{FontMetrics, TextElem, TextSize};
use crate::World; use ttf_parser::Tag;
use typst_library::text::ScriptMetrics;
/// Renders text in subscript. /// Renders text in subscript.
/// ///
@ -20,11 +19,16 @@ use crate::World;
/// ``` /// ```
#[elem(title = "Subscript", Show)] #[elem(title = "Subscript", Show)]
pub struct SubElem { 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 /// Ideally, subscripts glyphs are provided by the font (using the `subs`
/// codepoints. If that fails, it falls back to rendering lowered and shrunk /// OpenType feature). Otherwise, Typst is able to synthesize subscripts.
/// 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 /// ```example
/// N#sub(typographic: true)[1] /// N#sub(typographic: true)[1]
@ -33,17 +37,27 @@ pub struct SubElem {
#[default(true)] #[default(true)]
pub typographic: bool, pub typographic: bool,
/// The baseline shift for synthetic subscripts. Does not apply if /// The downward baseline shift for synthesized subscripts.
/// `typographic` is true and the font has subscript codepoints for the ///
/// given `body`. /// This only applies to synthesized subscripts. In other words, this has no
#[default(Em::new(0.2).into())] /// effect if `typographic` is `{true}` and the font provides the necessary
pub baseline: Length, /// 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 /// The font size for synthesized subscripts.
/// `typographic` is true and the font has subscript codepoints for the ///
/// given `body`. /// This only applies to synthesized subscripts. In other words, this has no
#[default(TextSize(Em::new(0.6).into()))] /// effect if `typographic` is `{true}` and the font provides the necessary
pub size: TextSize, /// 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. /// The text to display in subscript.
#[required] #[required]
@ -52,7 +66,7 @@ pub struct SubElem {
impl Show for Packed<SubElem> { impl Show for Packed<SubElem> {
#[typst_macros::time(name = "sub", span = self.span())] #[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(); let body = self.body.clone();
if TargetElem::target_in(styles).is_html() { if TargetElem::target_in(styles).is_html() {
@ -62,17 +76,14 @@ impl Show for Packed<SubElem> {
.spanned(self.span())); .spanned(self.span()));
} }
if self.typographic(styles) { show_script(
if let Some(text) = convert_script(&body, true) { styles,
if is_shapable(engine, &text, styles) { body,
return Ok(TextElem::packed(text)); self.typographic(styles),
} self.baseline(styles),
} self.size(styles),
}; ScriptKind::Sub,
)
Ok(body
.styled(TextElem::set_baseline(self.baseline(styles)))
.styled(TextElem::set_size(self.size(styles))))
} }
} }
@ -86,11 +97,16 @@ impl Show for Packed<SubElem> {
/// ``` /// ```
#[elem(title = "Superscript", Show)] #[elem(title = "Superscript", Show)]
pub struct SuperElem { 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 /// Ideally, superscripts glyphs are provided by the font (using the `sups`
/// superscript codepoints. If that fails, it falls back to rendering /// OpenType feature). Otherwise, Typst is able to synthesize superscripts.
/// raised and shrunk normal letters. ///
/// 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 /// ```example
/// N#super(typographic: true)[1] /// N#super(typographic: true)[1]
@ -99,17 +115,31 @@ pub struct SuperElem {
#[default(true)] #[default(true)]
pub typographic: bool, pub typographic: bool,
/// The baseline shift for synthetic superscripts. Does not apply if /// The downward baseline shift for synthesized superscripts.
/// `typographic` is true and the font has superscript codepoints for the ///
/// given `body`. /// This only applies to synthesized superscripts. In other words, this has
#[default(Em::new(-0.5).into())] /// no effect if `typographic` is `{true}` and the font provides the
pub baseline: Length, /// 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 /// The font size for synthesized superscripts.
/// `typographic` is true and the font has superscript codepoints for the ///
/// given `body`. /// This only applies to synthesized superscripts. In other words, this has
#[default(TextSize(Em::new(0.6).into()))] /// no effect if `typographic` is `{true}` and the font provides the
pub size: TextSize, /// 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. /// The text to display in superscript.
#[required] #[required]
@ -118,7 +148,7 @@ pub struct SuperElem {
impl Show for Packed<SuperElem> { impl Show for Packed<SuperElem> {
#[typst_macros::time(name = "super", span = self.span())] #[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(); let body = self.body.clone();
if TargetElem::target_in(styles).is_html() { if TargetElem::target_in(styles).is_html() {
@ -128,104 +158,102 @@ impl Show for Packed<SuperElem> {
.spanned(self.span())); .spanned(self.span()));
} }
if self.typographic(styles) { show_script(
if let Some(text) = convert_script(&body, false) { styles,
if is_shapable(engine, &text, styles) { body,
return Ok(TextElem::packed(text)); self.typographic(styles),
} self.baseline(styles),
} self.size(styles),
}; ScriptKind::Super,
)
Ok(body
.styled(TextElem::set_baseline(self.baseline(styles)))
.styled(TextElem::set_size(self.size(styles))))
} }
} }
/// Find and transform the text contained in `content` to the given script kind fn show_script(
/// if and only if it only consists of `Text`, `Space`, and `Empty` leaves. styles: StyleChain,
fn convert_script(content: &Content, sub: bool) -> Option<EcoString> { body: Content,
if content.is::<SpaceElem>() { typographic: bool,
Some(' '.into()) baseline: Smart<Length>,
} else if let Some(elem) = content.to_packed::<TextElem>() { size: Smart<TextSize>,
if sub { kind: ScriptKind,
elem.text.chars().map(to_subscript_codepoint).collect() ) -> SourceResult<Content> {
} else { let font_size = TextElem::size_in(styles);
elem.text.chars().map(to_superscript_codepoint).collect() Ok(body.styled(TextElem::set_shift_settings(Some(ShiftSettings {
} typographic,
} else if let Some(sequence) = content.to_packed::<SequenceElem>() { shift: baseline.map(|l| -Em::from_length(l, font_size)),
sequence size: size.map(|t| Em::from_length(t.0, font_size)),
.children kind,
.iter() }))))
.map(|item| convert_script(item, sub))
.collect()
} else {
None
}
} }
/// Checks whether the first retrievable family contains all code points of the /// Configuration values for sub- or superscript text.
/// given string. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
fn is_shapable(engine: &Engine, text: &str, styles: StyleChain) -> bool { pub struct ShiftSettings {
let world = engine.world; /// Whether the OpenType feature should be used if possible.
for family in TextElem::font_in(styles) { pub typographic: bool,
if let Some(font) = world /// The baseline shift of the script, relative to the outer text size.
.book() ///
.select(family.as_str(), variant(styles)) /// For superscripts, this is positive. For subscripts, this is negative. A
.and_then(|id| world.font(id)) /// value of [`Smart::Auto`] indicates that the value should be obtained
{ /// from font metrics.
let covers = family.covers(); pub shift: Smart<Em>,
return text.chars().all(|c| { /// The size of the script, relative to the outer text size.
covers.is_none_or(|cov| cov.is_match(c.encode_utf8(&mut [0; 4]))) ///
&& font.ttf().glyph_index(c).is_some() /// 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,
}
#[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. /// The corresponding OpenType feature.
fn to_superscript_codepoint(c: char) -> Option<char> { pub const fn feature(self) -> Tag {
match c { match self {
'1' => Some('¹'), Self::Sub => Tag::from_bytes(b"subs"),
'2' => Some('²'), Self::Super => Tag::from_bytes(b"sups"),
'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,
} }
} }
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. static DEFAULT_SUPERSCRIPT_METRICS: ScriptMetrics = ScriptMetrics {
fn to_subscript_codepoint(c: char) -> Option<char> { width: Em::new(0.6),
match c { height: Em::new(0.6),
'0'..='9' => char::from_u32(c as u32 - '0' as u32 + '₀' as u32), horizontal_offset: Em::zero(),
'+' => Some('₊'), vertical_offset: Em::new(0.5),
'' => 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,
}
}

View File

@ -22,8 +22,6 @@ pub(crate) fn build_metadata(gc: &GlobalContext) -> Metadata {
.keywords(gc.document.info.keywords.iter().map(EcoString::to_string).collect()) .keywords(gc.document.info.keywords.iter().map(EcoString::to_string).collect())
.authors(gc.document.info.author.iter().map(EcoString::to_string).collect()); .authors(gc.document.info.author.iter().map(EcoString::to_string).collect());
let lang = gc.languages.iter().max_by_key(|(_, &count)| count).map(|(&l, _)| l);
if let Some(lang) = lang { if let Some(lang) = lang {
metadata = metadata.language(lang.as_str().to_string()); metadata = metadata.language(lang.as_str().to_string());
} }

View File

@ -395,6 +395,10 @@ pub fn default_math_class(c: char) -> Option<MathClass> {
// https://github.com/typst/typst/issues/5764 // https://github.com/typst/typst/issues/5764
'⟇' => Some(MathClass::Binary), '⟇' => Some(MathClass::Binary),
// Arabic comma.
// https://github.com/latex3/unicode-math/pull/633#issuecomment-2028936135
'،' => Some(MathClass::Punctuation),
c => unicode_math_class::class(c), c => unicode_math_class::class(c),
} }
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 841 B

After

Width:  |  Height:  |  Size: 903 B

BIN
tests/ref/long-scripts.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 956 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 417 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1005 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 603 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 291 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 311 B

After

Width:  |  Height:  |  Size: 318 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 835 B

View File

@ -30,11 +30,17 @@ $ tilde(integral), tilde(integral)_a^b, tilde(integral_a^b) $
--- math-accent-sized --- --- math-accent-sized ---
// Test accent size. // Test accent size.
$tilde(sum), tilde(sum, size: #50%), accent(H, hat, size: #200%)$ $tilde(sum), tilde(sum, size: #25%), accent(H, hat, size: #125%)$
--- math-accent-sized-script --- --- math-accent-sized-script ---
// Test accent size in script size. // Test accent size in script size.
$tilde(U, size: #1.1em), x^tilde(U, size: #1.1em), sscript(tilde(U, size: #1.1em))$ $tilde(U, size: #0.6em), x^tilde(U, size: #0.6em), sscript(tilde(U, size: #0.6em))$
--- math-accent-sized-function ---
// Test accent size with a function.
$dash(A) arrow(I) hat(L)$ \
#set math.accent(size: x => x - 0.1em)
$dash(A) arrow(I) hat(L)$
--- math-accent-dotless --- --- math-accent-dotless ---
// Test dotless glyph variants. // Test dotless glyph variants.
@ -85,7 +91,7 @@ $ accent(integral, \u{20EC}), accent(integral, \u{20EC})_a^b, accent(integral_a^
--- math-accent-bottom-sized --- --- math-accent-bottom-sized ---
// Test bottom accent size. // Test bottom accent size.
$accent(sum, \u{0330}), accent(sum, \u{0330}, size: #50%), accent(H, \u{032D}, size: #200%)$ $accent(sum, \u{0330}), accent(sum, \u{0330}, size: #25%), accent(H, \u{032D}, size: #125%)$
--- math-accent-nested --- --- math-accent-nested ---
// Test nested top and bottom accents. // Test nested top and bottom accents.

View File

@ -187,5 +187,5 @@ $ a0 + a1 + a0_2 \
--- math-attach-scripts-extended-shapes --- --- math-attach-scripts-extended-shapes ---
// Test script attachments positioning if the base is an extended shape (or a // Test script attachments positioning if the base is an extended shape (or a
// sequence of extended shapes). // sequence of extended shapes).
$lr(size: #130%, [x])_0^1, [x]_0^1, \]_0^1, x_0^1, A_0^1$ \ $lr(size: #115%, [x])_0^1, [x]_0^1, \]_0^1, x_0^1, A_0^1$ \
$n^2, (n + 1)^2, sum_0^1, integral_0^1$ $n^2, (n + 1)^2, sum_0^1, integral_0^1$

View File

@ -16,6 +16,12 @@ $ x = cases(1, 2) $
#set math.cases(delim: sym.angle.l) #set math.cases(delim: sym.angle.l)
$ cases(a, b, c) $ $ cases(a, b, c) $
--- math-cases-delim-size ---
// Test setting delimiter size.
$ cases(reverse: #true, 1, 2, 3) cases(delim-size: #100%, 1, 2, 3) $
#set math.cases(delim-size: x => calc.max(x - 5pt, x * 0.901))
$ cases(1, 2) cases(1, 2, 3, 4) $
--- math-cases-linebreaks --- --- math-cases-linebreaks ---
// Warning: 40-49 linebreaks are ignored in branches // Warning: 40-49 linebreaks are ignored in branches
// Hint: 40-49 use commas instead to separate each line // Hint: 40-49 use commas instead to separate each line

View File

@ -31,9 +31,14 @@ $ lr(a/b\]) = a = lr(\{a/b) $
--- math-lr-size --- --- math-lr-size ---
// Test manual scaling. // Test manual scaling.
$ lr(]sum_(x=1)^n x], size: #70%) $ lr(]sum_(x=1)^n x], size: #60%)
< lr((1, 2), size: #200%) $ < lr((1, 2), size: #200%) $
--- math-lr-size-function ---
// Test using a function as an argument to size.
#set math.lr(size: x => if x > 10pt { 1em } else { 4 * x })
$ (a) (1/2) $
--- math-lr-shorthands --- --- math-lr-shorthands ---
// Test predefined delimiter pairings. // Test predefined delimiter pairings.
$floor(x/2), ceil(x/2), abs(x), norm(x)$ $floor(x/2), ceil(x/2), abs(x), norm(x)$
@ -57,16 +62,16 @@ $ { x mid(|) sum_(i=1)^oo phi_i (x) < 1 } \
#set page(width: auto) #set page(width: auto)
$ lr({ A mid(|) integral }) quad $ lr({ A mid(|) integral }) quad
lr(size: #1em, { A mid(|) integral }) quad lr(size: #0%, { A mid(|) integral }) quad
lr(size: #(1em+20%), { A mid(|) integral }) \ lr(size: #(1em+10%), { A mid(|) integral }) \
lr(] A mid(|) integral ]) quad lr(] A mid(|) integral ]) quad
lr(size: #1em, ] A mid(|) integral ]) quad lr(size: #0%, ] A mid(|) integral ]) quad
lr(size: #(1em+20%), ] A mid(|) integral ]) \ lr(size: #(1em+10%), ] A mid(|) integral ]) \
lr(( A mid(|) integral ]) quad lr(( A mid(|) integral ]) quad
lr(size: #1em, ( A mid(|) integral ]) quad lr(size: #0%, ( A mid(|) integral ]) quad
lr(size: #(1em+20%), ( A mid(|) integral ]) $ lr(size: #(1em+10%), ( A mid(|) integral ]) $
--- math-lr-mid-size-nested-equation --- --- math-lr-mid-size-nested-equation ---
// Test mid size when lr size is set, when nested in an equation. // Test mid size when lr size is set, when nested in an equation.
@ -74,8 +79,8 @@ $ lr({ A mid(|) integral }) quad
#let body = ${ A mid(|) integral }$ #let body = ${ A mid(|) integral }$
$ lr(body) quad $ lr(body) quad
lr(size: #1em, body) quad lr(size: #0%, body) quad
lr(size: #(1em+20%), body) $ lr(size: #(1em+10%), body) $
--- math-lr-mid-class --- --- math-lr-mid-class ---
// Test that `mid` creates a Relation, but that can be overridden. // Test that `mid` creates a Relation, but that can be overridden.

View File

@ -54,6 +54,12 @@ $ a + mat(delim: #none, 1, 2; 3, 4) + b $
$ mat(1, 2; 3, 4; delim: "[") $, $ mat(1, 2; 3, 4; delim: "[") $,
) )
--- math-mat-delim-size ---
// Test setting delimiter size.
$ mat(c; c; c) mat(delim-size: #100%, c; c; c) $
#set math.mat(delim-size: x => calc.max(x - 5pt, x * 0.901))
$ mat(delim: "[", f; f; f; f) mat(delim: ||, x; x; x; x) $
--- math-mat-spread --- --- math-mat-spread ---
// Test argument spreading in matrix. // Test argument spreading in matrix.
$ mat(..#range(1, 5).chunks(2)) $ mat(..#range(1, 5).chunks(2))

View File

@ -91,3 +91,9 @@ $ body^"text" $
} }
$body^"long text"$ $body^"long text"$
} }
--- math-stretch-function ---
// Test using a function as an argument to size.
$stretch(<-, size: #(x => x - 0.5em))_"function"$
#set math.stretch(size: x => x + 0.5em)
$stretch(|) |$

View File

@ -50,6 +50,12 @@ $ vec(1, 2) $
// Error: 22-33 invalid delimiter: "%" // Error: 22-33 invalid delimiter: "%"
#set math.vec(delim: (none, "%")) #set math.vec(delim: (none, "%"))
--- math-vec-delim-size ---
// Test setting delimiter size.
$ vec(1, 2, 3) vec(delim-size: #100%, 1, 2, 3) $
#set math.vec(delim-size: x => calc.max(x - 5pt, x * 0.901))
$ vec(delim: "{", 1, 2, 3) vec(delim: "[", 1, 2, 3) $
--- math-vec-linebreaks --- --- math-vec-linebreaks ---
// Warning: 20-29 linebreaks are ignored in elements // Warning: 20-29 linebreaks are ignored in elements
// Hint: 20-29 use commas instead to separate each line // Hint: 20-29 use commas instead to separate each line

View File

@ -1,22 +1,89 @@
// Test sub- and superscript shifts. // Test sub- and superscript shifts.
--- sub-super --- --- sub-super ---
#let sq = box(square(size: 4pt))
#table( #table(
columns: 3, columns: 3,
[Typo.], [Fallb.], [Synth], [Typo.], [Fallb.], [Synth.],
[x#super[1]], [x#super[5n]], [x#super[2 #box(square(size: 6pt))]], [x#super[1#sq]], [x#super[5: #sq]], [x#super(typographic: false)[2 #sq]],
[x#sub[1]], [x#sub[5n]], [x#sub[2 #box(square(size: 6pt))]], [x#sub[1#sq]], [x#sub[5: #sq]], [x#sub(typographic: false)[2 #sq]],
) )
--- sub-super-typographic ---
#set text(size: 20pt)
// Libertinus Serif supports "subs" and "sups" for `typo` and `sq`, but not for
// `synth`.
#let synth = [1,2,3]
#let typo = [123]
#let sq = [1#box(square(size: 4pt))2]
x#super(synth) x#super(typo) x#super(sq) \
x#sub(synth) x#sub(typo) x#sub(sq)
--- sub-super-italic-compensation ---
#set text(size: 20pt, style: "italic")
// Libertinus Serif supports "subs" and "sups" for `typo`, but not for `synth`.
#let synth = [1,2,3]
#let typo = [123]
#let sq = [1#box(square(size: 4pt))2]
x#super(synth) x#super(typo) x#super(sq) \
x#sub(synth) x#sub(typo) x#sub(sq)
--- sub-super-non-typographic --- --- sub-super-non-typographic ---
#set super(typographic: false, baseline: -0.25em, size: 0.7em) #set super(typographic: false, baseline: -0.25em, size: 0.7em)
n#super[1], n#sub[2], ... n#super[N] n#super[1], n#sub[2], ... n#super[N]
--- super-underline --- --- super-underline ---
#set underline(stroke: 0.5pt, offset: 0.15em) #set underline(stroke: 0.5pt, offset: 0.15em)
#underline[The claim#super[\[4\]]] has been disputed. \ #set super(typographic: false)
The claim#super[#underline[\[4\]]] has been disputed. \ #underline[A#super[4]] B \
It really has been#super(box(text(baseline: 0pt, underline[\[4\]]))) \ A#super[#underline[4]] B \
A #underline(super[4]) B \
#set super(typographic: true)
#underline[A#super[4]] B \
A#super[#underline[4]] B \
A #underline(super[4]) B
--- super-highlight ---
#set super(typographic: false)
#highlight[A#super[4]] B \
A#super[#highlight[4]] B \
A#super(highlight[4]) \
#set super(typographic: true)
#highlight[A#super[4]] B \
A#super[#highlight[4]] B \
A#super(highlight[4])
--- super-1em ---
#set text(size: 10pt)
#super(context test(1em.to-absolute(), 10pt))
--- long-scripts ---
|longscript| \
|#super(typographic: true)[longscript]| \
|#super(typographic: false)[longscript]| \
|#sub(typographic: true)[longscript]| \
|#sub(typographic: false)[longscript]|
--- script-metrics-bundeled-fonts ---
// Tests whether the script metrics are used properly by synthesizing
// superscripts and subscripts for all bundled fonts.
#set super(typographic: false)
#set sub(typographic: false)
#let test(font, weights, styles) = {
for weight in weights {
for style in styles {
text(font: font, weight: weight, style: style)[Xx#super[Xx]#sub[Xx]]
linebreak()
}
}
}
#test("DejaVu Sans Mono", ("regular", "bold"), ("normal", "oblique"))
#test("Libertinus Serif", ("regular", "semibold", "bold"), ("normal", "italic"))
#test("New Computer Modern", ("regular", "bold"), ("normal", "italic"))
#test("New Computer Modern Math", (400, 450, "bold"), ("normal",))
--- basic-sup-sub html --- --- basic-sup-sub html ---
1#super[st], 2#super[nd], 3#super[rd]. 1#super[st], 2#super[nd], 3#super[rd].