repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/pages/finalize.rs | crates/typst-layout/src/pages/finalize.rs | use typst_library::diag::SourceResult;
use typst_library::engine::Engine;
use typst_library::introspection::{ManualPageCounter, Tag};
use typst_library::layout::{Frame, FrameItem, Page, Point};
use super::LayoutedPage;
/// Piece together the inner page frame and the marginals. We can only do this
/// at the very end because inside/outside margins require knowledge of the
/// physical page number, which is unknown during parallel layout.
pub fn finalize(
engine: &mut Engine,
counter: &mut ManualPageCounter,
tags: &mut Vec<Tag>,
LayoutedPage {
inner,
mut margin,
binding,
two_sided,
header,
footer,
background,
foreground,
fill,
numbering,
supplement,
}: LayoutedPage,
) -> SourceResult<Page> {
// If two sided, left becomes inside and right becomes outside.
// Thus, for left-bound pages, we want to swap on even pages and
// for right-bound pages, we want to swap on odd pages.
if two_sided && binding.swap(counter.physical()) {
std::mem::swap(&mut margin.left, &mut margin.right);
}
// Create a frame for the full page.
let mut frame = Frame::hard(inner.size() + margin.sum_by_axis());
// Add tags.
for tag in tags.drain(..) {
frame.push(Point::zero(), FrameItem::Tag(tag));
}
// Add the "before" marginals. The order in which we push things here is
// important as it affects the relative ordering of introspectable elements
// and thus how counters resolve.
if let Some(background) = background {
frame.push_frame(Point::zero(), background);
}
if let Some(header) = header {
frame.push_frame(Point::with_x(margin.left), header);
}
// Add the inner contents.
frame.push_frame(Point::new(margin.left, margin.top), inner);
// Add the "after" marginals.
if let Some(footer) = footer {
let y = frame.height() - footer.height();
frame.push_frame(Point::new(margin.left, y), footer);
}
if let Some(foreground) = foreground {
frame.push_frame(Point::zero(), foreground);
}
// Apply counter updates from within the page to the manual page counter.
counter.visit(engine, &frame)?;
// Get this page's number and then bump the counter for the next page.
let number = counter.logical();
counter.step();
Ok(Page { frame, fill, numbering, supplement, number })
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/pages/mod.rs | crates/typst-layout/src/pages/mod.rs | //! Layout of content into a [`Document`].
mod collect;
mod finalize;
mod run;
use std::num::NonZeroUsize;
use comemo::{Tracked, TrackedMut};
use typst_library::World;
use typst_library::diag::SourceResult;
use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{Content, StyleChain};
use typst_library::introspection::{
DocumentPosition, Introspector, IntrospectorBuilder, Locator, ManualPageCounter,
SplitLocator, TagElem,
};
use typst_library::layout::{FrameItem, Page, PagedDocument, Point, Position, Transform};
use typst_library::model::DocumentInfo;
use typst_library::routines::{Arenas, Pair, RealizationKind, Routines};
use typst_utils::Protected;
use self::collect::{Item, collect};
use self::finalize::finalize;
use self::run::{LayoutedPage, layout_blank_page, layout_page_run};
/// Layout content into a document.
///
/// This first performs root-level realization and then lays out the resulting
/// elements. In contrast to [`layout_fragment`](crate::layout_fragment),
/// this does not take regions since the regions are defined by the page
/// configuration in the content and style chain.
#[typst_macros::time(name = "layout document")]
pub fn layout_document(
engine: &mut Engine,
content: &Content,
styles: StyleChain,
) -> SourceResult<PagedDocument> {
layout_document_impl(
engine.routines,
engine.world,
engine.introspector.into_raw(),
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
content,
styles,
)
}
/// The internal implementation of `layout_document`.
#[comemo::memoize]
#[allow(clippy::too_many_arguments)]
fn layout_document_impl(
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
content: &Content,
styles: StyleChain,
) -> SourceResult<PagedDocument> {
let introspector = Protected::from_raw(introspector);
let mut locator = Locator::root().split();
let mut engine = Engine {
routines,
world,
introspector,
traced,
sink,
route: Route::extend(route).unnested(),
};
// Mark the external styles as "outside" so that they are valid at the page
// level.
let styles = styles.to_map().outside();
let styles = StyleChain::new(&styles);
let arenas = Arenas::default();
let mut info = DocumentInfo::default();
let mut children = (engine.routines.realize)(
RealizationKind::LayoutDocument { info: &mut info },
&mut engine,
&mut locator,
&arenas,
content,
styles,
)?;
let pages = layout_pages(&mut engine, &mut children, &mut locator, styles)?;
let introspector = introspect_pages(&pages);
Ok(PagedDocument { pages, info, introspector })
}
/// Layouts the document's pages.
fn layout_pages<'a>(
engine: &mut Engine,
children: &'a mut [Pair<'a>],
locator: &mut SplitLocator<'a>,
styles: StyleChain<'a>,
) -> SourceResult<Vec<Page>> {
// Slice up the children into logical parts.
let items = collect(children, locator, styles);
// Layout the page runs in parallel.
let mut runs = engine.parallelize(
items.iter().filter_map(|item| match item {
Item::Run(children, initial, locator) => {
Some((children, initial, locator.relayout()))
}
_ => None,
}),
|engine, (children, initial, locator)| {
layout_page_run(engine, children, locator, *initial)
},
);
let mut pages = vec![];
let mut tags = vec![];
let mut counter = ManualPageCounter::new();
// Collect and finalize the runs, handling things like page parity and tags
// between pages.
for item in &items {
match item {
Item::Run(..) => {
let layouted = runs.next().unwrap()?;
for layouted in layouted {
let page = finalize(engine, &mut counter, &mut tags, layouted)?;
pages.push(page);
}
}
Item::Parity(parity, initial, locator) => {
if !parity.matches(pages.len()) {
continue;
}
let layouted = layout_blank_page(engine, locator.relayout(), *initial)?;
let page = finalize(engine, &mut counter, &mut tags, layouted)?;
pages.push(page);
}
Item::Tags(items) => {
tags.extend(
items
.iter()
.filter_map(|(c, _)| c.to_packed::<TagElem>())
.map(|elem| elem.tag.clone()),
);
}
}
}
// Add the remaining tags to the very end of the last page.
if !tags.is_empty() {
let last = pages.last_mut().unwrap();
let pos = Point::with_y(last.frame.height());
last.frame
.push_multiple(tags.into_iter().map(|tag| (pos, FrameItem::Tag(tag))));
}
Ok(pages)
}
/// Introspects pages.
#[typst_macros::time(name = "introspect pages")]
fn introspect_pages(pages: &[Page]) -> Introspector {
let mut builder = IntrospectorBuilder::new();
builder.pages = pages.len();
builder.page_numberings.reserve(pages.len());
builder.page_supplements.reserve(pages.len());
// Discover all elements.
let mut elems = Vec::new();
for (i, page) in pages.iter().enumerate() {
let nr = NonZeroUsize::new(1 + i).unwrap();
builder.page_numberings.push(page.numbering.clone());
builder.page_supplements.push(page.supplement.clone());
builder.discover_in_frame(
&mut elems,
&page.frame,
Transform::identity(),
&mut |point| DocumentPosition::Paged(Position { page: nr, point }),
);
}
builder.finalize(elems)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/pages/run.rs | crates/typst-layout/src/pages/run.rs | use comemo::{Track, Tracked, TrackedMut};
use typst_library::World;
use typst_library::diag::SourceResult;
use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{
Content, NativeElement, Resolve, Smart, StyleChain, Styles,
};
use typst_library::introspection::{
Counter, CounterDisplayElem, CounterKey, Introspector, Locator, LocatorLink,
};
use typst_library::layout::{
Abs, AlignElem, Alignment, Axes, Binding, ColumnsElem, Dir, Frame, HAlignment,
Length, OuterVAlignment, PageElem, Paper, Region, Regions, Rel, Sides, Size,
VAlignment,
};
use typst_library::model::Numbering;
use typst_library::pdf::ArtifactKind;
use typst_library::routines::{Pair, Routines};
use typst_library::text::{LocalName, TextElem};
use typst_library::visualize::Paint;
use typst_utils::{Numeric, Protected};
use crate::flow::{FlowMode, layout_flow};
/// A mostly finished layout for one page. Needs only knowledge of its exact
/// page number to be finalized into a `Page`. (Because the margins can depend
/// on the page number.)
#[derive(Clone)]
pub struct LayoutedPage {
pub inner: Frame,
pub margin: Sides<Abs>,
pub binding: Binding,
pub two_sided: bool,
pub header: Option<Frame>,
pub footer: Option<Frame>,
pub background: Option<Frame>,
pub foreground: Option<Frame>,
pub fill: Smart<Option<Paint>>,
pub numbering: Option<Numbering>,
pub supplement: Content,
}
/// Layout a single page suitable for parity adjustment.
pub fn layout_blank_page(
engine: &mut Engine,
locator: Locator,
initial: StyleChain,
) -> SourceResult<LayoutedPage> {
let layouted = layout_page_run(engine, &[], locator, initial)?;
Ok(layouted.into_iter().next().unwrap())
}
/// Layout a page run with uniform properties.
#[typst_macros::time(name = "page run")]
pub fn layout_page_run(
engine: &mut Engine,
children: &[Pair],
locator: Locator,
initial: StyleChain,
) -> SourceResult<Vec<LayoutedPage>> {
layout_page_run_impl(
engine.routines,
engine.world,
engine.introspector.into_raw(),
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
children,
locator.track(),
initial,
)
}
/// The internal implementation of `layout_page_run`.
#[comemo::memoize]
#[allow(clippy::too_many_arguments)]
fn layout_page_run_impl(
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
children: &[Pair],
locator: Tracked<Locator>,
initial: StyleChain,
) -> SourceResult<Vec<LayoutedPage>> {
let introspector = Protected::from_raw(introspector);
let link = LocatorLink::new(locator);
let mut locator = Locator::link(&link).split();
let mut engine = Engine {
routines,
world,
introspector,
traced,
sink,
route: Route::extend(route),
};
// Determine the page-wide styles.
let styles = Styles::root(children, initial);
let styles = StyleChain::new(&styles);
// When one of the lengths is infinite the page fits its content along
// that axis.
let width = styles.resolve(PageElem::width).unwrap_or(Abs::inf());
let height = styles.resolve(PageElem::height).unwrap_or(Abs::inf());
let mut size = Size::new(width, height);
if styles.get(PageElem::flipped) {
std::mem::swap(&mut size.x, &mut size.y);
}
let mut min = width.min(height);
if !min.is_finite() {
min = Paper::A4.width();
}
// Determine the margins.
let default = Rel::<Length>::from((2.5 / 21.0) * min);
let margin = styles.get(PageElem::margin);
let two_sided = margin.two_sided.unwrap_or(false);
let margin = margin
.sides
.map(|side| side.and_then(Smart::custom).unwrap_or(default))
.resolve(styles)
.relative_to(size);
let fill = styles.get_cloned(PageElem::fill);
let foreground = styles.get_ref(PageElem::foreground);
let background = styles.get_ref(PageElem::background);
let header_ascent = styles.resolve(PageElem::header_ascent).relative_to(margin.top);
let footer_descent =
styles.resolve(PageElem::footer_descent).relative_to(margin.bottom);
let numbering = styles.get_ref(PageElem::numbering);
let supplement = match styles.get_cloned(PageElem::supplement) {
Smart::Auto => TextElem::packed(PageElem::local_name_in(styles)),
Smart::Custom(content) => content.unwrap_or_default(),
};
let number_align = styles.get(PageElem::number_align);
let binding = styles.get(PageElem::binding).unwrap_or_else(|| {
match styles.resolve(TextElem::dir) {
Dir::LTR => Binding::Left,
_ => Binding::Right,
}
});
// Construct the numbering (for header or footer).
let numbering_marginal = numbering.as_ref().map(|numbering| {
let both = match numbering {
Numbering::Pattern(pattern) => pattern.pieces() >= 2,
Numbering::Func(_) => true,
};
let mut counter = CounterDisplayElem::new(
Counter::new(CounterKey::Page),
Smart::Custom(numbering.clone()),
both,
)
.pack();
// We interpret the Y alignment as selecting header or footer
// and then ignore it for aligning the actual number.
if let Some(x) = number_align.x() {
counter = counter.aligned(x.into());
}
counter
});
let header = styles.get_ref(PageElem::header);
let footer = styles.get_ref(PageElem::footer);
let (header, footer) = if matches!(number_align.y(), Some(OuterVAlignment::Top)) {
(header.as_ref().unwrap_or(&numbering_marginal), footer.as_ref().unwrap_or(&None))
} else {
(header.as_ref().unwrap_or(&None), footer.as_ref().unwrap_or(&numbering_marginal))
};
// Layout the children.
let area = size - margin.sum_by_axis();
let fragment = layout_flow(
&mut engine,
children,
&mut locator,
styles,
Regions::repeat(area, area.map(Abs::is_finite)),
styles.get(PageElem::columns),
styles.get(ColumnsElem::gutter).resolve(styles),
FlowMode::Root,
)?;
// Layouts a single marginal.
let mut layout_marginal = |content: &Option<Content>, area, align| {
let Some(content) = content else { return Ok(None) };
let aligned = content.clone().set(AlignElem::alignment, align);
crate::layout_frame(
&mut engine,
&aligned,
locator.next(&content.span()),
styles,
Region::new(area, Axes::splat(true)),
)
.map(Some)
};
// Layout marginals.
let mut layouted = Vec::with_capacity(fragment.len());
let header = header.clone().map(|h| h.artifact(ArtifactKind::Header));
let footer = footer.clone().map(|f| f.artifact(ArtifactKind::Footer));
let background = background.clone().map(|b| b.artifact(ArtifactKind::Page));
for inner in fragment {
let header_size = Size::new(inner.width(), margin.top - header_ascent);
let footer_size = Size::new(inner.width(), margin.bottom - footer_descent);
let full_size = inner.size() + margin.sum_by_axis();
let mid = HAlignment::Center + VAlignment::Horizon;
layouted.push(LayoutedPage {
inner,
fill: fill.clone(),
numbering: numbering.clone(),
supplement: supplement.clone(),
header: layout_marginal(&header, header_size, Alignment::BOTTOM)?,
footer: layout_marginal(&footer, footer_size, Alignment::TOP)?,
background: layout_marginal(&background, full_size, mid)?,
foreground: layout_marginal(foreground, full_size, mid)?,
margin,
binding,
two_sided,
});
}
Ok(layouted)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/box.rs | crates/typst-layout/src/inline/box.rs | use std::cell::LazyCell;
use typst_library::diag::SourceResult;
use typst_library::engine::Engine;
use typst_library::foundations::{Packed, StyleChain};
use typst_library::introspection::Locator;
use typst_library::layout::{BoxElem, Frame, FrameKind, Size};
use typst_library::visualize::Stroke;
use typst_utils::Numeric;
use crate::flow::unbreakable_pod;
use crate::shapes::{clip_rect, fill_and_stroke};
/// Lay out a box as part of inline layout.
#[typst_macros::time(name = "box", span = elem.span())]
pub fn layout_box(
elem: &Packed<BoxElem>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Size,
) -> SourceResult<Frame> {
// Fetch sizing properties.
let width = elem.width.get(styles);
let height = elem.height.get(styles);
let inset = elem.inset.resolve(styles).unwrap_or_default();
// Build the pod region.
let pod = unbreakable_pod(&width, &height.into(), &inset, styles, region);
// Layout the body.
let mut frame = match elem.body.get_ref(styles) {
// If we have no body, just create an empty frame. If necessary,
// its size will be adjusted below.
None => Frame::hard(Size::zero()),
// If we have a child, layout it into the body. Boxes are boundaries
// for gradient relativeness, so we set the `FrameKind` to `Hard`.
Some(body) => crate::layout_frame(engine, body, locator, styles, pod)?
.with_kind(FrameKind::Hard),
};
// Enforce a correct frame size on the expanded axes. Do this before
// applying the inset, since the pod shrunk.
frame.set_size(pod.expand.select(pod.size, frame.size()));
// Apply the inset.
if !inset.is_zero() {
crate::pad::grow(&mut frame, &inset);
}
// Prepare fill and stroke.
let fill = elem.fill.get_cloned(styles);
let stroke = elem
.stroke
.resolve(styles)
.unwrap_or_default()
.map(|s| s.map(Stroke::unwrap_or_default));
// Only fetch these if necessary (for clipping or filling/stroking).
let outset = LazyCell::new(|| elem.outset.resolve(styles).unwrap_or_default());
let radius = LazyCell::new(|| elem.radius.resolve(styles).unwrap_or_default());
// Clip the contents, if requested.
if elem.clip.get(styles) {
frame.clip(clip_rect(frame.size(), &radius, &stroke, &outset));
}
// Add fill and/or stroke.
if fill.is_some() || stroke.iter().any(Option::is_some) {
fill_and_stroke(&mut frame, fill, &stroke, &outset, &radius, elem.span());
}
// Assign label to the frame.
if let Some(label) = elem.label() {
frame.label(label);
}
// Apply baseline shift. Do this after setting the size and applying the
// inset, so that a relative shift is resolved relative to the final
// height.
let shift = elem.baseline.resolve(styles).relative_to(frame.height());
if !shift.is_zero() {
frame.set_baseline(frame.baseline() - shift);
}
Ok(frame)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/collect.rs | crates/typst-layout/src/inline/collect.rs | use typst_library::diag::warning;
use typst_library::foundations::{Packed, Resolve};
use typst_library::introspection::{SplitLocator, Tag, TagElem};
use typst_library::layout::{
Abs, BoxElem, Dir, Fr, Frame, HElem, InlineElem, InlineItem, Sizing, Spacing,
};
use typst_library::routines::Pair;
use typst_library::text::{
LinebreakElem, SmartQuoteElem, SmartQuoter, SmartQuotes, SpaceElem, TextElem,
is_default_ignorable,
};
use typst_syntax::Span;
use typst_utils::Numeric;
use super::*;
use crate::modifiers::{FrameModifiers, FrameModify, layout_and_modify};
// The characters by which spacing, inline content and pins are replaced in the
// full text.
const SPACING_REPLACE: &str = " "; // Space
const OBJ_REPLACE: &str = "\u{FFFC}"; // Object Replacement Character
// Unicode BiDi control characters.
const LTR_EMBEDDING: &str = "\u{202A}";
const RTL_EMBEDDING: &str = "\u{202B}";
const POP_EMBEDDING: &str = "\u{202C}";
const LTR_ISOLATE: &str = "\u{2066}";
const POP_ISOLATE: &str = "\u{2069}";
/// A prepared item in a inline layout.
#[derive(Debug)]
pub enum Item<'a> {
/// A shaped text run with consistent style and direction.
Text(ShapedText<'a>),
/// Absolute spacing between other items, and whether it is weak.
Absolute(Abs, bool),
/// Fractional spacing between other items.
Fractional(Fr, Option<(&'a Packed<BoxElem>, Locator<'a>, StyleChain<'a>)>),
/// Layouted inline-level content.
Frame(Frame),
/// A tag.
Tag(&'a Tag),
/// An item that is invisible and needs to be skipped, e.g. a Unicode
/// isolate.
Skip(&'static str),
}
impl<'a> Item<'a> {
/// Whether this is a tag item.
pub fn is_tag(&self) -> bool {
matches!(self, Self::Tag(_))
}
/// If this a text item, return it.
pub fn text(&self) -> Option<&ShapedText<'a>> {
match self {
Self::Text(shaped) => Some(shaped),
_ => None,
}
}
/// If this a text item, return it mutably.
pub fn text_mut(&mut self) -> Option<&mut ShapedText<'a>> {
match self {
Self::Text(shaped) => Some(shaped),
_ => None,
}
}
/// Return the textual representation of this item: Either just itself (for
/// a text item) or a replacement string (for any other item).
pub fn textual(&self) -> &str {
match self {
Self::Text(shaped) => shaped.text,
Self::Absolute(_, _) | Self::Fractional(_, _) => SPACING_REPLACE,
Self::Frame(_) => OBJ_REPLACE,
Self::Tag(_) => "",
Self::Skip(s) => s,
}
}
/// The text length of the item.
pub fn textual_len(&self) -> usize {
self.textual().len()
}
/// The natural layouted width of the item.
pub fn natural_width(&self) -> Abs {
match self {
Self::Text(shaped) => shaped.width(),
Self::Absolute(v, _) => *v,
Self::Frame(frame) => frame.width(),
Self::Fractional(_, _) | Self::Tag(_) => Abs::zero(),
Self::Skip(_) => Abs::zero(),
}
}
}
/// An item or not-yet shaped text. We can't shape text until we have collected
/// all items because only then we can compute BiDi, and we need to split shape
/// runs at level boundaries.
#[derive(Debug)]
pub enum Segment<'a> {
/// One or multiple collapsed text children. Stores how long the segment is
/// (in bytes of the full text string).
Text(usize, StyleChain<'a>),
/// An already prepared item.
Item(Item<'a>),
}
impl Segment<'_> {
/// The text length of the item.
pub fn textual_len(&self) -> usize {
match self {
Self::Text(len, _) => *len,
Self::Item(item) => item.textual_len(),
}
}
}
/// Collects all text into one string and a collection of segments that
/// correspond to pieces of that string. This also performs string-level
/// preprocessing like case transformations.
#[typst_macros::time]
pub fn collect<'a>(
children: &[Pair<'a>],
engine: &mut Engine<'_>,
locator: &mut SplitLocator<'a>,
config: &Config,
region: Size,
) -> SourceResult<(String, Vec<Segment<'a>>, SpanMapper)> {
let mut collector = Collector::new(2 + children.len());
let mut quoter = SmartQuoter::new();
if !config.first_line_indent.is_zero() {
collector.push_item(Item::Absolute(config.first_line_indent, false));
collector.spans.push(1, Span::detached());
}
if !config.hanging_indent.is_zero() {
collector.push_item(Item::Absolute(-config.hanging_indent, false));
collector.spans.push(1, Span::detached());
}
for &(child, styles) in children {
let prev_len = collector.full.len();
if child.is::<SpaceElem>() {
collector.push_text(" ", styles);
} else if let Some(elem) = child.to_packed::<TextElem>() {
collector.build_text(styles, |full| {
let dir = styles.resolve(TextElem::dir);
if dir != config.dir {
// Insert "Explicit Directional Embedding".
match dir {
Dir::LTR => full.push_str(LTR_EMBEDDING),
Dir::RTL => full.push_str(RTL_EMBEDDING),
_ => {}
}
}
if let Some(case) = styles.get(TextElem::case) {
full.push_str(&case.apply(&elem.text));
} else {
full.push_str(&elem.text);
}
if dir != config.dir {
// Insert "Pop Directional Formatting".
full.push_str(POP_EMBEDDING);
}
});
} else if let Some(elem) = child.to_packed::<HElem>() {
if elem.amount.is_zero() {
continue;
}
collector.push_item(match elem.amount {
Spacing::Fr(fr) => Item::Fractional(fr, None),
Spacing::Rel(rel) => Item::Absolute(
rel.resolve(styles).relative_to(region.x),
elem.weak.get(styles),
),
});
} else if let Some(elem) = child.to_packed::<LinebreakElem>() {
collector.push_text(
if elem.justify.get(styles) { "\u{2028}" } else { "\n" },
styles,
);
} else if let Some(elem) = child.to_packed::<SmartQuoteElem>() {
let double = elem.double.get(styles);
if elem.enabled.get(styles) {
let quotes = SmartQuotes::get(
elem.quotes.get_ref(styles),
styles.get(TextElem::lang),
styles.get(TextElem::region),
elem.alternative.get(styles),
);
let before =
collector.full.chars().rev().find(|&c| !is_default_ignorable(c));
let quote = quoter.quote(before, "es, double);
collector.push_text(quote, styles);
} else {
collector.push_text(SmartQuotes::fallback(double), styles);
}
} else if let Some(elem) = child.to_packed::<InlineElem>() {
collector.push_item(Item::Skip(LTR_ISOLATE));
for item in elem.layout(engine, locator.next(&elem.span()), styles, region)? {
match item {
InlineItem::Space(space, weak) => {
collector.push_item(Item::Absolute(space, weak));
}
InlineItem::Frame(mut frame) => {
frame.modify(&FrameModifiers::get_in(styles));
apply_shift(&engine.world, &mut frame, styles);
collector.push_item(Item::Frame(frame));
}
}
}
collector.push_item(Item::Skip(POP_ISOLATE));
} else if let Some(elem) = child.to_packed::<BoxElem>() {
let loc = locator.next(&elem.span());
if let Sizing::Fr(v) = elem.width.get(styles) {
collector.push_item(Item::Fractional(v, Some((elem, loc, styles))));
} else {
let mut frame = layout_and_modify(styles, |styles| {
layout_box(elem, engine, loc, styles, region)
})?;
apply_shift(&engine.world, &mut frame, styles);
collector.push_item(Item::Frame(frame));
}
} else if let Some(elem) = child.to_packed::<TagElem>() {
collector.push_item(Item::Tag(&elem.tag));
} else {
// Non-paragraph inline layout should never trigger this since it
// only won't be triggered if we see any non-inline content.
engine.sink.warn(warning!(
child.span(),
"{} may not occur inside of a paragraph and was ignored",
child.func().name(),
));
};
let len = collector.full.len() - prev_len;
collector.spans.push(len, child.span());
}
Ok((collector.full, collector.segments, collector.spans))
}
/// Collects segments.
struct Collector<'a> {
full: String,
segments: Vec<Segment<'a>>,
spans: SpanMapper,
}
impl<'a> Collector<'a> {
fn new(capacity: usize) -> Self {
Self {
full: String::new(),
segments: Vec::with_capacity(capacity),
spans: SpanMapper::new(),
}
}
fn push_text(&mut self, text: &str, styles: StyleChain<'a>) {
self.build_text(styles, |full| full.push_str(text));
}
fn build_text<F>(&mut self, styles: StyleChain<'a>, f: F)
where
F: FnOnce(&mut String),
{
let prev = self.full.len();
f(&mut self.full);
let segment_len = self.full.len() - prev;
// Merge adjacent text segments with the same styles.
if let Some(Segment::Text(last_len, last_styles)) = self.segments.last_mut()
&& *last_styles == styles
{
*last_len += segment_len;
return;
}
self.segments.push(Segment::Text(segment_len, styles));
}
fn push_item(&mut self, item: Item<'a>) {
match (self.segments.last_mut(), &item) {
// Merge adjacent weak spacing by taking the maximum.
(
Some(Segment::Item(Item::Absolute(prev_amount, true))),
Item::Absolute(amount, true),
) => {
*prev_amount = (*prev_amount).max(*amount);
}
_ => {
self.full.push_str(item.textual());
self.segments.push(Segment::Item(item));
}
}
}
}
/// Maps byte offsets back to spans.
#[derive(Default)]
pub struct SpanMapper(Vec<(usize, Span)>);
impl SpanMapper {
/// Create a new span mapper.
pub fn new() -> Self {
Self::default()
}
/// Push a span for a segment with the given length.
pub fn push(&mut self, len: usize, span: Span) {
self.0.push((len, span));
}
/// Determine the span at the given byte offset.
///
/// May return a detached span.
pub fn span_at(&self, offset: usize) -> (Span, u16) {
let mut cursor = 0;
for &(len, span) in &self.0 {
if (cursor..cursor + len).contains(&offset) {
return (span, u16::try_from(offset - cursor).unwrap_or(0));
}
cursor += len;
}
(Span::detached(), 0)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/shaping.rs | crates/typst-layout/src/inline/shaping.rs | use std::borrow::Cow;
use std::fmt::{self, Debug, Formatter};
use std::ops::Deref;
use std::sync::Arc;
use az::SaturatingAs;
use comemo::Tracked;
use rustybuzz::{BufferFlags, Feature, ShapePlan, UnicodeBuffer};
use ttf_parser::Tag;
use ttf_parser::gsub::SubstitutionSubtable;
use typst_library::World;
use typst_library::engine::Engine;
use typst_library::foundations::{Regex, Smart, StyleChain};
use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Rel, Size};
use typst_library::model::{JustificationLimits, ParElem};
use typst_library::text::{
Font, FontFamily, FontVariant, Glyph, Lang, Region, ShiftSettings, TextEdgeBounds,
TextElem, TextItem, families, features, is_default_ignorable, language, variant,
};
use typst_utils::SliceExt;
use unicode_bidi::{BidiInfo, Level as BidiLevel};
use unicode_script::{Script, UnicodeScript};
use super::{Item, Range, SpanMapper, decorate};
use crate::modifiers::FrameModifyText;
const SHY: char = '\u{ad}';
const SHY_STR: &str = "\u{ad}";
const HYPHEN: char = '-';
const HYPHEN_STR: &str = "-";
/// The result of shaping text.
///
/// This type contains owned or borrowed shaped text runs, which can be
/// measured, used to reshape substrings more quickly and converted into a
/// frame.
#[derive(Clone)]
pub struct ShapedText<'a> {
/// The start of the text in the full text.
pub base: usize,
/// The text that was shaped.
pub text: &'a str,
/// The text direction.
pub dir: Dir,
/// The text language.
pub lang: Lang,
/// The text region.
pub region: Option<Region>,
/// The text's style properties.
pub styles: StyleChain<'a>,
/// The font variant.
pub variant: FontVariant,
/// The shaped glyphs.
pub glyphs: Glyphs<'a>,
}
/// A copy-on-write collection of glyphs.
///
/// At the edges of the collection, there can be _trimmed_ glyphs for end-of-line
/// whitespace that should not affect layout, but should be emitted into the PDF
/// to keep things accessible.
///
/// These glyphs are not visible when deref-ing the `Glyphs` to a slice as they
/// should be ignored in almost all circumstances. They are only visible when
/// explicitly accessing [`all`](Self::all) glyphs.
#[derive(Clone)]
pub struct Glyphs<'a> {
/// All glyphs, including the trimmed ones.
inner: Cow<'a, [ShapedGlyph]>,
/// The range of untrimmed glyphs.
kept: Range,
}
impl<'a> Glyphs<'a> {
/// Create a borrowed glyph collection from an existing slice.
///
/// This happens after reshaping.
pub fn from_slice(glyphs: &'a [ShapedGlyph]) -> Self {
Self {
inner: Cow::Borrowed(glyphs),
kept: 0..glyphs.len(),
}
}
/// Create an owned glyph collection from an vector.
///
/// This happens after initial shaping.
pub fn from_vec(glyphs: Vec<ShapedGlyph>) -> Self {
let len = glyphs.len();
Self { inner: Cow::Owned(glyphs), kept: 0..len }
}
/// Clone the internal glyph data to make it modifiable. Should be avoided
/// if possible on potentially borrowed glyphs as it can be expensive
/// (benchmarks have shown ~10% slowdown on a text-heavy document if no
/// borrowing is used).
pub fn to_mut(&mut self) -> &mut [ShapedGlyph] {
&mut self.inner.to_mut()[self.kept.clone()]
}
/// Trims glyphs that satisfy the given condition from the start and end.
///
/// Those glyphs will not be visible during normal operation anymore, only
/// through [`all`](Self::all).
pub fn trim(&mut self, f: impl FnMut(&ShapedGlyph) -> bool + Copy) {
let (start, end) = self.inner.split_prefix_suffix(f);
self.kept = start..end;
}
/// Accesses all glyphs, not just the untrimmed ones.
pub fn all(&self) -> &[ShapedGlyph] {
self.inner.as_ref()
}
/// Whether this contains neither kept nor trimmed glyphs.
pub fn is_fully_empty(&self) -> bool {
self.inner.is_empty()
}
}
impl<'a> Deref for Glyphs<'a> {
type Target = [ShapedGlyph];
/// Returns only the kept (untrimmed) glyphs.
fn deref(&self) -> &Self::Target {
&self.inner[self.kept.clone()]
}
}
/// A single glyph resulting from shaping.
#[derive(Debug, Clone)]
pub struct ShapedGlyph {
/// The font the glyph is contained in.
pub font: Font,
/// The glyph's index in the font.
pub glyph_id: u16,
/// The advance width of the glyph.
pub x_advance: Em,
/// The horizontal offset of the glyph.
pub x_offset: Em,
/// The vertical offset of the glyph.
pub y_offset: Em,
/// The font size for the glyph.
pub size: Abs,
/// The adjustability of the glyph.
pub adjustability: Adjustability,
/// The byte range of this glyph's cluster in the full inline layout. A
/// cluster is a sequence of one or multiple glyphs that cannot be separated
/// and must always be treated as a union.
///
/// The range values of the glyphs in a [`ShapedText`] should not overlap
/// with each other, and they should be monotonically increasing (for
/// left-to-right or top-to-bottom text) or monotonically decreasing (for
/// right-to-left or bottom-to-top text).
pub range: Range,
/// Whether splitting the shaping result before this glyph would yield the
/// same results as shaping the parts to both sides of `text_index`
/// separately.
pub safe_to_break: bool,
/// The first char in this glyph's cluster.
pub c: char,
/// Whether this glyph is justifiable for CJK scripts.
pub is_justifiable: bool,
/// The script of the glyph.
pub script: Script,
}
#[derive(Debug, Default, Clone)]
pub struct Adjustability {
/// The left and right stretchability
pub stretchability: (Em, Em),
/// The left and right shrinkability
pub shrinkability: (Em, Em),
}
impl ShapedGlyph {
/// Whether the glyph is a space.
pub fn is_space(&self) -> bool {
is_space(self.c)
}
/// Whether the glyph is justifiable.
pub fn is_justifiable(&self) -> bool {
// GB style is not relevant here.
self.is_justifiable
}
/// Whether the glyph is part of Chinese or Japanese script (i.e. CJ, not CJK).
pub fn is_cj_script(&self) -> bool {
is_cj_script(self.c, self.script)
}
pub fn is_cjk_punctuation(&self) -> bool {
self.is_cjk_left_aligned_punctuation(CjkPunctStyle::Gb)
|| self.is_cjk_right_aligned_punctuation()
|| self.is_cjk_center_aligned_punctuation(CjkPunctStyle::Gb)
}
/// See <https://www.w3.org/TR/clreq/#punctuation_width_adjustment>
pub fn is_cjk_left_aligned_punctuation(&self, style: CjkPunctStyle) -> bool {
is_cjk_left_aligned_punctuation(
self.c,
self.x_advance,
self.stretchability(),
style,
)
}
/// See <https://www.w3.org/TR/clreq/#punctuation_width_adjustment>
pub fn is_cjk_right_aligned_punctuation(&self) -> bool {
is_cjk_right_aligned_punctuation(self.c, self.x_advance, self.stretchability())
}
/// See <https://www.w3.org/TR/clreq/#punctuation_width_adjustment>
pub fn is_cjk_center_aligned_punctuation(&self, style: CjkPunctStyle) -> bool {
is_cjk_center_aligned_punctuation(self.c, style)
}
/// Whether the glyph is a western letter or number.
pub fn is_letter_or_number(&self) -> bool {
matches!(self.c.script(), Script::Latin | Script::Greek | Script::Cyrillic)
|| matches!(self.c, '#' | '$' | '%' | '&')
|| self.c.is_ascii_digit()
}
/// The amount by which the glyph's advance width is allowed to be shrunk or
/// stretched to improve justification.
pub fn base_adjustability(
&self,
style: CjkPunctStyle,
limits: &JustificationLimits,
font_size: Abs,
stretchable: bool,
) -> Adjustability {
let width = self.x_advance;
// Do not ever shrink away more than three quarters of the glyph. As the
// width approaches zero, justification gets increasingly expensive and
// if negative it may not terminate.
let limited = |v: Em| v.min(width * 0.75);
if self.is_space() {
// To a space, both the spacing and tracking limits apply, just like
// `text.tracking` and `text.spacing` both apply to spaces.
let max = limits.spacing().max + limits.tracking().max;
let min = limits.spacing().min + limits.tracking().min;
Adjustability {
stretchability: (
Em::zero(),
(max - Rel::one())
.map(|length| Em::from_length(length, font_size))
.relative_to(width)
.max(Em::zero()),
),
shrinkability: (
Em::zero(),
limited(
(Rel::one() - min)
.map(|length| Em::from_length(length, font_size))
.relative_to(width),
),
),
}
} else if self.is_cjk_left_aligned_punctuation(style) {
Adjustability {
stretchability: (Em::zero(), Em::zero()),
shrinkability: (Em::zero(), width / 2.0),
}
} else if self.is_cjk_right_aligned_punctuation() {
Adjustability {
stretchability: (Em::zero(), Em::zero()),
shrinkability: (width / 2.0, Em::zero()),
}
} else if self.is_cjk_center_aligned_punctuation(style) {
Adjustability {
stretchability: (Em::zero(), Em::zero()),
shrinkability: (width / 4.0, width / 4.0),
}
} else if stretchable {
Adjustability {
stretchability: (
Em::zero(),
Em::from_length(limits.tracking().max, font_size).max(Em::zero()),
),
shrinkability: (
Em::zero(),
limited(Em::from_length(-limits.tracking().min, font_size)),
),
}
} else {
Adjustability::default()
}
}
/// The stretchability of the character.
pub fn stretchability(&self) -> (Em, Em) {
self.adjustability.stretchability
}
/// The shrinkability of the character.
pub fn shrinkability(&self) -> (Em, Em) {
self.adjustability.shrinkability
}
/// Shrink the width of glyph on the left side.
pub fn shrink_left(&mut self, amount: Em) {
self.x_offset -= amount;
self.x_advance -= amount;
self.adjustability.shrinkability.0 -= amount;
}
/// Shrink the width of glyph on the right side.
pub fn shrink_right(&mut self, amount: Em) {
self.x_advance -= amount;
self.adjustability.shrinkability.1 -= amount;
}
}
impl<'a> ShapedText<'a> {
/// Build the shaped text's frame.
///
/// The `justification` defines how much extra advance width each
/// [justifiable glyph](ShapedGlyph::is_justifiable) will get.
pub fn build(
&self,
engine: &Engine,
spans: &SpanMapper,
justification_ratio: f64,
extra_justification: Abs,
) -> Frame {
let (top, bottom) = self.measure(engine);
let size = Size::new(self.width(), top + bottom);
let mut offset = Abs::zero();
let mut frame = Frame::soft(size);
frame.set_baseline(top);
let size = self.styles.resolve(TextElem::size);
let shift = self.styles.resolve(TextElem::baseline);
let decos = self.styles.get_cloned(TextElem::deco);
let fill = self.styles.get_ref(TextElem::fill);
let stroke = self.styles.resolve(TextElem::stroke);
let span_offset = self.styles.get(TextElem::span_offset);
let mut i = 0;
for ((font, y_offset, glyph_size), group) in self
.glyphs
.all()
.group_by_key(|g| (g.font.clone(), g.y_offset, g.size))
{
let mut range = group[0].range.clone();
for glyph in group {
range.start = range.start.min(glyph.range.start);
range.end = range.end.max(glyph.range.end);
}
let pos = Point::new(offset, top + shift - y_offset.at(size));
let glyphs: Vec<Glyph> = group
.iter()
.map(|shaped: &ShapedGlyph| {
// Whether the glyph is _not_ trimmed end-of-line
// whitespace. Trimmed whitespace has its advance width and
// offset zeroed out and is not taken into account for
// justification.
let kept = self.glyphs.kept.contains(&i);
let (x_advance, x_offset) = if kept {
let adjustability_left = if justification_ratio < 0.0 {
shaped.shrinkability().0
} else {
shaped.stretchability().0
};
let adjustability_right = if justification_ratio < 0.0 {
shaped.shrinkability().1
} else {
shaped.stretchability().1
};
let justification_left = adjustability_left * justification_ratio;
let mut justification_right =
adjustability_right * justification_ratio;
if shaped.is_justifiable() {
justification_right +=
Em::from_abs(extra_justification, glyph_size)
}
frame.size_mut().x += justification_left.at(glyph_size)
+ justification_right.at(glyph_size);
(
shaped.x_advance + justification_left + justification_right,
shaped.x_offset + justification_left,
)
} else {
(Em::zero(), Em::zero())
};
i += 1;
// We may not be able to reach the offset completely if
// it exceeds u16, but better to have a roughly correct
// span offset than nothing.
let mut span = spans.span_at(shaped.range.start);
span.1 = span.1.saturating_add(span_offset.saturating_as());
// |<---- a Glyph ---->|
// -->|ShapedGlyph|<--
// +---+-----------+---+
// | | *********| |
// | | * | |
// | | * ****| |
// | | * *| |
// | | *********| |
// +---+--+--------+---+
// A B C D
// Note A, B, D could be positive, zero, or negative.
// A: justification_left
// B: ShapedGlyph's x_offset
// (though a small part of the glyph may go inside B)
// B+C: ShapedGlyph's x_advance
// D: justification_right
// A+B: Glyph's x_offset
// A+B+C+D: Glyph's x_advance
Glyph {
id: shaped.glyph_id,
x_advance,
x_offset,
y_advance: Em::zero(),
y_offset: Em::zero(),
range: (shaped.range.start - range.start).saturating_as()
..(shaped.range.end - range.start).saturating_as(),
span,
}
})
.collect();
let item = TextItem {
font,
size: glyph_size,
lang: self.lang,
region: self.region,
fill: fill.clone(),
stroke: stroke.clone().map(|s| s.unwrap_or_default()),
text: self.text[range.start - self.base..range.end - self.base].into(),
glyphs,
};
let width = item.width();
if decos.is_empty() {
frame.push(pos, FrameItem::Text(item));
} else {
// Apply line decorations.
frame.push(pos, FrameItem::Text(item.clone()));
for deco in &decos {
decorate(&mut frame, deco, &item, width, shift, pos);
}
}
offset += width;
}
frame.modify_text(self.styles);
frame
}
/// Computes the width of a run of glyphs relative to the font size,
/// accounting for their individual scaling factors and other font metrics.
pub fn width(&self) -> Abs {
self.glyphs.iter().map(|g| g.x_advance.at(g.size)).sum()
}
/// Measure the top and bottom extent of this text.
pub fn measure(&self, engine: &Engine) -> (Abs, Abs) {
let mut top = Abs::zero();
let mut bottom = Abs::zero();
let size = self.styles.resolve(TextElem::size);
let top_edge = self.styles.get(TextElem::top_edge);
let bottom_edge = self.styles.get(TextElem::bottom_edge);
// Expand top and bottom by reading the font's vertical metrics.
let mut expand = |font: &Font, bounds: TextEdgeBounds| {
let (t, b) = font.edges(top_edge, bottom_edge, size, bounds);
top.set_max(t);
bottom.set_max(b);
};
if self.glyphs.is_fully_empty() {
// When there are no glyphs, we just use the vertical metrics of the
// first available font.
let world = engine.world;
for family in families(self.styles) {
if let Some(font) = world
.book()
.select(family.as_str(), self.variant)
.and_then(|id| world.font(id))
{
expand(&font, TextEdgeBounds::Zero);
break;
}
}
} else {
for g in self.glyphs.iter() {
expand(&g.font, TextEdgeBounds::Glyph(g.glyph_id));
}
}
(top, bottom)
}
/// How many glyphs are in the text where we can insert additional
/// space when encountering underfull lines.
pub fn justifiables(&self) -> usize {
self.glyphs.iter().filter(|g| g.is_justifiable()).count()
}
/// Whether the last glyph is a CJK character which should not be justified
/// on line end.
pub fn cjk_justifiable_at_last(&self) -> bool {
self.glyphs
.last()
.map(|g| g.is_cj_script() || g.is_cjk_punctuation())
.unwrap_or(false)
}
/// The stretchability of the text.
pub fn stretchability(&self) -> Abs {
self.glyphs
.iter()
.map(|g| (g.stretchability().0 + g.stretchability().1).at(g.size))
.sum()
}
/// The shrinkability of the text
pub fn shrinkability(&self) -> Abs {
self.glyphs
.iter()
.map(|g| (g.shrinkability().0 + g.shrinkability().1).at(g.size))
.sum()
}
/// Reshape a range of the shaped text, reusing information from this
/// shaping process if possible.
///
/// The text `range` is relative to the whole inline layout.
pub fn reshape(&'a self, engine: &Engine, text_range: Range) -> ShapedText<'a> {
let text = &self.text[text_range.start - self.base..text_range.end - self.base];
if let Some(glyphs) = self.slice_safe_to_break(text_range.clone()) {
#[cfg(debug_assertions)]
assert_all_glyphs_in_range(glyphs, text, text_range.clone());
Self {
base: text_range.start,
text,
dir: self.dir,
lang: self.lang,
region: self.region,
styles: self.styles,
variant: self.variant,
glyphs: Glyphs::from_slice(glyphs),
}
} else {
shape(
engine,
text_range.start,
text,
self.styles,
self.dir,
self.lang,
self.region,
)
}
}
/// Derive an empty text run with the same properties as this one.
pub fn empty(&self) -> Self {
Self { text: "", glyphs: Glyphs::from_slice(&[]), ..*self }
}
/// Creates shaped text containing a hyphen.
///
/// If `soft` is true, the item will map to plain text as a soft hyphen.
/// Otherwise, it will map to a normal hyphen.
pub fn hyphen(
engine: &Engine,
fallback: bool,
base: &ShapedText<'a>,
pos: usize,
soft: bool,
) -> Option<Self> {
let world = engine.world;
let book = world.book();
let fallback_func = if fallback {
Some(|| book.select_fallback(None, base.variant, "-"))
} else {
None
};
let mut chain = families(base.styles)
.filter(|family| family.covers().is_none_or(|c| c.is_match("-")))
.map(|family| book.select(family.as_str(), base.variant))
.chain(fallback_func.iter().map(|f| f()))
.flatten();
chain.find_map(|id| {
let font = world.font(id)?;
let ttf = font.ttf();
let glyph_id = ttf.glyph_index('-')?;
let x_advance = font.to_em(ttf.glyph_hor_advance(glyph_id)?);
let size = base.styles.resolve(TextElem::size);
let (c, text) = if soft { (SHY, SHY_STR) } else { (HYPHEN, HYPHEN_STR) };
Some(ShapedText {
base: pos,
text,
dir: base.dir,
lang: base.lang,
region: base.region,
styles: base.styles,
variant: base.variant,
glyphs: Glyphs::from_vec(vec![ShapedGlyph {
font,
glyph_id: glyph_id.0,
x_advance,
x_offset: Em::zero(),
y_offset: Em::zero(),
size,
adjustability: Adjustability::default(),
range: pos..pos + text.len(),
safe_to_break: true,
c,
is_justifiable: false,
script: Script::Common,
}]),
})
})
}
/// Find the subslice of glyphs that represent the given text range if both
/// sides are safe to break.
fn slice_safe_to_break(&self, text_range: Range) -> Option<&[ShapedGlyph]> {
let Range { mut start, mut end } = text_range;
if !self.dir.is_positive() {
std::mem::swap(&mut start, &mut end);
}
let left = self.find_safe_to_break(start)?;
let right = self.find_safe_to_break(end)?;
Some(&self.glyphs[left..right])
}
/// Find the glyph offset matching the text index that is most towards the
/// start of the text and safe-to-break.
fn find_safe_to_break(&self, text_index: usize) -> Option<usize> {
let ltr = self.dir.is_positive();
// Handle edge cases.
let len = self.glyphs.len();
if text_index == self.base {
return Some(if ltr { 0 } else { len });
} else if text_index == self.base + self.text.len() {
return Some(if ltr { len } else { 0 });
}
// Find any glyph with the text index.
let found = self.glyphs.binary_search_by(|g: &ShapedGlyph| {
let ordering = g.range.start.cmp(&text_index);
if ltr { ordering } else { ordering.reverse() }
});
let mut idx = match found {
Ok(idx) => idx,
Err(idx) => {
// Handle the special case where we break before a '\n'
//
// For example: (assume `a` is a CJK character with three bytes)
// text: " a \n b "
// index: 0 1 2 3 4 5
// text_index: ^
// glyphs: 0 . 1
//
// We will get found = Err(1), because '\n' does not have a
// glyph. But it's safe to break here. Thus the following
// condition:
// - glyphs[0].end == text_index == 3
// - text[3] == '\n'
return (idx > 0
&& self.glyphs[idx - 1].range.end == text_index
&& self.text[text_index - self.base..].starts_with('\n'))
.then_some(idx);
}
};
// Search for the start-most glyph with the text index. This means
// we take empty range glyphs at the start and leave those at the end
// for the next line.
let dec = if ltr { usize::checked_sub } else { usize::checked_add };
while let Some(next) = dec(idx, 1) {
if self.glyphs.get(next).is_none_or(|g| g.range.start != text_index) {
break;
}
idx = next;
}
// RTL needs offset one because the left side of the range should be
// exclusive and the right side inclusive, contrary to the normal
// behaviour of ranges.
self.glyphs[idx].safe_to_break.then_some(idx + usize::from(!ltr))
}
}
impl Debug for ShapedText<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.text.fmt(f)
}
}
/// Group a range of text by BiDi level and script, shape the runs and generate
/// items for them.
pub fn shape_range<'a>(
items: &mut Vec<(Range, Item<'a>)>,
engine: &Engine,
text: &'a str,
bidi: &BidiInfo<'a>,
range: Range,
styles: StyleChain<'a>,
) {
let script = styles.get(TextElem::script);
let lang = styles.get(TextElem::lang);
let region = styles.get(TextElem::region);
let mut process = |range: Range, level: BidiLevel| {
let dir = if level.is_ltr() { Dir::LTR } else { Dir::RTL };
let shaped =
shape(engine, range.start, &text[range.clone()], styles, dir, lang, region);
items.push((range, Item::Text(shaped)));
};
let mut prev_level = BidiLevel::ltr();
let mut prev_script = Script::Unknown;
let mut cursor = range.start;
// Group by embedding level and script. If the text's script is explicitly
// set (rather than inferred from the glyphs), we keep the script at an
// unchanging `Script::Unknown` so that only level changes cause breaks.
for i in range.clone() {
if !text.is_char_boundary(i) {
continue;
}
let level = bidi.levels[i];
let curr_script = match script {
Smart::Auto => {
text[i..].chars().next().map_or(Script::Unknown, |c| c.script())
}
Smart::Custom(_) => Script::Unknown,
};
if level != prev_level || !is_compatible(curr_script, prev_script) {
if cursor < i {
process(cursor..i, prev_level);
}
cursor = i;
prev_level = level;
prev_script = curr_script;
} else if is_generic_script(prev_script) {
prev_script = curr_script;
}
}
process(cursor..range.end, prev_level);
}
/// Whether this is not a specific script.
fn is_generic_script(script: Script) -> bool {
matches!(script, Script::Unknown | Script::Common | Script::Inherited)
}
/// Whether these script can be part of the same shape run.
fn is_compatible(a: Script, b: Script) -> bool {
is_generic_script(a) || is_generic_script(b) || a == b
}
/// Shape text into [`ShapedText`].
#[allow(clippy::too_many_arguments)]
fn shape<'a>(
engine: &Engine,
base: usize,
text: &'a str,
styles: StyleChain<'a>,
dir: Dir,
lang: Lang,
region: Option<Region>,
) -> ShapedText<'a> {
let size = styles.resolve(TextElem::size);
let shift_settings = styles.get(TextElem::shift_settings);
let mut ctx = ShapingContext {
world: engine.world,
size,
glyphs: vec![],
used: vec![],
styles,
variant: variant(styles),
features: features(styles),
fallback: styles.get(TextElem::fallback),
dir,
shift_settings,
};
if !text.is_empty() {
shape_segment(&mut ctx, base, text, families(styles));
}
track_and_space(&mut ctx);
calculate_adjustability(&mut ctx, lang, region);
#[cfg(debug_assertions)]
assert_all_glyphs_in_range(&ctx.glyphs, text, base..(base + text.len()));
#[cfg(debug_assertions)]
assert_glyph_ranges_in_order(&ctx.glyphs, dir);
ShapedText {
base,
text,
dir,
lang,
region,
styles,
variant: ctx.variant,
glyphs: Glyphs::from_vec(ctx.glyphs),
}
}
/// Holds shaping results and metadata common to all shaped segments.
struct ShapingContext<'a> {
world: Tracked<'a, dyn World + 'a>,
glyphs: Vec<ShapedGlyph>,
used: Vec<Font>,
styles: StyleChain<'a>,
size: Abs,
variant: FontVariant,
features: Vec<rustybuzz::Feature>,
fallback: bool,
dir: Dir,
shift_settings: Option<ShiftSettings>,
}
pub trait SharedShapingContext<'a> {
fn world(&self) -> Tracked<'a, dyn World + 'a>;
/// Font families that have been used with unlimited coverage.
///
/// These font families are considered exhausted and will not be used again,
/// even if they are declared again (e.g., during fallback after normal selection).
fn used(&mut self) -> &mut Vec<Font>;
fn first(&self) -> Option<&Font>;
fn variant(&self) -> FontVariant;
fn fallback(&self) -> bool;
}
impl<'a> SharedShapingContext<'a> for ShapingContext<'a> {
fn world(&self) -> Tracked<'a, dyn World + 'a> {
self.world
}
fn used(&mut self) -> &mut Vec<Font> {
&mut self.used
}
fn first(&self) -> Option<&Font> {
self.used.first()
}
fn variant(&self) -> FontVariant {
self.variant
}
fn fallback(&self) -> bool {
self.fallback
}
}
pub fn get_font_and_covers<'a, C, F>(
ctx: &mut C,
text: &str,
mut families: impl Iterator<Item = &'a FontFamily>,
mut shape_tofus: F,
) -> Option<(Font, Option<&'a Regex>)>
where
C: SharedShapingContext<'a>,
F: FnMut(&mut C, &str, Font),
{
// Find the next available family.
let world = ctx.world();
let book = world.book();
let mut selection = None;
let mut covers = None;
for family in families.by_ref() {
selection = book
.select(family.as_str(), ctx.variant())
.and_then(|id| world.font(id))
.filter(|font| !ctx.used().contains(font));
if selection.is_some() {
covers = family.covers();
break;
}
}
// Do font fallback if the families are exhausted and fallback is enabled.
if selection.is_none() && ctx.fallback() {
let first = ctx.first().map(Font::info);
selection = book
.select_fallback(first, ctx.variant(), text)
.and_then(|id| world.font(id))
.filter(|font| !ctx.used().contains(font));
}
// Extract the font id or shape notdef glyphs if we couldn't find any font.
let Some(font) = selection else {
if let Some(font) = ctx.used().first().cloned() {
shape_tofus(ctx, text, font);
}
return None;
};
// This font has been exhausted and will not be used again.
if covers.is_none() {
ctx.used().push(font.clone());
}
Some((font, covers))
}
/// Shape text with font fallback using the `families` iterator.
fn shape_segment<'a>(
ctx: &mut ShapingContext<'a>,
base: usize,
text: &str,
mut families: impl Iterator<Item = &'a FontFamily> + Clone,
) {
// Don't try shaping newlines, tabs, or default ignorables.
if text
.chars()
.all(|c| c == '\n' || c == '\t' || is_default_ignorable(c))
{
return;
}
let Some((font, covers)) =
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/finalize.rs | crates/typst-layout/src/inline/finalize.rs | use typst_library::introspection::SplitLocator;
use typst_utils::Numeric;
use super::*;
/// Turns the selected lines into frames.
#[typst_macros::time]
pub fn finalize(
engine: &mut Engine,
p: &Preparation,
lines: &[Line],
region: Size,
expand: bool,
locator: &mut SplitLocator<'_>,
) -> SourceResult<Fragment> {
// Determine the resulting width: Full width of the region if we should
// expand or there's fractional spacing, fit-to-width otherwise.
let width = if !region.x.is_finite()
|| (!expand && lines.iter().all(|line| line.fr().is_zero()))
{
region.x.min(
p.config.hanging_indent
+ lines.iter().map(|line| line.width).max().unwrap_or_default(),
)
} else {
region.x
};
// Stack the lines into one frame per region.
lines
.iter()
.map(|line| commit(engine, p, line, width, region.y, locator))
.collect::<SourceResult<_>>()
.map(Fragment::frames)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/linebreak.rs | crates/typst-layout/src/inline/linebreak.rs | use std::ops::{Add, Sub};
use std::sync::LazyLock;
use az::SaturatingAs;
use icu_properties::LineBreak;
use icu_properties::maps::{CodePointMapData, CodePointMapDataBorrowed};
use icu_provider::AsDeserializingBufferProvider;
use icu_provider_adapters::fork::ForkByKeyProvider;
use icu_provider_blob::BlobDataProvider;
use icu_segmenter::LineSegmenter;
use typst_library::engine::Engine;
use typst_library::layout::{Abs, Em};
use typst_library::model::Linebreaks;
use typst_library::text::{Lang, TextElem};
use typst_syntax::link_prefix;
use unicode_segmentation::UnicodeSegmentation;
use super::*;
/// The cost of a line or inline layout.
type Cost = f64;
// Cost parameters.
//
// We choose higher costs than the Knuth-Plass paper (which would be 50) because
// it hyphenates way to eagerly in Typst otherwise. Could be related to the
// ratios coming out differently since Typst doesn't have the concept of glue,
// so things work a bit differently.
const DEFAULT_HYPH_COST: Cost = 135.0;
const DEFAULT_RUNT_COST: Cost = 100.0;
// Other parameters.
const MIN_RATIO: f64 = -1.0;
const MIN_APPROX_RATIO: f64 = -0.5;
const BOUND_EPS: f64 = 1e-3;
/// The ICU blob data.
fn blob() -> BlobDataProvider {
BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU).unwrap()
}
/// The general line break segmenter.
static SEGMENTER: LazyLock<LineSegmenter> =
LazyLock::new(|| LineSegmenter::try_new_lstm_with_buffer_provider(&blob()).unwrap());
/// The line break segmenter for Chinese/Japanese text.
static CJ_SEGMENTER: LazyLock<LineSegmenter> = LazyLock::new(|| {
let cj_blob =
BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU_CJ_SEGMENT)
.unwrap();
let cj_provider = ForkByKeyProvider::new(cj_blob, blob());
LineSegmenter::try_new_lstm_with_buffer_provider(&cj_provider).unwrap()
});
/// The Unicode line break properties for each code point.
static LINEBREAK_DATA: LazyLock<CodePointMapData<LineBreak>> = LazyLock::new(|| {
icu_properties::maps::load_line_break(&blob().as_deserializing()).unwrap()
});
// Zero width space.
const ZWS: char = '\u{200B}';
/// A line break opportunity.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Breakpoint {
/// Just a normal opportunity (e.g. after a space).
Normal,
/// A mandatory breakpoint (after '\n' or at the end of the text).
Mandatory,
/// An opportunity for hyphenating and how many chars are before/after it
/// in the word.
Hyphen(u8, u8),
}
impl Breakpoint {
/// Trim a line before this breakpoint.
pub fn trim(self, start: usize, line: &str) -> Trim {
match self {
// Trailing whitespace should be shaped, but the glyphs should have
// their advance width zeroed. This way, they are available for copy
// paste, but don't influence layout. The zero width space already
// has zero advance width, so would not need to be trimmed for that
// reason, but it can interfere with end-of-line adjustments in CJK
// layout, so it is included here. Unfortunately, there isn't
// currently a test for this.
Self::Normal => {
let trimmed =
line.trim_end_matches(|c: char| c.is_whitespace() || c == ZWS);
Trim {
layout: start + trimmed.len(),
shaping: start + line.len(),
}
}
// Trim linebreaks.
Self::Mandatory => {
let lb = LINEBREAK_DATA.as_borrowed();
let trimmed = line.trim_end_matches(|c| {
matches!(
lb.get(c),
LineBreak::MandatoryBreak
| LineBreak::CarriageReturn
| LineBreak::LineFeed
| LineBreak::NextLine
)
});
Trim::uniform(start + trimmed.len())
}
// Trim nothing.
Self::Hyphen(..) => Trim::uniform(start + line.len()),
}
}
/// Whether this is a hyphen breakpoint.
pub fn is_hyphen(self) -> bool {
matches!(self, Self::Hyphen(..))
}
}
/// How to trim the end of a line.
///
/// It's an invariant that `self.layout <= self.shaping`.
pub struct Trim {
/// The text in the range `layout..shaping` should be shaped but should not
/// affect layout. This ensures that we trim spaces for layout purposes, but
/// still render zero-advance space glyphs for copy paste.
pub layout: usize,
/// The text should only be shaped up until the given text offset. Newlines
/// are already trimmed here.
pub shaping: usize,
}
impl Trim {
/// Create an instance with equal layout and shaping trim.
fn uniform(trim: usize) -> Self {
Self { layout: trim, shaping: trim }
}
}
/// Breaks the text into lines.
pub fn linebreak<'a>(
engine: &Engine,
p: &'a Preparation<'a>,
width: Abs,
) -> Vec<Line<'a>> {
match p.config.linebreaks {
Linebreaks::Simple => linebreak_simple(engine, p, width),
Linebreaks::Optimized => linebreak_optimized(engine, p, width),
}
}
/// Performs line breaking in simple first-fit style. This means that we build
/// lines greedily, always taking the longest possible line. This may lead to
/// very unbalanced line, but is fast and simple.
#[typst_macros::time]
fn linebreak_simple<'a>(
engine: &Engine,
p: &'a Preparation<'a>,
width: Abs,
) -> Vec<Line<'a>> {
let mut lines = Vec::with_capacity(16);
let mut start = 0;
let mut last = None;
breakpoints(p, |end, breakpoint| {
// Compute the line and its size.
let mut attempt = line(engine, p, start..end, breakpoint, lines.last());
// If the line doesn't fit anymore, we push the last fitting attempt
// into the stack and rebuild the line from the attempt's end. The
// resulting line cannot be broken up further.
if !width.fits(attempt.width)
&& let Some((last_attempt, last_end)) = last.take()
{
lines.push(last_attempt);
start = last_end;
attempt = line(engine, p, start..end, breakpoint, lines.last());
}
// Finish the current line if there is a mandatory line break (i.e. due
// to "\n") or if the line doesn't fit horizontally already since then
// no shorter line will be possible.
if breakpoint == Breakpoint::Mandatory || !width.fits(attempt.width) {
lines.push(attempt);
start = end;
last = None;
} else {
last = Some((attempt, end));
}
});
if let Some((line, _)) = last {
lines.push(line);
}
lines
}
/// Performs line breaking in optimized Knuth-Plass style. Here, we use more
/// context to determine the line breaks than in the simple first-fit style. For
/// example, we might choose to cut a line short even though there is still a
/// bit of space to improve the fit of one of the following lines. The
/// Knuth-Plass algorithm is based on the idea of "cost". A line which has a
/// very tight or very loose fit has a higher cost than one that is just right.
/// Ending a line with a hyphen incurs extra cost and endings two successive
/// lines with hyphens even more.
///
/// To find the layout with the minimal total cost the algorithm uses dynamic
/// programming: For each possible breakpoint, it determines the optimal layout
/// _up to that point_. It walks over all possible start points for a line
/// ending at that point and finds the one for which the cost of the line plus
/// the cost of the optimal layout up to the start point (already computed and
/// stored in dynamic programming table) is minimal. The final result is simply
/// the layout determined for the last breakpoint at the end of text.
#[typst_macros::time]
fn linebreak_optimized<'a>(
engine: &Engine,
p: &'a Preparation<'a>,
width: Abs,
) -> Vec<Line<'a>> {
let metrics = CostMetrics::compute(p);
// Determines the exact costs of a likely good layout through Knuth-Plass
// with approximate metrics. We can use this cost as an upper bound to prune
// the search space in our proper optimization pass below.
let upper_bound = linebreak_optimized_approximate(engine, p, width, &metrics);
// Using the upper bound, perform exact optimized linebreaking.
linebreak_optimized_bounded(engine, p, width, &metrics, upper_bound)
}
/// Performs line breaking in optimized Knuth-Plass style, but with an upper
/// bound on the cost. This allows us to skip many parts of the search space.
#[typst_macros::time]
fn linebreak_optimized_bounded<'a>(
engine: &Engine,
p: &'a Preparation<'a>,
width: Abs,
metrics: &CostMetrics,
upper_bound: Cost,
) -> Vec<Line<'a>> {
/// An entry in the dynamic programming table for inline layout optimization.
struct Entry<'a> {
pred: usize,
total: Cost,
line: Line<'a>,
end: usize,
}
// Dynamic programming table.
let mut table = vec![Entry { pred: 0, total: 0.0, line: Line::empty(), end: 0 }];
let mut active = 0;
let mut prev_end = 0;
breakpoints(p, |end, breakpoint| {
// Find the optimal predecessor.
let mut best: Option<Entry> = None;
// A lower bound for the cost of all following line attempts.
let mut line_lower_bound = None;
for (pred_index, pred) in table.iter().enumerate().skip(active) {
let start = pred.end;
let unbreakable = prev_end == start;
// If the minimum cost we've established for the line is already
// too much, skip this attempt.
if line_lower_bound
.is_some_and(|lower| pred.total + lower > upper_bound + BOUND_EPS)
{
continue;
}
// Build the line.
let attempt = line(engine, p, start..end, breakpoint, Some(&pred.line));
// Determine the cost of the line and its stretch ratio.
let (line_ratio, line_cost) = ratio_and_cost(
p,
metrics,
width,
&pred.line,
&attempt,
breakpoint,
unbreakable,
);
// If the line is overfull, we adjust the set of active candidate
// line starts. This is the case if
// - justification is on, but we'd need to shrink too much
// - justification is off and the line just doesn't fit
//
// If this is the earliest breakpoint in the active set
// (active == i), remove it from the active set. If there is an
// earlier one (active < i), then the logically shorter line was
// in fact longer (can happen with negative spacing) and we
// can't trim the active set just yet.
if line_ratio < metrics.min_ratio && active == pred_index {
active += 1;
}
// The total cost of this line and its chain of predecessors.
let total = pred.total + line_cost;
// If the line is already underfull (`line_ratio > 0`), any shorter
// slice of the line will be even more underfull. So it'll only get
// worse from here and further attempts would also have a cost
// exceeding `bound`. There is one exception: When the line has
// negative spacing, we can't know for sure, so we don't assign the
// lower bound in that case.
if line_ratio > 0.0
&& line_lower_bound.is_none()
&& !attempt.has_negative_width_items()
{
line_lower_bound = Some(line_cost);
}
// If the cost already exceeds the upper bound, we don't need to
// integrate this result into the table.
if total > upper_bound + BOUND_EPS {
continue;
}
// If this attempt is better than what we had before, take it!
if best.as_ref().is_none_or(|best| best.total >= total) {
best = Some(Entry { pred: pred_index, total, line: attempt, end });
}
}
// If this is a mandatory break, all breakpoints before this one become
// inactive since no line can span over the mandatory break.
if breakpoint == Breakpoint::Mandatory {
active = table.len();
}
table.extend(best);
prev_end = end;
});
// Retrace the best path.
let mut lines = Vec::with_capacity(16);
let mut idx = table.len() - 1;
// This should only happen if our bound was faulty. Which shouldn't happen!
if table[idx].end != p.text.len() {
#[cfg(debug_assertions)]
panic!("bounded inline layout is incomplete");
#[cfg(not(debug_assertions))]
return linebreak_optimized_bounded(engine, p, width, metrics, Cost::INFINITY);
}
while idx != 0 {
table.truncate(idx + 1);
let entry = table.pop().unwrap();
lines.push(entry.line);
idx = entry.pred;
}
lines.reverse();
lines
}
/// Runs the normal Knuth-Plass algorithm, but instead of building proper lines
/// (which is costly) to determine costs, it determines approximate costs using
/// cumulative arrays.
///
/// This results in a likely good inline layouts, for which we then compute
/// the exact cost. This cost is an upper bound for proper optimized
/// linebreaking. We can use it to heavily prune the search space.
#[typst_macros::time]
fn linebreak_optimized_approximate(
engine: &Engine,
p: &Preparation,
width: Abs,
metrics: &CostMetrics,
) -> Cost {
// Determine the cumulative estimation metrics.
let estimates = Estimates::compute(p);
/// An entry in the dynamic programming table for inline layout optimization.
struct Entry {
pred: usize,
total: Cost,
end: usize,
unbreakable: bool,
breakpoint: Breakpoint,
}
// Dynamic programming table.
let mut table = vec![Entry {
pred: 0,
total: 0.0,
end: 0,
unbreakable: false,
breakpoint: Breakpoint::Mandatory,
}];
let mut active = 0;
let mut prev_end = 0;
breakpoints(p, |end, breakpoint| {
// Find the optimal predecessor.
let mut best: Option<Entry> = None;
for (pred_index, pred) in table.iter().enumerate().skip(active) {
let start = pred.end;
let unbreakable = prev_end == start;
// Whether the line is justified. This is not 100% accurate w.r.t
// to line()'s behaviour, but good enough.
let justify = p.config.justify && breakpoint != Breakpoint::Mandatory;
// We don't really know whether the line naturally ends with a dash
// here, so we can miss that case, but it's ok, since all of this
// just an estimate.
let consecutive_dash = pred.breakpoint.is_hyphen() && breakpoint.is_hyphen();
// Estimate how much the line's spaces would need to be stretched to
// make it the desired width. We trim at the end to not take into
// account trailing spaces. This is, again, only an approximation of
// the real behaviour of `line`.
let trimmed_end = start + p.text[start..end].trim_end().len();
let line_ratio = raw_ratio(
p,
width,
estimates.widths.estimate(start..trimmed_end)
+ if breakpoint.is_hyphen() {
metrics.approx_hyphen_width
} else {
Abs::zero()
},
estimates.stretchability.estimate(start..trimmed_end),
estimates.shrinkability.estimate(start..trimmed_end),
estimates.justifiables.estimate(start..trimmed_end),
);
// Determine the line's cost.
let line_cost = raw_cost(
metrics,
breakpoint,
line_ratio,
justify,
unbreakable,
consecutive_dash,
true,
);
// Adjust the set of active breakpoints.
// See `linebreak_optimized` for details.
if line_ratio < metrics.min_ratio && active == pred_index {
active += 1;
}
// The total cost of this line and its chain of predecessors.
let total = pred.total + line_cost;
// If this attempt is better than what we had before, take it!
if best.as_ref().is_none_or(|best| best.total >= total) {
best = Some(Entry {
pred: pred_index,
total,
end,
unbreakable,
breakpoint,
});
}
}
// If this is a mandatory break, all breakpoints before this one become
// inactive.
if breakpoint == Breakpoint::Mandatory {
active = table.len();
}
table.extend(best);
prev_end = end;
});
// Retrace the best path.
let mut indices = Vec::with_capacity(16);
let mut idx = table.len() - 1;
while idx != 0 {
indices.push(idx);
idx = table[idx].pred;
}
let mut pred = Line::empty();
let mut start = 0;
let mut exact = 0.0;
// The cost that we optimized was only an approximate cost, so the layout we
// got here is only likely to be good, not guaranteed to be the best. We now
// computes its exact cost as that gives us a sound upper bound for the
// proper optimization pass.
for idx in indices.into_iter().rev() {
let Entry { end, breakpoint, unbreakable, .. } = table[idx];
let attempt = line(engine, p, start..end, breakpoint, Some(&pred));
let (ratio, line_cost) =
ratio_and_cost(p, metrics, width, &pred, &attempt, breakpoint, unbreakable);
// If approximation produces a valid layout without too much shrinking,
// exact layout is guaranteed to find the same layout. If, however, the
// line is overfull, we do not have this guarantee. Then, our bound
// becomes useless and actively harmful (it could be lower than what
// optimal layout produces). Thus, we immediately bail with an infinite
// bound in this case.
if ratio < metrics.min_ratio {
return Cost::INFINITY;
}
pred = attempt;
start = end;
exact += line_cost;
}
exact
}
/// Compute the stretch ratio and cost of a line.
#[allow(clippy::too_many_arguments)]
fn ratio_and_cost(
p: &Preparation,
metrics: &CostMetrics,
available_width: Abs,
pred: &Line,
attempt: &Line,
breakpoint: Breakpoint,
unbreakable: bool,
) -> (f64, Cost) {
let ratio = raw_ratio(
p,
available_width,
attempt.width,
attempt.stretchability(),
attempt.shrinkability(),
attempt.justifiables(),
);
let cost = raw_cost(
metrics,
breakpoint,
ratio,
attempt.justify,
unbreakable,
pred.dash.is_some() && attempt.dash.is_some(),
false,
);
(ratio, cost)
}
/// Determine the stretch ratio for a line given raw metrics.
///
/// - A ratio < min_ratio indicates an overfull line.
/// - A negative ratio indicates a line that needs shrinking.
/// - A ratio of zero indicates a perfect line.
/// - A positive ratio indicates a line that needs stretching.
fn raw_ratio(
p: &Preparation,
available_width: Abs,
line_width: Abs,
stretchability: Abs,
shrinkability: Abs,
justifiables: usize,
) -> f64 {
// Determine how much the line's spaces would need to be stretched
// to make it the desired width.
let mut delta = available_width - line_width;
// Avoid possible floating point errors in previous calculation.
if delta.approx_eq(Abs::zero()) {
delta = Abs::zero();
}
// Determine how much stretch or shrink is natural.
let adjustability = if delta >= Abs::zero() { stretchability } else { shrinkability };
// Observations:
// - `delta` is negative for a line that needs shrinking and positive for a
// line that needs stretching.
// - `adjustability` must be non-negative to make sense.
// - `ratio` inherits the sign of `delta`.
let mut ratio = delta / adjustability.max(Abs::zero());
// The most likely cause of a NaN result is that `delta` was zero. This
// often happens with monospace fonts and CJK texts. It means that the line
// already fits perfectly, so `ratio` should be zero then.
if ratio.is_nan() {
ratio = 0.0;
}
// If the ratio exceeds 1, we should stretch above the natural
// stretchability using justifiables.
if ratio > 1.0 {
// We should stretch the line above its stretchability. Now
// calculate the extra amount. Also, don't divide by zero.
let extra_stretch = (delta - adjustability) / justifiables.max(1) as f64;
// Normalize the amount by half the em size.
ratio = 1.0 + extra_stretch / (p.config.font_size / 2.0);
}
// The min value must be < MIN_RATIO, but how much smaller doesn't matter
// since overfull lines have hard-coded huge costs anyway.
//
// The max value is clamped to 10 since it doesn't really matter whether a
// line is stretched 10x or 20x.
ratio.clamp(MIN_RATIO - 1.0, 10.0)
}
/// Compute the cost of a line given raw metrics.
///
/// This mostly follows the formula in the Knuth-Plass paper, but there are some
/// adjustments.
fn raw_cost(
metrics: &CostMetrics,
breakpoint: Breakpoint,
ratio: f64,
justify: bool,
unbreakable: bool,
consecutive_dash: bool,
approx: bool,
) -> Cost {
// Determine the stretch/shrink cost of the line.
let badness = if ratio < metrics.min_ratio(approx) {
// Overfull line always has maximum cost.
1_000_000.0
} else if breakpoint != Breakpoint::Mandatory || justify || ratio < 0.0 {
// If the line shall be justified or needs shrinking, it has normal
// badness with cost 100|ratio|^3. We limit the ratio to 10 as to not
// get to close to our maximum cost.
100.0 * ratio.abs().powi(3)
} else {
// If the line shouldn't be justified and doesn't need shrink, we don't
// pay any cost.
0.0
};
// Compute penalties.
let mut penalty = 0.0;
// Penalize runts (lone words before a mandatory break / at the end).
if unbreakable && breakpoint == Breakpoint::Mandatory {
penalty += metrics.runt_cost;
}
// Penalize hyphenation.
if let Breakpoint::Hyphen(l, r) = breakpoint {
// We penalize hyphenations close to the edges of the word (< LIMIT
// chars) extra. For each step of distance from the limit, we add 15%
// to the cost.
const LIMIT: u8 = 5;
let steps = LIMIT.saturating_sub(l) + LIMIT.saturating_sub(r);
let extra = 0.15 * steps as f64;
penalty += (1.0 + extra) * metrics.hyph_cost;
}
// Penalize two consecutive dashes extra (not necessarily hyphens).
// Knuth-Plass does this separately after the squaring, with a higher cost,
// but I couldn't find any explanation as to why.
if consecutive_dash {
penalty += metrics.hyph_cost;
}
// From the Knuth-Plass Paper: $ (1 + beta_j + pi_j)^2 $.
//
// We add one to minimize the number of lines when everything else is more
// or less equal.
(1.0 + badness + penalty).powi(2)
}
/// Calls `f` for all possible points in the text where lines can broken.
///
/// Yields for each breakpoint the text index, whether the break is mandatory
/// (after `\n`) and whether a hyphen is required (when breaking inside of a
/// word).
///
/// This is an internal instead of an external iterator because it makes the
/// code much simpler and the consumers of this function don't need the
/// composability and flexibility of external iteration anyway.
fn breakpoints(p: &Preparation, mut f: impl FnMut(usize, Breakpoint)) {
let text = p.text;
// Single breakpoint at the end for empty text.
if text.is_empty() {
f(0, Breakpoint::Mandatory);
return;
}
let hyphenate = p.config.hyphenate != Some(false);
let lb = LINEBREAK_DATA.as_borrowed();
let segmenter = match p.config.lang {
Some(Lang::CHINESE | Lang::JAPANESE) => &CJ_SEGMENTER,
_ => &SEGMENTER,
};
let mut last = 0;
let mut iter = segmenter.segment_str(text).peekable();
loop {
// Special case for links. UAX #14 doesn't handle them well.
let (head, tail) = text.split_at(last);
if head.ends_with("://") || tail.starts_with("www.") {
let (link, _) = link_prefix(tail);
linebreak_link(link, |i| f(last + i, Breakpoint::Normal));
last += link.len();
while iter.peek().is_some_and(|&p| p < last) {
iter.next();
}
}
// Get the next UAX #14 linebreak opportunity.
let Some(point) = iter.next() else { break };
// Skip breakpoint if there is no char before it. icu4x generates one
// at offset 0, but we don't want it.
let Some(c) = text[..point].chars().next_back() else { continue };
// Find out whether the last break was mandatory by checking against
// rules LB4 and LB5, special-casing the end of text according to LB3.
// See also: https://docs.rs/icu_segmenter/latest/icu_segmenter/struct.LineSegmenter.html
let breakpoint = if point == text.len() {
Breakpoint::Mandatory
} else {
const OBJ_REPLACE: char = '\u{FFFC}';
match lb.get(c) {
LineBreak::MandatoryBreak
| LineBreak::CarriageReturn
| LineBreak::LineFeed
| LineBreak::NextLine => Breakpoint::Mandatory,
// https://github.com/typst/typst/issues/5489
//
// OBJECT-REPLACEMENT-CHARACTERs provide Contingent Break
// opportunities before and after by default. This behaviour
// is however tailorable, see:
// https://www.unicode.org/reports/tr14/#CB
// https://www.unicode.org/reports/tr14/#TailorableBreakingRules
// https://www.unicode.org/reports/tr14/#LB20
//
// Don't provide a line breaking opportunity between a LTR-
// ISOLATE (or any other Combining Mark) and an OBJECT-
// REPLACEMENT-CHARACTER representing an inline item, if the
// LTR-ISOLATE could end up as the only character on the
// previous line.
LineBreak::CombiningMark
if text[point..].starts_with(OBJ_REPLACE)
&& last + c.len_utf8() == point =>
{
continue;
}
_ => Breakpoint::Normal,
}
};
// Hyphenate between the last and current breakpoint.
if hyphenate && last < point {
for segment in text[last..point].split_word_bounds() {
if !segment.is_empty() && segment.chars().all(char::is_alphabetic) {
hyphenations(p, &lb, last, segment, &mut f);
}
last += segment.len();
}
}
// Call `f` for the UAX #14 break opportunity.
f(point, breakpoint);
last = point;
}
}
/// Generate breakpoints for hyphenations within a word.
fn hyphenations(
p: &Preparation,
lb: &CodePointMapDataBorrowed<LineBreak>,
mut offset: usize,
word: &str,
mut f: impl FnMut(usize, Breakpoint),
) {
let Some(lang) = lang_at(p, offset) else { return };
let count = word.chars().count();
let end = offset + word.len();
let mut chars = 0;
for syllable in hypher::hyphenate(word, lang) {
offset += syllable.len();
chars += syllable.chars().count();
// Don't hyphenate after the final syllable.
if offset == end {
continue;
}
// Filter out hyphenation opportunities where hyphenation was actually
// disabled.
if !hyphenate_at(p, offset) {
continue;
}
// Filter out forbidden hyphenation opportunities.
if matches!(
syllable.chars().next_back().map(|c| lb.get(c)),
Some(LineBreak::Glue | LineBreak::WordJoiner | LineBreak::ZWJ)
) {
continue;
}
// Determine the number of codepoints before and after the hyphenation.
let l = chars.saturating_as::<u8>();
let r = (count - chars).saturating_as::<u8>();
// Call `f` for the word-internal hyphenation opportunity.
f(offset, Breakpoint::Hyphen(l, r));
}
}
/// Produce linebreak opportunities for a link.
fn linebreak_link(link: &str, mut f: impl FnMut(usize)) {
#[derive(PartialEq)]
enum Class {
Alphabetic,
Digit,
Open,
Other,
}
impl Class {
fn of(c: char) -> Self {
if c.is_alphabetic() {
Class::Alphabetic
} else if c.is_numeric() {
Class::Digit
} else if matches!(c, '(' | '[') {
Class::Open
} else {
Class::Other
}
}
}
let mut offset = 0;
let mut prev = Class::Other;
for (end, c) in link.char_indices() {
let class = Class::of(c);
// Emit opportunities when going from
// - other -> other
// - alphabetic -> numeric
// - numeric -> alphabetic
// Never before/after opening delimiters.
if end > 0
&& prev != Class::Open
&& if class == Class::Other { prev == Class::Other } else { class != prev }
{
let piece = &link[offset..end];
if piece.len() < 16 {
// For bearably long segments, emit them as one.
offset = end;
f(offset);
} else {
// If it gets very long (e.g. a hash in the URL), just allow a
// break at every char.
for c in piece.chars() {
offset += c.len_utf8();
f(offset);
}
}
}
prev = class;
}
}
/// Whether hyphenation is enabled at the given offset.
fn hyphenate_at(p: &Preparation, offset: usize) -> bool {
p.config.hyphenate.unwrap_or_else(|| {
let (_, item) = p.get(offset);
match item.text() {
Some(text) => {
text.styles.get(TextElem::hyphenate).unwrap_or(p.config.justify)
}
None => false,
}
})
}
/// The text language at the given offset.
fn lang_at(p: &Preparation, offset: usize) -> Option<hypher::Lang> {
let lang = p.config.lang.or_else(|| {
let (_, item) = p.get(offset);
let styles = item.text()?.styles;
Some(styles.get(TextElem::lang))
})?;
let bytes = lang.as_str().as_bytes().try_into().ok()?;
hypher::Lang::from_iso(bytes)
}
/// Resolved metrics relevant for cost computation.
struct CostMetrics {
min_ratio: f64,
min_approx_ratio: f64,
approx_hyphen_width: Abs,
hyph_cost: Cost,
runt_cost: Cost,
}
impl CostMetrics {
/// Compute shared metrics for inline layout optimization.
fn compute(p: &Preparation) -> Self {
Self {
// When justifying, we may stretch spaces below their natural width.
min_ratio: if p.config.justify { MIN_RATIO } else { 0.0 },
min_approx_ratio: if p.config.justify { MIN_APPROX_RATIO } else { 0.0 },
// Approximate hyphen width for estimates.
approx_hyphen_width: Em::new(0.33).at(p.config.font_size),
// Costs.
hyph_cost: DEFAULT_HYPH_COST * p.config.costs.hyphenation().get(),
runt_cost: DEFAULT_RUNT_COST * p.config.costs.runt().get(),
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/mod.rs | crates/typst-layout/src/inline/mod.rs | #[path = "box.rs"]
mod box_;
mod collect;
mod deco;
mod finalize;
mod line;
mod linebreak;
mod prepare;
mod shaping;
pub use self::box_::layout_box;
pub use self::shaping::{SharedShapingContext, create_shape_plan, get_font_and_covers};
use comemo::{Track, Tracked, TrackedMut};
use typst_library::World;
use typst_library::diag::SourceResult;
use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{Packed, Smart, StyleChain};
use typst_library::introspection::{Introspector, Locator, LocatorLink, SplitLocator};
use typst_library::layout::{Abs, AlignElem, Dir, FixedAlignment, Fragment, Size};
use typst_library::model::{
EnumElem, FirstLineIndent, JustificationLimits, Linebreaks, ListElem, ParElem,
ParLine, ParLineMarker, TermsElem,
};
use typst_library::routines::{Arenas, Pair, RealizationKind, Routines};
use typst_library::text::{Costs, Lang, TextElem};
use typst_utils::{Numeric, Protected, SliceExt};
use self::collect::{Item, Segment, SpanMapper, collect};
use self::deco::decorate;
use self::finalize::finalize;
use self::line::{Line, apply_shift, commit, line};
use self::linebreak::{Breakpoint, linebreak};
use self::prepare::{Preparation, prepare};
use self::shaping::{
BEGIN_PUNCT_PAT, END_PUNCT_PAT, ShapedGlyph, ShapedText, cjk_punct_style,
is_of_cj_script, shape_range,
};
/// Range of a substring of text.
type Range = std::ops::Range<usize>;
/// Layouts the paragraph.
pub fn layout_par(
elem: &Packed<ParElem>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Size,
expand: bool,
situation: ParSituation,
) -> SourceResult<Fragment> {
layout_par_impl(
elem,
engine.routines,
engine.world,
engine.introspector.into_raw(),
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
locator.track(),
styles,
region,
expand,
situation,
)
}
/// The internal, memoized implementation of `layout_par`.
#[comemo::memoize]
#[allow(clippy::too_many_arguments)]
fn layout_par_impl(
elem: &Packed<ParElem>,
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
locator: Tracked<Locator>,
styles: StyleChain,
region: Size,
expand: bool,
situation: ParSituation,
) -> SourceResult<Fragment> {
let introspector = Protected::from_raw(introspector);
let link = LocatorLink::new(locator);
let mut locator = Locator::link(&link).split();
let mut engine = Engine {
routines,
world,
introspector,
traced,
sink,
route: Route::extend(route),
};
let arenas = Arenas::default();
let children = (engine.routines.realize)(
RealizationKind::LayoutPar,
&mut engine,
&mut locator,
&arenas,
&elem.body,
styles,
)?;
layout_inline_impl(
&mut engine,
&children,
&mut locator,
styles,
region,
expand,
Some(situation),
&ConfigBase {
justify: elem.justify.get(styles),
linebreaks: elem.linebreaks.get(styles),
first_line_indent: elem.first_line_indent.get(styles),
hanging_indent: elem.hanging_indent.resolve(styles),
},
)
}
/// Lays out realized content with inline layout.
pub fn layout_inline<'a>(
engine: &mut Engine,
children: &[Pair<'a>],
locator: &mut SplitLocator<'a>,
shared: StyleChain<'a>,
region: Size,
expand: bool,
) -> SourceResult<Fragment> {
layout_inline_impl(
engine,
children,
locator,
shared,
region,
expand,
None,
&ConfigBase {
justify: shared.get(ParElem::justify),
linebreaks: shared.get(ParElem::linebreaks),
first_line_indent: shared.get(ParElem::first_line_indent),
hanging_indent: shared.resolve(ParElem::hanging_indent),
},
)
}
/// The internal implementation of [`layout_inline`].
#[allow(clippy::too_many_arguments)]
fn layout_inline_impl<'a>(
engine: &mut Engine,
children: &[Pair<'a>],
locator: &mut SplitLocator<'a>,
shared: StyleChain<'a>,
region: Size,
expand: bool,
par: Option<ParSituation>,
base: &ConfigBase,
) -> SourceResult<Fragment> {
// Prepare configuration that is shared across the whole inline layout.
let config = configuration(base, children, shared, par);
// Collect all text into one string for BiDi analysis.
let (text, segments, spans) = collect(children, engine, locator, &config, region)?;
// Perform BiDi analysis and performs some preparation steps before we
// proceed to line breaking.
let p = prepare(engine, &config, &text, segments, spans)?;
// Break the text into lines.
let lines = linebreak(engine, &p, region.x - config.hanging_indent);
// Turn the selected lines into frames.
finalize(engine, &p, &lines, region, expand, locator)
}
/// Determine the inline layout's configuration.
fn configuration(
base: &ConfigBase,
children: &[Pair],
shared: StyleChain,
situation: Option<ParSituation>,
) -> Config {
let justify = base.justify;
let font_size = shared.resolve(TextElem::size);
let dir = shared.resolve(TextElem::dir);
Config {
justify,
justification_limits: shared.get(ParElem::justification_limits),
linebreaks: base.linebreaks.unwrap_or_else(|| {
if justify { Linebreaks::Optimized } else { Linebreaks::Simple }
}),
first_line_indent: {
let FirstLineIndent { amount, all } = base.first_line_indent;
if !amount.is_zero()
&& match situation {
// First-line indent for the first paragraph after a list
// bullet just looks bad.
Some(ParSituation::First) => all && !in_list(shared),
Some(ParSituation::Consecutive) => true,
Some(ParSituation::Other) => all,
None => false,
}
&& shared.resolve(AlignElem::alignment).x == dir.start().into()
{
amount.at(font_size)
} else {
Abs::zero()
}
},
hanging_indent: if situation.is_some() {
base.hanging_indent
} else {
Abs::zero()
},
numbering_marker: shared.get_cloned(ParLine::numbering).map(|numbering| {
Packed::new(ParLineMarker::new(
numbering,
shared.get(ParLine::number_align),
shared.get(ParLine::number_margin),
// Delay resolving the number clearance until line numbers are
// laid out to avoid inconsistent spacing depending on varying
// font size.
shared.get(ParLine::number_clearance),
))
}),
align: shared.get(AlignElem::alignment).fix(dir).x,
font_size,
dir,
hyphenate: shared_get(children, shared, |s| s.get(TextElem::hyphenate))
.map(|uniform| uniform.unwrap_or(justify)),
lang: shared_get(children, shared, |s| s.get(TextElem::lang)),
fallback: shared.get(TextElem::fallback),
cjk_latin_spacing: shared.get(TextElem::cjk_latin_spacing).is_auto(),
costs: shared.get(TextElem::costs),
}
}
/// Distinguishes between a few different kinds of paragraphs.
///
/// In the form `Option<ParSituation>`, `None` implies that we are creating an
/// inline layout that isn't a semantic paragraph.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ParSituation {
/// The paragraph is the first thing in the flow.
First,
/// The paragraph follows another paragraph.
Consecutive,
/// Any other kind of paragraph.
Other,
}
/// Raw values from a `ParElem` or style chain. Used to initialize a [`Config`].
struct ConfigBase {
justify: bool,
linebreaks: Smart<Linebreaks>,
first_line_indent: FirstLineIndent,
hanging_indent: Abs,
}
/// Shared configuration for the whole inline layout.
struct Config {
/// Whether to justify text.
justify: bool,
/// Settings for justification.
justification_limits: JustificationLimits,
/// How to determine line breaks.
linebreaks: Linebreaks,
/// The indent the first line of a paragraph should have.
first_line_indent: Abs,
/// The indent that all but the first line of a paragraph should have.
hanging_indent: Abs,
/// Configuration for line numbering.
numbering_marker: Option<Packed<ParLineMarker>>,
/// The resolved horizontal alignment.
align: FixedAlignment,
/// The text size.
font_size: Abs,
/// The dominant direction.
dir: Dir,
/// A uniform hyphenation setting (only `Some(_)` if it's the same for all
/// children, otherwise `None`).
hyphenate: Option<bool>,
/// The text language (only `Some(_)` if it's the same for all
/// children, otherwise `None`).
lang: Option<Lang>,
/// Whether font fallback is enabled.
fallback: bool,
/// Whether to add spacing between CJK and Latin characters.
cjk_latin_spacing: bool,
/// Costs for various layout decisions.
costs: Costs,
}
/// Get a style property, but only if it is the same for all of the children.
fn shared_get<T: PartialEq>(
children: &[Pair],
styles: StyleChain<'_>,
getter: fn(StyleChain) -> T,
) -> Option<T> {
let value = getter(styles);
children
.group_by_key(|&(_, s)| s)
.all(|(s, _)| getter(s) == value)
.then_some(value)
}
/// Whether we have a list ancestor.
///
/// When we support some kind of more general ancestry mechanism, this can
/// become more elegant.
fn in_list(styles: StyleChain) -> bool {
styles.get(ListElem::depth).0 > 0
|| !styles.get_cloned(EnumElem::parents).is_empty()
|| styles.get(TermsElem::within)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/line.rs | crates/typst-layout/src/inline/line.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::{Deref, DerefMut};
use typst_library::engine::Engine;
use typst_library::foundations::Resolve;
use typst_library::introspection::{SplitLocator, Tag, TagFlags};
use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point};
use typst_library::model::ParLineMarker;
use typst_library::text::{Lang, TextElem, variant};
use typst_utils::Numeric;
use super::*;
use crate::inline::linebreak::Trim;
use crate::inline::shaping::Adjustability;
use crate::modifiers::layout_and_modify;
const SHY: char = '\u{ad}';
const HYPHEN: char = '-';
const EN_DASH: char = '–';
const EM_DASH: char = '—';
const LINE_SEPARATOR: char = '\u{2028}'; // We use LS to distinguish justified breaks.
/// A layouted line, consisting of a sequence of layouted inline items that are
/// mostly borrowed from the preparation phase. This type enables you to measure
/// the size of a line in a range before committing to building the line's
/// frame.
///
/// At most two inline items must be created individually for this line: The
/// first and last one since they may be broken apart by the start or end of the
/// line, respectively. But even those can partially reuse previous results when
/// the break index is safe-to-break per rustybuzz.
pub struct Line<'a> {
/// The items the line is made of.
pub items: Items<'a>,
/// The exact natural width of the line.
pub width: Abs,
/// Whether the line should be justified.
pub justify: bool,
/// Whether the line ends with a hyphen or dash, either naturally or through
/// hyphenation.
pub dash: Option<Dash>,
}
impl Line<'_> {
/// Create an empty line.
pub fn empty() -> Self {
Self {
items: Items::new(),
width: Abs::zero(),
justify: false,
dash: None,
}
}
/// How many glyphs are in the text where we can insert additional
/// space when encountering underfull lines.
pub fn justifiables(&self) -> usize {
let mut count = 0;
for shaped in self.items.iter().filter_map(Item::text) {
count += shaped.justifiables();
}
// CJK character at line end should not be adjusted.
if self
.items
.trailing_text()
.map(|s| s.cjk_justifiable_at_last())
.unwrap_or(false)
{
count -= 1;
}
count
}
/// How much the line can stretch.
pub fn stretchability(&self) -> Abs {
self.items
.iter()
.filter_map(Item::text)
.map(|s| s.stretchability())
.sum()
}
/// How much the line can shrink.
pub fn shrinkability(&self) -> Abs {
self.items
.iter()
.filter_map(Item::text)
.map(|s| s.shrinkability())
.sum()
}
/// Whether the line has items with negative width.
pub fn has_negative_width_items(&self) -> bool {
self.items.iter().any(|item| match item {
Item::Absolute(amount, _) => *amount < Abs::zero(),
Item::Frame(frame) => frame.width() < Abs::zero(),
_ => false,
})
}
/// The sum of fractions in the line.
pub fn fr(&self) -> Fr {
self.items
.iter()
.filter_map(|item| match item {
Item::Fractional(fr, _) => Some(*fr),
_ => None,
})
.sum()
}
}
/// A dash at the end of a line.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Dash {
/// A soft hyphen added to break a word.
Soft,
/// A regular hyphen, present in a compound word, e.g. beija-flor.
Hard,
/// Another kind of dash. Only relevant for cost computation.
Other,
}
/// Create a line which spans the given range.
pub fn line<'a>(
engine: &Engine,
p: &'a Preparation,
range: Range,
breakpoint: Breakpoint,
pred: Option<&Line<'a>>,
) -> Line<'a> {
// The line's full text.
let full = &p.text[range.clone()];
// Whether the line is justified.
let justify = full.ends_with(LINE_SEPARATOR)
|| (p.config.justify && breakpoint != Breakpoint::Mandatory);
// Process dashes.
let dash = if breakpoint.is_hyphen() || full.ends_with(SHY) {
Some(Dash::Soft)
} else if full.ends_with(HYPHEN) {
Some(Dash::Hard)
} else if full.ends_with([EN_DASH, EM_DASH]) {
Some(Dash::Other)
} else {
None
};
// Trim the line at the end, if necessary for this breakpoint.
let trim = breakpoint.trim(range.start, full);
let trimmed_range = range.start..trim.layout;
// Collect the items for the line.
let mut items = Items::new();
// Add a hyphen at the line start, if a previous dash should be repeated.
if let Some(pred) = pred
&& pred.dash == Some(Dash::Hard)
&& let Some(base) = pred.items.trailing_text()
&& should_repeat_hyphen(base.lang, full)
&& let Some(hyphen) =
ShapedText::hyphen(engine, p.config.fallback, base, trim.shaping, false)
{
items.push(Item::Text(hyphen), LogicalIndex::START_HYPHEN);
}
collect_items(&mut items, engine, p, range, &trim);
// Add a hyphen at the line end, if we ended on a soft hyphen.
if dash == Some(Dash::Soft)
&& let Some(base) = items.trailing_text()
&& let Some(hyphen) =
ShapedText::hyphen(engine, p.config.fallback, base, trim.shaping, true)
{
items.push(Item::Text(hyphen), LogicalIndex::END_HYPHEN);
}
// Ensure that there is no weak spacing at the start and end of the line.
trim_weak_spacing(&mut items);
// Deal with CJ characters at line boundaries.
// Use the trimmed range for robust boundary checks.
adjust_cj_at_line_boundaries(p, trimmed_range, &mut items);
// Deal with stretchability of glyphs at the end of the line.
adjust_glyph_stretch_at_line_end(p, &mut items);
// Compute the line's width.
let width = items.iter().map(Item::natural_width).sum();
Line { items, width, justify, dash }
}
/// Collects / reshapes all items for the line with the given `range`.
///
/// The `trim` defines an end position to which text items are trimmed. For
/// example, the `range` may span "hello\n", but the `trim` specifies that the
/// linebreak is trimmed.
///
/// We do not factor the `trim` directly into the `range` because we still want
/// to keep non-text items after the trim (e.g. tags).
fn collect_items<'a>(
items: &mut Items<'a>,
engine: &Engine,
p: &'a Preparation,
range: Range,
trim: &Trim,
) {
let mut fallback = None;
// Collect the items for each consecutively ordered run.
reorder(p, range.clone(), |subrange, rtl| {
let from = items.len();
collect_range(engine, p, subrange, trim, items, &mut fallback);
if rtl {
items.reorder(from);
}
});
// Add fallback text to expand the line height, if necessary.
if !items.iter().any(|item| matches!(item, Item::Text(_)))
&& let Some((idx, fallback)) = fallback
{
items.push(fallback, idx);
}
}
/// Trims weak spacing from the start and end of the line.
fn trim_weak_spacing(items: &mut Items) {
// Trim weak spacing at the start of the line.
let prefix = items
.iter()
.take_while(|item| matches!(item, Item::Absolute(_, true)))
.count();
if prefix > 0 {
items.drain(..prefix);
}
// Trim weak spacing at the end of the line.
while matches!(items.iter().next_back(), Some(Item::Absolute(_, true))) {
items.pop();
}
}
/// Calls `f` for the BiDi-reordered ranges of a line.
fn reorder<F>(p: &Preparation, range: Range, mut f: F)
where
F: FnMut(Range, bool),
{
// If there is nothing bidirectional going on, skip reordering.
let Some(bidi) = &p.bidi else {
f(range, p.config.dir == Dir::RTL);
return;
};
// The bidi crate panics for empty lines.
if range.is_empty() {
f(range, p.config.dir == Dir::RTL);
return;
}
// Find the paragraph that contains the line.
let para = bidi
.paragraphs
.iter()
.find(|para| para.range.contains(&range.start))
.unwrap();
// Compute the reordered ranges in visual order (left to right).
let (levels, runs) = bidi.visual_runs(para, range.clone());
// Call `f` for each run.
for run in runs {
let rtl = levels[run.start].is_rtl();
f(run, rtl)
}
}
/// Collects / reshapes all items for the given `subrange` with continuous
/// direction.
fn collect_range<'a>(
engine: &Engine,
p: &'a Preparation,
range: Range,
trim: &Trim,
items: &mut Items<'a>,
fallback: &mut Option<(LogicalIndex, ItemEntry<'a>)>,
) {
for (i, (subrange, item)) in p.slice(range.clone()) {
let idx = LogicalIndex::from_item_index(i);
// All non-text items are just kept, they can't be split.
let Item::Text(shaped) = item else {
items.push(item, idx);
continue;
};
// The intersection range of the item, the subrange, and the line's
// trimming.
let sliced = range.start.max(subrange.start)
..range.end.min(subrange.end).min(trim.shaping);
// Whether the item is split by the line.
let split = subrange.start < sliced.start || sliced.end < subrange.end;
if sliced.is_empty() {
// When there is no text, still keep this as a fallback item, which
// we can use to force a non-zero line-height when the line doesn't
// contain any other text.
*fallback = Some((idx, ItemEntry::from(Item::Text(shaped.empty()))));
continue;
}
let mut item: ItemEntry = if split {
// When the item is split in half, reshape it.
let reshaped = shaped.reshape(engine, sliced);
Item::Text(reshaped).into()
} else {
// When the item is fully contained, just keep it.
item.into()
};
// Trim end-of-line whitespace glyphs.
if trim.layout < range.end {
let shaped = item.text_mut().unwrap();
shaped.glyphs.trim(|glyph| trim.layout < glyph.range.end);
}
items.push(item, idx);
}
}
/// Add spacing around punctuation marks for CJ glyphs at line boundaries.
///
/// See Requirements for Chinese Text Layout, Section 3.1.6.3 Compression of
/// punctuation marks at line start or line end.
///
/// The `range` should only contain regular texts, with linebreaks trimmed.
fn adjust_cj_at_line_boundaries(p: &Preparation, range: Range, items: &mut Items) {
let text = &p.text[range];
if text.starts_with(BEGIN_PUNCT_PAT)
|| (p.config.cjk_latin_spacing && text.starts_with(is_of_cj_script))
{
adjust_cj_at_line_start(p, items);
}
if text.ends_with(END_PUNCT_PAT)
|| (p.config.cjk_latin_spacing && text.ends_with(is_of_cj_script))
{
adjust_cj_at_line_end(p, items);
}
}
/// Remove stretchability from the last glyph in the line to avoid trailing
/// space after a glyph due to glyph-level justification.
fn adjust_glyph_stretch_at_line_end(p: &Preparation, items: &mut Items) {
let glyph_limits = &p.config.justification_limits.tracking();
if glyph_limits.min.is_zero() && glyph_limits.max.is_zero() {
return;
}
// This is not perfect (ignores clusters and is not particularly fast), but
// it is good enough for now. The adjustability handling in general needs a
// cleanup.
let Some(shaped) = items.trailing_text_mut() else { return };
let Some(glyph) = shaped.glyphs.to_mut().last_mut() else { return };
glyph.adjustability = Adjustability::default();
}
/// Add spacing around punctuation marks for CJ glyphs at the line start.
fn adjust_cj_at_line_start(p: &Preparation, items: &mut Items) {
let Some(shaped) = items.leading_text_mut() else { return };
let Some(glyph) = shaped.glyphs.first() else { return };
if glyph.is_cjk_right_aligned_punctuation() {
// If the first glyph is a CJK punctuation, we want to
// shrink it.
let glyph = shaped.glyphs.to_mut().first_mut().unwrap();
let shrink = glyph.shrinkability().0;
glyph.shrink_left(shrink);
} else if p.config.cjk_latin_spacing
&& glyph.is_cj_script()
&& glyph.x_offset > Em::zero()
{
// If the first glyph is a CJK character adjusted by
// [`add_cjk_latin_spacing`], restore the original width.
let glyph = shaped.glyphs.to_mut().first_mut().unwrap();
let shrink = glyph.x_offset;
glyph.x_advance -= shrink;
glyph.x_offset = Em::zero();
glyph.adjustability.shrinkability.0 = Em::zero();
}
}
/// Add spacing around punctuation marks for CJ glyphs at the line end.
fn adjust_cj_at_line_end(p: &Preparation, items: &mut Items) {
let Some(shaped) = items.trailing_text_mut() else { return };
let Some(glyph) = shaped.glyphs.last() else { return };
// Deal with CJK punctuation at line ends.
let style = cjk_punct_style(shaped.lang, shaped.region);
if glyph.is_cjk_left_aligned_punctuation(style) {
// If the last glyph is a CJK punctuation, we want to
// shrink it.
let shrink = glyph.shrinkability().1;
let punct = shaped.glyphs.to_mut().last_mut().unwrap();
punct.shrink_right(shrink);
} else if p.config.cjk_latin_spacing
&& glyph.is_cj_script()
&& (glyph.x_advance - glyph.x_offset) > Em::one()
{
// If the last glyph is a CJK character adjusted by
// [`add_cjk_latin_spacing`], restore the original width.
let shrink = glyph.x_advance - glyph.x_offset - Em::one();
let glyph = shaped.glyphs.to_mut().last_mut().unwrap();
glyph.x_advance -= shrink;
glyph.adjustability.shrinkability.1 = Em::zero();
}
}
/// Whether a hyphen should be repeated at the start of the line in the given
/// language, when the following text is the given one.
fn should_repeat_hyphen(lang: Lang, following_text: &str) -> bool {
match lang {
// - Lower Sorbian: see https://dolnoserbski.de/ortografija/psawidla/K3
// - Czech: see https://prirucka.ujc.cas.cz/?id=164
// - Croatian: see http://pravopis.hr/pravilo/spojnica/68/
// - Polish: see https://www.ortograf.pl/zasady-pisowni/lacznik-zasady-pisowni
// - Portuguese: see https://www2.senado.leg.br/bdsf/bitstream/handle/id/508145/000997415.pdf (Base XX)
// - Slovak: see https://www.zones.sk/studentske-prace/gramatika/10620-pravopis-rozdelovanie-slov/
Lang::LOWER_SORBIAN
| Lang::CZECH
| Lang::CROATIAN
| Lang::POLISH
| Lang::PORTUGUESE
| Lang::SLOVAK => true,
// In Spanish the hyphen is required only if the word next to hyphen is
// not capitalized. Otherwise, the hyphen must not be repeated.
//
// See § 4.1.1.1.2.e on the "Ortografía de la lengua española"
// https://www.rae.es/ortografía/como-signo-de-división-de-palabras-a-final-de-línea
Lang::SPANISH => following_text.chars().next().is_some_and(|c| !c.is_uppercase()),
_ => false,
}
}
/// Apply the current baseline shift and italic compensation to a frame.
pub fn apply_shift<'a>(
world: &Tracked<'a, dyn World + 'a>,
frame: &mut Frame,
styles: StyleChain,
) {
let mut baseline = styles.resolve(TextElem::baseline);
let mut compensation = Abs::zero();
if let Some(scripts) = styles.get_ref(TextElem::shift_settings) {
let font_metrics = styles
.get_ref(TextElem::font)
.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.
#[allow(clippy::too_many_arguments)]
pub fn commit(
engine: &mut Engine,
p: &Preparation,
line: &Line,
width: Abs,
full: Abs,
locator: &mut SplitLocator<'_>,
) -> SourceResult<Frame> {
let mut remaining = width - line.width - p.config.hanging_indent;
let mut offset = Abs::zero();
// We always build the line from left to right. In an LTR paragraph, we must
// thus add the hanging indent to the offset. In an RTL paragraph, the
// hanging indent arises naturally due to the line width.
if p.config.dir == Dir::LTR {
offset += p.config.hanging_indent;
}
// Handle hanging punctuation to the left.
if let Some(text) = line.items.leading_text()
&& let Some(glyph) = text.glyphs.first()
&& !text.dir.is_positive()
&& text.styles.get(TextElem::overhang)
&& (line.items.len() > 1 || text.glyphs.len() > 1)
{
let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size);
offset -= amount;
remaining += amount;
}
// Handle hanging punctuation to the right.
if let Some(text) = line.items.trailing_text()
&& let Some(glyph) = text.glyphs.last()
&& text.dir.is_positive()
&& text.styles.get(TextElem::overhang)
&& (line.items.len() > 1 || text.glyphs.len() > 1)
{
let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size);
remaining += amount;
}
// Determine how much additional space is needed. The justification_ratio is
// for the first step justification, extra_justification is for the last
// step. For more info on multi-step justification, see Procedures for
// Inter- Character Space Expansion in W3C document Chinese Layout
// Requirements.
let fr = line.fr();
let mut justification_ratio = 0.0;
let mut extra_justification = Abs::zero();
let shrinkability = line.shrinkability();
let stretchability = line.stretchability();
if remaining < Abs::zero() && shrinkability > Abs::zero() {
// Attempt to reduce the length of the line, using shrinkability.
justification_ratio = (remaining / shrinkability).max(-1.0);
remaining = (remaining + shrinkability).min(Abs::zero());
} else if line.justify && fr.is_zero() {
// Attempt to increase the length of the line, using stretchability.
if stretchability > Abs::zero() {
justification_ratio = (remaining / stretchability).min(1.0);
remaining = (remaining - stretchability).max(Abs::zero());
}
let justifiables = line.justifiables();
if justifiables > 0 && remaining > Abs::zero() {
// Underfull line, distribute the extra space.
extra_justification = remaining / justifiables as f64;
remaining = Abs::zero();
}
}
let mut top = Abs::zero();
let mut bottom = Abs::zero();
// Build the frames and determine the height and baseline.
let mut frames = vec![];
for &(idx, ref item) in line.items.indexed_iter() {
let mut push = |offset: &mut Abs, frame: Frame, idx: LogicalIndex| {
let width = frame.width();
top.set_max(frame.baseline());
bottom.set_max(frame.size().y - frame.baseline());
frames.push((*offset, frame, idx));
*offset += width;
};
match &**item {
Item::Absolute(v, _) => {
offset += *v;
}
Item::Fractional(v, elem) => {
let amount = v.share(fr, remaining);
if let Some((elem, loc, styles)) = elem {
let region = Size::new(amount, full);
let mut frame = layout_and_modify(*styles, |styles| {
layout_box(elem, engine, loc.relayout(), styles, region)
})?;
apply_shift(&engine.world, &mut frame, *styles);
push(&mut offset, frame, idx);
} else {
offset += amount;
}
}
Item::Text(shaped) => {
let frame = shaped.build(
engine,
&p.spans,
justification_ratio,
extra_justification,
);
push(&mut offset, frame, idx);
}
Item::Frame(frame) => {
push(&mut offset, frame.clone(), idx);
}
Item::Tag(tag) => {
let mut frame = Frame::soft(Size::zero());
frame.push(Point::zero(), FrameItem::Tag((*tag).clone()));
frames.push((offset, frame, idx));
}
Item::Skip(_) => {}
}
}
// Remaining space is distributed now.
if !fr.is_zero() {
remaining = Abs::zero();
}
let size = Size::new(width, top + bottom);
let mut output = Frame::soft(size);
output.set_baseline(top);
if let Some(marker) = &p.config.numbering_marker {
add_par_line_marker(&mut output, marker, engine, locator, top);
}
// Ensure that the final frame's items are in logical order rather than in
// visual order. This is important because it affects the order of elements
// during introspection and thus things like counters.
frames.sort_unstable_by_key(|(_, _, idx)| *idx);
// Construct the line's frame.
for (offset, frame, _) in frames {
let x = offset + p.config.align.position(remaining);
let y = top - frame.baseline();
output.push_frame(Point::new(x, y), frame);
}
Ok(output)
}
/// Adds a paragraph line marker to a paragraph line's output frame if
/// line numbering is not `None` at this point. Ensures other style properties,
/// namely number margin, number align and number clearance, are stored in the
/// marker as well.
///
/// The `top` parameter is used to ensure the marker, and thus the line's
/// number in the margin, is aligned to the line's baseline.
fn add_par_line_marker(
output: &mut Frame,
marker: &Packed<ParLineMarker>,
engine: &mut Engine,
locator: &mut SplitLocator,
top: Abs,
) {
// Elements in tags must have a location for introspection to work. We do
// the work here instead of going through all of the realization process
// just for this, given we don't need to actually place the marker as we
// manually search for it in the frame later (when building a root flow,
// where line numbers can be displayed), so we just need it to be in a tag
// and to be valid (to have a location).
let mut marker = marker.clone();
let key = typst_utils::hash128(&marker);
let loc = locator.next_location(engine, key, marker.span());
marker.set_location(loc);
// Create start and end tags through which we can search for this line's
// marker later. The 'x' coordinate is not important, just the 'y'
// coordinate, as that's what is used for line numbers. We will place the
// tags among other subframes in the line such that it is aligned with the
// line's general baseline. However, the line number will still need to
// manually adjust its own 'y' position based on its own baseline.
let pos = Point::with_y(top);
let flags = TagFlags { introspectable: false, tagged: false };
output.push(pos, FrameItem::Tag(Tag::Start(marker.pack(), flags)));
output.push(pos, FrameItem::Tag(Tag::End(loc, key, flags)));
}
/// How much a character should hang into the end margin.
///
/// For more discussion, see:
/// <https://recoveringphysicist.com/21/>
fn overhang(c: char) -> f64 {
match c {
// Dashes.
'–' | '—' => 0.2,
'-' | '\u{ad}' => 0.55,
// Punctuation.
'.' | ',' => 0.8,
':' | ';' => 0.3,
// Arabic
'\u{60C}' | '\u{6D4}' => 0.4,
_ => 0.0,
}
}
/// A collection of owned or borrowed inline items.
pub struct Items<'a>(Vec<(LogicalIndex, ItemEntry<'a>)>);
impl<'a> Items<'a> {
/// Create empty items.
pub fn new() -> Self {
Self(vec![])
}
/// Push a new item.
pub fn push(&mut self, entry: impl Into<ItemEntry<'a>>, idx: LogicalIndex) {
self.0.push((idx, entry.into()));
}
/// Iterate over the items.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Item<'a>> {
self.0.iter().map(|(_, item)| &**item)
}
/// Iterate over the items with the indices that define their logical order.
/// See the docs above `logical_item_idx` for more details.
///
/// Note that this is different from `.iter().enumerate()` which would
/// provide the indices in visual order!
pub fn indexed_iter(
&self,
) -> impl DoubleEndedIterator<Item = &(LogicalIndex, ItemEntry<'a>)> {
self.0.iter()
}
/// Access the first item (skipping tags), if it is text.
pub fn leading_text(&self) -> Option<&ShapedText<'a>> {
self.0.iter().find(|(_, item)| !item.is_tag())?.1.text()
}
/// Access the first item (skipping tags) mutably, if it is text.
pub fn leading_text_mut(&mut self) -> Option<&mut ShapedText<'a>> {
self.0.iter_mut().find(|(_, item)| !item.is_tag())?.1.text_mut()
}
/// Access the last item (skipping tags), if it is text.
pub fn trailing_text(&self) -> Option<&ShapedText<'a>> {
self.0.iter().rev().find(|(_, item)| !item.is_tag())?.1.text()
}
/// Access the last item (skipping tags) mutably, if it is text.
pub fn trailing_text_mut(&mut self) -> Option<&mut ShapedText<'a>> {
self.0.iter_mut().rev().find(|(_, item)| !item.is_tag())?.1.text_mut()
}
/// Reorder the items starting at the given index to RTL.
pub fn reorder(&mut self, from: usize) {
self.0[from..].reverse()
}
}
impl<'a> Deref for Items<'a> {
type Target = Vec<(LogicalIndex, ItemEntry<'a>)>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Items<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Debug for Items<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_list().entries(&self.0).finish()
}
}
/// We use indices to remember the logical (as opposed to visual) order of
/// items. During line building, the items are stored in visual (BiDi-reordered)
/// order. When committing to a line and building its frame, we sort by logical
/// index.
///
/// - Special layout-generated items have custom indices that ensure correct
/// ordering w.r.t. to each other and normal elements, listed below.
/// - Normal items have their position in `p.items` plus the number of special
/// reserved prefix indices.
///
/// Logical indices must be unique within a line because we use an unstable
/// sort.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct LogicalIndex(usize);
impl LogicalIndex {
const START_HYPHEN: Self = Self(0);
const END_HYPHEN: Self = Self(usize::MAX);
/// Create a logical index from the index of an item in the [`p.items`](Preparation::items).
const fn from_item_index(i: usize) -> Self {
// This won't overflow because the `idx` comes from a vector which is
// limited to `isize::MAX` elements.
Self(i + 1)
}
}
/// A reference to or a boxed item.
///
/// This is conceptually similar to a [`Cow<'a, Item<'a>>`][std::borrow::Cow],
/// but we box owned items since an [`Item`] is much bigger than
/// a box.
pub enum ItemEntry<'a> {
Ref(&'a Item<'a>),
Box(Box<Item<'a>>),
}
impl<'a> ItemEntry<'a> {
fn text_mut(&mut self) -> Option<&mut ShapedText<'a>> {
match self {
Self::Ref(item) => {
let text = item.text()?;
*self = Self::Box(Box::new(Item::Text(text.clone())));
match self {
Self::Box(item) => item.text_mut(),
_ => unreachable!(),
}
}
Self::Box(item) => item.text_mut(),
}
}
}
impl<'a> Deref for ItemEntry<'a> {
type Target = Item<'a>;
fn deref(&self) -> &Self::Target {
match self {
Self::Ref(item) => item,
Self::Box(item) => item,
}
}
}
impl Debug for ItemEntry<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
impl<'a> From<&'a Item<'a>> for ItemEntry<'a> {
fn from(item: &'a Item<'a>) -> Self {
Self::Ref(item)
}
}
impl<'a> From<Item<'a>> for ItemEntry<'a> {
fn from(item: Item<'a>) -> Self {
Self::Box(Box::new(item))
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/prepare.rs | crates/typst-layout/src/inline/prepare.rs | use either::Either;
use typst_library::layout::{Dir, Em};
use typst_library::text::TextElem;
use unicode_bidi::{BidiInfo, Level as BidiLevel};
use super::*;
/// A representation in which children are already layouted and text is already
/// preshaped.
///
/// In many cases, we can directly reuse these results when constructing a line.
/// Only when a line break falls onto a text index that is not safe-to-break per
/// rustybuzz, we have to reshape that portion.
pub struct Preparation<'a> {
/// The full text.
pub text: &'a str,
/// Configuration for inline layout.
pub config: &'a Config,
/// Bidirectional text embedding levels.
///
/// This is `None` if all text directions are uniform (all the base
/// direction).
pub bidi: Option<BidiInfo<'a>>,
/// Text runs, spacing and layouted elements.
pub items: Vec<(Range, Item<'a>)>,
/// Maps from byte indices to item indices.
pub indices: Vec<usize>,
/// The span mapper.
pub spans: SpanMapper,
}
impl<'a> Preparation<'a> {
/// Get the item that contains the given `text_offset`.
pub fn get(&self, offset: usize) -> &(Range, Item<'a>) {
let idx = self.indices.get(offset).copied().unwrap_or(0);
&self.items[idx]
}
/// Iterate over the items that intersect the given `sliced` range alongside
/// their indices in `self.items` and their ranges in the paragraph's text.
pub fn slice(
&self,
sliced: Range,
) -> impl Iterator<Item = (usize, &(Range, Item<'a>))> {
// Usually, we don't want empty-range items at the start of the line
// (because they will be part of the previous line), but for the first
// line, we need to keep them.
let start = match sliced.start {
0 => 0,
n => self.indices.get(n).copied().unwrap_or(0),
};
self.items
.iter()
.enumerate()
.skip(start)
.take_while(move |(_, (range, _))| {
range.start < sliced.end || range.end <= sliced.end
})
}
}
/// Performs BiDi analysis and then prepares further layout by building a
/// representation on which we can do line breaking without layouting each and
/// every line from scratch.
#[typst_macros::time]
pub fn prepare<'a>(
engine: &mut Engine,
config: &'a Config,
text: &'a str,
segments: Vec<Segment<'a>>,
spans: SpanMapper,
) -> SourceResult<Preparation<'a>> {
let default_level = match config.dir {
Dir::RTL => BidiLevel::rtl(),
_ => BidiLevel::ltr(),
};
let bidi = BidiInfo::new(text, Some(default_level));
let is_bidi = bidi
.levels
.iter()
.any(|level| level.is_ltr() != default_level.is_ltr());
let mut cursor = 0;
let mut items = Vec::with_capacity(segments.len());
// Shape the text to finalize the items.
for segment in segments {
let len = segment.textual_len();
let end = cursor + len;
let range = cursor..end;
match segment {
Segment::Text(_, styles) => {
shape_range(&mut items, engine, text, &bidi, range, styles);
}
Segment::Item(item) => items.push((range, item)),
}
cursor = end;
}
// Build the mapping from byte to item indices.
let mut indices = Vec::with_capacity(text.len());
for (i, (range, _)) in items.iter().enumerate() {
indices.extend(range.clone().map(|_| i));
}
if config.cjk_latin_spacing {
add_cjk_latin_spacing(&mut items);
}
Ok(Preparation {
config,
text,
bidi: is_bidi.then_some(bidi),
items,
indices,
spans,
})
}
/// Add some spacing between Han characters and western characters. See
/// Requirements for Chinese Text Layout, Section 3.2.2 Mixed Text Composition
/// in Horizontal Written Mode
fn add_cjk_latin_spacing(items: &mut [(Range, Item)]) {
let mut iter = items
.iter_mut()
.filter(|(_, item)| !matches!(item, Item::Tag(_)))
.flat_map(|(_, item)| match item {
Item::Text(text) => Either::Left({
// Check whether the text is normal, sub- or superscript. At
// boundaries between these three, we do not want to insert
// CJK-Latin-Spacing.
let shift =
text.styles.get_ref(TextElem::shift_settings).map(|shift| shift.kind);
// Since we only call this function in [`prepare`], we can
// assume that the Cow is owned, and `to_mut` can be called
// without overhead.
text.glyphs.to_mut().iter_mut().map(move |g| Some((g, shift)))
}),
_ => Either::Right(std::iter::once(None)),
})
.peekable();
let mut prev: Option<(&mut ShapedGlyph, _)> = None;
while let Some(mut item) = iter.next() {
if let Some((glyph, shift)) = &mut item {
// Case 1: CJ followed by a Latin character
if glyph.is_cj_script()
&& let Some(Some((next_glyph, next_shift))) = iter.peek()
&& next_glyph.is_letter_or_number()
&& *shift == *next_shift
{
// The spacing defaults to 1/4 em, and can be shrunk to 1/8 em.
glyph.x_advance += Em::new(0.25);
glyph.adjustability.shrinkability.1 += Em::new(0.125);
}
// Case 2: Latin followed by a CJ character
if glyph.is_cj_script()
&& let Some((prev_glyph, prev_shift)) = prev
&& prev_glyph.is_letter_or_number()
&& *shift == prev_shift
{
glyph.x_advance += Em::new(0.25);
glyph.x_offset += Em::new(0.25);
glyph.adjustability.shrinkability.0 += Em::new(0.125);
}
}
prev = item;
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/inline/deco.rs | crates/typst-layout/src/inline/deco.rs | use kurbo::{BezPath, Line, ParamCurve};
use ttf_parser::{GlyphId, OutlineBuilder};
use typst_library::layout::{Abs, Em, Frame, FrameItem, Point, Size};
use typst_library::text::{
BottomEdge, DecoLine, Decoration, TextEdgeBounds, TextItem, TopEdge,
};
use typst_library::visualize::{FixedStroke, Geometry};
use typst_syntax::Span;
use crate::shapes::styled_rect;
/// Add line decorations to a single run of shaped text.
pub fn decorate(
frame: &mut Frame,
deco: &Decoration,
text: &TextItem,
width: Abs,
shift: Abs,
pos: Point,
) {
let font_metrics = text.font.metrics();
if let DecoLine::Highlight { fill, stroke, top_edge, bottom_edge, radius } =
&deco.line
{
let (top, bottom) = determine_edges(text, *top_edge, *bottom_edge);
let size = Size::new(width + 2.0 * deco.extent, top + bottom);
let rects = styled_rect(size, radius, fill.clone(), stroke);
let origin = Point::new(pos.x - deco.extent, pos.y - top - shift);
frame.prepend_multiple(
rects
.into_iter()
.map(|shape| (origin, FrameItem::Shape(shape, Span::detached()))),
);
return;
}
let (stroke, metrics, offset, evade, background) = match &deco.line {
DecoLine::Strikethrough { stroke, offset, background } => {
(stroke, font_metrics.strikethrough, offset, false, *background)
}
DecoLine::Overline { stroke, offset, evade, background } => {
(stroke, font_metrics.overline, offset, *evade, *background)
}
DecoLine::Underline { stroke, offset, evade, background } => {
(stroke, font_metrics.underline, offset, *evade, *background)
}
_ => return,
};
let offset = offset.unwrap_or(-metrics.position.at(text.size)) - shift;
let stroke = stroke.clone().unwrap_or(FixedStroke::from_pair(
text.fill.as_decoration(),
metrics.thickness.at(text.size),
));
let gap_padding = 0.08 * text.size;
let min_width = 0.162 * text.size;
let start = pos.x - deco.extent;
let end = pos.x + width + deco.extent;
let mut push_segment = |from: Abs, to: Abs, prepend: bool| {
let origin = Point::new(from, pos.y + offset);
let target = Point::new(to - from, Abs::zero());
if target.x >= min_width || !evade {
let shape = Geometry::Line(target).stroked(stroke.clone());
if prepend {
frame.prepend(origin, FrameItem::Shape(shape, Span::detached()));
} else {
frame.push(origin, FrameItem::Shape(shape, Span::detached()));
}
}
};
if !evade {
push_segment(start, end, background);
return;
}
let line = Line::new(
kurbo::Point::new(pos.x.to_raw(), offset.to_raw()),
kurbo::Point::new((pos.x + width).to_raw(), offset.to_raw()),
);
let mut x = pos.x;
let mut intersections = vec![];
for glyph in text.glyphs.iter() {
let dx = glyph.x_offset.at(text.size) + x;
let mut builder =
BezPathBuilder::new(font_metrics.units_per_em, text.size, dx.to_raw());
let bbox = text.font.ttf().outline_glyph(GlyphId(glyph.id), &mut builder);
let path = builder.finish();
x += glyph.x_advance.at(text.size);
// Only do the costly segments intersection test if the line
// intersects the bounding box.
let intersect = bbox.is_some_and(|bbox| {
let y_min = -text.font.to_em(bbox.y_max).at(text.size);
let y_max = -text.font.to_em(bbox.y_min).at(text.size);
offset >= y_min && offset <= y_max
});
if intersect {
// Find all intersections of segments with the line.
intersections.extend(
path.segments()
.flat_map(|seg| seg.intersect_line(line))
.map(|is| Abs::raw(line.eval(is.line_t).x)),
);
}
}
// Add start and end points, taking padding into account.
intersections.push(start - gap_padding);
intersections.push(end + gap_padding);
// When emitting the decorative line segments, we move from left to
// right. The intersections are not necessarily in this order, yet.
intersections.sort();
for edge in intersections.windows(2) {
let l = edge[0];
let r = edge[1];
// If we are too close, don't draw the segment
if r - l < gap_padding {
continue;
} else {
push_segment(l + gap_padding, r - gap_padding, background);
}
}
}
// Return the top/bottom edge of the text given the metric of the font.
fn determine_edges(
text: &TextItem,
top_edge: TopEdge,
bottom_edge: BottomEdge,
) -> (Abs, Abs) {
let mut top = Abs::zero();
let mut bottom = Abs::zero();
for g in text.glyphs.iter() {
let (t, b) = text.font.edges(
top_edge,
bottom_edge,
text.size,
TextEdgeBounds::Glyph(g.id),
);
top.set_max(t);
bottom.set_max(b);
}
(top, bottom)
}
/// Builds a kurbo [`BezPath`] for a glyph.
struct BezPathBuilder {
path: BezPath,
units_per_em: f64,
font_size: Abs,
x_offset: f64,
}
impl BezPathBuilder {
fn new(units_per_em: f64, font_size: Abs, x_offset: f64) -> Self {
Self {
path: BezPath::new(),
units_per_em,
font_size,
x_offset,
}
}
fn finish(self) -> BezPath {
self.path
}
fn p(&self, x: f32, y: f32) -> kurbo::Point {
kurbo::Point::new(self.s(x) + self.x_offset, -self.s(y))
}
fn s(&self, v: f32) -> f64 {
Em::from_units(v, self.units_per_em).at(self.font_size).to_raw()
}
}
impl OutlineBuilder for BezPathBuilder {
fn move_to(&mut self, x: f32, y: f32) {
self.path.move_to(self.p(x, y));
}
fn line_to(&mut self, x: f32, y: f32) {
self.path.line_to(self.p(x, y));
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
self.path.quad_to(self.p(x1, y1), self.p(x, y));
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
self.path.curve_to(self.p(x1, y1), self.p(x2, y2), self.p(x, y));
}
fn close(&mut self) {
self.path.close_path();
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/grid/rowspans.rs | crates/typst-layout/src/grid/rowspans.rs | use typst_library::diag::SourceResult;
use typst_library::engine::Engine;
use typst_library::foundations::Resolve;
use typst_library::layout::grid::resolve::Repeatable;
use typst_library::layout::{Abs, Axes, Frame, Point, Region, Regions, Size, Sizing};
use super::layouter::{Row, points};
use super::{Cell, GridLayouter, layout_cell};
/// All information needed to layout a single rowspan.
pub struct Rowspan {
/// First column of this rowspan.
pub x: usize,
/// First row of this rowspan.
pub y: usize,
/// The disambiguator for laying out the cells.
pub disambiguator: usize,
/// Amount of rows spanned by the cell at (x, y).
pub rowspan: usize,
/// Whether all rows of the rowspan are part of an unbreakable row group.
/// This is true e.g. in headers and footers, regardless of what the user
/// specified for the parent cell's `breakable` field.
pub is_effectively_unbreakable: bool,
/// The horizontal offset of this rowspan in all regions.
///
/// This is the offset from the text direction start, meaning that, on RTL
/// grids, this is the offset from the right of the grid, whereas, on LTR
/// grids, it is the offset from the left.
pub dx: Abs,
/// The vertical offset of this rowspan in the first region.
pub dy: Abs,
/// The index of the first region this rowspan appears in.
pub first_region: usize,
/// The full height in the first region this rowspan appears in, for
/// relative sizing.
pub region_full: Abs,
/// The vertical space available for this rowspan in each region.
pub heights: Vec<Abs>,
/// The index of the largest resolved spanned row so far.
/// Once a spanned row is resolved and its height added to `heights`, this
/// number is increased. Older rows, even if repeated through e.g. a
/// header, will no longer contribute height to this rowspan.
///
/// This is `None` if no spanned rows were resolved in `finish_region` yet.
pub max_resolved_row: Option<usize>,
/// See [`RowState::is_being_repeated`](super::layouter::RowState::is_being_repeated).
pub is_being_repeated: bool,
}
/// The output of the simulation of an unbreakable row group.
#[derive(Default)]
pub struct UnbreakableRowGroup {
/// The rows in this group of unbreakable rows.
/// Includes their indices and their predicted heights.
pub rows: Vec<(usize, Abs)>,
/// The total height of this row group.
pub height: Abs,
}
/// Data used to measure a cell in an auto row.
pub struct CellMeasurementData<'layouter> {
/// The available width for the cell across all regions.
pub width: Abs,
/// The available height for the cell in its first region.
/// Infinite when the auto row is unbreakable.
pub height: Abs,
/// The backlog of heights available for the cell in later regions.
///
/// When this is `None`, the `custom_backlog` field should be used instead.
/// That's because, otherwise, this field would have to contain a reference
/// to the `custom_backlog` field, which isn't possible in Rust without
/// resorting to unsafe hacks.
pub backlog: Option<&'layouter [Abs]>,
/// If the backlog needs to be built from scratch instead of reusing the
/// one at the current region, which is the case of a multi-region rowspan
/// (needs to join its backlog of already laid out heights with the current
/// backlog), then this vector will store the new backlog.
pub custom_backlog: Vec<Abs>,
/// The full height of the first region of the cell.
/// Infinite when the auto row is unbreakable.
pub full: Abs,
/// The height of the last repeated region to use in the measurement pod,
/// if any.
pub last: Option<Abs>,
/// The total height of previous rows spanned by the cell in the current
/// region (so far).
pub height_in_this_region: Abs,
/// The amount of previous regions spanned by the cell.
/// They are skipped for measurement purposes.
pub frames_in_previous_regions: usize,
}
impl GridLayouter<'_> {
/// Layout a rowspan over the already finished regions, plus the current
/// region's frame and height of resolved header rows, if it wasn't
/// finished yet (because we're being called from `finish_region`, but note
/// that this function is also called once after all regions are finished,
/// in which case `current_region_data` is `None`).
///
/// We need to do this only once we already know the heights of all
/// spanned rows, which is only possible after laying out the last row
/// spanned by the rowspan (or some row immediately after the last one).
pub fn layout_rowspan(
&mut self,
rowspan_data: Rowspan,
current_region_data: Option<(&mut Frame, Abs)>,
engine: &mut Engine,
) -> SourceResult<()> {
let Rowspan {
x,
y,
disambiguator,
rowspan,
is_effectively_unbreakable,
dx,
dy,
first_region,
region_full,
heights,
is_being_repeated,
..
} = rowspan_data;
let [first_height, backlog @ ..] = heights.as_slice() else {
// Nothing to layout.
return Ok(());
};
let cell = self.grid.cell(x, y).unwrap();
let width = self.cell_spanned_width(cell, x);
// In RTL cells expand to the left, thus the position
// must additionally be offset by the cell's width.
let dx = if self.is_rtl { self.width - (dx + width) } else { dx };
// Prepare regions.
let size = Size::new(width, *first_height);
let mut pod: Regions = Region::new(size, Axes::splat(true)).into();
pod.backlog = backlog;
if !is_effectively_unbreakable
&& self.grid.rows[y..][..rowspan]
.iter()
.any(|spanned_row| spanned_row == &Sizing::Auto)
{
// If the rowspan spans an auto row and is breakable, it will see
// '100%' as the full page height, at least at its first region.
// This is consistent with how it is measured, and with how
// non-rowspan cells behave in auto rows.
pod.full = region_full;
}
// Push the layouted frames directly into the finished frames.
let locator = self.cell_locator(Axes::new(x, y), disambiguator);
let fragment =
layout_cell(cell, engine, locator, self.styles, pod, is_being_repeated)?;
let (current_region, current_header_row_height) = current_region_data.unzip();
// Clever trick to process finished header rows:
// - If there are grid headers, the vector will be filled with one
// finished header row height per region, so, chaining with the height
// for the current one, we get the header row height for each region.
//
// - But if there are no grid headers, the vector will be empty, so in
// theory the regions and resolved header row heights wouldn't match.
// But that's fine - 'current_header_row_height' can only be either
// 'Some(zero)' or 'None' in such a case, and for all other rows we
// append infinite zeros. That is, in such a case, the resolved header
// row height is always zero, so that's our fallback.
let finished_header_rows = self
.finished_header_rows
.iter()
.map(|info| info.repeated_height)
.chain(current_header_row_height)
.chain(std::iter::repeat(Abs::zero()));
for ((i, (finished, header_dy)), frame) in self
.finished
.iter_mut()
.chain(current_region.into_iter())
.zip(finished_header_rows)
.skip(first_region)
.enumerate()
.zip(fragment)
{
let dy = if i == 0 {
// At first, we draw the rowspan starting at its expected
// vertical offset in the first region.
dy
} else {
// The rowspan continuation starts after the header (thus,
// at a position after the sum of the laid out header
// rows). Without a header, this is zero, so the rowspan can
// start at the very top of the region as usual.
header_dy
};
finished.push_frame(Point::new(dx, dy), frame);
}
Ok(())
}
/// Checks if a row contains the beginning of one or more rowspan cells.
/// If so, adds them to the rowspans vector.
pub fn check_for_rowspans(&mut self, disambiguator: usize, y: usize) {
let offsets = points(self.rcols.iter().copied());
for (x, dx) in (0..self.rcols.len()).zip(offsets) {
let Some(cell) = self.grid.cell(x, y) else {
continue;
};
let rowspan = self.grid.effective_rowspan_of_cell(cell);
if rowspan > 1 {
// Rowspan detected. We will lay it out later.
self.rowspans.push(Rowspan {
x,
y,
disambiguator,
rowspan,
// The field below will be updated in
// 'check_for_unbreakable_rows'.
is_effectively_unbreakable: !cell.breakable,
dx,
// The four fields below will be updated in 'finish_region'.
dy: Abs::zero(),
first_region: usize::MAX,
region_full: Abs::zero(),
heights: vec![],
max_resolved_row: None,
is_being_repeated: self.row_state.is_being_repeated,
});
}
}
}
/// Checks if the upcoming rows will be grouped together under an
/// unbreakable row group, and, if so, advances regions until there is
/// enough space for them. This can be needed, for example, if there's an
/// unbreakable rowspan crossing those rows.
pub fn check_for_unbreakable_rows(
&mut self,
current_row: usize,
engine: &mut Engine,
) -> SourceResult<()> {
if self.unbreakable_rows_left == 0 {
// By default, the amount of unbreakable rows starting at the
// current row is dynamic and depends on the amount of upcoming
// unbreakable cells (with or without a rowspan setting).
let mut amount_unbreakable_rows = None;
if let Some(footer) = &self.grid.footer
&& !footer.repeated
&& current_row >= footer.start
{
// Non-repeated footer, so keep it unbreakable.
//
// TODO(subfooters): This will become unnecessary
// once non-repeated footers are treated differently and
// have widow prevention.
amount_unbreakable_rows = Some(self.grid.rows.len() - footer.start);
}
let row_group = self.simulate_unbreakable_row_group(
current_row,
amount_unbreakable_rows,
&self.regions,
engine,
0,
)?;
// Skip to fitting region.
while !self.regions.size.y.fits(row_group.height)
&& self.may_progress_with_repeats()
{
self.finish_region(engine, false)?;
}
// Update unbreakable rows left.
self.unbreakable_rows_left = row_group.rows.len();
}
if self.unbreakable_rows_left > 1 {
// Mark rowspans as effectively unbreakable where applicable
// (if all of their spanned rows would be in the same unbreakable
// row group).
// Not needed if only one unbreakable row is left, since, then,
// no rowspan will be effectively unbreakable, at least necessarily.
// Note that this function is called after 'check_for_rowspans' and
// potentially updates the amount of remaining unbreakable rows, so
// it wouldn't be accurate to only check for this condition in that
// function. We need to check here instead.
for rowspan_data in
self.rowspans.iter_mut().filter(|rowspan| rowspan.y == current_row)
{
rowspan_data.is_effectively_unbreakable |=
self.unbreakable_rows_left >= rowspan_data.rowspan;
}
}
Ok(())
}
/// Simulates a group of unbreakable rows, starting with the index of the
/// first row in the group. If `amount_unbreakable_rows` is `None`, keeps
/// adding rows to the group until none have unbreakable cells in common.
/// Otherwise, adds specifically the given amount of rows to the group.
///
/// This is used to figure out how much height the next unbreakable row
/// group (if any) needs.
pub fn simulate_unbreakable_row_group(
&self,
first_row: usize,
amount_unbreakable_rows: Option<usize>,
regions: &Regions<'_>,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<UnbreakableRowGroup> {
let mut row_group = UnbreakableRowGroup::default();
let mut unbreakable_rows_left = amount_unbreakable_rows.unwrap_or(0);
for (y, row) in self.grid.rows.iter().enumerate().skip(first_row) {
if amount_unbreakable_rows.is_none() {
// When we don't set a fixed amount of unbreakable rows,
// determine the amount based on the rowspan of unbreakable
// cells in rows.
let additional_unbreakable_rows = self.check_for_unbreakable_cells(y);
unbreakable_rows_left =
unbreakable_rows_left.max(additional_unbreakable_rows);
}
if unbreakable_rows_left == 0 {
// This check is in case the first row does not have any
// unbreakable cells. Therefore, no unbreakable row group
// is formed.
break;
}
let height = match row {
Sizing::Rel(v) => v.resolve(self.styles).relative_to(regions.base().y),
// No need to pass the regions to the auto row, since
// unbreakable auto rows are always measured with infinite
// height, ignore backlog, and do not invoke the rowspan
// simulation procedure at all.
Sizing::Auto => self
.measure_auto_row(
engine,
disambiguator,
y,
false,
unbreakable_rows_left,
Some(&row_group),
)?
.unwrap()
.first()
.copied()
.unwrap_or_else(Abs::zero),
// Fractional rows don't matter when calculating the space
// needed for unbreakable rows
Sizing::Fr(_) => Abs::zero(),
};
row_group.height += height;
row_group.rows.push((y, height));
unbreakable_rows_left -= 1;
if unbreakable_rows_left == 0 {
// This second check is necessary so we can tell distinct
// but consecutive unbreakable row groups apart. If the
// unbreakable row group ended at this row, we stop before
// checking the next one.
break;
}
}
Ok(row_group)
}
/// Checks if one or more of the cells at the given row are unbreakable.
/// If so, returns the largest rowspan among the unbreakable cells;
/// the spanned rows must, as a result, be laid out in the same region.
pub fn check_for_unbreakable_cells(&self, y: usize) -> usize {
(0..self.grid.cols.len())
.filter_map(|x| self.grid.cell(x, y))
.filter(|cell| !cell.breakable)
.map(|cell| self.grid.effective_rowspan_of_cell(cell))
.max()
.unwrap_or(0)
}
/// Used by `measure_auto_row` to gather data needed to measure the cell.
pub fn prepare_auto_row_cell_measurement(
&self,
parent: Axes<usize>,
cell: &Cell,
breakable: bool,
row_group_data: Option<&UnbreakableRowGroup>,
) -> CellMeasurementData<'_> {
let rowspan = self.grid.effective_rowspan_of_cell(cell);
// This variable is used to construct a custom backlog if the cell
// is a rowspan, or if headers or footers are used. When measuring, we
// join the heights from previous regions to the current backlog to
// form a rowspan's expected backlog. We also subtract the header's
// and footer's heights from all regions.
let mut custom_backlog: Vec<Abs> = vec![];
// This function is used to subtract the expected header and footer
// height from each upcoming region size in the current backlog and
// last region.
let mut subtract_header_footer_height_from_regions = || {
// Only breakable auto rows need to update their backlogs based
// on the presence of a header or footer, given that unbreakable
// auto rows don't depend on the backlog, as they only span one
// region.
if breakable
&& (!self.repeating_headers.is_empty()
|| !self.pending_headers.is_empty()
|| matches!(&self.grid.footer, Some(footer) if footer.repeated))
{
// Subtract header and footer height from all upcoming regions
// when measuring the cell, including the last repeated region.
//
// This will update the 'custom_backlog' vector with the
// updated heights of the upcoming regions.
//
// We predict that header height will only include that of
// repeating headers, as we can assume non-repeating headers in
// the first region have been successfully placed, unless
// something didn't fit on the first region of the auto row,
// but we will only find that out after measurement, and if
// that happens, we discard the measurement and try again.
let mapped_regions = self.regions.map(&mut custom_backlog, |size| {
Size::new(
size.x,
size.y
- self.current.repeating_header_height
- self.current.footer_height,
)
});
// Callees must use the custom backlog instead of the current
// backlog, so we return 'None'.
return (None, mapped_regions.last);
}
// No need to change the backlog or last region.
(Some(self.regions.backlog), self.regions.last)
};
// Each declaration, from top to bottom:
// 1. The height available to the cell in the first region.
// Usually, this will just be the size remaining in the current
// region.
// 2. The backlog of upcoming region heights to specify as
// available to the cell.
// 3. The full height of the first region of the cell.
// 4. Height of the last repeated region to use in the measurement pod.
// 5. The total height of the cell covered by previously spanned
// rows in this region. This is used by rowspans to be able to tell
// how much the auto row needs to expand.
// 6. The amount of frames laid out by this cell in previous
// regions. When the cell isn't a rowspan, this is always zero.
// These frames are skipped after measuring.
let height;
let backlog;
let full;
let last;
let height_in_this_region;
let frames_in_previous_regions;
if rowspan == 1 {
// Not a rowspan, so the cell only occupies this row. Therefore:
// 1. When we measure the cell below, use the available height
// remaining in the region as the height it has available.
// However, if the auto row is unbreakable, measure with infinite
// height instead to see how much content expands.
// 2. Use the region's backlog and last region when measuring,
// however subtract the expected header and footer heights from
// each upcoming size, if there is a header or footer.
// 3. Use the same full region height.
// 4. No height occupied by this cell in this region so far.
// 5. Yes, this cell started in this region.
height = if breakable { self.regions.size.y } else { Abs::inf() };
(backlog, last) = subtract_header_footer_height_from_regions();
full = if breakable { self.regions.full } else { Abs::inf() };
height_in_this_region = Abs::zero();
frames_in_previous_regions = 0;
} else {
// Height of the rowspan covered by spanned rows in the current
// region.
let laid_out_height: Abs = self
.current
.lrows
.iter()
.filter_map(|row| match row {
Row::Frame(frame, y, _)
if (parent.y..parent.y + rowspan).contains(y) =>
{
Some(frame.height())
}
// Either we have a row outside of the rowspan, or a
// fractional row, whose size we can't really guess.
_ => None,
})
.sum();
// If we're currently simulating an unbreakable row group, also
// consider the height of previously spanned rows which are in
// the row group but not yet laid out.
let unbreakable_height: Abs = row_group_data
.into_iter()
.flat_map(|row_group| &row_group.rows)
.filter(|(y, _)| (parent.y..parent.y + rowspan).contains(y))
.map(|(_, height)| height)
.sum();
height_in_this_region = laid_out_height + unbreakable_height;
// Ensure we will measure the rowspan with the correct heights.
// For that, we will gather the total height spanned by this
// rowspan in previous regions.
if let Some((rowspan_full, [rowspan_height, rowspan_other_heights @ ..])) =
self.rowspans
.iter()
.find(|data| data.x == parent.x && data.y == parent.y)
.map(|data| (data.region_full, &*data.heights))
{
// The rowspan started in a previous region (as it already
// has at least one region height).
// Therefore, its initial height will be the height in its
// first spanned region, and the backlog will be the
// remaining heights, plus the current region's size, plus
// the current backlog.
frames_in_previous_regions = rowspan_other_heights.len() + 1;
let heights_up_to_current_region = rowspan_other_heights
.iter()
.copied()
.chain(std::iter::once(if breakable {
// Here we are calculating the available height for a
// rowspan from the top of the current region, so
// we have to use initial header heights (note that
// header height can change in the middle of the
// region).
self.current.initial_after_repeats
} else {
// When measuring unbreakable auto rows, infinite
// height is available for content to expand.
Abs::inf()
}));
custom_backlog = if breakable {
// This auto row is breakable. Therefore, join the
// rowspan's already laid out heights with the current
// region's height and current backlog to ensure a good
// level of accuracy in the measurements.
//
// Assume only repeating headers will survive starting at
// the next region.
let backlog = self.regions.backlog.iter().map(|&size| {
size - self.current.repeating_header_height
- self.current.footer_height
});
heights_up_to_current_region.chain(backlog).collect::<Vec<_>>()
} else {
// No extra backlog if this is an unbreakable auto row.
// Ensure, when measuring, that the rowspan can be laid
// out through all spanned rows which were already laid
// out so far, but don't go further than this region.
heights_up_to_current_region.collect::<Vec<_>>()
};
height = *rowspan_height;
backlog = None;
full = rowspan_full;
last = self.regions.last.map(|size| {
size - self.current.repeating_header_height
- self.current.footer_height
});
} else {
// The rowspan started in the current region, as its vector
// of heights in regions is currently empty.
// Therefore, the initial height it has available will be
// the current available size, plus the size spanned in
// previous rows in this region (and/or unbreakable row
// group, if it's being simulated).
// The backlog and full will be that of the current region.
// However, use infinite height instead if we're measuring an
// unbreakable auto row.
height = if breakable {
height_in_this_region + self.regions.size.y
} else {
Abs::inf()
};
(backlog, last) = subtract_header_footer_height_from_regions();
full = if breakable { self.regions.full } else { Abs::inf() };
frames_in_previous_regions = 0;
}
}
let width = self.cell_spanned_width(cell, parent.x);
CellMeasurementData {
width,
height,
backlog,
custom_backlog,
full,
last,
height_in_this_region,
frames_in_previous_regions,
}
}
/// Used in `measure_auto_row` to prepare a rowspan's `sizes` vector.
/// Returns `true` if we'll need to run a simulation to more accurately
/// expand the auto row based on the rowspan's demanded size, or `false`
/// otherwise.
#[allow(clippy::too_many_arguments)]
pub fn prepare_rowspan_sizes(
&self,
auto_row_y: usize,
sizes: &mut Vec<Abs>,
cell: &Cell,
parent_y: usize,
rowspan: usize,
unbreakable_rows_left: usize,
measurement_data: &CellMeasurementData<'_>,
) -> bool {
if sizes.len() <= 1
&& sizes.first().is_none_or(|&first_frame_size| {
first_frame_size <= measurement_data.height_in_this_region
})
{
// Ignore a rowspan fully covered by rows in previous
// regions and/or in the current region.
sizes.clear();
return false;
}
if let Some(first_frame_size) = sizes.first_mut() {
// Subtract already covered height from the size requested
// by this rowspan to the auto row in the first region.
*first_frame_size = (*first_frame_size
- measurement_data.height_in_this_region)
.max(Abs::zero());
}
let last_spanned_row = parent_y + rowspan - 1;
// When the rowspan is unbreakable, or all of its upcoming
// spanned rows are in the same unbreakable row group, its
// spanned gutter will certainly be in the same region as all
// of its other spanned rows, thus gutters won't be removed,
// and we can safely reduce how much the auto row expands by
// without using simulation.
let is_effectively_unbreakable_rowspan =
!cell.breakable || auto_row_y + unbreakable_rows_left > last_spanned_row;
// If the rowspan doesn't end at this row and the grid has
// gutter, we will need to run a simulation to find out how
// much to expand this row by later. This is because gutters
// spanned by this rowspan might be removed if they appear
// around a pagebreak, so the auto row might have to expand a
// bit more to compensate for the missing gutter height.
// However, unbreakable rowspans aren't affected by that
// problem.
if auto_row_y != last_spanned_row
&& !sizes.is_empty()
&& self.grid.has_gutter
&& !is_effectively_unbreakable_rowspan
{
return true;
}
// We can only predict the resolved size of upcoming fixed-size
// rows, but not fractional rows. In the future, we might be
// able to simulate and circumvent the problem with fractional
// rows. Relative rows are currently always measured relative
// to the first region as well.
// We can ignore auto rows since this is the last spanned auto
// row.
let will_be_covered_height: Abs = self
.grid
.rows
.iter()
.skip(auto_row_y + 1)
.take(last_spanned_row - auto_row_y)
.map(|row| match row {
Sizing::Rel(v) => {
v.resolve(self.styles).relative_to(self.regions.base().y)
}
_ => Abs::zero(),
})
.sum();
// Remove or reduce the sizes of the rowspan at the current or future
// regions where it will already be covered by further rows spanned by
// it.
subtract_end_sizes(sizes, will_be_covered_height);
// No need to run a simulation for this rowspan.
false
}
/// Performs a simulation to predict by how much height the last spanned
/// auto row will have to expand, given the current sizes of the auto row
/// in each region and the pending rowspans' data (parent Y, rowspan amount
/// and vector of requested sizes).
#[allow(clippy::too_many_arguments)]
pub fn simulate_and_measure_rowspans_in_auto_row(
&self,
y: usize,
resolved: &mut Vec<Abs>,
pending_rowspans: &[(usize, usize, Vec<Abs>)],
unbreakable_rows_left: usize,
row_group_data: Option<&UnbreakableRowGroup>,
mut disambiguator: usize,
engine: &mut Engine,
) -> SourceResult<()> {
// To begin our simulation, we have to unify the sizes demanded by
// each rowspan into one simple vector of sizes, as if they were
// all a single rowspan. These sizes will be appended to
// 'resolved' once we finish our simulation.
let mut simulated_sizes: Vec<Abs> = vec![];
let last_resolved_size = resolved.last().copied();
let mut max_spanned_row = y;
for (parent_y, rowspan, sizes) in pending_rowspans {
let mut sizes = sizes.iter();
for (target, size) in resolved.iter_mut().zip(&mut sizes) {
// First, we update the already resolved sizes as required
// by this rowspan. No need to simulate this since the auto row
// will already expand throughout already resolved regions.
// Our simulation, therefore, won't otherwise change already
// resolved sizes, other than, perhaps, the last one (at the
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/grid/mod.rs | crates/typst-layout/src/grid/mod.rs | mod layouter;
mod lines;
mod repeated;
mod rowspans;
pub use self::layouter::GridLayouter;
use typst_library::diag::SourceResult;
use typst_library::engine::Engine;
use typst_library::foundations::{Content, NativeElement, Packed, StyleChain};
use typst_library::introspection::{Location, Locator, SplitLocator, Tag, TagFlags};
use typst_library::layout::grid::resolve::Cell;
use typst_library::layout::{
Fragment, FrameItem, FrameParent, GridCell, GridElem, Inherit, Point, Regions,
};
use typst_library::model::{TableCell, TableElem};
use self::layouter::RowPiece;
use self::lines::{
LineSegment, generate_line_segments, hline_stroke_at_column, vline_stroke_at_row,
};
use self::rowspans::{Rowspan, UnbreakableRowGroup};
/// Layout the cell into the given regions.
///
/// The `disambiguator` indicates which instance of this cell this should be
/// layouted as. For normal cells, it is always `0`, but for headers and
/// footers, it indicates the index of the header/footer among all. See the
/// [`Locator`] docs for more details on the concepts behind this.
pub fn layout_cell(
cell: &Cell,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
regions: Regions,
is_repeated: bool,
) -> SourceResult<Fragment> {
// HACK: manually generate tags for table and grid cells. Ideally table and
// grid cells could just be marked as locatable, but the tags are somehow
// considered significant for layouting. This hack together with a check in
// the grid layouter makes the test suite pass.
let mut locator = locator.split();
let mut tags = None;
if let Some(table_cell) = cell.body.to_packed::<TableCell>() {
let mut table_cell = table_cell.clone();
table_cell.is_repeated.set(is_repeated);
tags = Some(generate_tags(table_cell, &mut locator, engine));
} else if let Some(grid_cell) = cell.body.to_packed::<GridCell>() {
let mut grid_cell = grid_cell.clone();
grid_cell.is_repeated.set(is_repeated);
tags = Some(generate_tags(grid_cell, &mut locator, engine));
}
let locator = locator.next(&cell.body.span());
let fragment = crate::layout_fragment(engine, &cell.body, locator, styles, regions)?;
// Manually insert tags.
let mut frames = fragment.into_frames();
if let Some((elem, loc, key)) = tags
&& let Some((first, remainder)) = frames.split_first_mut()
{
let flags = TagFlags { introspectable: true, tagged: true };
if remainder.is_empty() {
first.prepend(Point::zero(), FrameItem::Tag(Tag::Start(elem, flags)));
first.push(Point::zero(), FrameItem::Tag(Tag::End(loc, key, flags)));
} else {
// If there is more than one frame, set the logical parent of all
// frames to the cell, which converts them to group frames. Then
// prepend the start and end tags containing no content. The first
// frame is also a logical child to guarantee correct ordering
// in the introspector, since logical children are currently
// inserted immediately after the start tag of the parent element
// preceding any content within the parent element's tags.
for frame in frames.iter_mut() {
frame.set_parent(FrameParent::new(loc, Inherit::Yes));
}
frames.first_mut().unwrap().prepend_multiple([
(Point::zero(), FrameItem::Tag(Tag::Start(elem, flags))),
(Point::zero(), FrameItem::Tag(Tag::End(loc, key, flags))),
]);
}
}
Ok(Fragment::frames(frames))
}
fn generate_tags<T: NativeElement>(
mut cell: Packed<T>,
locator: &mut SplitLocator,
engine: &mut Engine,
) -> (Content, Location, u128) {
let key = typst_utils::hash128(&cell);
let loc = locator.next_location(engine, key, cell.span());
cell.set_location(loc);
(cell.pack(), loc, key)
}
/// Layout the grid.
#[typst_macros::time(span = elem.span())]
pub fn layout_grid(
elem: &Packed<GridElem>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
let grid = elem.grid.as_ref().unwrap();
GridLayouter::new(grid, regions, locator, styles, elem.span()).layout(engine)
}
/// Layout the table.
#[typst_macros::time(span = elem.span())]
pub fn layout_table(
elem: &Packed<TableElem>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
let grid = elem.grid.as_ref().unwrap();
GridLayouter::new(grid, regions, locator, styles, elem.span()).layout(engine)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/grid/layouter.rs | crates/typst-layout/src/grid/layouter.rs | use std::fmt::Debug;
use rustc_hash::FxHashMap;
use typst_library::diag::{SourceResult, bail};
use typst_library::engine::Engine;
use typst_library::foundations::{Resolve, StyleChain};
use typst_library::introspection::Locator;
use typst_library::layout::grid::resolve::{
Cell, CellGrid, Header, LinePosition, Repeatable,
};
use typst_library::layout::resolve::Entry;
use typst_library::layout::{
Abs, Axes, Dir, Fr, Fragment, Frame, FrameItem, Length, Point, Region, Regions, Rel,
Size, Sizing,
};
use typst_library::text::TextElem;
use typst_library::visualize::Geometry;
use typst_syntax::Span;
use typst_utils::Numeric;
use super::{
LineSegment, Rowspan, UnbreakableRowGroup, generate_line_segments,
hline_stroke_at_column, layout_cell, vline_stroke_at_row,
};
/// Performs grid layout.
pub struct GridLayouter<'a> {
/// The grid of cells.
pub(super) grid: &'a CellGrid,
/// The regions to layout children into.
pub(super) regions: Regions<'a>,
/// The locators for the each cell in the cell grid.
pub(super) cell_locators: FxHashMap<Axes<usize>, Locator<'a>>,
/// The inherited styles.
pub(super) styles: StyleChain<'a>,
/// Resolved column sizes.
pub(super) rcols: Vec<Abs>,
/// The sum of `rcols`.
pub(super) width: Abs,
/// Resolved row sizes, by region.
pub(super) rrows: Vec<Vec<RowPiece>>,
/// The amount of unbreakable rows remaining to be laid out in the
/// current unbreakable row group. While this is positive, no region breaks
/// should occur.
pub(super) unbreakable_rows_left: usize,
/// Rowspans not yet laid out because not all of their spanned rows were
/// laid out yet.
pub(super) rowspans: Vec<Rowspan>,
/// Grid layout state for the current region.
pub(super) current: Current,
/// Frames for finished regions.
pub(super) finished: Vec<Frame>,
/// The amount and height of header rows on each finished region.
pub(super) finished_header_rows: Vec<FinishedHeaderRowInfo>,
/// Whether this is an RTL grid.
pub(super) is_rtl: bool,
/// Currently repeating headers, one per level. Sorted by increasing
/// levels.
///
/// Note that some levels may be absent, in particular level 0, which does
/// not exist (so all levels are >= 1).
pub(super) repeating_headers: Vec<&'a Header>,
/// Headers, repeating or not, awaiting their first successful layout.
/// Sorted by increasing levels.
pub(super) pending_headers: &'a [Repeatable<Header>],
/// Next headers to be processed.
pub(super) upcoming_headers: &'a [Repeatable<Header>],
/// State of the row being currently laid out.
///
/// This is kept as a field to avoid passing down too many parameters from
/// `layout_row` into called functions, which would then have to pass them
/// down to `push_row`, which reads these values.
pub(super) row_state: RowState,
/// The span of the grid element.
pub(super) span: Span,
}
/// Grid layout state for the current region. This should be reset or updated
/// on each region break.
pub(super) struct Current {
/// The initial size of the current region before we started subtracting.
pub(super) initial: Size,
/// The height of the region after repeated headers were placed and footers
/// prepared. This also includes pending repeating headers from the start,
/// even if they were not repeated yet, since they will be repeated in the
/// next region anyway (bar orphan prevention).
///
/// This is used to quickly tell if any additional space in the region has
/// been occupied since then, meaning that additional space will become
/// available after a region break (see
/// [`GridLayouter::may_progress_with_repeats`]).
pub(super) initial_after_repeats: Abs,
/// Whether `layouter.regions.may_progress()` was `true` at the top of the
/// region.
pub(super) could_progress_at_top: bool,
/// Rows in the current region.
pub(super) lrows: Vec<Row>,
/// The amount of repeated header rows at the start of the current region.
/// Thus, excludes rows from pending headers (which were placed for the
/// first time).
///
/// Note that `repeating_headers` and `pending_headers` can change if we
/// find a new header inside the region (not at the top), so this field
/// is required to access information from the top of the region.
///
/// This information is used on finish region to calculate the total height
/// of resolved header rows at the top of the region, which is used by
/// multi-page rowspans so they can properly skip the header rows at the
/// top of each region during layout.
pub(super) repeated_header_rows: usize,
/// The end bound of the row range of the last repeating header at the
/// start of the region.
///
/// The last row might have disappeared from layout due to being empty, so
/// this is how we can become aware of where the last header ends without
/// having to check the vector of rows. Line layout uses this to determine
/// when to prioritize the last lines under a header.
///
/// A value of zero indicates no repeated headers were placed.
pub(super) last_repeated_header_end: usize,
/// Stores the length of `lrows` before a sequence of rows equipped with
/// orphan prevention was laid out. In this case, if no more rows without
/// orphan prevention are laid out after those rows before the region ends,
/// the rows will be removed, and there may be an attempt to place them
/// again in the new region. Effectively, this is the mechanism used for
/// orphan prevention of rows.
///
/// At the moment, this is only used by repeated headers (they aren't laid
/// out if alone in the region) and by new headers, which are moved to the
/// `pending_headers` vector and so will automatically be placed again
/// until they fit and are not orphans in at least one region (or exactly
/// one, for non-repeated headers).
pub(super) lrows_orphan_snapshot: Option<usize>,
/// The height of effectively repeating headers, that is, ignoring
/// non-repeating pending headers, in the current region.
///
/// This is used by multi-page auto rows so they can inform cell layout on
/// how much space should be taken by headers if they break across regions.
/// In particular, non-repeating headers only occupy the initial region,
/// but disappear on new regions, so they can be ignored.
///
/// This field is reset on each new region and properly updated by
/// `layout_auto_row` and `layout_relative_row`, and should not be read
/// before all header rows are fully laid out. It is usually fine because
/// header rows themselves are unbreakable, and unbreakable rows do not
/// need to read this field at all.
///
/// This height is not only computed at the beginning of the region. It is
/// updated whenever a new header is found, subtracting the height of
/// headers which stopped repeating and adding the height of all new
/// headers.
pub(super) repeating_header_height: Abs,
/// The height for each repeating header that was placed in this region.
/// Note that this includes headers not at the top of the region, before
/// their first repetition (pending headers), and excludes headers removed
/// by virtue of a new, conflicting header being found (short-lived
/// headers).
///
/// This is used to know how much to update `repeating_header_height` by
/// when finding a new header and causing existing repeating headers to
/// stop.
pub(super) repeating_header_heights: Vec<Abs>,
/// The simulated footer height for this region.
///
/// The simulation occurs before any rows are laid out for a region.
pub(super) footer_height: Abs,
}
/// Data about the row being laid out right now.
#[derive(Debug, Default)]
pub(super) struct RowState {
/// If this is `Some`, this will be updated by the currently laid out row's
/// height if it is auto or relative. This is used for header height
/// calculation.
pub(super) current_row_height: Option<Abs>,
/// This is `true` when laying out non-short lived headers and footers.
/// That is, headers and footers which are not immediately followed or
/// preceded (respectively) by conflicting headers and footers of same or
/// lower level, or the end or start of the table (respectively), which
/// would cause them to never repeat, even once.
///
/// If this is `false`, the next row to be laid out will remove an active
/// orphan snapshot and will flush pending headers, as there is no risk
/// that they will be orphans anymore.
pub(super) in_active_repeatable: bool,
/// This is `false` if a header row is laid out the first time, and `false`
/// for any other time. For footers it's the opposite, this will be `true`
/// the last time the footer is laid out, and `false` for all previous
/// occurrences.
pub(super) is_being_repeated: bool,
}
/// Data about laid out repeated header rows for a specific finished region.
#[derive(Debug, Default)]
pub(super) struct FinishedHeaderRowInfo {
/// The amount of repeated headers at the top of the region.
pub(super) repeated_amount: usize,
/// The end bound of the row range of the last repeated header at the top
/// of the region.
pub(super) last_repeated_header_end: usize,
/// The total height of repeated headers at the top of the region.
pub(super) repeated_height: Abs,
}
/// Details about a resulting row piece.
#[derive(Debug)]
pub struct RowPiece {
/// The height of the segment.
pub height: Abs,
/// The index of the row.
pub y: usize,
}
/// Produced by initial row layout, auto and relative rows are already finished,
/// fractional rows not yet.
pub(super) enum Row {
/// Finished row frame of auto or relative row with y index.
/// The last parameter indicates whether or not this is the last region
/// where this row is laid out, and it can only be false when a row uses
/// `layout_multi_row`, which in turn is only used by breakable auto rows.
Frame(Frame, usize, bool),
/// Fractional row with y index and disambiguator.
Fr(Fr, usize, usize),
}
impl Row {
/// Returns the `y` index of this row.
fn index(&self) -> usize {
match self {
Self::Frame(_, y, _) => *y,
Self::Fr(_, y, _) => *y,
}
}
}
impl<'a> GridLayouter<'a> {
/// Create a new grid layouter.
///
/// This prepares grid layout by unifying content and gutter tracks.
pub fn new(
grid: &'a CellGrid,
regions: Regions<'a>,
locator: Locator<'a>,
styles: StyleChain<'a>,
span: Span,
) -> Self {
// We use these regions for auto row measurement. Since at that moment,
// columns are already sized, we can enable horizontal expansion.
let mut regions = regions;
regions.expand = Axes::new(true, false);
// Prepare the locators for each cell in the cell grid.
let mut locator = locator.split();
let mut cell_locators = FxHashMap::default();
for y in 0..grid.rows.len() {
for x in 0..grid.cols.len() {
let Some(Entry::Cell(cell)) = grid.entry(x, y) else {
continue;
};
cell_locators.insert(Axes::new(x, y), locator.next(&cell.body.span()));
}
}
Self {
grid,
regions,
cell_locators,
styles,
rcols: vec![Abs::zero(); grid.cols.len()],
width: Abs::zero(),
rrows: vec![],
unbreakable_rows_left: 0,
rowspans: vec![],
finished: vec![],
finished_header_rows: vec![],
is_rtl: styles.resolve(TextElem::dir) == Dir::RTL,
repeating_headers: vec![],
upcoming_headers: &grid.headers,
pending_headers: Default::default(),
row_state: RowState::default(),
current: Current {
initial: regions.size,
initial_after_repeats: regions.size.y,
could_progress_at_top: regions.may_progress(),
lrows: vec![],
repeated_header_rows: 0,
last_repeated_header_end: 0,
lrows_orphan_snapshot: None,
repeating_header_height: Abs::zero(),
repeating_header_heights: vec![],
footer_height: Abs::zero(),
},
span,
}
}
/// Create a [`Locator`] for use in [`layout_cell`].
pub(super) fn cell_locator(
&self,
pos: Axes<usize>,
disambiguator: usize,
) -> Locator<'a> {
let mut cell_locator = self.cell_locators[&pos].relayout();
// The disambiguator is used for repeated cells, e.g. in repeated headers.
if disambiguator > 0 {
cell_locator = cell_locator.split().next_inner(disambiguator as u128);
}
cell_locator
}
/// Determines the columns sizes and then layouts the grid row-by-row.
pub fn layout(mut self, engine: &mut Engine) -> SourceResult<Fragment> {
self.measure_columns(engine)?;
if let Some(footer) = &self.grid.footer
&& footer.repeated
{
// Ensure rows in the first region will be aware of the
// possible presence of the footer.
self.prepare_footer(footer, engine, 0)?;
self.regions.size.y -= self.current.footer_height;
self.current.initial_after_repeats = self.regions.size.y;
}
let mut y = 0;
let mut consecutive_header_count = 0;
while y < self.grid.rows.len() {
if let Some(next_header) = self.upcoming_headers.get(consecutive_header_count)
&& next_header.range.contains(&y)
{
self.place_new_headers(&mut consecutive_header_count, engine)?;
y = next_header.range.end;
// Skip header rows during normal layout.
continue;
}
if let Some(footer) = &self.grid.footer
&& footer.repeated
&& y >= footer.start
{
if y == footer.start {
self.layout_footer(footer, engine, self.finished.len(), false)?;
self.flush_orphans();
}
y = footer.end;
continue;
}
self.layout_row(y, engine, 0)?;
// After the first non-header row is placed, pending headers are no
// longer orphans and can repeat, so we move them to repeating
// headers.
//
// Note that this is usually done in `push_row`, since the call to
// `layout_row` above might trigger region breaks (for multi-page
// auto rows), whereas this needs to be called as soon as any part
// of a row is laid out. However, it's possible a row has no
// visible output and thus does not push any rows even though it
// was successfully laid out, in which case we additionally flush
// here just in case.
self.flush_orphans();
y += 1;
}
self.finish_region(engine, true)?;
// Layout any missing rowspans.
// There are only two possibilities for rowspans not yet laid out
// (usually, a rowspan is laid out as soon as its last row, or any row
// after it, is laid out):
// 1. The rowspan was fully empty and only spanned fully empty auto
// rows, which were all prevented from being laid out. Those rowspans
// are ignored by 'layout_rowspan', and are not of any concern.
//
// 2. The rowspan's last row was an auto row at the last region which
// was not laid out, and no other rows were laid out after it. Those
// might still need to be laid out, so we check for them.
for rowspan in std::mem::take(&mut self.rowspans) {
self.layout_rowspan(rowspan, None, engine)?;
}
self.render_fills_strokes()
}
/// Layout a row with a certain initial state, returning the final state.
#[inline]
pub(super) fn layout_row_with_state(
&mut self,
y: usize,
engine: &mut Engine,
disambiguator: usize,
initial_state: RowState,
) -> SourceResult<RowState> {
// Keep a copy of the previous value in the stack, as this function can
// call itself recursively (e.g. if a region break is triggered and a
// header is placed), so we shouldn't outright overwrite it, but rather
// save and later restore the state when back to this call.
let previous = std::mem::replace(&mut self.row_state, initial_state);
// Keep it as a separate function to allow inlining the return below,
// as it's usually not needed.
self.layout_row_internal(y, engine, disambiguator)?;
Ok(std::mem::replace(&mut self.row_state, previous))
}
/// Layout the given row with the default row state.
#[inline]
pub(super) fn layout_row(
&mut self,
y: usize,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<()> {
self.layout_row_with_state(y, engine, disambiguator, RowState::default())?;
Ok(())
}
/// Layout the given row using the current state.
pub(super) fn layout_row_internal(
&mut self,
y: usize,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<()> {
// Skip to next region if current one is full, but only for content
// rows, not for gutter rows, and only if we aren't laying out an
// unbreakable group of rows.
let is_content_row = !self.grid.is_gutter_track(y);
if self.unbreakable_rows_left == 0 && self.regions.is_full() && is_content_row {
self.finish_region(engine, false)?;
}
if is_content_row {
// Gutter rows have no rowspans or possibly unbreakable cells.
self.check_for_rowspans(disambiguator, y);
self.check_for_unbreakable_rows(y, engine)?;
}
// Don't layout gutter rows at the top of a region.
if is_content_row || !self.current.lrows.is_empty() {
match self.grid.rows[y] {
Sizing::Auto => self.layout_auto_row(engine, disambiguator, y)?,
Sizing::Rel(v) => {
self.layout_relative_row(engine, disambiguator, v, y)?
}
Sizing::Fr(v) => {
if !self.row_state.in_active_repeatable {
self.flush_orphans();
}
self.current.lrows.push(Row::Fr(v, y, disambiguator))
}
}
}
self.unbreakable_rows_left = self.unbreakable_rows_left.saturating_sub(1);
Ok(())
}
/// Add lines and backgrounds.
fn render_fills_strokes(mut self) -> SourceResult<Fragment> {
let mut finished = std::mem::take(&mut self.finished);
let frame_amount = finished.len();
for (((frame_index, frame), rows), finished_header_rows) in
finished.iter_mut().enumerate().zip(&self.rrows).zip(
self.finished_header_rows
.iter()
.map(Some)
.chain(std::iter::repeat(None)),
)
{
if self.rcols.is_empty() || rows.is_empty() {
continue;
}
// Render grid lines.
// We collect lines into a vector before rendering so we can sort
// them based on thickness, such that the lines with largest
// thickness are drawn on top; and also so we can prepend all of
// them at once in the frame, as calling prepend() for each line,
// and thus pushing all frame items forward each time, would result
// in quadratic complexity.
let mut lines = vec![];
// Which line position to look for in the list of lines for a
// track, such that placing lines with those positions will
// correspond to placing them before the given track index.
//
// If the index represents a gutter track, this means the list of
// lines will actually correspond to the list of lines in the
// previous index, so we must look for lines positioned after the
// previous index, and not before, to determine which lines should
// be placed before gutter.
//
// Note that the maximum index is always an odd number when
// there's gutter, so we must check for it to ensure we don't give
// it the same treatment as a line before a gutter track.
let expected_line_position = |index, is_max_index: bool| {
if self.grid.is_gutter_track(index) && !is_max_index {
LinePosition::After
} else {
LinePosition::Before
}
};
// Render vertical lines.
// Render them first so horizontal lines have priority later.
for (x, dx) in points(self.rcols.iter().copied()).enumerate() {
let dx = if self.is_rtl { self.width - dx } else { dx };
let is_end_border = x == self.grid.cols.len();
let expected_vline_position = expected_line_position(x, is_end_border);
let vlines_at_column = self
.grid
.vlines
.get(if !self.grid.has_gutter {
x
} else if is_end_border {
// The end border has its own vector of lines, but
// dividing it by 2 and flooring would give us the
// vector of lines with the index of the last column.
// Add 1 so we get the border's lines.
x / 2 + 1
} else {
// If x is a gutter column, this will round down to the
// index of the previous content column, which is
// intentional - the only lines which can appear before
// a gutter column are lines for the previous column
// marked with "LinePosition::After". Therefore, we get
// the previous column's lines. Worry not, as
// 'generate_line_segments' will correctly filter lines
// based on their LinePosition for us.
//
// If x is a content column, this will correctly return
// its index before applying gutters, so nothing
// special here (lines with "LinePosition::After" would
// then be ignored for this column, as we are drawing
// lines before it, not after).
x / 2
})
.into_iter()
.flatten()
.filter(|line| line.position == expected_vline_position);
let tracks = rows.iter().map(|row| (row.y, row.height));
// Determine all different line segments we have to draw in
// this column, and convert them to points and shapes.
//
// Even a single, uniform line might generate more than one
// segment, if it happens to cross a colspan (over which it
// must not be drawn).
let segments = generate_line_segments(
self.grid,
tracks,
x,
vlines_at_column,
vline_stroke_at_row,
)
.map(|segment| {
let LineSegment { stroke, offset: dy, length, priority } = segment;
let stroke = (*stroke).clone().unwrap_or_default();
let thickness = stroke.thickness;
let half = thickness / 2.0;
let target = Point::with_y(length + thickness);
let vline = Geometry::Line(target).stroked(stroke);
(
thickness,
priority,
Point::new(dx, dy - half),
FrameItem::Shape(vline, self.span),
)
});
lines.extend(segments);
}
// Render horizontal lines.
// They are rendered second as they default to appearing on top.
// First, calculate their offsets from the top of the frame.
let hline_offsets = points(rows.iter().map(|piece| piece.height));
// Additionally, determine their indices (the indices of the
// rows they are drawn on top of). In principle, this will
// correspond to the rows' indices directly, except for the
// last hline index, which must be (amount of rows) in order to
// draw the table's bottom border.
let hline_indices = rows
.iter()
.map(|piece| piece.y)
.chain(std::iter::once(self.grid.rows.len()))
.enumerate();
// Converts a row to the corresponding index in the vector of
// hlines.
let hline_index_of_row = |y: usize| {
if !self.grid.has_gutter {
y
} else if y == self.grid.rows.len() {
y / 2 + 1
} else {
// Check the vlines loop for an explanation regarding
// these index operations.
y / 2
}
};
let get_hlines_at = |y| {
self.grid
.hlines
.get(hline_index_of_row(y))
.map(Vec::as_slice)
.unwrap_or(&[])
};
let mut prev_y = None;
for ((i, y), dy) in hline_indices.zip(hline_offsets) {
// Position of lines below the row index in the previous iteration.
let expected_prev_line_position = prev_y
.map(|prev_y| {
expected_line_position(
prev_y + 1,
prev_y + 1 == self.grid.rows.len(),
)
})
.unwrap_or(LinePosition::Before);
// Header's lines at the bottom have priority when repeated.
// This will store the end bound of the last header if the
// current iteration is calculating lines under it.
let last_repeated_header_end_above = match finished_header_rows {
Some(info) if prev_y.is_some() && i == info.repeated_amount => {
Some(info.last_repeated_header_end)
}
_ => None,
};
// If some grid rows were omitted between the previous resolved
// row and the current one, we ensure lines below the previous
// row don't "disappear" and are considered, albeit with less
// priority. However, don't do this when we're below a header,
// as it must have more priority instead of less, so it is
// chained later instead of before (stored in the
// 'header_hlines' variable below). The exception is when the
// last row in the header is removed, in which case we append
// both the lines under the row above us and also (later) the
// lines under the header's (removed) last row.
let prev_lines = match prev_y {
Some(prev_y)
if prev_y + 1 != y
&& last_repeated_header_end_above.is_none_or(
|last_repeated_header_end| {
prev_y + 1 != last_repeated_header_end
},
) =>
{
get_hlines_at(prev_y + 1)
}
_ => &[],
};
let expected_hline_position =
expected_line_position(y, y == self.grid.rows.len());
let hlines_at_y = get_hlines_at(y)
.iter()
.filter(|line| line.position == expected_hline_position);
let top_border_hlines = if prev_y.is_none() && y != 0 {
// For lines at the top of the region, give priority to
// the lines at the top border.
get_hlines_at(0)
} else {
&[]
};
let mut expected_header_line_position = LinePosition::Before;
let header_hlines = match (last_repeated_header_end_above, prev_y) {
(Some(header_end_above), Some(prev_y))
if !self.grid.has_gutter
|| matches!(
self.grid.rows[prev_y],
Sizing::Rel(length) if length.is_zero()
) =>
{
// For lines below a header, give priority to the
// lines originally below the header rather than
// the lines of what's below the repeated header.
// However, no need to do that when we're laying
// out the header for the first time, since the
// lines being normally laid out then will be
// precisely the lines below the header.
//
// Additionally, we don't repeat lines above the row
// below the header when gutter is enabled, since, in
// that case, there will be a gutter row between header
// and content, so no lines should overlap. The
// exception is when the gutter at the end of the
// header has a size of zero, which happens when only
// column-gutter is specified, for example. In that
// case, we still repeat the line under the gutter.
expected_header_line_position = expected_line_position(
header_end_above,
header_end_above == self.grid.rows.len(),
);
get_hlines_at(header_end_above)
}
_ => &[],
};
// The effective hlines to be considered at this row index are
// chained in order of increasing priority:
// 1. Lines from the row right above us, if needed;
// 2. Lines from the current row (usually, only those are
// present);
// 3. Lines from the top border (above the top cells, hence
// 'before' position only);
// 4. Lines from the header above us, if present.
let hlines_at_row =
prev_lines
.iter()
.filter(|line| line.position == expected_prev_line_position)
.chain(hlines_at_y)
.chain(
top_border_hlines
.iter()
.filter(|line| line.position == LinePosition::Before),
)
.chain(header_hlines.iter().filter(|line| {
line.position == expected_header_line_position
}));
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/grid/lines.rs | crates/typst-layout/src/grid/lines.rs | use std::sync::Arc;
use typst_library::foundations::{AlternativeFold, Fold};
use typst_library::layout::Abs;
use typst_library::layout::grid::resolve::{CellGrid, Line, Repeatable};
use typst_library::visualize::Stroke;
use super::RowPiece;
/// Indicates which priority a particular grid line segment should have, based
/// on the highest priority configuration that defined the segment's stroke.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum StrokePriority {
/// The stroke of the segment was derived solely from the grid's global
/// stroke setting, so it should have the lowest priority.
GridStroke = 0,
/// The segment's stroke was derived (even if partially) from a cell's
/// stroke override, so it should have priority over non-overridden cell
/// strokes and be drawn on top of them (when they have the same
/// thickness).
CellStroke = 1,
/// The segment's stroke was derived from a user's explicitly placed line
/// (hline or vline), and thus should have maximum priority, drawn on top
/// of any cell strokes (when they have the same thickness).
ExplicitLine = 2,
}
/// Data for a particular line segment in the grid as generated by
/// `generate_line_segments`.
#[derive(Debug, Eq, PartialEq)]
pub struct LineSegment {
/// The stroke with which to draw this segment.
pub stroke: Arc<Stroke<Abs>>,
/// The offset of this segment since the beginning of its axis.
/// For a vertical line segment, this is the offset since the top of the
/// table in the current page; for a horizontal line segment, this is the
/// offset since the start border of the table.
pub offset: Abs,
/// The length of this segment.
pub length: Abs,
/// The segment's drawing priority, indicating on top of which other
/// segments this one should be drawn.
pub priority: StrokePriority,
}
/// Generates the segments of lines that should be drawn alongside a certain
/// axis in the grid, going through the given tracks (orthogonal to the lines).
/// Each returned segment contains its stroke, its offset from the start, and
/// its length.
///
/// Accepts, as parameters, the index of the lines that should be produced
/// (for example, the column at which vertical lines will be drawn); a list of
/// user-specified lines with the same index (the `lines` parameter); whether
/// the given index corresponds to the maximum index for the line's axis; and a
/// function which returns the final stroke that should be used for each track
/// the line goes through, alongside the priority of the returned stroke (its
/// parameters are the grid, the index of the line to be drawn, the number of
/// the track to draw at and the stroke of the user hline/vline override at
/// this index to fold with, if any). Contiguous segments with the same stroke
/// and priority are joined together automatically.
///
/// The function should return `None` for positions at which the line would
/// otherwise cross a merged cell (for example, a vline could cross a colspan),
/// in which case a new segment should be drawn after the merged cell(s), even
/// if it would have the same stroke as the previous one.
///
/// Regarding priority, the function should return a priority of ExplicitLine
/// when the user-defined line's stroke at the current position isn't None
/// (note that it is passed by parameter to the function). When it is None, the
/// function should return a priority of CellStroke if the stroke returned was
/// given or affected by a per-cell override of the grid's global stroke.
/// When that isn't the case, the returned stroke was entirely provided by the
/// grid's global stroke, and thus a priority of GridStroke should be returned.
///
/// Note that we assume that the tracks are sorted according to ascending
/// number, and they must be iterable over pairs of (number, size). For
/// vertical lines, for instance, `tracks` would describe the rows in the
/// current region, as pairs (row index, row height).
pub fn generate_line_segments<'grid, F, I, L>(
grid: &'grid CellGrid,
tracks: I,
index: usize,
lines: L,
line_stroke_at_track: F,
) -> impl Iterator<Item = LineSegment> + 'grid
where
F: Fn(
&CellGrid,
usize,
usize,
Option<Option<Arc<Stroke<Abs>>>>,
) -> Option<(Arc<Stroke<Abs>>, StrokePriority)>
+ 'grid,
I: IntoIterator<Item = (usize, Abs)>,
I::IntoIter: 'grid,
L: IntoIterator<Item = &'grid Line>,
L::IntoIter: Clone + 'grid,
{
// The segment currently being drawn.
//
// It is extended for each consecutive track through which the line would
// be drawn with the same stroke and priority.
//
// Starts as None to force us to create a new segment as soon as we find
// the first track through which we should draw.
let mut current_segment: Option<LineSegment> = None;
// How far from the start (before the first track) have we gone so far.
// Used to determine the positions at which to draw each segment.
let mut offset = Abs::zero();
// How much to multiply line indices by to account for gutter.
let gutter_factor = if grid.has_gutter { 2 } else { 1 };
// Create an iterator of line segments, which will go through each track,
// from start to finish, to create line segments and extend them until they
// are interrupted and thus yielded through the iterator. We then repeat
// the process, picking up from the track after the one at which we had
// an interruption, until we have gone through all tracks.
//
// When going through each track, we check if the current segment would be
// interrupted, either because, at this track, we hit a merged cell over
// which we shouldn't draw, or because the line would have a different
// stroke or priority at this point (so we have to start a new segment). If
// so, the current segment is yielded and its variable is either set to
// 'None' (if no segment should be drawn at the point of interruption,
// meaning we might have to create a new segment later) or to the new
// segment (if we're starting to draw a segment with a different stroke or
// priority than before).
// Otherwise (if the current segment should span the current track), it is
// simply extended (or a new one is created, if it is 'None'), and no value
// is yielded for the current track, since the segment isn't yet complete
// (the next tracks might extend it further before it is interrupted and
// yielded). That is, we yield each segment only when it is interrupted,
// since then we will know its final length for sure.
//
// After the loop is done (and thus we went through all tracks), we
// interrupt the current segment one last time, to ensure the final segment
// is always interrupted and yielded, if it wasn't interrupted earlier.
let mut tracks = tracks.into_iter();
let lines = lines.into_iter();
std::iter::from_fn(move || {
// Each time this closure runs, we advance the track iterator as much
// as possible before returning because the current segment was
// interrupted. The for loop is resumed from where it stopped at the
// next call due to that, ensuring we go through all tracks and then
// stop.
for (track, size) in &mut tracks {
// Get the expected line stroke at this track by folding the
// strokes of each user-specified line (with priority to the
// user-specified line specified last).
let mut line_strokes = lines
.clone()
.filter(|line| {
line.end
.map(|end| {
// Subtract 1 from end index so we stop at the last
// cell before it (don't cross one extra gutter).
let end = if grid.has_gutter {
2 * end.get() - 1
} else {
end.get()
};
(gutter_factor * line.start..end).contains(&track)
})
.unwrap_or_else(|| track >= gutter_factor * line.start)
})
.map(|line| line.stroke.clone());
// Distinguish between unspecified stroke (None, if no lines
// were matched above) and specified stroke of None (Some(None),
// if some lines were matched and the one specified last had a
// stroke of None) by conditionally folding after 'next()'.
let line_stroke = line_strokes.next().map(|first_stroke| {
line_strokes.fold(first_stroke, |acc, line_stroke| line_stroke.fold(acc))
});
// The function shall determine if it is appropriate to draw
// the line at this position or not (i.e. whether or not it
// would cross a merged cell), and, if so, the final stroke it
// should have (because cells near this position could have
// stroke overrides, which have priority and should be folded
// with the stroke obtained above).
//
// If we are currently already drawing a segment and the function
// indicates we should, at this track, draw some other segment
// (with a different stroke or priority), or even no segment at
// all, we interrupt and yield the current segment (which was drawn
// up to the previous track) by returning it wrapped in 'Some()'
// (which indicates, in the context of 'std::iter::from_fn', that
// our iterator isn't over yet, and this should be its next value).
if let Some((stroke, priority)) =
line_stroke_at_track(grid, index, track, line_stroke)
{
// We should draw at this position. Let's check if we were
// already drawing in the previous position.
if let Some(current_segment) = &mut current_segment {
// We are currently building a segment. Let's check if
// we should extend it to this track as well.
if current_segment.stroke == stroke
&& current_segment.priority == priority
{
// Extend the current segment so it covers at least
// this track as well, since we should use the same
// stroke as in the previous one when a line goes
// through this track, with the same priority.
current_segment.length += size;
} else {
// We got a different stroke or priority now, so create
// a new segment with the new stroke and spanning the
// current track. Yield the old segment, as it was
// interrupted and is thus complete.
let new_segment =
LineSegment { stroke, offset, length: size, priority };
let old_segment = std::mem::replace(current_segment, new_segment);
offset += size;
return Some(old_segment);
}
} else {
// We should draw here, but there is no segment
// currently being drawn, either because the last
// position had a merged cell, had a stroke
// of 'None', or because this is the first track.
// Create a new segment to draw. We start spanning this
// track.
current_segment =
Some(LineSegment { stroke, offset, length: size, priority });
}
} else if let Some(old_segment) = Option::take(&mut current_segment) {
// We shouldn't draw here (stroke of None), so we yield the
// current segment, as it was interrupted.
offset += size;
return Some(old_segment);
}
// Either the current segment is None (meaning we didn't start
// drawing a segment yet since the last yielded one), so we keep
// searching for a track where we should draw one; or the current
// segment is Some but wasn't interrupted at this track, so we keep
// looping through the following tracks until it is interrupted,
// or we reach the end.
offset += size;
}
// Reached the end of all tracks, so we interrupt and finish
// the current segment. Note that, on future calls to this
// closure, the current segment will necessarily be 'None',
// so the iterator will necessarily end (that is, we will return None)
// after this.
//
// Note: Fully-qualified notation because rust-analyzer is confused.
Option::take(&mut current_segment)
})
}
/// Returns the correct stroke with which to draw a vline right before column
/// `x` when going through row `y`, given the stroke of the user-specified line
/// at this position, if any (note that a stroke of `None` is unspecified,
/// while `Some(None)` means specified to remove any stroke at this position).
/// Also returns the stroke's drawing priority, which depends on its source.
///
/// If the vline would go through a colspan, returns None (shouldn't be drawn).
/// If the one (when at the border) or two (otherwise) cells to the left and
/// right of the vline have right and left stroke overrides, respectively,
/// then the cells' stroke overrides are folded together with the vline's
/// stroke (with priority to the vline's stroke, followed by the right cell's
/// stroke, and, finally, the left cell's) and returned. If only one of the two
/// cells around the vline (if there are two) has an override, that cell's
/// stroke is given priority when folding. If, however, the cells around the
/// vline at this row do not have any stroke overrides, then the vline's own
/// stroke, as defined by user-specified lines (if any), is returned.
///
/// The priority associated with the returned stroke follows the rules
/// described in the docs for `generate_line_segment`.
pub fn vline_stroke_at_row(
grid: &CellGrid,
x: usize,
y: usize,
stroke: Option<Option<Arc<Stroke<Abs>>>>,
) -> Option<(Arc<Stroke<Abs>>, StrokePriority)> {
// When the vline isn't at the border, we need to check if a colspan would
// be present between columns 'x' and 'x-1' at row 'y', and thus overlap
// with the line.
// To do so, we analyze the cell right after this vline. If it is merged
// with a cell before this line (parent.x < x) which is at this row or
// above it (parent.y <= y, which is checked by
// 'effective_parent_cell_position'), this means it would overlap with the
// vline, so the vline must not be drawn at this row.
if x != 0 && x != grid.cols.len() {
// Use 'effective_parent_cell_position' to skip the gutters, if x or y
// represent gutter tracks.
// We would then analyze the cell one column after (if at a gutter
// column), and/or one row below (if at a gutter row), in order to
// check if it would be merged with a cell before the vline.
if let Some(parent) = grid.effective_parent_cell_position(x, y)
&& parent.x < x
{
// There is a colspan cell going through this vline's position,
// so don't draw it here.
return None;
}
}
let (left_cell_stroke, left_cell_prioritized) = x
.checked_sub(1)
.and_then(|left_x| {
// Let's find the parent cell of the position before us, in order
// to take its right stroke, even with gutter before us.
grid.effective_parent_cell_position(left_x, y)
})
.map(|parent| {
let left_cell = grid.cell(parent.x, parent.y).unwrap();
(left_cell.stroke.right.clone(), left_cell.stroke_overridden.right)
})
.unwrap_or((None, false));
let (right_cell_stroke, right_cell_prioritized) = if x < grid.cols.len() {
// Let's find the parent cell of the position after us, in order
// to take its left stroke, even with gutter after us.
grid.effective_parent_cell_position(x, y)
.map(|parent| {
let right_cell = grid.cell(parent.x, parent.y).unwrap();
(right_cell.stroke.left.clone(), right_cell.stroke_overridden.left)
})
.unwrap_or((None, false))
} else {
(None, false)
};
let priority = if stroke.is_some() {
StrokePriority::ExplicitLine
} else if left_cell_prioritized || right_cell_prioritized {
StrokePriority::CellStroke
} else {
StrokePriority::GridStroke
};
let (prioritized_cell_stroke, deprioritized_cell_stroke) =
if left_cell_prioritized && !right_cell_prioritized {
(left_cell_stroke, right_cell_stroke)
} else {
// When both cells' strokes have the same priority, we default to
// prioritizing the right cell's left stroke.
(right_cell_stroke, left_cell_stroke)
};
// When both cells specify a stroke for this line segment, fold
// both strokes, with priority to either the one prioritized cell,
// or to the right cell's left stroke in case of a tie. But when one of
// them doesn't specify a stroke, the other cell's stroke should be used
// instead, regardless of priority (hence the usage of 'fold_or').
let cell_stroke = prioritized_cell_stroke.fold_or(deprioritized_cell_stroke);
// Fold the line stroke and folded cell strokes, if possible.
// Give priority to the explicit line stroke.
// Otherwise, use whichever of the two isn't 'none' or unspecified.
let final_stroke = stroke.fold_or(Some(cell_stroke)).flatten();
final_stroke.zip(Some(priority))
}
/// Returns the correct stroke with which to draw a hline on top of row `y`
/// when going through column `x`, given the stroke of the user-specified line
/// at this position, if any (note that a stroke of `None` is unspecified,
/// while `Some(None)` means specified to remove any stroke at this position).
/// Also returns the stroke's drawing priority, which depends on its source.
///
/// The `local_top_y` parameter indicates which row is effectively on top of
/// this hline at the current region. This is `None` if the hline is above the
/// first row in the region, for instance. The `in_last_region` parameter
/// indicates whether this is the last region of the table. If not and this is
/// a line at the bottom border, the bottom border's line gains priority.
///
/// If the one (when at the border) or two (otherwise) cells above and below
/// the hline have bottom and top stroke overrides, respectively, then the
/// cells' stroke overrides are folded together with the hline's stroke (with
/// priority to hline's stroke, followed by the bottom cell's stroke, and,
/// finally, the top cell's) and returned. If only one of the two cells around
/// the vline (if there are two) has an override, that cell's stroke is given
/// priority when folding. If, however, the cells around the hline at this
/// column do not have any stroke overrides, then the hline's own stroke, as
/// defined by user-specified lines (if any), is directly returned.
///
/// The priority associated with the returned stroke follows the rules
/// described in the docs for `generate_line_segment`.
///
/// The rows argument is needed to know which rows are effectively present in
/// the current region, in order to avoid unnecessary hline splitting when a
/// rowspan's previous rows are either in a previous region or empty (and thus
/// wouldn't overlap with the hline, since its first row in the current region
/// is below the hline).
///
/// This function assumes columns are sorted by increasing `x`, and rows are
/// sorted by increasing `y`.
#[allow(clippy::too_many_arguments)]
pub fn hline_stroke_at_column(
grid: &CellGrid,
rows: &[RowPiece],
local_top_y: Option<usize>,
header_end_above: Option<usize>,
in_last_region: bool,
y: usize,
x: usize,
stroke: Option<Option<Arc<Stroke<Abs>>>>,
) -> Option<(Arc<Stroke<Abs>>, StrokePriority)> {
// When the hline isn't at the border, we need to check if a rowspan
// would be present between rows 'y' and 'y-1' at column 'x', and thus
// overlap with the line.
// To do so, we analyze the cell right below this hline. If it is
// merged with a cell above this line (parent.y < y) which is at this
// column or before it (parent.x <= x, which is checked by
// 'effective_parent_cell_position'), this means it would overlap with the
// hline, so the hline must not be drawn at this column.
if y != 0 && y != grid.rows.len() {
// Use 'effective_parent_cell_position' to skip the gutters, if x or y
// represent gutter tracks.
// We would then analyze the cell one column after (if at a gutter
// column), and/or one row below (if at a gutter row), in order to
// check if it would be merged with a cell before the hline.
if let Some(parent) = grid.effective_parent_cell_position(x, y)
&& parent.y < y
{
// Get the first 'y' spanned by the possible rowspan in this region.
// The 'parent.y' row and any other spanned rows above 'y' could be
// missing from this region, which could have lead the check above
// to be triggered, even though there is no spanned row above the
// hline in the final layout of this region, and thus no overlap
// with the hline, allowing it to be drawn regardless of the
// theoretical presence of a rowspan going across its position.
let local_parent_y = rows
.iter()
.find(|row| row.y >= parent.y)
.map(|row| row.y)
.unwrap_or(y);
if local_parent_y < y {
// There is a rowspan cell going through this hline's
// position, so don't draw it here.
return None;
}
}
}
// When the hline is at the top of the region and this isn't the first
// region, fold with the top stroke of the topmost cell at this column,
// that is, the top border.
let use_top_border_stroke = local_top_y.is_none() && y != 0;
let (top_cell_stroke, top_cell_prioritized) = local_top_y
.or(use_top_border_stroke.then_some(0))
.and_then(|top_y| {
// Let's find the parent cell of the position above us, in order
// to take its bottom stroke, even when we're below gutter.
grid.effective_parent_cell_position(x, top_y)
})
.map(|parent| {
let top_cell = grid.cell(parent.x, parent.y).unwrap();
if use_top_border_stroke {
(top_cell.stroke.top.clone(), top_cell.stroke_overridden.top)
} else {
(top_cell.stroke.bottom.clone(), top_cell.stroke_overridden.bottom)
}
})
.unwrap_or((None, false));
// Use the bottom border stroke with priority if we're not in the last
// region, we have the last index, and (as a failsafe) we don't have the
// last row of cells above us.
let use_bottom_border_stroke = !in_last_region
&& local_top_y.is_none_or(|top_y| top_y + 1 != grid.rows.len())
&& y == grid.rows.len();
let bottom_y =
if use_bottom_border_stroke { grid.rows.len().saturating_sub(1) } else { y };
let (bottom_cell_stroke, bottom_cell_prioritized) = if bottom_y < grid.rows.len() {
// Let's find the parent cell of the position below us, in order
// to take its top stroke, even when we're above gutter.
grid.effective_parent_cell_position(x, bottom_y)
.map(|parent| {
let bottom_cell = grid.cell(parent.x, parent.y).unwrap();
if use_bottom_border_stroke {
(
bottom_cell.stroke.bottom.clone(),
bottom_cell.stroke_overridden.bottom,
)
} else {
(bottom_cell.stroke.top.clone(), bottom_cell.stroke_overridden.top)
}
})
.unwrap_or((None, false))
} else {
// No cell below the bottom border.
(None, false)
};
let priority = if stroke.is_some() {
StrokePriority::ExplicitLine
} else if top_cell_prioritized || bottom_cell_prioritized {
StrokePriority::CellStroke
} else {
StrokePriority::GridStroke
};
// Top border stroke and header stroke are generally prioritized, unless
// they don't have explicit hline overrides and one or more user-provided
// hlines would appear at the same position, which then are prioritized.
let top_stroke_comes_from_header = header_end_above.zip(local_top_y).is_some_and(
|(last_repeated_header_end, local_top_y)| {
// Check if the last repeated header row is above this line.
//
// Note that `y == last_repeated_header_end` is impossible for a
// strictly repeated header (not in its original position).
local_top_y < last_repeated_header_end && y > last_repeated_header_end
},
);
// Prioritize the footer's top stroke as well where applicable.
let bottom_stroke_comes_from_footer = grid
.footer
.as_ref()
.and_then(Repeatable::as_repeated)
.is_some_and(|footer| {
// Ensure the row below us is a repeated footer.
// FIXME: Make this check more robust when footers at arbitrary
// positions are added.
local_top_y.unwrap_or(0) + 1 < footer.start && y >= footer.start
});
let (prioritized_cell_stroke, deprioritized_cell_stroke) =
if !use_bottom_border_stroke
&& !bottom_stroke_comes_from_footer
&& (use_top_border_stroke
|| top_stroke_comes_from_header
|| top_cell_prioritized && !bottom_cell_prioritized)
{
// Top border must always be prioritized, even if it did not
// request for that explicitly.
(top_cell_stroke, bottom_cell_stroke)
} else {
// When both cells' strokes have the same priority, we default to
// prioritizing the bottom cell's top stroke.
// Additionally, the bottom border cell's stroke always has
// priority. Same for stroke above footers.
(bottom_cell_stroke, top_cell_stroke)
};
// When both cells specify a stroke for this line segment, fold
// both strokes, with priority to either the one prioritized cell,
// or to the bottom cell's top stroke in case of a tie. But when one of
// them doesn't specify a stroke, the other cell's stroke should be used
// instead, regardless of priority (hence the usage of 'fold_or').
let cell_stroke = prioritized_cell_stroke.fold_or(deprioritized_cell_stroke);
// Fold the line stroke and folded cell strokes, if possible.
// Give priority to the explicit line stroke.
// Otherwise, use whichever of the two isn't 'none' or unspecified.
let final_stroke = stroke.fold_or(Some(cell_stroke)).flatten();
final_stroke.zip(Some(priority))
}
#[cfg(test)]
mod test {
use std::num::NonZeroUsize;
use typst_library::foundations::Content;
use typst_library::layout::grid::resolve::{Cell, Entry, LinePosition};
use typst_library::layout::{Axes, Sides, Sizing};
use typst_utils::NonZeroExt;
use super::*;
fn sample_cell() -> Cell {
Cell {
body: Content::default(),
fill: None,
colspan: NonZeroUsize::ONE,
rowspan: NonZeroUsize::ONE,
stroke: Sides::splat(Some(Arc::new(Stroke::default()))),
stroke_overridden: Sides::splat(false),
breakable: true,
}
}
fn cell_with_colspan_rowspan(colspan: usize, rowspan: usize) -> Cell {
Cell {
body: Content::default(),
fill: None,
colspan: NonZeroUsize::try_from(colspan).unwrap(),
rowspan: NonZeroUsize::try_from(rowspan).unwrap(),
stroke: Sides::splat(Some(Arc::new(Stroke::default()))),
stroke_overridden: Sides::splat(false),
breakable: true,
}
}
fn sample_grid_for_vlines(gutters: bool) -> CellGrid {
const COLS: usize = 4;
const ROWS: usize = 6;
let entries = vec![
// row 0
Entry::Cell(sample_cell()),
Entry::Cell(sample_cell()),
Entry::Cell(cell_with_colspan_rowspan(2, 1)),
Entry::Merged { parent: 2 },
// row 1
Entry::Cell(sample_cell()),
Entry::Cell(cell_with_colspan_rowspan(3, 1)),
Entry::Merged { parent: 5 },
Entry::Merged { parent: 5 },
// row 2
Entry::Merged { parent: 4 },
Entry::Cell(sample_cell()),
Entry::Cell(cell_with_colspan_rowspan(2, 1)),
Entry::Merged { parent: 10 },
// row 3
Entry::Cell(sample_cell()),
Entry::Cell(cell_with_colspan_rowspan(3, 2)),
Entry::Merged { parent: 13 },
Entry::Merged { parent: 13 },
// row 4
Entry::Cell(sample_cell()),
Entry::Merged { parent: 13 },
Entry::Merged { parent: 13 },
Entry::Merged { parent: 13 },
// row 5
Entry::Cell(sample_cell()),
Entry::Cell(sample_cell()),
Entry::Cell(cell_with_colspan_rowspan(2, 1)),
Entry::Merged { parent: 22 },
];
CellGrid::new_internal(
Axes::with_x(&[Sizing::Auto; COLS]),
if gutters {
Axes::new(&[Sizing::Auto; COLS - 1], &[Sizing::Auto; ROWS - 1])
} else {
Axes::default()
},
vec![],
vec![],
vec![],
None,
entries,
)
}
#[test]
fn test_vline_splitting_without_gutter() {
let stroke = Arc::new(Stroke::default());
let grid = sample_grid_for_vlines(false);
let rows = &[
RowPiece { height: Abs::pt(1.0), y: 0 },
RowPiece { height: Abs::pt(2.0), y: 1 },
RowPiece { height: Abs::pt(4.0), y: 2 },
RowPiece { height: Abs::pt(8.0), y: 3 },
RowPiece { height: Abs::pt(16.0), y: 4 },
RowPiece { height: Abs::pt(32.0), y: 5 },
];
let expected_vline_splits = &[
vec![LineSegment {
stroke: stroke.clone(),
offset: Abs::pt(0.),
length: Abs::pt(1. + 2. + 4. + 8. + 16. + 32.),
priority: StrokePriority::GridStroke,
}],
vec![LineSegment {
stroke: stroke.clone(),
offset: Abs::pt(0.),
length: Abs::pt(1. + 2. + 4. + 8. + 16. + 32.),
priority: StrokePriority::GridStroke,
}],
// interrupted a few times by colspans
vec![
LineSegment {
stroke: stroke.clone(),
offset: Abs::pt(0.),
length: Abs::pt(1.),
priority: StrokePriority::GridStroke,
},
LineSegment {
stroke: stroke.clone(),
offset: Abs::pt(1. + 2.),
length: Abs::pt(4.),
priority: StrokePriority::GridStroke,
},
LineSegment {
stroke: stroke.clone(),
offset: Abs::pt(1. + 2. + 4. + 8. + 16.),
length: Abs::pt(32.),
priority: StrokePriority::GridStroke,
},
],
// interrupted every time by colspans
vec![],
vec![LineSegment {
stroke,
offset: Abs::pt(0.),
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-layout/src/grid/repeated.rs | crates/typst-layout/src/grid/repeated.rs | use std::ops::Deref;
use typst_library::diag::SourceResult;
use typst_library::engine::Engine;
use typst_library::layout::grid::resolve::{Footer, Header, Repeatable};
use typst_library::layout::{Abs, Axes, Frame, Regions};
use super::layouter::{GridLayouter, RowState};
use super::rowspans::UnbreakableRowGroup;
impl<'a> GridLayouter<'a> {
/// Checks whether a region break could help a situation where we're out of
/// space for the next row. The criteria are:
///
/// 1. If we could progress at the top of the region, that indicates the
/// region has a backlog, or (if we're at the first region) a region break
/// is at all possible (`regions.last` is `Some()`), so that's sufficient.
///
/// 2. Otherwise, we may progress if another region break is possible
/// (`regions.last` is still `Some()`) and non-repeating rows have been
/// placed, since that means the space they occupy will be available in the
/// next region.
#[inline]
pub fn may_progress_with_repeats(&self) -> bool {
// TODO(subfooters): check below isn't enough to detect non-repeating
// footers... we can also change 'initial_after_repeats' to stop being
// calculated if there were any non-repeating footers.
self.current.could_progress_at_top
|| self.regions.last.is_some()
&& self.regions.size.y != self.current.initial_after_repeats
}
pub fn place_new_headers(
&mut self,
consecutive_header_count: &mut usize,
engine: &mut Engine,
) -> SourceResult<()> {
*consecutive_header_count += 1;
let (consecutive_headers, new_upcoming_headers) =
self.upcoming_headers.split_at(*consecutive_header_count);
if new_upcoming_headers.first().is_some_and(|next_header| {
consecutive_headers.last().is_none_or(|latest_header| {
!latest_header.short_lived
&& next_header.range.start == latest_header.range.end
}) && !next_header.short_lived
}) {
// More headers coming, so wait until we reach them.
return Ok(());
}
self.upcoming_headers = new_upcoming_headers;
*consecutive_header_count = 0;
let [first_header, ..] = consecutive_headers else {
self.flush_orphans();
return Ok(());
};
// Assuming non-conflicting headers sorted by increasing y, this must
// be the header with the lowest level (sorted by increasing levels).
let first_level = first_header.level;
// Stop repeating conflicting headers, even if the new headers are
// short-lived or won't repeat.
//
// If we go to a new region before the new headers fit alongside their
// children (or in general, for short-lived), the old headers should
// not be displayed anymore.
let first_conflicting_pos =
self.repeating_headers.partition_point(|h| h.level < first_level);
self.repeating_headers.truncate(first_conflicting_pos);
// Ensure upcoming rows won't see that these headers will occupy any
// space in future regions anymore.
for removed_height in
self.current.repeating_header_heights.drain(first_conflicting_pos..)
{
self.current.repeating_header_height -= removed_height;
}
// Layout short-lived headers immediately.
if consecutive_headers.last().is_some_and(|h| h.short_lived) {
// No chance of orphans as we're immediately placing conflicting
// headers afterwards, which basically are not headers, for all intents
// and purposes. It is therefore guaranteed that all new headers have
// been placed at least once.
self.flush_orphans();
// Layout each conflicting header independently, without orphan
// prevention (as they don't go into 'pending_headers').
// These headers are short-lived as they are immediately followed by a
// header of the same or lower level, such that they never actually get
// to repeat.
self.layout_new_headers(consecutive_headers, true, engine)?;
} else {
// Let's try to place pending headers at least once.
// This might be a waste as we could generate an orphan and thus have
// to try to place old and new headers all over again, but that happens
// for every new region anyway, so it's rather unavoidable.
let snapshot_created =
self.layout_new_headers(consecutive_headers, false, engine)?;
// Queue the new headers for layout. They will remain in this
// vector due to orphan prevention.
//
// After the first subsequent row is laid out, move to repeating, as
// it's then confirmed the headers won't be moved due to orphan
// prevention anymore.
self.pending_headers = consecutive_headers;
if !snapshot_created {
// Region probably couldn't progress.
//
// Mark new pending headers as final and ensure there isn't a
// snapshot.
self.flush_orphans();
}
}
Ok(())
}
/// Lays out rows belonging to a header, returning the calculated header
/// height only for that header. Indicates to the laid out rows that they
/// should inform their laid out heights if appropriate (auto or fixed
/// size rows only).
#[inline]
fn layout_header_rows(
&mut self,
header: &Header,
engine: &mut Engine,
disambiguator: usize,
as_short_lived: bool,
is_being_repeated: bool,
) -> SourceResult<Abs> {
let mut header_height = Abs::zero();
for y in header.range.clone() {
header_height += self
.layout_row_with_state(
y,
engine,
disambiguator,
RowState {
current_row_height: Some(Abs::zero()),
in_active_repeatable: !as_short_lived,
is_being_repeated,
},
)?
.current_row_height
.unwrap_or_default();
}
Ok(header_height)
}
/// This function should be called each time an additional row has been
/// laid out in a region to indicate that orphan prevention has succeeded.
///
/// It removes the current orphan snapshot and flushes pending headers,
/// such that a non-repeating header won't try to be laid out again
/// anymore, and a repeating header will begin to be part of
/// `repeating_headers`.
pub fn flush_orphans(&mut self) {
self.current.lrows_orphan_snapshot = None;
self.flush_pending_headers();
}
/// Indicates all currently pending headers have been successfully placed
/// once, since another row has been placed after them, so they are
/// certainly not orphans.
pub fn flush_pending_headers(&mut self) {
if self.pending_headers.is_empty() {
return;
}
for header in self.pending_headers {
if header.repeated {
// Vector remains sorted by increasing levels:
// - 'pending_headers' themselves are sorted, since we only
// push non-mutually-conflicting headers at a time.
// - Before pushing new pending headers in
// 'layout_new_pending_headers', we truncate repeating headers
// to remove anything with the same or higher levels as the
// first pending header.
// - Assuming it was sorted before, that truncation only keeps
// elements with a lower level.
// - Therefore, by pushing this header to the end, it will have
// a level larger than all the previous headers, and is thus
// in its 'correct' position.
self.repeating_headers.push(header);
}
}
self.pending_headers = Default::default();
}
/// Lays out the rows of repeating and pending headers at the top of the
/// region.
///
/// Assumes the footer height for the current region has already been
/// calculated. Skips regions as necessary to fit all headers and all
/// footers.
pub fn layout_active_headers(&mut self, engine: &mut Engine) -> SourceResult<()> {
// Generate different locations for content in headers across its
// repetitions by assigning a unique number for each one.
let disambiguator = self.finished.len();
let header_height = self.simulate_header_height(
self.repeating_headers
.iter()
.copied()
.chain(self.pending_headers.iter().map(Repeatable::deref)),
&self.regions,
engine,
disambiguator,
)?;
// We already take the footer into account below.
// While skipping regions, footer height won't be automatically
// re-calculated until the end.
let mut skipped_region = false;
while self.unbreakable_rows_left == 0
&& !self.regions.size.y.fits(header_height)
&& self.may_progress_with_repeats()
{
// Advance regions without any output until we can place the
// header and the footer.
self.finish_region_internal(
Frame::soft(Axes::splat(Abs::zero())),
vec![],
Default::default(),
);
// TODO(layout model): re-calculate heights of headers and footers
// on each region if 'full' changes? (Assuming height doesn't
// change for now...)
//
// Would remove the footer height update below (move it here).
skipped_region = true;
self.regions.size.y -= self.current.footer_height;
self.current.initial_after_repeats = self.regions.size.y;
}
if let Some(footer) = &self.grid.footer
&& footer.repeated
&& skipped_region
{
// Simulate the footer again; the region's 'full' might have
// changed.
self.regions.size.y += self.current.footer_height;
self.current.footer_height = self
.simulate_footer(footer, &self.regions, engine, disambiguator)?
.height;
self.regions.size.y -= self.current.footer_height;
}
let repeating_header_rows =
total_header_row_count(self.repeating_headers.iter().copied());
let pending_header_rows =
total_header_row_count(self.pending_headers.iter().map(Repeatable::deref));
// Group of headers is unbreakable.
// Thus, no risk of 'finish_region' being recursively called from
// within 'layout_row'.
self.unbreakable_rows_left += repeating_header_rows + pending_header_rows;
self.current.last_repeated_header_end =
self.repeating_headers.last().map(|h| h.range.end).unwrap_or_default();
// Reset the header height for this region.
// It will be re-calculated when laying out each header row.
self.current.repeating_header_height = Abs::zero();
self.current.repeating_header_heights.clear();
debug_assert!(self.current.lrows.is_empty());
debug_assert!(self.current.lrows_orphan_snapshot.is_none());
let may_progress = self.may_progress_with_repeats();
if may_progress {
// Enable orphan prevention for headers at the top of the region.
// Otherwise, we will flush pending headers below, after laying
// them out.
//
// It is very rare for this to make a difference as we're usually
// at the 'last' region after the first skip, at which the snapshot
// is handled by 'layout_new_headers'. Either way, we keep this
// here for correctness.
self.current.lrows_orphan_snapshot = Some(self.current.lrows.len());
}
// Use indices to avoid double borrow. We don't mutate headers in
// 'layout_row' so this is fine.
let mut i = 0;
while let Some(&header) = self.repeating_headers.get(i) {
let header_height =
self.layout_header_rows(header, engine, disambiguator, false, true)?;
self.current.repeating_header_height += header_height;
// We assume that this vector will be sorted according
// to increasing levels like 'repeating_headers' and
// 'pending_headers' - and, in particular, their union, as this
// vector is pushed repeating heights from both.
//
// This is guaranteed by:
// 1. We always push pending headers after repeating headers,
// as we assume they don't conflict because we remove
// conflicting repeating headers when pushing a new pending
// header.
//
// 2. We push in the same order as each.
//
// 3. This vector is also modified when pushing a new pending
// header, where we remove heights for conflicting repeating
// headers which have now stopped repeating. They are always at
// the end and new pending headers respect the existing sort,
// so the vector will remain sorted.
self.current.repeating_header_heights.push(header_height);
i += 1;
}
self.current.repeated_header_rows = self.current.lrows.len();
self.current.initial_after_repeats = self.regions.size.y;
let mut has_non_repeated_pending_header = false;
for header in self.pending_headers {
if !header.repeated {
self.current.initial_after_repeats = self.regions.size.y;
has_non_repeated_pending_header = true;
}
let header_height =
self.layout_header_rows(header, engine, disambiguator, false, false)?;
if header.repeated {
self.current.repeating_header_height += header_height;
self.current.repeating_header_heights.push(header_height);
}
}
if !has_non_repeated_pending_header {
self.current.initial_after_repeats = self.regions.size.y;
}
if !may_progress {
// Flush pending headers immediately, as placing them again later
// won't help.
self.flush_orphans();
}
Ok(())
}
/// Lays out headers found for the first time during row layout.
///
/// If 'short_lived' is true, these headers are immediately followed by
/// a conflicting header, so it is assumed they will not be pushed to
/// pending headers.
///
/// Returns whether orphan prevention was successfully setup, or couldn't
/// due to short-lived headers or the region couldn't progress.
pub fn layout_new_headers(
&mut self,
headers: &'a [Repeatable<Header>],
short_lived: bool,
engine: &mut Engine,
) -> SourceResult<bool> {
// At first, only consider the height of the given headers. However,
// for upcoming regions, we will have to consider repeating headers as
// well.
let header_height = self.simulate_header_height(
headers.iter().map(Repeatable::deref),
&self.regions,
engine,
0,
)?;
while self.unbreakable_rows_left == 0
&& !self.regions.size.y.fits(header_height)
&& self.may_progress_with_repeats()
{
// Note that, after the first region skip, the new headers will go
// at the top of the region, but after the repeating headers that
// remained (which will be automatically placed in 'finish_region').
self.finish_region(engine, false)?;
}
// Remove new headers at the end of the region if the upcoming row
// doesn't fit.
// TODO(subfooters): what if there is a footer right after it?
let should_snapshot = !short_lived
&& self.current.lrows_orphan_snapshot.is_none()
&& self.may_progress_with_repeats();
if should_snapshot {
// If we don't enter this branch while laying out non-short lived
// headers, that means we will have to immediately flush pending
// headers and mark them as final, since trying to place them in
// the next page won't help get more space.
self.current.lrows_orphan_snapshot = Some(self.current.lrows.len());
}
let mut at_top = self.regions.size.y == self.current.initial_after_repeats;
self.unbreakable_rows_left +=
total_header_row_count(headers.iter().map(Repeatable::deref));
for header in headers {
let header_height =
self.layout_header_rows(header, engine, 0, false, false)?;
// Only store this header height if it is actually going to
// become a pending header. Otherwise, pretend it's not a
// header... This is fine for consumers of 'header_height' as
// it is guaranteed this header won't appear in a future
// region, so multi-page rows and cells can effectively ignore
// this header.
if !short_lived && header.repeated {
self.current.repeating_header_height += header_height;
self.current.repeating_header_heights.push(header_height);
if at_top {
self.current.initial_after_repeats = self.regions.size.y;
}
} else {
at_top = false;
}
}
Ok(should_snapshot)
}
/// Calculates the total expected height of several headers.
pub fn simulate_header_height<'h: 'a>(
&self,
headers: impl IntoIterator<Item = &'h Header>,
regions: &Regions<'_>,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<Abs> {
let mut height = Abs::zero();
for header in headers {
height +=
self.simulate_header(header, regions, engine, disambiguator)?.height;
}
Ok(height)
}
/// Simulate the header's group of rows.
pub fn simulate_header(
&self,
header: &Header,
regions: &Regions<'_>,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<UnbreakableRowGroup> {
// Note that we assume the invariant that any rowspan in a header is
// fully contained within that header. Therefore, there won't be any
// unbreakable rowspans exceeding the header's rows, and we can safely
// assume that the amount of unbreakable rows following the first row
// in the header will be precisely the rows in the header.
self.simulate_unbreakable_row_group(
header.range.start,
Some(header.range.end - header.range.start),
regions,
engine,
disambiguator,
)
}
/// Updates `self.footer_height` by simulating the footer, and skips to fitting region.
pub fn prepare_footer(
&mut self,
footer: &Footer,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<()> {
let footer_height = self
.simulate_footer(footer, &self.regions, engine, disambiguator)?
.height;
let mut skipped_region = false;
while self.unbreakable_rows_left == 0
&& !self.regions.size.y.fits(footer_height)
&& self.regions.may_progress()
{
// Advance regions without any output until we can place the
// footer.
self.finish_region_internal(
Frame::soft(Axes::splat(Abs::zero())),
vec![],
Default::default(),
);
skipped_region = true;
}
// TODO(subfooters): Consider resetting header height etc. if we skip
// region. (Maybe move that step to `finish_region_internal`.)
//
// That is unnecessary at the moment as 'prepare_footers' is only
// called at the start of the region, so header height is always zero
// and no headers were placed so far, but what about when we can have
// footers in the middle of the region? Let's think about this then.
self.current.footer_height = if skipped_region {
// Simulate the footer again; the region's 'full' might have
// changed.
self.simulate_footer(footer, &self.regions, engine, disambiguator)?
.height
} else {
footer_height
};
Ok(())
}
/// Lays out all rows in the footer.
/// They are unbreakable.
pub fn layout_footer(
&mut self,
footer: &Footer,
engine: &mut Engine,
disambiguator: usize,
is_being_repeated: bool,
) -> SourceResult<()> {
// Ensure footer rows have their own height available.
// Won't change much as we're creating an unbreakable row group
// anyway, so this is mostly for correctness.
self.regions.size.y += self.current.footer_height;
let repeats = self.grid.footer.as_ref().is_some_and(|f| f.repeated);
let footer_len = self.grid.rows.len() - footer.start;
self.unbreakable_rows_left += footer_len;
for y in footer.start..self.grid.rows.len() {
self.layout_row_with_state(
y,
engine,
disambiguator,
RowState {
in_active_repeatable: repeats,
is_being_repeated,
..Default::default()
},
)?;
}
Ok(())
}
// Simulate the footer's group of rows.
pub fn simulate_footer(
&self,
footer: &Footer,
regions: &Regions<'_>,
engine: &mut Engine,
disambiguator: usize,
) -> SourceResult<UnbreakableRowGroup> {
// Note that we assume the invariant that any rowspan in a footer is
// fully contained within that footer. Therefore, there won't be any
// unbreakable rowspans exceeding the footer's rows, and we can safely
// assume that the amount of unbreakable rows following the first row
// in the footer will be precisely the rows in the footer.
self.simulate_unbreakable_row_group(
footer.start,
Some(footer.end - footer.start),
regions,
engine,
disambiguator,
)
}
}
/// The total amount of rows in the given list of headers.
#[inline]
pub fn total_header_row_count<'h>(
headers: impl IntoIterator<Item = &'h Header>,
) -> usize {
headers.into_iter().map(|h| h.range.end - h.range.start).sum()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/engine.rs | crates/typst-library/src/engine.rs | //! Definition of the central compilation context.
use std::sync::atomic::{AtomicUsize, Ordering};
use comemo::{Track, Tracked, TrackedMut};
use ecow::EcoVec;
use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator};
use rustc_hash::FxHashSet;
use typst_syntax::{FileId, Span};
use typst_utils::Protected;
use crate::World;
use crate::diag::{HintedStrResult, SourceDiagnostic, SourceResult, StrResult, bail};
use crate::foundations::{Styles, Value};
use crate::introspection::{Introspect, Introspection, Introspector};
use crate::routines::Routines;
/// Holds all data needed during compilation.
pub struct Engine<'a> {
/// Defines implementation of various Typst compiler routines as a table of
/// function pointers.
pub routines: &'a Routines,
/// The compilation environment.
pub world: Tracked<'a, dyn World + 'a>,
/// Provides access to information about the document.
pub introspector: Protected<Tracked<'a, Introspector>>,
/// May hold a span that is currently under inspection.
pub traced: Tracked<'a, Traced>,
/// A pure sink for warnings, delayed errors, and spans under inspection.
pub sink: TrackedMut<'a, Sink>,
/// The route the engine took during compilation. This is used to detect
/// cyclic imports and excessive nesting.
pub route: Route<'a>,
}
impl Engine<'_> {
/// Handles a result without immediately terminating execution. Instead, it
/// produces a delayed error that is only promoted to a fatal one if it
/// remains by the end of the introspection loop.
pub fn delay<T: Default>(&mut self, result: SourceResult<T>) -> T {
match result {
Ok(value) => value,
Err(errors) => {
self.sink.delay(errors);
T::default()
}
}
}
/// Runs tasks on the engine in parallel.
pub fn parallelize<P, I, T, U, F>(
&mut self,
iter: P,
f: F,
) -> impl Iterator<Item = U> + use<P, I, T, U, F>
where
P: IntoIterator<IntoIter = I>,
I: Iterator<Item = T>,
T: Send,
U: Send,
F: Fn(&mut Engine, T) -> U + Send + Sync,
{
let Engine {
world, introspector, traced, ref route, routines, ..
} = *self;
// We collect into a vector and then call `into_par_iter` instead of
// using `par_bridge` because it does not retain the ordering.
let work: Vec<T> = iter.into_iter().collect();
// Work in parallel.
let mut pairs: Vec<(U, Sink)> = Vec::with_capacity(work.len());
work.into_par_iter()
.map(|value| {
let mut sink = Sink::new();
let mut engine = Engine {
world,
introspector,
traced,
sink: sink.track_mut(),
route: route.clone(),
routines,
};
(f(&mut engine, value), sink)
})
.collect_into_vec(&mut pairs);
// Apply the subsinks to the outer sink.
for (_, sink) in &mut pairs {
let sink = std::mem::take(sink);
self.sink.extend(
sink.introspections,
sink.delayed,
sink.warnings,
sink.values,
);
}
pairs.into_iter().map(|(output, _)| output)
}
/// Performs an introspection on the introspector and returns its result.
///
/// As a side effect, the introspection is stored in the sink. If the
/// document does not converge, the recorded introspections are used to
/// determine the cause of non-convergence.
pub fn introspect<I>(&mut self, introspection: I) -> I::Output
where
I: Introspect,
{
let introspector = *self.introspector.access("is okay since we're recording it");
let output = introspection.introspect(self, introspector);
self.sink.introspection(Introspection::new(introspection));
output
}
}
/// May hold a span that is currently under inspection.
#[derive(Default)]
pub struct Traced(Option<Span>);
impl Traced {
/// Wraps a to-be-traced `Span`.
///
/// Call `Traced::default()` to trace nothing.
pub fn new(traced: Span) -> Self {
Self(Some(traced))
}
}
#[comemo::track]
impl Traced {
/// Returns the traced span _if_ it is part of the given source file or
/// `None` otherwise.
///
/// We hide the span if it isn't in the given file so that only results for
/// the file with the traced span are invalidated.
pub fn get(&self, id: FileId) -> Option<Span> {
if self.0.and_then(Span::id) == Some(id) { self.0 } else { None }
}
}
/// A push-only sink for recorded introspections, delayed errors, warnings, and
/// traced values.
///
/// All tracked methods of this type are of the form `(&mut self, ..) -> ()`, so
/// in principle they do not need validation (though that optimization is not
/// yet implemented in comemo).
#[derive(Default, Clone)]
pub struct Sink {
/// Introspections that were performed during compilation.
introspections: EcoVec<Introspection>,
/// Delayed errors: Those are errors that we can ignore until the last
/// iteration. For instance, show rules may throw during earlier iterations
/// because the introspector is not yet ready. We first ignore that and
/// proceed with empty content and only if the error remains by the end
/// of the last iteration, we promote it.
delayed: EcoVec<SourceDiagnostic>,
/// Warnings emitted during iteration.
warnings: EcoVec<SourceDiagnostic>,
/// Hashes of all warning's spans and messages for warning deduplication.
warnings_set: FxHashSet<u128>,
/// A sequence of traced values for a span.
values: EcoVec<(Value, Option<Styles>)>,
}
impl Sink {
/// The maximum number of traced values.
pub const MAX_VALUES: usize = 10;
/// Create a new empty sink.
pub fn new() -> Self {
Self::default()
}
/// Get the introspections.
pub fn introspections(&self) -> &[Introspection] {
&self.introspections
}
/// Get the stored delayed errors.
pub fn delayed(&mut self) -> EcoVec<SourceDiagnostic> {
std::mem::take(&mut self.delayed)
}
/// Get the stored warnings.
pub fn warnings(self) -> EcoVec<SourceDiagnostic> {
self.warnings
}
/// Get the values for the traced span.
pub fn values(self) -> EcoVec<(Value, Option<Styles>)> {
self.values
}
/// Extend from another sink.
pub fn extend_from_sink(&mut self, other: Sink) {
self.extend(other.introspections, other.delayed, other.warnings, other.values);
}
}
#[comemo::track]
impl Sink {
/// Trace an introspection.
pub fn introspection(&mut self, introspection: Introspection) {
self.introspections.push(introspection);
}
/// Push delayed errors.
pub fn delay(&mut self, errors: EcoVec<SourceDiagnostic>) {
self.delayed.extend(errors);
}
/// Add a warning.
pub fn warn(&mut self, warning: SourceDiagnostic) {
// Check if warning is a duplicate.
let hash = typst_utils::hash128(&(&warning.span, &warning.message));
if self.warnings_set.insert(hash) {
self.warnings.push(warning);
}
}
/// Trace a value and optionally styles for the traced span.
pub fn value(&mut self, value: Value, styles: Option<Styles>) {
if self.values.len() < Self::MAX_VALUES {
self.values.push((value, styles));
}
}
/// Extend from parts of another sink.
fn extend(
&mut self,
introspections: EcoVec<Introspection>,
delayed: EcoVec<SourceDiagnostic>,
warnings: EcoVec<SourceDiagnostic>,
values: EcoVec<(Value, Option<Styles>)>,
) {
self.introspections.extend(introspections);
self.delayed.extend(delayed);
for warning in warnings {
self.warn(warning);
}
if let Some(remaining) = Self::MAX_VALUES.checked_sub(self.values.len()) {
self.values.extend(values.into_iter().take(remaining));
}
}
}
/// The route the engine took during compilation. This is used to detect
/// cyclic imports and excessive nesting.
pub struct Route<'a> {
/// The parent route segment, if present.
///
/// This is used when an engine is created from another engine.
// We need to override the constraint's lifetime here so that `Tracked` is
// covariant over the constraint. If it becomes invariant, we're in for a
// world of lifetime pain.
outer: Option<Tracked<'a, Self, <Route<'static> as Track>::Call>>,
/// This is set if this route segment was inserted through the start of a
/// module evaluation.
id: Option<FileId>,
/// This is set whenever we enter a function, nested layout, or are applying
/// a show rule. The length of this segment plus the lengths of all `outer`
/// route segments make up the length of the route. If the length of the
/// route exceeds `MAX_DEPTH`, then we throw a "maximum ... depth exceeded"
/// error.
len: usize,
/// The upper bound we've established for the parent chain length.
///
/// We don't know the exact length (that would defeat the whole purpose
/// because it would prevent cache reuse of some computation at different,
/// non-exceeding depths).
upper: AtomicUsize,
}
impl<'a> Route<'a> {
/// Create a new, empty route.
pub fn root() -> Self {
Self {
id: None,
outer: None,
len: 0,
upper: AtomicUsize::new(0),
}
}
/// Extend the route with another segment with a default length of 1.
pub fn extend(outer: Tracked<'a, Self>) -> Self {
Route {
outer: Some(outer),
id: None,
len: 1,
upper: AtomicUsize::new(usize::MAX),
}
}
/// Attach a file id to the route segment.
pub fn with_id(self, id: FileId) -> Self {
Self { id: Some(id), ..self }
}
/// Set the length of the route segment to zero.
pub fn unnested(self) -> Self {
Self { len: 0, ..self }
}
/// Start tracking this route.
///
/// In comparison to [`Track::track`], this method skips this chain link
/// if it does not contribute anything.
pub fn track(&self) -> Tracked<'_, Self> {
match self.outer {
Some(outer) if self.id.is_none() && self.len == 0 => outer,
_ => Track::track(self),
}
}
/// Increase the nesting depth for this route segment.
pub fn increase(&mut self) {
self.len += 1;
}
/// Decrease the nesting depth for this route segment.
pub fn decrease(&mut self) {
self.len -= 1;
}
}
/// The maximum nesting depths. They are different so that even if show rule and
/// call checks are interleaved, for show rule problems we always get the show
/// rule error. The lower the max depth for a kind of error, the higher its
/// precedence compared to the others.
impl Route<'_> {
/// The maximum stack nesting depth.
const MAX_SHOW_RULE_DEPTH: usize = 64;
/// The maximum layout nesting depth.
const MAX_LAYOUT_DEPTH: usize = 72;
/// The maximum HTML nesting depth.
const MAX_HTML_DEPTH: usize = 72;
/// The maximum function call nesting depth.
const MAX_CALL_DEPTH: usize = 80;
/// Ensures that we are within the maximum show rule depth.
pub fn check_show_depth(&self) -> HintedStrResult<()> {
if !self.within(Route::MAX_SHOW_RULE_DEPTH) {
bail!(
"maximum show rule depth exceeded";
hint: "maybe a show rule matches its own output";
hint: "maybe there are too deeply nested elements";
);
}
Ok(())
}
/// Ensures that we are within the maximum layout depth.
pub fn check_layout_depth(&self) -> HintedStrResult<()> {
if !self.within(Route::MAX_LAYOUT_DEPTH) {
bail!(
"maximum layout depth exceeded";
hint: "try to reduce the amount of nesting in your layout";
);
}
Ok(())
}
/// Ensures that we are within the maximum HTML depth.
pub fn check_html_depth(&self) -> HintedStrResult<()> {
if !self.within(Route::MAX_HTML_DEPTH) {
bail!(
"maximum HTML depth exceeded";
hint: "try to reduce the amount of nesting of your HTML";
);
}
Ok(())
}
/// Ensures that we are within the maximum function call depth.
pub fn check_call_depth(&self) -> StrResult<()> {
if !self.within(Route::MAX_CALL_DEPTH) {
bail!("maximum function call depth exceeded");
}
Ok(())
}
}
#[comemo::track]
#[allow(clippy::needless_lifetimes)]
impl<'a> Route<'a> {
/// Whether the given id is part of the route.
pub fn contains(&self, id: FileId) -> bool {
self.id == Some(id) || self.outer.is_some_and(|outer| outer.contains(id))
}
/// Whether the route's depth is less than or equal to the given depth.
pub fn within(&self, depth: usize) -> bool {
// We only need atomicity and no synchronization of other operations, so
// `Relaxed` is fine.
use Ordering::Relaxed;
let upper = self.upper.load(Relaxed);
if upper.saturating_add(self.len) <= depth {
return true;
}
match self.outer {
Some(_) if depth < self.len => false,
Some(outer) => {
let within = outer.within(depth - self.len);
if within && depth < upper {
// We don't want to accidentally increase the upper bound,
// hence the compare-exchange.
self.upper.compare_exchange(upper, depth, Relaxed, Relaxed).ok();
}
within
}
None => true,
}
}
}
impl Default for Route<'_> {
fn default() -> Self {
Self::root()
}
}
impl Clone for Route<'_> {
fn clone(&self) -> Self {
Self {
outer: self.outer,
id: self.id,
len: self.len,
upper: AtomicUsize::new(self.upper.load(Ordering::Relaxed)),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/lib.rs | crates/typst-library/src/lib.rs | //! Typst's standard library.
//!
//! This crate also contains all of the compiler's central type definitions as
//! these are interwoven with the standard library types.
//!
//! In contrast to the _types,_ most of the compilation _behaviour_ is split out
//! into separate crates (`typst-eval`, `typst-realize`, `typst-layout`, etc.)
//!
//! Note that, unless you are working on the compiler itself, you will rarely
//! need to interact with this crate, as it is fully reexported by the `typst`
//! crate.
extern crate self as typst_library;
pub mod diag;
pub mod engine;
pub mod foundations;
pub mod introspection;
pub mod layout;
pub mod loading;
pub mod math;
pub mod model;
pub mod pdf;
pub mod routines;
pub mod symbols;
pub mod text;
pub mod visualize;
use std::ops::{Deref, Range};
use serde::{Deserialize, Serialize};
use typst_syntax::{FileId, Source, Span};
use typst_utils::{LazyHash, SmallBitSet};
use crate::diag::FileResult;
use crate::foundations::{Array, Binding, Bytes, Datetime, Dict, Module, Scope, Styles};
use crate::layout::{Alignment, Dir};
use crate::routines::Routines;
use crate::text::{Font, FontBook};
use crate::visualize::Color;
/// The environment in which typesetting occurs.
///
/// All loading functions (`main`, `source`, `file`, `font`) should perform
/// internal caching so that they are relatively cheap on repeated invocations
/// with the same argument. [`Source`], [`Bytes`], and [`Font`] are
/// all reference-counted and thus cheap to clone.
///
/// The compiler doesn't do the caching itself because the world has much more
/// information on when something can change. For example, fonts typically don't
/// change and can thus even be cached across multiple compilations (for
/// long-running applications like `typst watch`). Source files on the other
/// hand can change and should thus be cleared after each compilation. Advanced
/// clients like language servers can also retain the source files and
/// [edit](Source::edit) them in-place to benefit from better incremental
/// performance.
#[comemo::track]
pub trait World: Send + Sync {
/// The standard library.
///
/// Can be created through `Library::build()`.
fn library(&self) -> &LazyHash<Library>;
/// Metadata about all known fonts.
fn book(&self) -> &LazyHash<FontBook>;
/// Get the file id of the main source file.
fn main(&self) -> FileId;
/// Try to access the specified source file.
fn source(&self, id: FileId) -> FileResult<Source>;
/// Try to access the specified file.
fn file(&self, id: FileId) -> FileResult<Bytes>;
/// Try to access the font with the given index in the font book.
fn font(&self, index: usize) -> Option<Font>;
/// Get the current date.
///
/// If no offset is specified, the local date should be chosen. Otherwise,
/// the UTC date should be chosen with the corresponding offset in hours.
///
/// If this function returns `None`, Typst's `datetime` function will
/// return an error.
fn today(&self, offset: Option<i64>) -> Option<Datetime>;
}
macro_rules! world_impl {
($W:ident for $ptr:ty) => {
impl<$W: World> World for $ptr {
fn library(&self) -> &LazyHash<Library> {
self.deref().library()
}
fn book(&self) -> &LazyHash<FontBook> {
self.deref().book()
}
fn main(&self) -> FileId {
self.deref().main()
}
fn source(&self, id: FileId) -> FileResult<Source> {
self.deref().source(id)
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
self.deref().file(id)
}
fn font(&self, index: usize) -> Option<Font> {
self.deref().font(index)
}
fn today(&self, offset: Option<i64>) -> Option<Datetime> {
self.deref().today(offset)
}
}
};
}
world_impl!(W for std::boxed::Box<W>);
world_impl!(W for std::sync::Arc<W>);
world_impl!(W for &W);
/// Helper methods on [`World`] implementations.
pub trait WorldExt {
/// Get the byte range for a span.
///
/// Returns `None` if the `Span` does not point into any file.
fn range(&self, span: Span) -> Option<Range<usize>>;
}
impl<T: World + ?Sized> WorldExt for T {
fn range(&self, span: Span) -> Option<Range<usize>> {
span.range().or_else(|| self.source(span.id()?).ok()?.range(span))
}
}
/// Definition of Typst's standard library.
///
/// To create and configure the standard library, use the `LibraryExt` trait
/// and call
/// - `Library::default()` for a standard configuration
/// - `Library::builder().build()` if you want to customize the library
#[derive(Debug, Clone, Hash)]
pub struct Library {
/// The module that contains the definitions that are available everywhere.
pub global: Module,
/// The module that contains the definitions available in math mode.
pub math: Module,
/// The default style properties (for page size, font selection, and
/// everything else configurable via set and show rules).
pub styles: Styles,
/// The standard library as a value. Used to provide the `std` module.
pub std: Binding,
/// In-development features that were enabled.
pub features: Features,
}
/// Configurable builder for the standard library.
///
/// Constructed via the `LibraryExt` trait.
#[derive(Debug, Clone)]
pub struct LibraryBuilder {
routines: &'static Routines,
inputs: Option<Dict>,
features: Features,
}
impl LibraryBuilder {
/// Creates a new builder.
#[doc(hidden)]
pub fn from_routines(routines: &'static Routines) -> Self {
Self {
routines,
inputs: None,
features: Features::default(),
}
}
/// Configure the inputs visible through `sys.inputs`.
pub fn with_inputs(mut self, inputs: Dict) -> Self {
self.inputs = Some(inputs);
self
}
/// Configure in-development features that should be enabled.
///
/// No guarantees whatsover!
pub fn with_features(mut self, features: Features) -> Self {
self.features = features;
self
}
/// Consumes the builder and returns a `Library`.
pub fn build(self) -> Library {
let math = math::module();
let inputs = self.inputs.unwrap_or_default();
let global = global(self.routines, math.clone(), inputs, &self.features);
Library {
global: global.clone(),
math,
styles: Styles::new(),
std: Binding::detached(global),
features: self.features,
}
}
}
/// A selection of in-development features that should be enabled.
///
/// Can be collected from an iterator of [`Feature`]s.
#[derive(Debug, Default, Clone, Hash)]
pub struct Features(SmallBitSet);
impl Features {
/// Check whether the given feature is enabled.
pub fn is_enabled(&self, feature: Feature) -> bool {
self.0.contains(feature as usize)
}
}
impl FromIterator<Feature> for Features {
fn from_iter<T: IntoIterator<Item = Feature>>(iter: T) -> Self {
let mut set = SmallBitSet::default();
for feature in iter {
set.insert(feature as usize);
}
Self(set)
}
}
/// An in-development feature that should be enabled.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum Feature {
Html,
A11yExtras,
}
/// A group of related standard library definitions.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Category {
Foundations,
Introspection,
Layout,
DataLoading,
Math,
Model,
Symbols,
Text,
Visualize,
Pdf,
Html,
Svg,
Png,
}
impl Category {
/// The kebab-case name of the category.
pub fn name(&self) -> &'static str {
match self {
Self::Foundations => "foundations",
Self::Introspection => "introspection",
Self::Layout => "layout",
Self::DataLoading => "data-loading",
Self::Math => "math",
Self::Model => "model",
Self::Symbols => "symbols",
Self::Text => "text",
Self::Visualize => "visualize",
Self::Pdf => "pdf",
Self::Html => "html",
Self::Svg => "svg",
Self::Png => "png",
}
}
}
/// Construct the module with global definitions.
fn global(
routines: &Routines,
math: Module,
inputs: Dict,
features: &Features,
) -> Module {
let mut global = Scope::deduplicating();
self::foundations::define(&mut global, inputs, features);
self::model::define(&mut global);
self::text::define(&mut global);
self::layout::define(&mut global);
self::visualize::define(&mut global);
self::introspection::define(&mut global);
self::loading::define(&mut global);
self::symbols::define(&mut global);
global.define("math", math);
global.define("pdf", self::pdf::module(features));
if features.is_enabled(Feature::Html) {
global.define("html", (routines.html_module)());
}
prelude(&mut global);
Module::new("global", global)
}
/// Defines scoped values that are globally available, too.
fn prelude(global: &mut Scope) {
global.define("black", Color::BLACK);
global.define("gray", Color::GRAY);
global.define("silver", Color::SILVER);
global.define("white", Color::WHITE);
global.define("navy", Color::NAVY);
global.define("blue", Color::BLUE);
global.define("aqua", Color::AQUA);
global.define("teal", Color::TEAL);
global.define("eastern", Color::EASTERN);
global.define("purple", Color::PURPLE);
global.define("fuchsia", Color::FUCHSIA);
global.define("maroon", Color::MAROON);
global.define("red", Color::RED);
global.define("orange", Color::ORANGE);
global.define("yellow", Color::YELLOW);
global.define("olive", Color::OLIVE);
global.define("green", Color::GREEN);
global.define("lime", Color::LIME);
global.define("luma", Color::luma_data());
global.define("oklab", Color::oklab_data());
global.define("oklch", Color::oklch_data());
global.define("rgb", Color::rgb_data());
global.define("cmyk", Color::cmyk_data());
global.define("range", Array::range_data());
global.define("ltr", Dir::LTR);
global.define("rtl", Dir::RTL);
global.define("ttb", Dir::TTB);
global.define("btt", Dir::BTT);
global.define("start", Alignment::START);
global.define("left", Alignment::LEFT);
global.define("center", Alignment::CENTER);
global.define("right", Alignment::RIGHT);
global.define("end", Alignment::END);
global.define("top", Alignment::TOP);
global.define("horizon", Alignment::HORIZON);
global.define("bottom", Alignment::BOTTOM);
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/routines.rs | crates/typst-library/src/routines.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use comemo::{Tracked, TrackedMut};
use typst_syntax::{Span, SyntaxMode};
use typst_utils::LazyHash;
use crate::World;
use crate::diag::SourceResult;
use crate::engine::{Engine, Route, Sink, Traced};
use crate::foundations::{
Args, Closure, Content, Context, Func, Module, NativeRuleMap, Scope, StyleChain,
Styles, Value,
};
use crate::introspection::{Introspector, Locator, SplitLocator};
use crate::layout::{Frame, Region};
use crate::model::DocumentInfo;
use crate::visualize::Color;
/// Defines the `Routines` struct.
macro_rules! routines {
($(
$(#[$attr:meta])*
fn $name:ident $(<$($time:lifetime),*>)? ($($args:tt)*) -> $ret:ty
)*) => {
/// Defines implementation of various Typst compiler routines as a table
/// of function pointers.
///
/// This is essentially dynamic linking and done to allow for crate
/// splitting.
pub struct Routines {
/// Native show rules.
pub rules: NativeRuleMap,
$(
$(#[$attr])*
pub $name: $(for<$($time),*>)? fn ($($args)*) -> $ret
),*
}
impl Hash for Routines {
fn hash<H: Hasher>(&self, _: &mut H) {}
}
impl Debug for Routines {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("Routines(..)")
}
}
};
}
routines! {
/// Evaluates a string as code and return the resulting value.
fn eval_string(
routines: &Routines,
world: Tracked<dyn World + '_>,
sink: TrackedMut<Sink>,
introspector: Tracked<Introspector>,
context: Tracked<Context>,
string: &str,
span: Span,
mode: SyntaxMode,
scope: Scope,
) -> SourceResult<Value>
/// Call the closure in the context with the arguments.
fn eval_closure(
func: &Func,
closure: &LazyHash<Closure>,
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
context: Tracked<Context>,
args: Args,
) -> SourceResult<Value>
/// Realizes content into a flat list of well-known, styled items.
fn realize<'a>(
kind: RealizationKind,
engine: &mut Engine,
locator: &mut SplitLocator,
arenas: &'a Arenas,
content: &'a Content,
styles: StyleChain<'a>,
) -> SourceResult<Vec<Pair<'a>>>
/// Lays out content into a single region, producing a single frame.
fn layout_frame(
engine: &mut Engine,
content: &Content,
locator: Locator,
styles: StyleChain,
region: Region,
) -> SourceResult<Frame>
/// Constructs the `html` module.
fn html_module() -> Module
/// Wraps content in a span with a color.
///
/// This is a temporary workaround until `TextElem::fill` is supported in
/// HTML export.
fn html_span_filled(content: Content, color: Color) -> Content
}
/// Defines what kind of realization we are performing.
pub enum RealizationKind<'a> {
/// This the root realization for layout. Requires a mutable reference
/// to document metadata that will be filled from `set document` rules.
LayoutDocument { info: &'a mut DocumentInfo },
/// A nested realization in a container (e.g. a `block`). Requires a mutable
/// reference to an enum that will be set to `FragmentKind::Inline` if the
/// fragment's content was fully inline.
LayoutFragment { kind: &'a mut FragmentKind },
/// A nested realization in a paragraph (i.e. a `par`)
LayoutPar,
/// This the root realization for HTML. Requires a mutable reference to
/// document metadata that will be filled from `set document` rules.
///
/// The `is_inline` function checks whether content consists of an inline
/// HTML element. It's used by the `PAR` grouping rules. This is slightly
/// hacky and might be replaced by a mechanism to supply the grouping rules
/// as a realization user.
HtmlDocument { info: &'a mut DocumentInfo, is_inline: fn(&Content) -> bool },
/// A nested realization in a container (e.g. a `block`). Requires a mutable
/// reference to an enum that will be set to `FragmentKind::Inline` if the
/// fragment's content was fully inline.
HtmlFragment { kind: &'a mut FragmentKind, is_inline: fn(&Content) -> bool },
/// A realization within math.
Math,
}
impl RealizationKind<'_> {
/// It this a realization for HTML export?
pub fn is_html(&self) -> bool {
matches!(self, Self::HtmlDocument { .. } | Self::HtmlFragment { .. })
}
/// It this a realization for a container?
pub fn is_fragment(&self) -> bool {
matches!(self, Self::LayoutFragment { .. } | Self::HtmlFragment { .. })
}
/// It this a realization for the whole document?
pub fn is_document(&self) -> bool {
matches!(self, Self::LayoutDocument { .. } | Self::HtmlDocument { .. })
}
/// If this is a document-level realization, accesses the document info.
pub fn as_document_mut(&mut self) -> Option<&mut DocumentInfo> {
match self {
Self::LayoutDocument { info } | Self::HtmlDocument { info, .. } => {
Some(*info)
}
_ => None,
}
}
/// If this is a container-level realization, accesses the fragment kind.
pub fn as_fragment_mut(&mut self) -> Option<&mut FragmentKind> {
match self {
Self::LayoutFragment { kind } | Self::HtmlFragment { kind, .. } => {
Some(*kind)
}
_ => None,
}
}
}
/// The kind of fragment output that realization produced.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum FragmentKind {
/// The fragment's contents were fully inline, and as a result, the output
/// elements are too.
Inline,
/// The fragment contained non-inline content, so inline content was forced
/// into paragraphs, and as a result, the output elements are not inline.
Block,
}
/// Temporary storage arenas for lifetime extension during realization.
///
/// Must be kept live while the content returned from realization is processed.
#[derive(Default)]
pub struct Arenas {
/// A typed arena for owned content.
pub content: typed_arena::Arena<Content>,
/// A typed arena for owned styles.
pub styles: typed_arena::Arena<Styles>,
/// An untyped arena for everything that is `Copy`.
pub bump: bumpalo::Bump,
}
/// A pair of content and a style chain that applies to it.
pub type Pair<'a> = (&'a Content, StyleChain<'a>);
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/symbols.rs | crates/typst-library/src/symbols.rs | //! Modifiable symbols.
use crate::foundations::{Deprecation, Module, Scope, Symbol, Value};
/// Hook up all `symbol` definitions.
pub(super) fn define(global: &mut Scope) {
global.start_category(crate::Category::Symbols);
extend_scope_from_codex_module(global, codex::ROOT);
global.reset_category();
}
/// Hook up all math `symbol` definitions, i.e., elements of the `sym` module.
pub(super) fn define_math(math: &mut Scope) {
extend_scope_from_codex_module(math, codex::SYM);
}
fn extend_scope_from_codex_module(scope: &mut Scope, module: codex::Module) {
for (name, binding) in module.iter() {
let value = match binding.def {
codex::Def::Symbol(s) => Value::Symbol(s.into()),
codex::Def::Module(m) => Value::Module(Module::new(name, m.into())),
};
let scope_binding = scope.define(name, value);
if let Some(message) = binding.deprecation {
scope_binding.deprecated(Deprecation::new().with_message(message));
}
}
}
impl From<codex::Module> for Scope {
fn from(module: codex::Module) -> Scope {
let mut scope = Self::new();
extend_scope_from_codex_module(&mut scope, module);
scope
}
}
impl From<codex::Symbol> for Symbol {
fn from(symbol: codex::Symbol) -> Self {
match symbol {
codex::Symbol::Single(value) => Symbol::single(value),
codex::Symbol::Multi(list) => Symbol::list(list),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/diag.rs | crates/typst-library/src/diag.rs | //! Diagnostics.
use std::backtrace::{Backtrace, BacktraceStatus};
use std::fmt::{self, Display, Formatter, Write as _};
use std::io;
use std::path::{Path, PathBuf};
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use az::SaturatingAs;
use comemo::Tracked;
use ecow::{EcoVec, eco_vec};
use typst_syntax::package::{PackageSpec, PackageVersion};
use typst_syntax::{Lines, Span, Spanned, SyntaxError};
use utf8_iter::ErrorReportingUtf8Chars;
use crate::engine::Engine;
use crate::loading::{LoadSource, Loaded};
use crate::{World, WorldExt};
/// Early-return with an error for common result types used in Typst. If you
/// need to interact with the produced errors more, consider using `error!` or
/// `warning!` instead.
///
/// The main usage is `bail!(span, "message with {}", "formatting")`, which will
/// early-return an error for a [`SourceResult`]. If you leave out the span, it
/// will return an error for a [`StrResult`] or [`HintedStrResult`] instead.
///
/// You can also add hints by separating the initial message with a semicolon
/// and writing `hint: "..."`, see the example.
///
/// ```ignore
/// bail!("returning a {} error with no span", "formatted"); // StrResult (no span)
/// bail!(span, "returning a {} error", "formatted"); // SourceResult (has a span)
/// bail!(
/// span, "returning a {} error", "formatted";
/// hint: "with multiple hints";
/// hint: "the hints can have {} too", "formatting";
/// ); // SourceResult
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! __bail {
// If we don't have a span, forward to `error!` to create a `StrResult` or
// `HintedStrResult`.
(
$fmt:literal $(, $arg:expr)* $(,)?
$(; hint: $hint:literal $(, $hint_arg:expr)*)*
$(;)?
) => {
return Err($crate::diag::error!(
$fmt $(, $arg)*
$(; hint: $hint $(, $hint_arg)*)*
))
};
// Just early return for a `SourceResult`: `bail!(some_error)`.
($error:expr) => {
return Err(::ecow::eco_vec![$error])
};
// For `bail(span, ...)`, we reuse `error!` and produce a `SourceResult`.
($($tts:tt)*) => {
return Err(::ecow::eco_vec![$crate::diag::error!($($tts)*)])
};
}
/// Construct an [`EcoString`], [`HintedString`] or [`SourceDiagnostic`] with
/// severity `Error`.
///
/// If you just want to quickly return an error, consider the `bail!` macro.
/// If you want to create a warning, use the `warning!` macro.
///
/// You can also add hints by separating the initial message with a semicolon
/// and writing `hint: "..."`, see the example.
///
/// ```ignore
/// error!("a {} error with no span", "formatted"); // EcoString, same as `eco_format!`
/// error!(span, "an error with a {} message", "formatted"); // SourceDiagnostic
/// error!(
/// span, "an error with a {} message", "formatted";
/// hint: "with multiple hints";
/// hint: "the hints can have {} too", "formatting";
/// ); // SourceDiagnostic
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! __error {
// For `error!("just a {}", "string")`.
($fmt:literal $(, $arg:expr)* $(,)?) => {
$crate::diag::eco_format!($fmt $(, $arg)*).into()
};
// For `error!("a hinted {}", "string"; hint: "some hint"; hint: "...")`
(
$fmt:literal $(, $arg:expr)* $(,)?
$(; hint: $hint:literal $(, $hint_arg:expr)*)*
$(;)?
) => {
$crate::diag::HintedString::new(
$crate::diag::eco_format!($fmt $(, $arg)*)
) $(.with_hint($crate::diag::eco_format!($hint $(, $hint_arg)*)))*
};
// For `error!(span, ...)`
(
$span:expr, $fmt:literal $(, $arg:expr)* $(,)?
$(; hint: $hint:literal $(, $hint_arg:expr)*)*
$(;)?
) => {
$crate::diag::SourceDiagnostic::error(
$span,
$crate::diag::eco_format!($fmt $(, $arg)*)
) $(.with_hint($crate::diag::eco_format!($hint $(, $hint_arg)*)))*
};
}
/// Construct a [`SourceDiagnostic`] with severity `Warning`. To use the warning
/// you will need to add it to a sink, likely inside the [`Engine`], e.g.
/// `engine.sink.warn(warning!(...))`.
///
/// If you want to return early or construct an error, consider the `bail!` or
/// `error!` macros instead.
///
/// You can also add hints by separating the initial message with a semicolon
/// and writing `hint: "..."`, see the example.
///
/// ```ignore
/// warning!(span, "warning with a {} message", "formatted");
/// warning!(
/// span, "warning with a {} message", "formatted";
/// hint: "with multiple hints";
/// hint: "the hints can have {} too", "formatting";
/// );
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! __warning {
(
$span:expr, $fmt:literal $(, $arg:expr)* $(,)?
$(; hint: $hint:literal $(, $hint_arg:expr)*)*
$(;)?
) => {
$crate::diag::SourceDiagnostic::warning(
$span,
$crate::diag::eco_format!($fmt $(, $arg)*)
) $(.with_hint($crate::diag::eco_format!($hint $(, $hint_arg)*)))*
};
}
#[rustfmt::skip]
#[doc(inline)]
pub use {
crate::__bail as bail,
crate::__error as error,
crate::__warning as warning,
ecow::{eco_format, EcoString},
};
/// A result that can carry multiple source errors. The recommended way to
/// create an error for this type is with the `bail!` macro.
pub type SourceResult<T> = Result<T, EcoVec<SourceDiagnostic>>;
/// An output alongside warnings generated while producing it.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Warned<T> {
/// The produced output.
pub output: T,
/// Warnings generated while producing the output.
pub warnings: EcoVec<SourceDiagnostic>,
}
impl<T> Warned<T> {
/// Maps the output, keeping the same warnings.
pub fn map<R, F: FnOnce(T) -> R>(self, f: F) -> Warned<R> {
Warned { output: f(self.output), warnings: self.warnings }
}
}
/// An error or warning in a source or text file. The recommended way to create
/// one is with the `error!` or `warning!` macros.
///
/// The contained spans will only be detached if any of the input source files
/// were detached.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct SourceDiagnostic {
/// Whether the diagnostic is an error or a warning.
pub severity: Severity,
/// The span of the relevant node in the source code.
pub span: Span,
/// A diagnostic message describing the problem.
pub message: EcoString,
/// The trace of function calls leading to the problem.
pub trace: EcoVec<Spanned<Tracepoint>>,
/// Additional hints to the user.
///
/// - When the span is detached, these are generic hints. The CLI renders
/// them as a list at the bottom, each prefixed with `hint: `.
///
/// - When a span is given, the hint is related to a secondary piece of code
/// and will be annotated at that code.
pub hints: EcoVec<Spanned<EcoString>>,
}
/// The severity of a [`SourceDiagnostic`].
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Severity {
/// A fatal error.
Error,
/// A non-fatal warning.
Warning,
}
impl SourceDiagnostic {
/// Create a new, bare error.
pub fn error(span: Span, message: impl Into<EcoString>) -> Self {
Self {
severity: Severity::Error,
span,
trace: eco_vec![],
message: message.into(),
hints: eco_vec![],
}
}
/// Create a new, bare warning.
pub fn warning(span: Span, message: impl Into<EcoString>) -> Self {
Self {
severity: Severity::Warning,
span,
trace: eco_vec![],
message: message.into(),
hints: eco_vec![],
}
}
/// Adds a single hint to the diagnostic.
pub fn hint(&mut self, hint: impl Into<EcoString>) {
self.hints.push(Spanned::detached(hint.into()));
}
/// Adds a single hint specific to a source code location to the diagnostic.
pub fn spanned_hint(&mut self, hint: impl Into<EcoString>, span: Span) {
self.hints.push(Spanned::new(hint.into(), span));
}
/// Adds a single hint to the diagnostic.
pub fn with_hint(mut self, hint: impl Into<EcoString>) -> Self {
self.hint(hint);
self
}
/// Adds a single hint specific to a source code location to the diagnostic.
pub fn with_spanned_hint(mut self, hint: impl Into<EcoString>, span: Span) -> Self {
self.spanned_hint(hint, span);
self
}
/// Adds multiple user-facing hints to the diagnostic.
pub fn with_hints(mut self, hints: impl IntoIterator<Item = EcoString>) -> Self {
self.hints.extend(hints.into_iter().map(Spanned::detached));
self
}
/// Adds a single tracepoint to the diagnostic.
pub fn with_tracepoint(mut self, tracepoint: Tracepoint, span: Span) -> Self {
self.trace.push(Spanned::new(tracepoint, span));
self
}
}
impl From<SyntaxError> for SourceDiagnostic {
fn from(error: SyntaxError) -> Self {
Self {
severity: Severity::Error,
span: error.span,
message: error.message,
trace: eco_vec![],
hints: error.hints.into_iter().map(Spanned::detached).collect(),
}
}
}
/// Destination for a deprecation message when accessing a deprecated value.
pub trait DeprecationSink {
/// Emits the given deprecation message into this sink alongside a version
/// in which the deprecated item is planned to be removed.
fn emit(self, message: &str, until: Option<&str>);
}
impl DeprecationSink for () {
fn emit(self, _: &str, _: Option<&str>) {}
}
impl DeprecationSink for (&mut Engine<'_>, Span) {
/// Emits the deprecation message as a warning.
fn emit(self, message: &str, version: Option<&str>) {
self.0
.sink
.warn(SourceDiagnostic::warning(self.1, message).with_hints(
version.map(|v| eco_format!("it will be removed in Typst {}", v)),
));
}
}
/// A part of a diagnostic's [trace](SourceDiagnostic::trace).
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Tracepoint {
/// A function call.
Call(Option<EcoString>),
/// A show rule application.
Show(EcoString),
/// A module import.
Import,
}
impl Display for Tracepoint {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Tracepoint::Call(Some(name)) => {
write!(f, "error occurred in this call of function `{name}`")
}
Tracepoint::Call(None) => {
write!(f, "error occurred in this function call")
}
Tracepoint::Show(name) => {
write!(f, "error occurred while applying show rule to this {name}")
}
Tracepoint::Import => {
write!(f, "error occurred while importing this module")
}
}
}
}
/// Enrich a [`SourceResult`] with a tracepoint.
pub trait Trace<T> {
/// Add the tracepoint to all errors that lie outside the `span`.
fn trace<F>(self, world: Tracked<dyn World + '_>, make_point: F, span: Span) -> Self
where
F: Fn() -> Tracepoint;
}
impl<T> Trace<T> for SourceResult<T> {
fn trace<F>(self, world: Tracked<dyn World + '_>, make_point: F, span: Span) -> Self
where
F: Fn() -> Tracepoint,
{
self.map_err(|mut errors| {
let Some(trace_range) = world.range(span) else { return errors };
for error in errors.make_mut().iter_mut() {
// Skip traces that surround the error.
if let Some(error_range) = world.range(error.span)
&& error.span.id() == span.id()
&& trace_range.start <= error_range.start
&& trace_range.end >= error_range.end
{
continue;
}
error.trace.push(Spanned::new(make_point(), span));
}
errors
})
}
}
/// A result type with a string error message. The recommended way to create an
/// error for this type is with the [`bail!`] macro.
pub type StrResult<T> = Result<T, EcoString>;
/// Convert a [`StrResult`] or [`HintedStrResult`] to a [`SourceResult`] by
/// adding span information.
pub trait At<T> {
/// Add the span information.
fn at(self, span: Span) -> SourceResult<T>;
}
impl<T, S> At<T> for Result<T, S>
where
S: Into<EcoString>,
{
fn at(self, span: Span) -> SourceResult<T> {
self.map_err(|message| {
let mut diagnostic = SourceDiagnostic::error(span, message);
if diagnostic.message.contains("(access denied)") {
diagnostic.hint("cannot read file outside of project root");
diagnostic
.hint("you can adjust the project root with the --root argument");
}
eco_vec![diagnostic]
})
}
}
/// A result type with a string error message and hints. The recommended way to
/// create an error for this type is with the `bail!` macro.
pub type HintedStrResult<T> = Result<T, HintedString>;
/// A string message with hints. The recommended way to create one is with the
/// `error!` macro.
///
/// This is internally represented by a vector of strings.
/// - The first element of the vector contains the message.
/// - The remaining elements are the hints.
/// - This is done to reduce the size of a HintedString.
/// - The vector is guaranteed to not be empty.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct HintedString(EcoVec<EcoString>);
impl HintedString {
/// Creates a new hinted string with the given message.
pub fn new(message: EcoString) -> Self {
Self(eco_vec![message])
}
/// A diagnostic message describing the problem.
pub fn message(&self) -> &EcoString {
self.0.first().unwrap()
}
/// Additional hints to the user, indicating how this error could be avoided
/// or worked around.
pub fn hints(&self) -> &[EcoString] {
self.0.get(1..).unwrap_or(&[])
}
/// Adds a single hint to the hinted string.
pub fn hint(&mut self, hint: impl Into<EcoString>) {
self.0.push(hint.into());
}
/// Adds a single hint to the hinted string.
pub fn with_hint(mut self, hint: impl Into<EcoString>) -> Self {
self.hint(hint);
self
}
/// Adds user-facing hints to the hinted string.
pub fn with_hints(mut self, hints: impl IntoIterator<Item = EcoString>) -> Self {
self.0.extend(hints);
self
}
}
impl<S> From<S> for HintedString
where
S: Into<EcoString>,
{
fn from(value: S) -> Self {
Self::new(value.into())
}
}
impl<T> At<T> for HintedStrResult<T> {
fn at(self, span: Span) -> SourceResult<T> {
self.map_err(|err| {
let mut components = err.0.into_iter();
let message = components.next().unwrap();
let diag = SourceDiagnostic::error(span, message).with_hints(components);
eco_vec![diag]
})
}
}
/// Enrich a [`StrResult`] or [`HintedStrResult`] with a hint.
pub trait Hint<T> {
/// Add the hint.
fn hint(self, hint: impl Into<EcoString>) -> HintedStrResult<T>;
}
impl<T, S> Hint<T> for Result<T, S>
where
S: Into<EcoString>,
{
fn hint(self, hint: impl Into<EcoString>) -> HintedStrResult<T> {
self.map_err(|message| HintedString::new(message.into()).with_hint(hint))
}
}
impl<T> Hint<T> for HintedStrResult<T> {
fn hint(self, hint: impl Into<EcoString>) -> HintedStrResult<T> {
self.map_err(|mut error| {
error.hint(hint.into());
error
})
}
}
/// A result type with a file-related error.
pub type FileResult<T> = Result<T, FileError>;
/// An error that occurred while trying to load of a file.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum FileError {
/// A file was not found at this path.
NotFound(PathBuf),
/// A file could not be accessed.
AccessDenied,
/// A directory was found, but a file was expected.
IsDirectory,
/// The file is not a Typst source file, but should have been.
NotSource,
/// The file was not valid UTF-8, but should have been.
InvalidUtf8,
/// The package the file is part of could not be loaded.
Package(PackageError),
/// Another error.
///
/// The optional string can give more details, if available.
Other(Option<EcoString>),
}
impl FileError {
/// Create a file error from an I/O error.
pub fn from_io(err: io::Error, path: &Path) -> Self {
match err.kind() {
io::ErrorKind::NotFound => Self::NotFound(path.into()),
io::ErrorKind::PermissionDenied => Self::AccessDenied,
io::ErrorKind::InvalidData
if err.to_string().contains("stream did not contain valid UTF-8") =>
{
Self::InvalidUtf8
}
_ => Self::Other(Some(eco_format!("{err}"))),
}
}
}
impl std::error::Error for FileError {}
impl Display for FileError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::NotFound(path) => {
write!(f, "file not found (searched at {})", path.display())
}
Self::AccessDenied => f.pad("failed to load file (access denied)"),
Self::IsDirectory => f.pad("failed to load file (is a directory)"),
Self::NotSource => f.pad("not a Typst source file"),
Self::InvalidUtf8 => f.pad("file is not valid UTF-8"),
Self::Package(error) => error.fmt(f),
Self::Other(Some(err)) => write!(f, "failed to load file ({err})"),
Self::Other(None) => f.pad("failed to load file"),
}
}
}
impl From<Utf8Error> for FileError {
fn from(_: Utf8Error) -> Self {
Self::InvalidUtf8
}
}
impl From<FromUtf8Error> for FileError {
fn from(_: FromUtf8Error) -> Self {
Self::InvalidUtf8
}
}
impl From<PackageError> for FileError {
fn from(err: PackageError) -> Self {
Self::Package(err)
}
}
impl From<FileError> for EcoString {
fn from(err: FileError) -> Self {
eco_format!("{err}")
}
}
/// A result type with a package-related error.
pub type PackageResult<T> = Result<T, PackageError>;
/// An error that occurred while trying to load a package.
///
/// Some variants have an optional string can give more details, if available.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum PackageError {
/// The specified package does not exist.
NotFound(PackageSpec),
/// The specified package found, but the version does not exist.
VersionNotFound(PackageSpec, PackageVersion),
/// Failed to retrieve the package through the network.
NetworkFailed(Option<EcoString>),
/// The package archive was malformed.
MalformedArchive(Option<EcoString>),
/// Another error.
Other(Option<EcoString>),
}
impl std::error::Error for PackageError {}
impl Display for PackageError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::NotFound(spec) => {
write!(f, "package not found (searched for {spec})",)
}
Self::VersionNotFound(spec, latest) => {
write!(
f,
"package found, but version {} does not exist (latest is {})",
spec.version, latest,
)
}
Self::NetworkFailed(Some(err)) => {
write!(f, "failed to download package ({err})")
}
Self::NetworkFailed(None) => f.pad("failed to download package"),
Self::MalformedArchive(Some(err)) => {
write!(f, "failed to decompress package ({err})")
}
Self::MalformedArchive(None) => {
f.pad("failed to decompress package (archive malformed)")
}
Self::Other(Some(err)) => write!(f, "failed to load package ({err})"),
Self::Other(None) => f.pad("failed to load package"),
}
}
}
impl From<PackageError> for EcoString {
fn from(err: PackageError) -> Self {
eco_format!("{err}")
}
}
/// A result type with a data-loading-related error.
pub type LoadResult<T> = Result<T, LoadError>;
/// A call site independent error that occurred during data loading. This avoids
/// polluting the memoization with [`Span`]s and [`FileId`]s from source files.
/// Can be turned into a [`SourceDiagnostic`] using the [`LoadedWithin::within`]
/// method available on [`LoadResult`].
///
/// [`FileId`]: typst_syntax::FileId
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct LoadError {
/// The position in the file at which the error occurred.
pos: ReportPos,
/// Must contain a message formatted like this: `"failed to do thing (cause)"`.
message: EcoString,
}
impl LoadError {
/// Creates a new error from a position in a file, a base message
/// (e.g. `failed to parse JSON`) and a concrete error (e.g. `invalid
/// number`)
pub fn new(
pos: impl Into<ReportPos>,
message: impl std::fmt::Display,
error: impl std::fmt::Display,
) -> Self {
Self {
pos: pos.into(),
message: eco_format!("{message} ({error})"),
}
}
}
impl From<Utf8Error> for LoadError {
fn from(err: Utf8Error) -> Self {
let start = err.valid_up_to();
let end = start + err.error_len().unwrap_or(0);
LoadError::new(
start..end,
"failed to convert to string",
"file is not valid UTF-8",
)
}
}
/// Convert a [`LoadError`] or compatible [`Result`] to a [`SourceDiagnostic`]
/// or [`SourceResult`] by adding the [`Loaded`] context.
pub trait LoadedWithin {
/// The enriched type that has the context factored in.
type Output;
/// Report an error, possibly in an external file.
fn within(self, loaded: &Loaded) -> Self::Output;
}
impl<E> LoadedWithin for E
where
E: Into<LoadError>,
{
type Output = SourceDiagnostic;
fn within(self, loaded: &Loaded) -> Self::Output {
let LoadError { pos, message } = self.into();
load_err_in_text(loaded, pos, message)
}
}
impl<T, E> LoadedWithin for Result<T, E>
where
E: Into<LoadError>,
{
type Output = SourceResult<T>;
fn within(self, loaded: &Loaded) -> Self::Output {
self.map_err(|err| eco_vec![err.within(loaded)])
}
}
/// Report an error, possibly in an external file. This will delegate to
/// [`load_err_in_invalid_text`] if the data isn't valid UTF-8.
fn load_err_in_text(
loaded: &Loaded,
pos: impl Into<ReportPos>,
mut message: EcoString,
) -> SourceDiagnostic {
let pos = pos.into();
// This also does UTF-8 validation. Only report an error in an external
// file if it is human readable (valid UTF-8), otherwise fall back to
// `load_err_in_invalid_text`.
let lines = Lines::try_from(&loaded.data);
match (loaded.source.v, lines) {
(LoadSource::Path(file_id), Ok(lines)) => {
if let Some(range) = pos.range(&lines) {
let span = Span::from_range(file_id, range);
return SourceDiagnostic::error(span, message);
}
// Either `ReportPos::None` was provided, or resolving the range
// from the line/column failed. If present report the possibly
// wrong line/column in the error message anyway.
let span = Span::from_range(file_id, 0..loaded.data.len());
if let Some(pair) = pos.line_col(&lines) {
message.pop();
let (line, col) = pair.numbers();
write!(&mut message, " at {line}:{col})").ok();
}
SourceDiagnostic::error(span, message)
}
(LoadSource::Bytes, Ok(lines)) => {
if let Some(pair) = pos.line_col(&lines) {
message.pop();
let (line, col) = pair.numbers();
write!(&mut message, " at {line}:{col})").ok();
}
SourceDiagnostic::error(loaded.source.span, message)
}
_ => load_err_in_invalid_text(loaded, pos, message),
}
}
/// Report an error (possibly from an external file) that isn't valid UTF-8.
fn load_err_in_invalid_text(
loaded: &Loaded,
pos: impl Into<ReportPos>,
mut message: EcoString,
) -> SourceDiagnostic {
let line_col = pos.into().try_line_col(&loaded.data).map(|p| p.numbers());
match (loaded.source.v, line_col) {
(LoadSource::Path(file), _) => {
message.pop();
if let Some(package) = file.package() {
write!(
&mut message,
" in {package}{}",
file.vpath().as_rooted_path().display()
)
.ok();
} else {
write!(&mut message, " in {}", file.vpath().as_rootless_path().display())
.ok();
};
if let Some((line, col)) = line_col {
write!(&mut message, ":{line}:{col}").ok();
}
message.push(')');
}
(LoadSource::Bytes, Some((line, col))) => {
message.pop();
write!(&mut message, " at {line}:{col})").ok();
}
(LoadSource::Bytes, None) => (),
}
SourceDiagnostic::error(loaded.source.span, message)
}
/// A position at which an error was reported.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub enum ReportPos {
/// Contains a range, and a line/column pair.
Full(std::ops::Range<u32>, LineCol),
/// Contains a range.
Range(std::ops::Range<u32>),
/// Contains a line/column pair.
LineCol(LineCol),
#[default]
None,
}
impl From<std::ops::Range<usize>> for ReportPos {
fn from(value: std::ops::Range<usize>) -> Self {
Self::Range(value.start.saturating_as()..value.end.saturating_as())
}
}
impl From<LineCol> for ReportPos {
fn from(value: LineCol) -> Self {
Self::LineCol(value)
}
}
impl ReportPos {
/// Creates a position from a pre-existing range and line-column pair.
pub fn full(range: std::ops::Range<usize>, pair: LineCol) -> Self {
let range = range.start.saturating_as()..range.end.saturating_as();
Self::Full(range, pair)
}
/// Tries to determine the byte range for this position.
fn range(&self, lines: &Lines<String>) -> Option<std::ops::Range<usize>> {
match self {
ReportPos::Full(range, _) => Some(range.start as usize..range.end as usize),
ReportPos::Range(range) => Some(range.start as usize..range.end as usize),
&ReportPos::LineCol(pair) => {
let i =
lines.line_column_to_byte(pair.line as usize, pair.col as usize)?;
Some(i..i)
}
ReportPos::None => None,
}
}
/// Tries to determine the line/column for this position.
fn line_col(&self, lines: &Lines<String>) -> Option<LineCol> {
match self {
&ReportPos::Full(_, pair) => Some(pair),
ReportPos::Range(range) => {
let (line, col) = lines.byte_to_line_column(range.start as usize)?;
Some(LineCol::zero_based(line, col))
}
&ReportPos::LineCol(pair) => Some(pair),
ReportPos::None => None,
}
}
/// Either gets the line/column pair, or tries to compute it from possibly
/// invalid UTF-8 data.
fn try_line_col(&self, bytes: &[u8]) -> Option<LineCol> {
match self {
&ReportPos::Full(_, pair) => Some(pair),
ReportPos::Range(range) => {
LineCol::try_from_byte_pos(range.start as usize, bytes)
}
&ReportPos::LineCol(pair) => Some(pair),
ReportPos::None => None,
}
}
}
/// A line/column pair.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct LineCol {
/// The 0-based line.
line: u32,
/// The 0-based column.
col: u32,
}
impl LineCol {
/// Constructs the line/column pair from 0-based indices.
pub fn zero_based(line: usize, col: usize) -> Self {
Self {
line: line.saturating_as(),
col: col.saturating_as(),
}
}
/// Constructs the line/column pair from 1-based numbers.
pub fn one_based(line: usize, col: usize) -> Self {
Self::zero_based(line.saturating_sub(1), col.saturating_sub(1))
}
/// Try to compute a line/column pair from possibly invalid UTF-8 data.
pub fn try_from_byte_pos(pos: usize, bytes: &[u8]) -> Option<Self> {
let bytes = &bytes[..pos];
let mut line = 0;
#[allow(clippy::double_ended_iterator_last)]
let line_start = memchr::memchr_iter(b'\n', bytes)
.inspect(|_| line += 1)
.last()
.map(|i| i + 1)
.unwrap_or(bytes.len());
let col = ErrorReportingUtf8Chars::new(&bytes[line_start..]).count();
Some(LineCol::zero_based(line, col))
}
/// Returns the 0-based line/column indices.
pub fn indices(&self) -> (usize, usize) {
(self.line as usize, self.col as usize)
}
/// Returns the 1-based line/column numbers.
pub fn numbers(&self) -> (usize, usize) {
(self.line as usize + 1, self.col as usize + 1)
}
}
/// Format a user-facing error message for an XML-like file format.
pub fn format_xml_like_error(format: &str, error: roxmltree::Error) -> LoadError {
let pos = LineCol::one_based(error.pos().row as usize, error.pos().col as usize);
let message = match error {
roxmltree::Error::UnexpectedCloseTag(expected, actual, _) => {
eco_format!(
"failed to parse {format} (found closing tag '{actual}' instead of '{expected}')"
)
}
roxmltree::Error::UnknownEntityReference(entity, _) => {
eco_format!("failed to parse {format} (unknown entity '{entity}')")
}
roxmltree::Error::DuplicatedAttribute(attr, _) => {
eco_format!("failed to parse {format} (duplicate attribute '{attr}')")
}
roxmltree::Error::NoRootNode => {
eco_format!("failed to parse {format} (missing root node)")
}
err => eco_format!("failed to parse {format} ({err})"),
};
LoadError { pos: pos.into(), message }
}
/// Asserts a condition, generating an internal compiler error with the provided
/// message on failure.
#[track_caller]
pub fn assert_internal(cond: bool, msg: &str) -> HintedStrResult<()> {
if !cond { Err(internal_error(msg)) } else { Ok(()) }
}
/// Generates an internal compiler error with the provided message.
#[track_caller]
pub fn panic_internal(msg: &str) -> HintedStrResult<()> {
Err(internal_error(msg))
}
/// Adds a method analogous to [`Option::expect`] that raises an internal
/// compiler error instead of panicking.
pub trait ExpectInternal<T> {
/// Extracts the value, producing an internal error if `self` is `None`.
fn expect_internal(self, msg: &str) -> HintedStrResult<T>;
}
impl<T> ExpectInternal<T> for Option<T> {
#[track_caller]
fn expect_internal(self, msg: &str) -> HintedStrResult<T> {
match self {
Some(val) => Ok(val),
None => Err(internal_error(msg)),
}
}
}
/// The shared internal implementation of [`assert_internal`] and
/// [`expect_internal`].
#[track_caller]
fn internal_error(msg: &str) -> HintedString {
let loc = std::panic::Location::caller();
let mut error = error!(
"internal error: {msg} (occurred at {loc})";
hint: "please report this as a bug"
);
if cfg!(debug_assertions) {
let backtrace = Backtrace::capture();
if backtrace.status() == BacktraceStatus::Captured {
error.hint(eco_format!("compiler backtrace:\n{backtrace}"));
} else {
error.hint("set `RUST_BACKTRACE` to `1` or `full` to capture a backtrace");
}
}
error
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/pdf/mod.rs | crates/typst-library/src/pdf/mod.rs | //! PDF-specific functionality.
mod accessibility;
mod attach;
pub use self::accessibility::*;
pub use self::attach::*;
use crate::foundations::{Deprecation, Element, Module, Scope};
use crate::{Feature, Features};
/// Hook up all `pdf` definitions.
pub fn module(features: &Features) -> Module {
let mut pdf = Scope::deduplicating();
pdf.start_category(crate::Category::Pdf);
pdf.define_elem::<AttachElem>();
pdf.define("embed", Element::of::<AttachElem>()).deprecated(
// Remember to remove "embed" from `path_completion` when removing this.
Deprecation::new()
.with_message("the name `embed` is deprecated, use `attach` instead")
.with_until("0.15.0"),
);
pdf.define_elem::<ArtifactElem>();
if features.is_enabled(Feature::A11yExtras) {
pdf.define_func::<table_summary>();
pdf.define_func::<header_cell>();
pdf.define_func::<data_cell>();
}
Module::new("pdf", pdf)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/pdf/accessibility.rs | crates/typst-library/src/pdf/accessibility.rs | use std::num::NonZeroU32;
use ecow::EcoString;
use typst_macros::{Cast, elem, func};
use typst_utils::NonZeroExt;
use crate::diag::SourceResult;
use crate::diag::bail;
use crate::engine::Engine;
use crate::foundations::{Args, Construct, Content, NativeElement, Smart};
use crate::introspection::Tagged;
use crate::model::{TableCell, TableElem};
/// Marks content as a PDF artifact.
///
/// Artifacts are parts of the document that are not meant to be read by
/// Assistive Technology (AT), such as screen readers. Typical examples include
/// purely decorative images that do not contribute to the meaning of the
/// document, watermarks, or repeated content such as page numbers.
///
/// Typst will automatically mark certain content, such as page headers,
/// footers, backgrounds, and foregrounds, as artifacts. Likewise, paths and
/// shapes are automatically marked as artifacts, but their content is not.
/// Repetitions of table headers and footers are also marked as artifacts.
///
/// Once something is marked as an artifact, you cannot make any of its
/// contents accessible again. If you need to mark only part of something as an
/// artifact, you may need to use this function multiple times.
///
/// If you are unsure what constitutes an artifact, check the [Accessibility
/// Guide]($guides/accessibility/#artifacts).
///
/// In the future, this function may be moved out of the `pdf` module, making it
/// possible to hide content in HTML export from AT.
// TODO: maybe generalize this and use it to mark html elements with `aria-hidden="true"`?
#[elem(Tagged)]
pub struct ArtifactElem {
/// The artifact kind.
///
/// This will govern how the PDF reader treats the artifact during reflow
/// and content extraction (e.g. copy and paste).
#[default(ArtifactKind::Other)]
pub kind: ArtifactKind,
/// The content that is an artifact.
#[required]
pub body: Content,
}
/// The type of artifact.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum ArtifactKind {
/// Repeats on the top of each page.
Header,
/// Repeats at the bottom of each page.
Footer,
/// Not part of the document, but rather the page it is printed on. An
/// example would be cut marks or color bars.
Page,
/// Other artifacts, including purely cosmetic content, backgrounds,
/// watermarks, and repeated content.
#[default]
Other,
}
/// A summary of the purpose and structure of a complex table.
///
/// This will be available for Assistive Technology (AT), such as screen
/// readers, when exporting to PDF, but not for sighted readers of your file.
///
/// This field is intended for instructions that help the user navigate the
/// table using AT. It is not an alternative description, so do not duplicate
/// the contents of the table within. Likewise, do not use this for the core
/// takeaway of the table. Instead, include that in the text around the table
/// or, even better, in a [figure caption]($figure.caption).
///
/// If in doubt whether your table is complex enough to warrant a summary, err
/// on the side of not including one. If you are certain that your table is
/// complex enough, consider whether a sighted user might find it challenging.
/// They might benefit from the instructions you put here, so consider printing
/// them visibly in the document instead.
///
/// The API of this feature is temporary. Hence, calling this function requires
/// enabling the `a11y-extras` feature flag at the moment. Even if this
/// functionality should be available without a feature flag in the future, the
/// summary will remain exclusive to PDF export.
///
/// ```example
/// #figure(
/// pdf.table-summary(
/// // The summary just provides orientation and structural
/// // information for AT users.
/// summary: "The first two columns list the names of each participant. The last column contains cells spanning multiple rows for their assigned group.",
/// table(
/// columns: 3,
/// table.header[First Name][Given Name][Group],
/// [Mike], [Davis], table.cell(rowspan: 3)[Sales],
/// [Anna], [Smith],
/// [John], [Johnson],
/// [Sara], [Wilkins], table.cell(rowspan: 2)[Operations],
/// [Tom], [Brown],
/// ),
/// ),
/// // This is the key takeaway of the table, so we put it in the caption.
/// caption: [The Sales org now has a new member],
/// )
/// ```
#[func]
pub fn table_summary(
#[named] summary: Option<EcoString>,
/// The table.
table: TableElem,
) -> Content {
table.with_summary(summary).pack()
}
/// Explicitly defines a cell as a header cell.
///
/// Header cells help users of Assistive Technology (AT) understand and navigate
/// complex tables. When your table is correctly marked up with header cells, AT
/// can announce the relevant header information on-demand when entering a cell.
///
/// By default, Typst will automatically mark all cells within [`table.header`]
/// as header cells. They will apply to the columns below them. You can use that
/// function's [`level`]($table.header.level) parameter to make header cells
/// labelled by other header cells.
///
/// The `pdf.header-cell` function allows you to indicate that a cell is a
/// header cell in the following additional situations:
///
/// - You have a **header column** in which each cell applies to its row. In
/// that case, you pass `{"row"}` as an argument to the [`scope`
/// parameter]($pdf.header-cell.scope) to indicate that the header cell
/// applies to the row.
/// - You have a cell in [`table.header`], for example at the very start, that
/// labels both its row and column. In that case, you pass `{"both"}` as an
/// argument to the [`scope`]($pdf.header-cell.scope) parameter.
/// - You have a header cell in a row not containing other header cells. In that
/// case, you can use this function to mark it as a header cell.
///
/// The API of this feature is temporary. Hence, calling this function requires
/// enabling the `a11y-extras` feature flag at the moment. In a future Typst
/// release, this functionality may move out of the `pdf` module so that tables
/// in other export targets can contain the same information.
///
/// ```example
/// >>> #set text(font: "IBM Plex Sans")
/// #show table.cell.where(x: 0): set text(weight: "medium")
/// #show table.cell.where(y: 0): set text(weight: "bold")
///
/// #table(
/// columns: 3,
/// align: (start, end, end),
///
/// table.header(
/// // Top-left cell: Labels both the nutrient rows
/// // and the serving size columns.
/// pdf.header-cell(scope: "both")[Nutrient],
/// [Per 100g],
/// [Per Serving],
/// ),
///
/// // First column cells are row headers
/// pdf.header-cell(scope: "row")[Calories],
/// [250 kcal], [375 kcal],
/// pdf.header-cell(scope: "row")[Protein],
/// [8g], [12g],
/// pdf.header-cell(scope: "row")[Fat],
/// [12g], [18g],
/// pdf.header-cell(scope: "row")[Carbs],
/// [30g], [45g],
/// )
/// ```
#[func]
pub fn header_cell(
/// The nesting level of this header cell.
#[named]
#[default(NonZeroU32::ONE)]
level: NonZeroU32,
/// What track of the table this header cell applies to.
#[named]
#[default]
scope: TableHeaderScope,
/// The table cell.
///
/// This can be content or a call to [`table.cell`].
cell: TableCell,
) -> Content {
cell.with_kind(Smart::Custom(TableCellKind::Header(level, scope)))
.pack()
}
/// Explicitly defines this cell as a data cell.
///
/// Each cell in a table is either a header cell or a data cell. By default, all
/// cells in [`table.header`] are header cells, and all other cells data cells.
///
/// If your header contains a cell that is not a header cell, you can use this
/// function to mark it as a data cell.
///
/// The API of this feature is temporary. Hence, calling this function requires
/// enabling the `a11y-extras` feature flag at the moment. In a future Typst
/// release, this functionality may move out of the `pdf` module so that tables
/// in other export targets can contain the same information.
///
/// ```example
/// #show table.cell.where(x: 0): set text(weight: "bold")
/// #show table.cell.where(x: 1): set text(style: "italic")
/// #show table.cell.where(x: 1, y: 0): set text(style: "normal")
///
/// #table(
/// columns: 3,
/// align: (left, left, center),
///
/// table.header[Objective][Key Result][Status],
///
/// table.header(
/// level: 2,
/// table.cell(colspan: 2)[Improve Customer Satisfaction],
/// // Status is data for this objective, not a header
/// pdf.data-cell[✓ On Track],
/// ),
/// [], [Increase NPS to 50+], [45],
/// [], [Reduce churn to \<5%], [4.2%],
///
/// table.header(
/// level: 2,
/// table.cell(colspan: 2)[Grow Revenue],
/// pdf.data-cell[⚠ At Risk],
/// ),
/// [], [Achieve \$2M ARR], [\$1.8M],
/// [], [Close 50 enterprise deals], [38],
/// )
/// ```
#[func]
pub fn data_cell(
/// The table cell.
///
/// This can be content or a call to [`table.cell`].
cell: TableCell,
) -> Content {
cell.with_kind(Smart::Custom(TableCellKind::Data)).pack()
}
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum TableCellKind {
Header(NonZeroU32, TableHeaderScope),
Footer,
#[default]
Data,
}
/// Which table track a header cell labels.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum TableHeaderScope {
/// The header cell refers to both the row and the column.
Both,
/// The header cell refers to the column.
#[default]
Column,
/// The header cell refers to the row.
Row,
}
impl TableHeaderScope {
pub fn refers_to_column(&self) -> bool {
match self {
TableHeaderScope::Both => true,
TableHeaderScope::Column => true,
TableHeaderScope::Row => false,
}
}
pub fn refers_to_row(&self) -> bool {
match self {
TableHeaderScope::Both => true,
TableHeaderScope::Column => false,
TableHeaderScope::Row => true,
}
}
}
/// Used to delimit content for tagged PDF.
#[elem(Construct, Tagged)]
pub struct PdfMarkerTag {
#[internal]
#[required]
pub kind: PdfMarkerTagKind,
#[required]
pub body: Content,
}
impl Construct for PdfMarkerTag {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
macro_rules! pdf_marker_tag {
($(#[doc = $doc:expr] $variant:ident$(($($name:ident: $ty:ty)+))?,)+) => {
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum PdfMarkerTagKind {
$(
#[doc = $doc]
$variant $(($($ty),+))?
),+
}
impl PdfMarkerTag {
$(
#[doc = $doc]
#[allow(non_snake_case)]
pub fn $variant($($($name: $ty,)+)? body: Content) -> Content {
let span = body.span();
Self {
kind: PdfMarkerTagKind::$variant $(($($name),+))?,
body,
}.pack().spanned(span)
}
)+
}
}
}
pdf_marker_tag! {
/// `TOC`.
OutlineBody,
/// `L` bibliography list.
Bibliography(numbered: bool),
/// `LBody` wrapping `BibEntry`.
BibEntry,
/// `Lbl` (marker) of the list item.
ListItemLabel,
/// `LBody` of the list item.
ListItemBody,
/// `Lbl` of the term item.
TermsItemLabel,
/// `LBody` the term item including the label.
TermsItemBody,
/// A generic `Lbl`.
Label,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/pdf/attach.rs | crates/typst-library/src/pdf/attach.rs | use ecow::EcoString;
use typst_syntax::Spanned;
use crate::World;
use crate::diag::At;
use crate::foundations::{Bytes, Cast, Derived, elem};
use crate::introspection::Locatable;
/// A file that will be attached to the output PDF.
///
/// This can be used to distribute additional files associated with the PDF
/// within it. PDF readers will display the files in a file listing.
///
/// Some international standards use this mechanism to attach machine-readable
/// data (e.g., ZUGFeRD/Factur-X for invoices) that mirrors the visual content
/// of the PDF.
///
/// # Example
/// ```typ
/// #pdf.attach(
/// "experiment.csv",
/// relationship: "supplement",
/// mime-type: "text/csv",
/// description: "Raw Oxygen readings from the Arctic experiment",
/// )
/// ```
///
/// # Notes
/// - This element is ignored if exporting to a format other than PDF.
/// - File attachments are not currently supported for PDF/A-2, even if the
/// attached file conforms to PDF/A-1 or PDF/A-2.
#[elem(keywords = ["embed"], Locatable)]
pub struct AttachElem {
/// The [path]($syntax/#paths) of the file to be attached.
///
/// Must always be specified, but is only read from if no data is provided
/// in the following argument.
#[required]
#[parse(
let Spanned { v: path, span } =
args.expect::<Spanned<EcoString>>("path")?;
let id = span.resolve_path(&path).at(span)?;
// The derived part is the project-relative resolved path.
let resolved = id.vpath().as_rootless_path().to_string_lossy().replace("\\", "/").into();
Derived::new(path.clone(), resolved)
)]
pub path: Derived<EcoString, EcoString>,
/// Raw file data, optionally.
///
/// If omitted, the data is read from the specified path.
#[positional]
// Not actually required as an argument, but always present as a field.
// We can't distinguish between the two at the moment.
#[required]
#[parse(
match args.eat::<Bytes>()? {
Some(data) => data,
None => engine.world.file(id).at(span)?,
}
)]
pub data: Bytes,
/// The relationship of the attached file to the document.
///
/// Ignored if export doesn't target PDF/A-3.
pub relationship: Option<AttachedFileRelationship>,
/// The MIME type of the attached file.
pub mime_type: Option<EcoString>,
/// A description for the attached file.
pub description: Option<EcoString>,
}
/// The relationship of an attached file with the document.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum AttachedFileRelationship {
/// The PDF document was created from the source file.
Source,
/// The file was used to derive a visual presentation in the PDF.
Data,
/// An alternative representation of the document.
Alternative,
/// Additional resources for the document.
Supplement,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/none.rs | crates/typst-library/src/foundations/none.rs | use std::fmt::{self, Debug, Formatter};
use ecow::EcoString;
use serde::{Serialize, Serializer};
use crate::diag::HintedStrResult;
use crate::foundations::{
CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value, cast, ty,
};
/// A value that indicates the absence of any other value.
///
/// The none type has exactly one value: `{none}`.
///
/// When inserted into the document, it is not visible. This is also the value
/// that is produced by empty code blocks. It can be
/// [joined]($scripting/#blocks) with any value, yielding the other value.
///
/// # Example
/// ```example
/// Not visible: #none
/// ```
#[ty(cast, name = "none")]
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NoneValue;
impl Reflect for NoneValue {
fn input() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn output() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn castable(value: &Value) -> bool {
matches!(value, Value::None)
}
}
impl IntoValue for NoneValue {
fn into_value(self) -> Value {
Value::None
}
}
impl FromValue for NoneValue {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
Value::None => Ok(Self),
_ => Err(Self::error(&value)),
}
}
}
impl Debug for NoneValue {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("None")
}
}
impl Repr for NoneValue {
fn repr(&self) -> EcoString {
"none".into()
}
}
impl Serialize for NoneValue {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_none()
}
}
cast! {
(),
self => Value::None,
_: NoneValue => (),
}
impl<T: Reflect> Reflect for Option<T> {
fn input() -> CastInfo {
T::input() + NoneValue::input()
}
fn output() -> CastInfo {
T::output() + NoneValue::output()
}
fn castable(value: &Value) -> bool {
NoneValue::castable(value) || T::castable(value)
}
}
impl<T: IntoValue> IntoValue for Option<T> {
fn into_value(self) -> Value {
match self {
Some(v) => v.into_value(),
None => Value::None,
}
}
}
impl<T: FromValue> FromValue for Option<T> {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
Value::None => Ok(None),
v if T::castable(&v) => Ok(Some(T::from_value(v)?)),
_ => Err(Self::error(&value)),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/array.rs | crates/typst-library/src/foundations/array.rs | use std::cmp::Ordering;
use std::fmt::{Debug, Formatter};
use std::num::{NonZeroI64, NonZeroUsize};
use std::ops::{Add, AddAssign};
use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_format};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use typst_syntax::{Span, Spanned};
use crate::diag::{
At, HintedStrResult, HintedString, SourceDiagnostic, SourceResult, StrResult, bail,
};
use crate::engine::Engine;
use crate::foundations::{
Args, Bytes, CastInfo, Context, Dict, FromValue, Func, IntoValue, Reflect, Repr, Str,
Value, Version, cast, func, ops, repr, scope, ty,
};
/// Create a new [`Array`] from values.
#[macro_export]
#[doc(hidden)]
macro_rules! __array {
($value:expr; $count:expr) => {
$crate::foundations::Array::from($crate::foundations::eco_vec![
$crate::foundations::IntoValue::into_value($value);
$count
])
};
($($value:expr),* $(,)?) => {
$crate::foundations::Array::from($crate::foundations::eco_vec![$(
$crate::foundations::IntoValue::into_value($value)
),*])
};
}
#[doc(inline)]
pub use crate::__array as array;
/// A sequence of values.
///
/// You can construct an array by enclosing a comma-separated sequence of values
/// in parentheses. The values do not have to be of the same type.
///
/// You can access and update array items with the `.at()` method. Indices are
/// zero-based and negative indices wrap around to the end of the array. You can
/// iterate over an array using a [for loop]($scripting/#loops). Arrays can be
/// added together with the `+` operator, [joined together]($scripting/#blocks)
/// and multiplied with integers.
///
/// **Note:** An array of length one needs a trailing comma, as in `{(1,)}`.
/// This is to disambiguate from a simple parenthesized expressions like `{(1 +
/// 2) * 3}`. An empty array is written as `{()}`.
///
/// # Example
/// ```example
/// #let values = (1, 7, 4, -3, 2)
///
/// #values.at(0) \
/// #(values.at(0) = 3)
/// #values.at(-1) \
/// #values.find(calc.even) \
/// #values.filter(calc.odd) \
/// #values.map(calc.abs) \
/// #values.rev() \
/// #(1, (2, 3)).flatten() \
/// #(("A", "B", "C")
/// .join(", ", last: " and "))
/// ```
#[ty(scope, cast)]
#[derive(Default, Clone, PartialEq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Array(EcoVec<Value>);
impl Array {
/// Create a new, empty array.
pub fn new() -> Self {
Self::default()
}
/// Creates a new vec, with a known capacity.
pub fn with_capacity(capacity: usize) -> Self {
Self(EcoVec::with_capacity(capacity))
}
/// Return `true` if the length is 0.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Extract a slice of the whole array.
pub fn as_slice(&self) -> &[Value] {
self.0.as_slice()
}
/// Iterate over references to the contained values.
pub fn iter(&self) -> std::slice::Iter<'_, Value> {
self.0.iter()
}
/// Mutably borrow the first value in the array.
pub fn first_mut(&mut self) -> StrResult<&mut Value> {
self.0.make_mut().first_mut().ok_or_else(array_is_empty)
}
/// Mutably borrow the last value in the array.
pub fn last_mut(&mut self) -> StrResult<&mut Value> {
self.0.make_mut().last_mut().ok_or_else(array_is_empty)
}
/// Mutably borrow the value at the given index.
pub fn at_mut(&mut self, index: i64) -> StrResult<&mut Value> {
let len = self.len();
self.locate_opt(index, false)
.and_then(move |i| self.0.make_mut().get_mut(i))
.ok_or_else(|| out_of_bounds(index, len))
}
/// Resolve an index or throw an out of bounds error.
fn locate(&self, index: i64, end_ok: bool) -> StrResult<usize> {
self.locate_opt(index, end_ok)
.ok_or_else(|| out_of_bounds(index, self.len()))
}
/// Resolve an index, if it is within bounds.
///
/// `index == len` is considered in bounds if and only if `end_ok` is true.
fn locate_opt(&self, index: i64, end_ok: bool) -> Option<usize> {
let wrapped =
if index >= 0 { Some(index) } else { (self.len() as i64).checked_add(index) };
wrapped
.and_then(|v| usize::try_from(v).ok())
.filter(|&v| v < self.0.len() + end_ok as usize)
}
/// Repeat this array `n` times.
pub fn repeat(&self, n: usize) -> StrResult<Self> {
let count = self
.len()
.checked_mul(n)
.ok_or_else(|| format!("cannot repeat this array {n} times"))?;
Ok(self.iter().cloned().cycle().take(count).collect())
}
}
#[scope]
impl Array {
/// Converts a value to an array.
///
/// Note that this function is only intended for conversion of a collection-like
/// value to an array, not for creation of an array from individual items. Use
/// the array syntax `(1, 2, 3)` (or `(1,)` for a single-element array) instead.
///
/// ```example
/// #let hi = "Hello 😃"
/// #array(bytes(hi))
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to an array.
value: ToArray,
) -> Array {
value.0
}
/// The number of values in the array.
#[func(title = "Length")]
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns the first item in the array. May be used on the left-hand side
/// an assignment. Returns the default value if the array is empty
/// or fails with an error is no default value was specified.
#[func]
pub fn first(
&self,
/// A default value to return if the array is empty.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.0.first().cloned().or(default).ok_or_else(array_is_empty)
}
/// Returns the last item in the array. May be used on the left-hand side of
/// an assignment. Returns the default value if the array is empty
/// or fails with an error is no default value was specified.
#[func]
pub fn last(
&self,
/// A default value to return if the array is empty.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.0.last().cloned().or(default).ok_or_else(array_is_empty)
}
/// Returns the item at the specified index in the array. May be used on the
/// left-hand side of an assignment. Returns the default value if the index
/// is out of bounds or fails with an error if no default value was
/// specified.
#[func]
pub fn at(
&self,
/// The index at which to retrieve the item. If negative, indexes from
/// the back.
index: i64,
/// A default value to return if the index is out of bounds.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.locate_opt(index, false)
.and_then(|i| self.0.get(i).cloned())
.or(default)
.ok_or_else(|| out_of_bounds_no_default(index, self.len()))
}
/// Adds a value to the end of the array.
#[func]
pub fn push(
&mut self,
/// The value to insert at the end of the array.
value: Value,
) {
self.0.push(value);
}
/// Removes the last item from the array and returns it. Fails with an error
/// if the array is empty.
#[func]
pub fn pop(&mut self) -> StrResult<Value> {
self.0.pop().ok_or_else(array_is_empty)
}
/// Inserts a value into the array at the specified index, shifting all
/// subsequent elements to the right. Fails with an error if the index is
/// out of bounds.
///
/// To replace an element of an array, use [`at`]($array.at).
#[func]
pub fn insert(
&mut self,
/// The index at which to insert the item. If negative, indexes from
/// the back.
index: i64,
/// The value to insert into the array.
value: Value,
) -> StrResult<()> {
let i = self.locate(index, true)?;
self.0.insert(i, value);
Ok(())
}
/// Removes the value at the specified index from the array and return it.
#[func]
pub fn remove(
&mut self,
/// The index at which to remove the item. If negative, indexes from
/// the back.
index: i64,
/// A default value to return if the index is out of bounds.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.locate_opt(index, false)
.map(|i| self.0.remove(i))
.or(default)
.ok_or_else(|| out_of_bounds_no_default(index, self.len()))
}
/// Extracts a subslice of the array. Fails with an error if the start or end
/// index is out of bounds.
#[func]
pub fn slice(
&self,
/// The start index (inclusive). If negative, indexes from the back.
start: i64,
/// The end index (exclusive). If omitted, the whole slice until the end
/// of the array is extracted. If negative, indexes from the back.
#[default]
end: Option<i64>,
/// The number of items to extract. This is equivalent to passing
/// `start + count` as the `end` position. Mutually exclusive with `end`.
#[named]
count: Option<i64>,
) -> StrResult<Array> {
if end.is_some() && count.is_some() {
bail!("`end` and `count` are mutually exclusive");
}
let start = self.locate(start, true)?;
let end = end.or(count.map(|c| start as i64 + c));
let end = self.locate(end.unwrap_or(self.len() as i64), true)?.max(start);
Ok(self.0[start..end].into())
}
/// Whether the array contains the specified value.
///
/// This method also has dedicated syntax: You can write `{2 in (1, 2, 3)}`
/// instead of `{(1, 2, 3).contains(2)}`.
#[func]
pub fn contains(
&self,
/// The value to search for.
value: Value,
) -> bool {
self.0.contains(&value)
}
/// Searches for an item for which the given function returns `{true}` and
/// returns the first match or `{none}` if there is no match.
#[func]
pub fn find(
&self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item. Must return a boolean.
searcher: Func,
) -> SourceResult<Option<Value>> {
for item in self.iter() {
if searcher
.call(engine, context, [item.clone()])?
.cast::<bool>()
.at(searcher.span())?
{
return Ok(Some(item.clone()));
}
}
Ok(None)
}
/// Searches for an item for which the given function returns `{true}` and
/// returns the index of the first match or `{none}` if there is no match.
#[func]
pub fn position(
&self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item. Must return a boolean.
searcher: Func,
) -> SourceResult<Option<i64>> {
for (i, item) in self.iter().enumerate() {
if searcher
.call(engine, context, [item.clone()])?
.cast::<bool>()
.at(searcher.span())?
{
return Ok(Some(i as i64));
}
}
Ok(None)
}
/// Create an array consisting of a sequence of numbers.
///
/// If you pass just one positional parameter, it is interpreted as the
/// `end` of the range. If you pass two, they describe the `start` and `end`
/// of the range.
///
/// This function is available both in the array function's scope and
/// globally.
///
/// ```example
/// #range(5) \
/// #range(2, 5) \
/// #range(20, step: 4) \
/// #range(21, step: 4) \
/// #range(5, 2, step: -1)
/// ```
#[func]
pub fn range(
args: &mut Args,
/// The start of the range (inclusive).
#[external]
#[default]
start: i64,
/// The end of the range (exclusive).
#[external]
end: i64,
/// The distance between the generated numbers.
#[named]
#[default(NonZeroI64::new(1).unwrap())]
step: NonZeroI64,
) -> SourceResult<Array> {
let first = args.expect::<i64>("end")?;
let (start, end) = match args.eat::<i64>()? {
Some(second) => (first, second),
None => (0, first),
};
let step = step.get();
let mut x = start;
let mut array = Self::new();
while x.cmp(&end) == 0.cmp(&step) {
array.push(x.into_value());
x += step;
}
Ok(array)
}
/// Produces a new array with only the items from the original one for which
/// the given function returns `{true}`.
#[func]
pub fn filter(
&self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item. Must return a boolean.
test: Func,
) -> SourceResult<Array> {
let mut kept = EcoVec::new();
for item in self.iter() {
if test
.call(engine, context, [item.clone()])?
.cast::<bool>()
.at(test.span())?
{
kept.push(item.clone())
}
}
Ok(kept.into())
}
/// Produces a new array in which all items from the original one were
/// transformed with the given function.
#[func]
pub fn map(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item.
mapper: Func,
) -> SourceResult<Array> {
self.into_iter()
.map(|item| mapper.call(engine, context, [item]))
.collect()
}
/// Returns a new array with the values alongside their indices.
///
/// The returned array consists of `(index, value)` pairs in the form of
/// length-2 arrays. These can be [destructured]($scripting/#bindings) with
/// a let binding or for loop.
///
/// ```example
/// #for (i, value) in ("A", "B", "C").enumerate() {
/// [#i: #value \ ]
/// }
///
/// #("A", "B", "C").enumerate(start: 1)
/// ```
#[func]
pub fn enumerate(
self,
/// The index returned for the first pair of the returned list.
#[named]
#[default(0)]
start: i64,
) -> StrResult<Array> {
self.into_iter()
.enumerate()
.map(|(i, value)| {
Ok(array![
start
.checked_add_unsigned(i as u64)
.ok_or("array index is too large")?,
value
]
.into_value())
})
.collect()
}
/// Zips the array with other arrays.
///
/// Returns an array of arrays, where the `i`th inner array contains all the
/// `i`th elements from each original array.
///
/// If the arrays to be zipped have different lengths, they are zipped up to
/// the last element of the shortest array and all remaining elements are
/// ignored.
///
/// This function is variadic, meaning that you can zip multiple arrays
/// together at once: `{(1, 2).zip(("A", "B"), (10, 20))}` yields
/// `{((1, "A", 10), (2, "B", 20))}`.
#[func]
pub fn zip(
self,
args: &mut Args,
/// Whether all arrays have to have the same length.
/// For example, `{(1, 2).zip((1, 2, 3), exact: true)}` produces an
/// error.
#[named]
#[default(false)]
exact: bool,
/// The arrays to zip with.
#[external]
#[variadic]
others: Vec<Array>,
) -> SourceResult<Array> {
let remaining = args.remaining();
// Fast path for one array.
if remaining == 0 {
return Ok(self.into_iter().map(|item| array![item].into_value()).collect());
}
// Fast path for just two arrays.
if remaining == 1 {
let Spanned { v: other, span: other_span } =
args.expect::<Spanned<Array>>("others")?;
if exact && self.len() != other.len() {
bail!(
other_span,
"second array has different length ({}) from first array ({})",
other.len(),
self.len(),
);
}
return Ok(self
.into_iter()
.zip(other)
.map(|(first, second)| array![first, second].into_value())
.collect());
}
// If there is more than one array, we use the manual method.
let mut out = Self::with_capacity(self.len());
let arrays = args.all::<Spanned<Array>>()?;
if exact {
let errs = arrays
.iter()
.filter(|sp| sp.v.len() != self.len())
.map(|Spanned { v, span }| {
SourceDiagnostic::error(
*span,
eco_format!(
"array has different length ({}) from first array ({})",
v.len(),
self.len()
),
)
})
.collect::<EcoVec<_>>();
if !errs.is_empty() {
return Err(errs);
}
}
let mut iterators =
arrays.into_iter().map(|i| i.v.into_iter()).collect::<Vec<_>>();
for this in self {
let mut row = Self::with_capacity(1 + iterators.len());
row.push(this.clone());
for iterator in &mut iterators {
let Some(item) = iterator.next() else {
return Ok(out);
};
row.push(item);
}
out.push(row.into_value());
}
Ok(out)
}
/// Folds all items into a single value using an accumulator function.
///
/// ```example
/// #let array = (1, 2, 3, 4)
/// #array.fold(0, (acc, x) => acc + x)
/// ```
#[func]
pub fn fold(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The initial value to start with.
init: Value,
/// The folding function. Must have two parameters: One for the
/// accumulated value and one for an item.
folder: Func,
) -> SourceResult<Value> {
let mut acc = init;
for item in self {
acc = folder.call(engine, context, [acc, item])?;
}
Ok(acc)
}
/// Sums all items (works for all types that can be added).
#[func]
pub fn sum(
self,
/// What to return if the array is empty. Must be set if the array can
/// be empty.
#[named]
default: Option<Value>,
) -> HintedStrResult<Value> {
let mut iter = self.into_iter();
let mut acc = iter
.next()
.or(default)
.ok_or("cannot calculate sum of empty array with no default")?;
for item in iter {
acc = ops::add(acc, item)?;
}
Ok(acc)
}
/// Calculates the product of all items (works for all types that can be
/// multiplied).
#[func]
pub fn product(
self,
/// What to return if the array is empty. Must be set if the array can
/// be empty.
#[named]
default: Option<Value>,
) -> HintedStrResult<Value> {
let mut iter = self.into_iter();
let mut acc = iter
.next()
.or(default)
.ok_or("cannot calculate product of empty array with no default")?;
for item in iter {
acc = ops::mul(acc, item)?;
}
Ok(acc)
}
/// Whether the given function returns `{true}` for any item in the array.
#[func]
pub fn any(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item. Must return a boolean.
test: Func,
) -> SourceResult<bool> {
for item in self {
if test.call(engine, context, [item])?.cast::<bool>().at(test.span())? {
return Ok(true);
}
}
Ok(false)
}
/// Whether the given function returns `{true}` for all items in the array.
#[func]
pub fn all(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each item. Must return a boolean.
test: Func,
) -> SourceResult<bool> {
for item in self {
if !test.call(engine, context, [item])?.cast::<bool>().at(test.span())? {
return Ok(false);
}
}
Ok(true)
}
/// Combine all nested arrays into a single flat one.
#[func]
pub fn flatten(self) -> Array {
let mut flat = EcoVec::with_capacity(self.0.len());
for item in self {
if let Value::Array(nested) = item {
flat.extend(nested.flatten());
} else {
flat.push(item);
}
}
flat.into()
}
/// Return a new array with the same items, but in reverse order.
#[func(title = "Reverse")]
pub fn rev(self) -> Array {
self.into_iter().rev().collect()
}
/// Split the array at occurrences of the specified value.
///
/// ```example
/// #(1, 1, 2, 3, 2, 4, 5).split(2)
/// ```
#[func]
pub fn split(
&self,
/// The value to split at.
at: Value,
) -> Array {
self.as_slice()
.split(|value| *value == at)
.map(|subslice| Value::Array(subslice.iter().cloned().collect()))
.collect()
}
/// Combine all items in the array into one.
#[func]
pub fn join(
self,
/// A value to insert between each item of the array.
#[default]
separator: Option<Value>,
/// An alternative separator between the last two items.
#[named]
last: Option<Value>,
/// What to return if the array is empty.
#[named]
#[default]
default: Option<Value>,
) -> StrResult<Value> {
let len = self.0.len();
if let Some(result) = default
&& len == 0
{
return Ok(result);
}
let separator = separator.unwrap_or(Value::None);
let mut last = last;
let mut result = Value::None;
for (i, value) in self.into_iter().enumerate() {
if i > 0 {
if i + 1 == len && last.is_some() {
result = ops::join(result, last.take().unwrap())?;
} else {
result = ops::join(result, separator.clone())?;
}
}
result = ops::join(result, value)?;
}
Ok(result)
}
/// Returns an array with a copy of the separator value placed between
/// adjacent elements.
///
/// ```example
/// #("A", "B", "C").intersperse("-")
/// ```
#[func]
pub fn intersperse(
self,
/// The value that will be placed between each adjacent element.
separator: Value,
) -> Array {
// TODO: Use once stabilized:
// https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.intersperse
let size = match self.len() {
0 => return Array::new(),
n => (2 * n) - 1,
};
let mut vec = EcoVec::with_capacity(size);
let mut iter = self.into_iter();
if let Some(first) = iter.next() {
vec.push(first);
}
for value in iter {
vec.push(separator.clone());
vec.push(value);
}
Array(vec)
}
/// Splits an array into non-overlapping chunks, starting at the beginning,
/// ending with a single remainder chunk.
///
/// All chunks but the last have `chunk-size` elements.
/// If `exact` is set to `{true}`, the remainder is dropped if it
/// contains less than `chunk-size` elements.
///
/// ```example
/// #let array = (1, 2, 3, 4, 5, 6, 7, 8)
/// #array.chunks(3) \
/// #array.chunks(3, exact: true)
/// ```
#[func]
pub fn chunks(
self,
/// How many elements each chunk may at most contain.
chunk_size: NonZeroUsize,
/// Whether to keep the remainder if its size is less than `chunk-size`.
#[named]
#[default(false)]
exact: bool,
) -> Array {
let to_array = |chunk| Array::from(chunk).into_value();
if exact {
self.0.chunks_exact(chunk_size.get()).map(to_array).collect()
} else {
self.0.chunks(chunk_size.get()).map(to_array).collect()
}
}
/// Returns sliding windows of `window-size` elements over an array.
///
/// If the array length is less than `window-size`, this will return an empty array.
///
/// ```example
/// #let array = (1, 2, 3, 4, 5, 6, 7, 8)
/// #array.windows(5)
/// ```
#[func]
pub fn windows(
self,
/// How many elements each window will contain.
window_size: NonZeroUsize,
) -> Array {
self.0
.windows(window_size.get())
.map(|window| Array::from(window).into_value())
.collect()
}
/// Return a sorted version of this array, optionally by a given key
/// function. The sorting algorithm used is stable.
///
/// Returns an error if a pair of values selected for comparison could not
/// be compared, or if the key or comparison function (if given) yield an
/// error.
///
/// To sort according to multiple criteria at once, e.g. in case of equality
/// between some criteria, the key function can return an array. The results
/// are in lexicographic order.
///
/// ```example
/// #let array = (
/// (a: 2, b: 4),
/// (a: 1, b: 5),
/// (a: 2, b: 3),
/// )
/// #array.sorted(key: it => (it.a, it.b))
/// ```
#[func]
pub fn sorted(
self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// If given, applies this function to each element in the array to
/// determine the keys to sort by.
#[named]
key: Option<Func>,
/// If given, uses this function to compare every two elements in the
/// array.
///
/// The function will receive two elements in the array for comparison,
/// and should return a boolean indicating their order: `{true}`
/// indicates that the elements are in order, while `{false}` indicates
/// that they should be swapped. To keep the sort stable, if the two
/// elements are equal, the function should return `{true}`.
///
/// If this function does not order the elements properly (e.g., by
/// returning `{false}` for both `{(x, y)}` and `{(y, x)}`, or for
/// `{(x, x)}`), the resulting array will be in unspecified order.
///
/// When used together with `key`, `by` will be passed the keys instead
/// of the elements.
///
/// ```example
/// #(
/// "sorted",
/// "by",
/// "decreasing",
/// "length",
/// ).sorted(
/// key: s => s.len(),
/// by: (l, r) => l >= r,
/// )
/// ```
#[named]
by: Option<Func>,
) -> SourceResult<Array> {
// We use `glidesort` instead of the standard library sorting algorithm
// to prevent panics in case the comparison function does not define a
// valid order (see https://github.com/typst/typst/pull/5627 and
// https://github.com/typst/typst/issues/6285).
match by {
Some(by) => {
let mut are_in_order = |mut x, mut y| {
if let Some(f) = &key {
// We rely on `comemo`'s memoization of function
// evaluation to not excessively reevaluate the key.
x = f.call(engine, context, [x])?;
y = f.call(engine, context, [y])?;
}
match by.call(engine, context, [x, y])? {
Value::Bool(b) => Ok(b),
x => {
bail!(
span,
"expected boolean from `by` function, got {}",
x.ty(),
)
}
}
};
let mut result = Ok(());
let mut vec = self.0.into_iter().enumerate().collect::<Vec<_>>();
glidesort::sort_by(&mut vec, |(i, x), (j, y)| {
// Because we use booleans for the comparison function, in
// order to keep the sort stable, we need to compare in the
// right order.
if i < j {
// If `x` and `y` appear in this order in the original
// array, then we should change their order (i.e.,
// return `Ordering::Greater`) iff `y` is strictly less
// than `x` (i.e., `compare(x, y)` returns `false`).
// Otherwise, we should keep them in the same order
// (i.e., return `Ordering::Less`).
match are_in_order(x.clone(), y.clone()) {
Ok(false) => Ordering::Greater,
Ok(true) => Ordering::Less,
Err(err) => {
if result.is_ok() {
result = Err(err);
}
Ordering::Equal
}
}
} else {
// If `x` and `y` appear in the opposite order in the
// original array, then we should change their order
// (i.e., return `Ordering::Less`) iff `x` is strictly
// less than `y` (i.e., `compare(y, x)` returns
// `false`). Otherwise, we should keep them in the same
// order (i.e., return `Ordering::Less`).
match are_in_order(y.clone(), x.clone()) {
Ok(false) => Ordering::Less,
Ok(true) => Ordering::Greater,
Err(err) => {
if result.is_ok() {
result = Err(err);
}
Ordering::Equal
}
}
}
});
result.map(|()| vec.into_iter().map(|(_, x)| x).collect())
}
None => {
let mut key_of = |x: Value| match &key {
// We rely on `comemo`'s memoization of function evaluation
// to not excessively reevaluate the key.
Some(f) => f.call(engine, context, [x]),
None => Ok(x),
};
let mut result = Ok(());
let mut vec = self.0;
glidesort::sort_by(vec.make_mut(), |a, b| {
match (key_of(a.clone()), key_of(b.clone())) {
(Ok(a), Ok(b)) => ops::compare(&a, &b).unwrap_or_else(|err| {
if result.is_ok() {
result =
Err(HintedString::from(err).with_hint(match key {
None => {
"consider choosing a `key` \
or defining the comparison with `by`"
}
Some(_) => {
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/func.rs | crates/typst-library/src/foundations/func.rs | #[doc(inline)]
pub use typst_macros::func;
use std::fmt::{self, Debug, Formatter};
use std::sync::{Arc, LazyLock};
use comemo::{Tracked, TrackedMut};
use ecow::{EcoString, eco_format};
use typst_syntax::{Span, SyntaxNode, ast};
use typst_utils::{LazyHash, Static, singleton};
use crate::diag::{At, DeprecationSink, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Bytes, CastInfo, Content, Context, Element, IntoArgs, PluginFunc, Repr, Scope,
Selector, Type, Value, cast, scope, ty,
};
/// A mapping from argument values to a return value.
///
/// You can call a function by writing a comma-separated list of function
/// _arguments_ enclosed in parentheses directly after the function name.
/// Additionally, you can pass any number of trailing content block arguments
/// to a function _after_ the normal argument list. If the normal argument list
/// would become empty, it can be omitted. Typst supports positional and named
/// arguments. The former are identified by position and type, while the latter
/// are written as `name: value`.
///
/// Within math mode, function calls have special behaviour. See the
/// [math documentation]($category/math) for more details.
///
/// # Example
/// ```example
/// // Call a function.
/// #list([A], [B])
///
/// // Named arguments and trailing
/// // content blocks.
/// #enum(start: 2)[A][B]
///
/// // Version without parentheses.
/// #list[A][B]
/// ```
///
/// Functions are a fundamental building block of Typst. Typst provides
/// functions for a variety of typesetting tasks. Moreover, the markup you write
/// is backed by functions and all styling happens through functions. This
/// reference lists all available functions and how you can use them. Please
/// also refer to the documentation about [set]($styling/#set-rules) and
/// [show]($styling/#show-rules) rules to learn about additional ways you can
/// work with functions in Typst.
///
/// # Element functions
/// Some functions are associated with _elements_ like [headings]($heading) or
/// [tables]($table). When called, these create an element of their respective
/// kind. In contrast to normal functions, they can further be used in [set
/// rules]($styling/#set-rules), [show rules]($styling/#show-rules), and
/// [selectors]($selector).
///
/// # Function scopes
/// Functions can hold related definitions in their own scope, similar to a
/// [module]($scripting/#modules). Examples of this are [`assert.eq`] or
/// [`list.item`]. However, this feature is currently only available for
/// built-in functions.
///
/// # Defining functions
/// You can define your own function with a [let binding]($scripting/#bindings)
/// that has a parameter list after the binding's name. The parameter list can
/// contain mandatory positional parameters, named parameters with default
/// values and [argument sinks]($arguments).
///
/// The right-hand side of a function binding is the function body, which can be
/// a block or any other expression. It defines the function's return value and
/// can depend on the parameters. If the function body is a [code
/// block]($scripting/#blocks), the return value is the result of joining the
/// values of each expression in the block.
///
/// Within a function body, the `return` keyword can be used to exit early and
/// optionally specify a return value. If no explicit return value is given, the
/// body evaluates to the result of joining all expressions preceding the
/// `return`.
///
/// Functions that don't return any meaningful value return [`none`] instead.
/// The return type of such functions is not explicitly specified in the
/// documentation. (An example of this is [`array.push`]).
///
/// ```example
/// #let alert(body, fill: red) = {
/// set text(white)
/// set align(center)
/// rect(
/// fill: fill,
/// inset: 8pt,
/// radius: 4pt,
/// [*Warning:\ #body*],
/// )
/// }
///
/// #alert[
/// Danger is imminent!
/// ]
///
/// #alert(fill: blue)[
/// KEEP OFF TRACKS
/// ]
/// ```
///
/// # Importing functions
/// Functions can be imported from one file ([`module`]($scripting/#modules)) into
/// another using `{import}`. For example, assume that we have defined the `alert`
/// function from the previous example in a file called `foo.typ`. We can import
/// it into another file by writing `{import "foo.typ": alert}`.
///
/// # Unnamed functions { #unnamed }
/// You can also create an unnamed function without creating a binding by
/// specifying a parameter list followed by `=>` and the function body. If your
/// function has just one parameter, the parentheses around the parameter list
/// are optional. Unnamed functions are mainly useful for show rules, but also
/// for settable properties that take functions like the page function's
/// [`footer`]($page.footer) property.
///
/// ```example
/// #show "once?": it => [#it #it]
/// once?
/// ```
///
/// # Note on function purity
/// In Typst, all functions are _pure._ This means that for the same
/// arguments, they always return the same result. They cannot "remember" things to
/// produce another value when they are called a second time.
///
/// The only exception are built-in methods like
/// [`array.push(value)`]($array.push). These can modify the values they are
/// called on.
#[ty(scope, cast, name = "function")]
#[derive(Clone, Hash)]
pub struct Func {
/// The internal representation.
inner: FuncInner,
/// The span with which errors are reported when this function is called.
span: Span,
}
/// The different kinds of function representations.
#[derive(Clone, PartialEq, Hash)]
enum FuncInner {
/// A native Rust function.
Native(Static<NativeFuncData>),
/// A function for an element.
Element(Element),
/// A user-defined closure.
Closure(Arc<LazyHash<Closure>>),
/// A plugin WebAssembly function.
Plugin(Arc<PluginFunc>),
/// A nested function with pre-applied arguments.
With(Arc<(Func, Args)>),
}
impl Func {
/// The function's name (e.g. `min`).
///
/// Returns `None` if this is an anonymous closure.
pub fn name(&self) -> Option<&str> {
match &self.inner {
FuncInner::Native(native) => Some(native.name),
FuncInner::Element(elem) => Some(elem.name()),
FuncInner::Closure(closure) => closure.name(),
FuncInner::Plugin(func) => Some(func.name()),
FuncInner::With(with) => with.0.name(),
}
}
/// The function's title case name, for use in documentation (e.g. `Minimum`).
///
/// Returns `None` if this is a closure.
pub fn title(&self) -> Option<&'static str> {
match &self.inner {
FuncInner::Native(native) => Some(native.title),
FuncInner::Element(elem) => Some(elem.title()),
FuncInner::Closure(_) => None,
FuncInner::Plugin(_) => None,
FuncInner::With(with) => with.0.title(),
}
}
/// Documentation for the function (as Markdown).
pub fn docs(&self) -> Option<&'static str> {
match &self.inner {
FuncInner::Native(native) => Some(native.docs),
FuncInner::Element(elem) => Some(elem.docs()),
FuncInner::Closure(_) => None,
FuncInner::Plugin(_) => None,
FuncInner::With(with) => with.0.docs(),
}
}
/// Whether the function is known to be contextual.
pub fn contextual(&self) -> Option<bool> {
match &self.inner {
FuncInner::Native(native) => Some(native.contextual),
_ => None,
}
}
/// Get details about this function's parameters if available.
pub fn params(&self) -> Option<&'static [ParamInfo]> {
match &self.inner {
FuncInner::Native(native) => Some(&native.0.params),
FuncInner::Element(elem) => Some(elem.params()),
FuncInner::Closure(_) => None,
FuncInner::Plugin(_) => None,
FuncInner::With(with) => with.0.params(),
}
}
/// Get the parameter info for a parameter with the given name if it exist.
pub fn param(&self, name: &str) -> Option<&'static ParamInfo> {
self.params()?.iter().find(|param| param.name == name)
}
/// Get details about the function's return type.
pub fn returns(&self) -> Option<&'static CastInfo> {
match &self.inner {
FuncInner::Native(native) => Some(&native.0.returns),
FuncInner::Element(_) => {
Some(singleton!(CastInfo, CastInfo::Type(Type::of::<Content>())))
}
FuncInner::Closure(_) => None,
FuncInner::Plugin(_) => None,
FuncInner::With(with) => with.0.returns(),
}
}
/// Search keywords for the function.
pub fn keywords(&self) -> &'static [&'static str] {
match &self.inner {
FuncInner::Native(native) => native.keywords,
FuncInner::Element(elem) => elem.keywords(),
FuncInner::Closure(_) => &[],
FuncInner::Plugin(_) => &[],
FuncInner::With(with) => with.0.keywords(),
}
}
/// The function's associated scope of sub-definition.
pub fn scope(&self) -> Option<&'static Scope> {
match &self.inner {
FuncInner::Native(native) => Some(&native.0.scope),
FuncInner::Element(elem) => Some(elem.scope()),
FuncInner::Closure(_) => None,
FuncInner::Plugin(_) => None,
FuncInner::With(with) => with.0.scope(),
}
}
/// Get a field from this function's scope, if possible.
pub fn field(
&self,
field: &str,
sink: impl DeprecationSink,
) -> StrResult<&'static Value> {
let scope =
self.scope().ok_or("cannot access fields on user-defined functions")?;
match scope.get(field) {
Some(binding) => Ok(binding.read_checked(sink)),
None => match self.name() {
Some(name) => bail!("function `{name}` does not contain field `{field}`"),
None => bail!("function does not contain field `{field}`"),
},
}
}
/// Extract the element function, if it is one.
pub fn to_element(&self) -> Option<Element> {
match self.inner {
FuncInner::Element(func) => Some(func),
_ => None,
}
}
/// Extract the plugin function, if it is one.
pub fn to_plugin(&self) -> Option<&PluginFunc> {
match &self.inner {
FuncInner::Plugin(func) => Some(func),
_ => None,
}
}
/// Call the function with the given context and arguments.
pub fn call<A: IntoArgs>(
&self,
engine: &mut Engine,
context: Tracked<Context>,
args: A,
) -> SourceResult<Value> {
self.call_impl(engine, context, args.into_args(self.span))
}
/// Non-generic implementation of `call`.
#[typst_macros::time(name = "func call", span = self.span())]
fn call_impl(
&self,
engine: &mut Engine,
context: Tracked<Context>,
mut args: Args,
) -> SourceResult<Value> {
match &self.inner {
FuncInner::Native(native) => {
let value = (native.function.0)(engine, context, &mut args)?;
args.finish()?;
Ok(value)
}
FuncInner::Element(func) => {
let value = func.construct(engine, &mut args)?;
args.finish()?;
Ok(Value::Content(value))
}
FuncInner::Closure(closure) => (engine.routines.eval_closure)(
self,
closure,
engine.routines,
engine.world,
engine.introspector.into_raw(),
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
context,
args,
),
FuncInner::Plugin(func) => {
let inputs = args.all::<Bytes>()?;
let output = func.call(inputs).at(args.span)?;
args.finish()?;
Ok(Value::Bytes(output))
}
FuncInner::With(with) => {
args.items = with.1.items.iter().cloned().chain(args.items).collect();
with.0.call(engine, context, args)
}
}
}
/// The function's span.
pub fn span(&self) -> Span {
self.span
}
/// Attach a span to this function if it doesn't already have one.
pub fn spanned(mut self, span: Span) -> Self {
if self.span.is_detached() {
self.span = span;
}
self
}
}
#[scope]
impl Func {
/// Returns a new function that has the given arguments pre-applied.
#[func]
pub fn with(
self,
args: &mut Args,
/// The arguments to apply to the function.
#[external]
#[variadic]
arguments: Vec<Value>,
) -> Func {
let span = self.span;
Self {
inner: FuncInner::With(Arc::new((self, args.take()))),
span,
}
}
/// Returns a selector that filters for elements belonging to this function
/// whose fields have the values of the given arguments.
///
/// ```example
/// #show heading.where(level: 2): set text(blue)
/// = Section
/// == Subsection
/// === Sub-subsection
/// ```
#[func]
pub fn where_(
self,
args: &mut Args,
/// The fields to filter for.
#[variadic]
#[external]
fields: Vec<Value>,
) -> StrResult<Selector> {
let fields = args.to_named();
args.items.retain(|arg| arg.name.is_none());
let element = self
.to_element()
.ok_or("`where()` can only be called on element functions")?;
let fields = fields
.into_iter()
.map(|(key, value)| {
element.field_id(&key).map(|id| (id, value)).ok_or_else(|| {
eco_format!(
"element `{}` does not have field `{}`",
element.name(),
key
)
})
})
.collect::<StrResult<smallvec::SmallVec<_>>>()?;
Ok(element.where_(fields))
}
}
impl Debug for Func {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Func({})", self.name().unwrap_or(".."))
}
}
impl Repr for Func {
fn repr(&self) -> EcoString {
const DEFAULT: &str = "(..) => ..";
match &self.inner {
FuncInner::Native(native) => native.name.into(),
FuncInner::Element(elem) => elem.name().into(),
FuncInner::Closure(closure) => closure.name().unwrap_or(DEFAULT).into(),
FuncInner::Plugin(func) => func.name().clone(),
FuncInner::With(_) => DEFAULT.into(),
}
}
}
impl PartialEq for Func {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl PartialEq<&'static NativeFuncData> for Func {
fn eq(&self, other: &&'static NativeFuncData) -> bool {
match &self.inner {
FuncInner::Native(native) => *native == Static(*other),
_ => false,
}
}
}
impl PartialEq<Element> for Func {
fn eq(&self, other: &Element) -> bool {
match &self.inner {
FuncInner::Element(elem) => elem == other,
_ => false,
}
}
}
impl From<FuncInner> for Func {
fn from(inner: FuncInner) -> Self {
Self { inner, span: Span::detached() }
}
}
impl From<&'static NativeFuncData> for Func {
fn from(data: &'static NativeFuncData) -> Self {
FuncInner::Native(Static(data)).into()
}
}
impl From<Element> for Func {
fn from(func: Element) -> Self {
FuncInner::Element(func).into()
}
}
impl From<Closure> for Func {
fn from(closure: Closure) -> Self {
FuncInner::Closure(Arc::new(LazyHash::new(closure))).into()
}
}
impl From<PluginFunc> for Func {
fn from(func: PluginFunc) -> Self {
FuncInner::Plugin(Arc::new(func)).into()
}
}
/// A Typst function that is defined by a native Rust type that shadows a
/// native Rust function.
pub trait NativeFunc {
/// Get the function for the native Rust type.
fn func() -> Func {
Func::from(Self::data())
}
/// Get the function data for the native Rust function.
fn data() -> &'static NativeFuncData;
}
/// Defines a native function.
#[derive(Debug)]
pub struct NativeFuncData {
/// The implementation of the function.
pub function: NativeFuncPtr,
/// The function's normal name (e.g. `align`), as exposed to Typst.
pub name: &'static str,
/// The function's title case name (e.g. `Align`).
pub title: &'static str,
/// The documentation for this function as a string.
pub docs: &'static str,
/// A list of alternate search terms for this function.
pub keywords: &'static [&'static str],
/// Whether this function makes use of context.
pub contextual: bool,
/// Definitions in the scope of the function.
pub scope: DynLazyLock<Scope>,
/// A list of parameter information for each parameter.
pub params: DynLazyLock<Vec<ParamInfo>>,
/// Information about the return value of this function.
pub returns: DynLazyLock<CastInfo>,
}
cast! {
&'static NativeFuncData,
self => Func::from(self).into_value(),
}
/// A pointer to a native function's implementation.
pub struct NativeFuncPtr(pub &'static NativeFuncSignature);
/// The signature of a native function's implementation.
type NativeFuncSignature =
dyn Fn(&mut Engine, Tracked<Context>, &mut Args) -> SourceResult<Value> + Send + Sync;
impl Debug for NativeFuncPtr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad("NativeFuncPtr(..)")
}
}
/// A `LazyLock` that uses a static closure for initialization instead of only
/// working with function pointers.
///
/// Can be created from a normal function or closure by prepending with a `&`,
/// e.g. `LazyLock::new(&|| "hello")`. Can be created from a dynamic closure
/// by allocating and then leaking it. This is equivalent to having it
/// statically allocated, but allows for it to be generated at runtime.
type DynLazyLock<T> = LazyLock<T, &'static (dyn Fn() -> T + Send + Sync)>;
/// Describes a function parameter.
#[derive(Debug, Clone)]
pub struct ParamInfo {
/// The parameter's name.
pub name: &'static str,
/// Documentation for the parameter.
pub docs: &'static str,
/// Describe what values this parameter accepts.
pub input: CastInfo,
/// Creates an instance of the parameter's default value.
pub default: Option<fn() -> Value>,
/// Is the parameter positional?
pub positional: bool,
/// Is the parameter named?
///
/// Can be true even if `positional` is true if the parameter can be given
/// in both variants.
pub named: bool,
/// Can the parameter be given any number of times?
pub variadic: bool,
/// Is the parameter required?
pub required: bool,
/// Is the parameter settable with a set rule?
pub settable: bool,
}
/// Distinguishes between variants of closures.
#[derive(Debug, Hash)]
pub enum ClosureNode {
/// A regular closure. Must always be castable to a `ast::Closure`.
Closure(SyntaxNode),
/// Synthetic closure used for `context` expressions. Can be any `ast::Expr`
/// and has no parameters.
Context(SyntaxNode),
}
/// A user-defined closure.
#[derive(Debug, Hash)]
pub struct Closure {
/// The closure's syntax node.
pub node: ClosureNode,
/// Default values of named parameters.
pub defaults: Vec<Value>,
/// Captured values from outer scopes.
pub captured: Scope,
/// The number of positional parameters in the closure.
pub num_pos_params: usize,
}
impl Closure {
/// The name of the closure.
pub fn name(&self) -> Option<&str> {
match self.node {
ClosureNode::Closure(ref node) => {
node.cast::<ast::Closure>()?.name().map(|ident| ident.as_str())
}
_ => None,
}
}
}
cast! {
Closure,
self => Value::Func(self.into()),
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/bytes.rs | crates/typst-library/src/foundations/bytes.rs | use std::any::Any;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::{Add, AddAssign, Deref};
use std::str::Utf8Error;
use std::sync::Arc;
use ecow::{EcoString, eco_format};
use serde::{Serialize, Serializer};
use typst_syntax::Lines;
use typst_utils::LazyHash;
use crate::diag::{StrResult, bail};
use crate::foundations::{Array, Reflect, Repr, Str, Value, cast, func, scope, ty};
/// A sequence of bytes.
///
/// This is conceptually similar to an array of [integers]($int) between `{0}`
/// and `{255}`, but represented much more efficiently. You can iterate over it
/// using a [for loop]($scripting/#loops).
///
/// You can convert
/// - a [string]($str) or an [array] of integers to bytes with the [`bytes`]
/// constructor
/// - bytes to a string with the [`str`] constructor, with UTF-8 encoding
/// - bytes to an array of integers with the [`array`] constructor
///
/// When [reading]($read) data from a file, you can decide whether to load it
/// as a string or as raw bytes.
///
/// ```example
/// #bytes((123, 160, 22, 0)) \
/// #bytes("Hello 😃")
///
/// #let data = read(
/// "rhino.png",
/// encoding: none,
/// )
///
/// // Magic bytes.
/// #array(data.slice(0, 4)) \
/// #str(data.slice(1, 4))
/// ```
#[ty(scope, cast)]
#[derive(Clone, Hash)]
pub struct Bytes(Arc<LazyHash<dyn Bytelike>>);
impl Bytes {
/// Create `Bytes` from anything byte-like.
///
/// The `data` type will directly back this bytes object. This means you can
/// e.g. pass `&'static [u8]` or `[u8; 8]` and no extra vector will be
/// allocated.
///
/// If the type is `Vec<u8>` and the `Bytes` are unique (i.e. not cloned),
/// the vector will be reused when mutating to the `Bytes`.
///
/// If your source type is a string, prefer [`Bytes::from_string`] to
/// directly use the UTF-8 encoded string data without any copying.
pub fn new<T>(data: T) -> Self
where
T: AsRef<[u8]> + Send + Sync + 'static,
{
Self(Arc::new(LazyHash::new(data)))
}
/// Create `Bytes` from anything string-like, implicitly viewing the UTF-8
/// representation.
///
/// The `data` type will directly back this bytes object. This means you can
/// e.g. pass `String` or `EcoString` without any copying.
pub fn from_string<T>(data: T) -> Self
where
T: AsRef<str> + Send + Sync + 'static,
{
Self(Arc::new(LazyHash::new(StrWrapper(data))))
}
/// Return `true` if the length is 0.
pub fn is_empty(&self) -> bool {
self.as_slice().is_empty()
}
/// Return a view into the bytes.
pub fn as_slice(&self) -> &[u8] {
self
}
/// Try to view the bytes as an UTF-8 string.
///
/// If these bytes were created via `Bytes::from_string`, UTF-8 validation
/// is skipped.
pub fn as_str(&self) -> Result<&str, Utf8Error> {
self.inner().as_str()
}
/// Return a copy of the bytes as a vector.
pub fn to_vec(&self) -> Vec<u8> {
self.as_slice().to_vec()
}
/// Try to turn the bytes into a `Str`.
///
/// - If these bytes were created via `Bytes::from_string::<Str>`, the
/// string is cloned directly.
/// - If these bytes were created via `Bytes::from_string`, but from a
/// different type of string, UTF-8 validation is still skipped.
pub fn to_str(&self) -> Result<Str, Utf8Error> {
match (self.inner() as &dyn Any).downcast_ref::<Str>() {
Some(string) => Ok(string.clone()),
None => self.as_str().map(Into::into),
}
}
/// Resolve an index or throw an out of bounds error.
fn locate(&self, index: i64) -> StrResult<usize> {
self.locate_opt(index).ok_or_else(|| out_of_bounds(index, self.len()))
}
/// Resolve an index, if it is within bounds.
///
/// `index == len` is considered in bounds.
fn locate_opt(&self, index: i64) -> Option<usize> {
let len = self.as_slice().len();
let wrapped =
if index >= 0 { Some(index) } else { (len as i64).checked_add(index) };
wrapped.and_then(|v| usize::try_from(v).ok()).filter(|&v| v <= len)
}
/// Access the inner `dyn Bytelike`.
fn inner(&self) -> &dyn Bytelike {
&**self.0
}
}
#[scope]
impl Bytes {
/// Converts a value to bytes.
///
/// - Strings are encoded in UTF-8.
/// - Arrays of integers between `{0}` and `{255}` are converted directly. The
/// dedicated byte representation is much more efficient than the array
/// representation and thus typically used for large byte buffers (e.g. image
/// data).
///
/// ```example
/// #bytes("Hello 😃") \
/// #bytes((123, 160, 22, 0))
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to bytes.
value: ToBytes,
) -> Bytes {
value.0
}
/// The length in bytes.
#[func(title = "Length")]
pub fn len(&self) -> usize {
self.as_slice().len()
}
/// Returns the byte at the specified index. Returns the default value if
/// the index is out of bounds or fails with an error if no default value
/// was specified.
#[func]
pub fn at(
&self,
/// The index at which to retrieve the byte.
index: i64,
/// A default value to return if the index is out of bounds.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.locate_opt(index)
.and_then(|i| self.as_slice().get(i).map(|&b| Value::Int(b.into())))
.or(default)
.ok_or_else(|| out_of_bounds_no_default(index, self.len()))
}
/// Extracts a subslice of the bytes. Fails with an error if the start or
/// end index is out of bounds.
#[func]
pub fn slice(
&self,
/// The start index (inclusive).
start: i64,
/// The end index (exclusive). If omitted, the whole slice until the end
/// is extracted.
#[default]
end: Option<i64>,
/// The number of items to extract. This is equivalent to passing
/// `start + count` as the `end` position. Mutually exclusive with
/// `end`.
#[named]
count: Option<i64>,
) -> StrResult<Bytes> {
let start = self.locate(start)?;
let end = end.or(count.map(|c| start as i64 + c));
let end = self.locate(end.unwrap_or(self.len() as i64))?.max(start);
let slice = &self.as_slice()[start..end];
// We could hold a view into the original bytes here instead of
// making a copy, but it's unclear when that's worth it. Java
// originally did that for strings, but went back on it because a
// very small view into a very large buffer would be a sort of
// memory leak.
Ok(Bytes::new(slice.to_vec()))
}
}
impl Debug for Bytes {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Bytes({})", self.len())
}
}
impl Repr for Bytes {
fn repr(&self) -> EcoString {
eco_format!("bytes({})", self.len())
}
}
impl Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.inner().as_bytes()
}
}
impl Eq for Bytes {}
impl PartialEq for Bytes {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}
impl AsRef<[u8]> for Bytes {
fn as_ref(&self) -> &[u8] {
self
}
}
impl Add for Bytes {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self += rhs;
self
}
}
impl AddAssign for Bytes {
fn add_assign(&mut self, rhs: Self) {
if rhs.is_empty() {
// Nothing to do
} else if self.is_empty() {
*self = rhs;
} else if let Some(vec) = Arc::get_mut(&mut self.0).and_then(|unique| {
let inner: &mut dyn Bytelike = &mut **unique;
(inner as &mut dyn Any).downcast_mut::<Vec<u8>>()
}) {
vec.extend_from_slice(&rhs);
} else {
*self = Self::new([self.as_slice(), rhs.as_slice()].concat());
}
}
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&self.repr())
} else {
serializer.serialize_bytes(self)
}
}
}
impl TryFrom<&Bytes> for Lines<String> {
type Error = Utf8Error;
#[comemo::memoize]
fn try_from(value: &Bytes) -> Result<Lines<String>, Utf8Error> {
let text = value.as_str()?;
Ok(Lines::new(text.to_string()))
}
}
/// Any type that can back a byte buffer.
trait Bytelike: Any + Send + Sync {
fn as_bytes(&self) -> &[u8];
fn as_str(&self) -> Result<&str, Utf8Error>;
}
impl<T> Bytelike for T
where
T: AsRef<[u8]> + Send + Sync + 'static,
{
fn as_bytes(&self) -> &[u8] {
self.as_ref()
}
fn as_str(&self) -> Result<&str, Utf8Error> {
std::str::from_utf8(self.as_ref())
}
}
impl Hash for dyn Bytelike {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
/// Makes string-like objects usable with `Bytes`.
struct StrWrapper<T>(T);
impl<T> Bytelike for StrWrapper<T>
where
T: AsRef<str> + Send + Sync + 'static,
{
fn as_bytes(&self) -> &[u8] {
self.0.as_ref().as_bytes()
}
fn as_str(&self) -> Result<&str, Utf8Error> {
Ok(self.0.as_ref())
}
}
/// A value that can be cast to bytes.
pub struct ToBytes(Bytes);
cast! {
ToBytes,
v: Str => Self(Bytes::from_string(v)),
v: Array => Self(v.iter()
.map(|item| match item {
Value::Int(byte @ 0..=255) => Ok(*byte as u8),
Value::Int(_) => bail!("number must be between 0 and 255"),
value => Err(<u8 as Reflect>::error(value)),
})
.collect::<Result<Vec<u8>, _>>()
.map(Bytes::new)?
),
v: Bytes => Self(v),
}
/// The out of bounds access error message.
#[cold]
fn out_of_bounds(index: i64, len: usize) -> EcoString {
eco_format!("byte index out of bounds (index: {index}, len: {len})")
}
/// The out of bounds access error message when no default value was given.
#[cold]
fn out_of_bounds_no_default(index: i64, len: usize) -> EcoString {
eco_format!(
"byte index out of bounds (index: {index}, len: {len}) \
and no default value was specified",
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/version.rs | crates/typst-library/src/foundations/version.rs | use std::cmp::Ordering;
use std::fmt::{self, Display, Formatter, Write};
use std::hash::Hash;
use std::iter::repeat;
use ecow::{EcoString, EcoVec, eco_format};
use crate::diag::{StrResult, bail};
use crate::foundations::{Repr, cast, func, repr, scope, ty};
/// A version with an arbitrary number of components.
///
/// The first three components have names that can be used as fields: `major`,
/// `minor`, `patch`. All following components do not have names.
///
/// The list of components is semantically extended by an infinite list of
/// zeros. This means that, for example, `0.8` is the same as `0.8.0`. As a
/// special case, the empty version (that has no components at all) is the same
/// as `0`, `0.0`, `0.0.0`, and so on.
///
/// The current version of the Typst compiler is available as `sys.version`.
///
/// You can convert a version to an array of explicitly given components using
/// the [`array`] constructor.
#[ty(scope, cast)]
#[derive(Debug, Default, Clone, Hash)]
pub struct Version(EcoVec<u32>);
impl Version {
/// The names for the first components of a version.
pub const COMPONENTS: [&'static str; 3] = ["major", "minor", "patch"];
/// Create a new (empty) version.
pub fn new() -> Self {
Self::default()
}
/// Get a named component of a version.
///
/// Always non-negative. Returns `0` if the version isn't specified to the
/// necessary length.
pub fn component(&self, name: &str) -> StrResult<i64> {
self.0
.iter()
.zip(Self::COMPONENTS)
.find_map(|(&i, s)| (s == name).then_some(i as i64))
.ok_or_else(|| "unknown version component".into())
}
/// Push a component to the end of this version.
pub fn push(&mut self, component: u32) {
self.0.push(component);
}
/// The values of the version
pub fn values(&self) -> &[u32] {
&self.0
}
}
#[scope]
impl Version {
/// Creates a new version.
///
/// It can have any number of components (even zero).
///
/// ```example:"Constructing versions"
/// #version() \
/// #version(1) \
/// #version(1, 2, 3, 4) \
/// #version((1, 2, 3, 4)) \
/// #version((1, 2), 3)
/// ```
///
/// As a practical use case, this allows comparing the current version
/// ([`{sys.version}`]($version)) to a specific one.
///
/// ```example:"Comparing with the current version"
/// Current version: #sys.version \
/// #(sys.version >= version(0, 14, 0)) \
/// #(version(3, 2, 0) > version(4, 1, 0))
/// ```
#[func(constructor)]
pub fn construct(
/// The components of the version (array arguments are flattened)
#[variadic]
components: Vec<VersionComponents>,
) -> Version {
let mut version = Version::new();
for c in components {
match c {
VersionComponents::Single(v) => version.push(v),
VersionComponents::Multiple(values) => {
for v in values {
version.push(v);
}
}
}
}
version
}
/// Retrieves a component of a version.
///
/// The returned integer is always non-negative. Returns `0` if the version
/// isn't specified to the necessary length.
#[func]
pub fn at(
&self,
/// The index at which to retrieve the component. If negative, indexes
/// from the back of the explicitly given components.
index: i64,
) -> StrResult<i64> {
let mut index = index;
if index < 0 {
match (self.0.len() as i64).checked_add(index) {
Some(pos_index) if pos_index >= 0 => index = pos_index,
_ => bail!(
"component index out of bounds (index: {index}, len: {})",
self.0.len(),
),
}
}
Ok(usize::try_from(index)
.ok()
.and_then(|i| self.0.get(i).copied())
.unwrap_or_default() as i64)
}
}
impl FromIterator<u32> for Version {
fn from_iter<T: IntoIterator<Item = u32>>(iter: T) -> Self {
Self(EcoVec::from_iter(iter))
}
}
impl IntoIterator for Version {
type Item = u32;
type IntoIter = ecow::vec::IntoIter<u32>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Ord for Version {
fn cmp(&self, other: &Self) -> Ordering {
let max_len = self.0.len().max(other.0.len());
let tail = repeat(&0);
let self_iter = self.0.iter().chain(tail.clone());
let other_iter = other.0.iter().chain(tail);
for (l, r) in self_iter.zip(other_iter).take(max_len) {
match l.cmp(r) {
Ordering::Equal => (),
ord => return ord,
}
}
Ordering::Equal
}
}
impl PartialOrd for Version {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for Version {}
impl PartialEq for Version {
fn eq(&self, other: &Self) -> bool {
matches!(self.cmp(other), Ordering::Equal)
}
}
impl Display for Version {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let mut first = true;
for &v in &self.0 {
if !first {
f.write_char('.')?;
}
write!(f, "{v}")?;
first = false;
}
Ok(())
}
}
impl Repr for Version {
fn repr(&self) -> EcoString {
let parts: Vec<_> = self.0.iter().map(|v| eco_format!("{v}")).collect();
eco_format!("version{}", &repr::pretty_array_like(&parts, false))
}
}
/// One or multiple version components.
pub enum VersionComponents {
Single(u32),
Multiple(Vec<u32>),
}
cast! {
VersionComponents,
v: u32 => Self::Single(v),
v: Vec<u32> => Self::Multiple(v)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/calc.rs | crates/typst-library/src/foundations/calc.rs | //! Calculations and processing of numeric values.
use std::cmp;
use std::cmp::Ordering;
use az::SaturatingAs;
use typst_syntax::{Span, Spanned};
use typst_utils::{round_int_with_precision, round_with_precision};
use crate::diag::{At, HintedString, SourceResult, StrResult, bail};
use crate::foundations::{Decimal, IntoValue, Module, Scope, Value, cast, func, ops};
use crate::layout::{Angle, Fr, Length, Ratio};
/// A module with calculation definitions.
pub fn module() -> Module {
let mut scope = Scope::new();
scope.define_func::<abs>();
scope.define_func::<pow>();
scope.define_func::<exp>();
scope.define_func::<sqrt>();
scope.define_func::<root>();
scope.define_func::<sin>();
scope.define_func::<cos>();
scope.define_func::<tan>();
scope.define_func::<asin>();
scope.define_func::<acos>();
scope.define_func::<atan>();
scope.define_func::<atan2>();
scope.define_func::<sinh>();
scope.define_func::<cosh>();
scope.define_func::<tanh>();
scope.define_func::<log>();
scope.define_func::<ln>();
scope.define_func::<fact>();
scope.define_func::<perm>();
scope.define_func::<binom>();
scope.define_func::<gcd>();
scope.define_func::<lcm>();
scope.define_func::<floor>();
scope.define_func::<ceil>();
scope.define_func::<trunc>();
scope.define_func::<fract>();
scope.define_func::<round>();
scope.define_func::<clamp>();
scope.define_func::<min>();
scope.define_func::<max>();
scope.define_func::<even>();
scope.define_func::<odd>();
scope.define_func::<rem>();
scope.define_func::<div_euclid>();
scope.define_func::<rem_euclid>();
scope.define_func::<quo>();
scope.define_func::<norm>();
scope.define("inf", f64::INFINITY);
scope.define("pi", std::f64::consts::PI);
scope.define("tau", std::f64::consts::TAU);
scope.define("e", std::f64::consts::E);
Module::new("calc", scope)
}
/// Calculates the absolute value of a numeric value.
///
/// ```example
/// #calc.abs(-5) \
/// #calc.abs(5pt - 2cm) \
/// #calc.abs(2fr) \
/// #calc.abs(decimal("-342.440"))
/// ```
#[func(title = "Absolute")]
pub fn abs(
/// The value whose absolute value to calculate.
value: ToAbs,
) -> Value {
value.0
}
/// A value of which the absolute value can be taken.
pub struct ToAbs(Value);
cast! {
ToAbs,
v: i64 => Self(v.abs().into_value()),
v: f64 => Self(v.abs().into_value()),
v: Length => Self(Value::Length(v.try_abs()
.ok_or("cannot take absolute value of this length")?)),
v: Angle => Self(Value::Angle(v.abs())),
v: Ratio => Self(Value::Ratio(v.abs())),
v: Fr => Self(Value::Fraction(v.abs())),
v: Decimal => Self(Value::Decimal(v.abs()))
}
/// Raises a value to some exponent.
///
/// ```example
/// #calc.pow(2, 3) \
/// #calc.pow(decimal("2.5"), 2)
/// ```
#[func(title = "Power")]
pub fn pow(
span: Span,
/// The base of the power.
///
/// If this is a [`decimal`], the exponent can only be an [integer]($int).
base: DecNum,
/// The exponent of the power.
exponent: Spanned<Num>,
) -> SourceResult<DecNum> {
match exponent.v {
_ if exponent.v.float() == 0.0 && base.is_zero() => {
bail!(span, "zero to the power of zero is undefined")
}
Num::Int(i) if i32::try_from(i).is_err() => {
bail!(exponent.span, "exponent is too large")
}
Num::Float(f) if !f.is_normal() && f != 0.0 => {
bail!(exponent.span, "exponent may not be infinite, subnormal, or NaN")
}
_ => {}
};
match (base, exponent.v) {
(DecNum::Int(a), Num::Int(b)) if b >= 0 => a
.checked_pow(b as u32)
.map(DecNum::Int)
.ok_or_else(too_large)
.at(span),
(DecNum::Decimal(a), Num::Int(b)) => {
a.checked_powi(b).map(DecNum::Decimal).ok_or_else(too_large).at(span)
}
(a, b) => {
let Some(a) = a.float() else {
return Err(cant_apply_to_decimal_and_float()).at(span);
};
let result = if a == std::f64::consts::E {
b.float().exp()
} else if a == 2.0 {
b.float().exp2()
} else if let Num::Int(b) = b {
a.powi(b as i32)
} else {
a.powf(b.float())
};
if result.is_nan() {
bail!(span, "the result is not a real number")
}
Ok(DecNum::Float(result))
}
}
}
/// Raises a value to some exponent of e.
///
/// ```example
/// #calc.exp(1)
/// ```
#[func(title = "Exponential")]
pub fn exp(
span: Span,
/// The exponent of the power.
exponent: Spanned<Num>,
) -> SourceResult<f64> {
match exponent.v {
Num::Int(i) if i32::try_from(i).is_err() => {
bail!(exponent.span, "exponent is too large")
}
Num::Float(f) if !f.is_normal() && f != 0.0 => {
bail!(exponent.span, "exponent may not be infinite, subnormal, or NaN")
}
_ => {}
}
let result = exponent.v.float().exp();
if result.is_nan() {
bail!(span, "the result is not a real number")
}
Ok(result)
}
/// Calculates the square root of a number.
///
/// ```example
/// #calc.sqrt(16) \
/// #calc.sqrt(2.5)
/// ```
#[func(title = "Square Root")]
pub fn sqrt(
/// The number whose square root to calculate. Must be non-negative.
value: Spanned<Num>,
) -> SourceResult<f64> {
if value.v.float() < 0.0 {
bail!(value.span, "cannot take square root of negative number");
}
Ok(value.v.float().sqrt())
}
/// Calculates the real nth root of a number.
///
/// If the number is negative, then n must be odd.
///
/// ```example
/// #calc.root(16.0, 4) \
/// #calc.root(27.0, 3)
/// ```
#[func]
pub fn root(
/// The expression to take the root of.
radicand: f64,
/// Which root of the radicand to take.
index: Spanned<i64>,
) -> SourceResult<f64> {
if index.v == 0 {
bail!(index.span, "cannot take the 0th root of a number");
} else if radicand < 0.0 {
if index.v % 2 == 0 {
bail!(
index.span,
"negative numbers do not have a real nth root when n is even",
);
} else {
Ok(-(-radicand).powf(1.0 / index.v as f64))
}
} else {
Ok(radicand.powf(1.0 / index.v as f64))
}
}
/// Calculates the sine of an angle.
///
/// When called with an integer or a float, they will be interpreted as
/// radians.
///
/// ```example
/// #calc.sin(1.5) \
/// #calc.sin(90deg)
/// ```
#[func(title = "Sine")]
pub fn sin(
/// The angle whose sine to calculate.
angle: AngleLike,
) -> f64 {
match angle {
AngleLike::Angle(a) => a.sin(),
AngleLike::Int(n) => (n as f64).sin(),
AngleLike::Float(n) => n.sin(),
}
}
/// Calculates the cosine of an angle.
///
/// When called with an integer or a float, they will be interpreted as
/// radians.
///
/// ```example
/// #calc.cos(1.5) \
/// #calc.cos(90deg)
/// ```
#[func(title = "Cosine")]
pub fn cos(
/// The angle whose cosine to calculate.
angle: AngleLike,
) -> f64 {
match angle {
AngleLike::Angle(a) => a.cos(),
AngleLike::Int(n) => (n as f64).cos(),
AngleLike::Float(n) => n.cos(),
}
}
/// Calculates the tangent of an angle.
///
/// When called with an integer or a float, they will be interpreted as
/// radians.
///
/// ```example
/// #calc.tan(1.5) \
/// #calc.tan(90deg)
/// ```
#[func(title = "Tangent")]
pub fn tan(
/// The angle whose tangent to calculate.
angle: AngleLike,
) -> f64 {
match angle {
AngleLike::Angle(a) => a.tan(),
AngleLike::Int(n) => (n as f64).tan(),
AngleLike::Float(n) => n.tan(),
}
}
/// Calculates the arcsine of a number.
///
/// ```example
/// #calc.asin(0) \
/// #calc.asin(1)
/// ```
#[func(title = "Arcsine")]
pub fn asin(
/// The number whose arcsine to calculate. Must be between -1 and 1.
value: Spanned<Num>,
) -> SourceResult<Angle> {
let val = value.v.float();
if val < -1.0 || val > 1.0 {
bail!(value.span, "value must be between -1 and 1");
}
Ok(Angle::rad(val.asin()))
}
/// Calculates the arccosine of a number.
///
/// ```example
/// #calc.acos(0) \
/// #calc.acos(1)
/// ```
#[func(title = "Arccosine")]
pub fn acos(
/// The number whose arccosine to calculate. Must be between -1 and 1.
value: Spanned<Num>,
) -> SourceResult<Angle> {
let val = value.v.float();
if val < -1.0 || val > 1.0 {
bail!(value.span, "value must be between -1 and 1");
}
Ok(Angle::rad(val.acos()))
}
/// Calculates the arctangent of a number.
///
/// ```example
/// #calc.atan(0) \
/// #calc.atan(1)
/// ```
#[func(title = "Arctangent")]
pub fn atan(
/// The number whose arctangent to calculate.
value: Num,
) -> Angle {
Angle::rad(value.float().atan())
}
/// Calculates the four-quadrant arctangent of a coordinate.
///
/// The arguments are `(x, y)`, not `(y, x)`.
///
/// ```example
/// #calc.atan2(1, 1) \
/// #calc.atan2(-2, -3)
/// ```
#[func(title = "Four-quadrant Arctangent")]
pub fn atan2(
/// The X coordinate.
x: Num,
/// The Y coordinate.
y: Num,
) -> Angle {
Angle::rad(f64::atan2(y.float(), x.float()))
}
/// Calculates the hyperbolic sine of a hyperbolic angle.
///
/// ```example
/// #calc.sinh(0) \
/// #calc.sinh(1.5)
/// ```
#[func(title = "Hyperbolic Sine")]
pub fn sinh(
/// The hyperbolic angle whose hyperbolic sine to calculate.
value: f64,
) -> f64 {
value.sinh()
}
/// Calculates the hyperbolic cosine of a hyperbolic angle.
///
/// ```example
/// #calc.cosh(0) \
/// #calc.cosh(1.5)
/// ```
#[func(title = "Hyperbolic Cosine")]
pub fn cosh(
/// The hyperbolic angle whose hyperbolic cosine to calculate.
value: f64,
) -> f64 {
value.cosh()
}
/// Calculates the hyperbolic tangent of a hyperbolic angle.
///
/// ```example
/// #calc.tanh(0) \
/// #calc.tanh(1.5)
/// ```
#[func(title = "Hyperbolic Tangent")]
pub fn tanh(
/// The hyperbolic angle whose hyperbolic tangent to calculate.
value: f64,
) -> f64 {
value.tanh()
}
/// Calculates the logarithm of a number.
///
/// If the base is not specified, the logarithm is calculated in base 10.
///
/// ```example
/// #calc.log(100)
/// ```
#[func(title = "Logarithm")]
pub fn log(
span: Span,
/// The number whose logarithm to calculate. Must be strictly positive.
value: Spanned<Num>,
/// The base of the logarithm. May not be zero.
#[named]
#[default(Spanned::detached(10.0))]
base: Spanned<f64>,
) -> SourceResult<f64> {
let number = value.v.float();
if number <= 0.0 {
bail!(value.span, "value must be strictly positive")
}
if !base.v.is_normal() {
bail!(base.span, "base may not be zero, NaN, infinite, or subnormal")
}
let result = if base.v == std::f64::consts::E {
number.ln()
} else if base.v == 2.0 {
number.log2()
} else if base.v == 10.0 {
number.log10()
} else {
number.log(base.v)
};
if result.is_infinite() || result.is_nan() {
bail!(span, "the result is not a real number")
}
Ok(result)
}
/// Calculates the natural logarithm of a number.
///
/// ```example
/// #calc.ln(calc.e)
/// ```
#[func(title = "Natural Logarithm")]
pub fn ln(
span: Span,
/// The number whose logarithm to calculate. Must be strictly positive.
value: Spanned<Num>,
) -> SourceResult<f64> {
let number = value.v.float();
if number <= 0.0 {
bail!(value.span, "value must be strictly positive")
}
let result = number.ln();
if result.is_infinite() {
bail!(span, "result close to -inf")
}
Ok(result)
}
/// Calculates the factorial of a number.
///
/// ```example
/// #calc.fact(5)
/// ```
#[func(title = "Factorial")]
pub fn fact(
/// The number whose factorial to calculate. Must be non-negative.
number: u64,
) -> StrResult<i64> {
Ok(fact_impl(1, number).ok_or_else(too_large)?)
}
/// Calculates a permutation.
///
/// Returns the `k`-permutation of `n`, or the number of ways to choose `k`
/// items from a set of `n` with regard to order.
///
/// ```example
/// $ "perm"(n, k) &= n!/((n - k)!) \
/// "perm"(5, 3) &= #calc.perm(5, 3) $
/// ```
#[func(title = "Permutation")]
pub fn perm(
/// The base number. Must be non-negative.
base: u64,
/// The number of permutations. Must be non-negative.
numbers: u64,
) -> StrResult<i64> {
// By convention.
if base < numbers {
return Ok(0);
}
Ok(fact_impl(base - numbers + 1, base).ok_or_else(too_large)?)
}
/// Calculates the product of a range of numbers. Used to calculate
/// permutations. Returns None if the result is larger than `i64::MAX`
fn fact_impl(start: u64, end: u64) -> Option<i64> {
// By convention
if end + 1 < start {
return Some(0);
}
let real_start: u64 = cmp::max(1, start);
let mut count: u64 = 1;
for i in real_start..=end {
count = count.checked_mul(i)?;
}
count.try_into().ok()
}
/// Calculates a binomial coefficient.
///
/// Returns the `k`-combination of `n`, or the number of ways to choose `k`
/// items from a set of `n` without regard to order.
///
/// ```example
/// #calc.binom(10, 5)
/// ```
#[func(title = "Binomial")]
pub fn binom(
/// The upper coefficient. Must be non-negative.
n: u64,
/// The lower coefficient. Must be non-negative.
k: u64,
) -> StrResult<i64> {
Ok(binom_impl(n, k).ok_or_else(too_large)?)
}
/// Calculates a binomial coefficient, with `n` the upper coefficient and `k`
/// the lower coefficient. Returns `None` if the result is larger than
/// `i64::MAX`
fn binom_impl(n: u64, k: u64) -> Option<i64> {
if k > n {
return Some(0);
}
// By symmetry
let real_k = cmp::min(n - k, k);
if real_k == 0 {
return Some(1);
}
let mut result: u64 = 1;
for i in 0..real_k {
result = result.checked_mul(n - i)?.checked_div(i + 1)?;
}
result.try_into().ok()
}
/// Calculates the greatest common divisor of two integers.
///
/// This will error if the result of integer division would be larger than the
/// maximum 64-bit signed integer.
///
/// ```example
/// #calc.gcd(7, 42)
/// ```
#[func(title = "Greatest Common Divisor")]
pub fn gcd(
/// The first integer.
a: i64,
/// The second integer.
b: i64,
) -> StrResult<i64> {
let (mut a, mut b) = (a, b);
while b != 0 {
let temp = b;
b = a.checked_rem(b).ok_or_else(too_large)?;
a = temp;
}
Ok(a.abs())
}
/// Calculates the least common multiple of two integers.
///
/// ```example
/// #calc.lcm(96, 13)
/// ```
#[func(title = "Least Common Multiple")]
pub fn lcm(
/// The first integer.
a: i64,
/// The second integer.
b: i64,
) -> StrResult<i64> {
if a == b {
return Ok(a.abs());
}
Ok(a.checked_div(gcd(a, b)?)
.and_then(|gcd| gcd.checked_mul(b))
.map(|v| v.abs())
.ok_or_else(too_large)?)
}
/// Rounds a number down to the nearest integer.
///
/// If the number is already an integer, it is returned unchanged.
///
/// Note that this function will always return an [integer]($int), and will
/// error if the resulting [`float`] or [`decimal`] is larger than the maximum
/// 64-bit signed integer or smaller than the minimum for that type.
///
/// ```example
/// #calc.floor(500.1)
/// #assert(calc.floor(3) == 3)
/// #assert(calc.floor(3.14) == 3)
/// #assert(calc.floor(decimal("-3.14")) == -4)
/// ```
#[func]
pub fn floor(
/// The number to round down.
value: DecNum,
) -> StrResult<i64> {
match value {
DecNum::Int(n) => Ok(n),
DecNum::Float(n) => Ok(crate::foundations::convert_float_to_int(n.floor())
.map_err(|_| too_large())?),
DecNum::Decimal(n) => Ok(i64::try_from(n.floor()).map_err(|_| too_large())?),
}
}
/// Rounds a number up to the nearest integer.
///
/// If the number is already an integer, it is returned unchanged.
///
/// Note that this function will always return an [integer]($int), and will
/// error if the resulting [`float`] or [`decimal`] is larger than the maximum
/// 64-bit signed integer or smaller than the minimum for that type.
///
/// ```example
/// #calc.ceil(500.1)
/// #assert(calc.ceil(3) == 3)
/// #assert(calc.ceil(3.14) == 4)
/// #assert(calc.ceil(decimal("-3.14")) == -3)
/// ```
#[func]
pub fn ceil(
/// The number to round up.
value: DecNum,
) -> StrResult<i64> {
match value {
DecNum::Int(n) => Ok(n),
DecNum::Float(n) => Ok(crate::foundations::convert_float_to_int(n.ceil())
.map_err(|_| too_large())?),
DecNum::Decimal(n) => Ok(i64::try_from(n.ceil()).map_err(|_| too_large())?),
}
}
/// Returns the integer part of a number.
///
/// If the number is already an integer, it is returned unchanged.
///
/// Note that this function will always return an [integer]($int), and will
/// error if the resulting [`float`] or [`decimal`] is larger than the maximum
/// 64-bit signed integer or smaller than the minimum for that type.
///
/// ```example
/// #calc.trunc(15.9)
/// #assert(calc.trunc(3) == 3)
/// #assert(calc.trunc(-3.7) == -3)
/// #assert(calc.trunc(decimal("8493.12949582390")) == 8493)
/// ```
#[func(title = "Truncate")]
pub fn trunc(
/// The number to truncate.
value: DecNum,
) -> StrResult<i64> {
match value {
DecNum::Int(n) => Ok(n),
DecNum::Float(n) => Ok(crate::foundations::convert_float_to_int(n.trunc())
.map_err(|_| too_large())?),
DecNum::Decimal(n) => Ok(i64::try_from(n.trunc()).map_err(|_| too_large())?),
}
}
/// Returns the fractional part of a number.
///
/// If the number is an integer, returns `0`.
///
/// ```example
/// #calc.fract(-3.1)
/// #assert(calc.fract(3) == 0)
/// #assert(calc.fract(decimal("234.23949211")) == decimal("0.23949211"))
/// ```
#[func(title = "Fractional")]
pub fn fract(
/// The number to truncate.
value: DecNum,
) -> DecNum {
match value {
DecNum::Int(_) => DecNum::Int(0),
DecNum::Float(n) => DecNum::Float(n.fract()),
DecNum::Decimal(n) => DecNum::Decimal(n.fract()),
}
}
/// Rounds a number to the nearest integer.
///
/// Half-integers are rounded away from zero.
///
/// Optionally, a number of decimal places can be specified. If negative, its
/// absolute value will indicate the amount of significant integer digits to
/// remove before the decimal point.
///
/// Note that this function will return the same type as the operand. That is,
/// applying `round` to a [`float`] will return a `float`, and to a [`decimal`],
/// another `decimal`. You may explicitly convert the output of this function to
/// an integer with [`int`], but note that such a conversion will error if the
/// `float` or `decimal` is larger than the maximum 64-bit signed integer or
/// smaller than the minimum integer.
///
/// In addition, this function can error if there is an attempt to round beyond
/// the maximum or minimum integer or `decimal`. If the number is a `float`,
/// such an attempt will cause `{float.inf}` or `{-float.inf}` to be returned
/// for maximum and minimum respectively.
///
/// ```example
/// #calc.round(3.1415, digits: 2)
/// #assert(calc.round(3) == 3)
/// #assert(calc.round(3.14) == 3)
/// #assert(calc.round(3.5) == 4.0)
/// #assert(calc.round(3333.45, digits: -2) == 3300.0)
/// #assert(calc.round(-48953.45, digits: -3) == -49000.0)
/// #assert(calc.round(3333, digits: -2) == 3300)
/// #assert(calc.round(-48953, digits: -3) == -49000)
/// #assert(calc.round(decimal("-6.5")) == decimal("-7"))
/// #assert(calc.round(decimal("7.123456789"), digits: 6) == decimal("7.123457"))
/// #assert(calc.round(decimal("3333.45"), digits: -2) == decimal("3300"))
/// #assert(calc.round(decimal("-48953.45"), digits: -3) == decimal("-49000"))
/// ```
#[func]
pub fn round(
/// The number to round.
value: DecNum,
/// If positive, the number of decimal places.
///
/// If negative, the number of significant integer digits that should be
/// removed before the decimal point.
#[named]
#[default(0)]
digits: i64,
) -> StrResult<DecNum> {
match value {
DecNum::Int(n) => Ok(DecNum::Int(
round_int_with_precision(n, digits.saturating_as::<i16>())
.ok_or_else(too_large)?,
)),
DecNum::Float(n) => {
Ok(DecNum::Float(round_with_precision(n, digits.saturating_as::<i16>())))
}
DecNum::Decimal(n) => Ok(DecNum::Decimal(
n.round(digits.saturating_as::<i32>()).ok_or_else(too_large)?,
)),
}
}
/// Clamps a number between a minimum and maximum value.
///
/// ```example
/// #calc.clamp(5, 0, 4)
/// #assert(calc.clamp(5, 0, 10) == 5)
/// #assert(calc.clamp(5, 6, 10) == 6)
/// #assert(calc.clamp(decimal("5.45"), 2, decimal("45.9")) == decimal("5.45"))
/// #assert(calc.clamp(decimal("5.45"), decimal("6.75"), 12) == decimal("6.75"))
/// ```
#[func]
pub fn clamp(
span: Span,
/// The number to clamp.
value: DecNum,
/// The inclusive minimum value.
min: DecNum,
/// The inclusive maximum value.
max: Spanned<DecNum>,
) -> SourceResult<DecNum> {
// Ignore if there are incompatible types (decimal and float) since that
// will cause `apply3` below to error before calling clamp, avoiding a
// panic.
if min
.apply2(max.v, |min, max| max < min, |min, max| max < min, |min, max| max < min)
.unwrap_or(false)
{
bail!(max.span, "max must be greater than or equal to min")
}
value
.apply3(min, max.v, i64::clamp, f64::clamp, Decimal::clamp)
.ok_or_else(cant_apply_to_decimal_and_float)
.at(span)
}
/// Determines the minimum of a sequence of values.
///
/// ```example
/// #calc.min(1, -3, -5, 20, 3, 6) \
/// #calc.min("typst", "is", "cool")
/// ```
#[func(title = "Minimum")]
pub fn min(
span: Span,
/// The sequence of values from which to extract the minimum.
/// Must not be empty.
#[variadic]
values: Vec<Spanned<Value>>,
) -> SourceResult<Value> {
minmax(span, values, Ordering::Less)
}
/// Determines the maximum of a sequence of values.
///
/// ```example
/// #calc.max(1, -3, -5, 20, 3, 6) \
/// #calc.max("typst", "is", "cool")
/// ```
#[func(title = "Maximum")]
pub fn max(
span: Span,
/// The sequence of values from which to extract the maximum.
/// Must not be empty.
#[variadic]
values: Vec<Spanned<Value>>,
) -> SourceResult<Value> {
minmax(span, values, Ordering::Greater)
}
/// Find the minimum or maximum of a sequence of values.
fn minmax(
span: Span,
values: Vec<Spanned<Value>>,
goal: Ordering,
) -> SourceResult<Value> {
let mut iter = values.into_iter();
let Some(Spanned { v: mut extremum, .. }) = iter.next() else {
bail!(span, "expected at least one value");
};
for Spanned { v, span } in iter {
let ordering = ops::compare(&v, &extremum).at(span)?;
if ordering == goal {
extremum = v;
}
}
Ok(extremum)
}
/// Determines whether an integer is even.
///
/// ```example
/// #calc.even(4) \
/// #calc.even(5) \
/// #range(10).filter(calc.even)
/// ```
#[func]
pub fn even(
/// The number to check for evenness.
value: i64,
) -> bool {
value % 2 == 0
}
/// Determines whether an integer is odd.
///
/// ```example
/// #calc.odd(4) \
/// #calc.odd(5) \
/// #range(10).filter(calc.odd)
/// ```
#[func]
pub fn odd(
/// The number to check for oddness.
value: i64,
) -> bool {
value % 2 != 0
}
/// Calculates the remainder of two numbers.
///
/// The value `calc.rem(x, y)` always has the same sign as `x`, and is smaller
/// in magnitude than `y`.
///
/// This can error if given a [`decimal`] input and the dividend is too small in
/// magnitude compared to the divisor.
///
/// ```example
/// #calc.rem(7, 3) \
/// #calc.rem(7, -3) \
/// #calc.rem(-7, 3) \
/// #calc.rem(-7, -3) \
/// #calc.rem(1.75, 0.5)
/// ```
#[func(title = "Remainder")]
pub fn rem(
span: Span,
/// The dividend of the remainder.
dividend: DecNum,
/// The divisor of the remainder.
divisor: Spanned<DecNum>,
) -> SourceResult<DecNum> {
if divisor.v.is_zero() {
bail!(divisor.span, "divisor must not be zero");
}
dividend
.apply2(
divisor.v,
// `checked_rem` can only overflow on `i64::MIN % -1` which is
// mathematically zero.
|a, b| Some(DecNum::Int(a.checked_rem(b).unwrap_or(0))),
|a, b| Some(DecNum::Float(a % b)),
|a, b| a.checked_rem(b).map(DecNum::Decimal),
)
.ok_or_else(cant_apply_to_decimal_and_float)
.at(span)?
.ok_or("dividend too small compared to divisor")
.at(span)
}
/// Performs euclidean division of two numbers.
///
/// The result of this computation is that of a division rounded to the integer
/// `{n}` such that the dividend is greater than or equal to `{n}` times
/// the divisor.
///
/// This can error if the resulting number is larger than the maximum value or
/// smaller than the minimum value for its type.
///
/// ```example
/// #calc.div-euclid(7, 3) \
/// #calc.div-euclid(7, -3) \
/// #calc.div-euclid(-7, 3) \
/// #calc.div-euclid(-7, -3) \
/// #calc.div-euclid(1.75, 0.5) \
/// #calc.div-euclid(decimal("1.75"), decimal("0.5"))
/// ```
#[func(title = "Euclidean Division")]
pub fn div_euclid(
span: Span,
/// The dividend of the division.
dividend: DecNum,
/// The divisor of the division.
divisor: Spanned<DecNum>,
) -> SourceResult<DecNum> {
if divisor.v.is_zero() {
bail!(divisor.span, "divisor must not be zero");
}
dividend
.apply2(
divisor.v,
|a, b| a.checked_div_euclid(b).map(DecNum::Int),
|a, b| Some(DecNum::Float(a.div_euclid(b))),
|a, b| a.checked_div_euclid(b).map(DecNum::Decimal),
)
.ok_or_else(cant_apply_to_decimal_and_float)
.at(span)?
.ok_or_else(too_large)
.at(span)
}
/// This calculates the least nonnegative remainder of a division.
///
/// Warning: Due to a floating point round-off error, the remainder may equal
/// the absolute value of the divisor if the dividend is much smaller in
/// magnitude than the divisor and the dividend is negative. This only applies
/// for floating point inputs.
///
/// In addition, this can error if given a [`decimal`] input and the dividend is
/// too small in magnitude compared to the divisor.
///
/// ```example
/// #calc.rem-euclid(7, 3) \
/// #calc.rem-euclid(7, -3) \
/// #calc.rem-euclid(-7, 3) \
/// #calc.rem-euclid(-7, -3) \
/// #calc.rem-euclid(1.75, 0.5) \
/// #calc.rem-euclid(decimal("1.75"), decimal("0.5"))
/// ```
#[func(title = "Euclidean Remainder", keywords = ["modulo", "modulus"])]
pub fn rem_euclid(
span: Span,
/// The dividend of the remainder.
dividend: DecNum,
/// The divisor of the remainder.
divisor: Spanned<DecNum>,
) -> SourceResult<DecNum> {
if divisor.v.is_zero() {
bail!(divisor.span, "divisor must not be zero");
}
dividend
.apply2(
divisor.v,
// `checked_rem_euclid` can only overflow on `i64::MIN % -1` which
// is mathematically zero.
|a, b| Some(DecNum::Int(a.checked_rem_euclid(b).unwrap_or(0))),
|a, b| Some(DecNum::Float(a.rem_euclid(b))),
|a, b| a.checked_rem_euclid(b).map(DecNum::Decimal),
)
.ok_or_else(cant_apply_to_decimal_and_float)
.at(span)?
.ok_or("dividend too small compared to divisor")
.at(span)
}
/// Calculates the quotient (floored division) of two numbers.
///
/// Note that this function will always return an [integer]($int), and will
/// error if the resulting number is larger than the maximum 64-bit signed
/// integer or smaller than the minimum for that type.
///
/// ```example
/// $ "quo"(a, b) &= floor(a/b) \
/// "quo"(14, 5) &= #calc.quo(14, 5) \
/// "quo"(3.46, 0.5) &= #calc.quo(3.46, 0.5) $
/// ```
#[func(title = "Quotient")]
pub fn quo(
span: Span,
/// The dividend of the quotient.
dividend: DecNum,
/// The divisor of the quotient.
divisor: Spanned<DecNum>,
) -> SourceResult<i64> {
if divisor.v.is_zero() {
bail!(divisor.span, "divisor must not be zero");
}
let divided = dividend
.apply2(
divisor.v,
|a, b| {
let q = a.checked_div(b)?;
// Round towards negative infinity if the fraction is negative.
Some(DecNum::Int(if (a < 0) != (b < 0) && a % b != 0 {
q - 1
} else {
q
}))
},
|a, b| Some(DecNum::Float(a / b)),
|a, b| a.checked_div(b).map(DecNum::Decimal),
)
.ok_or_else(cant_apply_to_decimal_and_float)
.at(span)?
.ok_or_else(too_large)
.at(span)?;
floor(divided).at(span)
}
/// Calculates the p-norm of a sequence of values.
///
/// ```example
/// #calc.norm(1, 2, -3, 0.5) \
/// #calc.norm(p: 3, 1, 2)
/// ```
#[func(title = "𝑝-Norm")]
pub fn norm(
/// The p value to calculate the p-norm of.
#[named]
#[default(Spanned::detached(2.0))]
p: Spanned<f64>,
/// The sequence of values from which to calculate the p-norm.
/// Returns `0.0` if empty.
#[variadic]
values: Vec<f64>,
) -> SourceResult<f64> {
if p.v <= 0.0 {
bail!(p.span, "p must be greater than zero");
}
// Create an iterator over the absolute values.
let abs = values.into_iter().map(f64::abs);
Ok(if p.v.is_infinite() {
// When p is infinity, the p-norm is the maximum of the absolute values.
abs.max_by(|a, b| a.total_cmp(b)).unwrap_or(0.0)
} else {
abs.map(|v| v.powf(p.v)).sum::<f64>().powf(1.0 / p.v)
})
}
/// A value which can be passed to functions that work with integers and floats.
#[derive(Debug, Copy, Clone)]
pub enum Num {
Int(i64),
Float(f64),
}
impl Num {
fn float(self) -> f64 {
match self {
Self::Int(v) => v as f64,
Self::Float(v) => v,
}
}
}
cast! {
Num,
self => match self {
Self::Int(v) => v.into_value(),
Self::Float(v) => v.into_value(),
},
v: i64 => Self::Int(v),
v: f64 => Self::Float(v),
}
/// A value which can be passed to functions that work with integers, floats,
/// and decimals.
#[derive(Debug, Copy, Clone)]
pub enum DecNum {
Int(i64),
Float(f64),
Decimal(Decimal),
}
impl DecNum {
/// Checks if this number is equivalent to zero.
fn is_zero(self) -> bool {
match self {
Self::Int(i) => i == 0,
Self::Float(f) => f == 0.0,
Self::Decimal(d) => d.is_zero(),
}
}
/// If this `DecNum` holds an integer or float, returns a float.
/// Otherwise, returns `None`.
fn float(self) -> Option<f64> {
match self {
Self::Int(i) => Some(i as f64),
Self::Float(f) => Some(f),
Self::Decimal(_) => None,
}
}
/// If this `DecNum` holds an integer or decimal, returns a decimal.
/// Otherwise, returns `None`.
fn decimal(self) -> Option<Decimal> {
match self {
Self::Int(i) => Some(Decimal::from(i)),
Self::Float(_) => None,
Self::Decimal(d) => Some(d),
}
}
/// Tries to apply a function to two decimal or numeric arguments.
///
/// Fails with `None` if one is a float and the other is a decimal.
fn apply2<T>(
self,
other: Self,
int: impl FnOnce(i64, i64) -> T,
float: impl FnOnce(f64, f64) -> T,
decimal: impl FnOnce(Decimal, Decimal) -> T,
) -> Option<T> {
match (self, other) {
(Self::Int(a), Self::Int(b)) => Some(int(a, b)),
(Self::Decimal(a), Self::Decimal(b)) => Some(decimal(a, b)),
(Self::Decimal(a), Self::Int(b)) => Some(decimal(a, Decimal::from(b))),
(Self::Int(a), Self::Decimal(b)) => Some(decimal(Decimal::from(a), b)),
(a, b) => Some(float(a.float()?, b.float()?)),
}
}
/// Tries to apply a function to three decimal or numeric arguments.
///
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/datetime.rs | crates/typst-library/src/foundations/datetime.rs | use std::cmp::Ordering;
use std::hash::Hash;
use std::ops::{Add, Sub};
use arrayvec::ArrayVec;
use ecow::{EcoString, EcoVec, eco_format};
use time::error::{Format, InvalidFormatDescription};
use time::macros::format_description;
use time::{Month, PrimitiveDateTime, format_description};
use crate::World;
use crate::diag::{HintedStrResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Dict, Duration, Repr, Smart, Str, Value, cast, func, repr, scope, ty,
};
/// Represents a date, a time, or a combination of both.
///
/// Can be created by either specifying a custom datetime using this type's
/// constructor function or getting the current date with [`datetime.today`].
///
/// # Example
/// ```example
/// #let date = datetime(
/// year: 2020,
/// month: 10,
/// day: 4,
/// )
///
/// #date.display() \
/// #date.display(
/// "y:[year repr:last_two]"
/// )
///
/// #let time = datetime(
/// hour: 18,
/// minute: 2,
/// second: 23,
/// )
///
/// #time.display() \
/// #time.display(
/// "h:[hour repr:12][period]"
/// )
/// ```
///
/// # Datetime and Duration
/// You can get a [duration] by subtracting two datetime:
/// ```example
/// #let first-of-march = datetime(day: 1, month: 3, year: 2024)
/// #let first-of-jan = datetime(day: 1, month: 1, year: 2024)
/// #let distance = first-of-march - first-of-jan
/// #distance.hours()
/// ```
///
/// You can also add/subtract a datetime and a duration to retrieve a new,
/// offset datetime:
/// ```example
/// #let date = datetime(day: 1, month: 3, year: 2024)
/// #let two-days = duration(days: 2)
/// #let two-days-earlier = date - two-days
/// #let two-days-later = date + two-days
///
/// #date.display() \
/// #two-days-earlier.display() \
/// #two-days-later.display()
/// ```
///
/// # Format
/// You can specify a customized formatting using the
/// [`display`]($datetime.display) method. The format of a datetime is
/// specified by providing _components_ with a specified number of _modifiers_.
/// A component represents a certain part of the datetime that you want to
/// display, and with the help of modifiers you can define how you want to
/// display that component. In order to display a component, you wrap the name
/// of the component in square brackets (e.g. `[[year]]` will display the year).
/// In order to add modifiers, you add a space after the component name followed
/// by the name of the modifier, a colon and the value of the modifier (e.g.
/// `[[month repr:short]]` will display the short representation of the month).
///
/// The possible combination of components and their respective modifiers is as
/// follows:
///
/// - `year`: Displays the year of the datetime.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// year is padded.
/// - `repr` Can be either `full` in which case the full year is displayed or
/// `last_two` in which case only the last two digits are displayed.
/// - `sign`: Can be either `automatic` or `mandatory`. Specifies when the
/// sign should be displayed.
/// - `month`: Displays the month of the datetime.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// month is padded.
/// - `repr`: Can be either `numerical`, `long` or `short`. Specifies if the
/// month should be displayed as a number or a word. Unfortunately, when
/// choosing the word representation, it can currently only display the
/// English version. In the future, it is planned to support localization.
/// - `day`: Displays the day of the datetime.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// day is padded.
/// - `week_number`: Displays the week number of the datetime.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// week number is padded.
/// - `repr`: Can be either `ISO`, `sunday` or `monday`. In the case of `ISO`,
/// week numbers are between 1 and 53, while the other ones are between 0
/// and 53.
/// - `weekday`: Displays the weekday of the date.
/// - `repr` Can be either `long`, `short`, `sunday` or `monday`. In the case
/// of `long` and `short`, the corresponding English name will be displayed
/// (same as for the month, other languages are currently not supported). In
/// the case of `sunday` and `monday`, the numerical value will be displayed
/// (assuming Sunday and Monday as the first day of the week, respectively).
/// - `one_indexed`: Can be either `true` or `false`. Defines whether the
/// numerical representation of the week starts with 0 or 1.
/// - `hour`: Displays the hour of the date.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// hour is padded.
/// - `repr`: Can be either `24` or `12`. Changes whether the hour is
/// displayed in the 24-hour or 12-hour format.
/// - `period`: The AM/PM part of the hour
/// - `case`: Can be `lower` to display it in lower case and `upper` to
/// display it in upper case.
/// - `minute`: Displays the minute of the date.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// minute is padded.
/// - `second`: Displays the second of the date.
/// - `padding`: Can be either `zero`, `space` or `none`. Specifies how the
/// second is padded.
///
/// Keep in mind that not always all components can be used. For example, if you
/// create a new datetime with `{datetime(year: 2023, month: 10, day: 13)}`, it
/// will be stored as a plain date internally, meaning that you cannot use
/// components such as `hour` or `minute`, which would only work on datetimes
/// that have a specified time.
#[ty(scope, cast)]
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
pub enum Datetime {
/// Representation as a date.
Date(time::Date),
/// Representation as a time.
Time(time::Time),
/// Representation as a combination of date and time.
Datetime(time::PrimitiveDateTime),
}
impl Datetime {
/// Create a datetime from year, month, and day.
pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
Some(Datetime::Date(
time::Date::from_calendar_date(year, time::Month::try_from(month).ok()?, day)
.ok()?,
))
}
/// Create a datetime from hour, minute, and second.
pub fn from_hms(hour: u8, minute: u8, second: u8) -> Option<Self> {
Some(Datetime::Time(time::Time::from_hms(hour, minute, second).ok()?))
}
/// Create a datetime from day and time.
pub fn from_ymd_hms(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Option<Self> {
let date =
time::Date::from_calendar_date(year, time::Month::try_from(month).ok()?, day)
.ok()?;
let time = time::Time::from_hms(hour, minute, second).ok()?;
Some(Datetime::Datetime(PrimitiveDateTime::new(date, time)))
}
/// Try to parse a dictionary as a TOML date.
pub fn from_toml_dict(dict: &Dict) -> Option<Self> {
if dict.len() != 1 {
return None;
}
let Ok(Value::Str(string)) = dict.get("$__toml_private_datetime") else {
return None;
};
if let Ok(d) = time::PrimitiveDateTime::parse(
string,
&format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z"),
) {
Self::from_ymd_hms(
d.year(),
d.month() as u8,
d.day(),
d.hour(),
d.minute(),
d.second(),
)
} else if let Ok(d) = time::PrimitiveDateTime::parse(
string,
&format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"),
) {
Self::from_ymd_hms(
d.year(),
d.month() as u8,
d.day(),
d.hour(),
d.minute(),
d.second(),
)
} else if let Ok(d) =
time::Date::parse(string, &format_description!("[year]-[month]-[day]"))
{
Self::from_ymd(d.year(), d.month() as u8, d.day())
} else if let Ok(d) =
time::Time::parse(string, &format_description!("[hour]:[minute]:[second]"))
{
Self::from_hms(d.hour(), d.minute(), d.second())
} else {
None
}
}
/// Which kind of variant this datetime stores.
pub fn kind(&self) -> &'static str {
match self {
Datetime::Datetime(_) => "datetime",
Datetime::Date(_) => "date",
Datetime::Time(_) => "time",
}
}
}
#[scope]
impl Datetime {
/// Creates a new datetime.
///
/// You can specify the [datetime] using a year, month, day, hour, minute,
/// and second.
///
/// _Note_: Depending on which components of the datetime you specify, Typst
/// will store it in one of the following three ways:
/// * If you specify year, month and day, Typst will store just a date.
/// * If you specify hour, minute and second, Typst will store just a time.
/// * If you specify all of year, month, day, hour, minute and second, Typst
/// will store a full datetime.
///
/// Depending on how it is stored, the [`display`]($datetime.display) method
/// will choose a different formatting by default.
///
/// ```example
/// #datetime(
/// year: 2012,
/// month: 8,
/// day: 3,
/// ).display()
/// ```
#[func(constructor)]
pub fn construct(
/// The year of the datetime.
#[named]
year: Option<i32>,
/// The month of the datetime.
#[named]
month: Option<Month>,
/// The day of the datetime.
#[named]
day: Option<u8>,
/// The hour of the datetime.
#[named]
hour: Option<u8>,
/// The minute of the datetime.
#[named]
minute: Option<u8>,
/// The second of the datetime.
#[named]
second: Option<u8>,
) -> HintedStrResult<Datetime> {
fn format_missing_args(args: ArrayVec<&str, 3>) -> EcoString {
match args.as_slice() {
[] => unreachable!(),
[arg] => eco_format!("the {arg} argument"),
[arg1, arg2] => eco_format!("the {arg1} and {arg2} arguments"),
[args @ .., tail] => {
eco_format!("the {}, and {tail} arguments", args.join(", "))
}
}
}
let time = match (hour, minute, second) {
(Some(hour), Some(minute), Some(second)) => {
match time::Time::from_hms(hour, minute, second) {
Ok(time) => Some(time),
Err(_) => bail!("time is invalid"),
}
}
(None, None, None) => None,
(hour, minute, second) => {
let args = [
if hour.is_none() { Some("`hour`") } else { None },
if minute.is_none() { Some("`minute`") } else { None },
if second.is_none() { Some("`second`") } else { None },
];
bail!(
"time is incomplete";
hint: "add {} to get a valid time",
format_missing_args(args.into_iter().flatten().collect());
)
}
};
let date = match (year, month, day) {
(Some(year), Some(month), Some(day)) => {
match time::Date::from_calendar_date(year, month, day) {
Ok(date) => Some(date),
Err(_) => bail!("date is invalid"),
}
}
(None, None, None) => None,
(year, month, day) => {
let args = [
if year.is_none() { Some("`year`") } else { None },
if month.is_none() { Some("`month`") } else { None },
if day.is_none() { Some("`day`") } else { None },
];
bail!(
"date is incomplete";
hint: "add {} to get a valid date",
format_missing_args(args.into_iter().flatten().collect());
)
}
};
Ok(match (date, time) {
(Some(date), Some(time)) => {
Datetime::Datetime(PrimitiveDateTime::new(date, time))
}
(Some(date), None) => Datetime::Date(date),
(None, Some(time)) => Datetime::Time(time),
(None, None) => {
bail!(
"at least one of date or time must be fully specified";
hint: "add the `hour`, `minute`, and `second` arguments to get a valid time";
hint: "add the `year`, `month`, and `day` arguments to get a valid date";
)
}
})
}
/// Returns the current date.
///
/// In the CLI, this can be overridden with the `--creation-timestamp`
/// argument or by setting the
/// [`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/specs/source-date-epoch/)
/// environment variable. In both cases, the value should be given as a UNIX
/// timestamp.
///
/// ```example
/// Today's date is
/// #datetime.today().display().
/// ```
#[func]
pub fn today(
engine: &mut Engine,
/// An offset to apply to the current UTC date. If set to `{auto}`, the
/// offset will be the local offset.
#[named]
#[default]
offset: Smart<i64>,
) -> StrResult<Datetime> {
Ok(engine
.world
.today(offset.custom())
.ok_or("unable to get the current date")?)
}
/// Displays the datetime in a specified format.
///
/// Depending on whether you have defined just a date, a time or both, the
/// default format will be different. If you specified a date, it will be
/// `[[year]-[month]-[day]]`. If you specified a time, it will be
/// `[[hour]:[minute]:[second]]`. In the case of a datetime, it will be
/// `[[year]-[month]-[day] [hour]:[minute]:[second]]`.
///
/// See the [format syntax]($datetime/#format) for more information.
#[func]
pub fn display(
&self,
/// The format used to display the datetime.
#[default]
pattern: Smart<DisplayPattern>,
) -> StrResult<EcoString> {
let pat = |s| format_description::parse_borrowed::<2>(s).unwrap();
let result = match pattern {
Smart::Auto => match self {
Self::Date(date) => date.format(&pat("[year]-[month]-[day]")),
Self::Time(time) => time.format(&pat("[hour]:[minute]:[second]")),
Self::Datetime(datetime) => {
datetime.format(&pat("[year]-[month]-[day] [hour]:[minute]:[second]"))
}
},
Smart::Custom(DisplayPattern(_, format)) => match self {
Self::Date(date) => date.format(&format),
Self::Time(time) => time.format(&format),
Self::Datetime(datetime) => datetime.format(&format),
},
};
result.map(EcoString::from).map_err(format_time_format_error)
}
/// The year if it was specified, or `{none}` for times without a date.
#[func]
pub fn year(&self) -> Option<i32> {
match self {
Self::Date(date) => Some(date.year()),
Self::Time(_) => None,
Self::Datetime(datetime) => Some(datetime.year()),
}
}
/// The month if it was specified, or `{none}` for times without a date.
#[func]
pub fn month(&self) -> Option<u8> {
match self {
Self::Date(date) => Some(date.month().into()),
Self::Time(_) => None,
Self::Datetime(datetime) => Some(datetime.month().into()),
}
}
/// The weekday (counting Monday as 1) or `{none}` for times without a date.
#[func]
pub fn weekday(&self) -> Option<u8> {
match self {
Self::Date(date) => Some(date.weekday().number_from_monday()),
Self::Time(_) => None,
Self::Datetime(datetime) => Some(datetime.weekday().number_from_monday()),
}
}
/// The day if it was specified, or `{none}` for times without a date.
#[func]
pub fn day(&self) -> Option<u8> {
match self {
Self::Date(date) => Some(date.day()),
Self::Time(_) => None,
Self::Datetime(datetime) => Some(datetime.day()),
}
}
/// The hour if it was specified, or `{none}` for dates without a time.
#[func]
pub fn hour(&self) -> Option<u8> {
match self {
Self::Date(_) => None,
Self::Time(time) => Some(time.hour()),
Self::Datetime(datetime) => Some(datetime.hour()),
}
}
/// The minute if it was specified, or `{none}` for dates without a time.
#[func]
pub fn minute(&self) -> Option<u8> {
match self {
Self::Date(_) => None,
Self::Time(time) => Some(time.minute()),
Self::Datetime(datetime) => Some(datetime.minute()),
}
}
/// The second if it was specified, or `{none}` for dates without a time.
#[func]
pub fn second(&self) -> Option<u8> {
match self {
Self::Date(_) => None,
Self::Time(time) => Some(time.second()),
Self::Datetime(datetime) => Some(datetime.second()),
}
}
/// The ordinal (day of the year), or `{none}` for times without a date.
#[func]
pub fn ordinal(&self) -> Option<u16> {
match self {
Self::Datetime(datetime) => Some(datetime.ordinal()),
Self::Date(date) => Some(date.ordinal()),
Self::Time(_) => None,
}
}
}
impl Repr for Datetime {
fn repr(&self) -> EcoString {
let year = self.year().map(|y| eco_format!("year: {}", (y as i64).repr()));
let month = self.month().map(|m| eco_format!("month: {}", (m as i64).repr()));
let day = self.day().map(|d| eco_format!("day: {}", (d as i64).repr()));
let hour = self.hour().map(|h| eco_format!("hour: {}", (h as i64).repr()));
let minute = self.minute().map(|m| eco_format!("minute: {}", (m as i64).repr()));
let second = self.second().map(|s| eco_format!("second: {}", (s as i64).repr()));
let filtered = [year, month, day, hour, minute, second]
.into_iter()
.flatten()
.collect::<EcoVec<_>>();
eco_format!("datetime{}", &repr::pretty_array_like(&filtered, false))
}
}
impl PartialOrd for Datetime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(Self::Datetime(a), Self::Datetime(b)) => a.partial_cmp(b),
(Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
(Self::Time(a), Self::Time(b)) => a.partial_cmp(b),
_ => None,
}
}
}
impl Add<Duration> for Datetime {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
let rhs: time::Duration = rhs.into();
match self {
Self::Datetime(datetime) => Self::Datetime(datetime + rhs),
Self::Date(date) => Self::Date(date + rhs),
Self::Time(time) => Self::Time(time + rhs),
}
}
}
impl Sub<Duration> for Datetime {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
let rhs: time::Duration = rhs.into();
match self {
Self::Datetime(datetime) => Self::Datetime(datetime - rhs),
Self::Date(date) => Self::Date(date - rhs),
Self::Time(time) => Self::Time(time - rhs),
}
}
}
impl Sub for Datetime {
type Output = StrResult<Duration>;
fn sub(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(Self::Datetime(a), Self::Datetime(b)) => Ok((a - b).into()),
(Self::Date(a), Self::Date(b)) => Ok((a - b).into()),
(Self::Time(a), Self::Time(b)) => Ok((a - b).into()),
(a, b) => bail!("cannot subtract {} from {}", b.kind(), a.kind()),
}
}
}
/// A format in which a datetime can be displayed.
pub struct DisplayPattern(Str, format_description::OwnedFormatItem);
cast! {
DisplayPattern,
self => self.0.into_value(),
v: Str => {
let item = format_description::parse_owned::<2>(&v)
.map_err(format_time_invalid_format_description_error)?;
Self(v, item)
}
}
cast! {
Month,
v: u8 => Self::try_from(v).map_err(|_| "month is invalid")?
}
/// Format the `Format` error of the time crate in an appropriate way.
fn format_time_format_error(error: Format) -> EcoString {
match error {
Format::InvalidComponent(name) => eco_format!("invalid component '{}'", name),
Format::InsufficientTypeInformation { .. } => {
"failed to format datetime (insufficient information)".into()
}
err => eco_format!("failed to format datetime in the requested format ({err})"),
}
}
/// Format the `InvalidFormatDescription` error of the time crate in an
/// appropriate way.
fn format_time_invalid_format_description_error(
error: InvalidFormatDescription,
) -> EcoString {
match error {
InvalidFormatDescription::UnclosedOpeningBracket { index, .. } => {
eco_format!("missing closing bracket for bracket at index {}", index)
}
InvalidFormatDescription::InvalidComponentName { name, index, .. } => {
eco_format!("invalid component name '{}' at index {}", name, index)
}
InvalidFormatDescription::InvalidModifier { value, index, .. } => {
eco_format!("invalid modifier '{}' at index {}", value, index)
}
InvalidFormatDescription::Expected { what, index, .. } => {
eco_format!("expected {} at index {}", what, index)
}
InvalidFormatDescription::MissingComponentName { index, .. } => {
eco_format!("expected component name at index {}", index)
}
InvalidFormatDescription::MissingRequiredModifier { name, index, .. } => {
eco_format!(
"missing required modifier {} for component at index {}",
name,
index
)
}
InvalidFormatDescription::NotSupported { context, what, index, .. } => {
eco_format!("{} is not supported in {} at index {}", what, context, index)
}
err => eco_format!("failed to parse datetime format ({err})"),
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/module.rs | crates/typst-library/src/foundations/module.rs | use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use ecow::{EcoString, eco_format};
use typst_syntax::FileId;
use crate::diag::{DeprecationSink, StrResult, bail};
use crate::foundations::{Content, Repr, Scope, Value, ty};
/// A collection of variables and functions that are commonly related to
/// a single theme.
///
/// A module can
/// - be built-in
/// - stem from a [file import]($scripting/#modules)
/// - stem from a [package import]($scripting/#packages) (and thus indirectly
/// its entrypoint file)
/// - result from a call to the [plugin]($plugin) function
///
/// You can access definitions from the module using [field access
/// notation]($scripting/#fields) and interact with it using the [import and
/// include syntaxes]($scripting/#modules).
///
/// ```example
/// <<< #import "utils.typ"
/// <<< #utils.add(2, 5)
///
/// <<< #import utils: sub
/// <<< #sub(1, 4)
/// >>> #7
/// >>>
/// >>> #(-3)
/// ```
///
/// You can check whether a definition is present in a module using the `{in}`
/// operator, with a string on the left-hand side. This can be useful to
/// [conditionally access]($category/foundations/std/#conditional-access)
/// definitions in a module.
///
/// ```example
/// #("table" in std) \
/// #("nope" in std)
/// ```
///
/// Alternatively, it is possible to convert a module to a dictionary, and
/// therefore access its contents dynamically, using the [dictionary
/// constructor]($dictionary/#constructor).
#[ty(cast)]
#[derive(Clone, Hash)]
pub struct Module {
/// The module's name.
name: Option<EcoString>,
/// The reference-counted inner fields.
inner: Arc<ModuleInner>,
}
/// The internal representation of a [`Module`].
#[derive(Debug, Clone, Hash)]
struct ModuleInner {
/// The top-level definitions that were bound in this module.
scope: Scope,
/// The module's layoutable contents.
content: Content,
/// The id of the file which defines the module, if any.
file_id: Option<FileId>,
}
impl Module {
/// Create a new module.
pub fn new(name: impl Into<EcoString>, scope: Scope) -> Self {
Self {
name: Some(name.into()),
inner: Arc::new(ModuleInner {
scope,
content: Content::empty(),
file_id: None,
}),
}
}
/// Create a new anonymous module without a name.
pub fn anonymous(scope: Scope) -> Self {
Self {
name: None,
inner: Arc::new(ModuleInner {
scope,
content: Content::empty(),
file_id: None,
}),
}
}
/// Update the module's name.
pub fn with_name(mut self, name: impl Into<EcoString>) -> Self {
self.name = Some(name.into());
self
}
/// Update the module's scope.
pub fn with_scope(mut self, scope: Scope) -> Self {
Arc::make_mut(&mut self.inner).scope = scope;
self
}
/// Update the module's content.
pub fn with_content(mut self, content: Content) -> Self {
Arc::make_mut(&mut self.inner).content = content;
self
}
/// Update the module's file id.
pub fn with_file_id(mut self, file_id: FileId) -> Self {
Arc::make_mut(&mut self.inner).file_id = Some(file_id);
self
}
/// Get the module's name.
pub fn name(&self) -> Option<&EcoString> {
self.name.as_ref()
}
/// Access the module's scope.
pub fn scope(&self) -> &Scope {
&self.inner.scope
}
/// Access the module's file id.
///
/// Some modules are not associated with a file, like the built-in modules.
pub fn file_id(&self) -> Option<FileId> {
self.inner.file_id
}
/// Access the module's scope, mutably.
pub fn scope_mut(&mut self) -> &mut Scope {
&mut Arc::make_mut(&mut self.inner).scope
}
/// Try to access a definition in the module.
pub fn field(&self, field: &str, sink: impl DeprecationSink) -> StrResult<&Value> {
match self.scope().get(field) {
Some(binding) => Ok(binding.read_checked(sink)),
None => match &self.name {
Some(name) => bail!("module `{name}` does not contain `{field}`"),
None => bail!("module does not contain `{field}`"),
},
}
}
/// Extract the module's content.
pub fn content(self) -> Content {
match Arc::try_unwrap(self.inner) {
Ok(repr) => repr.content,
Err(arc) => arc.content.clone(),
}
}
}
impl Debug for Module {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Module")
.field("name", &self.name)
.field("scope", &self.inner.scope)
.field("content", &self.inner.content)
.finish()
}
}
impl Repr for Module {
fn repr(&self) -> EcoString {
match &self.name {
Some(module) => eco_format!("<module {module}>"),
None => "<module>".into(),
}
}
}
impl PartialEq for Module {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && Arc::ptr_eq(&self.inner, &other.inner)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/styles.rs | crates/typst-library/src/foundations/styles.rs | use std::any::{Any, TypeId};
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::{mem, ptr};
use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_vec};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use typst_syntax::Span;
use typst_utils::LazyHash;
use crate::diag::{SourceResult, Trace, Tracepoint};
use crate::engine::Engine;
use crate::foundations::{
Content, Context, Element, Field, Func, NativeElement, OneOrMultiple, Packed,
RefableProperty, Repr, Selector, SettableProperty, Target, cast, ty,
};
use crate::introspection::TagElem;
/// A list of style properties.
#[ty(cast)]
#[derive(Default, Clone, PartialEq, Hash)]
pub struct Styles(EcoVec<LazyHash<Style>>);
impl Styles {
/// Create a new, empty style list.
pub const fn new() -> Self {
Self(EcoVec::new())
}
/// Whether this contains no styles.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Iterate over the contained styles.
pub fn iter(&self) -> impl Iterator<Item = &Style> {
self.0.iter().map(|style| &**style)
}
/// Iterate over the contained styles.
pub fn as_slice(&self) -> &[LazyHash<Style>] {
self.0.as_slice()
}
/// Set an inner value for a style property.
///
/// If the property needs folding and the value is already contained in the
/// style map, `self` contributes the outer values and `value` is the inner
/// one.
pub fn set<E, const I: u8>(&mut self, field: Field<E, I>, value: E::Type)
where
E: SettableProperty<I>,
E::Type: Debug + Clone + Hash + Send + Sync + 'static,
{
self.push(Property::new(field, value));
}
/// Add a new style to the list.
pub fn push(&mut self, style: impl Into<Style>) {
self.0.push(LazyHash::new(style.into()));
}
/// Remove the style that was last set.
pub fn unset(&mut self) {
self.0.pop();
}
/// Apply outer styles. Like [`chain`](StyleChain::chain), but in-place.
pub fn apply(&mut self, mut outer: Self) {
outer.0.extend(mem::take(self).0);
*self = outer;
}
/// Apply one outer styles.
pub fn apply_one(&mut self, outer: Style) {
self.0.insert(0, LazyHash::new(outer));
}
/// Add an origin span to all contained properties.
pub fn spanned(mut self, span: Span) -> Self {
for entry in self.0.make_mut() {
if let Style::Property(property) = &mut **entry {
property.span = span;
}
}
self
}
/// Marks the styles as having been applied outside of any show rule.
pub fn outside(mut self) -> Self {
for entry in self.0.make_mut() {
match &mut **entry {
Style::Property(property) => property.outside = true,
Style::Recipe(recipe) => recipe.outside = true,
_ => {}
}
}
self
}
/// Marks the styles as being allowed to be lifted up to the page level.
pub fn liftable(mut self) -> Self {
for entry in self.0.make_mut() {
if let Style::Property(property) = &mut **entry {
property.liftable = true;
}
}
self
}
/// Whether there is a style for the given field of the given element.
pub fn has<E: NativeElement, const I: u8>(&self, _: Field<E, I>) -> bool {
let elem = E::ELEM;
self.0
.iter()
.filter_map(|style| style.property())
.any(|property| property.is_of(elem) && property.id == I)
}
/// Determines the styles used for content that it at the root, outside of
/// the user-controlled content (e.g. page marginals and footnotes). This
/// applies to both paged and HTML export.
///
/// As a base, we collect the styles that are shared by all elements in the
/// children (this can be a whole document in HTML or a page run in paged
/// export). As a fallback if there are no elements, we use the styles
/// active at the very start or, for page runs, at the pagebreak that
/// introduced the page. Then, to produce our trunk styles, we filter this
/// list of styles according to a few rules:
///
/// - Other styles are only kept if they are `outside && (initial ||
/// liftable)`.
/// - "Outside" means they were not produced within a show rule or, for page
/// runs, that the show rule "broke free" to the root level by emitting
/// page styles.
/// - "Initial" means they were active where the children start (efor pages,
/// at the pagebreak that introduced the page). Since these are
/// intuitively already active, they should be kept even if not liftable.
/// (E.g. `text(red, page(..)`) makes the footer red.)
/// - "Liftable" means they can be lifted to the root level even though
/// they weren't yet active at the very beginning. Set rule styles are
/// liftable as opposed to direct constructor calls:
/// - For `set page(..); set text(red)` the red text is kept even though
/// it comes after the weak pagebreak from set page.
/// - For `set page(..); text(red)[..]` the red isn't kept because the
/// constructor styles are not liftable.
pub fn root(children: &[(&Content, StyleChain)], initial: StyleChain) -> Styles {
// Determine the shared styles (excluding tags).
let base = StyleChain::trunk_from_pairs(children).unwrap_or(initial).to_map();
// Determine the initial styles that are also shared by everything. We can't
// use `StyleChain::trunk` because it currently doesn't deal with partially
// shared links (where a subslice matches).
let trunk_len = initial
.to_map()
.as_slice()
.iter()
.zip(base.as_slice())
.take_while(|&(a, b)| a == b)
.count();
// Filter the base styles according to our rules.
base.into_iter()
.enumerate()
.filter(|(i, style)| {
let initial = *i < trunk_len;
style.outside() && (initial || style.liftable())
})
.map(|(_, style)| style)
.collect()
}
}
impl From<LazyHash<Style>> for Styles {
fn from(style: LazyHash<Style>) -> Self {
Self(eco_vec![style])
}
}
impl From<Style> for Styles {
fn from(style: Style) -> Self {
Self(eco_vec![LazyHash::new(style)])
}
}
impl IntoIterator for Styles {
type Item = LazyHash<Style>;
type IntoIter = ecow::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<LazyHash<Style>> for Styles {
fn from_iter<T: IntoIterator<Item = LazyHash<Style>>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl Debug for Styles {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Styles ")?;
f.debug_list().entries(&self.0).finish()
}
}
impl Repr for Styles {
fn repr(&self) -> EcoString {
"styles(..)".into()
}
}
/// A single style property or recipe.
#[derive(Clone, Hash)]
pub enum Style {
/// A style property originating from a set rule or constructor.
Property(Property),
/// A show rule recipe.
Recipe(Recipe),
/// Disables a specific show rule recipe.
///
/// Note: This currently only works for regex recipes since it's the only
/// place we need it for the moment. Normal show rules use guards directly
/// on elements instead.
Revocation(RecipeIndex),
}
impl Style {
/// If this is a property, return it.
pub fn property(&self) -> Option<&Property> {
match self {
Self::Property(property) => Some(property),
_ => None,
}
}
/// If this is a recipe, return it.
pub fn recipe(&self) -> Option<&Recipe> {
match self {
Self::Recipe(recipe) => Some(recipe),
_ => None,
}
}
/// The style's span, if any.
pub fn span(&self) -> Span {
match self {
Self::Property(property) => property.span,
Self::Recipe(recipe) => recipe.span,
Self::Revocation(_) => Span::detached(),
}
}
/// Returns `Some(_)` with an optional span if this style is for
/// the given element.
pub fn element(&self) -> Option<Element> {
match self {
Style::Property(property) => Some(property.elem),
Style::Recipe(recipe) => match recipe.selector {
Some(Selector::Elem(elem, _)) => Some(elem),
_ => None,
},
Style::Revocation(_) => None,
}
}
/// Whether the style is allowed to be lifted up to the page level. Only
/// true for styles originating from set rules.
pub fn liftable(&self) -> bool {
match self {
Self::Property(property) => property.liftable,
Self::Recipe(_) => true,
Self::Revocation(_) => false,
}
}
/// Whether the style was applied outside of any show rule. This is set
/// during realization.
pub fn outside(&self) -> bool {
match self {
Self::Property(property) => property.outside,
Self::Recipe(recipe) => recipe.outside,
Self::Revocation(_) => false,
}
}
/// Turn this style into prehashed style.
pub fn wrap(self) -> LazyHash<Style> {
LazyHash::new(self)
}
}
impl Debug for Style {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Property(property) => property.fmt(f),
Self::Recipe(recipe) => recipe.fmt(f),
Self::Revocation(guard) => guard.fmt(f),
}
}
}
impl From<Property> for Style {
fn from(property: Property) -> Self {
Self::Property(property)
}
}
impl From<Recipe> for Style {
fn from(recipe: Recipe) -> Self {
Self::Recipe(recipe)
}
}
/// A style property originating from a set rule or constructor.
#[derive(Clone, Hash)]
pub struct Property {
/// The element the property belongs to.
elem: Element,
/// The property's ID.
id: u8,
/// The property's value.
value: Block,
/// The span of the set rule the property stems from.
span: Span,
/// Whether the property is allowed to be lifted up to the page level.
liftable: bool,
/// Whether the property was applied outside of any show rule.
outside: bool,
}
impl Property {
/// Create a new property from a key-value pair.
pub fn new<E, const I: u8>(_: Field<E, I>, value: E::Type) -> Self
where
E: SettableProperty<I>,
E::Type: Debug + Clone + Hash + Send + Sync + 'static,
{
Self {
elem: E::ELEM,
id: I,
value: Block::new(value),
span: Span::detached(),
liftable: false,
outside: false,
}
}
/// Whether this property is the given one.
pub fn is(&self, elem: Element, id: u8) -> bool {
self.elem == elem && self.id == id
}
/// Whether this property belongs to the given element.
pub fn is_of(&self, elem: Element) -> bool {
self.elem == elem
}
/// Turn this property into prehashed style.
pub fn wrap(self) -> LazyHash<Style> {
Style::Property(self).wrap()
}
}
impl Debug for Property {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"Set({}.{}: ",
self.elem.name(),
self.elem.field_name(self.id).unwrap_or("internal")
)?;
self.value.fmt(f)?;
write!(f, ")")
}
}
/// A block storage for storing style values.
///
/// We're using a `Box` since values will either be contained in an `Arc` and
/// therefore already on the heap or they will be small enough that we can just
/// clone them.
#[derive(Hash)]
struct Block(Box<dyn Blockable>);
impl Block {
/// Creates a new block.
fn new<T: Blockable>(value: T) -> Self {
Self(Box::new(value))
}
/// Downcasts the block to the specified type.
fn downcast<T: 'static>(&self, func: Element, id: u8) -> &T {
let inner: &dyn Blockable = &*self.0;
(inner as &dyn Any)
.downcast_ref()
.unwrap_or_else(|| block_wrong_type(func, id, self))
}
}
impl Debug for Block {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Clone for Block {
fn clone(&self) -> Self {
self.0.dyn_clone()
}
}
/// A value that can be stored in a block.
///
/// Auto derived for all types that implement [`Any`], [`Clone`], [`Hash`],
/// [`Debug`], [`Send`] and [`Sync`].
trait Blockable: Debug + Any + Send + Sync + 'static {
/// Equivalent to [`Hash`] for the block.
fn dyn_hash(&self, state: &mut dyn Hasher);
/// Equivalent to [`Clone`] for the block.
fn dyn_clone(&self) -> Block;
}
impl<T: Debug + Clone + Hash + Send + Sync + 'static> Blockable for T {
fn dyn_hash(&self, mut state: &mut dyn Hasher) {
// Also hash the TypeId since values with different types but
// equal data should be different.
TypeId::of::<Self>().hash(&mut state);
self.hash(&mut state);
}
fn dyn_clone(&self) -> Block {
Block(Box::new(self.clone()))
}
}
impl Hash for dyn Blockable {
fn hash<H: Hasher>(&self, state: &mut H) {
self.dyn_hash(state);
}
}
/// A show rule recipe.
#[derive(Clone, PartialEq, Hash)]
pub struct Recipe {
/// Determines whether the recipe applies to an element.
///
/// If this is `None`, then this recipe is from a show rule with
/// no selector (`show: rest => ...`), which is [eagerly applied][Content::styled_with_recipe]
/// to the rest of the content in the scope.
selector: Option<Selector>,
/// The transformation to perform on the match.
transform: Transformation,
/// The span that errors are reported with.
span: Span,
/// Relevant properties of the kind of construct the style originated from
/// and where it was applied.
outside: bool,
}
impl Recipe {
/// Create a new recipe from a key-value pair.
pub fn new(
selector: Option<Selector>,
transform: Transformation,
span: Span,
) -> Self {
Self { selector, transform, span, outside: false }
}
/// The recipe's selector.
pub fn selector(&self) -> Option<&Selector> {
self.selector.as_ref()
}
/// The recipe's transformation.
pub fn transform(&self) -> &Transformation {
&self.transform
}
/// The recipe's span.
pub fn span(&self) -> Span {
self.span
}
/// Apply the recipe to the given content.
pub fn apply(
&self,
engine: &mut Engine,
context: Tracked<Context>,
content: Content,
) -> SourceResult<Content> {
let mut content = match &self.transform {
Transformation::Content(content) => content.clone(),
Transformation::Func(func) => {
let mut result = func.call(engine, context, [content.clone()]);
if self.selector.is_some() {
let point = || Tracepoint::Show(content.func().name().into());
result = result.trace(engine.world, point, content.span());
}
result?.display()
}
Transformation::Style(styles) => content.styled_with_map(styles.clone()),
};
if content.span().is_detached() {
content = content.spanned(self.span);
}
Ok(content)
}
}
impl Debug for Recipe {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Show(")?;
if let Some(selector) = &self.selector {
selector.fmt(f)?;
f.write_str(", ")?;
}
self.transform.fmt(f)?;
f.write_str(")")
}
}
/// Identifies a show rule recipe from the top of the chain.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct RecipeIndex(pub usize);
/// A show rule transformation that can be applied to a match.
#[derive(Clone, PartialEq, Hash)]
pub enum Transformation {
/// Replacement content.
Content(Content),
/// A function to apply to the match.
Func(Func),
/// Apply styles to the content.
Style(Styles),
}
impl Debug for Transformation {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Content(content) => content.fmt(f),
Self::Func(func) => func.fmt(f),
Self::Style(styles) => styles.fmt(f),
}
}
}
cast! {
Transformation,
content: Content => Self::Content(content),
func: Func => Self::Func(func),
}
/// A chain of styles, similar to a linked list.
///
/// A style chain allows to combine properties from multiple style lists in a
/// element hierarchy in a non-allocating way. Rather than eagerly merging the
/// lists, each access walks the hierarchy from the innermost to the outermost
/// map, trying to find a match and then folding it with matches further up the
/// chain.
#[derive(Default, Copy, Clone, Hash)]
pub struct StyleChain<'a> {
/// The first link of this chain.
head: &'a [LazyHash<Style>],
/// The remaining links in the chain.
tail: Option<&'a Self>,
}
impl<'a> StyleChain<'a> {
/// Start a new style chain with root styles.
pub fn new(root: &'a Styles) -> Self {
Self { head: &root.0, tail: None }
}
/// Retrieves the value of the given field from the style chain.
///
/// A `Field` value is a zero-sized value that specifies which field of an
/// element you want to retrieve on the type-system level. It also ensures
/// that Rust can infer the correct return type.
///
/// Should be preferred over [`get_cloned`](Self::get_cloned) or
/// [`get_ref`](Self::get_ref), but is only available for [`Copy`] types.
/// For other types an explicit decision needs to be made whether cloning is
/// necessary.
pub fn get<E, const I: u8>(self, field: Field<E, I>) -> E::Type
where
E: SettableProperty<I>,
E::Type: Copy,
{
self.get_cloned(field)
}
/// Retrieves and clones the value from the style chain.
///
/// Prefer [`get`](Self::get) if the type is `Copy` and
/// [`get_ref`](Self::get_ref) if a reference suffices.
pub fn get_cloned<E, const I: u8>(self, _: Field<E, I>) -> E::Type
where
E: SettableProperty<I>,
{
if let Some(fold) = E::FOLD {
self.get_folded::<E::Type>(E::ELEM, I, fold, E::default())
} else {
self.get_unfolded::<E::Type>(E::ELEM, I)
.cloned()
.unwrap_or_else(E::default)
}
}
/// Retrieves a reference to the value of the given field from the style
/// chain.
///
/// Not possible if the value needs folding.
pub fn get_ref<E, const I: u8>(self, _: Field<E, I>) -> &'a E::Type
where
E: RefableProperty<I>,
{
self.get_unfolded(E::ELEM, I).unwrap_or_else(|| E::default_ref())
}
/// Retrieves the value and then immediately [resolves](Resolve) it.
pub fn resolve<E, const I: u8>(
self,
field: Field<E, I>,
) -> <E::Type as Resolve>::Output
where
E: SettableProperty<I>,
E::Type: Resolve,
{
self.get_cloned(field).resolve(self)
}
/// Retrieves a reference to a field, also taking into account the
/// instance's value if any.
fn get_unfolded<T: 'static>(self, func: Element, id: u8) -> Option<&'a T> {
self.find(func, id).map(|block| block.downcast(func, id))
}
/// Retrieves a reference to a field, also taking into account the
/// instance's value if any.
fn get_folded<T: 'static + Clone>(
self,
func: Element,
id: u8,
fold: fn(T, T) -> T,
default: T,
) -> T {
let iter = self
.properties(func, id)
.map(|block| block.downcast::<T>(func, id).clone());
if let Some(folded) = iter.reduce(fold) { fold(folded, default) } else { default }
}
/// Iterate over all values for the given property in the chain.
fn find(self, func: Element, id: u8) -> Option<&'a Block> {
self.properties(func, id).next()
}
/// Iterate over all values for the given property in the chain.
fn properties(self, func: Element, id: u8) -> impl Iterator<Item = &'a Block> {
self.entries()
.filter_map(|style| style.property())
.filter(move |property| property.is(func, id))
.map(|property| &property.value)
}
/// Make the given chainable the first link of this chain.
///
/// The resulting style chain contains styles from `local` as well as
/// `self`. The ones from `local` take precedence over the ones from
/// `self`. For folded properties `local` contributes the inner value.
pub fn chain<'b, C>(&'b self, local: &'b C) -> StyleChain<'b>
where
C: Chainable + ?Sized,
{
Chainable::chain(local, self)
}
/// Iterate over the entries of the chain.
pub fn entries(self) -> Entries<'a> {
Entries { inner: [].as_slice().iter(), links: self.links() }
}
/// Iterate over the recipes in the chain.
pub fn recipes(self) -> impl Iterator<Item = &'a Recipe> {
self.entries().filter_map(|style| style.recipe())
}
/// Iterate over the links of the chain.
pub fn links(self) -> Links<'a> {
Links(Some(self))
}
/// Convert to a style map.
pub fn to_map(self) -> Styles {
let mut styles: EcoVec<_> = self.entries().cloned().collect();
styles.make_mut().reverse();
Styles(styles)
}
/// Build owned styles from the suffix (all links beyond the `len`) of the
/// chain.
pub fn suffix(self, len: usize) -> Styles {
let mut styles = EcoVec::new();
let take = self.links().count().saturating_sub(len);
for link in self.links().take(take) {
styles.extend(link.iter().cloned().rev());
}
styles.make_mut().reverse();
Styles(styles)
}
/// Remove the last link from the chain.
pub fn pop(&mut self) {
*self = self.tail.copied().unwrap_or_default();
}
/// Determine the shared trunk of a collection of style chains.
pub fn trunk(iter: impl IntoIterator<Item = Self>) -> Option<Self> {
// Determine shared style depth and first span.
let mut iter = iter.into_iter();
let mut trunk = iter.next()?;
let mut depth = trunk.links().count();
for mut chain in iter {
let len = chain.links().count();
if len < depth {
for _ in 0..depth - len {
trunk.pop();
}
depth = len;
} else if len > depth {
for _ in 0..len - depth {
chain.pop();
}
}
while depth > 0 && chain != trunk {
trunk.pop();
chain.pop();
depth -= 1;
}
}
Some(trunk)
}
/// Determines the shared trunk of a list of elements.
///
/// This will ignore styles for tags (conceptually, they just don't exist).
pub fn trunk_from_pairs(iter: &[(&Content, Self)]) -> Option<Self> {
Self::trunk(iter.iter().filter(|(c, _)| !c.is::<TagElem>()).map(|&(_, s)| s))
}
}
impl Debug for StyleChain<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("StyleChain ")?;
f.debug_list()
.entries(self.entries().collect::<Vec<_>>().into_iter().rev())
.finish()
}
}
impl PartialEq for StyleChain<'_> {
fn eq(&self, other: &Self) -> bool {
ptr::eq(self.head, other.head)
&& match (self.tail, other.tail) {
(Some(a), Some(b)) => ptr::eq(a, b),
(None, None) => true,
_ => false,
}
}
}
/// Things that can be attached to a style chain.
pub trait Chainable {
/// Attach `self` as the first link of the chain.
fn chain<'a>(&'a self, outer: &'a StyleChain<'_>) -> StyleChain<'a>;
}
impl Chainable for LazyHash<Style> {
fn chain<'a>(&'a self, outer: &'a StyleChain<'_>) -> StyleChain<'a> {
StyleChain {
head: std::slice::from_ref(self),
tail: Some(outer),
}
}
}
impl Chainable for [LazyHash<Style>] {
fn chain<'a>(&'a self, outer: &'a StyleChain<'_>) -> StyleChain<'a> {
if self.is_empty() {
*outer
} else {
StyleChain { head: self, tail: Some(outer) }
}
}
}
impl<const N: usize> Chainable for [LazyHash<Style>; N] {
fn chain<'a>(&'a self, outer: &'a StyleChain<'_>) -> StyleChain<'a> {
Chainable::chain(self.as_slice(), outer)
}
}
impl Chainable for Styles {
fn chain<'a>(&'a self, outer: &'a StyleChain<'_>) -> StyleChain<'a> {
Chainable::chain(self.0.as_slice(), outer)
}
}
/// An iterator over the entries in a style chain.
pub struct Entries<'a> {
inner: std::slice::Iter<'a, LazyHash<Style>>,
links: Links<'a>,
}
impl<'a> Iterator for Entries<'a> {
type Item = &'a LazyHash<Style>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(entry) = self.inner.next_back() {
return Some(entry);
}
match self.links.next() {
Some(next) => self.inner = next.iter(),
None => return None,
}
}
}
}
/// An iterator over the links of a style chain.
pub struct Links<'a>(Option<StyleChain<'a>>);
impl<'a> Iterator for Links<'a> {
type Item = &'a [LazyHash<Style>];
fn next(&mut self) -> Option<Self::Item> {
let StyleChain { head, tail } = self.0?;
self.0 = tail.copied();
Some(head)
}
}
/// A property that is resolved with other properties from the style chain.
pub trait Resolve {
/// The type of the resolved output.
type Output;
/// Resolve the value using the style chain.
fn resolve(self, styles: StyleChain) -> Self::Output;
}
impl<T: Resolve> Resolve for Option<T> {
type Output = Option<T::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|v| v.resolve(styles))
}
}
/// A property that is folded to determine its final value.
///
/// In the example below, the chain of stroke values is folded into a single
/// value: `4pt + red`.
///
/// ```example
/// #set rect(stroke: red)
/// #set rect(stroke: 4pt)
/// #rect()
/// ```
///
/// Note: Folding must be associative, i.e. any implementation must satisfy
/// `fold(fold(a, b), c) == fold(a, fold(b, c))`.
pub trait Fold {
/// Fold this inner value with an outer folded value.
fn fold(self, outer: Self) -> Self;
}
impl Fold for bool {
fn fold(self, _: Self) -> Self {
self
}
}
impl<T: Fold> Fold for Option<T> {
fn fold(self, outer: Self) -> Self {
match (self, outer) {
(Some(inner), Some(outer)) => Some(inner.fold(outer)),
// An explicit `None` should be respected, thus we don't do
// `inner.or(outer)`.
(inner, _) => inner,
}
}
}
impl<T> Fold for Vec<T> {
fn fold(self, mut outer: Self) -> Self {
outer.extend(self);
outer
}
}
impl<T, const N: usize> Fold for SmallVec<[T; N]> {
fn fold(self, mut outer: Self) -> Self {
outer.extend(self);
outer
}
}
impl<T> Fold for OneOrMultiple<T> {
fn fold(self, mut outer: Self) -> Self {
outer.0.extend(self.0);
outer
}
}
/// A [folding](Fold) function.
pub type FoldFn<T> = fn(T, T) -> T;
/// A variant of fold for foldable optional (`Option<T>`) values where an inner
/// `None` value isn't respected (contrary to `Option`'s usual `Fold`
/// implementation, with which folding with an inner `None` always returns
/// `None`). Instead, when either of the `Option` objects is `None`, the other
/// one is necessarily returned by `fold_or`. Normal folding still occurs when
/// both values are `Some`, using `T`'s `Fold` implementation.
///
/// This is useful when `None` in a particular context means "unspecified"
/// rather than "absent", in which case a specified value (`Some`) is chosen
/// over an unspecified one (`None`), while two specified values are folded
/// together.
pub trait AlternativeFold {
/// Attempts to fold this inner value with an outer value. However, if
/// either value is `None`, returns the other one instead of folding.
fn fold_or(self, outer: Self) -> Self;
}
impl<T: Fold> AlternativeFold for Option<T> {
fn fold_or(self, outer: Self) -> Self {
match (self, outer) {
(Some(inner), Some(outer)) => Some(inner.fold(outer)),
// If one of values is `None`, return the other one instead of
// folding.
(inner, outer) => inner.or(outer),
}
}
}
/// A type that accumulates depth when folded.
#[derive(Debug, Default, Copy, Clone, PartialEq, Hash)]
pub struct Depth(pub usize);
impl Fold for Depth {
fn fold(self, outer: Self) -> Self {
Self(outer.0 + self.0)
}
}
#[cold]
fn block_wrong_type(func: Element, id: u8, value: &Block) -> ! {
panic!(
"attempted to read a value of a different type than was written {}.{}: {:?}",
func.name(),
func.field_name(id).unwrap(),
value
)
}
/// Holds native show rules.
pub struct NativeRuleMap {
rules: FxHashMap<(Element, Target), NativeShowRule>,
}
/// The signature of a native show rule.
pub type ShowFn<T> = fn(
elem: &Packed<T>,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Content>;
impl NativeRuleMap {
/// Creates a new rule map.
///
/// Should be populated with rules for all target-element combinations that
/// are supported.
///
/// Contains built-in rules for a few special elements.
pub fn new() -> Self {
let mut rules = Self { rules: FxHashMap::default() };
// ContextElem is as special as SequenceElem and StyledElem and could,
// in theory, also be special cased in realization.
rules.register_builtin(crate::foundations::CONTEXT_RULE);
// CounterDisplayElem only exists because the compiler can't currently
// express the equivalent of `context counter(..).display(..)` in native
// code (no native closures).
rules.register_builtin(crate::introspection::COUNTER_DISPLAY_RULE);
// These are all only for introspection and empty on all targets.
rules.register_empty::<crate::introspection::CounterUpdateElem>();
rules.register_empty::<crate::introspection::StateUpdateElem>();
rules.register_empty::<crate::introspection::MetadataElem>();
rules.register_empty::<crate::model::PrefixInfo>();
rules
}
/// Registers a rule for all targets.
fn register_empty<T: NativeElement>(&mut self) {
self.register_builtin::<T>(|_, _, _| Ok(Content::empty()));
}
/// Registers a rule for all targets.
fn register_builtin<T: NativeElement>(&mut self, f: ShowFn<T>) {
self.register(Target::Paged, f);
self.register(Target::Html, f);
}
/// Registers a rule for a target.
///
/// Panics if a rule already exists for this target-element combination.
pub fn register<T: NativeElement>(&mut self, target: Target, f: ShowFn<T>) {
let res = self.rules.insert((T::ELEM, target), NativeShowRule::new(f));
if res.is_some() {
panic!(
"duplicate native show rule for `{}` on {target:?} target",
T::ELEM.name()
)
}
}
/// Retrieves the rule that applies to the `content` on the current
/// `target`.
pub fn get(&self, target: Target, content: &Content) -> Option<NativeShowRule> {
self.rules.get(&(content.func(), target)).copied()
}
}
impl Default for NativeRuleMap {
fn default() -> Self {
Self::new()
}
}
pub use rule::NativeShowRule;
mod rule {
use super::*;
/// The show rule for a native element.
#[derive(Copy, Clone)]
pub struct NativeShowRule {
/// The element to which this rule applies.
elem: Element,
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/value.rs | crates/typst-library/src/foundations/value.rs | use std::any::{Any, TypeId};
use std::cmp::Ordering;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use ecow::{EcoString, eco_format};
use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer};
use serde::de::{Error, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use typst_syntax::{Span, ast};
use typst_utils::ArcExt;
use crate::diag::{DeprecationSink, HintedStrResult, HintedString, StrResult};
use crate::foundations::{
Args, Array, AutoValue, Bytes, CastInfo, Content, Datetime, Decimal, Dict, Duration,
Fold, FromValue, Func, IntoValue, Label, Module, NativeElement, NativeType,
NoneValue, Reflect, Repr, Resolve, Scope, Str, Styles, Symbol, SymbolElem, Type,
Version, fields, ops, repr,
};
use crate::layout::{Abs, Angle, Em, Fr, Length, Ratio, Rel};
use crate::text::{RawContent, RawElem, TextElem};
use crate::visualize::{Color, Gradient, Tiling};
/// A computational value.
#[derive(Default, Clone)]
pub enum Value {
/// The value that indicates the absence of a meaningful value.
#[default]
None,
/// A value that indicates some smart default behaviour.
Auto,
/// A boolean: `true, false`.
Bool(bool),
/// An integer: `120`.
Int(i64),
/// A floating-point number: `1.2`, `10e-4`.
Float(f64),
/// A length: `12pt`, `3cm`, `1.5em`, `1em - 2pt`.
Length(Length),
/// An angle: `1.5rad`, `90deg`.
Angle(Angle),
/// A ratio: `50%`.
Ratio(Ratio),
/// A relative length, combination of a ratio and a length: `20% + 5cm`.
Relative(Rel<Length>),
/// A fraction: `1fr`.
Fraction(Fr),
/// A color value: `#f79143ff`.
Color(Color),
/// A gradient value: `gradient.linear(...)`.
Gradient(Gradient),
/// A tiling fill: `tiling(...)`.
Tiling(Tiling),
/// A symbol: `arrow.l`.
Symbol(Symbol),
/// A version.
Version(Version),
/// A string: `"string"`.
Str(Str),
/// Raw bytes.
Bytes(Bytes),
/// A label: `<intro>`.
Label(Label),
/// A datetime
Datetime(Datetime),
/// A decimal value: `decimal("123.4500")`
Decimal(Decimal),
/// A duration
Duration(Duration),
/// A content value: `[*Hi* there]`.
Content(Content),
// Content styles.
Styles(Styles),
/// An array of values: `(1, "hi", 12cm)`.
Array(Array),
/// A dictionary value: `(a: 1, b: "hi")`.
Dict(Dict),
/// An executable function.
Func(Func),
/// Captured arguments to a function.
Args(Args),
/// A type.
Type(Type),
/// A module.
Module(Module),
/// A dynamic value.
Dyn(Dynamic),
}
impl Value {
/// Create a new dynamic value.
pub fn dynamic<T>(any: T) -> Self
where
T: Debug + Repr + NativeType + PartialEq + Hash + Sync + Send + 'static,
{
Self::Dyn(Dynamic::new(any))
}
/// Create a numeric value from a number with a unit.
pub fn numeric(pair: (f64, ast::Unit)) -> Self {
let (v, unit) = pair;
match unit {
ast::Unit::Pt => Abs::pt(v).into_value(),
ast::Unit::Mm => Abs::mm(v).into_value(),
ast::Unit::Cm => Abs::cm(v).into_value(),
ast::Unit::In => Abs::inches(v).into_value(),
ast::Unit::Rad => Angle::rad(v).into_value(),
ast::Unit::Deg => Angle::deg(v).into_value(),
ast::Unit::Em => Em::new(v).into_value(),
ast::Unit::Fr => Fr::new(v).into_value(),
ast::Unit::Percent => Ratio::new(v / 100.0).into_value(),
}
}
/// The type of this value.
pub fn ty(&self) -> Type {
match self {
Self::None => Type::of::<NoneValue>(),
Self::Auto => Type::of::<AutoValue>(),
Self::Bool(_) => Type::of::<bool>(),
Self::Int(_) => Type::of::<i64>(),
Self::Float(_) => Type::of::<f64>(),
Self::Length(_) => Type::of::<Length>(),
Self::Angle(_) => Type::of::<Angle>(),
Self::Ratio(_) => Type::of::<Ratio>(),
Self::Relative(_) => Type::of::<Rel<Length>>(),
Self::Fraction(_) => Type::of::<Fr>(),
Self::Color(_) => Type::of::<Color>(),
Self::Gradient(_) => Type::of::<Gradient>(),
Self::Tiling(_) => Type::of::<Tiling>(),
Self::Symbol(_) => Type::of::<Symbol>(),
Self::Version(_) => Type::of::<Version>(),
Self::Str(_) => Type::of::<Str>(),
Self::Bytes(_) => Type::of::<Bytes>(),
Self::Label(_) => Type::of::<Label>(),
Self::Datetime(_) => Type::of::<Datetime>(),
Self::Decimal(_) => Type::of::<Decimal>(),
Self::Duration(_) => Type::of::<Duration>(),
Self::Content(_) => Type::of::<Content>(),
Self::Styles(_) => Type::of::<Styles>(),
Self::Array(_) => Type::of::<Array>(),
Self::Dict(_) => Type::of::<Dict>(),
Self::Func(_) => Type::of::<Func>(),
Self::Args(_) => Type::of::<Args>(),
Self::Type(_) => Type::of::<Type>(),
Self::Module(_) => Type::of::<Module>(),
Self::Dyn(v) => v.ty(),
}
}
/// Try to cast the value into a specific type.
pub fn cast<T: FromValue>(self) -> HintedStrResult<T> {
T::from_value(self)
}
/// Try to access a field on the value.
pub fn field(&self, field: &str, sink: impl DeprecationSink) -> StrResult<Value> {
match self {
Self::Symbol(symbol) => {
symbol.clone().modified(sink, field).map(Self::Symbol)
}
Self::Version(version) => version.component(field).map(Self::Int),
Self::Dict(dict) => dict.get(field).cloned(),
Self::Content(content) => content.field_by_name(field),
Self::Type(ty) => ty.field(field, sink).cloned(),
Self::Func(func) => func.field(field, sink).cloned(),
Self::Module(module) => module.field(field, sink).cloned(),
_ => fields::field(self, field),
}
}
/// The associated scope, if this is a function, type, or module.
pub fn scope(&self) -> Option<&Scope> {
match self {
Self::Func(func) => func.scope(),
Self::Type(ty) => Some(ty.scope()),
Self::Module(module) => Some(module.scope()),
_ => None,
}
}
/// Try to extract documentation for the value.
pub fn docs(&self) -> Option<&'static str> {
match self {
Self::Func(func) => func.docs(),
Self::Type(ty) => Some(ty.docs()),
_ => None,
}
}
/// Return the display representation of the value.
pub fn display(self) -> Content {
match self {
Self::None => Content::empty(),
Self::Int(v) => TextElem::packed(repr::format_int_with_base(v, 10)),
Self::Float(v) => TextElem::packed(repr::display_float(v)),
Self::Decimal(v) => TextElem::packed(eco_format!("{v}")),
Self::Str(v) => TextElem::packed(v),
Self::Version(v) => TextElem::packed(eco_format!("{v}")),
Self::Symbol(v) => SymbolElem::packed(v.get()),
Self::Content(v) => v,
Self::Module(module) => module.content(),
_ => RawElem::new(RawContent::Text(self.repr()))
.with_lang(Some("typc".into()))
.with_block(false)
.pack(),
}
}
/// Attach a span to the value, if possible.
pub fn spanned(self, span: Span) -> Self {
match self {
Value::Content(v) => Value::Content(v.spanned(span)),
Value::Func(v) => Value::Func(v.spanned(span)),
v => v,
}
}
}
impl Debug for Value {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::None => Debug::fmt(&NoneValue, f),
Self::Auto => Debug::fmt(&AutoValue, f),
Self::Bool(v) => Debug::fmt(v, f),
Self::Int(v) => Debug::fmt(v, f),
Self::Float(v) => Debug::fmt(v, f),
Self::Length(v) => Debug::fmt(v, f),
Self::Angle(v) => Debug::fmt(v, f),
Self::Ratio(v) => Debug::fmt(v, f),
Self::Relative(v) => Debug::fmt(v, f),
Self::Fraction(v) => Debug::fmt(v, f),
Self::Color(v) => Debug::fmt(v, f),
Self::Gradient(v) => Debug::fmt(v, f),
Self::Tiling(v) => Debug::fmt(v, f),
Self::Symbol(v) => Debug::fmt(v, f),
Self::Version(v) => Debug::fmt(v, f),
Self::Str(v) => Debug::fmt(v, f),
Self::Bytes(v) => Debug::fmt(v, f),
Self::Label(v) => Debug::fmt(v, f),
Self::Datetime(v) => Debug::fmt(v, f),
Self::Decimal(v) => Debug::fmt(v, f),
Self::Duration(v) => Debug::fmt(v, f),
Self::Content(v) => Debug::fmt(v, f),
Self::Styles(v) => Debug::fmt(v, f),
Self::Array(v) => Debug::fmt(v, f),
Self::Dict(v) => Debug::fmt(v, f),
Self::Func(v) => Debug::fmt(v, f),
Self::Args(v) => Debug::fmt(v, f),
Self::Type(v) => Debug::fmt(v, f),
Self::Module(v) => Debug::fmt(v, f),
Self::Dyn(v) => Debug::fmt(v, f),
}
}
}
impl Repr for Value {
fn repr(&self) -> EcoString {
match self {
Self::None => NoneValue.repr(),
Self::Auto => AutoValue.repr(),
Self::Bool(v) => v.repr(),
Self::Int(v) => v.repr(),
Self::Float(v) => v.repr(),
Self::Length(v) => v.repr(),
Self::Angle(v) => v.repr(),
Self::Ratio(v) => v.repr(),
Self::Relative(v) => v.repr(),
Self::Fraction(v) => v.repr(),
Self::Color(v) => v.repr(),
Self::Gradient(v) => v.repr(),
Self::Tiling(v) => v.repr(),
Self::Symbol(v) => v.repr(),
Self::Version(v) => v.repr(),
Self::Str(v) => v.repr(),
Self::Bytes(v) => v.repr(),
Self::Label(v) => v.repr(),
Self::Datetime(v) => v.repr(),
Self::Decimal(v) => v.repr(),
Self::Duration(v) => v.repr(),
Self::Content(v) => v.repr(),
Self::Styles(v) => v.repr(),
Self::Array(v) => v.repr(),
Self::Dict(v) => v.repr(),
Self::Func(v) => v.repr(),
Self::Args(v) => v.repr(),
Self::Type(v) => v.repr(),
Self::Module(v) => v.repr(),
Self::Dyn(v) => v.repr(),
}
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
ops::equal(self, other)
}
}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
ops::compare(self, other).ok()
}
}
impl Hash for Value {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
Self::None => {}
Self::Auto => {}
Self::Bool(v) => v.hash(state),
Self::Int(v) => v.hash(state),
Self::Float(v) => v.to_bits().hash(state),
Self::Length(v) => v.hash(state),
Self::Angle(v) => v.hash(state),
Self::Ratio(v) => v.hash(state),
Self::Relative(v) => v.hash(state),
Self::Fraction(v) => v.hash(state),
Self::Color(v) => v.hash(state),
Self::Gradient(v) => v.hash(state),
Self::Tiling(v) => v.hash(state),
Self::Symbol(v) => v.hash(state),
Self::Version(v) => v.hash(state),
Self::Str(v) => v.hash(state),
Self::Bytes(v) => v.hash(state),
Self::Label(v) => v.hash(state),
Self::Content(v) => v.hash(state),
Self::Styles(v) => v.hash(state),
Self::Datetime(v) => v.hash(state),
Self::Decimal(v) => v.hash(state),
Self::Duration(v) => v.hash(state),
Self::Array(v) => v.hash(state),
Self::Dict(v) => v.hash(state),
Self::Func(v) => v.hash(state),
Self::Args(v) => v.hash(state),
Self::Type(v) => v.hash(state),
Self::Module(v) => v.hash(state),
Self::Dyn(v) => v.hash(state),
}
}
}
impl Serialize for Value {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::None => NoneValue.serialize(serializer),
Self::Bool(v) => v.serialize(serializer),
Self::Int(v) => v.serialize(serializer),
Self::Float(v) => v.serialize(serializer),
Self::Str(v) => v.serialize(serializer),
Self::Bytes(v) => v.serialize(serializer),
Self::Symbol(v) => v.serialize(serializer),
Self::Content(v) => v.serialize(serializer),
Self::Array(v) => v.serialize(serializer),
Self::Dict(v) => v.serialize(serializer),
// Fall back to repr() for other things.
other => serializer.serialize_str(&other.repr()),
}
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(ValueVisitor)
}
}
/// Visitor for value deserialization.
struct ValueVisitor;
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a Typst value")
}
fn visit_bool<E: Error>(self, v: bool) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_i8<E: Error>(self, v: i8) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_i16<E: Error>(self, v: i16) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_i32<E: Error>(self, v: i32) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_i128<E: Error>(self, v: i128) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_u8<E: Error>(self, v: u8) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_u16<E: Error>(self, v: u16) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_u32<E: Error>(self, v: u32) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_u128<E: Error>(self, v: u128) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_f32<E: Error>(self, v: f32) -> Result<Self::Value, E> {
Ok((v as f64).into_value())
}
fn visit_f64<E: Error>(self, v: f64) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_char<E: Error>(self, v: char) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_borrowed_str<E: Error>(self, v: &'de str) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
Ok(v.into_value())
}
fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
Ok(Bytes::new(v.to_vec()).into_value())
}
fn visit_borrowed_bytes<E: Error>(self, v: &'de [u8]) -> Result<Self::Value, E> {
Ok(Bytes::new(v.to_vec()).into_value())
}
fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
Ok(Bytes::new(v).into_value())
}
fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(
self,
deserializer: D,
) -> Result<Self::Value, D::Error> {
Value::deserialize(deserializer)
}
fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
Ok(Value::None)
}
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
Ok(Array::deserialize(SeqAccessDeserializer::new(seq))?.into_value())
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
let dict = Dict::deserialize(MapAccessDeserializer::new(map))?;
Ok(match Datetime::from_toml_dict(&dict) {
None => dict.into_value(),
Some(datetime) => datetime.into_value(),
})
}
}
/// A value that is not part of the built-in enum.
#[derive(Clone, Hash)]
pub struct Dynamic(Arc<dyn Bounds>);
impl Dynamic {
/// Create a new instance from any value that satisfies the required bounds.
pub fn new<T>(any: T) -> Self
where
T: Debug + Repr + NativeType + PartialEq + Hash + Sync + Send + 'static,
{
Self(Arc::new(any))
}
/// Whether the wrapped type is `T`.
pub fn is<T: 'static>(&self) -> bool {
let inner: &dyn Bounds = &*self.0;
(inner as &dyn Any).is::<T>()
}
/// Try to downcast to a reference to a specific type.
pub fn downcast<T: 'static>(&self) -> Option<&T> {
let inner: &dyn Bounds = &*self.0;
(inner as &dyn Any).downcast_ref()
}
/// The name of the stored value's type.
pub fn ty(&self) -> Type {
self.0.dyn_ty()
}
}
impl Debug for Dynamic {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Repr for Dynamic {
fn repr(&self) -> EcoString {
self.0.repr()
}
}
impl PartialEq for Dynamic {
fn eq(&self, other: &Self) -> bool {
self.0.dyn_eq(other)
}
}
trait Bounds: Debug + Repr + Any + Sync + Send + 'static {
fn dyn_eq(&self, other: &Dynamic) -> bool;
fn dyn_ty(&self) -> Type;
fn dyn_hash(&self, state: &mut dyn Hasher);
}
impl<T> Bounds for T
where
T: Debug + Repr + NativeType + PartialEq + Hash + Sync + Send + 'static,
{
fn dyn_eq(&self, other: &Dynamic) -> bool {
let Some(other) = other.downcast::<Self>() else { return false };
self == other
}
fn dyn_ty(&self) -> Type {
Type::of::<T>()
}
fn dyn_hash(&self, mut state: &mut dyn Hasher) {
// Also hash the TypeId since values with different types but
// equal data should be different.
TypeId::of::<Self>().hash(&mut state);
self.hash(&mut state);
}
}
impl Hash for dyn Bounds {
fn hash<H: Hasher>(&self, state: &mut H) {
self.dyn_hash(state);
}
}
/// Implements traits for primitives (Value enum variants).
macro_rules! primitive {
(
$ty:ty: $name:literal, $variant:ident
$(, $other:ident$(($binding:ident))? => $out:expr)*
) => {
impl Reflect for $ty {
fn input() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn output() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn castable(value: &Value) -> bool {
matches!(value, Value::$variant(_)
$(| primitive!(@$other $(($binding))?))*)
}
}
impl IntoValue for $ty {
fn into_value(self) -> Value {
Value::$variant(self)
}
}
impl FromValue for $ty {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
Value::$variant(v) => Ok(v),
$(Value::$other$(($binding))? => Ok($out),)*
v => Err(<Self as Reflect>::error(&v)),
}
}
}
};
(@$other:ident($binding:ident)) => { Value::$other(_) };
(@$other:ident) => { Value::$other };
}
primitive! { bool: "boolean", Bool }
primitive! { i64: "integer", Int }
primitive! { f64: "float", Float, Int(v) => v as f64 }
primitive! { Length: "length", Length }
primitive! { Angle: "angle", Angle }
primitive! { Ratio: "ratio", Ratio }
primitive! { Rel<Length>: "relative length",
Relative,
Length(v) => v.into(),
Ratio(v) => v.into()
}
primitive! { Fr: "fraction", Fraction }
primitive! { Color: "color", Color }
primitive! { Gradient: "gradient", Gradient }
primitive! { Tiling: "tiling", Tiling }
primitive! { Symbol: "symbol", Symbol }
primitive! { Version: "version", Version }
primitive! {
Str: "string",
Str,
Symbol(symbol) => symbol.get().into()
}
primitive! { Bytes: "bytes", Bytes }
primitive! { Label: "label", Label }
primitive! { Datetime: "datetime", Datetime }
primitive! { Decimal: "decimal", Decimal }
primitive! { Duration: "duration", Duration }
primitive! { Content: "content",
Content,
None => Content::empty(),
Symbol(v) => SymbolElem::packed(v.get()),
Str(v) => TextElem::packed(v)
}
primitive! { Styles: "styles", Styles }
primitive! { Array: "array", Array }
primitive! { Dict: "dictionary", Dict }
primitive! {
Func: "function",
Func,
Type(ty) => ty.constructor()?.clone(),
Symbol(symbol) => symbol.func()?
}
primitive! { Args: "arguments", Args }
primitive! { Type: "type", Type }
primitive! { Module: "module", Module }
impl<T: Reflect> Reflect for Arc<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
fn error(found: &Value) -> HintedString {
T::error(found)
}
}
impl<T: Clone + IntoValue> IntoValue for Arc<T> {
fn into_value(self) -> Value {
Arc::take(self).into_value()
}
}
impl<T: FromValue> FromValue for Arc<T> {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
v if T::castable(&v) => Ok(Arc::new(T::from_value(v)?)),
_ => Err(Self::error(&value)),
}
}
}
impl<T: Clone + Resolve> Resolve for Arc<T> {
type Output = Arc<T::Output>;
fn resolve(self, styles: super::StyleChain) -> Self::Output {
Arc::new(Arc::take(self).resolve(styles))
}
}
impl<T: Clone + Fold> Fold for Arc<T> {
fn fold(self, outer: Self) -> Self {
Arc::new(Arc::take(self).fold(Arc::take(outer)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::foundations::{array, dict};
#[track_caller]
fn test(value: impl IntoValue, exp: &str) {
assert_eq!(value.into_value().repr(), exp);
}
#[test]
fn test_value_size() {
assert!(std::mem::size_of::<Value>() <= 32);
}
#[test]
fn test_value_debug() {
// Primitives.
test(Value::None, "none");
test(Value::Auto, "auto");
test(Value::None.ty(), "type(none)");
test(Value::Auto.ty(), "type(auto)");
test(false, "false");
test(12i64, "12");
test(3.24, "3.24");
test(Abs::pt(5.5), "5.5pt");
test(Angle::deg(90.0), "90deg");
test(Ratio::one() / 2.0, "50%");
test(Ratio::new(0.3) + Length::from(Abs::cm(2.0)), "30% + 56.69pt");
test(Fr::one() * 7.55, "7.55fr");
// Collections.
test("hello", r#""hello""#);
test("\n", r#""\n""#);
test("\\", r#""\\""#);
test("\"", r#""\"""#);
test(array![], "()");
test(array![Value::None], "(none,)");
test(array![1, 2], "(1, 2)");
test(dict![], "(:)");
test(dict!["one" => 1], "(one: 1)");
test(dict!["two" => false, "one" => 1], "(two: false, one: 1)");
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/args.rs | crates/typst-library/src/foundations/args.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::Add;
use std::slice;
use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_format, eco_vec};
use typst_syntax::{Span, Spanned};
use crate::diag::{At, SourceDiagnostic, SourceResult, StrResult, bail, error};
use crate::engine::Engine;
use crate::foundations::{
Array, Context, Dict, FromValue, Func, IntoValue, Repr, Str, Value, cast, func, repr,
scope, ty,
};
/// Captured arguments to a function.
///
/// # Argument Sinks
/// Like built-in functions, custom functions can also take a variable number of
/// arguments. You can specify an _argument sink_ which collects all excess
/// arguments as `..sink`. The resulting `sink` value is of the `arguments`
/// type. It exposes methods to access the positional and named arguments.
///
/// ```example
/// #let format(title, ..authors) = {
/// let by = authors
/// .pos()
/// .join(", ", last: " and ")
///
/// [*#title* \ _Written by #by;_]
/// }
///
/// #format("ArtosFlow", "Jane", "Joe")
/// ```
///
/// # Spreading
/// Inversely to an argument sink, you can _spread_ arguments, arrays and
/// dictionaries into a function call with the `..spread` operator:
///
/// ```example
/// #let array = (2, 3, 5)
/// #calc.min(..array)
/// #let dict = (fill: blue)
/// #text(..dict)[Hello]
/// ```
#[ty(scope, cast, name = "arguments")]
#[derive(Clone, Hash)]
pub struct Args {
/// The callsite span for the function. This is not the span of the argument
/// list itself, but of the whole function call.
pub span: Span,
/// The positional and named arguments.
pub items: EcoVec<Arg>,
}
impl Args {
/// Create positional arguments from a span and values.
pub fn new<T: IntoValue>(span: Span, values: impl IntoIterator<Item = T>) -> Self {
let items = values
.into_iter()
.map(|value| Arg {
span,
name: None,
value: Spanned::new(value.into_value(), span),
})
.collect();
Self { span, items }
}
/// Attach a span to these arguments if they don't already have one.
pub fn spanned(mut self, span: Span) -> Self {
if self.span.is_detached() {
self.span = span;
}
self
}
/// Returns the number of remaining positional arguments.
pub fn remaining(&self) -> usize {
self.items.iter().filter(|slot| slot.name.is_none()).count()
}
/// Insert a positional argument at a specific index.
pub fn insert(&mut self, index: usize, span: Span, value: Value) {
self.items.insert(
index,
Arg {
span: self.span,
name: None,
value: Spanned::new(value, span),
},
)
}
/// Push a positional argument.
pub fn push(&mut self, span: Span, value: Value) {
self.items.push(Arg {
span: self.span,
name: None,
value: Spanned::new(value, span),
})
}
/// Consume and cast the first positional argument if there is one.
pub fn eat<T>(&mut self) -> SourceResult<Option<T>>
where
T: FromValue<Spanned<Value>>,
{
for (i, slot) in self.items.iter().enumerate() {
if slot.name.is_none() {
let value = self.items.remove(i).value;
let span = value.span;
return T::from_value(value).at(span).map(Some);
}
}
Ok(None)
}
/// Consume n positional arguments if possible.
pub fn consume(&mut self, n: usize) -> SourceResult<Vec<Arg>> {
let mut list = vec![];
let mut i = 0;
while i < self.items.len() && list.len() < n {
if self.items[i].name.is_none() {
list.push(self.items.remove(i));
} else {
i += 1;
}
}
if list.len() < n {
bail!(self.span, "not enough arguments");
}
Ok(list)
}
/// Consume and cast the first positional argument.
///
/// Returns a `missing argument: {what}` error if no positional argument is
/// left.
pub fn expect<T>(&mut self, what: &str) -> SourceResult<T>
where
T: FromValue<Spanned<Value>>,
{
match self.eat()? {
Some(v) => Ok(v),
None => bail!(self.missing_argument(what)),
}
}
/// The error message for missing arguments.
fn missing_argument(&self, what: &str) -> SourceDiagnostic {
for item in &self.items {
let Some(name) = item.name.as_deref() else { continue };
if name == what {
return error!(
item.span,
"the argument `{what}` is positional";
hint: "try removing `{}:`", name;
);
}
}
error!(self.span, "missing argument: {what}")
}
/// Find and consume the first castable positional argument.
pub fn find<T>(&mut self) -> SourceResult<Option<T>>
where
T: FromValue<Spanned<Value>>,
{
for (i, slot) in self.items.iter().enumerate() {
if slot.name.is_none() && T::castable(&slot.value.v) {
let value = self.items.remove(i).value;
let span = value.span;
return T::from_value(value).at(span).map(Some);
}
}
Ok(None)
}
/// Find and consume all castable positional arguments.
pub fn all<T>(&mut self) -> SourceResult<Vec<T>>
where
T: FromValue<Spanned<Value>>,
{
let mut list = vec![];
let mut errors = eco_vec![];
self.items.retain(|item| {
if item.name.is_some() {
return true;
}
let span = item.value.span;
let spanned = Spanned::new(std::mem::take(&mut item.value.v), span);
match T::from_value(spanned).at(span) {
Ok(val) => list.push(val),
Err(diags) => errors.extend(diags),
}
false
});
if !errors.is_empty() {
return Err(errors);
}
Ok(list)
}
/// Cast and remove the value for the given named argument, returning an
/// error if the conversion fails.
pub fn named<T>(&mut self, name: &str) -> SourceResult<Option<T>>
where
T: FromValue<Spanned<Value>>,
{
// We don't quit once we have a match because when multiple matches
// exist, we want to remove all of them and use the last one.
let mut i = 0;
let mut found = None;
while i < self.items.len() {
if self.items[i].name.as_deref() == Some(name) {
let value = self.items.remove(i).value;
let span = value.span;
found = Some(T::from_value(value).at(span)?);
} else {
i += 1;
}
}
Ok(found)
}
/// Same as named, but with fallback to find.
pub fn named_or_find<T>(&mut self, name: &str) -> SourceResult<Option<T>>
where
T: FromValue<Spanned<Value>>,
{
match self.named(name)? {
Some(value) => Ok(Some(value)),
None => self.find(),
}
}
/// Take out all arguments into a new instance.
pub fn take(&mut self) -> Self {
Self {
span: self.span,
items: std::mem::take(&mut self.items),
}
}
/// Return an "unexpected argument" error if there is any remaining
/// argument.
pub fn finish(self) -> SourceResult<()> {
if let Some(arg) = self.items.first() {
match &arg.name {
Some(name) => bail!(arg.span, "unexpected argument: {name}"),
_ => bail!(arg.span, "unexpected argument"),
}
}
Ok(())
}
}
/// A key that can be used to get an argument: either the index of a positional
/// argument, or the name of a named argument.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ArgumentKey {
Index(i64),
Name(Str),
}
cast! {
ArgumentKey,
v: i64 => Self::Index(v),
v: Str => Self::Name(v),
}
impl Args {
/// Tests whether there is no positional nor named argument.
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
fn get(&self, key: &ArgumentKey) -> Option<&Value> {
let item = match key {
&ArgumentKey::Index(index) => {
let mut iter = self.items.iter().filter(|item| item.name.is_none());
if index < 0 {
let index = (-(index + 1)).try_into().ok()?;
iter.nth_back(index)
} else {
let index = index.try_into().ok()?;
iter.nth(index)
}
}
// Accept the last argument with the right name.
ArgumentKey::Name(name) => {
self.items.iter().rfind(|item| item.name.as_ref() == Some(name))
}
};
item.map(|item| &item.value.v)
}
}
#[scope]
impl Args {
/// Construct spreadable arguments in place.
///
/// This function behaves like `{let args(..sink) = sink}`.
///
/// ```example
/// #let args = arguments(stroke: red, inset: 1em, [Body])
/// #box(..args)
/// ```
#[func(constructor)]
pub fn construct(
args: &mut Args,
/// The arguments to construct.
#[external]
#[variadic]
arguments: Vec<Value>,
) -> Args {
args.take()
}
/// The number of arguments, positional or named.
#[func(title = "Length")]
pub fn len(&self) -> usize {
self.items.len()
}
/// Returns the positional argument at the specified index, or the named
/// argument with the specified name.
///
/// If the key is an [integer]($int), this is equivalent to first calling
/// [`pos`]($arguments.pos) and then [`array.at`]. If it is a [string]($str),
/// this is equivalent to first calling [`named`]($arguments.named) and then
/// [`dictionary.at`].
#[func]
pub fn at(
&self,
/// The index or name of the argument to get.
key: ArgumentKey,
/// A default value to return if the key is invalid.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.get(&key)
.cloned()
.or(default)
.ok_or_else(|| missing_key_no_default(key))
}
/// Returns the captured positional arguments as an array.
#[func(name = "pos", title = "Positional")]
pub fn to_pos(&self) -> Array {
self.items
.iter()
.filter(|item| item.name.is_none())
.map(|item| item.value.v.clone())
.collect()
}
/// Returns the captured named arguments as a dictionary.
#[func(name = "named")]
pub fn to_named(&self) -> Dict {
self.items
.iter()
.filter_map(|item| item.name.clone().map(|name| (name, item.value.v.clone())))
.collect()
}
/// Produces a new `arguments` with only the arguments for which the value
/// passes the test.
///
/// ```example
/// #{
/// arguments(-1, a: 0, b: 1, 2)
/// .filter(v => v > 0)
/// }
/// ```
#[func]
pub fn filter(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each value. Must return a boolean.
test: Func,
) -> SourceResult<Args> {
let mut run_test = |v: &Value| {
test.call(engine, context, [v.clone()])?
.cast::<bool>()
.at(test.span())
};
self.into_iter()
.filter_map(|arg| {
run_test(&arg.value.v).map(|b| b.then_some(arg)).transpose()
})
.collect()
}
/// Produces a new `arguments` by transforming each argument value with the
/// passed function.
///
/// ```example
/// #{
/// arguments(0, a: 1, 2)
/// .map(v => v + 1)
/// }
/// ```
#[func]
pub fn map(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each value.
mapper: Func,
) -> SourceResult<Args> {
self.into_iter()
.map(|arg| {
let mapped_value = mapper.call(engine, context, [arg.value.v])?;
Ok(Arg {
span: arg.span,
name: arg.name,
value: Spanned::detached(mapped_value),
})
})
.collect()
}
}
impl Debug for Args {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_list().entries(&self.items).finish()
}
}
impl Repr for Args {
fn repr(&self) -> EcoString {
let pieces = self.items.iter().map(Arg::repr).collect::<Vec<_>>();
eco_format!("arguments{}", repr::pretty_array_like(&pieces, false))
}
}
impl PartialEq for Args {
fn eq(&self, other: &Self) -> bool {
self.to_pos() == other.to_pos() && self.to_named() == other.to_named()
}
}
impl Add for Args {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self.items.retain(|item| {
!item.name.as_ref().is_some_and(|name| {
rhs.items.iter().any(|a| a.name.as_ref() == Some(name))
})
});
self.items.extend(rhs.items);
self.span = Span::detached();
self
}
}
impl FromIterator<Arg> for Args {
fn from_iter<T: IntoIterator<Item = Arg>>(iter: T) -> Self {
Self {
span: Span::detached(),
items: iter.into_iter().collect(),
}
}
}
impl IntoIterator for Args {
type Item = Arg;
type IntoIter = <EcoVec<Arg> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
impl<'a> IntoIterator for &'a Args {
type Item = &'a Arg;
type IntoIter = slice::Iter<'a, Arg>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
/// An argument to a function call: `12` or `draw: false`.
#[derive(Clone, Hash)]
pub struct Arg {
/// The span of the whole argument.
pub span: Span,
/// The name of the argument (`None` for positional arguments).
pub name: Option<Str>,
/// The value of the argument.
pub value: Spanned<Value>,
}
impl Debug for Arg {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Some(name) = &self.name {
name.fmt(f)?;
f.write_str(": ")?;
self.value.v.fmt(f)
} else {
self.value.v.fmt(f)
}
}
}
impl Repr for Arg {
fn repr(&self) -> EcoString {
if let Some(name) = &self.name {
eco_format!("{}: {}", name, self.value.v.repr())
} else {
self.value.v.repr()
}
}
}
impl PartialEq for Arg {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.value.v == other.value.v
}
}
/// Things that can be used as arguments.
pub trait IntoArgs {
/// Convert into arguments, attaching the `fallback` span in case `Self`
/// doesn't have a span.
fn into_args(self, fallback: Span) -> Args;
}
impl IntoArgs for Args {
fn into_args(self, fallback: Span) -> Args {
self.spanned(fallback)
}
}
impl<I, T> IntoArgs for I
where
I: IntoIterator<Item = T>,
T: IntoValue,
{
fn into_args(self, fallback: Span) -> Args {
Args::new(fallback, self)
}
}
/// The missing key access error message when no default was given.
#[cold]
fn missing_key_no_default(key: ArgumentKey) -> EcoString {
eco_format!(
"arguments do not contain key {} \
and no default value was specified",
match key {
ArgumentKey::Index(i) => i.repr(),
ArgumentKey::Name(name) => name.repr(),
}
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/decimal.rs | crates/typst-library/src/foundations/decimal.rs | use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Neg;
use std::str::FromStr;
use ecow::{EcoString, eco_format};
use rust_decimal::MathematicalOps;
use typst_syntax::{Span, Spanned, ast};
use crate::World;
use crate::diag::{At, SourceResult, warning};
use crate::engine::Engine;
use crate::foundations::{Repr, Str, cast, func, repr, scope, ty};
/// A fixed-point decimal number type.
///
/// This type should be used for precise arithmetic operations on numbers
/// represented in base 10. A typical use case is representing currency.
///
/// # Example
/// ```example
/// Decimal: #(decimal("0.1") + decimal("0.2")) \
/// Float: #(0.1 + 0.2)
/// ```
///
/// # Construction and casts
/// To create a decimal number, use the `{decimal(string)}` constructor, such as
/// in `{decimal("3.141592653")}` **(note the double quotes!)**. This
/// constructor preserves all given fractional digits, provided they are
/// representable as per the limits specified below (otherwise, an error is
/// raised).
///
/// You can also convert any [integer]($int) to a decimal with the
/// `{decimal(int)}` constructor, e.g. `{decimal(59)}`. However, note that
/// constructing a decimal from a [floating-point number]($float), while
/// supported, **is an imprecise conversion and therefore discouraged.** A
/// warning will be raised if Typst detects that there was an accidental `float`
/// to `decimal` cast through its constructor, e.g. if writing `{decimal(3.14)}`
/// (note the lack of double quotes, indicating this is an accidental `float`
/// cast and therefore imprecise). It is recommended to use strings for
/// constant decimal values instead (e.g. `{decimal("3.14")}`).
///
/// The precision of a `float` to `decimal` cast can be slightly improved by
/// rounding the result to 15 digits with [`calc.round`], but there are still no
/// precision guarantees for that kind of conversion.
///
/// # Operations
/// Basic arithmetic operations are supported on two decimals and on pairs of
/// decimals and integers.
///
/// Built-in operations between `float` and `decimal` are not supported in order
/// to guard against accidental loss of precision. They will raise an error
/// instead.
///
/// Certain `calc` functions, such as trigonometric functions and power between
/// two real numbers, are also only supported for `float` (although raising
/// `decimal` to integer exponents is supported). You can opt into potentially
/// imprecise operations with the `{float(decimal)}` constructor, which casts
/// the `decimal` number into a `float`, allowing for operations without
/// precision guarantees.
///
/// # Displaying decimals
/// To display a decimal, simply insert the value into the document. To only
/// display a certain number of digits, [round]($calc.round) the decimal first.
/// Localized formatting of decimals and other numbers is not yet supported, but
/// planned for the future.
///
/// You can convert decimals to strings using the [`str`] constructor. This way,
/// you can post-process the displayed representation, e.g. to replace the
/// period with a comma (as a stand-in for proper built-in localization to
/// languages that use the comma).
///
/// # Precision and limits
/// A `decimal` number has a limit of 28 to 29 significant base-10 digits. This
/// includes the sum of digits before and after the decimal point. As such,
/// numbers with more fractional digits have a smaller range. The maximum and
/// minimum `decimal` numbers have a value of `{79228162514264337593543950335}`
/// and `{-79228162514264337593543950335}` respectively. In contrast with
/// [`float`], this type does not support infinity or NaN, so overflowing or
/// underflowing operations will raise an error.
///
/// Typical operations between `decimal` numbers, such as addition,
/// multiplication, and [power]($calc.pow) to an integer, will be highly precise
/// due to their fixed-point representation. Note, however, that multiplication
/// and division may not preserve all digits in some edge cases: while they are
/// considered precise, digits past the limits specified above are rounded off
/// and lost, so some loss of precision beyond the maximum representable digits
/// is possible. Note that this behavior can be observed not only when dividing,
/// but also when multiplying by numbers between 0 and 1, as both operations can
/// push a number's fractional digits beyond the limits described above, leading
/// to rounding. When those two operations do not surpass the digit limits, they
/// are fully precise.
#[ty(scope, cast)]
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Decimal(rust_decimal::Decimal);
impl Decimal {
pub const ZERO: Self = Self(rust_decimal::Decimal::ZERO);
pub const ONE: Self = Self(rust_decimal::Decimal::ONE);
pub const MIN: Self = Self(rust_decimal::Decimal::MIN);
pub const MAX: Self = Self(rust_decimal::Decimal::MAX);
/// Whether this decimal value is zero.
pub const fn is_zero(self) -> bool {
self.0.is_zero()
}
/// Whether this decimal value is negative.
pub const fn is_negative(self) -> bool {
self.0.is_sign_negative()
}
/// Whether this decimal has fractional part equal to zero (is an integer).
pub fn is_integer(self) -> bool {
self.0.is_integer()
}
/// Computes the absolute value of this decimal.
pub fn abs(self) -> Self {
Self(self.0.abs())
}
/// Computes the largest integer less than or equal to this decimal.
///
/// A decimal is returned as this may not be within `i64`'s range of
/// values.
pub fn floor(self) -> Self {
Self(self.0.floor())
}
/// Computes the smallest integer greater than or equal to this decimal.
///
/// A decimal is returned as this may not be within `i64`'s range of
/// values.
pub fn ceil(self) -> Self {
Self(self.0.ceil())
}
/// Returns the integer part of this decimal.
pub fn trunc(self) -> Self {
Self(self.0.trunc())
}
/// Returns the fractional part of this decimal (with the integer part set
/// to zero).
pub fn fract(self) -> Self {
Self(self.0.fract())
}
/// Rounds this decimal up to the specified amount of digits with the
/// traditional rounding rules, using the "midpoint away from zero"
/// strategy (6.5 -> 7, -6.5 -> -7).
///
/// If given a negative amount of digits, rounds to integer digits instead
/// with the same rounding strategy. For example, rounding to -3 digits
/// will turn 34567.89 into 35000.00 and -34567.89 into -35000.00.
///
/// Note that this can return `None` when using negative digits where the
/// rounded number would overflow the available range for decimals.
pub fn round(self, digits: i32) -> Option<Self> {
// Positive digits can be handled by just rounding with rust_decimal.
if let Ok(positive_digits) = u32::try_from(digits) {
return Some(Self(self.0.round_dp_with_strategy(
positive_digits,
rust_decimal::RoundingStrategy::MidpointAwayFromZero,
)));
}
// We received negative digits, so we round to integer digits.
let mut num = self.0;
let old_scale = num.scale();
let digits = -digits as u32;
let (Ok(_), Some(ten_to_digits)) = (
// Same as dividing by 10^digits.
num.set_scale(old_scale + digits),
rust_decimal::Decimal::TEN.checked_powi(digits as i64),
) else {
// Scaling more than any possible amount of integer digits.
let mut zero = rust_decimal::Decimal::ZERO;
zero.set_sign_negative(self.is_negative());
return Some(Self(zero));
};
// Round to this integer digit.
num = num.round_dp_with_strategy(
0,
rust_decimal::RoundingStrategy::MidpointAwayFromZero,
);
// Multiply by 10^digits again, which can overflow and fail.
num.checked_mul(ten_to_digits).map(Self)
}
/// Attempts to add two decimals.
///
/// Returns `None` on overflow or underflow.
pub fn checked_add(self, other: Self) -> Option<Self> {
self.0.checked_add(other.0).map(Self)
}
/// Attempts to subtract a decimal from another.
///
/// Returns `None` on overflow or underflow.
pub fn checked_sub(self, other: Self) -> Option<Self> {
self.0.checked_sub(other.0).map(Self)
}
/// Attempts to multiply two decimals.
///
/// Returns `None` on overflow or underflow.
pub fn checked_mul(self, other: Self) -> Option<Self> {
self.0.checked_mul(other.0).map(Self)
}
/// Attempts to divide two decimals.
///
/// Returns `None` if `other` is zero, as well as on overflow or underflow.
pub fn checked_div(self, other: Self) -> Option<Self> {
self.0.checked_div(other.0).map(Self)
}
/// Attempts to obtain the quotient of Euclidean division between two
/// decimals. Implemented similarly to [`f64::div_euclid`].
///
/// The returned quotient is truncated and adjusted if the remainder was
/// negative.
///
/// Returns `None` if `other` is zero, as well as on overflow or underflow.
pub fn checked_div_euclid(self, other: Self) -> Option<Self> {
let q = self.0.checked_div(other.0)?.trunc();
if self
.0
.checked_rem(other.0)
.as_ref()
.is_some_and(rust_decimal::Decimal::is_sign_negative)
{
return if other.0.is_sign_positive() {
q.checked_sub(rust_decimal::Decimal::ONE).map(Self)
} else {
q.checked_add(rust_decimal::Decimal::ONE).map(Self)
};
}
Some(Self(q))
}
/// Attempts to obtain the remainder of Euclidean division between two
/// decimals. Implemented similarly to [`f64::rem_euclid`].
///
/// The returned decimal `r` is non-negative within the range
/// `0.0 <= r < other.abs()`.
///
/// Returns `None` if `other` is zero, as well as on overflow or underflow.
pub fn checked_rem_euclid(self, other: Self) -> Option<Self> {
let r = self.0.checked_rem(other.0)?;
Some(Self(if r.is_sign_negative() { r.checked_add(other.0.abs())? } else { r }))
}
/// Attempts to calculate the remainder of the division of two decimals.
///
/// Returns `None` if `other` is zero, as well as on overflow or underflow.
pub fn checked_rem(self, other: Self) -> Option<Self> {
self.0.checked_rem(other.0).map(Self)
}
/// Attempts to take one decimal to the power of an integer.
///
/// Returns `None` for invalid operands, as well as on overflow or
/// underflow.
pub fn checked_powi(self, other: i64) -> Option<Self> {
self.0.checked_powi(other).map(Self)
}
}
#[scope]
impl Decimal {
/// Converts a value to a `decimal`.
///
/// It is recommended to use a string to construct the decimal number, or an
/// [integer]($int) (if desired). The string must contain a number in the
/// format `{"3.14159"}` (or `{"-3.141519"}` for negative numbers). The
/// fractional digits are fully preserved; if that's not possible due to the
/// limit of significant digits (around 28 to 29) having been reached, an
/// error is raised as the given decimal number wouldn't be representable.
///
/// While this constructor can be used with [floating-point numbers]($float)
/// to cast them to `decimal`, doing so is **discouraged** as **this cast is
/// inherently imprecise.** It is easy to accidentally perform this cast by
/// writing `{decimal(1.234)}` (note the lack of double quotes), which is
/// why Typst will emit a warning in that case. Please write
/// `{decimal("1.234")}` instead for that particular case (initialization of
/// a constant decimal). Also note that floats that are NaN or infinite
/// cannot be cast to decimals and will raise an error.
///
/// ```example
/// #decimal("1.222222222222222")
/// ```
#[func(constructor)]
pub fn construct(
engine: &mut Engine,
/// The value that should be converted to a decimal.
value: Spanned<ToDecimal>,
) -> SourceResult<Decimal> {
match value.v {
ToDecimal::Str(str) => Self::from_str(&str.replace(repr::MINUS_SIGN, "-"))
.map_err(|_| eco_format!("invalid decimal: {str}"))
.at(value.span),
ToDecimal::Int(int) => Ok(Self::from(int)),
ToDecimal::Float(float) => {
warn_on_float_literal(engine, value.span);
Self::try_from(float)
.map_err(|_| {
eco_format!(
"float is not a valid decimal: {}",
repr::format_float(float, None, true, "")
)
})
.at(value.span)
}
ToDecimal::Decimal(decimal) => Ok(decimal),
}
}
}
/// Emits a warning when a decimal is constructed from a float literal.
fn warn_on_float_literal(engine: &mut Engine, span: Span) -> Option<()> {
let id = span.id()?;
let source = engine.world.source(id).ok()?;
let node = source.find(span)?;
if node.is::<ast::Float>() {
engine.sink.warn(warning!(
span,
"creating a decimal using imprecise float literal";
hint: "use a string in the decimal constructor to avoid loss \
of precision: `decimal({})`",
node.text().repr();
));
}
Some(())
}
impl FromStr for Decimal {
type Err = rust_decimal::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
rust_decimal::Decimal::from_str_exact(s).map(Self)
}
}
impl From<i64> for Decimal {
fn from(value: i64) -> Self {
Self(rust_decimal::Decimal::from(value))
}
}
impl TryFrom<f64> for Decimal {
type Error = ();
/// Attempts to convert a Decimal to a float.
///
/// This can fail if the float is infinite or NaN, or otherwise cannot be
/// represented by a decimal number.
fn try_from(value: f64) -> Result<Self, Self::Error> {
rust_decimal::Decimal::from_f64_retain(value).map(Self).ok_or(())
}
}
impl TryFrom<Decimal> for f64 {
type Error = rust_decimal::Error;
/// Attempts to convert a Decimal to a float.
///
/// This should in principle be infallible according to the implementation,
/// but we mirror the decimal implementation's API either way.
fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.0.try_into()
}
}
impl TryFrom<Decimal> for i64 {
type Error = rust_decimal::Error;
/// Attempts to convert a Decimal to an integer.
///
/// Returns an error if the decimal has a fractional part, or if there
/// would be overflow or underflow.
fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.0.try_into()
}
}
impl Display for Decimal {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if self.0.is_sign_negative() {
f.write_str(repr::MINUS_SIGN)?;
}
self.0.abs().fmt(f)
}
}
impl Repr for Decimal {
fn repr(&self) -> EcoString {
eco_format!("decimal({})", eco_format!("{}", self.0).repr())
}
}
impl Neg for Decimal {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Hash for Decimal {
fn hash<H: Hasher>(&self, state: &mut H) {
// `rust_decimal`'s Hash implementation normalizes decimals before
// hashing them. This means decimals with different scales but
// equivalent value not only compare equal but also hash equally. Here,
// we hash all bytes explicitly to ensure the scale is also considered.
// This means that 123.314 == 123.31400, but 123.314.hash() !=
// 123.31400.hash().
//
// Note that this implies that equal decimals can have different hashes,
// which might generate problems with certain data structures, such as
// HashSet and HashMap.
self.0.serialize().hash(state);
}
}
/// A value that can be cast to a decimal.
pub enum ToDecimal {
/// A decimal to be converted to itself.
Decimal(Decimal),
/// A string with the decimal's representation.
Str(EcoString),
/// An integer to be converted to the equivalent decimal.
Int(i64),
/// A float to be converted to the equivalent decimal.
Float(f64),
}
cast! {
ToDecimal,
v: Decimal => Self::Decimal(v),
v: i64 => Self::Int(v),
v: bool => Self::Int(v as i64),
v: f64 => Self::Float(v),
v: Str => Self::Str(EcoString::from(v)),
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use typst_utils::hash128;
use super::Decimal;
#[test]
fn test_decimals_with_equal_scales_hash_identically() {
let a = Decimal::from_str("3.14").unwrap();
let b = Decimal::from_str("3.14").unwrap();
assert_eq!(a, b);
assert_eq!(hash128(&a), hash128(&b));
}
#[test]
fn test_decimals_with_different_scales_hash_differently() {
let a = Decimal::from_str("3.140").unwrap();
let b = Decimal::from_str("3.14000").unwrap();
assert_eq!(a, b);
assert_ne!(hash128(&a), hash128(&b));
}
#[track_caller]
fn test_round(value: &str, digits: i32, expected: &str) {
assert_eq!(
Decimal::from_str(value).unwrap().round(digits),
Some(Decimal::from_str(expected).unwrap()),
);
}
#[test]
fn test_decimal_positive_round() {
test_round("312.55553", 0, "313.00000");
test_round("312.55553", 3, "312.556");
test_round("312.5555300000", 3, "312.556");
test_round("-312.55553", 3, "-312.556");
test_round("312.55553", 28, "312.55553");
test_round("312.55553", 2341, "312.55553");
test_round("-312.55553", 2341, "-312.55553");
}
#[test]
fn test_decimal_negative_round() {
test_round("4596.55553", -1, "4600");
test_round("4596.555530000000", -1, "4600");
test_round("-4596.55553", -3, "-5000");
test_round("4596.55553", -28, "0");
test_round("-4596.55553", -2341, "0");
assert_eq!(Decimal::MAX.round(-1), None);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/target.rs | crates/typst-library/src/foundations/target.rs | use comemo::Tracked;
use crate::diag::HintedStrResult;
use crate::foundations::{Cast, Context, elem, func};
/// The export target.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Target {
/// The target that is used for paged, fully laid-out content.
#[default]
Paged,
/// The target that is used for HTML export.
Html,
}
impl Target {
/// Whether this is the HTML target.
pub fn is_html(self) -> bool {
self == Self::Html
}
}
/// This element exists solely to host the `target` style chain field.
/// It is never constructed and not visible to users.
#[elem]
pub struct TargetElem {
/// The compilation target.
pub target: Target,
}
/// Returns the current export target.
///
/// This function returns either
/// - `{"paged"}` (for PDF, PNG, and SVG export), or
/// - `{"html"}` (for HTML export).
///
/// The design of this function is not yet finalized and for this reason it is
/// guarded behind the `html` feature. Visit the [HTML documentation
/// page]($html) for more details.
///
/// # When to use it
/// This function allows you to format your document properly across both HTML
/// and paged export targets. It should primarily be used in templates and show
/// rules, rather than directly in content. This way, the document's contents
/// can be fully agnostic to the export target and content can be shared between
/// PDF and HTML export.
///
/// # Varying targets
/// This function is [contextual]($context) as the target can vary within a
/// single compilation: When exporting to HTML, the target will be `{"paged"}`
/// while within an [`html.frame`].
///
/// # Example
/// ```example
/// #let kbd(it) = context {
/// if target() == "html" {
/// html.elem("kbd", it)
/// } else {
/// set text(fill: rgb("#1f2328"))
/// let r = 3pt
/// box(
/// fill: rgb("#f6f8fa"),
/// stroke: rgb("#d1d9e0b3"),
/// outset: (y: r),
/// inset: (x: r),
/// radius: r,
/// raw(it)
/// )
/// }
/// }
///
/// Press #kbd("F1") for help.
/// ```
#[func(contextual)]
pub fn target(context: Tracked<Context>) -> HintedStrResult<Target> {
Ok(context.styles()?.get(TargetElem::target))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/bool.rs | crates/typst-library/src/foundations/bool.rs | use ecow::EcoString;
use crate::foundations::{Repr, ty};
/// A type with two states.
///
/// The boolean type has two values: `{true}` and `{false}`. It denotes whether
/// something is active or enabled.
///
/// # Example
/// ```example
/// #false \
/// #true \
/// #(1 < 2)
/// ```
#[ty(cast, title = "Boolean")]
type bool;
impl Repr for bool {
fn repr(&self) -> EcoString {
match self {
true => "true".into(),
false => "false".into(),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/fields.rs | crates/typst-library/src/foundations/fields.rs | //! Fields on values.
use ecow::{EcoString, eco_format};
use crate::diag::StrResult;
use crate::foundations::{IntoValue, Type, Value, Version};
use crate::layout::{Alignment, Length, Rel};
use crate::visualize::Stroke;
/// Try to access a field on a value.
///
/// This function is exclusively for types which have predefined fields, such as
/// stroke and length.
pub(crate) fn field(value: &Value, field: &str) -> StrResult<Value> {
let ty = value.ty();
let nope = || Err(no_fields(ty));
let missing = || Err(missing_field(ty, field));
// Special cases, such as module and dict, are handled by Value itself
let result = match value {
Value::Version(version) => match version.component(field) {
Ok(i) => i.into_value(),
Err(_) => return missing(),
},
Value::Length(length) => match field {
"em" => length.em.get().into_value(),
"abs" => length.abs.into_value(),
_ => return missing(),
},
Value::Relative(rel) => match field {
"ratio" => rel.rel.into_value(),
"length" => rel.abs.into_value(),
_ => return missing(),
},
Value::Dyn(dynamic) => {
if let Some(stroke) = dynamic.downcast::<Stroke>() {
match field {
"paint" => stroke.paint.clone().into_value(),
"thickness" => stroke.thickness.into_value(),
"cap" => stroke.cap.into_value(),
"join" => stroke.join.into_value(),
"dash" => stroke.dash.clone().into_value(),
"miter-limit" => {
stroke.miter_limit.map(|limit| limit.get()).into_value()
}
_ => return missing(),
}
} else if let Some(align) = dynamic.downcast::<Alignment>() {
match field {
"x" => align.x().into_value(),
"y" => align.y().into_value(),
_ => return missing(),
}
} else {
return nope();
}
}
_ => return nope(),
};
Ok(result)
}
/// The error message for a type not supporting field access.
#[cold]
fn no_fields(ty: Type) -> EcoString {
eco_format!("cannot access fields on type {ty}")
}
/// The missing field error message.
#[cold]
fn missing_field(ty: Type, field: &str) -> EcoString {
eco_format!("{ty} does not contain field \"{field}\"")
}
/// List the available fields for a type.
pub fn fields_on(ty: Type) -> &'static [&'static str] {
if ty == Type::of::<Version>() {
&Version::COMPONENTS
} else if ty == Type::of::<Length>() {
&["em", "abs"]
} else if ty == Type::of::<Rel>() {
&["ratio", "length"]
} else if ty == Type::of::<Stroke>() {
&["paint", "thickness", "cap", "join", "dash", "miter-limit"]
} else if ty == Type::of::<Alignment>() {
&["x", "y"]
} else {
&[]
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/scope.rs | crates/typst-library/src/foundations/scope.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use ecow::{EcoString, eco_format};
use indexmap::IndexMap;
use indexmap::map::Entry;
use rustc_hash::FxBuildHasher;
use typst_syntax::Span;
use crate::diag::{DeprecationSink, HintedStrResult, HintedString, StrResult, bail};
use crate::foundations::{
Func, IntoValue, NativeElement, NativeFunc, NativeFuncData, NativeType, Value,
};
use crate::{Category, Library};
/// A stack of scopes.
#[derive(Debug, Default, Clone)]
pub struct Scopes<'a> {
/// The active scope.
pub top: Scope,
/// The stack of lower scopes.
pub scopes: Vec<Scope>,
/// The standard library.
pub base: Option<&'a Library>,
}
impl<'a> Scopes<'a> {
/// Create a new, empty hierarchy of scopes.
pub fn new(base: Option<&'a Library>) -> Self {
Self { top: Scope::new(), scopes: vec![], base }
}
/// Enter a new scope.
pub fn enter(&mut self) {
self.scopes.push(std::mem::take(&mut self.top));
}
/// Exit the topmost scope.
///
/// This panics if no scope was entered.
pub fn exit(&mut self) {
self.top = self.scopes.pop().expect("no pushed scope");
}
/// Try to access a binding immutably.
pub fn get(&self, var: &str) -> HintedStrResult<&Binding> {
std::iter::once(&self.top)
.chain(self.scopes.iter().rev())
.find_map(|scope| scope.get(var))
.or_else(|| {
self.base.and_then(|base| match base.global.scope().get(var) {
Some(binding) => Some(binding),
None if var == "std" => Some(&base.std),
None => None,
})
})
.ok_or_else(|| unknown_variable(var))
}
/// Try to access a binding mutably.
pub fn get_mut(&mut self, var: &str) -> HintedStrResult<&mut Binding> {
std::iter::once(&mut self.top)
.chain(&mut self.scopes.iter_mut().rev())
.find_map(|scope| scope.get_mut(var))
.ok_or_else(|| {
match self.base.and_then(|base| base.global.scope().get(var)) {
Some(_) => cannot_mutate_constant(var),
_ if var == "std" => cannot_mutate_constant(var),
_ => unknown_variable(var),
}
})
}
/// Try to access a binding immutably in math.
pub fn get_in_math(&self, var: &str) -> HintedStrResult<&Binding> {
std::iter::once(&self.top)
.chain(self.scopes.iter().rev())
.find_map(|scope| scope.get(var))
.or_else(|| {
self.base.and_then(|base| match base.math.scope().get(var) {
Some(binding) => Some(binding),
None if var == "std" => Some(&base.std),
None => None,
})
})
.ok_or_else(|| {
unknown_variable_math(
var,
self.base.is_some_and(|base| base.global.scope().get(var).is_some()),
)
})
}
/// Check if an std variable is shadowed.
pub fn check_std_shadowed(&self, var: &str) -> bool {
self.base.is_some_and(|base| base.global.scope().get(var).is_some())
&& std::iter::once(&self.top)
.chain(self.scopes.iter().rev())
.any(|scope| scope.get(var).is_some())
}
}
/// A map from binding names to values.
#[derive(Default, Clone)]
pub struct Scope {
map: IndexMap<EcoString, Binding, FxBuildHasher>,
deduplicate: bool,
category: Option<Category>,
}
/// Scope construction.
impl Scope {
/// Create a new empty scope.
pub fn new() -> Self {
Default::default()
}
/// Create a new scope with duplication prevention.
pub fn deduplicating() -> Self {
Self { deduplicate: true, ..Default::default() }
}
/// Enter a new category.
pub fn start_category(&mut self, category: Category) {
self.category = Some(category);
}
/// Reset the category.
pub fn reset_category(&mut self) {
self.category = None;
}
/// Define a native function through a Rust type that shadows the function.
#[track_caller]
pub fn define_func<T: NativeFunc>(&mut self) -> &mut Binding {
let data = T::data();
self.define(data.name, Func::from(data))
}
/// Define a native function with raw function data.
#[track_caller]
pub fn define_func_with_data(
&mut self,
data: &'static NativeFuncData,
) -> &mut Binding {
self.define(data.name, Func::from(data))
}
/// Define a native type.
#[track_caller]
pub fn define_type<T: NativeType>(&mut self) -> &mut Binding {
let ty = T::ty();
self.define(ty.short_name(), ty)
}
/// Define a native element.
#[track_caller]
pub fn define_elem<T: NativeElement>(&mut self) -> &mut Binding {
let elem = T::ELEM;
self.define(elem.name(), elem)
}
/// Define a built-in with compile-time known name and returns a mutable
/// reference to it.
///
/// When the name isn't compile-time known, you should instead use:
/// - `Vm::bind` if you already have [`Binding`]
/// - `Vm::define` if you only have a [`Value`]
/// - [`Scope::bind`](Self::bind) if you are not operating in the context of
/// a `Vm` or if you are binding to something that is not an AST
/// identifier (e.g. when constructing a dynamic
/// [`Module`](super::Module))
#[track_caller]
pub fn define(&mut self, name: &'static str, value: impl IntoValue) -> &mut Binding {
#[cfg(debug_assertions)]
if self.deduplicate && self.map.contains_key(name) {
panic!("duplicate definition: {name}");
}
let mut binding = Binding::detached(value);
binding.category = self.category;
self.bind(name.into(), binding)
}
}
/// Scope manipulation and access.
impl Scope {
/// Inserts a binding into this scope and returns a mutable reference to it.
///
/// Prefer `Vm::bind` if you are operating in the context of a `Vm`.
pub fn bind(&mut self, name: EcoString, binding: Binding) -> &mut Binding {
match self.map.entry(name) {
Entry::Occupied(mut entry) => {
entry.insert(binding);
entry.into_mut()
}
Entry::Vacant(entry) => entry.insert(binding),
}
}
/// Try to access a binding immutably.
pub fn get(&self, var: &str) -> Option<&Binding> {
self.map.get(var)
}
/// Try to access a binding mutably.
pub fn get_mut(&mut self, var: &str) -> Option<&mut Binding> {
self.map.get_mut(var)
}
/// Iterate over all definitions.
pub fn iter(&self) -> impl Iterator<Item = (&EcoString, &Binding)> {
self.map.iter()
}
}
impl Debug for Scope {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Scope ")?;
f.debug_map()
.entries(self.map.iter().map(|(k, v)| (k, v.read())))
.finish()
}
}
impl Hash for Scope {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_usize(self.map.len());
for item in &self.map {
item.hash(state);
}
self.deduplicate.hash(state);
self.category.hash(state);
}
}
/// Defines the associated scope of a Rust type.
pub trait NativeScope {
/// The constructor function for the type, if any.
fn constructor() -> Option<&'static NativeFuncData>;
/// Get the associated scope for the type.
fn scope() -> Scope;
}
/// A bound value with metadata.
#[derive(Debug, Clone, Hash)]
pub struct Binding {
/// The bound value.
value: Value,
/// The kind of binding, determines how the value can be accessed.
kind: BindingKind,
/// A span associated with the binding.
span: Span,
/// The category of the binding.
category: Option<Category>,
/// The deprecation information if this item is deprecated.
deprecation: Option<Box<Deprecation>>,
}
/// The different kinds of slots.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum BindingKind {
/// A normal, mutable binding.
Normal,
/// A captured copy of another variable.
Captured(Capturer),
}
impl Binding {
/// Create a new binding with a span marking its definition site.
pub fn new(value: impl IntoValue, span: Span) -> Self {
Self {
value: value.into_value(),
span,
kind: BindingKind::Normal,
category: None,
deprecation: None,
}
}
/// Create a binding without a span.
pub fn detached(value: impl IntoValue) -> Self {
Self::new(value, Span::detached())
}
/// Marks this binding as deprecated, with the given `message`.
pub fn deprecated(&mut self, deprecation: Deprecation) -> &mut Self {
self.deprecation = Some(Box::new(deprecation));
self
}
/// Read the value.
pub fn read(&self) -> &Value {
&self.value
}
/// Read the value, checking for deprecation.
///
/// As the `sink`
/// - pass `()` to ignore the message.
/// - pass `(&mut engine, span)` to emit a warning into the engine.
pub fn read_checked(&self, sink: impl DeprecationSink) -> &Value {
if let Some(info) = &self.deprecation {
sink.emit(info.message, info.until);
}
&self.value
}
/// Try to write to the value.
///
/// This fails if the value is a read-only closure capture.
pub fn write(&mut self) -> StrResult<&mut Value> {
match self.kind {
BindingKind::Normal => Ok(&mut self.value),
BindingKind::Captured(capturer) => bail!(
"variables from outside the {} are \
read-only and cannot be modified",
match capturer {
Capturer::Function => "function",
Capturer::Context => "context expression",
},
),
}
}
/// Create a copy of the binding for closure capturing.
pub fn capture(&self, capturer: Capturer) -> Self {
Self {
kind: BindingKind::Captured(capturer),
..self.clone()
}
}
/// A span associated with the stored value.
pub fn span(&self) -> Span {
self.span
}
/// A deprecation message for the value, if any.
pub fn deprecation(&self) -> Option<&Deprecation> {
self.deprecation.as_deref()
}
/// The category of the value, if any.
pub fn category(&self) -> Option<Category> {
self.category
}
}
/// What the variable was captured by.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Capturer {
/// Captured by a function / closure.
Function,
/// Captured by a context expression.
Context,
}
/// Information about a deprecated binding.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Deprecation {
/// A deprecation message for the definition.
message: &'static str,
/// A version in which the deprecated binding is planned to be removed.
until: Option<&'static str>,
}
impl Deprecation {
/// Creates new deprecation info with a default message to display when
/// emitting the deprecation warning.
pub fn new() -> Self {
Self { message: "item is deprecated", until: None }
}
/// Set the message to display when emitting the deprecation warning.
pub fn with_message(mut self, message: &'static str) -> Self {
self.message = message;
self
}
/// Set the version in which the binding is planned to be removed.
pub fn with_until(mut self, version: &'static str) -> Self {
self.until = Some(version);
self
}
/// The message to display when emitting the deprecation warning.
pub fn message(&self) -> &'static str {
self.message
}
/// The version in which the binding is planned to be removed.
pub fn until(&self) -> Option<&'static str> {
self.until
}
}
impl Default for Deprecation {
fn default() -> Self {
Self::new()
}
}
/// The error message when trying to mutate a variable from the standard
/// library.
#[cold]
fn cannot_mutate_constant(var: &str) -> HintedString {
eco_format!("cannot mutate a constant: {}", var).into()
}
/// The error message when a variable wasn't found.
#[cold]
fn unknown_variable(var: &str) -> HintedString {
let mut res = HintedString::new(eco_format!("unknown variable: {}", var));
if var.contains('-') {
res.hint(eco_format!(
"if you meant to use subtraction, \
try adding spaces around the minus sign{}: `{}`",
if var.matches('-').count() > 1 { "s" } else { "" },
var.replace('-', " - ")
));
}
res
}
/// The error message when a variable wasn't found it math.
#[cold]
fn unknown_variable_math(var: &str, in_global: bool) -> HintedString {
let mut res = HintedString::new(eco_format!("unknown variable: {}", var));
if matches!(var, "none" | "auto" | "false" | "true") {
res.hint(eco_format!(
"if you meant to use a literal, \
try adding a hash before it: `#{var}`",
));
} else if in_global {
res.hint(eco_format!(
"`{var}` is not available directly in math, \
try adding a hash before it: `#{var}`",
));
} else {
res.hint(eco_format!(
"if you meant to display multiple letters as is, \
try adding spaces between each letter: `{}`",
var.chars().flat_map(|c| [' ', c]).skip(1).collect::<EcoString>()
));
res.hint(eco_format!(
"or if you meant to display this as text, \
try placing it in quotes: `\"{var}\"`"
));
}
res
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/mod.rs | crates/typst-library/src/foundations/mod.rs | //! Foundational types and functions.
pub mod calc;
pub mod ops;
pub mod repr;
pub mod sys;
mod args;
mod array;
mod auto;
mod bool;
mod bytes;
mod cast;
mod content;
mod context;
mod datetime;
mod decimal;
mod dict;
mod duration;
mod fields;
mod float;
mod func;
mod int;
mod label;
mod module;
mod none;
#[path = "plugin.rs"]
mod plugin_;
mod scope;
mod selector;
mod str;
mod styles;
mod symbol;
#[path = "target.rs"]
mod target_;
mod ty;
mod value;
mod version;
pub use self::args::*;
pub use self::array::*;
pub use self::auto::*;
pub use self::bytes::*;
pub use self::cast::*;
pub use self::content::*;
pub use self::context::*;
pub use self::datetime::*;
pub use self::decimal::*;
pub use self::dict::*;
pub use self::duration::*;
pub use self::fields::*;
pub use self::float::*;
pub use self::func::*;
pub use self::int::*;
pub use self::label::*;
pub use self::module::*;
pub use self::none::*;
pub use self::plugin_::*;
pub use self::repr::Repr;
pub use self::scope::*;
pub use self::selector::*;
pub use self::str::*;
pub use self::styles::*;
pub use self::symbol::*;
pub use self::target_::*;
pub use self::ty::*;
pub use self::value::*;
pub use self::version::*;
pub use typst_macros::{scope, ty};
#[rustfmt::skip]
#[doc(hidden)]
pub use {
ecow::{eco_format, eco_vec},
indexmap::IndexMap,
smallvec::SmallVec,
};
use comemo::{Track, TrackedMut};
use ecow::EcoString;
use typst_syntax::{Spanned, SyntaxMode};
use crate::diag::{SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::introspection::Introspector;
use crate::{Feature, Features};
/// Hook up all `foundations` definitions.
pub(super) fn define(global: &mut Scope, inputs: Dict, features: &Features) {
global.start_category(crate::Category::Foundations);
global.define_type::<bool>();
global.define_type::<i64>();
global.define_type::<f64>();
global.define_type::<Str>();
global.define_type::<Label>();
global.define_type::<Bytes>();
global.define_type::<Content>();
global.define_type::<Array>();
global.define_type::<Dict>();
global.define_type::<Func>();
global.define_type::<Args>();
global.define_type::<Type>();
global.define_type::<Module>();
global.define_type::<Regex>();
global.define_type::<Selector>();
global.define_type::<Datetime>();
global.define_type::<Decimal>();
global.define_type::<Symbol>();
global.define_type::<Duration>();
global.define_type::<Version>();
global.define_func::<repr::repr>();
global.define_func::<panic>();
global.define_func::<assert>();
global.define_func::<eval>();
global.define_func::<plugin>();
if features.is_enabled(Feature::Html) {
global.define_func::<target>();
}
global.define("calc", calc::module());
global.define("sys", sys::module(inputs));
global.reset_category();
}
/// Fails with an error.
///
/// Arguments are displayed to the user (not rendered in the document) as
/// strings, converting with `repr` if necessary.
///
/// # Example
/// The code below produces the error `panicked with: "this is wrong"`.
/// ```typ
/// #panic("this is wrong")
/// ```
#[func(keywords = ["error"])]
pub fn panic(
/// The values to panic with and display to the user.
#[variadic]
values: Vec<Value>,
) -> StrResult<Never> {
let mut msg = EcoString::from("panicked");
if !values.is_empty() {
msg.push_str(" with: ");
for (i, value) in values.iter().enumerate() {
if i > 0 {
msg.push_str(", ");
}
msg.push_str(&value.repr());
}
}
Err(msg)
}
/// Ensures that a condition is fulfilled.
///
/// Fails with an error if the condition is not fulfilled. Does not
/// produce any output in the document.
///
/// If you wish to test equality between two values, see [`assert.eq`] and
/// [`assert.ne`].
///
/// # Example
/// ```typ
/// #assert(1 < 2, message: "math broke")
/// ```
#[func(scope)]
pub fn assert(
/// The condition that must be true for the assertion to pass.
condition: bool,
/// The error message when the assertion fails.
#[named]
message: Option<EcoString>,
) -> StrResult<NoneValue> {
if !condition {
if let Some(message) = message {
bail!("assertion failed: {message}");
} else {
bail!("assertion failed");
}
}
Ok(NoneValue)
}
#[scope]
impl assert {
/// Ensures that two values are equal.
///
/// Fails with an error if the first value is not equal to the second. Does not
/// produce any output in the document.
///
/// ```typ
/// #assert.eq(10, 10)
/// ```
#[func(title = "Assert Equal")]
pub fn eq(
/// The first value to compare.
left: Value,
/// The second value to compare.
right: Value,
/// An optional message to display on error instead of the representations
/// of the compared values.
#[named]
message: Option<EcoString>,
) -> StrResult<NoneValue> {
if left != right {
if let Some(message) = message {
bail!("equality assertion failed: {message}");
} else {
bail!(
"equality assertion failed: value {} was not equal to {}",
left.repr(),
right.repr(),
);
}
}
Ok(NoneValue)
}
/// Ensures that two values are not equal.
///
/// Fails with an error if the first value is equal to the second. Does not
/// produce any output in the document.
///
/// ```typ
/// #assert.ne(3, 4)
/// ```
#[func(title = "Assert Not Equal")]
pub fn ne(
/// The first value to compare.
left: Value,
/// The second value to compare.
right: Value,
/// An optional message to display on error instead of the representations
/// of the compared values.
#[named]
message: Option<EcoString>,
) -> StrResult<NoneValue> {
if left == right {
if let Some(message) = message {
bail!("inequality assertion failed: {message}");
} else {
bail!(
"inequality assertion failed: value {} was equal to {}",
left.repr(),
right.repr(),
);
}
}
Ok(NoneValue)
}
}
/// Evaluates a string as Typst code.
///
/// This function should only be used as a last resort.
///
/// # Example
/// ```example
/// #eval("1 + 1") \
/// #eval("(1, 2, 3, 4)").len() \
/// #eval("*Markup!*", mode: "markup") \
/// ```
#[func(title = "Evaluate")]
pub fn eval(
engine: &mut Engine,
/// A string of Typst code to evaluate.
source: Spanned<String>,
/// The [syntactical mode]($reference/syntax/#modes) in which the string is
/// parsed.
///
/// ```example
/// #eval("= Heading", mode: "markup")
/// #eval("1_2^3", mode: "math")
/// ```
#[named]
#[default(SyntaxMode::Code)]
mode: SyntaxMode,
/// A scope of definitions that are made available.
///
/// ```example
/// #eval("x + 1", scope: (x: 2)) \
/// #eval(
/// "abc/xyz",
/// mode: "math",
/// scope: (
/// abc: $a + b + c$,
/// xyz: $x + y + z$,
/// ),
/// )
/// ```
#[named]
#[default]
scope: Dict,
) -> SourceResult<Value> {
let Spanned { v: text, span } = source;
let dict = scope;
let mut scope = Scope::new();
for (key, value) in dict {
scope.bind(key.into(), Binding::new(value, span));
}
(engine.routines.eval_string)(
engine.routines,
engine.world,
TrackedMut::reborrow_mut(&mut engine.sink),
// We create a new, detached introspector for string evaluation. Passing
// the real introspector should not have any consequences with
// `Context::none`, but also no benefits. We might want to pass through
// the context and introspector in the future, to allow introspection
// when calling `eval` from within a context expression, but this should
// be well-considered.
Introspector::default().track(),
Context::none().track(),
&text,
span,
mode,
scope,
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/float.rs | crates/typst-library/src/foundations/float.rs | use std::num::ParseFloatError;
use ecow::{EcoString, eco_format};
use crate::diag::{StrResult, bail};
use crate::foundations::{
Bytes, Decimal, Endianness, Repr, Str, cast, func, repr, scope, ty,
};
use crate::layout::Ratio;
/// A floating-point number.
///
/// A limited-precision representation of a real number. Typst uses 64 bits to
/// store floats. Wherever a float is expected, you can also pass an
/// [integer]($int).
///
/// You can convert a value to a float with this type's constructor.
///
/// NaN and positive infinity are available as `{float.nan}` and `{float.inf}`
/// respectively.
///
/// # Example
/// ```example
/// #3.14 \
/// #1e4 \
/// #(10 / 4)
/// ```
#[ty(scope, cast, name = "float")]
type f64;
#[scope(ext)]
impl f64 {
/// Positive infinity.
const INF: f64 = f64::INFINITY;
/// A NaN value, as defined by the
/// [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754).
const NAN: f64 = f64::NAN;
/// Converts a value to a float.
///
/// - Booleans are converted to `0.0` or `1.0`.
/// - Integers are converted to the closest 64-bit float. For integers with
/// absolute value less than `{calc.pow(2, 53)}`, this conversion is
/// exact.
/// - Ratios are divided by 100%.
/// - Strings are parsed in base 10 to the closest 64-bit float. Exponential
/// notation is supported.
///
/// ```example
/// #float(false) \
/// #float(true) \
/// #float(4) \
/// #float(40%) \
/// #float("2.7") \
/// #float("1e5")
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to a float.
value: ToFloat,
) -> f64 {
value.0
}
/// Checks if a float is not a number.
///
/// In IEEE 754, more than one bit pattern represents a NaN. This function
/// returns `true` if the float is any of those bit patterns.
///
/// ```example
/// #float.is-nan(0) \
/// #float.is-nan(1) \
/// #float.is-nan(float.nan)
/// ```
#[func]
pub fn is_nan(self) -> bool {
f64::is_nan(self)
}
/// Checks if a float is infinite.
///
/// Floats can represent positive infinity and negative infinity. This
/// function returns `{true}` if the float is an infinity.
///
/// ```example
/// #float.is-infinite(0) \
/// #float.is-infinite(1) \
/// #float.is-infinite(float.inf)
/// ```
#[func]
pub fn is_infinite(self) -> bool {
f64::is_infinite(self)
}
/// Calculates the sign of a floating point number.
///
/// - If the number is positive (including `{+0.0}`), returns `{1.0}`.
/// - If the number is negative (including `{-0.0}`), returns `{-1.0}`.
/// - If the number is NaN, returns `{float.nan}`.
///
/// ```example
/// #(5.0).signum() \
/// #(-5.0).signum() \
/// #(0.0).signum() \
/// #float.nan.signum()
/// ```
#[func]
pub fn signum(self) -> f64 {
f64::signum(self)
}
/// Interprets bytes as a float.
///
/// ```example
/// #float.from-bytes(bytes((0, 0, 0, 0, 0, 0, 240, 63))) \
/// #float.from-bytes(bytes((63, 240, 0, 0, 0, 0, 0, 0)), endian: "big")
/// ```
#[func]
pub fn from_bytes(
/// The bytes that should be converted to a float.
///
/// Must have a length of either 4 or 8. The bytes are then
/// interpreted in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)'s
/// binary32 (single-precision) or binary64 (double-precision) format
/// depending on the length of the bytes.
bytes: Bytes,
/// The endianness of the conversion.
#[named]
#[default(Endianness::Little)]
endian: Endianness,
) -> StrResult<f64> {
// Convert slice to an array of length 4 or 8.
if let Ok(buffer) = <[u8; 8]>::try_from(bytes.as_ref()) {
return Ok(match endian {
Endianness::Little => f64::from_le_bytes(buffer),
Endianness::Big => f64::from_be_bytes(buffer),
});
};
if let Ok(buffer) = <[u8; 4]>::try_from(bytes.as_ref()) {
return Ok(match endian {
Endianness::Little => f32::from_le_bytes(buffer),
Endianness::Big => f32::from_be_bytes(buffer),
} as f64);
};
bail!("bytes must have a length of 4 or 8");
}
/// Converts a float to bytes.
///
/// ```example
/// #array(1.0.to-bytes(endian: "big")) \
/// #array(1.0.to-bytes())
/// ```
#[func]
pub fn to_bytes(
self,
/// The endianness of the conversion.
#[named]
#[default(Endianness::Little)]
endian: Endianness,
/// The size of the resulting bytes.
///
/// This must be either 4 or 8. The call will return the
/// representation of this float in either
/// [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)'s binary32
/// (single-precision) or binary64 (double-precision) format
/// depending on the provided size.
#[named]
#[default(8)]
size: u32,
) -> StrResult<Bytes> {
Ok(match size {
8 => Bytes::new(match endian {
Endianness::Little => self.to_le_bytes(),
Endianness::Big => self.to_be_bytes(),
}),
4 => Bytes::new(match endian {
Endianness::Little => (self as f32).to_le_bytes(),
Endianness::Big => (self as f32).to_be_bytes(),
}),
_ => bail!("size must be either 4 or 8"),
})
}
}
impl Repr for f64 {
fn repr(&self) -> EcoString {
repr::format_float(*self, None, true, "")
}
}
/// A value that can be cast to a float.
pub struct ToFloat(f64);
cast! {
ToFloat,
v: f64 => Self(v),
v: bool => Self(v as i64 as f64),
v: i64 => Self(v as f64),
v: Decimal => Self(f64::try_from(v).map_err(|_| eco_format!("invalid float: {}", v))?),
v: Ratio => Self(v.get()),
v: Str => Self(
parse_float(v.clone().into())
.map_err(|_| eco_format!("invalid float: {}", v))?
),
}
fn parse_float(s: EcoString) -> Result<f64, ParseFloatError> {
s.replace(repr::MINUS_SIGN, "-").parse()
}
/// A floating-point number that must be positive (strictly larger than zero).
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct PositiveF64(f64);
impl PositiveF64 {
/// Wrap a float if it is positive.
pub fn new(value: f64) -> Option<Self> {
(value > 0.0).then_some(Self(value))
}
/// Get the underlying value.
pub fn get(self) -> f64 {
self.0
}
}
cast! {
PositiveF64,
self => self.get().into_value(),
v: f64 => Self::new(v).ok_or("number must be positive")?,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/cast.rs | crates/typst-library/src/foundations/cast.rs | #[rustfmt::skip]
#[doc(inline)]
pub use typst_macros::{cast, Cast};
use std::borrow::Cow;
use std::fmt::Write;
use std::hash::Hash;
use std::ops::Add;
use ecow::eco_format;
use smallvec::SmallVec;
use typst_syntax::{Span, Spanned, SyntaxMode};
use unicode_math_class::MathClass;
use crate::diag::{At, HintedStrResult, HintedString, SourceResult, StrResult};
use crate::foundations::{
Fold, NativeElement, Packed, Repr, Str, Type, Value, array, repr,
};
/// Determine details of a type.
///
/// Type casting works as follows:
/// - [`Reflect for T`](Reflect) describes the possible Typst values for `T`
/// (for documentation and autocomplete).
/// - [`IntoValue for T`](IntoValue) is for conversion from `T -> Value`
/// (infallible)
/// - [`FromValue for T`](FromValue) is for conversion from `Value -> T`
/// (fallible).
///
/// We can't use `TryFrom<Value>` due to conflicting impls. We could use
/// `From<T> for Value`, but that inverses the impl and leads to tons of
/// `.into()` all over the place that become hard to decipher.
pub trait Reflect {
/// Describe what can be cast into this value.
fn input() -> CastInfo;
/// Describe what this value can be cast into.
fn output() -> CastInfo;
/// Whether the given value can be converted to `T`.
///
/// This exists for performance. The check could also be done through the
/// [`CastInfo`], but it would be much more expensive (heap allocation +
/// dynamic checks instead of optimized machine code for each type).
fn castable(value: &Value) -> bool;
/// Produce an error message for an unacceptable value type.
///
/// ```ignore
/// assert_eq!(
/// <i64 as Reflect>::error(&Value::None),
/// "expected integer, found none",
/// );
/// ```
fn error(found: &Value) -> HintedString {
Self::input().error(found)
}
}
impl Reflect for Value {
fn input() -> CastInfo {
CastInfo::Any
}
fn output() -> CastInfo {
CastInfo::Any
}
fn castable(_: &Value) -> bool {
true
}
}
impl<T: Reflect> Reflect for Spanned<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: NativeElement + Reflect> Reflect for Packed<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: Reflect> Reflect for StrResult<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: Reflect> Reflect for HintedStrResult<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: Reflect> Reflect for SourceResult<T> {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: Reflect> Reflect for &T {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
impl<T: Reflect> Reflect for &mut T {
fn input() -> CastInfo {
T::input()
}
fn output() -> CastInfo {
T::output()
}
fn castable(value: &Value) -> bool {
T::castable(value)
}
}
/// Cast a Rust type into a Typst [`Value`].
///
/// See also: [`Reflect`].
pub trait IntoValue {
/// Cast this type into a value.
fn into_value(self) -> Value;
}
impl IntoValue for Value {
fn into_value(self) -> Value {
self
}
}
impl IntoValue for (&Str, &Value) {
fn into_value(self) -> Value {
Value::Array(array![self.0.clone(), self.1.clone()])
}
}
impl<T: IntoValue + Clone> IntoValue for Cow<'_, T> {
fn into_value(self) -> Value {
self.into_owned().into_value()
}
}
impl<T: NativeElement + IntoValue> IntoValue for Packed<T> {
fn into_value(self) -> Value {
Value::Content(self.pack())
}
}
impl<T: IntoValue> IntoValue for Spanned<T> {
fn into_value(self) -> Value {
self.v.into_value()
}
}
/// Cast a Rust type or result into a [`SourceResult<Value>`].
///
/// Converts `T`, [`StrResult<T>`], or [`SourceResult<T>`] into
/// [`SourceResult<Value>`] by `Ok`-wrapping or adding span information.
pub trait IntoResult {
/// Cast this type into a value.
fn into_result(self, span: Span) -> SourceResult<Value>;
}
impl<T: IntoValue> IntoResult for T {
fn into_result(self, _: Span) -> SourceResult<Value> {
Ok(self.into_value())
}
}
impl<T: IntoValue> IntoResult for StrResult<T> {
fn into_result(self, span: Span) -> SourceResult<Value> {
self.map(IntoValue::into_value).at(span)
}
}
impl<T: IntoValue> IntoResult for HintedStrResult<T> {
fn into_result(self, span: Span) -> SourceResult<Value> {
self.map(IntoValue::into_value).at(span)
}
}
impl<T: IntoValue> IntoResult for SourceResult<T> {
fn into_result(self, _: Span) -> SourceResult<Value> {
self.map(IntoValue::into_value)
}
}
impl<T: IntoValue> IntoValue for fn() -> T {
fn into_value(self) -> Value {
self().into_value()
}
}
/// Try to cast a Typst [`Value`] into a Rust type.
///
/// See also: [`Reflect`].
pub trait FromValue<V = Value>: Sized + Reflect {
/// Try to cast the value into an instance of `Self`.
fn from_value(value: V) -> HintedStrResult<Self>;
}
impl FromValue for Value {
fn from_value(value: Value) -> HintedStrResult<Self> {
Ok(value)
}
}
impl<T: NativeElement + FromValue> FromValue for Packed<T> {
fn from_value(mut value: Value) -> HintedStrResult<Self> {
let mut span = Span::detached();
if let Value::Content(content) = value {
match content.into_packed::<T>() {
Ok(packed) => return Ok(packed),
Err(content) => {
span = content.span();
value = Value::Content(content)
}
}
}
let val = T::from_value(value)?;
Ok(Packed::new(val).spanned(span))
}
}
impl<T: FromValue> FromValue<Spanned<Value>> for T {
fn from_value(value: Spanned<Value>) -> HintedStrResult<Self> {
T::from_value(value.v)
}
}
impl<T: FromValue> FromValue<Spanned<Value>> for Spanned<T> {
fn from_value(value: Spanned<Value>) -> HintedStrResult<Self> {
let span = value.span;
T::from_value(value.v).map(|t| Spanned::new(t, span))
}
}
/// Describes a possible value for a cast.
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash)]
pub enum CastInfo {
/// Any value is okay.
Any,
/// A specific value, plus short documentation for that value.
Value(Value, &'static str),
/// Any value of a type.
Type(Type),
/// Multiple alternatives.
Union(Vec<Self>),
}
impl CastInfo {
/// Produce an error message describing what was expected and what was
/// found.
pub fn error(&self, found: &Value) -> HintedString {
let mut matching_type = false;
let mut parts = vec![];
self.walk(|info| match info {
CastInfo::Any => parts.push("anything".into()),
CastInfo::Value(value, _) => {
parts.push(value.repr());
if value.ty() == found.ty() {
matching_type = true;
}
}
CastInfo::Type(ty) => parts.push(eco_format!("{ty}")),
CastInfo::Union(_) => {}
});
let mut msg = String::from("expected ");
if parts.is_empty() {
msg.push_str(" nothing");
}
msg.push_str(&repr::separated_list(&parts, "or"));
if !matching_type {
msg.push_str(", found ");
write!(msg, "{}", found.ty()).unwrap();
}
let mut msg: HintedString = msg.into();
if let Value::Int(i) = found {
if !matching_type && parts.iter().any(|p| p == "length") {
msg.hint(eco_format!("a length needs a unit - did you mean {i}pt?"));
}
} else if let Value::Str(s) = found {
if !matching_type && parts.iter().any(|p| p == "label") {
if typst_syntax::is_valid_label_literal_id(s) {
msg.hint(eco_format!(
"use `<{s}>` or `label({})` to create a label",
s.repr()
));
} else {
msg.hint(eco_format!("use `label({})` to create a label", s.repr()));
}
}
} else if let Value::Decimal(_) = found
&& !matching_type
&& parts.iter().any(|p| p == "float")
{
msg.hint(eco_format!(
"if loss of precision is acceptable, explicitly cast the \
decimal to a float with `float(value)`"
));
}
msg
}
/// Walk all contained non-union infos.
pub fn walk<F>(&self, mut f: F)
where
F: FnMut(&Self),
{
fn inner<F>(info: &CastInfo, f: &mut F)
where
F: FnMut(&CastInfo),
{
if let CastInfo::Union(infos) = info {
for child in infos {
inner(child, f);
}
} else {
f(info);
}
}
inner(self, &mut f)
}
}
impl Add for CastInfo {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self::Union(match (self, rhs) {
(Self::Union(mut lhs), Self::Union(rhs)) => {
for cast in rhs {
if !lhs.contains(&cast) {
lhs.push(cast);
}
}
lhs
}
(Self::Union(mut lhs), rhs) => {
if !lhs.contains(&rhs) {
lhs.push(rhs);
}
lhs
}
(lhs, Self::Union(mut rhs)) => {
if !rhs.contains(&lhs) {
rhs.insert(0, lhs);
}
rhs
}
(lhs, rhs) => vec![lhs, rhs],
})
}
}
/// A container for an argument.
pub trait Container {
/// The contained type.
type Inner;
}
impl<T> Container for Option<T> {
type Inner = T;
}
impl<T> Container for Vec<T> {
type Inner = T;
}
impl<T, const N: usize> Container for SmallVec<[T; N]> {
type Inner = T;
}
/// An uninhabitable type.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Never {}
impl Reflect for Never {
fn input() -> CastInfo {
CastInfo::Union(vec![])
}
fn output() -> CastInfo {
CastInfo::Union(vec![])
}
fn castable(_: &Value) -> bool {
false
}
}
impl IntoValue for Never {
fn into_value(self) -> Value {
match self {}
}
}
impl FromValue for Never {
fn from_value(value: Value) -> HintedStrResult<Self> {
Err(Self::error(&value))
}
}
cast! {
SyntaxMode,
self => IntoValue::into_value(match self {
SyntaxMode::Markup => "markup",
SyntaxMode::Math => "math",
SyntaxMode::Code => "code",
}),
/// Evaluate as markup, as in a Typst file.
"markup" => SyntaxMode::Markup,
/// Evaluate as math, as in an equation.
"math" => SyntaxMode::Math,
/// Evaluate as code, as after a hash.
"code" => SyntaxMode::Code,
}
cast! {
MathClass,
self => IntoValue::into_value(match self {
MathClass::Normal => "normal",
MathClass::Alphabetic => "alphabetic",
MathClass::Binary => "binary",
MathClass::Closing => "closing",
MathClass::Diacritic => "diacritic",
MathClass::Fence => "fence",
MathClass::GlyphPart => "glyph-part",
MathClass::Large => "large",
MathClass::Opening => "opening",
MathClass::Punctuation => "punctuation",
MathClass::Relation => "relation",
MathClass::Space => "space",
MathClass::Unary => "unary",
MathClass::Vary => "vary",
MathClass::Special => "special",
}),
/// The default class for non-special things.
"normal" => MathClass::Normal,
/// Punctuation, e.g. a comma.
"punctuation" => MathClass::Punctuation,
/// An opening delimiter, e.g. `(`.
"opening" => MathClass::Opening,
/// A closing delimiter, e.g. `)`.
"closing" => MathClass::Closing,
/// A delimiter that is the same on both sides, e.g. `|`.
"fence" => MathClass::Fence,
/// A large operator like `sum`.
"large" => MathClass::Large,
/// A relation like `=` or `prec`.
"relation" => MathClass::Relation,
/// A unary operator like `not`.
"unary" => MathClass::Unary,
/// A binary operator like `times`.
"binary" => MathClass::Binary,
/// An operator that can be both unary or binary like `+`.
"vary" => MathClass::Vary,
}
/// A type that contains a user-visible source portion and something that is
/// derived from it, but not user-visible.
///
/// An example usage would be `source` being a `DataSource` and `derived` a
/// TextMate theme parsed from it. With `Derived`, we can store both parts in
/// the `RawElem::theme` field and get automatic nice `Reflect` and `IntoValue`
/// impls.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Derived<S, D> {
/// The source portion.
pub source: S,
/// The derived portion.
pub derived: D,
}
impl<S, D> Derived<S, D> {
/// Create a new instance from the `source` and the `derived` data.
pub fn new(source: S, derived: D) -> Self {
Self { source, derived }
}
}
impl<S: Reflect, D> Reflect for Derived<S, D> {
fn input() -> CastInfo {
S::input()
}
fn output() -> CastInfo {
S::output()
}
fn castable(value: &Value) -> bool {
S::castable(value)
}
fn error(found: &Value) -> HintedString {
S::error(found)
}
}
impl<S: IntoValue, D> IntoValue for Derived<S, D> {
fn into_value(self) -> Value {
self.source.into_value()
}
}
impl<S: Fold, D: Fold> Fold for Derived<S, D> {
fn fold(self, outer: Self) -> Self {
Self {
source: self.source.fold(outer.source),
derived: self.derived.fold(outer.derived),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/ty.rs | crates/typst-library/src/foundations/ty.rs | #[doc(inline)]
pub use typst_macros::{scope, ty};
use std::cmp::Ordering;
use std::fmt::{self, Debug, Display, Formatter};
use std::sync::LazyLock;
use ecow::{EcoString, eco_format};
use typst_utils::Static;
use crate::diag::{DeprecationSink, StrResult, bail};
use crate::foundations::{
AutoValue, Func, NativeFuncData, NoneValue, Repr, Scope, Value, cast, func,
};
/// Describes a kind of value.
///
/// To style your document, you need to work with values of different kinds:
/// Lengths specifying the size of your elements, colors for your text and
/// shapes, and more. Typst categorizes these into clearly defined _types_ and
/// tells you where it expects which type of value.
///
/// Apart from basic types for numeric values and [typical]($int)
/// [types]($float) [known]($str) [from]($array) [programming]($dictionary)
/// languages, Typst provides a special type for [_content._]($content) A value
/// of this type can hold anything that you can enter into your document: Text,
/// elements like headings and shapes, and style information.
///
/// # Example
/// ```example
/// #let x = 10
/// #if type(x) == int [
/// #x is an integer!
/// ] else [
/// #x is another value...
/// ]
///
/// An image is of type
/// #type(image("glacier.jpg")).
/// ```
///
/// The type of `{10}` is `int`. Now, what is the type of `int` or even `type`?
/// ```example
/// #type(int) \
/// #type(type)
/// ```
///
/// Unlike other types like `int`, [none] and [auto] do not have a name
/// representing them. To test if a value is one of these, compare your value to
/// them directly, e.g:
/// ```example
/// #let val = none
/// #if val == none [
/// Yep, it's none.
/// ]
/// ```
///
/// Note that `type` will return [`content`] for all document elements. To
/// programmatically determine which kind of content you are dealing with, see
/// [`content.func`].
#[ty(scope, cast)]
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Type(Static<NativeTypeData>);
impl Type {
/// Get the type for `T`.
pub fn of<T: NativeType>() -> Self {
T::ty()
}
/// The type's short name, how it is used in code (e.g. `str`).
pub fn short_name(&self) -> &'static str {
self.0.name
}
/// The type's long name, for use in diagnostics (e.g. `string`).
pub fn long_name(&self) -> &'static str {
self.0.long_name
}
/// The type's title case name, for use in documentation (e.g. `String`).
pub fn title(&self) -> &'static str {
self.0.title
}
/// Documentation for the type (as Markdown).
pub fn docs(&self) -> &'static str {
self.0.docs
}
/// Search keywords for the type.
pub fn keywords(&self) -> &'static [&'static str] {
self.0.keywords
}
/// This type's constructor function.
pub fn constructor(&self) -> StrResult<Func> {
self.0
.constructor
.as_ref()
.map(|lazy| Func::from(*lazy))
.ok_or_else(|| eco_format!("type {self} does not have a constructor"))
}
/// The type's associated scope that holds sub-definitions.
pub fn scope(&self) -> &'static Scope {
&(self.0).0.scope
}
/// Get a field from this type's scope, if possible.
pub fn field(
&self,
field: &str,
sink: impl DeprecationSink,
) -> StrResult<&'static Value> {
match self.scope().get(field) {
Some(binding) => Ok(binding.read_checked(sink)),
None => bail!("type {self} does not contain field `{field}`"),
}
}
}
#[scope]
impl Type {
/// Determines a value's type.
///
/// ```example
/// #type(12) \
/// #type(14.7) \
/// #type("hello") \
/// #type(<glacier>) \
/// #type([Hi]) \
/// #type(x => x + 1) \
/// #type(type)
/// ```
#[func(constructor)]
pub fn construct(
/// The value whose type's to determine.
value: Value,
) -> Type {
value.ty()
}
}
impl Debug for Type {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Type({})", self.long_name())
}
}
impl Repr for Type {
fn repr(&self) -> EcoString {
if *self == Type::of::<AutoValue>() {
"type(auto)"
} else if *self == Type::of::<NoneValue>() {
"type(none)"
} else {
self.short_name()
}
.into()
}
}
impl Display for Type {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(self.long_name())
}
}
impl Ord for Type {
fn cmp(&self, other: &Self) -> Ordering {
self.long_name().cmp(other.long_name())
}
}
impl PartialOrd for Type {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// A Typst type that is defined by a native Rust type.
pub trait NativeType {
/// The type's name.
///
/// In contrast to `data()`, this is usable in const contexts.
const NAME: &'static str;
/// Get the type for the native Rust type.
fn ty() -> Type {
Type::from(Self::data())
}
// Get the type data for the native Rust type.
fn data() -> &'static NativeTypeData;
}
/// Defines a native type.
#[derive(Debug)]
pub struct NativeTypeData {
/// The type's normal name (e.g. `str`), as exposed to Typst.
pub name: &'static str,
/// The type's long name (e.g. `string`), for error messages.
pub long_name: &'static str,
/// The function's title case name (e.g. `String`).
pub title: &'static str,
/// The documentation for this type as a string.
pub docs: &'static str,
/// A list of alternate search terms for this type.
pub keywords: &'static [&'static str],
/// The constructor for this type.
pub constructor: LazyLock<Option<&'static NativeFuncData>>,
/// Definitions in the scope of the type.
pub scope: LazyLock<Scope>,
}
impl From<&'static NativeTypeData> for Type {
fn from(data: &'static NativeTypeData) -> Self {
Self(Static(data))
}
}
cast! {
&'static NativeTypeData,
self => Type::from(self).into_value(),
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/auto.rs | crates/typst-library/src/foundations/auto.rs | use std::fmt::{self, Debug, Formatter};
use ecow::EcoString;
use crate::diag::HintedStrResult;
use crate::foundations::{
CastInfo, Fold, FromValue, IntoValue, Reflect, Repr, Resolve, StyleChain, Type,
Value, ty,
};
/// A value that indicates a smart default.
///
/// The auto type has exactly one value: `{auto}`.
///
/// Parameters that support the `{auto}` value have some smart default or
/// contextual behaviour. A good example is the [text direction]($text.dir)
/// parameter. Setting it to `{auto}` lets Typst automatically determine the
/// direction from the [text language]($text.lang).
#[ty(cast, name = "auto")]
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AutoValue;
impl IntoValue for AutoValue {
fn into_value(self) -> Value {
Value::Auto
}
}
impl FromValue for AutoValue {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
Value::Auto => Ok(Self),
_ => Err(Self::error(&value)),
}
}
}
impl Reflect for AutoValue {
fn input() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn output() -> CastInfo {
CastInfo::Type(Type::of::<Self>())
}
fn castable(value: &Value) -> bool {
matches!(value, Value::Auto)
}
}
impl Debug for AutoValue {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Auto")
}
}
impl Repr for AutoValue {
fn repr(&self) -> EcoString {
"auto".into()
}
}
/// A value that can be automatically determined.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Smart<T> {
/// The value should be determined smartly based on the circumstances.
#[default]
Auto,
/// A specific value.
Custom(T),
}
impl<T> Smart<T> {
/// Whether the value is `Auto`.
pub fn is_auto(&self) -> bool {
matches!(self, Self::Auto)
}
/// Whether this holds a custom value.
pub fn is_custom(&self) -> bool {
matches!(self, Self::Custom(_))
}
/// Whether this is a `Smart::Custom(x)` and `f(x)` is true.
pub fn is_custom_and<F>(self, f: F) -> bool
where
F: Fn(T) -> bool,
{
match self {
Self::Auto => false,
Self::Custom(x) => f(x),
}
}
/// Returns a `Smart<&T>` borrowing the inner `T`.
pub fn as_ref(&self) -> Smart<&T> {
match self {
Smart::Auto => Smart::Auto,
Smart::Custom(v) => Smart::Custom(v),
}
}
/// Returns the contained custom value.
///
/// If the value is [`Smart::Auto`], returns `None`.
///
/// Equivalently, this just converts `Smart` to `Option`.
pub fn custom(self) -> Option<T> {
match self {
Self::Auto => None,
Self::Custom(x) => Some(x),
}
}
/// Map the contained custom value with `f`.
pub fn map<F, U>(self, f: F) -> Smart<U>
where
F: FnOnce(T) -> U,
{
match self {
Self::Auto => Smart::Auto,
Self::Custom(x) => Smart::Custom(f(x)),
}
}
/// Map the contained custom value with `f` if it contains a custom value,
/// otherwise returns `default`.
pub fn map_or<F, U>(self, default: U, f: F) -> U
where
F: FnOnce(T) -> U,
{
match self {
Self::Auto => default,
Self::Custom(x) => f(x),
}
}
/// Keeps `self` if it contains a custom value, otherwise returns `other`.
pub fn or(self, other: Smart<T>) -> Self {
match self {
Self::Custom(x) => Self::Custom(x),
Self::Auto => other,
}
}
/// Keeps `self` if it contains a custom value, otherwise returns the
/// output of the given function.
pub fn or_else<F>(self, f: F) -> Self
where
F: FnOnce() -> Self,
{
match self {
Self::Custom(x) => Self::Custom(x),
Self::Auto => f(),
}
}
/// Returns `Auto` if `self` is `Auto`, otherwise calls the provided
/// function on the contained value and returns the result.
pub fn and_then<F, U>(self, f: F) -> Smart<U>
where
F: FnOnce(T) -> Smart<U>,
{
match self {
Smart::Auto => Smart::Auto,
Smart::Custom(x) => f(x),
}
}
/// Returns the contained custom value or a provided default value.
pub fn unwrap_or(self, default: T) -> T {
match self {
Self::Auto => default,
Self::Custom(x) => x,
}
}
/// Returns the contained custom value or computes a default value.
pub fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T,
{
match self {
Self::Auto => f(),
Self::Custom(x) => x,
}
}
/// Returns the contained custom value or the default value.
pub fn unwrap_or_default(self) -> T
where
T: Default,
{
// we want to do this; the Clippy lint is not type-aware
#[allow(clippy::unwrap_or_default)]
self.unwrap_or_else(T::default)
}
}
impl<T> Smart<Smart<T>> {
/// Removes a single level of nesting, returns `Auto` if the inner or outer value is `Auto`.
pub fn flatten(self) -> Smart<T> {
match self {
Smart::Custom(Smart::Auto) | Smart::Auto => Smart::Auto,
Smart::Custom(Smart::Custom(v)) => Smart::Custom(v),
}
}
}
impl<T> From<Option<T>> for Smart<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(v) => Smart::Custom(v),
None => Smart::Auto,
}
}
}
impl<T: Reflect> Reflect for Smart<T> {
fn input() -> CastInfo {
T::input() + AutoValue::input()
}
fn output() -> CastInfo {
T::output() + AutoValue::output()
}
fn castable(value: &Value) -> bool {
AutoValue::castable(value) || T::castable(value)
}
}
impl<T: IntoValue> IntoValue for Smart<T> {
fn into_value(self) -> Value {
match self {
Smart::Custom(v) => v.into_value(),
Smart::Auto => Value::Auto,
}
}
}
impl<T: FromValue> FromValue for Smart<T> {
fn from_value(value: Value) -> HintedStrResult<Self> {
match value {
Value::Auto => Ok(Self::Auto),
v if T::castable(&v) => Ok(Self::Custom(T::from_value(v)?)),
_ => Err(Self::error(&value)),
}
}
}
impl<T: Resolve> Resolve for Smart<T> {
type Output = Smart<T::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|v| v.resolve(styles))
}
}
impl<T: Fold> Fold for Smart<T> {
fn fold(self, outer: Self) -> Self {
use Smart::Custom;
match (self, outer) {
(Custom(inner), Custom(outer)) => Custom(inner.fold(outer)),
// An explicit `auto` should be respected, thus we don't do
// `inner.or(outer)`.
(inner, _) => inner,
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/int.rs | crates/typst-library/src/foundations/int.rs | use std::num::{
IntErrorKind, NonZeroI64, NonZeroIsize, NonZeroU32, NonZeroU64, NonZeroUsize,
};
use ecow::{EcoString, eco_format};
use smallvec::SmallVec;
use typst_syntax::{Span, Spanned};
use crate::diag::{At, HintedString, SourceResult, StrResult, bail, error};
use crate::foundations::{
Base, Bytes, Cast, Decimal, Repr, Str, Value, cast, func, repr, scope, ty,
};
/// A whole number.
///
/// The number can be negative, zero, or positive. As Typst uses 64 bits to
/// store integers, integers cannot be smaller than `{-9223372036854775808}` or
/// larger than `{9223372036854775807}`. Integer literals are always positive,
/// so a negative integer such as `{-1}` is semantically the negation `-` of the
/// positive literal `1`. A positive integer greater than the maximum value and
/// a negative integer less than or equal to the minimum value cannot be
/// represented as an integer literal, and are instead parsed as a `{float}`.
/// The minimum integer value can still be obtained through integer arithmetic.
///
/// The number can also be specified as hexadecimal, octal, or binary by
/// starting it with a zero followed by either `x`, `o`, or `b`.
///
/// You can convert a value to an integer with this type's constructor.
///
/// # Example
/// ```example
/// #(1 + 2) \
/// #(2 - 5) \
/// #(3 + 4 < 8)
///
/// #0xff \
/// #0o10 \
/// #0b1001
/// ```
#[ty(scope, cast, name = "int", title = "Integer")]
type i64;
#[scope(ext)]
impl i64 {
/// Converts a value to an integer. Raises an error if there is an attempt
/// to parse an invalid string or produce an integer that doesn't fit
/// into a 64-bit signed integer.
///
/// - Booleans are converted to `0` or `1`.
/// - Floats and decimals are rounded to the next 64-bit integer towards zero.
/// - Strings are parsed in base 10 by default.
///
/// ```example
/// #int(false) \
/// #int(true) \
/// #int(2.7) \
/// #int(decimal("3.8")) \
/// #(int("27") + int("4")) \
/// #(int("beef", base: 16))
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to an integer.
value: Spanned<ToInt>,
/// The base (radix) for parsing strings, between 2 and 36.
#[named]
#[default(Spanned::new(Base::Default, Span::detached()))]
base: Spanned<Base>,
) -> SourceResult<i64> {
Ok(match value.v {
ToInt::Int(n) => match base.v {
Base::User(_) => bail!(base.span, "base is only supported for strings"),
_ => n,
},
ToInt::Str(s) => {
let base_value = base.v.value();
let radix: u32 = match base_value {
2..=36 => base_value as u32,
_ => bail!(base.span, "base must be between 2 and 36"),
};
match s.strip_prefix('-').or_else(|| s.strip_prefix(repr::MINUS_SIGN)) {
// Negative (without minus)
Some(s) => {
// Parse the digits part into u64
// => abs(i64::MIN) fits into u64
let bigger = u64::from_str_radix(s, radix)
.map_err(|e| parse_str_error(e.kind(), base))
.at(value.span)?;
// Number wouldn't fit into i64
if bigger > i64::MIN.unsigned_abs() {
return Err(parse_str_error(
&IntErrorKind::NegOverflow,
base,
))
.at(value.span);
}
bigger.wrapping_neg() as i64
}
// Positive
None => i64::from_str_radix(&s, radix)
.map_err(|e| parse_str_error(e.kind(), base))
.at(value.span)?,
}
}
})
}
/// Calculates the sign of an integer.
///
/// - If the number is positive, returns `{1}`.
/// - If the number is negative, returns `{-1}`.
/// - If the number is zero, returns `{0}`.
///
/// ```example
/// #(5).signum() \
/// #(-5).signum() \
/// #(0).signum()
/// ```
#[func]
pub fn signum(self) -> i64 {
i64::signum(self)
}
/// Calculates the bitwise NOT of an integer.
///
/// For the purposes of this function, the operand is treated as a signed
/// integer of 64 bits.
///
/// ```example
/// #4.bit-not() \
/// #(-1).bit-not()
/// ```
#[func(title = "Bitwise NOT")]
pub fn bit_not(self) -> i64 {
!self
}
/// Calculates the bitwise AND between two integers.
///
/// For the purposes of this function, the operands are treated as signed
/// integers of 64 bits.
///
/// ```example
/// #128.bit-and(192)
/// ```
#[func(title = "Bitwise AND")]
pub fn bit_and(
self,
/// The right-hand operand of the bitwise AND.
rhs: i64,
) -> i64 {
self & rhs
}
/// Calculates the bitwise OR between two integers.
///
/// For the purposes of this function, the operands are treated as signed
/// integers of 64 bits.
///
/// ```example
/// #64.bit-or(32)
/// ```
#[func(title = "Bitwise OR")]
pub fn bit_or(
self,
/// The right-hand operand of the bitwise OR.
rhs: i64,
) -> i64 {
self | rhs
}
/// Calculates the bitwise XOR between two integers.
///
/// For the purposes of this function, the operands are treated as signed
/// integers of 64 bits.
///
/// ```example
/// #64.bit-xor(96)
/// ```
#[func(title = "Bitwise XOR")]
pub fn bit_xor(
self,
/// The right-hand operand of the bitwise XOR.
rhs: i64,
) -> i64 {
self ^ rhs
}
/// Shifts the operand's bits to the left by the specified amount.
///
/// For the purposes of this function, the operand is treated as a signed
/// integer of 64 bits. An error will occur if the result is too large to
/// fit in a 64-bit integer.
///
/// ```example
/// #33.bit-lshift(2) \
/// #(-1).bit-lshift(3)
/// ```
#[func(title = "Bitwise Left Shift")]
pub fn bit_lshift(
self,
/// The amount of bits to shift. Must not be negative.
shift: u32,
) -> StrResult<i64> {
Ok(self.checked_shl(shift).ok_or("the result is too large")?)
}
/// Shifts the operand's bits to the right by the specified amount.
/// Performs an arithmetic shift by default (extends the sign bit to the left,
/// such that negative numbers stay negative), but that can be changed by the
/// `logical` parameter.
///
/// For the purposes of this function, the operand is treated as a signed
/// integer of 64 bits.
///
/// ```example
/// #64.bit-rshift(2) \
/// #(-8).bit-rshift(2) \
/// #(-8).bit-rshift(2, logical: true)
/// ```
#[func(title = "Bitwise Right Shift")]
pub fn bit_rshift(
self,
/// The amount of bits to shift. Must not be negative.
///
/// Shifts larger than 63 are allowed and will cause the return value to
/// saturate. For non-negative numbers, the return value saturates at
/// `{0}`, while, for negative numbers, it saturates at `{-1}` if
/// `logical` is set to `{false}`, or `{0}` if it is `{true}`. This
/// behavior is consistent with just applying this operation multiple
/// times. Therefore, the shift will always succeed.
shift: u32,
/// Toggles whether a logical (unsigned) right shift should be performed
/// instead of arithmetic right shift.
/// If this is `{true}`, negative operands will not preserve their sign
/// bit, and bits which appear to the left after the shift will be
/// `{0}`. This parameter has no effect on non-negative operands.
#[named]
#[default(false)]
logical: bool,
) -> i64 {
if logical {
if shift >= u64::BITS {
// Excessive logical right shift would be equivalent to setting
// all bits to zero. Using `.min(63)` is not enough for logical
// right shift, since `-1 >> 63` returns 1, whereas
// `calc.bit-rshift(-1, 64)` should return the same as
// `(-1 >> 63) >> 1`, which is zero.
0
} else {
// Here we reinterpret the signed integer's bits as unsigned to
// perform logical right shift, and then reinterpret back as signed.
// This is valid as, according to the Rust reference, casting between
// two integers of same size (i64 <-> u64) is a no-op (two's complement
// is used).
// Reference:
// https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#numeric-cast
((self as u64) >> shift) as i64
}
} else {
// Saturate at -1 (negative) or 0 (otherwise) on excessive arithmetic
// right shift. Shifting those numbers any further does not change
// them, so it is consistent.
let shift = shift.min(i64::BITS - 1);
self >> shift
}
}
/// Converts bytes to an integer.
///
/// ```example
/// #int.from-bytes(bytes((0, 0, 0, 0, 0, 0, 0, 1))) \
/// #int.from-bytes(bytes((1, 0, 0, 0, 0, 0, 0, 0)), endian: "big")
/// ```
#[func]
pub fn from_bytes(
/// The bytes that should be converted to an integer.
///
/// Must be of length at most 8 so that the result fits into a 64-bit
/// signed integer.
bytes: Bytes,
/// The endianness of the conversion.
#[named]
#[default(Endianness::Little)]
endian: Endianness,
/// Whether the bytes should be treated as a signed integer. If this is
/// `{true}` and the most significant bit is set, the resulting number
/// will negative.
#[named]
#[default(true)]
signed: bool,
) -> StrResult<i64> {
let len = bytes.len();
if len == 0 {
return Ok(0);
} else if len > 8 {
bail!("too many bytes to convert to a 64 bit number");
}
// `decimal` will hold the part of the buffer that should be filled with
// the input bytes, `rest` will remain as is or be filled with 0xFF for
// negative numbers if signed is true.
//
// – big-endian: `decimal` will be the rightmost bytes of the buffer.
// - little-endian: `decimal` will be the leftmost bytes of the buffer.
let mut buf = [0u8; 8];
let (rest, decimal) = match endian {
Endianness::Big => buf.split_at_mut(8 - len),
Endianness::Little => {
let (first, second) = buf.split_at_mut(len);
(second, first)
}
};
decimal.copy_from_slice(bytes.as_ref());
// Perform sign-extension if necessary.
if signed {
let most_significant_byte = match endian {
Endianness::Big => decimal[0],
Endianness::Little => decimal[len - 1],
};
if most_significant_byte & 0b1000_0000 != 0 {
rest.fill(0xFF);
}
}
Ok(match endian {
Endianness::Big => i64::from_be_bytes(buf),
Endianness::Little => i64::from_le_bytes(buf),
})
}
/// Converts an integer to bytes.
///
/// ```example
/// #array(10000.to-bytes(endian: "big")) \
/// #array(10000.to-bytes(size: 4))
/// ```
#[func]
pub fn to_bytes(
self,
/// The endianness of the conversion.
#[named]
#[default(Endianness::Little)]
endian: Endianness,
/// The size in bytes of the resulting bytes (must be at least zero). If
/// the integer is too large to fit in the specified size, the
/// conversion will truncate the remaining bytes based on the
/// endianness. To keep the same resulting value, if the endianness is
/// big-endian, the truncation will happen at the rightmost bytes.
/// Otherwise, if the endianness is little-endian, the truncation will
/// happen at the leftmost bytes.
///
/// Be aware that if the integer is negative and the size is not enough
/// to make the number fit, when passing the resulting bytes to
/// `int.from-bytes`, the resulting number might be positive, as the
/// most significant bit might not be set to 1.
#[named]
#[default(8)]
size: usize,
) -> Bytes {
let array = match endian {
Endianness::Big => self.to_be_bytes(),
Endianness::Little => self.to_le_bytes(),
};
let mut buf = SmallVec::<[u8; 8]>::from_elem(0, size);
match endian {
Endianness::Big => {
// Copy the bytes from the array to the buffer, starting from
// the end of the buffer.
let buf_start = size.saturating_sub(8);
let array_start = 8usize.saturating_sub(size);
buf[buf_start..].copy_from_slice(&array[array_start..])
}
Endianness::Little => {
// Copy the bytes from the array to the buffer, starting from
// the beginning of the buffer.
let end = size.min(8);
buf[..end].copy_from_slice(&array[..end])
}
}
Bytes::new(buf)
}
}
impl Repr for i64 {
fn repr(&self) -> EcoString {
eco_format!("{:?}", self)
}
}
/// Represents the byte order used for converting integers and floats to bytes
/// and vice versa.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Endianness {
/// Big-endian byte order: The highest-value byte is at the beginning of the
/// bytes.
Big,
/// Little-endian byte order: The lowest-value byte is at the beginning of
/// the bytes.
Little,
}
/// A value that can be cast to an integer.
pub enum ToInt {
Int(i64),
Str(Str),
}
cast! {
ToInt,
v: i64 => Self::Int(v),
v: bool => Self::Int(v as i64),
v: f64 => Self::Int(convert_float_to_int(v)?),
v: Decimal => Self::Int(i64::try_from(v).map_err(|_| eco_format!("number too large"))?),
v: Str => Self::Str(v),
}
pub fn convert_float_to_int(f: f64) -> StrResult<i64> {
if f <= i64::MIN as f64 - 1.0 || f >= i64::MAX as f64 + 1.0 {
Err(eco_format!("number too large"))
} else {
Ok(f as i64)
}
}
#[cold]
fn parse_str_error(kind: &IntErrorKind, base: Spanned<Base>) -> HintedString {
let base = base.v.value();
match kind {
IntErrorKind::Empty => error!("string must not be empty"),
IntErrorKind::InvalidDigit => match base {
10 => error!("string contains invalid digits"),
_ => error!("string contains invalid digits for a base {base} integer"),
},
IntErrorKind::PosOverflow => error!(
"integer value is too large";
hint: "value does not fit into a signed 64-bit integer";
hint: "try using a floating point number";
),
IntErrorKind::NegOverflow => error!(
"integer value is too small";
hint: "value does not fit into a signed 64-bit integer";
hint: "try using a floating point number";
),
IntErrorKind::Zero => unreachable!(),
_ => error!("invalid integer"),
}
}
macro_rules! signed_int {
($($ty:ty)*) => {
$(cast! {
$ty,
self => {
#[allow(irrefutable_let_patterns)]
if let Ok(int) = i64::try_from(self) {
Value::Int(int)
} else {
// Some numbers (i128) are too large to be cast as i64
// In that case, we accept that there may be a
// precision loss, and use a floating point number
Value::Float(self as _)
}
},
v: i64 => v.try_into().map_err(|_| "number too large")?,
})*
}
}
macro_rules! unsigned_int {
($($ty:ty)*) => {
$(cast! {
$ty,
self => {
#[allow(irrefutable_let_patterns)]
if let Ok(int) = i64::try_from(self) {
Value::Int(int)
} else {
// Some numbers (u64, u128) are too large to be cast as i64
// In that case, we accept that there may be a
// precision loss, and use a floating point number
Value::Float(self as _)
}
},
v: i64 => v.try_into().map_err(|_| {
if v < 0 {
"number must be at least zero"
} else {
"number too large"
}
})?,
})*
}
}
signed_int! { i8 i16 i32 i128 isize }
unsigned_int! { u8 u16 u32 u64 u128 usize }
cast! {
NonZeroI64,
self => Value::Int(self.get() as _),
v: i64 => v.try_into()
.map_err(|_| if v == 0 {
"number must not be zero"
} else {
"number too large"
})?,
}
cast! {
NonZeroIsize,
self => Value::Int(self.get() as _),
v: i64 => v
.try_into()
.and_then(|v: isize| v.try_into())
.map_err(|_| if v == 0 {
"number must not be zero"
} else {
"number too large"
})?,
}
cast! {
NonZeroU64,
self => Value::Int(self.get() as _),
v: i64 => v
.try_into()
.and_then(|v: u64| v.try_into())
.map_err(|_| if v <= 0 {
"number must be positive"
} else {
"number too large"
})?,
}
cast! {
NonZeroUsize,
self => Value::Int(self.get() as _),
v: i64 => v
.try_into()
.and_then(|v: usize| v.try_into())
.map_err(|_| if v <= 0 {
"number must be positive"
} else {
"number too large"
})?,
}
cast! {
NonZeroU32,
self => Value::Int(self.get() as _),
v: i64 => v
.try_into()
.and_then(|v: u32| v.try_into())
.map_err(|_| if v <= 0 {
"number must be positive"
} else {
"number too large"
})?,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/repr.rs | crates/typst-library/src/foundations/repr.rs | //! Debug representation of values.
use ecow::{EcoString, eco_format};
use typst_utils::round_with_precision;
use crate::foundations::{Str, Value, func};
/// The Unicode minus sign.
pub const MINUS_SIGN: &str = "\u{2212}";
/// Returns the string representation of a value.
///
/// When inserted into content, most values are displayed as this representation
/// in monospace with syntax-highlighting. The exceptions are `{none}`,
/// integers, floats, strings, content, and functions.
///
/// # Example
/// ```example
/// #none vs #repr(none) \
/// #"hello" vs #repr("hello") \
/// #(1, 2) vs #repr((1, 2)) \
/// #[*Hi*] vs #repr([*Hi*])
/// ```
///
/// # For debugging purposes only { #debugging-only }
///
/// This function is for debugging purposes. Its output should not be considered
/// stable and may change at any time.
///
/// To be specific, having the same `repr` does not guarantee that values are
/// equivalent, and `repr` is not a strict inverse of [`eval`]. In the following
/// example, for readability, the [`length`] is rounded to two significant
/// digits and the parameter list and body of the
/// [unnamed `function`]($function/#unnamed) are omitted.
///
/// ```example
/// #assert(2pt / 3 < 0.67pt)
/// #repr(2pt / 3)
///
/// #repr(x => x + 1)
/// ```
#[func(title = "Representation")]
pub fn repr(
/// The value whose string representation to produce.
value: Value,
) -> Str {
value.repr().into()
}
/// A trait that defines the `repr` of a Typst value.
pub trait Repr {
/// Return the debug representation of the value.
fn repr(&self) -> EcoString;
}
/// Format an integer in a base.
pub fn format_int_with_base(mut n: i64, base: i64) -> EcoString {
if n == 0 {
return "0".into();
}
// The largest output is `to_base(i64::MIN, 2)`, which is 64 bytes long,
// plus the length of the minus sign.
const SIZE: usize = 64 + MINUS_SIGN.len();
let mut digits = [b'\0'; SIZE];
let mut i = SIZE;
// It's tempting to take the absolute value, but this will fail for i64::MIN.
// Instead, we turn n negative, as -i64::MAX is perfectly representable.
let negative = n < 0;
if n > 0 {
n = -n;
}
while n != 0 {
let digit = char::from_digit(-(n % base) as u32, base as u32);
i -= 1;
digits[i] = digit.unwrap_or('?') as u8;
n /= base;
}
if negative {
let prev = i;
i -= MINUS_SIGN.len();
digits[i..prev].copy_from_slice(MINUS_SIGN.as_bytes());
}
std::str::from_utf8(&digits[i..]).unwrap_or_default().into()
}
/// Converts a float to a string representation with a specific precision and a
/// unit, all with a single allocation.
///
/// The returned string is always valid Typst code. As such, it might not be a
/// float literal. For example, it may return `"float.inf"`.
pub fn format_float(
mut value: f64,
precision: Option<u8>,
force_separator: bool,
unit: &str,
) -> EcoString {
if let Some(p) = precision {
value = round_with_precision(value, p as i16);
}
// Debug for f64 always prints a decimal separator, while Display only does
// when necessary.
let unit_multiplication = if unit.is_empty() { "" } else { " * 1" };
if value.is_nan() {
eco_format!("float.nan{unit_multiplication}{unit}")
} else if value.is_infinite() {
let sign = if value < 0.0 { "-" } else { "" };
eco_format!("{sign}float.inf{unit_multiplication}{unit}")
} else if force_separator {
eco_format!("{value:?}{unit}")
} else {
eco_format!("{value}{unit}")
}
}
/// Converts a float to a string representation with a precision of three
/// decimal places. This is intended to be used as part of a larger structure
/// containing multiple float components, such as colors.
pub fn format_float_component(value: f64) -> EcoString {
format_float(value, Some(3), false, "")
}
/// Converts a float to a string representation with a precision of two decimal
/// places, followed by a unit.
pub fn format_float_with_unit(value: f64, unit: &str) -> EcoString {
format_float(value, Some(2), false, unit)
}
/// Converts a float to a string that can be used to display the float as text.
pub fn display_float(value: f64) -> EcoString {
if value.is_nan() {
"NaN".into()
} else if value.is_infinite() {
let sign = if value < 0.0 { MINUS_SIGN } else { "" };
eco_format!("{sign}∞")
} else if value < 0.0 {
eco_format!("{}{}", MINUS_SIGN, value.abs())
} else {
eco_format!("{}", value.abs())
}
}
/// Formats pieces separated with commas and a final "and" or "or".
pub fn separated_list(pieces: &[impl AsRef<str>], last: &str) -> String {
let mut buf = String::new();
for (i, part) in pieces.iter().enumerate() {
match i {
0 => {}
1 if pieces.len() == 2 => {
buf.push(' ');
buf.push_str(last);
buf.push(' ');
}
i if i + 1 == pieces.len() => {
buf.push_str(", ");
buf.push_str(last);
buf.push(' ');
}
_ => buf.push_str(", "),
}
buf.push_str(part.as_ref());
}
buf
}
/// Formats a comma-separated list.
///
/// Tries to format horizontally, but falls back to vertical formatting if the
/// pieces are too long.
pub fn pretty_comma_list(pieces: &[impl AsRef<str>], trailing_comma: bool) -> String {
const MAX_WIDTH: usize = 50;
let mut buf = String::new();
let len = pieces.iter().map(|s| s.as_ref().len()).sum::<usize>()
+ 2 * pieces.len().saturating_sub(1);
if len <= MAX_WIDTH {
for (i, piece) in pieces.iter().enumerate() {
if i > 0 {
buf.push_str(", ");
}
buf.push_str(piece.as_ref());
}
if trailing_comma {
buf.push(',');
}
} else {
for piece in pieces {
buf.push_str(piece.as_ref().trim());
buf.push_str(",\n");
}
}
buf
}
/// Formats an array-like construct.
///
/// Tries to format horizontally, but falls back to vertical formatting if the
/// pieces are too long.
pub fn pretty_array_like(parts: &[impl AsRef<str>], trailing_comma: bool) -> String {
let list = pretty_comma_list(parts, trailing_comma);
let mut buf = String::new();
buf.push('(');
if list.contains('\n') {
buf.push('\n');
for (i, line) in list.lines().enumerate() {
if i > 0 {
buf.push('\n');
}
buf.push_str(" ");
buf.push_str(line);
}
buf.push('\n');
} else {
buf.push_str(&list);
}
buf.push(')');
buf
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_to_base() {
assert_eq!(&format_int_with_base(0, 10), "0");
assert_eq!(&format_int_with_base(0, 16), "0");
assert_eq!(&format_int_with_base(0, 36), "0");
assert_eq!(
&format_int_with_base(i64::MAX, 2),
"111111111111111111111111111111111111111111111111111111111111111"
);
assert_eq!(
&format_int_with_base(i64::MIN, 2),
"\u{2212}1000000000000000000000000000000000000000000000000000000000000000"
);
assert_eq!(&format_int_with_base(i64::MAX, 10), "9223372036854775807");
assert_eq!(&format_int_with_base(i64::MIN, 10), "\u{2212}9223372036854775808");
assert_eq!(&format_int_with_base(i64::MAX, 16), "7fffffffffffffff");
assert_eq!(&format_int_with_base(i64::MIN, 16), "\u{2212}8000000000000000");
assert_eq!(&format_int_with_base(i64::MAX, 36), "1y2p0ij32e8e7");
assert_eq!(&format_int_with_base(i64::MIN, 36), "\u{2212}1y2p0ij32e8e8");
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/label.rs | crates/typst-library/src/foundations/label.rs | use ecow::{EcoString, eco_format};
use typst_utils::{PicoStr, ResolvedPicoStr};
use crate::diag::StrResult;
use crate::foundations::{Repr, Str, bail, func, scope, ty};
/// A label for an element.
///
/// Inserting a label into content attaches it to the closest preceding element
/// that is not a space. The preceding element must be in the same scope as the
/// label, which means that `[Hello #[<label>]]`, for instance, wouldn't work.
///
/// A labelled element can be [referenced]($ref), [queried]($query) for, and
/// [styled]($styling) through its label.
///
/// Once constructed, you can get the name of a label using
/// [`str`]($str/#constructor).
///
/// # Example
/// ```example
/// #show <a>: set text(blue)
/// #show label("b"): set text(red)
///
/// = Heading <a>
/// *Strong* #label("b")
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: You can create a label by enclosing
/// its name in angle brackets. This works both in markup and code. A label's
/// name can contain letters, numbers, `_`, `-`, `:`, and `.`. A label cannot
/// be empty.
///
/// Note that there is a syntactical difference when using the dedicated syntax
/// for this function. In the code below, the `[<a>]` terminates the heading and
/// thus attaches to the heading itself, whereas the `[#label("b")]` is part of
/// the heading and thus attaches to the heading's text.
///
/// ```typ
/// // Equivalent to `#heading[Introduction] <a>`.
/// = Introduction <a>
///
/// // Equivalent to `#heading[Conclusion #label("b")]`.
/// = Conclusion #label("b")
/// ```
///
/// Currently, labels can only be attached to elements in markup mode, not in
/// code mode. This might change in the future.
#[ty(scope, cast)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Label(PicoStr);
impl Label {
/// Creates a label from an interned string.
///
/// Returns `None` if the given string is empty.
pub fn new(name: PicoStr) -> Option<Self> {
const EMPTY: PicoStr = PicoStr::constant("");
(name != EMPTY).then_some(Self(name))
}
/// Resolves the label to a string.
pub fn resolve(self) -> ResolvedPicoStr {
self.0.resolve()
}
/// Turns this label into its inner interned string.
pub fn into_inner(self) -> PicoStr {
self.0
}
}
#[scope]
impl Label {
/// Creates a label from a string.
#[func(constructor)]
pub fn construct(
/// The name of the label.
///
/// Unlike the [dedicated syntax](#syntax), this constructor accepts
/// any non-empty string, including names with special characters.
name: Str,
) -> StrResult<Label> {
if name.is_empty() {
bail!("label name must not be empty");
}
Ok(Self(PicoStr::intern(name.as_str())))
}
}
impl Repr for Label {
fn repr(&self) -> EcoString {
let resolved = self.resolve();
if typst_syntax::is_valid_label_literal_id(&resolved) {
eco_format!("<{resolved}>")
} else {
eco_format!("label({})", resolved.repr())
}
}
}
impl From<Label> for PicoStr {
fn from(value: Label) -> Self {
value.into_inner()
}
}
/// Indicates that an element cannot be labelled.
pub trait Unlabellable {}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/selector.rs | crates/typst-library/src/foundations/selector.rs | use std::any::{Any, TypeId};
use std::sync::Arc;
use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_format};
use smallvec::SmallVec;
use typst_syntax::Span;
use crate::diag::{At, HintedStrResult, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
CastInfo, Content, Context, Dict, Element, FromValue, Func, Label, Reflect, Regex,
Repr, Str, StyleChain, Symbol, Type, Value, cast, func, repr, scope, ty,
};
use crate::introspection::{Locatable, Location, QueryUniqueIntrospection, Unqueriable};
/// A helper macro to create a field selector used in [`Selector::Elem`]
#[macro_export]
#[doc(hidden)]
macro_rules! __select_where {
($ty:ty $(, $field:ident => $value:expr)* $(,)?) => {{
#[allow(unused_mut)]
let mut fields = $crate::foundations::SmallVec::new();
$(
fields.push((
<$ty>::$field.index(),
$crate::foundations::IntoValue::into_value($value),
));
)*
$crate::foundations::Selector::Elem(
<$ty as $crate::foundations::NativeElement>::ELEM,
Some(fields),
)
}};
}
#[doc(inline)]
pub use crate::__select_where as select_where;
/// A filter for selecting elements within the document.
///
/// To construct a selector you can:
/// - use an [element function]($function/#element-functions)
/// - filter for an element function with [specific fields]($function.where)
/// - use a [string]($str) or [regular expression]($regex)
/// - use a [`{<label>}`]($label)
/// - use a [`location`]
/// - call the [`selector`] constructor to convert any of the above types into a
/// selector value and use the methods below to refine it
///
/// Selectors are used to [apply styling rules]($styling/#show-rules) to
/// elements. You can also use selectors to [query] the document for certain
/// types of elements.
///
/// Furthermore, you can pass a selector to several of Typst's built-in
/// functions to configure their behaviour. One such example is the [outline]
/// where it can be used to change which elements are listed within the outline.
///
/// Multiple selectors can be combined using the methods shown below. However,
/// not all kinds of selectors are supported in all places, at the moment.
///
/// # Example
/// ```example
/// #context query(
/// heading.where(level: 1)
/// .or(heading.where(level: 2))
/// )
///
/// = This will be found
/// == So will this
/// === But this will not.
/// ```
#[ty(scope, cast)]
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Selector {
/// Matches a specific type of element.
///
/// If there is a dictionary, only elements with the fields from the
/// dictionary match.
Elem(Element, Option<SmallVec<[(u8, Value); 1]>>),
/// Matches the element at the specified location.
Location(Location),
/// Matches elements with a specific label.
Label(Label),
/// Matches text elements through a regular expression.
Regex(Regex),
/// Matches elements with a specific capability.
Can(TypeId),
/// Matches if any of the subselectors match.
Or(EcoVec<Self>),
/// Matches if all of the subselectors match.
And(EcoVec<Self>),
/// Matches all matches of `selector` before `end`.
Before { selector: Arc<Self>, end: Arc<Self>, inclusive: bool },
/// Matches all matches of `selector` after `start`.
After { selector: Arc<Self>, start: Arc<Self>, inclusive: bool },
}
impl Selector {
/// Define a simple text selector.
pub fn text(text: &str) -> StrResult<Self> {
if text.is_empty() {
bail!("text selector is empty");
}
Ok(Self::Regex(Regex::new(®ex::escape(text)).unwrap()))
}
/// Define a regex selector.
pub fn regex(regex: Regex) -> StrResult<Self> {
if regex.as_str().is_empty() {
bail!("regex selector is empty");
}
if regex.is_match("") {
bail!("regex matches empty text");
}
Ok(Self::Regex(regex))
}
/// Define a simple [`Selector::Can`] selector.
pub fn can<T: ?Sized + Any>() -> Self {
Self::Can(TypeId::of::<T>())
}
/// Whether the selector matches for the target.
pub fn matches(&self, target: &Content, styles: Option<StyleChain>) -> bool {
match self {
Self::Elem(element, dict) => {
target.elem() == *element
&& dict.iter().flat_map(|dict| dict.iter()).all(|(id, value)| {
target.get(*id, styles).as_ref().ok() == Some(value)
})
}
Self::Label(label) => target.label() == Some(*label),
Self::Can(cap) => target.func().can_type_id(*cap),
Self::Or(selectors) => {
selectors.iter().any(move |sel| sel.matches(target, styles))
}
Self::And(selectors) => {
selectors.iter().all(move |sel| sel.matches(target, styles))
}
Self::Location(location) => target.location() == Some(*location),
// Not supported here.
Self::Regex(_) | Self::Before { .. } | Self::After { .. } => false,
}
}
}
#[scope]
impl Selector {
/// Turns a value into a selector. The following values are accepted:
/// - An element function like a `heading` or `figure`.
/// - A [string]($str) or [regular expression]($regex).
/// - A `{<label>}`.
/// - A [`location`].
/// - A more complex selector like `{heading.where(level: 1)}`.
#[func(constructor)]
pub fn construct(
/// Can be an element function like a `heading` or `figure`, a `{<label>}`
/// or a more complex selector like `{heading.where(level: 1)}`.
target: Selector,
) -> Selector {
target
}
/// Selects all elements that match this or any of the other selectors.
#[func]
pub fn or(
self,
/// The other selectors to match on.
#[variadic]
others: Vec<Selector>,
) -> Selector {
Self::Or(others.into_iter().chain(Some(self)).collect())
}
/// Selects all elements that match this and all of the other selectors.
#[func]
pub fn and(
self,
/// The other selectors to match on.
#[variadic]
others: Vec<Selector>,
) -> Selector {
Self::And(others.into_iter().chain(Some(self)).collect())
}
/// Returns a modified selector that will only match elements that occur
/// before the first match of `end`.
#[func]
pub fn before(
self,
/// The original selection will end at the first match of `end`.
end: LocatableSelector,
/// Whether `end` itself should match or not. This is only relevant if
/// both selectors match the same type of element. Defaults to `{true}`.
#[named]
#[default(true)]
inclusive: bool,
) -> Selector {
Self::Before {
selector: Arc::new(self),
end: Arc::new(end.0),
inclusive,
}
}
/// Returns a modified selector that will only match elements that occur
/// after the first match of `start`.
#[func]
pub fn after(
self,
/// The original selection will start at the first match of `start`.
start: LocatableSelector,
/// Whether `start` itself should match or not. This is only relevant
/// if both selectors match the same type of element. Defaults to
/// `{true}`.
#[named]
#[default(true)]
inclusive: bool,
) -> Selector {
Self::After {
selector: Arc::new(self),
start: Arc::new(start.0),
inclusive,
}
}
}
impl From<Location> for Selector {
fn from(value: Location) -> Self {
Self::Location(value)
}
}
impl Repr for Selector {
fn repr(&self) -> EcoString {
match self {
Self::Elem(elem, dict) => {
if let Some(dict) = dict {
let dict = dict
.iter()
.map(|(id, value)| (elem.field_name(*id).unwrap(), value.clone()))
.map(|(name, value)| (EcoString::from(name).into(), value))
.collect::<Dict>();
eco_format!("{}.where{}", elem.name(), dict.repr())
} else {
elem.name().into()
}
}
Self::Label(label) => label.repr(),
Self::Regex(regex) => regex.repr(),
Self::Can(_) => eco_format!("selector(..)"),
Self::Or(selectors) | Self::And(selectors) => {
let function = if matches!(self, Self::Or(_)) { "or" } else { "and" };
let pieces: Vec<_> = selectors.iter().map(Selector::repr).collect();
eco_format!(
"selector.{}{}",
function,
repr::pretty_array_like(&pieces, false)
)
}
Self::Location(loc) => loc.repr(),
Self::Before { selector, end: split, inclusive }
| Self::After { selector, start: split, inclusive } => {
let method =
if matches!(self, Self::Before { .. }) { "before" } else { "after" };
let inclusive_arg = if !*inclusive { ", inclusive: false" } else { "" };
eco_format!(
"{}.{}({}{})",
selector.repr(),
method,
split.repr(),
inclusive_arg
)
}
}
}
}
cast! {
type Selector,
text: EcoString => Self::text(&text)?,
func: Func => func
.to_element()
.ok_or("only element functions can be used as selectors")?
.select(),
label: Label => Self::Label(label),
regex: Regex => Self::regex(regex)?,
location: Location => Self::Location(location),
}
/// A selector that can be used with `query`.
///
/// Hopefully, this is made obsolete by a more powerful query mechanism in the
/// future.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct LocatableSelector(pub Selector);
impl LocatableSelector {
/// Resolve this selector into a location that is guaranteed to be unique.
pub fn resolve_unique(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Location> {
match self.0.clone() {
Selector::Location(loc) => Ok(loc),
other => {
context.introspect().at(span)?;
engine
.introspect(QueryUniqueIntrospection(other, span))
.map(|c| c.location().unwrap())
.at(span)
}
}
}
}
impl Reflect for LocatableSelector {
fn input() -> CastInfo {
CastInfo::Union(vec![
CastInfo::Type(Type::of::<Label>()),
CastInfo::Type(Type::of::<Func>()),
CastInfo::Type(Type::of::<Location>()),
CastInfo::Type(Type::of::<Selector>()),
])
}
fn output() -> CastInfo {
CastInfo::Type(Type::of::<Selector>())
}
fn castable(value: &Value) -> bool {
Label::castable(value)
|| Func::castable(value)
|| Location::castable(value)
|| Selector::castable(value)
}
}
cast! {
LocatableSelector,
self => self.0.into_value(),
}
impl FromValue for LocatableSelector {
fn from_value(value: Value) -> HintedStrResult<Self> {
fn validate(selector: &Selector) -> StrResult<()> {
match selector {
Selector::Elem(elem, _) => {
if !elem.can::<dyn Locatable>() || elem.can::<dyn Unqueriable>() {
Err(eco_format!("{} is not locatable", elem.name()))?
}
}
Selector::Location(_) => {}
Selector::Label(_) => {}
Selector::Regex(_) => bail!("text is not locatable"),
Selector::Can(_) => bail!("capability is not locatable"),
Selector::Or(list) | Selector::And(list) => {
for selector in list {
validate(selector)?;
}
}
Selector::Before { selector, end: split, .. }
| Selector::After { selector, start: split, .. } => {
for selector in [selector, split] {
validate(selector)?;
}
}
}
Ok(())
}
if !Self::castable(&value) {
return Err(Self::error(&value));
}
let selector = Selector::from_value(value)?;
validate(&selector)?;
Ok(Self(selector))
}
}
impl From<Location> for LocatableSelector {
fn from(loc: Location) -> Self {
Self(Selector::Location(loc))
}
}
/// A selector that can be used with show rules.
///
/// Hopefully, this is made obsolete by a more powerful showing mechanism in the
/// future.
#[derive(Clone, PartialEq, Hash)]
pub struct ShowableSelector(pub Selector);
impl Reflect for ShowableSelector {
fn input() -> CastInfo {
CastInfo::Union(vec![
CastInfo::Type(Type::of::<Symbol>()),
CastInfo::Type(Type::of::<Str>()),
CastInfo::Type(Type::of::<Label>()),
CastInfo::Type(Type::of::<Func>()),
CastInfo::Type(Type::of::<Regex>()),
CastInfo::Type(Type::of::<Selector>()),
])
}
fn output() -> CastInfo {
CastInfo::Type(Type::of::<Selector>())
}
fn castable(value: &Value) -> bool {
Symbol::castable(value)
|| Str::castable(value)
|| Label::castable(value)
|| Func::castable(value)
|| Regex::castable(value)
|| Selector::castable(value)
}
}
cast! {
ShowableSelector,
self => self.0.into_value(),
}
impl FromValue for ShowableSelector {
fn from_value(value: Value) -> HintedStrResult<Self> {
fn validate(selector: &Selector, nested: bool) -> HintedStrResult<()> {
match selector {
Selector::Elem(_, _) => {}
Selector::Label(_) => {}
Selector::Regex(_) if !nested => {}
Selector::Or(list) | Selector::And(list) => {
for selector in list {
validate(selector, true)?;
}
}
Selector::Regex(_)
| Selector::Location(_)
| Selector::Can(_)
| Selector::Before { .. }
| Selector::After { .. } => {
bail!("this selector cannot be used with show")
}
}
Ok(())
}
if !Self::castable(&value) {
return Err(Self::error(&value));
}
let selector = Selector::from_value(value)?;
validate(&selector, false)?;
Ok(Self(selector))
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/context.rs | crates/typst-library/src/foundations/context.rs | use comemo::Track;
use crate::diag::{Hint, HintedStrResult, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Construct, Content, Func, ShowFn, StyleChain, Value, elem,
};
use crate::introspection::{Locatable, Location};
/// Data that is contextually made available to code.
///
/// _Contextual_ functions and expressions require the presence of certain
/// pieces of context to be evaluated. This includes things like `text.lang`,
/// `measure`, or `counter(heading).get()`.
#[derive(Debug, Default, Clone, Hash)]
pub struct Context<'a> {
/// The location in the document.
pub location: Option<Location>,
/// The active styles.
pub styles: Option<StyleChain<'a>>,
}
impl<'a> Context<'a> {
/// An empty context.
pub fn none() -> Self {
Self::default()
}
/// Create a new context from its parts.
pub fn new(location: Option<Location>, styles: Option<StyleChain<'a>>) -> Self {
Self { location, styles }
}
}
#[comemo::track]
impl<'a> Context<'a> {
/// Try to extract the location.
pub fn location(&self) -> HintedStrResult<Location> {
require(self.location)
}
/// Try to extract the styles.
pub fn styles(&self) -> HintedStrResult<StyleChain<'a>> {
require(self.styles)
}
/// Guard access to the introspector by requiring at least some piece of context.
pub fn introspect(&self) -> HintedStrResult<()> {
require(self.location.map(|_| ()).or(self.styles.map(|_| ())))
}
}
/// Extracts an optional piece of context, yielding an error with hints if
/// it isn't available.
fn require<T>(val: Option<T>) -> HintedStrResult<T> {
val.ok_or("can only be used when context is known")
.hint("try wrapping this in a `context` expression")
.hint(
"the `context` expression should wrap everything that depends on this function",
)
}
/// Executes a `context` block.
#[elem(Construct, Locatable)]
pub struct ContextElem {
/// The function to call with the context.
#[required]
#[internal]
func: Func,
}
impl Construct for ContextElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
pub const CONTEXT_RULE: ShowFn<ContextElem> = |elem, engine, styles| {
let loc = elem.location().unwrap();
let context = Context::new(Some(loc), Some(styles));
Ok(elem.func.call::<[Value; 0]>(engine, context.track(), [])?.display())
};
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/ops.rs | crates/typst-library/src/foundations/ops.rs | //! Operations on values.
use std::cmp::Ordering;
use ecow::eco_format;
use typst_utils::Numeric;
use crate::diag::{HintedStrResult, StrResult, bail};
use crate::foundations::{
Datetime, IntoValue, Regex, Repr, SymbolElem, Value, format_str,
};
use crate::layout::{Alignment, Length, Rel};
use crate::text::TextElem;
use crate::visualize::Stroke;
/// Bail with a type mismatch error.
macro_rules! mismatch {
($fmt:expr, $($value:expr),* $(,)?) => {
return Err(eco_format!($fmt, $($value.ty()),*).into())
};
}
/// Join a value with another value.
pub fn join(lhs: Value, rhs: Value) -> StrResult<Value> {
use Value::*;
Ok(match (lhs, rhs) {
(a, None) => a,
(None, b) => b,
(Symbol(a), Symbol(b)) => Str(format_str!("{a}{b}")),
(Str(a), Str(b)) => Str(a + b),
(Str(a), Symbol(b)) => Str(format_str!("{a}{b}")),
(Symbol(a), Str(b)) => Str(format_str!("{a}{b}")),
(Bytes(a), Bytes(b)) => Bytes(a + b),
(Content(a), Content(b)) => Content(a + b),
(Content(a), Symbol(b)) => Content(a + SymbolElem::packed(b.get())),
(Content(a), Str(b)) => Content(a + TextElem::packed(b)),
(Str(a), Content(b)) => Content(TextElem::packed(a) + b),
(Symbol(a), Content(b)) => Content(SymbolElem::packed(a.get()) + b),
(Array(a), Array(b)) => Array(a + b),
(Dict(a), Dict(b)) => Dict(a + b),
(Args(a), Args(b)) => Args(a + b),
(a, b) => mismatch!("cannot join {} with {}", a, b),
})
}
/// Apply the unary plus operator to a value.
pub fn pos(value: Value) -> HintedStrResult<Value> {
use Value::*;
Ok(match value {
Int(v) => Int(v),
Float(v) => Float(v),
Decimal(v) => Decimal(v),
Length(v) => Length(v),
Angle(v) => Angle(v),
Ratio(v) => Ratio(v),
Relative(v) => Relative(v),
Fraction(v) => Fraction(v),
Symbol(_) | Str(_) | Bytes(_) | Content(_) | Array(_) | Dict(_) | Datetime(_) => {
mismatch!("cannot apply unary '+' to {}", value)
}
Dyn(d) => {
if d.is::<Alignment>() {
mismatch!("cannot apply unary '+' to {}", d)
} else {
mismatch!("cannot apply '+' to {}", d)
}
}
v => mismatch!("cannot apply '+' to {}", v),
})
}
/// Compute the negation of a value.
pub fn neg(value: Value) -> HintedStrResult<Value> {
use Value::*;
Ok(match value {
Int(v) => Int(v.checked_neg().ok_or_else(too_large)?),
Float(v) => Float(-v),
Decimal(v) => Decimal(-v),
Length(v) => Length(-v),
Angle(v) => Angle(-v),
Ratio(v) => Ratio(-v),
Relative(v) => Relative(-v),
Fraction(v) => Fraction(-v),
Duration(v) => Duration(-v),
Datetime(_) => mismatch!("cannot apply unary '-' to {}", value),
v => mismatch!("cannot apply '-' to {}", v),
})
}
/// Compute the sum of two values.
pub fn add(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
use Value::*;
Ok(match (lhs, rhs) {
(a, None) => a,
(None, b) => b,
(Int(a), Int(b)) => Int(a.checked_add(b).ok_or_else(too_large)?),
(Int(a), Float(b)) => Float(a as f64 + b),
(Float(a), Int(b)) => Float(a + b as f64),
(Float(a), Float(b)) => Float(a + b),
(Decimal(a), Decimal(b)) => Decimal(a.checked_add(b).ok_or_else(too_large)?),
(Decimal(a), Int(b)) => Decimal(
a.checked_add(crate::foundations::Decimal::from(b))
.ok_or_else(too_large)?,
),
(Int(a), Decimal(b)) => Decimal(
crate::foundations::Decimal::from(a)
.checked_add(b)
.ok_or_else(too_large)?,
),
(Angle(a), Angle(b)) => Angle(a + b),
(Length(a), Length(b)) => Length(a + b),
(Length(a), Ratio(b)) => Relative(b + a),
(Length(a), Relative(b)) => Relative(b + a),
(Ratio(a), Length(b)) => Relative(a + b),
(Ratio(a), Ratio(b)) => Ratio(a + b),
(Ratio(a), Relative(b)) => Relative(b + a),
(Relative(a), Length(b)) => Relative(a + b),
(Relative(a), Ratio(b)) => Relative(a + b),
(Relative(a), Relative(b)) => Relative(a + b),
(Fraction(a), Fraction(b)) => Fraction(a + b),
(Symbol(a), Symbol(b)) => Str(format_str!("{a}{b}")),
(Str(a), Str(b)) => Str(a + b),
(Str(a), Symbol(b)) => Str(format_str!("{a}{b}")),
(Symbol(a), Str(b)) => Str(format_str!("{a}{b}")),
(Bytes(a), Bytes(b)) => Bytes(a + b),
(Content(a), Content(b)) => Content(a + b),
(Content(a), Symbol(b)) => Content(a + SymbolElem::packed(b.get())),
(Content(a), Str(b)) => Content(a + TextElem::packed(b)),
(Str(a), Content(b)) => Content(TextElem::packed(a) + b),
(Symbol(a), Content(b)) => Content(SymbolElem::packed(a.get()) + b),
(Array(a), Array(b)) => Array(a + b),
(Dict(a), Dict(b)) => Dict(a + b),
(Args(a), Args(b)) => Args(a + b),
(Color(color), Length(thickness)) | (Length(thickness), Color(color)) => {
Stroke::from_pair(color, thickness).into_value()
}
(Gradient(gradient), Length(thickness))
| (Length(thickness), Gradient(gradient)) => {
Stroke::from_pair(gradient, thickness).into_value()
}
(Tiling(tiling), Length(thickness)) | (Length(thickness), Tiling(tiling)) => {
Stroke::from_pair(tiling, thickness).into_value()
}
(Duration(a), Duration(b)) => Duration(a + b),
(Datetime(a), Duration(b)) => Datetime(a + b),
(Duration(a), Datetime(b)) => Datetime(b + a),
(Dyn(a), Dyn(b)) => {
// Alignments can be summed.
if let (Some(&a), Some(&b)) =
(a.downcast::<Alignment>(), b.downcast::<Alignment>())
{
return Ok((a + b)?.into_value());
}
mismatch!("cannot add {} and {}", a, b);
}
(a, b) => mismatch!("cannot add {} and {}", a, b),
})
}
/// Compute the difference of two values.
pub fn sub(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
use Value::*;
Ok(match (lhs, rhs) {
(Int(a), Int(b)) => Int(a.checked_sub(b).ok_or_else(too_large)?),
(Int(a), Float(b)) => Float(a as f64 - b),
(Float(a), Int(b)) => Float(a - b as f64),
(Float(a), Float(b)) => Float(a - b),
(Decimal(a), Decimal(b)) => Decimal(a.checked_sub(b).ok_or_else(too_large)?),
(Decimal(a), Int(b)) => Decimal(
a.checked_sub(crate::foundations::Decimal::from(b))
.ok_or_else(too_large)?,
),
(Int(a), Decimal(b)) => Decimal(
crate::foundations::Decimal::from(a)
.checked_sub(b)
.ok_or_else(too_large)?,
),
(Angle(a), Angle(b)) => Angle(a - b),
(Length(a), Length(b)) => Length(a - b),
(Length(a), Ratio(b)) => Relative(-b + a),
(Length(a), Relative(b)) => Relative(-b + a),
(Ratio(a), Length(b)) => Relative(a + -b),
(Ratio(a), Ratio(b)) => Ratio(a - b),
(Ratio(a), Relative(b)) => Relative(-b + a),
(Relative(a), Length(b)) => Relative(a + -b),
(Relative(a), Ratio(b)) => Relative(a + -b),
(Relative(a), Relative(b)) => Relative(a - b),
(Fraction(a), Fraction(b)) => Fraction(a - b),
(Duration(a), Duration(b)) => Duration(a - b),
(Datetime(a), Duration(b)) => Datetime(a - b),
(Datetime(a), Datetime(b)) => Duration((a - b)?),
(a, b) => mismatch!("cannot subtract {1} from {0}", a, b),
})
}
/// Compute the product of two values.
pub fn mul(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
use Value::*;
Ok(match (lhs, rhs) {
(Int(a), Int(b)) => Int(a.checked_mul(b).ok_or_else(too_large)?),
(Int(a), Float(b)) => Float(a as f64 * b),
(Float(a), Int(b)) => Float(a * b as f64),
(Float(a), Float(b)) => Float(a * b),
(Decimal(a), Decimal(b)) => Decimal(a.checked_mul(b).ok_or_else(too_large)?),
(Decimal(a), Int(b)) => Decimal(
a.checked_mul(crate::foundations::Decimal::from(b))
.ok_or_else(too_large)?,
),
(Int(a), Decimal(b)) => Decimal(
crate::foundations::Decimal::from(a)
.checked_mul(b)
.ok_or_else(too_large)?,
),
(Length(a), Int(b)) => Length(a * b as f64),
(Length(a), Float(b)) => Length(a * b),
(Length(a), Ratio(b)) => Length(a * b.get()),
(Int(a), Length(b)) => Length(b * a as f64),
(Float(a), Length(b)) => Length(b * a),
(Ratio(a), Length(b)) => Length(b * a.get()),
(Angle(a), Int(b)) => Angle(a * b as f64),
(Angle(a), Float(b)) => Angle(a * b),
(Angle(a), Ratio(b)) => Angle(a * b.get()),
(Int(a), Angle(b)) => Angle(a as f64 * b),
(Float(a), Angle(b)) => Angle(a * b),
(Ratio(a), Angle(b)) => Angle(a.get() * b),
(Ratio(a), Ratio(b)) => Ratio(a * b),
(Ratio(a), Int(b)) => Ratio(a * b as f64),
(Ratio(a), Float(b)) => Ratio(a * b),
(Int(a), Ratio(b)) => Ratio(a as f64 * b),
(Float(a), Ratio(b)) => Ratio(a * b),
(Relative(a), Int(b)) => Relative(a * b as f64),
(Relative(a), Float(b)) => Relative(a * b),
(Relative(a), Ratio(b)) => Relative(a * b.get()),
(Int(a), Relative(b)) => Relative(a as f64 * b),
(Float(a), Relative(b)) => Relative(a * b),
(Ratio(a), Relative(b)) => Relative(a.get() * b),
(Fraction(a), Int(b)) => Fraction(a * b as f64),
(Fraction(a), Float(b)) => Fraction(a * b),
(Fraction(a), Ratio(b)) => Fraction(a * b.get()),
(Int(a), Fraction(b)) => Fraction(a as f64 * b),
(Float(a), Fraction(b)) => Fraction(a * b),
(Ratio(a), Fraction(b)) => Fraction(a.get() * b),
(Str(a), Int(b)) => Str(a.repeat(Value::Int(b).cast()?)?),
(Int(a), Str(b)) => Str(b.repeat(Value::Int(a).cast()?)?),
(Array(a), Int(b)) => Array(a.repeat(Value::Int(b).cast()?)?),
(Int(a), Array(b)) => Array(b.repeat(Value::Int(a).cast()?)?),
(Content(a), b @ Int(_)) => Content(a.repeat(b.cast()?)),
(a @ Int(_), Content(b)) => Content(b.repeat(a.cast()?)),
(Int(a), Duration(b)) => Duration(b * (a as f64)),
(Float(a), Duration(b)) => Duration(b * a),
(Duration(a), Int(b)) => Duration(a * (b as f64)),
(Duration(a), Float(b)) => Duration(a * b),
(a, b) => mismatch!("cannot multiply {} with {}", a, b),
})
}
/// Compute the quotient of two values.
pub fn div(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
use Value::*;
if is_zero(&rhs) {
bail!("cannot divide by zero");
}
Ok(match (lhs, rhs) {
(Int(a), Int(b)) => Float(a as f64 / b as f64),
(Int(a), Float(b)) => Float(a as f64 / b),
(Float(a), Int(b)) => Float(a / b as f64),
(Float(a), Float(b)) => Float(a / b),
(Decimal(a), Decimal(b)) => Decimal(a.checked_div(b).ok_or_else(too_large)?),
(Decimal(a), Int(b)) => Decimal(
a.checked_div(crate::foundations::Decimal::from(b))
.ok_or_else(too_large)?,
),
(Int(a), Decimal(b)) => Decimal(
crate::foundations::Decimal::from(a)
.checked_div(b)
.ok_or_else(too_large)?,
),
(Length(a), Int(b)) => Length(a / b as f64),
(Length(a), Float(b)) => Length(a / b),
(Length(a), Length(b)) => Float(try_div_length(a, b)?),
(Length(a), Relative(b)) if b.rel.is_zero() => Float(try_div_length(a, b.abs)?),
(Angle(a), Int(b)) => Angle(a / b as f64),
(Angle(a), Float(b)) => Angle(a / b),
(Angle(a), Angle(b)) => Float(a / b),
(Ratio(a), Int(b)) => Ratio(a / b as f64),
(Ratio(a), Float(b)) => Ratio(a / b),
(Ratio(a), Ratio(b)) => Float(a / b),
(Ratio(a), Relative(b)) if b.abs.is_zero() => Float(a / b.rel),
(Relative(a), Int(b)) => Relative(a / b as f64),
(Relative(a), Float(b)) => Relative(a / b),
(Relative(a), Length(b)) if a.rel.is_zero() => Float(try_div_length(a.abs, b)?),
(Relative(a), Ratio(b)) if a.abs.is_zero() => Float(a.rel / b),
(Relative(a), Relative(b)) => Float(try_div_relative(a, b)?),
(Fraction(a), Int(b)) => Fraction(a / b as f64),
(Fraction(a), Float(b)) => Fraction(a / b),
(Fraction(a), Fraction(b)) => Float(a / b),
(Duration(a), Int(b)) => Duration(a / (b as f64)),
(Duration(a), Float(b)) => Duration(a / b),
(Duration(a), Duration(b)) => Float(a / b),
(a, b) => mismatch!("cannot divide {} by {}", a, b),
})
}
/// Whether a value is a numeric zero.
fn is_zero(v: &Value) -> bool {
use Value::*;
match *v {
Int(v) => v == 0,
Float(v) => v == 0.0,
Decimal(v) => v.is_zero(),
Length(v) => v.is_zero(),
Angle(v) => v.is_zero(),
Ratio(v) => v.is_zero(),
Relative(v) => v.is_zero(),
Fraction(v) => v.is_zero(),
Duration(v) => v.is_zero(),
_ => false,
}
}
/// Try to divide two lengths.
fn try_div_length(a: Length, b: Length) -> StrResult<f64> {
a.try_div(b).ok_or_else(|| "cannot divide these two lengths".into())
}
/// Try to divide two relative lengths.
fn try_div_relative(a: Rel<Length>, b: Rel<Length>) -> StrResult<f64> {
a.try_div(b)
.ok_or_else(|| "cannot divide these two relative lengths".into())
}
/// Compute the logical "not" of a value.
pub fn not(value: Value) -> HintedStrResult<Value> {
match value {
Value::Bool(b) => Ok(Value::Bool(!b)),
v => mismatch!("cannot apply 'not' to {}", v),
}
}
/// Compute the logical "and" of two values.
pub fn and(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
match (lhs, rhs) {
(Value::Bool(a), Value::Bool(b)) => Ok(Value::Bool(a && b)),
(a, b) => mismatch!("cannot apply 'and' to {} and {}", a, b),
}
}
/// Compute the logical "or" of two values.
pub fn or(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
match (lhs, rhs) {
(Value::Bool(a), Value::Bool(b)) => Ok(Value::Bool(a || b)),
(a, b) => mismatch!("cannot apply 'or' to {} and {}", a, b),
}
}
/// Compute whether two values are equal.
pub fn eq(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
Ok(Value::Bool(equal(&lhs, &rhs)))
}
/// Compute whether two values are unequal.
pub fn neq(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
Ok(Value::Bool(!equal(&lhs, &rhs)))
}
macro_rules! comparison {
($name:ident, $op:tt, $($pat:tt)*) => {
/// Compute how a value compares with another value.
pub fn $name(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
let ordering = compare(&lhs, &rhs)?;
Ok(Value::Bool(matches!(ordering, $($pat)*)))
}
};
}
comparison!(lt, "<", Ordering::Less);
comparison!(leq, "<=", Ordering::Less | Ordering::Equal);
comparison!(gt, ">", Ordering::Greater);
comparison!(geq, ">=", Ordering::Greater | Ordering::Equal);
/// Determine whether two values are equal.
pub fn equal(lhs: &Value, rhs: &Value) -> bool {
use Value::*;
match (lhs, rhs) {
// Compare reflexively.
(None, None) => true,
(Auto, Auto) => true,
(Bool(a), Bool(b)) => a == b,
(Int(a), Int(b)) => a == b,
(Float(a), Float(b)) => a == b,
(Decimal(a), Decimal(b)) => a == b,
(Length(a), Length(b)) => a == b,
(Angle(a), Angle(b)) => a == b,
(Ratio(a), Ratio(b)) => a == b,
(Relative(a), Relative(b)) => a == b,
(Fraction(a), Fraction(b)) => a == b,
(Color(a), Color(b)) => a == b,
(Symbol(a), Symbol(b)) => a == b,
(Version(a), Version(b)) => a == b,
(Str(a), Str(b)) => a == b,
(Bytes(a), Bytes(b)) => a == b,
(Label(a), Label(b)) => a == b,
(Content(a), Content(b)) => a == b,
(Array(a), Array(b)) => a == b,
(Dict(a), Dict(b)) => a == b,
(Func(a), Func(b)) => a == b,
(Args(a), Args(b)) => a == b,
(Type(a), Type(b)) => a == b,
(Module(a), Module(b)) => a == b,
(Datetime(a), Datetime(b)) => a == b,
(Duration(a), Duration(b)) => a == b,
(Dyn(a), Dyn(b)) => a == b,
// Some technically different things should compare equal.
(&Int(i), &Float(f)) | (&Float(f), &Int(i)) => i as f64 == f,
(&Int(i), &Decimal(d)) | (&Decimal(d), &Int(i)) => {
crate::foundations::Decimal::from(i) == d
}
(&Length(len), &Relative(rel)) | (&Relative(rel), &Length(len)) => {
len == rel.abs && rel.rel.is_zero()
}
(&Ratio(rat), &Relative(rel)) | (&Relative(rel), &Ratio(rat)) => {
rat == rel.rel && rel.abs.is_zero()
}
_ => false,
}
}
/// Compare two values.
pub fn compare(lhs: &Value, rhs: &Value) -> StrResult<Ordering> {
use Value::*;
Ok(match (lhs, rhs) {
(Bool(a), Bool(b)) => a.cmp(b),
(Int(a), Int(b)) => a.cmp(b),
(Float(a), Float(b)) => try_cmp_values(a, b)?,
(Decimal(a), Decimal(b)) => a.cmp(b),
(Length(a), Length(b)) => try_cmp_values(a, b)?,
(Angle(a), Angle(b)) => a.cmp(b),
(Ratio(a), Ratio(b)) => a.cmp(b),
(Relative(a), Relative(b)) => try_cmp_values(a, b)?,
(Fraction(a), Fraction(b)) => a.cmp(b),
(Version(a), Version(b)) => a.cmp(b),
(Str(a), Str(b)) => a.cmp(b),
// Some technically different things should be comparable.
(Int(a), Float(b)) => try_cmp_values(&(*a as f64), b)?,
(Float(a), Int(b)) => try_cmp_values(a, &(*b as f64))?,
(Int(a), Decimal(b)) => crate::foundations::Decimal::from(*a).cmp(b),
(Decimal(a), Int(b)) => a.cmp(&crate::foundations::Decimal::from(*b)),
(Length(a), Relative(b)) if b.rel.is_zero() => try_cmp_values(a, &b.abs)?,
(Ratio(a), Relative(b)) if b.abs.is_zero() => a.cmp(&b.rel),
(Relative(a), Length(b)) if a.rel.is_zero() => try_cmp_values(&a.abs, b)?,
(Relative(a), Ratio(b)) if a.abs.is_zero() => a.rel.cmp(b),
(Duration(a), Duration(b)) => a.cmp(b),
(Datetime(a), Datetime(b)) => try_cmp_datetimes(a, b)?,
(Array(a), Array(b)) => try_cmp_arrays(a.as_slice(), b.as_slice())?,
_ => mismatch!("cannot compare {} and {}", lhs, rhs),
})
}
/// Try to compare two values.
fn try_cmp_values<T: PartialOrd + Repr>(a: &T, b: &T) -> StrResult<Ordering> {
a.partial_cmp(b)
.ok_or_else(|| eco_format!("cannot compare {} with {}", a.repr(), b.repr()))
}
/// Try to compare two datetimes.
fn try_cmp_datetimes(a: &Datetime, b: &Datetime) -> StrResult<Ordering> {
a.partial_cmp(b)
.ok_or_else(|| eco_format!("cannot compare {} and {}", a.kind(), b.kind()))
}
/// Try to compare arrays of values lexicographically.
fn try_cmp_arrays(a: &[Value], b: &[Value]) -> StrResult<Ordering> {
a.iter()
.zip(b.iter())
.find_map(|(first, second)| {
match compare(first, second) {
// Keep searching for a pair of elements that isn't equal.
Ok(Ordering::Equal) => None,
// Found a pair which either is not equal or not comparable, so
// we stop searching.
result => Some(result),
}
})
.unwrap_or_else(|| {
// The two arrays are equal up to the shortest array's extent,
// so compare their lengths instead.
Ok(a.len().cmp(&b.len()))
})
}
/// Test whether one value is "in" another one.
pub fn in_(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
if let Some(b) = contains(&lhs, &rhs) {
Ok(Value::Bool(b))
} else {
mismatch!("cannot apply 'in' to {} and {}", lhs, rhs)
}
}
/// Test whether one value is "not in" another one.
pub fn not_in(lhs: Value, rhs: Value) -> HintedStrResult<Value> {
if let Some(b) = contains(&lhs, &rhs) {
Ok(Value::Bool(!b))
} else {
mismatch!("cannot apply 'not in' to {} and {}", lhs, rhs)
}
}
/// Test for containment.
pub fn contains(lhs: &Value, rhs: &Value) -> Option<bool> {
use Value::*;
match (lhs, rhs) {
(Str(a), Str(b)) => Some(b.as_str().contains(a.as_str())),
(Dyn(a), Str(b)) => a.downcast::<Regex>().map(|regex| regex.is_match(b)),
(Str(a), Dict(b)) => Some(b.contains(a)),
(Str(a), Module(b)) => Some(b.scope().get(a).is_some()),
(a, Array(b)) => Some(b.contains(a.clone())),
_ => Option::None,
}
}
#[cold]
fn too_large() -> &'static str {
"value is too large"
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/sys.rs | crates/typst-library/src/foundations/sys.rs | //! System-related things.
use crate::foundations::{Dict, Module, Scope, Version};
/// A module with system-related things.
pub fn module(inputs: Dict) -> Module {
let typst_version = typst_utils::version();
let version = Version::from_iter([
typst_version.major(),
typst_version.minor(),
typst_version.patch(),
]);
let mut scope = Scope::deduplicating();
scope.define("version", version);
scope.define("inputs", inputs);
Module::new("sys", scope)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/symbol.rs | crates/typst-library/src/foundations/symbol.rs | use std::collections::BTreeSet;
use std::fmt::{self, Debug, Display, Formatter};
use std::sync::Arc;
use codex::ModifierSet;
use ecow::{EcoString, eco_format};
use rustc_hash::FxHashMap;
use serde::{Serialize, Serializer};
use typst_syntax::{Span, Spanned, is_ident};
use typst_utils::hash128;
use unicode_segmentation::UnicodeSegmentation;
use crate::diag::{DeprecationSink, SourceResult, StrResult, bail, error};
use crate::foundations::{
Array, Content, Func, NativeElement, Packed, PlainText, Repr, cast, elem, func,
scope, ty,
};
/// A Unicode symbol.
///
/// Typst defines common symbols so that they can easily be written with
/// standard keyboards. The symbols are defined in modules, from which they can
/// be accessed using [field access notation]($scripting/#fields):
///
/// - General symbols are defined in the [`sym` module]($category/symbols/sym)
/// and are accessible without the `sym.` prefix in math mode.
/// - Emoji are defined in the [`emoji` module]($category/symbols/emoji)
///
/// Moreover, you can define custom symbols with this type's constructor
/// function.
///
/// ```example
/// #sym.arrow.r \
/// #sym.gt.eq.not \
/// $gt.eq.not$ \
/// #emoji.face.halo
/// ```
///
/// Many symbols have different variants, which can be selected by appending the
/// modifiers with dot notation. The order of the modifiers is not relevant.
/// Visit the documentation pages of the symbol modules and click on a symbol to
/// see its available variants.
///
/// ```example
/// $arrow.l$ \
/// $arrow.r$ \
/// $arrow.t.quad$
/// ```
#[ty(scope, cast)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Symbol(SymbolInner);
/// The internal representation of a [`Symbol`].
#[derive(Clone, Eq, PartialEq, Hash)]
enum SymbolInner {
/// A native symbol that has no named variant.
Single(&'static str),
/// A native symbol with multiple named variants.
Complex(&'static [Variant<&'static str>]),
/// A symbol that has modifiers applied.
Modified(Arc<Modified>),
}
/// A symbol with multiple named variants, where some modifiers may have been
/// applied. Also used for symbols defined at runtime by the user with no
/// modifier applied.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct Modified {
/// The full list of variants.
list: List,
/// The modifiers that are already applied.
modifiers: ModifierSet<EcoString>,
/// Whether we already emitted a deprecation warning for the currently
/// applied modifiers.
deprecated: bool,
}
/// A symbol variant, consisting of a set of modifiers, the variant's value, and an
/// optional deprecation message.
type Variant<S> = (ModifierSet<S>, S, Option<S>);
/// A collection of symbols.
#[derive(Clone, Eq, PartialEq, Hash)]
enum List {
Static(&'static [Variant<&'static str>]),
Runtime(Box<[Variant<EcoString>]>),
}
impl Symbol {
/// Create a new symbol from a single value.
pub const fn single(value: &'static str) -> Self {
Self(SymbolInner::Single(value))
}
/// Create a symbol with a static variant list.
#[track_caller]
pub const fn list(list: &'static [Variant<&'static str>]) -> Self {
debug_assert!(!list.is_empty());
Self(SymbolInner::Complex(list))
}
/// Create a symbol from a runtime char.
pub fn runtime_char(c: char) -> Self {
Self::runtime(Box::new([(ModifierSet::default(), c.into(), None)]))
}
/// Create a symbol with a runtime variant list.
#[track_caller]
pub fn runtime(list: Box<[Variant<EcoString>]>) -> Self {
debug_assert!(!list.is_empty());
Self(SymbolInner::Modified(Arc::new(Modified {
list: List::Runtime(list),
modifiers: ModifierSet::default(),
deprecated: false,
})))
}
/// Get the symbol's value.
pub fn get(&self) -> &str {
match &self.0 {
SymbolInner::Single(value) => value,
SymbolInner::Complex(_) => ModifierSet::<&'static str>::default()
.best_match_in(self.variants().map(|(m, v, _)| (m, v)))
.unwrap(),
SymbolInner::Modified(arc) => arc
.modifiers
.best_match_in(self.variants().map(|(m, v, _)| (m, v)))
.unwrap(),
}
}
/// Try to get the function associated with the symbol, if any.
pub fn func(&self) -> StrResult<Func> {
let value = self.get();
crate::math::accent::get_accent_func(value)
.or_else(|| crate::math::get_lr_wrapper_func(value))
.ok_or_else(|| eco_format!("symbol {self} is not callable"))
}
/// Apply a modifier to the symbol.
pub fn modified(
mut self,
sink: impl DeprecationSink,
modifier: &str,
) -> StrResult<Self> {
if let SymbolInner::Complex(list) = self.0 {
self.0 = SymbolInner::Modified(Arc::new(Modified {
list: List::Static(list),
modifiers: ModifierSet::default(),
deprecated: false,
}));
}
if let SymbolInner::Modified(arc) = &mut self.0 {
let modified = Arc::make_mut(arc);
modified.modifiers.insert_raw(modifier);
if let Some(deprecation) = modified
.modifiers
.best_match_in(modified.list.variants().map(|(m, _, d)| (m, d)))
{
// If we already emitted a deprecation warning during a previous
// modification of the symbol, do not emit another one.
if !modified.deprecated
&& let Some(message) = deprecation
{
modified.deprecated = true;
sink.emit(message, None);
}
return Ok(self);
}
}
bail!("unknown symbol modifier")
}
/// The characters that are covered by this symbol.
pub fn variants(&self) -> impl Iterator<Item = Variant<&str>> {
match &self.0 {
SymbolInner::Single(value) => Variants::Single(std::iter::once(*value)),
SymbolInner::Complex(list) => Variants::Static(list.iter()),
SymbolInner::Modified(arc) => arc.list.variants(),
}
}
/// Possible modifiers.
pub fn modifiers(&self) -> impl Iterator<Item = &str> + '_ {
let modifiers = match &self.0 {
SymbolInner::Modified(arc) => arc.modifiers.as_deref(),
_ => ModifierSet::default(),
};
self.variants()
.flat_map(|(m, _, _)| m)
.filter(|modifier| !modifier.is_empty() && !modifiers.contains(modifier))
.collect::<BTreeSet<_>>()
.into_iter()
}
}
#[scope]
impl Symbol {
/// Create a custom symbol with modifiers.
///
/// ```example
/// #let envelope = symbol(
/// "🖂",
/// ("stamped", "🖃"),
/// ("stamped.pen", "🖆"),
/// ("lightning", "🖄"),
/// ("fly", "🖅"),
/// )
///
/// #envelope
/// #envelope.stamped
/// #envelope.stamped.pen
/// #envelope.lightning
/// #envelope.fly
/// ```
#[func(constructor)]
pub fn construct(
span: Span,
/// The variants of the symbol.
///
/// Can be a just a string consisting of a single character for the
/// modifierless variant or an array with two strings specifying the modifiers
/// and the symbol. Individual modifiers should be separated by dots. When
/// displaying a symbol, Typst selects the first from the variants that have
/// all attached modifiers and the minimum number of other modifiers.
#[variadic]
variants: Vec<Spanned<SymbolVariant>>,
) -> SourceResult<Symbol> {
if variants.is_empty() {
bail!(span, "expected at least one variant");
}
// Maps from canonicalized 128-bit hashes to indices of variants we've
// seen before.
let mut seen = FxHashMap::<u128, usize>::default();
// A list of modifiers, cleared & reused in each iteration.
let mut modifiers = Vec::new();
let mut errors = ecow::eco_vec![];
// Validate the variants.
'variants: for (i, &Spanned { ref v, span }) in variants.iter().enumerate() {
modifiers.clear();
if v.1.is_empty() || v.1.graphemes(true).nth(1).is_some() {
errors.push(error!(
span, "invalid variant value: {}", v.1.repr();
hint: "variant value must be exactly one grapheme cluster";
));
}
if !v.0.is_empty() {
// Collect all modifiers.
for modifier in v.0.split('.') {
if !is_ident(modifier) {
errors.push(error!(
span,
"invalid symbol modifier: {}",
modifier.repr(),
));
continue 'variants;
}
modifiers.push(modifier);
}
}
// Canonicalize the modifier order.
modifiers.sort();
// Ensure that there are no duplicate modifiers.
if let Some(ms) = modifiers.windows(2).find(|ms| ms[0] == ms[1]) {
errors.push(error!(
span, "duplicate modifier within variant: {}", ms[0].repr();
hint: "modifiers are not ordered, so each one may appear only once";
));
continue 'variants;
}
// Check whether we had this set of modifiers before.
let hash = hash128(&modifiers);
if let Some(&i) = seen.get(&hash) {
errors.push(if v.0.is_empty() {
error!(span, "duplicate default variant")
} else if v.0 == variants[i].v.0 {
error!(span, "duplicate variant: {}", v.0.repr())
} else {
error!(
span, "duplicate variant: {}", v.0.repr();
hint: "variants with the same modifiers are identical, \
regardless of their order";
)
});
continue 'variants;
}
seen.insert(hash, i);
}
if !errors.is_empty() {
return Err(errors);
}
let list = variants
.into_iter()
.map(|s| (ModifierSet::from_raw_dotted(s.v.0), s.v.1, None))
.collect();
Ok(Symbol::runtime(list))
}
}
impl Display for Symbol {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.get())
}
}
impl Debug for SymbolInner {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Single(value) => Debug::fmt(value, f),
Self::Complex(list) => list.fmt(f),
Self::Modified(lists) => lists.fmt(f),
}
}
}
impl Debug for List {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Static(list) => list.fmt(f),
Self::Runtime(list) => list.fmt(f),
}
}
}
impl Repr for Symbol {
fn repr(&self) -> EcoString {
match &self.0 {
SymbolInner::Single(value) => eco_format!("symbol({})", value.repr()),
SymbolInner::Complex(variants) => {
eco_format!(
"symbol{}",
repr_variants(variants.iter().copied(), ModifierSet::default())
)
}
SymbolInner::Modified(arc) => {
let Modified { list, modifiers, .. } = arc.as_ref();
if modifiers.is_empty() {
eco_format!(
"symbol{}",
repr_variants(list.variants(), ModifierSet::default())
)
} else {
eco_format!(
"symbol{}",
repr_variants(list.variants(), modifiers.as_deref())
)
}
}
}
}
}
fn repr_variants<'a>(
variants: impl Iterator<Item = Variant<&'a str>>,
applied_modifiers: ModifierSet<&str>,
) -> String {
crate::foundations::repr::pretty_array_like(
&variants
.filter(|(modifiers, _, _)| {
// Only keep variants that can still be accessed, i.e., variants
// that contain all applied modifiers.
applied_modifiers.iter().all(|am| modifiers.contains(am))
})
.map(|(modifiers, value, _)| {
let trimmed_modifiers =
modifiers.into_iter().filter(|&m| !applied_modifiers.contains(m));
if trimmed_modifiers.clone().all(|m| m.is_empty()) {
value.repr()
} else {
let trimmed_modifiers =
trimmed_modifiers.collect::<Vec<_>>().join(".");
eco_format!("({}, {})", trimmed_modifiers.repr(), value.repr())
}
})
.collect::<Vec<_>>(),
false,
)
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.get())
}
}
impl List {
/// The characters that are covered by this list.
fn variants(&self) -> Variants<'_> {
match self {
List::Static(list) => Variants::Static(list.iter()),
List::Runtime(list) => Variants::Runtime(list.iter()),
}
}
}
/// A value that can be cast to a symbol.
pub struct SymbolVariant(EcoString, EcoString);
cast! {
SymbolVariant,
s: EcoString => Self(EcoString::new(), s),
array: Array => {
let mut iter = array.into_iter();
match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => Self(a.cast()?, b.cast()?),
_ => Err("variant array must contain exactly two entries")?,
}
},
}
/// Iterator over variants.
enum Variants<'a> {
Single(std::iter::Once<&'static str>),
Static(std::slice::Iter<'static, Variant<&'static str>>),
Runtime(std::slice::Iter<'a, Variant<EcoString>>),
}
impl<'a> Iterator for Variants<'a> {
type Item = Variant<&'a str>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Single(iter) => Some((ModifierSet::default(), iter.next()?, None)),
Self::Static(list) => list.next().copied(),
Self::Runtime(list) => {
list.next().map(|(m, s, d)| (m.as_deref(), s.as_str(), d.as_deref()))
}
}
}
}
/// A single character.
#[elem(Repr, PlainText)]
pub struct SymbolElem {
/// The symbol's value.
#[required]
pub text: EcoString, // This is called `text` for consistency with `TextElem`.
}
impl SymbolElem {
/// Create a new packed symbol element.
pub fn packed(text: impl Into<EcoString>) -> Content {
Self::new(text.into()).pack()
}
}
impl PlainText for Packed<SymbolElem> {
fn plain_text(&self, text: &mut EcoString) {
text.push_str(&self.text);
}
}
impl Repr for SymbolElem {
/// Use a custom repr that matches normal content.
fn repr(&self) -> EcoString {
eco_format!("[{}]", self.text)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/str.rs | crates/typst-library/src/foundations/str.rs | use std::borrow::{Borrow, Cow};
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::{Add, AddAssign, Deref, Range};
use comemo::Tracked;
use ecow::EcoString;
use serde::{Deserialize, Serialize};
use typst_syntax::Spanned;
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;
use crate::diag::{At, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Array, Bytes, Cast, Context, Decimal, Dict, Func, IntoValue, Label, Repr, Type,
Value, Version, cast, dict, func, repr, scope, ty,
};
use crate::layout::Alignment;
/// Create a new [`Str`] from a format string.
#[macro_export]
#[doc(hidden)]
macro_rules! __format_str {
($($tts:tt)*) => {{
$crate::foundations::Str::from($crate::foundations::eco_format!($($tts)*))
}};
}
#[doc(hidden)]
pub use ecow::eco_format;
#[doc(inline)]
pub use crate::__format_str as format_str;
/// A sequence of Unicode codepoints.
///
/// You can iterate over the grapheme clusters of the string using a [for
/// loop]($scripting/#loops). Grapheme clusters are basically characters but
/// keep together things that belong together, e.g. multiple codepoints that
/// together form a flag emoji. Strings can be added with the `+` operator,
/// [joined together]($scripting/#blocks) and multiplied with integers.
///
/// Typst provides utility methods for string manipulation. Many of these
/// methods (e.g., [`split`]($str.split), [`trim`]($str.trim) and
/// [`replace`]($str.replace)) operate on _patterns:_ A pattern can be either a
/// string or a [regular expression]($regex). This makes the methods quite
/// versatile.
///
/// All lengths and indices are expressed in terms of UTF-8 bytes. Indices are
/// zero-based and negative indices wrap around to the end of the string.
///
/// You can convert a value to a string with the `str` constructor.
///
/// # Example
/// ```example
/// #"hello world!" \
/// #"\"hello\n world\"!" \
/// #"1 2 3".split() \
/// #"1,2;3".split(regex("[,;]")) \
/// #(regex("\\d+") in "ten euros") \
/// #(regex("\\d+") in "10 euros")
/// ```
///
/// # Escape sequences { #escapes }
/// Just like in markup, you can escape a few symbols in strings:
/// - `[\\]` for a backslash
/// - `[\"]` for a quote
/// - `[\n]` for a newline
/// - `[\r]` for a carriage return
/// - `[\t]` for a tab
/// - `[\u{1f600}]` for a hexadecimal Unicode escape sequence
#[ty(scope, cast, title = "String")]
#[derive(Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct Str(EcoString);
impl Str {
/// Create a new, empty string.
pub fn new() -> Self {
Self(EcoString::new())
}
/// Return `true` if the length is 0.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Repeat the string a number of times.
pub fn repeat(&self, n: usize) -> StrResult<Self> {
if self.0.len().checked_mul(n).is_none() {
return Err(eco_format!("cannot repeat this string {n} times"));
}
Ok(Self(self.0.repeat(n)))
}
/// A string slice containing the entire string.
pub fn as_str(&self) -> &str {
self
}
/// Resolve an index or throw an out of bounds error.
fn locate(&self, index: i64) -> StrResult<usize> {
self.locate_opt(index)?
.ok_or_else(|| out_of_bounds(index, self.len()))
}
/// Resolve an index, if it is within bounds and on a valid char boundary.
///
/// `index == len` is considered in bounds.
fn locate_opt(&self, index: i64) -> StrResult<Option<usize>> {
let wrapped =
if index >= 0 { Some(index) } else { (self.len() as i64).checked_add(index) };
let resolved = wrapped
.and_then(|v| usize::try_from(v).ok())
.filter(|&v| v <= self.0.len());
if resolved.is_some_and(|i| !self.0.is_char_boundary(i)) {
return Err(not_a_char_boundary(index));
}
Ok(resolved)
}
}
#[scope]
impl Str {
/// Converts a value to a string.
///
/// - Integers are formatted in base 10. This can be overridden with the
/// optional `base` parameter.
/// - Floats are formatted in base 10 and never in exponential notation.
/// - Negative integers and floats are formatted with the Unicode minus sign
/// ("−" U+2212) instead of the ASCII minus sign ("-" U+002D).
/// - From labels the name is extracted.
/// - Bytes are decoded as UTF-8.
///
/// If you wish to convert from and to Unicode code points, see the
/// [`to-unicode`]($str.to-unicode) and [`from-unicode`]($str.from-unicode)
/// functions.
///
/// ```example
/// #str(10) \
/// #str(4000, base: 16) \
/// #str(2.7) \
/// #str(1e8) \
/// #str(<intro>)
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to a string.
value: ToStr,
/// The base (radix) to display integers in, between 2 and 36.
#[named]
#[default(Spanned::detached(Base::Default))]
base: Spanned<Base>,
) -> SourceResult<Str> {
Ok(match value {
ToStr::Str(s) => {
if matches!(base.v, Base::User(_)) {
bail!(base.span, "base is only supported for integers");
}
s
}
ToStr::Int(n) => {
let b = base.v.value();
if b == 1 && n > 0 {
bail!(
base.span, "base must be between 2 and 36";
hint: "generate a unary representation with `\"1\" * {n}`";
);
}
if b < 2 || b > 36 {
bail!(base.span, "base must be between 2 and 36");
}
repr::format_int_with_base(n, b).into()
}
})
}
/// The length of the string in UTF-8 encoded bytes.
#[func(title = "Length")]
pub fn len(&self) -> usize {
self.0.len()
}
/// Extracts the first grapheme cluster of the string.
///
/// Returns the provided default value if the string is empty or fails with
/// an error if no default value was specified.
#[func]
pub fn first(
&self,
/// A default value to return if the string is empty.
#[named]
default: Option<Str>,
) -> StrResult<Str> {
self.0
.graphemes(true)
.next()
.map(Into::into)
.or(default)
.ok_or_else(string_is_empty)
}
/// Extracts the last grapheme cluster of the string.
///
/// Returns the provided default value if the string is empty or fails with
/// an error if no default value was specified.
#[func]
pub fn last(
&self,
/// A default value to return if the string is empty.
#[named]
default: Option<Str>,
) -> StrResult<Str> {
self.0
.graphemes(true)
.next_back()
.map(Into::into)
.or(default)
.ok_or_else(string_is_empty)
}
/// Extracts the first grapheme cluster after the specified index. Returns
/// the default value if the index is out of bounds or fails with an error
/// if no default value was specified.
#[func]
pub fn at(
&self,
/// The byte index. If negative, indexes from the back.
index: i64,
/// A default value to return if the index is out of bounds.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
let len = self.len();
self.locate_opt(index)?
.and_then(|i| self.0[i..].graphemes(true).next().map(|s| s.into_value()))
.or(default)
.ok_or_else(|| no_default_and_out_of_bounds(index, len))
}
/// Extracts a substring of the string.
/// Fails with an error if the start or end index is out of bounds.
#[func]
pub fn slice(
&self,
/// The start byte index (inclusive). If negative, indexes from the
/// back.
start: i64,
/// The end byte index (exclusive). If omitted, the whole slice until
/// the end of the string is extracted. If negative, indexes from the
/// back.
#[default]
end: Option<i64>,
/// The number of bytes to extract. This is equivalent to passing
/// `start + count` as the `end` position. Mutually exclusive with `end`.
#[named]
count: Option<i64>,
) -> StrResult<Str> {
if end.is_some() && count.is_some() {
bail!("`end` and `count` are mutually exclusive");
}
let start = self.locate(start)?;
let end = end.or(count.map(|c| start as i64 + c));
let end = self.locate(end.unwrap_or(self.len() as i64))?.max(start);
Ok(self.0[start..end].into())
}
/// Returns the grapheme clusters of the string as an array of substrings.
#[func]
pub fn clusters(&self) -> Array {
self.as_str().graphemes(true).map(|s| Value::Str(s.into())).collect()
}
/// Returns the Unicode codepoints of the string as an array of substrings.
#[func]
pub fn codepoints(&self) -> Array {
self.chars().map(|c| Value::Str(c.into())).collect()
}
/// Converts a character into its corresponding code point.
///
/// ```example
/// #"a".to-unicode() \
/// #("a\u{0300}"
/// .codepoints()
/// .map(str.to-unicode))
/// ```
#[func]
pub fn to_unicode(
/// The character that should be converted.
character: char,
) -> u32 {
character as u32
}
/// Converts a unicode code point into its corresponding string.
///
/// ```example
/// #str.from-unicode(97)
/// ```
#[func]
pub fn from_unicode(
/// The code point that should be converted.
value: u32,
) -> StrResult<Str> {
let c: char = value
.try_into()
.map_err(|_| eco_format!("{value:#x} is not a valid codepoint"))?;
Ok(c.into())
}
/// Normalizes the string to the given Unicode normal form.
///
/// This is useful when manipulating strings containing Unicode combining
/// characters.
///
/// ```typ
/// #assert.eq("é".normalize(form: "nfd"), "e\u{0301}")
/// #assert.eq("ſ́".normalize(form: "nfkc"), "ś")
/// ```
#[func]
pub fn normalize(
&self,
#[named]
#[default(UnicodeNormalForm::Nfc)]
form: UnicodeNormalForm,
) -> Str {
match form {
UnicodeNormalForm::Nfc => self.nfc().collect(),
UnicodeNormalForm::Nfd => self.nfd().collect(),
UnicodeNormalForm::Nfkc => self.nfkc().collect(),
UnicodeNormalForm::Nfkd => self.nfkd().collect(),
}
}
/// Whether the string contains the specified pattern.
///
/// This method also has dedicated syntax: You can write `{"bc" in "abcd"}`
/// instead of `{"abcd".contains("bc")}`.
#[func]
pub fn contains(
&self,
/// The pattern to search for.
pattern: StrPattern,
) -> bool {
match pattern {
StrPattern::Str(pat) => self.0.contains(pat.as_str()),
StrPattern::Regex(re) => re.is_match(self),
}
}
/// Whether the string starts with the specified pattern.
#[func]
pub fn starts_with(
&self,
/// The pattern the string might start with.
pattern: StrPattern,
) -> bool {
match pattern {
StrPattern::Str(pat) => self.0.starts_with(pat.as_str()),
StrPattern::Regex(re) => re.find(self).is_some_and(|m| m.start() == 0),
}
}
/// Whether the string ends with the specified pattern.
#[func]
pub fn ends_with(
&self,
/// The pattern the string might end with.
pattern: StrPattern,
) -> bool {
match pattern {
StrPattern::Str(pat) => self.0.ends_with(pat.as_str()),
StrPattern::Regex(re) => {
let mut start_byte = 0;
while let Some(mat) = re.find_at(self, start_byte) {
if mat.end() == self.0.len() {
return true;
}
// There might still be a match overlapping this one, so
// restart at the next code point.
let Some(c) = self[mat.start()..].chars().next() else { break };
start_byte = mat.start() + c.len_utf8();
}
false
}
}
}
/// Searches for the specified pattern in the string and returns the first
/// match as a string or `{none}` if there is no match.
#[func]
pub fn find(
&self,
/// The pattern to search for.
pattern: StrPattern,
) -> Option<Str> {
match pattern {
StrPattern::Str(pat) => self.0.contains(pat.as_str()).then_some(pat),
StrPattern::Regex(re) => re.find(self).map(|m| m.as_str().into()),
}
}
/// Searches for the specified pattern in the string and returns the index
/// of the first match as an integer or `{none}` if there is no match.
#[func]
pub fn position(
&self,
/// The pattern to search for.
pattern: StrPattern,
) -> Option<usize> {
match pattern {
StrPattern::Str(pat) => self.0.find(pat.as_str()),
StrPattern::Regex(re) => re.find(self).map(|m| m.start()),
}
}
/// Searches for the specified pattern in the string and returns a
/// dictionary with details about the first match or `{none}` if there is no
/// match.
///
/// The returned dictionary has the following keys:
/// - `start`: The start offset of the match
/// - `end`: The end offset of the match
/// - `text`: The text that matched.
/// - `captures`: An array containing a string for each matched capturing
/// group. The first item of the array contains the first matched
/// capturing, not the whole match! This is empty unless the `pattern` was
/// a regex with capturing groups.
///
/// ```example:"Shape of the returned dictionary"
/// #let pat = regex("not (a|an) (apple|cat)")
/// #"I'm a doctor, not an apple.".match(pat) \
/// #"I am not a cat!".match(pat)
/// ```
///
/// ```example:"Different kinds of patterns"
/// #assert.eq("Is there a".match("for this?"), none)
/// #"The time of my life.".match(regex("[mit]+e"))
/// ```
#[func]
pub fn match_(
&self,
/// The pattern to search for.
pattern: StrPattern,
) -> Option<Dict> {
match pattern {
StrPattern::Str(pat) => {
self.0.match_indices(pat.as_str()).next().map(match_to_dict)
}
StrPattern::Regex(re) => re.captures(self).map(captures_to_dict),
}
}
/// Searches for the specified pattern in the string and returns an array of
/// dictionaries with details about all matches. For details about the
/// returned dictionaries, see [above]($str.match).
///
/// ```example
/// #"Day by Day.".matches("Day")
/// ```
#[func]
pub fn matches(
&self,
/// The pattern to search for.
pattern: StrPattern,
) -> Array {
match pattern {
StrPattern::Str(pat) => self
.0
.match_indices(pat.as_str())
.map(match_to_dict)
.map(Value::Dict)
.collect(),
StrPattern::Regex(re) => re
.captures_iter(self)
.map(captures_to_dict)
.map(Value::Dict)
.collect(),
}
}
/// Replace at most `count` occurrences of the given pattern with a
/// replacement string or function (beginning from the start). If no count
/// is given, all occurrences are replaced.
#[func]
pub fn replace(
&self,
engine: &mut Engine,
context: Tracked<Context>,
/// The pattern to search for.
pattern: StrPattern,
/// The string to replace the matches with or a function that gets a
/// dictionary for each match and can return individual replacement
/// strings.
///
/// The dictionary passed to the function has the same shape as the
/// dictionary returned by [`match`]($str.match).
replacement: Replacement,
/// If given, only the first `count` matches of the pattern are placed.
#[named]
count: Option<usize>,
) -> SourceResult<Str> {
// Heuristic: Assume the new string is about the same length as
// the current string.
let mut output = EcoString::with_capacity(self.as_str().len());
// Replace one match of a pattern with the replacement.
let mut last_match = 0;
let mut handle_match = |range: Range<usize>, dict: Dict| -> SourceResult<()> {
// Push everything until the match.
output.push_str(&self[last_match..range.start]);
last_match = range.end;
// Determine and push the replacement.
match &replacement {
Replacement::Str(s) => output.push_str(s),
Replacement::Func(func) => {
let piece = func
.call(engine, context, [dict])?
.cast::<Str>()
.at(func.span())?;
output.push_str(&piece);
}
}
Ok(())
};
// Iterate over the matches of the `pattern`.
let count = count.unwrap_or(usize::MAX);
match &pattern {
StrPattern::Str(pat) => {
for m in self.match_indices(pat.as_str()).take(count) {
let (start, text) = m;
handle_match(start..start + text.len(), match_to_dict(m))?;
}
}
StrPattern::Regex(re) => {
for caps in re.captures_iter(self).take(count) {
// Extract the entire match over all capture groups.
let m = caps.get(0).unwrap();
handle_match(m.start()..m.end(), captures_to_dict(caps))?;
}
}
}
// Push the remainder.
output.push_str(&self[last_match..]);
Ok(output.into())
}
/// Removes matches of a pattern from one or both sides of the string, once or
/// repeatedly and returns the resulting string.
#[func]
pub fn trim(
&self,
/// The pattern to search for. If `{none}`, trims white spaces.
#[default]
pattern: Option<StrPattern>,
/// Can be `{start}` or `{end}` to only trim the start or end of the
/// string. If omitted, both sides are trimmed.
#[named]
at: Option<StrSide>,
/// Whether to repeatedly removes matches of the pattern or just once.
/// Defaults to `{true}`.
#[named]
#[default(true)]
repeat: bool,
) -> Str {
let mut start = matches!(at, Some(StrSide::Start) | None);
let end = matches!(at, Some(StrSide::End) | None);
let trimmed = match pattern {
None => match at {
None => self.0.trim(),
Some(StrSide::Start) => self.0.trim_start(),
Some(StrSide::End) => self.0.trim_end(),
},
Some(StrPattern::Str(pat)) => {
let pat = pat.as_str();
let mut s = self.as_str();
if repeat {
if start {
s = s.trim_start_matches(pat);
}
if end {
s = s.trim_end_matches(pat);
}
} else {
if start {
s = s.strip_prefix(pat).unwrap_or(s);
}
if end {
s = s.strip_suffix(pat).unwrap_or(s);
}
}
s
}
Some(StrPattern::Regex(re)) => {
let s = self.as_str();
let mut last = None;
let mut range = 0..s.len();
for m in re.find_iter(s) {
// Does this match follow directly after the last one?
let consecutive = last == Some(m.start());
// As long as we're at the beginning or in a consecutive run
// of matches, and we're still trimming at the start, trim.
start &= m.start() == 0 || consecutive;
if start {
range.start = m.end();
start &= repeat;
}
// Reset end trim if we aren't consecutive anymore or aren't
// repeating.
if end && (!consecutive || !repeat) {
range.end = m.start();
}
last = Some(m.end());
}
// Is the last match directly at the end?
if last.is_some_and(|last| last < s.len()) {
range.end = s.len();
}
&s[range.start..range.start.max(range.end)]
}
};
trimmed.into()
}
/// Splits a string at matches of a specified pattern and returns an array
/// of the resulting parts.
///
/// When the empty string is used as a separator, it separates every
/// character (i.e., Unicode code point) in the string, along with the
/// beginning and end of the string. In practice, this means that the
/// resulting list of parts will contain the empty string at the start
/// and end of the list.
#[func]
pub fn split(
&self,
/// The pattern to split at. Defaults to whitespace.
#[default]
pattern: Option<StrPattern>,
) -> Array {
let s = self.as_str();
match pattern {
None => s.split_whitespace().map(|v| Value::Str(v.into())).collect(),
Some(StrPattern::Str(pat)) => {
s.split(pat.as_str()).map(|v| Value::Str(v.into())).collect()
}
Some(StrPattern::Regex(re)) => {
re.split(s).map(|v| Value::Str(v.into())).collect()
}
}
}
/// Reverse the string.
#[func(title = "Reverse")]
pub fn rev(&self) -> Str {
let mut s = EcoString::with_capacity(self.0.len());
for grapheme in self.as_str().graphemes(true).rev() {
s.push_str(grapheme);
}
s.into()
}
}
impl Deref for Str {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl Debug for Str {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(self.as_str(), f)
}
}
impl Display for Str {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self.as_str(), f)
}
}
impl Repr for Str {
fn repr(&self) -> EcoString {
self.as_ref().repr()
}
}
impl Repr for EcoString {
fn repr(&self) -> EcoString {
self.as_ref().repr()
}
}
impl Repr for str {
fn repr(&self) -> EcoString {
let mut r = EcoString::with_capacity(self.len() + 2);
r.push('"');
for c in self.chars() {
match c {
'\0' => r.push_str(r"\u{0}"),
'\'' => r.push('\''),
'"' => r.push_str(r#"\""#),
_ => r.extend(c.escape_debug()),
}
}
r.push('"');
r
}
}
impl Repr for char {
fn repr(&self) -> EcoString {
EcoString::from(*self).repr()
}
}
impl Add for Str {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self += rhs;
self
}
}
impl AddAssign for Str {
fn add_assign(&mut self, rhs: Self) {
self.0.push_str(rhs.as_str());
}
}
impl AsRef<str> for Str {
fn as_ref(&self) -> &str {
self
}
}
impl Borrow<str> for Str {
fn borrow(&self) -> &str {
self
}
}
impl From<char> for Str {
fn from(c: char) -> Self {
Self(c.into())
}
}
impl From<&str> for Str {
fn from(s: &str) -> Self {
Self(s.into())
}
}
impl From<EcoString> for Str {
fn from(s: EcoString) -> Self {
Self(s)
}
}
impl From<String> for Str {
fn from(s: String) -> Self {
Self(s.into())
}
}
impl From<Cow<'_, str>> for Str {
fn from(s: Cow<str>) -> Self {
Self(s.into())
}
}
impl FromIterator<char> for Str {
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl From<Str> for EcoString {
fn from(str: Str) -> Self {
str.0
}
}
impl From<Str> for String {
fn from(s: Str) -> Self {
s.0.into()
}
}
cast! {
char,
self => Value::Str(self.into()),
string: Str => {
let mut chars = string.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => c,
_ => bail!("expected exactly one character"),
}
},
}
cast! {
&str,
self => Value::Str(self.into()),
}
cast! {
EcoString,
self => Value::Str(self.into()),
v: Str => v.into(),
}
cast! {
String,
self => Value::Str(self.into()),
v: Str => v.into(),
}
/// A value that can be cast to a string.
pub enum ToStr {
/// A string value ready to be used as-is.
Str(Str),
/// An integer about to be formatted in a given base.
Int(i64),
}
cast! {
ToStr,
v: i64 => Self::Int(v),
v: f64 => Self::Str(repr::display_float(v).into()),
v: Decimal => Self::Str(format_str!("{}", v)),
v: Version => Self::Str(format_str!("{}", v)),
v: Bytes => Self::Str(v.to_str().map_err(|_| "bytes are not valid UTF-8")?),
v: Label => Self::Str(v.resolve().as_str().into()),
v: Type => Self::Str(v.long_name().into()),
v: Str => Self::Str(v),
}
/// Similar to `Option<i64>`, but the default value casts to `10` rather than
/// `none`, so that the right default value is documented.
#[derive(Debug, Copy, Clone)]
pub enum Base {
Default,
User(i64),
}
impl Base {
pub fn value(self) -> i64 {
match self {
Self::Default => 10,
Self::User(b) => b,
}
}
}
cast! {
Base,
self => self.value().into_value(),
v: i64 => Self::User(v),
}
/// A Unicode normalization form.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum UnicodeNormalForm {
/// Canonical composition where e.g. accented letters are turned into a
/// single Unicode codepoint.
#[string("nfc")]
Nfc,
/// Canonical decomposition where e.g. accented letters are split into a
/// separate base and diacritic.
#[string("nfd")]
Nfd,
/// Like NFC, but using the Unicode compatibility decompositions.
#[string("nfkc")]
Nfkc,
/// Like NFD, but using the Unicode compatibility decompositions.
#[string("nfkd")]
Nfkd,
}
/// Convert an item of std's `match_indices` to a dictionary.
fn match_to_dict((start, text): (usize, &str)) -> Dict {
dict! {
"start" => start,
"end" => start + text.len(),
"text" => text,
"captures" => Array::new(),
}
}
/// Convert regex captures to a dictionary.
fn captures_to_dict(cap: regex::Captures) -> Dict {
let m = cap.get(0).expect("missing first match");
dict! {
"start" => m.start(),
"end" => m.end(),
"text" => m.as_str(),
"captures" => cap.iter()
.skip(1)
.map(|opt| opt.map_or(Value::None, |m| m.as_str().into_value()))
.collect::<Array>(),
}
}
/// The out of bounds access error message.
#[cold]
fn out_of_bounds(index: i64, len: usize) -> EcoString {
eco_format!("string index out of bounds (index: {}, len: {})", index, len)
}
/// The out of bounds access error message when no default value was given.
#[cold]
fn no_default_and_out_of_bounds(index: i64, len: usize) -> EcoString {
eco_format!(
"no default value was specified and string index out of bounds (index: {}, len: {})",
index,
len
)
}
/// The char boundary access error message.
#[cold]
fn not_a_char_boundary(index: i64) -> EcoString {
eco_format!("string index {} is not a character boundary", index)
}
/// The error message when the string is empty.
#[cold]
fn string_is_empty() -> EcoString {
"string is empty".into()
}
/// A regular expression.
///
/// Can be used as a [show rule selector]($styling/#show-rules) and with
/// [string methods]($str) like `find`, `split`, and `replace`.
///
/// [See here](https://docs.rs/regex/latest/regex/#syntax) for a specification
/// of the supported syntax.
///
/// # Example
/// ```example
/// // Works with string methods.
/// #"a,b;c".split(regex("[,;]"))
///
/// // Works with show rules.
/// #show regex("\\d+"): set text(red)
///
/// The numbers 1 to 10.
/// ```
#[ty(scope)]
#[derive(Debug, Clone)]
pub struct Regex(regex::Regex);
impl Regex {
/// Create a new regular expression.
pub fn new(re: &str) -> StrResult<Self> {
regex::Regex::new(re).map(Self).map_err(|err| eco_format!("{err}"))
}
}
#[scope]
impl Regex {
/// Create a regular expression from a string.
#[func(constructor)]
pub fn construct(
/// The regular expression as a string.
///
/// Both Typst strings and regular expressions use backslashes for
/// escaping. To produce a regex escape sequence that is also valid in
/// Typst, you need to escape the backslash itself (e.g., writing
/// `{regex("\\\\")}` for the regex `\\`). Regex escape sequences that
/// are not valid Typst escape sequences (e.g., `\d` and `\b`) can be
/// entered into strings directly, but it's good practice to still
/// escape them to avoid ambiguity (i.e., `{regex("\\b\\d")}`). See the
/// [list of valid string escape sequences]($str/#escapes).
///
/// If you need many escape sequences, you can also create a raw element
/// and extract its text to use it for your regular expressions:
/// ``{regex(`\d+\.\d+\.\d+`.text)}``.
regex: Spanned<Str>,
) -> SourceResult<Regex> {
Self::new(®ex.v).at(regex.span)
}
}
impl Deref for Regex {
type Target = regex::Regex;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Repr for Regex {
fn repr(&self) -> EcoString {
eco_format!("regex({})", self.0.as_str().repr())
}
}
impl PartialEq for Regex {
fn eq(&self, other: &Self) -> bool {
self.0.as_str() == other.0.as_str()
}
}
impl Hash for Regex {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.as_str().hash(state);
}
}
/// A pattern which can be searched for in a string.
#[derive(Debug, Clone)]
pub enum StrPattern {
/// Just a string.
Str(Str),
/// A regular expression.
Regex(Regex),
}
cast! {
StrPattern,
self => match self {
Self::Str(v) => v.into_value(),
Self::Regex(v) => v.into_value(),
},
v: Str => Self::Str(v),
v: Regex => Self::Regex(v),
}
/// A side of a string.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum StrSide {
/// The logical start of the string, may be left or right depending on the
/// language.
Start,
/// The logical end of the string.
End,
}
cast! {
StrSide,
v: Alignment => match v {
Alignment::START => Self::Start,
Alignment::END => Self::End,
_ => bail!("expected either `start` or `end`"),
},
}
/// A replacement for a matched [`Str`]
pub enum Replacement {
/// A string a match is replaced with.
Str(Str),
/// Function of type Dict -> Str (see `captures_to_dict` or `match_to_dict`)
/// whose output is inserted for the match.
Func(Func),
}
cast! {
Replacement,
self => match self {
Self::Str(v) => v.into_value(),
Self::Func(v) => v.into_value(),
},
v: Str => Self::Str(v),
v: Func => Self::Func(v)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/dict.rs | crates/typst-library/src/foundations/dict.rs | use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::{Add, AddAssign};
use std::sync::Arc;
use comemo::Tracked;
use ecow::{EcoString, eco_format};
use indexmap::IndexMap;
use rustc_hash::FxBuildHasher;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use typst_syntax::is_ident;
use typst_utils::ArcExt;
use crate::diag::{At, Hint, HintedStrResult, SourceResult, StrResult};
use crate::engine::Engine;
use crate::foundations::{
Array, Context, Func, Module, Repr, Str, Value, array, cast, func, repr, scope, ty,
};
/// Create a new [`Dict`] from key-value pairs.
#[macro_export]
#[doc(hidden)]
macro_rules! __dict {
($($key:expr => $value:expr),* $(,)?) => {{
#[allow(unused_mut)]
let mut map = $crate::foundations::IndexMap::default();
$(map.insert($key.into(), $crate::foundations::IntoValue::into_value($value));)*
$crate::foundations::Dict::from(map)
}};
}
#[doc(inline)]
pub use crate::__dict as dict;
/// A map from string keys to values.
///
/// You can construct a dictionary by enclosing comma-separated `key: value`
/// pairs in parentheses. The values do not have to be of the same type. Since
/// empty parentheses already yield an empty array, you have to use the special
/// `(:)` syntax to create an empty dictionary.
///
/// A dictionary is conceptually similar to an [array], but it is indexed by
/// strings instead of integers. You can access and create dictionary entries
/// with the `.at()` method. If you know the key statically, you can
/// alternatively use [field access notation]($scripting/#fields) (`.key`) to
/// access the value. To check whether a key is present in the dictionary, use
/// the `in` keyword.
///
/// You can iterate over the pairs in a dictionary using a [for
/// loop]($scripting/#loops). This will iterate in the order the pairs were
/// inserted / declared initially.
///
/// Dictionaries can be added with the `+` operator and [joined together]($scripting/#blocks).
/// They can also be [spread]($arguments/#spreading) into a function call or
/// another dictionary[^1] with the `..spread` operator. In each case, if a
/// key appears multiple times, the last value will override the others.
///
/// # Example
/// ```example
/// #let dict = (
/// name: "Typst",
/// born: 2019,
/// )
///
/// #dict.name \
/// #(dict.launch = 20)
/// #dict.len() \
/// #dict.keys() \
/// #dict.values() \
/// #dict.at("born") \
/// #dict.insert("city", "Berlin")
/// #("name" in dict)
/// ```
///
/// [^1]: When spreading into a dictionary, if all items between the parentheses
/// are spread, you have to use the special `(:..spread)` syntax. Otherwise, it
/// will spread into an array.
#[ty(scope, cast, name = "dictionary")]
#[derive(Default, Clone, PartialEq)]
pub struct Dict(Arc<IndexMap<Str, Value, FxBuildHasher>>);
impl Dict {
/// Create a new, empty dictionary.
pub fn new() -> Self {
Self::default()
}
/// Whether the dictionary is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Borrow the value at the given key.
pub fn get(&self, key: &str) -> StrResult<&Value> {
self.0.get(key).ok_or_else(|| missing_key(key))
}
/// Mutably borrow the value the given `key` maps to.
pub fn at_mut(&mut self, key: &str) -> HintedStrResult<&mut Value> {
Arc::make_mut(&mut self.0)
.get_mut(key)
.ok_or_else(|| missing_key(key))
.hint("use `insert` to add or update values")
}
/// Remove the value if the dictionary contains the given key.
pub fn take(&mut self, key: &str) -> StrResult<Value> {
Arc::make_mut(&mut self.0)
.shift_remove(key)
.ok_or_else(|| missing_key(key))
}
/// Whether the dictionary contains a specific key.
pub fn contains(&self, key: &str) -> bool {
self.0.contains_key(key)
}
/// Clear the dictionary.
pub fn clear(&mut self) {
if Arc::strong_count(&self.0) == 1 {
Arc::make_mut(&mut self.0).clear();
} else {
*self = Self::new();
}
}
/// Iterate over pairs of references to the contained keys and values.
pub fn iter(&self) -> indexmap::map::Iter<'_, Str, Value> {
self.0.iter()
}
/// Check if there is any remaining pair, and if so return an
/// "unexpected key" error.
pub fn finish(&self, expected: &[&str]) -> StrResult<()> {
let mut iter = self.iter().peekable();
if iter.peek().is_none() {
return Ok(());
}
let unexpected: Vec<&str> = iter.map(|kv| kv.0.as_str()).collect();
Err(Self::unexpected_keys(unexpected, Some(expected)))
}
// Return an "unexpected key" error string.
pub fn unexpected_keys(
unexpected: Vec<&str>,
hint_expected: Option<&[&str]>,
) -> EcoString {
let format_as_list = |arr: &[&str]| {
repr::separated_list(
&arr.iter().map(|s| eco_format!("\"{s}\"")).collect::<Vec<_>>(),
"and",
)
};
let mut msg = String::from(match unexpected.len() {
1 => "unexpected key ",
_ => "unexpected keys ",
});
msg.push_str(&format_as_list(&unexpected[..]));
if let Some(expected) = hint_expected {
msg.push_str(", valid keys are ");
msg.push_str(&format_as_list(expected));
}
msg.into()
}
}
#[scope]
impl Dict {
/// Converts a value into a dictionary.
///
/// Note that this function is only intended for conversion of a
/// dictionary-like value to a dictionary, not for creation of a dictionary
/// from individual pairs. Use the dictionary syntax `(key: value)` instead.
///
/// ```example
/// #dictionary(sys).at("version")
/// ```
#[func(constructor)]
pub fn construct(
/// The value that should be converted to a dictionary.
value: ToDict,
) -> Dict {
value.0
}
/// The number of pairs in the dictionary.
#[func(title = "Length")]
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns the value associated with the specified key in the dictionary.
/// May be used on the left-hand side of an assignment if the key is already
/// present in the dictionary. Returns the default value if the key is not
/// part of the dictionary or fails with an error if no default value was
/// specified.
#[func]
pub fn at(
&self,
/// The key at which to retrieve the item.
key: Str,
/// A default value to return if the key is not part of the dictionary.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.0
.get(&key)
.cloned()
.or(default)
.ok_or_else(|| missing_key_no_default(&key))
}
/// Inserts a new pair into the dictionary. If the dictionary already
/// contains this key, the value is updated.
///
/// To insert multiple pairs at once, you can just alternatively another
/// dictionary with the `+=` operator.
#[func]
pub fn insert(
&mut self,
/// The key of the pair that should be inserted.
key: Str,
/// The value of the pair that should be inserted.
value: Value,
) {
Arc::make_mut(&mut self.0).insert(key, value);
}
/// Removes a pair from the dictionary by key and return the value.
#[func]
pub fn remove(
&mut self,
/// The key of the pair to remove.
key: Str,
/// A default value to return if the key does not exist.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
Arc::make_mut(&mut self.0)
.shift_remove(&key)
.or(default)
.ok_or_else(|| missing_key(&key))
}
/// Returns the keys of the dictionary as an array in insertion order.
#[func]
pub fn keys(&self) -> Array {
self.0.keys().cloned().map(Value::Str).collect()
}
/// Returns the values of the dictionary as an array in insertion order.
#[func]
pub fn values(&self) -> Array {
self.0.values().cloned().collect()
}
/// Returns the keys and values of the dictionary as an array of pairs. Each
/// pair is represented as an array of length two.
#[func]
pub fn pairs(&self) -> Array {
self.0
.iter()
.map(|(k, v)| Value::Array(array![k.clone(), v.clone()]))
.collect()
}
/// Produces a new dictionary with only the pairs from the original one for
/// which the given function returns `{true}`.
///
/// ```example:"Basic usage"
/// #{
/// (a: 0, b: 1, c: 2)
/// .filter(v => v > 0)
/// }
/// ```
///
/// ```example:"Filtering based on the key instead of the value"
/// #{
/// (a: 0, b: 1, c: 2)
/// .pairs()
/// .filter(((k, v)) => k != "a")
/// .to-dict()
/// }
/// ```
#[func]
pub fn filter(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each value. Must return a boolean.
test: Func,
) -> SourceResult<Dict> {
let mut run_test = |v: &Value| {
test.call(engine, context, [v.clone()])?
.cast::<bool>()
.at(test.span())
};
self.into_iter()
.filter_map(|(k, v)| run_test(&v).map(|b| b.then_some((k, v))).transpose())
.collect()
}
/// Produces a new dictionary where the keys are the same, but the values
/// are transformed with the given function.
///
/// ```example
/// #(a: 0, b: 1, c: 2).map(v => v + 1)
/// ```
#[func]
pub fn map(
self,
engine: &mut Engine,
context: Tracked<Context>,
/// The function to apply to each value.
mapper: Func,
) -> SourceResult<Dict> {
self.into_iter()
.map(|(k, v)| {
let mapped_value = mapper.call(engine, context, [v])?;
Ok((k, mapped_value))
})
.collect()
}
}
/// A value that can be cast to dictionary.
pub struct ToDict(Dict);
cast! {
ToDict,
v: Module => Self(v
.scope()
.iter()
.map(|(k, b)| (Str::from(k.clone()), b.read().clone()))
.collect()
),
}
impl Debug for Dict {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_map().entries(self.0.iter()).finish()
}
}
impl Repr for Dict {
fn repr(&self) -> EcoString {
if self.is_empty() {
return "(:)".into();
}
let max = 40;
let mut pieces: Vec<_> = self
.iter()
.take(max)
.map(|(key, value)| {
if is_ident(key) {
eco_format!("{key}: {}", value.repr())
} else {
eco_format!("{}: {}", key.repr(), value.repr())
}
})
.collect();
if self.len() > max {
pieces.push(eco_format!(".. ({} pairs omitted)", self.len() - max));
}
repr::pretty_array_like(&pieces, false).into()
}
}
impl Add for Dict {
type Output = Self;
fn add(mut self, rhs: Dict) -> Self::Output {
self += rhs;
self
}
}
impl AddAssign for Dict {
fn add_assign(&mut self, rhs: Dict) {
match Arc::try_unwrap(rhs.0) {
Ok(map) => self.extend(map),
Err(rc) => self.extend(rc.iter().map(|(k, v)| (k.clone(), v.clone()))),
}
}
}
impl Hash for Dict {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_usize(self.0.len());
for item in self {
item.hash(state);
}
}
}
impl Serialize for Dict {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Dict {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(IndexMap::<Str, Value, FxBuildHasher>::deserialize(deserializer)?.into())
}
}
impl Extend<(Str, Value)> for Dict {
fn extend<T: IntoIterator<Item = (Str, Value)>>(&mut self, iter: T) {
Arc::make_mut(&mut self.0).extend(iter);
}
}
impl FromIterator<(Str, Value)> for Dict {
fn from_iter<T: IntoIterator<Item = (Str, Value)>>(iter: T) -> Self {
Self(Arc::new(iter.into_iter().collect()))
}
}
impl IntoIterator for Dict {
type Item = (Str, Value);
type IntoIter = indexmap::map::IntoIter<Str, Value>;
fn into_iter(self) -> Self::IntoIter {
Arc::take(self.0).into_iter()
}
}
impl<'a> IntoIterator for &'a Dict {
type Item = (&'a Str, &'a Value);
type IntoIter = indexmap::map::Iter<'a, Str, Value>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl From<IndexMap<Str, Value, FxBuildHasher>> for Dict {
fn from(map: IndexMap<Str, Value, FxBuildHasher>) -> Self {
Self(Arc::new(map))
}
}
/// The missing key access error message.
#[cold]
fn missing_key(key: &str) -> EcoString {
eco_format!("dictionary does not contain key {}", key.repr())
}
/// The missing key access error message when no default was given.
#[cold]
fn missing_key_no_default(key: &str) -> EcoString {
eco_format!(
"dictionary does not contain key {} \
and no default value was specified",
key.repr()
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/plugin.rs | crates/typst-library/src/foundations/plugin.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
use ecow::{EcoString, eco_format};
use typst_syntax::Spanned;
use wasmi::Memory;
use crate::diag::{At, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{Binding, Bytes, Func, Module, Scope, Value, cast, func, scope};
use crate::loading::{DataSource, Load};
/// Loads a WebAssembly module.
///
/// The resulting [module] will contain one Typst [function] for each function
/// export of the loaded WebAssembly module.
///
/// Typst WebAssembly plugins need to follow a specific
/// [protocol]($plugin/#protocol). To run as a plugin, a program needs to be
/// compiled to a 32-bit shared WebAssembly library. Plugin functions may accept
/// multiple [byte buffers]($bytes) as arguments and return a single byte
/// buffer. They should typically be wrapped in idiomatic Typst functions that
/// perform the necessary conversions between native Typst types and bytes by
/// leveraging [`str`]($str/#constructor), [`bytes`]($bytes/#constructor), and
/// [data loading functions]($reference/data-loading).
///
/// For security reasons, plugins run in isolation from your system. This means
/// that printing, reading files, or similar things are not supported.
///
/// # Example
/// ```example
/// #let myplugin = plugin("hello.wasm")
/// #let concat(a, b) = str(
/// myplugin.concatenate(
/// bytes(a),
/// bytes(b),
/// )
/// )
///
/// #concat("hello", "world")
/// ```
///
/// Since the plugin function returns a module, it can be used with import
/// syntax:
/// ```typ
/// #import plugin("hello.wasm"): concatenate
/// ```
///
/// # Purity
/// Plugin functions **must be pure:** A plugin function call must not have any
/// observable side effects on future plugin calls and given the same arguments,
/// it must always return the same value.
///
/// The reason for this is that Typst functions must be pure (which is quite
/// fundamental to the language design) and, since Typst function can call
/// plugin functions, this requirement is inherited. In particular, if a plugin
/// function is called twice with the same arguments, Typst might cache the
/// results and call your function only once. Moreover, Typst may run multiple
/// instances of your plugin in multiple threads, with no state shared between
/// them.
///
/// Typst does not enforce plugin function purity (for efficiency reasons), but
/// calling an impure function will lead to unpredictable and irreproducible
/// results and must be avoided.
///
/// That said, mutable operations _can be_ useful for plugins that require
/// costly runtime initialization. Due to the purity requirement, such
/// initialization cannot be performed through a normal function call. Instead,
/// Typst exposes a [plugin transition API]($plugin.transition), which executes
/// a function call and then creates a derived module with new functions which
/// will observe the side effects produced by the transition call. The original
/// plugin remains unaffected.
///
/// # Plugins and Packages
/// Any Typst code can make use of a plugin simply by including a WebAssembly
/// file and loading it. However, because the byte-based plugin interface is
/// quite low-level, plugins are typically exposed through a package containing
/// the plugin and idiomatic wrapper functions.
///
/// # WASI
/// Many compilers will use the [WASI ABI](https://wasi.dev/) by default or as
/// their only option (e.g. emscripten), which allows printing, reading files,
/// etc. This ABI will not directly work with Typst. You will either need to
/// compile to a different target or [stub all
/// functions](https://github.com/astrale-sharp/wasm-minimal-protocol/tree/master/crates/wasi-stub).
///
/// # Protocol
/// To be used as a plugin, a WebAssembly module must conform to the following
/// protocol:
///
/// ## Exports
/// A plugin module can export functions to make them callable from Typst. To
/// conform to the protocol, an exported function should:
///
/// - Take `n` 32-bit integer arguments `a_1`, `a_2`, ..., `a_n` (interpreted as
/// lengths, so `usize/size_t` may be preferable), and return one 32-bit
/// integer.
///
/// - The function should first allocate a buffer `buf` of length `a_1 + a_2 +
/// ... + a_n`, and then call
/// `wasm_minimal_protocol_write_args_to_buffer(buf.ptr)`.
///
/// - The `a_1` first bytes of the buffer now constitute the first argument, the
/// `a_2` next bytes the second argument, and so on.
///
/// - The function can now do its job with the arguments and produce an output
/// buffer. Before returning, it should call
/// `wasm_minimal_protocol_send_result_to_host` to send its result back to the
/// host.
///
/// - To signal success, the function should return `0`.
///
/// - To signal an error, the function should return `1`. The written buffer is
/// then interpreted as an UTF-8 encoded error message.
///
/// ## Imports
/// Plugin modules need to import two functions that are provided by the
/// runtime. (Types and functions are described using WAT syntax.)
///
/// - `(import "typst_env" "wasm_minimal_protocol_write_args_to_buffer" (func
/// (param i32)))`
///
/// Writes the arguments for the current function into a plugin-allocated
/// buffer. When a plugin function is called, it [receives the
/// lengths](#exports) of its input buffers as arguments. It should then
/// allocate a buffer whose capacity is at least the sum of these lengths. It
/// should then call this function with a `ptr` to the buffer to fill it with
/// the arguments, one after another.
///
/// - `(import "typst_env" "wasm_minimal_protocol_send_result_to_host" (func
/// (param i32 i32)))`
///
/// Sends the output of the current function to the host (Typst). The first
/// parameter shall be a pointer to a buffer (`ptr`), while the second is the
/// length of that buffer (`len`). The memory pointed at by `ptr` can be freed
/// immediately after this function returns. If the message should be
/// interpreted as an error message, it should be encoded as UTF-8.
///
/// # Resources
/// For more resources, check out the [wasm-minimal-protocol
/// repository](https://github.com/astrale-sharp/wasm-minimal-protocol). It
/// contains:
///
/// - A list of example plugin implementations and a test runner for these
/// examples
/// - Wrappers to help you write your plugin in Rust (Zig wrapper in
/// development)
/// - A stubber for WASI
#[func(scope)]
pub fn plugin(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a WebAssembly file or raw WebAssembly bytes.
source: Spanned<DataSource>,
) -> SourceResult<Module> {
let loaded = source.load(engine.world)?;
Plugin::module(loaded.data).at(source.span)
}
#[scope]
impl plugin {
/// Calls a plugin function that has side effects and returns a new module
/// with plugin functions that are guaranteed to have observed the results
/// of the mutable call.
///
/// Note that calling an impure function through a normal function call
/// (without use of the transition API) is forbidden and leads to
/// unpredictable behaviour. Read the [section on purity]($plugin/#purity)
/// for more details.
///
/// In the example below, we load the plugin `hello-mut.wasm` which exports
/// two functions: The `get()` function retrieves a global array as a
/// string. The `add(value)` function adds a value to the global array.
///
/// We call `add` via the transition API. The call `mutated.get()` on the
/// derived module will observe the addition. Meanwhile the original module
/// remains untouched as demonstrated by the `base.get()` call.
///
/// _Note:_ Due to limitations in the internal WebAssembly implementation,
/// the transition API can only guarantee to reflect changes in the plugin's
/// memory, not in WebAssembly globals. If your plugin relies on changes to
/// globals being visible after transition, you might want to avoid use of
/// the transition API for now. We hope to lift this limitation in the
/// future.
///
/// ```typ
/// #let base = plugin("hello-mut.wasm")
/// #assert.eq(base.get(), "[]")
///
/// #let mutated = plugin.transition(base.add, "hello")
/// #assert.eq(base.get(), "[]")
/// #assert.eq(mutated.get(), "[hello]")
/// ```
#[func]
pub fn transition(
/// The plugin function to call.
func: PluginFunc,
/// The byte buffers to call the function with.
#[variadic]
arguments: Vec<Bytes>,
) -> StrResult<Module> {
func.transition(arguments)
}
}
/// A function loaded from a WebAssembly plugin.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct PluginFunc {
/// The underlying plugin, shared by this and the other functions.
plugin: Arc<Plugin>,
/// The name of the plugin function.
name: EcoString,
}
impl PluginFunc {
/// The name of the plugin function.
pub fn name(&self) -> &EcoString {
&self.name
}
/// Call the WebAssembly function with the given arguments.
#[comemo::memoize]
#[typst_macros::time(name = "call plugin")]
pub fn call(&self, args: Vec<Bytes>) -> StrResult<Bytes> {
self.plugin.call(&self.name, args)
}
/// Transition a plugin and turn the result into a module.
#[comemo::memoize]
#[typst_macros::time(name = "transition plugin")]
pub fn transition(&self, args: Vec<Bytes>) -> StrResult<Module> {
self.plugin.transition(&self.name, args).map(Plugin::into_module)
}
}
cast! {
PluginFunc,
self => Value::Func(self.into()),
v: Func => v.to_plugin().ok_or("expected plugin function")?.clone(),
}
/// A plugin with potentially multiple instances for multi-threaded
/// execution.
struct Plugin {
/// Shared by all variants of the plugin.
base: Arc<PluginBase>,
/// A pool of plugin instances.
///
/// When multiple plugin calls run concurrently due to multi-threading, we
/// create new instances whenever we run out of ones.
pool: Mutex<Vec<PluginInstance>>,
/// A snapshot that new instances should be restored to.
snapshot: Option<Snapshot>,
/// A combined hash that incorporates all function names and arguments used
/// in transitions of this plugin, such that this plugin has a deterministic
/// hash and equality check that can differentiate it from "siblings" (same
/// base, different transitions).
fingerprint: u128,
}
impl Plugin {
/// Create a plugin and turn it into a module.
#[comemo::memoize]
#[typst_macros::time(name = "load plugin")]
fn module(bytes: Bytes) -> StrResult<Module> {
Self::new(bytes).map(Self::into_module)
}
/// Create a new plugin from raw WebAssembly bytes.
fn new(bytes: Bytes) -> StrResult<Self> {
let mut config = wasmi::Config::default();
// Disable relaxed SIMD as it can introduce non-determinism.
config.wasm_relaxed_simd(false);
let engine = wasmi::Engine::new(&config);
let module = wasmi::Module::new(&engine, bytes.as_slice())
.map_err(|err| format!("failed to load WebAssembly module ({err})"))?;
// Ensure that the plugin exports its memory.
if !matches!(module.get_export("memory"), Some(wasmi::ExternType::Memory(_))) {
bail!("plugin does not export its memory");
}
let mut linker = wasmi::Linker::new(&engine);
linker
.func_wrap(
"typst_env",
"wasm_minimal_protocol_send_result_to_host",
wasm_minimal_protocol_send_result_to_host,
)
.unwrap();
linker
.func_wrap(
"typst_env",
"wasm_minimal_protocol_write_args_to_buffer",
wasm_minimal_protocol_write_args_to_buffer,
)
.unwrap();
let base = Arc::new(PluginBase { bytes, linker, module });
let instance = PluginInstance::new(&base, None)?;
Ok(Self {
base,
snapshot: None,
fingerprint: 0,
pool: Mutex::new(vec![instance]),
})
}
/// Execute a function with access to an instance.
fn call(&self, func: &str, args: Vec<Bytes>) -> StrResult<Bytes> {
// Acquire an instance from the pool (potentially creating a new one).
let mut instance = self.acquire()?;
// Execute the call on an instance from the pool. If the call fails, we
// return early and _don't_ return the instance to the pool as it might
// be irrecoverably damaged.
let output = instance.call(func, args)?;
// Return the instance to the pool.
self.pool.lock().unwrap().push(instance);
Ok(output)
}
/// Call a mutable plugin function, producing a new mutable whose functions
/// are guaranteed to be able to observe the mutation.
fn transition(&self, func: &str, args: Vec<Bytes>) -> StrResult<Plugin> {
// Derive a new transition hash from the old one and the function and arguments.
let fingerprint = typst_utils::hash128(&(self.fingerprint, func, &args));
// Execute the mutable call on an instance.
let mut instance = self.acquire()?;
// Call the function. If the call fails, we return early and _don't_
// return the instance to the pool as it might be irrecoverably damaged.
instance.call(func, args)?;
// Snapshot the instance after the mutable call.
let snapshot = instance.snapshot();
// Create a new plugin and move (this is important!) the used instance
// into it, so that the old plugin won't observe the mutation. Also
// save the snapshot so that instances that are initialized for the
// transitioned plugin's pool observe the mutation.
Ok(Self {
base: self.base.clone(),
snapshot: Some(snapshot),
fingerprint,
pool: Mutex::new(vec![instance]),
})
}
/// Acquire an instance from the pool (or create a new one).
fn acquire(&self) -> StrResult<PluginInstance> {
// Don't use match to ensure that the lock is released before we create
// a new instance.
if let Some(instance) = self.pool.lock().unwrap().pop() {
return Ok(instance);
}
PluginInstance::new(&self.base, self.snapshot.as_ref())
}
/// Turn a plugin into a Typst module containing plugin functions.
fn into_module(self) -> Module {
let shared = Arc::new(self);
// Build a scope from the collected functions.
let mut scope = Scope::new();
for export in shared.base.module.exports() {
if matches!(export.ty(), wasmi::ExternType::Func(_)) {
let name = EcoString::from(export.name());
let func = PluginFunc { plugin: shared.clone(), name: name.clone() };
scope.bind(name, Binding::detached(Func::from(func)));
}
}
Module::anonymous(scope)
}
}
impl Debug for Plugin {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("Plugin(..)")
}
}
impl PartialEq for Plugin {
fn eq(&self, other: &Self) -> bool {
self.base.bytes == other.base.bytes && self.fingerprint == other.fingerprint
}
}
impl Hash for Plugin {
fn hash<H: Hasher>(&self, state: &mut H) {
self.base.bytes.hash(state);
self.fingerprint.hash(state);
}
}
/// Shared by all pooled & transitioned variants of the plugin.
struct PluginBase {
/// The raw WebAssembly bytes.
bytes: Bytes,
/// The compiled WebAssembly module.
module: wasmi::Module,
/// A linker used to create a `Store` for execution.
linker: wasmi::Linker<CallData>,
}
/// An single plugin instance for single-threaded execution.
struct PluginInstance {
/// The underlying wasmi instance.
instance: wasmi::Instance,
/// The execution store of this concrete plugin instance.
store: wasmi::Store<CallData>,
}
/// A snapshot of a plugin instance.
struct Snapshot {
/// The number of pages in the main memory.
mem_pages: u64,
/// The data in the main memory.
mem_data: Vec<u8>,
}
impl PluginInstance {
/// Create a new execution instance of a plugin, potentially restoring
/// a snapshot.
#[typst_macros::time(name = "create plugin instance")]
fn new(base: &PluginBase, snapshot: Option<&Snapshot>) -> StrResult<PluginInstance> {
let mut store = wasmi::Store::new(base.linker.engine(), CallData::default());
let instance = base
.linker
.instantiate_and_start(&mut store, &base.module)
.map_err(|e| eco_format!("{e}"))?;
let mut instance = PluginInstance { instance, store };
if let Some(snapshot) = snapshot {
instance.restore(snapshot);
}
Ok(instance)
}
/// Call a plugin function with byte arguments.
fn call(&mut self, func: &str, args: Vec<Bytes>) -> StrResult<Bytes> {
let handle = self
.instance
.get_export(&self.store, func)
.unwrap()
.into_func()
.unwrap();
let ty = handle.ty(&self.store);
// Check function signature. Do this lazily only when a function is called
// because there might be exported functions like `_initialize` that don't
// match the schema.
if ty.params().iter().any(|&v| v != wasmi::core::ValType::I32) {
bail!(
"plugin function `{func}` has a parameter that is not a 32-bit integer",
);
}
if ty.results() != [wasmi::core::ValType::I32] {
bail!("plugin function `{func}` does not return exactly one 32-bit integer");
}
// Check inputs.
let expected = ty.params().len();
let given = args.len();
if expected != given {
bail!(
"plugin function takes {expected} argument{}, but {given} {} given",
if expected == 1 { "" } else { "s" },
if given == 1 { "was" } else { "were" },
);
}
// Collect the lengths of the argument buffers.
let lengths = args
.iter()
.map(|a| wasmi::Val::I32(a.len() as i32))
.collect::<Vec<_>>();
// Store the input data.
self.store.data_mut().args = args;
// Call the function.
let mut code = wasmi::Val::I32(-1);
handle
.call(&mut self.store, &lengths, std::slice::from_mut(&mut code))
.map_err(|err| eco_format!("plugin panicked: {err}"))?;
if let Some(MemoryError { offset, length, write }) =
self.store.data_mut().memory_error.take()
{
return Err(eco_format!(
"plugin tried to {kind} out of bounds: \
pointer {offset:#x} is out of bounds for {kind} of length {length}",
kind = if write { "write" } else { "read" }
));
}
// Extract the returned data.
let output = std::mem::take(&mut self.store.data_mut().output);
// Parse the functions return value.
match code {
wasmi::Val::I32(0) => {}
wasmi::Val::I32(1) => match std::str::from_utf8(&output) {
Ok(message) => bail!("plugin errored with: {message}"),
Err(_) => {
bail!("plugin errored, but did not return a valid error message")
}
},
_ => bail!("plugin did not respect the protocol"),
};
Ok(Bytes::new(output))
}
/// Creates a snapshot of this instance from which another one can be
/// initialized.
#[typst_macros::time(name = "save snapshot")]
fn snapshot(&self) -> Snapshot {
let memory = self.memory();
let mem_pages = memory.size(&self.store);
let mem_data = memory.data(&self.store).to_vec();
Snapshot { mem_pages, mem_data }
}
/// Restores the instance to a snapshot.
#[typst_macros::time(name = "restore snapshot")]
fn restore(&mut self, snapshot: &Snapshot) {
let memory = self.memory();
let current_size = memory.size(&self.store);
if current_size < snapshot.mem_pages {
memory
.grow(&mut self.store, snapshot.mem_pages - current_size)
.unwrap();
}
memory.data_mut(&mut self.store)[..snapshot.mem_data.len()]
.copy_from_slice(&snapshot.mem_data);
}
/// Retrieves a handle to the plugin's main memory.
fn memory(&self) -> Memory {
self.instance
.get_export(&self.store, "memory")
.unwrap()
.into_memory()
.unwrap()
}
}
/// The persistent store data used for communication between store and host.
#[derive(Default)]
struct CallData {
/// Arguments for a current call.
args: Vec<Bytes>,
/// The results of the current call.
output: Vec<u8>,
/// A memory error that occurred during execution of the current call.
memory_error: Option<MemoryError>,
}
/// If there was an error reading/writing memory, keep the offset + length to
/// display an error message.
struct MemoryError {
offset: u32,
length: u32,
write: bool,
}
/// Write the arguments to the plugin function into the plugin's memory.
fn wasm_minimal_protocol_write_args_to_buffer(
mut caller: wasmi::Caller<CallData>,
ptr: u32,
) {
let memory = caller.get_export("memory").unwrap().into_memory().unwrap();
let arguments = std::mem::take(&mut caller.data_mut().args);
let mut offset = ptr as usize;
for arg in arguments {
if memory.write(&mut caller, offset, arg.as_slice()).is_err() {
caller.data_mut().memory_error = Some(MemoryError {
offset: offset as u32,
length: arg.len() as u32,
write: true,
});
return;
}
offset += arg.len();
}
}
/// Extracts the output of the plugin function from the plugin's memory.
fn wasm_minimal_protocol_send_result_to_host(
mut caller: wasmi::Caller<CallData>,
ptr: u32,
len: u32,
) {
let memory = caller.get_export("memory").unwrap().into_memory().unwrap();
let mut buffer = std::mem::take(&mut caller.data_mut().output);
buffer.resize(len as usize, 0);
if memory.read(&caller, ptr as _, &mut buffer).is_err() {
caller.data_mut().memory_error =
Some(MemoryError { offset: ptr, length: len, write: false });
return;
}
caller.data_mut().output = buffer;
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/duration.rs | crates/typst-library/src/foundations/duration.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, Div, Mul, Neg, Sub};
use ecow::{EcoString, eco_format};
use time::ext::NumericalDuration;
use crate::foundations::{Repr, func, repr, scope, ty};
/// Represents a positive or negative span of time.
#[ty(scope, cast)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Duration(time::Duration);
impl Duration {
/// Whether the duration is empty / zero.
pub fn is_zero(&self) -> bool {
self.0.is_zero()
}
/// Decomposes the time into whole weeks, days, hours, minutes, and seconds.
pub fn decompose(&self) -> [i64; 5] {
let mut tmp = self.0;
let weeks = tmp.whole_weeks();
tmp -= weeks.weeks();
let days = tmp.whole_days();
tmp -= days.days();
let hours = tmp.whole_hours();
tmp -= hours.hours();
let minutes = tmp.whole_minutes();
tmp -= minutes.minutes();
let seconds = tmp.whole_seconds();
[weeks, days, hours, minutes, seconds]
}
}
#[scope]
impl Duration {
/// Creates a new duration.
///
/// You can specify the [duration] using weeks, days, hours, minutes and
/// seconds. You can also get a duration by subtracting two
/// [datetimes]($datetime).
///
/// ```example
/// #duration(
/// days: 3,
/// hours: 12,
/// ).hours()
/// ```
#[func(constructor)]
pub fn construct(
/// The number of seconds.
#[named]
#[default(0)]
seconds: i64,
/// The number of minutes.
#[named]
#[default(0)]
minutes: i64,
/// The number of hours.
#[named]
#[default(0)]
hours: i64,
/// The number of days.
#[named]
#[default(0)]
days: i64,
/// The number of weeks.
#[named]
#[default(0)]
weeks: i64,
) -> Duration {
Duration::from(
time::Duration::seconds(seconds)
+ time::Duration::minutes(minutes)
+ time::Duration::hours(hours)
+ time::Duration::days(days)
+ time::Duration::weeks(weeks),
)
}
/// The duration expressed in seconds.
///
/// This function returns the total duration represented in seconds as a
/// floating-point number rather than the second component of the duration.
#[func]
pub fn seconds(&self) -> f64 {
self.0.as_seconds_f64()
}
/// The duration expressed in minutes.
///
/// This function returns the total duration represented in minutes as a
/// floating-point number rather than the second component of the duration.
#[func]
pub fn minutes(&self) -> f64 {
self.seconds() / 60.0
}
/// The duration expressed in hours.
///
/// This function returns the total duration represented in hours as a
/// floating-point number rather than the second component of the duration.
#[func]
pub fn hours(&self) -> f64 {
self.seconds() / 3_600.0
}
/// The duration expressed in days.
///
/// This function returns the total duration represented in days as a
/// floating-point number rather than the second component of the duration.
#[func]
pub fn days(&self) -> f64 {
self.seconds() / 86_400.0
}
/// The duration expressed in weeks.
///
/// This function returns the total duration represented in weeks as a
/// floating-point number rather than the second component of the duration.
#[func]
pub fn weeks(&self) -> f64 {
self.seconds() / 604_800.0
}
}
impl Debug for Duration {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Repr for Duration {
fn repr(&self) -> EcoString {
let [weeks, days, hours, minutes, seconds] = self.decompose();
let mut vec = Vec::with_capacity(5);
if weeks != 0 {
vec.push(eco_format!("weeks: {}", weeks.repr()));
}
if days != 0 {
vec.push(eco_format!("days: {}", days.repr()));
}
if hours != 0 {
vec.push(eco_format!("hours: {}", hours.repr()));
}
if minutes != 0 {
vec.push(eco_format!("minutes: {}", minutes.repr()));
}
if seconds != 0 {
vec.push(eco_format!("seconds: {}", seconds.repr()));
}
eco_format!("duration{}", &repr::pretty_array_like(&vec, false))
}
}
impl From<time::Duration> for Duration {
fn from(value: time::Duration) -> Self {
Self(value)
}
}
impl From<Duration> for time::Duration {
fn from(value: Duration) -> Self {
value.0
}
}
impl Add for Duration {
type Output = Duration;
fn add(self, rhs: Self) -> Self::Output {
Duration(self.0 + rhs.0)
}
}
impl Sub for Duration {
type Output = Duration;
fn sub(self, rhs: Self) -> Self::Output {
Duration(self.0 - rhs.0)
}
}
impl Neg for Duration {
type Output = Duration;
fn neg(self) -> Self::Output {
Duration(-self.0)
}
}
impl Mul<f64> for Duration {
type Output = Duration;
fn mul(self, rhs: f64) -> Self::Output {
Duration(self.0 * rhs)
}
}
impl Div<f64> for Duration {
type Output = Duration;
fn div(self, rhs: f64) -> Self::Output {
Duration(self.0 / rhs)
}
}
impl Div for Duration {
type Output = f64;
fn div(self, rhs: Self) -> Self::Output {
self.0 / rhs.0
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/field.rs | crates/typst-library/src/foundations/content/field.rs | use std::fmt::{self, Debug};
use std::hash::Hash;
use std::marker::PhantomData;
use std::sync::OnceLock;
use ecow::{EcoString, eco_format};
use crate::foundations::{
Container, Content, FieldVtable, Fold, FoldFn, IntoValue, NativeElement, Packed,
Property, Reflect, Repr, Resolve, StyleChain,
};
/// An accessor for the `I`-th field of the element `E`. Values of this type are
/// generated for each field of an element can be used to interact with this
/// field programmatically, for example to access the style chain, as in
/// `styles.get(TextElem::size)`.
#[derive(Copy, Clone)]
pub struct Field<E: NativeElement, const I: u8>(pub PhantomData<E>);
impl<E: NativeElement, const I: u8> Field<E, I> {
/// Creates a new zero-sized accessor.
pub const fn new() -> Self {
Self(PhantomData)
}
/// The index of the projected field.
pub const fn index(self) -> u8 {
I
}
/// Creates a dynamic property instance for this field.
///
/// Prefer [`Content::set`] or
/// [`Styles::set`](crate::foundations::Styles::set) when working with
/// existing content or style value.
pub fn set(self, value: E::Type) -> Property
where
E: SettableProperty<I>,
E::Type: Debug + Clone + Hash + Send + Sync + 'static,
{
Property::new(self, value)
}
}
impl<E: NativeElement, const I: u8> Default for Field<E, I> {
fn default() -> Self {
Self::new()
}
}
/// A field that is present on every instance of the element.
pub trait RequiredField<const I: u8>: NativeElement {
type Type: Clone;
const FIELD: RequiredFieldData<Self, I>;
}
/// Metadata and routines for a [`RequiredField`].
pub struct RequiredFieldData<E: RequiredField<I>, const I: u8> {
name: &'static str,
docs: &'static str,
get: fn(&E) -> &E::Type,
}
impl<E: RequiredField<I>, const I: u8> RequiredFieldData<E, I> {
/// Creates the data from its parts. This is called in the `#[elem]` macro.
pub const fn new(
name: &'static str,
docs: &'static str,
get: fn(&E) -> &E::Type,
) -> Self {
Self { name, docs, get }
}
/// Creates the vtable for a `#[required]` field.
pub const fn vtable() -> FieldVtable<Packed<E>>
where
E: RequiredField<I>,
E::Type: Reflect + IntoValue + PartialEq,
{
FieldVtable {
name: E::FIELD.name,
docs: E::FIELD.docs,
positional: true,
required: true,
variadic: false,
settable: false,
synthesized: false,
input: || <E::Type as Reflect>::input(),
default: None,
has: |_| true,
get: |elem| Some((E::FIELD.get)(elem).clone().into_value()),
get_with_styles: |elem, _| Some((E::FIELD.get)(elem).clone().into_value()),
get_from_styles: |_| None,
materialize: |_, _| {},
eq: |a, b| (E::FIELD.get)(a) == (E::FIELD.get)(b),
}
}
/// Creates the vtable for a `#[variadic]` field.
pub const fn vtable_variadic() -> FieldVtable<Packed<E>>
where
E: RequiredField<I>,
E::Type: Container + IntoValue + PartialEq,
<E::Type as Container>::Inner: Reflect,
{
FieldVtable {
name: E::FIELD.name,
docs: E::FIELD.docs,
positional: true,
required: true,
variadic: true,
settable: false,
synthesized: false,
input: || <<E::Type as Container>::Inner as Reflect>::input(),
default: None,
has: |_| true,
get: |elem| Some((E::FIELD.get)(elem).clone().into_value()),
get_with_styles: |elem, _| Some((E::FIELD.get)(elem).clone().into_value()),
get_from_styles: |_| None,
materialize: |_, _| {},
eq: |a, b| (E::FIELD.get)(a) == (E::FIELD.get)(b),
}
}
}
/// A field that is initially unset, but may be set through a
/// [`Synthesize`](crate::foundations::Synthesize) implementation.
pub trait SynthesizedField<const I: u8>: NativeElement {
type Type: Clone;
const FIELD: SynthesizedFieldData<Self, I>;
}
/// Metadata and routines for a [`SynthesizedField`].
pub struct SynthesizedFieldData<E: SynthesizedField<I>, const I: u8> {
name: &'static str,
docs: &'static str,
get: fn(&E) -> &Option<E::Type>,
}
impl<E: SynthesizedField<I>, const I: u8> SynthesizedFieldData<E, I> {
/// Creates the data from its parts. This is called in the `#[elem]` macro.
pub const fn new(
name: &'static str,
docs: &'static str,
get: fn(&E) -> &Option<E::Type>,
) -> Self {
Self { name, docs, get }
}
/// Creates type-erased metadata and routines for a `#[synthesized]` field.
pub const fn vtable() -> FieldVtable<Packed<E>>
where
E: SynthesizedField<I>,
E::Type: Reflect + IntoValue + PartialEq,
{
FieldVtable {
name: E::FIELD.name,
docs: E::FIELD.docs,
positional: false,
required: false,
variadic: false,
settable: false,
synthesized: true,
input: || <E::Type as Reflect>::input(),
default: None,
has: |elem| (E::FIELD.get)(elem).is_some(),
get: |elem| (E::FIELD.get)(elem).clone().map(|v| v.into_value()),
get_with_styles: |elem, _| {
(E::FIELD.get)(elem).clone().map(|v| v.into_value())
},
get_from_styles: |_| None,
materialize: |_, _| {},
// Synthesized fields don't affect equality.
eq: |_, _| true,
}
}
}
/// A field that is not actually there. It's only visible in the docs.
pub trait ExternalField<const I: u8>: NativeElement {
type Type;
const FIELD: ExternalFieldData<Self, I>;
}
/// Metadata for an [`ExternalField`].
pub struct ExternalFieldData<E: ExternalField<I>, const I: u8> {
name: &'static str,
docs: &'static str,
default: fn() -> E::Type,
}
impl<E: ExternalField<I>, const I: u8> ExternalFieldData<E, I> {
/// Creates the data from its parts. This is called in the `#[elem]` macro.
pub const fn new(
name: &'static str,
docs: &'static str,
default: fn() -> E::Type,
) -> Self {
Self { name, docs, default }
}
/// Creates type-erased metadata and routines for an `#[external]` field.
pub const fn vtable() -> FieldVtable<Packed<E>>
where
E: ExternalField<I>,
E::Type: Reflect + IntoValue,
{
FieldVtable {
name: E::FIELD.name,
docs: E::FIELD.docs,
positional: false,
required: false,
variadic: false,
settable: false,
synthesized: false,
input: || <E::Type as Reflect>::input(),
default: Some(|| (E::FIELD.default)().into_value()),
has: |_| false,
get: |_| None,
get_with_styles: |_, _| None,
get_from_styles: |_| None,
materialize: |_, _| {},
eq: |_, _| true,
}
}
}
/// A field that has a default value and can be configured via a set rule, but
/// can also present on elements and be present in the constructor.
pub trait SettableField<const I: u8>: NativeElement {
type Type: Clone;
const FIELD: SettableFieldData<Self, I>;
}
/// Metadata and routines for a [`SettableField`].
pub struct SettableFieldData<E: SettableField<I>, const I: u8> {
get: fn(&E) -> &Settable<E, I>,
get_mut: fn(&mut E) -> &mut Settable<E, I>,
property: SettablePropertyData<E, I>,
}
impl<E: SettableField<I>, const I: u8> SettableFieldData<E, I> {
/// Creates the data from its parts. This is called in the `#[elem]` macro.
pub const fn new(
name: &'static str,
docs: &'static str,
positional: bool,
get: fn(&E) -> &Settable<E, I>,
get_mut: fn(&mut E) -> &mut Settable<E, I>,
default: fn() -> E::Type,
slot: fn() -> &'static OnceLock<E::Type>,
) -> Self {
Self {
get,
get_mut,
property: SettablePropertyData::new(name, docs, positional, default, slot),
}
}
/// Ensures that the property is folded on every access. See the
/// documentation of the [`Fold`] trait for more details.
pub const fn with_fold(mut self) -> Self
where
E::Type: Fold,
{
self.property.fold = Some(E::Type::fold);
self
}
/// Creates type-erased metadata and routines for a normal settable field.
pub const fn vtable() -> FieldVtable<Packed<E>>
where
E: SettableField<I>,
E::Type: Reflect + IntoValue + PartialEq,
{
FieldVtable {
name: E::FIELD.property.name,
docs: E::FIELD.property.docs,
positional: E::FIELD.property.positional,
required: false,
variadic: false,
settable: true,
synthesized: false,
input: || <E::Type as Reflect>::input(),
default: Some(|| E::default().into_value()),
has: |elem| (E::FIELD.get)(elem).is_set(),
get: |elem| (E::FIELD.get)(elem).as_option().clone().map(|v| v.into_value()),
get_with_styles: |elem, styles| {
Some((E::FIELD.get)(elem).get_cloned(styles).into_value())
},
get_from_styles: |styles| {
Some(styles.get_cloned::<E, I>(Field::new()).into_value())
},
materialize: |elem, styles| {
if !(E::FIELD.get)(elem).is_set() {
(E::FIELD.get_mut)(elem).set(styles.get_cloned::<E, I>(Field::new()));
}
},
eq: |a, b| (E::FIELD.get)(a).as_option() == (E::FIELD.get)(b).as_option(),
}
}
}
/// A field that has a default value and can be configured via a set rule, but
/// is never present on elements.
///
/// This is provided for all `SettableField` impls through a blanket impl. In
/// the case of `#[ghost]` fields, which only live in the style chain and not in
/// elements, it is also implemented manually.
pub trait SettableProperty<const I: u8>: NativeElement {
type Type: Clone;
const FIELD: SettablePropertyData<Self, I>;
const FOLD: Option<FoldFn<Self::Type>> = Self::FIELD.fold;
/// Produces an instance of the property's default value.
fn default() -> Self::Type {
// Avoid recreating an expensive instance over and over, but also
// avoid unnecessary lazy initialization for cheap types.
if std::mem::needs_drop::<Self::Type>() {
Self::default_ref().clone()
} else {
(Self::FIELD.default)()
}
}
/// Produces a static reference to this property's default value.
fn default_ref() -> &'static Self::Type {
(Self::FIELD.slot)().get_or_init(Self::FIELD.default)
}
}
impl<T, const I: u8> SettableProperty<I> for T
where
T: SettableField<I>,
{
type Type = <Self as SettableField<I>>::Type;
const FIELD: SettablePropertyData<Self, I> =
<Self as SettableField<I>>::FIELD.property;
}
/// Metadata and routines for a [`SettableProperty`].
pub struct SettablePropertyData<E: SettableProperty<I>, const I: u8> {
name: &'static str,
docs: &'static str,
positional: bool,
default: fn() -> E::Type,
slot: fn() -> &'static OnceLock<E::Type>,
fold: Option<FoldFn<E::Type>>,
}
impl<E: SettableProperty<I>, const I: u8> SettablePropertyData<E, I> {
/// Creates the data from its parts. This is called in the `#[elem]` macro.
pub const fn new(
name: &'static str,
docs: &'static str,
positional: bool,
default: fn() -> E::Type,
slot: fn() -> &'static OnceLock<E::Type>,
) -> Self {
Self { name, docs, positional, default, slot, fold: None }
}
/// Ensures that the property is folded on every access. See the
/// documentation of the [`Fold`] trait for more details.
pub const fn with_fold(self) -> Self
where
E::Type: Fold,
{
Self { fold: Some(E::Type::fold), ..self }
}
/// Creates type-erased metadata and routines for a `#[ghost]` field.
pub const fn vtable() -> FieldVtable<Packed<E>>
where
E: SettableProperty<I>,
E::Type: Reflect + IntoValue + PartialEq,
{
FieldVtable {
name: E::FIELD.name,
docs: E::FIELD.docs,
positional: E::FIELD.positional,
required: false,
variadic: false,
settable: true,
synthesized: false,
input: || <E::Type as Reflect>::input(),
default: Some(|| E::default().into_value()),
has: |_| false,
get: |_| None,
get_with_styles: |_, styles| {
Some(styles.get_cloned::<E, I>(Field::new()).into_value())
},
get_from_styles: |styles| {
Some(styles.get_cloned::<E, I>(Field::new()).into_value())
},
materialize: |_, _| {},
eq: |_, _| true,
}
}
}
/// A settable property that can be accessed by reference (because it is not
/// folded).
pub trait RefableProperty<const I: u8>: SettableProperty<I> {}
/// A settable field of an element.
///
/// The field can be in two states: Unset or present.
///
/// See [`StyleChain`] for more details about the available accessor methods.
#[derive(Copy, Clone, Hash)]
pub struct Settable<E: NativeElement, const I: u8>(Option<E::Type>)
where
E: SettableProperty<I>;
impl<E: NativeElement, const I: u8> Settable<E, I>
where
E: SettableProperty<I>,
{
/// Creates a new unset instance.
pub fn new() -> Self {
Self(None)
}
/// Sets the instance to a value.
pub fn set(&mut self, value: E::Type) {
self.0 = Some(value);
}
/// Clears the value from the instance.
pub fn unset(&mut self) {
self.0 = None;
}
/// Views the type as an [`Option`] which is `Some` if the type is set
/// and `None` if it is unset.
pub fn as_option(&self) -> &Option<E::Type> {
&self.0
}
/// Views the type as a mutable [`Option`].
pub fn as_option_mut(&mut self) -> &mut Option<E::Type> {
&mut self.0
}
/// Whether the field is set.
pub fn is_set(&self) -> bool {
self.0.is_some()
}
/// Retrieves the value given styles. The styles are used if the value is
/// unset.
pub fn get<'a>(&'a self, styles: StyleChain<'a>) -> E::Type
where
E::Type: Copy,
{
self.get_cloned(styles)
}
/// Retrieves and clones the value given styles. The styles are used if the
/// value is unset or if it needs folding.
pub fn get_cloned<'a>(&'a self, styles: StyleChain<'a>) -> E::Type {
if let Some(fold) = E::FOLD {
let mut res = styles.get_cloned::<E, I>(Field::new());
if let Some(value) = &self.0 {
res = fold(value.clone(), res);
}
res
} else if let Some(value) = &self.0 {
value.clone()
} else {
styles.get_cloned::<E, I>(Field::new())
}
}
/// Retrieves a reference to the value given styles. The styles are used if
/// the value is unset.
pub fn get_ref<'a>(&'a self, styles: StyleChain<'a>) -> &'a E::Type
where
E: RefableProperty<I>,
{
if let Some(value) = &self.0 {
value
} else {
styles.get_ref::<E, I>(Field::new())
}
}
/// Retrieves the value and then immediately [resolves](Resolve) it.
pub fn resolve<'a>(&'a self, styles: StyleChain<'a>) -> <E::Type as Resolve>::Output
where
E::Type: Resolve,
{
self.get_cloned(styles).resolve(styles)
}
}
impl<E: NativeElement, const I: u8> Debug for Settable<E, I>
where
E: SettableProperty<I>,
E::Type: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl<E: NativeElement, const I: u8> Default for Settable<E, I>
where
E: SettableProperty<I>,
{
fn default() -> Self {
Self(None)
}
}
impl<E: NativeElement, const I: u8> From<Option<E::Type>> for Settable<E, I>
where
E: SettableProperty<I>,
{
fn from(value: Option<E::Type>) -> Self {
Self(value)
}
}
/// An error arising when trying to access a field of content.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum FieldAccessError {
Unknown,
Unset,
}
impl FieldAccessError {
/// Formats the error message given the content and the field name.
#[cold]
pub fn message(self, content: &Content, field: &str) -> EcoString {
let elem_name = content.elem().name();
match self {
FieldAccessError::Unknown => {
eco_format!("{elem_name} does not have field {}", field.repr())
}
FieldAccessError::Unset => {
eco_format!(
"field {} in {elem_name} is not known at this point",
field.repr()
)
}
}
}
/// Formats the error message for an `at` calls without a default value.
#[cold]
pub fn message_no_default(self, content: &Content, field: &str) -> EcoString {
let mut msg = self.message(content, field);
msg.push_str(" and no default was specified");
msg
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/packed.rs | crates/typst-library/src/foundations/content/packed.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use typst_syntax::Span;
use crate::foundations::{Content, Label, NativeElement};
use crate::introspection::Location;
/// A packed element of a static type.
#[derive(Clone)]
#[repr(transparent)]
pub struct Packed<T: NativeElement>(
/// Invariant: Must be of type `T`.
Content,
PhantomData<T>,
);
impl<T: NativeElement> Packed<T> {
/// Pack element while retaining its static type.
pub fn new(element: T) -> Self {
// Safety: The element is known to be of type `T`.
Packed(element.pack(), PhantomData)
}
/// Try to cast type-erased content into a statically known packed element.
pub fn from_ref(content: &Content) -> Option<&Self> {
if content.is::<T>() {
// Safety:
// - We have checked the type.
// - Packed<T> is repr(transparent).
return Some(unsafe { std::mem::transmute::<&Content, &Packed<T>>(content) });
}
None
}
/// Try to cast type-erased content into a statically known packed element.
pub fn from_mut(content: &mut Content) -> Option<&mut Self> {
if content.is::<T>() {
// Safety:
// - We have checked the type.
// - Packed<T> is repr(transparent).
return Some(unsafe {
std::mem::transmute::<&mut Content, &mut Packed<T>>(content)
});
}
None
}
/// Try to cast type-erased content into a statically known packed element.
pub fn from_owned(content: Content) -> Result<Self, Content> {
if content.is::<T>() {
// Safety:
// - We have checked the type.
// - Packed<T> is repr(transparent).
return Ok(unsafe { std::mem::transmute::<Content, Packed<T>>(content) });
}
Err(content)
}
/// Pack back into content.
pub fn pack(self) -> Content {
self.0
}
/// Pack back into a reference to content.
pub fn pack_ref(&self) -> &Content {
&self.0
}
/// Pack back into a mutable reference to content.
pub fn pack_mut(&mut self) -> &mut Content {
&mut self.0
}
/// Extract the raw underlying element.
pub fn unpack(self) -> T {
// This function doesn't yet need owned self, but might in the future.
(*self).clone()
}
/// The element's span.
pub fn span(&self) -> Span {
self.0.span()
}
/// Set the span of the element.
pub fn spanned(self, span: Span) -> Self {
Self(self.0.spanned(span), PhantomData)
}
/// Accesses the label of the element.
pub fn label(&self) -> Option<Label> {
self.0.label()
}
/// Accesses the location of the element.
pub fn location(&self) -> Option<Location> {
self.0.location()
}
/// Sets the location of the element.
pub fn set_location(&mut self, location: Location) {
self.0.set_location(location);
}
}
impl<T: NativeElement> AsRef<T> for Packed<T> {
fn as_ref(&self) -> &T {
self
}
}
impl<T: NativeElement> AsMut<T> for Packed<T> {
fn as_mut(&mut self) -> &mut T {
self
}
}
impl<T: NativeElement> Deref for Packed<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: Packed<T> guarantees that the content is of element type `T`.
unsafe { (self.0).0.data::<T>() }
}
}
impl<T: NativeElement> DerefMut for Packed<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// Safety: Packed<T> guarantees that the content is of element type `T`.
unsafe { (self.0).0.data_mut::<T>() }
}
}
impl<T: NativeElement + Debug> Debug for Packed<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T: NativeElement> PartialEq for Packed<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: NativeElement> Hash for Packed<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/element.rs | crates/typst-library/src/foundations/content/element.rs | use std::any::TypeId;
use std::cmp::Ordering;
use std::fmt::{self, Debug};
use std::hash::Hash;
use std::sync::OnceLock;
use ecow::EcoString;
use smallvec::SmallVec;
use typst_utils::Static;
use crate::diag::SourceResult;
use crate::engine::Engine;
use crate::foundations::{
Args, Content, ContentVtable, FieldAccessError, Func, ParamInfo, Repr, Scope,
Selector, StyleChain, Styles, Value, cast,
};
use crate::text::{Lang, Region};
/// A document element.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Element(Static<ContentVtable>);
impl Element {
/// Get the element for `T`.
pub const fn of<T: NativeElement>() -> Self {
T::ELEM
}
/// Get the element for `T`.
pub const fn from_vtable(vtable: &'static ContentVtable) -> Self {
Self(Static(vtable))
}
/// The element's normal name (e.g. `enum`).
pub fn name(self) -> &'static str {
self.vtable().name
}
/// The element's title case name, for use in documentation
/// (e.g. `Numbered List`).
pub fn title(&self) -> &'static str {
self.vtable().title
}
/// Documentation for the element (as Markdown).
pub fn docs(&self) -> &'static str {
self.vtable().docs
}
/// Search keywords for the element.
pub fn keywords(&self) -> &'static [&'static str] {
self.vtable().keywords
}
/// Construct an instance of this element.
pub fn construct(
self,
engine: &mut Engine,
args: &mut Args,
) -> SourceResult<Content> {
(self.vtable().construct)(engine, args)
}
/// Execute the set rule for the element and return the resulting style map.
pub fn set(self, engine: &mut Engine, mut args: Args) -> SourceResult<Styles> {
let styles = (self.vtable().set)(engine, &mut args)?;
args.finish()?;
Ok(styles)
}
/// Whether the element has the given capability.
pub fn can<C>(self) -> bool
where
C: ?Sized + 'static,
{
self.can_type_id(TypeId::of::<C>())
}
/// Whether the element has the given capability where the capability is
/// given by a `TypeId`.
pub fn can_type_id(self, type_id: TypeId) -> bool {
(self.vtable().capability)(type_id).is_some()
}
/// Create a selector for this element.
pub fn select(self) -> Selector {
Selector::Elem(self, None)
}
/// Create a selector for this element, filtering for those that
/// [fields](crate::foundations::Content::field) match the given argument.
pub fn where_(self, fields: SmallVec<[(u8, Value); 1]>) -> Selector {
Selector::Elem(self, Some(fields))
}
/// The element's associated scope of sub-definition.
pub fn scope(&self) -> &'static Scope {
(self.vtable().store)().scope.get_or_init(|| (self.vtable().scope)())
}
/// Details about the element's fields.
pub fn params(&self) -> &'static [ParamInfo] {
(self.vtable().store)().params.get_or_init(|| {
self.vtable()
.fields
.iter()
.filter(|field| !field.synthesized)
.map(|field| ParamInfo {
name: field.name,
docs: field.docs,
input: (field.input)(),
default: field.default,
positional: field.positional,
named: !field.positional,
variadic: field.variadic,
required: field.required,
settable: field.settable,
})
.collect()
})
}
/// Extract the field ID for the given field name.
pub fn field_id(&self, name: &str) -> Option<u8> {
if name == "label" {
return Some(255);
}
(self.vtable().field_id)(name)
}
/// Extract the field name for the given field ID.
pub fn field_name(&self, id: u8) -> Option<&'static str> {
if id == 255 {
return Some("label");
}
self.vtable().field(id).map(|data| data.name)
}
/// Extract the value of the field for the given field ID and style chain.
pub fn field_from_styles(
&self,
id: u8,
styles: StyleChain,
) -> Result<Value, FieldAccessError> {
self.vtable()
.field(id)
.and_then(|field| (field.get_from_styles)(styles))
.ok_or(FieldAccessError::Unknown)
}
/// The element's local name, if any.
pub fn local_name(&self, lang: Lang, region: Option<Region>) -> Option<&'static str> {
self.vtable().local_name.map(|f| f(lang, region))
}
/// Retrieves the element's vtable for dynamic dispatch.
pub(super) fn vtable(&self) -> &'static ContentVtable {
(self.0).0
}
}
impl Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Element({})", self.name())
}
}
impl Repr for Element {
fn repr(&self) -> EcoString {
self.name().into()
}
}
impl Ord for Element {
fn cmp(&self, other: &Self) -> Ordering {
self.name().cmp(other.name())
}
}
impl PartialOrd for Element {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
cast! {
Element,
self => Value::Func(self.into()),
v: Func => v.to_element().ok_or("expected element")?,
}
/// Lazily initialized data for an element.
#[derive(Default)]
pub struct LazyElementStore {
pub scope: OnceLock<Scope>,
pub params: OnceLock<Vec<ParamInfo>>,
}
impl LazyElementStore {
/// Create an empty store.
pub const fn new() -> Self {
Self { scope: OnceLock::new(), params: OnceLock::new() }
}
}
/// A Typst element that is defined by a native Rust type.
///
/// # Safety
/// `ELEM` must hold the correct `Element` for `Self`.
pub unsafe trait NativeElement:
Debug + Clone + Hash + Construct + Set + Send + Sync + 'static
{
/// The associated element.
const ELEM: Element;
/// Pack the element into type-erased content.
fn pack(self) -> Content {
Content::new(self)
}
}
/// An element's constructor function.
pub trait Construct {
/// Construct an element from the arguments.
///
/// This is passed only the arguments that remain after execution of the
/// element's set rule.
fn construct(engine: &mut Engine, args: &mut Args) -> SourceResult<Content>
where
Self: Sized;
}
/// An element's set rule.
pub trait Set {
/// Parse relevant arguments into style properties for this element.
fn set(engine: &mut Engine, args: &mut Args) -> SourceResult<Styles>
where
Self: Sized;
}
/// Synthesize fields on an element. This happens before execution of any show
/// rule.
pub trait Synthesize {
/// Prepare the element for show rule application.
fn synthesize(&mut self, engine: &mut Engine, styles: StyleChain)
-> SourceResult<()>;
}
/// Defines built-in show set rules for an element.
///
/// This is a bit more powerful than a user-defined show-set because it can
/// access the element's fields.
pub trait ShowSet {
/// Finalize the fully realized form of the element. Use this for effects
/// that should work even in the face of a user-defined show rule.
fn show_set(&self, styles: StyleChain) -> Styles;
}
/// Tries to extract the plain-text representation of the element.
pub trait PlainText {
/// Write this element's plain text into the given buffer.
fn plain_text(&self, text: &mut EcoString);
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/raw.rs | crates/typst-library/src/foundations/content/raw.rs | use std::any::TypeId;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::ptr::NonNull;
use std::sync::atomic::{self, AtomicUsize, Ordering};
use typst_syntax::Span;
use typst_utils::{HashLock, SmallBitSet, fat};
use super::vtable;
use crate::foundations::{Element, Label, NativeElement, Packed};
use crate::introspection::Location;
/// The raw, low-level implementation of content.
///
/// The `ptr` + `elem` fields implement a fat pointer setup similar to an
/// `Arc<Inner<dyn Trait>>`, but in a manual way, allowing us to have a custom
/// [vtable].
pub struct RawContent {
/// A type-erased pointer to an allocation containing two things:
/// - A header that is the same for all elements
/// - Element-specific `data` that holds the specific element
///
/// This pointer is valid for both a `Header` and an `Inner<E>` where
/// `E::ELEM == self.elem` and can be freely cast between both. This is
/// possible because
/// - `Inner<E>` is `repr(C)`
/// - The first field of `Inner<E>` is `Header`
/// - ISO/IEC 9899:TC2 C standard § 6.7.2.1 - 13 states that a pointer to a
/// structure "points to its initial member" with no padding at the start
ptr: NonNull<Header>,
/// Describes which kind of element this content holds. This is used for
///
/// - Direct comparisons, e.g. `is::<HeadingElem>()`
/// - Behavior: An `Element` is just a pointer to a `ContentVtable`
/// containing not just data, but also function pointers for various
/// element-specific operations that can be performed
///
/// It is absolutely crucial that `elem == <E as NativeElement>::ELEM` for
/// `Inner<E>` pointed to by `ptr`. Otherwise, things will go very wrong
/// since we'd be using the wrong vtable.
elem: Element,
/// The content's span.
span: Span,
}
/// The allocated part of an element's representation.
///
/// This is `repr(C)` to ensure that a pointer to the whole structure may be
/// cast to a pointer to its first field.
#[repr(C)]
struct Inner<E> {
/// It is crucial that this is the first field because we cast between
/// pointers to `Inner<E>` and pointers to `Header`. See the documentation
/// of `RawContent::ptr` for more details.
header: Header,
/// The element struct. E.g. `E = HeadingElem`.
data: E,
}
/// The header that is shared by all elements.
struct Header {
/// The element's reference count. This works just like for `Arc`.
/// Unfortunately, we have to reimplement reference counting because we
/// have a custom fat pointer and `Arc` wouldn't know how to drop its
/// contents. Something with `ManuallyDrop<Arc<_>>` might also work, but at
/// that point we're not gaining much and with the way it's implemented now
/// we can also skip the unnecessary weak reference count.
refs: AtomicUsize,
/// Metadata for the element.
meta: Meta,
/// A cell for memoizing the hash of just the `data` part of the content.
hash: HashLock,
}
/// Metadata that elements can hold.
#[derive(Clone, Hash)]
pub(super) struct Meta {
/// An optional label attached to the element.
pub label: Option<Label>,
/// The element's location which identifies it in the laid-out output.
pub location: Option<Location>,
/// Manages the element during realization.
/// - If bit 0 is set, the element is prepared.
/// - If bit n is set, the element is guarded against the n-th show rule
/// recipe from the top of the style chain (counting from 1).
pub lifecycle: SmallBitSet,
}
impl RawContent {
/// Creates raw content wrapping an element, with all metadata set to
/// default (including a detached span).
pub(super) fn new<E: NativeElement>(data: E) -> Self {
Self::create(
data,
Meta {
label: None,
location: None,
lifecycle: SmallBitSet::new(),
},
HashLock::new(),
Span::detached(),
)
}
/// Creates and allocates raw content.
fn create<E: NativeElement>(data: E, meta: Meta, hash: HashLock, span: Span) -> Self {
let raw = Box::into_raw(Box::<Inner<E>>::new(Inner {
header: Header { refs: AtomicUsize::new(1), meta, hash },
data,
}));
// Safety: `Box` always holds a non-null pointer. See also
// `Box::into_non_null` (which is unstable).
let non_null = unsafe { NonNull::new_unchecked(raw) };
// Safety: See `RawContent::ptr`.
let ptr = non_null.cast::<Header>();
Self { ptr, elem: E::ELEM, span }
}
/// Destroys raw content and deallocates.
///
/// # Safety
/// - The reference count must be zero.
/// - The raw content must be be of type `E`.
pub(super) unsafe fn drop_impl<E: NativeElement>(&mut self) {
debug_assert_eq!(self.header().refs.load(Ordering::Relaxed), 0);
// Safety:
// - The caller guarantees that the content is of type `E`.
// - Thus, `ptr` must have been created from `Box<Inner<E>>` (see
// `RawContent::ptr`).
// - And to clean it up, we can just reproduce our box.
unsafe {
let ptr = self.ptr.cast::<Inner<E>>();
drop(Box::<Inner<E>>::from_raw(ptr.as_ptr()));
}
}
/// Clones a packed element into new raw content.
pub(super) fn clone_impl<E: NativeElement>(elem: &Packed<E>) -> Self {
let raw = &elem.pack_ref().0;
let header = raw.header();
RawContent::create(
elem.as_ref().clone(),
header.meta.clone(),
header.hash.clone(),
raw.span,
)
}
/// Accesses the header part of the raw content.
fn header(&self) -> &Header {
// Safety: `self.ptr` is a valid pointer to a header structure.
unsafe { self.ptr.as_ref() }
}
/// Mutably accesses the header part of the raw content.
fn header_mut(&mut self) -> &mut Header {
self.make_unique();
// Safety:
// - `self.ptr` is a valid pointer to a header structure.
// - We have unique access to the backing allocation (just ensured).
unsafe { self.ptr.as_mut() }
}
/// Retrieves the contained element **without checking that the content is
/// of the correct type.**
///
/// # Safety
/// This must be preceded by a check to [`is`]. The safe API for this is
/// [`Content::to_packed`] and the [`Packed`] struct.
pub(super) unsafe fn data<E: NativeElement>(&self) -> &E {
debug_assert!(self.is::<E>());
// Safety:
// - The caller guarantees that the content is of type `E`.
// - `self.ptr` is a valid pointer to an `Inner<E>` (see
// `RawContent::ptr`).
unsafe { &self.ptr.cast::<Inner<E>>().as_ref().data }
}
/// Retrieves the contained element mutably **without checking that the
/// content is of the correct type.**
///
/// Ensures that the element's allocation is unique.
///
/// # Safety
/// This must be preceded by a check to [`is`]. The safe API for this is
/// [`Content::to_packed_mut`] and the [`Packed`] struct.
pub(super) unsafe fn data_mut<E: NativeElement>(&mut self) -> &mut E {
debug_assert!(self.is::<E>());
// Ensure that the memoized hash is reset because we may mutate the
// element.
self.header_mut().hash.reset();
// Safety:
// - The caller guarantees that the content is of type `E`.
// - `self.ptr` is a valid pointer to an `Inner<E>` (see
// `RawContent::ptr`).
// - We have unique access to the backing allocation (due to header_mut).
unsafe { &mut self.ptr.cast::<Inner<E>>().as_mut().data }
}
/// Ensures that we have unique access to the backing allocation by cloning
/// if the reference count exceeds 1. This is used before performing
/// mutable operations, implementing a clone-on-write scheme.
fn make_unique(&mut self) {
if self.header().refs.load(Ordering::Relaxed) > 1 {
*self = self.handle().clone();
}
}
/// Retrieves the element this content is for.
pub(super) fn elem(&self) -> Element {
self.elem
}
/// Whether this content holds an element of type `E`.
pub(super) fn is<E: NativeElement>(&self) -> bool {
self.elem == E::ELEM
}
/// Retrieves the content's span.
pub(super) fn span(&self) -> Span {
self.span
}
/// Retrieves the content's span mutably.
pub(super) fn span_mut(&mut self) -> &mut Span {
&mut self.span
}
/// Retrieves the content's metadata.
pub(super) fn meta(&self) -> &Meta {
&self.header().meta
}
/// Retrieves the content's metadata mutably.
pub(super) fn meta_mut(&mut self) -> &mut Meta {
&mut self.header_mut().meta
}
/// Casts into a trait object for a given trait if the packed element
/// implements said trait.
pub(super) fn with<C>(&self) -> Option<&C>
where
C: ?Sized + 'static,
{
// Safety: The vtable comes from the `Capable` implementation which
// guarantees to return a matching vtable for `Packed<T>` and `C`. Since
// any `Packed<T>` is repr(transparent) with `Content` and `RawContent`,
// we can also use a `*const RawContent` pointer.
let vtable = (self.elem.vtable().capability)(TypeId::of::<C>())?;
let data = self as *const Self as *const ();
Some(unsafe { &*fat::from_raw_parts(data, vtable.as_ptr()) })
}
/// Casts into a mutable trait object for a given trait if the packed
/// element implements said trait.
pub(super) fn with_mut<C>(&mut self) -> Option<&mut C>
where
C: ?Sized + 'static,
{
// Safety: The vtable comes from the `Capable` implementation which
// guarantees to return a matching vtable for `Packed<T>` and `C`. Since
// any `Packed<T>` is repr(transparent) with `Content` and `RawContent`,
// we can also use a `*const Content` pointer.
//
// The resulting trait object contains an `&mut Packed<T>`. We do _not_
// need to ensure that we hold the only reference to the `Arc` here
// because `Packed<T>`'s DerefMut impl will take care of that if mutable
// access is required.
let vtable = (self.elem.vtable().capability)(TypeId::of::<C>())?;
let data = self as *mut Self as *mut ();
Some(unsafe { &mut *fat::from_raw_parts_mut(data, vtable.as_ptr()) })
}
}
impl RawContent {
/// Retrieves the element's vtable.
pub(super) fn handle(&self) -> vtable::ContentHandle<&RawContent> {
// Safety `self.elem.vtable()` is a matching vtable for `self`.
unsafe { vtable::Handle::new(self, self.elem.vtable()) }
}
/// Retrieves the element's vtable.
pub(super) fn handle_mut(&mut self) -> vtable::ContentHandle<&mut RawContent> {
// Safety `self.elem.vtable()` is a matching vtable for `self`.
unsafe { vtable::Handle::new(self, self.elem.vtable()) }
}
/// Retrieves the element's vtable.
pub(super) fn handle_pair<'a, 'b>(
&'a self,
other: &'b RawContent,
) -> Option<vtable::ContentHandle<(&'a RawContent, &'b RawContent)>> {
(self.elem == other.elem).then(|| {
// Safety:
// - `self.elem.vtable()` is a matching vtable for `self`.
// - It's also matching for `other` because `self.elem == other.elem`.
unsafe { vtable::Handle::new((self, other), self.elem.vtable()) }
})
}
}
impl Debug for RawContent {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.handle().debug(f)
}
}
impl Clone for RawContent {
fn clone(&self) -> Self {
// See Arc's clone impl for details about memory ordering.
let prev = self.header().refs.fetch_add(1, Ordering::Relaxed);
// See Arc's clone impl details about guarding against incredibly
// degenerate programs.
if prev > isize::MAX as usize {
ref_count_overflow(self.ptr, self.elem, self.span);
}
Self { ptr: self.ptr, elem: self.elem, span: self.span }
}
}
impl Drop for RawContent {
fn drop(&mut self) {
// Drop our ref-count. If there was more than one content before
// (including this one), we shouldn't deallocate. See Arc's drop impl
// for details about memory ordering.
if self.header().refs.fetch_sub(1, Ordering::Release) != 1 {
return;
}
// See Arc's drop impl for details.
atomic::fence(Ordering::Acquire);
// Safety:
// No other content references the backing allocation (just checked)
unsafe {
self.handle_mut().drop();
}
}
}
impl PartialEq for RawContent {
fn eq(&self, other: &Self) -> bool {
let Some(handle) = self.handle_pair(other) else { return false };
handle
.eq()
.unwrap_or_else(|| handle.fields().all(|handle| handle.eq()))
}
}
impl Hash for RawContent {
fn hash<H: Hasher>(&self, state: &mut H) {
self.elem.hash(state);
let header = self.header();
header.meta.hash(state);
header.hash.get_or_insert_with(|| self.handle().hash()).hash(state);
self.span.hash(state);
}
}
// Safety:
// - Works like `Arc`.
// - `NativeElement` implies `Send` and `Sync`, see below.
unsafe impl Sync for RawContent {}
unsafe impl Send for RawContent {}
fn _ensure_send_sync<T: NativeElement>() {
fn needs_send_sync<T: Send + Sync>() {}
needs_send_sync::<T>();
}
#[cold]
fn ref_count_overflow(ptr: NonNull<Header>, elem: Element, span: Span) -> ! {
// Drop to decrement the ref count to counter the increment in `clone()`
drop(RawContent { ptr, elem, span });
panic!("reference count overflow");
}
#[cfg(test)]
mod tests {
use crate::foundations::{NativeElement, Repr, StyleChain, Value};
use crate::introspection::Location;
use crate::model::HeadingElem;
use crate::text::TextElem;
#[test]
fn test_miri() {
let styles = StyleChain::default();
let mut first = HeadingElem::new(TextElem::packed("Hi!")).with_offset(2).pack();
let hash1 = typst_utils::hash128(&first);
first.set_location(Location::new(10));
let _ = format!("{first:?}");
let _ = first.repr();
assert!(first.is::<HeadingElem>());
assert!(!first.is::<TextElem>());
assert_eq!(first.to_packed::<TextElem>(), None);
assert_eq!(first.location(), Some(Location::new(10)));
assert_eq!(first.field_by_name("offset"), Ok(Value::Int(2)));
assert!(!first.has("depth".into()));
let second = first.clone();
first.materialize(styles);
let first_packed = first.to_packed::<HeadingElem>().unwrap();
let second_packed = second.to_packed::<HeadingElem>().unwrap();
assert!(first.has("depth".into()));
assert!(!second.has("depth".into()));
assert!(first_packed.depth.is_set());
assert!(!second_packed.depth.is_set());
assert_ne!(first, second);
assert_ne!(hash1, typst_utils::hash128(&first));
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/mod.rs | crates/typst-library/src/foundations/content/mod.rs | mod element;
mod field;
mod packed;
mod raw;
mod vtable;
pub use self::element::*;
pub use self::field::*;
pub use self::packed::Packed;
pub use self::vtable::{ContentVtable, FieldVtable};
#[doc(inline)]
pub use typst_macros::elem;
use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;
use std::iter::{self, Sum};
use std::ops::{Add, AddAssign, ControlFlow};
use comemo::Tracked;
use ecow::{EcoString, eco_format};
use serde::{Serialize, Serializer};
use typst_syntax::Span;
use typst_utils::singleton;
use crate::diag::{SourceResult, StrResult};
use crate::engine::Engine;
use crate::foundations::{
Context, Dict, IntoValue, Label, Property, Recipe, RecipeIndex, Repr, Selector, Str,
Style, StyleChain, Styles, Value, func, repr, scope, ty,
};
use crate::introspection::Location;
use crate::layout::{AlignElem, Alignment, Axes, Length, MoveElem, PadElem, Rel, Sides};
use crate::model::{Destination, EmphElem, LinkElem, LinkMarker, StrongElem};
use crate::pdf::{ArtifactElem, ArtifactKind};
use crate::text::UnderlineElem;
/// A piece of document content.
///
/// This type is at the heart of Typst. All markup you write and most
/// [functions]($function) you call produce content values. You can create a
/// content value by enclosing markup in square brackets. This is also how you
/// pass content to functions.
///
/// # Example
/// ```example
/// Type of *Hello!* is
/// #type([*Hello!*])
/// ```
///
/// Content can be added with the `+` operator,
/// [joined together]($scripting/#blocks) and multiplied with integers. Wherever
/// content is expected, you can also pass a [string]($str) or `{none}`.
///
/// # Representation
/// Content consists of elements with fields. When constructing an element with
/// its _element function,_ you provide these fields as arguments and when you
/// have a content value, you can access its fields with [field access
/// syntax]($scripting/#field-access).
///
/// Some fields are required: These must be provided when constructing an
/// element and as a consequence, they are always available through field access
/// on content of that type. Required fields are marked as such in the
/// documentation.
///
/// Most fields are optional: Like required fields, they can be passed to the
/// element function to configure them for a single element. However, these can
/// also be configured with [set rules]($styling/#set-rules) to apply them to
/// all elements within a scope. Optional fields are only available with field
/// access syntax when they were explicitly passed to the element function, not
/// when they result from a set rule.
///
/// Each element has a default appearance. However, you can also completely
/// customize its appearance with a [show rule]($styling/#show-rules). The show
/// rule is passed the element. It can access the element's field and produce
/// arbitrary content from it.
///
/// In the web app, you can hover over a content variable to see exactly which
/// elements the content is composed of and what fields they have.
/// Alternatively, you can inspect the output of the [`repr`] function.
#[ty(scope, cast)]
#[derive(Clone, PartialEq, Hash)]
#[repr(transparent)]
pub struct Content(raw::RawContent);
impl Content {
/// Creates a new content from an element.
pub fn new<T: NativeElement>(elem: T) -> Self {
Self(raw::RawContent::new(elem))
}
/// Creates a empty sequence content.
pub fn empty() -> Self {
singleton!(Content, SequenceElem::default().pack()).clone()
}
/// Get the element of this content.
pub fn elem(&self) -> Element {
self.0.elem()
}
/// Get the span of the content.
pub fn span(&self) -> Span {
self.0.span()
}
/// Set the span of the content.
pub fn spanned(mut self, span: Span) -> Self {
if self.0.span().is_detached() {
*self.0.span_mut() = span;
}
self
}
/// Get the label of the content.
pub fn label(&self) -> Option<Label> {
self.0.meta().label
}
/// Attach a label to the content.
pub fn labelled(mut self, label: Label) -> Self {
self.set_label(label);
self
}
/// Set the label of the content.
pub fn set_label(&mut self, label: Label) {
self.0.meta_mut().label = Some(label);
}
/// Assigns a location to the content.
///
/// This identifies the content and e.g. makes it linkable by
/// `.linked(Destination::Location(loc))`.
///
/// Useful in combination with [`Location::variant`].
pub fn located(mut self, loc: Location) -> Self {
self.set_location(loc);
self
}
/// Set the location of the content.
pub fn set_location(&mut self, location: Location) {
self.0.meta_mut().location = Some(location);
}
/// Check whether a show rule recipe is disabled.
pub fn is_guarded(&self, index: RecipeIndex) -> bool {
self.0.meta().lifecycle.contains(index.0)
}
/// Disable a show rule recipe.
pub fn guarded(mut self, index: RecipeIndex) -> Self {
self.0.meta_mut().lifecycle.insert(index.0);
self
}
/// Whether this content has already been prepared.
pub fn is_prepared(&self) -> bool {
self.0.meta().lifecycle.contains(0)
}
/// Mark this content as prepared.
pub fn mark_prepared(&mut self) {
self.0.meta_mut().lifecycle.insert(0);
}
/// Get a field by ID.
///
/// This is the preferred way to access fields. However, you can only use it
/// if you have set the field IDs yourself or are using the field IDs
/// generated by the `#[elem]` macro.
pub fn get(
&self,
id: u8,
styles: Option<StyleChain>,
) -> Result<Value, FieldAccessError> {
if id == 255
&& let Some(label) = self.label()
{
return Ok(label.into_value());
}
match self.0.handle().field(id) {
Some(handle) => match styles {
Some(styles) => handle.get_with_styles(styles),
None => handle.get(),
}
.ok_or(FieldAccessError::Unset),
None => Err(FieldAccessError::Unknown),
}
}
/// Get a field by name.
///
/// If you have access to the field IDs of the element, use [`Self::get`]
/// instead.
pub fn get_by_name(&self, name: &str) -> Result<Value, FieldAccessError> {
if name == "label" {
return self
.label()
.map(|label| label.into_value())
.ok_or(FieldAccessError::Unknown);
}
match self.elem().field_id(name).and_then(|id| self.0.handle().field(id)) {
Some(handle) => handle.get().ok_or(FieldAccessError::Unset),
None => Err(FieldAccessError::Unknown),
}
}
/// Get a field by ID, returning a missing field error if it does not exist.
///
/// This is the preferred way to access fields. However, you can only use it
/// if you have set the field IDs yourself or are using the field IDs
/// generated by the `#[elem]` macro.
pub fn field(&self, id: u8) -> StrResult<Value> {
self.get(id, None)
.map_err(|e| e.message(self, self.elem().field_name(id).unwrap()))
}
/// Get a field by name, returning a missing field error if it does not
/// exist.
///
/// If you have access to the field IDs of the element, use [`Self::field`]
/// instead.
pub fn field_by_name(&self, name: &str) -> StrResult<Value> {
self.get_by_name(name).map_err(|e| e.message(self, name))
}
/// Resolve all fields with the styles and save them in-place.
pub fn materialize(&mut self, styles: StyleChain) {
for id in 0..self.elem().vtable().fields.len() as u8 {
self.0.handle_mut().field(id).unwrap().materialize(styles);
}
}
/// Create a new sequence element from multiples elements.
pub fn sequence(iter: impl IntoIterator<Item = Self>) -> Self {
let vec: Vec<_> = iter.into_iter().collect();
if vec.is_empty() {
Self::empty()
} else if vec.len() == 1 {
vec.into_iter().next().unwrap()
} else {
SequenceElem::new(vec).into()
}
}
/// Whether the contained element is of type `T`.
pub fn is<T: NativeElement>(&self) -> bool {
self.0.is::<T>()
}
/// Downcasts the element to a packed value.
pub fn to_packed<T: NativeElement>(&self) -> Option<&Packed<T>> {
Packed::from_ref(self)
}
/// Downcasts the element to a mutable packed value.
pub fn to_packed_mut<T: NativeElement>(&mut self) -> Option<&mut Packed<T>> {
Packed::from_mut(self)
}
/// Downcasts the element into an owned packed value.
pub fn into_packed<T: NativeElement>(self) -> Result<Packed<T>, Self> {
Packed::from_owned(self)
}
/// Extract the raw underlying element.
pub fn unpack<T: NativeElement>(self) -> Result<T, Self> {
self.into_packed::<T>().map(Packed::unpack)
}
/// Whether the contained element has the given capability.
pub fn can<C>(&self) -> bool
where
C: ?Sized + 'static,
{
self.elem().can::<C>()
}
/// Cast to a trait object if the contained element has the given
/// capability.
pub fn with<C>(&self) -> Option<&C>
where
C: ?Sized + 'static,
{
self.0.with::<C>()
}
/// Cast to a mutable trait object if the contained element has the given
/// capability.
pub fn with_mut<C>(&mut self) -> Option<&mut C>
where
C: ?Sized + 'static,
{
self.0.with_mut::<C>()
}
/// Whether the content is an empty sequence.
pub fn is_empty(&self) -> bool {
let Some(sequence) = self.to_packed::<SequenceElem>() else {
return false;
};
sequence.children.is_empty()
}
/// Also auto expands sequence of sequences into flat sequence
pub fn sequence_recursive_for_each<'a>(&'a self, f: &mut impl FnMut(&'a Self)) {
if let Some(sequence) = self.to_packed::<SequenceElem>() {
for child in &sequence.children {
child.sequence_recursive_for_each(f);
}
} else {
f(self);
}
}
/// Style this content with a recipe, eagerly applying it if possible.
pub fn styled_with_recipe(
self,
engine: &mut Engine,
context: Tracked<Context>,
recipe: Recipe,
) -> SourceResult<Self> {
if recipe.selector().is_none() {
recipe.apply(engine, context, self)
} else {
Ok(self.styled(recipe))
}
}
/// Repeat this content `count` times.
pub fn repeat(&self, count: usize) -> Self {
Self::sequence(std::iter::repeat_with(|| self.clone()).take(count))
}
/// Sets a style property on the content.
pub fn set<E, const I: u8>(self, field: Field<E, I>, value: E::Type) -> Self
where
E: SettableProperty<I>,
E::Type: Debug + Clone + Hash + Send + Sync + 'static,
{
self.styled(Property::new(field, value))
}
/// Style this content with a style entry.
pub fn styled(mut self, style: impl Into<Style>) -> Self {
if let Some(style_elem) = self.to_packed_mut::<StyledElem>() {
style_elem.styles.apply_one(style.into());
self
} else {
self.styled_with_map(style.into().into())
}
}
/// Style this content with a full style map.
pub fn styled_with_map(mut self, styles: Styles) -> Self {
if styles.is_empty() {
return self;
}
if let Some(style_elem) = self.to_packed_mut::<StyledElem>() {
style_elem.styles.apply(styles);
self
} else {
StyledElem::new(self, styles).into()
}
}
/// Style this content with a full style map in-place.
pub fn style_in_place(&mut self, styles: Styles) {
if styles.is_empty() {
return;
}
if let Some(style_elem) = self.to_packed_mut::<StyledElem>() {
style_elem.styles.apply(styles);
} else {
*self = StyledElem::new(std::mem::take(self), styles).into();
}
}
/// Queries the content tree for the first element that match the given
/// selector.
///
/// This is a *naive hack* because contextual content and elements produced
/// in `show` rules will not be included in the results. It's used should
/// be avoided.
pub fn query_first_naive(&self, selector: &Selector) -> Option<Content> {
self.traverse(&mut |element| -> ControlFlow<Content> {
if selector.matches(&element, None) {
ControlFlow::Break(element)
} else {
ControlFlow::Continue(())
}
})
.break_value()
}
/// Extracts the plain text of this content.
pub fn plain_text(&self) -> EcoString {
let mut text = EcoString::new();
let _ = self.traverse(&mut |element| -> ControlFlow<()> {
if let Some(textable) = element.with::<dyn PlainText>() {
textable.plain_text(&mut text);
}
ControlFlow::Continue(())
});
text
}
/// Traverse this content.
pub fn traverse<F, B>(&self, f: &mut F) -> ControlFlow<B>
where
F: FnMut(Content) -> ControlFlow<B>,
{
/// Walks a given value to find any content that matches the selector.
///
/// Returns early if the function gives `ControlFlow::Break`.
fn walk_value<F, B>(value: Value, f: &mut F) -> ControlFlow<B>
where
F: FnMut(Content) -> ControlFlow<B>,
{
match value {
Value::Content(content) => content.traverse(f),
Value::Array(array) => {
for value in array {
walk_value(value, f)?;
}
ControlFlow::Continue(())
}
_ => ControlFlow::Continue(()),
}
}
// Call f on the element itself before recursively iterating its fields.
f(self.clone())?;
for (_, value) in self.fields() {
walk_value(value, f)?;
}
ControlFlow::Continue(())
}
}
impl Content {
/// Strongly emphasize this content.
pub fn strong(self) -> Self {
let span = self.span();
StrongElem::new(self).pack().spanned(span)
}
/// Emphasize this content.
pub fn emph(self) -> Self {
let span = self.span();
EmphElem::new(self).pack().spanned(span)
}
/// Underline this content.
pub fn underlined(self) -> Self {
let span = self.span();
UnderlineElem::new(self).pack().spanned(span)
}
/// Link the content somewhere.
pub fn linked(self, dest: Destination, alt: Option<EcoString>) -> Self {
let span = self.span();
LinkMarker::new(self, alt)
.pack()
.spanned(span)
.set(LinkElem::current, Some(dest))
}
/// Set alignments for this content.
pub fn aligned(self, align: Alignment) -> Self {
self.set(AlignElem::alignment, align)
}
/// Pad this content at the sides.
pub fn padded(self, padding: Sides<Rel<Length>>) -> Self {
let span = self.span();
PadElem::new(self)
.with_left(padding.left)
.with_top(padding.top)
.with_right(padding.right)
.with_bottom(padding.bottom)
.pack()
.spanned(span)
}
/// Transform this content's contents without affecting layout.
pub fn moved(self, delta: Axes<Rel<Length>>) -> Self {
let span = self.span();
MoveElem::new(self)
.with_dx(delta.x)
.with_dy(delta.y)
.pack()
.spanned(span)
}
/// Mark content as a PDF artifact.
pub fn artifact(self, kind: ArtifactKind) -> Self {
let span = self.span();
ArtifactElem::new(self).with_kind(kind).pack().spanned(span)
}
}
#[scope]
impl Content {
/// The content's element function. This function can be used to create the element
/// contained in this content. It can be used in set and show rules for the
/// element. Can be compared with global functions to check whether you have
/// a specific
/// kind of element.
#[func]
pub fn func(&self) -> Element {
self.elem()
}
/// Whether the content has the specified field.
#[func]
pub fn has(
&self,
/// The field to look for.
field: Str,
) -> bool {
if field.as_str() == "label" {
return self.label().is_some();
}
let Some(id) = self.elem().field_id(&field) else {
return false;
};
match self.0.handle().field(id) {
Some(field) => field.has(),
None => false,
}
}
/// Access the specified field on the content. Returns the default value if
/// the field does not exist or fails with an error if no default value was
/// specified.
#[func]
pub fn at(
&self,
/// The field to access.
field: Str,
/// A default value to return if the field does not exist.
#[named]
default: Option<Value>,
) -> StrResult<Value> {
self.get_by_name(&field)
.or_else(|e| default.ok_or(e))
.map_err(|e| e.message_no_default(self, &field))
}
/// Returns the fields of this content.
///
/// ```example
/// #rect(
/// width: 10cm,
/// height: 10cm,
/// ).fields()
/// ```
#[func]
pub fn fields(&self) -> Dict {
let mut dict = Dict::new();
for field in self.0.handle().fields() {
if let Some(value) = field.get() {
dict.insert(field.name.into(), value);
}
}
if let Some(label) = self.label() {
dict.insert("label".into(), label.into_value());
}
dict
}
/// The location of the content. This is only available on content returned
/// by [query] or provided by a [show rule]($reference/styling/#show-rules),
/// for other content it will be `{none}`. The resulting location can be
/// used with [counters]($counter), [state] and [queries]($query).
#[func]
pub fn location(&self) -> Option<Location> {
self.0.meta().location
}
}
impl Default for Content {
fn default() -> Self {
Self::empty()
}
}
impl Debug for Content {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T: NativeElement> From<T> for Content {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl Repr for Content {
fn repr(&self) -> EcoString {
self.0.handle().repr().unwrap_or_else(|| {
let fields = self
.0
.handle()
.fields()
.filter_map(|field| field.get().map(|v| (field.name, v.repr())))
.map(|(name, value)| eco_format!("{name}: {value}"))
.collect::<Vec<_>>();
eco_format!(
"{}{}",
self.elem().name(),
repr::pretty_array_like(&fields, false),
)
})
}
}
impl Add for Content {
type Output = Self;
fn add(self, mut rhs: Self) -> Self::Output {
let mut lhs = self;
match (lhs.to_packed_mut::<SequenceElem>(), rhs.to_packed_mut::<SequenceElem>()) {
(Some(seq_lhs), Some(rhs)) => {
seq_lhs.children.extend(rhs.children.iter().cloned());
lhs
}
(Some(seq_lhs), None) => {
seq_lhs.children.push(rhs);
lhs
}
(None, Some(rhs_seq)) => {
rhs_seq.children.insert(0, lhs);
rhs
}
(None, None) => Self::sequence([lhs, rhs]),
}
}
}
impl<'a> Add<&'a Self> for Content {
type Output = Self;
fn add(self, rhs: &'a Self) -> Self::Output {
let mut lhs = self;
match (lhs.to_packed_mut::<SequenceElem>(), rhs.to_packed::<SequenceElem>()) {
(Some(seq_lhs), Some(rhs)) => {
seq_lhs.children.extend(rhs.children.iter().cloned());
lhs
}
(Some(seq_lhs), None) => {
seq_lhs.children.push(rhs.clone());
lhs
}
(None, Some(_)) => {
let mut rhs = rhs.clone();
rhs.to_packed_mut::<SequenceElem>().unwrap().children.insert(0, lhs);
rhs
}
(None, None) => Self::sequence([lhs, rhs.clone()]),
}
}
}
impl AddAssign for Content {
fn add_assign(&mut self, rhs: Self) {
*self = std::mem::take(self) + rhs;
}
}
impl AddAssign<&Self> for Content {
fn add_assign(&mut self, rhs: &Self) {
*self = std::mem::take(self) + rhs;
}
}
impl Sum for Content {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Self::sequence(iter)
}
}
impl Serialize for Content {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_map(
iter::once(("func".into(), self.func().name().into_value()))
.chain(self.fields()),
)
}
}
/// A sequence of content.
#[elem(Debug, Repr)]
pub struct SequenceElem {
/// The elements.
#[required]
pub children: Vec<Content>,
}
impl Debug for SequenceElem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Sequence ")?;
f.debug_list().entries(&self.children).finish()
}
}
// Derive is currently incompatible with `elem` macro.
#[allow(clippy::derivable_impls)]
impl Default for SequenceElem {
fn default() -> Self {
Self { children: Default::default() }
}
}
impl Repr for SequenceElem {
fn repr(&self) -> EcoString {
if self.children.is_empty() {
"[]".into()
} else {
let elements = crate::foundations::repr::pretty_array_like(
&self.children.iter().map(|c| c.repr()).collect::<Vec<_>>(),
false,
);
eco_format!("sequence{}", elements)
}
}
}
/// Content alongside styles.
#[elem(Debug, Repr, PartialEq)]
pub struct StyledElem {
/// The content.
#[required]
pub child: Content,
/// The styles.
#[required]
pub styles: Styles,
}
impl Debug for StyledElem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
for style in self.styles.iter() {
writeln!(f, "#{style:?}")?;
}
self.child.fmt(f)
}
}
impl PartialEq for StyledElem {
fn eq(&self, other: &Self) -> bool {
self.child == other.child
}
}
impl Repr for StyledElem {
fn repr(&self) -> EcoString {
eco_format!("styled(child: {}, ..)", self.child.repr())
}
}
impl<T: NativeElement> IntoValue for T {
fn into_value(self) -> Value {
Value::Content(self.pack())
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/foundations/content/vtable.rs | crates/typst-library/src/foundations/content/vtable.rs | //! A custom [vtable] implementation for content.
//!
//! This is similar to what is generated by the Rust compiler under the hood
//! when using trait objects. However, ours has two key advantages:
//!
//! - It can store a _slice_ of sub-vtables for field-specific operations.
//! - It can store not only methods, but also plain data, allowing us to access
//! that data without going through dynamic dispatch.
//!
//! Because our vtable pointers are backed by `static` variables, we can also
//! perform checks for element types by comparing raw vtable pointers giving us
//! `RawContent::is` without dynamic dispatch.
//!
//! Overall, the custom vtable gives us just a little more flexibility and
//! optimizability than using built-in trait objects.
//!
//! Note that all vtable methods receive elements of type `Packed<E>`, but some
//! only perform actions on the `E` itself, with the shared part kept outside of
//! the vtable (e.g. `hash`), while some perform the full action (e.g. `clone`
//! as it needs to return new, fully populated raw content). Which one it is, is
//! documented for each.
//!
//! # Safety
//! This module contains a lot of `unsafe` keywords, but almost all of it is the
//! same and quite straightforward. All function pointers that operate on a
//! specific element type are marked as unsafe. In combination with `repr(C)`,
//! this grants us the ability to safely transmute a `ContentVtable<Packed<E>>`
//! into a `ContentVtable<RawContent>` (or just short `ContentVtable`). Callers
//! of functions marked as unsafe have to guarantee that the `ContentVtable` was
//! transmuted from the same `E` as the RawContent was constructed from. The
//! `Handle` struct provides a safe access layer, moving the guarantee that the
//! vtable is matching into a single spot.
//!
//! [vtable]: https://en.wikipedia.org/wiki/Virtual_method_table
use std::any::TypeId;
use std::fmt::{self, Debug, Formatter};
use std::ops::Deref;
use std::ptr::NonNull;
use ecow::EcoString;
use super::raw::RawContent;
use crate::diag::SourceResult;
use crate::engine::Engine;
use crate::foundations::{
Args, CastInfo, Construct, Content, LazyElementStore, NativeElement, NativeScope,
Packed, Repr, Scope, Set, StyleChain, Styles, Value,
};
use crate::text::{Lang, LocalName, Region};
/// Encapsulates content and a vtable, granting safe access to vtable operations.
pub(super) struct Handle<T, V: 'static>(T, &'static V);
impl<T, V> Handle<T, V> {
/// Produces a new handle from content and a vtable.
///
/// # Safety
/// The content and vtable must be matching, i.e. `vtable` must be derived
/// from the content's vtable.
pub(super) unsafe fn new(content: T, vtable: &'static V) -> Self {
Self(content, vtable)
}
}
impl<T, V> Deref for Handle<T, V> {
type Target = V;
fn deref(&self) -> &Self::Target {
self.1
}
}
pub(super) type ContentHandle<T> = Handle<T, ContentVtable>;
pub(super) type FieldHandle<T> = Handle<T, FieldVtable>;
/// A vtable for performing element-specific actions on type-erased content.
/// Also contains general metadata for the specific element.
#[repr(C)]
pub struct ContentVtable<T: 'static = RawContent> {
/// The element's normal name, as in code.
pub(super) name: &'static str,
/// The element's title-cased name.
pub(super) title: &'static str,
/// The element's documentation (as Markdown).
pub(super) docs: &'static str,
/// Search keywords for the documentation.
pub(super) keywords: &'static [&'static str],
/// Subvtables for all fields of the element.
pub(super) fields: &'static [FieldVtable<T>],
/// Determines the ID for a field name. This is a separate function instead
/// of searching through `fields` so that Rust can generate optimized code
/// for the string matching.
pub(super) field_id: fn(name: &str) -> Option<u8>,
/// The constructor of the element.
pub(super) construct: fn(&mut Engine, &mut Args) -> SourceResult<Content>,
/// The set rule of the element.
pub(super) set: fn(&mut Engine, &mut Args) -> SourceResult<Styles>,
/// The element's local name in a specific lang-region pairing.
pub(super) local_name: Option<fn(Lang, Option<Region>) -> &'static str>,
/// Produces the associated [`Scope`] of the element.
pub(super) scope: fn() -> Scope,
/// If the `capability` function returns `Some(p)`, then `p` must be a valid
/// pointer to a native Rust vtable of `Packed<Self>` w.r.t to the trait `C`
/// where `capability` is `TypeId::of::<dyn C>()`.
pub(super) capability: fn(capability: TypeId) -> Option<NonNull<()>>,
/// The `Drop` impl (for the whole raw content). The content must have a
/// reference count of zero and may not be used anymore after `drop` was
/// called.
pub(super) drop: unsafe fn(&mut RawContent),
/// The `Clone` impl (for the whole raw content).
pub(super) clone: unsafe fn(&T) -> RawContent,
/// The `Hash` impl (for just the element).
pub(super) hash: unsafe fn(&T) -> u128,
/// The `Debug` impl (for just the element).
pub(super) debug: unsafe fn(&T, &mut Formatter) -> fmt::Result,
/// The `PartialEq` impl (for just the element). If this is `None`,
/// field-wise equality checks (via `FieldVtable`) should be performed.
pub(super) eq: Option<unsafe fn(&T, &T) -> bool>,
/// The `Repr` impl (for just the element). If this is `None`, a generic
/// name + fields representation should be produced.
pub(super) repr: Option<unsafe fn(&T) -> EcoString>,
/// Produces a reference to a `static` variable holding a `LazyElementStore`
/// that is unique for this element and can be populated with data that is
/// somewhat costly to initialize at runtime and shouldn't be initialized
/// over and over again. Must be a function rather than a direct reference
/// so that we can store the vtable in a `const` without Rust complaining
/// about the presence of interior mutability.
pub(super) store: fn() -> &'static LazyElementStore,
}
impl ContentVtable {
/// Creates the vtable for an element.
pub const fn new<E: NativeElement>(
name: &'static str,
title: &'static str,
docs: &'static str,
fields: &'static [FieldVtable<Packed<E>>],
field_id: fn(name: &str) -> Option<u8>,
capability: fn(TypeId) -> Option<NonNull<()>>,
store: fn() -> &'static LazyElementStore,
) -> ContentVtable<Packed<E>> {
ContentVtable {
name,
title,
docs,
keywords: &[],
fields,
field_id,
construct: <E as Construct>::construct,
set: <E as Set>::set,
local_name: None,
scope: || Scope::new(),
capability,
drop: RawContent::drop_impl::<E>,
clone: RawContent::clone_impl::<E>,
hash: |elem| typst_utils::hash128(elem.as_ref()),
debug: |elem, f| Debug::fmt(elem.as_ref(), f),
eq: None,
repr: None,
store,
}
}
/// Retrieves the vtable of the element with the given ID.
pub fn field(&self, id: u8) -> Option<&'static FieldVtable> {
self.fields.get(usize::from(id))
}
}
impl<E: NativeElement> ContentVtable<Packed<E>> {
/// Attaches search keywords for the documentation.
pub const fn with_keywords(mut self, keywords: &'static [&'static str]) -> Self {
self.keywords = keywords;
self
}
/// Takes a [`Repr`] impl into account.
pub const fn with_repr(mut self) -> Self
where
E: Repr,
{
self.repr = Some(|e| E::repr(&**e));
self
}
/// Takes a [`PartialEq`] impl into account.
pub const fn with_partial_eq(mut self) -> Self
where
E: PartialEq,
{
self.eq = Some(|a, b| E::eq(&**a, &**b));
self
}
/// Takes a [`LocalName`] impl into account.
pub const fn with_local_name(mut self) -> Self
where
Packed<E>: LocalName,
{
self.local_name = Some(<Packed<E> as LocalName>::local_name);
self
}
/// Takes a [`NativeScope`] impl into account.
pub const fn with_scope(mut self) -> Self
where
E: NativeScope,
{
self.scope = || E::scope();
self
}
/// Type-erases the data.
pub const fn erase(self) -> ContentVtable {
// Safety:
// - `ContentVtable` is `repr(C)`.
// - `ContentVtable` does not hold any `E`-specific data except for
// function pointers.
// - All functions pointers have the same memory layout.
// - All functions containing `E` are marked as unsafe and callers need
// to uphold the guarantee that they only call them with raw content
// that is of type `E`.
// - `Packed<E>` and `RawContent` have the exact same memory layout
// because of `repr(transparent)`.
unsafe {
std::mem::transmute::<ContentVtable<Packed<E>>, ContentVtable<RawContent>>(
self,
)
}
}
}
impl<T> ContentHandle<T> {
/// Provides safe access to operations for the field with the given `id`.
pub(super) fn field(self, id: u8) -> Option<FieldHandle<T>> {
self.fields.get(usize::from(id)).map(|vtable| {
// Safety: Field vtables are of same type as the content vtable.
unsafe { Handle::new(self.0, vtable) }
})
}
/// Provides safe access to all field operations.
pub(super) fn fields(self) -> impl Iterator<Item = FieldHandle<T>>
where
T: Copy,
{
self.fields.iter().map(move |vtable| {
// Safety: Field vtables are of same type as the content vtable.
unsafe { Handle::new(self.0, vtable) }
})
}
}
impl ContentHandle<&RawContent> {
/// See [`ContentVtable::debug`].
pub fn debug(&self, f: &mut Formatter) -> fmt::Result {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.debug)(self.0, f) }
}
/// See [`ContentVtable::repr`].
pub fn repr(&self) -> Option<EcoString> {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { self.1.repr.map(|f| f(self.0)) }
}
/// See [`ContentVtable::clone`].
pub fn clone(&self) -> RawContent {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.clone)(self.0) }
}
/// See [`ContentVtable::hash`].
pub fn hash(&self) -> u128 {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.hash)(self.0) }
}
}
impl ContentHandle<&mut RawContent> {
/// See [`ContentVtable::drop`].
pub unsafe fn drop(&mut self) {
// Safety:
// - `Handle` has the invariant that the vtable is matching.
// - The caller satisfies the requirements of `drop`
unsafe { (self.1.drop)(self.0) }
}
}
impl ContentHandle<(&RawContent, &RawContent)> {
/// See [`ContentVtable::eq`].
pub fn eq(&self) -> Option<bool> {
// Safety: `Handle` has the invariant that the vtable is matching.
let (a, b) = self.0;
unsafe { self.1.eq.map(|f| f(a, b)) }
}
}
/// A vtable for performing field-specific actions on type-erased
/// content. Also contains general metadata for the specific field.
#[repr(C)]
pub struct FieldVtable<T: 'static = RawContent> {
/// The field's name, as in code.
pub(super) name: &'static str,
/// The fields's documentation (as Markdown).
pub(super) docs: &'static str,
/// Whether the field's parameter is positional.
pub(super) positional: bool,
/// Whether the field's parameter is variadic.
pub(super) variadic: bool,
/// Whether the field's parameter is required.
pub(super) required: bool,
/// Whether the field can be set via a set rule.
pub(super) settable: bool,
/// Whether the field is synthesized (i.e. initially not present).
pub(super) synthesized: bool,
/// Reflects what types the field's parameter accepts.
pub(super) input: fn() -> CastInfo,
/// Produces the default value of the field, if any. This would e.g. be
/// `None` for a required parameter.
pub(super) default: Option<fn() -> Value>,
/// Whether the field is set on the given element. Always true for required
/// fields, but can be false for settable or synthesized fields.
pub(super) has: unsafe fn(elem: &T) -> bool,
/// Retrieves the field and [turns it into a
/// value](crate::foundations::IntoValue).
pub(super) get: unsafe fn(elem: &T) -> Option<Value>,
/// Retrieves the field given styles. The resulting value may come from the
/// element, the style chain, or a mix (if it's a
/// [`Fold`](crate::foundations::Fold) field).
pub(super) get_with_styles: unsafe fn(elem: &T, StyleChain) -> Option<Value>,
/// Retrieves the field just from the styles.
pub(super) get_from_styles: fn(StyleChain) -> Option<Value>,
/// Sets the field from the styles if it is currently unset. (Or merges
/// with the style data in case of a `Fold` field).
pub(super) materialize: unsafe fn(elem: &mut T, styles: StyleChain),
/// Compares the field for equality.
pub(super) eq: unsafe fn(a: &T, b: &T) -> bool,
}
impl FieldHandle<&RawContent> {
/// See [`FieldVtable::has`].
pub fn has(&self) -> bool {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.has)(self.0) }
}
/// See [`FieldVtable::get`].
pub fn get(&self) -> Option<Value> {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.get)(self.0) }
}
/// See [`FieldVtable::get_with_styles`].
pub fn get_with_styles(&self, styles: StyleChain) -> Option<Value> {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.get_with_styles)(self.0, styles) }
}
}
impl FieldHandle<&mut RawContent> {
/// See [`FieldVtable::materialize`].
pub fn materialize(&mut self, styles: StyleChain) {
// Safety: `Handle` has the invariant that the vtable is matching.
unsafe { (self.1.materialize)(self.0, styles) }
}
}
impl FieldHandle<(&RawContent, &RawContent)> {
/// See [`FieldVtable::eq`].
pub fn eq(&self) -> bool {
// Safety: `Handle` has the invariant that the vtable is matching.
let (a, b) = self.0;
unsafe { (self.1.eq)(a, b) }
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/introspector.rs | crates/typst-library/src/introspection/introspector.rs | use std::collections::BTreeSet;
use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;
use std::num::NonZeroUsize;
use std::sync::RwLock;
use ecow::{EcoString, EcoVec};
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;
use typst_utils::NonZeroExt;
use crate::diag::{StrResult, bail};
use crate::foundations::{Content, Label, Repr, Selector};
use crate::introspection::{Location, Tag};
use crate::layout::{Frame, FrameItem, Point, Position, Transform};
use crate::model::Numbering;
/// Can be queried for elements and their positions.
#[derive(Default, Clone)]
pub struct Introspector {
/// The number of pages in the document.
pages: usize,
/// The page numberings, indexed by page number minus 1.
page_numberings: Vec<Option<Numbering>>,
/// The page supplements, indexed by page number minus 1.
page_supplements: Vec<Content>,
/// All introspectable elements.
elems: Vec<Pair>,
/// Lists all elements with a specific hash key. This is used for
/// introspector-assisted location assignment during measurement.
keys: MultiMap<u128, Location>,
/// Accelerates lookup of elements by location.
locations: FxHashMap<Location, usize>,
/// Accelerates lookup of elements by label.
labels: MultiMap<Label, usize>,
/// Maps from element locations to assigned HTML IDs. This used to support
/// intra-doc links in HTML export. In paged export, is is simply left
/// empty and [`Self::html_id`] is not used.
html_ids: FxHashMap<Location, EcoString>,
/// Caches queries done on the introspector. This is important because
/// even if all top-level queries are distinct, they often have shared
/// subqueries. Example: Individual counter queries with `before` that
/// all depend on a global counter query.
queries: QueryCache,
}
/// A pair of content and its position.
type Pair = (Content, DocumentPosition);
impl Introspector {
/// Iterates over all locatable elements.
pub fn all(&self) -> impl Iterator<Item = &Content> + '_ {
self.elems.iter().map(|(c, _)| c)
}
/// Checks how many times a label exists.
pub fn label_count(&self, label: Label) -> usize {
self.labels.get(&label).len()
}
/// Enriches an existing introspector with HTML IDs, which were assigned
/// to the DOM in a post-processing step.
pub fn set_html_ids(&mut self, html_ids: FxHashMap<Location, EcoString>) {
self.html_ids = html_ids;
}
/// Retrieves the element with the given index.
#[track_caller]
fn get_by_idx(&self, idx: usize) -> &Content {
&self.elems[idx].0
}
/// Retrieves the position of the element with the given index.
#[track_caller]
fn get_pos_by_idx(&self, idx: usize) -> DocumentPosition {
self.elems[idx].1.clone()
}
/// Retrieves an element by its location.
fn get_by_loc(&self, location: &Location) -> Option<&Content> {
self.locations.get(location).map(|&idx| self.get_by_idx(idx))
}
/// Retrieves the position of the element with the given index.
fn get_pos_by_loc(&self, location: &Location) -> Option<DocumentPosition> {
self.locations.get(location).map(|&idx| self.get_pos_by_idx(idx))
}
/// Performs a binary search for `elem` among the `list`.
fn binary_search(&self, list: &[Content], elem: &Content) -> Result<usize, usize> {
list.binary_search_by_key(&self.elem_index(elem), |elem| self.elem_index(elem))
}
/// Gets the index of this element.
fn elem_index(&self, elem: &Content) -> usize {
self.loc_index(&elem.location().unwrap())
}
/// Gets the index of the element with this location among all.
fn loc_index(&self, location: &Location) -> usize {
self.locations.get(location).copied().unwrap_or(usize::MAX)
}
}
#[comemo::track]
impl Introspector {
/// Query for all matching elements.
pub fn query(&self, selector: &Selector) -> EcoVec<Content> {
let hash = typst_utils::hash128(selector);
if let Some(output) = self.queries.get(hash) {
return output;
}
let output = match selector {
Selector::Elem(..) => self
.all()
.filter(|elem| selector.matches(elem, None))
.cloned()
.collect(),
Selector::Location(location) => {
self.get_by_loc(location).cloned().into_iter().collect()
}
Selector::Label(label) => self
.labels
.get(label)
.iter()
.map(|&idx| self.get_by_idx(idx).clone())
.collect(),
Selector::Or(selectors) => selectors
.iter()
.flat_map(|sel| self.query(sel))
.map(|elem| self.elem_index(&elem))
.collect::<BTreeSet<usize>>()
.into_iter()
.map(|idx| self.get_by_idx(idx).clone())
.collect(),
Selector::And(selectors) => {
let mut results: Vec<_> =
selectors.iter().map(|sel| self.query(sel)).collect();
// Extract the smallest result list and then keep only those
// elements in the smallest list that are also in all other
// lists.
results
.iter()
.enumerate()
.min_by_key(|(_, vec)| vec.len())
.map(|(i, _)| i)
.map(|i| results.swap_remove(i))
.iter()
.flatten()
.filter(|candidate| {
results
.iter()
.all(|other| self.binary_search(other, candidate).is_ok())
})
.cloned()
.collect()
}
Selector::Before { selector, end, inclusive } => {
let mut list = self.query(selector);
if let Some(end) = self.query_first(end) {
// Determine which elements are before `end`.
let split = match self.binary_search(&list, &end) {
// Element itself is contained.
Ok(i) => i + *inclusive as usize,
// Element itself is not contained.
Err(i) => i,
};
list = list[..split].into();
}
list
}
Selector::After { selector, start, inclusive } => {
let mut list = self.query(selector);
if let Some(start) = self.query_first(start) {
// Determine which elements are after `start`.
let split = match self.binary_search(&list, &start) {
// Element itself is contained.
Ok(i) => i + !*inclusive as usize,
// Element itself is not contained.
Err(i) => i,
};
list = list[split..].into();
}
list
}
// Not supported here.
Selector::Can(_) | Selector::Regex(_) => EcoVec::new(),
};
self.queries.insert(hash, output.clone());
output
}
/// Query for the first element that matches the selector.
pub fn query_first(&self, selector: &Selector) -> Option<Content> {
match selector {
Selector::Location(location) => self.get_by_loc(location).cloned(),
Selector::Label(label) => self
.labels
.get(label)
.first()
.map(|&idx| self.get_by_idx(idx).clone()),
_ => self.query(selector).first().cloned(),
}
}
/// Query for the first element that matches the selector.
pub fn query_unique(&self, selector: &Selector) -> StrResult<Content> {
match selector {
Selector::Location(location) => self
.get_by_loc(location)
.cloned()
.ok_or_else(|| "element does not exist in the document".into()),
Selector::Label(label) => self.query_label(*label).cloned(),
_ => {
let elems = self.query(selector);
if elems.len() > 1 {
bail!("selector matches multiple elements",);
}
elems
.into_iter()
.next()
.ok_or_else(|| "selector does not match any element".into())
}
}
}
/// Query for a unique element with the label.
pub fn query_label(&self, label: Label) -> StrResult<&Content> {
match *self.labels.get(&label) {
[idx] => Ok(self.get_by_idx(idx)),
[] => bail!("label `{}` does not exist in the document", label.repr()),
_ => bail!("label `{}` occurs multiple times in the document", label.repr()),
}
}
/// This is an optimized version of
/// `query(selector.before(end, true).len()` used by counters and state.
pub fn query_count_before(&self, selector: &Selector, end: Location) -> usize {
// See `query()` for details.
let list = self.query(selector);
if let Some(end) = self.get_by_loc(&end) {
match self.binary_search(&list, end) {
Ok(i) => i + 1,
Err(i) => i,
}
} else {
list.len()
}
}
/// The total number pages.
pub fn pages(&self) -> NonZeroUsize {
NonZeroUsize::new(self.pages).unwrap_or(NonZeroUsize::ONE)
}
/// Find the page number for the given location.
pub fn page(&self, location: Location) -> NonZeroUsize {
match self.position(location) {
DocumentPosition::Paged(position) => position.page,
_ => NonZeroUsize::ONE,
}
}
/// Find the position for the given location.
pub fn position(&self, location: Location) -> DocumentPosition {
self.get_pos_by_loc(&location)
.unwrap_or(DocumentPosition::Paged(Position {
page: NonZeroUsize::ONE,
point: Point::zero(),
}))
}
/// Gets the page numbering for the given location, if any.
pub fn page_numbering(&self, location: Location) -> Option<&Numbering> {
let page = self.page(location);
self.page_numberings
.get(page.get() - 1)
.and_then(|slot| slot.as_ref())
}
/// Gets the page supplement for the given location, if any.
pub fn page_supplement(&self, location: Location) -> Content {
let page = self.page(location);
self.page_supplements.get(page.get() - 1).cloned().unwrap_or_default()
}
/// Retrieves the ID to link to for this location in HTML export.
pub fn html_id(&self, location: Location) -> Option<&EcoString> {
self.html_ids.get(&location)
}
/// Try to find a location for an element with the given `key` hash
/// that is closest after the `anchor`.
///
/// This is used for introspector-assisted location assignment during
/// measurement. See the "Dealing with Measurement" section of the
/// [`Locator`](crate::introspection::Locator) docs for more details.
pub fn locator(&self, key: u128, anchor: Location) -> Option<Location> {
let anchor = self.loc_index(&anchor);
self.keys
.get(&key)
.iter()
.copied()
.min_by_key(|loc| self.loc_index(loc).wrapping_sub(anchor))
}
}
impl Debug for Introspector {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("Introspector(..)")
}
}
/// A map from one keys to multiple elements.
#[derive(Clone)]
struct MultiMap<K, V>(FxHashMap<K, SmallVec<[V; 1]>>);
impl<K, V> MultiMap<K, V>
where
K: Hash + Eq,
{
fn get(&self, key: &K) -> &[V] {
self.0.get(key).map_or(&[], |vec| vec.as_slice())
}
fn insert(&mut self, key: K, value: V) {
self.0.entry(key).or_default().push(value);
}
fn take(&mut self, key: &K) -> Option<impl Iterator<Item = V> + use<K, V>> {
self.0.remove(key).map(|vec| vec.into_iter())
}
}
impl<K, V> Default for MultiMap<K, V> {
fn default() -> Self {
Self(FxHashMap::default())
}
}
/// Caches queries.
#[derive(Default)]
struct QueryCache(RwLock<FxHashMap<u128, EcoVec<Content>>>);
impl QueryCache {
fn get(&self, hash: u128) -> Option<EcoVec<Content>> {
self.0.read().unwrap().get(&hash).cloned()
}
fn insert(&self, hash: u128, output: EcoVec<Content>) {
self.0.write().unwrap().insert(hash, output);
}
}
impl Clone for QueryCache {
fn clone(&self) -> Self {
Self(RwLock::new(self.0.read().unwrap().clone()))
}
}
/// Builds the introspector.
#[derive(Default)]
pub struct IntrospectorBuilder {
pub pages: usize,
pub page_numberings: Vec<Option<Numbering>>,
pub page_supplements: Vec<Content>,
pub html_ids: FxHashMap<Location, EcoString>,
seen: FxHashSet<Location>,
insertions: MultiMap<Location, Vec<Pair>>,
keys: MultiMap<u128, Location>,
locations: FxHashMap<Location, usize>,
labels: MultiMap<Label, usize>,
}
impl IntrospectorBuilder {
/// Create an empty builder.
pub fn new() -> Self {
Self::default()
}
/// Processes the tags in the frame.
pub fn discover_in_frame<F>(
&mut self,
sink: &mut Vec<Pair>,
frame: &Frame,
ts: Transform,
to_pos: &mut F,
) where
F: FnMut(Point) -> DocumentPosition,
{
for (pos, item) in frame.items() {
match item {
FrameItem::Group(group) => {
let ts = ts
.pre_concat(Transform::translate(pos.x, pos.y))
.pre_concat(group.transform);
if let Some(parent) = group.parent {
let mut nested = vec![];
self.discover_in_frame(&mut nested, &group.frame, ts, to_pos);
self.register_insertion(parent.location, nested);
} else {
self.discover_in_frame(sink, &group.frame, ts, to_pos);
}
}
FrameItem::Tag(tag) => {
self.discover_in_tag(sink, tag, to_pos(pos.transform(ts)));
}
_ => {}
}
}
}
/// Handle a tag.
pub fn discover_in_tag(
&mut self,
sink: &mut Vec<Pair>,
tag: &Tag,
position: DocumentPosition,
) {
match tag {
Tag::Start(elem, flags) => {
if flags.introspectable {
let loc = elem.location().unwrap();
if self.seen.insert(loc) {
sink.push((elem.clone(), position));
}
}
}
Tag::End(loc, key, flags) => {
if flags.introspectable {
self.keys.insert(*key, *loc);
}
}
}
}
/// Saves nested pairs as logically belonging to the `parent`.
pub fn register_insertion(&mut self, parent: Location, nested: Vec<Pair>) {
self.insertions.insert(parent, nested);
}
/// Build a complete introspector with all acceleration structures from a
/// list of top-level pairs.
pub fn finalize(mut self, root: Vec<Pair>) -> Introspector {
self.locations.reserve(self.seen.len());
// Save all pairs and their descendants in the correct order.
let mut elems = Vec::with_capacity(self.seen.len());
for pair in root {
self.visit(&mut elems, pair);
}
Introspector {
pages: self.pages,
page_numberings: self.page_numberings,
page_supplements: self.page_supplements,
html_ids: self.html_ids,
elems,
keys: self.keys,
locations: self.locations,
labels: self.labels,
queries: QueryCache::default(),
}
}
/// Saves a pair and all its descendants into `elems` and populates the
/// acceleration structures.
fn visit(&mut self, elems: &mut Vec<Pair>, pair: Pair) {
let elem = &pair.0;
let loc = elem.location().unwrap();
let idx = elems.len();
// Populate the location acceleration map.
self.locations.insert(loc, idx);
// Populate the label acceleration map.
if let Some(label) = elem.label() {
self.labels.insert(label, idx);
}
// Save the element.
elems.push(pair);
// Process potential descendants.
if let Some(insertions) = self.insertions.take(&loc) {
for pair in insertions.flatten() {
self.visit(elems, pair);
}
}
}
}
/// A position in an HTML tree.
#[derive(Clone, Debug, Hash)]
pub struct HtmlPosition {
/// Indices that can be used to traverse the tree from the root.
element: EcoVec<usize>,
/// The precise position inside of the specified element.
inner: Option<InnerHtmlPosition>,
}
impl HtmlPosition {
/// A position in an HTML document pointing to a specific node as a whole.
///
/// The items of the vector corresponds to indices that can be used to
/// traverse the DOM tree from the root to reach the node. In practice, this
/// means that the first item of the vector will often be `1` for the
/// `<body>` tag (`0` being the `<head>` tag in a typical HTML document).
///
/// Consecutive text nodes in Typst's HTML representation are grouped for
/// the purpose of this indexing as the segmentation is not observable in
/// the resulting DOM.
pub fn new(element: EcoVec<usize>) -> Self {
Self { element, inner: None }
}
/// Specifies a character offset inside of the node, to build a position
/// pointing to a specific point in text.
///
/// This only makes sense if the node is a text node, not an element or a
/// frame.
///
/// The offset is expressed in codepoints, not in bytes, to be
/// encoding-independent.
pub fn at_char(self, offset: usize) -> Self {
Self {
element: self.element,
inner: Some(InnerHtmlPosition::Character(offset)),
}
}
/// Specifies a point in a frame, to build a more precise position.
///
/// This only makes sense if the node is a frame.
pub fn in_frame(self, point: Point) -> Self {
Self {
element: self.element,
inner: Some(InnerHtmlPosition::Frame(point)),
}
}
/// Extra-information for a more precise location inside of the node
/// designated by [`HtmlPosition::element`].
pub fn details(&self) -> Option<&InnerHtmlPosition> {
self.inner.as_ref()
}
/// Indices for traversing an HTML tree to reach the node corresponding to
/// this position.
///
/// See [`HtmlPosition::new`] for more details.
pub fn element(&self) -> impl Iterator<Item = &usize> {
self.element.iter()
}
}
/// A precise position inside of an HTML node.
#[derive(Clone, Debug, Hash)]
pub enum InnerHtmlPosition {
/// If the node is a frame, the coordinates of the position.
Frame(Point),
/// If the node is a text node, the index of the codepoint at the position.
Character(usize),
}
/// Physical position in a document, be it paged or HTML.
///
/// Only one variant should be used for all positions in a same document. This
/// type exists to make it possible to write functions that are generic over the
/// document target.
#[derive(Clone, Debug, Hash)]
pub enum DocumentPosition {
/// If the document is paged, the position is expressed as coordinates
/// inside of a page.
Paged(Position),
/// If the document is an HTML document, the position points to a specific
/// node in the DOM tree.
Html(HtmlPosition),
}
impl DocumentPosition {
/// Returns the paged [`Position`] if this is one.
pub fn as_paged(self) -> Option<Position> {
match self {
DocumentPosition::Paged(position) => Some(position),
_ => None,
}
}
/// Returns the paged [`Position`] or a position at page 1, point `(0, 0)`
/// if this is not a paged position.
pub fn as_paged_or_default(self) -> Position {
self.as_paged()
.unwrap_or(Position { page: NonZeroUsize::ONE, point: Point::zero() })
}
/// Returns the [`HtmlPosition`] if available.
pub fn as_html(self) -> Option<HtmlPosition> {
match self {
DocumentPosition::Html(position) => Some(position),
_ => None,
}
}
}
impl From<Position> for DocumentPosition {
fn from(value: Position) -> Self {
Self::Paged(value)
}
}
impl From<HtmlPosition> for DocumentPosition {
fn from(value: HtmlPosition) -> Self {
Self::Html(value)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/locator.rs | crates/typst-library/src/introspection/locator.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;
use std::sync::OnceLock;
use comemo::{Track, Tracked};
use rustc_hash::FxHashMap;
use typst_syntax::Span;
use crate::diag::{SourceDiagnostic, warning};
use crate::engine::Engine;
use crate::introspection::{History, Introspect, Introspector, Location};
/// Provides locations for elements in the document.
///
/// A [`Location`] is a unique ID for an element generated during realization.
///
/// # How to use this
/// The same content may yield different results when laid out in different
/// parts of the document. To reflect this, every layout operation receives a
/// locator and every layout operation requires a locator. In code:
///
/// - all layouters receive an owned `Locator`
/// - all layout functions take an owned `Locator`
///
/// When a layouter only requires a single sublayout call, it can simply pass on
/// its locator. When a layouter needs to call multiple sublayouters, we need to
/// make an explicit decision:
///
/// - Split: When we're layouting multiple distinct children (or other pieces of
/// content), we need to split up the locator with [`Locator::split`]. This
/// allows us to produce multiple new `Locator`s for the sublayouts. When we
/// split the locator, each sublocator will be a distinct entity and using it
/// to e.g. layout the same piece of figure content will yield distinctly
/// numbered figures.
///
/// - Relayout: When we're layouting the same content multiple times (e.g. when
/// measuring something), we can call [`Locator::relayout`] to use the same
/// locator multiple times. This indicates to the compiler that it's actually
/// the same content. Using it to e.g. layout the same piece of figure content
/// will yield the same figure number both times. Typically, when we layout
/// something multiple times using `relayout`, only one of the outputs
/// actually ends up in the document, while the other outputs are only used
/// for measurement and then discarded.
///
/// The `Locator` intentionally does not implement `Copy` and `Clone` so that it
/// can only be used once. This ensures that whenever we are layouting multiple
/// things, we make an explicit decision whether we want to split or relayout.
///
/// # How it works
/// There are two primary considerations for the assignment of locations:
///
/// 1. Locations should match up over multiple layout iterations, so that
/// elements can be identified as being the same: That's the whole point of
/// them.
///
/// 2. Locations should be as stable as possible across document edits, so that
/// incremental compilation is effective.
///
/// 3. We want to assign them with as little long-lived state as possible to
/// enable parallelization of the layout process.
///
/// Let's look at a few different assignment strategies to get a feeling for
/// these requirements:
///
/// - A very simple way to generate unique IDs would be to just increase a
/// counter for each element. In this setup, (1) is somewhat satisfied: In
/// principle, the counter will line up across iterations, but things start to
/// break down once we generate content dependent on introspection since the
/// IDs generated for that new content will shift the IDs for all following
/// elements in the document. (2) is not satisfied since an edit in the middle
/// of the document shifts all later IDs. (3) is obviously not satisfied.
/// Conclusion: Not great.
///
/// - To make things more robust, we can incorporate some stable knowledge about
/// the element into the ID. For this, we can use the element's span since it
/// is already mostly unique: Elements resulting from different source code
/// locations are guaranteed to have different spans. However, we can also
/// have multiple distinct elements generated from the same source location:
/// e.g. `#for _ in range(5) { figure(..) }`. To handle this case, we can then
/// disambiguate elements with the same span with an increasing counter. In
/// this setup, (1) is mostly satisfied: Unless we do stuff like generating
/// colliding counter updates dependent on introspection, things will line up.
/// (2) is also reasonably well satisfied, as typical edits will only affect
/// the single element at the currently edited span. Only if we edit inside of
/// a function, loop, or similar construct, we will affect multiple elements.
/// (3) is still a problem though, since we count up.
///
/// - What's left is to get rid of the mutable state. Note that layout is a
/// recursive process and has a tree-shaped execution graph. Thus, we can try
/// to determine an element's ID based on the path of execution taken in this
/// graph. Something like "3rd element in layer 1, 7th element in layer 2,
/// ..". This is basically the first approach, but on a per-layer basis. Thus,
/// we can again apply our trick from the second approach, and use the span +
/// disambiguation strategy on a per-layer basis: "1st element with span X in
/// layer 1, 3rd element with span Y in layer 2". The chance for a collision
/// is now pretty low and our state is wholly local to each level. So, if we
/// want to parallelize layout within a layer, we can generate the IDs for
/// that layer upfront and then start forking out. The final remaining
/// question is how we can compactly encode this information: For this, as
/// always, we use hashing! We incorporate the ID information from each layer
/// into a single hash and thanks to the collision resistance of 128-bit
/// SipHash, we get almost guaranteed unique locations. We don't even store
/// the full layer information at all, but rather hash _hierarchically:_ Let
/// `k_x` be our local per-layer ID for layer `x` and `h_x` be the full
/// combined hash for layer `x`. We compute `h_n = hash(h_(n-1), k_n)`.
///
/// So that's what's going on conceptually in this type. For efficient
/// memoization, we do all of this in a tracked fashion, such that we only
/// observe the hash for all the layers above us, if we actually need to
/// generate a [`Location`]. Thus, if we have a piece of content that does not
/// contain any locatable elements, we can cache its layout even if it occurs in
/// different places.
///
/// # Dealing with measurement
/// As explained above, any kind of measurement the compiler performs requires a
/// locator that matches the one used during real layout. This ensures that the
/// locations assigned during measurement match up exactly with the locations of
/// real document elements. Without this guarantee, many introspection-driven
/// features (like counters, state, and citations) don't work correctly (since
/// they perform queries dependent on concrete locations).
///
/// This is all fine and good, but things get really tricky when the _user_
/// measures such introspecting content since the user isn't kindly managing
/// locators for us. Our standard `Locator` workflow assigns locations that
/// depend a lot on the exact placement in the hierarchy of elements. For this
/// reason, something that is measured, but then placed into something like a
/// grid will get a location influenced by the grid. Without a locator, we can't
/// make the connection between the measured content and the real content, so we
/// can't ensure that the locations match up.
///
/// One possible way to deal with this is to force the user to uniquely identify
/// content before being measured after all. This would mean that the user needs
/// to come up with an identifier that is unique within the surrounding context
/// block and attach it to the content in some way. However, after careful
/// consideration, I have concluded that this is simply too big of an ask from
/// users: Understanding why this is even necessary is pretty complicated and
/// how to best come up with a unique ID is even more so.
///
/// For this reason, I chose an alternative best-effort approach: The locator
/// has a custom "measurement mode" (entered through [`LocatorLink::measure`]),
/// in which it does its best to assign locations that match up. Specifically,
/// it uses the key hashes of the individual locatable elements in the measured
/// content (which may not be unique if content is reused) and combines them
/// with the context's location to find the most likely matching real element.
/// This approach works correctly almost all of the time (especially for
/// "normal" hand-written content where the key hashes rarely collide, as
/// opposed to code-heavy things where they do).
///
/// Support for enhancing this with user-provided uniqueness can still be added
/// in the future. It will most likely anyway be added simply because it's
/// automatically included when we add a way to "freeze" content for things like
/// slidehows. But it will be opt-in because it's just too much complication.
pub struct Locator<'a> {
/// A local hash that incorporates all layers since the last memoization
/// boundary.
local: u128,
/// A pointer to an outer cached locator, which contributes the information
/// for all the layers beyond the memoization boundary on-demand.
outer: Option<&'a LocatorLink<'a>>,
}
impl<'a> Locator<'a> {
/// Create a new root-level locator.
///
/// Should typically only be created at the document level, though there
/// are a few places where we use it as well that just don't support
/// introspection (e.g. tilings).
pub fn root() -> Self {
Self { local: 0, outer: None }
}
/// Creates a new synthetic locator.
///
/// This can be used to create a new dependent layout based on an element.
/// This is used for layouting footnote entries based on the location
/// of the associated footnote.
pub fn synthesize(location: Location) -> Self {
Self { local: location.hash(), outer: None }
}
/// Creates a new locator that points to the given link.
pub fn link(link: &'a LocatorLink<'a>) -> Self {
Self { local: 0, outer: Some(link) }
}
}
impl<'a> Locator<'a> {
/// Returns a type that can be used to generate `Locator`s for multiple
/// child elements. See the type-level docs for more details.
pub fn split(self) -> SplitLocator<'a> {
SplitLocator {
local: self.local,
outer: self.outer,
disambiguators: FxHashMap::default(),
}
}
/// Creates a copy of this locator for measurement or relayout of the same
/// content. See the type-level docs for more details.
///
/// This is effectively just `Clone`, but the `Locator` doesn't implement
/// `Clone` to make this operation explicit.
pub fn relayout(&self) -> Self {
Self { local: self.local, outer: self.outer }
}
}
#[comemo::track]
#[allow(clippy::needless_lifetimes)]
impl<'a> Locator<'a> {
/// Resolves the locator based on its local and the outer information.
fn resolve(&self) -> Resolved {
match self.outer {
None => Resolved::Hash(self.local),
Some(outer) => match outer.resolve() {
Resolved::Hash(outer) => {
Resolved::Hash(typst_utils::hash128(&(self.local, outer)))
}
Resolved::Measure(anchor, span) => Resolved::Measure(anchor, span),
},
}
}
}
impl Debug for Locator<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Locator({:?})", self.resolve())
}
}
/// The fully resolved value of a locator.
#[derive(Debug, Copy, Clone, Hash)]
enum Resolved {
/// The full hash, incorporating the local and all outer information.
Hash(u128),
/// Indicates that the locator is in measurement mode, with the given anchor
/// location.
Measure(Location, Span),
}
/// A type that generates unique sublocators.
pub struct SplitLocator<'a> {
/// A local hash that incorporates all layers since the last memoization
/// boundary.
local: u128,
/// A pointer to an outer cached locator, which contributes the information
/// for all the layers beyond the memoization boundary on-demand.
outer: Option<&'a LocatorLink<'a>>,
/// Simply counts up the number of times we've seen each local hash.
disambiguators: FxHashMap<u128, usize>,
}
impl<'a> SplitLocator<'a> {
/// Produces a sublocator for a subtree keyed by `key`. The keys do *not*
/// need to be unique among the `next()` calls on this split locator. (They
/// can even all be `&()`.)
///
/// However, stable & mostly unique keys lead to more stable locations
/// throughout edits, improving incremental compilation performance.
///
/// A common choice for a key is the span of the content that will be
/// layouted with this locator.
pub fn next<K: Hash>(&mut self, key: &K) -> Locator<'a> {
self.next_inner(typst_utils::hash128(key))
}
/// Produces a sublocator for a subtree.
pub fn next_inner(&mut self, key: u128) -> Locator<'a> {
// Produce a locator disambiguator, for elements with the same key
// within this `SplitLocator`.
let disambiguator = {
let slot = self.disambiguators.entry(key).or_default();
std::mem::replace(slot, *slot + 1)
};
// Combine the key, disambiguator and local hash into a sub-local hash.
// The outer information is not yet merged into this, it is added
// on-demand in `Locator::resolve`.
let local = typst_utils::hash128(&(key, disambiguator, self.local));
Locator { outer: self.outer, local }
}
/// Produces a unique location for an element.
pub fn next_location(
&mut self,
engine: &mut Engine,
key: u128,
elem_span: Span,
) -> Location {
match self.next_inner(key).resolve() {
Resolved::Hash(hash) => Location::new(hash),
Resolved::Measure(anchor, measure_span) => {
let introspection =
MeasureIntrospection { key, anchor, elem_span, measure_span };
// If we aren't able to find a matching element in the document,
// default to the anchor, so that it's at least remotely in
// the right area (so that counters can be resolved).
engine.introspect(introspection).unwrap_or(anchor)
}
}
}
}
/// Tries to find the closest matching element in the document during
/// measurement.
#[derive(Debug, Clone, PartialEq, Hash)]
struct MeasureIntrospection {
key: u128,
anchor: Location,
measure_span: Span,
elem_span: Span,
}
impl Introspect for MeasureIntrospection {
type Output = Option<Location>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.locator(self.key, self.anchor)
}
fn diagnose(&self, _: &History<Self::Output>) -> SourceDiagnostic {
let mut diag = warning!(
self.measure_span, "a measured element did not stabilize";
hint: "measurement tries to resolve introspections by finding the \
closest matching elements in the real document";
);
if !self.elem_span.is_detached() {
diag.spanned_hint(
"the closest match for this element did not stabilize",
self.elem_span,
);
}
diag
}
}
/// A locator can be linked to this type to only access information across the
/// memoization boundary on-demand, improving the cache hit chance.
pub struct LocatorLink<'a> {
/// The link itself.
kind: LinkKind<'a>,
/// The cached resolved link.
resolved: OnceLock<Resolved>,
}
/// The different kinds of locator links.
enum LinkKind<'a> {
/// An outer `Locator`, which we can resolved if necessary.
///
/// We need to override the constraint's lifetime here so that `Tracked` is
/// covariant over the constraint. If it becomes invariant, we're in for a
/// world of lifetime pain.
Outer(Tracked<'a, Locator<'a>, <Locator<'static> as Track>::Call>),
/// A link which indicates that we are in measurement mode.
Measure(Location, Span),
}
impl<'a> LocatorLink<'a> {
/// Create a locator link.
pub fn new(outer: Tracked<'a, Locator<'a>>) -> Self {
LocatorLink {
kind: LinkKind::Outer(outer),
resolved: OnceLock::new(),
}
}
/// Creates a link that puts any linked downstream locator into measurement
/// mode.
///
/// Read the "Dealing with measurement" section of the [`Locator`] docs for
/// more details.
pub fn measure(anchor: Location, span: Span) -> Self {
LocatorLink {
kind: LinkKind::Measure(anchor, span),
resolved: OnceLock::new(),
}
}
/// Resolve the link.
///
/// The result is cached in this link, so that we don't traverse the link
/// chain over and over again.
fn resolve(&self) -> Resolved {
*self.resolved.get_or_init(|| match self.kind {
LinkKind::Outer(outer) => outer.resolve(),
LinkKind::Measure(anchor, span) => Resolved::Measure(anchor, span),
})
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/state.rs | crates/typst-library/src/introspection/state.rs | use comemo::{Track, Tracked, TrackedMut};
use ecow::{EcoString, EcoVec, eco_format, eco_vec};
use typst_syntax::Span;
use typst_utils::Protected;
use crate::World;
use crate::diag::{At, SourceDiagnostic, SourceResult, bail, warning};
use crate::engine::{Engine, Route, Sink, Traced};
use crate::foundations::{
Args, Construct, Content, Context, Func, LocatableSelector, NativeElement, Repr,
Selector, Str, Value, cast, elem, func, scope, select_where, ty,
};
use crate::introspection::{History, Introspect, Introspector, Locatable, Location};
use crate::routines::Routines;
/// Manages stateful parts of your document.
///
/// Let's say you have some computations in your document and want to remember
/// the result of your last computation to use it in the next one. You might try
/// something similar to the code below and expect it to output 10, 13, 26, and
/// 21. However this **does not work** in Typst. If you test this code, you will
/// see that Typst complains with the following error message: _Variables from
/// outside the function are read-only and cannot be modified._
///
/// ```typ
/// // This doesn't work!
/// #let star = 0
/// #let compute(expr) = {
/// star = eval(
/// expr.replace("⭐", str(star))
/// )
/// [New value is #star.]
/// }
///
/// #compute("10") \
/// #compute("⭐ + 3") \
/// #compute("⭐ * 2") \
/// #compute("⭐ - 5")
/// ```
///
/// # State and document markup { #state-and-markup }
/// Why does it do that? Because, in general, this kind of computation with side
/// effects is problematic in document markup and Typst is upfront about that.
/// For the results to make sense, the computation must proceed in the same
/// order in which the results will be laid out in the document. In our simple
/// example, that's the case, but in general it might not be.
///
/// Let's look at a slightly different, but similar kind of state: The heading
/// numbering. We want to increase the heading counter at each heading. Easy
/// enough, right? Just add one. Well, it's not that simple. Consider the
/// following example:
///
/// ```example
/// #set heading(numbering: "1.")
/// #let template(body) = [
/// = Outline
/// ...
/// #body
/// ]
///
/// #show: template
///
/// = Introduction
/// ...
/// ```
///
/// Here, Typst first processes the body of the document after the show rule,
/// sees the `Introduction` heading, then passes the resulting content to the
/// `template` function and only then sees the `Outline`. Just counting up would
/// number the `Introduction` with `1` and the `Outline` with `2`.
///
/// # Managing state in Typst { #state-in-typst }
/// So what do we do instead? We use Typst's state management system. Calling
/// the `state` function with an identifying string key and an optional initial
/// value gives you a state value which exposes a few functions. The two most
/// important ones are `get` and `update`:
///
/// - The [`get`]($state.get) function retrieves the current value of the state.
/// Because the value can vary over the course of the document, it is a
/// _contextual_ function that can only be used when [context]($context) is
/// available.
///
/// - The [`update`]($state.update) function modifies the state. You can give it
/// any value. If given a non-function value, it sets the state to that value.
/// If given a function, that function receives the previous state and has to
/// return the new state.
///
/// Our initial example would now look like this:
///
/// ```example
/// #let star = state("star", 0)
/// #let compute(expr) = {
/// star.update(old =>
/// eval(expr.replace("⭐", str(old)))
/// )
/// [New value is #context star.get().]
/// }
///
/// #compute("10") \
/// #compute("⭐ + 3") \
/// #compute("⭐ * 2") \
/// #compute("⭐ - 5")
/// ```
///
/// State managed by Typst is always updated in layout order, not in evaluation
/// order. The `update` method returns content and its effect occurs at the
/// position where the returned content is inserted into the document.
///
/// As a result, we can now also store some of the computations in variables,
/// but they still show the correct results:
///
/// ```example
/// >>> #let star = state("star", 0)
/// >>> #let compute(expr) = {
/// >>> star.update(old =>
/// >>> eval(expr.replace("⭐", str(old)))
/// >>> )
/// >>> [New value is #context star.get().]
/// >>> }
/// <<< ...
///
/// #let more = [
/// #compute("⭐ * 2") \
/// #compute("⭐ - 5")
/// ]
///
/// #compute("10") \
/// #compute("⭐ + 3") \
/// #more
/// ```
///
/// This example is of course a bit silly, but in practice this is often exactly
/// what you want! A good example are heading counters, which is why Typst's
/// [counting system]($counter) is very similar to its state system.
///
/// # Time Travel
/// By using Typst's state management system you also get time travel
/// capabilities! We can find out what the value of the state will be at any
/// position in the document from anywhere else. In particular, the `at` method
/// gives us the value of the state at any particular location and the `final`
/// methods gives us the value of the state at the end of the document.
///
/// ```example
/// >>> #let star = state("star", 0)
/// >>> #let compute(expr) = {
/// >>> star.update(old =>
/// >>> eval(expr.replace("⭐", str(old)))
/// >>> )
/// >>> [New value is #context star.get().]
/// >>> }
/// <<< ...
///
/// Value at `<here>` is
/// #context star.at(<here>)
///
/// #compute("10") \
/// #compute("⭐ + 3") \
/// *Here.* <here> \
/// #compute("⭐ * 2") \
/// #compute("⭐ - 5")
/// ```
///
/// # A word of caution { #caution }
/// To resolve the values of all states, Typst evaluates parts of your code
/// multiple times. However, there is no guarantee that your state manipulation
/// can actually be completely resolved.
///
/// For instance, if you generate state updates depending on the final value of
/// a state, the results might never converge. The example below illustrates
/// this. We initialize our state with `1` and then update it to its own final
/// value plus 1. So it should be `2`, but then its final value is `2`, so it
/// should be `3`, and so on. This example displays a finite value because Typst
/// simply gives up after a few attempts.
///
/// ```example
/// // This is bad!
/// #let x = state("key", 1)
/// #context x.update(x.final() + 1)
/// #context x.get()
/// ```
///
/// In general, you should try not to generate state updates from within context
/// expressions. If possible, try to express your updates as non-contextual
/// values or functions that compute the new value from the previous value.
/// Sometimes, it cannot be helped, but in those cases it is up to you to ensure
/// that the result converges.
#[ty(scope)]
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct State {
/// The key that identifies the state.
key: Str,
/// The initial value of the state.
init: Value,
}
impl State {
/// Create a new state identified by a key.
pub fn new(key: Str, init: Value) -> State {
Self { key, init }
}
/// The selector for this state's updates.
pub fn select(&self) -> Selector {
select_where!(StateUpdateElem, key => self.key.clone())
}
/// Selects all state updates.
pub fn select_any() -> Selector {
StateUpdateElem::ELEM.select()
}
}
#[scope]
impl State {
/// Create a new state identified by a key.
#[func(constructor)]
pub fn construct(
/// The key that identifies this state.
///
/// Any [updates]($state.update) to the state will be identified with
/// the string key. If you construct multiple states with the same
/// `key`, then updating any one will affect all of them.
key: Str,
/// The initial value of the state.
///
/// If you construct multiple states with the same `key` but different
/// `init` values, they will each use their own initial value but share
/// updates. Specifically, the value of a state at some location in the
/// document will be computed from that state's initial value and all
/// preceding updates for the state's key.
///
/// ```example
/// #let banana = state("key", "🍌")
/// #let broccoli = state("key", "🥦")
///
/// #banana.update(it => it + "😋")
///
/// #context [
/// - #state("key", "🍎").get()
/// - #banana.get()
/// - #broccoli.get()
/// ]
/// ```
#[default]
init: Value,
) -> State {
Self::new(key, init)
}
/// Retrieves the value of the state at the current location.
///
/// This is equivalent to `{state.at(here())}`.
#[typst_macros::time(name = "state.get", span = span)]
#[func(contextual)]
pub fn get(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Value> {
let loc = context.location().at(span)?;
engine.introspect(StateAtIntrospection(self.clone(), loc, span))
}
/// Retrieves the value of the state at the given selector's unique match.
///
/// The `selector` must match exactly one element in the document. The most
/// useful kinds of selectors for this are [labels]($label) and
/// [locations]($location).
#[typst_macros::time(name = "state.at", span = span)]
#[func(contextual)]
pub fn at(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// The place at which the state's value should be retrieved.
selector: LocatableSelector,
) -> SourceResult<Value> {
let loc = selector.resolve_unique(engine, context, span)?;
engine.introspect(StateAtIntrospection(self.clone(), loc, span))
}
/// Retrieves the value of the state at the end of the document.
#[func(contextual)]
pub fn final_(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Value> {
context.introspect().at(span)?;
engine.introspect(StateFinalIntrospection(self.clone(), span))
}
/// Updates the value of the state.
///
/// Returns an invisible piece of [content] that must be inserted into the
/// document to take effect. This invisible content tells Typst that the
/// specified update should take place wherever the content is inserted into
/// the document.
///
/// State is a part of your document and runs like a thread embedded in the
/// document content. The value of a state is the result of all state
/// updates that happened in the document up until that point.
///
/// That's why `state.update` returns an invisible sliver of content that
/// you need to return and include in the document — a state update that is
/// not "placed" in the document does not happen, and "when" it happens is
/// determined by where you place it. That's also why you need [context] to
/// read state: You need to use the current document position to know where
/// on the state's "thread" you are.
///
/// Storing a state update in a variable (e.g.
/// `{let my-update = state("key").update(c => c * 2)}`) will have no effect
/// by itself. Only once you insert the variable `[#my-update]` somewhere
/// into the document content, the update will take effect — at the position
/// where it was inserted. You can also use `[#my-update]` multiple times at
/// different positions. Then, the update will take effect multiple times as
/// well.
///
/// In contrast to [`get`]($state.get), [`at`]($state.at), and
/// [`final`]($state.final), this function does not require [context]. This
/// is because, to create the state update, we do not need to know where in
/// the document we are. We only need this information to resolve the
/// state's value.
#[func]
pub fn update(
self,
span: Span,
/// A value to update to or a function to update with.
///
/// - If given a non-function value, sets the state to that value.
/// - If given a function, that function receives the state's previous
/// value and has to return the state's new value.
///
/// When updating the state based on its previous value, you should
/// prefer the function form instead of retrieving the previous value
/// from the [context]($context). This allows the compiler to resolve
/// the final state efficiently, minimizing the number of
/// [layout iterations]($context/#compiler-iterations) required.
///
/// In the following example, `{fill.update(f => not f)}` will paint odd
/// [items in the bullet list]($list.item) as expected. However, if it's
/// replaced with `{context fill.update(not fill.get())}`, then layout
/// will not converge within 5 attempts, as each update will take one
/// additional iteration to propagate.
///
/// ```example
/// #let fill = state("fill", false)
///
/// #show list.item: it => {
/// fill.update(f => not f)
/// context {
/// set text(fill: fuchsia) if fill.get()
/// it
/// }
/// }
///
/// #lorem(5).split().map(list.item).join()
/// ```
update: StateUpdate,
) -> Content {
StateUpdateElem::new(self.key, update).pack().spanned(span)
}
}
impl Repr for State {
fn repr(&self) -> EcoString {
eco_format!("state({}, {})", self.key.repr(), self.init.repr())
}
}
/// An update to perform on a state.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum StateUpdate {
/// Set the state to the specified value.
Set(Value),
/// Apply the given function to the state.
Func(Func),
}
cast! {
StateUpdate,
v: Func => Self::Func(v),
v: Value => Self::Set(v),
}
/// Executes an update of a state.
#[elem(Construct, Locatable)]
pub struct StateUpdateElem {
/// The key that identifies the state.
#[required]
key: Str,
/// The update to perform on the state.
#[required]
#[internal]
update: StateUpdate,
}
impl Construct for StateUpdateElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
/// Retrieves a state at a specific location.
#[derive(Debug, Clone, PartialEq, Hash)]
struct StateAtIntrospection(State, Location, Span);
impl Introspect for StateAtIntrospection {
type Output = SourceResult<Value>;
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
let Self(state, loc, _) = self;
let sequence = sequence(state, engine, introspector)?;
let offset = introspector.query_count_before(&state.select(), *loc);
Ok(sequence[offset].clone())
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(&self.0, self.2, history)
}
}
/// Retrieves the final value of a state.
#[derive(Debug, Clone, PartialEq, Hash)]
struct StateFinalIntrospection(State, Span);
impl Introspect for StateFinalIntrospection {
type Output = SourceResult<Value>;
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
let sequence = sequence(&self.0, engine, introspector)?;
Ok(sequence.last().unwrap().clone())
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(&self.0, self.1, history)
}
}
/// Produces the whole sequence of a state.
///
/// Due to memoization, this has to happen just once for all retrievals of the
/// same state, cutting down the number of computations from quadratic to
/// linear.
fn sequence(
state: &State,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> SourceResult<EcoVec<Value>> {
sequence_impl(
state,
engine.routines,
engine.world,
introspector,
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
)
}
/// Memoized implementation of `sequence`.
#[comemo::memoize]
fn sequence_impl(
state: &State,
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
) -> SourceResult<EcoVec<Value>> {
let mut engine = Engine {
routines,
world,
introspector: Protected::from_raw(introspector),
traced,
sink,
route: Route::extend(route).unnested(),
};
let mut current = state.init.clone();
let mut stops = eco_vec![current.clone()];
for elem in introspector.query(&state.select()) {
let elem = elem.to_packed::<StateUpdateElem>().unwrap();
match &elem.update {
StateUpdate::Set(value) => current = value.clone(),
StateUpdate::Func(func) => {
current = func.call(&mut engine, Context::none().track(), [current])?
}
}
stops.push(current.clone());
}
Ok(stops)
}
/// The warning when a state failed to converge.
fn format_convergence_warning(
state: &State,
span: Span,
history: &History<SourceResult<Value>>,
) -> SourceDiagnostic {
warning!(span, "value of `state({})` did not converge", state.key.repr())
.with_hint(history.hint("values", |ret| match ret {
Ok(v) => eco_format!("`{}`", v.repr()),
Err(_) => "(errored)".into(),
}))
.with_hint("see https://typst.app/help/state-convergence for help")
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/convergence.rs | crates/typst-library/src/introspection/convergence.rs | use std::any::{Any, TypeId};
use std::fmt::{Debug, Write};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use comemo::{Track, Tracked};
use ecow::{EcoString, EcoVec, eco_format};
use typst_syntax::Span;
use typst_utils::Protected;
use crate::World;
use crate::diag::{SourceDiagnostic, warning};
use crate::engine::{Engine, Route, Sink, Traced};
use crate::introspection::Introspector;
use crate::routines::Routines;
pub const MAX_ITERS: usize = 5;
pub const ITER_NAMES: &[&str] =
&["iter (1)", "iter (2)", "iter (3)", "iter (4)", "iter (5)"];
const INSTANCES: usize = MAX_ITERS + 1;
/// Analyzes all introspections that were performed during compilation and
/// produces non-convergence diagnostics.
#[typst_macros::time(name = "analyze introspections")]
pub fn analyze(
world: Tracked<dyn World + '_>,
routines: &Routines,
introspectors: [&Introspector; INSTANCES],
introspections: &[Introspection],
) -> EcoVec<SourceDiagnostic> {
let mut sink = Sink::new();
for introspection in introspections {
if let Some(warning) = introspection.0.diagnose(world, routines, introspectors) {
sink.warn(warning);
}
}
// Let's say you want to write some code that depends on the presence of an
// element in the document. You could (1) use the `QueryIntrospection` and
// then do your emptyness check afterwards or you could (2) write a new
// [introspection](Introspect) that queries internally and returns a
// boolean.
//
// In case (1), the introspection observes the same data as comemo. Thus,
// the introspection will have converged if and only if comemo validation
// also passed.
//
// However, in case (2) the introspection is filtering out data that comemo
// did observe. Thus, the validation may fail but the document actually did
// converge! In this case, we reach `analyze` (because comemo validation
// failed), but we get zero diagnostics. In this case, we do _not_ issue the
// convergence warning, since the document did in fact converge.
//
// Note that we could also entirely decouple convergence checks from comemo.
// However, it's nice to have as a fast path as the comemo checks are more
// lightweight.
let mut diags = sink.warnings();
if !diags.is_empty() {
let summary = warning!(
Span::detached(),
"document did not converge within five attempts";
hint: "see {} additional warning{} for more details",
diags.len(),
if diags.len() > 1 { "s" } else { "" };
hint: "see https://typst.app/help/convergence for help";
);
diags.insert(0, summary);
}
diags
}
/// An inquiry for retrieving a piece of information from the document.
///
/// This includes queries, counter retrievals, and various other things that can
/// be observed on a finished document.
///
/// Document iteration N+1 observes the `Output` values from the document built
/// by iteration N. If the output values do not stabilize by the iteration
/// limit, a non-convergence warning will be created via
/// [`diagnose`](Self::diagnose).
///
/// Some introspections directly map to functions on the introspector while
/// others are more high-level. To decide between these two options, think about
/// how you want a non-convergence diagnostic to look. If the diagnostic for the
/// generic introspection (e.g. `QueryIntrospection`) is sufficiently clear, you
/// can use that one directly. If you'd rather fine-tune the diagnostic for
/// non-convergence, create a new introspection.
///
/// A good example of this are counters and state: They could just use
/// `QueryIntrospection`, but are custom introspections so that the diagnostics
/// can expose non-convergence in a way that's closer to what the user operates
/// with.
pub trait Introspect: Debug + PartialEq + Hash + Send + Sync + Sized + 'static {
/// The kind of output the introspection produces. This is what should
/// stabilize.
///
/// Note that how much information you have in the output may affect
/// convergence behavior. For instance, if you reduce down the result of a
/// query introspection to a boolean specifying whether the query yielded at
/// least one element, this may converge one iteration sooner than a raw
/// query would have (even if you always reduce the query to the same bool
/// externally).
///
/// Thus, it matters whether this reduction is performed as part of the
/// introspection or externally. This is similar to how `location.page()`
/// may converge one iteration sooner than `location.position().page`.
/// Consider this example:
///
/// ```typ
/// #switch(n => if n == 5 {
/// v(1cm)
/// _ = locate(heading).page()
/// })
/// = Heading
/// ```
///
/// Both will always result in the same output, but observing the X/Y
/// position may end up requiring one extra iteration and if this happens
/// exactly at the limit of five iterations, the warning may appear (without
/// any effect on the document, which did actually converge).
///
/// In theory, we could detect this scenario by compiling one more time and
/// ensuring the document is _exactly_ the same. For now, we're not doing
/// this, but it's an option.
type Output: Hash;
/// Resolves the output value.
///
/// Will primarily use the `introspector`, but is passed the full engine in
/// case user functions need to be called (as is the case for counters).
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output;
/// Produces a diagnostic for non-convergence given the history of its
/// output values.
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic;
}
/// A type-erased representation of an [introspection](Introspect) that was
/// recorded during compilation.
#[derive(Debug, Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)]
pub struct Introspection(Arc<dyn Bounds>);
impl Introspection {
/// Type erase a strongly-typed introspection.
pub fn new<I>(inner: I) -> Self
where
I: Introspect,
{
Self(Arc::new(inner))
}
}
impl PartialEq for Introspection {
fn eq(&self, other: &Self) -> bool {
self.0.dyn_eq(other)
}
}
trait Bounds: Debug + Send + Sync + Any + 'static {
fn diagnose(
&self,
world: Tracked<dyn World + '_>,
routines: &Routines,
introspectors: [&Introspector; INSTANCES],
) -> Option<SourceDiagnostic>;
fn dyn_eq(&self, other: &Introspection) -> bool;
fn dyn_hash(&self, state: &mut dyn Hasher);
}
impl<T> Bounds for T
where
T: Introspect,
{
fn diagnose(
&self,
world: Tracked<dyn World + '_>,
routines: &Routines,
introspectors: [&Introspector; INSTANCES],
) -> Option<SourceDiagnostic> {
let history =
History::compute(world, routines, introspectors, |engine, introspector| {
self.introspect(engine, introspector)
});
(!history.converged()).then(|| self.diagnose(&history))
}
fn dyn_eq(&self, other: &Introspection) -> bool {
let inner: &dyn Bounds = &*other.0;
let Some(other) = (inner as &dyn Any).downcast_ref::<Self>() else {
return false;
};
self == other
}
fn dyn_hash(&self, mut state: &mut dyn Hasher) {
// Also hash the TypeId since introspections with different types but
// equal data should be different.
TypeId::of::<Self>().hash(&mut state);
self.hash(&mut state);
}
}
impl Hash for dyn Bounds {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.dyn_hash(state);
}
}
/// A history of values that were observed throughout iterations, alongside the
/// introspectors they were observed for.
pub struct History<'a, T>([(&'a Introspector, T); INSTANCES]);
impl<'a, T> History<'a, T> {
/// Computes the value for each introspector with an ad-hoc engine.
fn compute(
world: Tracked<dyn World + '_>,
routines: &Routines,
introspectors: [&'a Introspector; INSTANCES],
f: impl Fn(&mut Engine, Tracked<'a, Introspector>) -> T,
) -> Self {
Self(introspectors.map(|introspector| {
let tracked = introspector.track();
let traced = Traced::default();
let mut sink = Sink::new();
let mut engine = Engine {
world,
introspector: Protected::new(tracked),
traced: traced.track(),
sink: sink.track_mut(),
route: Route::default(),
routines,
};
(introspector, f(&mut engine, tracked))
}))
}
/// Whether the values in this history converged, i.e. the final and
/// pre-final values are the same.
pub fn converged(&self) -> bool
where
T: Hash,
{
// We compare by hash because the values should be fully the same, i.e.
// with no observable difference. When a state changes from `0.0`
// (float) to `0` (int), that could be observed in the next iteration
// and should not count as converged.
typst_utils::hash128(&self.0[MAX_ITERS - 1].1)
== typst_utils::hash128(&self.0[MAX_ITERS].1)
}
/// Transforms the contained values with `f`.
pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> History<'a, U> {
History(self.0.map(move |(i, t)| (i, f(t))))
}
/// Takes a reference to the contained values.
pub fn as_ref(&self) -> History<'a, &T> {
History(self.0.each_ref().map(|(i, t)| (*i, t)))
}
/// Accesses the final iteration's introspector.
pub fn final_introspector(&self) -> &'a Introspector {
self.0[MAX_ITERS].0
}
/// Produces a hint with the observed values for each iteration.
pub fn hint(&self, what: &str, mut f: impl FnMut(&T) -> EcoString) -> EcoString {
let mut hint = eco_format!("the following {what} were observed:");
for (i, (_, val)) in self.0.iter().enumerate() {
let attempt = match i {
0..MAX_ITERS => eco_format!("run {}", i + 1),
MAX_ITERS => eco_format!("final"),
_ => panic!(),
};
let output = f(val);
write!(hint, "\n- {attempt}: {output}").unwrap();
}
hint
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/here.rs | crates/typst-library/src/introspection/here.rs | use comemo::Tracked;
use crate::diag::HintedStrResult;
use crate::foundations::{Context, func};
use crate::introspection::Location;
/// Provides the current location in the document.
///
/// You can think of `here` as a low-level building block that directly extracts
/// the current location from the active [context]. Some other functions use it
/// internally: For instance, `{counter.get()}` is equivalent to
/// `{counter.at(here())}`.
///
/// Within show rules on [locatable]($location/#locatable) elements, `{here()}`
/// will match the location of the shown element.
///
/// If you want to display the current page number, refer to the documentation
/// of the [`counter`] type. While `here` can be used to determine the physical
/// page number, typically you want the logical page number that may, for
/// instance, have been reset after a preface.
///
/// # Examples
/// Determining the current position in the document in combination with the
/// [`position`]($location.position) method:
/// ```example
/// #context [
/// I am located at
/// #here().position()
/// ]
/// ```
///
/// Running a [query] for elements before the current position:
/// ```example
/// = Introduction
/// = Background
///
/// There are
/// #context query(
/// selector(heading).before(here())
/// ).len()
/// headings before me.
///
/// = Conclusion
/// ```
/// Refer to the [`selector`] type for more details on before/after selectors.
#[func(contextual)]
pub fn here(context: Tracked<Context>) -> HintedStrResult<Location> {
context.location()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/locate.rs | crates/typst-library/src/introspection/locate.rs | use comemo::Tracked;
use typst_syntax::Span;
use crate::diag::SourceResult;
use crate::engine::Engine;
use crate::foundations::{Context, LocatableSelector, func};
use crate::introspection::Location;
/// Determines the location of an element in the document.
///
/// Takes a selector that must match exactly one element and returns that
/// element's [`location`]. This location can, in particular, be used to
/// retrieve the physical [`page`]($location.page) number and
/// [`position`]($location.position) (page, x, y) for that element.
///
/// # Examples
/// Locating a specific element:
/// ```example
/// #context [
/// Introduction is at: \
/// #locate(<intro>).position()
/// ]
///
/// = Introduction <intro>
/// ```
#[func(contextual)]
pub fn locate(
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// A selector that should match exactly one element. This element will be
/// located.
///
/// Especially useful in combination with
/// - [`here`] to locate the current context,
/// - a [`location`] retrieved from some queried element via the
/// [`location()`]($content.location) method on content.
selector: LocatableSelector,
) -> SourceResult<Location> {
selector.resolve_unique(engine, context, span)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/mod.rs | crates/typst-library/src/introspection/mod.rs | //! Interaction between document parts.
mod convergence;
mod counter;
#[path = "here.rs"]
mod here_;
mod introspector;
#[path = "locate.rs"]
mod locate_;
mod location;
mod locator;
mod metadata;
#[path = "query.rs"]
mod query_;
mod state;
mod tag;
pub use self::convergence::*;
pub use self::counter::*;
pub use self::here_::*;
pub use self::introspector::*;
pub use self::locate_::*;
pub use self::location::*;
pub use self::locator::*;
pub use self::metadata::*;
pub use self::query_::*;
pub use self::state::*;
pub use self::tag::*;
use crate::foundations::Scope;
/// Hook up all `introspection` definitions.
pub fn define(global: &mut Scope) {
global.start_category(crate::Category::Introspection);
global.define_type::<Location>();
global.define_type::<Counter>();
global.define_type::<State>();
global.define_elem::<MetadataElem>();
global.define_func::<here>();
global.define_func::<query>();
global.define_func::<locate>();
global.reset_category();
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/location.rs | crates/typst-library/src/introspection/location.rs | use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize;
use comemo::Tracked;
use ecow::{EcoString, eco_format};
use typst_syntax::Span;
use crate::diag::{SourceDiagnostic, warning};
use crate::engine::Engine;
use crate::foundations::{Content, IntoValue, Repr, Selector, func, repr, scope, ty};
use crate::introspection::{History, Introspect, Introspector};
use crate::layout::{Abs, Position};
use crate::model::Numbering;
/// Makes an element available in the introspector.
pub trait Locatable {}
/// Marks an element as not queriable for the user.
pub trait Unqueriable: Locatable {}
/// Marks an element as tagged in PDF files.
pub trait Tagged {}
/// Identifies an element in the document.
///
/// A location uniquely identifies an element in the document and lets you
/// access its absolute position on the pages. You can retrieve the current
/// location with the [`here`] function and the location of a queried or shown
/// element with the [`location()`]($content.location) method on content.
///
/// # Locatable elements { #locatable }
/// Elements that are automatically assigned a location are called _locatable._
/// For efficiency reasons, not all elements are locatable.
///
/// - In the [Model category]($category/model), most elements are locatable.
/// This is because semantic elements like [headings]($heading) and
/// [figures]($figure) are often used with introspection.
///
/// - In the [Text category]($category/text), the [`raw`] element, and the
/// decoration elements [`underline`], [`overline`], [`strike`], and
/// [`highlight`] are locatable as these are also quite semantic in nature.
///
/// - In the [Introspection category]($category/introspection), the [`metadata`]
/// element is locatable as being queried for is its primary purpose.
///
/// - In the other categories, most elements are not locatable. Exceptions are
/// [`math.equation`] and [`image`].
///
/// To find out whether a specific element is locatable, you can try to
/// [`query`] for it.
///
/// Note that you can still observe elements that are not locatable in queries
/// through other means, for instance, when they have a label attached to them.
#[ty(scope)]
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Location(u128);
impl Location {
/// Create a new location from a unique hash.
pub fn new(hash: u128) -> Self {
Self(hash)
}
/// Extract the raw hash.
pub fn hash(self) -> u128 {
self.0
}
/// Produces a well-known variant of this location.
///
/// This is a synthetic location created from another one and is used, for
/// example, in bibliography management to create individual linkable
/// locations for reference entries from the bibliography's location.
pub fn variant(self, n: usize) -> Self {
Self(typst_utils::hash128(&(self.0, n)))
}
}
#[scope]
impl Location {
/// Returns the page number for this location.
///
/// Note that this does not return the value of the [page counter]($counter)
/// at this location, but the true page number (starting from one).
///
/// If you want to know the value of the page counter, use
/// `{counter(page).at(loc)}` instead.
///
/// Can be used with [`here`] to retrieve the physical page position
/// of the current context:
/// ```example
/// #context [
/// I am located on
/// page #here().page()
/// ]
/// ```
#[func]
pub fn page(self, engine: &mut Engine, span: Span) -> NonZeroUsize {
engine.introspect(PageIntrospection(self, span))
}
/// Returns a dictionary with the page number and the x, y position for this
/// location. The page number starts at one and the coordinates are measured
/// from the top-left of the page.
///
/// If you only need the page number, use `page()` instead as it allows
/// Typst to skip unnecessary work.
#[func]
pub fn position(self, engine: &mut Engine, span: Span) -> Position {
engine.introspect(PositionIntrospection(self, span))
}
/// Returns the page numbering pattern of the page at this location. This
/// can be used when displaying the page counter in order to obtain the
/// local numbering. This is useful if you are building custom indices or
/// outlines.
///
/// If the page numbering is set to `{none}` at that location, this function
/// returns `{none}`.
#[func]
pub fn page_numbering(self, engine: &mut Engine, span: Span) -> Option<Numbering> {
engine.introspect(PageNumberingIntrospection(self, span))
}
}
impl Debug for Location {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if f.alternate() {
write!(f, "Location({})", self.0)
} else {
// Print a shorter version by default to make it more readable.
let truncated = self.0 as u16;
write!(f, "Location({truncated})")
}
}
}
impl Repr for Location {
fn repr(&self) -> EcoString {
"location(..)".into()
}
}
/// Can be used to have a location as a key in an ordered set or map.
///
/// [`Location`] itself does not implement [`Ord`] because comparing hashes like
/// this has no semantic meaning. The potential for misuse (e.g. checking
/// whether locations have a particular relative ordering) is relatively high.
///
/// Still, it can be useful to have orderable locations for things like sets.
/// That's where this type comes in.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct LocationKey(u128);
impl LocationKey {
/// Create a location key from a location.
pub fn new(location: Location) -> Self {
Self(location.0)
}
}
impl From<Location> for LocationKey {
fn from(location: Location) -> Self {
Self::new(location)
}
}
/// Retrieves the exact position of an element in the document.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct PositionIntrospection(pub Location, pub Span);
impl Introspect for PositionIntrospection {
type Output = Position;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.position(self.0).as_paged_or_default()
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(
self.0,
self.1,
history,
"positions",
|element| eco_format!("{element} position"),
|pos| {
let coord = |v: Abs| repr::format_float(v.to_pt(), Some(0), false, "pt");
eco_format!(
"page {} at ({}, {})",
pos.page,
coord(pos.point.x),
coord(pos.point.y)
)
},
)
}
}
/// Retrieves the number of the page where an element is located.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct PageIntrospection(pub Location, pub Span);
impl Introspect for PageIntrospection {
type Output = NonZeroUsize;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.page(self.0)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(
self.0,
self.1,
history,
"page numbers",
|element| eco_format!("page number of the {element}"),
|n| eco_format!("page {n}"),
)
}
}
/// Retrieves the numbering of the page where an element is located.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct PageNumberingIntrospection(pub Location, pub Span);
impl Introspect for PageNumberingIntrospection {
type Output = Option<Numbering>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.page_numbering(self.0).cloned()
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(
self.0,
self.1,
history,
"numberings",
|element| {
eco_format!("numbering of the page on which the {element} is located")
},
|numbering| eco_format!("`{}`", numbering.clone().into_value().repr()),
)
}
}
/// Retrieves the supplement of the page where an element is located.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct PageSupplementIntrospection(pub Location, pub Span);
impl Introspect for PageSupplementIntrospection {
type Output = Content;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.page_supplement(self.0)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(
self.0,
self.1,
history,
"supplements",
|element| {
eco_format!("supplement of the page on which the {element} is located")
},
|supplement| eco_format!("`{}`", supplement.repr()),
)
}
}
/// The warning when an introspection on a [`Location`] did not converge.
fn format_convergence_warning<T>(
loc: Location,
span: Span,
history: &History<T>,
output_kind_plural: &str,
format_output_kind: impl FnOnce(&str) -> EcoString,
format_output: impl FnMut(&T) -> EcoString,
) -> SourceDiagnostic {
let elem = history.final_introspector().query_first(&Selector::Location(loc));
let kind = match &elem {
Some(content) => content.elem().name(),
None => "element",
};
let what = format_output_kind(kind);
let mut diag = warning!(span, "{what} did not stabilize");
if let Some(elem) = elem
&& !elem.span().is_detached()
{
diag.spanned_hint(eco_format!("{kind} was created here"), elem.span());
}
diag.with_hint(history.hint(output_kind_plural, format_output))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/query.rs | crates/typst-library/src/introspection/query.rs | use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_format};
use typst_syntax::Span;
use super::{History, Introspect};
use crate::diag::{HintedStrResult, SourceDiagnostic, StrResult, warning};
use crate::engine::Engine;
use crate::foundations::{
Array, Content, Context, Label, LocatableSelector, Repr, Selector, Value, func,
};
use crate::introspection::Introspector;
/// Finds elements in the document.
///
/// The `query` function lets you search your document for elements of a
/// particular type or with a particular label. To use it, you first need to
/// ensure that [context] is available.
///
/// # Finding elements
/// In the example below, we manually create a table of contents instead of
/// using the [`outline`] function.
///
/// To do this, we first query for all headings in the document at level 1 and
/// where `outlined` is true. Querying only for headings at level 1 ensures
/// that, for the purpose of this example, sub-headings are not included in the
/// table of contents. The `outlined` field is used to exclude the "Table of
/// Contents" heading itself.
///
/// Note that we open a `context` to be able to use the `query` function.
///
/// ```example
/// >>> #set page(
/// >>> width: 240pt,
/// >>> height: 180pt,
/// >>> margin: (top: 20pt, bottom: 35pt)
/// >>> )
/// #set page(numbering: "1")
///
/// #heading(outlined: false)[
/// Table of Contents
/// ]
/// #context {
/// let chapters = query(
/// heading.where(
/// level: 1,
/// outlined: true,
/// )
/// )
/// for chapter in chapters {
/// let loc = chapter.location()
/// let nr = counter(page).display(at: loc)
/// [#chapter.body #h(1fr) #nr \ ]
/// }
/// }
///
/// = Introduction
/// #lorem(10)
/// #pagebreak()
///
/// == Sub-Heading
/// #lorem(8)
///
/// = Discussion
/// #lorem(18)
/// ```
///
/// To get the page numbers, we first get the location of the elements returned
/// by `query` with [`location`]($content.location). We then also retrieve the
/// [page numbering]($location.page-numbering) and [page
/// counter]($counter/#page-counter) at that location and apply the numbering to
/// the counter.
///
/// # A word of caution { #caution }
/// To resolve all your queries, Typst evaluates and layouts parts of the
/// document multiple times. However, there is no guarantee that your queries
/// can actually be completely resolved. If you aren't careful a query can
/// affect itself—leading to a result that never stabilizes.
///
/// In the example below, we query for all headings in the document. We then
/// generate as many headings. In the beginning, there's just one heading,
/// titled `Real`. Thus, `count` is `1` and one `Fake` heading is generated.
/// Typst sees that the query's result has changed and processes it again. This
/// time, `count` is `2` and two `Fake` headings are generated. This goes on and
/// on. As we can see, the output has a finite amount of headings. This is
/// because Typst simply gives up after a few attempts.
///
/// In general, you should try not to write queries that affect themselves. The
/// same words of caution also apply to other introspection features like
/// [counters]($counter) and [state].
///
/// ```example
/// = Real
/// #context {
/// let elems = query(heading)
/// let count = elems.len()
/// count * [= Fake]
/// }
/// ```
///
/// # Command line queries
/// You can also perform queries from the command line with the `typst query`
/// command. This command executes an arbitrary query on the document and
/// returns the resulting elements in serialized form. Consider the following
/// `example.typ` file which contains some invisible [metadata]:
///
/// ```typ
/// #metadata("This is a note") <note>
/// ```
///
/// You can execute a query on it as follows using Typst's CLI:
/// ```sh
/// $ typst query example.typ "<note>"
/// [
/// {
/// "func": "metadata",
/// "value": "This is a note",
/// "label": "<note>"
/// }
/// ]
/// ```
///
/// ## Retrieving a specific field
///
/// Frequently, you're interested in only one specific field of the resulting
/// elements. In the case of the `metadata` element, the `value` field is the
/// interesting one. You can extract just this field with the `--field`
/// argument.
///
/// ```sh
/// $ typst query example.typ "<note>" --field value
/// ["This is a note"]
/// ```
///
/// If you are interested in just a single element, you can use the `--one`
/// flag to extract just it.
///
/// ```sh
/// $ typst query example.typ "<note>" --field value --one
/// "This is a note"
/// ```
///
/// ## Querying for a specific export target
///
/// In case you need to query a document when exporting for a specific target,
/// you can use the `--target` argument. Valid values are `paged`, and `html`
/// (if the [`html`] feature is enabled).
#[func(contextual)]
pub fn query(
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// Can be
/// - an element function like a `heading` or `figure`,
/// - a `{<label>}`,
/// - a more complex selector like `{heading.where(level: 1)}`,
/// - or `{selector(heading).before(here())}`.
///
/// Only [locatable]($location/#locatable) element functions are supported.
target: LocatableSelector,
) -> HintedStrResult<Array> {
context.introspect()?;
let vec = engine.introspect(QueryIntrospection(target.0, span));
Ok(vec.into_iter().map(Value::Content).collect())
}
/// Retrieves all matches of a selector in the document.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct QueryIntrospection(pub Selector, pub Span);
impl Introspect for QueryIntrospection {
type Output = EcoVec<Content>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.query(&self.0)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
let lengths = history.as_ref().map(|vec| vec.len());
let things = format_selector(&self.0, "elements");
let what = if !lengths.converged() {
eco_format!("number of {things}")
} else {
eco_format!("query for {things}")
};
format_convergence_warning(self.1, &lengths, &what)
}
}
/// Retrieves the first match of a selector in the document.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct QueryFirstIntrospection(pub Selector, pub Span);
impl Introspect for QueryFirstIntrospection {
type Output = Option<Content>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.query_first(&self.0)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
let lengths = history.as_ref().map(|vec| vec.is_some() as usize);
let thing = format_selector(&self.0, "element");
let what = eco_format!("query for the first {thing}");
format_convergence_warning(self.1, &lengths, &what)
}
}
/// Retrieves the only match of a selector in the document.
///
/// Fails if there are multiple occurrences.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct QueryUniqueIntrospection(pub Selector, pub Span);
impl Introspect for QueryUniqueIntrospection {
type Output = StrResult<Content>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.query_unique(&self.0)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
let lengths = history.as_ref().map(|vec| vec.is_ok() as usize);
let thing = format_selector(&self.0, "element");
let what = eco_format!("query for a unique {thing}");
format_convergence_warning(self.1, &lengths, &what)
}
}
/// Retrieves the only occurrence of a label in the document.
///
/// Fails if there are multiple occurrences.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct QueryLabelIntrospection(pub Label, pub Span);
impl Introspect for QueryLabelIntrospection {
type Output = StrResult<Content>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.query_label(self.0).cloned()
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
QueryUniqueIntrospection(Selector::Label(self.0), self.1).diagnose(history)
}
}
/// The warning when an introspection on a [`Location`] did not converge.
fn format_convergence_warning(
span: Span,
lengths: &History<usize>,
what: &str,
) -> SourceDiagnostic {
let mut diag = warning!(span, "{what} did not stabilize");
if !lengths.converged() {
diag.hint(lengths.hint("numbers of elements", |c| eco_format!("{c}")));
}
diag
}
/// Formats a selector human-readably.
fn format_selector(selector: &Selector, kind: &str) -> EcoString {
match selector {
Selector::Elem(elem, None) => eco_format!("{} {kind}", elem.name()),
Selector::Elem(elem, _) => eco_format!("matching {} {kind}", elem.name()),
Selector::Label(label) => eco_format!("{kind} labelled `{}`", label.repr()),
other => eco_format!("{kind} matching `{}`", other.repr()),
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/counter.rs | crates/typst-library/src/introspection/counter.rs | use std::fmt::Write;
use std::num::NonZeroUsize;
use std::str::FromStr;
use comemo::{Track, Tracked, TrackedMut};
use ecow::{EcoString, EcoVec, eco_format, eco_vec};
use smallvec::{SmallVec, smallvec};
use typst_syntax::Span;
use typst_utils::{NonZeroExt, Protected};
use crate::World;
use crate::diag::{At, HintedStrResult, SourceDiagnostic, SourceResult, bail, warning};
use crate::engine::{Engine, Route, Sink, Traced};
use crate::foundations::{
Args, Array, Construct, Content, Context, Element, Func, IntoValue, Label,
LocatableSelector, NativeElement, Packed, Repr, Selector, ShowFn, Smart, Str,
StyleChain, Value, cast, elem, func, scope, select_where, ty,
};
use crate::introspection::{
History, Introspect, Introspector, Locatable, Location, QueryFirstIntrospection, Tag,
Unqueriable,
};
use crate::layout::{Frame, FrameItem, PageElem};
use crate::math::EquationElem;
use crate::model::{FigureElem, FootnoteElem, HeadingElem, Numbering, NumberingPattern};
use crate::routines::Routines;
/// Counts through pages, elements, and more.
///
/// With the counter function, you can access and modify counters for pages,
/// headings, figures, and more. Moreover, you can define custom counters for
/// other things you want to count.
///
/// Since counters change throughout the course of the document, their current
/// value is _contextual._ It is recommended to read the chapter on [context]
/// before continuing here.
///
/// # Accessing a counter { #accessing }
/// To access the raw value of a counter, we can use the [`get`]($counter.get)
/// function. This function returns an [array]: Counters can have multiple
/// levels (in the case of headings for sections, subsections, and so on), and
/// each item in the array corresponds to one level.
///
/// ```example
/// #set heading(numbering: "1.")
///
/// = Introduction
/// Raw value of heading counter is
/// #context counter(heading).get()
/// ```
///
/// # Displaying a counter { #displaying }
/// Often, we want to display the value of a counter in a more human-readable
/// way. To do that, we can call the [`display`]($counter.display) function on
/// the counter. This function retrieves the current counter value and formats
/// it either with a provided or with an automatically inferred [numbering].
///
/// ```example
/// #set heading(numbering: "1.")
///
/// = Introduction
/// Some text here.
///
/// = Background
/// The current value is: #context {
/// counter(heading).display()
/// }
///
/// Or in roman numerals: #context {
/// counter(heading).display("I")
/// }
/// ```
///
/// # Modifying a counter { #modifying }
/// To modify a counter, you can use the `step` and `update` methods:
///
/// - The `step` method increases the value of the counter by one. Because
/// counters can have multiple levels , it optionally takes a `level`
/// argument. If given, the counter steps at the given depth.
///
/// - The `update` method allows you to arbitrarily modify the counter. In its
/// basic form, you give it an integer (or an array for multiple levels). For
/// more flexibility, you can instead also give it a function that receives
/// the current value and returns a new value.
///
/// The heading counter is stepped before the heading is displayed, so
/// `Analysis` gets the number seven even though the counter is at six after the
/// second update.
///
/// ```example
/// #set heading(numbering: "1.")
///
/// = Introduction
/// #counter(heading).step()
///
/// = Background
/// #counter(heading).update(3)
/// #counter(heading).update(n => n * 2)
///
/// = Analysis
/// Let's skip 7.1.
/// #counter(heading).step(level: 2)
///
/// == Analysis
/// Still at #context {
/// counter(heading).display()
/// }
/// ```
///
/// # Page counter
/// The page counter is special. It is automatically stepped at each pagebreak.
/// But like other counters, you can also step it manually. For example, you
/// could have Roman page numbers for your preface, then switch to Arabic page
/// numbers for your main content and reset the page counter to one.
///
/// ```example
/// >>> #set page(
/// >>> height: 100pt,
/// >>> margin: (bottom: 24pt, rest: 16pt),
/// >>> )
/// #set page(numbering: "(i)")
///
/// = Preface
/// The preface is numbered with
/// roman numerals.
///
/// #set page(numbering: "1 / 1")
/// #counter(page).update(1)
///
/// = Main text
/// Here, the counter is reset to one.
/// We also display both the current
/// page and total number of pages in
/// Arabic numbers.
/// ```
///
/// # Custom counters
/// To define your own counter, call the `counter` function with a string as a
/// key. This key identifies the counter globally.
///
/// ```example
/// #let mine = counter("mycounter")
/// #context mine.display() \
/// #mine.step()
/// #context mine.display() \
/// #mine.update(c => c * 3)
/// #context mine.display()
/// ```
///
/// # How to step
/// When you define and use a custom counter, in general, you should first step
/// the counter and then display it. This way, the stepping behaviour of a
/// counter can depend on the element it is stepped for. If you were writing a
/// counter for, let's say, theorems, your theorem's definition would thus first
/// include the counter step and only then display the counter and the theorem's
/// contents.
///
/// ```example
/// #let c = counter("theorem")
/// #let theorem(it) = block[
/// #c.step()
/// *Theorem #context c.display():*
/// #it
/// ]
///
/// #theorem[$1 = 1$]
/// #theorem[$2 < 3$]
/// ```
///
/// The rationale behind this is best explained on the example of the heading
/// counter: An update to the heading counter depends on the heading's level. By
/// stepping directly before the heading, we can correctly step from `1` to
/// `1.1` when encountering a level 2 heading. If we were to step after the
/// heading, we wouldn't know what to step to.
///
/// Because counters should always be stepped before the elements they count,
/// they always start at zero. This way, they are at one for the first display
/// (which happens after the first step).
///
/// # Time travel
/// Counters can travel through time! You can find out the final value of the
/// counter before it is reached and even determine what the value was at any
/// particular location in the document.
///
/// ```example
/// #let mine = counter("mycounter")
///
/// = Values
/// #context [
/// Value here: #mine.get() \
/// At intro: #mine.at(<intro>) \
/// Final value: #mine.final()
/// ]
///
/// #mine.update(n => n + 3)
///
/// = Introduction <intro>
/// #lorem(10)
///
/// #mine.step()
/// #mine.step()
/// ```
///
/// # Other kinds of state { #other-state }
/// The `counter` type is closely related to [state] type. Read its
/// documentation for more details on state management in Typst and why it
/// doesn't just use normal variables for counters.
#[ty(scope)]
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Counter(CounterKey);
impl Counter {
/// Create a new counter identified by a key.
pub fn new(key: CounterKey) -> Counter {
Self(key)
}
/// The counter for the given element.
pub fn of(func: Element) -> Self {
Self::new(CounterKey::Selector(Selector::Elem(func, None)))
}
/// Selects all state updates.
pub fn select_any() -> Selector {
CounterUpdateElem::ELEM.select()
}
/// The selector relevant for this counter's updates.
pub fn select(&self) -> Selector {
let mut selector = select_where!(CounterUpdateElem, key => self.0.clone());
if let CounterKey::Selector(key) = &self.0 {
selector = Selector::Or(eco_vec![selector, key.clone()]);
}
selector
}
/// Whether this is the page counter.
pub fn is_page(&self) -> bool {
self.0 == CounterKey::Page
}
/// Displays the value of the counter at the given location.
pub fn display_at(
&self,
engine: &mut Engine,
loc: Location,
styles: StyleChain,
numbering: &Numbering,
span: Span,
) -> SourceResult<Content> {
let context = Context::new(Some(loc), Some(styles));
Ok(engine
.introspect(CounterAtIntrospection(self.clone(), loc, span))?
.display(engine, context.track(), numbering)?
.display())
}
/// Resolves the numbering for this counter track.
///
/// This coupling between the counter type and the remaining standard
/// library is not great ...
fn matching_numbering(
&self,
engine: &mut Engine,
styles: StyleChain,
loc: Location,
span: Span,
) -> Option<Numbering> {
match self.0 {
CounterKey::Page => loc.page_numbering(engine, span),
CounterKey::Selector(Selector::Elem(func, _)) => engine
.introspect(QueryFirstIntrospection(Selector::Location(loc), span))
.and_then(|content| {
if func == HeadingElem::ELEM {
content
.to_packed::<HeadingElem>()
.and_then(|elem| elem.numbering.as_option().clone())
.flatten()
} else if func == FigureElem::ELEM {
content
.to_packed::<FigureElem>()
.and_then(|elem| elem.numbering.as_option().clone())
.flatten()
} else if func == EquationElem::ELEM {
content
.to_packed::<EquationElem>()
.and_then(|elem| elem.numbering.as_option().clone())
.flatten()
} else if func == FootnoteElem::ELEM {
content
.to_packed::<FootnoteElem>()
.and_then(|elem| elem.numbering.as_option().clone())
} else {
None
}
})
.or_else(|| {
if func == HeadingElem::ELEM {
styles.get_cloned(HeadingElem::numbering)
} else if func == FigureElem::ELEM {
styles.get_cloned(FigureElem::numbering)
} else if func == EquationElem::ELEM {
styles.get_cloned(EquationElem::numbering)
} else if func == FootnoteElem::ELEM {
Some(styles.get_cloned(FootnoteElem::numbering))
} else {
None
}
}),
_ => None,
}
}
}
#[scope]
impl Counter {
/// Create a new counter identified by a key.
#[func(constructor)]
pub fn construct(
/// The key that identifies this counter globally.
///
/// - If it is a string, creates a custom counter that is only affected
/// by manual updates,
/// - If it is the [`page`] function, counts through pages,
/// - If it is a [selector], counts through elements that match the
/// selector. For example,
/// - provide an element function: counts elements of that type,
/// - provide a [`where`]($function.where) selector:
/// counts a type of element with specific fields,
/// - provide a [`{<label>}`]($label): counts elements with that label.
key: CounterKey,
) -> Counter {
Self::new(key)
}
/// Retrieves the value of the counter at the current location. Always
/// returns an array of integers, even if the counter has just one number.
///
/// This is equivalent to `{counter.at(here())}`.
#[func(contextual)]
pub fn get(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<CounterState> {
let loc = context.location().at(span)?;
engine.introspect(CounterAtIntrospection(self.clone(), loc, span))
}
/// Displays the value of the counter.
///
/// You can provide both a custom numbering and a custom location. Both
/// default to `{auto}`, selecting sensible defaults (the numbering of
/// the counted element and the current location, respectively).
///
/// Returns the formatted output.
#[func(contextual)]
pub fn display(
self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// A [numbering pattern or a function]($numbering), which specifies how
/// to display the counter. If given a function, that function receives
/// each number of the counter as a separate argument. If the amount of
/// numbers varies, e.g. for the heading argument, you can use an
/// [argument sink]($arguments).
///
/// If this is omitted or set to `{auto}`, displays the counter with the
/// numbering style for the counted element or with the pattern
/// `{"1.1"}` if no such style exists.
#[default]
numbering: Smart<Numbering>,
/// The place at which the counter should be displayed.
///
/// If a selector is used, it must match exactly one element in the
/// document. The most useful kinds of selectors for this are
/// [labels]($label) and [locations]($location).
///
/// If this is omitted or set to `{auto}`, this displays the counter at
/// the current location. This is equivalent to using
/// [`{here()}`]($here).
///
/// The numbering will be executed with a context in which `{here()}`
/// resolves to the provided location, so that numberings which involve
/// further counters resolve correctly.
#[named]
#[default]
at: Smart<LocatableSelector>,
/// If enabled, displays the current and final top-level count together.
/// Both can be styled through a single numbering pattern. This is used
/// by the page numbering property to display the current and total
/// number of pages when a pattern like `{"1 / 1"}` is given.
#[named]
#[default(false)]
both: bool,
) -> SourceResult<Value> {
let location = match at {
Smart::Auto => context.location().at(span)?,
Smart::Custom(ref selector) => {
selector.resolve_unique(engine, context, span)?
}
};
let state = if both {
engine.introspect(CounterBothIntrospection(self.clone(), location, span))?
} else {
engine.introspect(CounterAtIntrospection(self.clone(), location, span))?
};
let numbering = numbering
.custom()
.or_else(|| {
self.matching_numbering(engine, context.styles().ok()?, location, span)
})
.unwrap_or_else(|| NumberingPattern::from_str("1.1").unwrap().into());
if at.is_custom() {
let context = Context::new(Some(location), context.styles().ok());
state.display(engine, context.track(), &numbering)
} else {
state.display(engine, context, &numbering)
}
}
/// Retrieves the value of the counter at the given location. Always returns
/// an array of integers, even if the counter has just one number.
///
/// The `selector` must match exactly one element in the document. The most
/// useful kinds of selectors for this are [labels]($label) and
/// [locations]($location).
#[func(contextual)]
pub fn at(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// The place at which the counter's value should be retrieved.
selector: LocatableSelector,
) -> SourceResult<CounterState> {
let loc = selector.resolve_unique(engine, context, span)?;
engine.introspect(CounterAtIntrospection(self.clone(), loc, span))
}
/// Retrieves the value of the counter at the end of the document. Always
/// returns an array of integers, even if the counter has just one number.
#[func(contextual)]
pub fn final_(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<CounterState> {
context.introspect().at(span)?;
engine.introspect(CounterFinalIntrospection(self.clone(), span))
}
/// Increases the value of the counter by one.
///
/// The update will be in effect at the position where the returned content
/// is inserted into the document. If you don't put the output into the
/// document, nothing happens! This would be the case, for example, if you
/// write `{let _ = counter(page).step()}`. Counter updates are always
/// applied in layout order and in that case, Typst wouldn't know when to
/// step the counter.
#[func]
pub fn step(
self,
span: Span,
/// The depth at which to step the counter. Defaults to `{1}`.
#[named]
#[default(NonZeroUsize::ONE)]
level: NonZeroUsize,
) -> Content {
self.update(span, CounterUpdate::Step(level))
}
/// Updates the value of the counter.
///
/// Just like with `step`, the update only occurs if you put the resulting
/// content into the document.
#[func]
pub fn update(
self,
span: Span,
/// If given an integer or array of integers, sets the counter to that
/// value. If given a function, that function receives the previous
/// counter value (with each number as a separate argument) and has to
/// return the new value (integer or array).
update: CounterUpdate,
) -> Content {
CounterUpdateElem::new(self.0, update).pack().spanned(span)
}
}
impl Repr for Counter {
fn repr(&self) -> EcoString {
eco_format!("counter({})", self.0.repr())
}
}
/// Identifies a counter.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CounterKey {
/// The page counter.
Page,
/// Counts elements matching the given selectors. Only works for
/// [locatable]($location/#locatable)
/// elements or labels.
Selector(Selector),
/// Counts through manual counters with the same key.
Str(Str),
}
cast! {
CounterKey,
self => match self {
Self::Page => PageElem::ELEM.into_value(),
Self::Selector(v) => v.into_value(),
Self::Str(v) => v.into_value(),
},
v: Str => Self::Str(v),
v: Label => Self::Selector(Selector::Label(v)),
v: Element => {
if v == PageElem::ELEM {
Self::Page
} else {
Self::Selector(LocatableSelector::from_value(v.into_value())?.0)
}
},
v: LocatableSelector => Self::Selector(v.0),
}
impl Repr for CounterKey {
fn repr(&self) -> EcoString {
match self {
Self::Page => "page".into(),
Self::Selector(selector) => selector.repr(),
Self::Str(str) => str.repr(),
}
}
}
/// An update to perform on a counter.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CounterUpdate {
/// Set the counter to the specified state.
Set(CounterState),
/// Increase the number for the given level by one.
Step(NonZeroUsize),
/// Apply the given function to the counter's state.
Func(Func),
}
cast! {
CounterUpdate,
v: CounterState => Self::Set(v),
v: Func => Self::Func(v),
}
/// Elements that have special counting behaviour.
pub trait Count {
/// Get the counter update for this element.
fn update(&self) -> Option<CounterUpdate>;
}
/// Counts through elements with different levels.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct CounterState(pub SmallVec<[u64; 3]>);
impl CounterState {
/// Get the initial counter state for the key.
pub fn init(page: bool) -> Self {
// Special case, because pages always start at one.
Self(smallvec![u64::from(page)])
}
/// Advance the counter and return the numbers for the given heading.
pub fn update(
&mut self,
engine: &mut Engine,
update: CounterUpdate,
) -> SourceResult<()> {
match update {
CounterUpdate::Set(state) => *self = state,
CounterUpdate::Step(level) => self.step(level, 1),
CounterUpdate::Func(func) => {
*self = func
.call(engine, Context::none().track(), self.0.iter().copied())?
.cast()
.at(func.span())?
}
}
Ok(())
}
/// Advance the number of the given level by the specified amount.
pub fn step(&mut self, level: NonZeroUsize, by: u64) {
let level = level.get();
while self.0.len() < level {
self.0.push(0);
}
self.0[level - 1] = self.0[level - 1].saturating_add(by);
self.0.truncate(level);
}
/// Get the first number of the state.
pub fn first(&self) -> u64 {
self.0.first().copied().unwrap_or(1)
}
/// Display the counter state with a numbering.
pub fn display(
&self,
engine: &mut Engine,
context: Tracked<Context>,
numbering: &Numbering,
) -> SourceResult<Value> {
numbering.apply(engine, context, &self.0)
}
}
cast! {
CounterState,
self => Value::Array(self.0.into_iter().map(IntoValue::into_value).collect()),
num: u64 => Self(smallvec![num]),
array: Array => Self(array
.into_iter()
.map(Value::cast)
.collect::<HintedStrResult<_>>()?),
}
/// Executes an update of a counter.
#[elem(Construct, Locatable, Count)]
pub struct CounterUpdateElem {
/// The key that identifies the counter.
#[required]
key: CounterKey,
/// The update to perform on the counter.
#[required]
#[internal]
update: CounterUpdate,
}
impl Construct for CounterUpdateElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
impl Count for Packed<CounterUpdateElem> {
fn update(&self) -> Option<CounterUpdate> {
Some(self.update.clone())
}
}
/// Executes a display of a counter.
#[elem(Construct, Unqueriable, Locatable)]
pub struct CounterDisplayElem {
/// The counter.
#[required]
#[internal]
counter: Counter,
/// The numbering to display the counter with.
#[required]
#[internal]
numbering: Smart<Numbering>,
/// Whether to display both the current and final value.
#[required]
#[internal]
both: bool,
}
impl Construct for CounterDisplayElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
pub const COUNTER_DISPLAY_RULE: ShowFn<CounterDisplayElem> = |elem, engine, styles| {
Ok(elem
.counter
.clone()
.display(
engine,
Context::new(elem.location(), Some(styles)).track(),
elem.span(),
elem.numbering.clone(),
Smart::Auto,
elem.both,
)?
.display())
};
/// An specialized handler of the page counter that tracks both the physical
/// and the logical page counter.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct ManualPageCounter {
physical: NonZeroUsize,
logical: u64,
}
impl ManualPageCounter {
/// Create a new fast page counter, starting at 1.
pub fn new() -> Self {
Self { physical: NonZeroUsize::ONE, logical: 1 }
}
/// Get the current physical page counter state.
pub fn physical(&self) -> NonZeroUsize {
self.physical
}
/// Get the current logical page counter state.
pub fn logical(&self) -> u64 {
self.logical
}
/// Advance past a page.
pub fn visit(&mut self, engine: &mut Engine, page: &Frame) -> SourceResult<()> {
for (_, item) in page.items() {
match item {
FrameItem::Group(group) => self.visit(engine, &group.frame)?,
FrameItem::Tag(Tag::Start(elem, _)) => {
let Some(elem) = elem.to_packed::<CounterUpdateElem>() else {
continue;
};
if elem.key == CounterKey::Page {
let mut state = CounterState(smallvec![self.logical]);
state.update(engine, elem.update.clone())?;
self.logical = state.first();
}
}
_ => {}
}
}
Ok(())
}
/// Step past a page _boundary._
pub fn step(&mut self) {
self.physical = self.physical.saturating_add(1);
self.logical += 1;
}
}
impl Default for ManualPageCounter {
fn default() -> Self {
Self::new()
}
}
/// Retrieves a counter at a specific location.
#[derive(Debug, Clone, PartialEq, Hash)]
struct CounterAtIntrospection(Counter, Location, Span);
impl Introspect for CounterAtIntrospection {
type Output = SourceResult<CounterState>;
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
let Self(counter, loc, _) = self;
let sequence = sequence(counter, engine, introspector)?;
let offset = introspector.query_count_before(&counter.select(), *loc);
let (mut state, page) = sequence[offset].clone();
if counter.is_page() {
let delta = introspector.page(*loc).get().saturating_sub(page.get());
state.step(NonZeroUsize::ONE, delta as u64);
}
Ok(state)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(&self.0, self.2, history)
}
}
/// Retrieves the first number of a counter at a specific location and the first
/// number of the final state, both in one operation.
#[derive(Debug, Clone, PartialEq, Hash)]
struct CounterBothIntrospection(Counter, Location, Span);
impl Introspect for CounterBothIntrospection {
type Output = SourceResult<CounterState>;
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
let Self(counter, loc, _) = self;
let sequence = sequence(counter, engine, introspector)?;
let offset = introspector.query_count_before(&counter.select(), *loc);
let (mut at_state, at_page) = sequence[offset].clone();
let (mut final_state, final_page) = sequence.last().unwrap().clone();
if counter.is_page() {
let at_delta = introspector.page(*loc).get().saturating_sub(at_page.get());
at_state.step(NonZeroUsize::ONE, at_delta as u64);
let final_delta = introspector.pages().get().saturating_sub(final_page.get());
final_state.step(NonZeroUsize::ONE, final_delta as u64);
}
Ok(CounterState(smallvec![at_state.first(), final_state.first()]))
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(&self.0, self.2, history)
}
}
/// Retrieves the final state of a counter.
#[derive(Debug, Clone, PartialEq, Hash)]
struct CounterFinalIntrospection(Counter, Span);
impl Introspect for CounterFinalIntrospection {
type Output = SourceResult<CounterState>;
fn introspect(
&self,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
let Self(counter, _) = self;
let sequence = sequence(counter, engine, introspector)?;
let (mut state, page) = sequence.last().unwrap().clone();
if counter.is_page() {
let delta = introspector.pages().get().saturating_sub(page.get());
state.step(NonZeroUsize::ONE, delta as u64);
}
Ok(state)
}
fn diagnose(&self, history: &History<Self::Output>) -> SourceDiagnostic {
format_convergence_warning(&self.0, self.1, history)
}
}
/// Produces the whole sequence of a counter.
///
/// Due to memoization, this has to happen just once for all retrievals of the
/// same counter, cutting down the number of computations from quadratic to
/// linear.
fn sequence(
counter: &Counter,
engine: &mut Engine,
introspector: Tracked<Introspector>,
) -> SourceResult<EcoVec<(CounterState, NonZeroUsize)>> {
sequence_impl(
counter,
engine.routines,
engine.world,
introspector,
engine.traced,
TrackedMut::reborrow_mut(&mut engine.sink),
engine.route.track(),
)
}
/// Memoized implementation of `sequence`.
#[comemo::memoize]
fn sequence_impl(
counter: &Counter,
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
traced: Tracked<Traced>,
sink: TrackedMut<Sink>,
route: Tracked<Route>,
) -> SourceResult<EcoVec<(CounterState, NonZeroUsize)>> {
let mut engine = Engine {
routines,
world,
introspector: Protected::from_raw(introspector),
traced,
sink,
route: Route::extend(route).unnested(),
};
let mut current = CounterState::init(matches!(counter.0, CounterKey::Page));
let mut page = NonZeroUsize::ONE;
let mut stops = eco_vec![(current.clone(), page)];
for elem in introspector.query(&counter.select()) {
if counter.is_page() {
let prev = page;
page = introspector.page(elem.location().unwrap());
let delta = page.get() - prev.get();
if delta > 0 {
current.step(NonZeroUsize::ONE, delta as u64);
}
}
if let Some(update) = match elem.with::<dyn Count>() {
Some(countable) => countable.update(),
None => Some(CounterUpdate::Step(NonZeroUsize::ONE)),
} {
current.update(&mut engine, update)?;
}
stops.push((current.clone(), page));
}
Ok(stops)
}
/// The warning when a counter failed to converge.
fn format_convergence_warning(
counter: &Counter,
span: Span,
history: &History<SourceResult<CounterState>>,
) -> SourceDiagnostic {
warning!(span, "value of {} did not converge", format_key(counter)).with_hint(
history.hint("values", |ret| match ret {
Ok(v) => format_counter_state(v),
Err(_) => "(errored)".into(),
}),
)
}
/// Formats a counter's key human-readably.
fn format_key(counter: &Counter) -> EcoString {
match counter.0 {
CounterKey::Page => "the page counter".into(),
_ => eco_format!("`{}`", counter.repr()),
}
}
/// Formats a counter's state human-readably.
fn format_counter_state(state: &CounterState) -> EcoString {
let mut output = EcoString::new();
let mut sep = "";
for value in state.0.as_slice() {
write!(output, "{sep}{value}").unwrap();
sep = ", ";
}
output
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/tag.rs | crates/typst-library/src/introspection/tag.rs | use std::fmt::{self, Debug, Formatter};
use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Construct, Content, NativeElement, Packed, Unlabellable, elem,
};
use crate::introspection::Location;
/// Marks the start or end of a locatable element.
#[derive(Clone, PartialEq, Hash)]
pub enum Tag {
/// The stored element starts here.
///
/// Content placed in a tag **must** have a [`Location`] or there will be
/// panics.
Start(Content, TagFlags),
/// The element with the given location and key hash ends here.
///
/// Note: The key hash is stored here instead of in `Start` simply to make
/// the two enum variants more balanced in size, keeping a `Tag`'s memory
/// size down. There are no semantic reasons for this.
End(Location, u128, TagFlags),
}
impl Tag {
/// Access the location of the tag.
pub fn location(&self) -> Location {
match self {
Tag::Start(elem, ..) => elem.location().unwrap(),
Tag::End(loc, ..) => *loc,
}
}
}
impl Debug for Tag {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let loc = self.location();
match self {
Tag::Start(elem, ..) => write!(f, "Start({:?}, {loc:?})", elem.elem().name()),
Tag::End(..) => write!(f, "End({loc:?})"),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct TagFlags {
/// Whether the element will be inserted into the
/// [`Introspector`](super::Introspector).
/// Either because it is [`Locatable`](super::Locatable), has been labelled,
/// or a location has been manually set.
pub introspectable: bool,
/// Whether the element is [`Tagged`](super::Tagged).
pub tagged: bool,
}
impl TagFlags {
pub fn any(&self) -> bool {
self.introspectable || self.tagged
}
}
/// Holds a tag for a locatable element that was realized.
///
/// The `TagElem` is handled by all layouters. The held element becomes
/// available for introspection in the next compiler iteration.
#[elem(Construct, Unlabellable)]
pub struct TagElem {
/// The introspectable element.
#[required]
#[internal]
pub tag: Tag,
}
impl TagElem {
/// Create a packed tag element.
pub fn packed(tag: Tag) -> Content {
let mut content = Self::new(tag).pack();
// We can skip preparation for the `TagElem`.
content.mark_prepared();
content
}
}
impl Construct for TagElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually")
}
}
impl Unlabellable for Packed<TagElem> {}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/introspection/metadata.rs | crates/typst-library/src/introspection/metadata.rs | use crate::foundations::{Value, elem};
use crate::introspection::Locatable;
/// Exposes a value to the query system without producing visible content.
///
/// This element can be retrieved with the [`query`] function and from the
/// command line with
/// [`typst query`]($reference/introspection/query/#command-line-queries). Its
/// purpose is to expose an arbitrary value to the introspection system. To
/// identify a metadata value among others, you can attach a [`label`] to it and
/// query for that label.
///
/// The `metadata` element is especially useful for command line queries because
/// it allows you to expose arbitrary values to the outside world.
///
/// ```example
/// // Put metadata somewhere.
/// #metadata("This is a note") <note>
///
/// // And find it from anywhere else.
/// #context {
/// query(<note>).first().value
/// }
/// ```
#[elem(Locatable)]
pub struct MetadataElem {
/// The value to embed into the document.
#[required]
pub value: Value,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/reference.rs | crates/typst-library/src/model/reference.rs | use comemo::Track;
use ecow::eco_format;
use crate::diag::{At, Hint, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Cast, Content, Context, Func, IntoValue, Label, NativeElement, Packed, Repr, Smart,
StyleChain, Synthesize, cast, elem,
};
use crate::introspection::{
Counter, CounterKey, Locatable, PageNumberingIntrospection,
PageSupplementIntrospection, QueryLabelIntrospection, Tagged,
};
use crate::math::EquationElem;
use crate::model::{
BibliographyElem, CiteElem, DirectLinkElem, Figurable, FootnoteElem, Numbering,
};
use crate::text::TextElem;
/// A reference to a label or bibliography.
///
/// Takes a label and cross-references it. There are two kind of references,
/// determined by its [`form`]($ref.form): `{"normal"}` and `{"page"}`.
///
/// The default, a `{"normal"}` reference, produces a textual reference to a
/// label. For example, a reference to a heading will yield an appropriate
/// string such as "Section 1" for a reference to the first heading. The word
/// "Section" depends on the [`lang`]($text.lang) setting and is localized
/// accordingly. The references are also links to the respective element.
/// Reference syntax can also be used to [cite] from a bibliography.
///
/// As the default form requires a supplement and numbering, the label must be
/// attached to a _referenceable element_. Referenceable elements include
/// [headings]($heading), [figures]($figure), [equations]($math.equation), and
/// [footnotes]($footnote). To create a custom referenceable element like a
/// theorem, you can create a figure of a custom [`kind`]($figure.kind) and
/// write a show rule for it. In the future, there might be a more direct way
/// to define a custom referenceable element.
///
/// If you just want to link to a labelled element and not get an automatic
/// textual reference, consider using the [`link`] function instead.
///
/// A `{"page"}` reference produces a page reference to a label, displaying the
/// page number at its location. You can use the
/// [page's supplement]($page.supplement) to modify the text before the page
/// number. Unlike a `{"normal"}` reference, the label can be attached to any
/// element.
///
/// # Example
/// ```example
/// #set page(numbering: "1")
/// #set heading(numbering: "1.")
/// #set math.equation(numbering: "(1)")
///
/// = Introduction <intro>
/// Recent developments in
/// typesetting software have
/// rekindled hope in previously
/// frustrated researchers. @distress
/// As shown in @results (see
/// #ref(<results>, form: "page")),
/// we ...
///
/// = Results <results>
/// We discuss our approach in
/// comparison with others.
///
/// == Performance <perf>
/// @slow demonstrates what slow
/// software looks like.
/// $ T(n) = O(2^n) $ <slow>
///
/// #bibliography("works.bib")
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: A `{"normal"}` reference to a
/// label can be created by typing an `@` followed by the name of the label
/// (e.g. `[= Introduction <intro>]` can be referenced by typing `[@intro]`).
///
/// To customize the supplement, add content in square brackets after the
/// reference: `[@intro[Chapter]]`.
///
/// # Customization
/// When you only ever need to reference pages of a figure/table/heading/etc. in
/// a document, the default `form` field value can be changed to `{"page"}` with
/// a set rule. If you prefer a short "p." supplement over "page", the
/// [`page.supplement`] field can be used for changing this:
///
/// ```example
/// #set page(
/// numbering: "1",
/// supplement: "p.",
/// >>> margin: (bottom: 3em),
/// >>> footer-descent: 1.25em,
/// )
/// #set ref(form: "page")
///
/// #figure(
/// stack(
/// dir: ltr,
/// spacing: 1em,
/// circle(),
/// square(),
/// ),
/// caption: [Shapes],
/// ) <shapes>
///
/// #pagebreak()
///
/// See @shapes for examples
/// of different shapes.
/// ```
///
/// If you write a show rule for references, you can access the referenced
/// element through the `element` field of the reference. The `element` may
/// be `{none}` even if it exists if Typst hasn't discovered it yet, so you
/// always need to handle that case in your code.
///
/// ```example
/// #set heading(numbering: "1.")
/// #set math.equation(numbering: "(1)")
///
/// #show ref: it => {
/// let eq = math.equation
/// let el = it.element
/// // Skip all other references.
/// if el == none or el.func() != eq { return it }
/// // Override equation references.
/// link(el.location(), counter(eq).display(at: el.location()))
/// }
///
/// = Beginnings <beginning>
/// In @beginning we prove @pythagoras.
/// $ a^2 + b^2 = c^2 $ <pythagoras>
/// ```
#[elem(title = "Reference", Locatable, Tagged, Synthesize)]
pub struct RefElem {
/// The target label that should be referenced.
///
/// Can be a label that is defined in the document or, if the
/// [`form`]($ref.form) is set to `["normal"]`, an entry from the
/// [`bibliography`].
#[required]
pub target: Label,
/// A supplement for the reference.
///
/// If the [`form`]($ref.form) is set to `{"normal"}`:
/// - For references to headings or figures, this is added before the
/// referenced number.
/// - For citations, this can be used to add a page number.
///
/// If the [`form`]($ref.form) is set to `{"page"}`, then this is added
/// before the page number of the label referenced.
///
/// If a function is specified, it is passed the referenced element and
/// should return content.
///
/// ```example
/// #set heading(numbering: "1.")
/// #show ref.where(
/// form: "normal"
/// ): set ref(supplement: it => {
/// if it.func() == heading {
/// "Chapter"
/// } else {
/// "Thing"
/// }
/// })
///
/// = Introduction <intro>
/// In @intro, we see how to turn
/// Sections into Chapters. And
/// in @intro[Part], it is done
/// manually.
/// ```
pub supplement: Smart<Option<Supplement>>,
/// The kind of reference to produce.
///
/// ```example
/// #set page(numbering: "1")
///
/// Here <here> we are on
/// #ref(<here>, form: "page").
/// ```
#[default(RefForm::Normal)]
pub form: RefForm,
/// A synthesized citation.
#[synthesized]
pub citation: Option<Packed<CiteElem>>,
/// The referenced element.
#[synthesized]
pub element: Option<Content>,
}
impl Synthesize for Packed<RefElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let span = self.span();
let citation = to_citation(self, engine, styles)?;
let elem = self.as_mut();
elem.citation = Some(Some(citation));
elem.element = Some(None);
if !BibliographyElem::has(engine, elem.target, span)
&& let Ok(found) =
engine.introspect(QueryLabelIntrospection(elem.target, span))
{
elem.element = Some(Some(found));
return Ok(());
}
Ok(())
}
}
impl Packed<RefElem> {
/// Realize as a linked, textual reference.
pub fn realize(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Content> {
let span = self.span();
let elem = engine.introspect(QueryLabelIntrospection(self.target, span));
let form = self.form.get(styles);
if form == RefForm::Page {
let elem = elem.at(span)?;
let elem = elem.clone();
let loc = elem.location().unwrap();
let numbering = engine
.introspect(PageNumberingIntrospection(loc, span))
.ok_or_else(|| eco_format!("cannot reference without page numbering"))
.hint(eco_format!(
"you can enable page numbering with `#set page(numbering: \"1\")`"
))
.at(span)?;
let supplement = engine.introspect(PageSupplementIntrospection(loc, span));
return realize_reference(
self,
engine,
styles,
Counter::new(CounterKey::Page),
numbering,
supplement,
elem,
);
}
// RefForm::Normal
if BibliographyElem::has(engine, self.target, span) {
if let Ok(elem) = elem {
bail!(
span,
"label `{}` occurs both in the document and its bibliography",
self.target.repr();
hint: "change either the {}'s label or the \
bibliography key to resolve the ambiguity",
elem.func().name();
);
}
return Ok(to_citation(self, engine, styles)?.pack().spanned(span));
}
let elem = elem.at(span)?;
if let Some(footnote) = elem.to_packed::<FootnoteElem>() {
return Ok(footnote.into_ref(self.target).pack().spanned(span));
}
let elem = elem.clone();
let refable = elem
.with::<dyn Refable>()
.ok_or_else(|| {
if elem.can::<dyn Figurable>() {
eco_format!(
"cannot reference {} directly, try putting it into a figure",
elem.func().name()
)
} else {
eco_format!("cannot reference {}", elem.func().name())
}
})
.at(span)?;
let numbering = refable
.numbering()
.ok_or_else(|| {
eco_format!("cannot reference {} without numbering", elem.func().name())
})
.hint(eco_format!(
"you can enable {} numbering with `#set {}(numbering: \"1.\")`",
elem.func().name(),
if elem.func() == EquationElem::ELEM {
"math.equation"
} else {
elem.func().name()
}
))
.at(span)?;
realize_reference(
self,
engine,
styles,
refable.counter(),
numbering.clone(),
refable.supplement(),
elem,
)
}
}
/// Show a reference.
fn realize_reference(
reference: &Packed<RefElem>,
engine: &mut Engine,
styles: StyleChain,
counter: Counter,
numbering: Numbering,
supplement: Content,
elem: Content,
) -> SourceResult<Content> {
let span = reference.span();
let loc = elem.location().unwrap();
let numbers = counter.display_at(engine, loc, styles, &numbering.trimmed(), span)?;
let supplement = match reference.supplement.get_ref(styles) {
Smart::Auto => supplement,
Smart::Custom(None) => Content::empty(),
Smart::Custom(Some(supplement)) => supplement.resolve(engine, styles, [elem])?,
};
let alt = {
let supplement = supplement.plain_text();
let numbering = numbers.plain_text();
eco_format!("{supplement} {numbering}",)
};
let mut content = numbers;
if !supplement.is_empty() {
content = supplement + TextElem::packed("\u{a0}") + content;
}
content = content.spanned(span);
Ok(DirectLinkElem::new(loc, content, Some(alt)).pack().spanned(span))
}
/// Turn a reference into a citation.
fn to_citation(
reference: &Packed<RefElem>,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Packed<CiteElem>> {
let mut elem = Packed::new(CiteElem::new(reference.target).with_supplement(
match reference.supplement.get_cloned(styles) {
Smart::Custom(Some(Supplement::Content(content))) => Some(content),
_ => None,
},
));
elem.synthesize(engine, styles)?;
Ok(elem)
}
/// Additional content for a reference.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Supplement {
Content(Content),
Func(Func),
}
impl Supplement {
/// Tries to resolve the supplement into its content.
pub fn resolve<T: IntoValue>(
&self,
engine: &mut Engine,
styles: StyleChain,
args: impl IntoIterator<Item = T>,
) -> SourceResult<Content> {
Ok(match self {
Supplement::Content(content) => content.clone(),
Supplement::Func(func) => func
.call(engine, Context::new(None, Some(styles)).track(), args)?
.display(),
})
}
}
cast! {
Supplement,
self => match self {
Self::Content(v) => v.into_value(),
Self::Func(v) => v.into_value(),
},
v: Content => Self::Content(v),
v: Func => Self::Func(v),
}
/// The form of the reference.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum RefForm {
/// Produces a textual reference to a label.
#[default]
Normal,
/// Produces a page reference to a label.
Page,
}
/// Marks an element as being able to be referenced. This is used to implement
/// the `@ref` element.
pub trait Refable {
/// The supplement, if not overridden by the reference.
fn supplement(&self) -> Content;
/// Returns the counter of this element.
fn counter(&self) -> Counter;
/// Returns the numbering of this element.
fn numbering(&self) -> Option<&Numbering>;
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/link.rs | crates/typst-library/src/model/link.rs | use std::ops::Deref;
use std::str::FromStr;
use ecow::{EcoString, eco_format};
use typst_syntax::Span;
use crate::diag::{At, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Construct, Content, Label, Packed, Repr, Selector, ShowSet, Smart, StyleChain,
Styles, cast, elem,
};
use crate::introspection::{
Counter, CounterKey, Introspector, Locatable, Location, QueryFirstIntrospection,
QueryLabelIntrospection, Tagged,
};
use crate::layout::{PageElem, Position};
use crate::model::{NumberingPattern, Refable};
use crate::text::{LocalName, TextElem};
/// Links to a URL or a location in the document.
///
/// By default, links do not look any different from normal text. However,
/// you can easily apply a style of your choice with a show rule.
///
/// # Example
/// ```example
/// #show link: underline
///
/// https://example.com \
///
/// #link("https://example.com") \
/// #link("https://example.com")[
/// See example.com
/// ]
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: Text that starts with `http://` or
/// `https://` is automatically turned into a link.
///
/// # Hyphenation
/// If you enable hyphenation or justification, by default, it will not apply to
/// links to prevent unwanted hyphenation in URLs. You can opt out of this
/// default via `{show link: set text(hyphenate: true)}`.
///
/// # Accessibility
/// The destination of a link should be clear from the link text itself, or at
/// least from the text immediately surrounding it. In PDF export, Typst will
/// automatically generate a tooltip description for links based on their
/// destination. For links to URLs, the URL itself will be used as the tooltip.
///
/// # Links in HTML export
/// In HTML export, a link to a [label] or [location] will be turned into a
/// fragment link to a named anchor point. To support this, targets without an
/// existing ID will automatically receive an ID in the DOM. How this works
/// varies by which kind of HTML node(s) the link target turned into:
///
/// - If the link target turned into a single HTML element, that element will
/// receive the ID. This is, for instance, typically the case when linking to
/// a top-level heading (which turns into a single `<h2>` element).
///
/// - If the link target turned into a single text node, the node will be
/// wrapped in a `<span>`, which will then receive the ID.
///
/// - If the link target turned into multiple nodes, the first node will receive
/// the ID.
///
/// - If the link target turned into no nodes at all, an empty span will be
/// generated to serve as a link target.
///
/// If you rely on a specific DOM structure, you should ensure that the link
/// target turns into one or multiple elements, as the compiler makes no
/// guarantees on the precise segmentation of text into text nodes.
///
/// If present, the automatic ID generation tries to reuse the link target's
/// label to create a human-readable ID. A label can be reused if:
///
/// - All characters are alphabetic or numeric according to Unicode, or a
/// hyphen, or an underscore.
///
/// - The label does not start with a digit or hyphen.
///
/// These rules ensure that the label is both a valid CSS identifier and a valid
/// URL fragment for linking.
///
/// As IDs must be unique in the DOM, duplicate labels might need disambiguation
/// when reusing them as IDs. The precise rules for this are as follows:
///
/// - If a label can be reused and is unique in the document, it will directly
/// be used as the ID.
///
/// - If it's reusable, but not unique, a suffix consisting of a hyphen and an
/// integer will be added. For instance, if the label `<mylabel>` exists
/// twice, it would turn into `mylabel-1` and `mylabel-2`.
///
/// - Otherwise, a unique ID of the form `loc-` followed by an integer will be
/// generated.
#[elem(Locatable)]
pub struct LinkElem {
/// The destination the link points to.
///
/// - To link to web pages, `dest` should be a valid URL string. If the URL
/// is in the `mailto:` or `tel:` scheme and the `body` parameter is
/// omitted, the email address or phone number will be the link's body,
/// without the scheme.
///
/// - To link to another part of the document, `dest` can take one of three
/// forms:
/// - A [label] attached to an element. If you also want automatic text
/// for the link based on the element, consider using a
/// [reference]($ref) instead.
///
/// - A [`location`] (typically retrieved from [`here`], [`locate`] or
/// [`query`]).
///
/// - A dictionary with a `page` key of type [integer]($int) and `x` and
/// `y` coordinates of type [length]. Pages are counted from one, and
/// the coordinates are relative to the page's top left corner.
///
/// ```example
/// = Introduction <intro>
/// #link("mailto:hello@typst.app") \
/// #link(<intro>)[Go to intro] \
/// #link((page: 1, x: 0pt, y: 0pt))[
/// Go to top
/// ]
/// ```
#[required]
#[parse(
let dest = args.expect::<LinkTarget>("destination")?;
dest.clone()
)]
pub dest: LinkTarget,
/// The content that should become a link.
///
/// If `dest` is an URL string, the parameter can be omitted. In this case,
/// the URL will be shown as the link.
#[required]
#[parse(match &dest {
LinkTarget::Dest(Destination::Url(url)) => match args.eat()? {
Some(body) => body,
None => body_from_url(url),
},
_ => args.expect("body")?,
})]
pub body: Content,
/// A destination style that should be applied to elements.
#[internal]
#[ghost]
pub current: Option<Destination>,
}
impl LinkElem {
/// Create a link element from a URL with its bare text.
pub fn from_url(url: Url) -> Self {
let body = body_from_url(&url);
Self::new(LinkTarget::Dest(Destination::Url(url)), body)
}
}
impl ShowSet for Packed<LinkElem> {
fn show_set(&self, _: StyleChain) -> Styles {
let mut out = Styles::new();
out.set(TextElem::hyphenate, Smart::Custom(false));
out
}
}
pub(crate) fn body_from_url(url: &Url) -> Content {
let stripped = url.strip_contact_scheme().map(|(_, s)| s.into());
TextElem::packed(stripped.unwrap_or_else(|| url.clone().into_inner()))
}
/// A target where a link can go.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum LinkTarget {
Dest(Destination),
Label(Label),
}
impl LinkTarget {
/// Resolves the destination.
pub fn resolve(&self, engine: &mut Engine, span: Span) -> SourceResult<Destination> {
Ok(match self {
LinkTarget::Dest(dest) => dest.clone(),
LinkTarget::Label(label) => {
let elem =
engine.introspect(QueryLabelIntrospection(*label, span)).at(span)?;
Destination::Location(elem.location().unwrap())
}
})
}
/// Resolves the destination without an engine.
pub fn resolve_with_introspector(
&self,
introspector: &Introspector,
) -> StrResult<Destination> {
Ok(match self {
LinkTarget::Dest(dest) => dest.clone(),
LinkTarget::Label(label) => {
let elem = introspector.query_label(*label)?;
Destination::Location(elem.location().unwrap())
}
})
}
}
cast! {
LinkTarget,
self => match self {
Self::Dest(v) => v.into_value(),
Self::Label(v) => v.into_value(),
},
v: Destination => Self::Dest(v),
v: Label => Self::Label(v),
}
impl From<Destination> for LinkTarget {
fn from(dest: Destination) -> Self {
Self::Dest(dest)
}
}
/// A link destination.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Destination {
/// A link to a URL.
Url(Url),
/// A link to a point on a page.
Position(Position),
/// An unresolved link to a location in the document.
Location(Location),
}
impl Destination {
pub fn alt_text(
&self,
engine: &mut Engine,
styles: StyleChain,
span: Span,
) -> SourceResult<EcoString> {
match self {
Destination::Url(url) => {
let contact = url.strip_contact_scheme().map(|(scheme, stripped)| {
eco_format!("{} {stripped}", scheme.local_name_in(styles))
});
Ok(contact.unwrap_or_else(|| url.clone().into_inner()))
}
Destination::Position(pos) => {
let page_nr = eco_format!("{}", pos.page.get());
let page_str = PageElem::local_name_in(styles);
Ok(eco_format!("{page_str} {page_nr}"))
}
&Destination::Location(loc) => {
let fallback = |engine: &mut Engine| {
// Fall back to a generating a page reference.
let numbering =
loc.page_numbering(engine, span).unwrap_or_else(|| {
NumberingPattern::from_str("1").unwrap().into()
});
let page_nr = Counter::new(CounterKey::Page)
.display_at(engine, loc, styles, &numbering, span)?
.plain_text();
let page_str = PageElem::local_name_in(styles);
Ok(eco_format!("{page_str} {page_nr}"))
};
// Try to generate more meaningful alt text if the location is a
// refable element.
if let Some(elem) = engine
.introspect(QueryFirstIntrospection(Selector::Location(loc), span))
&& let Some(refable) = elem.with::<dyn Refable>()
{
let counter = refable.counter();
let supplement = refable.supplement().plain_text();
if let Some(numbering) = refable.numbering() {
let numbers = counter.display_at(
engine,
loc,
styles,
&numbering.clone().trimmed(),
span,
)?;
return Ok(eco_format!("{supplement} {}", numbers.plain_text()));
} else {
let page_ref = fallback(engine)?;
return Ok(eco_format!("{supplement}, {page_ref}"));
}
}
fallback(engine)
}
}
}
}
impl Repr for Destination {
fn repr(&self) -> EcoString {
eco_format!("{self:?}")
}
}
cast! {
Destination,
self => match self {
Self::Url(v) => v.into_value(),
Self::Position(v) => v.into_value(),
Self::Location(v) => v.into_value(),
},
v: Url => Self::Url(v),
v: Position => Self::Position(v),
v: Location => Self::Location(v),
}
/// A uniform resource locator with a maximum length.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Url(EcoString);
impl Url {
/// Create a URL from a string, checking the maximum length.
pub fn new(url: impl Into<EcoString>) -> StrResult<Self> {
let url = url.into();
if url.len() > 8000 {
bail!("URL is too long")
} else if url.is_empty() {
bail!("URL must not be empty")
}
Ok(Self(url))
}
/// Extract the underlying [`EcoString`].
pub fn into_inner(self) -> EcoString {
self.0
}
pub fn strip_contact_scheme(&self) -> Option<(UrlContactScheme, &str)> {
[UrlContactScheme::Mailto, UrlContactScheme::Tel]
.into_iter()
.find_map(|scheme| {
let stripped = self.strip_prefix(scheme.as_str())?;
Some((scheme, stripped))
})
}
}
impl Deref for Url {
type Target = EcoString;
fn deref(&self) -> &Self::Target {
&self.0
}
}
cast! {
Url,
self => self.0.into_value(),
v: EcoString => Self::new(v)?,
}
/// This is a temporary hack to dispatch to
/// - a raw link that does not go through `LinkElem` in paged
/// - `LinkElem` in HTML (there is no equivalent to a direct link)
///
/// We'll want to dispatch all kinds of links to `LinkElem` in the future, but
/// this is a visually breaking change in paged export as e.g.
/// `show link: underline` will suddenly also affect references, bibliography
/// back references, footnote references, etc. We'll want to do this change
/// carefully and in a way where we provide a good way to keep styling only URL
/// links, which is a bit too complicated to achieve right now for such a basic
/// requirement.
#[elem(Construct)]
pub struct DirectLinkElem {
#[required]
#[internal]
pub loc: Location,
#[required]
#[internal]
pub body: Content,
#[required]
#[internal]
pub alt: Option<EcoString>,
}
impl Construct for DirectLinkElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
/// An element that wraps all content that is [`Content::linked`] to a
/// destination.
#[elem(Tagged, Construct)]
pub struct LinkMarker {
/// The content.
#[internal]
#[required]
pub body: Content,
#[internal]
#[required]
pub alt: Option<EcoString>,
}
impl Construct for LinkMarker {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
#[derive(Copy, Clone)]
pub enum UrlContactScheme {
/// The `mailto:` prefix.
Mailto,
/// The `tel:` prefix.
Tel,
}
impl UrlContactScheme {
pub fn as_str(self) -> &'static str {
match self {
Self::Mailto => "mailto:",
Self::Tel => "tel:",
}
}
pub fn local_name_in(self, styles: StyleChain) -> &'static str {
match self {
UrlContactScheme::Mailto => Email::local_name_in(styles),
UrlContactScheme::Tel => Telephone::local_name_in(styles),
}
}
}
#[derive(Copy, Clone)]
pub struct Email;
impl LocalName for Email {
const KEY: &'static str = "email";
}
#[derive(Copy, Clone)]
pub struct Telephone;
impl LocalName for Telephone {
const KEY: &'static str = "telephone";
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/par.rs | crates/typst-library/src/model/par.rs | use ecow::eco_format;
use typst_utils::singleton;
use crate::diag::{HintedStrResult, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
AlternativeFold, Args, Cast, CastInfo, Construct, Content, Dict, Fold, FromValue,
IntoValue, NativeElement, Packed, Reflect, Smart, Unlabellable, Value, cast, dict,
elem, scope,
};
use crate::introspection::{Count, CounterUpdate, Locatable, Tagged, Unqueriable};
use crate::layout::{Abs, Em, HAlignment, Length, OuterHAlignment, Ratio, Rel};
use crate::model::Numbering;
/// A logical subdivison of textual content.
///
/// Typst automatically collects _inline-level_ elements into paragraphs.
/// Inline-level elements include [text], [horizontal spacing]($h),
/// [boxes]($box), and [inline equations]($math.equation).
///
/// To separate paragraphs, use a blank line (or an explicit [`parbreak`]).
/// Paragraphs are also automatically interrupted by any block-level element
/// (like [`block`], [`place`], or anything that shows itself as one of these).
///
/// The `par` element is primarily used in set rules to affect paragraph
/// properties, but it can also be used to explicitly display its argument as a
/// paragraph of its own. Then, the paragraph's body may not contain any
/// block-level content.
///
/// # Boxes and blocks
/// As explained above, usually paragraphs only contain inline-level content.
/// However, you can integrate any kind of block-level content into a paragraph
/// by wrapping it in a [`box`].
///
/// Conversely, you can separate inline-level content from a paragraph by
/// wrapping it in a [`block`]. In this case, it will not become part of any
/// paragraph at all. Read the following section for an explanation of why that
/// matters and how it differs from just adding paragraph breaks around the
/// content.
///
/// # What becomes a paragraph?
/// When you add inline-level content to your document, Typst will automatically
/// wrap it in paragraphs. However, a typical document also contains some text
/// that is not semantically part of a paragraph, for example in a heading or
/// caption.
///
/// The rules for when Typst wraps inline-level content in a paragraph are as
/// follows:
///
/// - All text at the root of a document is wrapped in paragraphs.
///
/// - Text in a container (like a `block`) is only wrapped in a paragraph if the
/// container holds any block-level content. If all of the contents are
/// inline-level, no paragraph is created.
///
/// In the laid-out document, it's not immediately visible whether text became
/// part of a paragraph. However, it is still important for various reasons:
///
/// - Certain paragraph styling like `first-line-indent` will only apply to
/// proper paragraphs, not any text. Similarly, `par` show rules of course
/// only trigger on paragraphs.
///
/// - A proper distinction between paragraphs and other text helps people who
/// rely on Assistive Technology (AT) (such as screen readers) navigate and
/// understand the document properly.
///
/// - PDF export will generate a `P` tag only for paragraphs.
/// - HTML export will generate a `<p>` tag only for paragraphs.
///
/// When creating custom reusable components, you can and should take charge
/// over whether Typst creates paragraphs. By wrapping text in a [`block`]
/// instead of just adding paragraph breaks around it, you can force the absence
/// of a paragraph. Conversely, by adding a [`parbreak`] after some content in a
/// container, you can force it to become a paragraph even if it's just one
/// word. This is, for example, what [non-`tight`]($list.tight) lists do to
/// force their items to become paragraphs.
///
/// # Example
/// ```example
/// #set par(
/// first-line-indent: 1em,
/// spacing: 0.65em,
/// justify: true,
/// )
///
/// We proceed by contradiction.
/// Suppose that there exists a set
/// of positive integers $a$, $b$, and
/// $c$ that satisfies the equation
/// $a^n + b^n = c^n$ for some
/// integer value of $n > 2$.
///
/// Without loss of generality,
/// let $a$ be the smallest of the
/// three integers. Then, we ...
/// ```
#[elem(scope, title = "Paragraph", Locatable, Tagged)]
pub struct ParElem {
/// The spacing between lines.
///
/// Leading defines the spacing between the [bottom edge]($text.bottom-edge)
/// of one line and the [top edge]($text.top-edge) of the following line. By
/// default, these two properties are up to the font, but they can also be
/// configured manually with a text set rule.
///
/// By setting top edge, bottom edge, and leading, you can also configure a
/// consistent baseline-to-baseline distance. You could, for instance, set
/// the leading to `{1em}`, the top-edge to `{0.8em}`, and the bottom-edge
/// to `{-0.2em}` to get a baseline gap of exactly `{2em}`. The exact
/// distribution of the top- and bottom-edge values affects the bounds of
/// the first and last line.
///
/// ```preview
/// // Color palette
/// #let c = (
/// par-line: aqua.transparentize(60%),
/// leading-line: blue,
/// leading-text: blue.darken(20%),
/// spacing-line: orange.mix(red).darken(15%),
/// spacing-text: orange.mix(red).darken(20%),
/// )
///
/// // A sample text for measuring font metrics.
/// #let sample-text = [A]
///
/// // Number of lines in each paragraph
/// #let n-lines = (4, 4, 2)
/// #let annotated-lines = (4, 8)
///
/// // The wide margin is for annotations
/// #set page(width: 350pt, margin: (x: 20%))
///
/// #context {
/// let text-height = measure(sample-text).height
/// let line-height = text-height + par.leading.to-absolute()
///
/// let jumps = n-lines
/// .map(n => ((text-height,) * n).intersperse(par.leading))
/// .intersperse(par.spacing)
/// .flatten()
///
/// place(grid(
/// ..jumps
/// .enumerate()
/// .map(((i, h)) => if calc.even(i) {
/// // Draw a stripe for the line
/// block(height: h, width: 100%, fill: c.par-line)
/// } else {
/// // Put an annotation for the gap
/// let sw(a, b) = if h == par.leading { a } else { b }
///
/// align(end, block(
/// height: h,
/// outset: (right: sw(0.5em, 1em)),
/// stroke: (
/// left: none,
/// rest: 0.5pt + sw(c.leading-line, c.spacing-line),
/// ),
/// if i / 2 <= sw(..annotated-lines) {
/// place(horizon, dx: 1.3em, text(
/// 0.8em,
/// sw(c.leading-text, c.spacing-text),
/// sw([leading], [spacing]),
/// ))
/// },
/// ))
/// })
/// ))
///
/// // Mark top and bottom edges
/// place(
/// // pos: top/bottom edge
/// // dy: Δy to the last mark
/// // kind: leading/spacing
/// for (pos, dy, kind) in (
/// (bottom, text-height, "leading"),
/// (top, par.leading, "leading"),
/// (bottom, (n-lines.first() - 1) * line-height - par.leading, "spacing"),
/// (top, par.spacing, "spacing"),
/// ) {
/// v(dy)
///
/// let c-text = c.at(kind + "-text")
/// let c-line = c.at(kind + "-line")
///
/// place(end, box(
/// height: 0pt,
/// grid(
/// columns: 2,
/// column-gutter: 0.2em,
/// align: pos,
/// move(
/// // Compensate optical illusion
/// dy: if pos == top { -0.2em } else { 0.05em },
/// text(0.8em, c-text)[#repr(pos) edge],
/// ),
/// line(length: 1em, stroke: 0.5pt + c-line),
/// ),
/// ))
/// },
/// )
/// }
///
/// #set par(justify: true)
/// #set text(luma(25%), overhang: false)
/// #show ". ": it => it + parbreak()
/// #lorem(55)
/// ```
#[default(Em::new(0.65).into())]
pub leading: Length,
/// The spacing between paragraphs.
///
/// Just like leading, this defines the spacing between the bottom edge of a
/// paragraph's last line and the top edge of the next paragraph's first
/// line.
///
/// When a paragraph is adjacent to a [`block`] that is not a paragraph,
/// that block's [`above`]($block.above) or [`below`]($block.below) property
/// takes precedence over the paragraph spacing. Headings, for instance,
/// reduce the spacing below them by default for a better look.
#[default(Em::new(1.2).into())]
pub spacing: Length,
/// Whether to justify text in its line.
///
/// Hyphenation will be enabled for justified paragraphs if the
/// [text function's `hyphenate` property]($text.hyphenate) is set to
/// `{auto}` and the current language is known.
///
/// Note that the current [alignment]($align.alignment) still has an effect
/// on the placement of the last line except if it ends with a
/// [justified line break]($linebreak.justify).
///
/// By default, Typst only changes the spacing between words to achieve
/// justification. However, you can also allow it to adjust the spacing
/// between individual characters using the
/// [`justification-limits` property]($par.justification-limits).
#[default(false)]
pub justify: bool,
/// How much the spacing between words and characters may be adjusted during
/// justification.
///
/// When justifying text, Typst needs to stretch or shrink a line to the
/// full width of the measure. To achieve this, by default, it adjusts the
/// spacing between words. Additionally, it can also adjust the spacing
/// between individual characters. This property allows you to configure
/// lower and upper bounds for these adjustments.
///
/// The property accepts a dictionary with two entries, `spacing` and
/// `tracking`, each containing a dictionary with the keys `min` and `max`.
/// The `min` keys define down to which lower bound gaps may be shrunk while
/// the `max` keys define up to which upper bound they may be stretched.
///
/// - The `spacing` entry defines how much the width of spaces between words
/// may be adjusted. It is closely related to [`text.spacing`] and its
/// `min` and `max` keys accept [relative lengths]($relative), just like
/// the `spacing` property.
///
/// A `min` value of `{100%}` means that spaces should retain their normal
/// size (i.e. not be shrunk), while a value of `{90% - 0.01em}` would
/// indicate that a space can be shrunk to a width of 90% of its normal
/// width minus 0.01× the current font size. Similarly, a `max` value of
/// `{100% + 0.02em}` means that a space's width can be increased by 0.02×
/// the current font size. The ratio part must always be positive. The
/// length part, meanwhile, must not be positive for `min` and not be
/// negative for `max`.
///
/// Note that spaces may still be expanded beyond the `max` value if there
/// is no way to justify the line otherwise. However, other means of
/// justification (e.g. spacing apart characters if the `tracking` entry
/// is configured accordingly) are first used to their maximum.
///
/// - The `tracking` entry defines how much the spacing between letters may
/// be adjusted. It is closely related to [`text.tracking`] and its `min`
/// and `max` keys accept [lengths]($length), just like the `tracking`
/// property. Unlike `spacing`, it does not accept relative lengths
/// because the base of the relative length would vary for each character,
/// leading to an uneven visual appearance. The behavior compared to
/// `spacing` is as if the base was `{100%}`.
///
/// Otherwise, the `min` and `max` values work just like for `spacing`. A
/// `max` value of `{0.01em}` means that additional spacing amounting to
/// 0.01× of the current font size may be inserted between every pair of
/// characters. Note that this also includes the gaps between spaces and
/// characters, so for spaces the values of `tracking` act in addition to
/// the values for `spacing`.
///
/// If you only specify one of `spacing` or `tracking`, the other retains
/// its previously set value (or the default if it was not previously set).
///
/// If you want to enable character-level justification, a good value for
/// the `min` and `max` keys is around `{0.01em}` to `{0.02em}` (negated for
/// `min`). Using the same value for both gives a good baseline, but
/// tweaking the two values individually may produce more balanced results,
/// as demonstrated in the example below. Be careful not to set the bounds
/// too wide, as it quickly looks unnatural.
///
/// Using character-level justification is an impactful microtypographical
/// technique that can improve the appearance of justified text, especially
/// in narrow columns. Note though that character-level justification does
/// not work with every font or language. For example, cursive fonts connect
/// letters. Using character-level justification would lead to jagged
/// connections.
///
/// ```example:"Character-level justification"
/// #let example(name) = columns(2, gutter: 10pt)[
/// #place(top, float: true, scope: "parent", strong(name))
/// >>> Anne Christine Bayley (1~June 1934 – 31~December 2024) was an
/// >>> English surgeon. She was awarded the Order of the British Empire
/// >>> for her research into HIV/AIDS patients in Zambia and for
/// >>> documenting the spread of the disease among heterosexual patients in
/// >>> Africa. In addition to her clinical work, she was a lecturer and
/// >>> head of the surgery department at the University of Zambia School of
/// >>> Medicine. In the 1990s, she returned to England, where she was
/// >>> ordained as an Anglican priest. She continued to be active in Africa
/// >>> throughout her retirement years.
/// <<< /* Text from https://en.wikipedia.org/wiki/Anne_Bayley */
/// ]
///
/// #set page(width: 440pt, height: 21em, margin: 15pt)
/// #set par(justify: true)
/// #set text(size: 0.8em)
///
/// #grid(
/// columns: (1fr, 1fr),
/// gutter: 20pt,
/// {
/// // These are Typst's default limits.
/// set par(justification-limits: (
/// spacing: (min: 100% * 2 / 3, max: 150%),
/// tracking: (min: 0em, max: 0em),
/// ))
/// example[Word-level justification]
/// },
/// {
/// // These are our custom character-level limits.
/// set par(justification-limits: (
/// tracking: (min: -0.01em, max: 0.02em),
/// ))
/// example[Character-level justification]
/// },
/// )
/// ```
#[fold]
pub justification_limits: JustificationLimits,
/// How to determine line breaks.
///
/// When this property is set to `{auto}`, its default value, optimized line
/// breaks will be used for justified paragraphs. Enabling optimized line
/// breaks for ragged paragraphs may also be worthwhile to improve the
/// appearance of the text.
///
/// ```example
/// #set page(width: 207pt)
/// #set par(linebreaks: "simple")
/// Some texts feature many longer
/// words. Those are often exceedingly
/// challenging to break in a visually
/// pleasing way.
///
/// #set par(linebreaks: "optimized")
/// Some texts feature many longer
/// words. Those are often exceedingly
/// challenging to break in a visually
/// pleasing way.
/// ```
pub linebreaks: Smart<Linebreaks>,
/// The indent the first line of a paragraph should have.
///
/// By default, only the first line of a consecutive paragraph will be
/// indented (not the first one in the document or container, and not
/// paragraphs immediately following other block-level elements).
///
/// If you want to indent all paragraphs instead, you can pass a dictionary
/// containing the `amount` of indent as a length and the pair
/// `{all: true}`. When `all` is omitted from the dictionary, it defaults to
/// `{false}`.
///
/// By typographic convention, paragraph breaks are indicated either by some
/// space between paragraphs or by indented first lines. Consider
/// - reducing the [paragraph `spacing`]($par.spacing) to the
/// [`leading`]($par.leading) using `{set par(spacing: 0.65em)}`
/// - increasing the [block `spacing`]($block.spacing) (which inherits the
/// paragraph spacing by default) to the original paragraph spacing using
/// `{set block(spacing: 1.2em)}`
///
/// ```example
/// #set block(spacing: 1.2em)
/// #set par(
/// first-line-indent: 1.5em,
/// spacing: 0.65em,
/// )
///
/// The first paragraph is not affected
/// by the indent.
///
/// But the second paragraph is.
///
/// #line(length: 100%)
///
/// #set par(first-line-indent: (
/// amount: 1.5em,
/// all: true,
/// ))
///
/// Now all paragraphs are affected
/// by the first line indent.
///
/// Even the first one.
/// ```
pub first_line_indent: FirstLineIndent,
/// The indent that all but the first line of a paragraph should have.
///
/// ```example
/// #set par(hanging-indent: 1em)
///
/// #lorem(15)
/// ```
pub hanging_indent: Length,
/// The contents of the paragraph.
#[required]
pub body: Content,
}
#[scope]
impl ParElem {
#[elem]
type ParLine;
}
/// Configures how justification may distribute spacing.
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
pub struct JustificationLimits {
/// Limits for spacing, relative to the space width.
spacing: Option<Limits<Rel>>,
/// Limits for tracking, _in addition_ to the glyph width.
tracking: Option<Limits<Length>>,
}
impl JustificationLimits {
/// Access the spacing limits.
pub fn spacing(&self) -> &Limits<Rel> {
self.spacing.as_ref().unwrap_or(&Limits::SPACING_DEFAULT)
}
/// Access the tracking limits.
pub fn tracking(&self) -> &Limits<Length> {
self.tracking.as_ref().unwrap_or(&Limits::TRACKING_DEFAULT)
}
}
cast! {
JustificationLimits,
self => {
let mut dict = Dict::new();
if let Some(spacing) = &self.spacing {
dict.insert("spacing".into(), spacing.into_value());
}
if let Some(tracking) = &self.tracking {
dict.insert("tracking".into(), tracking.into_value());
}
Value::Dict(dict)
},
mut dict: Dict => {
let spacing = dict
.take("spacing")
.ok()
.map(|v| Limits::cast(v, "spacing"))
.transpose()?;
let tracking = dict
.take("tracking")
.ok()
.map(|v| Limits::cast(v, "tracking"))
.transpose()?;
dict.finish(&["spacing", "tracking"])?;
Self { spacing, tracking }
},
}
impl Fold for JustificationLimits {
fn fold(self, outer: Self) -> Self {
Self {
spacing: self.spacing.fold_or(outer.spacing),
tracking: self.tracking.fold_or(outer.tracking),
}
}
}
impl Default for JustificationLimits {
fn default() -> Self {
Self {
spacing: Some(Limits::SPACING_DEFAULT),
tracking: Some(Limits::TRACKING_DEFAULT),
}
}
}
/// Determines the minimum and maximum size by or to which spacing may be shrunk
/// and stretched.
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
pub struct Limits<T> {
/// Minimum allowable adjustment.
pub min: T,
/// Maximum allowable adjustment.
pub max: T,
}
impl Limits<Rel> {
const SPACING_DEFAULT: Self = Self {
min: Rel::new(Ratio::new(2.0 / 3.0), Length::zero()),
max: Rel::new(Ratio::new(1.5), Length::zero()),
};
}
impl Limits<Length> {
const TRACKING_DEFAULT: Self = Self { min: Length::zero(), max: Length::zero() };
}
impl<T: Reflect> Reflect for Limits<T> {
fn input() -> CastInfo {
Dict::input()
}
fn output() -> CastInfo {
Dict::output()
}
fn castable(value: &Value) -> bool {
Dict::castable(value)
}
}
impl<T: IntoValue> IntoValue for Limits<T> {
fn into_value(self) -> Value {
Value::Dict(dict! {
"min" => self.min,
"max" => self.max,
})
}
}
impl<T> Limits<T> {
/// Not implementing `FromValue` here because we want to pass the `field`
/// for the error message. Ideally, the casting infrastructure would be
/// bit more flexible here.
fn cast(value: Value, field: &str) -> HintedStrResult<Self>
where
T: FromValue + Limit,
{
let mut dict: Dict = value.cast()?;
let mut take = |key, check: fn(T) -> StrResult<T>| {
dict.take(key)?
.cast::<T>()
.map_err(|hinted| hinted.message().clone())
.and_then(check)
.map_err(|err| {
eco_format!("`{key}` value of `{field}` is invalid ({err})")
})
};
let min = take("min", Limit::checked_min)?;
let max = take("max", Limit::checked_max)?;
dict.finish(&["min", "max"])?;
Ok(Self { min, max })
}
}
impl<T> Fold for Limits<T> {
fn fold(self, _: Self) -> Self {
self
}
}
/// Validation for limit components.
trait Limit: Sized {
fn checked_min(self) -> StrResult<Self>;
fn checked_max(self) -> StrResult<Self>;
}
impl Limit for Length {
fn checked_min(self) -> StrResult<Self> {
if self.abs > Abs::zero() || self.em > Em::zero() {
bail!("length must be negative or zero");
}
Ok(self)
}
fn checked_max(self) -> StrResult<Self> {
if self.abs < Abs::zero() || self.em < Em::zero() {
bail!("length must be positive or zero");
}
Ok(self)
}
}
impl Limit for Rel<Length> {
fn checked_min(self) -> StrResult<Self> {
if self.rel <= Ratio::zero() {
bail!("ratio must be positive");
}
self.abs.checked_min()?;
Ok(self)
}
fn checked_max(self) -> StrResult<Self> {
if self.rel <= Ratio::zero() {
bail!("ratio must be positive");
}
self.abs.checked_max()?;
Ok(self)
}
}
/// How to determine line breaks in a paragraph.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Linebreaks {
/// Determine the line breaks in a simple first-fit style.
Simple,
/// Optimize the line breaks for the whole paragraph.
///
/// Typst will try to produce more evenly filled lines of text by
/// considering the whole paragraph when calculating line breaks.
Optimized,
}
/// Configuration for first line indent.
#[derive(Debug, Default, Copy, Clone, PartialEq, Hash)]
pub struct FirstLineIndent {
/// The amount of indent.
pub amount: Length,
/// Whether to indent all paragraphs, not just consecutive ones.
pub all: bool,
}
cast! {
FirstLineIndent,
self => Value::Dict(self.into()),
amount: Length => Self { amount, all: false },
mut dict: Dict => {
let amount = dict.take("amount")?.cast()?;
let all = dict.take("all").ok().map(|v| v.cast()).transpose()?.unwrap_or(false);
dict.finish(&["amount", "all"])?;
Self { amount, all }
},
}
impl From<FirstLineIndent> for Dict {
fn from(indent: FirstLineIndent) -> Self {
dict! {
"amount" => indent.amount,
"all" => indent.all,
}
}
}
/// A paragraph break.
///
/// This starts a new paragraph. Especially useful when used within code like
/// [for loops]($scripting/#loops). Multiple consecutive
/// paragraph breaks collapse into a single one.
///
/// # Example
/// ```example
/// #for i in range(3) {
/// [Blind text #i: ]
/// lorem(5)
/// parbreak()
/// }
/// ```
///
/// # Syntax
/// Instead of calling this function, you can insert a blank line into your
/// markup to create a paragraph break.
#[elem(title = "Paragraph Break", Unlabellable)]
pub struct ParbreakElem {}
impl ParbreakElem {
/// Get the globally shared paragraph element.
pub fn shared() -> &'static Content {
singleton!(Content, ParbreakElem::new().pack())
}
}
impl Unlabellable for Packed<ParbreakElem> {}
/// A paragraph line.
///
/// This element is exclusively used for line number configuration through set
/// rules and cannot be placed.
///
/// The [`numbering`]($par.line.numbering) option is used to enable line
/// numbers by specifying a numbering format.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// #set par.line(numbering: "1")
///
/// Roses are red. \
/// Violets are blue. \
/// Typst is there for you.
/// ```
///
/// The `numbering` option takes either a predefined
/// [numbering pattern]($numbering) or a function returning styled content. You
/// can disable line numbers for text inside certain elements by setting the
/// numbering to `{none}` using show-set rules.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// // Styled red line numbers.
/// #set par.line(
/// numbering: n => text(red)[#n]
/// )
///
/// // Disable numbers inside figures.
/// #show figure: set par.line(
/// numbering: none
/// )
///
/// Roses are red. \
/// Violets are blue.
///
/// #figure(
/// caption: [Without line numbers.]
/// )[
/// Lorem ipsum \
/// dolor sit amet
/// ]
///
/// The text above is a sample \
/// originating from distant times.
/// ```
///
/// This element exposes further options which may be used to control other
/// aspects of line numbering, such as its [alignment]($par.line.number-align)
/// or [margin]($par.line.number-margin). In addition, you can control whether
/// the numbering is reset on each page through the
/// [`numbering-scope`]($par.line.numbering-scope) option.
#[elem(name = "line", title = "Paragraph Line", keywords = ["line numbering"], Construct, Locatable)]
pub struct ParLine {
/// How to number each line. Accepts a
/// [numbering pattern or function]($numbering) taking a single number.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// #set par.line(numbering: "I")
///
/// Roses are red. \
/// Violets are blue. \
/// Typst is there for you.
/// ```
///
/// ```example
/// >>> #set page(width: 200pt, margin: (left: 3em))
/// #set par.line(
/// numbering: i => if calc.rem(i, 5) == 0 or i == 1 { i },
/// )
///
/// #lorem(60)
/// ```
#[ghost]
pub numbering: Option<Numbering>,
/// The alignment of line numbers associated with each line.
///
/// The default of `{auto}` indicates a smart default where numbers grow
/// horizontally away from the text, considering the margin they're in and
/// the current text direction.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// #set par.line(
/// numbering: "I",
/// number-align: left,
/// )
///
/// Hello world! \
/// Today is a beautiful day \
/// For exploring the world.
/// ```
#[ghost]
pub number_align: Smart<HAlignment>,
/// The margin at which line numbers appear.
///
/// _Note:_ In a multi-column document, the line numbers for paragraphs
/// inside the last column will always appear on the `{end}` margin (right
/// margin for left-to-right text and left margin for right-to-left),
/// regardless of this configuration. That behavior cannot be changed at
/// this moment.
///
/// ```example
/// >>> #set page(margin: (right: 3em))
/// #set par.line(
/// numbering: "1",
/// number-margin: right,
/// )
///
/// = Report
/// - Brightness: Dark, yet darker
/// - Readings: Negative
/// ```
#[ghost]
#[default(OuterHAlignment::Start)]
pub number_margin: OuterHAlignment,
/// The distance between line numbers and text.
///
/// The default value of `{auto}` results in a clearance that is adaptive to
/// the page width and yields reasonable results in most cases.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// #set par.line(
/// numbering: "1",
/// number-clearance: 4pt,
/// )
///
/// Typesetting \
/// Styling \
/// Layout
/// ```
#[ghost]
#[default]
pub number_clearance: Smart<Length>,
/// Controls when to reset line numbering.
///
/// _Note:_ The line numbering scope must be uniform across each page run (a
/// page run is a sequence of pages without an explicit pagebreak in
/// between). For this reason, set rules for it should be defined before any
/// page content, typically at the very start of the document.
///
/// ```example
/// >>> #set page(margin: (left: 3em))
/// #set par.line(
/// numbering: "1",
/// numbering-scope: "page",
/// )
///
/// First line \
/// Second line
/// #pagebreak()
/// First line again \
/// Second line again
/// ```
#[ghost]
#[default(LineNumberingScope::Document)]
pub numbering_scope: LineNumberingScope,
}
impl Construct for ParLine {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
/// Possible line numbering scope options, indicating how often the line number
/// counter should be reset.
///
/// Note that, currently, manually resetting the line number counter is not
/// supported.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum LineNumberingScope {
/// Indicates that the line number counter spans the whole document, i.e.,
/// it's never automatically reset.
Document,
/// Indicates that the line number counter should be reset at the start of
/// every new page.
Page,
}
/// A marker used to indicate the presence of a line.
///
/// This element is added to each line in a paragraph and later searched to
/// find out where to add line numbers.
#[elem(Construct, Unqueriable, Locatable, Count)]
pub struct ParLineMarker {
#[internal]
#[required]
pub numbering: Numbering,
#[internal]
#[required]
pub number_align: Smart<HAlignment>,
#[internal]
#[required]
pub number_margin: OuterHAlignment,
#[internal]
#[required]
pub number_clearance: Smart<Length>,
}
impl Construct for ParLineMarker {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
impl Count for Packed<ParLineMarker> {
fn update(&self) -> Option<CounterUpdate> {
// The line counter must be updated manually by the root flow.
None
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/terms.rs | crates/typst-library/src/model/terms.rs | use crate::diag::{bail, warning};
use crate::foundations::{
Array, Content, NativeElement, Packed, Reflect, Smart, Styles, cast, elem, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Em, HElem, Length};
use crate::model::{ListItemLike, ListLike};
/// A list of terms and their descriptions.
///
/// Displays a sequence of terms and their descriptions vertically. When the
/// descriptions span over multiple lines, they use hanging indent to
/// communicate the visual hierarchy.
///
/// # Example
/// ```example
/// / Ligature: A merged glyph.
/// / Kerning: A spacing adjustment
/// between two adjacent letters.
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: Starting a line with a slash,
/// followed by a term, a colon and a description creates a term list item.
#[elem(scope, title = "Term List", Locatable, Tagged)]
pub struct TermsElem {
/// Defines the default [spacing]($terms.spacing) of the term list. If it is
/// `{false}`, the items are spaced apart with
/// [paragraph spacing]($par.spacing). If it is `{true}`, they use
/// [paragraph leading]($par.leading) instead. This makes the list more
/// compact, which can look better if the items are short.
///
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// / Fact: If a term list has a lot
/// of text, and maybe other inline
/// content, it should not be tight
/// anymore.
///
/// / Tip: To make it wide, simply
/// insert a blank line between the
/// items.
/// ```
#[default(true)]
pub tight: bool,
/// The separator between the item and the description.
///
/// If you want to just separate them with a certain amount of space, use
/// `{h(2cm, weak: true)}` as the separator and replace `{2cm}` with your
/// desired amount of space.
///
/// ```example
/// #set terms(separator: [: ])
///
/// / Colon: A nice separator symbol.
/// ```
#[default(HElem::new(Em::new(0.6).into()).with_weak(true).pack())]
pub separator: Content,
/// The indentation of each item.
pub indent: Length,
/// The hanging indent of the description.
///
/// This is in addition to the whole item's `indent`.
///
/// ```example
/// #set terms(hanging-indent: 0pt)
/// / Term: This term list does not
/// make use of hanging indents.
/// ```
#[default(Em::new(2.0).into())]
pub hanging_indent: Length,
/// The spacing between the items of the term list.
///
/// If set to `{auto}`, uses paragraph [`leading`]($par.leading) for tight
/// term lists and paragraph [`spacing`]($par.spacing) for wide
/// (non-tight) term lists.
pub spacing: Smart<Length>,
/// The term list's children.
///
/// When using the term list syntax, adjacent items are automatically
/// collected into term lists, even through constructs like for loops.
///
/// ```example
/// #for (year, product) in (
/// "1978": "TeX",
/// "1984": "LaTeX",
/// "2019": "Typst",
/// ) [/ #product: Born in #year.]
/// ```
#[variadic]
#[parse(
for item in args.items.iter() {
if item.name.is_none() && Array::castable(&item.value.v) {
engine.sink.warn(warning!(
item.value.span,
"implicit conversion from array to `terms.item` is deprecated";
hint: "use `terms.item(term, description)` instead";
hint: "this conversion was never documented and is being phased out";
));
}
}
args.all()?
)]
pub children: Vec<Packed<TermItem>>,
/// Whether we are currently within a term list.
#[internal]
#[ghost]
pub within: bool,
}
#[scope]
impl TermsElem {
#[elem]
type TermItem;
}
/// A term list item.
#[elem(name = "item", title = "Term List Item", Tagged)]
pub struct TermItem {
/// The term described by the list item.
#[required]
pub term: Content,
/// The description of the term.
#[required]
pub description: Content,
}
cast! {
TermItem,
array: Array => {
let mut iter = array.into_iter();
let (term, description) = match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => (a.cast()?, b.cast()?),
_ => bail!("array must contain exactly two entries"),
};
Self::new(term, description)
},
v: Content => v.unpack::<Self>().map_err(|_| "expected term item or array")?,
}
impl ListLike for TermsElem {
type Item = TermItem;
fn create(children: Vec<Packed<Self::Item>>, tight: bool) -> Self {
Self::new(children).with_tight(tight)
}
}
impl ListItemLike for TermItem {
fn styled(mut item: Packed<Self>, styles: Styles) -> Packed<Self> {
item.term.style_in_place(styles.clone());
item.description.style_in_place(styles);
item
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/emph.rs | crates/typst-library/src/model/emph.rs | use crate::foundations::{Content, elem};
use crate::introspection::{Locatable, Tagged};
/// Emphasizes content by toggling italics.
///
/// - If the current [text style]($text.style) is `{"normal"}`, this turns it
/// into `{"italic"}`.
/// - If it is already `{"italic"}` or `{"oblique"}`, it turns it back to
/// `{"normal"}`.
///
/// # Example
/// ```example
/// This is _emphasized._ \
/// This is #emph[too.]
///
/// #show emph: it => {
/// text(blue, it.body)
/// }
///
/// This is _emphasized_ differently.
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: To emphasize content, simply
/// enclose it in underscores (`_`). Note that this only works at word
/// boundaries. To emphasize part of a word, you have to use the function.
#[elem(title = "Emphasis", keywords = ["italic"], Locatable, Tagged)]
pub struct EmphElem {
/// The content to emphasize.
#[required]
pub body: Content,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/title.rs | crates/typst-library/src/model/title.rs | use crate::diag::{Hint, HintedStrResult};
use crate::foundations::{Content, Packed, ShowSet, Smart, StyleChain, Styles, elem};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{BlockElem, Em};
use crate::model::DocumentElem;
use crate::text::{FontWeight, TextElem, TextSize};
/// A document title.
///
/// This should be used to display the main title of the whole document and
/// should occur only once per document. In contrast, level 1
/// [headings]($heading) are intended to be used for the top-level sections of
/// the document.
///
/// Note that additional frontmatter (like an author list) that should appear
/// together with the title does not belong in its body.
///
/// In HTML export, this shows as a `h1` element while level 1 headings show
/// as `h2` elements.
///
/// # Example
/// ```example
/// #set document(
/// title: [Interstellar Mail Delivery]
/// )
///
/// #title()
///
/// = Introduction
/// In recent years, ...
/// ```
#[elem(Locatable, Tagged, ShowSet)]
pub struct TitleElem {
/// The content of the title.
///
/// When omitted (or `{auto}`), this will default to [`document.title`]. In
/// this case, a document title must have been previously set with
/// `{set document(title: [..])}`.
///
/// ```example
/// #set document(title: "Course ABC, Homework 1")
/// #title[Homework 1]
///
/// ...
/// ```
#[positional]
pub body: Smart<Content>,
}
impl TitleElem {
pub fn resolve_body(&self, styles: StyleChain) -> HintedStrResult<Content> {
match self.body.get_cloned(styles) {
Smart::Auto => styles
.get_cloned(DocumentElem::title)
.ok_or("document title was not set")
.hint("set the title with `set document(title: [...])`")
.hint("or provide an explicit body with `title[..]`"),
Smart::Custom(body) => Ok(body),
}
}
}
impl ShowSet for Packed<TitleElem> {
fn show_set(&self, _styles: StyleChain) -> Styles {
const SIZE: Em = Em::new(1.7);
const ABOVE: Em = Em::new(1.125);
const BELOW: Em = Em::new(0.75);
let mut out = Styles::new();
out.set(TextElem::size, TextSize(SIZE.into()));
out.set(TextElem::weight, FontWeight::BOLD);
out.set(BlockElem::above, Smart::Custom(ABOVE.into()));
out.set(BlockElem::below, Smart::Custom(BELOW.into()));
out.set(BlockElem::sticky, true);
out
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/document.rs | crates/typst-library/src/model/document.rs | use ecow::EcoString;
use crate::diag::{HintedStrResult, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Array, Construct, Content, Datetime, OneOrMultiple, Smart, StyleChain, Styles,
Value, cast, elem,
};
use crate::text::{Locale, TextElem};
/// The root element of a document and its metadata.
///
/// All documents are automatically wrapped in a `document` element. You cannot
/// create a document element yourself. This function is only used with
/// [set rules]($styling/#set-rules) to specify document metadata. Such a set
/// rule must not occur inside of any layout container.
///
/// ```example
/// #set document(title: [Hello])
///
/// This has no visible output, but
/// embeds metadata into the PDF!
/// ```
///
/// Note that metadata set with this function is not rendered within the
/// document. Instead, it is embedded in the compiled PDF file.
#[elem(Construct)]
pub struct DocumentElem {
/// The document's title. This is rendered as the title of the PDF viewer
/// window or the browser tab of the page.
///
/// Adding a title is important for accessibility, as it makes it easier to
/// navigate to your document and identify it among other open documents.
/// When exporting to PDF/UA, a title is required.
///
/// While this can be arbitrary content, PDF viewers only support plain text
/// titles, so the conversion might be lossy.
#[ghost]
pub title: Option<Content>,
/// The document's authors.
#[ghost]
pub author: OneOrMultiple<EcoString>,
/// The document's description.
#[ghost]
pub description: Option<Content>,
/// The document's keywords.
#[ghost]
pub keywords: OneOrMultiple<EcoString>,
/// The document's creation date.
///
/// If this is `{auto}` (default), Typst uses the current date and time.
/// Setting it to `{none}` prevents Typst from embedding any creation date
/// into the PDF metadata.
///
/// The year component must be at least zero in order to be embedded into a
/// PDF.
///
/// If you want to create byte-by-byte reproducible PDFs, set this to
/// something other than `{auto}`.
#[ghost]
pub date: Smart<Option<Datetime>>,
}
impl Construct for DocumentElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "can only be used in set rules")
}
}
/// A list of authors.
#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct Author(Vec<EcoString>);
cast! {
Author,
self => self.0.into_value(),
v: EcoString => Self(vec![v]),
v: Array => Self(v.into_iter().map(Value::cast).collect::<HintedStrResult<_>>()?),
}
/// A list of keywords.
#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct Keywords(Vec<EcoString>);
cast! {
Keywords,
self => self.0.into_value(),
v: EcoString => Self(vec![v]),
v: Array => Self(v.into_iter().map(Value::cast).collect::<HintedStrResult<_>>()?),
}
/// Details about the document.
#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct DocumentInfo {
/// The document's title.
pub title: Option<EcoString>,
/// The document's author(s).
pub author: Vec<EcoString>,
/// The document's description.
pub description: Option<EcoString>,
/// The document's keywords.
pub keywords: Vec<EcoString>,
/// The document's creation date.
pub date: Smart<Option<Datetime>>,
/// The document's language, set from the first top-level set rule, e.g.
///
/// ```typc
/// set text(lang: "...", region: "...")
/// ```
pub locale: Smart<Locale>,
}
impl DocumentInfo {
/// Populate this document info with details from the given styles.
///
/// Document set rules are a bit special, so we need to do this manually.
pub fn populate(&mut self, styles: &Styles) {
let chain = StyleChain::new(styles);
if styles.has(DocumentElem::title) {
self.title = chain
.get_ref(DocumentElem::title)
.as_ref()
.map(|content| content.plain_text());
}
if styles.has(DocumentElem::author) {
self.author = chain.get_cloned(DocumentElem::author).0;
}
if styles.has(DocumentElem::description) {
self.description = chain
.get_ref(DocumentElem::description)
.as_ref()
.map(|content| content.plain_text());
}
if styles.has(DocumentElem::keywords) {
self.keywords = chain.get_cloned(DocumentElem::keywords).0;
}
if styles.has(DocumentElem::date) {
self.date = chain.get(DocumentElem::date);
}
}
/// Populate this document info with locale details from the given styles.
pub fn populate_locale(&mut self, styles: &Styles) {
if self.locale.is_custom() {
return;
}
let chain = StyleChain::new(styles);
let mut locale: Option<Locale> = None;
if styles.has(TextElem::lang) {
locale.get_or_insert_default().lang = chain.get(TextElem::lang);
}
if styles.has(TextElem::region) {
locale.get_or_insert_default().region = chain.get(TextElem::region);
}
self.locale = Smart::from(locale);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/list.rs | crates/typst-library/src/model/list.rs | use comemo::Track;
use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Array, Content, Context, Depth, Func, NativeElement, Packed, Smart, StyleChain,
Styles, Value, cast, elem, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Em, Length};
use crate::text::TextElem;
/// A bullet list.
///
/// Displays a sequence of items vertically, with each item introduced by a
/// marker.
///
/// # Example
/// ```example
/// Normal list.
/// - Text
/// - Math
/// - Layout
/// - ...
///
/// Multiple lines.
/// - This list item spans multiple
/// lines because it is indented.
///
/// Function call.
/// #list(
/// [Foundations],
/// [Calculate],
/// [Construct],
/// [Data Loading],
/// )
/// ```
///
/// # Syntax
/// This functions also has dedicated syntax: Start a line with a hyphen,
/// followed by a space to create a list item. A list item can contain multiple
/// paragraphs and other block-level content. All content that is indented
/// more than an item's marker becomes part of that item.
#[elem(scope, title = "Bullet List", Locatable, Tagged)]
pub struct ListElem {
/// Defines the default [spacing]($list.spacing) of the list. If it is
/// `{false}`, the items are spaced apart with
/// [paragraph spacing]($par.spacing). If it is `{true}`, they use
/// [paragraph leading]($par.leading) instead. This makes the list more
/// compact, which can look better if the items are short.
///
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// - If a list has a lot of text, and
/// maybe other inline content, it
/// should not be tight anymore.
///
/// - To make a list wide, simply insert
/// a blank line between the items.
/// ```
#[default(true)]
pub tight: bool,
/// The marker which introduces each item.
///
/// Instead of plain content, you can also pass an array with multiple
/// markers that should be used for nested lists. If the list nesting depth
/// exceeds the number of markers, the markers are cycled. For total
/// control, you may pass a function that maps the list's nesting depth
/// (starting from `{0}`) to a desired marker.
///
/// ```example
/// #set list(marker: [--])
/// - A more classic list
/// - With en-dashes
///
/// #set list(marker: ([•], [--]))
/// - Top-level
/// - Nested
/// - Items
/// - Items
/// ```
#[default(ListMarker::Content(vec![
// These are all available in the default font, vertically centered, and
// roughly of the same size (with the last one having slightly lower
// weight because it is not filled).
TextElem::packed('\u{2022}'), // Bullet
TextElem::packed('\u{2023}'), // Triangular Bullet
TextElem::packed('\u{2013}'), // En-dash
]))]
pub marker: ListMarker,
/// The indent of each item.
pub indent: Length,
/// The spacing between the marker and the body of each item.
#[default(Em::new(0.5).into())]
pub body_indent: Length,
/// The spacing between the items of the list.
///
/// If set to `{auto}`, uses paragraph [`leading`]($par.leading) for tight
/// lists and paragraph [`spacing`]($par.spacing) for wide (non-tight)
/// lists.
pub spacing: Smart<Length>,
/// The bullet list's children.
///
/// When using the list syntax, adjacent items are automatically collected
/// into lists, even through constructs like for loops.
///
/// ```example
/// #for letter in "ABC" [
/// - Letter #letter
/// ]
/// ```
#[variadic]
pub children: Vec<Packed<ListItem>>,
/// The nesting depth.
#[internal]
#[fold]
#[ghost]
pub depth: Depth,
}
#[scope]
impl ListElem {
#[elem]
type ListItem;
}
/// A bullet list item.
#[elem(name = "item", title = "Bullet List Item", Tagged)]
pub struct ListItem {
/// The item's body.
#[required]
pub body: Content,
}
cast! {
ListItem,
v: Content => v.unpack::<Self>().unwrap_or_else(Self::new)
}
/// A list's marker.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum ListMarker {
Content(Vec<Content>),
Func(Func),
}
impl ListMarker {
/// Resolve the marker for the given depth.
pub fn resolve(
&self,
engine: &mut Engine,
styles: StyleChain,
depth: usize,
) -> SourceResult<Content> {
Ok(match self {
Self::Content(list) => {
list.get(depth % list.len()).cloned().unwrap_or_default()
}
Self::Func(func) => func
.call(engine, Context::new(None, Some(styles)).track(), [depth])?
.display(),
})
}
}
cast! {
ListMarker,
self => match self {
Self::Content(vec) => if vec.len() == 1 {
vec.into_iter().next().unwrap().into_value()
} else {
vec.into_value()
},
Self::Func(func) => func.into_value(),
},
v: Content => Self::Content(vec![v]),
array: Array => {
if array.is_empty() {
bail!("array must contain at least one marker");
}
Self::Content(array.into_iter().map(Value::display).collect())
},
v: Func => Self::Func(v),
}
/// A list, enum, or term list.
pub trait ListLike: NativeElement {
/// The kind of list item this list is composed of.
type Item: ListItemLike;
/// Create this kind of list from its children and tightness.
fn create(children: Vec<Packed<Self::Item>>, tight: bool) -> Self;
}
/// A list item, enum item, or term list item.
pub trait ListItemLike: NativeElement {
/// Apply styles to the element's body.
fn styled(item: Packed<Self>, styles: Styles) -> Packed<Self>;
}
impl ListLike for ListElem {
type Item = ListItem;
fn create(children: Vec<Packed<Self::Item>>, tight: bool) -> Self {
Self::new(children).with_tight(tight)
}
}
impl ListItemLike for ListItem {
fn styled(mut item: Packed<Self>, styles: Styles) -> Packed<Self> {
item.body.style_in_place(styles);
item
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/table.rs | crates/typst-library/src/model/table.rs | use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::Arc;
use ecow::EcoString;
use typst_utils::NonZeroExt;
use crate::diag::{HintedStrResult, HintedString, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Content, Packed, Smart, StyleChain, Synthesize, cast, elem, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::resolve::{CellGrid, table_to_cellgrid};
use crate::layout::{
Abs, Alignment, Celled, GridCell, GridFooter, GridHLine, GridHeader, GridVLine,
Length, OuterHAlignment, OuterVAlignment, Rel, Sides, TrackSizings,
};
use crate::model::Figurable;
use crate::pdf::TableCellKind;
use crate::text::LocalName;
use crate::visualize::{Paint, Stroke};
/// A table of items.
///
/// Tables are used to arrange content in cells. Cells can contain arbitrary
/// content, including multiple paragraphs and are specified in row-major order.
/// For a hands-on explanation of all the ways you can use and customize tables
/// in Typst, check out the [Table Guide]($guides/tables).
///
/// Because tables are just grids with different defaults for some cell
/// properties (notably `stroke` and `inset`), refer to the [grid
/// documentation]($grid/#track-size) for more information on how to size the
/// table tracks and specify the cell appearance properties.
///
/// If you are unsure whether you should be using a table or a grid, consider
/// whether the content you are arranging semantically belongs together as a set
/// of related data points or similar or whether you are just want to enhance
/// your presentation by arranging unrelated content in a grid. In the former
/// case, a table is the right choice, while in the latter case, a grid is more
/// appropriate. Furthermore, Assistive Technology (AT) like screen readers will
/// announce content in a `table` as tabular while a grid's content will be
/// announced no different than multiple content blocks in the document flow. AT
/// users will be able to navigate tables two-dimensionally by cell.
///
/// Note that, to override a particular cell's properties or apply show rules on
/// table cells, you can use the [`table.cell`] element. See its documentation
/// for more information.
///
/// Although the `table` and the `grid` share most properties, set and show
/// rules on one of them do not affect the other. Locating most of your styling
/// in set and show rules is recommended, as it keeps the table's actual usages
/// clean and easy to read. It also allows you to easily change the appearance
/// of all tables in one place.
///
/// To give a table a caption and make it [referenceable]($ref), put it into a
/// [figure].
///
/// # Example
///
/// The example below demonstrates some of the most common table options.
/// ```example
/// #table(
/// columns: (1fr, auto, auto),
/// inset: 10pt,
/// align: horizon,
/// table.header(
/// [], [*Volume*], [*Parameters*],
/// ),
/// image("cylinder.svg"),
/// $ pi h (D^2 - d^2) / 4 $,
/// [
/// $h$: height \
/// $D$: outer radius \
/// $d$: inner radius
/// ],
/// image("tetrahedron.svg"),
/// $ sqrt(2) / 12 a^3 $,
/// [$a$: edge length]
/// )
/// ```
///
/// Much like with grids, you can use [`table.cell`] to customize the appearance
/// and the position of each cell.
///
/// ```example
/// >>> #set page(width: auto)
/// >>> #set text(font: "IBM Plex Sans")
/// >>> #let gray = rgb("#565565")
/// >>>
/// #set table(
/// stroke: none,
/// gutter: 0.2em,
/// fill: (x, y) =>
/// if x == 0 or y == 0 { gray },
/// inset: (right: 1.5em),
/// )
///
/// #show table.cell: it => {
/// if it.x == 0 or it.y == 0 {
/// set text(white)
/// strong(it)
/// } else if it.body == [] {
/// // Replace empty cells with 'N/A'
/// pad(..it.inset)[_N/A_]
/// } else {
/// it
/// }
/// }
///
/// #let a = table.cell(
/// fill: green.lighten(60%),
/// )[A]
/// #let b = table.cell(
/// fill: aqua.lighten(60%),
/// )[B]
///
/// #table(
/// columns: 4,
/// [], [Exam 1], [Exam 2], [Exam 3],
///
/// [John], [], a, [],
/// [Mary], [], a, a,
/// [Robert], b, a, b,
/// )
/// ```
///
/// # Accessibility
/// Tables are challenging to consume for users of Assistive Technology (AT). To
/// make the life of AT users easier, we strongly recommend that you use
/// [`table.header`] and [`table.footer`] to mark the header and footer sections
/// of your table. This will allow AT to announce the column labels for each
/// cell.
///
/// Because navigating a table by cell is more cumbersome than reading it
/// visually, you should consider making the core information in your table
/// available as text as well. You can do this by wrapping your table in a
/// [figure] and using its caption to summarize the table's content.
#[elem(scope, Locatable, Tagged, Synthesize, LocalName, Figurable)]
pub struct TableElem {
/// The column sizes. See the [grid documentation]($grid/#track-size) for
/// more information on track sizing.
pub columns: TrackSizings,
/// The row sizes. See the [grid documentation]($grid/#track-size) for more
/// information on track sizing.
pub rows: TrackSizings,
/// The gaps between rows and columns. This is a shorthand for setting
/// `column-gutter` and `row-gutter` to the same value. See the [grid
/// documentation]($grid.gutter) for more information on gutters.
#[external]
pub gutter: TrackSizings,
/// The gaps between columns. Takes precedence over `gutter`. See the
/// [grid documentation]($grid.gutter) for more information on gutters.
#[parse(
let gutter = args.named("gutter")?;
args.named("column-gutter")?.or_else(|| gutter.clone())
)]
pub column_gutter: TrackSizings,
/// The gaps between rows. Takes precedence over `gutter`. See the
/// [grid documentation]($grid.gutter) for more information on gutters.
#[parse(args.named("row-gutter")?.or_else(|| gutter.clone()))]
pub row_gutter: TrackSizings,
/// How much to pad the cells' content.
///
/// To specify the same inset for all cells, use a single length for all
/// sides, or a dictionary of lengths for individual sides. See the
/// [box's documentation]($box.inset) for more details.
///
/// To specify a varying inset for different cells, you can:
/// - use a single, uniform inset for all cells
/// - use an array of insets for each column
/// - use a function that maps a cell's X/Y position (both starting from
/// zero) to its inset
///
/// See the [grid documentation]($grid/#styling) for more details.
///
/// ```example
/// #table(
/// columns: 2,
/// inset: 10pt,
/// [Hello],
/// [World],
/// )
///
/// #table(
/// columns: 2,
/// inset: (x: 20pt, y: 10pt),
/// [Hello],
/// [World],
/// )
/// ```
#[fold]
#[default(Celled::Value(Sides::splat(Some(Abs::pt(5.0).into()))))]
pub inset: Celled<Sides<Option<Rel<Length>>>>,
/// How to align the cells' content.
///
/// If set to `{auto}`, the outer alignment is used.
///
/// You can specify the alignment in any of the following fashions:
/// - use a single alignment for all cells
/// - use an array of alignments corresponding to each column
/// - use a function that maps a cell's X/Y position (both starting from
/// zero) to its alignment
///
/// See the [Table Guide]($guides/tables/#alignment) for details.
///
/// ```example
/// #table(
/// columns: 3,
/// align: (left, center, right),
/// [Hello], [Hello], [Hello],
/// [A], [B], [C],
/// )
/// ```
pub align: Celled<Smart<Alignment>>,
/// How to fill the cells.
///
/// This can be:
/// - a single fill for all cells
/// - an array of fill corresponding to each column
/// - a function that maps a cell's position to its fill
///
/// Most notably, arrays and functions are useful for creating striped
/// tables. See the [Table Guide]($guides/tables/#fills) for more
/// details.
///
/// ```example
/// #table(
/// fill: (x, _) =>
/// if calc.odd(x) { luma(240) }
/// else { white },
/// align: (x, y) =>
/// if y == 0 { center }
/// else if x == 0 { left }
/// else { right },
/// columns: 4,
/// [], [*Q1*], [*Q2*], [*Q3*],
/// [Revenue:], [1000 €], [2000 €], [3000 €],
/// [Expenses:], [500 €], [1000 €], [1500 €],
/// [Profit:], [500 €], [1000 €], [1500 €],
/// )
/// ```
pub fill: Celled<Option<Paint>>,
/// How to [stroke] the cells.
///
/// Strokes can be disabled by setting this to `{none}`.
///
/// If it is necessary to place lines which can cross spacing between cells
/// produced by the [`gutter`]($table.gutter) option, or to override the
/// stroke between multiple specific cells, consider specifying one or more
/// of [`table.hline`] and [`table.vline`] alongside your table cells.
///
/// To specify the same stroke for all cells, use a single [stroke] for all
/// sides, or a dictionary of [strokes]($stroke) for individual sides. See
/// the [rectangle's documentation]($rect.stroke) for more details.
///
/// To specify varying strokes for different cells, you can:
/// - use a single stroke for all cells
/// - use an array of strokes corresponding to each column
/// - use a function that maps a cell's position to its stroke
///
/// See the [Table Guide]($guides/tables/#strokes) for more details.
#[fold]
#[default(Celled::Value(Sides::splat(Some(Some(Arc::new(Stroke::default()))))))]
pub stroke: Celled<Sides<Option<Option<Arc<Stroke>>>>>,
/// A summary of the purpose and structure of complex tables.
///
/// See the [`crate::pdf::accessibility::table_summary`] function for more
/// information.
#[internal]
#[parse(None)]
pub summary: Option<EcoString>,
#[internal]
#[synthesized]
pub grid: Arc<CellGrid>,
/// The contents of the table cells, plus any extra table lines specified
/// with the [`table.hline`] and [`table.vline`] elements.
#[variadic]
pub children: Vec<TableChild>,
}
#[scope]
impl TableElem {
#[elem]
type TableCell;
#[elem]
type TableHLine;
#[elem]
type TableVLine;
#[elem]
type TableHeader;
#[elem]
type TableFooter;
}
impl Synthesize for Packed<TableElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let grid = table_to_cellgrid(self, engine, styles)?;
self.grid = Some(Arc::new(grid));
Ok(())
}
}
impl LocalName for Packed<TableElem> {
const KEY: &'static str = "table";
}
impl Figurable for Packed<TableElem> {}
cast! {
TableElem,
v: Content => v.unpack::<Self>().map_err(|_| "expected table")?,
}
/// Any child of a table element.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum TableChild {
Header(Packed<TableHeader>),
Footer(Packed<TableFooter>),
Item(TableItem),
}
cast! {
TableChild,
self => match self {
Self::Header(header) => header.into_value(),
Self::Footer(footer) => footer.into_value(),
Self::Item(item) => item.into_value(),
},
v: Content => {
v.try_into()?
},
}
impl TryFrom<Content> for TableChild {
type Error = HintedString;
fn try_from(value: Content) -> HintedStrResult<Self> {
if value.is::<GridHeader>() {
bail!(
"cannot use `grid.header` as a table header";
hint: "use `table.header` instead";
)
}
if value.is::<GridFooter>() {
bail!(
"cannot use `grid.footer` as a table footer";
hint: "use `table.footer` instead";
)
}
value
.into_packed::<TableHeader>()
.map(Self::Header)
.or_else(|value| value.into_packed::<TableFooter>().map(Self::Footer))
.or_else(|value| TableItem::try_from(value).map(Self::Item))
}
}
/// A table item, which is the basic unit of table specification.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum TableItem {
HLine(Packed<TableHLine>),
VLine(Packed<TableVLine>),
Cell(Packed<TableCell>),
}
cast! {
TableItem,
self => match self {
Self::HLine(hline) => hline.into_value(),
Self::VLine(vline) => vline.into_value(),
Self::Cell(cell) => cell.into_value(),
},
v: Content => {
v.try_into()?
},
}
impl TryFrom<Content> for TableItem {
type Error = HintedString;
fn try_from(value: Content) -> HintedStrResult<Self> {
if value.is::<GridHeader>() {
bail!("cannot place a grid header within another header or footer");
}
if value.is::<TableHeader>() {
bail!("cannot place a table header within another header or footer");
}
if value.is::<GridFooter>() {
bail!("cannot place a grid footer within another footer or header");
}
if value.is::<TableFooter>() {
bail!("cannot place a table footer within another footer or header");
}
if value.is::<GridCell>() {
bail!(
"cannot use `grid.cell` as a table cell";
hint: "use `table.cell` instead";
);
}
if value.is::<GridHLine>() {
bail!(
"cannot use `grid.hline` as a table line";
hint: "use `table.hline` instead";
);
}
if value.is::<GridVLine>() {
bail!(
"cannot use `grid.vline` as a table line";
hint: "use `table.vline` instead";
);
}
Ok(value
.into_packed::<TableHLine>()
.map(Self::HLine)
.or_else(|value| value.into_packed::<TableVLine>().map(Self::VLine))
.or_else(|value| value.into_packed::<TableCell>().map(Self::Cell))
.unwrap_or_else(|value| {
let span = value.span();
Self::Cell(Packed::new(TableCell::new(value)).spanned(span))
}))
}
}
/// A repeatable table header.
///
/// You should wrap your tables' heading rows in this function even if you do
/// not plan to wrap your table across pages because Typst uses this function to
/// attach accessibility metadata to tables and ensure [Universal
/// Access]($guides/accessibility/#basics) to your document.
///
/// You can use the `repeat` parameter to control whether your table's header
/// will be repeated across pages.
///
/// Currently, this function is unsuitable for creating a header column or
/// single header cells. Either use regular cells, or, if you are exporting a
/// PDF, you can also use the [`pdf.header-cell`] function to mark a cell as a
/// header cell. Likewise, you can use [`pdf.data-cell`] to mark cells in this
/// function as data cells. Note that these functions are not final and thus
/// only available when you enable the `a11y-extras` feature (see the [PDF
/// module documentation]($pdf) for details).
///
/// ```example
/// #set page(height: 11.5em)
/// #set table(
/// fill: (x, y) =>
/// if x == 0 or y == 0 {
/// gray.lighten(40%)
/// },
/// align: right,
/// )
///
/// #show table.cell.where(x: 0): strong
/// #show table.cell.where(y: 0): strong
///
/// #table(
/// columns: 4,
/// table.header(
/// [], [Blue chip],
/// [Fresh IPO], [Penny st'k],
/// ),
/// table.cell(
/// rowspan: 6,
/// align: horizon,
/// rotate(-90deg, reflow: true)[
/// *USD / day*
/// ],
/// ),
/// [0.20], [104], [5],
/// [3.17], [108], [4],
/// [1.59], [84], [1],
/// [0.26], [98], [15],
/// [0.01], [195], [4],
/// [7.34], [57], [2],
/// )
/// ```
#[elem(name = "header", title = "Table Header")]
pub struct TableHeader {
/// Whether this header should be repeated across pages.
#[default(true)]
pub repeat: bool,
/// The level of the header. Must not be zero.
///
/// This allows repeating multiple headers at once. Headers with different
/// levels can repeat together, as long as they have ascending levels.
///
/// Notably, when a header with a lower level starts repeating, all higher
/// or equal level headers stop repeating (they are "replaced" by the new
/// header).
#[default(NonZeroU32::ONE)]
pub level: NonZeroU32,
/// The cells and lines within the header.
#[variadic]
pub children: Vec<TableItem>,
}
/// A repeatable table footer.
///
/// Just like the [`table.header`] element, the footer can repeat itself on
/// every page of the table. This is useful for improving legibility by adding
/// the column labels in both the header and footer of a large table, totals, or
/// other information that should be visible on every page.
///
/// No other table cells may be placed after the footer.
#[elem(name = "footer", title = "Table Footer")]
pub struct TableFooter {
/// Whether this footer should be repeated across pages.
#[default(true)]
pub repeat: bool,
/// The cells and lines within the footer.
#[variadic]
pub children: Vec<TableItem>,
}
/// A horizontal line in the table.
///
/// Overrides any per-cell stroke, including stroke specified through the
/// table's `stroke` field. Can cross spacing between cells created through the
/// table's [`column-gutter`]($table.column-gutter) option.
///
/// Use this function instead of the table's `stroke` field if you want to
/// manually place a horizontal line at a specific position in a single table.
/// Consider using [table's `stroke`]($table.stroke) field or [`table.cell`'s
/// `stroke`]($table.cell.stroke) field instead if the line you want to place is
/// part of all your tables' designs.
///
/// ```example
/// #set table.hline(stroke: .6pt)
///
/// #table(
/// stroke: none,
/// columns: (auto, 1fr),
/// [09:00], [Badge pick up],
/// [09:45], [Opening Keynote],
/// [10:30], [Talk: Typst's Future],
/// [11:15], [Session: Good PRs],
/// table.hline(start: 1),
/// [Noon], [_Lunch break_],
/// table.hline(start: 1),
/// [14:00], [Talk: Tracked Layout],
/// [15:00], [Talk: Automations],
/// [16:00], [Workshop: Tables],
/// table.hline(),
/// [19:00], [Day 1 Attendee Mixer],
/// )
/// ```
#[elem(name = "hline", title = "Table Horizontal Line")]
pub struct TableHLine {
/// The row above which the horizontal line is placed (zero-indexed).
/// Functions identically to the `y` field in [`grid.hline`]($grid.hline.y).
pub y: Smart<usize>,
/// The column at which the horizontal line starts (zero-indexed, inclusive).
pub start: usize,
/// The column before which the horizontal line ends (zero-indexed,
/// exclusive).
pub end: Option<NonZeroUsize>,
/// The line's stroke.
///
/// Specifying `{none}` removes any lines previously placed across this
/// line's range, including hlines or per-cell stroke below it.
#[fold]
#[default(Some(Arc::new(Stroke::default())))]
pub stroke: Option<Arc<Stroke>>,
/// The position at which the line is placed, given its row (`y`) - either
/// `{top}` to draw above it or `{bottom}` to draw below it.
///
/// This setting is only relevant when row gutter is enabled (and
/// shouldn't be used otherwise - prefer just increasing the `y` field by
/// one instead), since then the position below a row becomes different
/// from the position above the next row due to the spacing between both.
#[default(OuterVAlignment::Top)]
pub position: OuterVAlignment,
}
/// A vertical line in the table. See the docs for [`grid.vline`] for more
/// information regarding how to use this element's fields.
///
/// Overrides any per-cell stroke, including stroke specified through the
/// table's `stroke` field. Can cross spacing between cells created through the
/// table's [`row-gutter`]($table.row-gutter) option.
///
/// Similar to [`table.hline`], use this function if you want to manually place
/// a vertical line at a specific position in a single table and use the
/// [table's `stroke`]($table.stroke) field or [`table.cell`'s
/// `stroke`]($table.cell.stroke) field instead if the line you want to place is
/// part of all your tables' designs.
#[elem(name = "vline", title = "Table Vertical Line")]
pub struct TableVLine {
/// The column before which the vertical line is placed (zero-indexed).
/// Functions identically to the `x` field in [`grid.vline`].
pub x: Smart<usize>,
/// The row at which the vertical line starts (zero-indexed, inclusive).
pub start: usize,
/// The row on top of which the vertical line ends (zero-indexed,
/// exclusive).
pub end: Option<NonZeroUsize>,
/// The line's stroke.
///
/// Specifying `{none}` removes any lines previously placed across this
/// line's range, including vlines or per-cell stroke below it.
#[fold]
#[default(Some(Arc::new(Stroke::default())))]
pub stroke: Option<Arc<Stroke>>,
/// The position at which the line is placed, given its column (`x`) -
/// either `{start}` to draw before it or `{end}` to draw after it.
///
/// The values `{left}` and `{right}` are also accepted, but discouraged as
/// they cause your table to be inconsistent between left-to-right and
/// right-to-left documents.
///
/// This setting is only relevant when column gutter is enabled (and
/// shouldn't be used otherwise - prefer just increasing the `x` field by
/// one instead), since then the position after a column becomes different
/// from the position before the next column due to the spacing between
/// both.
#[default(OuterHAlignment::Start)]
pub position: OuterHAlignment,
}
/// A cell in the table. Use this to position a cell manually or to apply
/// styling. To do the latter, you can either use the function to override the
/// properties for a particular cell, or use it in show rules to apply certain
/// styles to multiple cells at once.
///
/// Perhaps the most important use case of `{table.cell}` is to make a cell span
/// multiple columns and/or rows with the `colspan` and `rowspan` fields.
///
/// ```example
/// >>> #set page(width: auto)
/// #show table.cell.where(y: 0): strong
/// #set table(
/// stroke: (x, y) => if y == 0 {
/// (bottom: 0.7pt + black)
/// },
/// align: (x, y) => (
/// if x > 0 { center }
/// else { left }
/// )
/// )
///
/// #table(
/// columns: 3,
/// table.header(
/// [Substance],
/// [Subcritical °C],
/// [Supercritical °C],
/// ),
/// [Hydrochloric Acid],
/// [12.0], [92.1],
/// [Sodium Myreth Sulfate],
/// [16.6], [104],
/// [Potassium Hydroxide],
/// table.cell(colspan: 2)[24.7],
/// )
/// ```
///
/// For example, you can override the fill, alignment or inset for a single
/// cell:
///
/// ```example
/// >>> #set page(width: auto)
/// // You can also import those.
/// #import table: cell, header
///
/// #table(
/// columns: 2,
/// align: center,
/// header(
/// [*Trip progress*],
/// [*Itinerary*],
/// ),
/// cell(
/// align: right,
/// fill: fuchsia.lighten(80%),
/// [🚗],
/// ),
/// [Get in, folks!],
/// [🚗], [Eat curbside hotdog],
/// cell(align: left)[🌴🚗],
/// cell(
/// inset: 0.06em,
/// text(1.62em)[🏝️🌅🌊],
/// ),
/// )
/// ```
///
/// You may also apply a show rule on `table.cell` to style all cells at once.
/// Combined with selectors, this allows you to apply styles based on a cell's
/// position:
///
/// ```example
/// #show table.cell.where(x: 0): strong
///
/// #table(
/// columns: 3,
/// gutter: 3pt,
/// [Name], [Age], [Strength],
/// [Hannes], [36], [Grace],
/// [Irma], [50], [Resourcefulness],
/// [Vikram], [49], [Perseverance],
/// )
/// ```
#[elem(name = "cell", title = "Table Cell")]
pub struct TableCell {
/// The cell's body.
#[required]
pub body: Content,
/// The cell's column (zero-indexed).
/// Functions identically to the `x` field in [`grid.cell`].
pub x: Smart<usize>,
/// The cell's row (zero-indexed).
/// Functions identically to the `y` field in [`grid.cell`].
pub y: Smart<usize>,
/// The amount of columns spanned by this cell.
#[default(NonZeroUsize::ONE)]
pub colspan: NonZeroUsize,
/// The amount of rows spanned by this cell.
#[default(NonZeroUsize::ONE)]
pub rowspan: NonZeroUsize,
/// The cell's [inset]($table.inset) override.
pub inset: Smart<Sides<Option<Rel<Length>>>>,
/// The cell's [alignment]($table.align) override.
pub align: Smart<Alignment>,
/// The cell's [fill]($table.fill) override.
pub fill: Smart<Option<Paint>>,
/// The cell's [stroke]($table.stroke) override.
#[fold]
pub stroke: Sides<Option<Option<Arc<Stroke>>>>,
/// Whether rows spanned by this cell can be placed in different pages.
/// When equal to `{auto}`, a cell spanning only fixed-size rows is
/// unbreakable, while a cell spanning at least one `{auto}`-sized row is
/// breakable.
pub breakable: Smart<bool>,
#[internal]
#[parse(Some(Smart::Auto))]
pub kind: Smart<TableCellKind>,
#[internal]
#[parse(Some(false))]
pub is_repeated: bool,
}
cast! {
TableCell,
v: Content => v.into(),
}
impl Default for Packed<TableCell> {
fn default() -> Self {
Packed::new(
// Explicitly set colspan and rowspan to ensure they won't be
// overridden by set rules (default cells are created after
// colspans and rowspans are processed in the resolver)
TableCell::new(Content::default())
.with_colspan(NonZeroUsize::ONE)
.with_rowspan(NonZeroUsize::ONE),
)
}
}
impl From<Content> for TableCell {
fn from(value: Content) -> Self {
#[allow(clippy::unwrap_or_default)]
value.unpack::<Self>().unwrap_or_else(Self::new)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/footnote.rs | crates/typst-library/src/model/footnote.rs | use std::num::NonZeroUsize;
use std::str::FromStr;
use ecow::{EcoString, eco_format};
use typst_utils::NonZeroExt;
use crate::diag::{At, SourceResult, StrResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Content, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, cast,
elem, scope,
};
use crate::introspection::{
Count, Counter, CounterUpdate, Locatable, Location, QueryLabelIntrospection, Tagged,
};
use crate::layout::{Abs, Em, Length, Ratio};
use crate::model::{Destination, DirectLinkElem, Numbering, NumberingPattern, ParElem};
use crate::text::{LocalName, SuperElem, TextElem, TextSize};
use crate::visualize::{LineElem, Stroke};
/// A footnote.
///
/// Includes additional remarks and references on the same page with footnotes.
/// A footnote will insert a superscript number that links to the note at the
/// bottom of the page. Notes are numbered sequentially throughout your document
/// and can break across multiple pages.
///
/// To customize the appearance of the entry in the footnote listing, see
/// [`footnote.entry`]. The footnote itself is realized as a normal superscript,
/// so you can use a set rule on the [`super`] function to customize it. You can
/// also apply a show rule to customize only the footnote marker (superscript
/// number) in the running text.
///
/// # Example
/// ```example
/// Check the docs for more details.
/// #footnote[https://typst.app/docs]
/// ```
///
/// The footnote automatically attaches itself to the preceding word, even if
/// there is a space before it in the markup. To force space, you can use the
/// string `[#" "]` or explicit [horizontal spacing]($h).
///
/// By giving a label to a footnote, you can have multiple references to it.
///
/// ```example
/// You can edit Typst documents online.
/// #footnote[https://typst.app/app] <fn>
/// Checkout Typst's website. @fn
/// And the online app. #footnote(<fn>)
/// ```
///
/// _Note:_ Set and show rules in the scope where `footnote` is called may not
/// apply to the footnote's content. See [here][issue] for more information.
///
/// # Accessibility
/// Footnotes will be read by Assistive Technology (AT) immediately after the
/// spot in the text where they are referenced, just like how they appear in
/// markup.
///
/// [issue]: https://github.com/typst/typst/issues/1467#issuecomment-1588799440
#[elem(scope, Locatable, Tagged, Count)]
pub struct FootnoteElem {
/// How to number footnotes. Accepts a
/// [numbering pattern or function]($numbering) taking a single number.
///
/// By default, the footnote numbering continues throughout your document.
/// If you prefer per-page footnote numbering, you can reset the footnote
/// [counter] in the page [header]($page.header). In the future, there might
/// be a simpler way to achieve this.
///
/// ```example
/// #set footnote(numbering: "*")
///
/// Footnotes:
/// #footnote[Star],
/// #footnote[Dagger]
/// ```
#[default(Numbering::Pattern(NumberingPattern::from_str("1").unwrap()))]
pub numbering: Numbering,
/// The content to put into the footnote. Can also be the label of another
/// footnote this one should point to.
#[required]
pub body: FootnoteBody,
}
#[scope]
impl FootnoteElem {
#[elem]
type FootnoteEntry;
}
impl LocalName for Packed<FootnoteElem> {
const KEY: &'static str = "footnote";
}
impl FootnoteElem {
pub fn alt_text(styles: StyleChain, num: &str) -> EcoString {
let local_name = Packed::<FootnoteElem>::local_name_in(styles);
eco_format!("{local_name} {num}")
}
/// Creates a new footnote that the passed content as its body.
pub fn with_content(content: Content) -> Self {
Self::new(FootnoteBody::Content(content))
}
/// Creates a new footnote referencing the footnote with the specified label.
pub fn with_label(label: Label) -> Self {
Self::new(FootnoteBody::Reference(label))
}
/// Creates a new footnote referencing the footnote with the specified label,
/// with the other fields from the current footnote cloned.
pub fn into_ref(&self, label: Label) -> Self {
Self {
body: FootnoteBody::Reference(label),
..self.clone()
}
}
/// Tests if this footnote is a reference to another footnote.
pub fn is_ref(&self) -> bool {
matches!(self.body, FootnoteBody::Reference(_))
}
/// Returns the content of the body of this footnote if it is not a ref.
pub fn body_content(&self) -> Option<&Content> {
match &self.body {
FootnoteBody::Content(content) => Some(content),
_ => None,
}
}
}
impl Packed<FootnoteElem> {
/// Returns the linking location and the resolved numbers.
pub fn realize(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<(Destination, Content)> {
let loc = self.declaration_location(engine).at(self.span())?;
let numbering = self.numbering.get_ref(styles);
let counter = Counter::of(FootnoteElem::ELEM);
let num = counter.display_at(engine, loc, styles, numbering, self.span())?;
Ok((Destination::Location(loc.variant(1)), num))
}
/// Returns the location of the definition of this footnote.
pub fn declaration_location(&self, engine: &mut Engine) -> StrResult<Location> {
match self.body {
FootnoteBody::Reference(label) => {
let element =
engine.introspect(QueryLabelIntrospection(label, self.span()))?;
let footnote = element
.to_packed::<FootnoteElem>()
.ok_or("referenced element should be a footnote")?;
if self.location() == footnote.location() {
bail!("footnote cannot reference itself");
}
footnote.declaration_location(engine)
}
_ => Ok(self.location().unwrap()),
}
}
}
impl Count for Packed<FootnoteElem> {
fn update(&self) -> Option<CounterUpdate> {
(!self.is_ref()).then(|| CounterUpdate::Step(NonZeroUsize::ONE))
}
}
/// The body of a footnote can be either some content or a label referencing
/// another footnote.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum FootnoteBody {
Content(Content),
Reference(Label),
}
cast! {
FootnoteBody,
self => match self {
Self::Content(v) => v.into_value(),
Self::Reference(v) => v.into_value(),
},
v: Content => Self::Content(v),
v: Label => Self::Reference(v),
}
/// An entry in a footnote list.
///
/// This function is not intended to be called directly. Instead, it is used in
/// set and show rules to customize footnote listings.
///
/// ```example
/// #show footnote.entry: set text(red)
///
/// My footnote listing
/// #footnote[It's down here]
/// has red text!
/// ```
///
/// _Note:_ Footnote entry properties must be uniform across each page run (a
/// page run is a sequence of pages without an explicit pagebreak in between).
/// For this reason, set and show rules for footnote entries should be defined
/// before any page content, typically at the very start of the document.
#[elem(name = "entry", title = "Footnote Entry", Locatable, Tagged, ShowSet)]
pub struct FootnoteEntry {
/// The footnote for this entry. Its location can be used to determine
/// the footnote counter state.
///
/// ```example
/// #show footnote.entry: it => {
/// let loc = it.note.location()
/// counter(footnote).display(at: loc, "1: ")
/// it.note.body
/// }
///
/// Customized #footnote[Hello]
/// listing #footnote[World! 🌏]
/// ```
#[required]
pub note: Packed<FootnoteElem>,
/// The separator between the document body and the footnote listing.
///
/// ```example
/// #set footnote.entry(
/// separator: repeat[.]
/// )
///
/// Testing a different separator.
/// #footnote[
/// Unconventional, but maybe
/// not that bad?
/// ]
/// ```
#[default(
LineElem::new()
.with_length(Ratio::new(0.3).into())
.with_stroke(Stroke {
thickness: Smart::Custom(Abs::pt(0.5).into()),
..Default::default()
})
.pack()
)]
pub separator: Content,
/// The amount of clearance between the document body and the separator.
///
/// ```example
/// #set footnote.entry(clearance: 3em)
///
/// Footnotes also need ...
/// #footnote[
/// ... some space to breathe.
/// ]
/// ```
#[default(Em::new(1.0).into())]
pub clearance: Length,
/// The gap between footnote entries.
///
/// ```example
/// #set footnote.entry(gap: 0.8em)
///
/// Footnotes:
/// #footnote[Spaced],
/// #footnote[Apart]
/// ```
#[default(Em::new(0.5).into())]
pub gap: Length,
/// The indent of each footnote entry.
///
/// ```example
/// #set footnote.entry(indent: 0em)
///
/// Footnotes:
/// #footnote[No],
/// #footnote[Indent]
/// ```
#[default(Em::new(1.0).into())]
pub indent: Length,
}
impl Packed<FootnoteEntry> {
/// Returns the location which should be attached to the entry, the linking
/// destination, the resolved numbers, and the body content.
pub fn realize(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<(Content, Content)> {
let span = self.span();
let default = StyleChain::default();
let numbering = self.note.numbering.get_ref(default);
let counter = Counter::of(FootnoteElem::ELEM);
let Some(loc) = self.note.location() else {
bail!(
self.span(), "footnote entry must have a location";
hint: "try using a query or a show rule to customize the footnote instead";
);
};
let num = counter.display_at(engine, loc, styles, numbering, span)?;
let alt = num.plain_text();
let sup = SuperElem::new(num).pack().spanned(span);
let prefix = DirectLinkElem::new(loc, sup, Some(alt)).pack().spanned(span);
let body = self.note.body_content().unwrap().clone();
Ok((prefix, body))
}
}
impl ShowSet for Packed<FootnoteEntry> {
fn show_set(&self, _: StyleChain) -> Styles {
let mut out = Styles::new();
out.set(ParElem::leading, Em::new(0.5).into());
out.set(TextElem::size, TextSize(Em::new(0.85).into()));
out
}
}
cast! {
FootnoteElem,
v: Content => v.unpack::<Self>().unwrap_or_else(Self::with_content)
}
/// This is an empty element inserted by the HTML footnote rule to indicate the
/// presence of the default footnote rule. It's only used by the error in
/// `FootnoteContainer::unsupported_with_custom_dom` and could be removed if
/// that's not needed anymore.
#[elem(Locatable)]
pub struct FootnoteMarker {}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/heading.rs | crates/typst-library/src/model/heading.rs | use std::num::NonZeroUsize;
use ecow::EcoString;
use typst_utils::NonZeroExt;
use crate::diag::SourceResult;
use crate::engine::Engine;
use crate::foundations::{
Content, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, Synthesize, elem,
};
use crate::introspection::{Count, Counter, CounterUpdate, Locatable, Tagged};
use crate::layout::{BlockElem, Em, Length};
use crate::model::{Numbering, Outlinable, Refable, Supplement};
use crate::text::{FontWeight, LocalName, TextElem, TextSize};
/// A section heading.
///
/// With headings, you can structure your document into sections. Each heading
/// has a _level,_ which starts at one and is unbounded upwards. This level
/// indicates the logical role of the following content (section, subsection,
/// etc.) A top-level heading indicates a top-level section of the document (not
/// the document's title). To insert a title, use the [`title`]($title) element
/// instead.
///
/// Typst can automatically number your headings for you. To enable numbering,
/// specify how you want your headings to be numbered with a
/// [numbering pattern or function]($numbering).
///
/// Independently of the numbering, Typst can also automatically generate an
/// [outline] of all headings for you. To exclude one or more headings from this
/// outline, you can set the `outlined` parameter to `{false}`.
///
/// When writing a [show rule]($styling/#show-rules) that accesses the
/// [`body` field]($heading.body) to create a completely custom look for
/// headings, make sure to wrap the content in a [`block`]($block) (which is
/// implicitly [sticky]($block.sticky) for headings through a built-in show-set
/// rule). This prevents headings from becoming "orphans", i.e. remaining
/// at the end of the page with the following content being on the next page.
///
/// # Example
/// ```example
/// #set heading(numbering: "1.a)")
///
/// = Introduction
/// In recent years, ...
///
/// == Preliminaries
/// To start, ...
/// ```
///
/// # Syntax
/// Headings have dedicated syntax: They can be created by starting a line with
/// one or multiple equals signs, followed by a space. The number of equals
/// signs determines the heading's logical nesting depth. The `{offset}` field
/// can be set to configure the starting depth.
///
/// # Accessibility
/// Headings are important for accessibility, as they help users of Assistive
/// Technologies (AT) like screen readers to navigate within your document.
/// Screen reader users will be able to skip from heading to heading, or get an
/// overview of all headings in the document.
///
/// To make your headings accessible, you should not skip heading levels. This
/// means that you should start with a first-level heading. Also, when the
/// previous heading was of level 3, the next heading should be of level 3
/// (staying at the same depth), level 4 (going exactly one level deeper), or
/// level 1 or 2 (new hierarchically higher headings).
///
/// # HTML export
/// As mentioned above, a top-level heading indicates a top-level section of
/// the document rather than its title. This is in contrast to the HTML `<h1>`
/// element of which there should be only one per document.
///
/// For this reason, in HTML export, a [`title`] element will turn into an
/// `<h1>` and headings turn into `<h2>` and lower (a level 1 heading thus turns
/// into `<h2>`, a level 2 heading into `<h3>`, etc).
#[elem(Locatable, Tagged, Synthesize, Count, ShowSet, LocalName, Refable, Outlinable)]
pub struct HeadingElem {
/// The absolute nesting depth of the heading, starting from one. If set
/// to `{auto}`, it is computed from `{offset + depth}`.
///
/// This is primarily useful for usage in [show rules]($styling/#show-rules)
/// (either with [`where`]($function.where) selectors or by accessing the
/// level directly on a shown heading).
///
/// ```example
/// #show heading.where(level: 2): set text(red)
///
/// = Level 1
/// == Level 2
///
/// #set heading(offset: 1)
/// = Also level 2
/// == Level 3
/// ```
pub level: Smart<NonZeroUsize>,
/// The relative nesting depth of the heading, starting from one. This is
/// combined with `{offset}` to compute the actual `{level}`.
///
/// This is set by the heading syntax, such that `[== Heading]` creates a
/// heading with logical depth of 2, but actual level `{offset + 2}`. If you
/// construct a heading manually, you should typically prefer this over
/// setting the absolute level.
#[default(NonZeroUsize::ONE)]
pub depth: NonZeroUsize,
/// The starting offset of each heading's `{level}`, used to turn its
/// relative `{depth}` into its absolute `{level}`.
///
/// ```example
/// = Level 1
///
/// #set heading(offset: 1, numbering: "1.1")
/// = Level 2
///
/// #heading(offset: 2, depth: 2)[
/// I'm level 4
/// ]
/// ```
#[default(0)]
pub offset: usize,
/// How to number the heading. Accepts a
/// [numbering pattern or function]($numbering) taking multiple numbers.
///
/// ```example
/// #set heading(numbering: "1.a.")
///
/// = A section
/// == A subsection
/// === A sub-subsection
/// ```
pub numbering: Option<Numbering>,
/// The resolved plain-text numbers.
///
/// This field is internal and only used for creating PDF bookmarks. We
/// don't currently have access to `World`, `Engine`, or `styles` in export,
/// which is needed to resolve the counter and numbering pattern into a
/// concrete string.
///
/// This remains unset if `numbering` is `None`.
#[internal]
#[synthesized]
pub numbers: EcoString,
/// A supplement for the heading.
///
/// For references to headings, this is added before the referenced number.
///
/// If a function is specified, it is passed the referenced heading and
/// should return content.
///
/// ```example
/// #set heading(numbering: "1.", supplement: [Chapter])
///
/// = Introduction <intro>
/// In @intro, we see how to turn
/// Sections into Chapters. And
/// in @intro[Part], it is done
/// manually.
/// ```
pub supplement: Smart<Option<Supplement>>,
/// Whether the heading should appear in the [outline].
///
/// Note that this property, if set to `{true}`, ensures the heading is also
/// shown as a bookmark in the exported PDF's outline (when exporting to
/// PDF). To change that behavior, use the `bookmarked` property.
///
/// ```example
/// #outline()
///
/// #heading[Normal]
/// This is a normal heading.
///
/// #heading(outlined: false)[Hidden]
/// This heading does not appear
/// in the outline.
/// ```
#[default(true)]
pub outlined: bool,
/// Whether the heading should appear as a bookmark in the exported PDF's
/// outline. Doesn't affect other export formats, such as PNG.
///
/// The default value of `{auto}` indicates that the heading will only
/// appear in the exported PDF's outline if its `outlined` property is set
/// to `{true}`, that is, if it would also be listed in Typst's [outline].
/// Setting this property to either `{true}` (bookmark) or `{false}` (don't
/// bookmark) bypasses that behavior.
///
/// ```example
/// #heading[Normal heading]
/// This heading will be shown in
/// the PDF's bookmark outline.
///
/// #heading(bookmarked: false)[Not bookmarked]
/// This heading won't be
/// bookmarked in the resulting
/// PDF.
/// ```
#[default(Smart::Auto)]
pub bookmarked: Smart<bool>,
/// The indent all but the first line of a heading should have.
///
/// The default value of `{auto}` uses the width of the numbering as indent
/// if the heading is aligned at the [start]($direction.start) of the [text
/// direction]($text.dir), and no indent for center and other alignments.
///
/// ```example
/// #set heading(numbering: "1.")
/// = A very, very, very, very, very, very long heading
///
/// #show heading: set align(center)
/// == A very long heading\ with center alignment
/// ```
#[default(Smart::Auto)]
pub hanging_indent: Smart<Length>,
/// The heading's title.
#[required]
pub body: Content,
}
impl HeadingElem {
pub fn resolve_level(&self, styles: StyleChain) -> NonZeroUsize {
self.level.get(styles).unwrap_or_else(|| {
NonZeroUsize::new(self.offset.get(styles) + self.depth.get(styles).get())
.expect("overflow to 0 on NoneZeroUsize + usize")
})
}
}
impl Synthesize for Packed<HeadingElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let supplement = match self.supplement.get_ref(styles) {
Smart::Auto => TextElem::packed(Self::local_name_in(styles)),
Smart::Custom(None) => Content::empty(),
Smart::Custom(Some(supplement)) => {
supplement.resolve(engine, styles, [self.clone().pack()])?
}
};
if let Some((numbering, location)) =
self.numbering.get_ref(styles).as_ref().zip(self.location())
// We are not early returning on error here because of
// https://github.com/typst/typst/issues/7428
//
// A more comprehensive fix might introduce the error catching logic
// of show rules for synthesis, too.
&& let Ok(numbers) = self.counter().display_at(
engine,
location,
styles,
numbering,
self.span(),
)
{
self.numbers = Some(numbers.plain_text());
}
let elem = self.as_mut();
elem.level.set(Smart::Custom(elem.resolve_level(styles)));
elem.supplement
.set(Smart::Custom(Some(Supplement::Content(supplement))));
Ok(())
}
}
impl ShowSet for Packed<HeadingElem> {
fn show_set(&self, styles: StyleChain) -> Styles {
let level = self.resolve_level(styles).get();
let scale = match level {
1 => 1.4,
2 => 1.2,
_ => 1.0,
};
let size = Em::new(scale);
let above = Em::new(if level == 1 { 1.8 } else { 1.44 }) / scale;
let below = Em::new(0.75) / scale;
let mut out = Styles::new();
out.set(TextElem::size, TextSize(size.into()));
out.set(TextElem::weight, FontWeight::BOLD);
out.set(BlockElem::above, Smart::Custom(above.into()));
out.set(BlockElem::below, Smart::Custom(below.into()));
out.set(BlockElem::sticky, true);
out
}
}
impl Count for Packed<HeadingElem> {
fn update(&self) -> Option<CounterUpdate> {
self.numbering
.get_ref(StyleChain::default())
.is_some()
.then(|| CounterUpdate::Step(self.resolve_level(StyleChain::default())))
}
}
impl Refable for Packed<HeadingElem> {
fn supplement(&self) -> Content {
// After synthesis, this should always be custom content.
match self.supplement.get_cloned(StyleChain::default()) {
Smart::Custom(Some(Supplement::Content(content))) => content,
_ => Content::empty(),
}
}
fn counter(&self) -> Counter {
Counter::of(HeadingElem::ELEM)
}
fn numbering(&self) -> Option<&Numbering> {
self.numbering.get_ref(StyleChain::default()).as_ref()
}
}
impl Outlinable for Packed<HeadingElem> {
fn outlined(&self) -> bool {
self.outlined.get(StyleChain::default())
}
fn level(&self) -> NonZeroUsize {
self.resolve_level(StyleChain::default())
}
fn prefix(&self, numbers: Content) -> Content {
numbers
}
fn body(&self) -> Content {
self.body.clone()
}
}
impl LocalName for Packed<HeadingElem> {
const KEY: &'static str = "heading";
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/cite.rs | crates/typst-library/src/model/cite.rs | use typst_syntax::Spanned;
use crate::diag::{At, HintedString, SourceResult, error};
use crate::engine::Engine;
use crate::foundations::{
Cast, Content, Derived, Label, Packed, Smart, StyleChain, Synthesize, cast, elem,
};
use crate::introspection::Locatable;
use crate::model::bibliography::Works;
use crate::model::{CslSource, CslStyle};
use crate::text::{Lang, Region, TextElem};
/// Cite a work from the bibliography.
///
/// Before you starting citing, you need to add a [bibliography] somewhere in
/// your document.
///
/// # Example
/// ```example
/// This was already noted by
/// pirates long ago. @arrgh
///
/// Multiple sources say ...
/// @arrgh @netwok.
///
/// You can also call `cite`
/// explicitly. #cite(<arrgh>)
///
/// #bibliography("works.bib")
/// ```
///
/// If your source name contains certain characters such as slashes, which are
/// not recognized by the `<>` syntax, you can explicitly call `label` instead.
///
/// ```typ
/// Computer Modern is an example of a modernist serif typeface.
/// #cite(label("DBLP:books/lib/Knuth86a")).
/// >>> #bibliography("works.bib")
/// ```
///
/// # Syntax
/// This function indirectly has dedicated syntax. [References]($ref) can be
/// used to cite works from the bibliography. The label then corresponds to the
/// citation key.
#[elem(Locatable, Synthesize)]
pub struct CiteElem {
/// The citation key that identifies the entry in the bibliography that
/// shall be cited, as a label.
///
/// ```example
/// // All the same
/// @netwok \
/// #cite(<netwok>) \
/// #cite(label("netwok"))
/// >>> #set text(0pt)
/// >>> #bibliography("works.bib", style: "apa")
/// ```
#[required]
pub key: Label,
/// A supplement for the citation such as page or chapter number.
///
/// In reference syntax, the supplement can be added in square brackets:
///
/// ```example
/// This has been proven. @distress[p.~7]
///
/// #bibliography("works.bib")
/// ```
pub supplement: Option<Content>,
/// The kind of citation to produce. Different forms are useful in different
/// scenarios: A normal citation is useful as a source at the end of a
/// sentence, while a "prose" citation is more suitable for inclusion in the
/// flow of text.
///
/// If set to `{none}`, the cited work is included in the bibliography, but
/// nothing will be displayed.
///
/// ```example
/// #cite(<netwok>, form: "prose")
/// show the outsized effects of
/// pirate life on the human psyche.
/// >>> #set text(0pt)
/// >>> #bibliography("works.bib", style: "apa")
/// ```
#[default(Some(CitationForm::Normal))]
pub form: Option<CitationForm>,
/// The citation style.
///
/// This can be:
/// - `{auto}` to automatically use the
/// [bibliography's style]($bibliography.style) for citations.
/// - A string with the name of one of the built-in styles (see below). Some
/// of the styles listed below appear twice, once with their full name and
/// once with a short alias.
/// - A path string to a [CSL file](https://citationstyles.org/). For more
/// details about paths, see the [Paths section]($syntax/#paths).
/// - Raw bytes from which a CSL style should be decoded.
#[parse(match args.named::<Spanned<Smart<CslSource>>>("style")? {
Some(Spanned { v: Smart::Custom(source), span }) => Some(Smart::Custom(
CslStyle::load(engine, Spanned::new(source, span))?
)),
Some(Spanned { v: Smart::Auto, .. }) => Some(Smart::Auto),
None => None,
})]
pub style: Smart<Derived<CslSource, CslStyle>>,
/// The text language setting where the citation is.
#[internal]
#[synthesized]
pub lang: Lang,
/// The text region setting where the citation is.
#[internal]
#[synthesized]
pub region: Option<Region>,
}
impl Synthesize for Packed<CiteElem> {
fn synthesize(&mut self, _: &mut Engine, styles: StyleChain) -> SourceResult<()> {
let elem = self.as_mut();
elem.lang = Some(styles.get(TextElem::lang));
elem.region = Some(styles.get(TextElem::region));
Ok(())
}
}
cast! {
CiteElem,
v: Content => v.unpack::<Self>().map_err(|_| "expected citation")?,
}
/// The form of the citation.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum CitationForm {
/// Display in the standard way for the active style.
#[default]
Normal,
/// Produces a citation that is suitable for inclusion in a sentence.
Prose,
/// Mimics a bibliography entry, with full information about the cited work.
Full,
/// Shows only the cited work's author(s).
Author,
/// Shows only the cited work's year.
Year,
}
/// A group of citations.
///
/// This is automatically created from adjacent citations during show rule
/// application.
#[elem(Locatable)]
pub struct CiteGroup {
/// The citations.
#[required]
pub children: Vec<Packed<CiteElem>>,
}
impl Packed<CiteGroup> {
pub fn realize(&self, engine: &mut Engine) -> SourceResult<Content> {
let location = self.location().unwrap();
let span = self.span();
Works::generate(engine, span)?
.citations
.get(&location)
.cloned()
.ok_or_else(failed_to_format_citation)
.at(span)?
}
}
/// The error message when a citation wasn't found in the pre-formatted list.
#[cold]
fn failed_to_format_citation() -> HintedString {
error!(
"cannot format citation in isolation";
hint: "check whether this citation is measured \
without being inserted into the document";
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/strong.rs | crates/typst-library/src/model/strong.rs | use crate::foundations::{Content, elem};
use crate::introspection::{Locatable, Tagged};
/// Strongly emphasizes content by increasing the font weight.
///
/// Increases the current font weight by a given `delta`.
///
/// # Example
/// ```example
/// This is *strong.* \
/// This is #strong[too.] \
///
/// #show strong: set text(red)
/// And this is *evermore.*
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: To strongly emphasize content,
/// simply enclose it in stars/asterisks (`*`). Note that this only works at
/// word boundaries. To strongly emphasize part of a word, you have to use the
/// function.
#[elem(title = "Strong Emphasis", keywords = ["bold", "weight"], Locatable, Tagged)]
pub struct StrongElem {
/// The delta to apply on the font weight.
///
/// ```example
/// #set strong(delta: 0)
/// No *effect!*
/// ```
#[default(300)]
pub delta: i64,
/// The content to strongly emphasize.
#[required]
pub body: Content,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/mod.rs | crates/typst-library/src/model/mod.rs | //! Structuring elements that define the document model.
mod bibliography;
mod cite;
mod document;
mod emph;
#[path = "enum.rs"]
mod enum_;
mod figure;
mod footnote;
mod heading;
mod link;
mod list;
#[path = "numbering.rs"]
mod numbering_;
mod outline;
mod par;
mod quote;
mod reference;
mod strong;
mod table;
mod terms;
mod title;
pub use self::bibliography::*;
pub use self::cite::*;
pub use self::document::*;
pub use self::emph::*;
pub use self::enum_::*;
pub use self::figure::*;
pub use self::footnote::*;
pub use self::heading::*;
pub use self::link::*;
pub use self::list::*;
pub use self::numbering_::*;
pub use self::outline::*;
pub use self::par::*;
pub use self::quote::*;
pub use self::reference::*;
pub use self::strong::*;
pub use self::table::*;
pub use self::terms::*;
pub use self::title::*;
use crate::foundations::Scope;
/// Hook up all `model` definitions.
pub fn define(global: &mut Scope) {
global.start_category(crate::Category::Model);
global.define_elem::<DocumentElem>();
global.define_elem::<ParElem>();
global.define_elem::<ParbreakElem>();
global.define_elem::<StrongElem>();
global.define_elem::<EmphElem>();
global.define_elem::<ListElem>();
global.define_elem::<EnumElem>();
global.define_elem::<TermsElem>();
global.define_elem::<LinkElem>();
global.define_elem::<TitleElem>();
global.define_elem::<HeadingElem>();
global.define_elem::<FigureElem>();
global.define_elem::<QuoteElem>();
global.define_elem::<FootnoteElem>();
global.define_elem::<OutlineElem>();
global.define_elem::<RefElem>();
global.define_elem::<CiteElem>();
global.define_elem::<BibliographyElem>();
global.define_elem::<TableElem>();
global.define_func::<numbering>();
global.reset_category();
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/bibliography.rs | crates/typst-library/src/model/bibliography.rs | use std::any::TypeId;
use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::{Arc, LazyLock};
use comemo::{Track, Tracked};
use ecow::{EcoString, EcoVec, eco_format};
use hayagriva::archive::ArchivedStyle;
use hayagriva::io::BibLaTeXError;
use hayagriva::{
BibliographyDriver, BibliographyRequest, CitationItem, CitationRequest, Library,
SpecificLocator, TransparentLocator, citationberg,
};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap};
use smallvec::SmallVec;
use typst_syntax::{Span, Spanned, SyntaxMode};
use typst_utils::{ManuallyHash, NonZeroExt, PicoStr};
use crate::World;
use crate::diag::{
At, HintedStrResult, LoadError, LoadResult, LoadedWithin, ReportPos,
SourceDiagnostic, SourceResult, StrResult, bail, error, warning,
};
use crate::engine::{Engine, Sink};
use crate::foundations::{
Bytes, CastInfo, Content, Context, Derived, FromValue, IntoValue, Label,
NativeElement, OneOrMultiple, Packed, Reflect, Scope, ShowSet, Smart, StyleChain,
Styles, Synthesize, Value, elem,
};
use crate::introspection::{
History, Introspect, Introspector, Locatable, Location, QueryIntrospection,
};
use crate::layout::{BlockBody, BlockElem, Em, HElem, PadElem};
use crate::loading::{DataSource, Load, LoadSource, Loaded, format_yaml_error};
use crate::model::{
CitationForm, CiteGroup, Destination, DirectLinkElem, FootnoteElem, HeadingElem,
LinkElem, Url,
};
use crate::routines::Routines;
use crate::text::{Lang, LocalName, Region, SmallcapsElem, SubElem, SuperElem, TextElem};
/// A bibliography / reference listing.
///
/// You can create a new bibliography by calling this function with a path
/// to a bibliography file in either one of two formats:
///
/// - A Hayagriva `.yaml`/`.yml` file. Hayagriva is a new bibliography
/// file format designed for use with Typst. Visit its
/// [documentation](https://github.com/typst/hayagriva/blob/main/docs/file-format.md)
/// for more details.
/// - A BibLaTeX `.bib` file.
///
/// As soon as you add a bibliography somewhere in your document, you can start
/// citing things with reference syntax (`[@key]`) or explicit calls to the
/// [citation]($cite) function (`[#cite(<key>)]`). The bibliography will only
/// show entries for works that were referenced in the document.
///
/// # Styles
/// Typst offers a wide selection of built-in
/// [citation and bibliography styles]($bibliography.style). Beyond those, you
/// can add and use custom [CSL](https://citationstyles.org/) (Citation Style
/// Language) files. Wondering which style to use? Here are some good defaults
/// based on what discipline you're working in:
///
/// | Fields | Typical Styles |
/// |-----------------|--------------------------------------------------------|
/// | Engineering, IT | `{"ieee"}` |
/// | Psychology, Life Sciences | `{"apa"}` |
/// | Social sciences | `{"chicago-author-date"}` |
/// | Humanities | `{"mla"}`, `{"chicago-notes"}`, `{"harvard-cite-them-right"}` |
/// | Economics | `{"harvard-cite-them-right"}` |
/// | Physics | `{"american-physics-society"}` |
///
/// # Example
/// ```example
/// This was already noted by
/// pirates long ago. @arrgh
///
/// Multiple sources say ...
/// @arrgh @netwok.
///
/// #bibliography("works.bib")
/// ```
#[elem(Locatable, Synthesize, ShowSet, LocalName)]
pub struct BibliographyElem {
/// One or multiple paths to or raw bytes for Hayagriva `.yaml` and/or
/// BibLaTeX `.bib` files.
///
/// This can be a:
/// - A path string to load a bibliography file from the given path. For
/// more details about paths, see the [Paths section]($syntax/#paths).
/// - Raw bytes from which the bibliography should be decoded.
/// - An array where each item is one of the above.
#[required]
#[parse(
let sources = args.expect("sources")?;
Bibliography::load(engine.world, sources)?
)]
pub sources: Derived<OneOrMultiple<DataSource>, Bibliography>,
/// The title of the bibliography.
///
/// - When set to `{auto}`, an appropriate title for the
/// [text language]($text.lang) will be used. This is the default.
/// - When set to `{none}`, the bibliography will not have a title.
/// - A custom title can be set by passing content.
///
/// The bibliography's heading will not be numbered by default, but you can
/// force it to be with a show-set rule:
/// `{show bibliography: set heading(numbering: "1.")}`
pub title: Smart<Option<Content>>,
/// Whether to include all works from the given bibliography files, even
/// those that weren't cited in the document.
///
/// To selectively add individual cited works without showing them, you can
/// also use the `cite` function with [`form`]($cite.form) set to `{none}`.
#[default(false)]
pub full: bool,
/// The bibliography style.
///
/// This can be:
/// - A string with the name of one of the built-in styles (see below). Some
/// of the styles listed below appear twice, once with their full name and
/// once with a short alias.
/// - A path string to a [CSL file](https://citationstyles.org/). For more
/// details about paths, see the [Paths section]($syntax/#paths).
/// - Raw bytes from which a CSL style should be decoded.
#[parse(match args.named::<Spanned<CslSource>>("style")? {
Some(source) => Some(CslStyle::load(engine, source)?),
None => None,
})]
#[default({
let default = ArchivedStyle::InstituteOfElectricalAndElectronicsEngineers;
Derived::new(CslSource::Named(default, None), CslStyle::from_archived(default))
})]
pub style: Derived<CslSource, CslStyle>,
/// The language setting where the bibliography is.
#[internal]
#[synthesized]
pub lang: Lang,
/// The region setting where the bibliography is.
#[internal]
#[synthesized]
pub region: Option<Region>,
}
impl BibliographyElem {
/// Find the document's bibliography.
pub fn find(engine: &mut Engine, span: Span) -> StrResult<Packed<Self>> {
let elems = engine.introspect(QueryIntrospection(Self::ELEM.select(), span));
let mut iter = elems.iter();
let Some(elem) = iter.next() else {
bail!("the document does not contain a bibliography");
};
if iter.next().is_some() {
bail!("multiple bibliographies are not yet supported");
}
Ok(elem.to_packed::<Self>().unwrap().clone())
}
/// Whether the bibliography contains the given key.
pub fn has(engine: &mut Engine, key: Label, span: Span) -> bool {
engine
.introspect(QueryIntrospection(Self::ELEM.select(), span))
.iter()
.any(|elem| elem.to_packed::<Self>().unwrap().sources.derived.has(key))
}
/// Find all bibliography keys.
pub fn keys(introspector: Tracked<Introspector>) -> Vec<(Label, Option<EcoString>)> {
let mut vec = vec![];
for elem in introspector.query(&Self::ELEM.select()).iter() {
let this = elem.to_packed::<Self>().unwrap();
for (key, entry) in this.sources.derived.iter() {
let detail = entry.title().map(|title| title.value.to_str().into());
vec.push((key, detail))
}
}
vec
}
}
impl Packed<BibliographyElem> {
/// Produces the heading for the bibliography, if any.
pub fn realize_title(&self, styles: StyleChain) -> Option<Content> {
self.title
.get_cloned(styles)
.unwrap_or_else(|| {
Some(TextElem::packed(Packed::<BibliographyElem>::local_name_in(styles)))
})
.map(|title| {
HeadingElem::new(title)
.with_depth(NonZeroUsize::ONE)
.pack()
.spanned(self.span())
})
}
}
impl Synthesize for Packed<BibliographyElem> {
fn synthesize(&mut self, _: &mut Engine, styles: StyleChain) -> SourceResult<()> {
let elem = self.as_mut();
elem.lang = Some(styles.get(TextElem::lang));
elem.region = Some(styles.get(TextElem::region));
Ok(())
}
}
impl ShowSet for Packed<BibliographyElem> {
fn show_set(&self, _: StyleChain) -> Styles {
const INDENT: Em = Em::new(1.0);
let mut out = Styles::new();
out.set(HeadingElem::numbering, None);
out.set(PadElem::left, INDENT.into());
out
}
}
impl LocalName for Packed<BibliographyElem> {
const KEY: &'static str = "bibliography";
}
/// A loaded bibliography.
#[derive(Clone, PartialEq, Hash)]
pub struct Bibliography(
Arc<ManuallyHash<IndexMap<Label, hayagriva::Entry, FxBuildHasher>>>,
);
impl Bibliography {
/// Load a bibliography from data sources.
fn load(
world: Tracked<dyn World + '_>,
sources: Spanned<OneOrMultiple<DataSource>>,
) -> SourceResult<Derived<OneOrMultiple<DataSource>, Self>> {
let loaded = sources.load(world)?;
let bibliography = Self::decode(&loaded)?;
Ok(Derived::new(sources.v, bibliography))
}
/// Decode a bibliography from loaded data sources.
#[comemo::memoize]
#[typst_macros::time(name = "load bibliography")]
fn decode(data: &[Loaded]) -> SourceResult<Bibliography> {
let mut map = IndexMap::default();
let mut duplicates = Vec::<EcoString>::new();
// We might have multiple bib/yaml files
for d in data.iter() {
let library = decode_library(d)?;
for entry in library {
let label = Label::new(PicoStr::intern(entry.key()))
.ok_or("bibliography contains entry with empty key")
.at(d.source.span)?;
match map.entry(label) {
indexmap::map::Entry::Vacant(vacant) => {
vacant.insert(entry);
}
indexmap::map::Entry::Occupied(_) => {
duplicates.push(entry.key().into());
}
}
}
}
if !duplicates.is_empty() {
// TODO: Store spans of entries for duplicate key error messages.
// Requires hayagriva entries to store their location, which should
// be fine, since they are 1kb anyway.
let span = data.first().unwrap().source.span;
bail!(span, "duplicate bibliography keys: {}", duplicates.join(", "));
}
Ok(Bibliography(Arc::new(ManuallyHash::new(map, typst_utils::hash128(data)))))
}
fn has(&self, key: Label) -> bool {
self.0.contains_key(&key)
}
fn get(&self, key: Label) -> Option<&hayagriva::Entry> {
self.0.get(&key)
}
fn iter(&self) -> impl Iterator<Item = (Label, &hayagriva::Entry)> {
self.0.iter().map(|(&k, v)| (k, v))
}
}
impl Debug for Bibliography {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_set().entries(self.0.keys()).finish()
}
}
/// Decode on library from one data source.
fn decode_library(loaded: &Loaded) -> SourceResult<Library> {
let data = loaded.data.as_str().within(loaded)?;
if let LoadSource::Path(file_id) = loaded.source.v {
// If we got a path, use the extension to determine whether it is
// YAML or BibLaTeX.
let ext = file_id
.vpath()
.as_rooted_path()
.extension()
.and_then(OsStr::to_str)
.unwrap_or_default();
match ext.to_lowercase().as_str() {
"yml" | "yaml" => hayagriva::io::from_yaml_str(data)
.map_err(format_yaml_error)
.within(loaded),
"bib" => hayagriva::io::from_biblatex_str(data)
.map_err(format_biblatex_error)
.within(loaded),
_ => bail!(
loaded.source.span,
"unknown bibliography format (must be .yaml/.yml or .bib)"
),
}
} else {
// If we just got bytes, we need to guess. If it can be decoded as
// hayagriva YAML, we'll use that.
let haya_err = match hayagriva::io::from_yaml_str(data) {
Ok(library) => return Ok(library),
Err(err) => err,
};
// If it can be decoded as BibLaTeX, we use that instead.
let bib_errs = match hayagriva::io::from_biblatex_str(data) {
// If the file is almost valid yaml, but contains no `@` character
// it will be successfully parsed as an empty BibLaTeX library,
// since BibLaTeX does support arbitrary text outside of entries.
Ok(library) if !library.is_empty() => return Ok(library),
Ok(_) => None,
Err(err) => Some(err),
};
// If neither decoded correctly, check whether `:` or `{` appears
// more often to guess whether it's more likely to be YAML or BibLaTeX
// and emit the more appropriate error.
let mut yaml = 0;
let mut biblatex = 0;
for c in data.chars() {
match c {
':' => yaml += 1,
'{' => biblatex += 1,
_ => {}
}
}
match bib_errs {
Some(bib_errs) if biblatex >= yaml => {
Err(format_biblatex_error(bib_errs)).within(loaded)
}
_ => Err(format_yaml_error(haya_err)).within(loaded),
}
}
}
/// Format a BibLaTeX loading error.
fn format_biblatex_error(errors: Vec<BibLaTeXError>) -> LoadError {
// TODO: return multiple errors?
let Some(error) = errors.into_iter().next() else {
// TODO: can this even happen, should we just unwrap?
return LoadError::new(
ReportPos::None,
"failed to parse BibLaTeX",
"something went wrong",
);
};
let (range, msg) = match error {
BibLaTeXError::Parse(error) => (error.span, error.kind.to_string()),
BibLaTeXError::Type(error) => (error.span, error.kind.to_string()),
};
LoadError::new(range, "failed to parse BibLaTeX", msg)
}
/// A loaded CSL style.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct CslStyle(Arc<ManuallyHash<citationberg::IndependentStyle>>);
impl CslStyle {
/// Load a CSL style from a data source.
pub fn load(
engine: &mut Engine,
Spanned { v: source, span }: Spanned<CslSource>,
) -> SourceResult<Derived<CslSource, Self>> {
let style = match &source {
CslSource::Named(style, deprecation) => {
if let Some(message) = deprecation {
engine.sink.warn(warning!(span, "{message}"));
}
Self::from_archived(*style)
}
CslSource::Normal(source) => {
let loaded = Spanned::new(source, span).load(engine.world)?;
Self::from_data(&loaded.data).within(&loaded)?
}
};
Ok(Derived::new(source, style))
}
/// Load a built-in CSL style.
#[comemo::memoize]
pub fn from_archived(archived: ArchivedStyle) -> CslStyle {
match archived.get() {
citationberg::Style::Independent(style) => Self(Arc::new(ManuallyHash::new(
style,
typst_utils::hash128(&(TypeId::of::<ArchivedStyle>(), archived)),
))),
// Ensured by `test_bibliography_load_builtin_styles`.
_ => unreachable!("archive should not contain dependent styles"),
}
}
/// Load a CSL style from file contents.
#[comemo::memoize]
pub fn from_data(bytes: &Bytes) -> LoadResult<CslStyle> {
let text = bytes.as_str()?;
citationberg::IndependentStyle::from_xml(text)
.map(|style| {
Self(Arc::new(ManuallyHash::new(
style,
typst_utils::hash128(&(TypeId::of::<Bytes>(), bytes)),
)))
})
.map_err(|err| {
LoadError::new(ReportPos::None, "failed to load CSL style", err)
})
}
/// Get the underlying independent style.
pub fn get(&self) -> &citationberg::IndependentStyle {
self.0.as_ref()
}
}
/// Source for a CSL style.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CslSource {
/// A predefined named style and potentially a deprecation warning.
Named(ArchivedStyle, Option<&'static str>),
/// A normal data source.
Normal(DataSource),
}
impl Reflect for CslSource {
#[comemo::memoize]
fn input() -> CastInfo {
let source = std::iter::once(DataSource::input());
/// All possible names and their short documentation for `ArchivedStyle`, including aliases.
static ARCHIVED_STYLE_NAMES: LazyLock<Vec<(&&str, &'static str)>> =
LazyLock::new(|| {
ArchivedStyle::all()
.iter()
.flat_map(|name| {
let (main_name, aliases) = name
.names()
.split_first()
.expect("all ArchivedStyle should have at least one name");
std::iter::once((main_name, name.display_name())).chain(
aliases.iter().map(move |alias| {
// Leaking is okay here, because we are in a `LazyLock`.
let docs: &'static str = Box::leak(
format!("A short alias of `{main_name}`")
.into_boxed_str(),
);
(alias, docs)
}),
)
})
.collect()
});
let names = ARCHIVED_STYLE_NAMES
.iter()
.map(|(value, docs)| CastInfo::Value(value.into_value(), docs));
CastInfo::Union(source.into_iter().chain(names).collect())
}
fn output() -> CastInfo {
DataSource::output()
}
fn castable(value: &Value) -> bool {
DataSource::castable(value)
}
}
impl FromValue for CslSource {
fn from_value(value: Value) -> HintedStrResult<Self> {
if EcoString::castable(&value) {
let string = EcoString::from_value(value.clone())?;
if Path::new(string.as_str()).extension().is_none() {
let mut warning = None;
if string.as_str() == "chicago-fullnotes" {
warning = Some(
"style \"chicago-fullnotes\" has been deprecated \
in favor of \"chicago-notes\"",
);
} else if string.as_str() == "modern-humanities-research-association" {
warning = Some(
"style \"modern-humanities-research-association\" \
has been deprecated in favor of \
\"modern-humanities-research-association-notes\"",
);
}
let style = ArchivedStyle::by_name(&string)
.ok_or_else(|| eco_format!("unknown style: {}", string))?;
return Ok(CslSource::Named(style, warning));
}
}
DataSource::from_value(value).map(CslSource::Normal)
}
}
impl IntoValue for CslSource {
fn into_value(self) -> Value {
match self {
// We prefer the shorter names which are at the back of the array.
Self::Named(v, _) => v.names().last().unwrap().into_value(),
Self::Normal(v) => v.into_value(),
}
}
}
/// Fully formatted citations and references, generated once (through
/// memoization) for the whole document. This setup is necessary because
/// citation formatting is inherently stateful and we need access to all
/// citations to do it.
pub struct Works {
/// Maps from the location of a citation group to its rendered content.
pub citations: FxHashMap<Location, SourceResult<Content>>,
/// Lists all references in the bibliography, with optional prefix, or
/// `None` if the citation style can't be used for bibliographies.
pub references: Option<Vec<(Option<Content>, Content, Location)>>,
/// Whether the bibliography should have hanging indent.
pub hanging_indent: bool,
}
impl Works {
/// Generate all citations and the whole bibliography.
pub fn generate(engine: &mut Engine, span: Span) -> SourceResult<Arc<Works>> {
let bibliography = BibliographyElem::find(engine, span).at(span)?;
let groups = engine.introspect(CiteGroupIntrospection(span));
Self::generate_impl(engine.routines, engine.world, bibliography, groups).at(span)
}
/// Generate all citations and the whole bibliography, given an existing
/// bibliography (no need to query it).
pub fn with_bibliography(
engine: &mut Engine,
bibliography: Packed<BibliographyElem>,
) -> SourceResult<Arc<Works>> {
let span = bibliography.span();
let groups = engine.introspect(CiteGroupIntrospection(span));
Self::generate_impl(engine.routines, engine.world, bibliography, groups).at(span)
}
/// The internal implementation of [`Works::generate`].
#[comemo::memoize]
fn generate_impl(
routines: &Routines,
world: Tracked<dyn World + '_>,
bibliography: Packed<BibliographyElem>,
groups: EcoVec<Content>,
) -> StrResult<Arc<Works>> {
let mut generator = Generator::new(routines, world, bibliography, groups)?;
let rendered = generator.drive();
let works = generator.display(&rendered)?;
Ok(Arc::new(works))
}
/// Extracts the generated references, failing with an error if none have
/// been generated.
pub fn references<'a>(
&'a self,
elem: &Packed<BibliographyElem>,
styles: StyleChain,
) -> SourceResult<&'a [(Option<Content>, Content, Location)]> {
self.references
.as_deref()
.ok_or_else(|| match elem.style.get_ref(styles).source {
CslSource::Named(style, _) => eco_format!(
"CSL style \"{}\" is not suitable for bibliographies",
style.display_name()
),
CslSource::Normal(..) => {
"CSL style is not suitable for bibliographies".into()
}
})
.at(elem.span())
}
}
/// Retrieves all citation groups in the document.
///
/// This is separate from `QueryIntrospection` so that we can customize the
/// diagnostic as the `CiteGroup` is internal. The default query message is also
/// not that helpful in this case.
#[derive(Debug, Clone, PartialEq, Hash)]
struct CiteGroupIntrospection(Span);
impl Introspect for CiteGroupIntrospection {
type Output = EcoVec<Content>;
fn introspect(
&self,
_: &mut Engine,
introspector: Tracked<Introspector>,
) -> Self::Output {
introspector.query(&CiteGroup::ELEM.select())
}
fn diagnose(&self, _: &History<Self::Output>) -> SourceDiagnostic {
warning!(
self.0, "citation grouping did not stabilize";
hint: "this can happen if the citations and bibliographies in the \
document did not stabilize by the end of the third layout iteration";
)
}
}
/// Context for generating the bibliography.
struct Generator<'a> {
/// The routines that are used to evaluate mathematical material in citations.
routines: &'a Routines,
/// The world that is used to evaluate mathematical material in citations.
world: Tracked<'a, dyn World + 'a>,
/// The document's bibliography.
bibliography: Packed<BibliographyElem>,
/// The document's citation groups.
groups: EcoVec<Content>,
/// Details about each group that are accumulated while driving hayagriva's
/// bibliography driver and needed when processing hayagriva's output.
infos: Vec<GroupInfo>,
/// Citations with unresolved keys.
failures: FxHashMap<Location, SourceResult<Content>>,
}
/// Details about a group of merged citations. All citations are put into groups
/// of adjacent ones (e.g., `@foo @bar` will merge into a group of length two).
/// Even single citations will be put into groups of length one.
struct GroupInfo {
/// The group's location.
location: Location,
/// The group's span.
span: Span,
/// Whether the group should be displayed in a footnote.
footnote: bool,
/// Details about the groups citations.
subinfos: SmallVec<[CiteInfo; 1]>,
}
/// Details about a citation item in a request.
struct CiteInfo {
/// The citation's key.
key: Label,
/// The citation's supplement.
supplement: Option<Content>,
/// Whether this citation was hidden.
hidden: bool,
}
impl<'a> Generator<'a> {
/// Create a new generator.
fn new(
routines: &'a Routines,
world: Tracked<'a, dyn World + 'a>,
bibliography: Packed<BibliographyElem>,
groups: EcoVec<Content>,
) -> StrResult<Self> {
let infos = Vec::with_capacity(groups.len());
Ok(Self {
routines,
world,
bibliography,
groups,
infos,
failures: FxHashMap::default(),
})
}
/// Drives hayagriva's citation driver.
fn drive(&mut self) -> hayagriva::Rendered {
static LOCALES: LazyLock<Vec<citationberg::Locale>> =
LazyLock::new(hayagriva::archive::locales);
let database = &self.bibliography.sources.derived;
let bibliography_style =
&self.bibliography.style.get_ref(StyleChain::default()).derived;
// Process all citation groups.
let mut driver = BibliographyDriver::new();
for elem in &self.groups {
let group = elem.to_packed::<CiteGroup>().unwrap();
let location = elem.location().unwrap();
let children = &group.children;
// Groups should never be empty.
let Some(first) = children.first() else { continue };
let mut subinfos = SmallVec::with_capacity(children.len());
let mut items = Vec::with_capacity(children.len());
let mut errors = EcoVec::new();
let mut normal = true;
// Create infos and items for each child in the group.
for child in children {
let Some(entry) = database.get(child.key) else {
errors.push(error!(
child.span(),
"key `{}` does not exist in the bibliography",
child.key.resolve(),
));
continue;
};
let supplement = child.supplement.get_cloned(StyleChain::default());
let locator = supplement.as_ref().map(|c| {
SpecificLocator(
citationberg::taxonomy::Locator::Custom,
hayagriva::LocatorPayload::Transparent(TransparentLocator::new(
c.clone(),
)),
)
});
let mut hidden = false;
let special_form = match child.form.get(StyleChain::default()) {
None => {
hidden = true;
None
}
Some(CitationForm::Normal) => None,
Some(CitationForm::Prose) => Some(hayagriva::CitePurpose::Prose),
Some(CitationForm::Full) => Some(hayagriva::CitePurpose::Full),
Some(CitationForm::Author) => Some(hayagriva::CitePurpose::Author),
Some(CitationForm::Year) => Some(hayagriva::CitePurpose::Year),
};
normal &= special_form.is_none();
subinfos.push(CiteInfo { key: child.key, supplement, hidden });
items.push(CitationItem::new(entry, locator, None, hidden, special_form));
}
if !errors.is_empty() {
self.failures.insert(location, Err(errors));
continue;
}
let style = match first.style.get_ref(StyleChain::default()) {
Smart::Auto => bibliography_style.get(),
Smart::Custom(style) => style.derived.get(),
};
self.infos.push(GroupInfo {
location,
subinfos,
span: first.span(),
footnote: normal
&& style.settings.class == citationberg::StyleClass::Note,
});
driver.citation(CitationRequest::new(
items,
style,
Some(locale(first.lang.unwrap_or(Lang::ENGLISH), first.region.flatten())),
&LOCALES,
None,
));
}
let locale = locale(
self.bibliography.lang.unwrap_or(Lang::ENGLISH),
self.bibliography.region.flatten(),
);
// Add hidden items for everything if we should print the whole
// bibliography.
if self.bibliography.full.get(StyleChain::default()) {
for (_, entry) in database.iter() {
driver.citation(CitationRequest::new(
vec![CitationItem::new(entry, None, None, true, None)],
bibliography_style.get(),
Some(locale.clone()),
&LOCALES,
None,
));
}
}
driver.finish(BibliographyRequest {
style: bibliography_style.get(),
locale: Some(locale),
locale_files: &LOCALES,
})
}
/// Displays hayagriva's output as content for the citations and references.
fn display(&mut self, rendered: &hayagriva::Rendered) -> StrResult<Works> {
let citations = self.display_citations(rendered)?;
let references = self.display_references(rendered)?;
let hanging_indent =
rendered.bibliography.as_ref().is_some_and(|b| b.hanging_indent);
Ok(Works { citations, references, hanging_indent })
}
/// Display the citation groups.
fn display_citations(
&mut self,
rendered: &hayagriva::Rendered,
) -> StrResult<FxHashMap<Location, SourceResult<Content>>> {
// Determine for each citation key where in the bibliography it is,
// so that we can link there.
let mut links = FxHashMap::default();
if let Some(bibliography) = &rendered.bibliography {
let location = self.bibliography.location().unwrap();
for (k, item) in bibliography.items.iter().enumerate() {
links.insert(item.key.as_str(), location.variant(k + 1));
}
}
let mut output = std::mem::take(&mut self.failures);
for (info, citation) in self.infos.iter().zip(&rendered.citations) {
let supplement = |i: usize| info.subinfos.get(i)?.supplement.clone();
let link = |i: usize| {
links.get(info.subinfos.get(i)?.key.resolve().as_str()).copied()
};
let renderer = ElemRenderer {
routines: self.routines,
world: self.world,
span: info.span,
supplement: &supplement,
link: &link,
};
let content = if info.subinfos.iter().all(|sub| sub.hidden) {
Content::empty()
} else {
let mut content =
renderer.display_elem_children(&citation.citation, None, true)?;
if info.footnote {
content = FootnoteElem::with_content(content).pack();
}
content
};
output.insert(info.location, Ok(content));
}
Ok(output)
}
/// Display the bibliography references.
#[allow(clippy::type_complexity)]
fn display_references(
&self,
rendered: &hayagriva::Rendered,
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/figure.rs | crates/typst-library/src/model/figure.rs | use std::borrow::Cow;
use std::num::NonZeroUsize;
use std::str::FromStr;
use ecow::EcoString;
use typst_utils::NonZeroExt;
use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Content, Element, NativeElement, Packed, Selector, ShowSet, Smart, StyleChain,
Styles, Synthesize, cast, elem, scope, select_where,
};
use crate::introspection::{
Count, Counter, CounterKey, CounterUpdate, Locatable, Location, Tagged,
};
use crate::layout::{
AlignElem, Alignment, BlockElem, Em, Length, OuterVAlignment, PlacementScope,
VAlignment,
};
use crate::model::{Numbering, NumberingPattern, Outlinable, Refable, Supplement};
use crate::text::{Lang, Locale, TextElem};
use crate::visualize::ImageElem;
/// A figure with an optional caption.
///
/// Automatically detects its kind to select the correct counting track. For
/// example, figures containing images will be numbered separately from figures
/// containing tables.
///
/// # Examples
/// The example below shows a basic figure with an image:
/// ```example
/// @glacier shows a glacier. Glaciers
/// are complex systems.
///
/// #figure(
/// image("glacier.jpg", width: 80%),
/// caption: [A curious figure.],
/// ) <glacier>
/// ```
///
/// You can also insert [tables]($table) into figures to give them a caption.
/// The figure will detect this and automatically use a separate counter.
///
/// ```example
/// #figure(
/// table(
/// columns: 4,
/// [t], [1], [2], [3],
/// [y], [0.3s], [0.4s], [0.8s],
/// ),
/// caption: [Timing results],
/// )
/// ```
///
/// This behaviour can be overridden by explicitly specifying the figure's
/// `kind`. All figures of the same kind share a common counter.
///
/// # Figure behaviour
/// By default, figures are placed within the flow of content. To make them
/// float to the top or bottom of the page, you can use the
/// [`placement`]($figure.placement) argument.
///
/// If your figure is too large and its contents are breakable across pages
/// (e.g. if it contains a large table), then you can make the figure itself
/// breakable across pages as well with this show rule:
/// ```typ
/// #show figure: set block(breakable: true)
/// ```
///
/// See the [block]($block.breakable) documentation for more information about
/// breakable and non-breakable blocks.
///
/// # Caption customization
/// You can modify the appearance of the figure's caption with its associated
/// [`caption`]($figure.caption) function. In the example below, we emphasize
/// all captions:
///
/// ```example
/// #show figure.caption: emph
///
/// #figure(
/// rect[Hello],
/// caption: [I am emphasized!],
/// )
/// ```
///
/// By using a [`where`]($function.where) selector, we can scope such rules to
/// specific kinds of figures. For example, to position the caption above
/// tables, but keep it below for all other kinds of figures, we could write the
/// following show-set rule:
///
/// ```example
/// #show figure.where(
/// kind: table
/// ): set figure.caption(position: top)
///
/// #figure(
/// table(columns: 2)[A][B][C][D],
/// caption: [I'm up here],
/// )
/// ```
///
/// # Accessibility
/// You can use the [`alt`]($figure.alt) parameter to provide an [alternative
/// description]($guides/accessibility/#textual-representations) of the figure
/// for screen readers and other Assistive Technology (AT). Refer to [its
/// documentation]($figure.alt) to learn more.
///
/// You can use figures to add alternative descriptions to paths, shapes, or
/// visualizations that do not have their own `alt` parameter. If your graphic
/// is purely decorative and does not have a semantic meaning, consider wrapping
/// it in [`pdf.artifact`] instead, which will hide it from AT when exporting to
/// PDF.
///
/// AT will always read the figure at the point where it appears in the
/// document, regardless of its [`placement`]($figure.placement). Put its markup
/// where it would make the most sense in the reading order.
#[elem(scope, Locatable, Tagged, Synthesize, Count, ShowSet, Refable, Outlinable)]
pub struct FigureElem {
/// The content of the figure. Often, an [image].
#[required]
pub body: Content,
/// An alternative description of the figure.
///
/// When you add an alternative description, AT will read both it and the
/// caption (if any). However, the content of the figure itself will be
/// skipped.
///
/// When the body of your figure is an [image]($image) with its own `alt`
/// text set, this parameter should not be used on the figure element.
/// Likewise, do not use this parameter when the figure contains a table,
/// code, or other content that is already accessible. In such cases, the
/// content of the figure will be read by AT, and adding an alternative
/// description would lead to a loss of information.
///
/// You can learn how to write good alternative descriptions in the
/// [Accessibility Guide]($guides/accessibility/#textual-representations).
pub alt: Option<EcoString>,
/// The figure's placement on the page.
///
/// - `{none}`: The figure stays in-flow exactly where it was specified
/// like other content.
/// - `{auto}`: The figure picks `{top}` or `{bottom}` depending on which
/// is closer.
/// - `{top}`: The figure floats to the top of the page.
/// - `{bottom}`: The figure floats to the bottom of the page.
///
/// The gap between the main flow content and the floating figure is
/// controlled by the [`clearance`]($place.clearance) argument on the
/// `place` function.
///
/// ```example
/// #set page(height: 200pt)
/// #show figure: set place(
/// clearance: 1em,
/// )
///
/// = Introduction
/// #figure(
/// placement: bottom,
/// caption: [A glacier],
/// image("glacier.jpg", width: 60%),
/// )
/// #lorem(60)
/// ```
pub placement: Option<Smart<VAlignment>>,
/// Relative to which containing scope the figure is placed.
///
/// Set this to `{"parent"}` to create a full-width figure in a two-column
/// document.
///
/// Has no effect if `placement` is `{none}`.
///
/// ```example
/// #set page(height: 250pt, columns: 2)
///
/// = Introduction
/// #figure(
/// placement: bottom,
/// scope: "parent",
/// caption: [A glacier],
/// image("glacier.jpg", width: 60%),
/// )
/// #lorem(60)
/// ```
pub scope: PlacementScope,
/// The figure's caption.
pub caption: Option<Packed<FigureCaption>>,
/// The kind of figure this is.
///
/// All figures of the same kind share a common counter.
///
/// If set to `{auto}`, the figure will try to automatically determine its
/// kind based on the type of its body. Automatically detected kinds are
/// [tables]($table) and [code]($raw). In other cases, the inferred kind is
/// that of an [image].
///
/// Setting this to something other than `{auto}` will override the
/// automatic detection. This can be useful if
/// - you wish to create a custom figure type that is not an
/// [image], a [table] or [code]($raw),
/// - you want to force the figure to use a specific counter regardless of
/// its content.
///
/// You can set the kind to be an element function or a string. If you set
/// it to an element function other than [`table`], [`raw`], or [`image`],
/// you will need to manually specify the figure's supplement.
///
/// ```example:"Customizing the figure kind"
/// #figure(
/// circle(radius: 10pt),
/// caption: [A curious atom.],
/// kind: "atom",
/// supplement: [Atom],
/// )
/// ```
///
/// If you want to modify a counter to skip a number or reset the counter,
/// you can access the [counter] of each kind of figure with a
/// [`where`]($function.where) selector:
///
/// - For [tables]($table): `{counter(figure.where(kind: table))}`
/// - For [images]($image): `{counter(figure.where(kind: image))}`
/// - For a custom kind: `{counter(figure.where(kind: kind))}`
///
/// ```example:"Modifying the figure counter for specific kinds"
/// #figure(
/// table(columns: 2, $n$, $1$),
/// caption: [The first table.],
/// )
///
/// #counter(
/// figure.where(kind: table)
/// ).update(41)
///
/// #figure(
/// table(columns: 2, $n$, $42$),
/// caption: [The 42nd table],
/// )
///
/// #figure(
/// rect[Image],
/// caption: [Does not affect images],
/// )
/// ```
///
/// To conveniently use the correct counter in a show rule, you can access
/// the `counter` field. There is an example of this in the documentation
/// [of the `figure.caption` element's `body` field]($figure.caption.body).
pub kind: Smart<FigureKind>,
/// The figure's supplement.
///
/// If set to `{auto}`, the figure will try to automatically determine the
/// correct supplement based on the `kind` and the active
/// [text language]($text.lang). If you are using a custom figure type, you
/// will need to manually specify the supplement.
///
/// If a function is specified, it is passed the first descendant of the
/// specified `kind` (typically, the figure's body) and should return
/// content.
///
/// ```example
/// #figure(
/// [The contents of my figure!],
/// caption: [My custom figure],
/// supplement: [Bar],
/// kind: "foo",
/// )
/// ```
pub supplement: Smart<Option<Supplement>>,
/// How to number the figure. Accepts a
/// [numbering pattern or function]($numbering) taking a single number.
#[default(Some(NumberingPattern::from_str("1").unwrap().into()))]
pub numbering: Option<Numbering>,
/// The vertical gap between the body and caption.
#[default(Em::new(0.65).into())]
pub gap: Length,
/// Whether the figure should appear in an [`outline`] of figures.
#[default(true)]
pub outlined: bool,
/// Convenience field to get access to the counter for this figure.
///
/// The counter only depends on the `kind`:
/// - For [tables]($table): `{counter(figure.where(kind: table))}`
/// - For [images]($image): `{counter(figure.where(kind: image))}`
/// - For a custom kind: `{counter(figure.where(kind: kind))}`
///
/// These are the counters you'll need to modify if you want to skip a
/// number or reset the counter.
#[synthesized]
pub counter: Option<Counter>,
/// The locale of this element (used for the alternative description).
#[internal]
#[synthesized]
pub locale: Locale,
}
#[scope]
impl FigureElem {
#[elem]
type FigureCaption;
}
impl FigureElem {
/// Retrieves the locale separator.
pub fn resolve_separator(&self, styles: StyleChain) -> Content {
match self.caption.get_ref(styles) {
Some(caption) => caption.resolve_separator(styles),
None => FigureCaption::local_separator_in(styles),
}
}
}
impl Synthesize for Packed<FigureElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let span = self.span();
let location = self.location();
let elem = self.as_mut();
let numbering = elem.numbering.get_ref(styles);
// Determine the figure's kind.
let kind = elem.kind.get_cloned(styles).unwrap_or_else(|| {
elem.body
.query_first_naive(&Selector::can::<dyn Figurable>())
.map(|elem| FigureKind::Elem(elem.func()))
.unwrap_or_else(|| FigureKind::Elem(ImageElem::ELEM))
});
// Resolve the supplement.
let supplement = match elem.supplement.get_ref(styles).as_ref() {
Smart::Auto => {
// Default to the local name for the kind, if available.
let name = match &kind {
FigureKind::Elem(func) => func
.local_name(
styles.get(TextElem::lang),
styles.get(TextElem::region),
)
.map(TextElem::packed),
FigureKind::Name(_) => None,
};
if numbering.is_some() && name.is_none() {
bail!(span, "please specify the figure's supplement")
}
Some(name.unwrap_or_default())
}
Smart::Custom(None) => None,
Smart::Custom(Some(supplement)) => {
// Resolve the supplement with the first descendant of the kind or
// just the body, if none was found.
let descendant = match kind {
FigureKind::Elem(func) => elem
.body
.query_first_naive(&Selector::Elem(func, None))
.map(Cow::Owned),
FigureKind::Name(_) => None,
};
let target = descendant.unwrap_or_else(|| Cow::Borrowed(&elem.body));
Some(supplement.resolve(engine, styles, [target])?)
}
};
// Construct the figure's counter.
let counter = Counter::new(CounterKey::Selector(
select_where!(FigureElem, kind => kind.clone()),
));
// Fill the figure's caption.
let mut caption = elem.caption.get_cloned(styles);
if let Some(caption) = &mut caption {
caption.synthesize(engine, styles)?;
caption.kind = Some(kind.clone());
caption.supplement = Some(supplement.clone());
caption.numbering = Some(numbering.clone());
caption.counter = Some(Some(counter.clone()));
caption.figure_location = Some(location);
}
elem.kind.set(Smart::Custom(kind));
elem.supplement
.set(Smart::Custom(supplement.map(Supplement::Content)));
elem.counter = Some(Some(counter));
elem.caption.set(caption);
elem.locale = Some(Locale::get_in(styles));
Ok(())
}
}
impl ShowSet for Packed<FigureElem> {
fn show_set(&self, _: StyleChain) -> Styles {
// Still allows breakable figures with
// `show figure: set block(breakable: true)`.
let mut map = Styles::new();
map.set(BlockElem::breakable, false);
map.set(AlignElem::alignment, Alignment::CENTER);
map
}
}
impl Count for Packed<FigureElem> {
fn update(&self) -> Option<CounterUpdate> {
// If the figure is numbered, step the counter by one.
// This steps the `counter(figure)` which is global to all numbered figures.
self.numbering()
.is_some()
.then(|| CounterUpdate::Step(NonZeroUsize::ONE))
}
}
impl Refable for Packed<FigureElem> {
fn supplement(&self) -> Content {
// After synthesis, this should always be custom content.
match self.supplement.get_cloned(StyleChain::default()) {
Smart::Custom(Some(Supplement::Content(content))) => content,
_ => Content::empty(),
}
}
fn counter(&self) -> Counter {
self.counter
.clone()
.flatten()
.unwrap_or_else(|| Counter::of(FigureElem::ELEM))
}
fn numbering(&self) -> Option<&Numbering> {
self.numbering.get_ref(StyleChain::default()).as_ref()
}
}
impl Outlinable for Packed<FigureElem> {
fn outlined(&self) -> bool {
self.outlined.get(StyleChain::default())
&& (self.caption.get_ref(StyleChain::default()).is_some()
|| self.numbering().is_some())
}
fn prefix(&self, numbers: Content) -> Content {
let supplement = self.supplement();
if !supplement.is_empty() {
supplement + TextElem::packed('\u{a0}') + numbers
} else {
numbers
}
}
fn body(&self) -> Content {
self.caption
.get_ref(StyleChain::default())
.as_ref()
.map(|caption| caption.body.clone())
.unwrap_or_default()
}
}
/// The caption of a figure. This element can be used in set and show rules to
/// customize the appearance of captions for all figures or figures of a
/// specific kind.
///
/// In addition to its `position` and `body`, the `caption` also provides the
/// figure's `kind`, `supplement`, `counter`, and `numbering` as fields. These
/// parts can be used in [`where`]($function.where) selectors and show rules to
/// build a completely custom caption.
///
/// ```example
/// #show figure.caption: emph
///
/// #figure(
/// rect[Hello],
/// caption: [A rectangle],
/// )
/// ```
#[elem(name = "caption", Locatable, Tagged, Synthesize)]
pub struct FigureCaption {
/// The caption's position in the figure. Either `{top}` or `{bottom}`.
///
/// ```example
/// #show figure.where(
/// kind: table
/// ): set figure.caption(position: top)
///
/// #figure(
/// table(columns: 2)[A][B],
/// caption: [I'm up here],
/// )
///
/// #figure(
/// rect[Hi],
/// caption: [I'm down here],
/// )
///
/// #figure(
/// table(columns: 2)[A][B],
/// caption: figure.caption(
/// position: bottom,
/// [I'm down here too!]
/// )
/// )
/// ```
#[default(OuterVAlignment::Bottom)]
pub position: OuterVAlignment,
/// The separator which will appear between the number and body.
///
/// If set to `{auto}`, the separator will be adapted to the current
/// [language]($text.lang) and [region]($text.region).
///
/// ```example
/// #set figure.caption(separator: [ --- ])
///
/// #figure(
/// rect[Hello],
/// caption: [A rectangle],
/// )
/// ```
pub separator: Smart<Content>,
/// The caption's body.
///
/// Can be used alongside `kind`, `supplement`, `counter`, `numbering`, and
/// `location` to completely customize the caption.
///
/// ```example
/// #show figure.caption: it => [
/// #underline(it.body) |
/// #it.supplement
/// #context it.counter.display(it.numbering)
/// ]
///
/// #figure(
/// rect[Hello],
/// caption: [A rectangle],
/// )
/// ```
#[required]
pub body: Content,
/// The figure's supplement.
#[synthesized]
pub kind: FigureKind,
/// The figure's supplement.
#[synthesized]
pub supplement: Option<Content>,
/// How to number the figure.
#[synthesized]
pub numbering: Option<Numbering>,
/// The counter for the figure.
#[synthesized]
pub counter: Option<Counter>,
/// The figure's location.
#[internal]
#[synthesized]
pub figure_location: Option<Location>,
}
impl Packed<FigureCaption> {
/// Realizes the textual caption content.
pub fn realize(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Content> {
let mut realized = self.body.clone();
if let (
Some(Some(mut supplement)),
Some(Some(numbering)),
Some(Some(counter)),
Some(Some(location)),
) = (
self.supplement.clone(),
&self.numbering,
&self.counter,
&self.figure_location,
) {
let numbers =
counter.display_at(engine, *location, styles, numbering, self.span())?;
if !supplement.is_empty() {
supplement += TextElem::packed('\u{a0}');
}
realized = supplement + numbers + self.resolve_separator(styles) + realized;
}
Ok(realized)
}
/// Retrieves the locale separator.
fn resolve_separator(&self, styles: StyleChain) -> Content {
self.separator
.get_cloned(styles)
.unwrap_or_else(|| FigureCaption::local_separator_in(styles))
}
}
impl FigureCaption {
/// Gets the default separator in the given language and (optionally)
/// region.
fn local_separator_in(styles: StyleChain) -> Content {
styles.get_cloned(FigureCaption::separator).unwrap_or_else(|| {
TextElem::packed(match styles.get(TextElem::lang) {
Lang::CHINESE => "\u{2003}",
Lang::FRENCH => ".\u{a0}– ",
Lang::RUSSIAN => ". ",
Lang::ENGLISH | _ => ": ",
})
})
}
}
impl Synthesize for Packed<FigureCaption> {
fn synthesize(&mut self, _: &mut Engine, styles: StyleChain) -> SourceResult<()> {
let separator = self.resolve_separator(styles);
self.separator.set(Smart::Custom(separator));
Ok(())
}
}
cast! {
FigureCaption,
v: Content => v.unpack::<Self>().unwrap_or_else(Self::new),
}
/// The `kind` parameter of a [`FigureElem`].
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum FigureKind {
/// The kind is an element function.
Elem(Element),
/// The kind is a name.
Name(EcoString),
}
cast! {
FigureKind,
self => match self {
Self::Elem(v) => v.into_value(),
Self::Name(v) => v.into_value(),
},
v: Element => Self::Elem(v),
v: EcoString => Self::Name(v),
}
/// An element that can be auto-detected in a figure.
///
/// This trait is used to determine the type of a figure.
pub trait Figurable {}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/outline.rs | crates/typst-library/src/model/outline.rs | use std::num::NonZeroUsize;
use std::str::FromStr;
use comemo::Tracked;
use smallvec::SmallVec;
use typst_syntax::Span;
use typst_utils::{Get, NonZeroExt};
use crate::diag::{At, HintedStrResult, SourceResult, StrResult, bail, error};
use crate::engine::Engine;
use crate::foundations::{
Args, Construct, Content, Context, Func, LocatableSelector, NativeElement, Packed,
Resolve, ShowSet, Smart, StyleChain, Styles, cast, elem, func, scope, select_where,
};
use crate::introspection::{
Counter, CounterKey, Locatable, Location, Locator, LocatorLink,
PageNumberingIntrospection, QueryIntrospection, Tagged, Unqueriable,
};
use crate::layout::{
Abs, Axes, BlockBody, BlockElem, BoxElem, Dir, Em, Fr, HElem, Length, Region, Rel,
RepeatElem, Sides,
};
use crate::model::{HeadingElem, NumberingPattern, ParElem, Refable};
use crate::pdf::PdfMarkerTag;
use crate::text::{LocalName, SpaceElem, TextElem};
/// A table of contents, figures, or other elements.
///
/// This function generates a list of all occurrences of an element in the
/// document, up to a given [`depth`]($outline.depth). The element's numbering
/// and page number will be displayed in the outline alongside its title or
/// caption.
///
/// # Example
/// ```example
/// #set heading(numbering: "1.")
/// #outline()
///
/// = Introduction
/// #lorem(5)
///
/// = Methods
/// == Setup
/// #lorem(10)
/// ```
///
/// # Alternative outlines
/// In its default configuration, this function generates a table of contents.
/// By setting the `target` parameter, the outline can be used to generate a
/// list of other kinds of elements than headings.
///
/// In the example below, we list all figures containing images by setting
/// `target` to `{figure.where(kind: image)}`. Just the same, we could have set
/// it to `{figure.where(kind: table)}` to generate a list of tables.
///
/// We could also set it to just `figure`, without using a [`where`]($function.where)
/// selector, but then the list would contain _all_ figures, be it ones
/// containing images, tables, or other material.
///
/// ```example
/// #outline(
/// title: [List of Figures],
/// target: figure.where(kind: image),
/// )
///
/// #figure(
/// image("tiger.jpg"),
/// caption: [A nice figure!],
/// )
/// ```
///
/// # Styling the outline
/// At the most basic level, you can style the outline by setting properties on
/// it and its entries. This way, you can customize the outline's
/// [title]($outline.title), how outline entries are
/// [indented]($outline.indent), and how the space between an entry's text and
/// its page number should be [filled]($outline.entry.fill).
///
/// Richer customization is possible through configuration of the outline's
/// [entries]($outline.entry). The outline generates one entry for each outlined
/// element.
///
/// ## Spacing the entries { #entry-spacing }
/// Outline entries are [blocks]($block), so you can adjust the spacing between
/// them with normal block-spacing rules:
///
/// ```example
/// #show outline.entry.where(
/// level: 1
/// ): set block(above: 1.2em)
///
/// #outline()
///
/// = About ACME Corp.
/// == History
/// === Origins
/// = Products
/// == ACME Tools
/// ```
///
/// ## Building an outline entry from its parts { #building-an-entry }
/// For full control, you can also write a transformational show rule on
/// `outline.entry`. However, the logic for properly formatting and indenting
/// outline entries is quite complex and the outline entry itself only contains
/// two fields: The level and the outlined element.
///
/// For this reason, various helper functions are provided. You can mix and
/// match these to compose an entry from just the parts you like.
///
/// The default show rule for an outline entry looks like this[^1]:
/// ```typ
/// #show outline.entry: it => link(
/// it.element.location(),
/// it.indented(it.prefix(), it.inner()),
/// )
/// ```
///
/// - The [`indented`]($outline.entry.indented) function takes an optional
/// prefix and inner content and automatically applies the proper indentation
/// to it, such that different entries align nicely and long headings wrap
/// properly.
///
/// - The [`prefix`]($outline.entry.prefix) function formats the element's
/// numbering (if any). It also appends a supplement for certain elements.
///
/// - The [`inner`]($outline.entry.inner) function combines the element's
/// [`body`]($outline.entry.body), the filler, and the
/// [`page` number]($outline.entry.page).
///
/// You can use these individual functions to format the outline entry in
/// different ways. Let's say, you'd like to fully remove the filler and page
/// numbers. To achieve this, you could write a show rule like this:
///
/// ```example
/// #show outline.entry: it => link(
/// it.element.location(),
/// // Keep just the body, dropping
/// // the fill and the page.
/// it.indented(it.prefix(), it.body()),
/// )
///
/// #outline()
///
/// = About ACME Corp.
/// == History
/// ```
///
/// [^1]: The outline of equations is the exception to this rule as it does not
/// have a body and thus does not use indented layout.
#[elem(scope, keywords = ["Table of Contents", "toc"], ShowSet, LocalName, Locatable, Tagged)]
pub struct OutlineElem {
/// The title of the outline.
///
/// - When set to `{auto}`, an appropriate title for the
/// [text language]($text.lang) will be used.
/// - When set to `{none}`, the outline will not have a title.
/// - A custom title can be set by passing content.
///
/// The outline's heading will not be numbered by default, but you can
/// force it to be with a show-set rule:
/// `{show outline: set heading(numbering: "1.")}`
pub title: Smart<Option<Content>>,
/// The type of element to include in the outline.
///
/// To list figures containing a specific kind of element, like an image or
/// a table, you can specify the desired kind in a [`where`]($function.where)
/// selector. See the section on [alternative outlines]($outline/#alternative-outlines)
/// for more details.
///
/// ```example
/// #outline(
/// title: [List of Tables],
/// target: figure.where(kind: table),
/// )
///
/// #figure(
/// table(
/// columns: 4,
/// [t], [1], [2], [3],
/// [y], [0.3], [0.7], [0.5],
/// ),
/// caption: [Experiment results],
/// )
/// ```
#[default(LocatableSelector(HeadingElem::ELEM.select()))]
pub target: LocatableSelector,
/// The maximum level up to which elements are included in the outline. When
/// this argument is `{none}`, all elements are included.
///
/// ```example
/// #set heading(numbering: "1.")
/// #outline(depth: 2)
///
/// = Yes
/// Top-level section.
///
/// == Still
/// Subsection.
///
/// === Nope
/// Not included.
/// ```
pub depth: Option<NonZeroUsize>,
/// How to indent the outline's entries.
///
/// - `{auto}`: Indents the numbering/prefix of a nested entry with the
/// title of its parent entry. If the entries are not numbered (e.g., via
/// [heading numbering]($heading.numbering)), this instead simply inserts
/// a fixed amount of `{1.2em}` indent per level.
///
/// - [Relative length]($relative): Indents the entry by the specified
/// length per nesting level. Specifying `{2em}`, for instance, would
/// indent top-level headings by `{0em}` (not nested), second level
/// headings by `{2em}` (nested once), third-level headings by `{4em}`
/// (nested twice) and so on.
///
/// - [Function]($function): You can further customize this setting with a
/// function. That function receives the nesting level as a parameter
/// (starting at 0 for top-level headings/elements) and should return a
/// (relative) length. For example, `{n => n * 2em}` would be equivalent
/// to just specifying `{2em}`.
///
/// ```example
/// >>> #show heading: none
/// #set heading(numbering: "I-I.")
/// #set outline(title: none)
///
/// #outline()
/// #line(length: 100%)
/// #outline(indent: 3em)
///
/// = Software engineering technologies
/// == Requirements
/// == Tools and technologies
/// === Code editors
/// == Analyzing alternatives
/// = Designing software components
/// = Testing and integration
/// ```
pub indent: Smart<OutlineIndent>,
}
#[scope]
impl OutlineElem {
#[elem]
type OutlineEntry;
}
impl Packed<OutlineElem> {
/// Produces the heading for the outline, if any.
pub fn realize_title(&self, styles: StyleChain) -> Option<Content> {
let span = self.span();
self.title
.get_cloned(styles)
.unwrap_or_else(|| {
Some(
TextElem::packed(Packed::<OutlineElem>::local_name_in(styles))
.spanned(span),
)
})
.map(|title| {
HeadingElem::new(title)
.with_depth(NonZeroUsize::ONE)
.pack()
.spanned(span)
})
}
/// Realizes the entries in a flat fashion.
pub fn realize_flat(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Vec<Packed<OutlineEntry>>> {
let mut entries = vec![];
for result in self.realize_iter(engine, styles) {
let (entry, _, included) = result?;
if included {
entries.push(entry);
}
}
Ok(entries)
}
/// Realizes the entries in a tree fashion.
pub fn realize_tree(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Vec<OutlineNode>> {
let flat = self.realize_iter(engine, styles).collect::<SourceResult<Vec<_>>>()?;
Ok(OutlineNode::build_tree(flat))
}
/// Realizes the entries as a lazy iterator.
fn realize_iter(
&self,
engine: &mut Engine,
styles: StyleChain,
) -> impl Iterator<Item = SourceResult<(Packed<OutlineEntry>, NonZeroUsize, bool)>>
{
let span = self.span();
let elems =
engine.introspect(QueryIntrospection(self.target.get_cloned(styles).0, span));
let depth = self.depth.get(styles).unwrap_or(NonZeroUsize::MAX);
elems.into_iter().map(move |elem| {
let Some(outlinable) = elem.with::<dyn Outlinable>() else {
bail!(self.span(), "cannot outline {}", elem.func().name());
};
let level = outlinable.level();
let include = outlinable.outlined() && level <= depth;
let entry = Packed::new(OutlineEntry::new(level, elem)).spanned(span);
Ok((entry, level, include))
})
}
}
/// A node in a tree of outline entry.
#[derive(Debug)]
pub struct OutlineNode<T = Packed<OutlineEntry>> {
/// The entry itself.
pub entry: T,
/// The entry's level.
pub level: NonZeroUsize,
/// Its descendants.
pub children: Vec<OutlineNode<T>>,
}
impl<T> OutlineNode<T> {
/// Turns a flat list of entries into a tree.
///
/// Each entry in the iterator should be accompanied by
/// - a level
/// - a boolean indicating whether it is included (`true`) or skipped (`false`)
pub fn build_tree(
flat: impl IntoIterator<Item = (T, NonZeroUsize, bool)>,
) -> Vec<Self> {
// Stores the level of the topmost skipped ancestor of the next included
// heading.
let mut last_skipped_level = None;
let mut tree: Vec<OutlineNode<T>> = vec![];
for (entry, level, include) in flat {
if include {
let mut children = &mut tree;
// Descend the tree through the latest included heading of each
// level until either:
// - reaching a node whose children would be siblings of this
// heading (=> add the current heading as a child of this
// node)
// - reaching a node with no children (=> this heading probably
// skipped a few nesting levels in Typst, or one or more
// ancestors of this heading weren't included, so add it as a
// child of this node, which is its deepest included ancestor)
// - or, if the latest heading(s) was(/were) skipped, then stop
// if reaching a node whose children would be siblings of the
// latest skipped heading of lowest level (=> those skipped
// headings would be ancestors of the current heading, so add
// it as a sibling of the least deep skipped ancestor among
// them, as those ancestors weren't added to the tree, and the
// current heading should not be mistakenly added as a
// descendant of a siblibg of that ancestor.)
//
// That is, if you had an included heading of level N, a skipped
// heading of level N, a skipped heading of level N + 1, and
// then an included heading of level N + 2, that last one is
// included as a level N heading (taking the place of its
// topmost skipped ancestor), so that it is not mistakenly added
// as a descendant of the previous level N heading.
while children.last().is_some_and(|last| {
last_skipped_level.is_none_or(|l| last.level < l)
&& last.level < level
}) {
children = &mut children.last_mut().unwrap().children;
}
// Since this heading was bookmarked, the next heading (if it is
// a child of this one) won't have a skipped direct ancestor.
last_skipped_level = None;
children.push(OutlineNode { entry, level, children: vec![] });
} else if last_skipped_level.is_none_or(|l| level < l) {
// Only the topmost / lowest-level skipped heading matters when
// we have consecutive skipped headings, hence the condition
// above.
last_skipped_level = Some(level);
}
}
tree
}
}
impl ShowSet for Packed<OutlineElem> {
fn show_set(&self, styles: StyleChain) -> Styles {
let mut out = Styles::new();
out.set(HeadingElem::outlined, false);
out.set(HeadingElem::numbering, None);
out.set(ParElem::justify, false);
out.set(BlockElem::above, Smart::Custom(styles.get(ParElem::leading).into()));
// Makes the outline itself available to its entries. Should be
// superseded by a proper ancestry mechanism in the future.
out.set(OutlineEntry::parent, Some(self.clone()));
out
}
}
impl LocalName for Packed<OutlineElem> {
const KEY: &'static str = "outline";
}
/// Defines how an outline is indented.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum OutlineIndent {
/// Indents by the specified length per level.
Rel(Rel),
/// Resolve the indent for a specific level through the given function.
Func(Func),
}
impl OutlineIndent {
/// Resolve the indent for an entry with the given level.
fn resolve(
&self,
engine: &mut Engine,
context: Tracked<Context>,
level: NonZeroUsize,
span: Span,
) -> SourceResult<Rel> {
let depth = level.get() - 1;
match self {
Self::Rel(length) => Ok(*length * depth as f64),
Self::Func(func) => func.call(engine, context, [depth])?.cast().at(span),
}
}
}
cast! {
OutlineIndent,
self => match self {
Self::Rel(v) => v.into_value(),
Self::Func(v) => v.into_value()
},
v: Rel<Length> => Self::Rel(v),
v: Func => Self::Func(v),
}
/// Marks an element as being able to be outlined.
pub trait Outlinable: Refable {
/// Whether this element should be included in the outline.
fn outlined(&self) -> bool;
/// The nesting level of this element.
fn level(&self) -> NonZeroUsize {
NonZeroUsize::ONE
}
/// Constructs the default prefix given the formatted numbering.
fn prefix(&self, numbers: Content) -> Content;
/// The body of the entry.
fn body(&self) -> Content;
}
/// Represents an entry line in an outline.
///
/// With show-set and show rules on outline entries, you can richly customize
/// the outline's appearance. See the
/// [section on styling the outline]($outline/#styling-the-outline) for details.
#[elem(scope, name = "entry", title = "Outline Entry", Locatable, Tagged)]
pub struct OutlineEntry {
/// The nesting level of this outline entry. Starts at `{1}` for top-level
/// entries.
#[required]
pub level: NonZeroUsize,
/// The element this entry refers to. Its location will be available
/// through the [`location`]($content.location) method on the content
/// and can be [linked]($link) to.
#[required]
pub element: Content,
/// Content to fill the space between the title and the page number. Can be
/// set to `{none}` to disable filling.
///
/// The `fill` will be placed into a fractionally sized box that spans the
/// space between the entry's body and the page number. When using show
/// rules to override outline entries, it is thus recommended to wrap the
/// fill in a [`box`] with fractional width, i.e.
/// `{box(width: 1fr, it.fill)}`.
///
/// When using [`repeat`], the [`gap`]($repeat.gap) property can be useful
/// to tweak the visual weight of the fill.
///
/// ```example
/// #set outline.entry(fill: line(length: 100%))
/// #outline()
///
/// = A New Beginning
/// ```
#[default(Some(
RepeatElem::new(TextElem::packed("."))
.with_gap(Em::new(0.15).into())
.pack()
))]
pub fill: Option<Content>,
/// Lets outline entries access the outline they are part of. This is a bit
/// of a hack and should be superseded by a proper ancestry mechanism.
#[ghost]
#[internal]
pub parent: Option<Packed<OutlineElem>>,
}
#[scope]
impl OutlineEntry {
/// A helper function for producing an indented entry layout: Lays out a
/// prefix and the rest of the entry in an indent-aware way.
///
/// If the parent outline's [`indent`]($outline.indent) is `{auto}`, the
/// inner content of all entries at level `N` is aligned with the prefix of
/// all entries at level `N + 1`, leaving at least `gap` space between the
/// prefix and inner parts. Furthermore, the `inner` contents of all entries
/// at the same level are aligned.
///
/// If the outline's indent is a fixed value or a function, the prefixes are
/// indented, but the inner contents are simply offset from the prefix by
/// the specified `gap`, rather than aligning outline-wide. For a visual
/// explanation, see [`outline.indent`].
#[func(contextual)]
pub fn indented(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// The `prefix` is aligned with the `inner` content of entries that
/// have level one less.
///
/// In the default show rule, this is just `it.prefix()`, but it can be
/// freely customized.
prefix: Option<Content>,
/// The formatted inner content of the entry.
///
/// In the default show rule, this is just `it.inner()`, but it can be
/// freely customized.
inner: Content,
/// The gap between the prefix and the inner content.
#[named]
#[default(Em::new(0.5).into())]
gap: Length,
) -> SourceResult<Content> {
let styles = context.styles().at(span)?;
let outline = styles
.get_ref(Self::parent)
.as_ref()
.ok_or("must be called within the context of an outline")
.at(span)?;
let outline_loc = outline.location().unwrap();
let prefix_width = prefix
.as_ref()
.map(|prefix| measure_prefix(engine, prefix, outline_loc, styles, span))
.transpose()?;
let prefix_inset = prefix_width.map(|w| w + gap.resolve(styles));
let indent = outline.indent.get_ref(styles);
let (base_indent, hanging_indent) = match &indent {
Smart::Auto => compute_auto_indents(
engine,
outline_loc,
styles,
self.level,
prefix_inset,
span,
),
Smart::Custom(amount) => {
let base = amount.resolve(engine, context, self.level, span)?;
(base, prefix_inset)
}
};
let body = if let (
Some(prefix),
Some(prefix_width),
Some(prefix_inset),
Some(hanging_indent),
) = (prefix, prefix_width, prefix_inset, hanging_indent)
{
// Save information about our prefix that other outline entries
// can query for (within `compute_auto_indent`) to align
// themselves).
let mut seq = Vec::with_capacity(5);
if indent.is_auto() {
seq.push(PrefixInfo::new(outline_loc, self.level, prefix_inset).pack());
}
// Dedent the prefix by the amount of hanging indent and then skip
// ahead so that the inner contents are aligned.
seq.extend([
HElem::new((-hanging_indent).into()).pack(),
PdfMarkerTag::Label(prefix),
HElem::new((hanging_indent - prefix_width).into()).pack(),
inner,
]);
Content::sequence(seq)
} else {
inner
};
let inset = Sides::default().with(
styles.resolve(TextElem::dir).start(),
Some(base_indent + Rel::from(hanging_indent.unwrap_or_default())),
);
Ok(BlockElem::new()
.with_inset(inset)
.with_body(Some(BlockBody::Content(body)))
.pack()
.spanned(span))
}
/// Formats the element's numbering (if any).
///
/// This also appends the element's supplement in case of figures or
/// equations. For instance, it would output `1.1` for a heading, but
/// `Figure 1` for a figure, as is usual for outlines.
#[func(contextual)]
pub fn prefix(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Option<Content>> {
let outlinable = self.outlinable().at(span)?;
let Some(numbering) = outlinable.numbering() else { return Ok(None) };
let loc = self.element_location().at(span)?;
let styles = context.styles().at(span)?;
let numbers = outlinable
.counter()
.display_at(engine, loc, styles, numbering, span)?;
Ok(Some(outlinable.prefix(numbers)))
}
/// Creates the default inner content of the entry.
///
/// This includes the body, the fill, and page number.
#[func(contextual)]
pub fn inner(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Content> {
let body = self.body().at(span)?;
let page = self.page(engine, context, span)?;
self.build_inner(context, span, body, page)
}
/// The content which is displayed in place of the referred element at its
/// entry in the outline. For a heading, this is its
/// [`body`]($heading.body); for a figure a caption and for equations, it is
/// empty.
#[func]
pub fn body(&self) -> StrResult<Content> {
Ok(self.outlinable()?.body())
}
/// The page number of this entry's element, formatted with the numbering
/// set for the referenced page.
#[func(contextual)]
pub fn page(
&self,
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
) -> SourceResult<Content> {
let loc = self.element_location().at(span)?;
let styles = context.styles().at(span)?;
let numbering = engine
.introspect(PageNumberingIntrospection(loc, span))
.unwrap_or_else(|| NumberingPattern::from_str("1").unwrap().into());
Counter::new(CounterKey::Page).display_at(engine, loc, styles, &numbering, span)
}
}
impl OutlineEntry {
pub fn build_inner(
&self,
context: Tracked<Context>,
span: Span,
body: Content,
page: Content,
) -> SourceResult<Content> {
let styles = context.styles().at(span)?;
let mut seq = vec![];
// Isolate the entry body in RTL because the page number is typically
// LTR. I'm not sure whether LTR should conceptually also be isolated,
// but in any case we don't do it for now because the text shaping
// pipeline does tend to choke a bit on default ignorables (in
// particular the CJK-Latin spacing).
//
// See also:
// - https://github.com/typst/typst/issues/4476
// - https://github.com/typst/typst/issues/5176
let rtl = styles.resolve(TextElem::dir) == Dir::RTL;
if rtl {
// "Right-to-Left Embedding"
seq.push(TextElem::packed("\u{202B}"));
}
seq.push(body);
if rtl {
// "Pop Directional Formatting"
seq.push(TextElem::packed("\u{202C}"));
}
// Add the filler between the section name and page number.
if let Some(filler) = self.fill.get_cloned(styles) {
seq.push(SpaceElem::shared().clone());
seq.push(
BoxElem::new()
.with_body(Some(filler))
.with_width(Fr::one().into())
.pack()
.spanned(span),
);
seq.push(SpaceElem::shared().clone());
} else {
seq.push(HElem::new(Fr::one().into()).pack().spanned(span));
}
// Add the page number. The word joiner in front ensures that the page
// number doesn't stand alone in its line.
seq.push(TextElem::packed("\u{2060}"));
seq.push(page);
Ok(Content::sequence(seq))
}
fn outlinable(&self) -> StrResult<&dyn Outlinable> {
self.element
.with::<dyn Outlinable>()
.ok_or_else(|| error!("cannot outline {}", self.element.func().name()))
}
/// Returns the location of the outlined element.
pub fn element_location(&self) -> HintedStrResult<Location> {
let elem = &self.element;
elem.location().ok_or_else(|| {
if elem.can::<dyn Outlinable>() {
error!(
"{} must have a location", elem.func().name();
hint: "try using a show rule to customize the outline.entry instead";
)
} else {
error!("cannot outline {}", elem.func().name())
}
})
}
}
cast! {
OutlineEntry,
v: Content => v.unpack::<Self>().map_err(|_| "expected outline entry")?
}
/// Measures the width of a prefix.
fn measure_prefix(
engine: &mut Engine,
prefix: &Content,
loc: Location,
styles: StyleChain,
span: Span,
) -> SourceResult<Abs> {
let pod = Region::new(Axes::splat(Abs::inf()), Axes::splat(false));
let link = LocatorLink::measure(loc, span);
Ok((engine.routines.layout_frame)(engine, prefix, Locator::link(&link), styles, pod)?
.width())
}
/// Compute the base indent and hanging indent for an auto-indented outline
/// entry of the given level, with the given prefix inset.
fn compute_auto_indents(
engine: &mut Engine,
outline_loc: Location,
styles: StyleChain,
level: NonZeroUsize,
prefix_inset: Option<Abs>,
span: Span,
) -> (Rel, Option<Abs>) {
let elems = engine.introspect(QueryIntrospection(
select_where!(PrefixInfo, key => outline_loc),
span,
));
let indents = determine_prefix_widths(&elems);
let fallback = Em::new(1.2).resolve(styles);
let get = |i: usize| indents.get(i).copied().flatten().unwrap_or(fallback);
let last = level.get() - 1;
let base: Abs = (0..last).map(get).sum();
let hang = prefix_inset.map(|p| p.max(get(last)));
(base.into(), hang)
}
/// Determines the maximum prefix inset (prefix width + gap) at each outline
/// level, for the outline with the given `loc`. Levels for which there is no
/// information available yield `None`.
#[comemo::memoize]
fn determine_prefix_widths(elems: &[Content]) -> SmallVec<[Option<Abs>; 4]> {
let mut widths = SmallVec::<[Option<Abs>; 4]>::new();
for elem in elems {
let info = elem.to_packed::<PrefixInfo>().unwrap();
let level = info.level.get();
if widths.len() < level {
widths.resize(level, None);
}
widths[level - 1].get_or_insert(info.inset).set_max(info.inset);
}
widths
}
/// Helper type for introspection-based prefix alignment.
#[elem(Construct, Unqueriable, Locatable)]
pub(crate) struct PrefixInfo {
/// The location of the outline this prefix is part of. This is used to
/// scope prefix computations to a specific outline.
#[required]
key: Location,
/// The level of this prefix's entry.
#[required]
#[internal]
level: NonZeroUsize,
/// The width of the prefix, including the gap.
#[required]
#[internal]
inset: Abs,
}
impl Construct for PrefixInfo {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/numbering.rs | crates/typst-library/src/model/numbering.rs | use std::str::FromStr;
use chinese_number::{
ChineseCase, ChineseVariant, from_u64_to_chinese_ten_thousand as u64_to_chinese,
};
use comemo::Tracked;
use ecow::{EcoString, EcoVec, eco_format};
use crate::diag::SourceResult;
use crate::engine::Engine;
use crate::foundations::{Context, Func, Str, Value, cast, func};
/// Applies a numbering to a sequence of numbers.
///
/// A numbering defines how a sequence of numbers should be displayed as
/// content. It is defined either through a pattern string or an arbitrary
/// function.
///
/// A numbering pattern consists of counting symbols, for which the actual
/// number is substituted, their prefixes, and one suffix. The prefixes and the
/// suffix are displayed as-is.
///
/// # Example
/// ```example
/// #numbering("1.1)", 1, 2, 3) \
/// #numbering("1.a.i", 1, 2) \
/// #numbering("I – 1", 12, 2) \
/// #numbering(
/// (..nums) => nums
/// .pos()
/// .map(str)
/// .join(".") + ")",
/// 1, 2, 3,
/// )
/// ```
///
/// # Numbering patterns and numbering functions
/// There are multiple instances where you can provide a numbering pattern or
/// function in Typst. For example, when defining how to number
/// [headings]($heading) or [figures]($figure). Every time, the expected format
/// is the same as the one described below for the
/// [`numbering`]($numbering.numbering) parameter.
///
/// The following example illustrates that a numbering function is just a
/// regular [function] that accepts numbers and returns [`content`].
/// ```example
/// #let unary(.., last) = "|" * last
/// #set heading(numbering: unary)
/// = First heading
/// = Second heading
/// = Third heading
/// ```
#[func]
pub fn numbering(
engine: &mut Engine,
context: Tracked<Context>,
/// Defines how the numbering works.
///
/// **Counting symbols** are `1`, `a`, `A`, `i`, `I`, `α`, `Α`, `一`, `壹`,
/// `あ`, `い`, `ア`, `イ`, `א`, `가`, `ㄱ`, `*`, `١`, `۱`, `१`, `১`, `ক`,
/// `①`, and `⓵`. They are replaced by the number in the sequence,
/// preserving the original case.
///
/// The `*` character means that symbols should be used to count, in the
/// order of `*`, `†`, `‡`, `§`, `¶`, `‖`. If there are more than six
/// items, the number is represented using repeated symbols.
///
/// **Suffixes** are all characters after the last counting symbol. They are
/// displayed as-is at the end of any rendered number.
///
/// **Prefixes** are all characters that are neither counting symbols nor
/// suffixes. They are displayed as-is at in front of their rendered
/// equivalent of their counting symbol.
///
/// This parameter can also be an arbitrary function that gets each number
/// as an individual argument. When given a function, the `numbering`
/// function just forwards the arguments to that function. While this is not
/// particularly useful in itself, it means that you can just give arbitrary
/// numberings to the `numbering` function without caring whether they are
/// defined as a pattern or function.
numbering: Numbering,
/// The numbers to apply the numbering to. Must be non-negative.
///
/// In general, numbers are counted from one. A number of zero indicates
/// that the first element has not yet appeared.
///
/// If `numbering` is a pattern and more numbers than counting symbols are
/// given, the last counting symbol with its prefix is repeated.
#[variadic]
numbers: Vec<u64>,
) -> SourceResult<Value> {
numbering.apply(engine, context, &numbers)
}
/// How to number a sequence of things.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Numbering {
/// A pattern with prefix, numbering, lower / upper case and suffix.
Pattern(NumberingPattern),
/// A closure mapping from an item's number to content.
Func(Func),
}
impl Numbering {
/// Apply the pattern to the given numbers.
pub fn apply(
&self,
engine: &mut Engine,
context: Tracked<Context>,
numbers: &[u64],
) -> SourceResult<Value> {
Ok(match self {
Self::Pattern(pattern) => Value::Str(pattern.apply(numbers).into()),
Self::Func(func) => func.call(engine, context, numbers.iter().copied())?,
})
}
/// Trim the prefix suffix if this is a pattern.
pub fn trimmed(mut self) -> Self {
if let Self::Pattern(pattern) = &mut self {
pattern.trimmed = true;
}
self
}
}
impl From<NumberingPattern> for Numbering {
fn from(pattern: NumberingPattern) -> Self {
Self::Pattern(pattern)
}
}
cast! {
Numbering,
self => match self {
Self::Pattern(pattern) => pattern.into_value(),
Self::Func(func) => func.into_value(),
},
v: NumberingPattern => Self::Pattern(v),
v: Func => Self::Func(v),
}
/// How to turn a number into text.
///
/// A pattern consists of a prefix, followed by one of the counter symbols (see
/// [`numbering()`] docs), and then a suffix.
///
/// Examples of valid patterns:
/// - `1)`
/// - `a.`
/// - `(I)`
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct NumberingPattern {
pub pieces: EcoVec<(EcoString, NumberingKind)>,
pub suffix: EcoString,
trimmed: bool,
}
impl NumberingPattern {
/// Apply the pattern to the given number.
pub fn apply(&self, numbers: &[u64]) -> EcoString {
let mut fmt = EcoString::new();
let mut numbers = numbers.iter();
for (i, ((prefix, kind), &n)) in self.pieces.iter().zip(&mut numbers).enumerate()
{
if i > 0 || !self.trimmed {
fmt.push_str(prefix);
}
fmt.push_str(&kind.apply(n));
}
for ((prefix, kind), &n) in self.pieces.last().into_iter().cycle().zip(numbers) {
if prefix.is_empty() {
fmt.push_str(&self.suffix);
} else {
fmt.push_str(prefix);
}
fmt.push_str(&kind.apply(n));
}
if !self.trimmed {
fmt.push_str(&self.suffix);
}
fmt
}
/// Apply only the k-th segment of the pattern to a number.
pub fn apply_kth(&self, k: usize, number: u64) -> EcoString {
let mut fmt = EcoString::new();
if let Some((prefix, _)) = self.pieces.first() {
fmt.push_str(prefix);
}
if let Some((_, kind)) = self
.pieces
.iter()
.chain(self.pieces.last().into_iter().cycle())
.nth(k)
{
fmt.push_str(&kind.apply(number));
}
fmt.push_str(&self.suffix);
fmt
}
/// How many counting symbols this pattern has.
pub fn pieces(&self) -> usize {
self.pieces.len()
}
}
impl FromStr for NumberingPattern {
type Err = &'static str;
fn from_str(pattern: &str) -> Result<Self, Self::Err> {
let mut pieces = EcoVec::new();
let mut handled = 0;
for (i, c) in pattern.char_indices() {
let Some(kind) = NumberingKind::from_char(c) else {
continue;
};
let prefix = pattern[handled..i].into();
pieces.push((prefix, kind));
handled = c.len_utf8() + i;
}
let suffix = pattern[handled..].into();
if pieces.is_empty() {
return Err("invalid numbering pattern");
}
Ok(Self { pieces, suffix, trimmed: false })
}
}
cast! {
NumberingPattern,
self => {
let mut pat = EcoString::new();
for (prefix, kind) in &self.pieces {
pat.push_str(prefix);
pat.push(kind.to_char());
}
pat.push_str(&self.suffix);
pat.into_value()
},
v: Str => v.parse()?,
}
/// Different kinds of numberings.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum NumberingKind {
/// Arabic numerals (1, 2, 3, etc.).
Arabic,
/// Lowercase Latin letters (a, b, c, etc.). Items beyond z use base-26.
LowerLatin,
/// Uppercase Latin letters (A, B, C, etc.). Items beyond Z use base-26.
UpperLatin,
/// Lowercase Roman numerals (i, ii, iii, etc.).
LowerRoman,
/// Uppercase Roman numerals (I, II, III, etc.).
UpperRoman,
/// Lowercase Greek letters (α, β, γ, etc.).
LowerGreek,
/// Uppercase Greek letters (Α, Β, Γ, etc.).
UpperGreek,
/// Paragraph/note-like symbols: *, †, ‡, §, ¶, and ‖. Further items use
/// repeated symbols.
Symbol,
/// Hebrew numerals, including Geresh/Gershayim.
Hebrew,
/// Simplified Chinese standard numerals. This corresponds to the
/// `ChineseCase::Lower` variant.
LowerSimplifiedChinese,
/// Simplified Chinese "banknote" numerals. This corresponds to the
/// `ChineseCase::Upper` variant.
UpperSimplifiedChinese,
// TODO: Pick the numbering pattern based on languages choice.
// As the first character of Simplified and Traditional Chinese numbering
// are the same, we are unable to determine if the context requires
// Simplified or Traditional by only looking at this character.
#[allow(unused)]
/// Traditional Chinese standard numerals. This corresponds to the
/// `ChineseCase::Lower` variant.
LowerTraditionalChinese,
#[allow(unused)]
/// Traditional Chinese "banknote" numerals. This corresponds to the
/// `ChineseCase::Upper` variant.
UpperTraditionalChinese,
/// Hiragana in the gojūon order. Includes n but excludes wi and we.
HiraganaAiueo,
/// Hiragana in the iroha order. Includes wi and we but excludes n.
HiraganaIroha,
/// Katakana in the gojūon order. Includes n but excludes wi and we.
KatakanaAiueo,
/// Katakana in the iroha order. Includes wi and we but excludes n.
KatakanaIroha,
/// Korean jamo (ㄱ, ㄴ, ㄷ, etc.).
KoreanJamo,
/// Korean syllables (가, 나, 다, etc.).
KoreanSyllable,
/// Eastern Arabic numerals, used in some Arabic-speaking countries.
EasternArabic,
/// The variant of Eastern Arabic numerals used in Persian and Urdu.
EasternArabicPersian,
/// Devanagari numerals.
DevanagariNumber,
/// Bengali numerals.
BengaliNumber,
/// Bengali letters (ক, খ, গ, ...কক, কখ etc.).
BengaliLetter,
/// Circled numbers (①, ②, ③, etc.), up to 50.
CircledNumber,
/// Double-circled numbers (⓵, ⓶, ⓷, etc.), up to 10.
DoubleCircledNumber,
}
impl NumberingKind {
/// Create a numbering kind from a representative character.
pub fn from_char(c: char) -> Option<Self> {
Some(match c {
'1' => NumberingKind::Arabic,
'a' => NumberingKind::LowerLatin,
'A' => NumberingKind::UpperLatin,
'i' => NumberingKind::LowerRoman,
'I' => NumberingKind::UpperRoman,
'α' => NumberingKind::LowerGreek,
'Α' => NumberingKind::UpperGreek,
'*' => NumberingKind::Symbol,
'א' => NumberingKind::Hebrew,
'一' => NumberingKind::LowerSimplifiedChinese,
'壹' => NumberingKind::UpperSimplifiedChinese,
'あ' => NumberingKind::HiraganaAiueo,
'い' => NumberingKind::HiraganaIroha,
'ア' => NumberingKind::KatakanaAiueo,
'イ' => NumberingKind::KatakanaIroha,
'ㄱ' => NumberingKind::KoreanJamo,
'가' => NumberingKind::KoreanSyllable,
'\u{0661}' => NumberingKind::EasternArabic,
'\u{06F1}' => NumberingKind::EasternArabicPersian,
'\u{0967}' => NumberingKind::DevanagariNumber,
'\u{09E7}' => NumberingKind::BengaliNumber,
'\u{0995}' => NumberingKind::BengaliLetter,
'①' => NumberingKind::CircledNumber,
'⓵' => NumberingKind::DoubleCircledNumber,
_ => return None,
})
}
/// The representative character for this numbering kind.
pub fn to_char(self) -> char {
match self {
Self::Arabic => '1',
Self::LowerLatin => 'a',
Self::UpperLatin => 'A',
Self::LowerRoman => 'i',
Self::UpperRoman => 'I',
Self::LowerGreek => 'α',
Self::UpperGreek => 'Α',
Self::Symbol => '*',
Self::Hebrew => 'א',
Self::LowerSimplifiedChinese | Self::LowerTraditionalChinese => '一',
Self::UpperSimplifiedChinese | Self::UpperTraditionalChinese => '壹',
Self::HiraganaAiueo => 'あ',
Self::HiraganaIroha => 'い',
Self::KatakanaAiueo => 'ア',
Self::KatakanaIroha => 'イ',
Self::KoreanJamo => 'ㄱ',
Self::KoreanSyllable => '가',
Self::EasternArabic => '\u{0661}',
Self::EasternArabicPersian => '\u{06F1}',
Self::DevanagariNumber => '\u{0967}',
Self::BengaliNumber => '\u{09E7}',
Self::BengaliLetter => '\u{0995}',
Self::CircledNumber => '①',
Self::DoubleCircledNumber => '⓵',
}
}
/// Apply the numbering to the given number.
pub fn apply(self, n: u64) -> EcoString {
match self {
Self::Arabic => {
numeric(&['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], n)
}
Self::LowerRoman => additive(
&[
("m̅", 1000000),
("d̅", 500000),
("c̅", 100000),
("l̅", 50000),
("x̅", 10000),
("v̅", 5000),
("i̅v̅", 4000),
("m", 1000),
("cm", 900),
("d", 500),
("cd", 400),
("c", 100),
("xc", 90),
("l", 50),
("xl", 40),
("x", 10),
("ix", 9),
("v", 5),
("iv", 4),
("i", 1),
("n", 0),
],
n,
),
Self::UpperRoman => additive(
&[
("M̅", 1000000),
("D̅", 500000),
("C̅", 100000),
("L̅", 50000),
("X̅", 10000),
("V̅", 5000),
("I̅V̅", 4000),
("M", 1000),
("CM", 900),
("D", 500),
("CD", 400),
("C", 100),
("XC", 90),
("L", 50),
("XL", 40),
("X", 10),
("IX", 9),
("V", 5),
("IV", 4),
("I", 1),
("N", 0),
],
n,
),
Self::LowerGreek => additive(
&[
("͵θ", 9000),
("͵η", 8000),
("͵ζ", 7000),
("͵ϛ", 6000),
("͵ε", 5000),
("͵δ", 4000),
("͵γ", 3000),
("͵β", 2000),
("͵α", 1000),
("ϡ", 900),
("ω", 800),
("ψ", 700),
("χ", 600),
("φ", 500),
("υ", 400),
("τ", 300),
("σ", 200),
("ρ", 100),
("ϟ", 90),
("π", 80),
("ο", 70),
("ξ", 60),
("ν", 50),
("μ", 40),
("λ", 30),
("κ", 20),
("ι", 10),
("θ", 9),
("η", 8),
("ζ", 7),
("ϛ", 6),
("ε", 5),
("δ", 4),
("γ", 3),
("β", 2),
("α", 1),
("𐆊", 0),
],
n,
),
Self::UpperGreek => additive(
&[
("͵Θ", 9000),
("͵Η", 8000),
("͵Ζ", 7000),
("͵Ϛ", 6000),
("͵Ε", 5000),
("͵Δ", 4000),
("͵Γ", 3000),
("͵Β", 2000),
("͵Α", 1000),
("Ϡ", 900),
("Ω", 800),
("Ψ", 700),
("Χ", 600),
("Φ", 500),
("Υ", 400),
("Τ", 300),
("Σ", 200),
("Ρ", 100),
("Ϟ", 90),
("Π", 80),
("Ο", 70),
("Ξ", 60),
("Ν", 50),
("Μ", 40),
("Λ", 30),
("Κ", 20),
("Ι", 10),
("Θ", 9),
("Η", 8),
("Ζ", 7),
("Ϛ", 6),
("Ε", 5),
("Δ", 4),
("Γ", 3),
("Β", 2),
("Α", 1),
("𐆊", 0),
],
n,
),
Self::Hebrew => additive(
&[
("ת", 400),
("ש", 300),
("ר", 200),
("ק", 100),
("צ", 90),
("פ", 80),
("ע", 70),
("ס", 60),
("נ", 50),
("מ", 40),
("ל", 30),
("כ", 20),
("יט", 19),
("יח", 18),
("יז", 17),
("טז", 16),
("טו", 15),
("י", 10),
("ט", 9),
("ח", 8),
("ז", 7),
("ו", 6),
("ה", 5),
("ד", 4),
("ג", 3),
("ב", 2),
("א", 1),
("-", 0),
],
n,
),
Self::LowerLatin => alphabetic(
&[
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
],
n,
),
Self::UpperLatin => alphabetic(
&[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
],
n,
),
Self::HiraganaAiueo => alphabetic(
&[
'あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ',
'し', 'す', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と', 'な', 'に',
'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ', 'ま', 'み', 'む',
'め', 'も', 'や', 'ゆ', 'よ', 'ら', 'り', 'る', 'れ', 'ろ', 'わ',
'を', 'ん',
],
n,
),
Self::HiraganaIroha => alphabetic(
&[
'い', 'ろ', 'は', 'に', 'ほ', 'へ', 'と', 'ち', 'り', 'ぬ', 'る',
'を', 'わ', 'か', 'よ', 'た', 'れ', 'そ', 'つ', 'ね', 'な', 'ら',
'む', 'う', 'ゐ', 'の', 'お', 'く', 'や', 'ま', 'け', 'ふ', 'こ',
'え', 'て', 'あ', 'さ', 'き', 'ゆ', 'め', 'み', 'し', 'ゑ', 'ひ',
'も', 'せ', 'す',
],
n,
),
Self::KatakanaAiueo => alphabetic(
&[
'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ',
'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ',
'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム',
'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ',
'ヲ', 'ン',
],
n,
),
Self::KatakanaIroha => alphabetic(
&[
'イ', 'ロ', 'ハ', 'ニ', 'ホ', 'ヘ', 'ト', 'チ', 'リ', 'ヌ', 'ル',
'ヲ', 'ワ', 'カ', 'ヨ', 'タ', 'レ', 'ソ', 'ツ', 'ネ', 'ナ', 'ラ',
'ム', 'ウ', 'ヰ', 'ノ', 'オ', 'ク', 'ヤ', 'マ', 'ケ', 'フ', 'コ',
'エ', 'テ', 'ア', 'サ', 'キ', 'ユ', 'メ', 'ミ', 'シ', 'ヱ', 'ヒ',
'モ', 'セ', 'ス',
],
n,
),
Self::KoreanJamo => alphabetic(
&[
'ㄱ', 'ㄴ', 'ㄷ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅅ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ',
'ㅌ', 'ㅍ', 'ㅎ',
],
n,
),
Self::KoreanSyllable => alphabetic(
&[
'가', '나', '다', '라', '마', '바', '사', '아', '자', '차', '카',
'타', '파', '하',
],
n,
),
Self::BengaliLetter => alphabetic(
&[
'ক', 'খ', 'গ', 'ঘ', 'ঙ', 'চ', 'ছ', 'জ', 'ঝ', 'ঞ', 'ট', 'ঠ', 'ড', 'ঢ',
'ণ', 'ত', 'থ', 'দ', 'ধ', 'ন', 'প', 'ফ', 'ব', 'ভ', 'ম', 'য', 'র', 'ল',
'শ', 'ষ', 'স', 'হ',
],
n,
),
Self::CircledNumber => fixed(
&[
'⓪', '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬',
'⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳', '㉑', '㉒', '㉓', '㉔', '㉕',
'㉖', '㉗', '㉘', '㉙', '㉚', '㉛', '㉜', '㉝', '㉞', '㉟', '㊱',
'㊲', '㊳', '㊴', '㊵', '㊶', '㊷', '㊸', '㊹', '㊺', '㊻', '㊼',
'㊽', '㊾', '㊿',
],
n,
),
Self::DoubleCircledNumber => {
fixed(&['0', '⓵', '⓶', '⓷', '⓸', '⓹', '⓺', '⓻', '⓼', '⓽', '⓾'], n)
}
Self::LowerSimplifiedChinese => {
u64_to_chinese(ChineseVariant::Simple, ChineseCase::Lower, n).into()
}
Self::UpperSimplifiedChinese => {
u64_to_chinese(ChineseVariant::Simple, ChineseCase::Upper, n).into()
}
Self::LowerTraditionalChinese => {
u64_to_chinese(ChineseVariant::Traditional, ChineseCase::Lower, n).into()
}
Self::UpperTraditionalChinese => {
u64_to_chinese(ChineseVariant::Traditional, ChineseCase::Upper, n).into()
}
Self::EasternArabic => {
numeric(&['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'], n)
}
Self::EasternArabicPersian => {
numeric(&['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'], n)
}
Self::DevanagariNumber => {
numeric(&['०', '१', '२', '३', '४', '५', '६', '७', '८', '९'], n)
}
Self::BengaliNumber => {
numeric(&['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'], n)
}
Self::Symbol => symbolic(&['*', '†', '‡', '§', '¶', '‖'], n),
}
}
}
/// Stringify a number using symbols representing values. The decimal
/// representation of the number is recovered by summing over the values of the
/// symbols present.
///
/// Consider the situation where ['I': 1, 'IV': 4, 'V': 5],
///
/// ```text
/// 1 => 'I'
/// 2 => 'II'
/// 3 => 'III'
/// 4 => 'IV'
/// 5 => 'V'
/// 6 => 'VI'
/// 7 => 'VII'
/// 8 => 'VIII'
/// ```
///
/// where this is the start of the familiar Roman numeral system.
fn additive(symbols: &[(&str, u64)], mut n: u64) -> EcoString {
if n == 0 {
if let Some(&(symbol, 0)) = symbols.last() {
return symbol.into();
}
return '0'.into();
}
let mut s = EcoString::new();
for (symbol, weight) in symbols {
if *weight == 0 || *weight > n {
continue;
}
let reps = n / weight;
for _ in 0..reps {
s.push_str(symbol);
}
n -= weight * reps;
if n == 0 {
return s;
}
}
s
}
/// Stringify a number using a base-n (where n is the number of provided
/// symbols) system without a zero symbol.
///
/// Consider the situation where ['A', 'B', 'C'] are the provided symbols,
///
/// ```text
/// 1 => 'A'
/// 2 => 'B'
/// 3 => 'C'
/// 4 => 'AA
/// 5 => 'AB'
/// 6 => 'AC'
/// 7 => 'BA'
/// ...
/// ```
///
/// This system is commonly used in spreadsheet software.
fn alphabetic(symbols: &[char], mut n: u64) -> EcoString {
let n_digits = symbols.len() as u64;
if n == 0 {
return '-'.into();
}
let mut s = EcoString::new();
while n != 0 {
n -= 1;
s.push(symbols[(n % n_digits) as usize]);
n /= n_digits;
}
s.chars().rev().collect()
}
/// Stringify a number using the symbols provided, defaulting to the arabic
/// representation when the number is greater than the number of symbols.
///
/// Consider the situation where ['0', 'A', 'B', 'C'] are the provided symbols,
///
/// ```text
/// 0 => '0'
/// 1 => 'A'
/// 2 => 'B'
/// 3 => 'C'
/// 4 => '4'
/// ...
/// n => 'n'
/// ```
fn fixed(symbols: &[char], n: u64) -> EcoString {
let n_digits = symbols.len() as u64;
if n < n_digits {
return symbols[(n) as usize].into();
}
eco_format!("{n}")
}
/// Stringify a number using a base-n (where n is the number of provided
/// symbols) system with a zero symbol.
///
/// Consider the situation where ['0', '1', '2'] are the provided symbols,
///
/// ```text
/// 0 => '0'
/// 1 => '1'
/// 2 => '2'
/// 3 => '10'
/// 4 => '11'
/// 5 => '12'
/// 6 => '20'
/// ...
/// ```
///
/// which is the familiar trinary counting system.
fn numeric(symbols: &[char], mut n: u64) -> EcoString {
let n_digits = symbols.len() as u64;
if n == 0 {
return symbols[0].into();
}
let mut s = EcoString::new();
while n != 0 {
s.push(symbols[(n % n_digits) as usize]);
n /= n_digits;
}
s.chars().rev().collect()
}
/// Stringify a number using repeating symbols.
///
/// Consider the situation where ['A', 'B', 'C'] are the provided symbols,
///
/// ```text
/// 0 => '-'
/// 1 => 'A'
/// 2 => 'B'
/// 3 => 'C'
/// 4 => 'AA'
/// 5 => 'BB'
/// 6 => 'CC'
/// 7 => 'AAA'
/// ...
/// ```
fn symbolic(symbols: &[char], n: u64) -> EcoString {
let n_digits = symbols.len() as u64;
if n == 0 {
return '-'.into();
}
EcoString::from(symbols[((n - 1) % n_digits) as usize])
.repeat((n.div_ceil(n_digits)) as usize)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/quote.rs | crates/typst-library/src/model/quote.rs | use typst_syntax::Span;
use crate::foundations::{
Content, Depth, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles,
cast, elem,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{BlockElem, Em, PadElem};
use crate::model::{CitationForm, CiteElem};
use crate::text::{SmartQuotes, SpaceElem, TextElem};
/// Displays a quote alongside an optional attribution.
///
/// # Example
/// ```example
/// Plato is often misquoted as the author of #quote[I know that I know
/// nothing], however, this is a derivation form his original quote:
///
/// #set quote(block: true)
///
/// #quote(attribution: [Plato])[
/// ... ἔοικα γοῦν τούτου γε σμικρῷ τινι αὐτῷ τούτῳ σοφώτερος εἶναι, ὅτι
/// ἃ μὴ οἶδα οὐδὲ οἴομαι εἰδέναι.
/// ]
/// #quote(attribution: [from the Henry Cary literal translation of 1897])[
/// ... I seem, then, in just this little thing to be wiser than this man at
/// any rate, that what I do not know I do not think I know either.
/// ]
/// ```
///
/// By default block quotes are padded left and right by `{1em}`, alignment and
/// padding can be controlled with show rules:
/// ```example
/// #set quote(block: true)
/// #show quote: set align(center)
/// #show quote: set pad(x: 5em)
///
/// #quote[
/// You cannot pass... I am a servant of the Secret Fire, wielder of the
/// flame of Anor. You cannot pass. The dark fire will not avail you,
/// flame of Udûn. Go back to the Shadow! You cannot pass.
/// ]
/// ```
#[elem(Locatable, Tagged, ShowSet)]
pub struct QuoteElem {
/// Whether this is a block quote.
///
/// ```example
/// An inline citation would look like
/// this: #quote(
/// attribution: [René Descartes]
/// )[
/// cogito, ergo sum
/// ], and a block equation like this:
/// #quote(
/// block: true,
/// attribution: [JFK]
/// )[
/// Ich bin ein Berliner.
/// ]
/// ```
pub block: bool,
/// Whether double quotes should be added around this quote.
///
/// The double quotes used are inferred from the `quotes` property on
/// [smartquote], which is affected by the `lang` property on [text].
///
/// - `{true}`: Wrap this quote in double quotes.
/// - `{false}`: Do not wrap this quote in double quotes.
/// - `{auto}`: Infer whether to wrap this quote in double quotes based on
/// the `block` property. If `block` is `{false}`, double quotes are
/// automatically added.
///
/// ```example
/// #set text(lang: "de")
///
/// Ein deutsch-sprechender Author
/// zitiert unter umständen JFK:
/// #quote[Ich bin ein Berliner.]
///
/// #set text(lang: "en")
///
/// And an english speaking one may
/// translate the quote:
/// #quote[I am a Berliner.]
/// ```
pub quotes: Smart<bool>,
/// The attribution of this quote, usually the author or source. Can be a
/// label pointing to a bibliography entry or any content. By default only
/// displayed for block quotes, but can be changed using a `{show}` rule.
///
/// ```example
/// #quote(attribution: [René Descartes])[
/// cogito, ergo sum
/// ]
///
/// #show quote.where(block: false): it => {
/// ["] + h(0pt, weak: true) + it.body + h(0pt, weak: true) + ["]
/// if it.attribution != none [ (#it.attribution)]
/// }
///
/// #quote(
/// attribution: link("https://typst.app/home")[typst.app]
/// )[
/// Compose papers faster
/// ]
///
/// #set quote(block: true)
///
/// #quote(attribution: <tolkien54>)[
/// You cannot pass... I am a servant
/// of the Secret Fire, wielder of the
/// flame of Anor. You cannot pass. The
/// dark fire will not avail you, flame
/// of Udûn. Go back to the Shadow! You
/// cannot pass.
/// ]
///
/// #bibliography("works.bib", style: "apa")
/// ```
pub attribution: Option<Attribution>,
/// The quote.
#[required]
pub body: Content,
/// The nesting depth.
#[internal]
#[fold]
#[ghost]
pub depth: Depth,
}
impl QuoteElem {
/// Quotes the body content with the appropriate quotes based on the current
/// styles and surroundings.
pub fn quoted(body: Content, styles: StyleChain<'_>) -> Content {
let quotes = SmartQuotes::get_in(styles);
// Alternate between single and double quotes.
let Depth(depth) = styles.get(QuoteElem::depth);
let double = depth % 2 == 0;
Content::sequence([
TextElem::packed(quotes.open(double)),
body,
TextElem::packed(quotes.close(double)),
])
.set(QuoteElem::depth, Depth(1))
}
}
/// Attribution for a [quote](QuoteElem).
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Attribution {
Content(Content),
Label(Label),
}
impl Attribution {
/// Realize as an em dash followed by text or a citation.
pub fn realize(&self, span: Span) -> Content {
Content::sequence([
TextElem::packed('—'),
SpaceElem::shared().clone(),
match self {
Attribution::Content(content) => content.clone(),
Attribution::Label(label) => CiteElem::new(*label)
.with_form(Some(CitationForm::Prose))
.pack()
.spanned(span),
},
])
}
}
cast! {
Attribution,
self => match self {
Self::Content(content) => content.into_value(),
Self::Label(label) => label.into_value(),
},
content: Content => Self::Content(content),
label: Label => Self::Label(label),
}
impl ShowSet for Packed<QuoteElem> {
fn show_set(&self, styles: StyleChain) -> Styles {
let mut out = Styles::new();
if self.block.get(styles) {
out.set(PadElem::left, Em::new(1.0).into());
out.set(PadElem::right, Em::new(1.0).into());
out.set(BlockElem::above, Smart::Custom(Em::new(2.4).into()));
out.set(BlockElem::below, Smart::Custom(Em::new(1.8).into()));
}
out
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/model/enum.rs | crates/typst-library/src/model/enum.rs | use std::str::FromStr;
use smallvec::SmallVec;
use crate::diag::{bail, warning};
use crate::foundations::{
Array, Content, Packed, Reflect, Smart, Styles, cast, elem, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Alignment, Em, HAlignment, Length, VAlignment};
use crate::model::{ListItemLike, ListLike, Numbering, NumberingPattern};
/// A numbered list.
///
/// Displays a sequence of items vertically and numbers them consecutively.
///
/// # Example
/// ```example
/// Automatically numbered:
/// + Preparations
/// + Analysis
/// + Conclusions
///
/// Manually numbered:
/// 2. What is the first step?
/// 5. I am confused.
/// + Moving on ...
///
/// Multiple lines:
/// + This enum item has multiple
/// lines because the next line
/// is indented.
///
/// Function call.
/// #enum[First][Second]
/// ```
///
/// You can easily switch all your enumerations to a different numbering style
/// with a set rule.
/// ```example
/// #set enum(numbering: "a)")
///
/// + Starting off ...
/// + Don't forget step two
/// ```
///
/// You can also use [`enum.item`] to programmatically customize the number of
/// each item in the enumeration:
///
/// ```example
/// #enum(
/// enum.item(1)[First step],
/// enum.item(5)[Fifth step],
/// enum.item(10)[Tenth step]
/// )
/// ```
///
/// # Syntax
/// This functions also has dedicated syntax:
///
/// - Starting a line with a plus sign creates an automatically numbered
/// enumeration item.
/// - Starting a line with a number followed by a dot creates an explicitly
/// numbered enumeration item.
///
/// Enumeration items can contain multiple paragraphs and other block-level
/// content. All content that is indented more than an item's marker becomes
/// part of that item.
#[elem(scope, title = "Numbered List", Locatable, Tagged)]
pub struct EnumElem {
/// Defines the default [spacing]($enum.spacing) of the enumeration. If it
/// is `{false}`, the items are spaced apart with
/// [paragraph spacing]($par.spacing). If it is `{true}`, they use
/// [paragraph leading]($par.leading) instead. This makes the list more
/// compact, which can look better if the items are short.
///
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// + If an enum has a lot of text, and
/// maybe other inline content, it
/// should not be tight anymore.
///
/// + To make an enum wide, simply
/// insert a blank line between the
/// items.
/// ```
#[default(true)]
pub tight: bool,
/// How to number the enumeration. Accepts a
/// [numbering pattern or function]($numbering).
///
/// If the numbering pattern contains multiple counting symbols, they apply
/// to nested enums. If given a function, the function receives one argument
/// if `full` is `{false}` and multiple arguments if `full` is `{true}`.
///
/// ```example
/// #set enum(numbering: "1.a)")
/// + Different
/// + Numbering
/// + Nested
/// + Items
/// + Style
///
/// #set enum(numbering: n => super[#n])
/// + Superscript
/// + Numbering!
/// ```
#[default(Numbering::Pattern(NumberingPattern::from_str("1.").unwrap()))]
pub numbering: Numbering,
/// Which number to start the enumeration with.
///
/// ```example
/// #enum(
/// start: 3,
/// [Skipping],
/// [Ahead],
/// )
/// ```
pub start: Smart<u64>,
/// Whether to display the full numbering, including the numbers of
/// all parent enumerations.
///
///
/// ```example
/// #set enum(numbering: "1.a)", full: true)
/// + Cook
/// + Heat water
/// + Add ingredients
/// + Eat
/// ```
#[default(false)]
pub full: bool,
/// Whether to reverse the numbering for this enumeration.
///
/// ```example
/// #set enum(reversed: true)
/// + Coffee
/// + Tea
/// + Milk
/// ```
#[default(false)]
pub reversed: bool,
/// The indentation of each item.
pub indent: Length,
/// The space between the numbering and the body of each item.
#[default(Em::new(0.5).into())]
pub body_indent: Length,
/// The spacing between the items of the enumeration.
///
/// If set to `{auto}`, uses paragraph [`leading`]($par.leading) for tight
/// enumerations and paragraph [`spacing`]($par.spacing) for wide
/// (non-tight) enumerations.
pub spacing: Smart<Length>,
/// The alignment that enum numbers should have.
///
/// By default, this is set to `{end + top}`, which aligns enum numbers
/// towards end of the current text direction (in left-to-right script,
/// for example, this is the same as `{right}`) and at the top of the line.
/// The choice of `{end}` for horizontal alignment of enum numbers is
/// usually preferred over `{start}`, as numbers then grow away from the
/// text instead of towards it, avoiding certain visual issues. This option
/// lets you override this behaviour, however. (Also to note is that the
/// [unordered list]($list) uses a different method for this, by giving the
/// `marker` content an alignment directly.).
///
/// ````example
/// #set enum(number-align: start + bottom)
///
/// Here are some powers of two:
/// 1. One
/// 2. Two
/// 4. Four
/// 8. Eight
/// 16. Sixteen
/// 32. Thirty two
/// ````
#[default(HAlignment::End + VAlignment::Top)]
pub number_align: Alignment,
/// The numbered list's items.
///
/// When using the enum syntax, adjacent items are automatically collected
/// into enumerations, even through constructs like for loops.
///
/// ```example
/// #for phase in (
/// "Launch",
/// "Orbit",
/// "Descent",
/// ) [+ #phase]
/// ```
#[variadic]
#[parse(
for item in args.items.iter() {
if item.name.is_none() && Array::castable(&item.value.v) {
engine.sink.warn(warning!(
item.value.span,
"implicit conversion from array to `enum.item` is deprecated";
hint: "use `enum.item(number)[body]` instead";
hint: "this conversion was never documented and is being phased out";
));
}
}
args.all()?
)]
pub children: Vec<Packed<EnumItem>>,
/// The numbers of parent items.
#[internal]
#[fold]
#[ghost]
pub parents: SmallVec<[u64; 4]>,
}
#[scope]
impl EnumElem {
#[elem]
type EnumItem;
}
/// An enumeration item.
#[elem(name = "item", title = "Numbered List Item", Tagged)]
pub struct EnumItem {
/// The item's number.
#[positional]
pub number: Smart<u64>,
/// The item's body.
#[required]
pub body: Content,
}
cast! {
EnumItem,
array: Array => {
let mut iter = array.into_iter();
let (number, body) = match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => (a.cast()?, b.cast()?),
_ => bail!("array must contain exactly two entries"),
};
Self::new(body).with_number(number)
},
v: Content => v.unpack::<Self>().unwrap_or_else(Self::new),
}
impl ListLike for EnumElem {
type Item = EnumItem;
fn create(children: Vec<Packed<Self::Item>>, tight: bool) -> Self {
Self::new(children).with_tight(tight)
}
}
impl ListItemLike for EnumItem {
fn styled(mut item: Packed<Self>, styles: Styles) -> Packed<Self> {
item.body.style_in_place(styles);
item
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/math/op.rs | crates/typst-library/src/math/op.rs | use ecow::EcoString;
use crate::foundations::{Content, NativeElement, Scope, SymbolElem, elem};
use crate::layout::HElem;
use crate::math::{Mathy, THIN, upright};
use crate::text::TextElem;
/// A text operator in an equation.
///
/// # Example
/// ```example
/// $ tan x = (sin x)/(cos x) $
/// $ op("custom",
/// limits: #true)_(n->oo) n $
/// ```
///
/// # Predefined Operators { #predefined }
/// Typst predefines the operators `arccos`, `arcsin`, `arctan`, `arg`, `cos`,
/// `cosh`, `cot`, `coth`, `csc`, `csch`, `ctg`, `deg`, `det`, `dim`, `exp`,
/// `gcd`, `lcm`, `hom`, `id`, `im`, `inf`, `ker`, `lg`, `lim`, `liminf`,
/// `limsup`, `ln`, `log`, `max`, `min`, `mod`, `Pr`, `sec`, `sech`, `sin`,
/// `sinc`, `sinh`, `sup`, `tan`, `tanh`, `tg` and `tr`.
#[elem(title = "Text Operator", Mathy)]
pub struct OpElem {
/// The operator's text.
#[required]
pub text: Content,
/// Whether the operator should show attachments as limits in display mode.
#[default(false)]
pub limits: bool,
}
macro_rules! ops {
($($name:ident $(: $value:literal)? $(($tts:tt))?),* $(,)?) => {
pub(super) fn define(math: &mut Scope) {
$({
let operator = EcoString::from(ops!(@name $name $(: $value)?));
math.define(
stringify!($name),
// Latex also uses their equivalent of `TextElem` here.
OpElem::new(TextElem::new(operator).into())
.with_limits(ops!(@limit $($tts)*))
.pack()
);
})*
let dif = |d| {
HElem::new(THIN.into()).with_weak(true).pack()
+ upright(SymbolElem::packed(d))
};
math.define("dif", dif('d'));
math.define("Dif", dif('D'));
}
};
(@name $name:ident) => { stringify!($name) };
(@name $name:ident: $value:literal) => { $value };
(@limit limits) => { true };
(@limit) => { false };
}
ops! {
arccos,
arcsin,
arctan,
arg,
cos,
cosh,
cot,
coth,
csc,
csch,
ctg,
deg,
det (limits),
dim,
exp,
gcd (limits),
lcm (limits),
hom,
id,
im,
inf (limits),
ker,
lg,
lim (limits),
liminf: "lim inf" (limits),
limsup: "lim sup" (limits),
ln,
log,
max (limits),
min (limits),
mod,
Pr (limits),
sec,
sech,
sin,
sinc,
sinh,
sup (limits),
tan,
tanh,
tg,
tr,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/math/underover.rs | crates/typst-library/src/math/underover.rs | use crate::foundations::{Content, elem};
use crate::math::Mathy;
/// A horizontal line under content.
///
/// ```example
/// $ underline(1 + 2 + ... + 5) $
/// ```
#[elem(Mathy)]
pub struct UnderlineElem {
/// The content above the line.
#[required]
pub body: Content,
}
/// A horizontal line over content.
///
/// ```example
/// $ overline(1 + 2 + ... + 5) $
/// ```
#[elem(Mathy)]
pub struct OverlineElem {
/// The content below the line.
#[required]
pub body: Content,
}
/// A horizontal brace under content, with an optional annotation below.
///
/// ```example
/// $ underbrace(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct UnderbraceElem {
/// The content above the brace.
#[required]
pub body: Content,
/// The optional content below the brace.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal brace over content, with an optional annotation above.
///
/// ```example
/// $ overbrace(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct OverbraceElem {
/// The content below the brace.
#[required]
pub body: Content,
/// The optional content above the brace.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal bracket under content, with an optional annotation below.
///
/// ```example
/// $ underbracket(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct UnderbracketElem {
/// The content above the bracket.
#[required]
pub body: Content,
/// The optional content below the bracket.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal bracket over content, with an optional annotation above.
///
/// ```example
/// $ overbracket(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct OverbracketElem {
/// The content below the bracket.
#[required]
pub body: Content,
/// The optional content above the bracket.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal parenthesis under content, with an optional annotation below.
///
/// ```example
/// $ underparen(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct UnderparenElem {
/// The content above the parenthesis.
#[required]
pub body: Content,
/// The optional content below the parenthesis.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal parenthesis over content, with an optional annotation above.
///
/// ```example
/// $ overparen(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct OverparenElem {
/// The content below the parenthesis.
#[required]
pub body: Content,
/// The optional content above the parenthesis.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal tortoise shell bracket under content, with an optional
/// annotation below.
///
/// ```example
/// $ undershell(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct UndershellElem {
/// The content above the tortoise shell bracket.
#[required]
pub body: Content,
/// The optional content below the tortoise shell bracket.
#[positional]
pub annotation: Option<Content>,
}
/// A horizontal tortoise shell bracket over content, with an optional
/// annotation above.
///
/// ```example
/// $ overshell(0 + 1 + dots.c + n, n + 1 "numbers") $
/// ```
#[elem(Mathy)]
pub struct OvershellElem {
/// The content below the tortoise shell bracket.
#[required]
pub body: Content,
/// The optional content above the tortoise shell bracket.
#[positional]
pub annotation: Option<Content>,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/math/frac.rs | crates/typst-library/src/math/frac.rs | use typst_syntax::Spanned;
use crate::diag::bail;
use crate::foundations::{Cast, Content, Value, elem};
use crate::math::Mathy;
/// A mathematical fraction.
///
/// # Example
/// ```example
/// $ 1/2 < (x+1)/2 $
/// $ ((x+1)) / 2 = frac(a, b) $
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: Use a slash to turn neighbouring
/// expressions into a fraction. Multiple atoms can be grouped into a single
/// expression using round grouping parentheses. Such parentheses are removed
/// from the output, but you can nest multiple to force them.
#[elem(title = "Fraction", Mathy)]
pub struct FracElem {
/// The fraction's numerator.
#[required]
pub num: Content,
/// The fraction's denominator.
#[required]
pub denom: Content,
/// How the fraction should be laid out.
///
/// ```example:"Styles"
/// $ frac(x, y, style: "vertical") $
/// $ frac(x, y, style: "skewed") $
/// $ frac(x, y, style: "horizontal") $
/// ```
///
/// ```example:"Setting the default"
/// #set math.frac(style: "skewed")
/// $ a / b $
/// ```
///
/// ```example:"Handling of grouping parentheses"
/// // Grouping parentheses are removed.
/// #set math.frac(style: "vertical")
/// $ (a + b) / b $
///
/// // Grouping parentheses are removed.
/// #set math.frac(style: "skewed")
/// $ (a + b) / b $
///
/// // Grouping parentheses are retained.
/// #set math.frac(style: "horizontal")
/// $ (a + b) / b $
/// ```
///
/// ```example:"Different styles in inline vs block equations"
/// // This changes the style for inline equations only.
/// #show math.equation.where(block: false): set math.frac(style: "horizontal")
///
/// This $(x-y)/z = 3$ is inline math, and this is block math:
/// $ (x-y)/z = 3 $
/// ```
#[default(FracStyle::Vertical)]
pub style: FracStyle,
/// Whether the numerator was originally surrounded by parentheses
/// that were stripped by the parser.
#[internal]
#[parse(None)]
#[default(false)]
pub num_deparenthesized: bool,
/// Whether the denominator was originally surrounded by parentheses
/// that were stripped by the parser.
#[internal]
#[parse(None)]
#[default(false)]
pub denom_deparenthesized: bool,
}
/// Fraction style
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FracStyle {
/// Stacked numerator and denominator with a bar.
#[default]
Vertical,
/// Numerator and denominator separated by a slash.
Skewed,
/// Numerator and denominator placed inline and parentheses are not
/// absorbed.
Horizontal,
}
/// A binomial expression.
///
/// # Example
/// ```example
/// $ binom(n, k) $
/// $ binom(n, k_1, k_2, k_3, ..., k_m) $
/// ```
#[elem(title = "Binomial", Mathy)]
pub struct BinomElem {
/// The binomial's upper index.
#[required]
pub upper: Content,
/// The binomial's lower index.
#[required]
#[variadic]
#[parse(
let values = args.all::<Spanned<Value>>()?;
if values.is_empty() {
// Prevents one element binomials
bail!(args.span, "missing argument: lower");
}
values.into_iter().map(|spanned| spanned.v.display()).collect()
)]
pub lower: Vec<Content>,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-library/src/math/root.rs | crates/typst-library/src/math/root.rs | use typst_syntax::Span;
use crate::foundations::{Content, NativeElement, elem, func};
use crate::math::Mathy;
/// A square root.
///
/// ```example
/// $ sqrt(3 - 2 sqrt(2)) = sqrt(2) - 1 $
/// ```
#[func(title = "Square Root")]
pub fn sqrt(
span: Span,
/// The expression to take the square root of.
radicand: Content,
) -> Content {
RootElem::new(radicand).pack().spanned(span)
}
/// A general root.
///
/// ```example
/// $ root(3, x) $
/// ```
#[elem(Mathy)]
pub struct RootElem {
/// Which root of the radicand to take.
#[positional]
pub index: Option<Content>,
/// The expression to take the root of.
#[required]
pub radicand: Content,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.