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-library/src/math/cancel.rs | crates/typst-library/src/math/cancel.rs | use crate::foundations::{Content, Func, Smart, cast, elem};
use crate::layout::{Angle, Em, Length, Ratio, Rel};
use crate::math::Mathy;
use crate::visualize::Stroke;
/// Displays a diagonal line over a part of an equation.
///
/// This is commonly used to show the elimination of a term.
///
/// # Example
/// ```example
/// >>> #set page(width: 140pt)
/// Here, we can simplify:
/// $ (a dot b dot cancel(x)) /
/// cancel(x) $
/// ```
#[elem(Mathy)]
pub struct CancelElem {
/// The content over which the line should be placed.
#[required]
pub body: Content,
/// The length of the line, relative to the length of the diagonal spanning
/// the whole element being "cancelled". A value of `{100%}` would then have
/// the line span precisely the element's diagonal.
///
/// ```example
/// >>> #set page(width: 140pt)
/// $ a + cancel(x, length: #200%)
/// - cancel(x, length: #200%) $
/// ```
#[default(Rel::new(Ratio::one(), Em::new(0.3).into()))]
pub length: Rel<Length>,
/// Whether the cancel line should be inverted (flipped along the y-axis).
/// For the default angle setting, inverted means the cancel line
/// points to the top left instead of top right.
///
/// ```example
/// >>> #set page(width: 140pt)
/// $ (a cancel((b + c), inverted: #true)) /
/// cancel(b + c, inverted: #true) $
/// ```
#[default(false)]
pub inverted: bool,
/// Whether two opposing cancel lines should be drawn, forming a cross over
/// the element. Overrides `inverted`.
///
/// ```example
/// >>> #set page(width: 140pt)
/// $ cancel(Pi, cross: #true) $
/// ```
#[default(false)]
pub cross: bool,
/// How much to rotate the cancel line.
///
/// - If given an angle, the line is rotated by that angle clockwise with
/// respect to the y-axis.
/// - If `{auto}`, the line assumes the default angle; that is, along the
/// rising diagonal of the content box.
/// - If given a function `angle => angle`, the line is rotated, with
/// respect to the y-axis, by the angle returned by that function. The
/// function receives the default angle as its input.
///
/// ```example
/// >>> #set page(width: 140pt)
/// $ cancel(Pi)
/// cancel(Pi, angle: #0deg)
/// cancel(Pi, angle: #45deg)
/// cancel(Pi, angle: #90deg)
/// cancel(1/(1+x), angle: #(a => a + 45deg))
/// cancel(1/(1+x), angle: #(a => a + 90deg)) $
/// ```
pub angle: Smart<CancelAngle>,
/// How to [stroke]($stroke) the cancel line.
///
/// ```example
/// >>> #set page(width: 140pt)
/// $ cancel(
/// sum x,
/// stroke: #(
/// paint: red,
/// thickness: 1.5pt,
/// dash: "dashed",
/// ),
/// ) $
/// ```
#[fold]
#[default(Stroke {
// Default stroke has 0.05em for better visuals.
thickness: Smart::Custom(Em::new(0.05).into()),
..Default::default()
})]
pub stroke: Stroke,
}
/// Defines the cancel line.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CancelAngle {
Angle(Angle),
Func(Func),
}
cast! {
CancelAngle,
self => match self {
Self::Angle(v) => v.into_value(),
Self::Func(v) => v.into_value()
},
v: Angle => CancelAngle::Angle(v),
v: Func => CancelAngle::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/math/lr.rs | crates/typst-library/src/math/lr.rs | use std::collections::HashMap;
use std::sync::LazyLock;
use bumpalo::Bump;
use comemo::Tracked;
use crate::engine::Engine;
use crate::foundations::{
Args, CastInfo, Content, Context, Func, IntoValue, NativeElement, NativeFunc,
NativeFuncData, NativeFuncPtr, ParamInfo, Reflect, Scope, SymbolElem, Type, elem,
func,
};
use crate::layout::{Length, Rel};
use crate::math::Mathy;
/// Scales delimiters.
///
/// While matched delimiters scale by default, this can be used to scale
/// unmatched delimiters and to control the delimiter scaling more precisely.
#[elem(title = "Left/Right", Mathy)]
pub struct LrElem {
/// The size of the brackets, relative to the height of the wrapped content.
#[default(Rel::one())]
pub size: Rel<Length>,
/// The delimited content, including the delimiters.
#[required]
#[parse(
let mut arguments = args.all::<Content>()?.into_iter();
let mut body = arguments.next().unwrap_or_default();
arguments.for_each(|arg| body += SymbolElem::packed(',') + arg);
body
)]
pub body: Content,
}
/// Scales delimiters vertically to the nearest surrounding `{lr()}` group.
///
/// ```example
/// $ { x mid(|) sum_(i=1)^n w_i|f_i (x)| < 1 } $
/// ```
#[elem(Mathy)]
pub struct MidElem {
/// The content to be scaled.
#[required]
pub body: Content,
}
/// Floors an expression.
///
/// ```example
/// $ floor(x/2) $
/// ```
#[func]
pub fn floor(
/// The size of the brackets, relative to the height of the wrapped content.
///
/// Default: The current value of [`lr.size`]($math.lr.size).
#[named]
size: Option<Rel<Length>>,
/// The expression to floor.
body: Content,
) -> Content {
delimited(body, '⌊', '⌋', size)
}
/// Ceils an expression.
///
/// ```example
/// $ ceil(x/2) $
/// ```
#[func]
pub fn ceil(
/// The size of the brackets, relative to the height of the wrapped content.
///
/// Default: The current value of [`lr.size`]($math.lr.size).
#[named]
size: Option<Rel<Length>>,
/// The expression to ceil.
body: Content,
) -> Content {
delimited(body, '⌈', '⌉', size)
}
/// Rounds an expression.
///
/// ```example
/// $ round(x/2) $
/// ```
#[func]
pub fn round(
/// The size of the brackets, relative to the height of the wrapped content.
///
/// Default: The current value of [`lr.size`]($math.lr.size).
#[named]
size: Option<Rel<Length>>,
/// The expression to round.
body: Content,
) -> Content {
delimited(body, '⌊', '⌉', size)
}
/// Takes the absolute value of an expression.
///
/// ```example
/// $ abs(x/2) $
/// ```
#[func]
pub fn abs(
/// The size of the brackets, relative to the height of the wrapped content.
///
/// Default: The current value of [`lr.size`]($math.lr.size).
#[named]
size: Option<Rel<Length>>,
/// The expression to take the absolute value of.
body: Content,
) -> Content {
delimited(body, '|', '|', size)
}
/// Takes the norm of an expression.
///
/// ```example
/// $ norm(x/2) $
/// ```
#[func]
pub fn norm(
/// The size of the brackets, relative to the height of the wrapped content.
///
/// Default: The current value of [`lr.size`]($math.lr.size).
#[named]
size: Option<Rel<Length>>,
/// The expression to take the norm of.
body: Content,
) -> Content {
delimited(body, '‖', '‖', size)
}
/// Gets the Left/Right wrapper function corresponding to a symbol value, if
/// any.
pub fn get_lr_wrapper_func(value: &str) -> Option<Func> {
let left = value.parse::<char>().ok()?;
match left {
// Unlike `round`, `abs`, and `norm`, `floor` and `ceil` are of type
// `symbol` and cast to a function like other L/R symbols. We could thus
// rely on autogeneration for these as well, but since they are
// specifically called out in the documentation on the L/R page (via the
// group mechanism), it's nice for them to have a bit of extra
// documentation.
'⌈' => Some(ceil::func()),
'⌊' => Some(floor::func()),
l => FUNCS.get(&l).map(Func::from),
}
}
/// The delimiter pairings supported for use as callable symbols.
const DELIMS: &[(char, char)] = &[
// The `ceil` and `floor` pairs are omitted here because they are handled
// manually.
('(', ')'),
('⟮', '⟯'),
('⦇', '⦈'),
('⦅', '⦆'),
('⦓', '⦔'),
('⦕', '⦖'),
('{', '}'),
('⦃', '⦄'),
('[', ']'),
('⦍', '⦐'),
('⦏', '⦎'),
('⟦', '⟧'),
('⦋', '⦌'),
('❲', '❳'),
('⟬', '⟭'),
('⦗', '⦘'),
('⟅', '⟆'),
('⎰', '⎱'),
('⎱', '⎰'),
('⧘', '⧙'),
('⧚', '⧛'),
('⟨', '⟩'),
('⧼', '⧽'),
('⦑', '⦒'),
('⦉', '⦊'),
('⟪', '⟫'),
('⌜', '⌝'),
('⌞', '⌟'),
// Fences.
('|', '|'),
('‖', '‖'),
('⦀', '⦀'),
('⦙', '⦙'),
('⦚', '⦚'),
];
/// Lazily created left/right wrapper functions.
static FUNCS: LazyLock<HashMap<char, NativeFuncData>> = LazyLock::new(|| {
let bump = Box::leak(Box::new(Bump::new()));
DELIMS
.iter()
.copied()
.map(|(l, r)| (l, create_lr_func_data(l, r, bump)))
.collect()
});
/// Creates metadata for an L/R wrapper function.
fn create_lr_func_data(left: char, right: char, bump: &'static Bump) -> NativeFuncData {
let title = bumpalo::format!(in bump, "{}{} Left/Right", left, right).into_bump_str();
let docs = bumpalo::format!(in bump, "Wraps an expression in {}{}.", left, right)
.into_bump_str();
NativeFuncData {
function: NativeFuncPtr(bump.alloc(
move |_: &mut Engine, _: Tracked<Context>, args: &mut Args| {
let size = args.named("size")?;
let body = args.expect("body")?;
Ok(delimited(body, left, right, size).into_value())
},
)),
name: "(..) => ..",
title,
docs,
keywords: &[],
contextual: false,
scope: LazyLock::new(&|| Scope::new()),
params: LazyLock::new(&|| create_lr_param_info()),
returns: LazyLock::new(&|| CastInfo::Type(Type::of::<Content>())),
}
}
/// Creates parameter signature metadata for an L/R function.
fn create_lr_param_info() -> Vec<ParamInfo> {
vec.",
input: Rel::<Length>::input(),
default: None,
positional: false,
named: true,
variadic: false,
required: false,
settable: false,
},
ParamInfo {
name: "body",
docs: "The expression to wrap.",
input: Content::input(),
default: None,
positional: true,
named: false,
variadic: false,
required: true,
settable: false,
},
]
}
/// Creates an L/R element with the given delimiters.
fn delimited(
body: Content,
left: char,
right: char,
size: Option<Rel<Length>>,
) -> Content {
let span = body.span();
let mut elem = LrElem::new(Content::sequence([
SymbolElem::packed(left),
body,
SymbolElem::packed(right),
]));
// Push size only if size is provided
if let Some(size) = size {
elem.size.set(size);
}
elem.pack().spanned(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/math/equation.rs | crates/typst-library/src/math/equation.rs | use std::num::NonZeroUsize;
use codex::styling::MathVariant;
use ecow::EcoString;
use typst_utils::NonZeroExt;
use unicode_math_class::MathClass;
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::{
AlignElem, Alignment, BlockElem, OuterHAlignment, SpecificAlignment, VAlignment,
};
use crate::math::MathSize;
use crate::model::{Numbering, Outlinable, ParLine, Refable, Supplement};
use crate::text::{FontFamily, FontList, FontWeight, LocalName, Locale, TextElem};
/// A mathematical equation.
///
/// Can be displayed inline with text or as a separate block. An equation
/// becomes block-level through the presence of whitespace after the opening
/// dollar sign and whitespace before the closing dollar sign.
///
/// # Example
/// ```example
/// #set text(font: "New Computer Modern")
///
/// Let $a$, $b$, and $c$ be the side
/// lengths of right-angled triangle.
/// Then, we know that:
/// $ a^2 + b^2 = c^2 $
///
/// Prove by induction:
/// $ sum_(k=1)^n k = (n(n+1)) / 2 $
/// ```
///
/// By default, block-level equations will not break across pages. This can be
/// changed through `{show math.equation: set block(breakable: true)}`.
///
/// # Syntax
/// This function also has dedicated syntax: Write mathematical markup within
/// dollar signs to create an equation. Starting and ending the equation with
/// whitespace lifts it into a separate block that is centered horizontally.
/// For more details about math syntax, see the
/// [main math page]($category/math).
#[elem(Locatable, Tagged, Synthesize, ShowSet, Count, LocalName, Refable, Outlinable)]
pub struct EquationElem {
/// Whether the equation is displayed as a separate block.
#[default(false)]
pub block: bool,
/// How to number block-level equations. Accepts a
/// [numbering pattern or function]($numbering) taking a single number.
///
/// ```example
/// #set math.equation(numbering: "(1)")
///
/// We define:
/// $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio>
///
/// With @ratio, we get:
/// $ F_n = floor(1 / sqrt(5) phi.alt^n) $
/// ```
pub numbering: Option<Numbering>,
/// The alignment of the equation numbering.
///
/// By default, the alignment is `{end + horizon}`. For the horizontal
/// component, you can use `{right}`, `{left}`, or `{start}` and `{end}`
/// of the text direction; for the vertical component, you can use
/// `{top}`, `{horizon}`, or `{bottom}`.
///
/// ```example
/// #set math.equation(numbering: "(1)", number-align: bottom)
///
/// We can calculate:
/// $ E &= sqrt(m_0^2 + p^2) \
/// &approx 125 "GeV" $
/// ```
#[default(SpecificAlignment::Both(OuterHAlignment::End, VAlignment::Horizon))]
pub number_align: SpecificAlignment<OuterHAlignment, VAlignment>,
/// A supplement for the equation.
///
/// For references to equations, this is added before the referenced number.
///
/// If a function is specified, it is passed the referenced equation and
/// should return content.
///
/// ```example
/// #set math.equation(numbering: "(1)", supplement: [Eq.])
///
/// We define:
/// $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio>
///
/// With @ratio, we get:
/// $ F_n = floor(1 / sqrt(5) phi.alt^n) $
/// ```
pub supplement: Smart<Option<Supplement>>,
/// An alternative description of the mathematical equation.
///
/// This should describe the full equation in natural language and will be
/// made available to Assistive Technology. You can learn more in the
/// [Textual Representations section of the Accessibility
/// Guide]($guides/accessibility/#textual-representations).
///
/// ```example
/// #math.equation(
/// alt: "integral from 1 to infinity of a x squared plus b with respect to x",
/// block: true,
/// $ integral_1^oo a x^2 + b dif x $,
/// )
/// ```
pub alt: Option<EcoString>,
/// The contents of the equation.
#[required]
pub body: Content,
/// The size of the glyphs.
#[internal]
#[default(MathSize::Text)]
#[ghost]
pub size: MathSize,
/// The style variant to select.
#[internal]
#[ghost]
pub variant: Option<MathVariant>,
/// Affects the height of exponents.
#[internal]
#[default(false)]
#[ghost]
pub cramped: bool,
/// Whether to use bold glyphs.
#[internal]
#[default(false)]
#[ghost]
pub bold: bool,
/// Whether to use italic glyphs.
#[internal]
#[ghost]
pub italic: Option<bool>,
/// A forced class to use for all fragment.
#[internal]
#[ghost]
pub class: Option<MathClass>,
/// Values of `scriptPercentScaleDown` and `scriptScriptPercentScaleDown`
/// respectively in the current font's MathConstants table.
#[internal]
#[default((70, 50))]
#[ghost]
pub script_scale: (i16, i16),
/// The locale of this element (used for the alternative description).
#[internal]
#[synthesized]
pub locale: Locale,
}
impl Synthesize for Packed<EquationElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let supplement = match self.as_ref().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()])?
}
};
self.supplement
.set(Smart::Custom(Some(Supplement::Content(supplement))));
self.locale = Some(Locale::get_in(styles));
Ok(())
}
}
impl ShowSet for Packed<EquationElem> {
fn show_set(&self, styles: StyleChain) -> Styles {
let mut out = Styles::new();
if self.block.get(styles) {
out.set(AlignElem::alignment, Alignment::CENTER);
out.set(BlockElem::breakable, false);
out.set(ParLine::numbering, None);
out.set(EquationElem::size, MathSize::Display);
} else {
out.set(EquationElem::size, MathSize::Text);
}
out.set(TextElem::weight, FontWeight::from_number(450));
out.set(
TextElem::font,
FontList(vec![FontFamily::new("New Computer Modern Math")]),
);
out
}
}
impl Count for Packed<EquationElem> {
fn update(&self) -> Option<CounterUpdate> {
(self.block.get(StyleChain::default()) && self.numbering().is_some())
.then(|| CounterUpdate::Step(NonZeroUsize::ONE))
}
}
impl LocalName for Packed<EquationElem> {
const KEY: &'static str = "equation";
}
impl Refable for Packed<EquationElem> {
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(EquationElem::ELEM)
}
fn numbering(&self) -> Option<&Numbering> {
self.numbering.get_ref(StyleChain::default()).as_ref()
}
}
impl Outlinable for Packed<EquationElem> {
fn outlined(&self) -> bool {
self.block.get(StyleChain::default()) && 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 {
Content::empty()
}
}
| 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/mod.rs | crates/typst-library/src/math/mod.rs | //! Mathematical formulas.
pub mod accent;
mod attach;
mod cancel;
mod equation;
mod frac;
mod lr;
mod matrix;
mod op;
mod root;
mod style;
mod underover;
pub use self::accent::{Accent, AccentElem};
pub use self::attach::*;
pub use self::cancel::*;
pub use self::equation::*;
pub use self::frac::*;
pub use self::lr::*;
pub use self::matrix::*;
pub use self::op::*;
pub use self::root::*;
pub use self::style::*;
pub use self::underover::*;
use typst_utils::singleton;
use unicode_math_class::MathClass;
use crate::foundations::{Content, Module, NativeElement, Scope, elem};
use crate::layout::{Em, HElem};
use crate::text::TextElem;
// Spacings.
pub const THIN: Em = Em::new(1.0 / 6.0);
pub const MEDIUM: Em = Em::new(2.0 / 9.0);
pub const THICK: Em = Em::new(5.0 / 18.0);
pub const QUAD: Em = Em::new(1.0);
pub const WIDE: Em = Em::new(2.0);
/// Create a module with all math definitions.
pub fn module() -> Module {
let mut math = Scope::deduplicating();
math.start_category(crate::Category::Math);
math.define_elem::<EquationElem>();
math.define_elem::<TextElem>();
math.define_elem::<LrElem>();
math.define_elem::<MidElem>();
math.define_elem::<AttachElem>();
math.define_elem::<StretchElem>();
math.define_elem::<ScriptsElem>();
math.define_elem::<LimitsElem>();
math.define_elem::<AccentElem>();
math.define_elem::<UnderlineElem>();
math.define_elem::<OverlineElem>();
math.define_elem::<UnderbraceElem>();
math.define_elem::<OverbraceElem>();
math.define_elem::<UnderbracketElem>();
math.define_elem::<OverbracketElem>();
math.define_elem::<UnderparenElem>();
math.define_elem::<OverparenElem>();
math.define_elem::<UndershellElem>();
math.define_elem::<OvershellElem>();
math.define_elem::<CancelElem>();
math.define_elem::<FracElem>();
math.define_elem::<BinomElem>();
math.define_elem::<VecElem>();
math.define_elem::<MatElem>();
math.define_elem::<CasesElem>();
math.define_elem::<RootElem>();
math.define_elem::<ClassElem>();
math.define_elem::<OpElem>();
math.define_elem::<PrimesElem>();
math.define_func::<abs>();
math.define_func::<norm>();
math.define_func::<round>();
math.define_func::<sqrt>();
math.define_func::<upright>();
math.define_func::<bold>();
math.define_func::<italic>();
math.define_func::<serif>();
math.define_func::<sans>();
math.define_func::<scr>();
math.define_func::<cal>();
math.define_func::<frak>();
math.define_func::<mono>();
math.define_func::<bb>();
math.define_func::<display>();
math.define_func::<inline>();
math.define_func::<script>();
math.define_func::<sscript>();
// Text operators.
op::define(&mut math);
// Spacings.
math.define("thin", HElem::new(THIN.into()).pack());
math.define("med", HElem::new(MEDIUM.into()).pack());
math.define("thick", HElem::new(THICK.into()).pack());
math.define("quad", HElem::new(QUAD.into()).pack());
math.define("wide", HElem::new(WIDE.into()).pack());
// Symbols.
crate::symbols::define_math(&mut math);
Module::new("math", math)
}
/// Trait for recognizing math elements and auto-wrapping them in equations.
pub trait Mathy {}
/// A math alignment point: `&`, `&&`.
#[elem(title = "Alignment Point", Mathy)]
pub struct AlignPointElem {}
impl AlignPointElem {
/// Get the globally shared alignment point element.
pub fn shared() -> &'static Content {
singleton!(Content, AlignPointElem::new().pack())
}
}
/// Forced use of a certain math class.
///
/// This is useful to treat certain symbols as if they were of a different
/// class, e.g. to make a symbol behave like a relation. The class of a symbol
/// defines the way it is laid out, including spacing around it, and how its
/// scripts are attached by default. Note that the latter can always be
/// overridden using [`{limits}`](math.limits) and [`{scripts}`](math.scripts).
///
/// # Example
/// ```example
/// #let loves = math.class(
/// "relation",
/// sym.suit.heart,
/// )
///
/// $x loves y and y loves 5$
/// ```
#[elem(Mathy)]
pub struct ClassElem {
/// The class to apply to the content.
#[required]
pub class: MathClass,
/// The content to which the class is applied.
#[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/math/style.rs | crates/typst-library/src/math/style.rs | use codex::styling::MathVariant;
use crate::foundations::{Cast, Content, func};
use crate::math::EquationElem;
/// Bold font style in math.
///
/// ```example
/// $ bold(A) := B^+ $
/// ```
#[func(keywords = ["mathbf"])]
pub fn bold(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::bold, true)
}
/// Upright (non-italic) font style in math.
///
/// ```example
/// $ upright(A) != A $
/// ```
#[func(keywords = ["mathup"])]
pub fn upright(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::italic, Some(false))
}
/// Italic font style in math.
///
/// For roman letters and greek lowercase letters, this is already the default.
#[func(keywords = ["mathit"])]
pub fn italic(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::italic, Some(true))
}
/// Serif (roman) font style in math.
///
/// This is already the default.
#[func(keywords = ["mathrm"])]
pub fn serif(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::Plain))
}
/// Sans-serif font style in math.
///
/// ```example
/// $ sans(A B C) $
/// ```
#[func(title = "Sans Serif", keywords = ["mathsf"])]
pub fn sans(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::SansSerif))
}
/// Calligraphic (chancery) font style in math.
///
/// ```example
/// Let $cal(P)$ be the set of ...
/// ```
///
/// This is the default calligraphic/script style for most math fonts. See
/// [`scr`]($math.scr) for more on how to get the other style (roundhand).
#[func(title = "Calligraphic", keywords = ["mathcal", "chancery"])]
pub fn cal(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::Chancery))
}
/// Script (roundhand) font style in math.
///
/// ```example
/// $scr(L)$ is not the set of linear
/// maps $cal(L)$.
/// ```
///
/// There are two ways that fonts can support differentiating `cal` and `scr`.
/// The first is using Unicode variation sequences. This works out of the box
/// in Typst, however only a few math fonts currently support this.
///
/// The other way is using [font features]($text.features). For example, the
/// roundhand style might be available in a font through the
/// _[stylistic set]($text.stylistic-set) 1_ (`ss01`) feature. To use it in
/// Typst, you could then define your own version of `scr` like in the example
/// below.
///
/// ```example:"Recreation using stylistic set 1"
/// #let scr(it) = text(
/// stylistic-set: 1,
/// $cal(it)$,
/// )
///
/// We establish $cal(P) != scr(P)$.
/// ```
#[func(title = "Script Style", keywords = ["mathscr", "roundhand"])]
pub fn scr(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::Roundhand))
}
/// Fraktur font style in math.
///
/// ```example
/// $ frak(P) $
/// ```
#[func(title = "Fraktur", keywords = ["mathfrak"])]
pub fn frak(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::Fraktur))
}
/// Monospace font style in math.
///
/// ```example
/// $ mono(x + y = z) $
/// ```
#[func(title = "Monospace", keywords = ["mathtt"])]
pub fn mono(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::Monospace))
}
/// Blackboard bold (double-struck) font style in math.
///
/// For uppercase latin letters, blackboard bold is additionally available
/// through [symbols]($category/symbols/sym) of the form `NN` and `RR`.
///
/// ```example
/// $ bb(b) $
/// $ bb(N) = NN $
/// $ f: NN -> RR $
/// ```
#[func(title = "Blackboard Bold", keywords = ["mathbb"])]
pub fn bb(
/// The content to style.
body: Content,
) -> Content {
body.set(EquationElem::variant, Some(MathVariant::DoubleStruck))
}
/// Forced display style in math.
///
/// This is the normal size for block equations.
///
/// ```example
/// $sum_i x_i/2 = display(sum_i x_i/2)$
/// ```
#[func(title = "Display Size", keywords = ["displaystyle"])]
pub fn display(
/// The content to size.
body: Content,
/// Whether to impose a height restriction for exponents, like regular sub-
/// and superscripts do.
#[named]
#[default(false)]
cramped: bool,
) -> Content {
body.set(EquationElem::size, MathSize::Display)
.set(EquationElem::cramped, cramped)
}
/// Forced inline (text) style in math.
///
/// This is the normal size for inline equations.
///
/// ```example
/// $ sum_i x_i/2
/// = inline(sum_i x_i/2) $
/// ```
#[func(title = "Inline Size", keywords = ["textstyle"])]
pub fn inline(
/// The content to size.
body: Content,
/// Whether to impose a height restriction for exponents, like regular sub-
/// and superscripts do.
#[named]
#[default(false)]
cramped: bool,
) -> Content {
body.set(EquationElem::size, MathSize::Text)
.set(EquationElem::cramped, cramped)
}
/// Forced script style in math.
///
/// This is the smaller size used in powers or sub- or superscripts.
///
/// ```example
/// $sum_i x_i/2 = script(sum_i x_i/2)$
/// ```
#[func(title = "Script Size", keywords = ["scriptstyle"])]
pub fn script(
/// The content to size.
body: Content,
/// Whether to impose a height restriction for exponents, like regular sub-
/// and superscripts do.
#[named]
#[default(true)]
cramped: bool,
) -> Content {
body.set(EquationElem::size, MathSize::Script)
.set(EquationElem::cramped, cramped)
}
/// Forced second script style in math.
///
/// This is the smallest size, used in second-level sub- and superscripts
/// (script of the script).
///
/// ```example
/// $sum_i x_i/2 = sscript(sum_i x_i/2)$
/// ```
#[func(title = "Script-Script Size", keywords = ["scriptscriptstyle"])]
pub fn sscript(
/// The content to size.
body: Content,
/// Whether to impose a height restriction for exponents, like regular sub-
/// and superscripts do.
#[named]
#[default(true)]
cramped: bool,
) -> Content {
body.set(EquationElem::size, MathSize::ScriptScript)
.set(EquationElem::cramped, cramped)
}
/// The size of elements in an equation.
///
/// See the TeXbook p. 141.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Cast)]
pub enum MathSize {
/// Second-level sub- and superscripts.
ScriptScript,
/// Sub- and superscripts.
Script,
/// Math in text.
Text,
/// Math on its own line.
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/math/attach.rs | crates/typst-library/src/math/attach.rs | use crate::foundations::{Content, Packed, elem};
use crate::layout::{Length, Rel};
use crate::math::{EquationElem, Mathy};
/// A base with optional attachments.
///
/// ```example
/// $ attach(
/// Pi, t: alpha, b: beta,
/// tl: 1, tr: 2+3, bl: 4+5, br: 6,
/// ) $
/// ```
#[elem(Mathy)]
pub struct AttachElem {
/// The base to which things are attached.
#[required]
pub base: Content,
/// The top attachment, smartly positioned at top-right or above the base.
///
/// You can wrap the base in `{limits()}` or `{scripts()}` to override the
/// smart positioning.
pub t: Option<Content>,
/// The bottom attachment, smartly positioned at the bottom-right or below
/// the base.
///
/// You can wrap the base in `{limits()}` or `{scripts()}` to override the
/// smart positioning.
pub b: Option<Content>,
/// The top-left attachment (before the base).
pub tl: Option<Content>,
/// The bottom-left attachment (before base).
pub bl: Option<Content>,
/// The top-right attachment (after the base).
pub tr: Option<Content>,
/// The bottom-right attachment (after the base).
pub br: Option<Content>,
}
impl Packed<AttachElem> {
/// If an AttachElem's base is also an AttachElem, merge attachments into the
/// base AttachElem where possible.
pub fn merge_base(&self) -> Option<Self> {
// Extract from an EquationElem.
let mut base = &self.base;
while let Some(equation) = base.to_packed::<EquationElem>() {
base = &equation.body;
}
// Move attachments from elem into base where possible.
if let Some(base) = base.to_packed::<AttachElem>() {
let mut elem = self.clone();
let mut base = base.clone();
macro_rules! merge {
($content:ident) => {
if !base.$content.is_set() && elem.$content.is_set() {
base.$content = elem.$content.clone();
elem.$content.unset();
}
};
}
merge!(t);
merge!(b);
merge!(tl);
merge!(tr);
merge!(bl);
merge!(br);
elem.base = base.pack();
return Some(elem);
}
None
}
}
/// Grouped primes.
///
/// ```example
/// $ a'''_b = a^'''_b $
/// ```
///
/// # Syntax
/// This function has dedicated syntax: use apostrophes instead of primes. They
/// will automatically attach to the previous element, moving superscripts to
/// the next level.
#[elem(Mathy)]
pub struct PrimesElem {
/// The number of grouped primes.
#[required]
pub count: usize,
}
/// Forces a base to display attachments as scripts.
///
/// ```example
/// $ scripts(sum)_1^2 != sum_1^2 $
/// ```
#[elem(Mathy)]
pub struct ScriptsElem {
/// The base to attach the scripts to.
#[required]
pub body: Content,
}
/// Forces a base to display attachments as limits.
///
/// ```example
/// $ limits(A)_1^2 != A_1^2 $
/// ```
#[elem(Mathy)]
pub struct LimitsElem {
/// The base to attach the limits to.
#[required]
pub body: Content,
/// Whether to also force limits in inline equations.
///
/// When applying limits globally (e.g., through a show rule), it is
/// typically a good idea to disable this.
#[default(true)]
pub inline: bool,
}
/// Stretches a glyph.
///
/// This function can also be used to automatically stretch the base of an
/// attachment, so that it fits the top and bottom attachments.
///
/// Note that only some glyphs can be stretched, and which ones can depend on
/// the math font being used. However, most math fonts are the same in this
/// regard.
///
/// ```example
/// $ H stretch(=)^"define" U + p V $
/// $ f : X stretch(->>, size: #150%)_"surjective" Y $
/// $ x stretch(harpoons.ltrb, size: #3em) y
/// stretch(\[, size: #150%) z $
/// ```
#[elem(Mathy)]
pub struct StretchElem {
/// The glyph to stretch.
#[required]
pub body: Content,
/// The size to stretch to, relative to the maximum size of the glyph and
/// its attachments.
#[default(Rel::one())]
pub size: Rel<Length>,
}
| 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/accent.rs | crates/typst-library/src/math/accent.rs | use std::collections::HashMap;
use std::sync::LazyLock;
use bumpalo::Bump;
use comemo::Tracked;
use icu_properties::CanonicalCombiningClass;
use icu_properties::maps::CodePointMapData;
use icu_provider::AsDeserializingBufferProvider;
use icu_provider_blob::BlobDataProvider;
use crate::engine::Engine;
use crate::foundations::{
Args, CastInfo, Content, Context, Func, IntoValue, NativeElement, NativeFuncData,
NativeFuncPtr, ParamInfo, Reflect, Scope, Str, SymbolElem, Type, cast, elem,
};
use crate::layout::{Length, Rel};
use crate::math::Mathy;
/// Attaches an accent to a base.
///
/// # Example
/// ```example
/// $grave(a) = accent(a, `)$ \
/// $arrow(a) = accent(a, arrow)$ \
/// $tilde(a) = accent(a, \u{0303})$
/// ```
#[elem(Mathy)]
pub struct AccentElem {
/// The base to which the accent is applied. May consist of multiple
/// letters.
///
/// ```example
/// $arrow(A B C)$
/// ```
#[required]
pub base: Content,
/// The accent to apply to the base.
///
/// Supported accents include:
///
/// | Accent | Name | Codepoint |
/// | ------------- | --------------- | --------- |
/// | Grave | `grave` | <code>`</code> |
/// | Acute | `acute` | `´` |
/// | Circumflex | `hat` | `^` |
/// | Tilde | `tilde` | `~` |
/// | Macron | `macron` | `¯` |
/// | Dash | `dash` | `‾` |
/// | Breve | `breve` | `˘` |
/// | Dot | `dot` | `.` |
/// | Double dot, Diaeresis | `dot.double`, `diaer` | `¨` |
/// | Triple dot | `dot.triple` | <code>⃛</code> |
/// | Quadruple dot | `dot.quad` | <code>⃜</code> |
/// | Circle | `circle` | `∘` |
/// | Double acute | `acute.double` | `˝` |
/// | Caron | `caron` | `ˇ` |
/// | Right arrow | `arrow`, `->` | `→` |
/// | Left arrow | `arrow.l`, `<-` | `←` |
/// | Left/Right arrow | `arrow.l.r` | `↔` |
/// | Right harpoon | `harpoon` | `⇀` |
/// | Left harpoon | `harpoon.lt` | `↼` |
#[required]
pub accent: Accent,
/// The size of the accent, relative to the width of the base.
///
/// ```example
/// $dash(A, size: #150%)$
/// ```
#[default(Rel::one())]
pub size: Rel<Length>,
/// Whether to remove the dot on top of lowercase i and j when adding a top
/// accent.
///
/// This enables the `dtls` OpenType feature.
///
/// ```example
/// $hat(dotless: #false, i)$
/// ```
#[default(true)]
pub dotless: bool,
}
/// An accent character.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Accent(pub char);
impl Accent {
/// Tries to select the appropriate combining accent for a string, falling
/// back to the string's lone character if there is no corresponding one.
///
/// Returns `None` if there isn't one and the string has more than one
/// character.
pub fn normalize(s: &str) -> Option<Self> {
Self::combining(s).or_else(|| s.parse::<char>().ok().map(Self))
}
/// Tries to select a well-known combining accent that matches for the
/// value.
pub fn combining(value: &str) -> Option<Self> {
let c = value.parse::<char>().ok();
ACCENTS
.iter()
.copied()
.find(|&(accent, names)| Some(accent) == c || names.contains(&value))
.map(|(accent, _)| Self(accent))
}
/// Whether this accent is a bottom accent or not.
pub fn is_bottom(&self) -> bool {
if matches!(self.0, '⏟' | '⎵' | '⏝' | '⏡') {
return true;
}
static COMBINING_CLASS_DATA: LazyLock<CodePointMapData<CanonicalCombiningClass>> =
LazyLock::new(|| {
icu_properties::maps::load_canonical_combining_class(
&BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU)
.unwrap()
.as_deserializing(),
)
.unwrap()
});
matches!(
COMBINING_CLASS_DATA.as_borrowed().get(self.0),
CanonicalCombiningClass::Below
)
}
}
/// Gets the accent function corresponding to a symbol value, if any.
pub fn get_accent_func(value: &str) -> Option<Func> {
Accent::combining(value).map(|accent| (&FUNCS[&accent]).into())
}
// Keep it synced with the documenting table above and the
// `math-accent-sym-call` test.`
/// A list of accents, each with a list of alternative names.
const ACCENTS: &[(char, &[&str])] = &[
// Note: Symbols that can have a text presentation must explicitly have that
// alternative listed here.
('\u{0300}', &["`"]),
('\u{0301}', &["´"]),
('\u{0302}', &["^", "ˆ"]),
('\u{0303}', &["~", "∼", "˜"]),
('\u{0304}', &["¯"]),
('\u{0305}', &["-", "–", "‾", "−"]),
('\u{0306}', &["˘"]),
('\u{0307}', &[".", "˙", "⋅"]),
('\u{0308}', &["¨"]),
('\u{20db}', &[]),
('\u{20dc}', &[]),
('\u{030a}', &["∘", "○"]),
('\u{030b}', &["˝"]),
('\u{030c}', &["ˇ"]),
('\u{20d6}', &["←"]),
('\u{20d7}', &["→", "⟶"]),
('\u{20e1}', &["↔", "↔\u{fe0e}", "⟷"]),
('\u{20d0}', &["↼"]),
('\u{20d1}', &["⇀"]),
];
/// Lazily created accent functions.
static FUNCS: LazyLock<HashMap<Accent, NativeFuncData>> = LazyLock::new(|| {
let bump = Box::leak(Box::new(Bump::new()));
ACCENTS
.iter()
.copied()
.map(|(accent, _)| (Accent(accent), create_accent_func_data(accent, bump)))
.collect()
});
/// Creates metadata for an accent wrapper function.
fn create_accent_func_data(accent: char, bump: &'static Bump) -> NativeFuncData {
let title = bumpalo::format!(in bump, "Accent ({})", accent).into_bump_str();
let docs = bumpalo::format!(in bump, "Adds the accent {} on an expression.", accent)
.into_bump_str();
NativeFuncData {
function: NativeFuncPtr(bump.alloc(
move |_: &mut Engine, _: Tracked<Context>, args: &mut Args| {
let base = args.expect("base")?;
let size = args.named("size")?;
let dotless = args.named("dotless")?;
let mut elem = AccentElem::new(base, Accent(accent));
if let Some(size) = size {
elem = elem.with_size(size);
}
if let Some(dotless) = dotless {
elem = elem.with_dotless(dotless);
}
Ok(elem.pack().into_value())
},
)),
name: "(..) => ..",
title,
docs,
keywords: &[],
contextual: false,
scope: LazyLock::new(&|| Scope::new()),
params: LazyLock::new(&|| create_accent_param_info()),
returns: LazyLock::new(&|| CastInfo::Type(Type::of::<Content>())),
}
}
/// Creates parameter signature metadata for an accent function.
fn create_accent_param_info() -> Vec<ParamInfo> {
vec![
ParamInfo {
name: "base",
docs: "The base to which the accent is applied.",
input: Content::input(),
default: None,
positional: true,
named: false,
variadic: false,
required: true,
settable: false,
},
ParamInfo {
name: "size",
docs: "The size of the accent, relative to the width of the base.",
input: Rel::<Length>::input(),
default: None,
positional: false,
named: true,
variadic: false,
required: false,
settable: false,
},
ParamInfo {
name: "dotless",
docs: "Whether to remove the dot on top of lowercase i and j when adding a top accent.",
input: bool::input(),
default: None,
positional: false,
named: true,
variadic: false,
required: false,
settable: false,
},
]
}
cast! {
Accent,
self => self.0.into_value(),
// The string cast handles
// - strings: `accent(a, "↔")`
// - symbol values: `accent(a, <->)`
// - shorthands: `accent(a, arrow.l.r)`
v: Str => Self::normalize(&v).ok_or("expected exactly one character")?,
// The content cast is for accent uses like `accent(a, ↔)`
v: Content => v.to_packed::<SymbolElem>()
.and_then(|elem| Accent::normalize(&elem.text))
.ok_or("expected a single-codepoint symbol")?,
}
| 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/matrix.rs | crates/typst-library/src/math/matrix.rs | use smallvec::{SmallVec, smallvec};
use typst_syntax::Spanned;
use typst_utils::{Numeric, default_math_class};
use unicode_math_class::MathClass;
use crate::diag::{At, HintedStrResult, StrResult, bail};
use crate::foundations::{
Array, Content, Dict, Fold, NoneValue, Resolve, Smart, StyleChain, Symbol, Value,
array, cast, dict, elem,
};
use crate::layout::{Abs, Em, HAlignment, Length, Rel};
use crate::math::Mathy;
use crate::visualize::Stroke;
const DEFAULT_ROW_GAP: Em = Em::new(0.2);
const DEFAULT_COL_GAP: Em = Em::new(0.5);
/// A column vector.
///
/// Content in the vector's elements can be aligned with the
/// [`align`]($math.vec.align) parameter, or the `&` symbol.
///
/// This function is for typesetting vector components. To typeset a symbol that
/// represents a vector, [`arrow`]($math.accent) and [`bold`]($math.bold) are
/// commonly used.
///
/// # Example
/// ```example
/// $ vec(a, b, c) dot vec(1, 2, 3)
/// = a + 2b + 3c $
/// ```
#[elem(title = "Vector", Mathy)]
pub struct VecElem {
/// The delimiter to use.
///
/// Can be a single character specifying the left delimiter, in which case
/// the right delimiter is inferred. Otherwise, can be an array containing a
/// left and a right delimiter.
///
/// ```example
/// #set math.vec(delim: "[")
/// $ vec(1, 2) $
/// ```
#[default(DelimiterPair::PAREN)]
pub delim: DelimiterPair,
/// The horizontal alignment that each element should have.
///
/// ```example
/// #set math.vec(align: right)
/// $ vec(-1, 1, -1) $
/// ```
#[default(HAlignment::Center)]
pub align: HAlignment,
/// The gap between elements.
///
/// ```example
/// #set math.vec(gap: 1em)
/// $ vec(1, 2) $
/// ```
#[default(DEFAULT_ROW_GAP.into())]
pub gap: Rel<Length>,
/// The elements of the vector.
#[variadic]
pub children: Vec<Content>,
}
/// A matrix.
///
/// The elements of a row should be separated by commas, while the rows
/// themselves should be separated by semicolons. The semicolon syntax merges
/// preceding arguments separated by commas into an array. You can also use this
/// special syntax of math function calls to define custom functions that take
/// 2D data.
///
/// Content in cells can be aligned with the [`align`]($math.mat.align)
/// parameter, or content in cells that are in the same row can be aligned with
/// the `&` symbol.
///
/// # Example
/// ```example
/// $ mat(
/// 1, 2, ..., 10;
/// 2, 2, ..., 10;
/// dots.v, dots.v, dots.down, dots.v;
/// 10, 10, ..., 10;
/// ) $
/// ```
#[elem(title = "Matrix", Mathy)]
pub struct MatElem {
/// The delimiter to use.
///
/// Can be a single character specifying the left delimiter, in which case
/// the right delimiter is inferred. Otherwise, can be an array containing a
/// left and a right delimiter.
///
/// ```example
/// #set math.mat(delim: "[")
/// $ mat(1, 2; 3, 4) $
/// ```
#[default(DelimiterPair::PAREN)]
pub delim: DelimiterPair,
/// The horizontal alignment that each cell should have.
///
/// ```example
/// #set math.mat(align: right)
/// $ mat(-1, 1, 1; 1, -1, 1; 1, 1, -1) $
/// ```
#[default(HAlignment::Center)]
pub align: HAlignment,
/// Draws augmentation lines in a matrix.
///
/// - `{none}`: No lines are drawn.
/// - A single number: A vertical augmentation line is drawn
/// after the specified column number. Negative numbers start from the end.
/// - A dictionary: With a dictionary, multiple augmentation lines can be
/// drawn both horizontally and vertically. Additionally, the style of the
/// lines can be set. The dictionary can contain the following keys:
/// - `hline`: The offsets at which horizontal lines should be drawn.
/// For example, an offset of `2` would result in a horizontal line
/// being drawn after the second row of the matrix. Accepts either an
/// integer for a single line, or an array of integers
/// for multiple lines. Like for a single number, negative numbers start from the end.
/// - `vline`: The offsets at which vertical lines should be drawn.
/// For example, an offset of `2` would result in a vertical line being
/// drawn after the second column of the matrix. Accepts either an
/// integer for a single line, or an array of integers
/// for multiple lines. Like for a single number, negative numbers start from the end.
/// - `stroke`: How to [stroke]($stroke) the line. If set to `{auto}`,
/// takes on a thickness of 0.05 em and square line caps.
///
/// ```example:"Basic usage"
/// $ mat(1, 0, 1; 0, 1, 2; augment: #2) $
/// // Equivalent to:
/// $ mat(1, 0, 1; 0, 1, 2; augment: #(-1)) $
/// ```
///
/// ```example:"Customizing the augmentation line"
/// $ mat(0, 0, 0; 1, 1, 1; augment: #(hline: 1, stroke: 2pt + green)) $
/// ```
#[fold]
pub augment: Option<Augment>,
/// The gap between rows and columns.
///
/// This is a shorthand to set `row-gap` and `column-gap` to the same value.
///
/// ```example
/// #set math.mat(gap: 1em)
/// $ mat(1, 2; 3, 4) $
/// ```
#[external]
pub gap: Rel<Length>,
/// The gap between rows.
///
/// ```example
/// #set math.mat(row-gap: 1em)
/// $ mat(1, 2; 3, 4) $
/// ```
#[parse(
let gap = args.named("gap")?;
args.named("row-gap")?.or(gap)
)]
#[default(DEFAULT_ROW_GAP.into())]
pub row_gap: Rel<Length>,
/// The gap between columns.
///
/// ```example
/// #set math.mat(column-gap: 1em)
/// $ mat(1, 2; 3, 4) $
/// ```
#[parse(args.named("column-gap")?.or(gap))]
#[default(DEFAULT_COL_GAP.into())]
pub column_gap: Rel<Length>,
/// An array of arrays with the rows of the matrix.
///
/// ```example
/// #let data = ((1, 2, 3), (4, 5, 6))
/// #let matrix = math.mat(..data)
/// $ v := matrix $
/// ```
#[variadic]
#[parse(
let mut rows = vec![];
let mut width = 0;
let values = args.all::<Spanned<Value>>()?;
if values.iter().any(|spanned| matches!(spanned.v, Value::Array(_))) {
for Spanned { v, span } in values {
let array = v.cast::<Array>().at(span)?;
let row: Vec<_> = array.into_iter().map(Value::display).collect();
width = width.max(row.len());
rows.push(row);
}
} else {
rows = vec![values.into_iter().map(|spanned| spanned.v.display()).collect()];
}
for row in &mut rows {
if row.len() < width {
row.resize(width, Content::empty());
}
}
rows
)]
pub rows: Vec<Vec<Content>>,
}
/// A case distinction.
///
/// Content across different branches can be aligned with the `&` symbol.
///
/// # Example
/// ```example
/// $ f(x, y) := cases(
/// 1 "if" (x dot y)/2 <= 0,
/// 2 "if" x "is even",
/// 3 "if" x in NN,
/// 4 "else",
/// ) $
/// ```
#[elem(Mathy)]
pub struct CasesElem {
/// The delimiter to use.
///
/// Can be a single character specifying the left delimiter, in which case
/// the right delimiter is inferred. Otherwise, can be an array containing a
/// left and a right delimiter.
///
/// ```example
/// #set math.cases(delim: "[")
/// $ x = cases(1, 2) $
/// ```
#[default(DelimiterPair::BRACE)]
pub delim: DelimiterPair,
/// Whether the direction of cases should be reversed.
///
/// ```example
/// #set math.cases(reverse: true)
/// $ cases(1, 2) = x $
/// ```
#[default(false)]
pub reverse: bool,
/// The gap between branches.
///
/// ```example
/// #set math.cases(gap: 1em)
/// $ x = cases(1, 2) $
/// ```
#[default(DEFAULT_ROW_GAP.into())]
pub gap: Rel<Length>,
/// The branches of the case distinction.
#[variadic]
pub children: Vec<Content>,
}
/// A delimiter is a single character that is used to delimit a matrix, vector
/// or cases. The character has to be a Unicode codepoint tagged as a math
/// "opening", "closing" or "fence".
///
/// Typically, the delimiter is stretched to fit the height of whatever it
/// delimits.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Delimiter(Option<char>);
cast! {
Delimiter,
self => self.0.into_value(),
_: NoneValue => Self::none(),
v: Symbol => Self::char(v.get().parse::<char>().map_err(|_| "expected a single-codepoint symbol")?)?,
v: char => Self::char(v)?,
}
impl Delimiter {
pub fn none() -> Self {
Self(None)
}
pub fn char(c: char) -> StrResult<Self> {
if !matches!(
default_math_class(c),
Some(MathClass::Opening | MathClass::Closing | MathClass::Fence),
) {
bail!("invalid delimiter: \"{}\"", c)
}
Ok(Self(Some(c)))
}
pub fn get(self) -> Option<char> {
self.0
}
pub fn find_matching(self) -> Self {
match self.0 {
None => Self::none(),
Some('[') => Self(Some(']')),
Some(']') => Self(Some('[')),
Some('{') => Self(Some('}')),
Some('}') => Self(Some('{')),
Some(c) => match default_math_class(c) {
Some(MathClass::Opening) => Self(char::from_u32(c as u32 + 1)),
Some(MathClass::Closing) => Self(char::from_u32(c as u32 - 1)),
_ => Self(Some(c)),
},
}
}
}
/// A pair of delimiters (one closing, one opening) used for matrices, vectors
/// and cases.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct DelimiterPair {
open: Delimiter,
close: Delimiter,
}
cast! {
DelimiterPair,
self => array![self.open, self.close].into_value(),
v: Array => match v.as_slice() {
[open, close] => Self {
open: open.clone().cast()?,
close: close.clone().cast()?,
},
_ => bail!("expected 2 delimiters, found {}", v.len())
},
v: Delimiter => Self { open: v, close: v.find_matching() }
}
impl DelimiterPair {
const PAREN: Self = Self {
open: Delimiter(Some('(')),
close: Delimiter(Some(')')),
};
const BRACE: Self = Self {
open: Delimiter(Some('{')),
close: Delimiter(Some('}')),
};
/// The delimiter's opening character.
pub fn open(self) -> Option<char> {
self.open.get()
}
/// The delimiter's closing character.
pub fn close(self) -> Option<char> {
self.close.get()
}
}
/// Parameters specifying how augmentation lines
/// should be drawn on a matrix.
#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct Augment<T: Numeric = Length> {
pub hline: AugmentOffsets,
pub vline: AugmentOffsets,
pub stroke: Smart<Stroke<T>>,
}
impl<T: Numeric + Fold> Fold for Augment<T> {
fn fold(self, outer: Self) -> Self {
Self {
stroke: match (self.stroke, outer.stroke) {
(Smart::Custom(inner), Smart::Custom(outer)) => {
Smart::Custom(inner.fold(outer))
}
// Usually, folding an inner `auto` with an `outer` prefers
// the explicit `auto`. However, here `auto` means unspecified
// and thus we want `outer`.
(inner, outer) => inner.or(outer),
},
..self
}
}
}
impl Resolve for Augment {
type Output = Augment<Abs>;
fn resolve(self, styles: StyleChain) -> Self::Output {
Augment {
hline: self.hline,
vline: self.vline,
stroke: self.stroke.resolve(styles),
}
}
}
cast! {
Augment,
self => {
// if the stroke is auto and there is only one vertical line,
if self.stroke.is_auto() && self.hline.0.is_empty() && self.vline.0.len() == 1 {
return self.vline.0[0].into_value();
}
dict! {
"hline" => self.hline,
"vline" => self.vline,
"stroke" => self.stroke,
}.into_value()
},
v: isize => Augment {
hline: AugmentOffsets::default(),
vline: AugmentOffsets(smallvec![v]),
stroke: Smart::Auto,
},
mut dict: Dict => {
let mut take = |key| dict.take(key).ok().map(AugmentOffsets::from_value).transpose();
let hline = take("hline")?.unwrap_or_default();
let vline = take("vline")?.unwrap_or_default();
let stroke = dict.take("stroke")
.ok()
.map(Stroke::from_value)
.transpose()?
.map(Smart::Custom)
.unwrap_or(Smart::Auto);
Augment { hline, vline, stroke }
},
}
cast! {
Augment<Abs>,
self => self.into_value(),
}
/// The offsets at which augmentation lines should be drawn on a matrix.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct AugmentOffsets(pub SmallVec<[isize; 1]>);
cast! {
AugmentOffsets,
self => self.0.into_value(),
v: isize => Self(smallvec![v]),
v: Array => Self(v.into_iter().map(Value::cast).collect::<HintedStrResult<_>>()?),
}
| 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/layout/axes.rs | crates/typst-library/src/layout/axes.rs | use std::any::Any;
use std::fmt::{self, Debug, Formatter};
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Deref, Not};
use typst_utils::Get;
use crate::diag::{HintedStrResult, bail};
use crate::foundations::{
Array, CastInfo, FromValue, IntoValue, Reflect, Resolve, Smart, StyleChain, Value,
array, cast,
};
use crate::layout::{Abs, Dir, Rel, Size};
/// A container with a horizontal and vertical component.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Axes<T> {
/// The horizontal component.
pub x: T,
/// The vertical component.
pub y: T,
}
impl<T> Axes<T> {
/// Create a new instance from the two components.
pub const fn new(x: T, y: T) -> Self {
Self { x, y }
}
/// Create a new instance with two equal components.
pub fn splat(v: T) -> Self
where
T: Clone,
{
Self { x: v.clone(), y: v }
}
/// Map the individual fields with `f`.
pub fn map<F, U>(self, mut f: F) -> Axes<U>
where
F: FnMut(T) -> U,
{
Axes { x: f(self.x), y: f(self.y) }
}
/// Convert from `&Axes<T>` to `Axes<&T>`.
pub fn as_ref(&self) -> Axes<&T> {
Axes { x: &self.x, y: &self.y }
}
/// Convert from `&Axes<T>` to `Axes<&<T as Deref>::Target>`.
pub fn as_deref(&self) -> Axes<&T::Target>
where
T: Deref,
{
Axes { x: &self.x, y: &self.y }
}
/// Convert from `&mut Axes<T>` to `Axes<&mut T>`.
pub fn as_mut(&mut self) -> Axes<&mut T> {
Axes { x: &mut self.x, y: &mut self.y }
}
/// Zip two instances into an instance over a tuple.
pub fn zip<U>(self, other: Axes<U>) -> Axes<(T, U)> {
Axes { x: (self.x, other.x), y: (self.y, other.y) }
}
/// Apply a function to this and another-instance componentwise.
pub fn zip_map<F, V, U>(self, other: Axes<V>, mut f: F) -> Axes<U>
where
F: FnMut(T, V) -> U,
{
Axes { x: f(self.x, other.x), y: f(self.y, other.y) }
}
/// Whether a condition is true for at least one of fields.
pub fn any<F>(self, mut f: F) -> bool
where
F: FnMut(&T) -> bool,
{
f(&self.x) || f(&self.y)
}
/// Whether a condition is true for both fields.
pub fn all<F>(self, mut f: F) -> bool
where
F: FnMut(&T) -> bool,
{
f(&self.x) && f(&self.y)
}
}
impl<T: Default> Axes<T> {
/// Create a new instance with y set to its default value.
pub fn with_x(x: T) -> Self {
Self { x, y: T::default() }
}
/// Create a new instance with x set to its default value.
pub fn with_y(y: T) -> Self {
Self { x: T::default(), y }
}
}
impl<T: Ord> Axes<T> {
/// The component-wise minimum of this and another instance.
pub fn min(self, other: Self) -> Self {
Self { x: self.x.min(other.x), y: self.y.min(other.y) }
}
/// The component-wise minimum of this and another instance.
pub fn max(self, other: Self) -> Self {
Self { x: self.x.max(other.x), y: self.y.max(other.y) }
}
/// The minimum of width and height.
pub fn min_by_side(self) -> T {
self.x.min(self.y)
}
/// The minimum of width and height.
pub fn max_by_side(self) -> T {
self.x.max(self.y)
}
}
impl Axes<Rel<Abs>> {
/// Evaluate the axes relative to the given `size`.
pub fn relative_to(&self, size: Size) -> Size {
Size {
x: self.x.relative_to(size.x),
y: self.y.relative_to(size.y),
}
}
}
impl<T> Get<Axis> for Axes<T> {
type Component = T;
fn get_ref(&self, axis: Axis) -> &T {
match axis {
Axis::X => &self.x,
Axis::Y => &self.y,
}
}
fn get_mut(&mut self, axis: Axis) -> &mut T {
match axis {
Axis::X => &mut self.x,
Axis::Y => &mut self.y,
}
}
}
impl<T> Debug for Axes<T>
where
T: Debug + 'static,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if (&self.x as &dyn Any).is::<Abs>() {
write!(f, "Size({:?}, {:?})", self.x, self.y)
} else {
write!(f, "Axes({:?}, {:?})", self.x, self.y)
}
}
}
/// The two layouting axes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Axis {
/// The horizontal axis.
X,
/// The vertical axis.
Y,
}
impl Axis {
/// The direction with the given positivity for this axis.
pub fn dir(self, positive: bool) -> Dir {
match (self, positive) {
(Self::X, true) => Dir::LTR,
(Self::X, false) => Dir::RTL,
(Self::Y, true) => Dir::TTB,
(Self::Y, false) => Dir::BTT,
}
}
/// The other axis.
pub fn other(self) -> Self {
match self {
Self::X => Self::Y,
Self::Y => Self::X,
}
}
}
cast! {
Axis,
self => match self {
Self::X => "horizontal".into_value(),
Self::Y => "vertical".into_value(),
},
"horizontal" => Self::X,
"vertical" => Self::Y,
}
impl<T> Axes<Smart<T>> {
/// Unwrap the individual fields.
pub fn unwrap_or(self, other: Axes<T>) -> Axes<T> {
Axes {
x: self.x.unwrap_or(other.x),
y: self.y.unwrap_or(other.y),
}
}
}
impl Axes<bool> {
/// Select `t.x` if `self.x` is true and `f.x` otherwise and same for `y`.
pub fn select<T>(self, t: Axes<T>, f: Axes<T>) -> Axes<T> {
Axes {
x: if self.x { t.x } else { f.x },
y: if self.y { t.y } else { f.y },
}
}
}
impl Not for Axes<bool> {
type Output = Self;
fn not(self) -> Self::Output {
Self { x: !self.x, y: !self.y }
}
}
impl BitOr for Axes<bool> {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
Self { x: self.x | rhs.x, y: self.y | rhs.y }
}
}
impl BitOr<bool> for Axes<bool> {
type Output = Self;
fn bitor(self, rhs: bool) -> Self::Output {
Self { x: self.x | rhs, y: self.y | rhs }
}
}
impl BitAnd for Axes<bool> {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
Self { x: self.x & rhs.x, y: self.y & rhs.y }
}
}
impl BitAnd<bool> for Axes<bool> {
type Output = Self;
fn bitand(self, rhs: bool) -> Self::Output {
Self { x: self.x & rhs, y: self.y & rhs }
}
}
impl BitOrAssign for Axes<bool> {
fn bitor_assign(&mut self, rhs: Self) {
self.x |= rhs.x;
self.y |= rhs.y;
}
}
impl BitAndAssign for Axes<bool> {
fn bitand_assign(&mut self, rhs: Self) {
self.x &= rhs.x;
self.y &= rhs.y;
}
}
impl<T: Reflect> Reflect for Axes<T> {
fn input() -> CastInfo {
Array::input()
}
fn output() -> CastInfo {
Array::output()
}
fn castable(value: &Value) -> bool {
Array::castable(value)
}
}
impl<T: FromValue> FromValue for Axes<T> {
fn from_value(value: Value) -> HintedStrResult<Self> {
let array = value.cast::<Array>()?;
let mut iter = array.into_iter();
match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => Ok(Axes::new(a.cast()?, b.cast()?)),
_ => bail!(
"array must contain exactly two items";
hint: "the first item determines the value for the X axis \
and the second item the value for the Y axis";
),
}
}
}
impl<T: IntoValue> IntoValue for Axes<T> {
fn into_value(self) -> Value {
array![self.x.into_value(), self.y.into_value()].into_value()
}
}
impl<T: Resolve> Resolve for Axes<T> {
type Output = Axes<T::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|v| v.resolve(styles))
}
}
| 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/layout/fr.rs | crates/typst-library/src/layout/fr.rs | use std::fmt::{self, Debug, Formatter};
use std::iter::Sum;
use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::foundations::{Repr, repr, ty};
use crate::layout::Abs;
/// Defines how the remaining space in a layout is distributed.
///
/// Each fractionally sized element gets space based on the ratio of its
/// fraction to the sum of all fractions.
///
/// For more details, also see the [h] and [v] functions and the
/// [grid function]($grid).
///
/// # Example
/// ```example
/// Left #h(1fr) Left-ish #h(2fr) Right
/// ```
#[ty(cast, name = "fraction")]
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Fr(Scalar);
impl Fr {
/// Takes up zero space: `0fr`.
pub const fn zero() -> Self {
Self(Scalar::ZERO)
}
/// Takes up as much space as all other items with this fraction: `1fr`.
pub const fn one() -> Self {
Self(Scalar::ONE)
}
/// Create a new fraction.
pub const fn new(ratio: f64) -> Self {
Self(Scalar::new(ratio))
}
/// Get the underlying number.
pub const fn get(self) -> f64 {
(self.0).get()
}
/// The absolute value of this fraction.
pub fn abs(self) -> Self {
Self::new(self.get().abs())
}
/// Determine this fraction's share in the remaining space.
pub fn share(self, total: Self, remaining: Abs) -> Abs {
let ratio = self / total;
if ratio.is_finite() && remaining.is_finite() {
(ratio * remaining).max(Abs::zero())
} else {
Abs::zero()
}
}
}
impl Numeric for Fr {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.0.is_finite()
}
}
impl Debug for Fr {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}fr", self.get())
}
}
impl Repr for Fr {
fn repr(&self) -> EcoString {
repr::format_float_with_unit(self.get(), "fr")
}
}
impl Neg for Fr {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Add for Fr {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
typst_utils::sub_impl!(Fr - Fr -> Fr);
impl Mul<f64> for Fr {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self(self.0 * other)
}
}
impl Mul<Fr> for f64 {
type Output = Fr;
fn mul(self, other: Fr) -> Fr {
other * self
}
}
impl Div for Fr {
type Output = f64;
fn div(self, other: Self) -> f64 {
self.get() / other.get()
}
}
impl Div<f64> for Fr {
type Output = Self;
fn div(self, other: f64) -> Self {
Self(self.0 / other)
}
}
typst_utils::assign_impl!(Fr += Fr);
typst_utils::assign_impl!(Fr -= Fr);
typst_utils::assign_impl!(Fr *= f64);
typst_utils::assign_impl!(Fr /= f64);
impl Sum for Fr {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Self(iter.map(|s| s.0).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/layout/page.rs | crates/typst-library/src/layout/page.rs | use std::num::NonZeroUsize;
use std::ops::RangeInclusive;
use std::str::FromStr;
use typst_utils::{NonZeroExt, Scalar, singleton};
use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, AutoValue, Cast, Construct, Content, Dict, Fold, NativeElement, Set, Smart,
Value, cast, elem,
};
use crate::introspection::Introspector;
use crate::layout::{
Abs, Alignment, FlushElem, Frame, HAlignment, Length, OuterVAlignment, Ratio, Rel,
Sides, SpecificAlignment,
};
use crate::model::{DocumentInfo, Numbering};
use crate::text::LocalName;
use crate::visualize::{Color, Paint};
/// Layouts its child onto one or multiple pages.
///
/// Although this function is primarily used in set rules to affect page
/// properties, it can also be used to explicitly render its argument onto
/// a set of pages of its own.
///
/// Pages can be set to use `{auto}` as their width or height. In this case, the
/// pages will grow to fit their content on the respective axis.
///
/// The [Guide for Page Setup]($guides/page-setup) explains how to use
/// this and related functions to set up a document with many examples.
///
/// # Example
/// ```example
/// >>> #set page(margin: auto)
/// #set page("us-letter")
///
/// There you go, US friends!
/// ```
///
/// # Accessibility
/// The contents of the page's header, footer, foreground, and background are
/// invisible to Assistive Technology (AT) like screen readers. Only the body of
/// the page is read by AT. Do not include vital information not included
/// elsewhere in the document in these areas.
///
/// # Styling
/// Note that the [`page`] element cannot be targeted by show rules; writing
/// `{show page: ..}` has no effect. To repeat content on every page, you can
/// instead configure the [`header`]($page.header), [`footer`]($page.footer),
/// [`background`]($page.background), and [`foreground`]($page.foreground)
/// properties with a set rule.
#[elem(Construct)]
pub struct PageElem {
/// A standard paper size to set width and height.
///
/// This is just a shorthand for setting `width` and `height` and, as such,
/// cannot be retrieved in a context expression.
#[external]
#[default(Paper::A4)]
pub paper: Paper,
/// The width of the page.
///
/// ```example
/// #set page(
/// width: 3cm,
/// margin: (x: 0cm),
/// )
///
/// #for i in range(3) {
/// box(square(width: 1cm))
/// }
/// ```
#[parse(
let paper = args.named_or_find::<Paper>("paper")?;
args.named("width")?
.or_else(|| paper.map(|paper| Smart::Custom(paper.width().into())))
)]
#[default(Smart::Custom(Paper::A4.width().into()))]
#[ghost]
pub width: Smart<Length>,
/// The height of the page.
///
/// If this is set to `{auto}`, page breaks can only be triggered manually
/// by inserting a [page break]($pagebreak) or by adding another non-empty
/// page set rule. Most examples throughout this documentation use `{auto}`
/// for the height of the page to dynamically grow and shrink to fit their
/// content.
#[parse(
args.named("height")?
.or_else(|| paper.map(|paper| Smart::Custom(paper.height().into())))
)]
#[default(Smart::Custom(Paper::A4.height().into()))]
#[ghost]
pub height: Smart<Length>,
/// Whether the page is flipped into landscape orientation.
///
/// ```example
/// #set page(
/// "us-business-card",
/// flipped: true,
/// fill: rgb("f2e5dd"),
/// )
///
/// #set align(bottom + end)
/// #text(14pt)[*Sam H. Richards*] \
/// _Procurement Manager_
///
/// #set text(10pt)
/// 17 Main Street \
/// New York, NY 10001 \
/// +1 555 555 5555
/// ```
#[default(false)]
#[ghost]
pub flipped: bool,
/// The page's margins.
///
/// - `{auto}`: The margins are set automatically to 2.5/21 times the smaller
/// dimension of the page. This results in 2.5 cm margins for an A4 page.
/// - A single length: The same margin on all sides.
/// - A dictionary: With a dictionary, the margins can be set individually.
/// The dictionary can contain the following keys in order of precedence:
/// - `top`: The top margin.
/// - `right`: The right margin.
/// - `bottom`: The bottom margin.
/// - `left`: The left margin.
/// - `inside`: The margin at the inner side of the page (where the
/// [binding]($page.binding) is).
/// - `outside`: The margin at the outer side of the page (opposite to the
/// [binding]($page.binding)).
/// - `x`: The horizontal margins.
/// - `y`: The vertical margins.
/// - `rest`: The margins on all sides except those for which the
/// dictionary explicitly sets a size.
///
/// All keys are optional; omitted keys will use their previously set value,
/// or the default margin if never set. In addition, the values for `left`
/// and `right` are mutually exclusive with the values for `inside` and
/// `outside`.
///
/// ```example
/// #set page(
/// width: 3cm,
/// height: 4cm,
/// margin: (x: 8pt, y: 4pt),
/// )
///
/// #rect(
/// width: 100%,
/// height: 100%,
/// fill: aqua,
/// )
/// ```
#[fold]
#[ghost]
pub margin: Margin,
/// On which side the pages will be bound.
///
/// - `{auto}`: Equivalent to `left` if the [text direction]($text.dir)
/// is left-to-right and `right` if it is right-to-left.
/// - `left`: Bound on the left side.
/// - `right`: Bound on the right side.
///
/// This affects the meaning of the `inside` and `outside` options for
/// margins.
#[ghost]
pub binding: Smart<Binding>,
/// How many columns the page has.
///
/// If you need to insert columns into a page or other container, you can
/// also use the [`columns` function]($columns).
///
/// ```example:single
/// #set page(columns: 2, height: 4.8cm)
/// Climate change is one of the most
/// pressing issues of our time, with
/// the potential to devastate
/// communities, ecosystems, and
/// economies around the world. It's
/// clear that we need to take urgent
/// action to reduce our carbon
/// emissions and mitigate the impacts
/// of a rapidly changing climate.
/// ```
#[default(NonZeroUsize::ONE)]
#[ghost]
pub columns: NonZeroUsize,
/// The page's background fill.
///
/// Setting this to something non-transparent instructs the printer to color
/// the complete page. If you are considering larger production runs, it may
/// be more environmentally friendly and cost-effective to source pre-dyed
/// pages and not set this property.
///
/// When set to `{none}`, the background becomes transparent. Note that PDF
/// pages will still appear with a (usually white) background in viewers,
/// but they are actually transparent. (If you print them, no color is used
/// for the background.)
///
/// The default of `{auto}` results in `{none}` for PDF output, and
/// `{white}` for PNG and SVG.
///
/// ```example
/// #set page(fill: rgb("444352"))
/// #set text(fill: rgb("fdfdfd"))
/// *Dark mode enabled.*
/// ```
#[ghost]
pub fill: Smart<Option<Paint>>,
/// How to number the pages. You can refer to the Page Setup Guide for
/// [customizing page numbers]($guides/page-setup/#page-numbers).
///
/// Accepts a [numbering pattern or function]($numbering) taking one or two
/// numbers:
/// 1. The first number is the current page number.
/// 2. The second number is the total number of pages. In a numbering
/// pattern, the second number can be omitted. If a function is passed,
/// it will receive one argument in the context of links or references,
/// and two arguments when producing the visible page numbers.
///
/// These are logical numbers controlled by the page counter, and may thus
/// not match the physical numbers. Specifically, they are the
/// [current]($counter.get) and the [final]($counter.final) value of
/// `{counter(page)}`. See the [`counter`]($counter/#page-counter)
/// documentation for more details.
///
/// If an explicit [`footer`]($page.footer) (or [`header`]($page.header) for
/// [top-aligned]($page.number-align) numbering) is given, the numbering is
/// ignored.
///
/// ```example
/// #set page(
/// height: 100pt,
/// margin: (top: 16pt, bottom: 24pt),
/// numbering: "1 / 1",
/// )
///
/// #lorem(48)
/// ```
#[ghost]
pub numbering: Option<Numbering>,
/// A supplement for the pages.
///
/// For page references, this is added before the page number.
///
/// ```example
/// #set page(numbering: "1.", supplement: [p.])
///
/// = Introduction <intro>
/// We are on #ref(<intro>, form: "page")!
/// ```
#[ghost]
pub supplement: Smart<Option<Content>>,
/// The alignment of the page numbering.
///
/// If the vertical component is `top`, the numbering is placed into the
/// header and if it is `bottom`, it is placed in the footer. Horizon
/// alignment is forbidden. If an explicit matching `header` or `footer` is
/// given, the numbering is ignored.
///
/// ```example
/// #set page(
/// margin: (top: 16pt, bottom: 24pt),
/// numbering: "1",
/// number-align: right,
/// )
///
/// #lorem(30)
/// ```
#[default(SpecificAlignment::Both(HAlignment::Center, OuterVAlignment::Bottom))]
#[ghost]
pub number_align: SpecificAlignment<HAlignment, OuterVAlignment>,
/// The page's header. Fills the top margin of each page.
///
/// - Content: Shows the content as the header.
/// - `{auto}`: Shows the page number if a [`numbering`]($page.numbering) is
/// set and [`number-align`]($page.number-align) is `top`.
/// - `{none}`: Suppresses the header.
///
/// ```example
/// #set par(justify: true)
/// #set page(
/// margin: (top: 32pt, bottom: 20pt),
/// header: [
/// #set text(8pt)
/// #smallcaps[Typst Academy]
/// #h(1fr) _Exercise Sheet 3_
/// ],
/// )
///
/// #lorem(19)
/// ```
#[ghost]
pub header: Smart<Option<Content>>,
/// The amount the header is raised into the top margin.
#[default(Ratio::new(0.3).into())]
#[ghost]
pub header_ascent: Rel<Length>,
/// The page's footer. Fills the bottom margin of each page.
///
/// - Content: Shows the content as the footer.
/// - `{auto}`: Shows the page number if a [`numbering`]($page.numbering) is
/// set and [`number-align`]($page.number-align) is `bottom`.
/// - `{none}`: Suppresses the footer.
///
/// For just a page number, the `numbering` property typically suffices. If
/// you want to create a custom footer but still display the page number,
/// you can directly access the [page counter]($counter).
///
/// ```example
/// #set par(justify: true)
/// #set page(
/// height: 100pt,
/// margin: 20pt,
/// footer: context [
/// #set align(right)
/// #set text(8pt)
/// #counter(page).display(
/// "1 of I",
/// both: true,
/// )
/// ]
/// )
///
/// #lorem(48)
/// ```
#[ghost]
pub footer: Smart<Option<Content>>,
/// The amount the footer is lowered into the bottom margin.
#[default(Ratio::new(0.3).into())]
#[ghost]
pub footer_descent: Rel<Length>,
/// Content in the page's background.
///
/// This content will be placed behind the page's body. It can be
/// used to place a background image or a watermark.
///
/// ```example
/// #set page(background: rotate(24deg,
/// text(18pt, fill: rgb("FFCBC4"))[
/// *CONFIDENTIAL*
/// ]
/// ))
///
/// = Typst's secret plans
/// In the year 2023, we plan to take
/// over the world (of typesetting).
/// ```
#[ghost]
pub background: Option<Content>,
/// Content in the page's foreground.
///
/// This content will overlay the page's body.
///
/// ```example
/// #set page(foreground: text(24pt)[🤓])
///
/// Reviewer 2 has marked our paper
/// "Weak Reject" because they did
/// not understand our approach...
/// ```
#[ghost]
pub foreground: Option<Content>,
/// The contents of the page(s).
///
/// Multiple pages will be created if the content does not fit on a single
/// page. A new page with the page properties prior to the function invocation
/// will be created after the body has been typeset.
#[external]
#[required]
pub body: Content,
}
impl Construct for PageElem {
fn construct(engine: &mut Engine, args: &mut Args) -> SourceResult<Content> {
// The page constructor is special: It doesn't create a page element.
// Instead, it just ensures that the passed content lives in a separate
// page and styles it. Because no element node is produced, `show`
// rules can't match `page`; use `set` rules instead.
let styles = Self::set(engine, args)?;
let body = args.expect::<Content>("body")?;
Ok(Content::sequence([
PagebreakElem::shared_weak().clone(),
// We put an effectless, invisible non-tag element on the page.
// This has two desirable consequences:
// - The page is kept even if the body is empty
// - The page doesn't inherit shared styles from the body
FlushElem::new().pack(),
body,
PagebreakElem::shared_boundary().clone(),
])
.styled_with_map(styles))
}
}
impl LocalName for PageElem {
const KEY: &'static str = "page";
}
/// A manual page break.
///
/// Must not be used inside any containers.
///
/// # Example
/// ```example
/// The next page contains
/// more details on compound theory.
/// #pagebreak()
///
/// == Compound Theory
/// In 1984, the first ...
/// ```
///
/// Even without manual page breaks, content will be automatically paginated
/// based on the configured page size. You can set [the page height]($page.height)
/// to `{auto}` to let the page grow dynamically until a manual page break
/// occurs.
///
/// Pagination tries to avoid single lines of text at the top or bottom of a
/// page (these are called _widows_ and _orphans_). You can adjust the
/// [`text.costs`] parameter to disable this behavior.
#[elem(title = "Page Break")]
pub struct PagebreakElem {
/// If `{true}`, the page break is skipped if the current page is already
/// empty.
#[default(false)]
pub weak: bool,
/// If given, ensures that the next page will be an even/odd page, with an
/// empty page in between if necessary.
///
/// ```example
/// #set page(height: 30pt)
///
/// First.
/// #pagebreak(to: "odd")
/// Third.
/// ```
pub to: Option<Parity>,
/// Whether this pagebreak designates an end boundary of a page run. This is
/// an even weaker version of pagebreak `weak` because it not only doesn't
/// force an empty page, but also doesn't force its initial styles onto a
/// staged empty page.
#[internal]
#[parse(None)]
#[default(false)]
pub boundary: bool,
}
impl PagebreakElem {
/// Get the globally shared weak pagebreak element.
pub fn shared_weak() -> &'static Content {
singleton!(Content, PagebreakElem::new().with_weak(true).pack())
}
/// Get the globally shared boundary pagebreak element.
pub fn shared_boundary() -> &'static Content {
singleton!(
Content,
PagebreakElem::new().with_weak(true).with_boundary(true).pack()
)
}
}
/// A finished document with metadata and page frames.
#[derive(Debug, Default, Clone)]
pub struct PagedDocument {
/// The document's finished pages.
pub pages: Vec<Page>,
/// Details about the document.
pub info: DocumentInfo,
/// Provides the ability to execute queries on the document.
pub introspector: Introspector,
}
/// A finished page.
#[derive(Debug, Clone, Hash)]
pub struct Page {
/// The frame that defines the page.
pub frame: Frame,
/// How the page is filled.
///
/// - When `None`, the background is transparent.
/// - When `Auto`, the background is transparent for PDF and white
/// for raster and SVG targets.
///
/// Exporters should access the resolved value of this property through
/// `fill_or_transparent()` or `fill_or_white()`.
pub fill: Smart<Option<Paint>>,
/// The page's numbering.
pub numbering: Option<Numbering>,
/// The page's supplement.
pub supplement: Content,
/// The logical page number (controlled by `counter(page)` and may thus not
/// match the physical number).
pub number: u64,
}
impl Page {
/// Get the configured background or `None` if it is `Auto`.
///
/// This is used in PDF export.
pub fn fill_or_transparent(&self) -> Option<Paint> {
self.fill.clone().unwrap_or(None)
}
/// Get the configured background or white if it is `Auto`.
///
/// This is used in raster and SVG export.
pub fn fill_or_white(&self) -> Option<Paint> {
self.fill.clone().unwrap_or_else(|| Some(Color::WHITE.into()))
}
}
/// Specification of the page's margins.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Margin {
/// The margins for each side.
pub sides: Sides<Option<Smart<Rel<Length>>>>,
/// Whether to swap `left` and `right` to make them `inside` and `outside`
/// (when to swap depends on the binding).
pub two_sided: Option<bool>,
}
impl Margin {
/// Create an instance with four equal components.
pub fn splat(value: Option<Smart<Rel<Length>>>) -> Self {
Self { sides: Sides::splat(value), two_sided: None }
}
}
impl Default for Margin {
fn default() -> Self {
Self {
sides: Sides::splat(Some(Smart::Auto)),
two_sided: None,
}
}
}
impl Fold for Margin {
fn fold(self, outer: Self) -> Self {
Margin {
sides: self.sides.fold(outer.sides),
two_sided: self.two_sided.fold(outer.two_sided),
}
}
}
cast! {
Margin,
self => {
let two_sided = self.two_sided.unwrap_or(false);
if !two_sided && self.sides.is_uniform()
&& let Some(left) = self.sides.left {
return left.into_value();
}
let mut dict = Dict::new();
let mut handle = |key: &str, component: Option<Smart<Rel<Length>>>| {
if let Some(c) = component {
dict.insert(key.into(), c.into_value());
}
};
handle("top", self.sides.top);
handle("bottom", self.sides.bottom);
if two_sided {
handle("inside", self.sides.left);
handle("outside", self.sides.right);
} else {
handle("left", self.sides.left);
handle("right", self.sides.right);
}
Value::Dict(dict)
},
_: AutoValue => Self::splat(Some(Smart::Auto)),
v: Rel<Length> => Self::splat(Some(Smart::Custom(v))),
mut dict: Dict => {
let mut take = |key| dict.take(key).ok().map(Value::cast).transpose();
let rest = take("rest")?;
let x = take("x")?.or(rest);
let y = take("y")?.or(rest);
let top = take("top")?.or(y);
let bottom = take("bottom")?.or(y);
let outside = take("outside")?;
let inside = take("inside")?;
let left = take("left")?;
let right = take("right")?;
let implicitly_two_sided = outside.is_some() || inside.is_some();
let implicitly_not_two_sided = left.is_some() || right.is_some();
if implicitly_two_sided && implicitly_not_two_sided {
bail!("`inside` and `outside` are mutually exclusive with `left` and `right`");
}
// - If 'implicitly_two_sided' is false here, then
// 'implicitly_not_two_sided' will be guaranteed to be true
// due to the previous two 'if' conditions.
// - If both are false, this means that this margin change does not
// affect lateral margins, and thus shouldn't make a difference on
// the 'two_sided' attribute of this margin.
let two_sided = (implicitly_two_sided || implicitly_not_two_sided)
.then_some(implicitly_two_sided);
dict.finish(&[
"left", "top", "right", "bottom", "outside", "inside", "x", "y", "rest",
])?;
Margin {
sides: Sides {
left: inside.or(left).or(x),
top,
right: outside.or(right).or(x),
bottom,
},
two_sided,
}
}
}
/// Specification of the page's binding.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Binding {
/// Bound on the left, as customary in LTR languages.
Left,
/// Bound on the right, as customary in RTL languages.
Right,
}
impl Binding {
/// Whether to swap left and right margin for the page with this number.
pub fn swap(self, number: NonZeroUsize) -> bool {
match self {
// Left-bound must swap on even pages
// (because it is correct on the first page).
Self::Left => number.get() % 2 == 0,
// Right-bound must swap on odd pages
// (because it is wrong on the first page).
Self::Right => number.get() % 2 == 1,
}
}
}
cast! {
Binding,
self => match self {
Self::Left => Alignment::LEFT.into_value(),
Self::Right => Alignment::RIGHT.into_value(),
},
v: Alignment => match v {
Alignment::LEFT => Self::Left,
Alignment::RIGHT => Self::Right,
_ => bail!("must be `left` or `right`"),
},
}
/// A list of page ranges to be exported.
#[derive(Debug, Clone)]
pub struct PageRanges(Vec<PageRange>);
/// A range of pages to export.
///
/// The range is one-indexed. For example, `1..=3` indicates the first, second
/// and third pages should be exported.
pub type PageRange = RangeInclusive<Option<NonZeroUsize>>;
impl PageRanges {
/// Create new page ranges.
pub fn new(ranges: Vec<PageRange>) -> Self {
Self(ranges)
}
/// Check if a page, given its number, should be included when exporting the
/// document while restricting the exported pages to these page ranges.
/// This is the one-indexed version of 'includes_page_index'.
pub fn includes_page(&self, page: NonZeroUsize) -> bool {
self.includes_page_index(page.get() - 1)
}
/// Check if a page, given its index, should be included when exporting the
/// document while restricting the exported pages to these page ranges.
/// This is the zero-indexed version of 'includes_page'.
pub fn includes_page_index(&self, page: usize) -> bool {
let page = NonZeroUsize::try_from(page + 1).unwrap();
self.0.iter().any(|range| match (range.start(), range.end()) {
(Some(start), Some(end)) => (start..=end).contains(&&page),
(Some(start), None) => (start..).contains(&&page),
(None, Some(end)) => (..=end).contains(&&page),
(None, None) => true,
})
}
}
/// Whether something should be even or odd.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Parity {
/// Next page will be an even page.
Even,
/// Next page will be an odd page.
Odd,
}
impl Parity {
/// Whether the given number matches the parity.
pub fn matches(self, number: usize) -> bool {
match self {
Self::Even => number % 2 == 0,
Self::Odd => number % 2 == 1,
}
}
}
/// Specification of a paper.
#[derive(Debug, Copy, Clone, Hash)]
pub struct Paper {
/// The name of the paper.
name: &'static str,
/// The width of the paper in millimeters.
width: Scalar,
/// The height of the paper in millimeters.
height: Scalar,
}
impl Paper {
/// The width of the paper.
pub fn width(self) -> Abs {
Abs::mm(self.width.get())
}
/// The height of the paper.
pub fn height(self) -> Abs {
Abs::mm(self.height.get())
}
}
/// Defines paper constants and a paper parsing implementation.
macro_rules! papers {
($(($var:ident: $width:expr, $height: expr, $name:literal))*) => {
/// Predefined papers.
///
/// Each paper is parsable from its name in kebab-case.
impl Paper {
$(pub const $var: Self = Self {
name: $name,
width: Scalar::new($width),
height: Scalar::new($height),
};)*
}
impl FromStr for Paper {
type Err = &'static str;
fn from_str(name: &str) -> Result<Self, Self::Err> {
match name.to_lowercase().as_str() {
$($name => Ok(Self::$var),)*
_ => Err("unknown paper size"),
}
}
}
cast! {
Paper,
self => self.name.into_value(),
$(
/// Produces a paper of the respective size.
$name => Self::$var,
)*
}
};
}
// All paper sizes in mm.
//
// Resources:
// - https://papersizes.io/
// - https://en.wikipedia.org/wiki/Paper_size
// - https://www.theedkins.co.uk/jo/units/oldunits/print.htm
// - https://vintagepaper.co/blogs/news/traditional-paper-sizes
papers! {
// ---------------------------------------------------------------------- //
// ISO 216 A Series
(A0: 841.0, 1189.0, "a0")
(A1: 594.0, 841.0, "a1")
(A2: 420.0, 594.0, "a2")
(A3: 297.0, 420.0, "a3")
(A4: 210.0, 297.0, "a4")
(A5: 148.0, 210.0, "a5")
(A6: 105.0, 148.0, "a6")
(A7: 74.0, 105.0, "a7")
(A8: 52.0, 74.0, "a8")
(A9: 37.0, 52.0, "a9")
(A10: 26.0, 37.0, "a10")
(A11: 18.0, 26.0, "a11")
// ISO 216 B Series
(ISO_B1: 707.0, 1000.0, "iso-b1")
(ISO_B2: 500.0, 707.0, "iso-b2")
(ISO_B3: 353.0, 500.0, "iso-b3")
(ISO_B4: 250.0, 353.0, "iso-b4")
(ISO_B5: 176.0, 250.0, "iso-b5")
(ISO_B6: 125.0, 176.0, "iso-b6")
(ISO_B7: 88.0, 125.0, "iso-b7")
(ISO_B8: 62.0, 88.0, "iso-b8")
// ISO 216 C Series
(ISO_C3: 324.0, 458.0, "iso-c3")
(ISO_C4: 229.0, 324.0, "iso-c4")
(ISO_C5: 162.0, 229.0, "iso-c5")
(ISO_C6: 114.0, 162.0, "iso-c6")
(ISO_C7: 81.0, 114.0, "iso-c7")
(ISO_C8: 57.0, 81.0, "iso-c8")
// DIN D Series (extension to ISO)
(DIN_D3: 272.0, 385.0, "din-d3")
(DIN_D4: 192.0, 272.0, "din-d4")
(DIN_D5: 136.0, 192.0, "din-d5")
(DIN_D6: 96.0, 136.0, "din-d6")
(DIN_D7: 68.0, 96.0, "din-d7")
(DIN_D8: 48.0, 68.0, "din-d8")
// SIS (used in academia)
(SIS_G5: 169.0, 239.0, "sis-g5")
(SIS_E5: 115.0, 220.0, "sis-e5")
// ANSI Extensions
(ANSI_A: 216.0, 279.0, "ansi-a")
(ANSI_B: 279.0, 432.0, "ansi-b")
(ANSI_C: 432.0, 559.0, "ansi-c")
(ANSI_D: 559.0, 864.0, "ansi-d")
(ANSI_E: 864.0, 1118.0, "ansi-e")
// ANSI Architectural Paper
(ARCH_A: 229.0, 305.0, "arch-a")
(ARCH_B: 305.0, 457.0, "arch-b")
(ARCH_C: 457.0, 610.0, "arch-c")
(ARCH_D: 610.0, 914.0, "arch-d")
(ARCH_E1: 762.0, 1067.0, "arch-e1")
(ARCH_E: 914.0, 1219.0, "arch-e")
// JIS B Series
(JIS_B0: 1030.0, 1456.0, "jis-b0")
(JIS_B1: 728.0, 1030.0, "jis-b1")
(JIS_B2: 515.0, 728.0, "jis-b2")
(JIS_B3: 364.0, 515.0, "jis-b3")
(JIS_B4: 257.0, 364.0, "jis-b4")
(JIS_B5: 182.0, 257.0, "jis-b5")
(JIS_B6: 128.0, 182.0, "jis-b6")
(JIS_B7: 91.0, 128.0, "jis-b7")
(JIS_B8: 64.0, 91.0, "jis-b8")
(JIS_B9: 45.0, 64.0, "jis-b9")
(JIS_B10: 32.0, 45.0, "jis-b10")
(JIS_B11: 22.0, 32.0, "jis-b11")
// SAC D Series
(SAC_D0: 764.0, 1064.0, "sac-d0")
(SAC_D1: 532.0, 760.0, "sac-d1")
(SAC_D2: 380.0, 528.0, "sac-d2")
(SAC_D3: 264.0, 376.0, "sac-d3")
(SAC_D4: 188.0, 260.0, "sac-d4")
(SAC_D5: 130.0, 184.0, "sac-d5")
(SAC_D6: 92.0, 126.0, "sac-d6")
// ISO 7810 ID
(ISO_ID_1: 85.6, 53.98, "iso-id-1")
(ISO_ID_2: 74.0, 105.0, "iso-id-2")
(ISO_ID_3: 88.0, 125.0, "iso-id-3")
// ---------------------------------------------------------------------- //
// Asia
(ASIA_F4: 210.0, 330.0, "asia-f4")
// Japan
(JP_SHIROKU_BAN_4: 264.0, 379.0, "jp-shiroku-ban-4")
(JP_SHIROKU_BAN_5: 189.0, 262.0, "jp-shiroku-ban-5")
(JP_SHIROKU_BAN_6: 127.0, 188.0, "jp-shiroku-ban-6")
(JP_KIKU_4: 227.0, 306.0, "jp-kiku-4")
(JP_KIKU_5: 151.0, 227.0, "jp-kiku-5")
(JP_BUSINESS_CARD: 91.0, 55.0, "jp-business-card")
// China
(CN_BUSINESS_CARD: 90.0, 54.0, "cn-business-card")
// Europe
(EU_BUSINESS_CARD: 85.0, 55.0, "eu-business-card")
// French Traditional (AFNOR)
(FR_TELLIERE: 340.0, 440.0, "fr-tellière")
(FR_COURONNE_ECRITURE: 360.0, 460.0, "fr-couronne-écriture")
(FR_COURONNE_EDITION: 370.0, 470.0, "fr-couronne-édition")
(FR_RAISIN: 500.0, 650.0, "fr-raisin")
(FR_CARRE: 450.0, 560.0, "fr-carré")
(FR_JESUS: 560.0, 760.0, "fr-jésus")
// United Kingdom Imperial
(UK_BRIEF: 406.4, 342.9, "uk-brief")
(UK_DRAFT: 254.0, 406.4, "uk-draft")
(UK_FOOLSCAP: 203.2, 330.2, "uk-foolscap")
(UK_QUARTO: 203.2, 254.0, "uk-quarto")
(UK_CROWN: 508.0, 381.0, "uk-crown")
(UK_BOOK_A: 111.0, 178.0, "uk-book-a")
(UK_BOOK_B: 129.0, 198.0, "uk-book-b")
// Unites States
(US_LETTER: 215.9, 279.4, "us-letter")
(US_LEGAL: 215.9, 355.6, "us-legal")
(US_TABLOID: 279.4, 431.8, "us-tabloid")
(US_EXECUTIVE: 84.15, 266.7, "us-executive")
(US_FOOLSCAP_FOLIO: 215.9, 342.9, "us-foolscap-folio")
(US_STATEMENT: 139.7, 215.9, "us-statement")
(US_LEDGER: 431.8, 279.4, "us-ledger")
(US_OFICIO: 215.9, 340.36, "us-oficio")
(US_GOV_LETTER: 203.2, 266.7, "us-gov-letter")
(US_GOV_LEGAL: 215.9, 330.2, "us-gov-legal")
(US_BUSINESS_CARD: 88.9, 50.8, "us-business-card")
(US_DIGEST: 139.7, 215.9, "us-digest")
(US_TRADE: 152.4, 228.6, "us-trade")
// ---------------------------------------------------------------------- //
// Other
(NEWSPAPER_COMPACT: 280.0, 430.0, "newspaper-compact")
(NEWSPAPER_BERLINER: 315.0, 470.0, "newspaper-berliner")
(NEWSPAPER_BROADSHEET: 381.0, 578.0, "newspaper-broadsheet")
(PRESENTATION_16_9: 297.0, 167.0625, "presentation-16-9")
(PRESENTATION_4_3: 280.0, 210.0, "presentation-4-3")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_paged_document_is_send_and_sync() {
fn ensure_send_and_sync<T: Send + Sync>() {}
ensure_send_and_sync::<PagedDocument>();
}
}
| 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/layout/repeat.rs | crates/typst-library/src/layout/repeat.rs | use crate::foundations::{Content, elem};
use crate::introspection::Tagged;
use crate::layout::Length;
/// Repeats content to the available space.
///
/// This can be useful when implementing a custom index, reference, or outline.
///
/// Space may be inserted between the instances of the body parameter, so be
/// sure to adjust the [`justify`]($repeat.justify) parameter accordingly.
///
/// Errors if there are no bounds on the available space, as it would create
/// infinite content.
///
/// # Example
/// ```example
/// Sign on the dotted line:
/// #box(width: 1fr, repeat[.])
///
/// #set text(10pt)
/// #v(8pt, weak: true)
/// #align(right)[
/// Berlin, the 22nd of December, 2022
/// ]
/// ```
///
/// # Accessibility
/// Repeated content is automatically marked as an [artifact]($pdf.artifact) and
/// hidden from Assistive Technology (AT). Do not use this function to create
/// content that contributes to the meaning of your document.
#[elem(Tagged)]
pub struct RepeatElem {
/// The content to repeat.
#[required]
pub body: Content,
/// The gap between each instance of the body.
#[default]
pub gap: Length,
/// Whether to increase the gap between instances to completely fill the
/// available space.
#[default(true)]
pub justify: bool,
}
| 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/layout/place.rs | crates/typst-library/src/layout/place.rs | use crate::foundations::{Cast, Content, Smart, elem, scope};
use crate::introspection::{Locatable, Tagged, Unqueriable};
use crate::layout::{Alignment, Em, Length, Rel};
/// Places content relatively to its parent container.
///
/// Placed content can be either overlaid (the default) or floating. Overlaid
/// content is aligned with the parent container according to the given
/// [`alignment`]($place.alignment), and shown over any other content added so
/// far in the container. Floating content is placed at the top or bottom of
/// the container, displacing other content down or up respectively. In both
/// cases, the content position can be adjusted with [`dx`]($place.dx) and
/// [`dy`]($place.dy) offsets without affecting the layout.
///
/// The parent can be any container such as a [`block`], [`box`],
/// [`rect`], etc. A top level `place` call will place content directly
/// in the text area of the current page. This can be used for absolute
/// positioning on the page: with a `top + left`
/// [`alignment`]($place.alignment), the offsets `dx` and `dy` will set the
/// position of the element's top left corner relatively to the top left corner
/// of the text area. For absolute positioning on the full page including
/// margins, you can use `place` in [`page.foreground`] or [`page.background`].
///
/// # Examples
/// ```example
/// #set page(height: 120pt)
/// Hello, world!
///
/// #rect(
/// width: 100%,
/// height: 2cm,
/// place(horizon + right, square()),
/// )
///
/// #place(
/// top + left,
/// dx: -5pt,
/// square(size: 5pt, fill: red),
/// )
/// ```
///
/// # Effect on the position of other elements { #effect-on-other-elements }
/// Overlaid elements don't take space in the flow of content, but a `place`
/// call inserts an invisible block-level element in the flow. This can
/// affect the layout by breaking the current paragraph. To avoid this,
/// you can wrap the `place` call in a [`box`] when the call is made
/// in the middle of a paragraph. The alignment and offsets will then be
/// relative to this zero-size box. To make sure it doesn't interfere with
/// spacing, the box should be attached to a word using a word joiner.
///
/// For example, the following defines a function for attaching an annotation
/// to the following word:
///
/// ```example
/// >>> #set page(height: 70pt)
/// #let annotate(..args) = {
/// box(place(..args))
/// sym.wj
/// h(0pt, weak: true)
/// }
///
/// A placed #annotate(square(), dy: 2pt)
/// square in my text.
/// ```
///
/// The zero-width weak spacing serves to discard spaces between the function
/// call and the next word.
///
/// # Accessibility
/// Assistive Technology (AT) will always read the placed element at the point
/// where it logically appears in the document, regardless of where this
/// function physically moved it. Put its markup where it would make the most
/// sense in the reading order.
#[elem(scope, Unqueriable, Locatable, Tagged)]
pub struct PlaceElem {
/// Relative to which position in the parent container to place the content.
///
/// - If `float` is `{false}`, then this can be any alignment other than `{auto}`.
/// - If `float` is `{true}`, then this must be `{auto}`, `{top}`, or `{bottom}`.
///
/// When `float` is `{false}` and no vertical alignment is specified, the
/// content is placed at the current position on the vertical axis.
#[positional]
#[default(Smart::Custom(Alignment::START))]
pub alignment: Smart<Alignment>,
/// Relative to which containing scope something is placed.
///
/// The parent scope is primarily used with figures and, for
/// this reason, the figure function has a mirrored [`scope`
/// parameter]($figure.scope). Nonetheless, it can also be more generally
/// useful to break out of the columns. A typical example would be to
/// [create a single-column title section]($guides/page-setup/#columns)
/// in a two-column document.
///
/// Note that parent-scoped placement is currently only supported if `float`
/// is `{true}`. This may change in the future.
///
/// ```example
/// #set page(height: 150pt, columns: 2)
/// #place(
/// top + center,
/// scope: "parent",
/// float: true,
/// rect(width: 80%, fill: aqua),
/// )
///
/// #lorem(25)
/// ```
pub scope: PlacementScope,
/// Whether the placed element has floating layout.
///
/// Floating elements are positioned at the top or bottom of the parent
/// container, displacing in-flow content. They are always placed in the
/// in-flow order relative to each other, as well as before any content
/// following a later [`place.flush`] element.
///
/// ```example
/// #set page(height: 150pt)
/// #let note(where, body) = place(
/// center + where,
/// float: true,
/// clearance: 6pt,
/// rect(body),
/// )
///
/// #lorem(10)
/// #note(bottom)[Bottom 1]
/// #note(bottom)[Bottom 2]
/// #lorem(40)
/// #note(top)[Top]
/// #lorem(10)
/// ```
pub float: bool,
/// The spacing between the placed element and other elements in a floating
/// layout.
///
/// Has no effect if `float` is `{false}`.
#[default(Em::new(1.5).into())]
pub clearance: Length,
/// The horizontal displacement of the placed content.
///
/// ```example
/// #set page(height: 100pt)
/// #for x in range(-8, 8) {
/// place(center + horizon,
/// dx: x * 8pt, dy: x * 4pt,
/// text(
/// size: calc.root(x + 10, 3) * 6pt,
/// fill: color.mix((green, 8 - x), (blue, 8 + x)),
/// )[T]
/// )
/// }
/// ```
///
/// This does not affect the layout of in-flow content.
/// In other words, the placed content is treated as if it
/// were wrapped in a [`move`] element.
pub dx: Rel<Length>,
/// The vertical displacement of the placed content.
///
/// This does not affect the layout of in-flow content.
/// In other words, the placed content is treated as if it
/// were wrapped in a [`move`] element.
pub dy: Rel<Length>,
/// The content to place.
#[required]
pub body: Content,
}
#[scope]
impl PlaceElem {
#[elem]
type FlushElem;
}
/// Relative to which containing scope something shall be placed.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum PlacementScope {
/// Place into the current column.
#[default]
Column,
/// Place relative to the parent, letting the content span over all columns.
Parent,
}
/// Asks the layout algorithm to place pending floating elements before
/// continuing with the content.
///
/// This is useful for preventing floating figures from spilling
/// into the next section.
///
/// ```example
/// >>> #set page(height: 160pt, width: 150pt)
/// #lorem(15)
///
/// #figure(
/// rect(width: 100%, height: 50pt),
/// placement: auto,
/// caption: [A rectangle],
/// )
///
/// #place.flush()
///
/// This text appears after the figure.
/// ```
#[elem]
pub struct FlushElem {}
| 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/layout/abs.rs | crates/typst-library/src/layout/abs.rs | use std::fmt::{self, Debug, Formatter};
use std::iter::Sum;
use std::ops::{Add, Div, Mul, Neg, Rem};
use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::foundations::{Fold, Repr, Value, cast, repr};
/// An absolute length.
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Abs(Scalar);
impl Abs {
/// The zero length.
pub const fn zero() -> Self {
Self(Scalar::ZERO)
}
/// The infinite length.
pub const fn inf() -> Self {
Self(Scalar::INFINITY)
}
/// Create an absolute length from a number of raw units.
pub const fn raw(raw: f64) -> Self {
Self(Scalar::new(raw))
}
/// Create an absolute length from a value in a unit.
pub fn with_unit(val: f64, unit: AbsUnit) -> Self {
Self(Scalar::new(val * unit.raw_scale()))
}
/// Create an absolute length from a number of points.
pub fn pt(pt: f64) -> Self {
Self::with_unit(pt, AbsUnit::Pt)
}
/// Create an absolute length from a number of millimeters.
pub fn mm(mm: f64) -> Self {
Self::with_unit(mm, AbsUnit::Mm)
}
/// Create an absolute length from a number of centimeters.
pub fn cm(cm: f64) -> Self {
Self::with_unit(cm, AbsUnit::Cm)
}
/// Create an absolute length from a number of inches.
pub fn inches(inches: f64) -> Self {
Self::with_unit(inches, AbsUnit::In)
}
/// Get the value of this absolute length in raw units.
pub const fn to_raw(self) -> f64 {
self.0.get()
}
/// Get the value of this absolute length in a unit.
pub fn to_unit(self, unit: AbsUnit) -> f64 {
self.to_raw() / unit.raw_scale()
}
/// Convert this to a number of points.
pub fn to_pt(self) -> f64 {
self.to_unit(AbsUnit::Pt)
}
/// Convert this to a number of millimeters.
pub fn to_mm(self) -> f64 {
self.to_unit(AbsUnit::Mm)
}
/// Convert this to a number of centimeters.
pub fn to_cm(self) -> f64 {
self.to_unit(AbsUnit::Cm)
}
/// Convert this to a number of inches.
pub fn to_inches(self) -> f64 {
self.to_unit(AbsUnit::In)
}
/// The absolute value of this length.
pub fn abs(self) -> Self {
Self::raw(self.to_raw().abs())
}
/// The minimum of this and another absolute length.
pub fn min(self, other: Self) -> Self {
Self(self.0.min(other.0))
}
/// Set to the minimum of this and another absolute length.
pub fn set_min(&mut self, other: Self) {
*self = (*self).min(other);
}
/// The maximum of this and another absolute length.
pub fn max(self, other: Self) -> Self {
Self(self.0.max(other.0))
}
/// Set to the maximum of this and another absolute length.
pub fn set_max(&mut self, other: Self) {
*self = (*self).max(other);
}
/// Whether the other absolute length fits into this one (i.e. is smaller).
/// Allows for a bit of slack.
pub fn fits(self, other: Self) -> bool {
self.0 + AbsUnit::EPS >= other.0
}
/// Compares two absolute lengths for whether they are approximately equal.
pub fn approx_eq(self, other: Self) -> bool {
self == other || (self - other).to_raw().abs() < AbsUnit::EPS
}
/// Whether the size is close to zero or negative.
pub fn approx_empty(self) -> bool {
self.to_raw() <= AbsUnit::EPS
}
/// Returns a number that represent the sign of this length
pub fn signum(self) -> f64 {
self.0.get().signum()
}
}
impl Numeric for Abs {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.0.is_finite()
}
}
impl Debug for Abs {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}pt", self.to_pt())
}
}
impl Repr for Abs {
fn repr(&self) -> EcoString {
repr::format_float_with_unit(self.to_pt(), "pt")
}
}
impl Neg for Abs {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Add for Abs {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
typst_utils::sub_impl!(Abs - Abs -> Abs);
impl Mul<f64> for Abs {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self(self.0 * other)
}
}
impl Mul<Abs> for f64 {
type Output = Abs;
fn mul(self, other: Abs) -> Abs {
other * self
}
}
impl Div<f64> for Abs {
type Output = Self;
fn div(self, other: f64) -> Self {
Self(self.0 / other)
}
}
impl Div for Abs {
type Output = f64;
fn div(self, other: Self) -> f64 {
self.to_raw() / other.to_raw()
}
}
typst_utils::assign_impl!(Abs += Abs);
typst_utils::assign_impl!(Abs -= Abs);
typst_utils::assign_impl!(Abs *= f64);
typst_utils::assign_impl!(Abs /= f64);
impl Rem for Abs {
type Output = Self;
fn rem(self, other: Self) -> Self::Output {
Self(self.0 % other.0)
}
}
impl Sum for Abs {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Self(iter.map(|s| s.0).sum())
}
}
impl<'a> Sum<&'a Self> for Abs {
fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
Self(iter.map(|s| s.0).sum())
}
}
impl Fold for Abs {
fn fold(self, _: Self) -> Self {
self
}
}
cast! {
Abs,
self => Value::Length(self.into()),
}
/// Different units of absolute measurement.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum AbsUnit {
/// Points.
Pt,
/// Millimeters.
Mm,
/// Centimeters.
Cm,
/// Inches.
In,
}
impl AbsUnit {
/// The epsilon for approximate length comparisons.
const EPS: f64 = 1e-4;
/// How many raw units correspond to a value of `1.0` in this unit.
const fn raw_scale(self) -> f64 {
// We choose a raw scale which has an integer conversion value to all
// four units of interest, so that whole numbers in all units can be
// represented accurately.
match self {
AbsUnit::Pt => 127.0,
AbsUnit::Mm => 360.0,
AbsUnit::Cm => 3600.0,
AbsUnit::In => 9144.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_length_unit_conversion() {
assert!((Abs::mm(150.0).to_cm() - 15.0) < 1e-4);
}
}
| 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/layout/columns.rs | crates/typst-library/src/layout/columns.rs | use std::num::NonZeroUsize;
use crate::foundations::{Content, elem};
use crate::layout::{Length, Ratio, Rel};
/// Separates a region into multiple equally sized columns.
///
/// The `column` function lets you separate the interior of any container into
/// multiple columns. It will currently not balance the height of the columns.
/// Instead, the columns will take up the height of their container or the
/// remaining height on the page. Support for balanced columns is planned for
/// the future.
///
/// When arranging content across multiple columns, use [`colbreak`]($colbreak)
/// to explicitly continue in the next column.
///
/// # Example
/// ```example
/// #columns(2, gutter: 8pt)[
/// This text is in the
/// first column.
///
/// #colbreak()
///
/// This text is in the
/// second column.
/// ]
/// ```
///
/// # Page-level columns { #page-level }
/// If you need to insert columns across your whole document, use the `{page}`
/// function's [`columns` parameter]($page.columns) instead. This will create
/// the columns directly at the page-level rather than wrapping all of your
/// content in a layout container. As a result, things like
/// [pagebreaks]($pagebreak), [footnotes]($footnote), and [line
/// numbers]($par.line) will continue to work as expected. For more information,
/// also read the [relevant part of the page setup
/// guide]($guides/page-setup/#columns).
///
/// # Breaking out of columns { #breaking-out }
/// To temporarily break out of columns (e.g. for a paper's title), use
/// parent-scoped floating placement:
///
/// ```example:single
/// #set page(columns: 2, height: 150pt)
///
/// #place(
/// top + center,
/// scope: "parent",
/// float: true,
/// text(1.4em, weight: "bold")[
/// My document
/// ],
/// )
///
/// #lorem(40)
/// ```
#[elem]
pub struct ColumnsElem {
/// The number of columns.
#[positional]
#[default(NonZeroUsize::new(2).unwrap())]
pub count: NonZeroUsize,
/// The size of the gutter space between each column.
#[default(Ratio::new(0.04).into())]
pub gutter: Rel<Length>,
/// The content that should be layouted into the columns.
#[required]
pub body: Content,
}
/// Forces a column break.
///
/// The function will behave like a [page break]($pagebreak) when used in a
/// single column layout or the last column on a page. Otherwise, content after
/// the column break will be placed in the next column.
///
/// # Example
/// ```example
/// #set page(columns: 2)
/// Preliminary findings from our
/// ongoing research project have
/// revealed a hitherto unknown
/// phenomenon of extraordinary
/// significance.
///
/// #colbreak()
/// Through rigorous experimentation
/// and analysis, we have discovered
/// a hitherto uncharacterized process
/// that defies our current
/// understanding of the fundamental
/// laws of nature.
/// ```
#[elem(title = "Column Break")]
pub struct ColbreakElem {
/// If `{true}`, the column break is skipped if the current column is
/// already empty.
#[default(false)]
pub weak: bool,
}
| 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/layout/pad.rs | crates/typst-library/src/layout/pad.rs | use crate::foundations::{Content, elem};
use crate::layout::{Length, Rel};
/// Adds spacing around content.
///
/// The spacing can be specified for each side individually, or for all sides at
/// once by specifying a positional argument.
///
/// # Example
/// ```example
/// #set align(center)
///
/// #pad(x: 16pt, image("typing.jpg"))
/// _Typing speeds can be
/// measured in words per minute._
/// ```
#[elem(title = "Padding")]
pub struct PadElem {
/// The padding at the left side.
#[parse(
let all = args.named("rest")?.or(args.find()?);
let x = args.named("x")?.or(all);
let y = args.named("y")?.or(all);
args.named("left")?.or(x)
)]
pub left: Rel<Length>,
/// The padding at the top side.
#[parse(args.named("top")?.or(y))]
pub top: Rel<Length>,
/// The padding at the right side.
#[parse(args.named("right")?.or(x))]
pub right: Rel<Length>,
/// The padding at the bottom side.
#[parse(args.named("bottom")?.or(y))]
pub bottom: Rel<Length>,
/// A shorthand to set `left` and `right` to the same value.
#[external]
pub x: Rel<Length>,
/// A shorthand to set `top` and `bottom` to the same value.
#[external]
pub y: Rel<Length>,
/// A shorthand to set all four sides to the same value.
#[external]
pub rest: Rel<Length>,
/// The content to pad at the sides.
#[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/layout/hide.rs | crates/typst-library/src/layout/hide.rs | use crate::foundations::{Content, elem};
use crate::introspection::Tagged;
/// Hides content without affecting layout.
///
/// The `hide` function allows you to hide content while the layout still "sees"
/// it. This is useful for creating blank space that is exactly as large as some
/// content.
///
/// # Example
/// ```example
/// Hello Jane \
/// #hide[Hello] Joe
/// ```
///
/// # Redaction
/// This function may also be useful for redacting content as its arguments are
/// neither present visually nor accessible to Assistive Technology. That said,
/// there can be _some_ traces of the hidden content (such as a bookmarked
/// heading in the PDF's Document Outline).
///
/// Note that, depending on the circumstances, it may be possible for content to
/// be reverse engineered based on its size in the layout. We thus do not
/// recommend using this function to hide highly sensitive information.
#[elem(Tagged)]
pub struct HideElem {
/// The content to hide.
#[required]
pub body: Content,
/// This style is set on the content contained in the `hide` element.
#[internal]
#[ghost]
pub hidden: bool,
}
| 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/layout/fragment.rs | crates/typst-library/src/layout/fragment.rs | use std::fmt::{self, Debug, Formatter};
use crate::layout::Frame;
/// A partial layout result.
#[derive(Clone)]
pub struct Fragment(Vec<Frame>);
impl Fragment {
/// Create a fragment from a single frame.
pub fn frame(frame: Frame) -> Self {
Self(vec![frame])
}
/// Create a fragment from multiple frames.
pub fn frames(frames: Vec<Frame>) -> Self {
Self(frames)
}
/// Return `true` if the length is 0.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// The number of frames in the fragment.
pub fn len(&self) -> usize {
self.0.len()
}
/// Extract the first and only frame.
///
/// Panics if there are multiple frames.
#[track_caller]
pub fn into_frame(self) -> Frame {
assert_eq!(self.0.len(), 1, "expected exactly one frame");
self.0.into_iter().next().unwrap()
}
/// Extract the frames.
pub fn into_frames(self) -> Vec<Frame> {
self.0
}
/// Extract a slice with the contained frames.
pub fn as_slice(&self) -> &[Frame] {
&self.0
}
/// Iterate over the contained frames.
pub fn iter(&self) -> std::slice::Iter<'_, Frame> {
self.0.iter()
}
/// Iterate over the contained frames.
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Frame> {
self.0.iter_mut()
}
}
impl Debug for Fragment {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.0.as_slice() {
[frame] => frame.fmt(f),
frames => frames.fmt(f),
}
}
}
impl IntoIterator for Fragment {
type Item = Frame;
type IntoIter = std::vec::IntoIter<Frame>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a Fragment {
type Item = &'a Frame;
type IntoIter = std::slice::Iter<'a, Frame>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'a> IntoIterator for &'a mut Fragment {
type Item = &'a mut Frame;
type IntoIter = std::slice::IterMut<'a, Frame>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
| 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/layout/container.rs | crates/typst-library/src/layout/container.rs | use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, AutoValue, Construct, Content, NativeElement, Packed, Smart, StyleChain, Value,
cast, elem,
};
use crate::introspection::Locator;
use crate::layout::{
Abs, Corners, Em, Fr, Fragment, Frame, Length, Region, Regions, Rel, Sides, Size,
Spacing,
};
use crate::visualize::{Paint, Stroke};
/// An inline-level container that sizes content.
///
/// All elements except inline math, text, and boxes are block-level and cannot
/// occur inside of a [paragraph]($par). The box function can be used to
/// integrate such elements into a paragraph. Boxes take the size of their
/// contents by default but can also be sized explicitly.
///
/// # Example
/// ```example
/// Refer to the docs
/// #box(
/// height: 9pt,
/// image("docs.svg")
/// )
/// for more information.
/// ```
#[elem]
pub struct BoxElem {
/// The width of the box.
///
/// Boxes can have [fractional]($fraction) widths, as the example below
/// demonstrates.
///
/// _Note:_ Currently, only boxes and only their widths might be fractionally
/// sized within paragraphs. Support for fractionally sized images, shapes,
/// and more might be added in the future.
///
/// ```example
/// Line in #box(width: 1fr, line(length: 100%)) between.
/// ```
pub width: Sizing,
/// The height of the box.
pub height: Smart<Rel<Length>>,
/// An amount to shift the box's baseline by.
///
/// ```example
/// Image: #box(baseline: 40%, image("tiger.jpg", width: 2cm)).
/// ```
pub baseline: Rel<Length>,
/// The box's background color. See the
/// [rectangle's documentation]($rect.fill) for more details.
pub fill: Option<Paint>,
/// The box's border color. See the
/// [rectangle's documentation]($rect.stroke) for more details.
#[fold]
pub stroke: Sides<Option<Option<Stroke>>>,
/// How much to round the box's corners. See the
/// [rectangle's documentation]($rect.radius) for more details.
#[fold]
pub radius: Corners<Option<Rel<Length>>>,
/// How much to pad the box's content.
///
/// This can be a single length for all sides or a dictionary of lengths
/// for individual sides. When passing a dictionary, it can contain the
/// following keys in order of precedence: `top`, `right`, `bottom`, `left`
/// (controlling the respective cell sides), `x`, `y` (controlling vertical
/// and horizontal insets), and `rest` (covers all insets not styled by
/// other dictionary entries). All keys are optional; omitted keys will use
/// their previously set value, or the default value if never set.
///
/// [Relative lengths]($relative) for this parameter are relative to the box
/// size excluding [outset]($box.outset). Note that relative insets and
/// outsets are different from relative [widths]($box.width) and
/// [heights]($box.height), which are relative to the container.
///
/// _Note:_ When the box contains text, its exact size depends on the
/// current [text edges]($text.top-edge).
///
/// ```example
/// #rect(inset: 0pt)[Tight]
/// ```
#[fold]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the box's size without affecting the layout.
///
/// This can be a single length for all sides or a dictionary of lengths for
/// individual sides. [Relative lengths]($relative) for this parameter are
/// relative to the box size excluding outset. See the documentation for
/// [inset]($box.inset) above for further details.
///
/// This is useful to prevent padding from affecting line layout. For a
/// generalized version of the example below, see the documentation for the
/// [raw text's block parameter]($raw.block).
///
/// ```example
/// An inline
/// #box(
/// fill: luma(235),
/// inset: (x: 3pt, y: 0pt),
/// outset: (y: 3pt),
/// radius: 2pt,
/// )[rectangle].
/// ```
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// Whether to clip the content inside the box.
///
/// Clipping is useful when the box's content is larger than the box itself,
/// as any content that exceeds the box's bounds will be hidden.
///
/// ```example
/// #box(
/// width: 50pt,
/// height: 50pt,
/// clip: true,
/// image("tiger.jpg", width: 100pt, height: 100pt)
/// )
/// ```
#[default(false)]
pub clip: bool,
/// The contents of the box.
#[positional]
pub body: Option<Content>,
}
/// An inline-level container that can produce arbitrary items that can break
/// across lines.
#[elem(Construct)]
pub struct InlineElem {
/// A callback that is invoked with the regions to produce arbitrary
/// inline items.
#[required]
#[internal]
body: callbacks::InlineCallback,
}
impl Construct for InlineElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
impl InlineElem {
/// Create an inline-level item with a custom layouter.
#[allow(clippy::type_complexity)]
pub fn layouter<T: NativeElement>(
captured: Packed<T>,
callback: fn(
content: &Packed<T>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Size,
) -> SourceResult<Vec<InlineItem>>,
) -> Self {
Self::new(callbacks::InlineCallback::new(captured, callback))
}
}
impl Packed<InlineElem> {
/// Layout the element.
pub fn layout(
&self,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Size,
) -> SourceResult<Vec<InlineItem>> {
self.body.call(engine, locator, styles, region)
}
}
/// Layouted items suitable for placing in a paragraph.
#[derive(Debug, Clone)]
pub enum InlineItem {
/// Absolute spacing between other items, and whether it is weak.
Space(Abs, bool),
/// Layouted inline-level content.
Frame(Frame),
}
/// A block-level container.
///
/// Such a container can be used to separate content, size it, and give it a
/// background or border.
///
/// Blocks are also the primary way to control whether text becomes part of a
/// paragraph or not. See [the paragraph documentation]($par/#what-becomes-a-paragraph)
/// for more details.
///
/// # Examples
/// With a block, you can give a background to content while still allowing it
/// to break across multiple pages.
/// ```example
/// #set page(height: 100pt)
/// #block(
/// fill: luma(230),
/// inset: 8pt,
/// radius: 4pt,
/// lorem(30),
/// )
/// ```
///
/// Blocks are also useful to force elements that would otherwise be inline to
/// become block-level, especially when writing show rules.
/// ```example
/// #show heading: it => it.body
/// = Blockless
/// More text.
///
/// #show heading: it => block(it.body)
/// = Blocky
/// More text.
/// ```
#[elem]
pub struct BlockElem {
/// The block's width.
///
/// ```example
/// #set align(center)
/// #block(
/// width: 60%,
/// inset: 8pt,
/// fill: silver,
/// lorem(10),
/// )
/// ```
pub width: Smart<Rel<Length>>,
/// The block's height. When the height is larger than the remaining space
/// on a page and [`breakable`]($block.breakable) is `{true}`, the
/// block will continue on the next page with the remaining height.
///
/// ```example
/// #set page(height: 80pt)
/// #set align(center)
/// #block(
/// width: 80%,
/// height: 150%,
/// fill: aqua,
/// )
/// ```
pub height: Sizing,
/// Whether the block can be broken and continue on the next page.
///
/// ```example
/// #set page(height: 80pt)
/// The following block will
/// jump to its own page.
/// #block(
/// breakable: false,
/// lorem(15),
/// )
/// ```
#[default(true)]
pub breakable: bool,
/// The block's background color. See the
/// [rectangle's documentation]($rect.fill) for more details.
pub fill: Option<Paint>,
/// The block's border color. See the
/// [rectangle's documentation]($rect.stroke) for more details.
#[fold]
pub stroke: Sides<Option<Option<Stroke>>>,
/// How much to round the block's corners. See the
/// [rectangle's documentation]($rect.radius) for more details.
#[fold]
pub radius: Corners<Option<Rel<Length>>>,
/// How much to pad the block's content. See the
/// [box's documentation]($box.inset) for more details.
#[fold]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the block's size without affecting the layout. See
/// the [box's documentation]($box.outset) for more details.
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// The spacing around the block. When `{auto}`, inherits the paragraph
/// [`spacing`]($par.spacing).
///
/// For two adjacent blocks, the larger of the first block's `above` and the
/// second block's `below` spacing wins. Moreover, block spacing takes
/// precedence over paragraph [`spacing`]($par.spacing).
///
/// Note that this is only a shorthand to set `above` and `below` to the
/// same value. Since the values for `above` and `below` might differ, a
/// [context] block only provides access to `{block.above}` and
/// `{block.below}`, not to `{block.spacing}` directly.
///
/// This property can be used in combination with a show rule to adjust the
/// spacing around arbitrary block-level elements.
///
/// ```example
/// #set align(center)
/// #show math.equation: set block(above: 8pt, below: 16pt)
///
/// This sum of $x$ and $y$:
/// $ x + y = z $
/// A second paragraph.
/// ```
#[external]
#[default(Em::new(1.2).into())]
pub spacing: Spacing,
/// The spacing between this block and its predecessor.
#[parse(
let spacing = args.named("spacing")?;
args.named("above")?.or(spacing)
)]
pub above: Smart<Spacing>,
/// The spacing between this block and its successor.
#[parse(args.named("below")?.or(spacing))]
pub below: Smart<Spacing>,
/// Whether to clip the content inside the block.
///
/// Clipping is useful when the block's content is larger than the block itself,
/// as any content that exceeds the block's bounds will be hidden.
///
/// ```example
/// #block(
/// width: 50pt,
/// height: 50pt,
/// clip: true,
/// image("tiger.jpg", width: 100pt, height: 100pt)
/// )
/// ```
#[default(false)]
pub clip: bool,
/// Whether this block must stick to the following one, with no break in
/// between.
///
/// This is, by default, set on heading blocks to prevent orphaned headings
/// at the bottom of the page.
///
/// ```example
/// >>> #set page(height: 140pt)
/// // Disable stickiness of headings.
/// #show heading: set block(sticky: false)
/// #lorem(20)
///
/// = Chapter
/// #lorem(10)
/// ```
#[default(false)]
pub sticky: bool,
/// The contents of the block.
#[positional]
pub body: Option<BlockBody>,
}
impl BlockElem {
/// Create a block with a custom single-region layouter.
///
/// Such a block must have `breakable: false` (which is set by this
/// constructor).
pub fn single_layouter<T: NativeElement>(
captured: Packed<T>,
f: fn(
content: &Packed<T>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Region,
) -> SourceResult<Frame>,
) -> Self {
Self::new()
.with_breakable(false)
.with_body(Some(BlockBody::SingleLayouter(
callbacks::BlockSingleCallback::new(captured, f),
)))
}
/// Create a block with a custom multi-region layouter.
pub fn multi_layouter<T: NativeElement>(
captured: Packed<T>,
f: fn(
content: &Packed<T>,
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment>,
) -> Self {
Self::new().with_body(Some(BlockBody::MultiLayouter(
callbacks::BlockMultiCallback::new(captured, f),
)))
}
}
/// The contents of a block.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum BlockBody {
/// The block contains normal content.
Content(Content),
/// The block contains a layout callback that needs access to just one
/// base region.
SingleLayouter(callbacks::BlockSingleCallback),
/// The block contains a layout callback that needs access to the exact
/// regions.
MultiLayouter(callbacks::BlockMultiCallback),
}
impl Default for BlockBody {
fn default() -> Self {
Self::Content(Content::default())
}
}
cast! {
BlockBody,
self => match self {
Self::Content(content) => content.into_value(),
_ => Value::Auto,
},
v: Content => Self::Content(v),
}
/// Defines how to size something along an axis.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Sizing {
/// A track that fits its item's contents.
#[default]
Auto,
/// A size specified in absolute terms and relative to the parent's size.
Rel(Rel),
/// A size specified as a fraction of the remaining free space in the
/// parent.
Fr(Fr),
}
impl Sizing {
/// Whether this is an automatic sizing.
pub fn is_auto(self) -> bool {
matches!(self, Self::Auto)
}
/// Whether this is fractional sizing.
pub fn is_fractional(self) -> bool {
matches!(self, Self::Fr(_))
}
}
impl From<Smart<Rel>> for Sizing {
fn from(smart: Smart<Rel>) -> Self {
match smart {
Smart::Auto => Self::Auto,
Smart::Custom(rel) => Self::Rel(rel),
}
}
}
impl<T: Into<Spacing>> From<T> for Sizing {
fn from(spacing: T) -> Self {
match spacing.into() {
Spacing::Rel(rel) => Self::Rel(rel),
Spacing::Fr(fr) => Self::Fr(fr),
}
}
}
cast! {
Sizing,
self => match self {
Self::Auto => Value::Auto,
Self::Rel(rel) => rel.into_value(),
Self::Fr(fr) => fr.into_value(),
},
_: AutoValue => Self::Auto,
v: Rel<Length> => Self::Rel(v),
v: Fr => Self::Fr(v),
}
/// Manual closure implementations for layout callbacks.
///
/// Normal closures are not `Hash`, so we can't use them.
mod callbacks {
use super::*;
macro_rules! callback {
($name:ident = ($($param:ident: $param_ty:ty),* $(,)?) -> $ret:ty) => {
#[derive(Debug, Clone, Hash)]
pub struct $name {
captured: Content,
f: fn(&Content, $($param_ty),*) -> $ret,
}
impl $name {
pub fn new<T: NativeElement>(
captured: Packed<T>,
f: fn(&Packed<T>, $($param_ty),*) -> $ret,
) -> Self {
Self {
// Type-erased the content.
captured: captured.pack(),
// Safety: The only difference between the two function
// pointer types is the type of the first parameter,
// which changes from `&Packed<T>` to `&Content`. This
// is safe because:
// - `Packed<T>` is a transparent wrapper around
// `Content`, so for any `T` it has the same memory
// representation as `Content`.
// - While `Packed<T>` imposes the additional constraint
// that the content is of type `T`, this constraint is
// upheld: It is initially the case because we store a
// `Packed<T>` above. It keeps being the case over the
// lifetime of the closure because `capture` is a
// private field and `Content`'s `Clone` impl is
// guaranteed to retain the type (if it didn't,
// literally everything would break).
#[allow(clippy::missing_transmute_annotations)]
f: unsafe { std::mem::transmute(f) },
}
}
pub fn call(&self, $($param: $param_ty),*) -> $ret {
(self.f)(&self.captured, $($param),*)
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
// Comparing function pointers is problematic. Since for
// each type of content, there is typically just one
// callback, we skip it. It barely matters anyway since
// getting into a comparison codepath for inline & block
// elements containing callback bodies is close to
// impossible (as these are generally generated in show
// rules).
self.captured.eq(&other.captured)
}
}
};
}
callback! {
InlineCallback = (
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Size,
) -> SourceResult<Vec<InlineItem>>
}
callback! {
BlockSingleCallback = (
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
region: Region,
) -> SourceResult<Frame>
}
callback! {
BlockMultiCallback = (
engine: &mut Engine,
locator: Locator,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment>
}
}
| 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/layout/transform.rs | crates/typst-library/src/layout/transform.rs | use crate::foundations::{Content, Smart, cast, elem};
use crate::layout::{Abs, Alignment, Angle, HAlignment, Length, Ratio, Rel, VAlignment};
/// Moves content without affecting layout.
///
/// The `move` function allows you to move content while the layout still 'sees'
/// it at the original positions. Containers will still be sized as if the
/// content was not moved.
///
/// # Example
/// ```example
/// #rect(inset: 0pt, fill: gray, move(
/// dx: 4pt, dy: 6pt,
/// rect(
/// inset: 8pt,
/// fill: white,
/// stroke: black,
/// [Abra cadabra]
/// )
/// ))
/// ```
///
/// # Accessibility
/// Moving is transparent to Assistive Technology (AT). Your content will be
/// read in the order it appears in the source, regardless of any visual
/// movement. If you need to hide content from AT altogether in PDF export,
/// consider using [`pdf.artifact`].
#[elem]
pub struct MoveElem {
/// The horizontal displacement of the content.
pub dx: Rel<Length>,
/// The vertical displacement of the content.
pub dy: Rel<Length>,
/// The content to move.
#[required]
pub body: Content,
}
/// Rotates content without affecting layout.
///
/// Rotates an element by a given angle. The layout will act as if the element
/// was not rotated unless you specify `{reflow: true}`.
///
/// # Example
/// ```example
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// ..range(16)
/// .map(i => rotate(24deg * i)[X]),
/// )
/// ```
#[elem]
pub struct RotateElem {
/// The amount of rotation.
///
/// ```example
/// #rotate(-1.571rad)[Space!]
/// ```
#[positional]
pub angle: Angle,
/// The origin of the rotation.
///
/// If, for instance, you wanted the bottom left corner of the rotated
/// element to stay aligned with the baseline, you would set it to `bottom +
/// left` instead.
///
/// ```example
/// #set text(spacing: 8pt)
/// #let square = square.with(width: 8pt)
///
/// #box(square())
/// #box(rotate(30deg, origin: center, square()))
/// #box(rotate(30deg, origin: top + left, square()))
/// #box(rotate(30deg, origin: bottom + right, square()))
/// ```
#[fold]
#[default(HAlignment::Center + VAlignment::Horizon)]
pub origin: Alignment,
/// Whether the rotation impacts the layout.
///
/// If set to `{false}`, the rotated content will retain the bounding box of
/// the original content. If set to `{true}`, the bounding box will take the
/// rotation of the content into account and adjust the layout accordingly.
///
/// ```example
/// Hello #rotate(90deg, reflow: true)[World]!
/// ```
#[default(false)]
pub reflow: bool,
/// The content to rotate.
#[required]
pub body: Content,
}
/// Scales content without affecting layout.
///
/// Lets you mirror content by specifying a negative scale on a single axis.
///
/// # Example
/// ```example
/// #set align(center)
/// #scale(x: -100%)[This is mirrored.]
/// #scale(x: -100%, reflow: true)[This is mirrored.]
/// ```
#[elem]
pub struct ScaleElem {
/// The scaling factor for both axes, as a positional argument. This is just
/// an optional shorthand notation for setting `x` and `y` to the same
/// value.
#[external]
#[positional]
#[default(Smart::Custom(ScaleAmount::Ratio(Ratio::one())))]
pub factor: Smart<ScaleAmount>,
/// The horizontal scaling factor.
///
/// The body will be mirrored horizontally if the parameter is negative.
#[parse(
let all = args.find()?;
args.named("x")?.or(all)
)]
#[default(Smart::Custom(ScaleAmount::Ratio(Ratio::one())))]
pub x: Smart<ScaleAmount>,
/// The vertical scaling factor.
///
/// The body will be mirrored vertically if the parameter is negative.
#[parse(args.named("y")?.or(all))]
#[default(Smart::Custom(ScaleAmount::Ratio(Ratio::one())))]
pub y: Smart<ScaleAmount>,
/// The origin of the transformation.
///
/// ```example
/// A#box(scale(75%)[A])A \
/// B#box(scale(75%, origin: bottom + left)[B])B
/// ```
#[fold]
#[default(HAlignment::Center + VAlignment::Horizon)]
pub origin: Alignment,
/// Whether the scaling impacts the layout.
///
/// If set to `{false}`, the scaled content will be allowed to overlap
/// other content. If set to `{true}`, it will compute the new size of
/// the scaled content and adjust the layout accordingly.
///
/// ```example
/// Hello #scale(x: 20%, y: 40%, reflow: true)[World]!
/// ```
#[default(false)]
pub reflow: bool,
/// The content to scale.
#[required]
pub body: Content,
}
/// To what size something shall be scaled.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ScaleAmount {
Ratio(Ratio),
Length(Length),
}
cast! {
ScaleAmount,
self => match self {
ScaleAmount::Ratio(ratio) => ratio.into_value(),
ScaleAmount::Length(length) => length.into_value(),
},
ratio: Ratio => ScaleAmount::Ratio(ratio),
length: Length => ScaleAmount::Length(length),
}
/// Skews content.
///
/// Skews an element in horizontal and/or vertical direction. The layout will
/// act as if the element was not skewed unless you specify `{reflow: true}`.
///
/// # Example
/// ```example
/// #skew(ax: -12deg)[
/// This is some fake italic text.
/// ]
/// ```
#[elem]
pub struct SkewElem {
/// The horizontal skewing angle.
///
/// ```example
/// #skew(ax: 30deg)[Skewed]
/// ```
#[default(Angle::zero())]
pub ax: Angle,
/// The vertical skewing angle.
///
/// ```example
/// #skew(ay: 30deg)[Skewed]
/// ```
#[default(Angle::zero())]
pub ay: Angle,
/// The origin of the skew transformation.
///
/// The origin will stay fixed during the operation.
///
/// ```example
/// X #box(skew(ax: -30deg, origin: center + horizon)[X]) X \
/// X #box(skew(ax: -30deg, origin: bottom + left)[X]) X \
/// X #box(skew(ax: -30deg, origin: top + right)[X]) X
/// ```
#[fold]
#[default(HAlignment::Center + VAlignment::Horizon)]
pub origin: Alignment,
/// Whether the skew transformation impacts the layout.
///
/// If set to `{false}`, the skewed content will retain the bounding box of
/// the original content. If set to `{true}`, the bounding box will take the
/// transformation of the content into account and adjust the layout accordingly.
///
/// ```example
/// Hello #skew(ay: 30deg, reflow: true, "World")!
/// ```
#[default(false)]
pub reflow: bool,
/// The content to skew.
#[required]
pub body: Content,
}
/// A scale-skew-translate transformation.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Transform {
pub sx: Ratio,
pub ky: Ratio,
pub kx: Ratio,
pub sy: Ratio,
pub tx: Abs,
pub ty: Abs,
}
impl Transform {
/// The identity transformation.
pub const fn identity() -> Self {
Self {
sx: Ratio::one(),
ky: Ratio::zero(),
kx: Ratio::zero(),
sy: Ratio::one(),
tx: Abs::zero(),
ty: Abs::zero(),
}
}
/// A translate transform.
pub const fn translate(tx: Abs, ty: Abs) -> Self {
Self { tx, ty, ..Self::identity() }
}
/// A scale transform.
pub const fn scale(sx: Ratio, sy: Ratio) -> Self {
Self { sx, sy, ..Self::identity() }
}
/// A scale transform at a specific position.
pub fn scale_at(sx: Ratio, sy: Ratio, px: Abs, py: Abs) -> Self {
Self::translate(px, py)
.pre_concat(Self::scale(sx, sy))
.pre_concat(Self::translate(-px, -py))
}
/// A rotate transform at a specific position.
pub fn rotate_at(angle: Angle, px: Abs, py: Abs) -> Self {
Self::translate(px, py)
.pre_concat(Self::rotate(angle))
.pre_concat(Self::translate(-px, -py))
}
/// A rotate transform.
pub fn rotate(angle: Angle) -> Self {
let cos = Ratio::new(angle.cos());
let sin = Ratio::new(angle.sin());
Self {
sx: cos,
ky: sin,
kx: -sin,
sy: cos,
..Self::default()
}
}
/// A skew transform.
pub fn skew(ax: Angle, ay: Angle) -> Self {
Self {
kx: Ratio::new(ax.tan()),
ky: Ratio::new(ay.tan()),
..Self::identity()
}
}
/// Whether this is the identity transformation.
pub fn is_identity(self) -> bool {
self == Self::identity()
}
/// Pre-concatenate another transformation.
pub fn pre_concat(self, prev: Self) -> Self {
Transform {
sx: self.sx * prev.sx + self.kx * prev.ky,
ky: self.ky * prev.sx + self.sy * prev.ky,
kx: self.sx * prev.kx + self.kx * prev.sy,
sy: self.ky * prev.kx + self.sy * prev.sy,
tx: self.sx.of(prev.tx) + self.kx.of(prev.ty) + self.tx,
ty: self.ky.of(prev.tx) + self.sy.of(prev.ty) + self.ty,
}
}
/// Post-concatenate another transformation.
pub fn post_concat(self, next: Self) -> Self {
next.pre_concat(self)
}
/// Inverts the transformation.
///
/// Returns `None` if the determinant of the matrix is zero.
pub fn invert(self) -> Option<Self> {
// Allow the trivial case to be inlined.
if self.is_identity() {
return Some(self);
}
// Fast path for scale-translate-only transforms.
if self.kx.is_zero() && self.ky.is_zero() {
if self.sx.is_zero() || self.sy.is_zero() {
return Some(Self::translate(-self.tx, -self.ty));
}
let inv_x = 1.0 / self.sx;
let inv_y = 1.0 / self.sy;
return Some(Self {
sx: Ratio::new(inv_x),
ky: Ratio::zero(),
kx: Ratio::zero(),
sy: Ratio::new(inv_y),
tx: -self.tx * inv_x,
ty: -self.ty * inv_y,
});
}
let det = self.sx * self.sy - self.kx * self.ky;
if det.get().abs() < 1e-12 {
return None;
}
let inv_det = 1.0 / det;
Some(Self {
sx: (self.sy * inv_det),
ky: (-self.ky * inv_det),
kx: (-self.kx * inv_det),
sy: (self.sx * inv_det),
tx: Abs::pt(
(self.kx.get() * self.ty.to_pt() - self.sy.get() * self.tx.to_pt())
* inv_det,
),
ty: Abs::pt(
(self.ky.get() * self.tx.to_pt() - self.sx.get() * self.ty.to_pt())
* inv_det,
),
})
}
}
impl Default for Transform {
fn default() -> Self {
Self::identity()
}
}
| 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/layout/regions.rs | crates/typst-library/src/layout/regions.rs | use std::fmt::{self, Debug, Formatter};
use crate::layout::{Abs, Axes, Size};
/// A single region to layout into.
#[derive(Debug, Copy, Clone, Hash)]
pub struct Region {
/// The size of the region.
pub size: Size,
/// Whether elements should expand to fill the regions instead of shrinking
/// to fit the content.
pub expand: Axes<bool>,
}
impl Region {
/// Create a new region.
pub fn new(size: Size, expand: Axes<bool>) -> Self {
Self { size, expand }
}
}
impl From<Region> for Regions<'_> {
fn from(region: Region) -> Self {
Regions {
size: region.size,
expand: region.expand,
full: region.size.y,
backlog: &[],
last: None,
}
}
}
/// A sequence of regions to layout into.
///
/// A *region* is a contiguous rectangular space in which elements
/// can be laid out. All regions within a `Regions` object have the
/// same width, namely `self.size.x`. This means that it is not
/// currently possible to, for instance, have content wrap to the
/// side of a floating element.
#[derive(Copy, Clone, Hash)]
pub struct Regions<'a> {
/// The remaining size of the first region.
pub size: Size,
/// Whether elements should expand to fill the regions instead of shrinking
/// to fit the content.
pub expand: Axes<bool>,
/// The full height of the region for relative sizing.
pub full: Abs,
/// The height of followup regions. The width is the same for all regions.
pub backlog: &'a [Abs],
/// The height of the final region that is repeated once the backlog is
/// drained. The width is the same for all regions.
pub last: Option<Abs>,
}
impl Regions<'_> {
/// Create a new sequence of same-size regions that repeats indefinitely.
pub fn repeat(size: Size, expand: Axes<bool>) -> Self {
Self {
size,
full: size.y,
backlog: &[],
last: Some(size.y),
expand,
}
}
/// The base size, which doesn't take into account that the regions is
/// already partially used up.
///
/// This is also used for relative sizing.
pub fn base(&self) -> Size {
Size::new(self.size.x, self.full)
}
/// Create new regions where all sizes are mapped with `f`.
///
/// Note that since all regions must have the same width, the width returned
/// by `f` is ignored for the backlog and the final region.
pub fn map<'v, F>(&self, backlog: &'v mut Vec<Abs>, mut f: F) -> Regions<'v>
where
F: FnMut(Size) -> Size,
{
let x = self.size.x;
backlog.clear();
backlog.extend(self.backlog.iter().map(|&y| f(Size::new(x, y)).y));
Regions {
size: f(self.size),
full: f(Size::new(x, self.full)).y,
backlog,
last: self.last.map(|y| f(Size::new(x, y)).y),
expand: self.expand,
}
}
/// Whether the first region is full and a region break is called for.
pub fn is_full(&self) -> bool {
Abs::zero().fits(self.size.y) && self.may_progress()
}
/// Whether a region break is permitted.
pub fn may_break(&self) -> bool {
!self.backlog.is_empty() || self.last.is_some()
}
/// Whether calling `next()` may improve a situation where there is a lack
/// of space.
pub fn may_progress(&self) -> bool {
!self.backlog.is_empty() || self.last.is_some_and(|height| self.size.y != height)
}
/// Advance to the next region if there is any.
pub fn next(&mut self) {
if let Some(height) = self
.backlog
.split_first()
.map(|(first, tail)| {
self.backlog = tail;
*first
})
.or(self.last)
{
self.size.y = height;
self.full = height;
}
}
/// An iterator that returns the sizes of the first and all following
/// regions, equivalently to what would be produced by calling
/// [`next()`](Self::next) repeatedly until all regions are exhausted.
/// This iterator may be infinite.
pub fn iter(&self) -> impl Iterator<Item = Size> + '_ {
let first = std::iter::once(self.size);
let backlog = self.backlog.iter();
let last = self.last.iter().cycle();
first.chain(backlog.chain(last).map(|&h| Size::new(self.size.x, h)))
}
}
impl Debug for Regions<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("Regions ")?;
let mut list = f.debug_list();
let mut prev = self.size.y;
list.entry(&self.size);
for &height in self.backlog {
list.entry(&Size::new(self.size.x, height));
prev = height;
}
if let Some(last) = self.last {
if last != prev {
list.entry(&Size::new(self.size.x, last));
}
list.entry(&(..));
}
list.finish()
}
}
| 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/layout/rect.rs | crates/typst-library/src/layout/rect.rs | use crate::layout::{Point, Size};
/// A rectangle in 2D.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Rect {
/// The top left corner (minimum coordinate).
pub min: Point,
/// The bottom right corner (maximum coordinate).
pub max: Point,
}
impl Rect {
/// Create a new rectangle from the minimum/maximum coordinate.
pub fn new(min: Point, max: Point) -> Self {
Self { min, max }
}
/// Create a new rectangle from the position and size.
pub fn from_pos_size(pos: Point, size: Size) -> Self {
Self { min: pos, max: pos + size.to_point() }
}
/// Compute the size of the rectangle.
pub fn size(&self) -> Size {
Size::new(self.max.x - self.min.x, self.max.y - self.min.y)
}
}
| 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/layout/angle.rs | crates/typst-library/src/layout/angle.rs | use std::f64::consts::PI;
use std::fmt::{self, Debug, Formatter};
use std::iter::Sum;
use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::foundations::{Repr, func, repr, scope, ty};
/// An angle describing a rotation.
///
/// Typst supports the following angular units:
///
/// - Degrees: `{180deg}`
/// - Radians: `{3.14rad}`
///
/// # Example
/// ```example
/// #rotate(10deg)[Hello there!]
/// ```
#[ty(scope, cast)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Angle(Scalar);
impl Angle {
/// The zero angle.
pub const fn zero() -> Self {
Self(Scalar::ZERO)
}
/// Create an angle from a number of raw units.
pub const fn raw(raw: f64) -> Self {
Self(Scalar::new(raw))
}
/// Create an angle from a value in a unit.
pub fn with_unit(val: f64, unit: AngleUnit) -> Self {
Self(Scalar::new(val * unit.raw_scale()))
}
/// Create an angle from a number of radians.
pub fn rad(rad: f64) -> Self {
Self::with_unit(rad, AngleUnit::Rad)
}
/// Create an angle from a number of degrees.
pub fn deg(deg: f64) -> Self {
Self::with_unit(deg, AngleUnit::Deg)
}
/// Get the value of this angle in raw units.
pub const fn to_raw(self) -> f64 {
(self.0).get()
}
/// Get the value of this angle in a unit.
pub fn to_unit(self, unit: AngleUnit) -> f64 {
self.to_raw() / unit.raw_scale()
}
/// The absolute value of the this angle.
pub fn abs(self) -> Self {
Self::raw(self.to_raw().abs())
}
/// Get the sine of this angle in radians.
pub fn sin(self) -> f64 {
self.to_rad().sin()
}
/// Get the cosine of this angle in radians.
pub fn cos(self) -> f64 {
self.to_rad().cos()
}
/// Get the tangent of this angle in radians.
pub fn tan(self) -> f64 {
self.to_rad().tan()
}
/// Get the quadrant of the Cartesian plane that this angle lies in.
///
/// The angle is automatically normalized to the range `0deg..=360deg`.
///
/// The quadrants are defined as follows:
/// - First: `0deg..=90deg` (top-right)
/// - Second: `90deg..=180deg` (top-left)
/// - Third: `180deg..=270deg` (bottom-left)
/// - Fourth: `270deg..=360deg` (bottom-right)
pub fn quadrant(self) -> Quadrant {
let angle = self.to_deg().rem_euclid(360.0);
if angle <= 90.0 {
Quadrant::First
} else if angle <= 180.0 {
Quadrant::Second
} else if angle <= 270.0 {
Quadrant::Third
} else {
Quadrant::Fourth
}
}
}
#[scope]
impl Angle {
/// Converts this angle to radians.
#[func(name = "rad", title = "Radians")]
pub fn to_rad(self) -> f64 {
self.to_unit(AngleUnit::Rad)
}
/// Converts this angle to degrees.
#[func(name = "deg", title = "Degrees")]
pub fn to_deg(self) -> f64 {
self.to_unit(AngleUnit::Deg)
}
}
impl Numeric for Angle {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.0.is_finite()
}
}
impl Debug for Angle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}deg", self.to_deg())
}
}
impl Repr for Angle {
fn repr(&self) -> EcoString {
repr::format_float_with_unit(self.to_deg(), "deg")
}
}
impl Neg for Angle {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Add for Angle {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
typst_utils::sub_impl!(Angle - Angle -> Angle);
impl Mul<f64> for Angle {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self(self.0 * other)
}
}
impl Mul<Angle> for f64 {
type Output = Angle;
fn mul(self, other: Angle) -> Angle {
other * self
}
}
impl Div for Angle {
type Output = f64;
fn div(self, other: Self) -> f64 {
self.to_raw() / other.to_raw()
}
}
impl Div<f64> for Angle {
type Output = Self;
fn div(self, other: f64) -> Self {
Self(self.0 / other)
}
}
typst_utils::assign_impl!(Angle += Angle);
typst_utils::assign_impl!(Angle -= Angle);
typst_utils::assign_impl!(Angle *= f64);
typst_utils::assign_impl!(Angle /= f64);
impl Sum for Angle {
fn sum<I: Iterator<Item = Angle>>(iter: I) -> Self {
Self(iter.map(|s| s.0).sum())
}
}
/// Different units of angular measurement.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum AngleUnit {
/// Radians.
Rad,
/// Degrees.
Deg,
}
impl AngleUnit {
/// How many raw units correspond to a value of `1.0` in this unit.
fn raw_scale(self) -> f64 {
match self {
Self::Rad => 1.0,
Self::Deg => PI / 180.0,
}
}
}
/// A quadrant of the Cartesian plane.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Quadrant {
/// The first quadrant, containing positive x and y values.
First,
/// The second quadrant, containing negative x and positive y values.
Second,
/// The third quadrant, containing negative x and y values.
Third,
/// The fourth quadrant, containing positive x and negative y values.
Fourth,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_angle_unit_conversion() {
assert!((Angle::rad(2.0 * PI).to_deg() - 360.0) < 1e-4);
assert!((Angle::deg(45.0).to_rad() - std::f64::consts::FRAC_PI_4) < 1e-4);
}
}
| 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/layout/em.rs | crates/typst-library/src/layout/em.rs | use std::fmt::{self, Debug, Formatter};
use std::iter::Sum;
use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::foundations::{Repr, Resolve, StyleChain, Value, cast, repr};
use crate::layout::{Abs, Length};
use crate::text::TextElem;
/// A length that is relative to the font size.
///
/// `1em` is the same as the font size.
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Em(Scalar);
impl Em {
/// The zero em length.
pub const fn zero() -> Self {
Self(Scalar::ZERO)
}
/// The font size.
pub const fn one() -> Self {
Self(Scalar::ONE)
}
/// Creates a font-relative length.
pub const fn new(em: f64) -> Self {
Self(Scalar::new(em))
}
/// Creates an em length from font units at the given units per em.
pub fn from_units(units: impl Into<f64>, units_per_em: f64) -> Self {
Self(Scalar::new(units.into() / units_per_em))
}
/// Creates an em length from an absolute length at the given font size.
pub fn from_abs(length: Abs, font_size: Abs) -> Self {
let result = length / font_size;
if result.is_finite() { Self(Scalar::new(result)) } else { Self::zero() }
}
/// Creates an em length from a length at the given font size.
pub fn from_length(length: Length, font_size: Abs) -> Em {
length.em + Self::from_abs(length.abs, font_size)
}
/// The number of em units.
pub const fn get(self) -> f64 {
(self.0).get()
}
/// The absolute value of this em length.
pub fn abs(self) -> Self {
Self::new(self.get().abs())
}
/// Converts to an absolute length at the given font size.
pub fn at(self, font_size: Abs) -> Abs {
let resolved = font_size * self.get();
if resolved.is_finite() { resolved } else { Abs::zero() }
}
}
impl Numeric for Em {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.0.is_finite()
}
}
impl Debug for Em {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}em", self.get())
}
}
impl Repr for Em {
fn repr(&self) -> EcoString {
repr::format_float_with_unit(self.get(), "em")
}
}
impl Neg for Em {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Add for Em {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
typst_utils::sub_impl!(Em - Em -> Em);
impl Mul<f64> for Em {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self(self.0 * other)
}
}
impl Mul<Em> for f64 {
type Output = Em;
fn mul(self, other: Em) -> Em {
other * self
}
}
impl Div<f64> for Em {
type Output = Self;
fn div(self, other: f64) -> Self {
Self(self.0 / other)
}
}
impl Div for Em {
type Output = f64;
fn div(self, other: Self) -> f64 {
self.get() / other.get()
}
}
typst_utils::assign_impl!(Em += Em);
typst_utils::assign_impl!(Em -= Em);
typst_utils::assign_impl!(Em *= f64);
typst_utils::assign_impl!(Em /= f64);
impl Sum for Em {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Self(iter.map(|s| s.0).sum())
}
}
cast! {
Em,
self => Value::Length(self.into()),
}
impl Resolve for Em {
type Output = Abs;
fn resolve(self, styles: StyleChain) -> Self::Output {
if self.is_zero() { Abs::zero() } else { self.at(styles.resolve(TextElem::size)) }
}
}
| 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/layout/align.rs | crates/typst-library/src/layout/align.rs | use std::ops::Add;
use ecow::{EcoString, eco_format};
use crate::diag::{HintedStrResult, StrResult, bail};
use crate::foundations::{
CastInfo, Content, Fold, FromValue, IntoValue, Reflect, Repr, Resolve, StyleChain,
Value, cast, elem, func, scope, ty,
};
use crate::layout::{Abs, Axes, Axis, Dir, Side};
use crate::text::TextElem;
/// Aligns content horizontally and vertically.
///
/// # Example
/// Let's start with centering our content horizontally:
/// ```example
/// #set page(height: 120pt)
/// #set align(center)
///
/// Centered text, a sight to see \
/// In perfect balance, visually \
/// Not left nor right, it stands alone \
/// A work of art, a visual throne
/// ```
///
/// To center something vertically, use _horizon_ alignment:
/// ```example
/// #set page(height: 120pt)
/// #set align(horizon)
///
/// Vertically centered, \
/// the stage had entered, \
/// a new paragraph.
/// ```
///
/// # Combining alignments
/// You can combine two alignments with the `+` operator. Let's also only apply
/// this to one piece of content by using the function form instead of a set
/// rule:
/// ```example
/// #set page(height: 120pt)
/// Though left in the beginning ...
///
/// #align(right + bottom)[
/// ... they were right in the end, \
/// and with addition had gotten, \
/// the paragraph to the bottom!
/// ]
/// ```
///
/// # Nested alignment
/// You can use varying alignments for layout containers and the elements within
/// them. This way, you can create intricate layouts:
///
/// ```example
/// #align(center, block[
/// #set align(left)
/// Though centered together \
/// alone \
/// we \
/// are \
/// left.
/// ])
/// ```
///
/// # Alignment within the same line
/// The `align` function performs block-level alignment and thus always
/// interrupts the current paragraph. To have different alignment for parts
/// of the same line, you should use [fractional spacing]($h) instead:
///
/// ```example
/// Start #h(1fr) End
/// ```
#[elem]
pub struct AlignElem {
/// The [alignment] along both axes.
///
/// ```example
/// #set page(height: 6cm)
/// #set text(lang: "ar")
///
/// مثال
/// #align(
/// end + horizon,
/// rect(inset: 12pt)[ركن]
/// )
/// ```
#[positional]
#[fold]
#[default]
pub alignment: Alignment,
/// The content to align.
#[required]
pub body: Content,
}
/// Where to align something along an axis.
///
/// Possible values are:
/// - `start`: Aligns at the [start]($direction.start) of the [text
/// direction]($text.dir).
/// - `end`: Aligns at the [end]($direction.end) of the [text
/// direction]($text.dir).
/// - `left`: Align at the left.
/// - `center`: Aligns in the middle, horizontally.
/// - `right`: Aligns at the right.
/// - `top`: Aligns at the top.
/// - `horizon`: Aligns in the middle, vertically.
/// - `bottom`: Align at the bottom.
///
/// These values are available globally and also in the alignment type's scope,
/// so you can write either of the following two:
///
/// ```example
/// #align(center)[Hi]
/// #align(alignment.center)[Hi]
/// ```
///
/// # 2D alignments
/// To align along both axes at the same time, add the two alignments using the
/// `+` operator. For example, `top + right` aligns the content to the top right
/// corner.
///
/// ```example
/// #set page(height: 3cm)
/// #align(center + bottom)[Hi]
/// ```
///
/// # Fields
/// The `x` and `y` fields hold the alignment's horizontal and vertical
/// components, respectively (as yet another `alignment`). They may be `{none}`.
///
/// ```example
/// #(top + right).x \
/// #left.x \
/// #left.y (none)
/// ```
#[ty(scope)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Alignment {
H(HAlignment),
V(VAlignment),
Both(HAlignment, VAlignment),
}
impl Alignment {
/// The horizontal component.
pub const fn x(self) -> Option<HAlignment> {
match self {
Self::H(h) | Self::Both(h, _) => Some(h),
Self::V(_) => None,
}
}
/// The vertical component.
pub const fn y(self) -> Option<VAlignment> {
match self {
Self::V(v) | Self::Both(_, v) => Some(v),
Self::H(_) => None,
}
}
/// Normalize the alignment to a LTR-TTB space.
pub fn fix(self, text_dir: Dir) -> Axes<FixedAlignment> {
Axes::new(
self.x().unwrap_or_default().fix(text_dir),
self.y().unwrap_or_default().fix(text_dir),
)
}
}
#[scope]
impl Alignment {
pub const START: Self = Alignment::H(HAlignment::Start);
pub const LEFT: Self = Alignment::H(HAlignment::Left);
pub const CENTER: Self = Alignment::H(HAlignment::Center);
pub const RIGHT: Self = Alignment::H(HAlignment::Right);
pub const END: Self = Alignment::H(HAlignment::End);
pub const TOP: Self = Alignment::V(VAlignment::Top);
pub const HORIZON: Self = Alignment::V(VAlignment::Horizon);
pub const BOTTOM: Self = Alignment::V(VAlignment::Bottom);
/// The axis this alignment belongs to.
/// - `{"horizontal"}` for `start`, `left`, `center`, `right`, and `end`
/// - `{"vertical"}` for `top`, `horizon`, and `bottom`
/// - `{none}` for 2-dimensional alignments
///
/// ```example
/// #left.axis() \
/// #bottom.axis()
/// ```
#[func]
pub const fn axis(self) -> Option<Axis> {
match self {
Self::H(_) => Some(Axis::X),
Self::V(_) => Some(Axis::Y),
Self::Both(..) => None,
}
}
/// The inverse alignment.
///
/// ```example
/// #top.inv() \
/// #left.inv() \
/// #center.inv() \
/// #(left + bottom).inv()
/// ```
#[func(title = "Inverse")]
pub const fn inv(self) -> Alignment {
match self {
Self::H(h) => Self::H(h.inv()),
Self::V(v) => Self::V(v.inv()),
Self::Both(h, v) => Self::Both(h.inv(), v.inv()),
}
}
}
impl Default for Alignment {
fn default() -> Self {
HAlignment::default() + VAlignment::default()
}
}
impl Add for Alignment {
type Output = StrResult<Self>;
fn add(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(Self::H(h), Self::V(v)) | (Self::V(v), Self::H(h)) => Ok(h + v),
(Self::H(_), Self::H(_)) => bail!("cannot add two horizontal alignments"),
(Self::V(_), Self::V(_)) => bail!("cannot add two vertical alignments"),
(Self::H(_), Self::Both(..)) | (Self::Both(..), Self::H(_)) => {
bail!("cannot add a horizontal and a 2D alignment")
}
(Self::V(_), Self::Both(..)) | (Self::Both(..), Self::V(_)) => {
bail!("cannot add a vertical and a 2D alignment")
}
(Self::Both(..), Self::Both(..)) => {
bail!("cannot add two 2D alignments")
}
}
}
}
impl Repr for Alignment {
fn repr(&self) -> EcoString {
match self {
Self::H(h) => h.repr(),
Self::V(v) => v.repr(),
Self::Both(h, v) => eco_format!("{} + {}", h.repr(), v.repr()),
}
}
}
impl Fold for Alignment {
fn fold(self, outer: Self) -> Self {
match (self, outer) {
(Self::H(h), Self::V(v) | Self::Both(_, v)) => Self::Both(h, v),
(Self::V(v), Self::H(h) | Self::Both(h, _)) => Self::Both(h, v),
_ => self,
}
}
}
impl Resolve for Alignment {
type Output = Axes<FixedAlignment>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.fix(styles.resolve(TextElem::dir))
}
}
impl From<Side> for Alignment {
fn from(side: Side) -> Self {
match side {
Side::Left => Self::LEFT,
Side::Top => Self::TOP,
Side::Right => Self::RIGHT,
Side::Bottom => Self::BOTTOM,
}
}
}
/// Alignment on this axis can be fixed to an absolute direction.
pub trait FixAlignment {
/// Resolve to the absolute alignment.
fn fix(self, dir: Dir) -> FixedAlignment;
}
/// Where to align something horizontally.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum HAlignment {
#[default]
Start,
Left,
Center,
Right,
End,
}
impl HAlignment {
/// The inverse horizontal alignment.
pub const fn inv(self) -> Self {
match self {
Self::Start => Self::End,
Self::Left => Self::Right,
Self::Center => Self::Center,
Self::Right => Self::Left,
Self::End => Self::Start,
}
}
}
impl FixAlignment for HAlignment {
fn fix(self, dir: Dir) -> FixedAlignment {
match (self, dir.is_positive()) {
(Self::Start, true) | (Self::End, false) => FixedAlignment::Start,
(Self::Left, _) => FixedAlignment::Start,
(Self::Center, _) => FixedAlignment::Center,
(Self::Right, _) => FixedAlignment::End,
(Self::End, true) | (Self::Start, false) => FixedAlignment::End,
}
}
}
impl Repr for HAlignment {
fn repr(&self) -> EcoString {
match self {
Self::Start => "start".into(),
Self::Left => "left".into(),
Self::Center => "center".into(),
Self::Right => "right".into(),
Self::End => "end".into(),
}
}
}
impl Add<VAlignment> for HAlignment {
type Output = Alignment;
fn add(self, rhs: VAlignment) -> Self::Output {
Alignment::Both(self, rhs)
}
}
impl From<HAlignment> for Alignment {
fn from(align: HAlignment) -> Self {
Self::H(align)
}
}
impl TryFrom<Alignment> for HAlignment {
type Error = EcoString;
fn try_from(value: Alignment) -> StrResult<Self> {
match value {
Alignment::H(h) => Ok(h),
v => bail!(
"expected `start`, `left`, `center`, `right`, or `end`, found {}",
v.repr(),
),
}
}
}
impl Resolve for HAlignment {
type Output = FixedAlignment;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.fix(styles.resolve(TextElem::dir))
}
}
cast! {
HAlignment,
self => Alignment::H(self).into_value(),
align: Alignment => Self::try_from(align)?,
}
/// A horizontal alignment which only allows `left`/`right` and `start`/`end`,
/// thus excluding `center`.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum OuterHAlignment {
#[default]
Start,
Left,
Right,
End,
}
impl FixAlignment for OuterHAlignment {
fn fix(self, dir: Dir) -> FixedAlignment {
match (self, dir.is_positive()) {
(Self::Start, true) | (Self::End, false) => FixedAlignment::Start,
(Self::Left, _) => FixedAlignment::Start,
(Self::Right, _) => FixedAlignment::End,
(Self::End, true) | (Self::Start, false) => FixedAlignment::End,
}
}
}
impl Resolve for OuterHAlignment {
type Output = FixedAlignment;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.fix(styles.resolve(TextElem::dir))
}
}
impl From<OuterHAlignment> for HAlignment {
fn from(value: OuterHAlignment) -> Self {
match value {
OuterHAlignment::Start => Self::Start,
OuterHAlignment::Left => Self::Left,
OuterHAlignment::Right => Self::Right,
OuterHAlignment::End => Self::End,
}
}
}
impl TryFrom<Alignment> for OuterHAlignment {
type Error = EcoString;
fn try_from(value: Alignment) -> StrResult<Self> {
match value {
Alignment::H(HAlignment::Start) => Ok(Self::Start),
Alignment::H(HAlignment::Left) => Ok(Self::Left),
Alignment::H(HAlignment::Right) => Ok(Self::Right),
Alignment::H(HAlignment::End) => Ok(Self::End),
v => bail!("expected `start`, `left`, `right`, or `end`, found {}", v.repr()),
}
}
}
cast! {
OuterHAlignment,
self => HAlignment::from(self).into_value(),
align: Alignment => Self::try_from(align)?,
}
/// Where to align something vertically.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum VAlignment {
#[default]
Top,
Horizon,
Bottom,
}
impl VAlignment {
/// The inverse vertical alignment.
pub const fn inv(self) -> Self {
match self {
Self::Top => Self::Bottom,
Self::Horizon => Self::Horizon,
Self::Bottom => Self::Top,
}
}
/// Returns the position of this alignment in a container with the given
/// extent.
pub fn position(self, extent: Abs) -> Abs {
match self {
Self::Top => Abs::zero(),
Self::Horizon => extent / 2.0,
Self::Bottom => extent,
}
}
}
impl FixAlignment for VAlignment {
fn fix(self, _: Dir) -> FixedAlignment {
// The vertical alignment does not depend on text direction.
match self {
Self::Top => FixedAlignment::Start,
Self::Horizon => FixedAlignment::Center,
Self::Bottom => FixedAlignment::End,
}
}
}
impl Repr for VAlignment {
fn repr(&self) -> EcoString {
match self {
Self::Top => "top".into(),
Self::Horizon => "horizon".into(),
Self::Bottom => "bottom".into(),
}
}
}
impl Add<HAlignment> for VAlignment {
type Output = Alignment;
fn add(self, rhs: HAlignment) -> Self::Output {
Alignment::Both(rhs, self)
}
}
impl Resolve for VAlignment {
type Output = FixedAlignment;
fn resolve(self, _: StyleChain) -> Self::Output {
self.fix(Dir::TTB)
}
}
impl From<VAlignment> for Alignment {
fn from(align: VAlignment) -> Self {
Self::V(align)
}
}
impl TryFrom<Alignment> for VAlignment {
type Error = EcoString;
fn try_from(value: Alignment) -> StrResult<Self> {
match value {
Alignment::V(v) => Ok(v),
v => bail!("expected `top`, `horizon`, or `bottom`, found {}", v.repr()),
}
}
}
cast! {
VAlignment,
self => Alignment::V(self).into_value(),
align: Alignment => Self::try_from(align)?,
}
/// A vertical alignment which only allows `top` and `bottom`, thus excluding
/// `horizon`.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum OuterVAlignment {
#[default]
Top,
Bottom,
}
impl FixAlignment for OuterVAlignment {
fn fix(self, _: Dir) -> FixedAlignment {
// The vertical alignment does not depend on text direction.
match self {
Self::Top => FixedAlignment::Start,
Self::Bottom => FixedAlignment::End,
}
}
}
impl From<OuterVAlignment> for VAlignment {
fn from(value: OuterVAlignment) -> Self {
match value {
OuterVAlignment::Top => Self::Top,
OuterVAlignment::Bottom => Self::Bottom,
}
}
}
impl TryFrom<Alignment> for OuterVAlignment {
type Error = EcoString;
fn try_from(value: Alignment) -> StrResult<Self> {
match value {
Alignment::V(VAlignment::Top) => Ok(Self::Top),
Alignment::V(VAlignment::Bottom) => Ok(Self::Bottom),
v => bail!("expected `top` or `bottom`, found {}", v.repr()),
}
}
}
cast! {
OuterVAlignment,
self => VAlignment::from(self).into_value(),
align: Alignment => Self::try_from(align)?,
}
/// An internal representation that combines horizontal or vertical alignments. The
/// allowed alignment positions are designated by the type parameter `H` and `V`.
///
/// This is not user-visible, but an internal type to impose type safety. For example,
/// `SpecificAlignment<HAlignment, OuterVAlignment>` does not allow vertical alignment
/// position "center", because `V = OuterVAlignment` doesn't have it.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum SpecificAlignment<H, V> {
H(H),
V(V),
Both(H, V),
}
impl<H, V> SpecificAlignment<H, V>
where
H: Default + Copy + FixAlignment,
V: Default + Copy + FixAlignment,
{
/// The horizontal component.
pub const fn x(self) -> Option<H> {
match self {
Self::H(h) | Self::Both(h, _) => Some(h),
Self::V(_) => None,
}
}
/// The vertical component.
pub const fn y(self) -> Option<V> {
match self {
Self::V(v) | Self::Both(_, v) => Some(v),
Self::H(_) => None,
}
}
/// Normalize the alignment to a LTR-TTB space.
pub fn fix(self, text_dir: Dir) -> Axes<FixedAlignment> {
Axes::new(
self.x().unwrap_or_default().fix(text_dir),
self.y().unwrap_or_default().fix(text_dir),
)
}
}
impl<H, V> Resolve for SpecificAlignment<H, V>
where
H: Default + Copy + FixAlignment,
V: Default + Copy + FixAlignment,
{
type Output = Axes<FixedAlignment>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.fix(styles.resolve(TextElem::dir))
}
}
impl<H, V> From<SpecificAlignment<H, V>> for Alignment
where
HAlignment: From<H>,
VAlignment: From<V>,
{
fn from(value: SpecificAlignment<H, V>) -> Self {
type FromType<H, V> = SpecificAlignment<H, V>;
match value {
FromType::H(h) => Self::H(HAlignment::from(h)),
FromType::V(v) => Self::V(VAlignment::from(v)),
FromType::Both(h, v) => Self::Both(HAlignment::from(h), VAlignment::from(v)),
}
}
}
impl<H, V> Reflect for SpecificAlignment<H, V>
where
H: Reflect,
V: Reflect,
{
fn input() -> CastInfo {
Alignment::input()
}
fn output() -> CastInfo {
Alignment::output()
}
fn castable(value: &Value) -> bool {
H::castable(value) || V::castable(value)
}
}
impl<H, V> IntoValue for SpecificAlignment<H, V>
where
HAlignment: From<H>,
VAlignment: From<V>,
{
fn into_value(self) -> Value {
Alignment::from(self).into_value()
}
}
impl<H, V> FromValue for SpecificAlignment<H, V>
where
H: Reflect + TryFrom<Alignment, Error = EcoString>,
V: Reflect + TryFrom<Alignment, Error = EcoString>,
{
fn from_value(value: Value) -> HintedStrResult<Self> {
if Alignment::castable(&value) {
let align = Alignment::from_value(value)?;
let result = match align {
Alignment::H(_) => Self::H(H::try_from(align)?),
Alignment::V(_) => Self::V(V::try_from(align)?),
Alignment::Both(h, v) => {
Self::Both(H::try_from(h.into())?, V::try_from(v.into())?)
}
};
return Ok(result);
}
Err(Self::error(&value))
}
}
/// A fixed alignment in the global coordinate space.
///
/// For horizontal alignment, start is globally left and for vertical alignment
/// it is globally top.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum FixedAlignment {
Start,
Center,
End,
}
impl FixedAlignment {
/// Returns the position of this alignment in a container with the given
/// extent.
pub fn position(self, extent: Abs) -> Abs {
match self {
Self::Start => Abs::zero(),
Self::Center => extent / 2.0,
Self::End => extent,
}
}
/// The inverse alignment.
pub const fn inv(self) -> Self {
match self {
Self::Start => Self::End,
Self::Center => Self::Center,
Self::End => Self::Start,
}
}
}
impl From<Side> for FixedAlignment {
fn from(side: Side) -> Self {
match side {
Side::Left => Self::Start,
Side::Top => Self::Start,
Side::Right => Self::End,
Side::Bottom => Self::End,
}
}
}
| 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/layout/mod.rs | crates/typst-library/src/layout/mod.rs | //! Composable layouts.
mod abs;
mod align;
mod angle;
mod axes;
mod columns;
mod container;
mod corners;
mod dir;
mod em;
mod fr;
mod fragment;
mod frame;
pub mod grid;
mod hide;
#[path = "layout.rs"]
mod layout_;
mod length;
#[path = "measure.rs"]
mod measure_;
mod pad;
mod page;
mod place;
mod point;
mod ratio;
mod rect;
mod regions;
mod rel;
mod repeat;
mod sides;
mod size;
mod spacing;
mod stack;
mod transform;
pub use self::abs::*;
pub use self::align::*;
pub use self::angle::*;
pub use self::axes::*;
pub use self::columns::*;
pub use self::container::*;
pub use self::corners::*;
pub use self::dir::*;
pub use self::em::*;
pub use self::fr::*;
pub use self::fragment::*;
pub use self::frame::*;
pub use self::grid::*;
pub use self::hide::*;
pub use self::layout_::*;
pub use self::length::*;
pub use self::measure_::*;
pub use self::pad::*;
pub use self::page::*;
pub use self::place::*;
pub use self::point::*;
pub use self::ratio::*;
pub use self::rect::*;
pub use self::regions::*;
pub use self::rel::*;
pub use self::repeat::*;
pub use self::sides::*;
pub use self::size::*;
pub use self::spacing::*;
pub use self::stack::*;
pub use self::transform::*;
use crate::foundations::Scope;
/// Hook up all `layout` definitions.
pub fn define(global: &mut Scope) {
global.start_category(crate::Category::Layout);
global.define_type::<Length>();
global.define_type::<Angle>();
global.define_type::<Ratio>();
global.define_type::<Rel<Length>>();
global.define_type::<Fr>();
global.define_type::<Dir>();
global.define_type::<Alignment>();
global.define_elem::<PageElem>();
global.define_elem::<PagebreakElem>();
global.define_elem::<VElem>();
global.define_elem::<HElem>();
global.define_elem::<BoxElem>();
global.define_elem::<BlockElem>();
global.define_elem::<StackElem>();
global.define_elem::<GridElem>();
global.define_elem::<ColumnsElem>();
global.define_elem::<ColbreakElem>();
global.define_elem::<PlaceElem>();
global.define_elem::<AlignElem>();
global.define_elem::<PadElem>();
global.define_elem::<RepeatElem>();
global.define_elem::<MoveElem>();
global.define_elem::<ScaleElem>();
global.define_elem::<RotateElem>();
global.define_elem::<SkewElem>();
global.define_elem::<HideElem>();
global.define_func::<measure>();
global.define_func::<layout>();
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/layout/layout.rs | crates/typst-library/src/layout/layout.rs | use typst_syntax::Span;
use crate::foundations::{Content, Func, NativeElement, elem, func};
use crate::introspection::Locatable;
/// Provides access to the current outer container's (or page's, if none)
/// dimensions (width and height).
///
/// Accepts a function that receives a single parameter, which is a dictionary
/// with keys `width` and `height`, both of type [`length`]. The function is
/// provided [context], meaning you don't need to use it in combination with the
/// `context` keyword. This is why [`measure`] can be called in the example
/// below.
///
/// ```example
/// #let text = lorem(30)
/// #layout(size => [
/// #let (height,) = measure(
/// width: size.width,
/// text,
/// )
/// This text is #height high with
/// the current page width: \
/// #text
/// ])
/// ```
///
/// Note that the `layout` function forces its contents into a [block]-level
/// container, so placement relative to the page or pagebreaks are not possible
/// within it.
///
/// If the `layout` call is placed inside a box with a width of `{800pt}` and a
/// height of `{400pt}`, then the specified function will be given the argument
/// `{(width: 800pt, height: 400pt)}`. If it is placed directly into the page, it
/// receives the page's dimensions minus its margins. This is mostly useful in
/// combination with [measurement]($measure).
///
/// To retrieve the _remaining_ height of the page rather than its full size,
/// you can wrap your `layout` call in a `{block(height: 1fr)}`. This works
/// because the block automatically grows to fill the remaining space (see the
/// [fraction] documentation for more details).
///
/// ```example
/// #set page(height: 150pt)
///
/// #lorem(20)
///
/// #block(height: 1fr, layout(size => [
/// Remaining height: #size.height
/// ]))
/// ```
///
/// You can also use this function to resolve a [`ratio`] to a fixed length.
/// This might come in handy if you're building your own layout abstractions.
///
/// ```example
/// #layout(size => {
/// let half = 50% * size.width
/// [Half a page is #half wide.]
/// })
/// ```
///
/// Note that the width or height provided by `layout` will be infinite if the
/// corresponding page dimension is set to `{auto}`.
#[func]
pub fn layout(
span: Span,
/// A function to call with the outer container's size. Its return value is
/// displayed in the document.
///
/// The container's size is given as a [dictionary] with the keys `width`
/// and `height`, both of type [`length`].
///
/// This function is called once for each time the content returned by
/// `layout` appears in the document. This makes it possible to generate
/// content that depends on the dimensions of its container.
func: Func,
) -> Content {
LayoutElem::new(func).pack().spanned(span)
}
/// Executes a `layout` call.
#[elem(Locatable)]
pub struct LayoutElem {
/// The function to call with the outer container's (or page's) size.
#[required]
pub func: Func,
}
| 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/layout/stack.rs | crates/typst-library/src/layout/stack.rs | use std::fmt::{self, Debug, Formatter};
use crate::foundations::{Content, cast, elem};
use crate::layout::{Dir, Spacing};
/// Arranges content and spacing horizontally or vertically.
///
/// The stack places a list of items along an axis, with optional spacing
/// between each item.
///
/// # Example
/// ```example
/// #stack(
/// dir: ttb,
/// rect(width: 40pt),
/// rect(width: 120pt),
/// rect(width: 90pt),
/// )
/// ```
///
/// # Accessibility
/// Stacks do not carry any special semantics. The contents of the stack are
/// read by Assistive Technology (AT) in the order in which they have been
/// passed to this function.
#[elem]
pub struct StackElem {
/// The direction along which the items are stacked. Possible values are:
///
/// - `{ltr}`: Left to right.
/// - `{rtl}`: Right to left.
/// - `{ttb}`: Top to bottom.
/// - `{btt}`: Bottom to top.
///
/// You can use the `start` and `end` methods to obtain the initial and
/// final points (respectively) of a direction, as `alignment`. You can also
/// use the `axis` method to determine whether a direction is
/// `{"horizontal"}` or `{"vertical"}`. The `inv` method returns a
/// direction's inverse direction.
///
/// For example, `{ttb.start()}` is `top`, `{ttb.end()}` is `bottom`,
/// `{ttb.axis()}` is `{"vertical"}` and `{ttb.inv()}` is equal to `btt`.
#[default(Dir::TTB)]
pub dir: Dir,
/// Spacing to insert between items where no explicit spacing was provided.
pub spacing: Option<Spacing>,
/// The children to stack along the axis.
#[variadic]
pub children: Vec<StackChild>,
}
/// A child of a stack element.
#[derive(Clone, PartialEq, Hash)]
pub enum StackChild {
/// Spacing between other children.
Spacing(Spacing),
/// Arbitrary block-level content.
Block(Content),
}
impl Debug for StackChild {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Spacing(kind) => kind.fmt(f),
Self::Block(block) => block.fmt(f),
}
}
}
cast! {
StackChild,
self => match self {
Self::Spacing(spacing) => spacing.into_value(),
Self::Block(content) => content.into_value(),
},
v: Spacing => Self::Spacing(v),
v: Content => Self::Block(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/layout/ratio.rs | crates/typst-library/src/layout/ratio.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::foundations::{Repr, repr, ty};
/// A ratio of a whole.
///
/// A ratio is written as a number, followed by a percent sign. Ratios most
/// often appear as part of a [relative length]($relative), to specify the size
/// of some layout element relative to the page or some container.
///
/// ```example
/// #rect(width: 25%)
/// ```
///
/// However, they can also describe any other property that is relative to some
/// base, e.g. an amount of [horizontal scaling]($scale.x) or the
/// [height of parentheses]($math.lr.size) relative to the height of the content
/// they enclose.
///
/// # Scripting
/// Within your own code, you can use ratios as you like. You can multiply them
/// with various other types as shown below:
///
/// | Multiply by | Example | Result |
/// |-----------------|-------------------------|-----------------|
/// | [`ratio`] | `{27% * 10%}` | `{2.7%}` |
/// | [`length`] | `{27% * 100pt}` | `{27pt}` |
/// | [`relative`] | `{27% * (10% + 100pt)}` | `{2.7% + 27pt}` |
/// | [`angle`] | `{27% * 100deg}` | `{27deg}` |
/// | [`int`] | `{27% * 2}` | `{54%}` |
/// | [`float`] | `{27% * 0.37037}` | `{10%}` |
/// | [`fraction`] | `{27% * 3fr}` | `{0.81fr}` |
///
/// When ratios are [displayed]($repr) in the document, they are rounded to two
/// significant digits for readability.
#[ty(cast)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Ratio(Scalar);
impl Ratio {
/// A ratio of `0%` represented as `0.0`.
pub const fn zero() -> Self {
Self(Scalar::ZERO)
}
/// A ratio of `100%` represented as `1.0`.
pub const fn one() -> Self {
Self(Scalar::ONE)
}
/// Create a new ratio from a value, where `1.0` means `100%`.
pub const fn new(ratio: f64) -> Self {
Self(Scalar::new(ratio))
}
/// Get the underlying ratio.
pub const fn get(self) -> f64 {
(self.0).get()
}
/// Whether the ratio is zero.
pub fn is_zero(self) -> bool {
self.0 == 0.0
}
/// Whether the ratio is one.
pub fn is_one(self) -> bool {
self.0 == 1.0
}
/// The absolute value of this ratio.
pub fn abs(self) -> Self {
Self::new(self.get().abs())
}
/// Return the ratio of the given `whole`.
pub fn of<T: Numeric>(self, whole: T) -> T {
let resolved = whole * self.get();
if resolved.is_finite() { resolved } else { T::zero() }
}
}
impl Debug for Ratio {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}%", self.get() * 100.0)
}
}
impl Repr for Ratio {
fn repr(&self) -> EcoString {
repr::format_float_with_unit(self.get() * 100.0, "%")
}
}
impl Neg for Ratio {
type Output = Self;
fn neg(self) -> Self {
Self(-self.0)
}
}
impl Add for Ratio {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}
typst_utils::sub_impl!(Ratio - Ratio -> Ratio);
impl Mul for Ratio {
type Output = Self;
fn mul(self, other: Self) -> Self {
Self(self.0 * other.0)
}
}
impl Mul<f64> for Ratio {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self(self.0 * other)
}
}
impl Mul<Ratio> for f64 {
type Output = Ratio;
fn mul(self, other: Ratio) -> Ratio {
other * self
}
}
impl Div for Ratio {
type Output = f64;
fn div(self, other: Self) -> f64 {
self.get() / other.get()
}
}
impl Div<f64> for Ratio {
type Output = Self;
fn div(self, other: f64) -> Self {
Self(self.0 / other)
}
}
impl Div<Ratio> for f64 {
type Output = Self;
fn div(self, other: Ratio) -> Self {
self / other.get()
}
}
typst_utils::assign_impl!(Ratio += Ratio);
typst_utils::assign_impl!(Ratio -= Ratio);
typst_utils::assign_impl!(Ratio *= Ratio);
typst_utils::assign_impl!(Ratio *= f64);
typst_utils::assign_impl!(Ratio /= f64);
| 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/layout/spacing.rs | crates/typst-library/src/layout/spacing.rs | use typst_utils::{Numeric, singleton};
use crate::foundations::{Content, NativeElement, cast, elem};
use crate::layout::{Abs, Em, Fr, Length, Ratio, Rel};
/// Inserts horizontal spacing into a paragraph.
///
/// The spacing can be absolute, relative, or fractional. In the last case, the
/// remaining space on the line is distributed among all fractional spacings
/// according to their relative fractions.
///
/// # Example
/// ```example
/// First #h(1cm) Second \
/// First #h(30%) Second
/// ```
///
/// # Fractional spacing
/// With fractional spacing, you can align things within a line without forcing
/// a paragraph break (like [`align`] would). Each fractionally sized element
/// gets space based on the ratio of its fraction to the sum of all fractions.
///
/// ```example
/// First #h(1fr) Second \
/// First #h(1fr) Second #h(1fr) Third \
/// First #h(2fr) Second #h(1fr) Third
/// ```
///
/// # Mathematical Spacing { #math-spacing }
/// In [mathematical formulas]($category/math), you can additionally use these
/// constants to add spacing between elements: `thin` (1/6 em), `med` (2/9 em),
/// `thick` (5/18 em), `quad` (1 em), `wide` (2 em).
#[elem(title = "Spacing (H)")]
pub struct HElem {
/// How much spacing to insert.
#[required]
pub amount: Spacing,
/// If `{true}`, the spacing collapses at the start or end of a paragraph.
/// Moreover, from multiple adjacent weak spacings all but the largest one
/// collapse.
///
/// Weak spacing in markup also causes all adjacent markup spaces to be
/// removed, regardless of the amount of spacing inserted. To force a space
/// next to weak spacing, you can explicitly write `[#" "]` (for a normal
/// space) or `[~]` (for a non-breaking space). The latter can be useful to
/// create a construct that always attaches to the preceding word with one
/// non-breaking space, independently of whether a markup space existed in
/// front or not.
///
/// ```example
/// #h(1cm, weak: true)
/// We identified a group of _weak_
/// specimens that fail to manifest
/// in most cases. However, when
/// #h(8pt, weak: true) supported
/// #h(8pt, weak: true) on both sides,
/// they do show up.
///
/// Further #h(0pt, weak: true) more,
/// even the smallest of them swallow
/// adjacent markup spaces.
/// ```
#[default(false)]
pub weak: bool,
}
impl HElem {
/// Zero-width horizontal weak spacing that eats surrounding spaces.
pub fn hole() -> &'static Content {
singleton!(Content, HElem::new(Abs::zero().into()).with_weak(true).pack())
}
}
/// Inserts vertical spacing into a flow of blocks.
///
/// The spacing can be absolute, relative, or fractional. In the last case,
/// the remaining space on the page is distributed among all fractional spacings
/// according to their relative fractions.
///
/// # Example
/// ```example
/// #grid(
/// rows: 3cm,
/// columns: 6,
/// gutter: 1fr,
/// [A #parbreak() B],
/// [A #v(0pt) B],
/// [A #v(10pt) B],
/// [A #v(0pt, weak: true) B],
/// [A #v(40%, weak: true) B],
/// [A #v(1fr) B],
/// )
/// ```
#[elem(title = "Spacing (V)")]
pub struct VElem {
/// How much spacing to insert.
#[required]
pub amount: Spacing,
/// If `{true}`, the spacing collapses at the start or end of a flow.
/// Moreover, from multiple adjacent weak spacings all but the largest one
/// collapse. Weak spacings will always collapse adjacent paragraph spacing,
/// even if the paragraph spacing is larger.
///
/// ```example
/// The following theorem is
/// foundational to the field:
/// #v(4pt, weak: true)
/// $ x^2 + y^2 = r^2 $
/// #v(4pt, weak: true)
/// The proof is simple:
/// ```
pub weak: bool,
/// Whether the spacing collapses if not immediately preceded by a
/// paragraph.
#[internal]
#[parse(Some(false))]
pub attach: bool,
}
cast! {
VElem,
v: Content => v.unpack::<Self>().map_err(|_| "expected `v` element")?,
}
/// Kinds of spacing.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Spacing {
/// Spacing specified in absolute terms and relative to the parent's size.
Rel(Rel<Length>),
/// Spacing specified as a fraction of the remaining free space in the
/// parent.
Fr(Fr),
}
impl Spacing {
/// Whether this is fractional spacing.
pub fn is_fractional(self) -> bool {
matches!(self, Self::Fr(_))
}
/// Whether the spacing is actually no spacing.
pub fn is_zero(&self) -> bool {
match self {
Self::Rel(rel) => rel.is_zero(),
Self::Fr(fr) => fr.is_zero(),
}
}
}
impl From<Abs> for Spacing {
fn from(abs: Abs) -> Self {
Self::Rel(abs.into())
}
}
impl From<Em> for Spacing {
fn from(em: Em) -> Self {
Self::Rel(Rel::new(Ratio::zero(), em.into()))
}
}
impl From<Length> for Spacing {
fn from(length: Length) -> Self {
Self::Rel(length.into())
}
}
impl From<Fr> for Spacing {
fn from(fr: Fr) -> Self {
Self::Fr(fr)
}
}
cast! {
Spacing,
self => match self {
Self::Rel(rel) => {
if rel.rel.is_zero() {
rel.abs.into_value()
} else if rel.abs.is_zero() {
rel.rel.into_value()
} else {
rel.into_value()
}
}
Self::Fr(fr) => fr.into_value(),
},
v: Rel<Length> => Self::Rel(v),
v: Fr => Self::Fr(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/layout/dir.rs | crates/typst-library/src/layout/dir.rs | use ecow::EcoString;
use crate::foundations::{Repr, func, scope, ty};
use crate::layout::{Axis, Side};
/// The four directions into which content can be laid out.
///
/// Possible values are:
/// - `{ltr}`: Left to right.
/// - `{rtl}`: Right to left.
/// - `{ttb}`: Top to bottom.
/// - `{btt}`: Bottom to top.
///
/// These values are available globally and
/// also in the direction type's scope, so you can write either of the following
/// two:
/// ```example
/// #stack(dir: rtl)[A][B][C]
/// #stack(dir: direction.rtl)[A][B][C]
/// ```
#[ty(scope, name = "direction")]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Dir {
/// Left to right.
LTR,
/// Right to left.
RTL,
/// Top to bottom.
TTB,
/// Bottom to top.
BTT,
}
impl Dir {
/// Whether this direction points into the positive coordinate direction.
///
/// The positive directions are left-to-right and top-to-bottom.
pub const fn is_positive(self) -> bool {
match self {
Self::LTR | Self::TTB => true,
Self::RTL | Self::BTT => false,
}
}
}
#[scope]
impl Dir {
pub const LTR: Self = Self::LTR;
pub const RTL: Self = Self::RTL;
pub const TTB: Self = Self::TTB;
pub const BTT: Self = Self::BTT;
/// Returns a direction from a starting point.
///
/// ```example
/// #direction.from(left) \
/// #direction.from(right) \
/// #direction.from(top) \
/// #direction.from(bottom)
/// ```
#[func]
pub const fn from(side: Side) -> Dir {
match side {
Side::Left => Self::LTR,
Side::Right => Self::RTL,
Side::Top => Self::TTB,
Side::Bottom => Self::BTT,
}
}
/// Returns a direction from an end point.
///
/// ```example
/// #direction.to(left) \
/// #direction.to(right) \
/// #direction.to(top) \
/// #direction.to(bottom)
/// ```
#[func]
pub const fn to(side: Side) -> Dir {
match side {
Side::Right => Self::LTR,
Side::Left => Self::RTL,
Side::Bottom => Self::TTB,
Side::Top => Self::BTT,
}
}
/// The axis this direction belongs to, either `{"horizontal"}` or
/// `{"vertical"}`.
///
/// ```example
/// #ltr.axis() \
/// #ttb.axis()
/// ```
#[func]
pub const fn axis(self) -> Axis {
match self {
Self::LTR | Self::RTL => Axis::X,
Self::TTB | Self::BTT => Axis::Y,
}
}
/// The corresponding sign, for use in calculations.
///
/// ```example
/// #ltr.sign() \
/// #rtl.sign() \
/// #ttb.sign() \
/// #btt.sign()
/// ```
#[func]
pub const fn sign(self) -> i64 {
match self {
Self::LTR | Self::TTB => 1,
Self::RTL | Self::BTT => -1,
}
}
/// The start point of this direction, as an alignment.
///
/// ```example
/// #ltr.start() \
/// #rtl.start() \
/// #ttb.start() \
/// #btt.start()
/// ```
#[func]
pub const fn start(self) -> Side {
match self {
Self::LTR => Side::Left,
Self::RTL => Side::Right,
Self::TTB => Side::Top,
Self::BTT => Side::Bottom,
}
}
/// The end point of this direction, as an alignment.
///
/// ```example
/// #ltr.end() \
/// #rtl.end() \
/// #ttb.end() \
/// #btt.end()
/// ```
#[func]
pub const fn end(self) -> Side {
match self {
Self::LTR => Side::Right,
Self::RTL => Side::Left,
Self::TTB => Side::Bottom,
Self::BTT => Side::Top,
}
}
/// The inverse direction.
///
/// ```example
/// #ltr.inv() \
/// #rtl.inv() \
/// #ttb.inv() \
/// #btt.inv()
/// ```
#[func(title = "Inverse")]
pub const fn inv(self) -> Dir {
match self {
Self::LTR => Self::RTL,
Self::RTL => Self::LTR,
Self::TTB => Self::BTT,
Self::BTT => Self::TTB,
}
}
}
impl Repr for Dir {
fn repr(&self) -> EcoString {
match self {
Self::LTR => "ltr".into(),
Self::RTL => "rtl".into(),
Self::TTB => "ttb".into(),
Self::BTT => "btt".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/layout/frame.rs | crates/typst-library/src/layout/frame.rs | //! Finished documents.
use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize;
use std::sync::Arc;
use typst_syntax::Span;
use typst_utils::{LazyHash, Numeric};
use crate::foundations::{Dict, Label, Value, cast, dict};
use crate::introspection::{Location, Tag};
use crate::layout::{Abs, Axes, FixedAlignment, Length, Point, Size, Transform};
use crate::model::Destination;
use crate::text::TextItem;
use crate::visualize::{Color, Curve, FixedStroke, Geometry, Image, Paint, Shape};
/// A finished layout with items at fixed positions.
#[derive(Default, Clone, Hash)]
pub struct Frame {
/// The size of the frame.
size: Size,
/// The baseline of the frame measured from the top. If this is `None`, the
/// frame's implicit baseline is at the bottom.
baseline: Option<Abs>,
/// The items composing this layout.
items: Arc<LazyHash<Vec<(Point, FrameItem)>>>,
/// The hardness of this frame.
///
/// Determines whether it is a boundary for gradient drawing.
kind: FrameKind,
}
/// Constructor, accessors and setters.
impl Frame {
/// Create a new, empty frame.
///
/// Panics the size is not finite.
#[track_caller]
pub fn new(size: Size, kind: FrameKind) -> Self {
assert!(size.is_finite());
Self {
size,
baseline: None,
items: Arc::new(LazyHash::new(vec![])),
kind,
}
}
/// Create a new, empty soft frame.
///
/// Panics if the size is not finite.
#[track_caller]
pub fn soft(size: Size) -> Self {
Self::new(size, FrameKind::Soft)
}
/// Create a new, empty hard frame.
///
/// Panics if the size is not finite.
#[track_caller]
pub fn hard(size: Size) -> Self {
Self::new(size, FrameKind::Hard)
}
/// Sets the frame's hardness.
pub fn set_kind(&mut self, kind: FrameKind) {
self.kind = kind;
}
/// Sets the frame's hardness builder-style.
pub fn with_kind(mut self, kind: FrameKind) -> Self {
self.kind = kind;
self
}
/// Whether the frame is hard or soft.
pub fn kind(&self) -> FrameKind {
self.kind
}
/// Whether the frame contains no items.
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
/// The size of the frame.
pub fn size(&self) -> Size {
self.size
}
/// The size of the frame, mutably.
pub fn size_mut(&mut self) -> &mut Size {
&mut self.size
}
/// Set the size of the frame.
pub fn set_size(&mut self, size: Size) {
self.size = size;
}
/// The width of the frame.
pub fn width(&self) -> Abs {
self.size.x
}
/// The height of the frame.
pub fn height(&self) -> Abs {
self.size.y
}
/// The vertical position of the frame's baseline.
pub fn baseline(&self) -> Abs {
self.baseline.unwrap_or(self.size.y)
}
/// Whether the frame has a non-default baseline.
pub fn has_baseline(&self) -> bool {
self.baseline.is_some()
}
/// Set the frame's baseline from the top.
pub fn set_baseline(&mut self, baseline: Abs) {
self.baseline = Some(baseline);
}
/// The distance from the baseline to the top of the frame.
///
/// This is the same as `baseline()`, but more in line with the terminology
/// used in math layout.
pub fn ascent(&self) -> Abs {
self.baseline()
}
/// The distance from the baseline to the bottom of the frame.
pub fn descent(&self) -> Abs {
self.size.y - self.baseline()
}
/// An iterator over the items inside this frame alongside their positions
/// relative to the top-left of the frame.
pub fn items(&self) -> std::slice::Iter<'_, (Point, FrameItem)> {
self.items.iter()
}
}
/// Insert items and subframes.
impl Frame {
/// The layer the next item will be added on. This corresponds to the number
/// of items in the frame.
pub fn layer(&self) -> usize {
self.items.len()
}
/// Add an item at a position in the foreground.
pub fn push(&mut self, pos: Point, item: FrameItem) {
Arc::make_mut(&mut self.items).push((pos, item));
}
/// Add multiple items at a position in the foreground.
///
/// The first item in the iterator will be the one that is most in the
/// background.
pub fn push_multiple<I>(&mut self, items: I)
where
I: IntoIterator<Item = (Point, FrameItem)>,
{
Arc::make_mut(&mut self.items).extend(items);
}
/// Add a frame at a position in the foreground.
///
/// Automatically decides whether to inline the frame or to include it as a
/// group based on the number of items in it.
pub fn push_frame(&mut self, pos: Point, frame: Frame) {
if self.should_inline(&frame) {
self.inline(self.layer(), pos, frame);
} else {
self.push(pos, FrameItem::Group(GroupItem::new(frame)));
}
}
/// Insert an item at the given layer in the frame.
///
/// This panics if the layer is greater than the number of layers present.
#[track_caller]
pub fn insert(&mut self, layer: usize, pos: Point, item: FrameItem) {
Arc::make_mut(&mut self.items).insert(layer, (pos, item));
}
/// Add an item at a position in the background.
pub fn prepend(&mut self, pos: Point, item: FrameItem) {
self.insert(0, pos, item);
}
/// Add multiple items at a position in the background.
///
/// The first item in the iterator will be the one that is most in the
/// background.
pub fn prepend_multiple<I>(&mut self, items: I)
where
I: IntoIterator<Item = (Point, FrameItem)>,
{
Arc::make_mut(&mut self.items).splice(0..0, items);
}
/// Add a frame at a position in the background.
pub fn prepend_frame(&mut self, pos: Point, frame: Frame) {
if self.should_inline(&frame) {
self.inline(0, pos, frame);
} else {
self.prepend(pos, FrameItem::Group(GroupItem::new(frame)));
}
}
/// Whether the given frame should be inlined.
fn should_inline(&self, frame: &Frame) -> bool {
// We do not inline big frames and hard frames.
frame.kind().is_soft() && (self.items.is_empty() || frame.items.len() <= 5)
}
/// Inline a frame at the given layer.
fn inline(&mut self, layer: usize, pos: Point, frame: Frame) {
// Skip work if there's nothing to do.
if frame.items.is_empty() {
return;
}
// Try to just reuse the items.
if pos.is_zero() && self.items.is_empty() {
self.items = frame.items;
return;
}
// Try to transfer the items without adjusting the position.
// Also try to reuse the items if the Arc isn't shared.
let range = layer..layer;
if pos.is_zero() {
let sink = Arc::make_mut(&mut self.items);
match Arc::try_unwrap(frame.items) {
Ok(items) => {
sink.splice(range, items.into_inner());
}
Err(arc) => {
sink.splice(range, arc.iter().cloned());
}
}
return;
}
// We have to adjust the item positions.
// But still try to reuse the items if the Arc isn't shared.
let sink = Arc::make_mut(&mut self.items);
match Arc::try_unwrap(frame.items) {
Ok(items) => {
sink.splice(
range,
items.into_inner().into_iter().map(|(p, e)| (p + pos, e)),
);
}
Err(arc) => {
sink.splice(range, arc.iter().cloned().map(|(p, e)| (p + pos, e)));
}
}
}
}
/// Modify the frame.
impl Frame {
/// Remove all items from the frame.
pub fn clear(&mut self) {
if Arc::strong_count(&self.items) == 1 {
Arc::make_mut(&mut self.items).clear();
} else {
self.items = Arc::new(LazyHash::new(vec![]));
}
}
/// Adjust the frame's size, translate the original content by an offset
/// computed according to the given alignments, and return the amount of
/// offset.
pub fn resize(&mut self, target: Size, align: Axes<FixedAlignment>) -> Point {
if self.size == target {
return Point::zero();
}
let offset =
align.zip_map(target - self.size, FixedAlignment::position).to_point();
self.size = target;
self.translate(offset);
offset
}
/// Move the baseline and contents of the frame by an offset.
pub fn translate(&mut self, offset: Point) {
if !offset.is_zero() {
if let Some(baseline) = &mut self.baseline {
*baseline += offset.y;
}
for (point, _) in Arc::make_mut(&mut self.items).iter_mut() {
*point += offset;
}
}
}
/// Hide all content in the frame, but keep metadata.
pub fn hide(&mut self) {
Arc::make_mut(&mut self.items).retain_mut(|(_, item)| match item {
FrameItem::Group(group) => {
group.frame.hide();
!group.frame.is_empty()
}
FrameItem::Tag(_) => true,
_ => false,
});
}
/// Add a background fill.
pub fn fill(&mut self, fill: impl Into<Paint>) {
self.prepend(
Point::zero(),
FrameItem::Shape(Geometry::Rect(self.size()).filled(fill), Span::detached()),
);
}
/// Arbitrarily transform the contents of the frame.
pub fn transform(&mut self, transform: Transform) {
if !self.is_empty() {
self.group(|g| g.transform = transform);
}
}
/// Clip the contents of a frame to a clip curve.
///
/// The clip curve can be the size of the frame in the case of a rectangular
/// frame. In the case of a frame with rounded corner, this should be a
/// curve that matches the frame's outline.
pub fn clip(&mut self, clip_curve: Curve) {
if !self.is_empty() {
self.group(|g| g.clip = Some(clip_curve));
}
}
/// Add a label to the frame.
pub fn label(&mut self, label: Label) {
self.group(|g| g.label = Some(label));
}
/// Set a parent for the frame. As a result, all elements in the frame
/// become logically ordered immediately after the given location.
pub fn set_parent(&mut self, parent: FrameParent) {
if !self.is_empty() {
self.group(|g| g.parent = Some(parent));
}
}
/// Wrap the frame's contents in a group and modify that group with `f`.
fn group<F>(&mut self, f: F)
where
F: FnOnce(&mut GroupItem),
{
let mut wrapper = Frame::soft(self.size);
wrapper.baseline = self.baseline;
let mut group = GroupItem::new(std::mem::take(self));
f(&mut group);
wrapper.push(Point::zero(), FrameItem::Group(group));
*self = wrapper;
}
}
/// Tools for debugging.
impl Frame {
/// Add a full size aqua background and a red baseline for debugging.
pub fn mark_box(mut self) -> Self {
self.mark_box_in_place();
self
}
/// Debug in place. Add a full size aqua background and a red baseline for debugging.
pub fn mark_box_in_place(&mut self) {
self.insert(
0,
Point::zero(),
FrameItem::Shape(
Geometry::Rect(self.size).filled(Color::TEAL.with_alpha(0.5)),
Span::detached(),
),
);
self.insert(
1,
Point::with_y(self.baseline()),
FrameItem::Shape(
Geometry::Line(Point::with_x(self.size.x))
.stroked(FixedStroke::from_pair(Color::RED, Abs::pt(1.0))),
Span::detached(),
),
);
}
/// Add a green marker at a position for debugging.
pub fn mark_point(&mut self, pos: Point) {
let radius = Abs::pt(2.0);
self.push(
pos - Point::splat(radius),
FrameItem::Shape(
Geometry::Curve(Curve::ellipse(Size::splat(2.0 * radius)))
.filled(Color::GREEN),
Span::detached(),
),
);
}
/// Add a green marker line at a position for debugging.
pub fn mark_line(&mut self, y: Abs) {
self.push(
Point::with_y(y),
FrameItem::Shape(
Geometry::Line(Point::with_x(self.size.x))
.stroked(FixedStroke::from_pair(Color::GREEN, Abs::pt(1.0))),
Span::detached(),
),
);
}
}
impl Debug for Frame {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Frame ")?;
f.debug_list()
.entries(self.items.iter().map(|(_, item)| item))
.finish()
}
}
/// The hardness of a frame.
///
/// This corresponds to whether or not the frame is considered to be the
/// innermost parent of its contents. This is used to determine the coordinate
/// reference system for gradients.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub enum FrameKind {
/// A container which follows its parent's size.
///
/// Soft frames are the default since they do not impact the layout of
/// a gradient set on one of its children.
#[default]
Soft,
/// A container which uses its own size.
///
/// This is used for pages, blocks, and boxes.
Hard,
}
impl FrameKind {
/// Returns `true` if the frame is soft.
pub fn is_soft(self) -> bool {
matches!(self, Self::Soft)
}
/// Returns `true` if the frame is hard.
pub fn is_hard(self) -> bool {
matches!(self, Self::Hard)
}
}
/// The building block frames are composed of.
#[derive(Clone, Hash)]
pub enum FrameItem {
/// A subframe with optional transformation and clipping.
Group(GroupItem),
/// A run of shaped text.
Text(TextItem),
/// A geometric shape with optional fill and stroke.
Shape(Shape, Span),
/// An image and its size.
Image(Image, Size, Span),
/// An internal or external link to a destination.
Link(Destination, Size),
/// An introspectable element that produced something within this frame.
Tag(Tag),
}
impl Debug for FrameItem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Group(group) => group.fmt(f),
Self::Text(text) => write!(f, "{text:?}"),
Self::Shape(shape, _) => write!(f, "{shape:?}"),
Self::Image(image, _, _) => write!(f, "{image:?}"),
Self::Link(dest, _) => write!(f, "Link({dest:?})"),
Self::Tag(tag) => write!(f, "{tag:?}"),
}
}
}
/// A subframe with optional transformation and clipping.
#[derive(Clone, Hash)]
pub struct GroupItem {
/// The group's frame.
pub frame: Frame,
/// A transformation to apply to the group.
pub transform: Transform,
/// A curve which should be used to clip the group.
pub clip: Option<Curve>,
/// The group's label.
pub label: Option<Label>,
/// The group's logical parent. All elements in this group are logically
/// ordered immediately after the parent's start location. This can be
/// thought of as inserting the elements at the end but still inside of the
/// parent.
pub parent: Option<FrameParent>,
}
impl GroupItem {
/// Create a new group with default settings.
pub fn new(frame: Frame) -> Self {
Self {
frame,
transform: Transform::identity(),
clip: None,
label: None,
parent: None,
}
}
}
impl Debug for GroupItem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Group ")?;
self.frame.fmt(f)
}
}
/// The parent of a [`GroupItem`]. The child will be logically ordered at the
/// end but still inside of the parent.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct FrameParent {
/// The location of the parent element.
pub location: Location,
/// Whether the child has inherited the parent's styles.
pub inherit: Inherit,
}
impl FrameParent {
/// Create a new frame parent.
pub const fn new(location: Location, inherit: Inherit) -> Self {
Self { location, inherit }
}
}
/// Whether the child has inherited the parent's styles.
///
/// # Inherited
///
/// The placed text will inherit the styles from its parent (the place element).
/// So `explanation` will be underlined.
///
/// ```typ
/// #underline[
/// Some text #place(float: true, bottom + right)[explanation].
/// ]
/// ```
///
/// # Not Inherited
///
/// The footnote entry won't inherit the styles from it's parent (the footnote).
/// So `explanation` won't be underlined, unless other styles apply.
///
/// ```typ
/// #underline[
/// Some text #footnote[explanation].
/// ]
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Inherit {
Yes,
No,
}
/// A physical position in a document.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Position {
/// The page, starting at 1.
pub page: NonZeroUsize,
/// The exact coordinates on the page (from the top left, as usual).
pub point: Point,
}
cast! {
Position,
self => Value::Dict(self.into()),
mut dict: Dict => {
let page = dict.take("page")?.cast()?;
let x: Length = dict.take("x")?.cast()?;
let y: Length = dict.take("y")?.cast()?;
dict.finish(&["page", "x", "y"])?;
Self { page, point: Point::new(x.abs, y.abs) }
},
}
impl From<Position> for Dict {
fn from(pos: Position) -> Self {
dict! {
"page" => pos.page,
"x" => pos.point.x,
"y" => pos.point.y,
}
}
}
| 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/layout/length.rs | crates/typst-library/src/layout/length.rs | use std::cmp::Ordering;
use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, Div, Mul, Neg};
use comemo::Tracked;
use ecow::{EcoString, eco_format};
use typst_syntax::Span;
use typst_utils::Numeric;
use crate::diag::{HintedStrResult, SourceResult, bail};
use crate::foundations::{Context, Fold, Repr, Resolve, StyleChain, func, scope, ty};
use crate::layout::{Abs, Em};
/// A size or distance, possibly expressed with contextual units.
///
/// Typst supports the following length units:
///
/// - Points: `{72pt}`
/// - Millimeters: `{254mm}`
/// - Centimeters: `{2.54cm}`
/// - Inches: `{1in}`
/// - Relative to font size: `{2.5em}`
///
/// You can multiply lengths with and divide them by integers and floats.
///
/// # Example
/// ```example
/// #rect(width: 20pt)
/// #rect(width: 2em)
/// #rect(width: 1in)
///
/// #(3em + 5pt).em \
/// #(20pt).em \
/// #(40em + 2pt).abs \
/// #(5em).abs
/// ```
///
/// # Fields
/// - `abs`: A length with just the absolute component of the current length
/// (that is, excluding the `em` component).
/// - `em`: The amount of `em` units in this length, as a [float].
#[ty(scope, cast)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Length {
/// The absolute part.
pub abs: Abs,
/// The font-relative part.
pub em: Em,
}
impl Length {
/// The zero length.
pub const fn zero() -> Self {
Self { abs: Abs::zero(), em: Em::zero() }
}
/// Try to compute the absolute value of the length.
pub fn try_abs(self) -> Option<Self> {
(self.abs.is_zero() || self.em.is_zero())
.then(|| Self { abs: self.abs.abs(), em: self.em.abs() })
}
/// Try to divide two lengths.
pub fn try_div(self, other: Self) -> Option<f64> {
if self.abs.is_zero() && other.abs.is_zero() {
Some(self.em / other.em)
} else if self.em.is_zero() && other.em.is_zero() {
Some(self.abs / other.abs)
} else {
None
}
}
/// Convert to an absolute length at the given font size.
pub fn at(self, font_size: Abs) -> Abs {
self.abs + self.em.at(font_size)
}
/// Fails with an error if the length has a non-zero font-relative part.
fn ensure_that_em_is_zero(&self, span: Span, unit: &str) -> SourceResult<()> {
if self.em == Em::zero() {
return Ok(());
}
bail!(
span,
"cannot convert a length with non-zero em units (`{}`) to {unit}",
self.repr();
hint: "use `length.to-absolute()` to resolve its em component \
(requires context)";
hint: "or use `length.abs.{unit}()` instead to ignore its em component";
)
}
}
#[scope]
impl Length {
/// Converts this length to points.
///
/// Fails with an error if this length has non-zero `em` units (such as
/// `5em + 2pt` instead of just `2pt`). Use the `abs` field (such as in
/// `(5em + 2pt).abs.pt()`) to ignore the `em` component of the length (thus
/// converting only its absolute component).
#[func(name = "pt", title = "Points")]
pub fn to_pt(&self, span: Span) -> SourceResult<f64> {
self.ensure_that_em_is_zero(span, "pt")?;
Ok(self.abs.to_pt())
}
/// Converts this length to millimeters.
///
/// Fails with an error if this length has non-zero `em` units. See the
/// [`pt`]($length.pt) method for more details.
#[func(name = "mm", title = "Millimeters")]
pub fn to_mm(&self, span: Span) -> SourceResult<f64> {
self.ensure_that_em_is_zero(span, "mm")?;
Ok(self.abs.to_mm())
}
/// Converts this length to centimeters.
///
/// Fails with an error if this length has non-zero `em` units. See the
/// [`pt`]($length.pt) method for more details.
#[func(name = "cm", title = "Centimeters")]
pub fn to_cm(&self, span: Span) -> SourceResult<f64> {
self.ensure_that_em_is_zero(span, "cm")?;
Ok(self.abs.to_cm())
}
/// Converts this length to inches.
///
/// Fails with an error if this length has non-zero `em` units. See the
/// [`pt`]($length.pt) method for more details.
#[func(name = "inches")]
pub fn to_inches(&self, span: Span) -> SourceResult<f64> {
self.ensure_that_em_is_zero(span, "inches")?;
Ok(self.abs.to_inches())
}
/// Resolve this length to an absolute length.
///
/// ```example
/// #set text(size: 12pt)
/// #context [
/// #(6pt).to-absolute() \
/// #(6pt + 10em).to-absolute() \
/// #(10em).to-absolute()
/// ]
///
/// #set text(size: 6pt)
/// #context [
/// #(6pt).to-absolute() \
/// #(6pt + 10em).to-absolute() \
/// #(10em).to-absolute()
/// ]
/// ```
#[func]
pub fn to_absolute(&self, context: Tracked<Context>) -> HintedStrResult<Length> {
Ok(self.resolve(context.styles()?).into())
}
}
impl Debug for Length {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match (self.abs.is_zero(), self.em.is_zero()) {
(false, false) => write!(f, "{:?} + {:?}", self.abs, self.em),
(true, false) => self.em.fmt(f),
(_, true) => self.abs.fmt(f),
}
}
}
impl Repr for Length {
fn repr(&self) -> EcoString {
match (self.abs.is_zero(), self.em.is_zero()) {
(false, false) => eco_format!("{} + {}", self.abs.repr(), self.em.repr()),
(true, false) => self.em.repr(),
(_, true) => self.abs.repr(),
}
}
}
impl Numeric for Length {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.abs.is_finite() && self.em.is_finite()
}
}
impl PartialOrd for Length {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.em.is_zero() && other.em.is_zero() {
self.abs.partial_cmp(&other.abs)
} else if self.abs.is_zero() && other.abs.is_zero() {
self.em.partial_cmp(&other.em)
} else {
None
}
}
}
impl From<Abs> for Length {
fn from(abs: Abs) -> Self {
Self { abs, em: Em::zero() }
}
}
impl From<Em> for Length {
fn from(em: Em) -> Self {
Self { abs: Abs::zero(), em }
}
}
impl Neg for Length {
type Output = Self;
fn neg(self) -> Self::Output {
Self { abs: -self.abs, em: -self.em }
}
}
impl Add for Length {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self { abs: self.abs + rhs.abs, em: self.em + rhs.em }
}
}
typst_utils::sub_impl!(Length - Length -> Length);
impl Mul<f64> for Length {
type Output = Self;
fn mul(self, rhs: f64) -> Self::Output {
Self { abs: self.abs * rhs, em: self.em * rhs }
}
}
impl Mul<Length> for f64 {
type Output = Length;
fn mul(self, rhs: Length) -> Self::Output {
rhs * self
}
}
impl Div<f64> for Length {
type Output = Self;
fn div(self, rhs: f64) -> Self::Output {
Self { abs: self.abs / rhs, em: self.em / rhs }
}
}
typst_utils::assign_impl!(Length += Length);
typst_utils::assign_impl!(Length -= Length);
typst_utils::assign_impl!(Length *= f64);
typst_utils::assign_impl!(Length /= f64);
impl Resolve for Length {
type Output = Abs;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.abs + self.em.resolve(styles)
}
}
impl Fold for Length {
fn fold(self, _: Self) -> Self {
self
}
}
| 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/layout/measure.rs | crates/typst-library/src/layout/measure.rs | use comemo::Tracked;
use typst_syntax::Span;
use crate::diag::{At, SourceResult};
use crate::engine::Engine;
use crate::foundations::{
Content, Context, Dict, Resolve, Smart, Target, TargetElem, dict, func,
};
use crate::introspection::{Locator, LocatorLink};
use crate::layout::{Abs, Axes, Length, Region, Size};
/// Measures the layouted size of content.
///
/// The `measure` function lets you determine the layouted size of content.
/// By default an infinite space is assumed, so the measured dimensions may
/// not necessarily match the final dimensions of the content.
/// If you want to measure in the current layout dimensions, you can combine
/// `measure` and [`layout`].
///
/// # Example
/// The same content can have a different size depending on the [context] that
/// it is placed into. In the example below, the `[#content]` is of course
/// bigger when we increase the font size.
///
/// ```example
/// #let content = [Hello!]
/// #content
/// #set text(14pt)
/// #content
/// ```
///
/// For this reason, you can only measure when context is available.
///
/// ```example
/// #let thing(body) = context {
/// let size = measure(body)
/// [Width of "#body" is #size.width]
/// }
///
/// #thing[Hey] \
/// #thing[Welcome]
/// ```
///
/// The measure function returns a dictionary with the entries `width` and
/// `height`, both of type [`length`].
#[func(contextual)]
pub fn measure(
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
/// The width available to layout the content.
///
/// Setting this to `{auto}` indicates infinite available width.
///
/// Note that using the `width` and `height` parameters of this function is
/// different from measuring a sized [`block`] containing the content. In
/// the following example, the former will get the dimensions of the inner
/// content instead of the dimensions of the block.
///
/// ```example
/// #context measure(lorem(100), width: 400pt)
///
/// #context measure(block(lorem(100), width: 400pt))
/// ```
#[named]
#[default(Smart::Auto)]
width: Smart<Length>,
/// The height available to layout the content.
///
/// Setting this to `{auto}` indicates infinite available height.
#[named]
#[default(Smart::Auto)]
height: Smart<Length>,
/// The content whose size to measure.
content: Content,
) -> SourceResult<Dict> {
// Create a pod region with the available space.
let styles = context.styles().at(span)?;
let pod = Region::new(
Axes::new(
width.resolve(styles).unwrap_or(Abs::inf()),
height.resolve(styles).unwrap_or(Abs::inf()),
),
Axes::splat(false),
);
// We put the locator into a special "measurement mode" to ensure that
// introspection-driven features within the content continue to work. Read
// the "Dealing with measurement" section of the [`Locator`] docs for more
// details.
let here = context.location().at(span)?;
let link = LocatorLink::measure(here, span);
let locator = Locator::link(&link);
let style = TargetElem::target.set(Target::Paged).wrap();
let frame = (engine.routines.layout_frame)(
engine,
&content,
locator,
styles.chain(&style),
pod,
)?;
let Size { x, y } = frame.size();
Ok(dict! { "width" => x, "height" => y })
}
| 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/layout/point.rs | crates/typst-library/src/layout/point.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, Div, Mul, Neg};
use typst_utils::{Get, Numeric};
use crate::layout::{Abs, Axis, Size, Transform};
/// A point in 2D.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Point {
/// The x coordinate.
pub x: Abs,
/// The y coordinate.
pub y: Abs,
}
impl Point {
/// The origin point.
pub const fn zero() -> Self {
Self { x: Abs::zero(), y: Abs::zero() }
}
/// Create a new point from x and y coordinates.
pub const fn new(x: Abs, y: Abs) -> Self {
Self { x, y }
}
/// Create an instance with two equal components.
pub const fn splat(value: Abs) -> Self {
Self { x: value, y: value }
}
/// Create a new point with y set to zero.
pub const fn with_x(x: Abs) -> Self {
Self { x, y: Abs::zero() }
}
/// Create a new point with x set to zero.
pub const fn with_y(y: Abs) -> Self {
Self { x: Abs::zero(), y }
}
/// The component-wise minimum of this and another point.
pub fn min(self, other: Self) -> Self {
Self { x: self.x.min(other.x), y: self.y.min(other.y) }
}
/// The component-wise minimum of this and another point.
pub fn max(self, other: Self) -> Self {
Self { x: self.x.max(other.x), y: self.y.max(other.y) }
}
/// Maps the point with the given function.
pub fn map(self, f: impl Fn(Abs) -> Abs) -> Self {
Self { x: f(self.x), y: f(self.y) }
}
/// The distance between this point and the origin.
pub fn hypot(self) -> Abs {
Abs::raw(self.x.to_raw().hypot(self.y.to_raw()))
}
// TODO: this is a bit awkward on a point struct.
pub fn normalized(self) -> Self {
self / self.hypot().to_raw()
}
/// Rotate the point 90 degrees counter-clockwise.
pub fn rot90ccw(self) -> Self {
Self { x: self.y, y: -self.x }
}
/// Transform the point with the given transformation.
///
/// In the event that one of the coordinates is infinite, the result will
/// be zero.
pub fn transform(self, ts: Transform) -> Self {
Self::new(
ts.sx.of(self.x) + ts.kx.of(self.y) + ts.tx,
ts.ky.of(self.x) + ts.sy.of(self.y) + ts.ty,
)
}
/// Transforms the point with the given transformation, without accounting
/// for infinite values.
pub fn transform_inf(self, ts: Transform) -> Self {
Self::new(
ts.sx.get() * self.x + ts.kx.get() * self.y + ts.tx,
ts.ky.get() * self.x + ts.sy.get() * self.y + ts.ty,
)
}
/// Convert to a size.
pub fn to_size(self) -> Size {
Size::new(self.x, self.y)
}
}
impl Numeric for Point {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
}
impl Get<Axis> for Point {
type Component = Abs;
fn get_ref(&self, axis: Axis) -> &Abs {
match axis {
Axis::X => &self.x,
Axis::Y => &self.y,
}
}
fn get_mut(&mut self, axis: Axis) -> &mut Abs {
match axis {
Axis::X => &mut self.x,
Axis::Y => &mut self.y,
}
}
}
impl Debug for Point {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Point({:?}, {:?})", self.x, self.y)
}
}
impl Neg for Point {
type Output = Self;
fn neg(self) -> Self {
Self { x: -self.x, y: -self.y }
}
}
impl Add for Point {
type Output = Self;
fn add(self, other: Self) -> Self {
Self { x: self.x + other.x, y: self.y + other.y }
}
}
typst_utils::sub_impl!(Point - Point -> Point);
impl Mul<f64> for Point {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self { x: self.x * other, y: self.y * other }
}
}
impl Mul<Point> for f64 {
type Output = Point;
fn mul(self, other: Point) -> Point {
other * self
}
}
impl Div<f64> for Point {
type Output = Self;
fn div(self, other: f64) -> Self {
Self { x: self.x / other, y: self.y / other }
}
}
typst_utils::assign_impl!(Point += Point);
typst_utils::assign_impl!(Point -= Point);
typst_utils::assign_impl!(Point *= f64);
typst_utils::assign_impl!(Point /= f64);
| 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/layout/rel.rs | crates/typst-library/src/layout/rel.rs | use std::cmp::Ordering;
use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use ecow::{EcoString, eco_format};
use typst_utils::Numeric;
use crate::foundations::{Fold, Repr, Resolve, StyleChain, cast, ty};
use crate::layout::{Abs, Em, Length, Ratio};
/// A length in relation to some known length.
///
/// This type is a combination of a [length] with a [ratio]. It results from
/// addition and subtraction of a length and a ratio. Wherever a relative length
/// is expected, you can also use a bare length or ratio.
///
/// # Relative to the page
/// A common use case is setting the width or height of a layout element (e.g.,
/// [block], [rect], etc.) as a certain percentage of the width of the page.
/// Here, the rectangle's width is set to `{25%}`, so it takes up one fourth of
/// the page's _inner_ width (the width minus margins).
///
/// ```example
/// #rect(width: 25%)
/// ```
///
/// Bare lengths or ratios are always valid where relative lengths are expected,
/// but the two can also be freely mixed:
/// ```example
/// #rect(width: 25% + 1cm)
/// ```
///
/// If you're trying to size an element so that it takes up the page's _full_
/// width, you have a few options (this highly depends on your exact use case):
///
/// 1. Set page margins to `{0pt}` (`[#set page(margin: 0pt)]`)
/// 2. Multiply the ratio by the known full page width (`{21cm * 69%}`)
/// 3. Use padding which will negate the margins (`[#pad(x: -2.5cm, ...)]`)
/// 4. Use the page [background](page.background) or
/// [foreground](page.foreground) field as those don't take margins into
/// account (note that it will render the content outside of the document
/// flow, see [place] to control the content position)
///
/// # Relative to a container
/// When a layout element (e.g. a [rect]) is nested in another layout container
/// (e.g. a [block]) instead of being a direct descendant of the page, relative
/// widths become relative to the container:
///
/// ```example
/// #block(
/// width: 100pt,
/// fill: aqua,
/// rect(width: 50%),
/// )
/// ```
///
/// # Scripting
/// You can multiply relative lengths by [ratios]($ratio), [integers]($int), and
/// [floats]($float).
///
/// A relative length has the following fields:
/// - `length`: Its [length] component.
/// - `ratio`: Its [ratio] component.
///
/// ```example
/// #(100% - 50pt).length \
/// #(100% - 50pt).ratio
/// ```
#[ty(cast, name = "relative", title = "Relative Length")]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Rel<T: Numeric = Length> {
/// The relative part.
pub rel: Ratio,
/// The absolute part.
pub abs: T,
}
impl<T: Numeric> Rel<T> {
/// The zero relative.
pub fn zero() -> Self {
Self { rel: Ratio::zero(), abs: T::zero() }
}
/// A relative with a ratio of `100%` and no absolute part.
pub fn one() -> Self {
Self { rel: Ratio::one(), abs: T::zero() }
}
/// Create a new relative from its parts.
pub const fn new(rel: Ratio, abs: T) -> Self {
Self { rel, abs }
}
/// Whether both parts are zero.
pub fn is_zero(self) -> bool {
self.rel.is_zero() && self.abs == T::zero()
}
/// Whether the relative part is one and the absolute part is zero.
pub fn is_one(self) -> bool {
self.rel.is_one() && self.abs == T::zero()
}
/// Evaluate this relative to the given `whole`.
pub fn relative_to(self, whole: T) -> T {
self.rel.of(whole) + self.abs
}
/// Map the absolute part with `f`.
pub fn map<F, U>(self, f: F) -> Rel<U>
where
F: FnOnce(T) -> U,
U: Numeric,
{
Rel { rel: self.rel, abs: f(self.abs) }
}
}
impl Rel<Length> {
/// Try to divide two relative lengths.
pub fn try_div(self, other: Self) -> Option<f64> {
if self.rel.is_zero() && other.rel.is_zero() {
self.abs.try_div(other.abs)
} else if self.abs.is_zero() && other.abs.is_zero() {
Some(self.rel / other.rel)
} else {
None
}
}
}
impl<T: Numeric + Debug> Debug for Rel<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match (self.rel.is_zero(), self.abs.is_zero()) {
(false, false) => write!(f, "{:?} + {:?}", self.rel, self.abs),
(false, true) => self.rel.fmt(f),
(true, _) => self.abs.fmt(f),
}
}
}
impl<T: Numeric + Repr> Repr for Rel<T> {
fn repr(&self) -> EcoString {
eco_format!("{} + {}", self.rel.repr(), self.abs.repr())
}
}
impl From<Abs> for Rel<Length> {
fn from(abs: Abs) -> Self {
Rel::from(Length::from(abs))
}
}
impl From<Em> for Rel<Length> {
fn from(em: Em) -> Self {
Rel::from(Length::from(em))
}
}
impl<T: Numeric> From<T> for Rel<T> {
fn from(abs: T) -> Self {
Self { rel: Ratio::zero(), abs }
}
}
impl<T: Numeric> From<Ratio> for Rel<T> {
fn from(rel: Ratio) -> Self {
Self { rel, abs: T::zero() }
}
}
impl<T: Numeric + PartialOrd> PartialOrd for Rel<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.rel.is_zero() && other.rel.is_zero() {
self.abs.partial_cmp(&other.abs)
} else if self.abs.is_zero() && other.abs.is_zero() {
self.rel.partial_cmp(&other.rel)
} else {
None
}
}
}
impl<T: Numeric> Neg for Rel<T> {
type Output = Self;
fn neg(self) -> Self {
Self { rel: -self.rel, abs: -self.abs }
}
}
impl<T: Numeric> Add for Rel<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
rel: self.rel + other.rel,
abs: self.abs + other.abs,
}
}
}
impl<T: Numeric> Sub for Rel<T> {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
self + -other
}
}
impl<T: Numeric> Mul<f64> for Rel<T> {
type Output = Self;
fn mul(self, other: f64) -> Self::Output {
Self { rel: self.rel * other, abs: self.abs * other }
}
}
impl<T: Numeric> Mul<Rel<T>> for f64 {
type Output = Rel<T>;
fn mul(self, other: Rel<T>) -> Self::Output {
other * self
}
}
impl<T: Numeric> Div<f64> for Rel<T> {
type Output = Self;
fn div(self, other: f64) -> Self::Output {
Self { rel: self.rel / other, abs: self.abs / other }
}
}
impl<T: Numeric + AddAssign> AddAssign for Rel<T> {
fn add_assign(&mut self, other: Self) {
self.rel += other.rel;
self.abs += other.abs;
}
}
impl<T: Numeric + SubAssign> SubAssign for Rel<T> {
fn sub_assign(&mut self, other: Self) {
self.rel -= other.rel;
self.abs -= other.abs;
}
}
impl<T: Numeric + MulAssign<f64>> MulAssign<f64> for Rel<T> {
fn mul_assign(&mut self, other: f64) {
self.rel *= other;
self.abs *= other;
}
}
impl<T: Numeric + DivAssign<f64>> DivAssign<f64> for Rel<T> {
fn div_assign(&mut self, other: f64) {
self.rel /= other;
self.abs /= other;
}
}
impl<T: Numeric> Add<T> for Ratio {
type Output = Rel<T>;
fn add(self, other: T) -> Self::Output {
Rel::from(self) + Rel::from(other)
}
}
impl<T: Numeric> Add<T> for Rel<T> {
type Output = Self;
fn add(self, other: T) -> Self::Output {
self + Rel::from(other)
}
}
impl<T: Numeric> Add<Ratio> for Rel<T> {
type Output = Self;
fn add(self, other: Ratio) -> Self::Output {
self + Rel::from(other)
}
}
impl<T> Resolve for Rel<T>
where
T: Resolve + Numeric,
<T as Resolve>::Output: Numeric,
{
type Output = Rel<<T as Resolve>::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|abs| abs.resolve(styles))
}
}
impl<T> Fold for Rel<T>
where
T: Numeric + Fold,
{
fn fold(self, outer: Self) -> Self {
Self { rel: self.rel, abs: self.abs.fold(outer.abs) }
}
}
cast! {
Rel<Abs>,
self => self.map(Length::from).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/layout/sides.rs | crates/typst-library/src/layout/sides.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::Add;
use typst_utils::Get;
use crate::diag::{HintedStrResult, bail};
use crate::foundations::{
AlternativeFold, CastInfo, Dict, Fold, FromValue, IntoValue, Reflect, Resolve,
StyleChain, Value, cast,
};
use crate::layout::{Abs, Alignment, Axes, Axis, Corner, Corners, Rel, Size};
/// A container with left, top, right and bottom components.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Sides<T> {
/// The value for the left side.
pub left: T,
/// The value for the top side.
pub top: T,
/// The value for the right side.
pub right: T,
/// The value for the bottom side.
pub bottom: T,
}
impl<T> Sides<T> {
/// Create a new instance from the four components.
pub const fn new(left: T, top: T, right: T, bottom: T) -> Self {
Self { left, top, right, bottom }
}
/// Create an instance with four equal components.
pub fn splat(value: T) -> Self
where
T: Clone,
{
Self {
left: value.clone(),
top: value.clone(),
right: value.clone(),
bottom: value,
}
}
/// Map the individual fields with `f`.
pub fn map<F, U>(self, mut f: F) -> Sides<U>
where
F: FnMut(T) -> U,
{
Sides {
left: f(self.left),
top: f(self.top),
right: f(self.right),
bottom: f(self.bottom),
}
}
/// Convert from `&Sides<T>` to `Sides<&T>`.
pub fn as_ref(&self) -> Sides<&T> {
Sides {
left: &self.left,
top: &self.top,
right: &self.right,
bottom: &self.bottom,
}
}
/// Zip two instances into one.
pub fn zip<U>(self, other: Sides<U>) -> Sides<(T, U)> {
Sides {
left: (self.left, other.left),
top: (self.top, other.top),
right: (self.right, other.right),
bottom: (self.bottom, other.bottom),
}
}
/// An iterator over the sides, starting with the left side, clockwise.
pub fn iter(&self) -> impl Iterator<Item = &T> {
[&self.left, &self.top, &self.right, &self.bottom].into_iter()
}
/// Map two adjacent sides into a corner `f`.
pub fn map_corners<F, U>(self, mut f: F) -> Corners<U>
where
F: FnMut(T, T) -> U,
T: Copy,
{
Corners {
top_left: f(self.left, self.top),
top_right: f(self.top, self.right),
bottom_right: f(self.right, self.bottom),
bottom_left: f(self.bottom, self.left),
}
}
/// Whether all sides are equal.
pub fn is_uniform(&self) -> bool
where
T: PartialEq,
{
self.left == self.top && self.top == self.right && self.right == self.bottom
}
}
impl<T: Add> Sides<T> {
/// Sums up `left` and `right` into `x`, and `top` and `bottom` into `y`.
pub fn sum_by_axis(self) -> Axes<T::Output> {
Axes::new(self.left + self.right, self.top + self.bottom)
}
}
impl<T> Sides<Option<T>> {
/// Unwrap-or the individual sides.
pub fn unwrap_or(self, default: T) -> Sides<T>
where
T: Clone,
{
self.map(|v| v.unwrap_or(default.clone()))
}
/// Unwrap-or-default the individual sides.
pub fn unwrap_or_default(self) -> Sides<T>
where
T: Default,
{
self.map(Option::unwrap_or_default)
}
}
impl Sides<Rel<Abs>> {
/// Evaluate the sides relative to the given `size`.
pub fn relative_to(&self, size: Size) -> Sides<Abs> {
Sides {
left: self.left.relative_to(size.x),
top: self.top.relative_to(size.y),
right: self.right.relative_to(size.x),
bottom: self.bottom.relative_to(size.y),
}
}
/// Whether all sides are zero.
pub fn is_zero(&self) -> bool {
self.left.is_zero()
&& self.top.is_zero()
&& self.right.is_zero()
&& self.bottom.is_zero()
}
}
impl<T> Get<Side> for Sides<T> {
type Component = T;
fn get_ref(&self, side: Side) -> &T {
match side {
Side::Left => &self.left,
Side::Top => &self.top,
Side::Right => &self.right,
Side::Bottom => &self.bottom,
}
}
fn get_mut(&mut self, side: Side) -> &mut T {
match side {
Side::Left => &mut self.left,
Side::Top => &mut self.top,
Side::Right => &mut self.right,
Side::Bottom => &mut self.bottom,
}
}
}
impl<T: Debug + PartialEq> Debug for Sides<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.is_uniform() {
f.write_str("Sides::splat(")?;
self.left.fmt(f)?;
f.write_str(")")
} else {
f.debug_struct("Sides")
.field("left", &self.left)
.field("top", &self.top)
.field("right", &self.right)
.field("bottom", &self.bottom)
.finish()
}
}
}
impl<T: Reflect> Reflect for Sides<Option<T>> {
fn input() -> CastInfo {
T::input() + Dict::input()
}
fn output() -> CastInfo {
T::output() + Dict::output()
}
fn castable(value: &Value) -> bool {
Dict::castable(value) || T::castable(value)
}
}
impl<T> IntoValue for Sides<Option<T>>
where
T: PartialEq + IntoValue,
{
fn into_value(self) -> Value {
if self.is_uniform()
&& let Some(left) = self.left
{
return left.into_value();
}
let mut dict = Dict::new();
let mut handle = |key: &str, component: Option<T>| {
if let Some(c) = component {
dict.insert(key.into(), c.into_value());
}
};
handle("left", self.left);
handle("top", self.top);
handle("right", self.right);
handle("bottom", self.bottom);
Value::Dict(dict)
}
}
impl<T> FromValue for Sides<Option<T>>
where
T: Default + FromValue + Clone,
{
fn from_value(mut value: Value) -> HintedStrResult<Self> {
let expected_keys = ["left", "top", "right", "bottom", "x", "y", "rest"];
if let Value::Dict(dict) = &mut value {
if dict.is_empty() {
return Ok(Self::splat(None));
} else if dict.iter().any(|(key, _)| expected_keys.contains(&key.as_str())) {
let mut take = |key| dict.take(key).ok().map(T::from_value).transpose();
let rest = take("rest")?;
let x = take("x")?.or_else(|| rest.clone());
let y = take("y")?.or_else(|| rest.clone());
let sides = Sides {
left: take("left")?.or_else(|| x.clone()),
top: take("top")?.or_else(|| y.clone()),
right: take("right")?.or_else(|| x.clone()),
bottom: take("bottom")?.or_else(|| y.clone()),
};
dict.finish(&expected_keys)?;
return Ok(sides);
}
}
if T::castable(&value) {
Ok(Self::splat(Some(T::from_value(value)?)))
} else if let Value::Dict(dict) = &value {
let keys = dict.iter().map(|kv| kv.0.as_str()).collect();
// Do not hint at expected_keys, because T may be castable from Dict
// objects with other sets of expected keys.
Err(Dict::unexpected_keys(keys, None).into())
} else {
Err(Self::error(&value))
}
}
}
impl<T: Resolve> Resolve for Sides<T> {
type Output = Sides<T::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|v| v.resolve(styles))
}
}
impl<T: Fold> Fold for Sides<Option<T>> {
fn fold(self, outer: Self) -> Self {
// Usually, folding an inner `None` with an `outer` prefers the
// explicit `None`. However, here `None` means unspecified and thus
// we want `outer`, so we use `fold_or` to opt into such behavior.
self.zip(outer).map(|(inner, outer)| inner.fold_or(outer))
}
}
/// The four sides of objects.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Side {
/// The left side.
Left,
/// The top side.
Top,
/// The right side.
Right,
/// The bottom side.
Bottom,
}
impl Side {
/// The opposite side.
pub fn inv(self) -> Self {
match self {
Self::Left => Self::Right,
Self::Top => Self::Bottom,
Self::Right => Self::Left,
Self::Bottom => Self::Top,
}
}
/// The next side, clockwise.
pub fn next_cw(self) -> Self {
match self {
Self::Left => Self::Top,
Self::Top => Self::Right,
Self::Right => Self::Bottom,
Self::Bottom => Self::Left,
}
}
/// The next side, counter-clockwise.
pub fn next_ccw(self) -> Self {
match self {
Self::Left => Self::Bottom,
Self::Top => Self::Left,
Self::Right => Self::Top,
Self::Bottom => Self::Right,
}
}
/// The first corner of the side in clockwise order.
pub fn start_corner(self) -> Corner {
match self {
Self::Left => Corner::BottomLeft,
Self::Top => Corner::TopLeft,
Self::Right => Corner::TopRight,
Self::Bottom => Corner::BottomRight,
}
}
/// The second corner of the side in clockwise order.
pub fn end_corner(self) -> Corner {
self.next_cw().start_corner()
}
/// Return the corresponding axis.
pub fn axis(self) -> Axis {
match self {
Self::Left | Self::Right => Axis::Y,
Self::Top | Self::Bottom => Axis::X,
}
}
}
cast! {
Side,
self => Alignment::from(self).into_value(),
align: Alignment => match align {
Alignment::LEFT => Self::Left,
Alignment::RIGHT => Self::Right,
Alignment::TOP => Self::Top,
Alignment::BOTTOM => Self::Bottom,
_ => bail!("cannot convert this alignment to a side"),
},
}
| 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/layout/corners.rs | crates/typst-library/src/layout/corners.rs | use std::fmt::{self, Debug, Formatter};
use typst_utils::Get;
use crate::diag::HintedStrResult;
use crate::foundations::{
AlternativeFold, CastInfo, Dict, Fold, FromValue, IntoValue, Reflect, Resolve,
StyleChain, Value,
};
use crate::layout::Side;
/// A container with components for the four corners of a rectangle.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Corners<T> {
/// The value for the top left corner.
pub top_left: T,
/// The value for the top right corner.
pub top_right: T,
/// The value for the bottom right corner.
pub bottom_right: T,
/// The value for the bottom left corner.
pub bottom_left: T,
}
impl<T> Corners<T> {
/// Create a new instance from the four components.
pub const fn new(top_left: T, top_right: T, bottom_right: T, bottom_left: T) -> Self {
Self { top_left, top_right, bottom_right, bottom_left }
}
/// Create an instance with four equal components.
pub fn splat(value: T) -> Self
where
T: Clone,
{
Self {
top_left: value.clone(),
top_right: value.clone(),
bottom_right: value.clone(),
bottom_left: value,
}
}
/// Map the individual fields with `f`.
pub fn map<F, U>(self, mut f: F) -> Corners<U>
where
F: FnMut(T) -> U,
{
Corners {
top_left: f(self.top_left),
top_right: f(self.top_right),
bottom_right: f(self.bottom_right),
bottom_left: f(self.bottom_left),
}
}
/// Zip two instances into one.
pub fn zip<U>(self, other: Corners<U>) -> Corners<(T, U)> {
Corners {
top_left: (self.top_left, other.top_left),
top_right: (self.top_right, other.top_right),
bottom_right: (self.bottom_right, other.bottom_right),
bottom_left: (self.bottom_left, other.bottom_left),
}
}
/// An iterator over the corners, starting with the top left corner,
/// clockwise.
pub fn iter(&self) -> impl Iterator<Item = &T> {
[&self.top_left, &self.top_right, &self.bottom_right, &self.bottom_left]
.into_iter()
}
/// Whether all sides are equal.
pub fn is_uniform(&self) -> bool
where
T: PartialEq,
{
self.top_left == self.top_right
&& self.top_right == self.bottom_right
&& self.bottom_right == self.bottom_left
}
}
impl<T> Corners<Option<T>> {
/// Unwrap-or-default the individual corners.
pub fn unwrap_or_default(self) -> Corners<T>
where
T: Default,
{
self.map(Option::unwrap_or_default)
}
}
impl<T> Get<Corner> for Corners<T> {
type Component = T;
fn get_ref(&self, corner: Corner) -> &T {
match corner {
Corner::TopLeft => &self.top_left,
Corner::TopRight => &self.top_right,
Corner::BottomRight => &self.bottom_right,
Corner::BottomLeft => &self.bottom_left,
}
}
fn get_mut(&mut self, corner: Corner) -> &mut T {
match corner {
Corner::TopLeft => &mut self.top_left,
Corner::TopRight => &mut self.top_right,
Corner::BottomRight => &mut self.bottom_right,
Corner::BottomLeft => &mut self.bottom_left,
}
}
}
impl<T: Debug + PartialEq> Debug for Corners<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.is_uniform() {
f.write_str("Corners::splat(")?;
self.top_left.fmt(f)?;
f.write_str(")")
} else {
f.debug_struct("Corners")
.field("top_left", &self.top_left)
.field("top_right", &self.top_right)
.field("bottom_right", &self.bottom_right)
.field("bottom_left", &self.bottom_left)
.finish()
}
}
}
impl<T: Reflect> Reflect for Corners<Option<T>> {
fn input() -> CastInfo {
T::input() + Dict::input()
}
fn output() -> CastInfo {
T::output() + Dict::output()
}
fn castable(value: &Value) -> bool {
Dict::castable(value) || T::castable(value)
}
}
impl<T> IntoValue for Corners<Option<T>>
where
T: PartialEq + IntoValue,
{
fn into_value(self) -> Value {
if self.is_uniform()
&& let Some(top_left) = self.top_left
{
return top_left.into_value();
}
let mut dict = Dict::new();
let mut handle = |key: &str, component: Option<T>| {
if let Some(c) = component {
dict.insert(key.into(), c.into_value());
}
};
handle("top-left", self.top_left);
handle("top-right", self.top_right);
handle("bottom-right", self.bottom_right);
handle("bottom-left", self.bottom_left);
Value::Dict(dict)
}
}
impl<T> FromValue for Corners<Option<T>>
where
T: FromValue + Clone,
{
fn from_value(mut value: Value) -> HintedStrResult<Self> {
let expected_keys = [
"top-left",
"top-right",
"bottom-right",
"bottom-left",
"left",
"top",
"right",
"bottom",
"rest",
];
if let Value::Dict(dict) = &mut value {
if dict.is_empty() {
return Ok(Self::splat(None));
} else if dict.iter().any(|(key, _)| expected_keys.contains(&key.as_str())) {
let mut take = |key| dict.take(key).ok().map(T::from_value).transpose();
let rest = take("rest")?;
let left = take("left")?.or_else(|| rest.clone());
let top = take("top")?.or_else(|| rest.clone());
let right = take("right")?.or_else(|| rest.clone());
let bottom = take("bottom")?.or_else(|| rest.clone());
let corners = Corners {
top_left: take("top-left")?
.or_else(|| top.clone())
.or_else(|| left.clone()),
top_right: take("top-right")?
.or_else(|| top.clone())
.or_else(|| right.clone()),
bottom_right: take("bottom-right")?
.or_else(|| bottom.clone())
.or_else(|| right.clone()),
bottom_left: take("bottom-left")?
.or_else(|| bottom.clone())
.or_else(|| left.clone()),
};
dict.finish(&expected_keys)?;
return Ok(corners);
}
}
if T::castable(&value) {
Ok(Self::splat(Some(T::from_value(value)?)))
} else if let Value::Dict(dict) = &value {
let keys = dict.iter().map(|kv| kv.0.as_str()).collect();
// Do not hint at expected_keys, because T may be castable from Dict
// objects with other sets of expected keys.
Err(Dict::unexpected_keys(keys, None).into())
} else {
Err(Self::error(&value))
}
}
}
impl<T: Resolve> Resolve for Corners<T> {
type Output = Corners<T::Output>;
fn resolve(self, styles: StyleChain) -> Self::Output {
self.map(|v| v.resolve(styles))
}
}
impl<T: Fold> Fold for Corners<Option<T>> {
fn fold(self, outer: Self) -> Self {
// Usually, folding an inner `None` with an `outer` prefers the
// explicit `None`. However, here `None` means unspecified and thus
// we want `outer`, so we use `fold_or` to opt into such behavior.
self.zip(outer).map(|(inner, outer)| inner.fold_or(outer))
}
}
/// The four corners of a rectangle.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Corner {
/// The top left corner.
TopLeft,
/// The top right corner.
TopRight,
/// The bottom right corner.
BottomRight,
/// The bottom left corner.
BottomLeft,
}
impl Corner {
/// The opposite corner.
pub fn inv(self) -> Self {
match self {
Self::TopLeft => Self::BottomRight,
Self::TopRight => Self::BottomLeft,
Self::BottomRight => Self::TopLeft,
Self::BottomLeft => Self::TopRight,
}
}
/// The next corner, clockwise.
pub fn next_cw(self) -> Self {
match self {
Self::TopLeft => Self::TopRight,
Self::TopRight => Self::BottomRight,
Self::BottomRight => Self::BottomLeft,
Self::BottomLeft => Self::TopLeft,
}
}
/// The next corner, counter-clockwise.
pub fn next_ccw(self) -> Self {
match self {
Self::TopLeft => Self::BottomLeft,
Self::TopRight => Self::TopLeft,
Self::BottomRight => Self::TopRight,
Self::BottomLeft => Self::BottomRight,
}
}
/// The next side, clockwise.
pub fn side_cw(self) -> Side {
match self {
Self::TopLeft => Side::Top,
Self::TopRight => Side::Right,
Self::BottomRight => Side::Bottom,
Self::BottomLeft => Side::Left,
}
}
/// The next side, counter-clockwise.
pub fn side_ccw(self) -> Side {
match self {
Self::TopLeft => Side::Left,
Self::TopRight => Side::Top,
Self::BottomRight => Side::Right,
Self::BottomLeft => Side::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/layout/size.rs | crates/typst-library/src/layout/size.rs | use std::ops::{Add, Div, Mul, Neg};
use typst_utils::Numeric;
use crate::layout::{Abs, Axes, Point, Ratio};
/// A size in 2D.
pub type Size = Axes<Abs>;
impl Size {
/// The zero value.
pub const fn zero() -> Self {
Self { x: Abs::zero(), y: Abs::zero() }
}
/// Whether the other size fits into this one (smaller width and height).
pub fn fits(self, other: Self) -> bool {
self.x.fits(other.x) && self.y.fits(other.y)
}
/// Convert to a point.
pub fn to_point(self) -> Point {
Point::new(self.x, self.y)
}
/// Converts to a ratio of width to height.
pub fn aspect_ratio(self) -> Ratio {
Ratio::new(self.x / self.y)
}
}
impl Numeric for Size {
fn zero() -> Self {
Self::zero()
}
fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
}
impl Neg for Size {
type Output = Self;
fn neg(self) -> Self {
Self { x: -self.x, y: -self.y }
}
}
impl Add for Size {
type Output = Self;
fn add(self, other: Self) -> Self {
Self { x: self.x + other.x, y: self.y + other.y }
}
}
typst_utils::sub_impl!(Size - Size -> Size);
impl Mul<f64> for Size {
type Output = Self;
fn mul(self, other: f64) -> Self {
Self { x: self.x * other, y: self.y * other }
}
}
impl Mul<Size> for f64 {
type Output = Size;
fn mul(self, other: Size) -> Size {
other * self
}
}
impl Div<f64> for Size {
type Output = Self;
fn div(self, other: f64) -> Self {
Self { x: self.x / other, y: self.y / other }
}
}
typst_utils::assign_impl!(Size -= Size);
typst_utils::assign_impl!(Size += Size);
typst_utils::assign_impl!(Size *= f64);
typst_utils::assign_impl!(Size /= f64);
| 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/layout/grid/mod.rs | crates/typst-library/src/layout/grid/mod.rs | pub mod resolve;
use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::Arc;
use comemo::Track;
use smallvec::{SmallVec, smallvec};
use typst_utils::NonZeroExt;
use crate::diag::{At, HintedStrResult, HintedString, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Array, CastInfo, Content, Context, Fold, FromValue, Func, IntoValue, Packed, Reflect,
Resolve, Smart, StyleChain, Synthesize, Value, cast, elem, scope,
};
use crate::introspection::Tagged;
use crate::layout::resolve::{CellGrid, grid_to_cellgrid};
use crate::layout::{
Alignment, Length, OuterHAlignment, OuterVAlignment, Rel, Sides, Sizing,
};
use crate::model::{TableCell, TableFooter, TableHLine, TableHeader, TableVLine};
use crate::visualize::{Paint, Stroke};
/// Arranges content in a grid.
///
/// The grid element allows you to arrange content in a grid. You can define the
/// number of rows and columns, as well as the size of the gutters between them.
/// There are multiple sizing modes for columns and rows that can be used to
/// create complex layouts.
///
/// While the grid and table elements work very similarly, they are intended for
/// different use cases and carry different semantics. The grid element is
/// intended for presentational and layout purposes, while the [`table`] element
/// is intended for, in broad terms, presenting multiple related data points.
/// Set and show rules on one of these elements do not affect the other. Refer
/// to the [Accessibility Section]($grid/#accessibility) to learn how grids and
/// tables are presented to users of Assistive Technology (AT) like screen
/// readers.
///
/// # Sizing the tracks { #track-size }
///
/// A grid's sizing is determined by the track sizes specified in the arguments.
/// There are multiple sizing parameters: [`columns`]($grid.columns),
/// [`rows`]($grid.rows) and [`gutter`]($grid.gutter).
/// Because each of the sizing parameters accepts the same values, we will
/// explain them just once, here. Each sizing argument accepts an array of
/// individual track sizes. A track size is either:
///
/// - `{auto}`: The track will be sized to fit its contents. It will be at most
/// as large as the remaining space. If there is more than one `{auto}` track
/// width, and together they claim more than the available space, the `{auto}`
/// tracks will fairly distribute the available space among themselves.
///
/// - A fixed or relative length (e.g. `{10pt}` or `{20% - 1cm}`): The track
/// will be exactly of this size.
///
/// - A fractional length (e.g. `{1fr}`): Once all other tracks have been sized,
/// the remaining space will be divided among the fractional tracks according
/// to their fractions. For example, if there are two fractional tracks, each
/// with a fraction of `{1fr}`, they will each take up half of the remaining
/// space.
///
/// To specify a single track, the array can be omitted in favor of a single
/// value. To specify multiple `{auto}` tracks, enter the number of tracks
/// instead of an array. For example, `columns:` `{3}` is equivalent to
/// `columns:` `{(auto, auto, auto)}`.
///
/// # Examples
/// The example below demonstrates the different track sizing options. It also
/// shows how you can use [`grid.cell`] to make an individual cell span two grid
/// tracks.
///
/// ```example
/// // We use `rect` to emphasize the
/// // area of cells.
/// #set rect(
/// inset: 8pt,
/// fill: rgb("e4e5ea"),
/// width: 100%,
/// )
///
/// #grid(
/// columns: (60pt, 1fr, 2fr),
/// rows: (auto, 60pt),
/// gutter: 3pt,
/// rect[Fixed width, auto height],
/// rect[1/3 of the remains],
/// rect[2/3 of the remains],
/// rect(height: 100%)[Fixed height],
/// grid.cell(
/// colspan: 2,
/// image("tiger.jpg", width: 100%),
/// ),
/// )
/// ```
///
/// You can also [spread]($arguments/#spreading) an array of strings or content
/// into a grid to populate its cells.
///
/// ```example
/// #grid(
/// columns: 5,
/// gutter: 5pt,
/// ..range(25).map(str)
/// )
/// ```
///
/// # Styling the grid { #styling }
/// The grid and table elements work similarly. For a hands-on explanation,
/// refer to the [Table Guide]($guides/tables/#fills); for a quick overview,
/// continue reading.
///
/// The grid's appearance can be customized through different parameters. These
/// are the most important ones:
///
/// - [`align`]($grid.align) to change how cells are aligned
/// - [`inset`]($grid.inset) to optionally add internal padding to cells
/// - [`fill`]($grid.fill) to give cells a background
/// - [`stroke`]($grid.stroke) to optionally enable grid lines with a certain
/// stroke
///
/// To meet different needs, there are various ways to set them.
///
/// If you need to override the above options for individual cells, you can use
/// the [`grid.cell`] element. Likewise, you can override individual grid lines
/// with the [`grid.hline`] and [`grid.vline`] elements.
///
/// To configure an overall style for a grid, you may instead specify the option
/// in any of the following fashions:
///
/// - As a single value that applies to all cells.
/// - As an array of values corresponding to each column. The array will be
/// cycled if there are more columns than the array has items.
/// - As a function in the form of `(x, y) => value`. It receives the cell's
/// column and row indices (both starting from zero) and should return the
/// value to apply to that cell.
///
/// ```example
/// #grid(
/// columns: 5,
///
/// // By a single value
/// align: center,
/// // By a single but more complicated value
/// inset: (x: 2pt, y: 3pt),
/// // By an array of values (cycling)
/// fill: (rgb("#239dad50"), none),
/// // By a function that returns a value
/// stroke: (x, y) => if calc.rem(x + y, 3) == 0 { 0.5pt },
///
/// ..range(5 * 3).map(n => numbering("A", n + 1))
/// )
/// ```
///
/// On top of that, you may [apply styling rules]($styling) to [`grid`] and
/// [`grid.cell`]. Especially, the [`x`]($grid.cell.x) and [`y`]($grid.cell.y)
/// fields of `grid.cell` can be used in a [`where`]($function.where) selector,
/// making it possible to style cells at specific columns or rows, or individual
/// positions.
///
/// ## Stroke styling precedence
/// As explained above, there are three ways to set the stroke of a grid cell:
/// through [`{grid.cell}`'s `stroke` field]($grid.cell.stroke), by using
/// [`{grid.hline}`]($grid.hline) and [`{grid.vline}`]($grid.vline), or by
/// setting the [`{grid}`'s `stroke` field]($grid.stroke). When multiple of
/// these settings are present and conflict, the `hline` and `vline` settings
/// take the highest precedence, followed by the `cell` settings, and finally
/// the `grid` settings.
///
/// Furthermore, strokes of a repeated grid header or footer will take
/// precedence over regular cell strokes.
///
/// # Accessibility
/// Grids do not carry any special semantics. Assistive Technology (AT) does not
/// offer the ability to navigate two-dimensionally by cell in grids. If you
/// want to present tabular data, use the [`table`] element instead.
///
/// AT will read the grid cells in their semantic order. Usually, this is the
/// order in which you passed them to the grid. However, if you manually
/// positioned them using [`grid.cell`'s `x` and `y` arguments]($grid.cell.x),
/// cells will be read row by row, from left to right (in left-to-right
/// documents). A cell will be read when its position is first reached.
#[elem(scope, Synthesize, Tagged)]
pub struct GridElem {
/// The column sizes.
///
/// Either specify a track size array or provide an integer to create a grid
/// with that many `{auto}`-sized columns. Note that opposed to rows and
/// gutters, providing a single track size will only ever create a single
/// column.
///
/// See the [track size section](#track-size) above for more details.
pub columns: TrackSizings,
/// The row sizes.
///
/// If there are more cells than fit the defined rows, the last row is
/// repeated until there are no more cells.
///
/// See the [track size section](#track-size) above for more details.
pub rows: TrackSizings,
/// The gaps between rows and columns. This is a shorthand to set
/// [`column-gutter`]($grid.column-gutter) and [`row-gutter`]($grid.row-gutter)
/// to the same value.
///
/// If there are more gutters than defined sizes, the last gutter is
/// repeated.
///
/// See the [track size section](#track-size) above for more details.
#[external]
pub gutter: TrackSizings,
/// The gaps between columns.
#[parse(
let gutter = args.named("gutter")?;
args.named("column-gutter")?.or_else(|| gutter.clone())
)]
pub column_gutter: TrackSizings,
/// The gaps between rows.
#[parse(args.named("row-gutter")?.or_else(|| gutter.clone()))]
pub row_gutter: TrackSizings,
/// How much to pad the cells' content.
///
/// To specify a uniform inset for all cells, you can 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 varying inset for different cells, you can:
/// - use a single inset for all cells
/// - use an array of insets corresponding to each column
/// - use a function that maps a cell's position to its inset
///
/// See the [styling section](#styling) above for more details.
///
/// In addition, you can find an example at the [`table.inset`] parameter.
#[fold]
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 position to its alignment
///
/// See the [styling section](#styling) above for details.
///
/// In addition, you can find an example at the [`table.align`] parameter.
pub align: Celled<Smart<Alignment>>,
/// How to fill the cells.
///
/// This can be:
/// - a single color for all cells
/// - an array of colors corresponding to each column
/// - a function that maps a cell's position to its color
///
/// Most notably, arrays and functions are useful for creating striped grids.
/// See the [styling section](#styling) above for more details.
///
/// ```example
/// #grid(
/// fill: (x, y) =>
/// if calc.even(x + y) { luma(230) }
/// else { white },
/// align: center + horizon,
/// columns: 4,
/// inset: 2pt,
/// [X], [O], [X], [O],
/// [O], [X], [O], [X],
/// [X], [O], [X], [O],
/// [O], [X], [O], [X],
/// )
/// ```
pub fill: Celled<Option<Paint>>,
/// How to [stroke]($stroke) the cells.
///
/// Grids have no strokes by default, which can be changed by setting this
/// option to the desired stroke.
///
/// If it is necessary to place lines which can cross spacing between cells
/// produced by the [`gutter`]($grid.gutter) option, or to override the
/// stroke between multiple specific cells, consider specifying one or more
/// of [`grid.hline`] and [`grid.vline`] alongside your grid cells.
///
/// To specify the same stroke for all cells, you can 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 [styling section](#styling) above for more details.
///
/// ```example:"Passing a function to set a stroke based on position"
/// #set page(width: 420pt)
/// #set text(number-type: "old-style")
/// #show grid.cell.where(y: 0): set text(size: 1.3em)
///
/// #grid(
/// columns: (1fr, 2fr, 2fr),
/// row-gutter: 1.5em,
/// inset: (left: 0.5em),
/// stroke: (x, y) => if x > 0 { (left: 0.5pt + gray) },
/// align: horizon,
///
/// [Winter \ 2007 \ Season],
/// [Aaron Copland \ *The Tender Land* \ January 2007],
/// [Eric Satie \ *Gymnopedie 1, 2* \ February 2007],
///
/// [],
/// [Jan 12 \ *Middlebury College \ Center for the Arts* \ 20:00],
/// [Feb 2 \ *Johnson State College Dibden Center for the Arts* \ 19:30],
///
/// [],
/// [Skip a week \ #text(0.8em)[_Prepare your exams!_]],
/// [Feb 9 \ *Castleton State College \ Fine Arts Center* \ 19:30],
///
/// [],
/// [Jan 26, 27 \ *Lyndon State College Alexander Twilight Theater* \ 20:00],
/// [
/// Feb 17 --- #smallcaps[Anniversary] \
/// *Middlebury College \ Center for the Arts* \
/// 19:00 #text(0.7em)[(for a special guest)]
/// ],
/// )
/// ```
///
/// ```example:"Folding the stroke dictionary"
/// #set page(height: 13em, width: 26em)
///
/// #let cv(..jobs) = grid(
/// columns: 2,
/// inset: 5pt,
/// stroke: (x, y) => if x == 0 and y > 0 {
/// (right: (
/// paint: luma(180),
/// thickness: 1.5pt,
/// dash: "dotted",
/// ))
/// },
/// grid.header(grid.cell(colspan: 2)[
/// *Professional Experience*
/// #box(width: 1fr, line(length: 100%, stroke: luma(180)))
/// ]),
/// ..{
/// let last = none
/// for job in jobs.pos() {
/// (
/// if job.year != last [*#job.year*],
/// [
/// *#job.company* - #job.role _(#job.timeframe)_ \
/// #job.details
/// ]
/// )
/// last = job.year
/// }
/// }
/// )
///
/// #cv(
/// (
/// year: 2012,
/// company: [Pear Seed & Co.],
/// role: [Lead Engineer],
/// timeframe: [Jul - Dec],
/// details: [
/// - Raised engineers from 3x to 10x
/// - Did a great job
/// ],
/// ),
/// (
/// year: 2012,
/// company: [Mega Corp.],
/// role: [VP of Sales],
/// timeframe: [Mar - Jun],
/// details: [- Closed tons of customers],
/// ),
/// (
/// year: 2013,
/// company: [Tiny Co.],
/// role: [CEO],
/// timeframe: [Jan - Dec],
/// details: [- Delivered 4x more shareholder value],
/// ),
/// (
/// year: 2014,
/// company: [Glorbocorp Ltd],
/// role: [CTO],
/// timeframe: [Jan - Mar],
/// details: [- Drove containerization forward],
/// ),
/// )
/// ```
#[fold]
pub stroke: Celled<Sides<Option<Option<Arc<Stroke>>>>>,
#[internal]
#[synthesized]
pub grid: Arc<CellGrid>,
/// The contents of the grid cells, plus any extra grid lines specified with
/// the [`grid.hline`] and [`grid.vline`] elements.
///
/// The cells are populated in row-major order.
#[variadic]
pub children: Vec<GridChild>,
}
#[scope]
impl GridElem {
#[elem]
type GridCell;
#[elem]
type GridHLine;
#[elem]
type GridVLine;
#[elem]
type GridHeader;
#[elem]
type GridFooter;
}
impl Synthesize for Packed<GridElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let grid = grid_to_cellgrid(self, engine, styles)?;
self.grid = Some(Arc::new(grid));
Ok(())
}
}
/// Track sizing definitions.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct TrackSizings(pub SmallVec<[Sizing; 4]>);
cast! {
TrackSizings,
self => self.0.into_value(),
sizing: Sizing => Self(smallvec![sizing]),
count: NonZeroUsize => Self(smallvec![Sizing::Auto; count.get()]),
values: Array => Self(values.into_iter().map(Value::cast).collect::<HintedStrResult<_>>()?),
}
/// Any child of a grid element.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum GridChild {
Header(Packed<GridHeader>),
Footer(Packed<GridFooter>),
Item(GridItem),
}
cast! {
GridChild,
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 GridChild {
type Error = HintedString;
fn try_from(value: Content) -> HintedStrResult<Self> {
if value.is::<TableHeader>() {
bail!(
"cannot use `table.header` as a grid header";
hint: "use `grid.header` instead";
)
}
if value.is::<TableFooter>() {
bail!(
"cannot use `table.footer` as a grid footer";
hint: "use `grid.footer` instead";
)
}
value
.into_packed::<GridHeader>()
.map(Self::Header)
.or_else(|value| value.into_packed::<GridFooter>().map(Self::Footer))
.or_else(|value| GridItem::try_from(value).map(Self::Item))
}
}
/// A grid item, which is the basic unit of grid specification.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum GridItem {
HLine(Packed<GridHLine>),
VLine(Packed<GridVLine>),
Cell(Packed<GridCell>),
}
cast! {
GridItem,
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 GridItem {
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::<TableCell>() {
bail!(
"cannot use `table.cell` as a grid cell";
hint: "use `grid.cell` instead";
);
}
if value.is::<TableHLine>() {
bail!(
"cannot use `table.hline` as a grid line";
hint: "use `grid.hline` instead";
);
}
if value.is::<TableVLine>() {
bail!(
"cannot use `table.vline` as a grid line";
hint: "use `grid.vline` instead";
);
}
Ok(value
.into_packed::<GridHLine>()
.map(Self::HLine)
.or_else(|value| value.into_packed::<GridVLine>().map(Self::VLine))
.or_else(|value| value.into_packed::<GridCell>().map(Self::Cell))
.unwrap_or_else(|value| {
let span = value.span();
Self::Cell(Packed::new(GridCell::new(value)).spanned(span))
}))
}
}
/// A repeatable grid header.
///
/// If `repeat` is set to `true`, the header will be repeated across pages. For
/// an example, refer to the [`table.header`] element and the [`grid.stroke`]
/// parameter.
#[elem(name = "header", title = "Grid Header")]
pub struct GridHeader {
/// 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<GridItem>,
}
/// A repeatable grid footer.
///
/// Just like the [`grid.header`] element, the footer can repeat itself on every
/// page of the grid.
///
/// No other grid cells may be placed after the footer.
#[elem(name = "footer", title = "Grid Footer")]
pub struct GridFooter {
/// Whether this footer should be repeated across pages.
#[default(true)]
pub repeat: bool,
/// The cells and lines within the footer.
#[variadic]
pub children: Vec<GridItem>,
}
/// A horizontal line in the grid.
///
/// Overrides any per-cell stroke, including stroke specified through the grid's
/// `stroke` field. Can cross spacing between cells created through the grid's
/// `column-gutter` option.
///
/// An example for this function can be found at the [`table.hline`] element.
#[elem(name = "hline", title = "Grid Horizontal Line")]
pub struct GridHLine {
/// The row above which the horizontal line is placed (zero-indexed).
/// If the `position` field is set to `{bottom}`, the line is placed below
/// the row with the given index instead (see [`grid.hline.position`] for
/// details).
///
/// Specifying `{auto}` causes the line to be placed at the row below the
/// last automatically positioned cell (that is, cell without coordinate
/// overrides) before the line among the grid's children. If there is no
/// such cell before the line, it is placed at the top of the grid (row 0).
/// Note that specifying for this option exactly the total amount of rows
/// in the grid causes this horizontal line to override the bottom border
/// of the grid, while a value of 0 overrides the top border.
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).
/// Therefore, the horizontal line will be drawn up to and across column
/// `end - 1`.
///
/// A value equal to `{none}` or to the amount of columns causes it to
/// extend all the way towards the end of the grid.
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 grid.
///
/// Overrides any per-cell stroke, including stroke specified through the
/// grid's `stroke` field. Can cross spacing between cells created through
/// the grid's `row-gutter` option.
#[elem(name = "vline", title = "Grid Vertical Line")]
pub struct GridVLine {
/// The column before which the vertical line is placed (zero-indexed).
/// If the `position` field is set to `{end}`, the line is placed after the
/// column with the given index instead (see [`grid.vline.position`] for
/// details).
///
/// Specifying `{auto}` causes the line to be placed at the column after
/// the last automatically positioned cell (that is, cell without
/// coordinate overrides) before the line among the grid's children. If
/// there is no such cell before the line, it is placed before the grid's
/// first column (column 0).
/// Note that specifying for this option exactly the total amount of
/// columns in the grid causes this vertical line to override the end
/// border of the grid (right in LTR, left in RTL), while a value of 0
/// overrides the start border (left in LTR, right in RTL).
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).
/// Therefore, the vertical line will be drawn up to and across row
/// `end - 1`.
///
/// A value equal to `{none}` or to the amount of rows causes it to extend
/// all the way towards the bottom of the grid.
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 grid 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 grid. You can use this function in the argument list of a grid
/// to override grid style properties for an individual cell or manually
/// positioning it within the grid. You can also use this function in show rules
/// to apply certain styles to multiple cells at once.
///
/// For example, you can override the position and stroke for a single cell:
///
/// ```example
/// >>> #set page(width: auto)
/// >>> #set text(15pt, font: "Noto Sans Symbols 2", bottom-edge: -.2em)
/// <<< #set text(15pt, font: "Noto Sans Symbols 2")
/// #show regex("[♚-♟︎]"): set text(fill: rgb("21212A"))
/// #show regex("[♔-♙]"): set text(fill: rgb("111015"))
///
/// #grid(
/// fill: (x, y) => rgb(
/// if calc.odd(x + y) { "7F8396" }
/// else { "EFF0F3" }
/// ),
/// columns: (1em,) * 8,
/// rows: 1em,
/// align: center + horizon,
///
/// [♖], [♘], [♗], [♕], [♔], [♗], [♘], [♖],
/// [♙], [♙], [♙], [♙], [], [♙], [♙], [♙],
/// grid.cell(
/// x: 4, y: 3,
/// stroke: blue.transparentize(60%)
/// )[♙],
///
/// ..(grid.cell(y: 6)[♟],) * 8,
/// ..([♜], [♞], [♝], [♛], [♚], [♝], [♞], [♜])
/// .map(grid.cell.with(y: 7)),
/// )
/// ```
///
/// You may also apply a show rule on `grid.cell` to style all cells at once,
/// which allows you, for example, to apply styles based on a cell's position.
/// Refer to the examples of the [`table.cell`] element to learn more about
/// this.
#[elem(name = "cell", title = "Grid Cell")]
pub struct GridCell {
/// The cell's body.
#[required]
pub body: Content,
/// The cell's column (zero-indexed).
/// This field may be used in show rules to style a cell depending on its
/// column.
///
/// You may override this field to pick in which column the cell must
/// be placed. If no row (`y`) is chosen, the cell will be placed in the
/// first row (starting at row 0) with that column available (or a new row
/// if none). If both `x` and `y` are chosen, however, the cell will be
/// placed in that exact position. An error is raised if that position is
/// not available (thus, it is usually wise to specify cells with a custom
/// position before cells with automatic positions).
///
/// ```example
/// #let circ(c) = circle(
/// fill: c, width: 5mm
/// )
///
/// #grid(
/// columns: 4,
/// rows: 7mm,
/// stroke: .5pt + blue,
/// align: center + horizon,
/// inset: 1mm,
///
/// grid.cell(x: 2, y: 2, circ(aqua)),
/// circ(yellow),
/// grid.cell(x: 3, circ(green)),
/// circ(black),
/// )
/// ```
pub x: Smart<usize>,
/// The cell's row (zero-indexed).
/// This field may be used in show rules to style a cell depending on its
/// row.
///
/// You may override this field to pick in which row the cell must be
/// placed. If no column (`x`) is chosen, the cell will be placed in the
/// first column (starting at column 0) available in the chosen row. If all
/// columns in the chosen row are already occupied, an error is raised.
///
/// ```example
/// #let tri(c) = polygon.regular(
/// fill: c,
/// size: 5mm,
/// vertices: 3,
/// )
///
/// #grid(
/// columns: 2,
/// stroke: blue,
/// inset: 1mm,
///
/// tri(black),
/// grid.cell(y: 1, tri(teal)),
/// grid.cell(y: 1, tri(red)),
/// grid.cell(y: 2, tri(orange))
/// )
/// ```
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]($grid.inset) override.
pub inset: Smart<Sides<Option<Rel<Length>>>>,
/// The cell's [alignment]($grid.align) override.
pub align: Smart<Alignment>,
/// The cell's [fill]($grid.fill) override.
pub fill: Smart<Option<Paint>>,
/// The cell's [stroke]($grid.stroke) override.
#[fold]
pub stroke: Sides<Option<Option<Arc<Stroke>>>>,
#[internal]
#[parse(Some(false))]
pub is_repeated: bool,
/// 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>,
}
cast! {
GridCell,
v: Content => v.into(),
}
impl Default for Packed<GridCell> {
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)
GridCell::new(Content::default())
.with_colspan(NonZeroUsize::ONE)
.with_rowspan(NonZeroUsize::ONE),
)
}
}
impl From<Content> for GridCell {
fn from(value: Content) -> Self {
#[allow(clippy::unwrap_or_default)]
value.unpack::<Self>().unwrap_or_else(Self::new)
}
}
/// A value that can be configured per cell.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Celled<T> {
/// A bare value, the same for all cells.
Value(T),
/// A closure mapping from cell coordinates to a value.
Func(Func),
/// An array of values corresponding to each column. The array will be
/// cycled if there are more columns than the array has items.
Array(Vec<T>),
}
impl<T: Default + Clone + FromValue> Celled<T> {
/// Resolve the value based on the cell position.
pub fn resolve(
&self,
engine: &mut Engine,
styles: StyleChain,
x: usize,
y: usize,
) -> SourceResult<T> {
Ok(match self {
Self::Value(value) => value.clone(),
Self::Func(func) => func
.call(engine, Context::new(None, Some(styles)).track(), [x, y])?
.cast()
.at(func.span())?,
Self::Array(array) => x
.checked_rem(array.len())
.and_then(|i| array.get(i))
.cloned()
.unwrap_or_default(),
})
}
}
| 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/layout/grid/resolve.rs | crates/typst-library/src/layout/grid/resolve.rs | use std::num::{NonZeroU32, NonZeroUsize};
use std::ops::{Deref, DerefMut, Range};
use std::sync::Arc;
use ecow::eco_format;
use typst_library::Dir;
use typst_library::diag::{
At, Hint, HintedStrResult, HintedString, SourceResult, Trace, Tracepoint, bail,
};
use typst_library::engine::Engine;
use typst_library::foundations::{Content, Fold, Packed, Smart, StyleChain};
use typst_library::layout::{
Abs, Alignment, Axes, Celled, GridCell, GridChild, GridElem, GridItem, Length,
OuterHAlignment, OuterVAlignment, Rel, ResolvedCelled, Sides, Sizing,
};
use typst_library::model::{TableCell, TableChild, TableElem, TableItem};
use typst_library::text::TextElem;
use typst_library::visualize::{Paint, Stroke};
use typst_syntax::Span;
use typst_utils::{NonZeroExt, SmallBitSet};
use crate::pdf::{TableCellKind, TableHeaderScope};
/// Convert a grid to a cell grid.
#[typst_macros::time(span = elem.span())]
pub fn grid_to_cellgrid(
elem: &Packed<GridElem>,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<CellGrid> {
let inset = elem.inset.get_cloned(styles);
let align = elem.align.get_ref(styles);
let columns = elem.columns.get_ref(styles);
let rows = elem.rows.get_ref(styles);
let column_gutter = elem.column_gutter.get_ref(styles);
let row_gutter = elem.row_gutter.get_ref(styles);
let fill = elem.fill.get_ref(styles);
let stroke = elem.stroke.resolve(styles);
let tracks = Axes::new(columns.0.as_slice(), rows.0.as_slice());
let gutter = Axes::new(column_gutter.0.as_slice(), row_gutter.0.as_slice());
// Use trace to link back to the grid when a specific cell errors
let tracepoint = || Tracepoint::Call(Some(eco_format!("grid")));
let resolve_item = |item: &GridItem| grid_item_to_resolvable(item, styles);
let children = elem.children.iter().map(|child| match child {
GridChild::Header(header) => ResolvableGridChild::Header {
repeat: header.repeat.get(styles),
level: header.level.get(styles),
span: header.span(),
items: header.children.iter().map(resolve_item),
},
GridChild::Footer(footer) => ResolvableGridChild::Footer {
repeat: footer.repeat.get(styles),
span: footer.span(),
items: footer.children.iter().map(resolve_item),
},
GridChild::Item(item) => {
ResolvableGridChild::Item(grid_item_to_resolvable(item, styles))
}
});
resolve_cellgrid(
tracks,
gutter,
children,
fill,
align,
&inset,
&stroke,
engine,
styles,
elem.span(),
)
.trace(engine.world, tracepoint, elem.span())
}
/// Convert a table to a cell grid.
#[typst_macros::time(span = elem.span())]
pub fn table_to_cellgrid(
elem: &Packed<TableElem>,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<CellGrid> {
let inset = elem.inset.get_cloned(styles);
let align = elem.align.get_ref(styles);
let columns = elem.columns.get_ref(styles);
let rows = elem.rows.get_ref(styles);
let column_gutter = elem.column_gutter.get_ref(styles);
let row_gutter = elem.row_gutter.get_ref(styles);
let fill = elem.fill.get_ref(styles);
let stroke = elem.stroke.resolve(styles);
let tracks = Axes::new(columns.0.as_slice(), rows.0.as_slice());
let gutter = Axes::new(column_gutter.0.as_slice(), row_gutter.0.as_slice());
// Use trace to link back to the table when a specific cell errors
let tracepoint = || Tracepoint::Call(Some(eco_format!("table")));
let resolve_item = |item: &TableItem| table_item_to_resolvable(item, styles);
let children = elem.children.iter().map(|child| match child {
TableChild::Header(header) => ResolvableGridChild::Header {
repeat: header.repeat.get(styles),
level: header.level.get(styles),
span: header.span(),
items: header.children.iter().map(resolve_item),
},
TableChild::Footer(footer) => ResolvableGridChild::Footer {
repeat: footer.repeat.get(styles),
span: footer.span(),
items: footer.children.iter().map(resolve_item),
},
TableChild::Item(item) => {
ResolvableGridChild::Item(table_item_to_resolvable(item, styles))
}
});
resolve_cellgrid(
tracks,
gutter,
children,
fill,
align,
&inset,
&stroke,
engine,
styles,
elem.span(),
)
.trace(engine.world, tracepoint, elem.span())
}
fn grid_item_to_resolvable(
item: &GridItem,
styles: StyleChain,
) -> ResolvableGridItem<Packed<GridCell>> {
match item {
GridItem::HLine(hline) => ResolvableGridItem::HLine {
y: hline.y.get(styles),
start: hline.start.get(styles),
end: hline.end.get(styles),
stroke: hline.stroke.resolve(styles),
span: hline.span(),
position: match hline.position.get(styles) {
OuterVAlignment::Top => LinePosition::Before,
OuterVAlignment::Bottom => LinePosition::After,
},
},
GridItem::VLine(vline) => ResolvableGridItem::VLine {
x: vline.x.get(styles),
start: vline.start.get(styles),
end: vline.end.get(styles),
stroke: vline.stroke.resolve(styles),
span: vline.span(),
position: match vline.position.get(styles) {
OuterHAlignment::Left if styles.resolve(TextElem::dir) == Dir::RTL => {
LinePosition::After
}
OuterHAlignment::Right if styles.resolve(TextElem::dir) == Dir::RTL => {
LinePosition::Before
}
OuterHAlignment::Start | OuterHAlignment::Left => LinePosition::Before,
OuterHAlignment::End | OuterHAlignment::Right => LinePosition::After,
},
},
GridItem::Cell(cell) => ResolvableGridItem::Cell(cell.clone()),
}
}
fn table_item_to_resolvable(
item: &TableItem,
styles: StyleChain,
) -> ResolvableGridItem<Packed<TableCell>> {
match item {
TableItem::HLine(hline) => ResolvableGridItem::HLine {
y: hline.y.get(styles),
start: hline.start.get(styles),
end: hline.end.get(styles),
stroke: hline.stroke.resolve(styles),
span: hline.span(),
position: match hline.position.get(styles) {
OuterVAlignment::Top => LinePosition::Before,
OuterVAlignment::Bottom => LinePosition::After,
},
},
TableItem::VLine(vline) => ResolvableGridItem::VLine {
x: vline.x.get(styles),
start: vline.start.get(styles),
end: vline.end.get(styles),
stroke: vline.stroke.resolve(styles),
span: vline.span(),
position: match vline.position.get(styles) {
OuterHAlignment::Left if styles.resolve(TextElem::dir) == Dir::RTL => {
LinePosition::After
}
OuterHAlignment::Right if styles.resolve(TextElem::dir) == Dir::RTL => {
LinePosition::Before
}
OuterHAlignment::Start | OuterHAlignment::Left => LinePosition::Before,
OuterHAlignment::End | OuterHAlignment::Right => LinePosition::After,
},
},
TableItem::Cell(cell) => ResolvableGridItem::Cell(cell.clone()),
}
}
impl ResolvableCell for Packed<TableCell> {
fn resolve_cell(
mut self,
x: usize,
y: usize,
fill: &Option<Paint>,
align: Smart<Alignment>,
inset: Sides<Option<Rel<Length>>>,
stroke: Sides<Option<Option<Arc<Stroke<Abs>>>>>,
breakable: bool,
styles: StyleChain,
kind: Smart<TableCellKind>,
) -> Cell {
let cell = &mut *self;
let colspan = cell.colspan.get(styles);
let rowspan = cell.rowspan.get(styles);
let breakable = cell.breakable.get(styles).unwrap_or(breakable);
let fill = cell.fill.get_cloned(styles).unwrap_or_else(|| fill.clone());
let kind = cell.kind.get(styles).or(kind);
let cell_stroke = cell.stroke.resolve(styles);
let stroke_overridden =
cell_stroke.as_ref().map(|side| matches!(side, Some(Some(_))));
// Using a typical 'Sides' fold, an unspecified side loses to a
// specified side. Additionally, when both are specified, an inner
// None wins over the outer Some, and vice-versa. When both are
// specified and Some, fold occurs, which, remarkably, leads to an Arc
// clone.
//
// In the end, we flatten because, for layout purposes, an unspecified
// cell stroke is the same as specifying 'none', so we equate the two
// concepts.
let stroke = cell_stroke.fold(stroke).map(Option::flatten);
cell.x.set(Smart::Custom(x));
cell.y.set(Smart::Custom(y));
cell.fill.set(Smart::Custom(fill.clone()));
cell.align.set(match align {
Smart::Custom(align) => Smart::Custom(
cell.align.get(styles).map_or(align, |inner| inner.fold(align)),
),
// Don't fold if the table is using outer alignment. Use the
// cell's alignment instead (which, in the end, will fold with
// the outer alignment when it is effectively displayed).
Smart::Auto => cell.align.get(styles),
});
cell.inset.set(Smart::Custom(
cell.inset.get(styles).map_or(inset, |inner| inner.fold(inset)),
));
cell.stroke.set(
// Here we convert the resolved stroke to a regular stroke, however
// with resolved units (that is, 'em' converted to absolute units).
// We also convert any stroke unspecified by both the cell and the
// outer stroke ('None' in the folded stroke) to 'none', that is,
// all sides are present in the resulting Sides object accessible
// by show rules on table cells.
stroke.as_ref().map(|side| {
Some(side.as_ref().map(|cell_stroke| {
Arc::new((**cell_stroke).clone().map(Length::from))
}))
}),
);
cell.breakable.set(Smart::Custom(breakable));
cell.kind.set(kind);
Cell {
body: self.pack(),
fill,
colspan,
rowspan,
stroke,
stroke_overridden,
breakable,
}
}
fn x(&self, styles: StyleChain) -> Smart<usize> {
self.x.get(styles)
}
fn y(&self, styles: StyleChain) -> Smart<usize> {
self.y.get(styles)
}
fn colspan(&self, styles: StyleChain) -> NonZeroUsize {
self.colspan.get(styles)
}
fn rowspan(&self, styles: StyleChain) -> NonZeroUsize {
self.rowspan.get(styles)
}
fn span(&self) -> Span {
Packed::span(self)
}
}
impl ResolvableCell for Packed<GridCell> {
fn resolve_cell(
mut self,
x: usize,
y: usize,
fill: &Option<Paint>,
align: Smart<Alignment>,
inset: Sides<Option<Rel<Length>>>,
stroke: Sides<Option<Option<Arc<Stroke<Abs>>>>>,
breakable: bool,
styles: StyleChain,
_: Smart<TableCellKind>,
) -> Cell {
let cell = &mut *self;
let colspan = cell.colspan.get(styles);
let rowspan = cell.rowspan.get(styles);
let breakable = cell.breakable.get(styles).unwrap_or(breakable);
let fill = cell.fill.get_cloned(styles).unwrap_or_else(|| fill.clone());
let cell_stroke = cell.stroke.resolve(styles);
let stroke_overridden =
cell_stroke.as_ref().map(|side| matches!(side, Some(Some(_))));
// Using a typical 'Sides' fold, an unspecified side loses to a
// specified side. Additionally, when both are specified, an inner
// None wins over the outer Some, and vice-versa. When both are
// specified and Some, fold occurs, which, remarkably, leads to an Arc
// clone.
//
// In the end, we flatten because, for layout purposes, an unspecified
// cell stroke is the same as specifying 'none', so we equate the two
// concepts.
let stroke = cell_stroke.fold(stroke).map(Option::flatten);
cell.x.set(Smart::Custom(x));
cell.y.set(Smart::Custom(y));
cell.fill.set(Smart::Custom(fill.clone()));
cell.align.set(match align {
Smart::Custom(align) => Smart::Custom(
cell.align.get(styles).map_or(align, |inner| inner.fold(align)),
),
// Don't fold if the grid is using outer alignment. Use the
// cell's alignment instead (which, in the end, will fold with
// the outer alignment when it is effectively displayed).
Smart::Auto => cell.align.get(styles),
});
cell.inset.set(Smart::Custom(
cell.inset.get(styles).map_or(inset, |inner| inner.fold(inset)),
));
cell.stroke.set(
// Here we convert the resolved stroke to a regular stroke, however
// with resolved units (that is, 'em' converted to absolute units).
// We also convert any stroke unspecified by both the cell and the
// outer stroke ('None' in the folded stroke) to 'none', that is,
// all sides are present in the resulting Sides object accessible
// by show rules on grid cells.
stroke.as_ref().map(|side| {
Some(side.as_ref().map(|cell_stroke| {
Arc::new((**cell_stroke).clone().map(Length::from))
}))
}),
);
cell.breakable.set(Smart::Custom(breakable));
Cell {
body: self.pack(),
fill,
colspan,
rowspan,
stroke,
stroke_overridden,
breakable,
}
}
fn x(&self, styles: StyleChain) -> Smart<usize> {
self.x.get(styles)
}
fn y(&self, styles: StyleChain) -> Smart<usize> {
self.y.get(styles)
}
fn colspan(&self, styles: StyleChain) -> NonZeroUsize {
self.colspan.get(styles)
}
fn rowspan(&self, styles: StyleChain) -> NonZeroUsize {
self.rowspan.get(styles)
}
fn span(&self) -> Span {
Packed::span(self)
}
}
/// Represents an explicit grid line (horizontal or vertical) specified by the
/// user.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Line {
/// The index of the track after this line. This will be the index of the
/// row a horizontal line is above of, or of the column right after a
/// vertical line.
///
/// Must be within `0..=tracks.len()` (where `tracks` is either `grid.cols`
/// or `grid.rows`, ignoring gutter tracks, as appropriate).
pub index: usize,
/// The index of the track at which this line starts being drawn.
/// This is the first column a horizontal line appears in, or the first row
/// a vertical line appears in.
///
/// Must be within `0..tracks.len()` minus gutter tracks.
pub start: usize,
/// The index after the last track through which the line is drawn.
/// Thus, the line is drawn through tracks `start..end` (note that `end` is
/// exclusive).
///
/// Must be within `1..=tracks.len()` minus gutter tracks.
/// `None` indicates the line should go all the way to the end.
pub end: Option<NonZeroUsize>,
/// The line's stroke. This is `None` when the line is explicitly used to
/// override a previously specified line.
pub stroke: Option<Arc<Stroke<Abs>>>,
/// The line's position in relation to the track with its index.
pub position: LinePosition,
}
/// A repeatable grid header. Starts at the first row.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Header {
/// The range of rows included in this header.
pub range: Range<usize>,
/// The header's level.
///
/// Higher level headers repeat together with lower level headers. If a
/// lower level header stops repeating, all higher level headers do as
/// well.
pub level: NonZeroU32,
/// Whether this header cannot be repeated nor should have orphan
/// prevention because it would be about to cease repetition, either
/// because it is followed by headers of conflicting levels, or because
/// it is at the end of the table (possibly followed by some footers at the
/// end).
pub short_lived: bool,
}
/// A repeatable grid footer. Stops at the last row.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Footer {
/// The first row included in this footer.
pub start: usize,
/// The index after the last row included in this footer.
pub end: usize,
/// The footer's level.
///
/// Used similarly to header level.
pub level: u32,
}
impl Footer {
/// The footer's range of included rows.
#[inline]
pub fn range(&self) -> Range<usize> {
self.start..self.end
}
}
/// A possibly repeatable grid child (header or footer).
///
/// It still exists even when not repeatable, but must not have additional
/// considerations by grid layout, other than for consistency (such as making
/// a certain group of rows unbreakable).
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Repeatable<T> {
inner: T,
/// Whether the user requested the child to repeat.
pub repeated: bool,
}
impl<T> Deref for Repeatable<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for Repeatable<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl<T> Repeatable<T> {
/// Returns `Some` if the value is repeated, `None` otherwise.
#[inline]
pub fn as_repeated(&self) -> Option<&T> {
if self.repeated { Some(&self.inner) } else { None }
}
}
/// Used for cell-like elements which are aware of their final properties in
/// the table, and may have property overrides.
pub trait ResolvableCell {
/// Resolves the cell's fields, given its coordinates and default grid-wide
/// fill, align, inset and stroke properties, plus the expected value of
/// the `breakable` field.
/// Returns a final Cell.
#[allow(clippy::too_many_arguments)]
fn resolve_cell(
self,
x: usize,
y: usize,
fill: &Option<Paint>,
align: Smart<Alignment>,
inset: Sides<Option<Rel<Length>>>,
stroke: Sides<Option<Option<Arc<Stroke<Abs>>>>>,
breakable: bool,
styles: StyleChain,
kind: Smart<TableCellKind>,
) -> Cell;
/// Returns this cell's column override.
fn x(&self, styles: StyleChain) -> Smart<usize>;
/// Returns this cell's row override.
fn y(&self, styles: StyleChain) -> Smart<usize>;
/// The amount of columns spanned by this cell.
fn colspan(&self, styles: StyleChain) -> NonZeroUsize;
/// The amount of rows spanned by this cell.
fn rowspan(&self, styles: StyleChain) -> NonZeroUsize;
/// The cell's span, for errors.
fn span(&self) -> Span;
}
/// A grid item, possibly affected by automatic cell positioning. Can be either
/// a line or a cell.
pub enum ResolvableGridItem<T: ResolvableCell> {
/// A horizontal line in the grid.
HLine {
/// The row above which the horizontal line is drawn.
y: Smart<usize>,
start: usize,
end: Option<NonZeroUsize>,
stroke: Option<Arc<Stroke<Abs>>>,
/// The span of the corresponding line element.
span: Span,
/// The line's position. "before" here means on top of row `y`, while
/// "after" means below it.
position: LinePosition,
},
/// A vertical line in the grid.
VLine {
/// The column before which the vertical line is drawn.
x: Smart<usize>,
start: usize,
end: Option<NonZeroUsize>,
stroke: Option<Arc<Stroke<Abs>>>,
/// The span of the corresponding line element.
span: Span,
/// The line's position. "before" here means to the left of column `x`,
/// while "after" means to its right (both considering LTR).
position: LinePosition,
},
/// A cell in the grid.
Cell(T),
}
/// Represents a cell in CellGrid, to be laid out by GridLayouter.
#[derive(Debug, PartialEq, Hash)]
pub struct Cell {
/// The cell's body.
pub body: Content,
/// The cell's fill.
pub fill: Option<Paint>,
/// The amount of columns spanned by the cell.
pub colspan: NonZeroUsize,
/// The amount of rows spanned by the cell.
pub rowspan: NonZeroUsize,
/// The cell's stroke.
///
/// We use an Arc to avoid unnecessary space usage when all sides are the
/// same, or when the strokes come from a common source.
pub stroke: Sides<Option<Arc<Stroke<Abs>>>>,
/// Which stroke sides were explicitly overridden by the cell, over the
/// grid's global stroke setting.
///
/// This is used to define whether or not this cell's stroke sides should
/// have priority over adjacent cells' stroke sides, if those don't
/// override their own stroke properties (and thus have less priority when
/// defining with which stroke to draw grid lines around this cell).
pub stroke_overridden: Sides<bool>,
/// Whether rows spanned by this cell can be placed in different pages.
/// By default, a cell spanning only fixed-size rows is unbreakable, while
/// a cell spanning at least one `auto`-sized row is breakable.
pub breakable: bool,
}
impl Cell {
/// Create a simple cell given its body.
pub fn new(body: Content) -> Self {
Self {
body,
fill: None,
colspan: NonZeroUsize::ONE,
rowspan: NonZeroUsize::ONE,
stroke: Sides::splat(None),
stroke_overridden: Sides::splat(false),
breakable: true,
}
}
}
/// Indicates whether the line should be drawn before or after the track with
/// its index. This is mostly only relevant when gutter is used, since, then,
/// the position after a track is not the same as before the next
/// non-gutter track.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum LinePosition {
/// The line should be drawn before its track (e.g. hline on top of a row).
Before,
/// The line should be drawn after its track (e.g. hline below a row).
After,
}
/// A grid entry.
#[derive(Debug, PartialEq, Hash)]
pub enum Entry {
/// An entry which holds a cell.
Cell(Cell),
/// An entry which is merged with another cell.
Merged {
/// The index of the cell this entry is merged with.
parent: usize,
},
}
impl Entry {
/// Obtains the cell inside this entry, if this is not a merged cell.
pub fn as_cell(&self) -> Option<&Cell> {
match self {
Self::Cell(cell) => Some(cell),
Self::Merged { .. } => None,
}
}
}
/// Any grid child, which can be either a header or an item.
pub enum ResolvableGridChild<T: ResolvableCell, I> {
Header { repeat: bool, level: NonZeroU32, span: Span, items: I },
Footer { repeat: bool, span: Span, items: I },
Item(ResolvableGridItem<T>),
}
/// A grid of cells, including the columns, rows, and cell data.
#[derive(Debug, PartialEq, Hash)]
pub struct CellGrid {
/// The grid cells.
pub entries: Vec<Entry>,
/// The column tracks including gutter tracks.
pub cols: Vec<Sizing>,
/// The row tracks including gutter tracks.
pub rows: Vec<Sizing>,
/// The vertical lines before each column, or on the end border.
/// Gutter columns are not included.
/// Contains up to 'cols_without_gutter.len() + 1' vectors of lines.
pub vlines: Vec<Vec<Line>>,
/// The horizontal lines on top of each row, or on the bottom border.
/// Gutter rows are not included.
/// Contains up to 'rows_without_gutter.len() + 1' vectors of lines.
pub hlines: Vec<Vec<Line>>,
/// The repeatable headers of this grid.
pub headers: Vec<Repeatable<Header>>,
/// The repeatable footer of this grid.
pub footer: Option<Repeatable<Footer>>,
/// Whether this grid has gutters.
pub has_gutter: bool,
}
impl CellGrid {
/// Generates the cell grid, given the tracks and cells.
pub fn new(
tracks: Axes<&[Sizing]>,
gutter: Axes<&[Sizing]>,
cells: impl IntoIterator<Item = Cell>,
) -> Self {
let entries = cells.into_iter().map(Entry::Cell).collect();
Self::new_internal(tracks, gutter, vec![], vec![], vec![], None, entries)
}
/// Generates the cell grid, given the tracks and resolved entries.
pub fn new_internal(
tracks: Axes<&[Sizing]>,
gutter: Axes<&[Sizing]>,
vlines: Vec<Vec<Line>>,
hlines: Vec<Vec<Line>>,
headers: Vec<Repeatable<Header>>,
footer: Option<Repeatable<Footer>>,
entries: Vec<Entry>,
) -> Self {
let mut cols = vec![];
let mut rows = vec![];
// Number of content columns: Always at least one.
let num_cols = tracks.x.len().max(1);
// Number of content rows: At least as many as given, but also at least
// as many as needed to place each item.
let num_rows = {
let len = entries.len();
let given = tracks.y.len();
let needed = len / num_cols + (len % num_cols).clamp(0, 1);
given.max(needed)
};
let has_gutter = gutter.any(|tracks| !tracks.is_empty());
let auto = Sizing::Auto;
let zero = Sizing::Rel(Rel::zero());
let get_or = |tracks: &[_], idx, default| {
tracks.get(idx).or(tracks.last()).copied().unwrap_or(default)
};
// Collect content and gutter columns.
for x in 0..num_cols {
cols.push(get_or(tracks.x, x, auto));
if has_gutter {
cols.push(get_or(gutter.x, x, zero));
}
}
// Collect content and gutter rows.
for y in 0..num_rows {
rows.push(get_or(tracks.y, y, auto));
if has_gutter {
rows.push(get_or(gutter.y, y, zero));
}
}
// Remove superfluous gutter tracks.
if has_gutter {
cols.pop();
rows.pop();
}
Self {
cols,
rows,
entries,
vlines,
hlines,
headers,
footer,
has_gutter,
}
}
/// Get the grid entry in column `x` and row `y`.
///
/// Returns `None` if it's a gutter cell.
#[track_caller]
pub fn entry(&self, x: usize, y: usize) -> Option<&Entry> {
assert!(x < self.cols.len());
assert!(y < self.rows.len());
if self.has_gutter {
// Even columns and rows are children, odd ones are gutter.
if x % 2 == 0 && y % 2 == 0 {
let c = 1 + self.cols.len() / 2;
self.entries.get((y / 2) * c + x / 2)
} else {
None
}
} else {
let c = self.cols.len();
self.entries.get(y * c + x)
}
}
/// Get the content of the cell in column `x` and row `y`.
///
/// Returns `None` if it's a gutter cell or merged position.
#[track_caller]
pub fn cell(&self, x: usize, y: usize) -> Option<&Cell> {
self.entry(x, y).and_then(Entry::as_cell)
}
/// Returns the position of the parent cell of the grid entry at the given
/// position. It is guaranteed to have a non-gutter, non-merged cell at
/// the returned position, due to how the grid is built.
/// - If the entry at the given position is a cell, returns the given
/// position.
/// - If it is a merged cell, returns the parent cell's position.
/// - If it is a gutter cell, returns None.
#[track_caller]
pub fn parent_cell_position(&self, x: usize, y: usize) -> Option<Axes<usize>> {
self.entry(x, y).map(|entry| match entry {
Entry::Cell(_) => Axes::new(x, y),
Entry::Merged { parent } => {
let c = self.non_gutter_column_count();
let factor = if self.has_gutter { 2 } else { 1 };
Axes::new(factor * (*parent % c), factor * (*parent / c))
}
})
}
/// Returns the position of the actual parent cell of a merged position,
/// even if the given position is gutter, in which case we return the
/// parent of the nearest adjacent content cell which could possibly span
/// the given gutter position. If the given position is not a gutter cell,
/// then this function will return the same as `parent_cell_position` would.
/// If the given position is a gutter cell, but no cell spans it, returns
/// `None`.
///
/// This is useful for lines. A line needs to check if a cell next to it
/// has a stroke override - even at a gutter position there could be a
/// stroke override, since a cell could be merged with two cells at both
/// ends of the gutter cell (e.g. to its left and to its right), and thus
/// that cell would impose a stroke under the gutter. This function allows
/// getting the position of that cell (which spans the given gutter
/// position, if it is gutter), if it exists; otherwise returns None (it's
/// gutter and no cell spans it).
#[track_caller]
pub fn effective_parent_cell_position(
&self,
x: usize,
y: usize,
) -> Option<Axes<usize>> {
if self.has_gutter {
// If (x, y) is a gutter cell, we skip it (skip a gutter column and
// row) to the nearest adjacent content cell, in the direction
// which merged cells grow toward (increasing x and increasing y),
// such that we can verify if that adjacent cell is merged with the
// gutter cell by checking if its parent would come before (x, y).
// Otherwise, no cell is merged with this gutter cell, and we
// return None.
self.parent_cell_position(x + x % 2, y + y % 2)
.filter(|&parent| parent.x <= x && parent.y <= y)
} else {
self.parent_cell_position(x, y)
}
}
/// Checks if the track with the given index is gutter.
/// Does not check if the index is a valid track.
#[inline]
pub fn is_gutter_track(&self, index: usize) -> bool {
self.has_gutter && index % 2 == 1
}
/// Returns the effective colspan of a cell, considering the gutters it
/// might span if the grid has gutters.
#[inline]
pub fn effective_colspan_of_cell(&self, cell: &Cell) -> usize {
if self.has_gutter { 2 * cell.colspan.get() - 1 } else { cell.colspan.get() }
}
/// Returns the effective rowspan of a cell, considering the gutters it
/// might span if the grid has gutters.
#[inline]
pub fn effective_rowspan_of_cell(&self, cell: &Cell) -> usize {
if self.has_gutter { 2 * cell.rowspan.get() - 1 } else { cell.rowspan.get() }
}
#[inline]
pub fn non_gutter_column_count(&self) -> usize {
if self.has_gutter {
// Calculation: With gutters, we have
// 'cols = 2 * (non-gutter cols) - 1', since there is a gutter
// column between each regular column. Therefore,
// 'floor(cols / 2)' will be equal to
// 'floor(non-gutter cols - 1/2) = non-gutter-cols - 1',
// so 'non-gutter cols = 1 + floor(cols / 2)'.
1 + self.cols.len() / 2
} else {
self.cols.len()
}
}
#[inline]
pub fn non_gutter_row_count(&self) -> usize {
if self.has_gutter {
// Calculation: With gutters, we have
// 'rows = 2 * (non-gutter rows) - 1', since there is a gutter
// row between each regular row. Therefore,
// 'floor(rows / 2)' will be equal to
// 'floor(non-gutter rows - 1/2) = non-gutter-rows - 1',
// so 'non-gutter rows = 1 + floor(rows / 2)'.
1 + self.rows.len() / 2
} else {
self.rows.len()
}
}
#[inline]
| 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/visualize/stroke.rs | crates/typst-library/src/visualize/stroke.rs | use ecow::EcoString;
use typst_utils::{Numeric, Scalar};
use crate::diag::{HintedStrResult, SourceResult};
use crate::foundations::{
Args, Cast, Dict, Fold, FromValue, NoneValue, Repr, Resolve, Smart, StyleChain,
Value, cast, dict, func, scope, ty,
};
use crate::layout::{Abs, Length};
use crate::visualize::{Color, Gradient, Paint, Tiling};
/// Defines how to draw a line.
///
/// A stroke has a _paint_ (a solid color or gradient), a _thickness,_ a line
/// _cap,_ a line _join,_ a _miter limit,_ and a _dash_ pattern. All of these
/// values are optional and have sensible defaults.
///
/// # Example
/// ```example
/// #set line(length: 100%)
/// #stack(
/// spacing: 1em,
/// line(stroke: 2pt + red),
/// line(stroke: (paint: blue, thickness: 4pt, cap: "round")),
/// line(stroke: (paint: blue, thickness: 1pt, dash: "dashed")),
/// line(stroke: 2pt + gradient.linear(..color.map.rainbow)),
/// )
/// ```
///
/// # Simple strokes
/// You can create a simple solid stroke from a color, a thickness, or a
/// combination of the two. Specifically, wherever a stroke is expected you can
/// pass any of the following values:
///
/// - A length specifying the stroke's thickness. The color is inherited,
/// defaulting to black.
/// - A color to use for the stroke. The thickness is inherited, defaulting to
/// `{1pt}`.
/// - A stroke combined from color and thickness using the `+` operator as in
/// `{2pt + red}`.
///
/// For full control, you can also provide a [dictionary] or a `{stroke}` object
/// to any function that expects a stroke. The dictionary's keys may include any
/// of the parameters for the constructor function, shown below.
///
/// # Fields
/// On a stroke object, you can access any of the fields listed in the
/// constructor function. For example, `{(2pt + blue).thickness}` is `{2pt}`.
/// Meanwhile, `{stroke(red).cap}` is `{auto}` because it's unspecified. Fields
/// set to `{auto}` are inherited.
#[ty(scope, cast)]
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Stroke<T: Numeric = Length> {
/// The stroke's paint.
pub paint: Smart<Paint>,
/// The stroke's thickness.
pub thickness: Smart<T>,
/// The stroke's line cap.
pub cap: Smart<LineCap>,
/// The stroke's line join.
pub join: Smart<LineJoin>,
/// The stroke's line dash pattern.
pub dash: Smart<Option<DashPattern<T>>>,
/// The miter limit.
pub miter_limit: Smart<Scalar>,
}
impl Stroke {
/// Create a stroke from a paint and a thickness.
pub fn from_pair(paint: impl Into<Paint>, thickness: Length) -> Self {
Self {
paint: Smart::Custom(paint.into()),
thickness: Smart::Custom(thickness),
..Default::default()
}
}
}
#[scope]
impl Stroke {
/// Converts a value to a stroke or constructs a stroke with the given
/// parameters.
///
/// Note that in most cases you do not need to convert values to strokes in
/// order to use them, as they will be converted automatically. However,
/// this constructor can be useful to ensure a value has all the fields of a
/// stroke.
///
/// ```example
/// #let my-func(x) = {
/// x = stroke(x) // Convert to a stroke
/// [Stroke has thickness #x.thickness.]
/// }
/// #my-func(3pt) \
/// #my-func(red) \
/// #my-func(stroke(cap: "round", thickness: 1pt))
/// ```
#[func(constructor)]
pub fn construct(
args: &mut Args,
/// The color or gradient to use for the stroke.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{black}`.
#[external]
paint: Smart<Paint>,
/// The stroke's thickness.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{1pt}`.
#[external]
thickness: Smart<Length>,
/// How the ends of the stroke are rendered.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{"butt"}`.
#[external]
cap: Smart<LineCap>,
/// How sharp turns are rendered.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{"miter"}`.
#[external]
join: Smart<LineJoin>,
/// The dash pattern to use. This can be:
///
/// - One of the predefined patterns:
/// - `{"solid"}` or `{none}`
/// - `{"dotted"}`
/// - `{"densely-dotted"}`
/// - `{"loosely-dotted"}`
/// - `{"dashed"}`
/// - `{"densely-dashed"}`
/// - `{"loosely-dashed"}`
/// - `{"dash-dotted"}`
/// - `{"densely-dash-dotted"}`
/// - `{"loosely-dash-dotted"}`
/// - An [array] with alternating lengths for dashes and gaps. You can
/// also use the string `{"dot"}` for a length equal to the line
/// thickness.
/// - A [dictionary] with the keys `array` (same as the array above),
/// and `phase` (of type [length]), which defines where in the pattern
/// to start drawing.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{none}`.
///
/// ```example
/// #set line(length: 100%, stroke: 2pt)
/// #stack(
/// spacing: 1em,
/// line(stroke: (dash: "dashed")),
/// line(stroke: (dash: (10pt, 5pt, "dot", 5pt))),
/// line(stroke: (dash: (array: (10pt, 5pt, "dot", 5pt), phase: 10pt))),
/// )
/// ```
#[external]
dash: Smart<Option<DashPattern>>,
/// Number at which protruding sharp bends are rendered with a bevel
/// instead or a miter join. The higher the number, the sharper an angle
/// can be before it is bevelled. Only applicable if `join` is
/// `{"miter"}`.
///
/// Specifically, the miter limit is the maximum ratio between the
/// corner's protrusion length and the stroke's thickness.
///
/// If set to `{auto}`, the value is inherited, defaulting to `{4.0}`.
///
/// ```example
/// #let items = (
/// curve.move((15pt, 0pt)),
/// curve.line((0pt, 30pt)),
/// curve.line((30pt, 30pt)),
/// curve.line((10pt, 20pt)),
/// )
///
/// #set curve(stroke: 6pt + blue)
/// #stack(
/// dir: ltr,
/// spacing: 1cm,
/// curve(stroke: (miter-limit: 1), ..items),
/// curve(stroke: (miter-limit: 4), ..items),
/// curve(stroke: (miter-limit: 5), ..items),
/// )
/// ```
#[external]
miter_limit: Smart<f64>,
) -> SourceResult<Stroke> {
if let Some(stroke) = args.eat::<Stroke>()? {
return Ok(stroke);
}
fn take<T: FromValue>(args: &mut Args, arg: &str) -> SourceResult<Smart<T>> {
Ok(args.named::<Smart<T>>(arg)?.unwrap_or(Smart::Auto))
}
let paint = take::<Paint>(args, "paint")?;
let thickness = take::<Length>(args, "thickness")?;
let cap = take::<LineCap>(args, "cap")?;
let join = take::<LineJoin>(args, "join")?;
let dash = take::<Option<DashPattern>>(args, "dash")?;
let miter_limit = take::<f64>(args, "miter-limit")?.map(Scalar::new);
Ok(Self { paint, thickness, cap, join, dash, miter_limit })
}
}
impl<T: Numeric> Stroke<T> {
/// Map the contained lengths with `f`.
pub fn map<F, U: Numeric>(self, f: F) -> Stroke<U>
where
F: Fn(T) -> U,
{
Stroke {
paint: self.paint,
thickness: self.thickness.map(&f),
cap: self.cap,
join: self.join,
dash: self.dash.map(|dash| {
dash.map(|dash| DashPattern {
array: dash
.array
.into_iter()
.map(|l| match l {
DashLength::Length(v) => DashLength::Length(f(v)),
DashLength::LineWidth => DashLength::LineWidth,
})
.collect(),
phase: f(dash.phase),
})
}),
miter_limit: self.miter_limit,
}
}
}
impl Stroke<Abs> {
/// Unpack the stroke, filling missing fields from the `default`.
pub fn unwrap_or(self, default: FixedStroke) -> FixedStroke {
let thickness = self.thickness.unwrap_or(default.thickness);
let dash = self
.dash
.map(|dash| {
dash.map(|dash| DashPattern {
array: dash.array.into_iter().map(|l| l.finish(thickness)).collect(),
phase: dash.phase,
})
})
.unwrap_or(default.dash);
FixedStroke {
paint: self.paint.unwrap_or(default.paint),
thickness,
cap: self.cap.unwrap_or(default.cap),
join: self.join.unwrap_or(default.join),
dash,
miter_limit: self.miter_limit.unwrap_or(default.miter_limit),
}
}
/// Unpack the stroke, filling missing fields with the default values.
pub fn unwrap_or_default(self) -> FixedStroke {
// we want to do this; the Clippy lint is not type-aware
#[allow(clippy::unwrap_or_default)]
self.unwrap_or(FixedStroke::default())
}
}
impl<T: Numeric + Repr> Repr for Stroke<T> {
fn repr(&self) -> EcoString {
let mut r = EcoString::new();
let Self { paint, thickness, cap, join, dash, miter_limit } = &self;
if cap.is_auto() && join.is_auto() && dash.is_auto() && miter_limit.is_auto() {
match (&self.paint, &self.thickness) {
(Smart::Custom(paint), Smart::Custom(thickness)) => {
r.push_str(&thickness.repr());
r.push_str(" + ");
r.push_str(&paint.repr());
}
(Smart::Custom(paint), Smart::Auto) => r.push_str(&paint.repr()),
(Smart::Auto, Smart::Custom(thickness)) => r.push_str(&thickness.repr()),
(Smart::Auto, Smart::Auto) => r.push_str("1pt + black"),
}
} else {
r.push('(');
let mut sep = "";
if let Smart::Custom(paint) = &paint {
r.push_str(sep);
r.push_str("paint: ");
r.push_str(&paint.repr());
sep = ", ";
}
if let Smart::Custom(thickness) = &thickness {
r.push_str(sep);
r.push_str("thickness: ");
r.push_str(&thickness.repr());
sep = ", ";
}
if let Smart::Custom(cap) = &cap {
r.push_str(sep);
r.push_str("cap: ");
r.push_str(&cap.repr());
sep = ", ";
}
if let Smart::Custom(join) = &join {
r.push_str(sep);
r.push_str("join: ");
r.push_str(&join.repr());
sep = ", ";
}
if let Smart::Custom(dash) = &dash {
r.push_str(sep);
r.push_str("dash: ");
if let Some(dash) = dash {
r.push_str(&dash.repr());
} else {
r.push_str(&NoneValue.repr());
}
sep = ", ";
}
if let Smart::Custom(miter_limit) = &miter_limit {
r.push_str(sep);
r.push_str("miter-limit: ");
r.push_str(&miter_limit.get().repr());
}
r.push(')');
}
r
}
}
impl<T: Numeric + Fold> Fold for Stroke<T> {
fn fold(self, outer: Self) -> Self {
Self {
paint: self.paint.or(outer.paint),
thickness: self.thickness.or(outer.thickness),
cap: self.cap.or(outer.cap),
join: self.join.or(outer.join),
dash: self.dash.or(outer.dash),
miter_limit: self.miter_limit.or(outer.miter_limit),
}
}
}
impl Resolve for Stroke {
type Output = Stroke<Abs>;
fn resolve(self, styles: StyleChain) -> Self::Output {
Stroke {
paint: self.paint,
thickness: self.thickness.resolve(styles),
cap: self.cap,
join: self.join,
dash: self.dash.resolve(styles),
miter_limit: self.miter_limit,
}
}
}
cast! {
type Stroke,
thickness: Length => Self {
thickness: Smart::Custom(thickness),
..Default::default()
},
color: Color => Self {
paint: Smart::Custom(color.into()),
..Default::default()
},
gradient: Gradient => Self {
paint: Smart::Custom(gradient.into()),
..Default::default()
},
tiling: Tiling => Self {
paint: Smart::Custom(tiling.into()),
..Default::default()
},
mut dict: Dict => {
// Get a value by key, accepting either Auto or something convertible to type T.
fn take<T: FromValue>(dict: &mut Dict, key: &str) -> HintedStrResult<Smart<T>> {
Ok(dict.take(key).ok().map(Smart::<T>::from_value)
.transpose()?.unwrap_or(Smart::Auto))
}
let paint = take::<Paint>(&mut dict, "paint")?;
let thickness = take::<Length>(&mut dict, "thickness")?;
let cap = take::<LineCap>(&mut dict, "cap")?;
let join = take::<LineJoin>(&mut dict, "join")?;
let dash = take::<Option<DashPattern>>(&mut dict, "dash")?;
let miter_limit = take::<f64>(&mut dict, "miter-limit")?;
dict.finish(&["paint", "thickness", "cap", "join", "dash", "miter-limit"])?;
Self {
paint,
thickness,
cap,
join,
dash,
miter_limit: miter_limit.map(Scalar::new),
}
},
}
cast! {
Stroke<Abs>,
self => self.map(Length::from).into_value(),
}
/// The line cap of a stroke
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum LineCap {
/// Square stroke cap with the edge at the stroke's end point.
Butt,
/// Circular stroke cap centered at the stroke's end point.
Round,
/// Square stroke cap centered at the stroke's end point.
Square,
}
impl Repr for LineCap {
fn repr(&self) -> EcoString {
match self {
Self::Butt => "butt".repr(),
Self::Round => "round".repr(),
Self::Square => "square".repr(),
}
}
}
/// The line join of a stroke
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum LineJoin {
/// Segments are joined with sharp edges. Sharp bends exceeding the miter
/// limit are bevelled instead.
Miter,
/// Segments are joined with circular corners.
Round,
/// Segments are joined with a bevel (a straight edge connecting the butts
/// of the joined segments).
Bevel,
}
impl Repr for LineJoin {
fn repr(&self) -> EcoString {
match self {
Self::Miter => "miter".repr(),
Self::Round => "round".repr(),
Self::Bevel => "bevel".repr(),
}
}
}
/// A line dash pattern.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct DashPattern<T: Numeric = Length, DT = DashLength<T>> {
/// The dash array.
pub array: Vec<DT>,
/// The dash phase.
pub phase: T,
}
impl<T: Numeric + Repr, DT: Repr> Repr for DashPattern<T, DT> {
fn repr(&self) -> EcoString {
let mut r = EcoString::from("(array: (");
for (i, elem) in self.array.iter().enumerate() {
if i != 0 {
r.push_str(", ")
}
r.push_str(&elem.repr())
}
r.push_str("), phase: ");
r.push_str(&self.phase.repr());
r.push(')');
r
}
}
impl<T: Numeric + Default> From<Vec<DashLength<T>>> for DashPattern<T> {
fn from(array: Vec<DashLength<T>>) -> Self {
Self { array, phase: T::default() }
}
}
impl Resolve for DashPattern {
type Output = DashPattern<Abs>;
fn resolve(self, styles: StyleChain) -> Self::Output {
DashPattern {
array: self.array.into_iter().map(|l| l.resolve(styles)).collect(),
phase: self.phase.resolve(styles),
}
}
}
// Same names as tikz:
// https://tex.stackexchange.com/questions/45275/tikz-get-values-for-predefined-dash-patterns
cast! {
DashPattern,
self => dict! { "array" => self.array, "phase" => self.phase }.into_value(),
"solid" => Vec::new().into(),
"dotted" => vec![DashLength::LineWidth, Abs::pt(2.0).into()].into(),
"densely-dotted" => vec![DashLength::LineWidth, Abs::pt(1.0).into()].into(),
"loosely-dotted" => vec![DashLength::LineWidth, Abs::pt(4.0).into()].into(),
"dashed" => vec![Abs::pt(3.0).into(), Abs::pt(3.0).into()].into(),
"densely-dashed" => vec![Abs::pt(3.0).into(), Abs::pt(2.0).into()].into(),
"loosely-dashed" => vec![Abs::pt(3.0).into(), Abs::pt(6.0).into()].into(),
"dash-dotted" => vec![Abs::pt(3.0).into(), Abs::pt(2.0).into(), DashLength::LineWidth, Abs::pt(2.0).into()].into(),
"densely-dash-dotted" => vec![Abs::pt(3.0).into(), Abs::pt(1.0).into(), DashLength::LineWidth, Abs::pt(1.0).into()].into(),
"loosely-dash-dotted" => vec![Abs::pt(3.0).into(), Abs::pt(4.0).into(), DashLength::LineWidth, Abs::pt(4.0).into()].into(),
array: Vec<DashLength> => Self { array, phase: Length::zero() },
mut dict: Dict => {
let array: Vec<DashLength> = dict.take("array")?.cast()?;
let phase = dict.take("phase").ok().map(Value::cast)
.transpose()?.unwrap_or(Length::zero());
dict.finish(&["array", "phase"])?;
Self {
array,
phase,
}
},
}
/// The length of a dash in a line dash pattern.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum DashLength<T: Numeric = Length> {
LineWidth,
Length(T),
}
impl<T: Numeric> DashLength<T> {
fn finish(self, line_width: T) -> T {
match self {
Self::LineWidth => line_width,
Self::Length(l) => l,
}
}
}
impl<T: Numeric + Repr> Repr for DashLength<T> {
fn repr(&self) -> EcoString {
match self {
Self::LineWidth => "dot".repr(),
Self::Length(v) => v.repr(),
}
}
}
impl Resolve for DashLength {
type Output = DashLength<Abs>;
fn resolve(self, styles: StyleChain) -> Self::Output {
match self {
Self::LineWidth => DashLength::LineWidth,
Self::Length(v) => DashLength::Length(v.resolve(styles)),
}
}
}
impl From<Abs> for DashLength {
fn from(l: Abs) -> Self {
DashLength::Length(l.into())
}
}
cast! {
DashLength,
self => match self {
Self::LineWidth => "dot".into_value(),
Self::Length(v) => v.into_value(),
},
"dot" => Self::LineWidth,
v: Length => Self::Length(v),
}
/// A fully specified stroke of a geometric shape.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct FixedStroke {
/// The stroke's paint.
pub paint: Paint,
/// The stroke's thickness.
pub thickness: Abs,
/// The stroke's line cap.
pub cap: LineCap,
/// The stroke's line join.
pub join: LineJoin,
/// The stroke's line dash pattern.
pub dash: Option<DashPattern<Abs, Abs>>,
/// The miter limit. Defaults to 4.0, same as `tiny-skia`.
pub miter_limit: Scalar,
}
impl FixedStroke {
/// Create a stroke from a paint and a thickness.
pub fn from_pair(paint: impl Into<Paint>, thickness: Abs) -> Self {
Self {
paint: paint.into(),
thickness,
..Default::default()
}
}
}
impl Default for FixedStroke {
fn default() -> Self {
Self {
paint: Paint::Solid(Color::BLACK),
thickness: Abs::pt(1.0),
cap: LineCap::Butt,
join: LineJoin::Miter,
dash: None,
miter_limit: Scalar::new(4.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/visualize/paint.rs | crates/typst-library/src/visualize/paint.rs | use std::fmt::{self, Debug, Formatter};
use ecow::EcoString;
use crate::foundations::{Repr, Smart, cast};
use crate::visualize::{Color, Gradient, RelativeTo, Tiling};
/// How a fill or stroke should be painted.
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum Paint {
/// A solid color.
Solid(Color),
/// A gradient.
Gradient(Gradient),
/// A tiling.
Tiling(Tiling),
}
impl Paint {
/// Unwraps a solid color used for text rendering.
pub fn unwrap_solid(&self) -> Color {
match self {
Self::Solid(color) => *color,
Self::Gradient(_) | Self::Tiling(_) => panic!("expected solid color"),
}
}
/// Gets the relative coordinate system for this paint.
pub fn relative(&self) -> Smart<RelativeTo> {
match self {
Self::Solid(_) => Smart::Auto,
Self::Gradient(gradient) => gradient.relative(),
Self::Tiling(tiling) => tiling.relative(),
}
}
/// Turns this paint into a paint for a text decoration.
///
/// If this paint is a gradient, it will be converted to a gradient with
/// relative set to [`RelativeTo::Parent`].
pub fn as_decoration(&self) -> Self {
match self {
Self::Solid(color) => Self::Solid(*color),
Self::Gradient(gradient) => {
Self::Gradient(gradient.clone().with_relative(RelativeTo::Parent))
}
Self::Tiling(tiling) => {
Self::Tiling(tiling.clone().with_relative(RelativeTo::Parent))
}
}
}
}
impl Debug for Paint {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Solid(v) => v.fmt(f),
Self::Gradient(v) => v.fmt(f),
Self::Tiling(v) => v.fmt(f),
}
}
}
impl From<Tiling> for Paint {
fn from(tiling: Tiling) -> Self {
Self::Tiling(tiling)
}
}
impl Repr for Paint {
fn repr(&self) -> EcoString {
match self {
Self::Solid(color) => color.repr(),
Self::Gradient(gradient) => gradient.repr(),
Self::Tiling(tiling) => tiling.repr(),
}
}
}
impl<T: Into<Color>> From<T> for Paint {
fn from(t: T) -> Self {
Self::Solid(t.into())
}
}
impl From<Gradient> for Paint {
fn from(gradient: Gradient) -> Self {
Self::Gradient(gradient)
}
}
cast! {
Paint,
self => match self {
Self::Solid(color) => color.into_value(),
Self::Gradient(gradient) => gradient.into_value(),
Self::Tiling(tiling) => tiling.into_value(),
},
color: Color => Self::Solid(color),
gradient: Gradient => Self::Gradient(gradient),
tiling: Tiling => Self::Tiling(tiling),
}
| 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/visualize/path.rs | crates/typst-library/src/visualize/path.rs | use self::PathVertex::{AllControlPoints, MirroredControlPoint, Vertex};
use crate::diag::bail;
use crate::foundations::{Array, Reflect, Smart, array, cast, elem};
use crate::layout::{Axes, Length, Rel};
use crate::visualize::{FillRule, Paint, Stroke};
/// A path through a list of points, connected by Bézier curves.
///
/// # Example
/// ```example
/// #path(
/// fill: blue.lighten(80%),
/// stroke: blue,
/// closed: true,
/// (0pt, 50pt),
/// (100%, 50pt),
/// ((50%, 0pt), (40pt, 0pt)),
/// )
/// ```
#[elem]
pub struct PathElem {
/// How to fill the path.
///
/// When setting a fill, the default stroke disappears. To create a
/// rectangle with both fill and stroke, you have to configure both.
pub fill: Option<Paint>,
/// The drawing rule used to fill the path.
///
/// ```example
/// // We use `.with` to get a new
/// // function that has the common
/// // arguments pre-applied.
/// #let star = path.with(
/// fill: red,
/// closed: true,
/// (25pt, 0pt),
/// (10pt, 50pt),
/// (50pt, 20pt),
/// (0pt, 20pt),
/// (40pt, 50pt),
/// )
///
/// #star(fill-rule: "non-zero")
/// #star(fill-rule: "even-odd")
/// ```
#[default]
pub fill_rule: FillRule,
/// How to [stroke] the path.
///
/// Can be set to `{none}` to disable the stroke or to `{auto}` for a
/// stroke of `{1pt}` black if and only if no fill is given.
#[fold]
pub stroke: Smart<Option<Stroke>>,
/// Whether to close this path with one last Bézier curve. This curve will
/// take into account the adjacent control points. If you want to close
/// with a straight line, simply add one last point that's the same as the
/// start point.
#[default(false)]
pub closed: bool,
/// The vertices of the path.
///
/// Each vertex can be defined in 3 ways:
///
/// - A regular point, as given to the [`line`] or [`polygon`] function.
/// - An array of two points, the first being the vertex and the second
/// being the control point. The control point is expressed relative to
/// the vertex and is mirrored to get the second control point. The given
/// control point is the one that affects the curve coming _into_ this
/// vertex (even for the first point). The mirrored control point affects
/// the curve going out of this vertex.
/// - An array of three points, the first being the vertex and the next
/// being the control points (control point for curves coming in and out,
/// respectively).
#[variadic]
pub vertices: Vec<PathVertex>,
}
/// A component used for path creation.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum PathVertex {
Vertex(Axes<Rel<Length>>),
MirroredControlPoint(Axes<Rel<Length>>, Axes<Rel<Length>>),
AllControlPoints(Axes<Rel<Length>>, Axes<Rel<Length>>, Axes<Rel<Length>>),
}
impl PathVertex {
pub fn vertex(&self) -> Axes<Rel<Length>> {
match self {
Vertex(x) => *x,
MirroredControlPoint(x, _) => *x,
AllControlPoints(x, _, _) => *x,
}
}
pub fn control_point_from(&self) -> Axes<Rel<Length>> {
match self {
Vertex(_) => Axes::new(Rel::zero(), Rel::zero()),
MirroredControlPoint(_, a) => a.map(|x| -x),
AllControlPoints(_, _, b) => *b,
}
}
pub fn control_point_to(&self) -> Axes<Rel<Length>> {
match self {
Vertex(_) => Axes::new(Rel::zero(), Rel::zero()),
MirroredControlPoint(_, a) => *a,
AllControlPoints(_, a, _) => *a,
}
}
}
cast! {
PathVertex,
self => match self {
Vertex(x) => x.into_value(),
MirroredControlPoint(x, c) => array![x, c].into_value(),
AllControlPoints(x, c1, c2) => array![x, c1, c2].into_value(),
},
array: Array => {
let mut iter = array.into_iter();
match (iter.next(), iter.next(), iter.next(), iter.next()) {
(Some(a), None, None, None) => {
Vertex(a.cast()?)
},
(Some(a), Some(b), None, None) => {
if Axes::<Rel<Length>>::castable(&a) {
MirroredControlPoint(a.cast()?, b.cast()?)
} else {
Vertex(Axes::new(a.cast()?, b.cast()?))
}
},
(Some(a), Some(b), Some(c), None) => {
AllControlPoints(a.cast()?, b.cast()?, c.cast()?)
},
_ => bail!("path vertex must have 1, 2, or 3 points"),
}
},
}
| 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/visualize/shape.rs | crates/typst-library/src/visualize/shape.rs | use crate::foundations::{Cast, Content, Smart, elem};
use crate::layout::{Abs, Corners, Length, Point, Rect, Rel, Sides, Size, Sizing};
use crate::visualize::{Curve, FixedStroke, Paint, Stroke};
/// A rectangle with optional content.
///
/// # Example
/// ```example
/// // Without content.
/// #rect(width: 35%, height: 30pt)
///
/// // With content.
/// #rect[
/// Automatically sized \
/// to fit the content.
/// ]
/// ```
#[elem(title = "Rectangle")]
pub struct RectElem {
/// The rectangle's width, relative to its parent container.
pub width: Smart<Rel<Length>>,
/// The rectangle's height, relative to its parent container.
pub height: Sizing,
/// How to fill the rectangle.
///
/// When setting a fill, the default stroke disappears. To create a
/// rectangle with both fill and stroke, you have to configure both.
///
/// ```example
/// #rect(fill: blue)
/// ```
pub fill: Option<Paint>,
/// How to stroke the rectangle. This can be:
///
/// - `{none}` to disable stroking
///
/// - `{auto}` for a stroke of `{1pt + black}` if and only if no fill is
/// given.
///
/// - Any kind of [stroke]
///
/// - A dictionary describing the stroke for each side individually. The
/// dictionary can contain the following keys in order of precedence:
///
/// - `top`: The top stroke.
/// - `right`: The right stroke.
/// - `bottom`: The bottom stroke.
/// - `left`: The left stroke.
/// - `x`: The left and right stroke.
/// - `y`: The top and bottom stroke.
/// - `rest`: The stroke on all sides except those for which the
/// dictionary explicitly sets a size.
///
/// All keys are optional; omitted keys will use their previously set
/// value, or the default stroke if never set.
///
/// ```example
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// rect(stroke: red),
/// rect(stroke: 2pt),
/// rect(stroke: 2pt + red),
/// )
/// ```
#[fold]
pub stroke: Smart<Sides<Option<Option<Stroke>>>>,
/// How much to round the rectangle's corners, relative to the minimum of
/// the width and height divided by two. This can be:
///
/// - A relative length for a uniform corner radius.
///
/// - A dictionary: With a dictionary, the stroke for each side can be set
/// individually. The dictionary can contain the following keys in order
/// of precedence:
/// - `top-left`: The top-left corner radius.
/// - `top-right`: The top-right corner radius.
/// - `bottom-right`: The bottom-right corner radius.
/// - `bottom-left`: The bottom-left corner radius.
/// - `left`: The top-left and bottom-left corner radii.
/// - `top`: The top-left and top-right corner radii.
/// - `right`: The top-right and bottom-right corner radii.
/// - `bottom`: The bottom-left and bottom-right corner radii.
/// - `rest`: The radii for all corners except those for which the
/// dictionary explicitly sets a size.
///
/// ```example
/// #set rect(stroke: 4pt)
/// #rect(
/// radius: (
/// left: 5pt,
/// top-right: 20pt,
/// bottom-right: 10pt,
/// ),
/// stroke: (
/// left: red,
/// top: yellow,
/// right: green,
/// bottom: blue,
/// ),
/// )
/// ```
#[fold]
pub radius: Corners<Option<Rel<Length>>>,
/// How much to pad the rectangle's content.
/// See the [box's documentation]($box.inset) for more details.
#[fold]
#[default(Sides::splat(Some(Abs::pt(5.0).into())))]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the rectangle's size without affecting the layout.
/// See the [box's documentation]($box.outset) for more details.
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// The content to place into the rectangle.
///
/// When this is omitted, the rectangle takes on a default size of at most
/// `{45pt}` by `{30pt}`.
#[positional]
pub body: Option<Content>,
}
/// A square with optional content.
///
/// # Example
/// ```example
/// // Without content.
/// #square(size: 40pt)
///
/// // With content.
/// #square[
/// Automatically \
/// sized to fit.
/// ]
/// ```
#[elem]
pub struct SquareElem {
/// The square's side length. This is mutually exclusive with `width` and
/// `height`.
#[external]
pub size: Smart<Length>,
/// The square's width. This is mutually exclusive with `size` and `height`.
///
/// In contrast to `size`, this can be relative to the parent container's
/// width.
#[parse(
let size = args.named::<Smart<Length>>("size")?.map(|s| s.map(Rel::from));
match size {
None => args.named("width")?,
size => size,
}
)]
pub width: Smart<Rel<Length>>,
/// The square's height. This is mutually exclusive with `size` and `width`.
///
/// In contrast to `size`, this can be relative to the parent container's
/// height.
#[parse(match size {
None => args.named("height")?,
size => size.map(Into::into),
})]
pub height: Sizing,
/// How to fill the square. See the [rectangle's documentation]($rect.fill)
/// for more details.
pub fill: Option<Paint>,
/// How to stroke the square. See the
/// [rectangle's documentation]($rect.stroke) for more details.
#[fold]
pub stroke: Smart<Sides<Option<Option<Stroke>>>>,
/// How much to round the square's corners. See the
/// [rectangle's documentation]($rect.radius) for more details.
#[fold]
pub radius: Corners<Option<Rel<Length>>>,
/// How much to pad the square's content. See the
/// [box's documentation]($box.inset) for more details.
#[fold]
#[default(Sides::splat(Some(Abs::pt(5.0).into())))]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the square's size without affecting the layout. See
/// the [box's documentation]($box.outset) for more details.
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// The content to place into the square. The square expands to fit this
/// content, keeping the 1-1 aspect ratio.
///
/// When this is omitted, the square takes on a default size of at most
/// `{30pt}`.
#[positional]
pub body: Option<Content>,
}
/// An ellipse with optional content.
///
/// # Example
/// ```example
/// // Without content.
/// #ellipse(width: 35%, height: 30pt)
///
/// // With content.
/// #ellipse[
/// #set align(center)
/// Automatically sized \
/// to fit the content.
/// ]
/// ```
#[elem]
pub struct EllipseElem {
/// The ellipse's width, relative to its parent container.
pub width: Smart<Rel<Length>>,
/// The ellipse's height, relative to its parent container.
pub height: Sizing,
/// How to fill the ellipse. See the [rectangle's documentation]($rect.fill)
/// for more details.
pub fill: Option<Paint>,
/// How to stroke the ellipse. See the
/// [rectangle's documentation]($rect.stroke) for more details.
#[fold]
pub stroke: Smart<Option<Stroke>>,
/// How much to pad the ellipse's content. See the
/// [box's documentation]($box.inset) for more details.
#[fold]
#[default(Sides::splat(Some(Abs::pt(5.0).into())))]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the ellipse's size without affecting the layout. See
/// the [box's documentation]($box.outset) for more details.
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// The content to place into the ellipse.
///
/// When this is omitted, the ellipse takes on a default size of at most
/// `{45pt}` by `{30pt}`.
#[positional]
pub body: Option<Content>,
}
/// A circle with optional content.
///
/// # Example
/// ```example
/// // Without content.
/// #circle(radius: 25pt)
///
/// // With content.
/// #circle[
/// #set align(center + horizon)
/// Automatically \
/// sized to fit.
/// ]
/// ```
#[elem]
pub struct CircleElem {
/// The circle's radius. This is mutually exclusive with `width` and
/// `height`.
#[external]
pub radius: Length,
/// The circle's width. This is mutually exclusive with `radius` and
/// `height`.
///
/// In contrast to `radius`, this can be relative to the parent container's
/// width.
#[parse(
let size = args
.named::<Smart<Length>>("radius")?
.map(|s| s.map(|r| 2.0 * Rel::from(r)));
match size {
None => args.named("width")?,
size => size,
}
)]
pub width: Smart<Rel<Length>>,
/// The circle's height. This is mutually exclusive with `radius` and
/// `width`.
///
/// In contrast to `radius`, this can be relative to the parent container's
/// height.
#[parse(match size {
None => args.named("height")?,
size => size.map(Into::into),
})]
pub height: Sizing,
/// How to fill the circle. See the [rectangle's documentation]($rect.fill)
/// for more details.
pub fill: Option<Paint>,
/// How to stroke the circle. See the
/// [rectangle's documentation]($rect.stroke) for more details.
#[fold]
#[default(Smart::Auto)]
pub stroke: Smart<Option<Stroke>>,
/// How much to pad the circle's content. See the
/// [box's documentation]($box.inset) for more details.
#[fold]
#[default(Sides::splat(Some(Abs::pt(5.0).into())))]
pub inset: Sides<Option<Rel<Length>>>,
/// How much to expand the circle's size without affecting the layout. See
/// the [box's documentation]($box.outset) for more details.
#[fold]
pub outset: Sides<Option<Rel<Length>>>,
/// The content to place into the circle. The circle expands to fit this
/// content, keeping the 1-1 aspect ratio.
#[positional]
pub body: Option<Content>,
}
/// A geometric shape with optional fill and stroke.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Shape {
/// The shape's geometry.
pub geometry: Geometry,
/// The shape's background fill.
pub fill: Option<Paint>,
/// The shape's fill rule.
pub fill_rule: FillRule,
/// The shape's border stroke.
pub stroke: Option<FixedStroke>,
}
/// A fill rule for curve drawing.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FillRule {
/// Specifies that "inside" is computed by a non-zero sum of signed edge crossings.
#[default]
NonZero,
/// Specifies that "inside" is computed by an odd number of edge crossings.
EvenOdd,
}
/// A shape's geometry.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Geometry {
/// A line to a point (relative to its position).
Line(Point),
/// A rectangle with its origin in the topleft corner.
Rect(Size),
/// A curve consisting of movements, lines, and Bézier segments.
Curve(Curve),
}
impl Geometry {
/// Fill the geometry without a stroke.
pub fn filled(self, fill: impl Into<Paint>) -> Shape {
Shape {
geometry: self,
fill: Some(fill.into()),
fill_rule: FillRule::default(),
stroke: None,
}
}
/// Stroke the geometry without a fill.
pub fn stroked(self, stroke: FixedStroke) -> Shape {
Shape {
geometry: self,
fill: None,
fill_rule: FillRule::default(),
stroke: Some(stroke),
}
}
/// The bounding box of the geometry.
pub fn bbox(&self) -> Rect {
match self {
Self::Line(end) => {
let min = end.min(Point::zero());
let max = end.max(Point::zero());
Rect::new(min, max)
}
Self::Rect(size) => {
let p = size.to_point();
let min = p.min(Point::zero());
let max = p.max(Point::zero());
Rect::new(min, max)
}
Self::Curve(curve) => curve.bbox(),
}
}
/// The bounding box of the geometry.
pub fn bbox_size(&self) -> Size {
match self {
Self::Line(line) => Size::new(line.x, line.y),
Self::Rect(rect) => *rect,
Self::Curve(curve) => curve.bbox_size(),
}
}
}
| 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/visualize/curve.rs | crates/typst-library/src/visualize/curve.rs | use kurbo::ParamCurveExtrema;
use typst_macros::{Cast, scope};
use typst_utils::Numeric;
use crate::diag::{HintedStrResult, HintedString, bail};
use crate::foundations::{Content, Packed, Smart, cast, elem};
use crate::layout::{Abs, Axes, Length, Point, Rect, Rel, Size};
use crate::visualize::{FillRule, Paint, Stroke};
use super::FixedStroke;
/// A curve consisting of movements, lines, and Bézier segments.
///
/// At any point in time, there is a conceptual pen or cursor.
/// - Move elements move the cursor without drawing.
/// - Line/Quadratic/Cubic elements draw a segment from the cursor to a new
/// position, potentially with control point for a Bézier curve.
/// - Close elements draw a straight or smooth line back to the start of the
/// curve or the latest preceding move segment.
///
/// For layout purposes, the bounding box of the curve is a tight rectangle
/// containing all segments as well as the point `{(0pt, 0pt)}`.
///
/// Positions may be specified absolutely (i.e. relatively to `{(0pt, 0pt)}`),
/// or relative to the current pen/cursor position, that is, the position where
/// the previous segment ended.
///
/// Bézier curve control points can be skipped by passing `{none}` or
/// automatically mirrored from the preceding segment by passing `{auto}`.
///
/// # Example
/// ```example
/// #curve(
/// fill: blue.lighten(80%),
/// stroke: blue,
/// curve.move((0pt, 50pt)),
/// curve.line((100pt, 50pt)),
/// curve.cubic(none, (90pt, 0pt), (50pt, 0pt)),
/// curve.close(),
/// )
/// ```
#[elem(scope)]
pub struct CurveElem {
/// How to fill the curve.
///
/// When setting a fill, the default stroke disappears. To create a curve
/// with both fill and stroke, you have to configure both.
pub fill: Option<Paint>,
/// The drawing rule used to fill the curve.
///
/// ```example
/// // We use `.with` to get a new
/// // function that has the common
/// // arguments pre-applied.
/// #let star = curve.with(
/// fill: red,
/// curve.move((25pt, 0pt)),
/// curve.line((10pt, 50pt)),
/// curve.line((50pt, 20pt)),
/// curve.line((0pt, 20pt)),
/// curve.line((40pt, 50pt)),
/// curve.close(),
/// )
///
/// #star(fill-rule: "non-zero")
/// #star(fill-rule: "even-odd")
/// ```
#[default]
pub fill_rule: FillRule,
/// How to [stroke] the curve.
///
/// Can be set to `{none}` to disable the stroke or to `{auto}` for a
/// stroke of `{1pt}` black if and only if no fill is given.
///
/// ```example
/// #let down = curve.line((40pt, 40pt), relative: true)
/// #let up = curve.line((40pt, -40pt), relative: true)
///
/// #curve(
/// stroke: 4pt + gradient.linear(red, blue),
/// down, up, down, up, down,
/// )
/// ```
#[fold]
pub stroke: Smart<Option<Stroke>>,
/// The components of the curve, in the form of moves, line and Bézier
/// segment, and closes.
#[variadic]
pub components: Vec<CurveComponent>,
}
#[scope]
impl CurveElem {
#[elem]
type CurveMove;
#[elem]
type CurveLine;
#[elem]
type CurveQuad;
#[elem]
type CurveCubic;
#[elem]
type CurveClose;
}
/// A component used for curve creation.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CurveComponent {
Move(Packed<CurveMove>),
Line(Packed<CurveLine>),
Quad(Packed<CurveQuad>),
Cubic(Packed<CurveCubic>),
Close(Packed<CurveClose>),
}
cast! {
CurveComponent,
self => match self {
Self::Move(element) => element.into_value(),
Self::Line(element) => element.into_value(),
Self::Quad(element) => element.into_value(),
Self::Cubic(element) => element.into_value(),
Self::Close(element) => element.into_value(),
},
v: Content => {
v.try_into()?
}
}
impl TryFrom<Content> for CurveComponent {
type Error = HintedString;
fn try_from(value: Content) -> HintedStrResult<Self> {
value
.into_packed::<CurveMove>()
.map(Self::Move)
.or_else(|value| value.into_packed::<CurveLine>().map(Self::Line))
.or_else(|value| value.into_packed::<CurveQuad>().map(Self::Quad))
.or_else(|value| value.into_packed::<CurveCubic>().map(Self::Cubic))
.or_else(|value| value.into_packed::<CurveClose>().map(Self::Close))
.or_else(|_| bail!("expecting a curve element"))
}
}
/// Starts a new curve component.
///
/// If no `curve.move` element is passed, the curve will start at
/// `{(0pt, 0pt)}`.
///
/// ```example
/// #curve(
/// fill: blue.lighten(80%),
/// fill-rule: "even-odd",
/// stroke: blue,
/// curve.line((50pt, 0pt)),
/// curve.line((50pt, 50pt)),
/// curve.line((0pt, 50pt)),
/// curve.close(),
/// curve.move((10pt, 10pt)),
/// curve.line((40pt, 10pt)),
/// curve.line((40pt, 40pt)),
/// curve.line((10pt, 40pt)),
/// curve.close(),
/// )
/// ```
#[elem(name = "move", title = "Curve Move")]
pub struct CurveMove {
/// The starting point for the new component.
#[required]
pub start: Axes<Rel<Length>>,
/// Whether the coordinates are relative to the previous point.
#[default(false)]
pub relative: bool,
}
/// Adds a straight line from the current point to a following one.
///
/// ```example
/// #curve(
/// stroke: blue,
/// curve.line((50pt, 0pt)),
/// curve.line((50pt, 50pt)),
/// curve.line((100pt, 50pt)),
/// curve.line((100pt, 0pt)),
/// curve.line((150pt, 0pt)),
/// )
/// ```
#[elem(name = "line", title = "Curve Line")]
pub struct CurveLine {
/// The point at which the line shall end.
#[required]
pub end: Axes<Rel<Length>>,
/// Whether the coordinates are relative to the previous point.
///
/// ```example
/// #curve(
/// stroke: blue,
/// curve.line((50pt, 0pt), relative: true),
/// curve.line((0pt, 50pt), relative: true),
/// curve.line((50pt, 0pt), relative: true),
/// curve.line((0pt, -50pt), relative: true),
/// curve.line((50pt, 0pt), relative: true),
/// )
/// ```
#[default(false)]
pub relative: bool,
}
/// Adds a quadratic Bézier curve segment from the last point to `end`, using
/// `control` as the control point.
///
/// ```example
/// // Function to illustrate where the control point is.
/// #let mark((x, y)) = place(
/// dx: x - 1pt, dy: y - 1pt,
/// circle(fill: aqua, radius: 2pt),
/// )
///
/// #mark((20pt, 20pt))
///
/// #curve(
/// stroke: blue,
/// curve.move((0pt, 100pt)),
/// curve.quad((20pt, 20pt), (100pt, 0pt)),
/// )
/// ```
#[elem(name = "quad", title = "Curve Quadratic Segment")]
pub struct CurveQuad {
/// The control point of the quadratic Bézier curve.
///
/// - If `{auto}` and this segment follows another quadratic Bézier curve,
/// the previous control point will be mirrored.
/// - If `{none}`, the control point defaults to `end`, and the curve will
/// be a straight line.
///
/// ```example
/// #curve(
/// stroke: 2pt,
/// curve.quad((20pt, 40pt), (40pt, 40pt), relative: true),
/// curve.quad(auto, (40pt, -40pt), relative: true),
/// )
/// ```
#[required]
pub control: Smart<Option<Axes<Rel<Length>>>>,
/// The point at which the segment shall end.
#[required]
pub end: Axes<Rel<Length>>,
/// Whether the `control` and `end` coordinates are relative to the previous
/// point.
#[default(false)]
pub relative: bool,
}
/// Adds a cubic Bézier curve segment from the last point to `end`, using
/// `control-start` and `control-end` as the control points.
///
/// ```example
/// // Function to illustrate where the control points are.
/// #let handle(start, end) = place(
/// line(stroke: red, start: start, end: end)
/// )
///
/// #handle((0pt, 80pt), (10pt, 20pt))
/// #handle((90pt, 60pt), (100pt, 0pt))
///
/// #curve(
/// stroke: blue,
/// curve.move((0pt, 80pt)),
/// curve.cubic((10pt, 20pt), (90pt, 60pt), (100pt, 0pt)),
/// )
/// ```
#[elem(name = "cubic", title = "Curve Cubic Segment")]
pub struct CurveCubic {
/// The control point going out from the start of the curve segment.
///
/// - If `{auto}` and this element follows another `curve.cubic` element,
/// the last control point will be mirrored. In SVG terms, this makes
/// `curve.cubic` behave like the `S` operator instead of the `C` operator.
///
/// - If `{none}`, the curve has no first control point, or equivalently,
/// the control point defaults to the curve's starting point.
///
/// ```example
/// #curve(
/// stroke: blue,
/// curve.move((0pt, 50pt)),
/// // - No start control point
/// // - End control point at `(20pt, 0pt)`
/// // - End point at `(50pt, 0pt)`
/// curve.cubic(none, (20pt, 0pt), (50pt, 0pt)),
/// // - No start control point
/// // - No end control point
/// // - End point at `(50pt, 0pt)`
/// curve.cubic(none, none, (100pt, 50pt)),
/// )
///
/// #curve(
/// stroke: blue,
/// curve.move((0pt, 50pt)),
/// curve.cubic(none, (20pt, 0pt), (50pt, 0pt)),
/// // Passing `auto` instead of `none` means the start control point
/// // mirrors the end control point of the previous curve. Mirror of
/// // `(20pt, 0pt)` w.r.t `(50pt, 0pt)` is `(80pt, 0pt)`.
/// curve.cubic(auto, none, (100pt, 50pt)),
/// )
///
/// #curve(
/// stroke: blue,
/// curve.move((0pt, 50pt)),
/// curve.cubic(none, (20pt, 0pt), (50pt, 0pt)),
/// // `(80pt, 0pt)` is the same as `auto` in this case.
/// curve.cubic((80pt, 0pt), none, (100pt, 50pt)),
/// )
/// ```
#[required]
pub control_start: Option<Smart<Axes<Rel<Length>>>>,
/// The control point going into the end point of the curve segment.
///
/// If set to `{none}`, the curve has no end control point, or equivalently,
/// the control point defaults to the curve's end point.
#[required]
pub control_end: Option<Axes<Rel<Length>>>,
/// The point at which the curve segment shall end.
#[required]
pub end: Axes<Rel<Length>>,
/// Whether the `control-start`, `control-end`, and `end` coordinates are
/// relative to the previous point.
#[default(false)]
pub relative: bool,
}
/// Closes the curve by adding a segment from the last point to the start of the
/// curve (or the last preceding `curve.move` point).
///
/// ```example
/// // We define a function to show the same shape with
/// // both closing modes.
/// #let shape(mode: "smooth") = curve(
/// fill: blue.lighten(80%),
/// stroke: blue,
/// curve.move((0pt, 50pt)),
/// curve.line((100pt, 50pt)),
/// curve.cubic(auto, (90pt, 0pt), (50pt, 0pt)),
/// curve.close(mode: mode),
/// )
///
/// #shape(mode: "smooth")
/// #shape(mode: "straight")
/// ```
#[elem(name = "close", title = "Curve Close")]
pub struct CurveClose {
/// How to close the curve.
pub mode: CloseMode,
}
/// How to close a curve.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum CloseMode {
/// Closes the curve with a smooth segment that takes into account the
/// control point opposite the start point.
#[default]
Smooth,
/// Closes the curve with a straight line.
Straight,
}
/// A curve consisting of movements, lines, and Bézier segments.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Curve(pub Vec<CurveItem>);
/// An item in a curve.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum CurveItem {
Move(Point),
Line(Point),
Cubic(Point, Point, Point),
Close,
}
impl Curve {
/// Creates an empty curve.
pub const fn new() -> Self {
Self(vec![])
}
/// Creates a curve that describes a rectangle.
pub fn rect(size: Size) -> Self {
let z = Abs::zero();
let point = Point::new;
let mut curve = Self::new();
curve.move_(point(z, z));
curve.line(point(size.x, z));
curve.line(point(size.x, size.y));
curve.line(point(z, size.y));
curve.close();
curve
}
/// Creates a curve that describes an axis-aligned ellipse.
pub fn ellipse(size: Size) -> Self {
// https://stackoverflow.com/a/2007782
let z = Abs::zero();
let rx = size.x / 2.0;
let ry = size.y / 2.0;
let m = 0.551784;
let mx = m * rx;
let my = m * ry;
let point = |x, y| Point::new(x + rx, y + ry);
let mut curve = Curve::new();
curve.move_(point(-rx, z));
curve.cubic(point(-rx, -my), point(-mx, -ry), point(z, -ry));
curve.cubic(point(mx, -ry), point(rx, -my), point(rx, z));
curve.cubic(point(rx, my), point(mx, ry), point(z, ry));
curve.cubic(point(-mx, ry), point(-rx, my), point(-rx, z));
curve
}
/// Push a [`Move`](CurveItem::Move) item.
pub fn move_(&mut self, p: Point) {
self.0.push(CurveItem::Move(p));
}
/// Push a [`Line`](CurveItem::Line) item.
pub fn line(&mut self, p: Point) {
self.0.push(CurveItem::Line(p));
}
/// Push a [`Cubic`](CurveItem::Cubic) item.
pub fn cubic(&mut self, p1: Point, p2: Point, p3: Point) {
self.0.push(CurveItem::Cubic(p1, p2, p3));
}
/// Push a [`Close`](CurveItem::Close) item.
pub fn close(&mut self) {
self.0.push(CurveItem::Close);
}
/// Check if the curve is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Translate all points in this curve by the given offset.
pub fn translate(&mut self, offset: Point) {
if offset.is_zero() {
return;
}
for item in self.0.iter_mut() {
match item {
CurveItem::Move(p) => *p += offset,
CurveItem::Line(p) => *p += offset,
CurveItem::Cubic(p1, p2, p3) => {
*p1 += offset;
*p2 += offset;
*p3 += offset;
}
CurveItem::Close => (),
}
}
}
/// Computes the bounding box of this curve.
pub fn bbox(&self) -> Rect {
let mut min = Point::splat(Abs::inf());
let mut max = Point::splat(-Abs::inf());
let mut cursor = Point::zero();
for item in self.0.iter() {
match item {
CurveItem::Move(to) => {
cursor = *to;
}
CurveItem::Line(to) => {
min = min.min(cursor).min(*to);
max = max.max(cursor).max(*to);
cursor = *to;
}
CurveItem::Cubic(c0, c1, end) => {
let cubic = kurbo::CubicBez::new(
kurbo::Point::new(cursor.x.to_pt(), cursor.y.to_pt()),
kurbo::Point::new(c0.x.to_pt(), c0.y.to_pt()),
kurbo::Point::new(c1.x.to_pt(), c1.y.to_pt()),
kurbo::Point::new(end.x.to_pt(), end.y.to_pt()),
);
let bbox = cubic.bounding_box();
min.x = min.x.min(Abs::pt(bbox.x0)).min(Abs::pt(bbox.x1));
min.y = min.y.min(Abs::pt(bbox.y0)).min(Abs::pt(bbox.y1));
max.x = max.x.max(Abs::pt(bbox.x0)).max(Abs::pt(bbox.x1));
max.y = max.y.max(Abs::pt(bbox.y0)).max(Abs::pt(bbox.y1));
cursor = *end;
}
CurveItem::Close => (),
}
}
Rect::new(min, max)
}
/// Computes the size of the bounding box of this curve.
pub fn bbox_size(&self) -> Size {
self.bbox().size()
}
}
impl Curve {
fn to_kurbo(&self) -> impl Iterator<Item = kurbo::PathEl> + '_ {
use kurbo::PathEl;
self.0.iter().map(|item| match *item {
CurveItem::Move(point) => PathEl::MoveTo(point_to_kurbo(point)),
CurveItem::Line(point) => PathEl::LineTo(point_to_kurbo(point)),
CurveItem::Cubic(point, point1, point2) => PathEl::CurveTo(
point_to_kurbo(point),
point_to_kurbo(point1),
point_to_kurbo(point2),
),
CurveItem::Close => PathEl::ClosePath,
})
}
/// When this curve is interpreted as a clip mask, would it contain `point`?
pub fn contains(&self, fill_rule: FillRule, needle: Point) -> bool {
let kurbo = kurbo::BezPath::from_vec(self.to_kurbo().collect());
let windings = kurbo::Shape::winding(&kurbo, point_to_kurbo(needle));
match fill_rule {
FillRule::NonZero => windings != 0,
FillRule::EvenOdd => windings % 2 != 0,
}
}
/// When this curve is stroked with `stroke`, would the stroke contain
/// `point`?
pub fn stroke_contains(&self, stroke: &FixedStroke, needle: Point) -> bool {
let width = stroke.thickness.to_raw();
let cap = match stroke.cap {
super::LineCap::Butt => kurbo::Cap::Butt,
super::LineCap::Round => kurbo::Cap::Round,
super::LineCap::Square => kurbo::Cap::Square,
};
let join = match stroke.join {
super::LineJoin::Miter => kurbo::Join::Miter,
super::LineJoin::Round => kurbo::Join::Round,
super::LineJoin::Bevel => kurbo::Join::Bevel,
};
let miter_limit = stroke.miter_limit.get();
let mut style = kurbo::Stroke::new(width)
.with_caps(cap)
.with_join(join)
.with_miter_limit(miter_limit);
if let Some(dash) = &stroke.dash {
style = style.with_dashes(
dash.phase.to_raw(),
dash.array.iter().copied().map(Abs::to_raw),
);
}
let opts = kurbo::StrokeOpts::default();
let tolerance = 0.01;
let expanded = kurbo::stroke(self.to_kurbo(), &style, &opts, tolerance);
kurbo::Shape::contains(&expanded, point_to_kurbo(needle))
}
}
fn point_to_kurbo(point: Point) -> kurbo::Point {
kurbo::Point::new(point.x.to_raw(), point.y.to_raw())
}
| 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/visualize/polygon.rs | crates/typst-library/src/visualize/polygon.rs | use std::f64::consts::PI;
use typst_syntax::Span;
use crate::foundations::{Content, NativeElement, Smart, elem, func, scope};
use crate::layout::{Axes, Em, Length, Rel};
use crate::visualize::{FillRule, Paint, Stroke};
/// A closed polygon.
///
/// The polygon is defined by its corner points and is closed automatically.
///
/// # Example
/// ```example
/// #polygon(
/// fill: blue.lighten(80%),
/// stroke: blue,
/// (20%, 0pt),
/// (60%, 0pt),
/// (80%, 2cm),
/// (0%, 2cm),
/// )
/// ```
#[elem(scope)]
pub struct PolygonElem {
/// How to fill the polygon.
///
/// When setting a fill, the default stroke disappears. To create a
/// rectangle with both fill and stroke, you have to configure both.
pub fill: Option<Paint>,
/// The drawing rule used to fill the polygon.
///
/// See the [curve documentation]($curve.fill-rule) for an example.
#[default]
pub fill_rule: FillRule,
/// How to [stroke] the polygon.
///
/// Can be set to `{none}` to disable the stroke or to `{auto}` for a
/// stroke of `{1pt}` black if and only if no fill is given.
#[fold]
pub stroke: Smart<Option<Stroke>>,
/// The vertices of the polygon. Each point is specified as an array of two
/// [relative lengths]($relative).
#[variadic]
pub vertices: Vec<Axes<Rel<Length>>>,
}
#[scope]
impl PolygonElem {
/// A regular polygon, defined by its size and number of vertices.
///
/// ```example
/// #polygon.regular(
/// fill: blue.lighten(80%),
/// stroke: blue,
/// size: 30pt,
/// vertices: 3,
/// )
/// ```
#[func(title = "Regular Polygon")]
pub fn regular(
span: Span,
/// How to fill the polygon. See the general
/// [polygon's documentation]($polygon.fill) for more details.
#[named]
fill: Option<Option<Paint>>,
/// How to stroke the polygon. See the general
/// [polygon's documentation]($polygon.stroke) for more details.
#[named]
stroke: Option<Smart<Option<Stroke>>>,
/// The diameter of the [circumcircle](https://en.wikipedia.org/wiki/Circumcircle)
/// of the regular polygon.
#[named]
#[default(Em::one().into())]
size: Length,
/// The number of vertices in the polygon.
#[named]
#[default(3)]
vertices: u64,
) -> Content {
let radius = size / 2.0;
let angle = |i: f64| {
2.0 * PI * i / (vertices as f64) + PI * (1.0 / 2.0 - 1.0 / vertices as f64)
};
let (horizontal_offset, vertical_offset) = (0..=vertices)
.map(|v| {
(
(radius * angle(v as f64).cos()) + radius,
(radius * angle(v as f64).sin()) + radius,
)
})
.fold((radius, radius), |(min_x, min_y), (v_x, v_y)| {
(
if min_x < v_x { min_x } else { v_x },
if min_y < v_y { min_y } else { v_y },
)
});
let vertices = (0..=vertices)
.map(|v| {
let x = (radius * angle(v as f64).cos()) + radius - horizontal_offset;
let y = (radius * angle(v as f64).sin()) + radius - vertical_offset;
Axes::new(x, y).map(Rel::from)
})
.collect();
let mut elem = PolygonElem::new(vertices);
if let Some(fill) = fill {
elem.fill.set(fill);
}
if let Some(stroke) = stroke {
elem.stroke.set(stroke);
}
elem.pack().spanned(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/visualize/mod.rs | crates/typst-library/src/visualize/mod.rs | //! Drawing and visualization.
mod color;
mod curve;
mod gradient;
mod image;
mod line;
mod paint;
mod path;
mod polygon;
mod shape;
mod stroke;
mod tiling;
pub use self::color::*;
pub use self::curve::*;
pub use self::gradient::*;
pub use self::image::*;
pub use self::line::*;
pub use self::paint::*;
pub use self::path::*;
pub use self::polygon::*;
pub use self::shape::*;
pub use self::stroke::*;
pub use self::tiling::*;
use crate::foundations::Deprecation;
use crate::foundations::{Element, Scope, Type};
/// Hook up all visualize definitions.
pub(super) fn define(global: &mut Scope) {
global.start_category(crate::Category::Visualize);
global.define_type::<Color>();
global.define_type::<Gradient>();
global.define_type::<Tiling>();
global.define_type::<Stroke>();
global.define_elem::<ImageElem>();
global.define_elem::<LineElem>();
global.define_elem::<RectElem>();
global.define_elem::<SquareElem>();
global.define_elem::<EllipseElem>();
global.define_elem::<CircleElem>();
global.define_elem::<PolygonElem>();
global.define_elem::<CurveElem>();
global.define("path", Element::of::<PathElem>()).deprecated(
Deprecation::new()
.with_message("the `path` function is deprecated, use `curve` instead"),
);
global.define("pattern", Type::of::<Tiling>()).deprecated(
Deprecation::new()
.with_message("the name `pattern` is deprecated, use `tiling` instead")
.with_until("0.15.0"),
);
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/visualize/line.rs | crates/typst-library/src/visualize/line.rs | use crate::foundations::elem;
use crate::layout::{Abs, Angle, Axes, Length, Rel};
use crate::visualize::Stroke;
/// A line from one point to another.
///
/// # Example
/// ```example
/// #set page(height: 100pt)
///
/// #line(length: 100%)
/// #line(end: (50%, 50%))
/// #line(
/// length: 4cm,
/// stroke: 2pt + maroon,
/// )
/// ```
#[elem]
pub struct LineElem {
/// The start point of the line.
///
/// Must be an array of exactly two relative lengths.
pub start: Axes<Rel<Length>>,
/// The point where the line ends.
pub end: Option<Axes<Rel<Length>>>,
/// The line's length. This is only respected if `end` is `{none}`.
#[default(Abs::pt(30.0).into())]
pub length: Rel<Length>,
/// The angle at which the line points away from the origin. This is only
/// respected if `end` is `{none}`.
pub angle: Angle,
/// How to [stroke] the line.
///
/// ```example
/// #set line(length: 100%)
/// #stack(
/// spacing: 1em,
/// line(stroke: 2pt + red),
/// line(stroke: (paint: blue, thickness: 4pt, cap: "round")),
/// line(stroke: (paint: blue, thickness: 1pt, dash: "dashed")),
/// line(stroke: (paint: blue, thickness: 1pt, dash: ("dot", 2pt, 4pt, 2pt))),
/// )
/// ```
#[fold]
pub stroke: Stroke,
}
| 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/visualize/color.rs | crates/typst-library/src/visualize/color.rs | use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::LazyLock;
use ecow::{EcoString, EcoVec, eco_format};
use palette::encoding::{self, Linear};
use palette::{
Alpha, Darken, Desaturate, FromColor, Lighten, OklabHue, RgbHue, Saturate, ShiftHue,
};
use qcms::Profile;
use typst_syntax::{Span, Spanned};
use crate::diag::{At, SourceResult, StrResult, bail};
use crate::foundations::{
Args, Array, IntoValue, Module, Repr, Scope, Str, Value, array, cast, func, repr,
scope, ty,
};
use crate::layout::{Angle, Ratio};
// Type aliases for `palette` internal types in f32.
pub type Oklab = palette::oklab::Oklaba<f32>;
pub type Oklch = palette::oklch::Oklcha<f32>;
pub type LinearRgb = palette::rgb::Rgba<Linear<encoding::Srgb>, f32>;
pub type Rgb = palette::rgb::Rgba<encoding::Srgb, f32>;
pub type Hsl = palette::hsl::Hsla<encoding::Srgb, f32>;
pub type Hsv = palette::hsv::Hsva<encoding::Srgb, f32>;
pub type Luma = palette::luma::Lumaa<encoding::Srgb, f32>;
/// The ICC profile used to convert from CMYK to RGB.
///
/// This is a minimal CMYK profile that only contains the necessary information
/// to convert from CMYK to RGB. It is based on the CGATS TR 001-1995
/// specification. See
/// <https://github.com/saucecontrol/Compact-ICC-Profiles#cmyk>.
static CMYK_TO_XYZ: LazyLock<Box<Profile>> = LazyLock::new(|| {
Profile::new_from_slice(typst_assets::icc::CMYK_TO_XYZ, false).unwrap()
});
/// The target sRGB profile.
static SRGB_PROFILE: LazyLock<Box<Profile>> = LazyLock::new(|| {
let mut out = Profile::new_sRGB();
out.precache_output_transform();
out
});
static TO_SRGB: LazyLock<qcms::Transform> = LazyLock::new(|| {
qcms::Transform::new_to(
&CMYK_TO_XYZ,
&SRGB_PROFILE,
qcms::DataType::CMYK,
qcms::DataType::RGB8,
// Our input profile only supports perceptual intent.
qcms::Intent::Perceptual,
)
.unwrap()
});
/// A color in a specific color space.
///
/// Typst supports:
/// - sRGB through the [`rgb` function]($color.rgb)
/// - Device CMYK through the [`cmyk` function]($color.cmyk)
/// - D65 Gray through the [`luma` function]($color.luma)
/// - Oklab through the [`oklab` function]($color.oklab)
/// - Oklch through the [`oklch` function]($color.oklch)
/// - Linear RGB through the [`color.linear-rgb` function]($color.linear-rgb)
/// - HSL through the [`color.hsl` function]($color.hsl)
/// - HSV through the [`color.hsv` function]($color.hsv)
///
///
/// # Example
///
/// ```example
/// #rect(fill: aqua)
/// ```
///
/// # Predefined colors
/// Typst defines the following built-in colors:
///
/// | Color | Definition |
/// |-----------|:-------------------|
/// | `black` | `{luma(0)}` |
/// | `gray` | `{luma(170)}` |
/// | `silver` | `{luma(221)}` |
/// | `white` | `{luma(255)}` |
/// | `navy` | `{rgb("#001f3f")}` |
/// | `blue` | `{rgb("#0074d9")}` |
/// | `aqua` | `{rgb("#7fdbff")}` |
/// | `teal` | `{rgb("#39cccc")}` |
/// | `eastern` | `{rgb("#239dad")}` |
/// | `purple` | `{rgb("#b10dc9")}` |
/// | `fuchsia` | `{rgb("#f012be")}` |
/// | `maroon` | `{rgb("#85144b")}` |
/// | `red` | `{rgb("#ff4136")}` |
/// | `orange` | `{rgb("#ff851b")}` |
/// | `yellow` | `{rgb("#ffdc00")}` |
/// | `olive` | `{rgb("#3d9970")}` |
/// | `green` | `{rgb("#2ecc40")}` |
/// | `lime` | `{rgb("#01ff70")}` |
///
/// The predefined colors and the most important color constructors are
/// available globally and also in the color type's scope, so you can write
/// either `color.red` or just `red`.
///
/// ```preview
/// #let colors = (
/// "black", "gray", "silver", "white",
/// "navy", "blue", "aqua", "teal",
/// "eastern", "purple", "fuchsia",
/// "maroon", "red", "orange", "yellow",
/// "olive", "green", "lime",
/// )
///
/// #set text(font: "PT Sans")
/// #set page(width: auto)
/// #grid(
/// columns: 9,
/// gutter: 10pt,
/// ..colors.map(name => {
/// let col = eval(name)
/// let luminance = luma(col).components().first()
/// set text(fill: white) if luminance < 50%
/// set square(stroke: black) if col == white
/// set align(center + horizon)
/// square(size: 50pt, fill: col, name)
/// })
/// )
/// ```
///
/// # Predefined color maps
/// Typst also includes a number of preset color maps that can be used for
/// [gradients]($gradient/#stops). These are simply arrays of colors defined in
/// the module `color.map`.
///
/// ```example
/// #circle(fill: gradient.linear(..color.map.crest))
/// ```
///
/// | Map | Details |
/// |------------|:------------------------------------------------------------|
/// | `turbo` | A perceptually uniform rainbow-like color map. Read [this blog post](https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html) for more details. |
/// | `cividis` | A blue to gray to yellow color map. See [this blog post](https://bids.github.io/colormap/) for more details. |
/// | `rainbow` | Cycles through the full color spectrum. This color map is best used by setting the interpolation color space to [HSL]($color.hsl). The rainbow gradient is **not suitable** for data visualization because it is not perceptually uniform, so the differences between values become unclear to your readers. It should only be used for decorative purposes. |
/// | `spectral` | Red to yellow to blue color map. |
/// | `viridis` | A purple to teal to yellow color map. |
/// | `inferno` | A black to red to yellow color map. |
/// | `magma` | A black to purple to yellow color map. |
/// | `plasma` | A purple to pink to yellow color map. |
/// | `rocket` | A black to red to white color map. |
/// | `mako` | A black to teal to white color map. |
/// | `coolwarm` | A blue to white to red color map with smooth transitions. |
/// | `vlag` | A light blue to white to red color map. |
/// | `icefire` | A light teal to black to orange color map. |
/// | `flare` | A orange to purple color map that is perceptually uniform. |
/// | `crest` | A light green to blue color map. |
///
/// Some popular presets are not included because they are not available under a
/// free licence. Others, like
/// [Jet](https://jakevdp.github.io/blog/2014/10/16/how-bad-is-your-colormap/),
/// are not included because they are not color blind friendly. Feel free to use
/// or create a package with other presets that are useful to you!
///
/// ```preview
/// #set page(width: auto, height: auto)
/// #set text(font: "PT Sans", size: 8pt)
///
/// #let maps = (
/// "turbo", "cividis", "rainbow", "spectral",
/// "viridis", "inferno", "magma", "plasma",
/// "rocket", "mako", "coolwarm", "vlag",
/// "icefire", "flare", "crest",
/// )
///
/// #stack(dir: ltr, spacing: 3pt, ..maps.map((name) => {
/// let map = eval("color.map." + name)
/// stack(
/// dir: ttb,
/// block(
/// width: 15pt,
/// height: 100pt,
/// fill: gradient.linear(..map, angle: 90deg),
/// ),
/// block(
/// width: 15pt,
/// height: 32pt,
/// move(dy: 8pt, rotate(90deg, name)),
/// ),
/// )
/// }))
/// ```
#[ty(scope, cast)]
#[derive(Copy, Clone)]
pub enum Color {
/// A 32-bit luma color.
Luma(Luma),
/// A 32-bit L\*a\*b\* color in the Oklab color space.
Oklab(Oklab),
/// A 32-bit LCh color in the Oklab color space.
Oklch(Oklch),
/// A 32-bit RGB color.
Rgb(Rgb),
/// A 32-bit linear RGB color.
LinearRgb(LinearRgb),
/// A 32-bit CMYK color.
Cmyk(Cmyk),
/// A 32-bit HSL color.
Hsl(Hsl),
/// A 32-bit HSV color.
Hsv(Hsv),
}
#[scope]
impl Color {
/// The module of preset color maps.
pub const MAP: fn() -> Module = || typst_utils::singleton!(Module, map()).clone();
pub const BLACK: Self = Self::Luma(Luma::new(0.0, 1.0));
pub const GRAY: Self = Self::Luma(Luma::new(0.6666666, 1.0));
pub const WHITE: Self = Self::Luma(Luma::new(1.0, 1.0));
pub const SILVER: Self = Self::Luma(Luma::new(0.8666667, 1.0));
pub const NAVY: Self = Self::Rgb(Rgb::new(0.0, 0.121569, 0.247059, 1.0));
pub const BLUE: Self = Self::Rgb(Rgb::new(0.0, 0.454902, 0.85098, 1.0));
pub const AQUA: Self = Self::Rgb(Rgb::new(0.4980392, 0.858823, 1.0, 1.0));
pub const TEAL: Self = Self::Rgb(Rgb::new(0.223529, 0.8, 0.8, 1.0));
pub const EASTERN: Self = Self::Rgb(Rgb::new(0.13725, 0.615686, 0.678431, 1.0));
pub const PURPLE: Self = Self::Rgb(Rgb::new(0.694118, 0.050980, 0.788235, 1.0));
pub const FUCHSIA: Self = Self::Rgb(Rgb::new(0.941177, 0.070588, 0.745098, 1.0));
pub const MAROON: Self = Self::Rgb(Rgb::new(0.521569, 0.078431, 0.294118, 1.0));
pub const RED: Self = Self::Rgb(Rgb::new(1.0, 0.254902, 0.211765, 1.0));
pub const ORANGE: Self = Self::Rgb(Rgb::new(1.0, 0.521569, 0.105882, 1.0));
pub const YELLOW: Self = Self::Rgb(Rgb::new(1.0, 0.8627451, 0.0, 1.0));
pub const OLIVE: Self = Self::Rgb(Rgb::new(0.239216, 0.6, 0.4392157, 1.0));
pub const GREEN: Self = Self::Rgb(Rgb::new(0.1803922, 0.8, 0.2509804, 1.0));
pub const LIME: Self = Self::Rgb(Rgb::new(0.0039216, 1.0, 0.4392157, 1.0));
/// Create a grayscale color.
///
/// A grayscale color is represented internally by a single `lightness`
/// component.
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #for x in range(250, step: 50) {
/// box(square(fill: luma(x)))
/// }
/// ```
#[func]
pub fn luma(
args: &mut Args,
/// The lightness component.
#[external]
lightness: Component,
/// The alpha component.
#[external]
alpha: RatioComponent,
/// Alternatively: The color to convert to grayscale.
///
/// If this is given, the `lightness` should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Luma(color.to_luma())
} else {
let Component(gray) =
args.expect("gray component").unwrap_or(Component(Ratio::one()));
let RatioComponent(alpha) =
args.eat()?.unwrap_or(RatioComponent(Ratio::one()));
Self::Luma(Luma::new(gray.get() as f32, alpha.get() as f32))
})
}
/// Create an [Oklab](https://bottosson.github.io/posts/oklab/) color.
///
/// This color space is well suited for the following use cases:
/// - Color manipulation such as saturating while keeping perceived hue
/// - Creating grayscale images with uniform perceived lightness
/// - Creating smooth and uniform color transition and gradients
///
/// A linear Oklab color is represented internally by an array of four
/// components:
/// - lightness ([`ratio`])
/// - a ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - b ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - alpha ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #square(
/// fill: oklab(27%, 20%, -3%, 50%)
/// )
/// ```
#[func]
pub fn oklab(
args: &mut Args,
/// The lightness component.
#[external]
lightness: RatioComponent,
/// The a ("green/red") component.
#[external]
a: ChromaComponent,
/// The b ("blue/yellow") component.
#[external]
b: ChromaComponent,
/// The alpha component.
#[external]
alpha: RatioComponent,
/// Alternatively: The color to convert to Oklab.
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Oklab(color.to_oklab())
} else {
let RatioComponent(l) = args.expect("lightness component")?;
let ChromaComponent(a) = args.expect("A component")?;
let ChromaComponent(b) = args.expect("B component")?;
let RatioComponent(alpha) =
args.eat()?.unwrap_or(RatioComponent(Ratio::one()));
Self::Oklab(Oklab::new(l.get() as f32, a, b, alpha.get() as f32))
})
}
/// Create an [Oklch](https://bottosson.github.io/posts/oklab/) color.
///
/// This color space is well suited for the following use cases:
/// - Color manipulation involving lightness, chroma, and hue
/// - Creating grayscale images with uniform perceived lightness
/// - Creating smooth and uniform color transition and gradients
///
/// A linear Oklch color is represented internally by an array of four
/// components:
/// - lightness ([`ratio`])
/// - chroma ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - hue ([`angle`])
/// - alpha ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #square(
/// fill: oklch(40%, 0.2, 160deg, 50%)
/// )
/// ```
#[func]
pub fn oklch(
args: &mut Args,
/// The lightness component.
#[external]
lightness: RatioComponent,
/// The chroma component.
#[external]
chroma: ChromaComponent,
/// The hue component.
#[external]
hue: Angle,
/// The alpha component.
#[external]
alpha: RatioComponent,
/// Alternatively: The color to convert to Oklch.
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Oklch(color.to_oklch())
} else {
let RatioComponent(l) = args.expect("lightness component")?;
let ChromaComponent(c) = args.expect("chroma component")?;
let h: Angle = args.expect("hue component")?;
let RatioComponent(alpha) =
args.eat()?.unwrap_or(RatioComponent(Ratio::one()));
Self::Oklch(Oklch::new(
l.get() as f32,
c,
OklabHue::from_degrees(h.to_deg() as f32),
alpha.get() as f32,
))
})
}
/// Create an RGB(A) color with linear luma.
///
/// This color space is similar to sRGB, but with the distinction that the
/// color component are not gamma corrected. This makes it easier to perform
/// color operations such as blending and interpolation. Although, you
/// should prefer to use the [`oklab` function]($color.oklab) for these.
///
/// A linear RGB(A) color is represented internally by an array of four
/// components:
/// - red ([`ratio`])
/// - green ([`ratio`])
/// - blue ([`ratio`])
/// - alpha ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #square(fill: color.linear-rgb(
/// 30%, 50%, 10%,
/// ))
/// ```
#[func(title = "Linear RGB")]
pub fn linear_rgb(
args: &mut Args,
/// The red component.
#[external]
red: Component,
/// The green component.
#[external]
green: Component,
/// The blue component.
#[external]
blue: Component,
/// The alpha component.
#[external]
alpha: Component,
/// Alternatively: The color to convert to linear RGB(A).
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::LinearRgb(color.to_linear_rgb())
} else {
let Component(r) = args.expect("red component")?;
let Component(g) = args.expect("green component")?;
let Component(b) = args.expect("blue component")?;
let Component(a) = args.eat()?.unwrap_or(Component(Ratio::one()));
Self::LinearRgb(LinearRgb::new(
r.get() as f32,
g.get() as f32,
b.get() as f32,
a.get() as f32,
))
})
}
/// Create an RGB(A) color.
///
/// The color is specified in the sRGB color space.
///
/// An RGB(A) color is represented internally by an array of four components:
/// - red ([`ratio`])
/// - green ([`ratio`])
/// - blue ([`ratio`])
/// - alpha ([`ratio`])
///
/// These components are also available using the [`components`]($color.components)
/// method.
///
/// ```example
/// #square(fill: rgb("#b1f2eb"))
/// #square(fill: rgb(87, 127, 230))
/// #square(fill: rgb(25%, 13%, 65%))
/// ```
#[func(title = "RGB")]
pub fn rgb(
args: &mut Args,
/// The red component.
#[external]
red: Component,
/// The green component.
#[external]
green: Component,
/// The blue component.
#[external]
blue: Component,
/// The alpha component.
#[external]
alpha: Component,
/// Alternatively: The color in hexadecimal notation.
///
/// Accepts three, four, six or eight hexadecimal digits and optionally
/// a leading hash.
///
/// If this is given, the individual components should not be given.
///
/// ```example
/// #text(16pt, rgb("#239dad"))[
/// *Typst*
/// ]
/// ```
#[external]
hex: Str,
/// Alternatively: The color to convert to RGB(a).
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(string) = args.find::<Spanned<Str>>()? {
Self::from_str(&string.v).at(string.span)?
} else if let Some(color) = args.find::<Color>()? {
Color::Rgb(color.to_rgb())
} else {
let Component(r) = args.expect("red component")?;
let Component(g) = args.expect("green component")?;
let Component(b) = args.expect("blue component")?;
let Component(a) = args.eat()?.unwrap_or(Component(Ratio::one()));
Self::Rgb(Rgb::new(
r.get() as f32,
g.get() as f32,
b.get() as f32,
a.get() as f32,
))
})
}
/// Create a CMYK color.
///
/// This is useful if you want to target a specific printer. The conversion
/// to RGB for display preview might differ from how your printer reproduces
/// the color.
///
/// A CMYK color is represented internally by an array of four components:
/// - cyan ([`ratio`])
/// - magenta ([`ratio`])
/// - yellow ([`ratio`])
/// - key ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// Note that CMYK colors are not currently supported when PDF/A output is
/// enabled.
///
/// ```example
/// #square(
/// fill: cmyk(27%, 0%, 3%, 5%)
/// )
/// ```
#[func(title = "CMYK")]
pub fn cmyk(
args: &mut Args,
/// The cyan component.
#[external]
cyan: RatioComponent,
/// The magenta component.
#[external]
magenta: RatioComponent,
/// The yellow component.
#[external]
yellow: RatioComponent,
/// The key component.
#[external]
key: RatioComponent,
/// Alternatively: The color to convert to CMYK.
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Cmyk(color.to_cmyk())
} else {
let RatioComponent(c) = args.expect("cyan component")?;
let RatioComponent(m) = args.expect("magenta component")?;
let RatioComponent(y) = args.expect("yellow component")?;
let RatioComponent(k) = args.expect("key/black component")?;
Self::Cmyk(Cmyk::new(
c.get() as f32,
m.get() as f32,
y.get() as f32,
k.get() as f32,
))
})
}
/// Create an HSL color.
///
/// This color space is useful for specifying colors by hue, saturation and
/// lightness. It is also useful for color manipulation, such as saturating
/// while keeping perceived hue.
///
/// An HSL color is represented internally by an array of four components:
/// - hue ([`angle`])
/// - saturation ([`ratio`])
/// - lightness ([`ratio`])
/// - alpha ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #square(
/// fill: color.hsl(30deg, 50%, 60%)
/// )
/// ```
#[func(title = "HSL")]
pub fn hsl(
args: &mut Args,
/// The hue angle.
#[external]
hue: Angle,
/// The saturation component.
#[external]
saturation: Component,
/// The lightness component.
#[external]
lightness: Component,
/// The alpha component.
#[external]
alpha: Component,
/// Alternatively: The color to convert to HSL.
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Hsl(color.to_hsl())
} else {
let h: Angle = args.expect("hue component")?;
let Component(s) = args.expect("saturation component")?;
let Component(l) = args.expect("lightness component")?;
let Component(a) = args.eat()?.unwrap_or(Component(Ratio::one()));
Self::Hsl(Hsl::new(
RgbHue::from_degrees(h.to_deg() as f32),
s.get() as f32,
l.get() as f32,
a.get() as f32,
))
})
}
/// Create an HSV color.
///
/// This color space is useful for specifying colors by hue, saturation and
/// value. It is also useful for color manipulation, such as saturating
/// while keeping perceived hue.
///
/// An HSV color is represented internally by an array of four components:
/// - hue ([`angle`])
/// - saturation ([`ratio`])
/// - value ([`ratio`])
/// - alpha ([`ratio`])
///
/// These components are also available using the
/// [`components`]($color.components) method.
///
/// ```example
/// #square(
/// fill: color.hsv(30deg, 50%, 60%)
/// )
/// ```
#[func(title = "HSV")]
pub fn hsv(
args: &mut Args,
/// The hue angle.
#[external]
hue: Angle,
/// The saturation component.
#[external]
saturation: Component,
/// The value component.
#[external]
value: Component,
/// The alpha component.
#[external]
alpha: Component,
/// Alternatively: The color to convert to HSL.
///
/// If this is given, the individual components should not be given.
#[external]
color: Color,
) -> SourceResult<Color> {
Ok(if let Some(color) = args.find::<Color>()? {
Color::Hsv(color.to_hsv())
} else {
let h: Angle = args.expect("hue component")?;
let Component(s) = args.expect("saturation component")?;
let Component(v) = args.expect("value component")?;
let Component(a) = args.eat()?.unwrap_or(Component(Ratio::one()));
Self::Hsv(Hsv::new(
RgbHue::from_degrees(h.to_deg() as f32),
s.get() as f32,
v.get() as f32,
a.get() as f32,
))
})
}
/// Extracts the components of this color.
///
/// The size and values of this array depends on the color space. You can
/// obtain the color space using [`space`]($color.space). Below is a table
/// of the color spaces and their components:
///
/// | Color space | C1 | C2 | C3 | C4 |
/// |-------------------------|-----------|------------|-----------|--------|
/// | [`luma`]($color.luma) | Lightness | | | |
/// | [`oklab`]($color.oklab) | Lightness | `a` | `b` | Alpha |
/// | [`oklch`]($color.oklch) | Lightness | Chroma | Hue | Alpha |
/// | [`linear-rgb`]($color.linear-rgb) | Red | Green | Blue | Alpha |
/// | [`rgb`]($color.rgb) | Red | Green | Blue | Alpha |
/// | [`cmyk`]($color.cmyk) | Cyan | Magenta | Yellow | Key |
/// | [`hsl`]($color.hsl) | Hue | Saturation | Lightness | Alpha |
/// | [`hsv`]($color.hsv) | Hue | Saturation | Value | Alpha |
///
/// For the meaning and type of each individual value, see the documentation
/// of the corresponding color space. The alpha component is optional and
/// only included if the `alpha` argument is `true`. The length of the
/// returned array depends on the number of components and whether the alpha
/// component is included.
///
/// ```example
/// // note that the alpha component is included by default
/// #rgb(40%, 60%, 80%).components()
/// ```
#[func]
pub fn components(
self,
/// Whether to include the alpha component.
#[named]
#[default(true)]
alpha: bool,
) -> Array {
let mut components = match self {
Self::Luma(c) => {
array![Ratio::new(c.luma.into()), Ratio::new(c.alpha.into())]
}
Self::Oklab(c) => {
array![
Ratio::new(c.l.into()),
f64::from(c.a),
f64::from(c.b),
Ratio::new(c.alpha.into())
]
}
Self::Oklch(c) => {
array![
Ratio::new(c.l.into()),
f64::from(c.chroma),
hue_angle(c.hue.into_degrees()),
Ratio::new(c.alpha.into()),
]
}
Self::LinearRgb(c) => {
array![
Ratio::new(c.red.into()),
Ratio::new(c.green.into()),
Ratio::new(c.blue.into()),
Ratio::new(c.alpha.into()),
]
}
Self::Rgb(c) => {
array![
Ratio::new(c.red.into()),
Ratio::new(c.green.into()),
Ratio::new(c.blue.into()),
Ratio::new(c.alpha.into()),
]
}
Self::Cmyk(c) => {
array![
Ratio::new(c.c.into()),
Ratio::new(c.m.into()),
Ratio::new(c.y.into()),
Ratio::new(c.k.into())
]
}
Self::Hsl(c) => {
array![
hue_angle(c.hue.into_degrees()),
Ratio::new(c.saturation.into()),
Ratio::new(c.lightness.into()),
Ratio::new(c.alpha.into()),
]
}
Self::Hsv(c) => {
array![
hue_angle(c.hue.into_degrees()),
Ratio::new(c.saturation.into()),
Ratio::new(c.value.into()),
Ratio::new(c.alpha.into()),
]
}
};
// Remove the alpha component if the corresponding argument was set.
if !alpha && !matches!(self, Self::Cmyk(_)) {
let _ = components.pop();
}
components
}
/// Returns the constructor function for this color's space.
///
/// Returns one of:
/// - [`luma`]($color.luma)
/// - [`oklab`]($color.oklab)
/// - [`oklch`]($color.oklch)
/// - [`linear-rgb`]($color.linear-rgb)
/// - [`rgb`]($color.rgb)
/// - [`cmyk`]($color.cmyk)
/// - [`hsl`]($color.hsl)
/// - [`hsv`]($color.hsv)
///
/// ```example
/// #let color = cmyk(1%, 2%, 3%, 4%)
/// #(color.space() == cmyk)
/// ```
#[func]
pub fn space(self) -> ColorSpace {
match self {
Self::Luma(_) => ColorSpace::D65Gray,
Self::Oklab(_) => ColorSpace::Oklab,
Self::Oklch(_) => ColorSpace::Oklch,
Self::LinearRgb(_) => ColorSpace::LinearRgb,
Self::Rgb(_) => ColorSpace::Srgb,
Self::Cmyk(_) => ColorSpace::Cmyk,
Self::Hsl(_) => ColorSpace::Hsl,
Self::Hsv(_) => ColorSpace::Hsv,
}
}
/// Returns the color's RGB(A) hex representation (such as `#ffaa32` or
/// `#020304fe`). The alpha component (last two digits in `#020304fe`) is
/// omitted if it is equal to `ff` (255 / 100%).
#[func]
pub fn to_hex(self) -> EcoString {
let (r, g, b, a) = self.to_rgb().into_format::<u8, u8>().into_components();
if a != 255 {
eco_format!("#{:02x}{:02x}{:02x}{:02x}", r, g, b, a)
} else {
eco_format!("#{:02x}{:02x}{:02x}", r, g, b)
}
}
/// Lightens a color by a given factor.
#[func]
pub fn lighten(
self,
/// The factor to lighten the color by.
factor: Ratio,
) -> Color {
let factor = factor.get() as f32;
match self {
Self::Luma(c) => Self::Luma(c.lighten(factor)),
Self::Oklab(c) => Self::Oklab(c.lighten(factor)),
Self::Oklch(c) => Self::Oklch(c.lighten(factor)),
Self::LinearRgb(c) => Self::LinearRgb(c.lighten(factor)),
Self::Rgb(c) => Self::Rgb(c.lighten(factor)),
Self::Cmyk(c) => Self::Cmyk(c.lighten(factor)),
Self::Hsl(c) => Self::Hsl(c.lighten(factor)),
Self::Hsv(c) => Self::Hsv(c.lighten(factor)),
}
}
/// Darkens a color by a given factor.
#[func]
pub fn darken(
self,
/// The factor to darken the color by.
factor: Ratio,
) -> Color {
let factor = factor.get() as f32;
match self {
Self::Luma(c) => Self::Luma(c.darken(factor)),
Self::Oklab(c) => Self::Oklab(c.darken(factor)),
Self::Oklch(c) => Self::Oklch(c.darken(factor)),
Self::LinearRgb(c) => Self::LinearRgb(c.darken(factor)),
Self::Rgb(c) => Self::Rgb(c.darken(factor)),
Self::Cmyk(c) => Self::Cmyk(c.darken(factor)),
Self::Hsl(c) => Self::Hsl(c.darken(factor)),
Self::Hsv(c) => Self::Hsv(c.darken(factor)),
}
}
/// Increases the saturation of a color by a given factor.
#[func]
pub fn saturate(
self,
span: Span,
/// The factor to saturate the color by.
factor: Ratio,
) -> SourceResult<Color> {
let f = factor.get() as f32;
Ok(match self {
Self::Luma(_) => bail!(
span, "cannot saturate grayscale color";
hint: "try converting your color to RGB first";
),
Self::Hsl(c) => Self::Hsl(c.saturate(f)),
Self::Hsv(c) => Self::Hsv(c.saturate(f)),
Self::Oklab(_)
| Self::Oklch(_)
| Self::LinearRgb(_)
| Self::Rgb(_)
| 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/visualize/tiling.rs | crates/typst-library/src/visualize/tiling.rs | use std::hash::Hash;
use std::sync::Arc;
use ecow::{EcoString, eco_format};
use typst_syntax::{Span, Spanned};
use typst_utils::{LazyHash, Numeric};
use crate::World;
use crate::diag::{SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{Content, Repr, Smart, StyleChain, func, scope, ty};
use crate::introspection::Locator;
use crate::layout::{Abs, Axes, Frame, Length, Region, Size};
use crate::visualize::RelativeTo;
/// A repeating tiling fill.
///
/// Typst supports the most common type of tilings, where a pattern is repeated
/// in a grid-like fashion, covering the entire area of an element that is
/// filled or stroked. The pattern is defined by a tile size and a body defining
/// the content of each cell. You can also add horizontal or vertical spacing
/// between the cells of the tiling.
///
/// # Examples
///
/// ```example
/// #let pat = tiling(size: (30pt, 30pt))[
/// #place(line(start: (0%, 0%), end: (100%, 100%)))
/// #place(line(start: (0%, 100%), end: (100%, 0%)))
/// ]
///
/// #rect(fill: pat, width: 100%, height: 60pt, stroke: 1pt)
/// ```
///
/// Tilings are also supported on text, but only when setting the
/// [relativeness]($tiling.relative) to either `{auto}` (the default value) or
/// `{"parent"}`. To create word-by-word or glyph-by-glyph tilings, you can
/// wrap the words or characters of your text in [boxes]($box) manually or
/// through a [show rule]($styling/#show-rules).
///
/// ```example
/// #let pat = tiling(
/// size: (30pt, 30pt),
/// relative: "parent",
/// square(
/// size: 30pt,
/// fill: gradient
/// .conic(..color.map.rainbow),
/// )
/// )
///
/// #set text(fill: pat)
/// #lorem(10)
/// ```
///
/// You can also space the elements further or closer apart using the
/// [`spacing`]($tiling.spacing) feature of the tiling. If the spacing
/// is lower than the size of the tiling, the tiling will overlap.
/// If it is higher, the tiling will have gaps of the same color as the
/// background of the tiling.
///
/// ```example
/// #let pat = tiling(
/// size: (30pt, 30pt),
/// spacing: (10pt, 10pt),
/// relative: "parent",
/// square(
/// size: 30pt,
/// fill: gradient
/// .conic(..color.map.rainbow),
/// ),
/// )
///
/// #rect(
/// width: 100%,
/// height: 60pt,
/// fill: pat,
/// )
/// ```
///
/// # Relativeness
/// The location of the starting point of the tiling is dependent on the
/// dimensions of a container. This container can either be the shape that it is
/// being painted on, or the closest surrounding container. This is controlled
/// by the `relative` argument of a tiling constructor. By default, tilings
/// are relative to the shape they are being painted on, unless the tiling is
/// applied on text, in which case they are relative to the closest ancestor
/// container.
///
/// Typst determines the ancestor container as follows:
/// - For shapes that are placed at the root/top level of the document, the
/// closest ancestor is the page itself.
/// - For other shapes, the ancestor is the innermost [`block`] or [`box`] that
/// contains the shape. This includes the boxes and blocks that are implicitly
/// created by show rules and elements. For example, a [`rotate`] will not
/// affect the parent of a gradient, but a [`grid`] will.
///
/// # Compatibility
/// This type used to be called `pattern`. The name remains as an alias, but is
/// deprecated since Typst 0.13.
#[ty(scope, cast, keywords = ["pattern"])]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Tiling(Arc<TilingInner>);
/// The internal representation of a [`Tiling`].
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct TilingInner {
/// The tiling's rendered content.
frame: LazyHash<Frame>,
/// The tiling's tile size.
size: Size,
/// The tiling's tile spacing.
spacing: Size,
/// The tiling's relative transform.
relative: Smart<RelativeTo>,
}
#[scope]
impl Tiling {
/// Construct a new tiling.
///
/// ```example
/// #let pat = tiling(
/// size: (20pt, 20pt),
/// relative: "parent",
/// place(
/// dx: 5pt,
/// dy: 5pt,
/// rotate(45deg, square(
/// size: 5pt,
/// fill: black,
/// )),
/// ),
/// )
///
/// #rect(width: 100%, height: 60pt, fill: pat)
/// ```
#[func(constructor)]
pub fn construct(
engine: &mut Engine,
span: Span,
/// The bounding box of each cell of the tiling.
#[named]
#[default(Spanned::detached(Smart::Auto))]
size: Spanned<Smart<Axes<Length>>>,
/// The spacing between cells of the tiling.
#[named]
#[default(Spanned::detached(Axes::splat(Length::zero())))]
spacing: Spanned<Axes<Length>>,
/// The [relative placement](#relativeness) of the tiling.
///
/// For an element placed at the root/top level of the document, the
/// parent is the page itself. For other elements, the parent is the
/// innermost block, box, column, grid, or stack that contains the
/// element.
#[named]
#[default(Smart::Auto)]
relative: Smart<RelativeTo>,
/// The content of each cell of the tiling.
body: Content,
) -> SourceResult<Tiling> {
let size_span = size.span;
if let Smart::Custom(size) = size.v {
// Ensure that sizes are absolute.
if !size.x.em.is_zero() || !size.y.em.is_zero() {
bail!(size_span, "tile size must be absolute");
}
// Ensure that sizes are non-zero and finite.
if size.x.is_zero()
|| size.y.is_zero()
|| !size.x.is_finite()
|| !size.y.is_finite()
{
bail!(size_span, "tile size must be non-zero and non-infinite");
}
}
// Ensure that spacing is absolute.
if !spacing.v.x.em.is_zero() || !spacing.v.y.em.is_zero() {
bail!(spacing.span, "tile spacing must be absolute");
}
// Ensure that spacing is finite.
if !spacing.v.x.is_finite() || !spacing.v.y.is_finite() {
bail!(spacing.span, "tile spacing must be finite");
}
// The size of the frame
let size = size.v.map(|l| l.map(|a| a.abs));
let region = size.unwrap_or_else(|| Axes::splat(Abs::inf()));
// Layout the tiling.
let world = engine.world;
let library = world.library();
let locator = Locator::root();
let styles = StyleChain::new(&library.styles);
let pod = Region::new(region, Axes::splat(false));
let mut frame =
(engine.routines.layout_frame)(engine, &body, locator, styles, pod)?;
// Set the size of the frame if the size is enforced.
if let Smart::Custom(size) = size {
frame.set_size(size);
}
// Check that the frame is non-zero.
if frame.width().is_zero() || frame.height().is_zero() {
bail!(
span, "tile size must be non-zero";
hint: "try setting the size manually";
);
}
Ok(Self(Arc::new(TilingInner {
size: frame.size(),
frame: LazyHash::new(frame),
spacing: spacing.v.map(|l| l.abs),
relative,
})))
}
}
impl Tiling {
/// Set the relative placement of the tiling.
pub fn with_relative(mut self, relative: RelativeTo) -> Self {
if let Some(this) = Arc::get_mut(&mut self.0) {
this.relative = Smart::Custom(relative);
} else {
self.0 = Arc::new(TilingInner {
relative: Smart::Custom(relative),
..self.0.as_ref().clone()
});
}
self
}
/// Return the frame of the tiling.
pub fn frame(&self) -> &Frame {
&self.0.frame
}
/// Return the size of the tiling in absolute units.
pub fn size(&self) -> Size {
self.0.size
}
/// Return the spacing of the tiling in absolute units.
pub fn spacing(&self) -> Size {
self.0.spacing
}
/// Returns the relative placement of the tiling.
pub fn relative(&self) -> Smart<RelativeTo> {
self.0.relative
}
/// Returns the relative placement of the tiling.
pub fn unwrap_relative(&self, on_text: bool) -> RelativeTo {
self.0.relative.unwrap_or_else(|| {
if on_text { RelativeTo::Parent } else { RelativeTo::Self_ }
})
}
}
impl Repr for Tiling {
fn repr(&self) -> EcoString {
let mut out =
eco_format!("tiling(({}, {})", self.0.size.x.repr(), self.0.size.y.repr());
if self.0.spacing.is_zero() {
out.push_str(", spacing: (");
out.push_str(&self.0.spacing.x.repr());
out.push_str(", ");
out.push_str(&self.0.spacing.y.repr());
out.push(')');
}
out.push_str(", ..)");
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/visualize/gradient.rs | crates/typst-library/src/visualize/gradient.rs | use std::f64::consts::{FRAC_PI_2, PI, TAU};
use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;
use std::sync::Arc;
use ecow::EcoString;
use kurbo::Vec2;
use typst_syntax::{Span, Spanned};
use crate::diag::{SourceResult, bail};
use crate::foundations::{
Args, Array, Cast, Func, IntoValue, Repr, Smart, array, cast, func, scope, ty,
};
use crate::layout::{Angle, Axes, Dir, Quadrant, Ratio};
use crate::visualize::{Color, ColorSpace, WeightedColor};
/// A color gradient.
///
/// Typst supports linear gradients through the
/// [`gradient.linear` function]($gradient.linear), radial gradients through
/// the [`gradient.radial` function]($gradient.radial), and conic gradients
/// through the [`gradient.conic` function]($gradient.conic).
///
/// A gradient can be used for the following purposes:
/// - As a fill to paint the interior of a shape:
/// `{rect(fill: gradient.linear(..))}`
/// - As a stroke to paint the outline of a shape:
/// `{rect(stroke: 1pt + gradient.linear(..))}`
/// - As the fill of text:
/// `{set text(fill: gradient.linear(..))}`
/// - As a color map you can [sample]($gradient.sample) from:
/// `{gradient.linear(..).sample(50%)}`
///
/// # Examples
/// ```example
/// >>> #set square(size: 50pt)
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// square(fill: gradient.linear(..color.map.rainbow)),
/// square(fill: gradient.radial(..color.map.rainbow)),
/// square(fill: gradient.conic(..color.map.rainbow)),
/// )
/// ```
///
/// Gradients are also supported on text, but only when setting the
/// [relativeness]($gradient.relative) to either `{auto}` (the default value) or
/// `{"parent"}`. To create word-by-word or glyph-by-glyph gradients, you can
/// wrap the words or characters of your text in [boxes]($box) manually or
/// through a [show rule]($styling/#show-rules).
///
/// ```example
/// >>> #set page(width: auto, height: auto, margin: 12pt)
/// >>> #set text(size: 12pt)
/// #set text(fill: gradient.linear(red, blue))
/// #let rainbow(content) = {
/// set text(fill: gradient.linear(..color.map.rainbow))
/// box(content)
/// }
///
/// This is a gradient on text, but with a #rainbow[twist]!
/// ```
///
/// # Stops
/// A gradient is composed of a series of stops. Each of these stops has a color
/// and an offset. The offset is a [ratio]($ratio) between `{0%}` and `{100%}` or
/// an angle between `{0deg}` and `{360deg}`. The offset is a relative position
/// that determines how far along the gradient the stop is located. The stop's
/// color is the color of the gradient at that position. You can choose to omit
/// the offsets when defining a gradient. In this case, Typst will space all
/// stops evenly.
///
/// Typst predefines color maps that you can use as stops. See the
/// [`color`]($color/#predefined-color-maps) documentation for more details.
///
/// # Relativeness
/// The location of the `{0%}` and `{100%}` stops depends on the dimensions
/// of a container. This container can either be the shape that it is being
/// painted on, or the closest surrounding container. This is controlled by the
/// `relative` argument of a gradient constructor. By default, gradients are
/// relative to the shape they are being painted on, unless the gradient is
/// applied on text, in which case they are relative to the closest ancestor
/// container.
///
/// Typst determines the ancestor container as follows:
/// - For shapes that are placed at the root/top level of the document, the
/// closest ancestor is the page itself.
/// - For other shapes, the ancestor is the innermost [`block`] or [`box`] that
/// contains the shape. This includes the boxes and blocks that are implicitly
/// created by show rules and elements. For example, a [`rotate`] will not
/// affect the parent of a gradient, but a [`grid`] will.
///
/// # Color spaces and interpolation
/// Gradients can be interpolated in any color space. By default, gradients are
/// interpolated in the [Oklab]($color.oklab) color space, which is a
/// [perceptually uniform](https://programmingdesignsystems.com/color/perceptually-uniform-color-spaces/index.html)
/// color space. This means that the gradient will be perceived as having a
/// smooth progression of colors. This is particularly useful for data
/// visualization.
///
/// However, you can choose to interpolate the gradient in any supported color
/// space you want, but beware that some color spaces are not suitable for
/// perceptually interpolating between colors. Consult the table below when
/// choosing an interpolation space.
///
/// | Color space | Perceptually uniform? |
/// | ------------------------------- |-----------------------|
/// | [Oklab]($color.oklab) | *Yes* |
/// | [Oklch]($color.oklch) | *Yes* |
/// | [sRGB]($color.rgb) | *No* |
/// | [linear-RGB]($color.linear-rgb) | *Yes* |
/// | [CMYK]($color.cmyk) | *No* |
/// | [Grayscale]($color.luma) | *Yes* |
/// | [HSL]($color.hsl) | *No* |
/// | [HSV]($color.hsv) | *No* |
///
/// ```preview
/// >>> #set text(fill: white, font: "IBM Plex Sans", 8pt)
/// >>> #set block(spacing: 0pt)
/// #let spaces = (
/// ("Oklab", color.oklab),
/// ("Oklch", color.oklch),
/// ("sRGB", color.rgb),
/// ("linear-RGB", color.linear-rgb),
/// ("CMYK", color.cmyk),
/// ("Grayscale", color.luma),
/// ("HSL", color.hsl),
/// ("HSV", color.hsv),
/// )
///
/// #for (name, space) in spaces {
/// block(
/// width: 100%,
/// inset: 4pt,
/// fill: gradient.linear(
/// red,
/// blue,
/// space: space,
/// ),
/// strong(upper(name)),
/// )
/// }
/// ```
///
/// # Direction
/// Some gradients are sensitive to direction. For example, a linear gradient
/// has an angle that determines its direction. Typst uses a clockwise angle,
/// with 0° being from left to right, 90° from top to bottom, 180° from right to
/// left, and 270° from bottom to top.
///
/// ```example
/// >>> #set square(size: 50pt)
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// square(fill: gradient.linear(red, blue, angle: 0deg)),
/// square(fill: gradient.linear(red, blue, angle: 90deg)),
/// square(fill: gradient.linear(red, blue, angle: 180deg)),
/// square(fill: gradient.linear(red, blue, angle: 270deg)),
/// )
/// ```
///
/// # Note on file sizes
///
/// Gradients can be quite large, especially if they have many stops. This is
/// because gradients are stored as a list of colors and offsets, which can
/// take up a lot of space. If you are concerned about file sizes, you should
/// consider the following:
/// - SVG gradients are currently inefficiently encoded. This will be improved
/// in the future.
/// - PDF gradients in the [`color.oklab`], [`color.hsv`], [`color.hsl`], and
/// [`color.oklch`] color spaces are stored as a list of [`color.rgb`] colors
/// with extra stops in between. This avoids needing to encode these color
/// spaces in your PDF file, but it does add extra stops to your gradient,
/// which can increase the file size.
#[ty(scope, cast)]
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum Gradient {
Linear(Arc<LinearGradient>),
Radial(Arc<RadialGradient>),
Conic(Arc<ConicGradient>),
}
#[scope]
#[allow(clippy::too_many_arguments)]
impl Gradient {
/// Creates a new linear gradient, in which colors transition along a
/// straight line.
///
/// ```example
/// #rect(
/// width: 100%,
/// height: 20pt,
/// fill: gradient.linear(
/// ..color.map.viridis,
/// ),
/// )
/// ```
#[func(title = "Linear Gradient")]
pub fn linear(
args: &mut Args,
span: Span,
/// The color [stops](#stops) of the gradient.
#[variadic]
stops: Vec<Spanned<GradientStop>>,
/// The color space in which to interpolate the gradient.
///
/// Defaults to a perceptually uniform color space called
/// [Oklab]($color.oklab).
#[named]
#[default(ColorSpace::Oklab)]
space: ColorSpace,
/// The [relative placement](#relativeness) of the gradient.
///
/// For an element placed at the root/top level of the document, the
/// parent is the page itself. For other elements, the parent is the
/// innermost block, box, column, grid, or stack that contains the
/// element.
#[named]
#[default(Smart::Auto)]
relative: Smart<RelativeTo>,
/// The direction of the gradient.
#[external]
#[default(Dir::LTR)]
dir: Dir,
/// The angle of the gradient.
#[external]
angle: Angle,
) -> SourceResult<Gradient> {
let angle = if let Some(angle) = args.named::<Angle>("angle")? {
angle
} else if let Some(dir) = args.named::<Dir>("dir")? {
match dir {
Dir::LTR => Angle::rad(0.0),
Dir::RTL => Angle::rad(PI),
Dir::TTB => Angle::rad(FRAC_PI_2),
Dir::BTT => Angle::rad(3.0 * FRAC_PI_2),
}
} else {
Angle::rad(0.0)
};
if stops.len() < 2 {
bail!(
span, "a gradient must have at least two stops";
hint: "try filling the shape with a single color instead";
);
}
Ok(Self::Linear(Arc::new(LinearGradient {
stops: process_stops(&stops)?,
angle,
space,
relative,
anti_alias: true,
})))
}
/// Creates a new radial gradient, in which colors radiate away from an
/// origin.
///
/// The gradient is defined by two circles: the focal circle and the end
/// circle. The focal circle is a circle with center `focal-center` and
/// radius `focal-radius`, that defines the points at which the gradient
/// starts and has the color of the first stop. The end circle is a circle
/// with center `center` and radius `radius`, that defines the points at
/// which the gradient ends and has the color of the last stop. The gradient
/// is then interpolated between these two circles.
///
/// Using these four values, also called the focal point for the starting
/// circle and the center and radius for the end circle, we can define a
/// gradient with more interesting properties than a basic radial gradient.
///
/// ```example
/// >>> #set circle(radius: 30pt)
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// circle(fill: gradient.radial(
/// ..color.map.viridis,
/// )),
/// circle(fill: gradient.radial(
/// ..color.map.viridis,
/// focal-center: (10%, 40%),
/// focal-radius: 5%,
/// )),
/// )
/// ```
#[func(title = "Radial Gradient")]
fn radial(
span: Span,
/// The color [stops](#stops) of the gradient.
#[variadic]
stops: Vec<Spanned<GradientStop>>,
/// The color space in which to interpolate the gradient.
///
/// Defaults to a perceptually uniform color space called
/// [Oklab]($color.oklab).
#[named]
#[default(ColorSpace::Oklab)]
space: ColorSpace,
/// The [relative placement](#relativeness) of the gradient.
///
/// For an element placed at the root/top level of the document, the parent
/// is the page itself. For other elements, the parent is the innermost block,
/// box, column, grid, or stack that contains the element.
#[named]
#[default(Smart::Auto)]
relative: Smart<RelativeTo>,
/// The center of the end circle of the gradient.
///
/// A value of `{(50%, 50%)}` means that the end circle is
/// centered inside of its container.
#[named]
#[default(Axes::splat(Ratio::new(0.5)))]
center: Axes<Ratio>,
/// The radius of the end circle of the gradient.
///
/// By default, it is set to `{50%}`. The ending radius must be bigger
/// than the focal radius.
#[named]
#[default(Spanned::detached(Ratio::new(0.5)))]
radius: Spanned<Ratio>,
/// The center of the focal circle of the gradient.
///
/// The focal center must be inside of the end circle.
///
/// A value of `{(50%, 50%)}` means that the focal circle is
/// centered inside of its container.
///
/// By default it is set to the same as the center of the last circle.
#[named]
#[default(Smart::Auto)]
focal_center: Smart<Axes<Ratio>>,
/// The radius of the focal circle of the gradient.
///
/// The focal center must be inside of the end circle.
///
/// By default, it is set to `{0%}`. The focal radius must be smaller
/// than the ending radius`.
#[named]
#[default(Spanned::detached(Ratio::new(0.0)))]
focal_radius: Spanned<Ratio>,
) -> SourceResult<Gradient> {
if stops.len() < 2 {
bail!(
span, "a gradient must have at least two stops";
hint: "try filling the shape with a single color instead";
);
}
if focal_radius.v > radius.v {
bail!(
focal_radius.span,
"the focal radius must be smaller than the end radius";
hint: "try using a focal radius of `0%` instead";
);
}
let focal_center = focal_center.unwrap_or(center);
let d_center_sqr = (focal_center.x - center.x).get().powi(2)
+ (focal_center.y - center.y).get().powi(2);
if d_center_sqr.sqrt() >= (radius.v - focal_radius.v).get() {
bail!(
span,
"the focal circle must be inside of the end circle";
hint: "try using a focal center of `auto` instead";
);
}
Ok(Gradient::Radial(Arc::new(RadialGradient {
stops: process_stops(&stops)?,
center: center.map(From::from),
radius: radius.v,
focal_center,
focal_radius: focal_radius.v,
space,
relative,
anti_alias: true,
})))
}
/// Creates a new conic gradient, in which colors change radially around a
/// center point.
///
/// You can control the center point of the gradient by using the `center`
/// argument. By default, the center point is the center of the shape.
///
/// ```example
/// >>> #set circle(radius: 30pt)
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// circle(fill: gradient.conic(
/// ..color.map.viridis,
/// )),
/// circle(fill: gradient.conic(
/// ..color.map.viridis,
/// center: (20%, 30%),
/// )),
/// )
/// ```
#[func(title = "Conic Gradient")]
pub fn conic(
span: Span,
/// The color [stops](#stops) of the gradient.
#[variadic]
stops: Vec<Spanned<GradientStop>>,
/// The angle of the gradient.
#[named]
#[default(Angle::zero())]
angle: Angle,
/// The color space in which to interpolate the gradient.
///
/// Defaults to a perceptually uniform color space called
/// [Oklab]($color.oklab).
#[named]
#[default(ColorSpace::Oklab)]
space: ColorSpace,
/// The [relative placement](#relativeness) of the gradient.
///
/// For an element placed at the root/top level of the document, the parent
/// is the page itself. For other elements, the parent is the innermost block,
/// box, column, grid, or stack that contains the element.
#[named]
#[default(Smart::Auto)]
relative: Smart<RelativeTo>,
/// The center of the circle of the gradient.
///
/// A value of `{(50%, 50%)}` means that the circle is centered inside
/// of its container.
#[named]
#[default(Axes::splat(Ratio::new(0.5)))]
center: Axes<Ratio>,
) -> SourceResult<Gradient> {
if stops.len() < 2 {
bail!(
span, "a gradient must have at least two stops";
hint: "try filling the shape with a single color instead";
);
}
Ok(Gradient::Conic(Arc::new(ConicGradient {
stops: process_stops(&stops)?,
angle,
center: center.map(From::from),
space,
relative,
anti_alias: true,
})))
}
/// Creates a sharp version of this gradient.
///
/// Sharp gradients have discrete jumps between colors, instead of a
/// smooth transition. They are particularly useful for creating color
/// lists for a preset gradient.
///
/// ```example
/// #set rect(width: 100%, height: 20pt)
/// #let grad = gradient.linear(..color.map.rainbow)
/// #rect(fill: grad)
/// #rect(fill: grad.sharp(5))
/// #rect(fill: grad.sharp(5, smoothness: 20%))
/// ```
#[func]
pub fn sharp(
&self,
/// The number of stops in the gradient.
steps: Spanned<usize>,
/// How much to smooth the gradient.
#[named]
#[default(Spanned::detached(Ratio::zero()))]
smoothness: Spanned<Ratio>,
) -> SourceResult<Gradient> {
if steps.v < 2 {
bail!(steps.span, "sharp gradients must have at least two stops");
}
if smoothness.v.get() < 0.0 || smoothness.v.get() > 1.0 {
bail!(smoothness.span, "smoothness must be between 0 and 1");
}
let n = steps.v;
let smoothness = smoothness.v.get();
let colors = (0..n)
.flat_map(|i| {
let c = self
.sample(RatioOrAngle::Ratio(Ratio::new(i as f64 / (n - 1) as f64)));
[c, c]
})
.collect::<Vec<_>>();
let mut positions = Vec::with_capacity(n * 2);
let index_to_progress = |i| i as f64 * 1.0 / n as f64;
let progress = smoothness * 1.0 / (4.0 * n as f64);
for i in 0..n {
let mut j = 2 * i;
positions.push(index_to_progress(i));
if j > 0 {
positions[j] += progress;
}
j += 1;
positions.push(index_to_progress(i + 1));
if j < colors.len() - 1 {
positions[j] -= progress;
}
}
let mut stops = colors
.into_iter()
.zip(positions)
.map(|(c, p)| (c, Ratio::new(p)))
.collect::<Vec<_>>();
stops.dedup();
Ok(match self {
Self::Linear(linear) => Self::Linear(Arc::new(LinearGradient {
stops,
angle: linear.angle,
space: linear.space,
relative: linear.relative,
anti_alias: false,
})),
Self::Radial(radial) => Self::Radial(Arc::new(RadialGradient {
stops,
center: radial.center,
radius: radial.radius,
focal_center: radial.focal_center,
focal_radius: radial.focal_radius,
space: radial.space,
relative: radial.relative,
anti_alias: false,
})),
Self::Conic(conic) => Self::Conic(Arc::new(ConicGradient {
stops,
angle: conic.angle,
center: conic.center,
space: conic.space,
relative: conic.relative,
anti_alias: false,
})),
})
}
/// Repeats this gradient a given number of times, optionally mirroring it
/// at every second repetition.
///
/// ```example
/// #circle(
/// radius: 40pt,
/// fill: gradient
/// .radial(aqua, white)
/// .repeat(4),
/// )
/// ```
#[func]
pub fn repeat(
&self,
/// The number of times to repeat the gradient.
repetitions: Spanned<usize>,
/// Whether to mirror the gradient at every second repetition, i.e.,
/// the first instance (and all odd ones) stays unchanged.
///
/// ```example
/// #circle(
/// radius: 40pt,
/// fill: gradient
/// .conic(green, black)
/// .repeat(2, mirror: true)
/// )
/// ```
#[named]
#[default(false)]
mirror: bool,
) -> SourceResult<Gradient> {
if repetitions.v == 0 {
bail!(repetitions.span, "must repeat at least once");
}
let n = repetitions.v;
let mut stops = std::iter::repeat_n(self.stops_ref(), n)
.enumerate()
.flat_map(|(i, stops)| {
let mut stops = stops
.iter()
.map(move |&(color, offset)| {
let r = offset.get();
if i % 2 == 1 && mirror {
(color, Ratio::new((i as f64 + 1.0 - r) / n as f64))
} else {
(color, Ratio::new((i as f64 + r) / n as f64))
}
})
.collect::<Vec<_>>();
if i % 2 == 1 && mirror {
stops.reverse();
}
stops
})
.collect::<Vec<_>>();
stops.dedup();
Ok(match self {
Self::Linear(linear) => Self::Linear(Arc::new(LinearGradient {
stops,
angle: linear.angle,
space: linear.space,
relative: linear.relative,
anti_alias: linear.anti_alias,
})),
Self::Radial(radial) => Self::Radial(Arc::new(RadialGradient {
stops,
center: radial.center,
radius: radial.radius,
focal_center: radial.focal_center,
focal_radius: radial.focal_radius,
space: radial.space,
relative: radial.relative,
anti_alias: radial.anti_alias,
})),
Self::Conic(conic) => Self::Conic(Arc::new(ConicGradient {
stops,
angle: conic.angle,
center: conic.center,
space: conic.space,
relative: conic.relative,
anti_alias: conic.anti_alias,
})),
})
}
/// Returns the kind of this gradient.
#[func]
pub fn kind(&self) -> Func {
match self {
Self::Linear(_) => Self::linear_data().into(),
Self::Radial(_) => Self::radial_data().into(),
Self::Conic(_) => Self::conic_data().into(),
}
}
/// Returns the stops of this gradient.
#[func]
pub fn stops(&self) -> Vec<GradientStop> {
match self {
Self::Linear(linear) => linear
.stops
.iter()
.map(|(color, offset)| GradientStop {
color: *color,
offset: Some(*offset),
})
.collect(),
Self::Radial(radial) => radial
.stops
.iter()
.map(|(color, offset)| GradientStop {
color: *color,
offset: Some(*offset),
})
.collect(),
Self::Conic(conic) => conic
.stops
.iter()
.map(|(color, offset)| GradientStop {
color: *color,
offset: Some(*offset),
})
.collect(),
}
}
/// Returns the mixing space of this gradient.
#[func]
pub fn space(&self) -> ColorSpace {
match self {
Self::Linear(linear) => linear.space,
Self::Radial(radial) => radial.space,
Self::Conic(conic) => conic.space,
}
}
/// Returns the relative placement of this gradient.
#[func]
pub fn relative(&self) -> Smart<RelativeTo> {
match self {
Self::Linear(linear) => linear.relative,
Self::Radial(radial) => radial.relative,
Self::Conic(conic) => conic.relative,
}
}
/// Returns the angle of this gradient.
///
/// Returns `{none}` if the gradient is neither linear nor conic.
#[func]
pub fn angle(&self) -> Option<Angle> {
match self {
Self::Linear(linear) => Some(linear.angle),
Self::Radial(_) => None,
Self::Conic(conic) => Some(conic.angle),
}
}
/// Returns the center of this gradient.
///
/// Returns `{none}` if the gradient is neither radial nor conic.
#[func]
pub fn center(&self) -> Option<Axes<Ratio>> {
match self {
Self::Linear(_) => None,
Self::Radial(radial) => Some(radial.center),
Self::Conic(conic) => Some(conic.center),
}
}
/// Returns the radius of this gradient.
///
/// Returns `{none}` if the gradient is not radial.
#[func]
pub fn radius(&self) -> Option<Ratio> {
match self {
Self::Linear(_) => None,
Self::Radial(radial) => Some(radial.radius),
Self::Conic(_) => None,
}
}
/// Returns the focal-center of this gradient.
///
/// Returns `{none}` if the gradient is not radial.
#[func]
pub fn focal_center(&self) -> Option<Axes<Ratio>> {
match self {
Self::Linear(_) => None,
Self::Radial(radial) => Some(radial.focal_center),
Self::Conic(_) => None,
}
}
/// Returns the focal-radius of this gradient.
///
/// Returns `{none}` if the gradient is not radial.
#[func]
pub fn focal_radius(&self) -> Option<Ratio> {
match self {
Self::Linear(_) => None,
Self::Radial(radial) => Some(radial.focal_radius),
Self::Conic(_) => None,
}
}
/// Sample the gradient at a given position.
///
/// The position is either a position along the gradient (a [ratio] between
/// `{0%}` and `{100%}`) or an [angle]. Any value outside of this range will
/// be clamped.
#[func]
pub fn sample(
&self,
/// The position at which to sample the gradient.
t: RatioOrAngle,
) -> Color {
let value: f64 = t.to_ratio().get();
match self {
Self::Linear(linear) => sample_stops(&linear.stops, linear.space, value),
Self::Radial(radial) => sample_stops(&radial.stops, radial.space, value),
Self::Conic(conic) => sample_stops(&conic.stops, conic.space, value),
}
}
/// Samples the gradient at multiple positions at once and returns the
/// results as an array.
#[func]
pub fn samples(
&self,
/// The positions at which to sample the gradient.
#[variadic]
ts: Vec<RatioOrAngle>,
) -> Array {
ts.into_iter().map(|t| self.sample(t).into_value()).collect()
}
}
impl Gradient {
/// Clones this gradient, but with a different relative placement.
pub fn with_relative(mut self, relative: RelativeTo) -> Self {
match &mut self {
Self::Linear(linear) => {
Arc::make_mut(linear).relative = Smart::Custom(relative);
}
Self::Radial(radial) => {
Arc::make_mut(radial).relative = Smart::Custom(relative);
}
Self::Conic(conic) => {
Arc::make_mut(conic).relative = Smart::Custom(relative);
}
}
self
}
/// Returns a reference to the stops of this gradient.
pub fn stops_ref(&self) -> &[(Color, Ratio)] {
match self {
Gradient::Linear(linear) => &linear.stops,
Gradient::Radial(radial) => &radial.stops,
Gradient::Conic(conic) => &conic.stops,
}
}
/// Samples the gradient at a given position, in the given container.
/// Handles the aspect ratio and angle directly.
pub fn sample_at(&self, (x, y): (f32, f32), (width, height): (f32, f32)) -> Color {
// Normalize the coordinates.
let (mut x, mut y) = (x / width, y / height);
let t = match self {
Self::Linear(linear) => {
// Aspect ratio correction.
let angle = Gradient::correct_aspect_ratio(
linear.angle,
Ratio::new((width / height) as f64),
)
.to_rad();
let (sin, cos) = angle.sin_cos();
let length = sin.abs() + cos.abs();
if angle > FRAC_PI_2 && angle < 3.0 * FRAC_PI_2 {
x = 1.0 - x;
}
if angle > PI {
y = 1.0 - y;
}
(x as f64 * cos.abs() + y as f64 * sin.abs()) / length
}
Self::Radial(radial) => {
// Source: @Enivex - https://typst.app/project/pYLeS0QyCCe8mf0pdnwoAI
let cr = radial.radius.get();
let fr = radial.focal_radius.get();
let z = Vec2::new(x as f64, y as f64);
let p = Vec2::new(radial.center.x.get(), radial.center.y.get());
let q =
Vec2::new(radial.focal_center.x.get(), radial.focal_center.y.get());
if (z - q).hypot() < fr {
0.0
} else if (z - p).hypot() > cr {
1.0
} else {
let uz = (z - q).normalize();
let az = (q - p).dot(uz);
let rho = cr.powi(2) - (q - p).hypot().powi(2);
let bz = (az.powi(2) + rho).sqrt() - az;
((z - q).hypot() - fr) / (bz - fr)
}
}
Self::Conic(conic) => {
let (x, y) =
(x as f64 - conic.center.x.get(), y as f64 - conic.center.y.get());
let angle = Gradient::correct_aspect_ratio(
conic.angle,
Ratio::new((width / height) as f64),
);
((-y.atan2(x) + PI + angle.to_rad()) % TAU) / TAU
}
};
self.sample(RatioOrAngle::Ratio(Ratio::new(t.clamp(0.0, 1.0))))
}
/// Does this gradient need to be anti-aliased?
pub fn anti_alias(&self) -> bool {
match self {
Self::Linear(linear) => linear.anti_alias,
Self::Radial(radial) => radial.anti_alias,
Self::Conic(conic) => conic.anti_alias,
}
}
/// Returns the relative placement of this gradient, handling
/// the special case of `auto`.
pub fn unwrap_relative(&self, on_text: bool) -> RelativeTo {
self.relative().unwrap_or_else(|| {
if on_text { RelativeTo::Parent } else { RelativeTo::Self_ }
})
}
/// Corrects this angle for the aspect ratio of a gradient.
///
/// This is used specifically for gradients.
pub fn correct_aspect_ratio(angle: Angle, aspect_ratio: Ratio) -> Angle {
let rad = (angle.to_rad().rem_euclid(TAU).tan() / aspect_ratio.get()).atan();
let rad = match angle.quadrant() {
Quadrant::First => rad,
Quadrant::Second => rad + PI,
Quadrant::Third => rad + PI,
Quadrant::Fourth => rad + TAU,
};
Angle::rad(rad.rem_euclid(TAU))
}
}
impl Debug for Gradient {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Linear(v) => v.fmt(f),
Self::Radial(v) => v.fmt(f),
Self::Conic(v) => v.fmt(f),
}
}
}
impl Repr for Gradient {
fn repr(&self) -> EcoString {
match self {
Self::Radial(radial) => radial.repr(),
Self::Linear(linear) => linear.repr(),
Self::Conic(conic) => conic.repr(),
}
}
}
/// A gradient that interpolates between two colors along an axis.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct LinearGradient {
| 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/visualize/image/svg.rs | crates/typst-library/src/visualize/image/svg.rs | use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
use comemo::Tracked;
use ecow::{EcoString, eco_format};
use rustc_hash::FxHashMap;
use siphasher::sip128::{Hasher128, SipHasher13};
use typst_syntax::FileId;
use crate::World;
use crate::diag::{FileError, LoadError, LoadResult, ReportPos, format_xml_like_error};
use crate::foundations::Bytes;
use crate::layout::Axes;
use crate::visualize::VectorFormat;
use crate::visualize::image::raster::{ExchangeFormat, RasterFormat};
use crate::visualize::image::{ImageFormat, determine_format_from_path};
use crate::text::{
Font, FontBook, FontFlags, FontStretch, FontStyle, FontVariant, FontWeight,
};
/// A decoded SVG.
#[derive(Clone, Hash)]
pub struct SvgImage(Arc<SvgImageInner>);
/// The internal representation of an [`SvgImage`].
struct SvgImageInner {
data: Bytes,
size: Axes<f64>,
font_hash: u128,
tree: usvg::Tree,
}
impl SvgImage {
/// Decode an SVG image without fonts.
#[comemo::memoize]
#[typst_macros::time(name = "load svg")]
pub fn new(data: Bytes) -> LoadResult<SvgImage> {
let tree =
usvg::Tree::from_data(&data, &base_options()).map_err(format_usvg_error)?;
Ok(Self(Arc::new(SvgImageInner {
data,
size: tree_size(&tree),
font_hash: 0,
tree,
})))
}
/// Decode an SVG image with access to fonts and linked images.
#[comemo::memoize]
#[typst_macros::time(name = "load svg")]
pub fn with_fonts_images(
data: Bytes,
world: Tracked<dyn World + '_>,
families: &[&str],
svg_file: Option<FileId>,
) -> LoadResult<SvgImage> {
let book = world.book();
let font_resolver = Mutex::new(FontResolver::new(world, book, families));
let image_resolver = Mutex::new(ImageResolver::new(world, svg_file));
let tree = usvg::Tree::from_data(
&data,
&usvg::Options {
font_resolver: usvg::FontResolver {
select_font: Box::new(|font, db| {
font_resolver.lock().unwrap().select_font(font, db)
}),
select_fallback: Box::new(|c, exclude_fonts, db| {
font_resolver.lock().unwrap().select_fallback(
c,
exclude_fonts,
db,
)
}),
},
image_href_resolver: usvg::ImageHrefResolver {
resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
resolve_string: Box::new(|href, _opts| {
image_resolver.lock().unwrap().load(href)
}),
},
..base_options()
},
)
.map_err(format_usvg_error)?;
if let Some(err) = image_resolver.into_inner().unwrap().error {
return Err(err);
}
let font_hash = font_resolver.into_inner().unwrap().finish();
Ok(Self(Arc::new(SvgImageInner {
data,
size: tree_size(&tree),
font_hash,
tree,
})))
}
/// The raw image data.
pub fn data(&self) -> &Bytes {
&self.0.data
}
/// The SVG's width in pixels.
pub fn width(&self) -> f64 {
self.0.size.x
}
/// The SVG's height in pixels.
pub fn height(&self) -> f64 {
self.0.size.y
}
/// Accesses the usvg tree.
pub fn tree(&self) -> &usvg::Tree {
&self.0.tree
}
}
impl Hash for SvgImageInner {
fn hash<H: Hasher>(&self, state: &mut H) {
// An SVG might contain fonts, which must be incorporated into the hash.
// We can't hash a usvg tree directly, but the raw SVG data + a hash of
// all used fonts gives us something similar.
self.data.hash(state);
self.font_hash.hash(state);
}
}
/// The base conversion options, to be extended with font-related options
/// because those can change across the document.
fn base_options() -> usvg::Options<'static> {
usvg::Options {
// Disable usvg's default to "Times New Roman".
font_family: String::new(),
// We don't override the DPI here, because we already
// force the image into the corresponding DPI by setting
// the width and height. Changing the DPI only trips up
// the logic in `resvg`.
// Override usvg's resource loading defaults.
resources_dir: None,
image_href_resolver: usvg::ImageHrefResolver {
resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
resolve_string: Box::new(|_, _| None),
},
..Default::default()
}
}
/// The pixel size of an SVG.
fn tree_size(tree: &usvg::Tree) -> Axes<f64> {
Axes::new(tree.size().width() as f64, tree.size().height() as f64)
}
/// Format the user-facing SVG decoding error message.
fn format_usvg_error(error: usvg::Error) -> LoadError {
let error = match error {
usvg::Error::NotAnUtf8Str => "file is not valid UTF-8",
usvg::Error::MalformedGZip => "file is not compressed correctly",
usvg::Error::ElementsLimitReached => "file is too large",
usvg::Error::InvalidSize => "width, height, or viewbox is invalid",
usvg::Error::ParsingFailed(error) => return format_xml_like_error("SVG", error),
};
LoadError::new(ReportPos::None, "failed to parse SVG", error)
}
/// Provides Typst's fonts to usvg.
struct FontResolver<'a> {
/// Typst's font book.
book: &'a FontBook,
/// The world we use to load fonts.
world: Tracked<'a, dyn World + 'a>,
/// The active list of font families at the location of the SVG.
families: &'a [&'a str],
/// A mapping from Typst font indices to fontdb IDs.
to_id: FxHashMap<usize, Option<fontdb::ID>>,
/// The reverse mapping.
from_id: FxHashMap<fontdb::ID, Font>,
/// Accumulates a hash of all used fonts.
hasher: SipHasher13,
}
impl<'a> FontResolver<'a> {
/// Create a new font provider.
fn new(
world: Tracked<'a, dyn World + 'a>,
book: &'a FontBook,
families: &'a [&'a str],
) -> Self {
Self {
book,
world,
families,
to_id: FxHashMap::default(),
from_id: FxHashMap::default(),
hasher: SipHasher13::new(),
}
}
/// Returns a hash of all used fonts.
fn finish(self) -> u128 {
self.hasher.finish128().as_u128()
}
}
impl FontResolver<'_> {
/// Select a font.
fn select_font(
&mut self,
font: &usvg::Font,
db: &mut Arc<fontdb::Database>,
) -> Option<fontdb::ID> {
let variant = FontVariant {
style: font.style().into(),
weight: FontWeight::from_number(font.weight()),
stretch: font.stretch().into(),
};
// Find a family that is available.
font.families()
.iter()
.filter_map(|family| match family {
usvg::FontFamily::Named(named) => Some(named.as_str()),
// We don't support generic families at the moment.
_ => None,
})
.chain(self.families.iter().copied())
.filter_map(|named| self.book.select(&named.to_lowercase(), variant))
.find_map(|index| self.get_or_load(index, db))
}
/// Select a fallback font.
fn select_fallback(
&mut self,
c: char,
exclude_fonts: &[fontdb::ID],
db: &mut Arc<fontdb::Database>,
) -> Option<fontdb::ID> {
// Get the font info of the originally selected font.
let like = exclude_fonts
.first()
.and_then(|first| self.from_id.get(first))
.map(|font| font.info());
// usvg doesn't provide a variant in the fallback handler, but
// `exclude_fonts` is actually never empty in practice. Still, we
// prefer to fall back to the default variant rather than panicking
// in case that changes in the future.
let variant = like.map(|info| info.variant).unwrap_or_default();
// Select the font.
let index =
self.book.select_fallback(like, variant, c.encode_utf8(&mut [0; 4]))?;
self.get_or_load(index, db)
}
/// Tries to retrieve the ID for the index or loads the font, allocating
/// a new ID.
fn get_or_load(
&mut self,
index: usize,
db: &mut Arc<fontdb::Database>,
) -> Option<fontdb::ID> {
self.to_id
.get(&index)
.copied()
.unwrap_or_else(|| self.load(index, db))
}
/// Tries to load the font with the given index in the font book into the
/// database and returns its ID.
fn load(
&mut self,
index: usize,
db: &mut Arc<fontdb::Database>,
) -> Option<fontdb::ID> {
let font = self.world.font(index)?;
let info = font.info();
let variant = info.variant;
let id = Arc::make_mut(db).push_face_info(fontdb::FaceInfo {
id: fontdb::ID::dummy(),
source: fontdb::Source::Binary(Arc::new(font.data().clone())),
index: font.index(),
families: vec![(
info.family.clone(),
ttf_parser::Language::English_UnitedStates,
)],
post_script_name: String::new(),
style: match variant.style {
FontStyle::Normal => fontdb::Style::Normal,
FontStyle::Italic => fontdb::Style::Italic,
FontStyle::Oblique => fontdb::Style::Oblique,
},
weight: fontdb::Weight(variant.weight.to_number()),
stretch: match variant.stretch.round() {
FontStretch::ULTRA_CONDENSED => ttf_parser::Width::UltraCondensed,
FontStretch::EXTRA_CONDENSED => ttf_parser::Width::ExtraCondensed,
FontStretch::CONDENSED => ttf_parser::Width::Condensed,
FontStretch::SEMI_CONDENSED => ttf_parser::Width::SemiCondensed,
FontStretch::NORMAL => ttf_parser::Width::Normal,
FontStretch::SEMI_EXPANDED => ttf_parser::Width::SemiExpanded,
FontStretch::EXPANDED => ttf_parser::Width::Expanded,
FontStretch::EXTRA_EXPANDED => ttf_parser::Width::ExtraExpanded,
FontStretch::ULTRA_EXPANDED => ttf_parser::Width::UltraExpanded,
_ => unreachable!(),
},
monospaced: info.flags.contains(FontFlags::MONOSPACE),
});
font.hash(&mut self.hasher);
self.to_id.insert(index, Some(id));
self.from_id.insert(id, font);
Some(id)
}
}
/// Resolves linked images in an SVG.
/// (Linked SVG images from an SVG are not supported yet.)
struct ImageResolver<'a> {
/// The world used to load linked images.
world: Tracked<'a, dyn World + 'a>,
/// Parent folder of the SVG file, used to resolve hrefs to linked images, if any.
svg_file: Option<FileId>,
/// The first error that occurred when loading a linked image, if any.
error: Option<LoadError>,
}
impl<'a> ImageResolver<'a> {
fn new(world: Tracked<'a, dyn World + 'a>, svg_file: Option<FileId>) -> Self {
Self { world, svg_file, error: None }
}
/// Load a linked image or return None if a previous image caused an error,
/// or if the linked image failed to load.
/// Only the first error message is retained.
fn load(&mut self, href: &str) -> Option<usvg::ImageKind> {
if self.error.is_some() {
return None;
}
match self.load_or_error(href) {
Ok(image) => Some(image),
Err(err) => {
self.error = Some(LoadError::new(
ReportPos::None,
eco_format!("failed to load linked image {} in SVG", href),
err,
));
None
}
}
}
/// Load a linked image or return an error message string.
fn load_or_error(&mut self, href: &str) -> Result<usvg::ImageKind, EcoString> {
// If the href starts with "file://", strip this prefix to construct an ordinary path.
let href = href.strip_prefix("file://").unwrap_or(href);
// Do not accept absolute hrefs. They would be parsed in Typst in a way
// that is not compatible with their interpretation in the SVG standard.
if href.starts_with("/") {
return Err("absolute paths are not allowed".into());
}
// Exit early if the href is an URL.
if let Some(pos) = href.find("://") {
let scheme = &href[..pos];
if scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
{
return Err("URLs are not allowed".into());
}
}
// Resolve the path to the linked image.
if self.svg_file.is_none() {
return Err("cannot access file system from here".into());
}
// Replace the file name in svg_file by href.
let href_file = self.svg_file.unwrap().join(href);
// Load image if file can be accessed.
match self.world.file(href_file) {
Ok(bytes) => {
let arc_data = Arc::new(bytes.to_vec());
let format = match determine_format_from_path(href) {
Some(format) => Some(format),
None => ImageFormat::detect(&arc_data),
};
match format {
Some(ImageFormat::Vector(vector_format)) => match vector_format {
VectorFormat::Svg => {
Err("SVG images are not supported yet".into())
}
VectorFormat::Pdf => {
Err("PDF documents are not supported".into())
}
},
Some(ImageFormat::Raster(raster_format)) => match raster_format {
RasterFormat::Exchange(exchange_format) => {
match exchange_format {
ExchangeFormat::Gif => Ok(usvg::ImageKind::GIF(arc_data)),
ExchangeFormat::Jpg => {
Ok(usvg::ImageKind::JPEG(arc_data))
}
ExchangeFormat::Png => Ok(usvg::ImageKind::PNG(arc_data)),
ExchangeFormat::Webp => {
Ok(usvg::ImageKind::WEBP(arc_data))
}
}
}
RasterFormat::Pixel(_) => {
Err("pixel formats are not supported".into())
}
},
None => Err("unknown image format".into()),
}
}
// TODO: Somehow unify this with `impl Display for FileError`.
Err(err) => Err(match err {
FileError::NotFound(path) => {
eco_format!("file not found, searched at {}", path.display())
}
FileError::AccessDenied => "access denied".into(),
FileError::IsDirectory => "is a directory".into(),
FileError::Other(Some(msg)) => msg,
FileError::Other(None) => "unspecified error".into(),
_ => eco_format!("unexpected error: {}", 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/visualize/image/mod.rs | crates/typst-library/src/visualize/image/mod.rs | //! Image handling.
mod pdf;
mod raster;
mod svg;
pub use self::pdf::PdfImage;
pub use self::raster::{
ExchangeFormat, PixelEncoding, PixelFormat, RasterFormat, RasterImage,
};
pub use self::svg::SvgImage;
use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize;
use std::sync::Arc;
use ecow::EcoString;
use hayro_syntax::LoadPdfError;
use typst_syntax::{Span, Spanned};
use typst_utils::{LazyHash, NonZeroExt};
use crate::diag::{At, LoadedWithin, SourceResult, StrResult, bail, warning};
use crate::engine::Engine;
use crate::foundations::{
Bytes, Cast, Content, Derived, NativeElement, Packed, Smart, StyleChain, Synthesize,
cast, elem, func, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Length, Rel, Sizing};
use crate::loading::{DataSource, Load, LoadSource, Loaded, Readable};
use crate::model::Figurable;
use crate::text::{LocalName, Locale, families};
use crate::visualize::image::pdf::PdfDocument;
/// A raster or vector graphic.
///
/// You can wrap the image in a [`figure`] to give it a number and caption.
///
/// Like most elements, images are _block-level_ by default and thus do not
/// integrate themselves into adjacent paragraphs. To force an image to become
/// inline, put it into a [`box`].
///
/// # Example
/// ```example
/// #figure(
/// image("molecular.jpg", width: 80%),
/// caption: [
/// A step in the molecular testing
/// pipeline of our lab.
/// ],
/// )
/// ```
#[elem(scope, Locatable, Tagged, Synthesize, LocalName, Figurable)]
pub struct ImageElem {
/// A [path]($syntax/#paths) to an image file or raw bytes making up an
/// image in one of the supported [formats]($image.format).
///
/// Bytes can be used to specify raw pixel data in a row-major,
/// left-to-right, top-to-bottom format.
///
/// ```example
/// #let original = read("diagram.svg")
/// #let changed = original.replace(
/// "#2B80FF", // blue
/// green.to-hex(),
/// )
///
/// #image(bytes(original))
/// #image(bytes(changed))
/// ```
#[required]
#[parse(
let source = args.expect::<Spanned<DataSource>>("source")?;
let loaded = source.load(engine.world)?;
Derived::new(source.v, loaded)
)]
pub source: Derived<DataSource, Loaded>,
/// The image's format.
///
/// By default, the format is detected automatically. Typically, you thus
/// only need to specify this when providing raw bytes as the
/// [`source`]($image.source) (even then, Typst will try to figure out the
/// format automatically, but that's not always possible).
///
/// Supported formats are `{"png"}`, `{"jpg"}`, `{"gif"}`, `{"svg"}`,
/// `{"pdf"}`, `{"webp"}` as well as raw pixel data.
///
/// Note that several restrictions apply when using PDF files as images:
///
/// - When exporting to PDF, any PDF image file used must have a version
/// equal to or lower than the [export target PDF
/// version]($pdf/#pdf-versions).
/// - PDF files as images are currently not supported when exporting with a
/// specific PDF standard, like PDF/A-3 or PDF/UA-1. In these cases, you
/// can instead use SVGs to embed vector images.
/// - The image file must not be password-protected.
/// - Tags in your PDF image will not be preserved. Instead, you must
/// provide an [alternative description]($image.alt) to make the image
/// accessible.
///
/// When providing raw pixel data as the `source`, you must specify a
/// dictionary with the following keys as the `format`:
/// - `encoding` ([str]): The encoding of the pixel data. One of:
/// - `{"rgb8"}` (three 8-bit channels: red, green, blue)
/// - `{"rgba8"}` (four 8-bit channels: red, green, blue, alpha)
/// - `{"luma8"}` (one 8-bit channel)
/// - `{"lumaa8"}` (two 8-bit channels: luma and alpha)
/// - `width` ([int]): The pixel width of the image.
/// - `height` ([int]): The pixel height of the image.
///
/// The pixel width multiplied by the height multiplied by the channel count
/// for the specified encoding must then match the `source` data.
///
/// ```example
/// #image(
/// read(
/// "tetrahedron.svg",
/// encoding: none,
/// ),
/// format: "svg",
/// width: 2cm,
/// )
///
/// #image(
/// bytes(range(16).map(x => x * 16)),
/// format: (
/// encoding: "luma8",
/// width: 4,
/// height: 4,
/// ),
/// width: 2cm,
/// )
/// ```
pub format: Smart<ImageFormat>,
/// The width of the image.
pub width: Smart<Rel<Length>>,
/// The height of the image.
pub height: Sizing,
/// An alternative description of the image.
///
/// This text is used by Assistive Technology (AT) like screen readers to
/// describe the image to users with visual impairments.
///
/// When the image is wrapped in a [`figure`]($figure), use this parameter
/// rather than the [figure's `alt` parameter]($figure.alt) to describe the
/// image. The only exception to this rule is when the image and the other
/// contents in the figure form a single semantic unit. In this case, use
/// the figure's `alt` parameter to describe the entire composition and do
/// not use this parameter.
///
/// You can learn how to write good alternative descriptions in the
/// [Accessibility Guide]($guides/accessibility/#textual-representations).
pub alt: Option<EcoString>,
/// The page number that should be embedded as an image. This attribute only
/// has an effect for PDF files.
#[default(NonZeroUsize::ONE)]
pub page: NonZeroUsize,
/// How the image should adjust itself to a given area (the area is defined
/// by the `width` and `height` fields). Note that `fit` doesn't visually
/// change anything if the area's aspect ratio is the same as the image's
/// one.
///
/// ```example
/// #set page(width: 300pt, height: 50pt, margin: 10pt)
/// #image("tiger.jpg", width: 100%, fit: "cover")
/// #image("tiger.jpg", width: 100%, fit: "contain")
/// #image("tiger.jpg", width: 100%, fit: "stretch")
/// ```
#[default(ImageFit::Cover)]
pub fit: ImageFit,
/// A hint to viewers how they should scale the image.
///
/// When set to `{auto}`, the default is left up to the viewer. For PNG
/// export, Typst will default to smooth scaling, like most PDF and SVG
/// viewers.
///
/// _Note:_ The exact look may differ across PDF viewers.
pub scaling: Smart<ImageScaling>,
/// An ICC profile for the image.
///
/// ICC profiles define how to interpret the colors in an image. When set
/// to `{auto}`, Typst will try to extract an ICC profile from the image.
#[parse(match args.named::<Spanned<Smart<DataSource>>>("icc")? {
Some(Spanned { v: Smart::Custom(source), span }) => Some(Smart::Custom({
let loaded = Spanned::new(&source, span).load(engine.world)?;
Derived::new(source, loaded.data)
})),
Some(Spanned { v: Smart::Auto, .. }) => Some(Smart::Auto),
None => None,
})]
pub icc: Smart<Derived<DataSource, Bytes>>,
/// The locale of this element (used for the alternative description).
#[internal]
#[synthesized]
pub locale: Locale,
}
impl Synthesize for Packed<ImageElem> {
fn synthesize(&mut self, _: &mut Engine, styles: StyleChain) -> SourceResult<()> {
self.locale = Some(Locale::get_in(styles));
Ok(())
}
}
#[scope]
#[allow(clippy::too_many_arguments)]
impl ImageElem {
/// Decode a raster or vector graphic from bytes or a string.
#[func(title = "Decode Image")]
#[deprecated(
message = "`image.decode` is deprecated, directly pass bytes to `image` instead",
until = "0.15.0"
)]
pub fn decode(
span: Span,
/// The data to decode as an image. Can be a string for SVGs.
data: Spanned<Readable>,
/// The image's format. Detected automatically by default.
#[named]
format: Option<Smart<ImageFormat>>,
/// The width of the image.
#[named]
width: Option<Smart<Rel<Length>>>,
/// The height of the image.
#[named]
height: Option<Sizing>,
/// A text describing the image.
#[named]
alt: Option<Option<EcoString>>,
/// How the image should adjust itself to a given area.
#[named]
fit: Option<ImageFit>,
/// A hint to viewers how they should scale the image.
#[named]
scaling: Option<Smart<ImageScaling>>,
) -> StrResult<Content> {
let bytes = data.v.into_bytes();
let loaded =
Loaded::new(Spanned::new(LoadSource::Bytes, data.span), bytes.clone());
let source = Derived::new(DataSource::Bytes(bytes), loaded);
let mut elem = ImageElem::new(source);
if let Some(format) = format {
elem.format.set(format);
}
if let Some(width) = width {
elem.width.set(width);
}
if let Some(height) = height {
elem.height.set(height);
}
if let Some(alt) = alt {
elem.alt.set(alt);
}
if let Some(fit) = fit {
elem.fit.set(fit);
}
if let Some(scaling) = scaling {
elem.scaling.set(scaling);
}
Ok(elem.pack().spanned(span))
}
}
impl Packed<ImageElem> {
/// Decodes the image.
pub fn decode(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Image> {
let span = self.span();
let loaded = &self.source.derived;
let format = self.determine_format(styles).at(span)?;
// Construct the image itself.
let kind = match format {
ImageFormat::Raster(format) => ImageKind::Raster(
RasterImage::new(
loaded.data.clone(),
format,
self.icc.get_ref(styles).as_ref().map(|icc| icc.derived.clone()),
)
.at(span)?,
),
ImageFormat::Vector(VectorFormat::Svg) => {
// Warn the user if the image contains a foreign object. Not
// perfect because the svg could also be encoded, but that's an
// edge case.
if memchr::memmem::find(&loaded.data, b"<foreignObject").is_some() {
engine.sink.warn(warning!(
span,
"image contains foreign object";
hint: "SVG images with foreign objects might render incorrectly \
in Typst";
hint: "see https://github.com/typst/typst/issues/1421 for more \
information";
));
}
// Identify the SVG file in case contained hrefs need to be resolved.
let svg_file = match self.source.source {
DataSource::Path(ref path) => span.resolve_path(path).ok(),
DataSource::Bytes(_) => span.id(),
};
ImageKind::Svg(
SvgImage::with_fonts_images(
loaded.data.clone(),
engine.world,
&families(styles).map(|f| f.as_str()).collect::<Vec<_>>(),
svg_file,
)
.within(loaded)?,
)
}
ImageFormat::Vector(VectorFormat::Pdf) => {
let document = match PdfDocument::new(loaded.data.clone()) {
Ok(doc) => doc,
Err(e) => match e {
// TODO: the `DecyptionError` is currently not public
LoadPdfError::Decryption(_) => {
bail!(
span,
"the PDF is encrypted or password-protected";
hint: "such PDFs are currently not supported";
hint: "preprocess the PDF to remove the encryption";
);
}
LoadPdfError::Invalid => {
bail!(
span,
"the PDF could not be loaded";
hint: "perhaps the PDF file is malformed";
);
}
},
};
// See https://github.com/LaurenzV/hayro/issues/141.
if document.pdf().xref().has_optional_content_groups() {
engine.sink.warn(warning!(
span,
"PDF contains optional content groups";
hint: "the image might display incorrectly in PDF export";
hint: "preprocess the PDF to flatten or remove optional content \
groups";
));
}
// The user provides the page number start from 1, but further
// down the pipeline, page numbers are 0-based.
let page_num = self.page.get(styles).get();
let page_idx = page_num - 1;
let num_pages = document.num_pages();
let Some(pdf_image) = PdfImage::new(document, page_idx) else {
let s = if num_pages == 1 { "" } else { "s" };
bail!(
span,
"page {page_num} does not exist";
hint: "the document only has {num_pages} page{s}";
);
};
ImageKind::Pdf(pdf_image)
}
};
Ok(Image::new(kind, self.alt.get_cloned(styles), self.scaling.get(styles)))
}
/// Tries to determine the image format based on the format that was
/// explicitly defined, or else the extension, or else the data.
fn determine_format(&self, styles: StyleChain) -> StrResult<ImageFormat> {
if let Smart::Custom(v) = self.format.get(styles) {
return Ok(v);
};
let Derived { source, derived: loaded } = &self.source;
if let DataSource::Path(path) = source
&& let Some(format) = determine_format_from_path(path.as_str())
{
return Ok(format);
}
Ok(ImageFormat::detect(&loaded.data).ok_or("unknown image format")?)
}
}
/// Derive the image format from the file extension of a path.
fn determine_format_from_path(path: &str) -> Option<ImageFormat> {
let ext = std::path::Path::new(path)
.extension()
.and_then(OsStr::to_str)
.unwrap_or_default()
.to_lowercase();
match ext.as_str() {
// Raster formats
"png" => Some(ExchangeFormat::Png.into()),
"jpg" | "jpeg" => Some(ExchangeFormat::Jpg.into()),
"gif" => Some(ExchangeFormat::Gif.into()),
"webp" => Some(ExchangeFormat::Webp.into()),
// Vector formats
"svg" | "svgz" => Some(VectorFormat::Svg.into()),
"pdf" => Some(VectorFormat::Pdf.into()),
_ => None,
}
}
impl LocalName for Packed<ImageElem> {
const KEY: &'static str = "figure";
}
impl Figurable for Packed<ImageElem> {}
/// How an image should adjust itself to a given area,
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum ImageFit {
/// The image should completely cover the area (preserves aspect ratio by
/// cropping the image only horizontally or vertically). This is the
/// default.
Cover,
/// The image should be fully contained in the area (preserves aspect
/// ratio; doesn't crop the image; one dimension can be narrower than
/// specified).
Contain,
/// The image should be stretched so that it exactly fills the area, even if
/// this means that the image will be distorted (doesn't preserve aspect
/// ratio and doesn't crop the image).
Stretch,
}
/// A loaded raster or vector image.
///
/// Values of this type are cheap to clone and hash.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct Image(Arc<LazyHash<ImageInner>>);
/// The internal representation of an [`Image`].
#[derive(Hash)]
struct ImageInner {
/// The raw, undecoded image data.
kind: ImageKind,
/// A text describing the image.
alt: Option<EcoString>,
/// The scaling algorithm to use.
scaling: Smart<ImageScaling>,
}
impl Image {
/// When scaling an image to it's natural size, we default to this DPI
/// if the image doesn't contain DPI metadata.
pub const DEFAULT_DPI: f64 = 72.0;
/// Should always be the same as the default DPI used by usvg.
pub const USVG_DEFAULT_DPI: f64 = 96.0;
/// Create an image from a `RasterImage` or `SvgImage`.
pub fn new(
kind: impl Into<ImageKind>,
alt: Option<EcoString>,
scaling: Smart<ImageScaling>,
) -> Self {
Self::new_impl(kind.into(), alt, scaling)
}
/// Create an image with optional properties set to the default.
pub fn plain(kind: impl Into<ImageKind>) -> Self {
Self::new(kind, None, Smart::Auto)
}
/// The internal, non-generic implementation. This is memoized to reuse
/// the `Arc` and `LazyHash`.
#[comemo::memoize]
fn new_impl(
kind: ImageKind,
alt: Option<EcoString>,
scaling: Smart<ImageScaling>,
) -> Image {
Self(Arc::new(LazyHash::new(ImageInner { kind, alt, scaling })))
}
/// The format of the image.
pub fn format(&self) -> ImageFormat {
match &self.0.kind {
ImageKind::Raster(raster) => raster.format().into(),
ImageKind::Svg(_) => VectorFormat::Svg.into(),
ImageKind::Pdf(_) => VectorFormat::Pdf.into(),
}
}
/// The width of the image in pixels.
pub fn width(&self) -> f64 {
match &self.0.kind {
ImageKind::Raster(raster) => raster.width() as f64,
ImageKind::Svg(svg) => svg.width(),
ImageKind::Pdf(pdf) => pdf.width() as f64,
}
}
/// The height of the image in pixels.
pub fn height(&self) -> f64 {
match &self.0.kind {
ImageKind::Raster(raster) => raster.height() as f64,
ImageKind::Svg(svg) => svg.height(),
ImageKind::Pdf(pdf) => pdf.height() as f64,
}
}
/// The image's pixel density in pixels per inch, if known.
pub fn dpi(&self) -> Option<f64> {
match &self.0.kind {
ImageKind::Raster(raster) => raster.dpi(),
ImageKind::Svg(_) => Some(Image::USVG_DEFAULT_DPI),
ImageKind::Pdf(_) => Some(Image::DEFAULT_DPI),
}
}
/// A text describing the image.
pub fn alt(&self) -> Option<&str> {
self.0.alt.as_deref()
}
/// The image scaling algorithm to use for this image.
pub fn scaling(&self) -> Smart<ImageScaling> {
self.0.scaling
}
/// The decoded image.
pub fn kind(&self) -> &ImageKind {
&self.0.kind
}
}
impl Debug for Image {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Image")
.field("format", &self.format())
.field("width", &self.width())
.field("height", &self.height())
.field("alt", &self.alt())
.field("scaling", &self.scaling())
.finish()
}
}
/// A kind of image.
#[derive(Clone, Hash)]
pub enum ImageKind {
/// A raster image.
Raster(RasterImage),
/// An SVG image.
Svg(SvgImage),
/// A PDF image.
Pdf(PdfImage),
}
impl From<RasterImage> for ImageKind {
fn from(image: RasterImage) -> Self {
Self::Raster(image)
}
}
impl From<SvgImage> for ImageKind {
fn from(image: SvgImage) -> Self {
Self::Svg(image)
}
}
/// A raster or vector image format.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ImageFormat {
/// A raster graphics format.
Raster(RasterFormat),
/// A vector graphics format.
Vector(VectorFormat),
}
impl ImageFormat {
/// Try to detect the format of an image from data.
pub fn detect(data: &[u8]) -> Option<Self> {
if let Some(format) = ExchangeFormat::detect(data) {
return Some(Self::Raster(RasterFormat::Exchange(format)));
}
if is_svg(data) {
return Some(Self::Vector(VectorFormat::Svg));
}
if is_pdf(data) {
return Some(Self::Vector(VectorFormat::Pdf));
}
None
}
}
/// Checks whether the data looks like a PDF file.
fn is_pdf(data: &[u8]) -> bool {
let head = &data[..data.len().min(2048)];
memchr::memmem::find(head, b"%PDF-").is_some()
}
/// Checks whether the data looks like an SVG or a compressed SVG.
fn is_svg(data: &[u8]) -> bool {
// Check for the gzip magic bytes. This check is perhaps a bit too
// permissive as other formats than SVGZ could use gzip.
if data.starts_with(&[0x1f, 0x8b]) {
return true;
}
// If the first 2048 bytes contain the SVG namespace declaration, we assume
// that it's an SVG. Note that, if the SVG does not contain a namespace
// declaration, usvg will reject it.
let head = &data[..data.len().min(2048)];
memchr::memmem::find(head, b"http://www.w3.org/2000/svg").is_some()
}
/// A vector graphics format.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum VectorFormat {
/// The vector graphics format of the web.
Svg,
/// High-fidelity document and graphics format, with focus on exact
/// reproduction in print.
Pdf,
}
impl<R> From<R> for ImageFormat
where
R: Into<RasterFormat>,
{
fn from(format: R) -> Self {
Self::Raster(format.into())
}
}
impl From<VectorFormat> for ImageFormat {
fn from(format: VectorFormat) -> Self {
Self::Vector(format)
}
}
cast! {
ImageFormat,
self => match self {
Self::Raster(v) => v.into_value(),
Self::Vector(v) => v.into_value(),
},
v: RasterFormat => Self::Raster(v),
v: VectorFormat => Self::Vector(v),
}
/// The image scaling algorithm a viewer should use.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum ImageScaling {
/// Scale with a smoothing algorithm such as bilinear interpolation.
Smooth,
/// Scale with nearest neighbor or a similar algorithm to preserve the
/// pixelated look of the image.
Pixelated,
}
| 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/visualize/image/pdf.rs | crates/typst-library/src/visualize/image/pdf.rs | use std::hash::{Hash, Hasher};
use std::sync::Arc;
use hayro_syntax::page::Page;
use hayro_syntax::{LoadPdfError, Pdf};
use crate::foundations::Bytes;
/// A PDF document.
#[derive(Clone, Hash)]
pub struct PdfDocument(Arc<PdfDocumentInner>);
/// The internal representation of a [`PdfDocument`].
struct PdfDocumentInner {
pdf: Arc<Pdf>,
data: Bytes,
}
impl PdfDocument {
/// Loads a PDF document.
#[comemo::memoize]
#[typst_macros::time(name = "load pdf document")]
pub fn new(data: Bytes) -> Result<PdfDocument, LoadPdfError> {
let pdf = Arc::new(Pdf::new(Arc::new(data.clone()))?);
Ok(Self(Arc::new(PdfDocumentInner { data, pdf })))
}
/// Returns the underlying PDF document.
pub fn pdf(&self) -> &Arc<Pdf> {
&self.0.pdf
}
/// Return the number of pages in the PDF.
pub fn num_pages(&self) -> usize {
self.0.pdf.pages().len()
}
}
impl Hash for PdfDocumentInner {
fn hash<H: Hasher>(&self, state: &mut H) {
self.data.hash(state);
}
}
/// A specific page of a PDF acting as an image.
#[derive(Clone, Hash)]
pub struct PdfImage(Arc<PdfImageInner>);
/// The internal representation of a [`PdfImage`].
struct PdfImageInner {
document: PdfDocument,
page_index: usize,
width: f32,
height: f32,
}
impl PdfImage {
/// Creates a new PDF image.
///
/// Returns `None` if the page index is not valid.
#[comemo::memoize]
pub fn new(document: PdfDocument, page_index: usize) -> Option<PdfImage> {
let (width, height) = document.0.pdf.pages().get(page_index)?.render_dimensions();
Some(Self(Arc::new(PdfImageInner { document, page_index, width, height })))
}
/// Returns the underlying Typst PDF document.
pub fn document(&self) -> &PdfDocument {
&self.0.document
}
/// Returns the PDF page of the image.
pub fn page(&self) -> &Page<'_> {
&self.document().pdf().pages()[self.0.page_index]
}
/// Returns the width of the image.
pub fn width(&self) -> f32 {
self.0.width
}
/// Returns the height of the image.
pub fn height(&self) -> f32 {
self.0.height
}
/// Returns the page index of the image.
pub fn page_index(&self) -> usize {
self.0.page_index
}
}
impl Hash for PdfImageInner {
fn hash<H: Hasher>(&self, state: &mut H) {
self.document.hash(state);
self.page_index.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/visualize/image/raster.rs | crates/typst-library/src/visualize/image/raster.rs | use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::io;
use std::sync::Arc;
use crate::diag::{StrResult, bail};
use crate::foundations::{Bytes, Cast, Dict, Smart, Value, cast, dict};
use ecow::{EcoString, eco_format};
use image::codecs::gif::GifDecoder;
use image::codecs::jpeg::JpegDecoder;
use image::codecs::png::PngDecoder;
use image::codecs::webp::WebPDecoder;
use image::{
DynamicImage, ImageBuffer, ImageDecoder, ImageResult, Limits, Pixel, guess_format,
};
/// A decoded raster image.
#[derive(Clone, Hash)]
pub struct RasterImage(Arc<RasterImageInner>);
/// The internal representation of a [`RasterImage`].
struct RasterImageInner {
data: Bytes,
format: RasterFormat,
dynamic: Arc<DynamicImage>,
exif_rotation: Option<u32>,
icc: Option<Bytes>,
dpi: Option<f64>,
}
impl RasterImage {
/// Decode a raster image.
pub fn new(
data: Bytes,
format: impl Into<RasterFormat>,
icc: Smart<Bytes>,
) -> StrResult<Self> {
Self::new_impl(data, format.into(), icc)
}
/// Create a raster image with optional properties set to the default.
pub fn plain(data: Bytes, format: impl Into<RasterFormat>) -> StrResult<Self> {
Self::new(data, format, Smart::Auto)
}
/// The internal, non-generic implementation.
#[comemo::memoize]
#[typst_macros::time(name = "load raster image")]
fn new_impl(
data: Bytes,
format: RasterFormat,
icc: Smart<Bytes>,
) -> StrResult<RasterImage> {
let mut exif_rot = None;
let (dynamic, icc, dpi) = match format {
RasterFormat::Exchange(format) => {
fn decode<T: ImageDecoder>(
decoder: ImageResult<T>,
icc: Smart<Bytes>,
) -> ImageResult<(image::DynamicImage, Option<Bytes>)> {
let mut decoder = decoder?;
let icc = icc.custom().or_else(|| {
decoder
.icc_profile()
.ok()
.flatten()
.filter(|icc| !icc.is_empty())
.map(Bytes::new)
});
decoder.set_limits(Limits::default())?;
let dynamic = image::DynamicImage::from_decoder(decoder)?;
Ok((dynamic, icc))
}
let cursor = io::Cursor::new(&data);
let (mut dynamic, icc) = match format {
ExchangeFormat::Jpg => decode(JpegDecoder::new(cursor), icc),
ExchangeFormat::Png => decode(PngDecoder::new(cursor), icc),
ExchangeFormat::Gif => decode(GifDecoder::new(cursor), icc),
ExchangeFormat::Webp => decode(WebPDecoder::new(cursor), icc),
}
.map_err(format_image_error)?;
let exif = exif::Reader::new()
.read_from_container(&mut std::io::Cursor::new(&data))
.ok();
// Apply rotation from EXIF metadata.
if let Some(rotation) = exif.as_ref().and_then(exif_rotation) {
apply_rotation(&mut dynamic, rotation);
exif_rot = Some(rotation);
}
// Extract pixel density.
let dpi = determine_dpi(&data, exif.as_ref());
(dynamic, icc, dpi)
}
RasterFormat::Pixel(format) => {
if format.width == 0 || format.height == 0 {
bail!("zero-sized images are not allowed");
}
let channels = match format.encoding {
PixelEncoding::Rgb8 => 3,
PixelEncoding::Rgba8 => 4,
PixelEncoding::Luma8 => 1,
PixelEncoding::Lumaa8 => 2,
};
let Some(expected_size) = format
.width
.checked_mul(format.height)
.and_then(|size| size.checked_mul(channels))
else {
bail!("pixel dimensions are too large");
};
if expected_size as usize != data.len() {
bail!("pixel dimensions and pixel data do not match");
}
fn to<P: Pixel<Subpixel = u8>>(
data: &Bytes,
format: PixelFormat,
) -> ImageBuffer<P, Vec<u8>> {
ImageBuffer::from_raw(format.width, format.height, data.to_vec())
.unwrap()
}
let dynamic = match format.encoding {
PixelEncoding::Rgb8 => to::<image::Rgb<u8>>(&data, format).into(),
PixelEncoding::Rgba8 => to::<image::Rgba<u8>>(&data, format).into(),
PixelEncoding::Luma8 => to::<image::Luma<u8>>(&data, format).into(),
PixelEncoding::Lumaa8 => to::<image::LumaA<u8>>(&data, format).into(),
};
(dynamic, icc.custom(), None)
}
};
Ok(Self(Arc::new(RasterImageInner {
data,
format,
exif_rotation: exif_rot,
dynamic: Arc::new(dynamic),
icc,
dpi,
})))
}
/// The raw image data.
pub fn data(&self) -> &Bytes {
&self.0.data
}
/// The image's format.
pub fn format(&self) -> RasterFormat {
self.0.format
}
/// The image's pixel width.
pub fn width(&self) -> u32 {
self.dynamic().width()
}
/// The image's pixel height.
pub fn height(&self) -> u32 {
self.dynamic().height()
}
/// The EXIF orientation value of the original image.
///
/// The [`dynamic`](Self::dynamic) image already has this factored in. This
/// value is only relevant to consumers of the raw [`data`](Self::data).
pub fn exif_rotation(&self) -> Option<u32> {
self.0.exif_rotation
}
/// The image's pixel density in pixels per inch, if known.
///
/// This is guaranteed to be positive.
pub fn dpi(&self) -> Option<f64> {
self.0.dpi
}
/// Access the underlying dynamic image.
pub fn dynamic(&self) -> &Arc<DynamicImage> {
&self.0.dynamic
}
/// Access the ICC profile, if any.
pub fn icc(&self) -> Option<&Bytes> {
self.0.icc.as_ref()
}
}
impl Hash for RasterImageInner {
fn hash<H: Hasher>(&self, state: &mut H) {
// The image is fully defined by data, format, and ICC profile.
self.data.hash(state);
self.format.hash(state);
self.icc.hash(state);
}
}
/// A raster graphics format.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum RasterFormat {
/// A format typically used in image exchange.
Exchange(ExchangeFormat),
/// A format of raw pixel data.
Pixel(PixelFormat),
}
impl From<ExchangeFormat> for RasterFormat {
fn from(format: ExchangeFormat) -> Self {
Self::Exchange(format)
}
}
impl From<PixelFormat> for RasterFormat {
fn from(format: PixelFormat) -> Self {
Self::Pixel(format)
}
}
cast! {
RasterFormat,
self => match self {
Self::Exchange(v) => v.into_value(),
Self::Pixel(v) => v.into_value(),
},
v: ExchangeFormat => Self::Exchange(v),
v: PixelFormat => Self::Pixel(v),
}
/// A raster format typically used in image exchange, with efficient encoding.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum ExchangeFormat {
/// Raster format for illustrations and transparent graphics.
Png,
/// Lossy raster format suitable for photos.
Jpg,
/// Raster format that is typically used for short animated clips. Typst can
/// load GIFs, but they will become static.
Gif,
/// Raster format that supports both lossy and lossless compression.
Webp,
}
impl ExchangeFormat {
/// Try to detect the format of data in a buffer.
pub fn detect(data: &[u8]) -> Option<Self> {
guess_format(data).ok().and_then(|format| format.try_into().ok())
}
}
impl From<ExchangeFormat> for image::ImageFormat {
fn from(format: ExchangeFormat) -> Self {
match format {
ExchangeFormat::Png => image::ImageFormat::Png,
ExchangeFormat::Jpg => image::ImageFormat::Jpeg,
ExchangeFormat::Gif => image::ImageFormat::Gif,
ExchangeFormat::Webp => image::ImageFormat::WebP,
}
}
}
impl TryFrom<image::ImageFormat> for ExchangeFormat {
type Error = EcoString;
fn try_from(format: image::ImageFormat) -> StrResult<Self> {
Ok(match format {
image::ImageFormat::Png => ExchangeFormat::Png,
image::ImageFormat::Jpeg => ExchangeFormat::Jpg,
image::ImageFormat::Gif => ExchangeFormat::Gif,
image::ImageFormat::WebP => ExchangeFormat::Webp,
_ => bail!("format not yet supported"),
})
}
}
/// Information that is needed to understand a pixmap buffer.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct PixelFormat {
/// The channel encoding.
encoding: PixelEncoding,
/// The pixel width.
width: u32,
/// The pixel height.
height: u32,
}
/// Determines the channel encoding of raw pixel data.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum PixelEncoding {
/// Three 8-bit channels: Red, green, blue.
Rgb8,
/// Four 8-bit channels: Red, green, blue, alpha.
Rgba8,
/// One 8-bit channel.
Luma8,
/// Two 8-bit channels: Luma and alpha.
Lumaa8,
}
cast! {
PixelFormat,
self => Value::Dict(self.into()),
mut dict: Dict => {
let format = Self {
encoding: dict.take("encoding")?.cast()?,
width: dict.take("width")?.cast()?,
height: dict.take("height")?.cast()?,
};
dict.finish(&["encoding", "width", "height"])?;
format
}
}
impl From<PixelFormat> for Dict {
fn from(format: PixelFormat) -> Self {
dict! {
"encoding" => format.encoding,
"width" => format.width,
"height" => format.height,
}
}
}
/// Try to get the rotation from the EXIF metadata.
fn exif_rotation(exif: &exif::Exif) -> Option<u32> {
exif.get_field(exif::Tag::Orientation, exif::In::PRIMARY)?
.value
.get_uint(0)
}
/// Apply an EXIF rotation to a dynamic image.
fn apply_rotation(image: &mut DynamicImage, rotation: u32) {
use image::imageops as ops;
match rotation {
2 => ops::flip_horizontal_in_place(image),
3 => ops::rotate180_in_place(image),
4 => ops::flip_vertical_in_place(image),
5 => {
ops::flip_horizontal_in_place(image);
*image = image.rotate270();
}
6 => *image = image.rotate90(),
7 => {
ops::flip_horizontal_in_place(image);
*image = image.rotate90();
}
8 => *image = image.rotate270(),
_ => {}
}
}
/// Try to determine the DPI (dots per inch) of the image.
///
/// This is guaranteed to be a positive value, or `None` if invalid or
/// unspecified.
fn determine_dpi(data: &[u8], exif: Option<&exif::Exif>) -> Option<f64> {
// Try to extract the DPI from the EXIF metadata. If that doesn't yield
// anything, fall back to specialized procedures for extracting JPEG or PNG
// DPI metadata. GIF does not have any.
exif.and_then(exif_dpi)
.or_else(|| jpeg_dpi(data))
.or_else(|| png_dpi(data))
.filter(|&dpi| dpi > 0.0)
}
/// Try to get the DPI from the EXIF metadata.
fn exif_dpi(exif: &exif::Exif) -> Option<f64> {
let axis = |tag| {
let dpi = exif.get_field(tag, exif::In::PRIMARY)?;
let exif::Value::Rational(rational) = &dpi.value else { return None };
Some(rational.first()?.to_f64())
};
[axis(exif::Tag::XResolution), axis(exif::Tag::YResolution)]
.into_iter()
.flatten()
.max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal))
}
/// Tries to extract the DPI from raw JPEG data (by inspecting the JFIF APP0
/// section).
fn jpeg_dpi(data: &[u8]) -> Option<f64> {
let validate_at = |index: usize, expect: &[u8]| -> Option<()> {
data.get(index..)?.starts_with(expect).then_some(())
};
let u16_at = |index: usize| -> Option<u16> {
data.get(index..index + 2)?.try_into().ok().map(u16::from_be_bytes)
};
validate_at(0, b"\xFF\xD8\xFF\xE0\0")?;
validate_at(6, b"JFIF\0")?;
validate_at(11, b"\x01")?;
let len = u16_at(4)?;
if len < 16 {
return None;
}
let units = *data.get(13)?;
let x = u16_at(14)?;
let y = u16_at(16)?;
let dpu = x.max(y) as f64;
Some(match units {
1 => dpu, // already inches
2 => dpu * 2.54, // cm -> inches
_ => return None,
})
}
/// Tries to extract the DPI from raw PNG data.
fn png_dpi(mut data: &[u8]) -> Option<f64> {
let mut decoder = png::StreamingDecoder::new();
let dims = loop {
let (consumed, event) = decoder.update(data, &mut Vec::new()).ok()?;
match event {
png::Decoded::PixelDimensions(dims) => break dims,
// Bail as soon as there is anything data-like.
png::Decoded::ChunkBegin(_, png::chunk::IDAT)
| png::Decoded::ImageData
| png::Decoded::ImageEnd => return None,
_ => {}
}
data = data.get(consumed..)?;
if consumed == 0 {
return None;
}
};
let dpu = dims.xppu.max(dims.yppu) as f64;
match dims.unit {
png::Unit::Meter => Some(dpu * 0.0254), // meter -> inches
png::Unit::Unspecified => None,
}
}
/// Format the user-facing raster graphic decoding error message.
fn format_image_error(error: image::ImageError) -> EcoString {
match error {
image::ImageError::Limits(_) => "file is too large".into(),
err => eco_format!("failed to decode image ({err})"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_dpi() {
#[track_caller]
fn test(path: &str, format: ExchangeFormat, dpi: f64) {
let data = typst_dev_assets::get(path).unwrap();
let bytes = Bytes::new(data);
let image = RasterImage::plain(bytes, format).unwrap();
assert_eq!(image.dpi().map(f64::round), Some(dpi));
}
test("images/f2t.jpg", ExchangeFormat::Jpg, 220.0);
test("images/tiger.jpg", ExchangeFormat::Jpg, 72.0);
test("images/graph.png", ExchangeFormat::Png, 144.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/text/case.rs | crates/typst-library/src/text/case.rs | use crate::foundations::{Cast, Content, Str, cast, func};
use crate::text::TextElem;
/// Converts a string or content to lowercase.
///
/// # Example
/// ```example
/// #lower("ABC") \
/// #lower[*My Text*] \
/// #lower[already low]
/// ```
#[func(title = "Lowercase")]
pub fn lower(
/// The text to convert to lowercase.
text: Caseable,
) -> Caseable {
case(text, Case::Lower)
}
/// Converts a string or content to uppercase.
///
/// # Example
/// ```example
/// #upper("abc") \
/// #upper[*my text*] \
/// #upper[ALREADY HIGH]
/// ```
#[func(title = "Uppercase")]
pub fn upper(
/// The text to convert to uppercase.
text: Caseable,
) -> Caseable {
case(text, Case::Upper)
}
/// Change the case of text.
fn case(text: Caseable, case: Case) -> Caseable {
match text {
Caseable::Str(v) => Caseable::Str(case.apply(&v).into()),
Caseable::Content(v) => Caseable::Content(v.set(TextElem::case, Some(case))),
}
}
/// A value whose case can be changed.
pub enum Caseable {
Str(Str),
Content(Content),
}
cast! {
Caseable,
self => match self {
Self::Str(v) => v.into_value(),
Self::Content(v) => v.into_value(),
},
v: Str => Self::Str(v),
v: Content => Self::Content(v),
}
/// A case transformation on text.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Case {
/// Everything is lowercased.
Lower,
/// Everything is uppercased.
Upper,
}
impl Case {
/// Apply the case to a string.
pub fn apply(self, text: &str) -> String {
match self {
Self::Lower => text.to_lowercase(),
Self::Upper => text.to_uppercase(),
}
}
}
| 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/text/linebreak.rs | crates/typst-library/src/text/linebreak.rs | use typst_utils::singleton;
use crate::foundations::{Content, NativeElement, elem};
/// Inserts a line break.
///
/// Advances the paragraph to the next line. A single trailing line break at the
/// end of a paragraph is ignored, but more than one creates additional empty
/// lines.
///
/// # Example
/// ```example
/// *Date:* 26.12.2022 \
/// *Topic:* Infrastructure Test \
/// *Severity:* High \
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: To insert a line break, simply write
/// a backslash followed by whitespace. This always creates an unjustified
/// break.
#[elem(title = "Line Break")]
pub struct LinebreakElem {
/// Whether to justify the line before the break.
///
/// This is useful if you found a better line break opportunity in your
/// justified text than Typst did.
///
/// ```example
/// #set par(justify: true)
/// #let jb = linebreak(justify: true)
///
/// I have manually tuned the #jb
/// line breaks in this paragraph #jb
/// for an _interesting_ result. #jb
/// ```
#[default(false)]
pub justify: bool,
}
impl LinebreakElem {
/// Get the globally shared linebreak element.
pub fn shared() -> &'static Content {
singleton!(Content, LinebreakElem::new().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/text/lorem.rs | crates/typst-library/src/text/lorem.rs | use crate::foundations::{Str, func};
/// Creates blind text.
///
/// This function yields a Latin-like _Lorem Ipsum_ blind text with the given
/// number of words. The sequence of words generated by the function is always
/// the same but randomly chosen. As usual for blind texts, it does not make any
/// sense. Use it as a placeholder to try layouts.
///
/// # Example
/// ```example
/// = Blind Text
/// #lorem(30)
///
/// = More Blind Text
/// #lorem(15)
/// ```
#[func(keywords = ["Blind Text"])]
pub fn lorem(
/// The length of the blind text in words.
words: usize,
) -> Str {
lipsum::lipsum(words).replace("--", "–").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/text/smallcaps.rs | crates/typst-library/src/text/smallcaps.rs | use crate::foundations::{Content, elem};
/// Displays text in small capitals.
///
/// # Example
/// ```example
/// Hello \
/// #smallcaps[Hello]
/// ```
///
/// # Smallcaps fonts
/// By default, this uses the `smcp` and `c2sc` OpenType features on the font.
/// Not all fonts support these features. Sometimes, smallcaps are part of a
/// dedicated font. This is, for example, the case for the _Latin Modern_ family
/// of fonts. In those cases, you can use a show-set rule to customize the
/// appearance of the text in smallcaps:
///
/// ```typ
/// #show smallcaps: set text(font: "Latin Modern Roman Caps")
/// ```
///
/// In the future, this function will support synthesizing smallcaps from normal
/// letters, but this is not yet implemented.
///
/// # Smallcaps headings
/// You can use a [show rule]($styling/#show-rules) to apply smallcaps
/// formatting to all your headings. In the example below, we also center-align
/// our headings and disable the standard bold font.
///
/// ```example
/// #set par(justify: true)
/// #set heading(numbering: "I.")
///
/// #show heading: smallcaps
/// #show heading: set align(center)
/// #show heading: set text(
/// weight: "regular"
/// )
///
/// = Introduction
/// #lorem(40)
/// ```
#[elem(title = "Small Capitals")]
pub struct SmallcapsElem {
/// Whether to turn uppercase letters into small capitals as well.
///
/// Unless overridden by a show rule, this enables the `c2sc` OpenType
/// feature.
///
/// ```example
/// #smallcaps(all: true)[UNICEF] is an
/// agency of #smallcaps(all: true)[UN].
/// ```
#[default(false)]
pub all: bool,
/// The content to display in small capitals.
#[required]
pub body: Content,
}
/// What becomes small capitals.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Smallcaps {
/// Minuscules become small capitals.
Minuscules,
/// All letters become small capitals.
All,
}
| 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/text/smartquote.rs | crates/typst-library/src/text/smartquote.rs | use ecow::EcoString;
use typst_syntax::is_newline;
use unicode_segmentation::UnicodeSegmentation;
use crate::diag::{HintedStrResult, StrResult, bail};
use crate::foundations::{
Array, Dict, FromValue, Packed, PlainText, Smart, Str, StyleChain, array, cast, dict,
elem,
};
use crate::layout::Dir;
use crate::text::{Lang, Region, TextElem};
/// A language-aware quote that reacts to its context.
///
/// Automatically turns into an appropriate opening or closing quote based on
/// the active [text language]($text.lang).
///
/// # Example
/// ```example
/// "This is in quotes."
///
/// #set text(lang: "de")
/// "Das ist in Anführungszeichen."
///
/// #set text(lang: "fr")
/// "C'est entre guillemets."
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: The normal quote characters
/// (`'` and `"`). Typst automatically makes your quotes smart.
#[elem(name = "smartquote", PlainText)]
pub struct SmartQuoteElem {
/// Whether this should be a double quote.
#[default(true)]
pub double: bool,
/// Whether smart quotes are enabled.
///
/// To disable smartness for a single quote, you can also escape it with a
/// backslash.
///
/// ```example
/// #set smartquote(enabled: false)
///
/// These are "dumb" quotes.
/// ```
#[default(true)]
pub enabled: bool,
/// Whether to use alternative quotes.
///
/// Does nothing for languages that don't have alternative quotes, or if
/// explicit quotes were set.
///
/// ```example
/// #set text(lang: "de")
/// #set smartquote(alternative: true)
///
/// "Das ist in anderen Anführungszeichen."
/// ```
#[default(false)]
pub alternative: bool,
/// The quotes to use.
///
/// - When set to `{auto}`, the appropriate single quotes for the
/// [text language]($text.lang) will be used. This is the default.
/// - Custom quotes can be passed as a string, array, or dictionary of either
/// - [string]($str): a string consisting of two characters containing the
/// opening and closing double quotes (characters here refer to Unicode
/// grapheme clusters)
/// - [array]: an array containing the opening and closing double quotes
/// - [dictionary]: a dictionary containing the double and single quotes, each
/// specified as either `{auto}`, string, or array
///
/// ```example
/// #set text(lang: "de")
/// 'Das sind normale Anführungszeichen.'
///
/// #set smartquote(quotes: "()")
/// "Das sind eigene Anführungszeichen."
///
/// #set smartquote(quotes: (single: ("[[", "]]"), double: auto))
/// 'Das sind eigene Anführungszeichen.'
/// ```
pub quotes: Smart<SmartQuoteDict>,
}
impl PlainText for Packed<SmartQuoteElem> {
fn plain_text(&self, text: &mut EcoString) {
text.push_str(SmartQuotes::fallback(self.double.as_option().unwrap_or(true)));
}
}
/// A smart quote substitutor with zero lookahead.
#[derive(Debug, Clone)]
pub struct SmartQuoter {
/// The amount of quotes that have been opened.
depth: u8,
/// Each bit indicates whether the quote at this nesting depth is a double.
/// Maximum supported depth is thus 32.
kinds: u32,
}
impl SmartQuoter {
/// Start quoting.
pub fn new() -> Self {
Self { depth: 0, kinds: 0 }
}
/// Determine which smart quote to substitute given this quoter's nesting
/// state and the character immediately preceding the quote.
pub fn quote<'a>(
&mut self,
before: Option<char>,
quotes: &SmartQuotes<'a>,
double: bool,
) -> &'a str {
let opened = self.top();
let before = before.unwrap_or(' ');
// If we are after a number and haven't most recently opened a quote of
// this kind, produce a prime. Otherwise, we prefer a closing quote.
if before.is_numeric() && opened != Some(double) {
return if double { "″" } else { "′" };
}
// If we have a single smart quote, didn't recently open a single
// quotation, and are after an alphabetic char or an object (e.g. a
// math equation), interpret this as an apostrophe.
if !double
&& opened != Some(false)
&& (before.is_alphabetic() || before == '\u{FFFC}')
{
return "’";
}
// If the most recently opened quotation is of this kind and the
// previous char does not indicate a nested quotation, close it.
if opened == Some(double)
&& !before.is_whitespace()
&& !is_newline(before)
&& !is_opening_bracket(before)
{
self.pop();
return quotes.close(double);
}
// Otherwise, open a new the quotation.
self.push(double);
quotes.open(double)
}
/// The top of our quotation stack. Returns `Some(double)` for the most
/// recently opened quote or `None` if we didn't open one.
fn top(&self) -> Option<bool> {
self.depth.checked_sub(1).map(|i| (self.kinds >> i) & 1 == 1)
}
/// Push onto the quotation stack.
fn push(&mut self, double: bool) {
if self.depth < 32 {
self.kinds |= (double as u32) << self.depth;
self.depth += 1;
}
}
/// Pop from the quotation stack.
fn pop(&mut self) {
self.depth -= 1;
self.kinds &= (1 << self.depth) - 1;
}
}
impl Default for SmartQuoter {
fn default() -> Self {
Self::new()
}
}
/// Whether the character is an opening bracket, parenthesis, or brace.
fn is_opening_bracket(c: char) -> bool {
matches!(c, '(' | '{' | '[')
}
/// Decides which quotes to substitute smart quotes with.
pub struct SmartQuotes<'s> {
/// The opening single quote.
pub single_open: &'s str,
/// The closing single quote.
pub single_close: &'s str,
/// The opening double quote.
pub double_open: &'s str,
/// The closing double quote.
pub double_close: &'s str,
}
impl<'s> SmartQuotes<'s> {
/// Retrieve the smart quotes as configured by the current styles.
pub fn get_in(styles: StyleChain<'s>) -> Self {
Self::get(
styles.get_ref(SmartQuoteElem::quotes),
styles.get(TextElem::lang),
styles.get(TextElem::region),
styles.get(SmartQuoteElem::alternative),
)
}
/// Create a new `Quotes` struct with the given quotes, optionally falling
/// back to the defaults for a language and region.
///
/// The language should be specified as an all-lowercase ISO 639-1 code, the
/// region as an all-uppercase ISO 3166-alpha2 code.
///
/// Currently, the supported languages are: English, Czech, Danish, German,
/// Swiss / Liechtensteinian German, Estonian, Icelandic, Italian, Latin,
/// Lithuanian, Latvian, Slovak, Slovenian, Spanish, Bosnian, Finnish,
/// Swedish, French, Swiss French, Hungarian, Polish, Romanian, Japanese,
/// Traditional Chinese, Russian, Norwegian, Hebrew and Croatian.
///
/// For unknown languages, the English quotes are used as fallback.
pub fn get(
quotes: &'s Smart<SmartQuoteDict>,
lang: Lang,
region: Option<Region>,
alternative: bool,
) -> Self {
let region = region.as_ref().map(Region::as_str);
let default = ("‘", "’", "“", "”");
let low_high = ("‚", "‘", "„", "“");
let (single_open, single_close, double_open, double_close) = match lang.as_str() {
"de" if matches!(region, Some("CH" | "LI")) => match alternative {
false => ("‹", "›", "«", "»"),
true => low_high,
},
"fr" if matches!(region, Some("CH")) => match alternative {
false => ("‹\u{202F}", "\u{202F}›", "«\u{202F}", "\u{202F}»"),
true => default,
},
"cs" | "da" | "de" | "sk" | "sl" if alternative => ("›", "‹", "»", "«"),
"cs" | "de" | "et" | "is" | "lt" | "lv" | "sk" | "sl" => low_high,
"da" => ("‘", "’", "“", "”"),
"fr" if alternative => default,
"fr" => ("“", "”", "«\u{202F}", "\u{202F}»"),
"fi" | "sv" if alternative => ("’", "’", "»", "»"),
"bs" | "fi" | "sv" => ("’", "’", "”", "”"),
"it" if alternative => default,
"la" if alternative => ("“", "”", "«\u{202F}", "\u{202F}»"),
"it" | "la" => ("“", "”", "«", "»"),
"es" if matches!(region, Some("ES") | None) => ("“", "”", "«", "»"),
"hu" | "pl" | "ro" => ("’", "’", "„", "”"),
"no" | "nb" | "nn" if alternative => low_high,
"no" | "nb" | "nn" => ("’", "’", "«", "»"),
"ru" => ("„", "“", "«", "»"),
"uk" => ("“", "”", "«", "»"),
"el" => ("‘", "’", "«", "»"),
"he" => ("’", "’", "”", "”"),
"hr" => ("‘", "’", "„", "”"),
"bg" => ("’", "’", "„", "“"),
"ar" if !alternative => ("’", "‘", "«", "»"),
_ if lang.dir() == Dir::RTL => ("’", "‘", "”", "“"),
_ => default,
};
fn inner_or_default<'s>(
quotes: Smart<&'s SmartQuoteDict>,
f: impl FnOnce(&'s SmartQuoteDict) -> Smart<&'s SmartQuoteSet>,
default: [&'s str; 2],
) -> [&'s str; 2] {
match quotes.and_then(f) {
Smart::Auto => default,
Smart::Custom(SmartQuoteSet { open, close }) => {
[open, close].map(|s| s.as_str())
}
}
}
let quotes = quotes.as_ref();
let [single_open, single_close] =
inner_or_default(quotes, |q| q.single.as_ref(), [single_open, single_close]);
let [double_open, double_close] =
inner_or_default(quotes, |q| q.double.as_ref(), [double_open, double_close]);
Self {
single_open,
single_close,
double_open,
double_close,
}
}
/// The opening quote.
pub fn open(&self, double: bool) -> &'s str {
if double { self.double_open } else { self.single_open }
}
/// The closing quote.
pub fn close(&self, double: bool) -> &'s str {
if double { self.double_close } else { self.single_close }
}
/// Get the fallback "dumb" quotes for when smart quotes are disabled.
pub fn fallback(double: bool) -> &'static str {
if double { "\"" } else { "'" }
}
}
/// An opening and closing quote.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct SmartQuoteSet {
open: EcoString,
close: EcoString,
}
cast! {
SmartQuoteSet,
self => array![self.open, self.close].into_value(),
value: Array => {
let [open, close] = array_to_set(value)?;
Self { open, close }
},
value: Str => {
let [open, close] = str_to_set(value.as_str())?;
Self { open, close }
},
}
fn str_to_set(value: &str) -> StrResult<[EcoString; 2]> {
let mut iter = value.graphemes(true);
match (iter.next(), iter.next(), iter.next()) {
(Some(open), Some(close), None) => Ok([open.into(), close.into()]),
_ => {
let count = value.graphemes(true).count();
bail!(
"expected 2 characters, found {count} character{}",
if count > 1 { "s" } else { "" },
);
}
}
}
fn array_to_set(value: Array) -> HintedStrResult<[EcoString; 2]> {
let value = value.as_slice();
if value.len() != 2 {
bail!(
"expected 2 quotes, found {} quote{}",
value.len(),
if value.len() > 1 { "s" } else { "" },
);
}
let open: EcoString = value[0].clone().cast()?;
let close: EcoString = value[1].clone().cast()?;
Ok([open, close])
}
/// A dict of single and double quotes.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct SmartQuoteDict {
double: Smart<SmartQuoteSet>,
single: Smart<SmartQuoteSet>,
}
cast! {
SmartQuoteDict,
self => dict! { "double" => self.double, "single" => self.single }.into_value(),
mut value: Dict => {
let keys = ["double", "single"];
let double = value
.take("double")
.ok()
.map(FromValue::from_value)
.transpose()?
.unwrap_or(Smart::Auto);
let single = value
.take("single")
.ok()
.map(FromValue::from_value)
.transpose()?
.unwrap_or(Smart::Auto);
value.finish(&keys)?;
Self { single, double }
},
value: SmartQuoteSet => Self {
double: Smart::Custom(value),
single: Smart::Auto,
},
}
| 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/text/shift.rs | crates/typst-library/src/text/shift.rs | use crate::introspection::Tagged;
use ttf_parser::Tag;
use crate::foundations::{Content, Smart, elem};
use crate::layout::{Em, Length};
use crate::text::{FontMetrics, ScriptMetrics, TextSize};
/// Renders text in subscript.
///
/// The text is rendered smaller and its baseline is lowered.
///
/// # Example
/// ```example
/// Revenue#sub[yearly]
/// ```
#[elem(title = "Subscript", Tagged)]
pub struct SubElem {
/// Whether to use subscript glyphs from the font if available.
///
/// Ideally, subscripts glyphs are provided by the font (using the `subs`
/// OpenType feature). Otherwise, Typst is able to synthesize subscripts by
/// lowering and scaling down regular glyphs.
///
/// When this is set to `{false}`, synthesized glyphs will be used
/// regardless of whether the font provides dedicated subscript glyphs. When
/// `{true}`, synthesized glyphs may still be used in case the font does not
/// provide the necessary subscript glyphs.
///
/// ```example
/// N#sub(typographic: true)[1]
/// N#sub(typographic: false)[1]
/// ```
#[default(true)]
pub typographic: bool,
/// The downward baseline shift for synthesized subscripts.
///
/// This only applies to synthesized subscripts. In other words, this has no
/// effect if `typographic` is `{true}` and the font provides the necessary
/// subscript glyphs.
///
/// If set to `{auto}`, the baseline is shifted according to the metrics
/// provided by the font, with a fallback to `{0.2em}` in case the font does
/// not define the necessary metrics.
pub baseline: Smart<Length>,
/// The font size for synthesized subscripts.
///
/// This only applies to synthesized subscripts. In other words, this has no
/// effect if `typographic` is `{true}` and the font provides the necessary
/// subscript glyphs.
///
/// If set to `{auto}`, the size is scaled according to the metrics provided
/// by the font, with a fallback to `{0.6em}` in case the font does not
/// define the necessary metrics.
pub size: Smart<TextSize>,
/// The text to display in subscript.
#[required]
pub body: Content,
}
/// Renders text in superscript.
///
/// The text is rendered smaller and its baseline is raised.
///
/// # Example
/// ```example
/// 1#super[st] try!
/// ```
#[elem(title = "Superscript", Tagged)]
pub struct SuperElem {
/// Whether to use superscript glyphs from the font if available.
///
/// Ideally, superscripts glyphs are provided by the font (using the `sups`
/// OpenType feature). Otherwise, Typst is able to synthesize superscripts
/// by raising and scaling down regular glyphs.
///
/// When this is set to `{false}`, synthesized glyphs will be used
/// regardless of whether the font provides dedicated superscript glyphs.
/// When `{true}`, synthesized glyphs may still be used in case the font
/// does not provide the necessary superscript glyphs.
///
/// ```example
/// N#super(typographic: true)[1]
/// N#super(typographic: false)[1]
/// ```
#[default(true)]
pub typographic: bool,
/// The downward baseline shift for synthesized superscripts.
///
/// This only applies to synthesized superscripts. In other words, this has
/// no effect if `typographic` is `{true}` and the font provides the
/// necessary superscript glyphs.
///
/// If set to `{auto}`, the baseline is shifted according to the metrics
/// provided by the font, with a fallback to `{-0.5em}` in case the font
/// does not define the necessary metrics.
///
/// Note that, since the baseline shift is applied downward, you will need
/// to provide a negative value for the content to appear as raised above
/// the normal baseline.
pub baseline: Smart<Length>,
/// The font size for synthesized superscripts.
///
/// This only applies to synthesized superscripts. In other words, this has
/// no effect if `typographic` is `{true}` and the font provides the
/// necessary superscript glyphs.
///
/// If set to `{auto}`, the size is scaled according to the metrics provided
/// by the font, with a fallback to `{0.6em}` in case the font does not
/// define the necessary metrics.
pub size: Smart<TextSize>,
/// The text to display in superscript.
#[required]
pub body: Content,
}
/// Configuration values for sub- or superscript text.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct ShiftSettings {
/// Whether the OpenType feature should be used if possible.
pub typographic: bool,
/// The baseline shift of the script, relative to the outer text size.
///
/// For superscripts, this is positive. For subscripts, this is negative. A
/// value of [`Smart::Auto`] indicates that the value should be obtained
/// from font metrics.
pub shift: Smart<Em>,
/// The size of the script, relative to the outer text size.
///
/// A value of [`Smart::Auto`] indicates that the value should be obtained
/// from font metrics.
pub size: Smart<Em>,
/// The kind of script (either a subscript, or a superscript).
///
/// This is used to know which OpenType table to use to resolve
/// [`Smart::Auto`] values.
pub kind: ScriptKind,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ScriptKind {
Sub,
Super,
}
impl ScriptKind {
/// Returns the default metrics for this script kind.
///
/// This can be used as a last resort if neither the user nor the font
/// provided those metrics.
pub fn default_metrics(self) -> &'static ScriptMetrics {
match self {
Self::Sub => &DEFAULT_SUBSCRIPT_METRICS,
Self::Super => &DEFAULT_SUPERSCRIPT_METRICS,
}
}
/// Reads the script metrics from the font table for to this script kind.
pub fn read_metrics(self, font_metrics: &FontMetrics) -> &ScriptMetrics {
match self {
Self::Sub => font_metrics.subscript.as_ref(),
Self::Super => font_metrics.superscript.as_ref(),
}
.unwrap_or(self.default_metrics())
}
/// The corresponding OpenType feature.
pub const fn feature(self) -> Tag {
match self {
Self::Sub => Tag::from_bytes(b"subs"),
Self::Super => Tag::from_bytes(b"sups"),
}
}
}
pub static DEFAULT_SUBSCRIPT_METRICS: ScriptMetrics = ScriptMetrics {
width: Em::new(0.6),
height: Em::new(0.6),
horizontal_offset: Em::zero(),
vertical_offset: Em::new(-0.2),
};
pub static DEFAULT_SUPERSCRIPT_METRICS: ScriptMetrics = ScriptMetrics {
width: Em::new(0.6),
height: Em::new(0.6),
horizontal_offset: Em::zero(),
vertical_offset: Em::new(0.5),
};
| 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/text/raw.rs | crates/typst-library/src/text/raw.rs | use std::cell::LazyCell;
use std::ops::Range;
use std::sync::{Arc, LazyLock};
use comemo::Tracked;
use ecow::{EcoString, EcoVec};
use syntect::highlighting::{self as synt};
use syntect::parsing::{ParseSyntaxError, SyntaxDefinition, SyntaxSet, SyntaxSetBuilder};
use typst_syntax::{LinkedNode, Span, Spanned, split_newlines};
use typst_utils::ManuallyHash;
use unicode_segmentation::UnicodeSegmentation;
use super::Lang;
use crate::World;
use crate::diag::{
LineCol, LoadError, LoadResult, LoadedWithin, ReportPos, SourceResult,
};
use crate::engine::Engine;
use crate::foundations::{
Bytes, Content, Derived, OneOrMultiple, Packed, PlainText, ShowSet, Smart,
StyleChain, Styles, Synthesize, Target, TargetElem, cast, elem, scope,
};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Em, HAlignment};
use crate::loading::{DataSource, Load};
use crate::model::{Figurable, ParElem};
use crate::routines::Routines;
use crate::text::{FontFamily, FontList, LocalName, TextElem, TextSize};
use crate::visualize::Color;
/// Raw text with optional syntax highlighting.
///
/// Displays the text verbatim and in a monospace font. This is typically used
/// to embed computer code into your document.
///
/// Note that text given to this element cannot contain arbitrary formatting,
/// such as `[*strong*]` or `[_emphasis_]`, as it is displayed verbatim. If
/// you'd like to display any kind of content with a monospace font, instead of
/// using [`raw`], you should change its font to a monospace font using the
/// [`text`]($text) function.
///
/// # Example
/// ````example
/// Adding `rbx` to `rcx` gives
/// the desired result.
///
/// What is ```rust fn main()``` in Rust
/// would be ```c int main()``` in C.
///
/// ```rust
/// fn main() {
/// println!("Hello World!");
/// }
/// ```
///
/// This has ``` `backticks` ``` in it
/// (but the spaces are trimmed). And
/// ``` here``` the leading space is
/// also trimmed.
/// ````
///
/// You can also construct a [`raw`] element programmatically from a string (and
/// provide the language tag via the optional [`lang`]($raw.lang) argument).
/// ```example
/// #raw("fn " + "main() {}", lang: "rust")
/// ```
///
/// # Syntax
/// This function also has dedicated syntax. You can enclose text in 1 or 3+
/// backticks (`` ` ``) to make it raw. Two backticks produce empty raw text.
/// This works both in markup and code.
///
/// When you use three or more backticks, you can additionally specify a
/// language tag for syntax highlighting directly after the opening backticks.
/// Within raw blocks, everything (except for the language tag, if applicable)
/// is rendered as is, in particular, there are no escape sequences.
///
/// The language tag ends at the first whitespace or backtick. If your text
/// starts with something that looks like an identifier, but no syntax
/// highlighting is needed, start the text with a single space (which will be
/// trimmed) or use the single backtick syntax. If your text should start or end
/// with a backtick, put a space before or after it (it will be trimmed).
///
/// If no syntax highlighting is available by default for your specified
/// language tag (or if you want to override the built-in definition), you may
/// provide a custom syntax specification file to the
/// [`syntaxes`]($raw.syntaxes) field.
///
/// # Styling
/// By default, the `raw` element uses the `DejaVu Sans Mono` font (included
/// with Typst), with a smaller font size of `{0.8em}` (that is, 80% of
/// the global font size). This is because monospace fonts tend to be visually
/// larger than non-monospace fonts.
///
/// You can customize these properties with show-set rules:
///
/// ````example
/// // Switch to Cascadia Code for both
/// // inline and block raw.
/// #show raw: set text(font: "Cascadia Code")
///
/// // Reset raw blocks to the same size as normal text,
/// // but keep inline raw at the reduced size.
/// #show raw.where(block: true): set text(1em / 0.8)
///
/// Now using the `Cascadia Code` font for raw text.
/// Here's some Python code. It looks larger now:
///
/// ```py
/// def python():
/// return 5 + 5
/// ```
/// ````
///
/// In addition, you can customize the syntax highlighting colors by setting
/// a custom theme through the [`theme`]($raw.theme) field.
///
/// For complete customization of the appearance of a raw block, a show rule
/// on [`raw.line`]($raw.line) could be helpful, such as to add line numbers.
///
/// Note that, in raw text, typesetting features like
/// [hyphenation]($text.hyphenate), [overhang]($text.overhang),
/// [CJK-Latin spacing]($text.cjk-latin-spacing) (and
/// [justification]($par.justify) for [raw blocks]($raw.block)) will be
/// disabled by default.
#[elem(
scope,
title = "Raw Text / Code",
Synthesize,
Locatable,
Tagged,
ShowSet,
LocalName,
Figurable,
PlainText
)]
pub struct RawElem {
/// The raw text.
///
/// You can also use raw blocks creatively to create custom syntaxes for
/// your automations.
///
/// ````example:"Implementing a DSL using raw and show rules"
/// // Parse numbers in raw blocks with the
/// // `mydsl` tag and sum them up.
/// #show raw.where(lang: "mydsl"): it => {
/// let sum = 0
/// for part in it.text.split("+") {
/// sum += int(part.trim())
/// }
/// sum
/// }
///
/// ```mydsl
/// 1 + 2 + 3 + 4 + 5
/// ```
/// ````
#[required]
pub text: RawContent,
/// Whether the raw text is displayed as a separate block.
///
/// In markup mode, using one-backtick notation makes this `{false}`.
/// Using three-backtick notation makes it `{true}` if the enclosed content
/// contains at least one line break.
///
/// ````example
/// // Display inline code in a small box
/// // that retains the correct baseline.
/// #show raw.where(block: false): box.with(
/// fill: luma(240),
/// inset: (x: 3pt, y: 0pt),
/// outset: (y: 3pt),
/// radius: 2pt,
/// )
///
/// // Display block code in a larger block
/// // with more padding.
/// #show raw.where(block: true): block.with(
/// fill: luma(240),
/// inset: 10pt,
/// radius: 4pt,
/// )
///
/// With `rg`, you can search through your files quickly.
/// This example searches the current directory recursively
/// for the text `Hello World`:
///
/// ```bash
/// rg "Hello World"
/// ```
/// ````
#[default(false)]
pub block: bool,
/// The language to syntax-highlight in.
///
/// Apart from typical language tags known from Markdown, this supports the
/// `{"typ"}`, `{"typc"}`, and `{"typm"}` tags for
/// [Typst markup]($reference/syntax/#markup),
/// [Typst code]($reference/syntax/#code), and
/// [Typst math]($reference/syntax/#math), respectively.
///
/// ````example
/// ```typ
/// This is *Typst!*
/// ```
///
/// This is ```typ also *Typst*```, but inline!
/// ````
pub lang: Option<EcoString>,
/// The horizontal alignment that each line in a raw block should have.
/// This option is ignored if this is not a raw block (if specified
/// `block: false` or single backticks were used in markup mode).
///
/// By default, this is set to `{start}`, meaning that raw text is
/// aligned towards the start of the text direction inside the block
/// by default, regardless of the current context's alignment (allowing
/// you to center the raw block itself without centering the text inside
/// it, for example).
///
/// ````example
/// #set raw(align: center)
///
/// ```typc
/// let f(x) = x
/// code = "centered"
/// ```
/// ````
#[default(HAlignment::Start)]
pub align: HAlignment,
/// Additional syntax definitions to load. The syntax definitions should be
/// in the [`sublime-syntax` file format](https://www.sublimetext.com/docs/syntax.html).
///
/// You can pass any of the following values:
///
/// - A path string to load a syntax file from the given path. For more
/// details about paths, see the [Paths section]($syntax/#paths).
/// - Raw bytes from which the syntax should be decoded.
/// - An array where each item is one of the above.
///
/// ````example
/// #set raw(syntaxes: "SExpressions.sublime-syntax")
///
/// ```sexp
/// (defun factorial (x)
/// (if (zerop x)
/// ; with a comment
/// 1
/// (* x (factorial (- x 1)))))
/// ```
/// ````
#[parse(match args.named("syntaxes")? {
Some(sources) => Some(RawSyntax::load(engine.world, sources)?),
None => None,
})]
#[fold]
pub syntaxes: Derived<OneOrMultiple<DataSource>, Vec<RawSyntax>>,
/// The theme to use for syntax highlighting. Themes should be in the
/// [`tmTheme` file format](https://www.sublimetext.com/docs/color_schemes_tmtheme.html).
///
/// You can pass any of the following values:
///
/// - `{none}`: Disables syntax highlighting.
/// - `{auto}`: Highlights with Typst's default theme.
/// - A path string to load a theme file from the given path. For more
/// details about paths, see the [Paths section]($syntax/#paths).
/// - Raw bytes from which the theme should be decoded.
///
/// Applying a theme only affects the color of specifically highlighted
/// text. It does not consider the theme's foreground and background
/// properties, so that you retain control over the color of raw text. You
/// can apply the foreground color yourself with the [`text`] function and
/// the background with a [filled block]($block.fill). You could also use
/// the [`xml`] function to extract these properties from the theme.
///
/// ````example
/// #set raw(theme: "halcyon.tmTheme")
/// #show raw: it => block(
/// fill: rgb("#1d2433"),
/// inset: 8pt,
/// radius: 5pt,
/// text(fill: rgb("#a2aabc"), it)
/// )
///
/// ```typ
/// = Chapter 1
/// #let hi = "Hello World"
/// ```
/// ````
#[parse(match args.named::<Spanned<Smart<Option<DataSource>>>>("theme")? {
Some(Spanned { v: Smart::Custom(Some(source)), span }) => Some(Smart::Custom(
Some(RawTheme::load(engine.world, Spanned::new(source, span))?)
)),
Some(Spanned { v: Smart::Custom(None), .. }) => Some(Smart::Custom(None)),
Some(Spanned { v: Smart::Auto, .. }) => Some(Smart::Auto),
None => None,
})]
pub theme: Smart<Option<Derived<DataSource, RawTheme>>>,
/// The size for a tab stop in spaces. A tab is replaced with enough spaces to
/// align with the next multiple of the size.
///
/// ````example
/// #set raw(tab-size: 8)
/// ```tsv
/// Year Month Day
/// 2000 2 3
/// 2001 2 1
/// 2002 3 10
/// ```
/// ````
#[default(2)]
pub tab_size: usize,
/// The stylized lines of raw text.
///
/// Made accessible for the [`raw.line` element]($raw.line).
/// Allows more styling control in `show` rules.
#[synthesized]
pub lines: Vec<Packed<RawLine>>,
}
#[scope]
impl RawElem {
#[elem]
type RawLine;
}
impl RawElem {
/// The supported language names and tags.
pub fn languages() -> Vec<(&'static str, Vec<&'static str>)> {
RAW_SYNTAXES
.syntaxes()
.iter()
.map(|syntax| {
(
syntax.name.as_str(),
syntax.file_extensions.iter().map(|s| s.as_str()).collect(),
)
})
.chain([
("Typst", vec!["typ"]),
("Typst (code)", vec!["typc"]),
("Typst (math)", vec!["typm"]),
])
.collect()
}
}
impl Synthesize for Packed<RawElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let seq = self.highlight(engine.routines, styles);
self.lines = Some(seq);
Ok(())
}
}
impl Packed<RawElem> {
#[comemo::memoize]
fn highlight(&self, routines: &Routines, styles: StyleChain) -> Vec<Packed<RawLine>> {
let elem = self.as_ref();
let lines = preprocess(&elem.text, styles, self.span());
let count = lines.len() as i64;
let lang = elem
.lang
.get_ref(styles)
.as_ref()
.map(|s| s.to_lowercase())
.or(Some("txt".into()));
let non_highlighted_result = |lines: EcoVec<(EcoString, Span)>| {
lines.into_iter().enumerate().map(|(i, (line, line_span))| {
Packed::new(RawLine::new(
i as i64 + 1,
count,
line.clone(),
TextElem::packed(line).spanned(line_span),
))
.spanned(line_span)
})
};
let syntaxes = LazyCell::new(|| elem.syntaxes.get_cloned(styles));
let theme: &synt::Theme = match elem.theme.get_ref(styles) {
Smart::Auto => &RAW_THEME,
Smart::Custom(Some(theme)) => theme.derived.get(),
Smart::Custom(None) => return non_highlighted_result(lines).collect(),
};
let foreground = theme.settings.foreground.unwrap_or(synt::Color::BLACK);
let target = styles.get(TargetElem::target);
let mut seq = vec![];
if matches!(lang.as_deref(), Some("typ" | "typst" | "typc" | "typm")) {
let text =
lines.iter().map(|(s, _)| s.clone()).collect::<Vec<_>>().join("\n");
let root = match lang.as_deref() {
Some("typc") => typst_syntax::parse_code(&text),
Some("typm") => typst_syntax::parse_math(&text),
_ => typst_syntax::parse(&text),
};
ThemedHighlighter::new(
&text,
LinkedNode::new(&root),
synt::Highlighter::new(theme),
&mut |i, _, range, style| {
// Find span and start of line.
// Note: Dedent is already applied to the text
let span = lines.get(i).map_or_else(Span::detached, |l| l.1);
let span_offset = text[..range.start]
.rfind('\n')
.map_or(0, |i| range.start - (i + 1));
styled(
routines,
target,
&text[range],
foreground,
style,
span,
span_offset,
)
},
&mut |i, range, line| {
let span = lines.get(i).map_or_else(Span::detached, |l| l.1);
seq.push(
Packed::new(RawLine::new(
(i + 1) as i64,
count,
EcoString::from(&text[range]),
Content::sequence(line.drain(..)),
))
.spanned(span),
);
},
)
.highlight();
} else if let Some((syntax_set, syntax)) = lang.and_then(|token| {
// Prefer user-provided syntaxes over built-in ones.
syntaxes
.derived
.iter()
.map(|syntax| syntax.get())
.chain(std::iter::once(&*RAW_SYNTAXES))
.find_map(|set| {
set.find_syntax_by_token(&token).map(|syntax| (set, syntax))
})
}) {
let mut highlighter = syntect::easy::HighlightLines::new(syntax, theme);
for (i, (line, line_span)) in lines.into_iter().enumerate() {
let mut line_content = vec![];
let mut span_offset = 0;
for (style, piece) in highlighter
.highlight_line(line.as_str(), syntax_set)
.into_iter()
.flatten()
{
line_content.push(styled(
routines,
target,
piece,
foreground,
style,
line_span,
span_offset,
));
span_offset += piece.len();
}
seq.push(
Packed::new(RawLine::new(
i as i64 + 1,
count,
line,
Content::sequence(line_content),
))
.spanned(line_span),
);
}
} else {
seq.extend(non_highlighted_result(lines));
};
seq
}
}
impl ShowSet for Packed<RawElem> {
fn show_set(&self, styles: StyleChain) -> Styles {
let mut out = Styles::new();
out.set(TextElem::overhang, false);
out.set(TextElem::lang, Lang::ENGLISH);
out.set(TextElem::hyphenate, Smart::Custom(false));
out.set(TextElem::size, TextSize(Em::new(0.8).into()));
out.set(TextElem::font, FontList(vec![FontFamily::new("DejaVu Sans Mono")]));
out.set(TextElem::cjk_latin_spacing, Smart::Custom(None));
if self.block.get(styles) {
out.set(ParElem::justify, false);
}
out
}
}
impl LocalName for Packed<RawElem> {
const KEY: &'static str = "raw";
}
impl Figurable for Packed<RawElem> {}
impl PlainText for Packed<RawElem> {
fn plain_text(&self, text: &mut EcoString) {
text.push_str(&self.text.get());
}
}
/// The content of the raw text.
#[derive(Debug, Clone, Hash)]
pub enum RawContent {
/// From a string.
Text(EcoString),
/// From lines of text.
Lines(EcoVec<(EcoString, Span)>),
}
impl RawContent {
/// Returns or synthesizes the text content of the raw text.
fn get(&self) -> EcoString {
match self.clone() {
RawContent::Text(text) => text,
RawContent::Lines(lines) => {
let mut lines = lines.into_iter().map(|(s, _)| s);
if lines.len() <= 1 {
lines.next().unwrap_or_default()
} else {
lines.collect::<Vec<_>>().join("\n").into()
}
}
}
}
}
impl PartialEq for RawContent {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(RawContent::Text(a), RawContent::Text(b)) => a == b,
(lines @ RawContent::Lines(_), RawContent::Text(text))
| (RawContent::Text(text), lines @ RawContent::Lines(_)) => {
*text == lines.get()
}
(RawContent::Lines(a), RawContent::Lines(b)) => Iterator::eq(
a.iter().map(|(line, _)| line),
b.iter().map(|(line, _)| line),
),
}
}
}
cast! {
RawContent,
self => self.get().into_value(),
v: EcoString => Self::Text(v),
}
/// A loaded syntax.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct RawSyntax(Arc<ManuallyHash<SyntaxSet>>);
impl RawSyntax {
/// Load syntaxes from sources.
fn load(
world: Tracked<dyn World + '_>,
sources: Spanned<OneOrMultiple<DataSource>>,
) -> SourceResult<Derived<OneOrMultiple<DataSource>, Vec<RawSyntax>>> {
let loaded = sources.load(world)?;
let list = loaded
.iter()
.map(|data| Self::decode(&data.data).within(data))
.collect::<SourceResult<_>>()?;
Ok(Derived::new(sources.v, list))
}
/// Decode a syntax from a loaded source.
#[comemo::memoize]
#[typst_macros::time(name = "load syntaxes")]
fn decode(bytes: &Bytes) -> LoadResult<RawSyntax> {
let str = bytes.as_str()?;
let syntax = SyntaxDefinition::load_from_str(str, false, None)
.map_err(format_syntax_error)?;
let mut builder = SyntaxSetBuilder::new();
builder.add(syntax);
Ok(RawSyntax(Arc::new(ManuallyHash::new(
builder.build(),
typst_utils::hash128(bytes),
))))
}
/// Return the underlying syntax set.
fn get(&self) -> &SyntaxSet {
self.0.as_ref()
}
}
fn format_syntax_error(error: ParseSyntaxError) -> LoadError {
let pos = syntax_error_pos(&error);
LoadError::new(pos, "failed to parse syntax", error)
}
fn syntax_error_pos(error: &ParseSyntaxError) -> ReportPos {
match error {
ParseSyntaxError::InvalidYaml(scan_error) => {
let m = scan_error.marker();
ReportPos::full(
m.index()..m.index(),
LineCol::one_based(m.line(), m.col() + 1),
)
}
_ => ReportPos::None,
}
}
/// A loaded syntect theme.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct RawTheme(Arc<ManuallyHash<synt::Theme>>);
impl RawTheme {
/// Load a theme from a data source.
fn load(
world: Tracked<dyn World + '_>,
source: Spanned<DataSource>,
) -> SourceResult<Derived<DataSource, Self>> {
let loaded = source.load(world)?;
let theme = Self::decode(&loaded.data).within(&loaded)?;
Ok(Derived::new(source.v, theme))
}
/// Decode a theme from bytes.
#[comemo::memoize]
fn decode(bytes: &Bytes) -> LoadResult<RawTheme> {
let mut cursor = std::io::Cursor::new(bytes.as_slice());
let theme =
synt::ThemeSet::load_from_reader(&mut cursor).map_err(format_theme_error)?;
Ok(RawTheme(Arc::new(ManuallyHash::new(theme, typst_utils::hash128(bytes)))))
}
/// Get the underlying syntect theme.
pub fn get(&self) -> &synt::Theme {
self.0.as_ref()
}
}
fn format_theme_error(error: syntect::LoadingError) -> LoadError {
let pos = match &error {
syntect::LoadingError::ParseSyntax(err, _) => syntax_error_pos(err),
_ => ReportPos::None,
};
LoadError::new(pos, "failed to parse theme", error)
}
/// A highlighted line of raw text.
///
/// This is a helper element that is synthesized by [`raw`] elements.
///
/// It allows you to access various properties of the line, such as the line
/// number, the raw non-highlighted text, the highlighted text, and whether it
/// is the first or last line of the raw block.
#[elem(name = "line", title = "Raw Text / Code Line", Tagged, PlainText)]
pub struct RawLine {
/// The line number of the raw line inside of the raw block, starts at 1.
#[required]
pub number: i64,
/// The total number of lines in the raw block.
#[required]
pub count: i64,
/// The line of raw text.
#[required]
pub text: EcoString,
/// The highlighted raw text.
#[required]
pub body: Content,
}
impl PlainText for Packed<RawLine> {
fn plain_text(&self, text: &mut EcoString) {
text.push_str(&self.text);
}
}
/// Wrapper struct for the state required to highlight Typst code.
struct ThemedHighlighter<'a> {
/// The code being highlighted.
code: &'a str,
/// The current node being highlighted.
node: LinkedNode<'a>,
/// The highlighter.
highlighter: synt::Highlighter<'a>,
/// The current scopes.
scopes: Vec<syntect::parsing::Scope>,
/// The current highlighted line.
current_line: Vec<Content>,
/// The range of the current line.
range: Range<usize>,
/// The current line number.
line: usize,
/// The function to style a piece of text.
style_fn: StyleFn<'a>,
/// The function to append a line.
line_fn: LineFn<'a>,
}
// Shorthands for highlighter closures.
type StyleFn<'a> =
&'a mut dyn FnMut(usize, &LinkedNode, Range<usize>, synt::Style) -> Content;
type LineFn<'a> = &'a mut dyn FnMut(usize, Range<usize>, &mut Vec<Content>);
impl<'a> ThemedHighlighter<'a> {
pub fn new(
code: &'a str,
top: LinkedNode<'a>,
highlighter: synt::Highlighter<'a>,
style_fn: StyleFn<'a>,
line_fn: LineFn<'a>,
) -> Self {
Self {
code,
node: top,
highlighter,
range: 0..0,
scopes: Vec::new(),
current_line: Vec::new(),
line: 0,
style_fn,
line_fn,
}
}
pub fn highlight(&mut self) {
self.highlight_inner();
if !self.current_line.is_empty() {
(self.line_fn)(
self.line,
self.range.start..self.code.len(),
&mut self.current_line,
);
self.current_line.clear();
}
}
fn highlight_inner(&mut self) {
if self.node.children().len() == 0 {
let style = self.highlighter.style_for_stack(&self.scopes);
let segment = &self.code[self.node.range()];
let mut len = 0;
for (i, line) in split_newlines(segment).into_iter().enumerate() {
if i != 0 {
(self.line_fn)(
self.line,
self.range.start..self.range.end + len - 1,
&mut self.current_line,
);
self.range.start = self.range.end + len;
self.line += 1;
}
let offset = self.node.range().start + len;
let token_range = offset..(offset + line.len());
self.current_line.push((self.style_fn)(
self.line,
&self.node,
token_range,
style,
));
len += line.len() + 1;
}
self.range.end += segment.len();
}
for child in self.node.children() {
let mut scopes = self.scopes.clone();
if let Some(tag) = typst_syntax::highlight(&child) {
scopes.push(syntect::parsing::Scope::new(tag.tm_scope()).unwrap())
}
std::mem::swap(&mut scopes, &mut self.scopes);
self.node = child;
self.highlight_inner();
std::mem::swap(&mut scopes, &mut self.scopes);
}
}
}
fn preprocess(
text: &RawContent,
styles: StyleChain,
span: Span,
) -> EcoVec<(EcoString, Span)> {
if let RawContent::Lines(lines) = text
&& lines.iter().all(|(s, _)| !s.contains('\t'))
{
return lines.clone();
}
let mut text = text.get();
if text.contains('\t') {
let tab_size = styles.get(RawElem::tab_size);
text = align_tabs(&text, tab_size);
}
split_newlines(&text)
.into_iter()
.map(|line| (line.into(), span))
.collect()
}
/// Style a piece of text with a syntect style.
fn styled(
routines: &Routines,
target: Target,
piece: &str,
foreground: synt::Color,
style: synt::Style,
span: Span,
span_offset: usize,
) -> Content {
let mut body = TextElem::packed(piece).spanned(span);
if span_offset > 0 {
body = body.set(TextElem::span_offset, span_offset);
}
if style.foreground != foreground {
let color = to_typst(style.foreground);
body = match target {
Target::Html => (routines.html_span_filled)(body, color),
Target::Paged => body.set(TextElem::fill, color.into()),
};
}
if style.font_style.contains(synt::FontStyle::BOLD) {
body = body.strong().spanned(span);
}
if style.font_style.contains(synt::FontStyle::ITALIC) {
body = body.emph().spanned(span);
}
if style.font_style.contains(synt::FontStyle::UNDERLINE) {
body = body.underlined().spanned(span);
}
body
}
fn to_typst(synt::Color { r, g, b, a }: synt::Color) -> Color {
Color::from_u8(r, g, b, a)
}
fn to_syn(color: Color) -> synt::Color {
let (r, g, b, a) = color.to_rgb().into_format::<u8, u8>().into_components();
synt::Color { r, g, b, a }
}
/// Create a syntect theme item.
fn item(
scope: &str,
color: Option<&str>,
font_style: Option<synt::FontStyle>,
) -> synt::ThemeItem {
synt::ThemeItem {
scope: scope.parse().unwrap(),
style: synt::StyleModifier {
foreground: color.map(|s| to_syn(s.parse::<Color>().unwrap())),
background: None,
font_style,
},
}
}
/// Replace tabs with spaces to align with multiples of `tab_size`.
fn align_tabs(text: &str, tab_size: usize) -> EcoString {
let replacement = " ".repeat(tab_size);
let divisor = tab_size.max(1);
let amount = text.chars().filter(|&c| c == '\t').count();
let mut res = EcoString::with_capacity(text.len() - amount + amount * tab_size);
let mut column = 0;
for grapheme in text.graphemes(true) {
let c = grapheme.parse::<char>();
if c == Ok('\t') {
let required = tab_size - column % divisor;
res.push_str(&replacement[..required]);
column += required;
} else if c.is_ok_and(typst_syntax::is_newline) || grapheme == "\r\n" {
res.push_str(grapheme);
column = 0;
} else {
res.push_str(grapheme);
column += 1;
}
}
res
}
/// The syntect syntax definitions.
///
/// Syntax set is generated from the syntaxes from the `bat` project
/// <https://github.com/sharkdp/bat/tree/master/assets/syntaxes>
pub static RAW_SYNTAXES: LazyLock<syntect::parsing::SyntaxSet> =
LazyLock::new(two_face::syntax::extra_no_newlines);
/// The default theme used for syntax highlighting.
pub static RAW_THEME: LazyLock<synt::Theme> = LazyLock::new(|| synt::Theme {
name: Some("Typst Light".into()),
author: Some("The Typst Project Developers".into()),
settings: synt::ThemeSettings::default(),
scopes: vec![
item("comment", Some("#74747c"), None),
item("constant.character.escape", Some("#1d6c76"), None),
item("markup.bold", None, Some(synt::FontStyle::BOLD)),
item("markup.italic", None, Some(synt::FontStyle::ITALIC)),
item("markup.underline", None, Some(synt::FontStyle::UNDERLINE)),
item("markup.raw", Some("#6b6b6f"), None),
item("string.other.math.typst", None, None),
item("punctuation.definition.math", Some("#198810"), None),
item("keyword.operator.math", Some("#1d6c76"), None),
item("markup.heading, entity.name.section", None, Some(synt::FontStyle::BOLD)),
item(
"markup.heading.typst",
None,
Some(synt::FontStyle::BOLD | synt::FontStyle::UNDERLINE),
),
item("punctuation.definition.list", Some("#8b41b1"), None),
item("markup.list.term", None, Some(synt::FontStyle::BOLD)),
item("entity.name.label, markup.other.reference", Some("#1d6c76"), None),
item("keyword, constant.language, variable.language", Some("#d73948"), None),
item("storage.type, storage.modifier", Some("#d73948"), None),
item("constant", Some("#b60157"), None),
item("string", Some("#198810"), None),
item("entity.name, variable.function, support", Some("#4b69c6"), None),
item("support.macro", Some("#16718d"), None),
item("meta.annotation", Some("#301414"), None),
item("entity.other, meta.interpolation", Some("#8b41b1"), None),
item("meta.diff.range", Some("#8b41b1"), None),
item("markup.inserted, meta.diff.header.to-file", Some("#198810"), None),
item("markup.deleted, meta.diff.header.from-file", Some("#d73948"), None),
item("meta.mapping.key.json string.quoted.double.json", Some("#4b69c6"), None),
item("meta.mapping.value.json string.quoted.double.json", Some("#198810"), 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/text/mod.rs | crates/typst-library/src/text/mod.rs | //! Text handling.
mod case;
mod deco;
mod font;
mod item;
mod lang;
mod linebreak;
#[path = "lorem.rs"]
mod lorem_;
mod raw;
mod shift;
#[path = "smallcaps.rs"]
mod smallcaps_;
mod smartquote;
mod space;
pub use self::case::*;
pub use self::deco::*;
pub use self::font::*;
pub use self::item::*;
pub use self::lang::*;
pub use self::linebreak::*;
pub use self::lorem_::*;
pub use self::raw::*;
pub use self::shift::*;
pub use self::smallcaps_::*;
pub use self::smartquote::*;
pub use self::space::*;
use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;
use std::str::FromStr;
use std::sync::LazyLock;
use ecow::{EcoString, eco_format};
use icu_properties::sets::CodePointSetData;
use icu_provider::AsDeserializingBufferProvider;
use icu_provider_blob::BlobDataProvider;
use rustybuzz::Feature;
use smallvec::SmallVec;
use ttf_parser::Tag;
use typst_syntax::Spanned;
use typst_utils::singleton;
use unicode_segmentation::UnicodeSegmentation;
use crate::World;
use crate::diag::{Hint, HintedStrResult, SourceResult, StrResult, bail, warning};
use crate::engine::Engine;
use crate::foundations::{
Args, Array, Cast, Construct, Content, Dict, Fold, IntoValue, NativeElement, Never,
NoneValue, Packed, PlainText, Regex, Repr, Resolve, Scope, Set, Smart, Str,
StyleChain, cast, dict, elem,
};
use crate::layout::{Abs, Axis, Dir, Em, Length, Ratio, Rel};
use crate::math::{EquationElem, MathSize};
use crate::visualize::{Color, Paint, RelativeTo, Stroke};
/// Hook up all `text` definitions.
pub(super) fn define(global: &mut Scope) {
global.start_category(crate::Category::Text);
global.define_elem::<TextElem>();
global.define_elem::<LinebreakElem>();
global.define_elem::<SmartQuoteElem>();
global.define_elem::<SubElem>();
global.define_elem::<SuperElem>();
global.define_elem::<UnderlineElem>();
global.define_elem::<OverlineElem>();
global.define_elem::<StrikeElem>();
global.define_elem::<HighlightElem>();
global.define_elem::<SmallcapsElem>();
global.define_elem::<RawElem>();
global.define_func::<lower>();
global.define_func::<upper>();
global.define_func::<lorem>();
global.reset_category();
}
/// Customizes the look and layout of text in a variety of ways.
///
/// This function is used frequently, both with set rules and directly. While
/// the set rule is often the simpler choice, calling the `text` function
/// directly can be useful when passing text as an argument to another function.
///
/// # Example
/// ```example
/// #set text(18pt)
/// With a set rule.
///
/// #emph(text(blue)[
/// With a function call.
/// ])
/// ```
#[elem(Debug, Construct, PlainText, Repr)]
pub struct TextElem {
/// A font family descriptor or priority list of font family descriptors.
///
/// A font family descriptor can be a plain string representing the family
/// name or a dictionary with the following keys:
///
/// - `name` (required): The font family name.
/// - `covers` (optional): Defines the Unicode codepoints for which the
/// family shall be used. This can be:
/// - A predefined coverage set:
/// - `{"latin-in-cjk"}` covers all codepoints except for those which
/// exist in Latin fonts, but should preferably be taken from CJK
/// fonts.
/// - A [regular expression]($regex) that defines exactly which codepoints
/// shall be covered. Accepts only the subset of regular expressions
/// which consist of exactly one dot, letter, or character class.
///
/// When processing text, Typst tries all specified font families in order
/// until it finds a font that has the necessary glyphs. In the example
/// below, the font `Inria Serif` is preferred, but since it does not
/// contain Arabic glyphs, the arabic text uses `Noto Sans Arabic` instead.
///
/// The collection of available fonts differs by platform:
///
/// - In the web app, you can see the list of available fonts by clicking on
/// the "Ag" button. You can provide additional fonts by uploading `.ttf`
/// or `.otf` files into your project. They will be discovered
/// automatically. The priority is: project fonts > server fonts.
///
/// - Locally, Typst uses your installed system fonts or embedded fonts in
/// the CLI, which are `Libertinus Serif`, `New Computer Modern`,
/// `New Computer Modern Math`, and `DejaVu Sans Mono`. In addition, you
/// can use the `--font-path` argument or `TYPST_FONT_PATHS` environment
/// variable to add directories that should be scanned for fonts. The
/// priority is: `--font-paths` > system fonts > embedded fonts. Run
/// `typst fonts` to see the fonts that Typst has discovered on your
/// system. Note that you can pass the `--ignore-system-fonts` parameter
/// to the CLI to ensure Typst won't search for system fonts.
///
/// ```example
/// #set text(font: "PT Sans")
/// This is sans-serif.
///
/// #set text(font: (
/// "Inria Serif",
/// "Noto Sans Arabic",
/// ))
///
/// This is Latin. \
/// هذا عربي.
///
/// // Change font only for numbers.
/// #set text(font: (
/// (name: "PT Sans", covers: regex("[0-9]")),
/// "Libertinus Serif"
/// ))
///
/// The number 123.
///
/// // Mix Latin and CJK fonts.
/// #set text(font: (
/// (name: "Inria Serif", covers: "latin-in-cjk"),
/// "Noto Serif CJK SC"
/// ))
/// 分别设置“中文”和English字体
/// ```
#[parse({
let font_list: Option<Spanned<FontList>> = args.named("font")?;
if let Some(list) = &font_list {
check_font_list(engine, list);
}
font_list.map(|font_list| font_list.v)
})]
#[default(FontList(vec![FontFamily::new("Libertinus Serif")]))]
#[ghost]
pub font: FontList,
/// Whether to allow last resort font fallback when the primary font list
/// contains no match. This lets Typst search through all available fonts
/// for the most similar one that has the necessary glyphs.
///
/// _Note:_ Currently, there are no warnings when fallback is disabled and
/// no glyphs are found. Instead, your text shows up in the form of "tofus":
/// Small boxes that indicate the lack of an appropriate glyph. In the
/// future, you will be able to instruct Typst to issue warnings so you know
/// something is up.
///
/// ```example
/// #set text(font: "Inria Serif")
/// هذا عربي
///
/// #set text(fallback: false)
/// هذا عربي
/// ```
#[default(true)]
#[ghost]
pub fallback: bool,
/// The desired font style.
///
/// When an italic style is requested and only an oblique one is available,
/// it is used. Similarly, the other way around, an italic style can stand
/// in for an oblique one. When neither an italic nor an oblique style is
/// available, Typst selects the normal style. Since most fonts are only
/// available either in an italic or oblique style, the difference between
/// italic and oblique style is rarely observable.
///
/// If you want to emphasize your text, you should do so using the [emph]
/// function instead. This makes it easy to adapt the style later if you
/// change your mind about how to signify the emphasis.
///
/// ```example
/// #text(font: "Libertinus Serif", style: "italic")[Italic]
/// #text(font: "DejaVu Sans", style: "oblique")[Oblique]
/// ```
#[ghost]
pub style: FontStyle,
/// The desired thickness of the font's glyphs. Accepts an integer between
/// `{100}` and `{900}` or one of the predefined weight names. When the
/// desired weight is not available, Typst selects the font from the family
/// that is closest in weight.
///
/// If you want to strongly emphasize your text, you should do so using the
/// [strong] function instead. This makes it easy to adapt the style later
/// if you change your mind about how to signify the strong emphasis.
///
/// ```example
/// #set text(font: "IBM Plex Sans")
///
/// #text(weight: "light")[Light] \
/// #text(weight: "regular")[Regular] \
/// #text(weight: "medium")[Medium] \
/// #text(weight: 500)[Medium] \
/// #text(weight: "bold")[Bold]
/// ```
#[ghost]
pub weight: FontWeight,
/// The desired width of the glyphs. Accepts a ratio between `{50%}` and
/// `{200%}`. When the desired width is not available, Typst selects the
/// font from the family that is closest in stretch. This will only stretch
/// the text if a condensed or expanded version of the font is available.
///
/// If you want to adjust the amount of space between characters instead of
/// stretching the glyphs itself, use the [`tracking`]($text.tracking)
/// property instead.
///
/// ```example
/// #text(stretch: 75%)[Condensed] \
/// #text(stretch: 100%)[Normal]
/// ```
#[ghost]
pub stretch: FontStretch,
/// The size of the glyphs. This value forms the basis of the `em` unit:
/// `{1em}` is equivalent to the font size.
///
/// You can also give the font size itself in `em` units. Then, it is
/// relative to the previous font size.
///
/// ```example
/// #set text(size: 20pt)
/// very #text(1.5em)[big] text
/// ```
#[parse(args.named_or_find("size")?)]
#[fold]
#[default(TextSize(Abs::pt(11.0).into()))]
#[ghost]
pub size: TextSize,
/// The glyph fill paint.
///
/// ```example
/// #set text(fill: red)
/// This text is red.
/// ```
#[parse({
let paint: Option<Spanned<Paint>> = args.named_or_find("fill")?;
if let Some(paint) = &paint
&& paint.v.relative() == Smart::Custom(RelativeTo::Self_) {
bail!(
paint.span,
"gradients and tilings on text must be relative to the parent";
hint: "make sure to set `relative: auto` on your text fill";
);
}
paint.map(|paint| paint.v)
})]
#[default(Color::BLACK.into())]
#[ghost]
pub fill: Paint,
/// How to stroke the text.
///
/// ```example
/// #text(stroke: 0.5pt + red)[Stroked]
/// ```
#[ghost]
pub stroke: Option<Stroke>,
/// The amount of space that should be added between characters.
///
/// ```example
/// #set text(tracking: 1.5pt)
/// Distant text.
/// ```
#[ghost]
pub tracking: Length,
/// The amount of space between words.
///
/// Can be given as an absolute length, but also relative to the width of
/// the space character in the font.
///
/// If you want to adjust the amount of space between characters rather than
/// words, use the [`tracking`]($text.tracking) property instead.
///
/// ```example
/// #set text(spacing: 200%)
/// Text with distant words.
/// ```
#[default(Rel::one())]
#[ghost]
pub spacing: Rel<Length>,
/// Whether to automatically insert spacing between CJK and Latin characters.
///
/// ```example
/// #set text(cjk-latin-spacing: auto)
/// 第4章介绍了基本的API。
///
/// #set text(cjk-latin-spacing: none)
/// 第4章介绍了基本的API。
/// ```
#[ghost]
pub cjk_latin_spacing: Smart<Option<Never>>,
/// An amount to shift the text baseline by.
///
/// ```example
/// A #text(baseline: 3pt)[lowered]
/// word.
/// ```
#[ghost]
pub baseline: Length,
/// Whether certain glyphs can hang over into the margin in justified text.
/// This can make justification visually more pleasing.
///
/// ```example
/// #set page(width: 220pt)
///
/// #set par(justify: true)
/// This justified text has a hyphen in
/// the paragraph's second line. Hanging
/// the hyphen slightly into the margin
/// results in a clearer paragraph edge.
///
/// #set text(overhang: false)
/// This justified text has a hyphen in
/// the paragraph's second line. Hanging
/// the hyphen slightly into the margin
/// results in a clearer paragraph edge.
/// ```
#[default(true)]
#[ghost]
pub overhang: bool,
/// The top end of the conceptual frame around the text used for layout and
/// positioning. This affects the size of containers that hold text.
///
/// ```example
/// #set rect(inset: 0pt)
/// #set text(size: 20pt)
///
/// #set text(top-edge: "ascender")
/// #rect(fill: aqua)[Typst]
///
/// #set text(top-edge: "cap-height")
/// #rect(fill: aqua)[Typst]
/// ```
#[default(TopEdge::Metric(TopEdgeMetric::CapHeight))]
#[ghost]
pub top_edge: TopEdge,
/// The bottom end of the conceptual frame around the text used for layout
/// and positioning. This affects the size of containers that hold text.
///
/// ```example
/// #set rect(inset: 0pt)
/// #set text(size: 20pt)
///
/// #set text(bottom-edge: "baseline")
/// #rect(fill: aqua)[Typst]
///
/// #set text(bottom-edge: "descender")
/// #rect(fill: aqua)[Typst]
/// ```
#[default(BottomEdge::Metric(BottomEdgeMetric::Baseline))]
#[ghost]
pub bottom_edge: BottomEdge,
/// An [ISO 639-1/2/3 language code.](https://en.wikipedia.org/wiki/ISO_639)
///
/// Setting the correct language affects various parts of Typst:
///
/// - The text processing pipeline can make more informed choices.
/// - Hyphenation will use the correct patterns for the language.
/// - [Smart quotes]($smartquote) turns into the correct quotes for the
/// language.
/// - And all other things which are language-aware.
///
/// Choosing the correct language is important for accessibility. For
/// example, screen readers will use it to choose a voice that matches the
/// language of the text. If your document is in another language than
/// English (the default), you should set the text language at the start of
/// your document, before any other content. You can, for example, put it
/// right after the `[#set document(/* ... */)]` rule that [sets your
/// document's title]($document.title).
///
/// If your document contains passages in a different language than the main
/// language, you should locally change the text language just for those parts,
/// either with a set rule [scoped to a block]($scripting/#blocks) or using
/// a direct text function call such as `[#text(lang: "de")[...]]`.
///
/// If multiple codes are available for your language, you should prefer the
/// two-letter code (ISO 639-1) over the three-letter codes (ISO 639-2/3).
/// When you have to use a three-letter code and your language differs
/// between ISO 639-2 and ISO 639-3, use ISO 639-2 for PDF 1.7 (Typst's
/// default for PDF export) and below and ISO 639-3 for PDF 2.0 and HTML
/// export.
///
/// The language code is case-insensitive, and will be lowercased when
/// accessed through [context]($context).
///
/// ```example:"Setting the text language to German"
/// #set text(lang: "de")
/// #outline()
///
/// = Einleitung
/// In diesem Dokument, ...
/// ```
#[default(Lang::ENGLISH)]
#[ghost]
pub lang: Lang,
/// An [ISO 3166-1 alpha-2 region code.](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)
///
/// This lets the text processing pipeline make more informed choices.
///
/// The region code is case-insensitive, and will be uppercased when
/// accessed through [context]($context).
#[ghost]
pub region: Option<Region>,
/// The OpenType writing script.
///
/// The combination of `{lang}` and `{script}` determine how font features,
/// such as glyph substitution, are implemented. Frequently the value is a
/// modified (all-lowercase) ISO 15924 script identifier, and the `math`
/// writing script is used for features appropriate for mathematical
/// symbols.
///
/// When set to `{auto}`, the default and recommended setting, an
/// appropriate script is chosen for each block of characters sharing a
/// common Unicode script property.
///
/// ```example
/// #set text(
/// font: "Libertinus Serif",
/// size: 20pt,
/// )
///
/// #let scedilla = [Ş]
/// #scedilla // S with a cedilla
///
/// #set text(lang: "ro", script: "latn")
/// #scedilla // S with a subscript comma
///
/// #set text(lang: "ro", script: "grek")
/// #scedilla // S with a cedilla
/// ```
#[ghost]
pub script: Smart<WritingScript>,
/// The dominant direction for text and inline objects. Possible values are:
///
/// - `{auto}`: Automatically infer the direction from the `lang` property.
/// - `{ltr}`: Layout text from left to right.
/// - `{rtl}`: Layout text from right to left.
///
/// When writing in right-to-left scripts like Arabic or Hebrew, you should
/// set the [text language]($text.lang) or direction. While individual runs
/// of text are automatically layouted in the correct direction, setting the
/// dominant direction gives the bidirectional reordering algorithm the
/// necessary information to correctly place punctuation and inline objects.
/// Furthermore, setting the direction affects the alignment values `start`
/// and `end`, which are equivalent to `left` and `right` in `ltr` text and
/// the other way around in `rtl` text.
///
/// If you set this to `rtl` and experience bugs or in some way bad looking
/// output, please get in touch with us through the
/// [Forum](https://forum.typst.app/),
/// [Discord server](https://discord.gg/2uDybryKPe),
/// or our [contact form](https://typst.app/contact).
///
/// ```example
/// #set text(dir: rtl)
/// هذا عربي.
/// ```
#[ghost]
pub dir: TextDir,
/// Whether to hyphenate text to improve line breaking. When `{auto}`, text
/// will be hyphenated if and only if justification is enabled.
///
/// Setting the [text language]($text.lang) ensures that the correct
/// hyphenation patterns are used.
///
/// ```example
/// #set page(width: 200pt)
///
/// #set par(justify: true)
/// This text illustrates how
/// enabling hyphenation can
/// improve justification.
///
/// #set text(hyphenate: false)
/// This text illustrates how
/// enabling hyphenation can
/// improve justification.
/// ```
#[ghost]
pub hyphenate: Smart<bool>,
/// The "cost" of various choices when laying out text. A higher cost means
/// the layout engine will make the choice less often. Costs are specified
/// as a ratio of the default cost, so `{50%}` will make text layout twice
/// as eager to make a given choice, while `{200%}` will make it half as
/// eager.
///
/// Currently, the following costs can be customized:
/// - `hyphenation`: splitting a word across multiple lines
/// - `runt`: ending a paragraph with a line with a single word
/// - `widow`: leaving a single line of paragraph on the next page
/// - `orphan`: leaving single line of paragraph on the previous page
///
/// Hyphenation is generally avoided by placing the whole word on the next
/// line, so a higher hyphenation cost can result in awkward justification
/// spacing. Note: Hyphenation costs will only be applied when the
/// [`linebreaks`]($par.linebreaks) are set to "optimized". (For example
/// by default implied by [`justify`]($par.justify).)
///
/// Runts are avoided by placing more or fewer words on previous lines, so a
/// higher runt cost can result in more awkward in justification spacing.
///
/// Text layout prevents widows and orphans by default because they are
/// generally discouraged by style guides. However, in some contexts they
/// are allowed because the prevention method, which moves a line to the
/// next page, can result in an uneven number of lines between pages. The
/// `widow` and `orphan` costs allow disabling these modifications.
/// (Currently, `{0%}` allows widows/orphans; anything else, including the
/// default of `{100%}`, prevents them. More nuanced cost specification for
/// these modifications is planned for the future.)
///
/// ```example
/// #set text(hyphenate: true, size: 11.4pt)
/// #set par(justify: true)
///
/// #lorem(10)
///
/// // Set hyphenation to ten times the normal cost.
/// #set text(costs: (hyphenation: 1000%))
///
/// #lorem(10)
/// ```
#[fold]
#[ghost]
pub costs: Costs,
/// Whether to apply kerning.
///
/// When enabled, specific letter pairings move closer together or further
/// apart for a more visually pleasing result. The example below
/// demonstrates how decreasing the gap between the "T" and "o" results in a
/// more natural look. Setting this to `{false}` disables kerning by turning
/// off the OpenType `kern` font feature.
///
/// ```example
/// #set text(size: 25pt)
/// Totally
///
/// #set text(kerning: false)
/// Totally
/// ```
#[default(true)]
#[ghost]
pub kerning: bool,
/// Whether to apply stylistic alternates.
///
/// Sometimes fonts contain alternative glyphs for the same codepoint.
/// Setting this to `{true}` switches to these by enabling the OpenType
/// `salt` font feature. An integer may be used to select between multiple
/// alternates.
///
/// ```example
/// #set text(
/// font: "IBM Plex Sans",
/// size: 20pt,
/// )
///
/// 0, a, g, ß
///
/// #set text(alternates: true)
/// 0, a, g, ß
/// ```
#[ghost]
pub alternates: Alternates,
/// Which stylistic sets to apply. Font designers can categorize alternative
/// glyphs forms into stylistic sets. As this value is highly font-specific,
/// you need to consult your font to know which sets are available.
///
/// This can be set to an integer or an array of integers, all
/// of which must be between `{1}` and `{20}`, enabling the
/// corresponding OpenType feature(s) from `ss01` to `ss20`.
/// Setting this to `{none}` will disable all stylistic sets.
///
/// ```example
/// #set text(font: "IBM Plex Serif")
/// ß vs #text(stylistic-set: 5)[ß] \
/// 10 years ago vs #text(stylistic-set: (1, 2, 3))[10 years ago]
/// ```
#[ghost]
pub stylistic_set: StylisticSets,
/// Whether standard ligatures are active.
///
/// Certain letter combinations like "fi" are often displayed as a single
/// merged glyph called a _ligature._ Setting this to `{false}` disables
/// these ligatures by turning off the OpenType `liga` and `clig` font
/// features.
///
/// ```example
/// #set text(size: 20pt)
/// A fine ligature.
///
/// #set text(ligatures: false)
/// A fine ligature.
/// ```
///
/// Note that some programming fonts use other OpenType font features to
/// implement "ligatures," including the contextual alternates (`calt`)
/// feature, which is also enabled by default. Use the general
/// [`features`]($text.features) parameter to control such features.
#[default(true)]
#[ghost]
pub ligatures: bool,
/// Whether ligatures that should be used sparingly are active. Setting this
/// to `{true}` enables the OpenType `dlig` font feature.
#[default(false)]
#[ghost]
pub discretionary_ligatures: bool,
/// Whether historical ligatures are active. Setting this to `{true}`
/// enables the OpenType `hlig` font feature.
#[default(false)]
#[ghost]
pub historical_ligatures: bool,
/// Which kind of numbers / figures to select. When set to `{auto}`, the
/// default numbers for the font are used.
///
/// ```example
/// #set text(font: "Noto Sans", 20pt)
/// #set text(number-type: "lining")
/// Number 9.
///
/// #set text(number-type: "old-style")
/// Number 9.
/// ```
#[ghost]
pub number_type: Smart<NumberType>,
/// The width of numbers / figures. When set to `{auto}`, the default
/// numbers for the font are used.
///
/// ```example
/// #set text(font: "Noto Sans", 20pt)
/// #set text(number-width: "proportional")
/// A 12 B 34. \
/// A 56 B 78.
///
/// #set text(number-width: "tabular")
/// A 12 B 34. \
/// A 56 B 78.
/// ```
#[ghost]
pub number_width: Smart<NumberWidth>,
/// Whether to have a slash through the zero glyph. Setting this to `{true}`
/// enables the OpenType `zero` font feature.
///
/// ```example
/// 0, #text(slashed-zero: true)[0]
/// ```
#[default(false)]
#[ghost]
pub slashed_zero: bool,
/// Whether to turn numbers into fractions. Setting this to `{true}`
/// enables the OpenType `frac` font feature.
///
/// It is not advisable to enable this property globally as it will mess
/// with all appearances of numbers after a slash (e.g., in URLs). Instead,
/// enable it locally when you want a fraction.
///
/// ```example
/// 1/2 \
/// #text(fractions: true)[1/2]
/// ```
#[default(false)]
#[ghost]
pub fractions: bool,
/// Raw OpenType features to apply.
///
/// - If given an array of strings, sets the features identified by the
/// strings to `{1}`.
/// - If given a dictionary mapping to numbers, sets the features
/// identified by the keys to the values. This allows interacting with
/// non-boolean features such as `swsh`.
///
/// ```example:"Give an array of strings"
/// // Enable the `frac` feature manually.
/// #set text(features: ("frac",))
/// 1/2
/// ```
///
/// ```example:"Give a dictionary mapping to numbers"
/// #set text(font: "Cascadia Code")
/// =>
/// // Disable the contextual alternates (`calt`) feature.
/// #set text(features: (calt: 0))
/// =>
/// ```
#[fold]
#[ghost]
pub features: FontFeatures,
/// Content in which all text is styled according to the other arguments.
#[external]
#[required]
pub body: Content,
/// The text.
#[required]
pub text: EcoString,
/// The offset of the text in the text syntax node referenced by this
/// element's span.
#[internal]
#[ghost]
pub span_offset: usize,
/// A delta to apply on the font weight.
#[internal]
#[fold]
#[ghost]
pub delta: WeightDelta,
/// Whether the font style should be inverted.
#[internal]
#[fold]
#[default(ItalicToggle(false))]
#[ghost]
pub emph: ItalicToggle,
/// Decorative lines.
#[internal]
#[fold]
#[ghost]
pub deco: SmallVec<[Decoration; 1]>,
/// A case transformation that should be applied to the text.
#[internal]
#[ghost]
pub case: Option<Case>,
/// Whether small capital glyphs should be used. ("smcp", "c2sc")
#[internal]
#[ghost]
pub smallcaps: Option<Smallcaps>,
/// The configuration for superscripts or subscripts, if one of them is
/// enabled.
#[internal]
#[ghost]
pub shift_settings: Option<ShiftSettings>,
}
impl TextElem {
/// Create a new packed text element.
pub fn packed(text: impl Into<EcoString>) -> Content {
Self::new(text.into()).pack()
}
}
impl Debug for TextElem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Text({})", self.text)
}
}
impl Repr for TextElem {
fn repr(&self) -> EcoString {
eco_format!("[{}]", self.text)
}
}
impl Construct for TextElem {
fn construct(engine: &mut Engine, args: &mut Args) -> SourceResult<Content> {
// The text constructor is special: It doesn't create a text element.
// Instead, it leaves the passed argument structurally unchanged, but
// styles all text in it.
let styles = Self::set(engine, args)?;
let body = args.expect::<Content>("body")?;
Ok(body.styled_with_map(styles))
}
}
impl PlainText for Packed<TextElem> {
fn plain_text(&self, text: &mut EcoString) {
text.push_str(&self.text);
}
}
/// A lowercased font family like "arial".
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct FontFamily {
// The name of the font family
name: EcoString,
// A regex that defines the Unicode codepoints supported by the font.
covers: Option<Covers>,
}
impl FontFamily {
/// Create a named font family variant.
pub fn new(string: &str) -> Self {
Self::with_coverage(string, None)
}
/// Create a font family by name and optional Unicode coverage.
pub fn with_coverage(string: &str, covers: Option<Covers>) -> Self {
Self { name: string.to_lowercase().into(), covers }
}
/// The lowercased family name.
pub fn as_str(&self) -> &str {
&self.name
}
/// The user-set coverage of the font family.
pub fn covers(&self) -> Option<&Regex> {
self.covers.as_ref().map(|covers| covers.as_regex())
}
}
cast! {
FontFamily,
self => match self.covers {
Some(covers) => dict![
"name" => self.name,
"covers" => covers
].into_value(),
None => self.name.into_value()
},
string: EcoString => Self::new(&string),
mut v: Dict => {
let ret = Self::with_coverage(
&v.take("name")?.cast::<EcoString>()?,
v.take("covers").ok().map(|v| v.cast()).transpose()?
);
v.finish(&["name", "covers"])?;
ret
},
}
/// Defines which codepoints a font family will be used for.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Covers {
/// Covers all codepoints except those used both in Latin and CJK fonts.
LatinInCjk,
/// Covers the set of codepoints for which the regex matches.
Regex(Regex),
}
impl Covers {
/// Retrieve the regex for the coverage.
pub fn as_regex(&self) -> &Regex {
match self {
Self::LatinInCjk => singleton!(
Regex,
Regex::new(
"[^\u{00B7}\u{2013}\u{2014}\u{2018}\u{2019}\
\u{201C}\u{201D}\u{2025}-\u{2027}\u{2E3A}]"
)
.unwrap()
),
Self::Regex(regex) => regex,
}
}
}
cast! {
Covers,
self => match self {
Self::LatinInCjk => "latin-in-cjk".into_value(),
Self::Regex(regex) => regex.into_value(),
},
/// Covers all codepoints except those used both in Latin and CJK fonts.
"latin-in-cjk" => Covers::LatinInCjk,
regex: Regex => {
let ast = regex_syntax::ast::parse::Parser::new().parse(regex.as_str());
match ast {
Ok(
regex_syntax::ast::Ast::ClassBracketed(..)
| regex_syntax::ast::Ast::ClassUnicode(..)
| regex_syntax::ast::Ast::ClassPerl(..)
| regex_syntax::ast::Ast::Dot(..)
| regex_syntax::ast::Ast::Literal(..),
) => {}
_ => bail!(
"coverage regex may only use dot, letters, and character classes";
hint: "the regex is applied to each letter individually";
),
}
Covers::Regex(regex)
},
}
/// Font family fallback list.
///
/// Must contain at least one font.
#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct FontList(pub Vec<FontFamily>);
impl FontList {
pub fn new(fonts: Vec<FontFamily>) -> StrResult<Self> {
if fonts.is_empty() {
bail!("font fallback list must not be empty")
} else {
Ok(Self(fonts))
}
}
}
impl<'a> IntoIterator for &'a FontList {
type IntoIter = std::slice::Iter<'a, FontFamily>;
type Item = &'a FontFamily;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
cast! {
FontList,
self => if self.0.len() == 1 {
self.0.into_iter().next().unwrap().into_value()
} else {
self.0.into_value()
},
family: FontFamily => Self(vec![family]),
| 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/text/item.rs | crates/typst-library/src/text/item.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::Range;
use ecow::EcoString;
use typst_syntax::Span;
use crate::layout::{Abs, Em, Point, Rect};
use crate::text::{Font, Lang, Region, is_default_ignorable};
use crate::visualize::{FixedStroke, Paint};
/// A run of shaped text.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct TextItem {
/// The font the glyphs are contained in.
pub font: Font,
/// The font size.
pub size: Abs,
/// Glyph color.
pub fill: Paint,
/// Glyph stroke.
pub stroke: Option<FixedStroke>,
/// The natural language of the text.
pub lang: Lang,
/// The region of the text.
pub region: Option<Region>,
/// The item's plain text.
pub text: EcoString,
/// The glyphs. The number of glyphs may be different from the number of
/// characters in the plain text due to e.g. ligatures.
pub glyphs: Vec<Glyph>,
}
impl TextItem {
/// The width of the text run.
pub fn width(&self) -> Abs {
self.glyphs.iter().map(|g| g.x_advance).sum::<Em>().at(self.size)
}
/// The height of the text run.
pub fn height(&self) -> Abs {
self.glyphs.iter().map(|g| g.y_advance).sum::<Em>().at(self.size)
}
/// The bounding box of the text run.
#[comemo::memoize]
pub fn bbox(&self) -> Rect {
let mut min = Point::splat(Abs::inf());
let mut max = Point::splat(-Abs::inf());
let mut cursor = Point::zero();
for glyph in self.glyphs.iter() {
let advance =
Point::new(glyph.x_advance.at(self.size), glyph.y_advance.at(self.size));
let offset =
Point::new(glyph.x_offset.at(self.size), glyph.y_offset.at(self.size));
if let Some(rect) =
self.font.ttf().glyph_bounding_box(ttf_parser::GlyphId(glyph.id))
{
let pos = cursor + offset;
let a = pos
+ Point::new(
self.font.to_em(rect.x_min).at(self.size),
self.font.to_em(rect.y_min).at(self.size),
);
let b = pos
+ Point::new(
self.font.to_em(rect.x_max).at(self.size),
self.font.to_em(rect.y_max).at(self.size),
);
min = min.min(a).min(b);
max = max.max(a).max(b);
}
cursor += advance;
}
// Text runs use a y-up coordinate system, in contrast to the default
// frame orientation.
min.y *= -1.0;
max.y *= -1.0;
Rect::new(min, max)
}
}
impl Debug for TextItem {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("Text(")?;
self.text.fmt(f)?;
f.write_str(")")
}
}
/// A glyph in a run of shaped text.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Glyph {
/// The glyph's index in the font.
pub id: u16,
/// The advance width of the glyph.
pub x_advance: Em,
/// The horizontal offset of the glyph.
pub x_offset: Em,
/// The advance height (Y-up) of the glyph.
pub y_advance: Em,
/// The vertical offset (Y-up) of the glyph.
pub y_offset: Em,
/// The range of the glyph in its item's text. The range's length may
/// be more than one due to multi-byte UTF-8 encoding or ligatures.
pub range: Range<u16>,
/// The source code location of the text.
pub span: (Span, u16),
}
impl Glyph {
/// The range of the glyph in its item's text.
pub fn range(&self) -> Range<usize> {
usize::from(self.range.start)..usize::from(self.range.end)
}
}
/// A slice of a [`TextItem`].
pub struct TextItemView<'a> {
/// The whole item this is a part of
pub item: &'a TextItem,
/// The glyphs of this slice
pub glyph_range: Range<usize>,
}
impl<'a> TextItemView<'a> {
/// Build a TextItemView for the whole contents of a TextItem.
pub fn full(text: &'a TextItem) -> Self {
Self::from_glyph_range(text, 0..text.glyphs.len())
}
/// Build a new [`TextItemView`] from a [`TextItem`] and a range of glyphs.
pub fn from_glyph_range(text: &'a TextItem, glyph_range: Range<usize>) -> Self {
TextItemView { item: text, glyph_range }
}
/// Returns an iterator over the glyphs of the slice.
///
/// Note that the ranges are not remapped. They still point into the
/// original text.
pub fn glyphs(&self) -> &[Glyph] {
&self.item.glyphs[self.glyph_range.clone()]
}
/// The plain text for the given glyph from `glyphs()`. This is an
/// approximation since glyphs do not correspond 1-1 with codepoints.
pub fn glyph_text(&self, glyph: &Glyph) -> EcoString {
// Trim default ignorables which might have ended up in the glyph's
// cluster. Keep interior ones so that joined emojis work. All of this
// is a hack and needs to be reworked. See
// https://github.com/typst/typst/pull/5099
self.item.text[glyph.range()]
.trim_matches(is_default_ignorable)
.into()
}
/// The total width of this text slice
pub fn width(&self) -> Abs {
self.glyphs()
.iter()
.map(|g| g.x_advance)
.sum::<Em>()
.at(self.item.size)
}
/// The total height of this text slice
pub fn height(&self) -> Abs {
self.glyphs()
.iter()
.map(|g| g.y_advance)
.sum::<Em>()
.at(self.item.size)
}
}
| 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/text/space.rs | crates/typst-library/src/text/space.rs | use ecow::EcoString;
use typst_utils::singleton;
use crate::foundations::{
Content, NativeElement, Packed, PlainText, Repr, Unlabellable, elem,
};
/// A text space.
#[elem(Unlabellable, PlainText, Repr)]
pub struct SpaceElem {}
impl SpaceElem {
/// Get the globally shared space element.
pub fn shared() -> &'static Content {
singleton!(Content, SpaceElem::new().pack())
}
}
impl Repr for SpaceElem {
fn repr(&self) -> EcoString {
"[ ]".into()
}
}
impl Unlabellable for Packed<SpaceElem> {}
impl PlainText for Packed<SpaceElem> {
fn plain_text(&self, text: &mut EcoString) {
text.push(' ');
}
}
| 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/text/deco.rs | crates/typst-library/src/text/deco.rs | use crate::foundations::{Content, Smart, elem};
use crate::introspection::{Locatable, Tagged};
use crate::layout::{Abs, Corners, Length, Rel, Sides};
use crate::text::{BottomEdge, BottomEdgeMetric, TopEdge, TopEdgeMetric};
use crate::visualize::{Color, FixedStroke, Paint, Stroke};
/// Underlines text.
///
/// # Example
/// ```example
/// This is #underline[important].
/// ```
#[elem(Locatable, Tagged)]
pub struct UnderlineElem {
/// How to [stroke] the line.
///
/// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font.
///
/// ```example
/// Take #underline(
/// stroke: 1.5pt + red,
/// offset: 2pt,
/// [care],
/// )
/// ```
#[fold]
pub stroke: Smart<Stroke>,
/// The position of the line relative to the baseline, read from the font
/// tables if `{auto}`.
///
/// ```example
/// #underline(offset: 5pt)[
/// The Tale Of A Faraway Line I
/// ]
/// ```
pub offset: Smart<Length>,
/// The amount by which to extend the line beyond (or within if negative)
/// the content.
///
/// ```example
/// #align(center,
/// underline(extent: 2pt)[Chapter 1]
/// )
/// ```
pub extent: Length,
/// Whether the line skips sections in which it would collide with the
/// glyphs.
///
/// ```example
/// This #underline(evade: true)[is great].
/// This #underline(evade: false)[is less great].
/// ```
#[default(true)]
pub evade: bool,
/// Whether the line is placed behind the content it underlines.
///
/// ```example
/// #set underline(stroke: (thickness: 1em, paint: maroon, cap: "round"))
/// #underline(background: true)[This is stylized.] \
/// #underline(background: false)[This is partially hidden.]
/// ```
#[default(false)]
pub background: bool,
/// The content to underline.
#[required]
pub body: Content,
}
/// Adds a line over text.
///
/// # Example
/// ```example
/// #overline[A line over text.]
/// ```
#[elem(Locatable, Tagged)]
pub struct OverlineElem {
/// How to [stroke] the line.
///
/// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font.
///
/// ```example
/// #set text(fill: olive)
/// #overline(
/// stroke: green.darken(20%),
/// offset: -12pt,
/// [The Forest Theme],
/// )
/// ```
#[fold]
pub stroke: Smart<Stroke>,
/// The position of the line relative to the baseline. Read from the font
/// tables if `{auto}`.
///
/// ```example
/// #overline(offset: -1.2em)[
/// The Tale Of A Faraway Line II
/// ]
/// ```
pub offset: Smart<Length>,
/// The amount by which to extend the line beyond (or within if negative)
/// the content.
///
/// ```example
/// #set overline(extent: 4pt)
/// #set underline(extent: 4pt)
/// #overline(underline[Typography Today])
/// ```
pub extent: Length,
/// Whether the line skips sections in which it would collide with the
/// glyphs.
///
/// ```example
/// #overline(
/// evade: false,
/// offset: -7.5pt,
/// stroke: 1pt,
/// extent: 3pt,
/// [Temple],
/// )
/// ```
#[default(true)]
pub evade: bool,
/// Whether the line is placed behind the content it overlines.
///
/// ```example
/// #set overline(stroke: (thickness: 1em, paint: maroon, cap: "round"))
/// #overline(background: true)[This is stylized.] \
/// #overline(background: false)[This is partially hidden.]
/// ```
#[default(false)]
pub background: bool,
/// The content to add a line over.
#[required]
pub body: Content,
}
/// Strikes through text.
///
/// # Example
/// ```example
/// This is #strike[not] relevant.
/// ```
#[elem(title = "Strikethrough", Locatable, Tagged)]
pub struct StrikeElem {
/// How to [stroke] the line.
///
/// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font.
///
/// _Note:_ Please don't use this for real redaction as you can still copy
/// paste the text.
///
/// ```example
/// This is #strike(stroke: 1.5pt + red)[very stricken through]. \
/// This is #strike(stroke: 10pt)[redacted].
/// ```
#[fold]
pub stroke: Smart<Stroke>,
/// The position of the line relative to the baseline. Read from the font
/// tables if `{auto}`.
///
/// This is useful if you are unhappy with the offset your font provides.
///
/// ```example
/// #set text(font: "Inria Serif")
/// This is #strike(offset: auto)[low-ish]. \
/// This is #strike(offset: -3.5pt)[on-top].
/// ```
pub offset: Smart<Length>,
/// The amount by which to extend the line beyond (or within if negative)
/// the content.
///
/// ```example
/// This #strike(extent: -2pt)[skips] parts of the word.
/// This #strike(extent: 2pt)[extends] beyond the word.
/// ```
pub extent: Length,
/// Whether the line is placed behind the content.
///
/// ```example
/// #set strike(stroke: red)
/// #strike(background: true)[This is behind.] \
/// #strike(background: false)[This is in front.]
/// ```
#[default(false)]
pub background: bool,
/// The content to strike through.
#[required]
pub body: Content,
}
/// Highlights text with a background color.
///
/// # Example
/// ```example
/// This is #highlight[important].
/// ```
#[elem(Locatable, Tagged)]
pub struct HighlightElem {
/// The color to highlight the text with.
///
/// ```example
/// This is #highlight(
/// fill: blue
/// )[highlighted with blue].
/// ```
#[default(Some(Color::from_u8(0xFF, 0xFD, 0x11, 0xA1).into()))]
pub fill: Option<Paint>,
/// The highlight's border color. See the
/// [rectangle's documentation]($rect.stroke) for more details.
///
/// ```example
/// This is a #highlight(
/// stroke: fuchsia
/// )[stroked highlighting].
/// ```
#[fold]
pub stroke: Sides<Option<Option<Stroke>>>,
/// The top end of the background rectangle.
///
/// ```example
/// #set highlight(top-edge: "ascender")
/// #highlight[a] #highlight[aib]
///
/// #set highlight(top-edge: "x-height")
/// #highlight[a] #highlight[aib]
/// ```
#[default(TopEdge::Metric(TopEdgeMetric::Ascender))]
pub top_edge: TopEdge,
/// The bottom end of the background rectangle.
///
/// ```example
/// #set highlight(bottom-edge: "descender")
/// #highlight[a] #highlight[ap]
///
/// #set highlight(bottom-edge: "baseline")
/// #highlight[a] #highlight[ap]
/// ```
#[default(BottomEdge::Metric(BottomEdgeMetric::Descender))]
pub bottom_edge: BottomEdge,
/// The amount by which to extend the background to the sides beyond
/// (or within if negative) the content.
///
/// ```example
/// A long #highlight(extent: 4pt)[background].
/// ```
pub extent: Length,
/// How much to round the highlight's corners. See the
/// [rectangle's documentation]($rect.radius) for more details.
///
/// ```example
/// Listen #highlight(
/// radius: 5pt, extent: 2pt
/// )[carefully], it will be on the test.
/// ```
#[fold]
pub radius: Corners<Option<Rel<Length>>>,
/// The content that should be highlighted.
#[required]
pub body: Content,
}
/// A text decoration.
///
/// Can be positioned over, under, or on top of text, or highlight the text with
/// a background.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Decoration {
pub line: DecoLine,
pub extent: Abs,
}
/// A kind of decorative line.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(clippy::large_enum_variant)]
pub enum DecoLine {
Underline {
stroke: Stroke<Abs>,
offset: Smart<Abs>,
evade: bool,
background: bool,
},
Strikethrough {
stroke: Stroke<Abs>,
offset: Smart<Abs>,
background: bool,
},
Overline {
stroke: Stroke<Abs>,
offset: Smart<Abs>,
evade: bool,
background: bool,
},
Highlight {
fill: Option<Paint>,
stroke: Sides<Option<FixedStroke>>,
top_edge: TopEdge,
bottom_edge: BottomEdge,
radius: Corners<Rel<Abs>>,
},
}
| 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/text/lang.rs | crates/typst-library/src/text/lang.rs | use std::str::FromStr;
use ecow::{EcoString, eco_format};
use rustc_hash::FxHashMap;
use crate::diag::Hint;
use crate::foundations::{StyleChain, cast};
use crate::layout::Dir;
use crate::text::TextElem;
macro_rules! translation {
($lang:literal) => {
($lang, include_str!(concat!("../../translations/", $lang, ".txt")))
};
}
const TRANSLATIONS: &[(&str, &str)] = &[
translation!("af"),
translation!("alt"),
translation!("am"),
translation!("ar"),
translation!("as"),
translation!("ast"),
translation!("az"),
translation!("be"),
translation!("bg"),
translation!("bn"),
translation!("bo"),
translation!("br"),
translation!("bs"),
translation!("bua"),
translation!("ca"),
translation!("ckb"),
translation!("cs"),
translation!("cu"),
translation!("cy"),
translation!("da"),
translation!("de"),
translation!("dsb"),
translation!("el"),
translation!("en"),
translation!("eo"),
translation!("es"),
translation!("et"),
translation!("eu"),
translation!("fa"),
translation!("fi"),
translation!("fil"),
translation!("fr"),
translation!("fr-CA"),
translation!("fur"),
translation!("ga"),
translation!("gd"),
translation!("gl"),
translation!("grc"),
translation!("gu"),
translation!("ha"),
translation!("he"),
translation!("hi"),
translation!("hr"),
translation!("hsb"),
translation!("hu"),
translation!("hy"),
translation!("ia"),
translation!("id"),
translation!("is"),
translation!("isv"),
translation!("it"),
translation!("ja"),
translation!("ka"),
translation!("km"),
translation!("kmr"),
translation!("kn"),
translation!("ko"),
translation!("ku"),
translation!("la"),
translation!("lb"),
translation!("lo"),
translation!("lt"),
translation!("lv"),
translation!("mk"),
translation!("ml"),
translation!("mr"),
translation!("ms"),
translation!("nb"),
translation!("nl"),
translation!("nn"),
translation!("no"),
translation!("oc"),
translation!("or"),
translation!("pa"),
translation!("pl"),
translation!("pms"),
translation!("pt"),
translation!("pt-PT"),
translation!("rm"),
translation!("ro"),
translation!("ru"),
translation!("se"),
translation!("si"),
translation!("sk"),
translation!("sl"),
translation!("sq"),
translation!("sr"),
translation!("sv"),
translation!("ta"),
translation!("te"),
translation!("th"),
translation!("tk"),
translation!("tl"),
translation!("tr"),
translation!("ug"),
translation!("uk"),
translation!("ur"),
translation!("vi"),
translation!("zh"),
translation!("zh-TW"),
];
/// A locale consisting of a language and an optional region.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Locale {
pub lang: Lang,
pub region: Option<Region>,
}
impl Default for Locale {
fn default() -> Self {
Self::DEFAULT
}
}
impl Locale {
pub const DEFAULT: Self = Self::new(Lang::ENGLISH, None);
pub const fn new(lang: Lang, region: Option<Region>) -> Self {
Locale { lang, region }
}
pub fn get_in(styles: StyleChain) -> Self {
Locale::new(styles.get(TextElem::lang), styles.get(TextElem::region))
}
pub fn rfc_3066(self) -> EcoString {
let mut buf = EcoString::from(self.lang.as_str());
if let Some(region) = self.region {
buf.push('-');
buf.push_str(region.as_str());
}
buf
}
}
/// An identifier for a natural language.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Lang([u8; 3], u8);
impl Lang {
pub const ABKHAZIAN: Self = Self(*b"ab ", 2);
pub const AFAR: Self = Self(*b"aa ", 2);
pub const AFRIKAANS: Self = Self(*b"af ", 2);
pub const AGHEM: Self = Self(*b"agq", 3);
pub const AKAN: Self = Self(*b"ak ", 2);
pub const AKKADIAN: Self = Self(*b"akk", 3);
pub const ALBANIAN: Self = Self(*b"sq ", 2);
pub const ALGERIAN_ARABIC: Self = Self(*b"arq", 3);
pub const AMHARIC: Self = Self(*b"am ", 2);
pub const ANCIENT_EGYPTIAN: Self = Self(*b"egy", 3);
pub const ANCIENT_GREEK: Self = Self(*b"grc", 3);
pub const ANCIENT_HEBREW: Self = Self(*b"hbo", 3);
pub const ARABIC: Self = Self(*b"ar ", 2);
pub const ARAMAIC: Self = Self(*b"arc", 3);
pub const ARMENIAN: Self = Self(*b"hy ", 2);
pub const ASSAMESE: Self = Self(*b"as ", 2);
pub const ASTURIAN: Self = Self(*b"ast", 3);
pub const ASU: Self = Self(*b"asa", 3);
pub const ATSAM: Self = Self(*b"cch", 3);
pub const AVESTAN: Self = Self(*b"ae ", 2);
pub const AWADHI: Self = Self(*b"awa", 3);
pub const AYMARA: Self = Self(*b"ay ", 2);
pub const AZERBAIJANI: Self = Self(*b"az ", 2);
pub const BAFIA: Self = Self(*b"ksf", 3);
pub const BALINESE: Self = Self(*b"ban", 3);
pub const BALUCHI: Self = Self(*b"bal", 3);
pub const BAMBARA: Self = Self(*b"bm ", 2);
pub const BANGLA: Self = Self(*b"bn ", 2);
pub const BASAA: Self = Self(*b"bas", 3);
pub const BASHKIR: Self = Self(*b"ba ", 2);
pub const BASQUE: Self = Self(*b"eu ", 2);
pub const BATAK_TOBA: Self = Self(*b"bbc", 3);
pub const BAVARIAN: Self = Self(*b"bar", 3);
pub const BELARUSIAN: Self = Self(*b"be ", 2);
pub const BEMBA: Self = Self(*b"bem", 3);
pub const BENA: Self = Self(*b"bez", 3);
pub const BETAWI: Self = Self(*b"bew", 3);
pub const BHOJPURI: Self = Self(*b"bho", 3);
pub const BLIN: Self = Self(*b"byn", 3);
pub const BODO: Self = Self(*b"brx", 3);
pub const BOSNIAN: Self = Self(*b"bs ", 2);
pub const BRETON: Self = Self(*b"br ", 2);
pub const BULGARIAN: Self = Self(*b"bg ", 2);
pub const BURIAT: Self = Self(*b"bua", 3);
pub const BURMESE: Self = Self(*b"my ", 2);
pub const CANTONESE: Self = Self(*b"yue", 3);
pub const CARIAN: Self = Self(*b"xcr", 3);
pub const CATALAN: Self = Self(*b"ca ", 2);
pub const CEBUANO: Self = Self(*b"ceb", 3);
pub const CENTRAL_ATLAS_TAMAZIGHT: Self = Self(*b"tzm", 3);
pub const CENTRAL_KURDISH: Self = Self(*b"ckb", 3);
pub const CHAKMA: Self = Self(*b"ccp", 3);
pub const CHECHEN: Self = Self(*b"ce ", 2);
pub const CHEROKEE: Self = Self(*b"chr", 3);
pub const CHIGA: Self = Self(*b"cgg", 3);
pub const CHINESE: Self = Self(*b"zh ", 2);
pub const CHURCH_SLAVIC: Self = Self(*b"cu ", 2);
pub const CHUVASH: Self = Self(*b"cv ", 2);
pub const CLASSICAL_MANDAIC: Self = Self(*b"myz", 3);
pub const COLOGNIAN: Self = Self(*b"ksh", 3);
pub const COPTIC: Self = Self(*b"cop", 3);
pub const CORNISH: Self = Self(*b"kw ", 2);
pub const CORSICAN: Self = Self(*b"co ", 2);
pub const CROATIAN: Self = Self(*b"hr ", 2);
pub const CZECH: Self = Self(*b"cs ", 2);
pub const DANISH: Self = Self(*b"da ", 2);
pub const DIVEHI: Self = Self(*b"dv ", 2);
pub const DOGRI: Self = Self(*b"doi", 3);
pub const DUALA: Self = Self(*b"dua", 3);
pub const DUTCH: Self = Self(*b"nl ", 2);
pub const DZONGKHA: Self = Self(*b"dz ", 2);
pub const EGYPTIAN_ARABIC: Self = Self(*b"arz", 3);
pub const EMBU: Self = Self(*b"ebu", 3);
pub const ENGLISH: Self = Self(*b"en ", 2);
pub const ERZYA: Self = Self(*b"myv", 3);
pub const ESPERANTO: Self = Self(*b"eo ", 2);
pub const ESTONIAN: Self = Self(*b"et ", 2);
pub const ETRUSCAN: Self = Self(*b"ett", 3);
pub const EWE: Self = Self(*b"ee ", 2);
pub const EWONDO: Self = Self(*b"ewo", 3);
pub const FAROESE: Self = Self(*b"fo ", 2);
pub const FILIPINO: Self = Self(*b"fil", 3);
pub const FINNISH: Self = Self(*b"fi ", 2);
pub const FRENCH: Self = Self(*b"fr ", 2);
pub const FRIULIAN: Self = Self(*b"fur", 3);
pub const FULAH: Self = Self(*b"ff ", 2);
pub const GA: Self = Self(*b"gaa", 3);
pub const GALICIAN: Self = Self(*b"gl ", 2);
pub const GANDA: Self = Self(*b"lg ", 2);
pub const GEEZ: Self = Self(*b"gez", 3);
pub const GEORGIAN: Self = Self(*b"ka ", 2);
pub const GERMAN: Self = Self(*b"de ", 2);
pub const GOTHIC: Self = Self(*b"got", 3);
pub const GREEK: Self = Self(*b"el ", 2);
pub const GUARANI: Self = Self(*b"gn ", 2);
pub const GUJARATI: Self = Self(*b"gu ", 2);
pub const GUSII: Self = Self(*b"guz", 3);
pub const HARYANVI: Self = Self(*b"bgc", 3);
pub const HAUSA: Self = Self(*b"ha ", 2);
pub const HAWAIIAN: Self = Self(*b"haw", 3);
pub const HEBREW: Self = Self(*b"he ", 2);
pub const HINDI: Self = Self(*b"hi ", 2);
pub const HMONG_NJUA: Self = Self(*b"hnj", 3);
pub const HUNGARIAN: Self = Self(*b"hu ", 2);
pub const ICELANDIC: Self = Self(*b"is ", 2);
pub const IGBO: Self = Self(*b"ig ", 2);
pub const INARI_SAMI: Self = Self(*b"smn", 3);
pub const INDONESIAN: Self = Self(*b"id ", 2);
pub const INGUSH: Self = Self(*b"inh", 3);
pub const INTERLINGUA: Self = Self(*b"ia ", 2);
pub const INTERSLAVIC: Self = Self(*b"isv", 3);
pub const INUKTITUT: Self = Self(*b"iu ", 2);
pub const IRISH: Self = Self(*b"ga ", 2);
pub const ITALIAN: Self = Self(*b"it ", 2);
pub const JAPANESE: Self = Self(*b"ja ", 2);
pub const JAVANESE: Self = Self(*b"jv ", 2);
pub const JJU: Self = Self(*b"kaj", 3);
pub const JOLA_FONYI: Self = Self(*b"dyo", 3);
pub const KABUVERDIANU: Self = Self(*b"kea", 3);
pub const KABYLE: Self = Self(*b"kab", 3);
pub const KAINGANG: Self = Self(*b"kgp", 3);
pub const KAKO: Self = Self(*b"kkj", 3);
pub const KALAALLISUT: Self = Self(*b"kl ", 2);
pub const KALENJIN: Self = Self(*b"kln", 3);
pub const KAMBA: Self = Self(*b"kam", 3);
pub const KANGRI: Self = Self(*b"xnr", 3);
pub const KANNADA: Self = Self(*b"kn ", 2);
pub const KASHMIRI: Self = Self(*b"ks ", 2);
pub const KAZAKH: Self = Self(*b"kk ", 2);
pub const KHMER: Self = Self(*b"km ", 2);
pub const KIKUYU: Self = Self(*b"ki ", 2);
pub const KINYARWANDA: Self = Self(*b"rw ", 2);
pub const KOMI: Self = Self(*b"kv ", 2);
pub const KONKANI: Self = Self(*b"kok", 3);
pub const KOREAN: Self = Self(*b"ko ", 2);
pub const KOYRABORO_SENNI: Self = Self(*b"ses", 3);
pub const KOYRA_CHIINI: Self = Self(*b"khq", 3);
pub const KURDISH: Self = Self(*b"ku ", 2);
pub const KWASIO: Self = Self(*b"nmg", 3);
pub const KYRGYZ: Self = Self(*b"ky ", 2);
pub const LADINO: Self = Self(*b"lad", 3);
pub const LAKOTA: Self = Self(*b"lkt", 3);
pub const LANGI: Self = Self(*b"lag", 3);
pub const LAO: Self = Self(*b"lo ", 2);
pub const LATIN: Self = Self(*b"la ", 2);
pub const LATVIAN: Self = Self(*b"lv ", 2);
pub const LEPCHA: Self = Self(*b"lep", 3);
pub const LIGURIAN: Self = Self(*b"lij", 3);
pub const LIMBU: Self = Self(*b"lif", 3);
pub const LINEAR_A: Self = Self(*b"lab", 3);
pub const LINGALA: Self = Self(*b"ln ", 2);
pub const LITHUANIAN: Self = Self(*b"lt ", 2);
pub const LOMBARD: Self = Self(*b"lmo", 3);
pub const LOWER_SORBIAN: Self = Self(*b"dsb", 3);
pub const LOW_GERMAN: Self = Self(*b"nds", 3);
pub const LUBA_KATANGA: Self = Self(*b"lu ", 2);
pub const LUO: Self = Self(*b"luo", 3);
pub const LUXEMBOURGISH: Self = Self(*b"lb ", 2);
pub const LUYIA: Self = Self(*b"luy", 3);
pub const LYCIAN: Self = Self(*b"xlc", 3);
pub const LYDIAN: Self = Self(*b"xld", 3);
pub const LU: Self = Self(*b"khb", 3);
pub const MACEDONIAN: Self = Self(*b"mk ", 2);
pub const MACHAME: Self = Self(*b"jmc", 3);
pub const MAITHILI: Self = Self(*b"mai", 3);
pub const MAKASAR: Self = Self(*b"mak", 3);
pub const MAKHUWA_MEETTO: Self = Self(*b"mgh", 3);
pub const MAKHUWA: Self = Self(*b"vmw", 3);
pub const MAKONDE: Self = Self(*b"kde", 3);
pub const MALAGASY: Self = Self(*b"mg ", 2);
pub const MALAY: Self = Self(*b"ms ", 2);
pub const MALAYALAM: Self = Self(*b"ml ", 2);
pub const MALTESE: Self = Self(*b"mt ", 2);
pub const MANIPURI: Self = Self(*b"mni", 3);
pub const MANX: Self = Self(*b"gv ", 2);
pub const MARATHI: Self = Self(*b"mr ", 2);
pub const MASAI: Self = Self(*b"mas", 3);
pub const MAZANDERANI: Self = Self(*b"mzn", 3);
pub const MERU: Self = Self(*b"mer", 3);
pub const METAʼ: Self = Self(*b"mgo", 3);
pub const MONGOLIAN: Self = Self(*b"mn ", 2);
pub const MORISYEN: Self = Self(*b"mfe", 3);
pub const MUNDANG: Self = Self(*b"mua", 3);
pub const MUSCOGEE: Self = Self(*b"mus", 3);
pub const MAORI: Self = Self(*b"mi ", 2);
pub const NAMA: Self = Self(*b"naq", 3);
pub const NAVAJO: Self = Self(*b"nv ", 2);
pub const NEPALI: Self = Self(*b"ne ", 2);
pub const NEWARI: Self = Self(*b"new", 3);
pub const NGIEMBOON: Self = Self(*b"nnh", 3);
pub const NGOMBA: Self = Self(*b"jgo", 3);
pub const NHEENGATU: Self = Self(*b"yrl", 3);
pub const NIGERIAN_PIDGIN: Self = Self(*b"pcm", 3);
pub const NORTHERN_FRISIAN: Self = Self(*b"frr", 3);
pub const NORTHERN_KURDISH: Self = Self(*b"kmr", 3);
pub const NORTHERN_LURI: Self = Self(*b"lrc", 3);
pub const NORTHERN_SAMI: Self = Self(*b"se ", 2);
pub const NORTHERN_SOTHO: Self = Self(*b"nso", 3);
pub const NORTH_NDEBELE: Self = Self(*b"nd ", 2);
pub const NORWEGIAN: Self = Self(*b"no ", 2);
pub const NORWEGIAN_BOKMAL: Self = Self(*b"nb ", 2);
pub const NORWEGIAN_NYNORSK: Self = Self(*b"nn ", 2);
pub const NUER: Self = Self(*b"nus", 3);
pub const NYANJA: Self = Self(*b"ny ", 2);
pub const NYANKOLE: Self = Self(*b"nyn", 3);
pub const NKO: Self = Self(*b"nqo", 3);
pub const OCCITAN: Self = Self(*b"oc ", 2);
pub const ODIA: Self = Self(*b"or ", 2);
pub const OLD_IRISH: Self = Self(*b"sga", 3);
pub const OLD_NORSE: Self = Self(*b"non", 3);
pub const OLD_PERSIAN: Self = Self(*b"peo", 3);
pub const OLD_UIGHUR: Self = Self(*b"oui", 3);
pub const OROMO: Self = Self(*b"om ", 2);
pub const OSAGE: Self = Self(*b"osa", 3);
pub const OSSETIC: Self = Self(*b"os ", 2);
pub const PAPIAMENTO: Self = Self(*b"pap", 3);
pub const PASHTO: Self = Self(*b"ps ", 2);
pub const PERSIAN: Self = Self(*b"fa ", 2);
pub const PHOENICIAN: Self = Self(*b"phn", 3);
pub const PIEDMONTESE: Self = Self(*b"pms", 3);
pub const POLISH: Self = Self(*b"pl ", 2);
pub const PORTUGUESE: Self = Self(*b"pt ", 2);
pub const PRUSSIAN: Self = Self(*b"prg", 3);
pub const PUNJABI: Self = Self(*b"pa ", 2);
pub const QUECHUA: Self = Self(*b"qu ", 2);
pub const RAJASTHANI: Self = Self(*b"raj", 3);
pub const ROMANIAN: Self = Self(*b"ro ", 2);
pub const ROMANSH: Self = Self(*b"rm ", 2);
pub const ROMBO: Self = Self(*b"rof", 3);
pub const RUNDI: Self = Self(*b"rn ", 2);
pub const RUSSIAN: Self = Self(*b"ru ", 2);
pub const RWA: Self = Self(*b"rwk", 3);
pub const SABAEAN: Self = Self(*b"xsa", 3);
pub const SAHO: Self = Self(*b"ssy", 3);
pub const SAKHA: Self = Self(*b"sah", 3);
pub const SAMARITAN: Self = Self(*b"smp", 3);
pub const SAMBURU: Self = Self(*b"saq", 3);
pub const SANGO: Self = Self(*b"sg ", 2);
pub const SANGU: Self = Self(*b"sbp", 3);
pub const SANSKRIT: Self = Self(*b"sa ", 2);
pub const SANTALI: Self = Self(*b"sat", 3);
pub const SARAIKI: Self = Self(*b"skr", 3);
pub const SARDINIAN: Self = Self(*b"sc ", 2);
pub const SCOTTISH_GAELIC: Self = Self(*b"gd ", 2);
pub const SENA: Self = Self(*b"seh", 3);
pub const SERBIAN: Self = Self(*b"sr ", 2);
pub const SHAMBALA: Self = Self(*b"ksb", 3);
pub const SHONA: Self = Self(*b"sn ", 2);
pub const SICHUAN_YI: Self = Self(*b"ii ", 2);
pub const SICILIAN: Self = Self(*b"scn", 3);
pub const SILESIAN: Self = Self(*b"szl", 3);
pub const SINDHI: Self = Self(*b"sd ", 2);
pub const SINHALA: Self = Self(*b"si ", 2);
pub const SINTE_ROMANI: Self = Self(*b"rmo", 3);
pub const SLOVAK: Self = Self(*b"sk ", 2);
pub const SLOVENIAN: Self = Self(*b"sl ", 2);
pub const SOGA: Self = Self(*b"xog", 3);
pub const SOMALI: Self = Self(*b"so ", 2);
pub const SOUTHERN_ALTAI: Self = Self(*b"alt", 3);
pub const SOUTHERN_SOTHO: Self = Self(*b"st ", 2);
pub const SOUTH_NDEBELE: Self = Self(*b"nr ", 2);
pub const SPANISH: Self = Self(*b"es ", 2);
pub const STANDARD_MOROCCAN_TAMAZIGHT: Self = Self(*b"zgh", 3);
pub const SUNDANESE: Self = Self(*b"su ", 2);
pub const SWAHILI: Self = Self(*b"sw ", 2);
pub const SWATI: Self = Self(*b"ss ", 2);
pub const SWEDISH: Self = Self(*b"sv ", 2);
pub const SWISS_GERMAN: Self = Self(*b"gsw", 3);
pub const SYRIAC: Self = Self(*b"syr", 3);
pub const TACHELHIT: Self = Self(*b"shi", 3);
pub const TAITA: Self = Self(*b"dav", 3);
pub const TAI_NUA: Self = Self(*b"tdd", 3);
pub const TAJIK: Self = Self(*b"tg ", 2);
pub const TAMIL: Self = Self(*b"ta ", 2);
pub const TANGUT: Self = Self(*b"txg", 3);
pub const TAROKO: Self = Self(*b"trv", 3);
pub const TASAWAQ: Self = Self(*b"twq", 3);
pub const TATAR: Self = Self(*b"tt ", 2);
pub const TELUGU: Self = Self(*b"te ", 2);
pub const TESO: Self = Self(*b"teo", 3);
pub const THAI: Self = Self(*b"th ", 2);
pub const TIBETAN: Self = Self(*b"bo ", 2);
pub const TIGRE: Self = Self(*b"tig", 3);
pub const TIGRINYA: Self = Self(*b"ti ", 2);
pub const TOK_PISIN: Self = Self(*b"tpi", 3);
pub const TONGAN: Self = Self(*b"to ", 2);
pub const TSONGA: Self = Self(*b"ts ", 2);
pub const TSWANA: Self = Self(*b"tn ", 2);
pub const TURKISH: Self = Self(*b"tr ", 2);
pub const TURKMEN: Self = Self(*b"tk ", 2);
pub const TYAP: Self = Self(*b"kcg", 3);
pub const UGARITIC: Self = Self(*b"uga", 3);
pub const UKRAINIAN: Self = Self(*b"uk ", 2);
pub const UNKNOWN_LANGUAGE: Self = Self(*b"und", 3);
pub const UPPER_SORBIAN: Self = Self(*b"hsb", 3);
pub const URDU: Self = Self(*b"ur ", 2);
pub const UYGHUR: Self = Self(*b"ug ", 2);
pub const UZBEK: Self = Self(*b"uz ", 2);
pub const VAI: Self = Self(*b"vai", 3);
pub const VENDA: Self = Self(*b"ve ", 2);
pub const VENETIAN: Self = Self(*b"vec", 3);
pub const VIETNAMESE: Self = Self(*b"vi ", 2);
pub const VOLAPUK: Self = Self(*b"vo ", 2);
pub const VUNJO: Self = Self(*b"vun", 3);
pub const WALSER: Self = Self(*b"wae", 3);
pub const WARAY: Self = Self(*b"war", 3);
pub const WELSH: Self = Self(*b"cy ", 2);
pub const WESTERN_FRISIAN: Self = Self(*b"fy ", 2);
pub const WOLAYTTA: Self = Self(*b"wal", 3);
pub const WOLOF: Self = Self(*b"wo ", 2);
pub const XHOSA: Self = Self(*b"xh ", 2);
pub const YANGBEN: Self = Self(*b"yav", 3);
pub const YIDDISH: Self = Self(*b"yi ", 2);
pub const YORUBA: Self = Self(*b"yo ", 2);
pub const ZARMA: Self = Self(*b"dje", 3);
pub const ZHUANG: Self = Self(*b"za ", 2);
pub const ZULU: Self = Self(*b"zu ", 2);
/// Return the language code as an all lowercase string slice.
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0[..usize::from(self.1)]).unwrap_or_default()
}
/// The default direction for the language.
pub fn dir(self) -> Dir {
match self.as_str() {
"ar" | "dv" | "fa" | "he" | "ks" | "pa" | "ps" | "sd" | "ug" | "ur"
| "yi" => Dir::RTL,
_ => Dir::LTR,
}
}
}
impl FromStr for Lang {
type Err = &'static str;
/// Construct a language from a two- or three-byte ISO 639-1/2/3 code.
fn from_str(iso: &str) -> Result<Self, Self::Err> {
let len = iso.len();
if matches!(len, 2..=3) && iso.is_ascii() {
let mut bytes = [b' '; 3];
bytes[..len].copy_from_slice(iso.as_bytes());
bytes.make_ascii_lowercase();
Ok(Self(bytes, len as u8))
} else {
Err("expected two or three letter language code (ISO 639-1/2/3)")
}
}
}
cast! {
Lang,
self => self.as_str().into_value(),
string: EcoString => {
let result = Self::from_str(&string);
if result.is_err()
&& let Some((lang, region)) = string.split_once('-')
&& Lang::from_str(lang).is_ok() && Region::from_str(region).is_ok() {
return result
.hint(eco_format!(
"you should leave only \"{}\" in the `lang` parameter and specify \"{}\" in the `region` parameter",
lang, region,
));
}
result?
}
}
/// An identifier for a region somewhere in the world.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Region([u8; 2]);
impl Region {
/// Return the region code as an all uppercase string slice.
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).unwrap_or_default()
}
}
impl PartialEq<&str> for Region {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl FromStr for Region {
type Err = &'static str;
/// Construct a region from its two-byte ISO 3166-1 alpha-2 code.
fn from_str(iso: &str) -> Result<Self, Self::Err> {
if iso.len() == 2 && iso.is_ascii() {
let mut bytes: [u8; 2] = iso.as_bytes().try_into().unwrap();
bytes.make_ascii_uppercase();
Ok(Self(bytes))
} else {
Err("expected two letter region code (ISO 3166-1 alpha-2)")
}
}
}
cast! {
Region,
self => self.as_str().into_value(),
string: EcoString => Self::from_str(&string)?,
}
/// An ISO 15924-type script identifier.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct WritingScript([u8; 4], u8);
impl WritingScript {
/// Return the script as an all lowercase string slice.
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0[..usize::from(self.1)]).unwrap_or_default()
}
/// Return the description of the script as raw bytes.
pub fn as_bytes(&self) -> &[u8; 4] {
&self.0
}
}
impl FromStr for WritingScript {
type Err = &'static str;
/// Construct a region from its ISO 15924 code.
fn from_str(iso: &str) -> Result<Self, Self::Err> {
let len = iso.len();
if matches!(len, 3..=4) && iso.is_ascii() {
let mut bytes = [b' '; 4];
bytes[..len].copy_from_slice(iso.as_bytes());
bytes.make_ascii_lowercase();
Ok(Self(bytes, len as u8))
} else {
Err("expected three or four letter script code (ISO 15924 or 'math')")
}
}
}
cast! {
WritingScript,
self => self.as_str().into_value(),
string: EcoString => Self::from_str(&string)?,
}
/// The name with which an element is referenced.
pub trait LocalName {
/// The key of an element in order to get its localized name.
const KEY: &'static str;
/// Get the name in the given language and (optionally) region.
fn local_name(lang: Lang, region: Option<Region>) -> &'static str {
localized_str(lang, region, Self::KEY)
}
/// Gets the local name from the style chain.
fn local_name_in(styles: StyleChain) -> &'static str
where
Self: Sized,
{
Self::local_name(styles.get(TextElem::lang), styles.get(TextElem::region))
}
}
/// Retrieves the localized string for a given language and region.
/// Silently falls back to English if no fitting string exists for
/// the given language + region. Panics if no fitting string exists
/// in both given language + region and English.
#[comemo::memoize]
pub fn localized_str(lang: Lang, region: Option<Region>, key: &str) -> &'static str {
let lang_region_bundle = parse_language_bundle(lang, region).unwrap();
if let Some(str) = lang_region_bundle.get(key) {
return str;
}
let lang_bundle = parse_language_bundle(lang, None).unwrap();
if let Some(str) = lang_bundle.get(key) {
return str;
}
let english_bundle = parse_language_bundle(Lang::ENGLISH, None).unwrap();
english_bundle.get(key).unwrap()
}
/// Parses the translation file for a given language and region.
/// Only returns an error if the language file is malformed.
#[comemo::memoize]
fn parse_language_bundle(
lang: Lang,
region: Option<Region>,
) -> Result<FxHashMap<&'static str, &'static str>, &'static str> {
let language_tuple = TRANSLATIONS.iter().find(|it| it.0 == lang_str(lang, region));
let Some((_lang_name, language_file)) = language_tuple else {
return Ok(FxHashMap::default());
};
let mut bundle = FxHashMap::default();
let lines = language_file.trim().lines();
for line in lines {
if line.trim().starts_with('#') {
continue;
}
let (key, val) = line
.split_once('=')
.ok_or("malformed translation file: line without \"=\"")?;
let (key, val) = (key.trim(), val.trim());
if val.is_empty() {
return Err("malformed translation file: empty translation value");
}
let duplicate = bundle.insert(key.trim(), val.trim());
if duplicate.is_some() {
return Err("malformed translation file: duplicate key");
}
}
Ok(bundle)
}
/// Convert language + region to a string to be able to get a file name.
fn lang_str(lang: Lang, region: Option<Region>) -> EcoString {
EcoString::from(lang.as_str())
+ region.map_or_else(EcoString::new, |r| EcoString::from("-") + r.as_str())
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use rustc_hash::FxHashSet;
use typst_utils::option_eq;
use super::*;
fn translation_files_iter() -> impl Iterator<Item = PathBuf> {
std::fs::read_dir("translations")
.unwrap()
.map(|e| e.unwrap().path())
.filter(|e| e.is_file() && e.extension().is_some_and(|e| e == "txt"))
}
#[test]
fn test_region_option_eq() {
let region = Some(Region([b'U', b'S']));
assert!(option_eq(region, "US"));
assert!(!option_eq(region, "AB"));
}
#[test]
fn test_all_translations_included() {
let defined_keys =
FxHashSet::<&str>::from_iter(TRANSLATIONS.iter().map(|(lang, _)| *lang));
let mut checked = 0;
for file in translation_files_iter() {
assert!(
defined_keys.contains(
file.file_stem()
.expect("translation file should have basename")
.to_str()
.expect("translation file name should be UTF-8 encoded")
),
"translation from {:?} should be registered in TRANSLATIONS in {}",
file.file_name().unwrap(),
file!(),
);
checked += 1;
}
assert_eq!(TRANSLATIONS.len(), checked);
}
#[test]
fn test_all_translation_files_formatted() {
for file in translation_files_iter() {
let content = std::fs::read_to_string(&file)
.expect("translation file should be in UTF-8 encoding");
let filename = file.file_name().unwrap();
assert!(
content.ends_with('\n'),
"translation file {filename:?} should end with linebreak",
);
for line in content.lines() {
assert_eq!(
line.trim(),
line,
"line {line:?} in {filename:?} should not have extra whitespaces"
);
}
}
}
#[test]
fn test_translations_sorted() {
assert!(
TRANSLATIONS.is_sorted_by_key(|(lang, _)| lang),
"TRANSLATIONS should be sorted"
);
}
}
| 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/text/font/mod.rs | crates/typst-library/src/text/font/mod.rs | //! Font handling.
pub mod color;
mod book;
mod exceptions;
mod variant;
pub use self::book::{Coverage, FontBook, FontFlags, FontInfo};
pub use self::variant::{FontStretch, FontStyle, FontVariant, FontWeight};
use std::cell::OnceCell;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use ttf_parser::{GlyphId, name_id};
use self::book::find_name;
use crate::foundations::{Bytes, Cast};
use crate::layout::{Abs, Em, Frame};
use crate::text::{
BottomEdge, DEFAULT_SUBSCRIPT_METRICS, DEFAULT_SUPERSCRIPT_METRICS, TopEdge,
};
/// An OpenType font.
///
/// Values of this type are cheap to clone and hash.
#[derive(Clone)]
pub struct Font(Arc<FontInner>);
/// The internal representation of a [`Font`].
struct FontInner {
/// The font's index in the buffer.
index: u32,
/// Metadata about the font.
info: FontInfo,
/// The font's metrics.
metrics: FontMetrics,
/// The underlying ttf-parser face.
ttf: ttf_parser::Face<'static>,
/// The underlying rustybuzz face.
rusty: rustybuzz::Face<'static>,
// NOTE: `ttf` and `rusty` reference `data`, so it's important for `data`
// to be dropped after them or they will be left dangling while they're
// dropped. Fields are dropped in declaration order, so `data` needs to be
// declared after `ttf` and `rusty`.
/// The raw font data, possibly shared with other fonts from the same
/// collection. The vector's allocation must not move, because `ttf` points
/// into it using unsafe code.
data: Bytes,
}
impl Font {
/// Parse a font from data and collection index.
pub fn new(data: Bytes, index: u32) -> Option<Self> {
// Safety:
// - The slices's location is stable in memory:
// - We don't move the underlying vector
// - Nobody else can move it since we have a strong ref to the `Arc`.
// - The internal 'static lifetime is not leaked because its rewritten
// to the self-lifetime in `ttf()`.
let slice: &'static [u8] =
unsafe { std::slice::from_raw_parts(data.as_ptr(), data.len()) };
let ttf = ttf_parser::Face::parse(slice, index).ok()?;
let rusty = rustybuzz::Face::from_slice(slice, index)?;
let metrics = FontMetrics::from_ttf(&ttf);
let info = FontInfo::from_ttf(&ttf)?;
Some(Self(Arc::new(FontInner { data, index, info, metrics, ttf, rusty })))
}
/// Parse all fonts in the given data.
pub fn iter(data: Bytes) -> impl Iterator<Item = Self> {
let count = ttf_parser::fonts_in_collection(&data).unwrap_or(1);
(0..count).filter_map(move |index| Self::new(data.clone(), index))
}
/// The underlying buffer.
pub fn data(&self) -> &Bytes {
&self.0.data
}
/// The font's index in the buffer.
pub fn index(&self) -> u32 {
self.0.index
}
/// The font's metadata.
pub fn info(&self) -> &FontInfo {
&self.0.info
}
/// The font's metrics.
pub fn metrics(&self) -> &FontMetrics {
&self.0.metrics
}
/// The font's math constants.
#[inline]
pub fn math(&self) -> &MathConstants {
self.0.metrics.math.get_or_init(|| FontMetrics::init_math(self))
}
/// The number of font units per one em.
pub fn units_per_em(&self) -> f64 {
self.0.metrics.units_per_em
}
/// Convert from font units to an em length.
pub fn to_em(&self, units: impl Into<f64>) -> Em {
Em::from_units(units, self.units_per_em())
}
/// Look up the horizontal advance width of a glyph.
pub fn x_advance(&self, glyph: u16) -> Option<Em> {
self.0
.ttf
.glyph_hor_advance(GlyphId(glyph))
.map(|units| self.to_em(units))
}
/// Look up the vertical advance width of a glyph.
pub fn y_advance(&self, glyph: u16) -> Option<Em> {
self.0
.ttf
.glyph_ver_advance(GlyphId(glyph))
.map(|units| self.to_em(units))
}
/// Lookup a name by id.
pub fn find_name(&self, id: u16) -> Option<String> {
find_name(&self.0.ttf, id)
}
/// A reference to the underlying `ttf-parser` face.
pub fn ttf(&self) -> &ttf_parser::Face<'_> {
// We can't implement Deref because that would leak the
// internal 'static lifetime.
&self.0.ttf
}
/// A reference to the underlying `rustybuzz` face.
pub fn rusty(&self) -> &rustybuzz::Face<'_> {
// We can't implement Deref because that would leak the
// internal 'static lifetime.
&self.0.rusty
}
/// Resolve the top and bottom edges of text.
pub fn edges(
&self,
top_edge: TopEdge,
bottom_edge: BottomEdge,
font_size: Abs,
bounds: TextEdgeBounds,
) -> (Abs, Abs) {
let cell = OnceCell::new();
let bbox = |gid, f: fn(ttf_parser::Rect) -> i16| {
cell.get_or_init(|| self.ttf().glyph_bounding_box(GlyphId(gid)))
.map(|bbox| self.to_em(f(bbox)).at(font_size))
.unwrap_or_default()
};
let top = match top_edge {
TopEdge::Metric(metric) => match metric.try_into() {
Ok(metric) => self.metrics().vertical(metric).at(font_size),
Err(_) => match bounds {
TextEdgeBounds::Zero => Abs::zero(),
TextEdgeBounds::Frame(frame) => frame.ascent(),
TextEdgeBounds::Glyph(gid) => bbox(gid, |b| b.y_max),
},
},
TopEdge::Length(length) => length.at(font_size),
};
let bottom = match bottom_edge {
BottomEdge::Metric(metric) => match metric.try_into() {
Ok(metric) => -self.metrics().vertical(metric).at(font_size),
Err(_) => match bounds {
TextEdgeBounds::Zero => Abs::zero(),
TextEdgeBounds::Frame(frame) => frame.descent(),
TextEdgeBounds::Glyph(gid) => -bbox(gid, |b| b.y_min),
},
},
BottomEdge::Length(length) => -length.at(font_size),
};
(top, bottom)
}
}
impl Hash for Font {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.data.hash(state);
self.0.index.hash(state);
}
}
impl Debug for Font {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Font({}, {:?})", self.info().family, self.info().variant)
}
}
impl Eq for Font {}
impl PartialEq for Font {
fn eq(&self, other: &Self) -> bool {
self.0.data == other.0.data && self.0.index == other.0.index
}
}
/// Metrics of a font.
#[derive(Debug, Clone)]
pub struct FontMetrics {
/// How many font units represent one em unit.
pub units_per_em: f64,
/// The distance from the baseline to the typographic ascender.
pub ascender: Em,
/// The approximate height of uppercase letters.
pub cap_height: Em,
/// The approximate height of non-ascending lowercase letters.
pub x_height: Em,
/// The distance from the baseline to the typographic descender.
pub descender: Em,
/// Recommended metrics for a strikethrough line.
pub strikethrough: LineMetrics,
/// Recommended metrics for an underline.
pub underline: LineMetrics,
/// Recommended metrics for an overline.
pub overline: LineMetrics,
/// Metrics for subscripts, if provided by the font.
pub subscript: Option<ScriptMetrics>,
/// Metrics for superscripts, if provided by the font.
pub superscript: Option<ScriptMetrics>,
/// Metrics for math layout.
pub math: OnceLock<Box<MathConstants>>,
}
impl FontMetrics {
/// Extract the font's metrics.
pub fn from_ttf(ttf: &ttf_parser::Face) -> Self {
let units_per_em = f64::from(ttf.units_per_em());
let to_em = |units| Em::from_units(units, units_per_em);
let ascender = to_em(ttf.typographic_ascender().unwrap_or(ttf.ascender()));
let cap_height = ttf.capital_height().filter(|&h| h > 0).map_or(ascender, to_em);
let x_height = ttf.x_height().filter(|&h| h > 0).map_or(ascender, to_em);
let descender = to_em(ttf.typographic_descender().unwrap_or(ttf.descender()));
let strikeout = ttf.strikeout_metrics();
let underline = ttf.underline_metrics();
let strikethrough = LineMetrics {
position: strikeout.map_or(Em::new(0.25), |s| to_em(s.position)),
thickness: strikeout
.or(underline)
.map_or(Em::new(0.06), |s| to_em(s.thickness)),
};
let underline = LineMetrics {
position: underline.map_or(Em::new(-0.2), |s| to_em(s.position)),
thickness: underline
.or(strikeout)
.map_or(Em::new(0.06), |s| to_em(s.thickness)),
};
let overline = LineMetrics {
position: cap_height + Em::new(0.1),
thickness: underline.thickness,
};
let subscript = ttf.subscript_metrics().map(|metrics| ScriptMetrics {
width: to_em(metrics.x_size),
height: to_em(metrics.y_size),
horizontal_offset: to_em(metrics.x_offset),
vertical_offset: -to_em(metrics.y_offset),
});
let superscript = ttf.superscript_metrics().map(|metrics| ScriptMetrics {
width: to_em(metrics.x_size),
height: to_em(metrics.y_size),
horizontal_offset: to_em(metrics.x_offset),
vertical_offset: to_em(metrics.y_offset),
});
Self {
units_per_em,
ascender,
cap_height,
x_height,
descender,
strikethrough,
underline,
overline,
superscript,
subscript,
math: OnceLock::new(),
}
}
fn init_math(font: &Font) -> Box<MathConstants> {
let ttf = font.ttf();
let metrics = font.metrics();
let space_width = ttf
.glyph_index(' ')
.and_then(|id| ttf.glyph_hor_advance(id).map(|units| font.to_em(units)))
.unwrap_or(typst_library::math::THICK);
let is_cambria = || {
font.find_name(name_id::POST_SCRIPT_NAME)
.is_some_and(|name| name == "CambriaMath")
};
Box::new(
ttf.tables()
.math
.and_then(|math| math.constants)
.map(|constants| MathConstants {
space_width,
script_percent_scale_down: constants.script_percent_scale_down(),
script_script_percent_scale_down: constants
.script_script_percent_scale_down(),
display_operator_min_height: font.to_em(if is_cambria() {
constants.delimited_sub_formula_min_height()
} else {
constants.display_operator_min_height()
}),
axis_height: font.to_em(constants.axis_height().value),
accent_base_height: font.to_em(constants.accent_base_height().value),
flattened_accent_base_height: font
.to_em(constants.flattened_accent_base_height().value),
subscript_shift_down: font
.to_em(constants.subscript_shift_down().value),
subscript_top_max: font.to_em(constants.subscript_top_max().value),
subscript_baseline_drop_min: font
.to_em(constants.subscript_baseline_drop_min().value),
superscript_shift_up: font
.to_em(constants.superscript_shift_up().value),
superscript_shift_up_cramped: font
.to_em(constants.superscript_shift_up_cramped().value),
superscript_bottom_min: font
.to_em(constants.superscript_bottom_min().value),
superscript_baseline_drop_max: font
.to_em(constants.superscript_baseline_drop_max().value),
sub_superscript_gap_min: font
.to_em(constants.sub_superscript_gap_min().value),
superscript_bottom_max_with_subscript: font
.to_em(constants.superscript_bottom_max_with_subscript().value),
space_after_script: font.to_em(constants.space_after_script().value),
upper_limit_gap_min: font
.to_em(constants.upper_limit_gap_min().value),
upper_limit_baseline_rise_min: font
.to_em(constants.upper_limit_baseline_rise_min().value),
lower_limit_gap_min: font
.to_em(constants.lower_limit_gap_min().value),
lower_limit_baseline_drop_min: font
.to_em(constants.lower_limit_baseline_drop_min().value),
fraction_numerator_shift_up: font
.to_em(constants.fraction_numerator_shift_up().value),
fraction_numerator_display_style_shift_up: font.to_em(
constants.fraction_numerator_display_style_shift_up().value,
),
fraction_denominator_shift_down: font
.to_em(constants.fraction_denominator_shift_down().value),
fraction_denominator_display_style_shift_down: font.to_em(
constants.fraction_denominator_display_style_shift_down().value,
),
fraction_numerator_gap_min: font
.to_em(constants.fraction_numerator_gap_min().value),
fraction_num_display_style_gap_min: font
.to_em(constants.fraction_num_display_style_gap_min().value),
fraction_rule_thickness: font
.to_em(constants.fraction_rule_thickness().value),
fraction_denominator_gap_min: font
.to_em(constants.fraction_denominator_gap_min().value),
fraction_denom_display_style_gap_min: font
.to_em(constants.fraction_denom_display_style_gap_min().value),
skewed_fraction_vertical_gap: font
.to_em(constants.skewed_fraction_vertical_gap().value),
skewed_fraction_horizontal_gap: font
.to_em(constants.skewed_fraction_horizontal_gap().value),
overbar_vertical_gap: font
.to_em(constants.overbar_vertical_gap().value),
overbar_rule_thickness: font
.to_em(constants.overbar_rule_thickness().value),
overbar_extra_ascender: font
.to_em(constants.overbar_extra_ascender().value),
underbar_vertical_gap: font
.to_em(constants.underbar_vertical_gap().value),
underbar_rule_thickness: font
.to_em(constants.underbar_rule_thickness().value),
underbar_extra_descender: font
.to_em(constants.underbar_extra_descender().value),
radical_vertical_gap: font
.to_em(constants.radical_vertical_gap().value),
radical_display_style_vertical_gap: font
.to_em(constants.radical_display_style_vertical_gap().value),
radical_rule_thickness: font
.to_em(constants.radical_rule_thickness().value),
radical_extra_ascender: font
.to_em(constants.radical_extra_ascender().value),
radical_kern_before_degree: font
.to_em(constants.radical_kern_before_degree().value),
radical_kern_after_degree: font
.to_em(constants.radical_kern_after_degree().value),
radical_degree_bottom_raise_percent: constants
.radical_degree_bottom_raise_percent()
as f64
/ 100.0,
})
// Most of these fallback constants are from the MathML Core
// spec, with the exceptions of
// - `flattened_accent_base_height` from Building Math Fonts
// - `overbar_rule_thickness` and `underbar_rule_thickness`
// from our best guess
// - `skewed_fraction_vertical_gap` and `skewed_fraction_horizontal_gap`
// from our best guess
// - `script_percent_scale_down` and
// `script_script_percent_scale_down` from Building Math
// Fonts as the defaults given in MathML Core have more
// precision than i16.
//
// https://www.w3.org/TR/mathml-core/#layout-constants-mathconstants
// https://github.com/notofonts/math/blob/main/documentation/building-math-fonts/index.md
.unwrap_or(MathConstants {
space_width,
script_percent_scale_down: 70,
script_script_percent_scale_down: 50,
display_operator_min_height: Em::zero(),
axis_height: metrics.x_height / 2.0,
accent_base_height: metrics.x_height,
flattened_accent_base_height: metrics.cap_height,
subscript_shift_down: metrics
.subscript
.map(|metrics| metrics.vertical_offset)
.unwrap_or(DEFAULT_SUBSCRIPT_METRICS.vertical_offset),
subscript_top_max: 0.8 * metrics.x_height,
subscript_baseline_drop_min: Em::zero(),
superscript_shift_up: metrics
.superscript
.map(|metrics| metrics.vertical_offset)
.unwrap_or(DEFAULT_SUPERSCRIPT_METRICS.vertical_offset),
superscript_shift_up_cramped: Em::zero(),
superscript_bottom_min: 0.25 * metrics.x_height,
superscript_baseline_drop_max: Em::zero(),
sub_superscript_gap_min: 4.0 * metrics.underline.thickness,
superscript_bottom_max_with_subscript: 0.8 * metrics.x_height,
space_after_script: Em::new(1.0 / 24.0),
upper_limit_gap_min: Em::zero(),
upper_limit_baseline_rise_min: Em::zero(),
lower_limit_gap_min: Em::zero(),
lower_limit_baseline_drop_min: Em::zero(),
fraction_numerator_shift_up: Em::zero(),
fraction_numerator_display_style_shift_up: Em::zero(),
fraction_denominator_shift_down: Em::zero(),
fraction_denominator_display_style_shift_down: Em::zero(),
fraction_numerator_gap_min: metrics.underline.thickness,
fraction_num_display_style_gap_min: 3.0 * metrics.underline.thickness,
fraction_rule_thickness: metrics.underline.thickness,
fraction_denominator_gap_min: metrics.underline.thickness,
fraction_denom_display_style_gap_min: 3.0
* metrics.underline.thickness,
skewed_fraction_vertical_gap: Em::zero(),
skewed_fraction_horizontal_gap: Em::new(0.5),
overbar_vertical_gap: 3.0 * metrics.underline.thickness,
overbar_rule_thickness: metrics.underline.thickness,
overbar_extra_ascender: metrics.underline.thickness,
underbar_vertical_gap: 3.0 * metrics.underline.thickness,
underbar_rule_thickness: metrics.underline.thickness,
underbar_extra_descender: metrics.underline.thickness,
radical_vertical_gap: 1.25 * metrics.underline.thickness,
radical_display_style_vertical_gap: metrics.underline.thickness
+ 0.25 * metrics.x_height,
radical_rule_thickness: metrics.underline.thickness,
radical_extra_ascender: metrics.underline.thickness,
radical_kern_before_degree: Em::new(5.0 / 18.0),
radical_kern_after_degree: Em::new(-10.0 / 18.0),
radical_degree_bottom_raise_percent: 0.6,
}),
)
}
/// Look up a vertical metric.
pub fn vertical(&self, metric: VerticalFontMetric) -> Em {
match metric {
VerticalFontMetric::Ascender => self.ascender,
VerticalFontMetric::CapHeight => self.cap_height,
VerticalFontMetric::XHeight => self.x_height,
VerticalFontMetric::Baseline => Em::zero(),
VerticalFontMetric::Descender => self.descender,
}
}
}
/// Metrics for a decorative line.
#[derive(Debug, Copy, Clone)]
pub struct LineMetrics {
/// The vertical offset of the line from the baseline. Positive goes
/// upwards, negative downwards.
pub position: Em,
/// The thickness of the line.
pub thickness: Em,
}
/// Metrics for subscripts or superscripts.
#[derive(Debug, Copy, Clone)]
pub struct ScriptMetrics {
/// The width of those scripts, relative to the outer font size.
pub width: Em,
/// The height of those scripts, relative to the outer font size.
pub height: Em,
/// The horizontal (to the right) offset of those scripts, relative to the
/// outer font size.
///
/// This is used for italic correction.
pub horizontal_offset: Em,
/// The vertical (to the top) offset of those scripts, relative to the outer font size.
///
/// For superscripts, this is positive. For subscripts, this is negative.
pub vertical_offset: Em,
}
/// Constants from the OpenType MATH constants table used in Typst.
///
/// Ones not currently used are omitted.
#[derive(Debug, Copy, Clone)]
pub struct MathConstants {
// This is not from the OpenType MATH spec.
pub space_width: Em,
// These are both i16 instead of f64 as they need to go on the StyleChain.
pub script_percent_scale_down: i16,
pub script_script_percent_scale_down: i16,
pub display_operator_min_height: Em,
pub axis_height: Em,
pub accent_base_height: Em,
pub flattened_accent_base_height: Em,
pub subscript_shift_down: Em,
pub subscript_top_max: Em,
pub subscript_baseline_drop_min: Em,
pub superscript_shift_up: Em,
pub superscript_shift_up_cramped: Em,
pub superscript_bottom_min: Em,
pub superscript_baseline_drop_max: Em,
pub sub_superscript_gap_min: Em,
pub superscript_bottom_max_with_subscript: Em,
pub space_after_script: Em,
pub upper_limit_gap_min: Em,
pub upper_limit_baseline_rise_min: Em,
pub lower_limit_gap_min: Em,
pub lower_limit_baseline_drop_min: Em,
pub fraction_numerator_shift_up: Em,
pub fraction_numerator_display_style_shift_up: Em,
pub fraction_denominator_shift_down: Em,
pub fraction_denominator_display_style_shift_down: Em,
pub fraction_numerator_gap_min: Em,
pub fraction_num_display_style_gap_min: Em,
pub fraction_rule_thickness: Em,
pub fraction_denominator_gap_min: Em,
pub fraction_denom_display_style_gap_min: Em,
pub skewed_fraction_vertical_gap: Em,
pub skewed_fraction_horizontal_gap: Em,
pub overbar_vertical_gap: Em,
pub overbar_rule_thickness: Em,
pub overbar_extra_ascender: Em,
pub underbar_vertical_gap: Em,
pub underbar_rule_thickness: Em,
pub underbar_extra_descender: Em,
pub radical_vertical_gap: Em,
pub radical_display_style_vertical_gap: Em,
pub radical_rule_thickness: Em,
pub radical_extra_ascender: Em,
pub radical_kern_before_degree: Em,
pub radical_kern_after_degree: Em,
pub radical_degree_bottom_raise_percent: f64,
}
/// Identifies a vertical metric of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum VerticalFontMetric {
/// The font's ascender, which typically exceeds the height of all glyphs.
Ascender,
/// The approximate height of uppercase letters.
CapHeight,
/// The approximate height of non-ascending lowercase letters.
XHeight,
/// The baseline on which the letters rest.
Baseline,
/// The font's ascender, which typically exceeds the depth of all glyphs.
Descender,
}
/// Defines how to resolve a `Bounds` text edge.
#[derive(Debug, Copy, Clone)]
pub enum TextEdgeBounds<'a> {
/// Set the bounds to zero.
Zero,
/// Use the bounding box of the given glyph for the bounds.
Glyph(u16),
/// Use the dimension of the given frame for the bounds.
Frame(&'a Frame),
}
| 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/text/font/color.rs | crates/typst-library/src/text/font/color.rs | //! Utilities for color font handling
use std::io::Read;
use ttf_parser::{GlyphId, RgbaColor};
use typst_syntax::Span;
use usvg::tiny_skia_path;
use xmlwriter::XmlWriter;
use crate::foundations::Bytes;
use crate::layout::{Abs, Frame, FrameItem, Point, Size};
use crate::text::{Font, Glyph};
use crate::visualize::{
ExchangeFormat, FixedStroke, Geometry, Image, RasterImage, SvgImage,
};
/// Whether this glyph should be rendered via simple outlining instead of via
/// `glyph_frame`.
pub fn should_outline(font: &Font, glyph: &Glyph) -> bool {
let ttf = font.ttf();
let glyph_id = GlyphId(glyph.id);
(ttf.tables().glyf.is_some() || ttf.tables().cff.is_some())
&& !ttf
.glyph_raster_image(glyph_id, u16::MAX)
.is_some_and(|img| img.format == ttf_parser::RasterImageFormat::PNG)
&& !ttf.is_color_glyph(glyph_id)
&& ttf.glyph_svg_image(glyph_id).is_none()
}
/// Returns a frame representing a glyph and whether it is a fallback tofu
/// frame.
///
/// Should only be called on glyphs for which [`should_outline`] returns false.
///
/// The glyphs are sized in font units, [`text.item.size`] is not taken into
/// account.
///
/// [`text.item.size`]: crate::text::TextItem::size
#[comemo::memoize]
pub fn glyph_frame(font: &Font, glyph_id: u16) -> (Frame, bool) {
let upem = Abs::pt(font.units_per_em());
let glyph_id = GlyphId(glyph_id);
let mut frame = Frame::soft(Size::splat(upem));
let mut tofu = false;
if draw_glyph(&mut frame, font, upem, glyph_id).is_none()
&& font.ttf().glyph_index(' ') != Some(glyph_id)
{
// Generate a fallback tofu if the glyph couldn't be drawn, unless it is
// the space glyph. Then, an empty frame does the job. (This happens for
// some rare CBDT fonts, which don't define a bitmap for the space, but
// also don't have a glyf or CFF table.)
draw_fallback_tofu(&mut frame, font, upem, glyph_id);
tofu = true;
}
(frame, tofu)
}
/// Tries to draw a glyph.
fn draw_glyph(
frame: &mut Frame,
font: &Font,
upem: Abs,
glyph_id: GlyphId,
) -> Option<()> {
let ttf = font.ttf();
if let Some(raster_image) = ttf
.glyph_raster_image(glyph_id, u16::MAX)
.filter(|img| img.format == ttf_parser::RasterImageFormat::PNG)
{
draw_raster_glyph(frame, font, upem, raster_image)
} else if ttf.is_color_glyph(glyph_id) {
draw_colr_glyph(frame, font, upem, glyph_id)
} else if ttf.glyph_svg_image(glyph_id).is_some() {
draw_svg_glyph(frame, font, upem, glyph_id)
} else {
None
}
}
/// Draws a fallback tofu box with the advance width of the glyph.
fn draw_fallback_tofu(frame: &mut Frame, font: &Font, upem: Abs, glyph_id: GlyphId) {
let advance = font
.ttf()
.glyph_hor_advance(glyph_id)
.map(|advance| Abs::pt(advance as f64))
.unwrap_or(upem / 3.0);
let inset = 0.15 * advance;
let height = 0.7 * upem;
let pos = Point::new(inset, upem - height);
let size = Size::new(advance - inset * 2.0, height);
let thickness = upem / 20.0;
let stroke = FixedStroke { thickness, ..Default::default() };
let shape = Geometry::Rect(size).stroked(stroke);
frame.push(pos, FrameItem::Shape(shape, Span::detached()));
}
/// Draws a raster glyph in a frame.
///
/// Supports only PNG images.
fn draw_raster_glyph(
frame: &mut Frame,
font: &Font,
upem: Abs,
raster_image: ttf_parser::RasterGlyphImage,
) -> Option<()> {
let data = Bytes::new(raster_image.data.to_vec());
let image = Image::plain(RasterImage::plain(data, ExchangeFormat::Png).ok()?);
// Apple Color emoji doesn't provide offset information (or at least
// not in a way ttf-parser understands), so we artificially shift their
// baseline to make it look good.
let y_offset = if font.info().family.to_lowercase() == "apple color emoji" {
20.0
} else {
-(raster_image.y as f64)
};
let position = Point::new(
upem * raster_image.x as f64 / raster_image.pixels_per_em as f64,
upem * y_offset / raster_image.pixels_per_em as f64,
);
let aspect_ratio = image.width() / image.height();
let size = Size::new(upem, upem * aspect_ratio);
frame.push(position, FrameItem::Image(image, size, Span::detached()));
Some(())
}
/// Convert a COLR glyph into an SVG file.
pub fn colr_glyph_to_svg(font: &Font, glyph_id: GlyphId) -> Option<String> {
let mut svg = XmlWriter::new(xmlwriter::Options::default());
let ttf = font.ttf();
let width = ttf.global_bounding_box().width() as f64;
let height = ttf.global_bounding_box().height() as f64;
let x_min = ttf.global_bounding_box().x_min as f64;
let y_max = ttf.global_bounding_box().y_max as f64;
let tx = -x_min;
let ty = -y_max;
svg.start_element("svg");
svg.write_attribute("xmlns", "http://www.w3.org/2000/svg");
svg.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.write_attribute("width", &width);
svg.write_attribute("height", &height);
svg.write_attribute_fmt("viewBox", format_args!("0 0 {width} {height}"));
let mut path_buf = String::with_capacity(256);
let gradient_index = 1;
let clip_path_index = 1;
svg.start_element("g");
svg.write_attribute_fmt(
"transform",
format_args!("matrix(1 0 0 -1 0 0) matrix(1 0 0 1 {tx} {ty})"),
);
let mut glyph_painter = GlyphPainter {
face: ttf,
svg: &mut svg,
path_buf: &mut path_buf,
gradient_index,
clip_path_index,
palette_index: 0,
transform: ttf_parser::Transform::default(),
outline_transform: ttf_parser::Transform::default(),
transforms_stack: vec![ttf_parser::Transform::default()],
};
ttf.paint_color_glyph(glyph_id, 0, RgbaColor::new(0, 0, 0, 255), &mut glyph_painter)?;
svg.end_element();
Some(svg.end_document())
}
/// Draws a glyph from the COLR table into the frame.
fn draw_colr_glyph(
frame: &mut Frame,
font: &Font,
upem: Abs,
glyph_id: GlyphId,
) -> Option<()> {
let svg_string = colr_glyph_to_svg(font, glyph_id)?;
let ttf = font.ttf();
let width = ttf.global_bounding_box().width() as f64;
let height = ttf.global_bounding_box().height() as f64;
let x_min = ttf.global_bounding_box().x_min as f64;
let y_max = ttf.global_bounding_box().y_max as f64;
let data = Bytes::from_string(svg_string);
let image = Image::plain(SvgImage::new(data).ok()?);
let y_shift = Abs::pt(upem.to_pt() - y_max);
let position = Point::new(Abs::pt(x_min), y_shift);
let size = Size::new(Abs::pt(width), Abs::pt(height));
frame.push(position, FrameItem::Image(image, size, Span::detached()));
Some(())
}
/// Draws an SVG glyph in a frame.
fn draw_svg_glyph(
frame: &mut Frame,
font: &Font,
upem: Abs,
glyph_id: GlyphId,
) -> Option<()> {
// TODO: Our current conversion of the SVG table works for Twitter Color Emoji,
// but might not work for others. See also: https://github.com/RazrFalcon/resvg/pull/776
let mut data = font.ttf().glyph_svg_image(glyph_id)?.data;
// Decompress SVGZ.
let mut decoded = vec![];
if data.starts_with(&[0x1f, 0x8b]) {
let mut decoder = flate2::read::GzDecoder::new(data);
decoder.read_to_end(&mut decoded).ok()?;
data = &decoded;
}
// Parse XML.
let xml = std::str::from_utf8(data).ok()?;
let document = roxmltree::Document::parse(xml).ok()?;
// Parse SVG.
let opts = usvg::Options::default();
let tree = usvg::Tree::from_xmltree(&document, &opts).ok()?;
let bbox = tree.root().bounding_box();
let width = bbox.width() as f64;
let height = bbox.height() as f64;
let left = bbox.left() as f64;
let top = bbox.top() as f64;
let mut data = tree.to_string(&usvg::WriteOptions::default());
// The SVG coordinates and the font coordinates are not the same: the Y axis
// is mirrored. But the origin of the axes are the same (which means that
// the horizontal axis in the SVG document corresponds to the baseline). See
// the reference for more details:
// https://learn.microsoft.com/en-us/typography/opentype/spec/svg#coordinate-systems-and-glyph-metrics
//
// If we used the SVG document as it is, svg2pdf would produce a cropped
// glyph (only what is under the baseline would be visible). So we need to
// embed the original SVG in another one that has the exact dimensions of
// the glyph, with a transform to make it fit. We also need to remove the
// viewBox, height and width attributes from the inner SVG, otherwise usvg
// takes into account these values to clip the embedded SVG.
make_svg_unsized(&mut data);
let wrapper_svg = format!(
r#"
<svg
width="{width}"
height="{height}"
viewBox="0 0 {width} {height}"
xmlns="http://www.w3.org/2000/svg">
<g transform="matrix(1 0 0 1 {tx} {ty})">
{inner}
</g>
</svg>
"#,
inner = data,
tx = -left,
ty = -top,
);
let data = Bytes::from_string(wrapper_svg);
let image = Image::plain(SvgImage::new(data).ok()?);
let position = Point::new(Abs::pt(left), Abs::pt(top) + upem);
let size = Size::new(Abs::pt(width), Abs::pt(height));
frame.push(position, FrameItem::Image(image, size, Span::detached()));
Some(())
}
/// Remove all size specifications (viewBox, width and height attributes) from a
/// SVG document.
fn make_svg_unsized(svg: &mut String) {
let mut viewbox_range = None;
let mut width_range = None;
let mut height_range = None;
let mut s = unscanny::Scanner::new(svg);
s.eat_until("<svg");
s.eat_if("<svg");
while !s.eat_if('>') && !s.done() {
s.eat_whitespace();
let start = s.cursor();
let attr_name = s.eat_until('=').trim();
// Eat the equal sign and the quote.
s.eat();
s.eat();
let mut escaped = false;
while (escaped || !s.eat_if('"')) && !s.done() {
escaped = s.eat() == Some('\\');
}
match attr_name {
"viewBox" => viewbox_range = Some(start..s.cursor()),
"width" => width_range = Some(start..s.cursor()),
"height" => height_range = Some(start..s.cursor()),
_ => {}
}
}
// Remove the `viewBox` attribute.
if let Some(range) = viewbox_range {
svg.replace_range(range.clone(), &" ".repeat(range.len()));
}
// Remove the `width` attribute.
if let Some(range) = width_range {
svg.replace_range(range.clone(), &" ".repeat(range.len()));
}
// Remove the `height` attribute.
if let Some(range) = height_range {
svg.replace_range(range, "");
}
}
struct ColrBuilder<'a>(&'a mut String);
impl ColrBuilder<'_> {
fn finish(&mut self) {
if !self.0.is_empty() {
self.0.pop(); // remove trailing space
}
}
}
impl ttf_parser::OutlineBuilder for ColrBuilder<'_> {
fn move_to(&mut self, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "M {x} {y} ").unwrap()
}
fn line_to(&mut self, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "L {x} {y} ").unwrap()
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "Q {x1} {y1} {x} {y} ").unwrap()
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "C {x1} {y1} {x2} {y2} {x} {y} ").unwrap()
}
fn close(&mut self) {
self.0.push_str("Z ")
}
}
// NOTE: This is only a best-effort translation of COLR into SVG. It's not feature-complete
// and it's also not possible to make it feature-complete using just raw SVG features.
pub(crate) struct GlyphPainter<'a> {
pub(crate) face: &'a ttf_parser::Face<'a>,
pub(crate) svg: &'a mut xmlwriter::XmlWriter,
pub(crate) path_buf: &'a mut String,
pub(crate) gradient_index: usize,
pub(crate) clip_path_index: usize,
pub(crate) palette_index: u16,
pub(crate) transform: ttf_parser::Transform,
pub(crate) outline_transform: ttf_parser::Transform,
pub(crate) transforms_stack: Vec<ttf_parser::Transform>,
}
impl<'a> GlyphPainter<'a> {
fn write_gradient_stops(&mut self, stops: ttf_parser::colr::GradientStopsIter) {
for stop in stops {
self.svg.start_element("stop");
self.svg.write_attribute("offset", &stop.stop_offset);
self.write_color_attribute("stop-color", stop.color);
let opacity = f32::from(stop.color.alpha) / 255.0;
self.svg.write_attribute("stop-opacity", &opacity);
self.svg.end_element();
}
}
fn write_color_attribute(&mut self, name: &str, color: ttf_parser::RgbaColor) {
self.svg.write_attribute_fmt(
name,
format_args!("rgb({}, {}, {})", color.red, color.green, color.blue),
);
}
fn write_transform_attribute(&mut self, name: &str, ts: ttf_parser::Transform) {
if ts.is_default() {
return;
}
self.svg.write_attribute_fmt(
name,
format_args!("matrix({} {} {} {} {} {})", ts.a, ts.b, ts.c, ts.d, ts.e, ts.f),
);
}
fn write_spread_method_attribute(
&mut self,
extend: ttf_parser::colr::GradientExtend,
) {
self.svg.write_attribute(
"spreadMethod",
match extend {
ttf_parser::colr::GradientExtend::Pad => &"pad",
ttf_parser::colr::GradientExtend::Repeat => &"repeat",
ttf_parser::colr::GradientExtend::Reflect => &"reflect",
},
);
}
fn paint_solid(&mut self, color: ttf_parser::RgbaColor) {
self.svg.start_element("path");
self.write_color_attribute("fill", color);
let opacity = f32::from(color.alpha) / 255.0;
self.svg.write_attribute("fill-opacity", &opacity);
self.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_linear_gradient(&mut self, gradient: ttf_parser::colr::LinearGradient<'a>) {
let gradient_id = format!("lg{}", self.gradient_index);
self.gradient_index += 1;
let gradient_transform = paint_transform(self.outline_transform, self.transform);
// TODO: We ignore x2, y2. Have to apply them somehow.
// TODO: The way spreadMode works in ttf and svg is a bit different. In SVG, the spreadMode
// will always be applied based on x1/y1 and x2/y2. However, in TTF the spreadMode will
// be applied from the first/last stop. So if we have a gradient with x1=0 x2=1, and
// a stop at x=0.4 and x=0.6, then in SVG we will always see a padding, while in ttf
// we will see the actual spreadMode. We need to account for that somehow.
self.svg.start_element("linearGradient");
self.svg.write_attribute("id", &gradient_id);
self.svg.write_attribute("x1", &gradient.x0);
self.svg.write_attribute("y1", &gradient.y0);
self.svg.write_attribute("x2", &gradient.x1);
self.svg.write_attribute("y2", &gradient.y1);
self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
self.write_spread_method_attribute(gradient.extend);
self.write_transform_attribute("gradientTransform", gradient_transform);
self.write_gradient_stops(
gradient.stops(self.palette_index, self.face.variation_coordinates()),
);
self.svg.end_element();
self.svg.start_element("path");
self.svg
.write_attribute_fmt("fill", format_args!("url(#{gradient_id})"));
self.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_radial_gradient(&mut self, gradient: ttf_parser::colr::RadialGradient<'a>) {
let gradient_id = format!("rg{}", self.gradient_index);
self.gradient_index += 1;
let gradient_transform = paint_transform(self.outline_transform, self.transform);
self.svg.start_element("radialGradient");
self.svg.write_attribute("id", &gradient_id);
self.svg.write_attribute("cx", &gradient.x1);
self.svg.write_attribute("cy", &gradient.y1);
self.svg.write_attribute("r", &gradient.r1);
self.svg.write_attribute("fr", &gradient.r0);
self.svg.write_attribute("fx", &gradient.x0);
self.svg.write_attribute("fy", &gradient.y0);
self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
self.write_spread_method_attribute(gradient.extend);
self.write_transform_attribute("gradientTransform", gradient_transform);
self.write_gradient_stops(
gradient.stops(self.palette_index, self.face.variation_coordinates()),
);
self.svg.end_element();
self.svg.start_element("path");
self.svg
.write_attribute_fmt("fill", format_args!("url(#{gradient_id})"));
self.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_sweep_gradient(&mut self, _: ttf_parser::colr::SweepGradient<'a>) {}
}
fn paint_transform(
outline_transform: ttf_parser::Transform,
transform: ttf_parser::Transform,
) -> ttf_parser::Transform {
let outline_transform = tiny_skia_path::Transform::from_row(
outline_transform.a,
outline_transform.b,
outline_transform.c,
outline_transform.d,
outline_transform.e,
outline_transform.f,
);
let gradient_transform = tiny_skia_path::Transform::from_row(
transform.a,
transform.b,
transform.c,
transform.d,
transform.e,
transform.f,
);
let gradient_transform = outline_transform
.invert()
// In theory, we should error out. But the transform shouldn't ever be uninvertible, so let's ignore it.
.unwrap_or_default()
.pre_concat(gradient_transform);
ttf_parser::Transform {
a: gradient_transform.sx,
b: gradient_transform.ky,
c: gradient_transform.kx,
d: gradient_transform.sy,
e: gradient_transform.tx,
f: gradient_transform.ty,
}
}
impl GlyphPainter<'_> {
fn clip_with_path(&mut self, path: &str) {
let clip_id = format!("cp{}", self.clip_path_index);
self.clip_path_index += 1;
self.svg.start_element("clipPath");
self.svg.write_attribute("id", &clip_id);
self.svg.start_element("path");
self.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", &path);
self.svg.end_element();
self.svg.end_element();
self.svg.start_element("g");
self.svg
.write_attribute_fmt("clip-path", format_args!("url(#{clip_id})"));
}
}
impl<'a> ttf_parser::colr::Painter<'a> for GlyphPainter<'a> {
fn outline_glyph(&mut self, glyph_id: ttf_parser::GlyphId) {
self.path_buf.clear();
let mut builder = ColrBuilder(self.path_buf);
match self.face.outline_glyph(glyph_id, &mut builder) {
Some(v) => v,
None => return,
};
builder.finish();
// We have to write outline using the current transform.
self.outline_transform = self.transform;
}
fn push_layer(&mut self, mode: ttf_parser::colr::CompositeMode) {
self.svg.start_element("g");
use ttf_parser::colr::CompositeMode;
// TODO: Need to figure out how to represent the other blend modes
// in SVG.
let mode = match mode {
CompositeMode::SourceOver => "normal",
CompositeMode::Screen => "screen",
CompositeMode::Overlay => "overlay",
CompositeMode::Darken => "darken",
CompositeMode::Lighten => "lighten",
CompositeMode::ColorDodge => "color-dodge",
CompositeMode::ColorBurn => "color-burn",
CompositeMode::HardLight => "hard-light",
CompositeMode::SoftLight => "soft-light",
CompositeMode::Difference => "difference",
CompositeMode::Exclusion => "exclusion",
CompositeMode::Multiply => "multiply",
CompositeMode::Hue => "hue",
CompositeMode::Saturation => "saturation",
CompositeMode::Color => "color",
CompositeMode::Luminosity => "luminosity",
_ => "normal",
};
self.svg.write_attribute_fmt(
"style",
format_args!("mix-blend-mode: {mode}; isolation: isolate"),
);
}
fn pop_layer(&mut self) {
self.svg.end_element(); // g
}
fn push_transform(&mut self, transform: ttf_parser::Transform) {
self.transforms_stack.push(self.transform);
self.transform = ttf_parser::Transform::combine(self.transform, transform);
}
fn paint(&mut self, paint: ttf_parser::colr::Paint<'a>) {
match paint {
ttf_parser::colr::Paint::Solid(color) => self.paint_solid(color),
ttf_parser::colr::Paint::LinearGradient(lg) => self.paint_linear_gradient(lg),
ttf_parser::colr::Paint::RadialGradient(rg) => self.paint_radial_gradient(rg),
ttf_parser::colr::Paint::SweepGradient(sg) => self.paint_sweep_gradient(sg),
}
}
fn pop_transform(&mut self) {
if let Some(ts) = self.transforms_stack.pop() {
self.transform = ts
}
}
fn push_clip(&mut self) {
self.clip_with_path(&self.path_buf.clone());
}
fn pop_clip(&mut self) {
self.svg.end_element();
}
fn push_clip_box(&mut self, clipbox: ttf_parser::colr::ClipBox) {
let x_min = clipbox.x_min;
let x_max = clipbox.x_max;
let y_min = clipbox.y_min;
let y_max = clipbox.y_max;
let clip_path = format!(
"M {x_min} {y_min} L {x_max} {y_min} L {x_max} {y_max} L {x_min} {y_max} Z"
);
self.clip_with_path(&clip_path);
}
}
| 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/text/font/book.rs | crates/typst-library/src/text/font/book.rs | use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use serde::{Deserialize, Serialize};
use ttf_parser::{PlatformId, Tag, name_id};
use unicode_segmentation::UnicodeSegmentation;
use super::exceptions::find_exception;
use crate::text::{
Font, FontStretch, FontStyle, FontVariant, FontWeight, is_default_ignorable,
};
/// Metadata about a collection of fonts.
#[derive(Debug, Default, Clone, Hash)]
pub struct FontBook {
/// Maps from lowercased family names to font indices.
families: BTreeMap<String, Vec<usize>>,
/// Metadata about each font in the collection.
infos: Vec<FontInfo>,
}
impl FontBook {
/// Create a new, empty font book.
pub fn new() -> Self {
Self { families: BTreeMap::new(), infos: vec![] }
}
/// Create a font book from a collection of font infos.
pub fn from_infos(infos: impl IntoIterator<Item = FontInfo>) -> Self {
let mut book = Self::new();
for info in infos {
book.push(info);
}
book
}
/// Create a font book for a collection of fonts.
pub fn from_fonts<'a>(fonts: impl IntoIterator<Item = &'a Font>) -> Self {
Self::from_infos(fonts.into_iter().map(|font| font.info().clone()))
}
/// Insert metadata into the font book.
pub fn push(&mut self, info: FontInfo) {
let index = self.infos.len();
let family = info.family.to_lowercase();
self.families.entry(family).or_default().push(index);
self.infos.push(info);
}
/// Get the font info for the given index.
pub fn info(&self, index: usize) -> Option<&FontInfo> {
self.infos.get(index)
}
/// Returns true if the book contains a font family with the given name.
pub fn contains_family(&self, family: &str) -> bool {
self.families.contains_key(family)
}
/// An ordered iterator over all font families this book knows and details
/// about the fonts that are part of them.
pub fn families(
&self,
) -> impl Iterator<Item = (&str, impl Iterator<Item = &FontInfo>)> + '_ {
// Since the keys are lowercased, we instead use the family field of the
// first face's info.
self.families.values().map(|ids| {
let family = self.infos[ids[0]].family.as_str();
let infos = ids.iter().map(|&id| &self.infos[id]);
(family, infos)
})
}
/// Try to find a font from the given `family` that matches the given
/// `variant` as closely as possible.
///
/// The `family` should be all lowercase.
pub fn select(&self, family: &str, variant: FontVariant) -> Option<usize> {
let ids = self.families.get(family)?;
self.find_best_variant(None, variant, ids.iter().copied())
}
/// Iterate over all variants of a family.
pub fn select_family(&self, family: &str) -> impl Iterator<Item = usize> + '_ {
self.families
.get(family)
.map(|vec| vec.as_slice())
.unwrap_or_default()
.iter()
.copied()
}
/// Try to find and load a fallback font that
/// - is as close as possible to the font `like` (if any)
/// - is as close as possible to the given `variant`
/// - is suitable for shaping the given `text`
pub fn select_fallback(
&self,
like: Option<&FontInfo>,
variant: FontVariant,
text: &str,
) -> Option<usize> {
// Find the fonts that contain the text's first non-space and
// non-ignorable char ...
let c = text
.chars()
.find(|&c| !c.is_whitespace() && !is_default_ignorable(c))?;
let ids = self
.infos
.iter()
.enumerate()
.filter(|(_, info)| info.coverage.contains(c as u32))
.map(|(index, _)| index);
// ... and find the best variant among them.
self.find_best_variant(like, variant, ids)
}
/// Find the font in the passed iterator that
/// - is closest to the font `like` (if any)
/// - is closest to the given `variant`
///
/// To do that we compute a key for all variants and select the one with the
/// minimal key. This key prioritizes:
/// - If `like` is some other font:
/// - Are both fonts (not) monospaced?
/// - Do both fonts (not) have serifs?
/// - How many words do the families share in their prefix? E.g. "Noto
/// Sans" and "Noto Sans Arabic" share two words, whereas "IBM Plex
/// Arabic" shares none with "Noto Sans", so prefer "Noto Sans Arabic"
/// if `like` is "Noto Sans". In case there are two equally good
/// matches, we prefer the shorter one because it is less special (e.g.
/// if `like` is "Noto Sans Arabic", we prefer "Noto Sans" over "Noto
/// Sans CJK HK".)
/// - The style (normal / italic / oblique). If we want italic or oblique
/// but it doesn't exist, the other one of the two is still better than
/// normal.
/// - The absolute distance to the target stretch.
/// - The absolute distance to the target weight.
fn find_best_variant(
&self,
like: Option<&FontInfo>,
variant: FontVariant,
ids: impl IntoIterator<Item = usize>,
) -> Option<usize> {
let mut best = None;
let mut best_key = None;
for id in ids {
let current = &self.infos[id];
let key = (
like.map(|like| {
(
current.flags.contains(FontFlags::MONOSPACE)
!= like.flags.contains(FontFlags::MONOSPACE),
current.flags.contains(FontFlags::SERIF)
!= like.flags.contains(FontFlags::SERIF),
Reverse(shared_prefix_words(¤t.family, &like.family)),
current.family.len(),
)
}),
current.variant.style.distance(variant.style),
current.variant.stretch.distance(variant.stretch),
current.variant.weight.distance(variant.weight),
);
if best_key.is_none_or(|b| key < b) {
best = Some(id);
best_key = Some(key);
}
}
best
}
}
/// Properties of a single font.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct FontInfo {
/// The typographic font family this font is part of.
pub family: String,
/// Properties that distinguish this font from other fonts in the same
/// family.
pub variant: FontVariant,
/// Properties of the font.
pub flags: FontFlags,
/// The unicode coverage of the font.
pub coverage: Coverage,
}
bitflags::bitflags! {
/// Bitflags describing characteristics of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontFlags: u32 {
/// All glyphs have the same width.
const MONOSPACE = 1 << 0;
/// Glyphs have short strokes at their stems.
const SERIF = 1 << 1;
/// Font face has a MATH table
const MATH = 1 << 2;
/// Font face has an fvar table
const VARIABLE = 1 << 3;
}
}
impl FontInfo {
/// Compute metadata for font at the `index` of the given data.
pub fn new(data: &[u8], index: u32) -> Option<Self> {
let ttf = ttf_parser::Face::parse(data, index).ok()?;
Self::from_ttf(&ttf)
}
/// Compute metadata for all fonts in the given data.
pub fn iter(data: &[u8]) -> impl Iterator<Item = FontInfo> + '_ {
let count = ttf_parser::fonts_in_collection(data).unwrap_or(1);
(0..count).filter_map(move |index| Self::new(data, index))
}
/// Compute metadata for a single ttf-parser face.
pub(super) fn from_ttf(ttf: &ttf_parser::Face) -> Option<Self> {
let ps_name = find_name(ttf, name_id::POST_SCRIPT_NAME);
let exception = ps_name.as_deref().and_then(find_exception);
// We cannot use Name ID 16 "Typographic Family", because for some
// fonts it groups together more than just Style / Weight / Stretch
// variants (e.g. Display variants of Noto fonts) and then some
// variants become inaccessible from Typst. And even though the
// fsSelection bit WWS should help us decide whether that is the
// case, it's wrong for some fonts (e.g. for certain variants of "Noto
// Sans Display").
//
// So, instead we use Name ID 1 "Family" and trim many common
// suffixes for which know that they just describe styling (e.g.
// "ExtraBold").
let family =
exception.and_then(|c| c.family.map(str::to_string)).or_else(|| {
let family = find_name(ttf, name_id::FAMILY)?;
Some(typographic_family(&family).to_string())
})?;
let variant = {
let style = exception.and_then(|c| c.style).unwrap_or_else(|| {
let mut full = find_name(ttf, name_id::FULL_NAME).unwrap_or_default();
full.make_ascii_lowercase();
// Some fonts miss the relevant bits for italic or oblique, so
// we also try to infer that from the full name.
//
// We do not use `ttf.is_italic()` because that also checks the
// italic angle which leads to false positives for some oblique
// fonts.
//
// See <https://github.com/typst/typst/issues/7479>.
let italic =
ttf.style() == ttf_parser::Style::Italic || full.contains("italic");
let oblique = ttf.is_oblique()
|| full.contains("oblique")
|| full.contains("slanted");
match (italic, oblique) {
(false, false) => FontStyle::Normal,
(true, _) => FontStyle::Italic,
(_, true) => FontStyle::Oblique,
}
});
let weight = exception.and_then(|c| c.weight).unwrap_or_else(|| {
let number = ttf.weight().to_number();
FontWeight::from_number(number)
});
let stretch = exception
.and_then(|c| c.stretch)
.unwrap_or_else(|| FontStretch::from_number(ttf.width().to_number()));
FontVariant { style, weight, stretch }
};
// Determine the unicode coverage.
let mut codepoints = vec![];
for subtable in ttf.tables().cmap.into_iter().flat_map(|table| table.subtables) {
if subtable.is_unicode() {
subtable.codepoints(|c| codepoints.push(c));
}
}
let mut flags = FontFlags::empty();
flags.set(FontFlags::MONOSPACE, ttf.is_monospaced());
flags.set(FontFlags::MATH, ttf.tables().math.is_some());
flags.set(FontFlags::VARIABLE, ttf.is_variable());
// Determine whether this is a serif or sans-serif font.
if let Some(panose) = ttf
.raw_face()
.table(Tag::from_bytes(b"OS/2"))
.and_then(|os2| os2.get(32..45))
&& matches!(panose, [2, 2..=10, ..])
{
flags.insert(FontFlags::SERIF);
}
Some(FontInfo {
family,
variant,
flags,
coverage: Coverage::from_vec(codepoints),
})
}
/// Whether this is the macOS LastResort font. It can yield tofus with
/// glyph ID != 0.
pub fn is_last_resort(&self) -> bool {
self.family == "LastResort"
}
}
/// Try to find and decode the name with the given id.
pub(super) fn find_name(ttf: &ttf_parser::Face, name_id: u16) -> Option<String> {
ttf.names().into_iter().find_map(|entry| {
if entry.name_id == name_id {
if let Some(string) = entry.to_string() {
return Some(string);
}
if entry.platform_id == PlatformId::Macintosh && entry.encoding_id == 0 {
return Some(decode_mac_roman(entry.name));
}
}
None
})
}
/// Decode mac roman encoded bytes into a string.
fn decode_mac_roman(coded: &[u8]) -> String {
#[rustfmt::skip]
const TABLE: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è',
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü',
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø',
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø',
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{a0}', 'À', 'Ã', 'Õ', 'Œ', 'œ',
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl',
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô',
'\u{f8ff}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
fn char_from_mac_roman(code: u8) -> char {
if code < 128 { code as char } else { TABLE[(code - 128) as usize] }
}
coded.iter().copied().map(char_from_mac_roman).collect()
}
/// Trim style naming from a family name and fix bad names.
fn typographic_family(mut family: &str) -> &str {
// Separators between names, modifiers and styles.
const SEPARATORS: [char; 3] = [' ', '-', '_'];
// Modifiers that can appear in combination with suffixes.
const MODIFIERS: &[&str] =
&["extra", "ext", "ex", "x", "semi", "sem", "sm", "demi", "dem", "ultra"];
// Style suffixes.
#[rustfmt::skip]
const SUFFIXES: &[&str] = &[
"normal", "italic", "oblique", "slanted",
"thin", "th", "hairline", "light", "lt", "regular", "medium", "med",
"md", "bold", "bd", "demi", "extb", "black", "blk", "bk", "heavy",
"narrow", "condensed", "cond", "cn", "cd", "compressed", "expanded", "exp"
];
// Trim spacing and weird leading dots in Apple fonts.
family = family.trim().trim_start_matches('.');
// Lowercase the string so that the suffixes match case-insensitively.
let lower = family.to_ascii_lowercase();
let mut len = usize::MAX;
let mut trimmed = lower.as_str();
// Trim style suffixes repeatedly.
while trimmed.len() < len {
len = trimmed.len();
// Find style suffix.
let mut t = trimmed;
let mut shortened = false;
while let Some(s) = SUFFIXES.iter().find_map(|s| t.strip_suffix(s)) {
shortened = true;
t = s;
}
if !shortened {
break;
}
// Strip optional separator.
if let Some(s) = t.strip_suffix(SEPARATORS) {
trimmed = s;
t = s;
}
// Also allow an extra modifier, but apply it only if it is separated it
// from the text before it (to prevent false positives).
if let Some(t) = MODIFIERS.iter().find_map(|s| t.strip_suffix(s))
&& let Some(stripped) = t.strip_suffix(SEPARATORS)
{
trimmed = stripped;
}
}
// Apply style suffix trimming.
family = &family[..len];
family
}
/// How many words the two strings share in their prefix.
fn shared_prefix_words(left: &str, right: &str) -> usize {
left.unicode_words()
.zip(right.unicode_words())
.take_while(|(l, r)| l == r)
.count()
}
/// A compactly encoded set of codepoints.
///
/// The set is represented by alternating specifications of how many codepoints
/// are not in the set and how many are in the set.
///
/// For example, for the set `{2, 3, 4, 9, 10, 11, 15, 18, 19}`, there are:
/// - 2 codepoints not inside (0, 1)
/// - 3 codepoints inside (2, 3, 4)
/// - 4 codepoints not inside (5, 6, 7, 8)
/// - 3 codepoints inside (9, 10, 11)
/// - 3 codepoints not inside (12, 13, 14)
/// - 1 codepoint inside (15)
/// - 2 codepoints not inside (16, 17)
/// - 2 codepoints inside (18, 19)
///
/// So the resulting encoding is `[2, 3, 4, 3, 3, 1, 2, 2]`.
#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Coverage(Vec<u32>);
impl Coverage {
/// Encode a vector of codepoints.
pub fn from_vec(mut codepoints: Vec<u32>) -> Self {
codepoints.sort();
codepoints.dedup();
let mut runs = Vec::new();
let mut next = 0;
for c in codepoints {
if let Some(run) = runs.last_mut().filter(|_| c == next) {
*run += 1;
} else {
runs.push(c - next);
runs.push(1);
}
next = c + 1;
}
Self(runs)
}
/// Whether the codepoint is covered.
pub fn contains(&self, c: u32) -> bool {
let mut inside = false;
let mut cursor = 0;
for &run in &self.0 {
if (cursor..cursor + run).contains(&c) {
return inside;
}
cursor += run;
inside = !inside;
}
false
}
/// Iterate over all covered codepoints.
pub fn iter(&self) -> impl Iterator<Item = u32> + '_ {
let mut inside = false;
let mut cursor = 0;
self.0.iter().flat_map(move |run| {
let range = if inside { cursor..cursor + run } else { 0..0 };
inside = !inside;
cursor += run;
range
})
}
}
impl Debug for Coverage {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("Coverage(..)")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trim_styles() {
assert_eq!(typographic_family("Atma Light"), "Atma");
assert_eq!(typographic_family("eras bold"), "eras");
assert_eq!(typographic_family("footlight mt light"), "footlight mt");
assert_eq!(typographic_family("times new roman"), "times new roman");
assert_eq!(typographic_family("noto sans mono cond sembd"), "noto sans mono");
assert_eq!(typographic_family("noto serif SEMCOND sembd"), "noto serif");
assert_eq!(typographic_family("crimson text"), "crimson text");
assert_eq!(typographic_family("footlight light"), "footlight");
assert_eq!(typographic_family("Noto Sans"), "Noto Sans");
assert_eq!(typographic_family("Noto Sans Light"), "Noto Sans");
assert_eq!(typographic_family("Noto Sans Semicondensed Heavy"), "Noto Sans");
assert_eq!(typographic_family("Familx"), "Familx");
assert_eq!(typographic_family("Font Ultra"), "Font Ultra");
assert_eq!(typographic_family("Font Ultra Bold"), "Font");
}
#[test]
fn test_coverage() {
#[track_caller]
fn test(set: &[u32], runs: &[u32]) {
let coverage = Coverage::from_vec(set.to_vec());
assert_eq!(coverage.0, runs);
let max = 5 + set.iter().copied().max().unwrap_or_default();
for c in 0..max {
assert_eq!(set.contains(&c), coverage.contains(c));
}
}
test(&[], &[]);
test(&[0], &[0, 1]);
test(&[1], &[1, 1]);
test(&[0, 1], &[0, 2]);
test(&[0, 1, 3], &[0, 2, 1, 1]);
test(
// {2, 3, 4, 9, 10, 11, 15, 18, 19}
&[18, 19, 2, 4, 9, 11, 15, 3, 3, 10],
&[2, 3, 4, 3, 3, 1, 2, 2],
)
}
#[test]
fn test_coverage_iter() {
let codepoints = vec![2, 3, 7, 8, 9, 14, 15, 19, 21];
let coverage = Coverage::from_vec(codepoints.clone());
assert_eq!(coverage.iter().collect::<Vec<_>>(), codepoints);
}
}
| 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/text/font/exceptions.rs | crates/typst-library/src/text/font/exceptions.rs | use serde::Deserialize;
use super::{FontStretch, FontStyle, FontWeight};
pub fn find_exception(postscript_name: &str) -> Option<&'static Exception> {
EXCEPTION_MAP.get(postscript_name)
}
#[derive(Debug, Default, Deserialize)]
pub struct Exception {
pub family: Option<&'static str>,
pub style: Option<FontStyle>,
pub weight: Option<FontWeight>,
pub stretch: Option<FontStretch>,
}
impl Exception {
const fn new() -> Self {
Self {
family: None,
style: None,
weight: None,
stretch: None,
}
}
const fn family(self, family: &'static str) -> Self {
Self { family: Some(family), ..self }
}
const fn style(self, style: FontStyle) -> Self {
Self { style: Some(style), ..self }
}
const fn weight(self, weight: u16) -> Self {
Self { weight: Some(FontWeight(weight)), ..self }
}
#[allow(unused)] // left for future use
const fn stretch(self, stretch: u16) -> Self {
Self { stretch: Some(FontStretch(stretch)), ..self }
}
}
/// A map which keys are PostScript name and values are override entries.
static EXCEPTION_MAP: phf::Map<&'static str, Exception> = phf::phf_map! {
// The old version of Arial-Black, published by Microsoft in 1996 in their
// "core fonts for the web" project, has a wrong weight of 400.
// See https://corefonts.sourceforge.net/.
"Arial-Black" => Exception::new()
.weight(900),
// Archivo Narrow is different from Archivo and Archivo Black. Since Archivo Black
// seems identical to Archivo weight 900, only differentiate between Archivo and
// Archivo Narrow.
"ArchivoNarrow-Regular" => Exception::new()
.family("Archivo Narrow"),
"ArchivoNarrow-Italic" => Exception::new()
.family("Archivo Narrow"),
"ArchivoNarrow-Bold" => Exception::new()
.family("Archivo Narrow"),
"ArchivoNarrow-BoldItalic" => Exception::new()
.family("Archivo Narrow"),
// Fandol fonts designed for Chinese typesetting.
// See https://ctan.org/tex-archive/fonts/fandol/.
"FandolHei-Bold" => Exception::new()
.weight(700),
"FandolSong-Bold" => Exception::new()
.weight(700),
// Noto fonts
"NotoNaskhArabicUISemi-Bold" => Exception::new()
.family("Noto Naskh Arabic UI")
.weight(600),
"NotoSansSoraSompengSemi-Bold" => Exception::new()
.family("Noto Sans Sora Sompeng")
.weight(600),
"NotoSans-DisplayBlackItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedBlackItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedBold" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedExtraBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedExtraLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedMediumItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedSemiBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayCondensedThinItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedBlackItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedBold" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedExtraBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedExtraLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedMediumItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedSemiBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraCondensedThinItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayExtraLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayMediumItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedBlackItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedBold" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedExtraBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedExtraLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedLightItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedMediumItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedSemiBoldItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplaySemiCondensedThinItalic" => Exception::new()
.family("Noto Sans Display"),
"NotoSans-DisplayThinItalic" => Exception::new()
.family("Noto Sans Display"),
// The following three postscript names are only used in the version 2.007
// of the Noto Sans font. Other versions, while have different postscript
// name, happen to have correct metadata.
"NotoSerif-DisplayCondensedBold" => Exception::new()
.family("Noto Serif Display"),
"NotoSerif-DisplayExtraCondensedBold" => Exception::new()
.family("Noto Serif Display"),
"NotoSerif-DisplaySemiCondensedBold" => Exception::new()
.family("Noto Serif Display"),
// New Computer Modern
"NewCM08-Book" => Exception::new()
.family("New Computer Modern 08")
.weight(450),
"NewCM08-BookItalic" => Exception::new()
.family("New Computer Modern 08")
.weight(450),
"NewCM08-Italic" => Exception::new()
.family("New Computer Modern 08"),
"NewCM08-Regular" => Exception::new()
.family("New Computer Modern 08"),
"NewCM10-Bold" => Exception::new()
.family("New Computer Modern"),
"NewCM10-BoldItalic" => Exception::new()
.family("New Computer Modern"),
"NewCM10-Book" => Exception::new()
.family("New Computer Modern")
.weight(450),
"NewCM10-BookItalic" => Exception::new()
.family("New Computer Modern")
.weight(450),
"NewCM10-Italic" => Exception::new()
.family("New Computer Modern"),
"NewCM10-Regular" => Exception::new()
.family("New Computer Modern"),
"NewCMMath-Bold" => Exception::new()
.family("New Computer Modern Math"),
"NewCMMath-Book" => Exception::new()
.family("New Computer Modern Math")
.weight(450),
"NewCMMath-Regular" => Exception::new()
.family("New Computer Modern Math"),
"NewCMMono10-Bold" => Exception::new()
.family("New Computer Modern Mono"),
"NewCMMono10-BoldOblique" => Exception::new()
.family("New Computer Modern Mono"),
"NewCMMono10-Book" => Exception::new()
.family("New Computer Modern Mono")
.weight(450),
"NewCMMono10-BookItalic" => Exception::new()
.family("New Computer Modern Mono")
.weight(450),
"NewCMMono10-Italic" => Exception::new()
.family("New Computer Modern Mono"),
"NewCMMono10-Regular" => Exception::new()
.family("New Computer Modern Mono"),
"NewCMSans08-Book" => Exception::new()
.family("New Computer Modern Sans 08")
.weight(450),
"NewCMSans08-BookOblique" => Exception::new()
.family("New Computer Modern Sans 08")
.weight(450),
"NewCMSans08-Oblique" => Exception::new()
.family("New Computer Modern Sans 08"),
"NewCMSans08-Regular" => Exception::new()
.family("New Computer Modern Sans 08"),
"NewCMSans10-Bold" => Exception::new()
.family("New Computer Modern Sans"),
"NewCMSans10-BoldOblique" => Exception::new()
.family("New Computer Modern Sans"),
"NewCMSans10-Book" => Exception::new()
.family("New Computer Modern Sans")
.weight(450),
"NewCMSans10-BookOblique" => Exception::new()
.family("New Computer Modern Sans")
.weight(450)
.style(FontStyle::Oblique),
"NewCMSans10-Oblique" => Exception::new()
.family("New Computer Modern Sans")
.style(FontStyle::Oblique),
"NewCMSans10-Regular" => Exception::new()
.family("New Computer Modern Sans"),
"NewCMSansMath-Regular" => Exception::new()
.family("New Computer Modern Sans Math"),
"NewCMUncial08-Bold" => Exception::new()
.family("New Computer Modern Uncial 08"),
"NewCMUncial08-Book" => Exception::new()
.family("New Computer Modern Uncial 08")
.weight(450),
"NewCMUncial08-Regular" => Exception::new()
.family("New Computer Modern Uncial 08"),
"NewCMUncial10-Bold" => Exception::new()
.family("New Computer Modern Uncial"),
"NewCMUncial10-Book" => Exception::new()
.family("New Computer Modern Uncial")
.weight(450),
"NewCMUncial10-Regular" => Exception::new()
.family("New Computer Modern Uncial"),
// Latin Modern
"LMMono8-Regular" => Exception::new()
.family("Latin Modern Mono 8"),
"LMMono9-Regular" => Exception::new()
.family("Latin Modern Mono 9"),
"LMMono12-Regular" => Exception::new()
.family("Latin Modern Mono 12"),
"LMMonoLt10-BoldOblique" => Exception::new()
.style(FontStyle::Oblique),
"LMMonoLt10-Regular" => Exception::new()
.weight(300),
"LMMonoLt10-Oblique" => Exception::new()
.weight(300)
.style(FontStyle::Oblique),
"LMMonoLtCond10-Regular" => Exception::new()
.weight(300)
.stretch(666),
"LMMonoLtCond10-Oblique" => Exception::new()
.weight(300)
.style(FontStyle::Oblique)
.stretch(666),
"LMMonoPropLt10-Regular" => Exception::new()
.weight(300),
"LMMonoPropLt10-Oblique" => Exception::new()
.weight(300),
"LMRoman5-Regular" => Exception::new()
.family("Latin Modern Roman 5"),
"LMRoman6-Regular" => Exception::new()
.family("Latin Modern Roman 6"),
"LMRoman7-Regular" => Exception::new()
.family("Latin Modern Roman 7"),
"LMRoman8-Regular" => Exception::new()
.family("Latin Modern Roman 8"),
"LMRoman9-Regular" => Exception::new()
.family("Latin Modern Roman 9"),
"LMRoman12-Regular" => Exception::new()
.family("Latin Modern Roman 12"),
"LMRoman17-Regular" => Exception::new()
.family("Latin Modern Roman 17"),
"LMRoman7-Italic" => Exception::new()
.family("Latin Modern Roman 7"),
"LMRoman8-Italic" => Exception::new()
.family("Latin Modern Roman 8"),
"LMRoman9-Italic" => Exception::new()
.family("Latin Modern Roman 9"),
"LMRoman12-Italic" => Exception::new()
.family("Latin Modern Roman 12"),
"LMRoman5-Bold" => Exception::new()
.family("Latin Modern Roman 5"),
"LMRoman6-Bold" => Exception::new()
.family("Latin Modern Roman 6"),
"LMRoman7-Bold" => Exception::new()
.family("Latin Modern Roman 7"),
"LMRoman8-Bold" => Exception::new()
.family("Latin Modern Roman 8"),
"LMRoman9-Bold" => Exception::new()
.family("Latin Modern Roman 9"),
"LMRoman12-Bold" => Exception::new()
.family("Latin Modern Roman 12"),
"LMRomanSlant8-Regular" => Exception::new()
.family("Latin Modern Roman 8"),
"LMRomanSlant9-Regular" => Exception::new()
.family("Latin Modern Roman 9"),
"LMRomanSlant12-Regular" => Exception::new()
.family("Latin Modern Roman 12"),
"LMRomanSlant17-Regular" => Exception::new()
.family("Latin Modern Roman 17"),
"LMSans8-Regular" => Exception::new()
.family("Latin Modern Sans 8"),
"LMSans9-Regular" => Exception::new()
.family("Latin Modern Sans 9"),
"LMSans12-Regular" => Exception::new()
.family("Latin Modern Sans 12"),
"LMSans17-Regular" => Exception::new()
.family("Latin Modern Sans 17"),
"LMSans8-Oblique" => Exception::new()
.family("Latin Modern Sans 8"),
"LMSans9-Oblique" => Exception::new()
.family("Latin Modern Sans 9"),
"LMSans12-Oblique" => Exception::new()
.family("Latin Modern Sans 12"),
"LMSans17-Oblique" => Exception::new()
.family("Latin Modern Sans 17"),
// STKaiti is a set of Kai fonts. Their weight values need to be corrected
// according to their PostScript names.
"STKaitiSC-Regular" => Exception::new().weight(400),
"STKaitiTC-Regular" => Exception::new().weight(400),
"STKaitiSC-Bold" => Exception::new().weight(700),
"STKaitiTC-Bold" => Exception::new().weight(700),
"STKaitiSC-Black" => Exception::new().weight(900),
"STKaitiTC-Black" => Exception::new().weight(900),
};
| 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/text/font/variant.rs | crates/typst-library/src/text/font/variant.rs | use std::fmt::{self, Debug, Formatter};
use ecow::EcoString;
use serde::{Deserialize, Serialize};
use crate::foundations::{Cast, IntoValue, Repr, cast};
use crate::layout::Ratio;
/// Properties that distinguish a font from other fonts in the same family.
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
pub struct FontVariant {
/// The style of the font (normal / italic / oblique).
pub style: FontStyle,
/// How heavy the font is (100 - 900).
pub weight: FontWeight,
/// How condensed or expanded the font is (0.5 - 2.0).
pub stretch: FontStretch,
}
impl FontVariant {
/// Create a variant from its three components.
pub fn new(style: FontStyle, weight: FontWeight, stretch: FontStretch) -> Self {
Self { style, weight, stretch }
}
}
impl Debug for FontVariant {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}-{:?}-{:?}", self.style, self.weight, self.stretch)
}
}
/// The style of a font.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Cast, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FontStyle {
/// The default, typically upright style.
#[default]
Normal,
/// A cursive style with custom letterform.
Italic,
/// Just a slanted version of the normal style.
Oblique,
}
impl FontStyle {
/// The conceptual distance between the styles, expressed as a number.
pub fn distance(self, other: Self) -> u16 {
if self == other {
0
} else if self != Self::Normal && other != Self::Normal {
1
} else {
2
}
}
}
impl From<usvg::FontStyle> for FontStyle {
fn from(style: usvg::FontStyle) -> Self {
match style {
usvg::FontStyle::Normal => Self::Normal,
usvg::FontStyle::Italic => Self::Italic,
usvg::FontStyle::Oblique => Self::Oblique,
}
}
}
/// The weight of a font.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontWeight(pub(super) u16);
/// Font weight names and numbers.
/// See `<https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-weight#common_weight_name_mapping>`
impl FontWeight {
/// Thin weight (100).
pub const THIN: Self = Self(100);
/// Extra light weight (200).
pub const EXTRALIGHT: Self = Self(200);
/// Light weight (300).
pub const LIGHT: Self = Self(300);
/// Regular weight (400).
pub const REGULAR: Self = Self(400);
/// Medium weight (500).
pub const MEDIUM: Self = Self(500);
/// Semibold weight (600).
pub const SEMIBOLD: Self = Self(600);
/// Bold weight (700).
pub const BOLD: Self = Self(700);
/// Extrabold weight (800).
pub const EXTRABOLD: Self = Self(800);
/// Black weight (900).
pub const BLACK: Self = Self(900);
/// Create a font weight from a number between 100 and 900, clamping it if
/// necessary.
pub fn from_number(weight: u16) -> Self {
Self(weight.clamp(100, 900))
}
/// The number between 100 and 900.
pub fn to_number(self) -> u16 {
self.0
}
/// Add (or remove) weight, saturating at the boundaries of 100 and 900.
pub fn thicken(self, delta: i16) -> Self {
Self((self.0 as i16).saturating_add(delta).clamp(100, 900) as u16)
}
/// The absolute number distance between this and another font weight.
pub fn distance(self, other: Self) -> u16 {
(self.0 as i16 - other.0 as i16).unsigned_abs()
}
}
impl Default for FontWeight {
fn default() -> Self {
Self::REGULAR
}
}
impl Debug for FontWeight {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<fontdb::Weight> for FontWeight {
fn from(weight: fontdb::Weight) -> Self {
Self::from_number(weight.0)
}
}
cast! {
FontWeight,
self => IntoValue::into_value(match self {
FontWeight::THIN => "thin",
FontWeight::EXTRALIGHT => "extralight",
FontWeight::LIGHT => "light",
FontWeight::REGULAR => "regular",
FontWeight::MEDIUM => "medium",
FontWeight::SEMIBOLD => "semibold",
FontWeight::BOLD => "bold",
FontWeight::EXTRABOLD => "extrabold",
FontWeight::BLACK => "black",
_ => return self.to_number().into_value(),
}),
v: i64 => Self::from_number(v.clamp(0, u16::MAX as i64) as u16),
/// Thin weight (100).
"thin" => Self::THIN,
/// Extra light weight (200).
"extralight" => Self::EXTRALIGHT,
/// Light weight (300).
"light" => Self::LIGHT,
/// Regular weight (400).
"regular" => Self::REGULAR,
/// Medium weight (500).
"medium" => Self::MEDIUM,
/// Semibold weight (600).
"semibold" => Self::SEMIBOLD,
/// Bold weight (700).
"bold" => Self::BOLD,
/// Extrabold weight (800).
"extrabold" => Self::EXTRABOLD,
/// Black weight (900).
"black" => Self::BLACK,
}
/// The width of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontStretch(pub(super) u16);
impl FontStretch {
/// Ultra-condensed stretch (50%).
pub const ULTRA_CONDENSED: Self = Self(500);
/// Extra-condensed stretch weight (62.5%).
pub const EXTRA_CONDENSED: Self = Self(625);
/// Condensed stretch (75%).
pub const CONDENSED: Self = Self(750);
/// Semi-condensed stretch (87.5%).
pub const SEMI_CONDENSED: Self = Self(875);
/// Normal stretch (100%).
pub const NORMAL: Self = Self(1000);
/// Semi-expanded stretch (112.5%).
pub const SEMI_EXPANDED: Self = Self(1125);
/// Expanded stretch (125%).
pub const EXPANDED: Self = Self(1250);
/// Extra-expanded stretch (150%).
pub const EXTRA_EXPANDED: Self = Self(1500);
/// Ultra-expanded stretch (200%).
pub const ULTRA_EXPANDED: Self = Self(2000);
/// Create a font stretch from a ratio between 0.5 and 2.0, clamping it if
/// necessary.
pub fn from_ratio(ratio: Ratio) -> Self {
Self((ratio.get().clamp(0.5, 2.0) * 1000.0) as u16)
}
/// Create a font stretch from an OpenType-style number between 1 and 9,
/// clamping it if necessary.
pub fn from_number(stretch: u16) -> Self {
match stretch {
0 | 1 => Self::ULTRA_CONDENSED,
2 => Self::EXTRA_CONDENSED,
3 => Self::CONDENSED,
4 => Self::SEMI_CONDENSED,
5 => Self::NORMAL,
6 => Self::SEMI_EXPANDED,
7 => Self::EXPANDED,
8 => Self::EXTRA_EXPANDED,
_ => Self::ULTRA_EXPANDED,
}
}
/// The ratio between 0.5 and 2.0 corresponding to this stretch.
pub fn to_ratio(self) -> Ratio {
Ratio::new(self.0 as f64 / 1000.0)
}
/// Round to one of the pre-defined variants.
pub fn round(self) -> Self {
match self.0 {
..=562 => Self::ULTRA_CONDENSED,
563..=687 => Self::EXTRA_CONDENSED,
688..=812 => Self::CONDENSED,
813..=937 => Self::SEMI_CONDENSED,
938..=1062 => Self::NORMAL,
1063..=1187 => Self::SEMI_EXPANDED,
1188..=1374 => Self::EXPANDED,
1375..=1749 => Self::EXTRA_EXPANDED,
1750.. => Self::ULTRA_EXPANDED,
}
}
/// The absolute ratio distance between this and another font stretch.
pub fn distance(self, other: Self) -> Ratio {
(self.to_ratio() - other.to_ratio()).abs()
}
}
impl Default for FontStretch {
fn default() -> Self {
Self::NORMAL
}
}
impl Repr for FontStretch {
fn repr(&self) -> EcoString {
self.to_ratio().repr()
}
}
impl From<usvg::FontStretch> for FontStretch {
fn from(stretch: usvg::FontStretch) -> Self {
match stretch {
usvg::FontStretch::UltraCondensed => Self::ULTRA_CONDENSED,
usvg::FontStretch::ExtraCondensed => Self::EXTRA_CONDENSED,
usvg::FontStretch::Condensed => Self::CONDENSED,
usvg::FontStretch::SemiCondensed => Self::SEMI_CONDENSED,
usvg::FontStretch::Normal => Self::NORMAL,
usvg::FontStretch::SemiExpanded => Self::SEMI_EXPANDED,
usvg::FontStretch::Expanded => Self::EXPANDED,
usvg::FontStretch::ExtraExpanded => Self::EXTRA_EXPANDED,
usvg::FontStretch::UltraExpanded => Self::ULTRA_EXPANDED,
}
}
}
cast! {
FontStretch,
self => self.to_ratio().into_value(),
v: Ratio => Self::from_ratio(v),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_font_weight_distance() {
let d = |a, b| FontWeight(a).distance(FontWeight(b));
assert_eq!(d(500, 200), 300);
assert_eq!(d(500, 500), 0);
assert_eq!(d(500, 900), 400);
assert_eq!(d(10, 100), 90);
}
#[test]
fn test_font_stretch_debug() {
assert_eq!(FontStretch::EXPANDED.repr(), "125%")
}
}
| 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/loading/json.rs | crates/typst-library/src/loading/json.rs | use ecow::eco_format;
use typst_syntax::Spanned;
use crate::diag::{At, LineCol, LoadError, LoadedWithin, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{Str, Value, func, scope};
use crate::loading::{DataSource, Load, Readable};
/// Reads structured data from a JSON file.
///
/// The file must contain a valid JSON value, such as object or array. The JSON
/// values will be converted into corresponding Typst values as listed in the
/// [table below](#conversion).
///
/// The function returns a dictionary, an array or, depending on the JSON file,
/// another JSON data type.
///
/// The JSON files in the example contain objects with the keys `temperature`,
/// `unit`, and `weather`.
///
/// # Example
/// ```example
/// #let forecast(day) = block[
/// #box(square(
/// width: 2cm,
/// inset: 8pt,
/// fill: if day.weather == "sunny" {
/// yellow
/// } else {
/// aqua
/// },
/// align(
/// bottom + right,
/// strong(day.weather),
/// ),
/// ))
/// #h(6pt)
/// #set text(22pt, baseline: -8pt)
/// #day.temperature °#day.unit
/// ]
///
/// #forecast(json("monday.json"))
/// #forecast(json("tuesday.json"))
/// ```
///
/// # Conversion details { #conversion }
///
/// | JSON value | Converted into Typst |
/// | ---------- | -------------------- |
/// | `null` | `{none}` |
/// | bool | [`bool`] |
/// | number | [`float`] or [`int`] |
/// | string | [`str`] |
/// | array | [`array`] |
/// | object | [`dictionary`] |
///
/// | Typst value | Converted into JSON |
/// | ------------------------------------- | -------------------------------- |
/// | types that can be converted from JSON | corresponding JSON value |
/// | [`bytes`] | string via [`repr`] |
/// | [`symbol`] | string |
/// | [`content`] | an object describing the content |
/// | other types ([`length`], etc.) | string via [`repr`] |
///
/// ## Notes
/// - In most cases, JSON numbers will be converted to floats or integers
/// depending on whether they are whole numbers. However, be aware that
/// integers larger than 2<sup>63</sup>-1 or smaller than -2<sup>63</sup> will
/// be converted to floating-point numbers, which may result in an
/// approximative value.
///
/// - Bytes are not encoded as JSON arrays for performance and readability
/// reasons. Consider using [`cbor.encode`] for binary data.
///
/// - The `repr` function is [for debugging purposes only]($repr/#debugging-only),
/// and its output is not guaranteed to be stable across Typst versions.
#[func(scope, title = "JSON")]
pub fn json(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a JSON file or raw JSON bytes.
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
let raw = loaded.data.as_slice();
// If the file starts with a UTF-8 Byte Order Mark (BOM), return a
// friendly error message.
if raw.starts_with(b"\xef\xbb\xbf") {
bail!(
LoadError::new(
LineCol::one_based(1, 1),
"failed to parse JSON",
"unexpected Byte Order Mark",
)
.within(&loaded)
.with_hint("JSON requires UTF-8 without a BOM")
);
}
serde_json::from_slice(raw)
.map_err(|err| {
let pos = LineCol::one_based(err.line(), err.column());
LoadError::new(pos, "failed to parse JSON", err)
})
.within(&loaded)
}
#[scope]
impl json {
/// Reads structured data from a JSON string/bytes.
#[func(title = "Decode JSON")]
#[deprecated(
message = "`json.decode` is deprecated, directly pass bytes to `json` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// JSON data.
data: Spanned<Readable>,
) -> SourceResult<Value> {
json(engine, data.map(Readable::into_source))
}
/// Encodes structured data into a JSON string.
#[func(title = "Encode JSON")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
/// Whether to pretty print the JSON with newlines and indentation.
#[named]
#[default(true)]
pretty: bool,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
if pretty {
serde_json::to_string_pretty(&value)
} else {
serde_json::to_string(&value)
}
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as JSON ({err})"))
.at(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/loading/xml.rs | crates/typst-library/src/loading/xml.rs | use roxmltree::ParsingOptions;
use typst_syntax::Spanned;
use crate::diag::{LoadError, LoadedWithin, SourceResult, format_xml_like_error};
use crate::engine::Engine;
use crate::foundations::{Array, Dict, IntoValue, Str, Value, dict, func, scope};
use crate::loading::{DataSource, Load, Readable};
/// Reads structured data from an XML file.
///
/// The XML file is parsed into an array of dictionaries and strings. XML nodes
/// can be elements or strings. Elements are represented as dictionaries with
/// the following keys:
///
/// - `tag`: The name of the element as a string.
/// - `attrs`: A dictionary of the element's attributes as strings.
/// - `children`: An array of the element's child nodes.
///
/// The XML file in the example contains a root `news` tag with multiple
/// `article` tags. Each article has a `title`, `author`, and `content` tag. The
/// `content` tag contains one or more paragraphs, which are represented as `p`
/// tags.
///
/// # Example
/// ```example
/// #let find-child(elem, tag) = {
/// elem.children
/// .find(e => "tag" in e and e.tag == tag)
/// }
///
/// #let article(elem) = {
/// let title = find-child(elem, "title")
/// let author = find-child(elem, "author")
/// let pars = find-child(elem, "content")
///
/// [= #title.children.first()]
/// text(10pt, weight: "medium")[
/// Published by
/// #author.children.first()
/// ]
///
/// for p in pars.children {
/// if type(p) == dictionary {
/// parbreak()
/// p.children.first()
/// }
/// }
/// }
///
/// #let data = xml("example.xml")
/// #for elem in data.first().children {
/// if type(elem) == dictionary {
/// article(elem)
/// }
/// }
/// ```
#[func(scope, title = "XML")]
pub fn xml(
engine: &mut Engine,
/// A [path]($syntax/#paths) to an XML file or raw XML bytes.
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
let text = loaded.data.as_str().within(&loaded)?;
let document = roxmltree::Document::parse_with_options(
text,
ParsingOptions { allow_dtd: true, ..Default::default() },
)
.map_err(format_xml_error)
.within(&loaded)?;
Ok(convert_xml(document.root()))
}
#[scope]
impl xml {
/// Reads structured data from an XML string/bytes.
#[func(title = "Decode XML")]
#[deprecated(
message = "`xml.decode` is deprecated, directly pass bytes to `xml` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// XML data.
data: Spanned<Readable>,
) -> SourceResult<Value> {
xml(engine, data.map(Readable::into_source))
}
}
/// Convert an XML node to a Typst value.
fn convert_xml(node: roxmltree::Node) -> Value {
if node.is_text() {
return node.text().unwrap_or_default().into_value();
}
let children: Array = node.children().map(convert_xml).collect();
if node.is_root() {
return Value::Array(children);
}
let tag: Str = node.tag_name().name().into();
let attrs: Dict = node
.attributes()
.map(|attr| (attr.name().into(), attr.value().into_value()))
.collect();
Value::Dict(dict! {
"tag" => tag,
"attrs" => attrs,
"children" => children,
})
}
/// Format the user-facing XML error message.
fn format_xml_error(error: roxmltree::Error) -> LoadError {
format_xml_like_error("XML", 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/loading/cbor.rs | crates/typst-library/src/loading/cbor.rs | use ecow::eco_format;
use typst_syntax::Spanned;
use crate::diag::{At, SourceResult};
use crate::engine::Engine;
use crate::foundations::{Bytes, Value, func, scope};
use crate::loading::{DataSource, Load};
/// Reads structured data from a CBOR file.
///
/// The file must contain a valid CBOR serialization. The CBOR values will be
/// converted into corresponding Typst values as listed in the
/// [table below](#conversion).
///
/// The function returns a dictionary, an array or, depending on the CBOR file,
/// another CBOR data type.
///
/// # Conversion details { #conversion }
///
/// | CBOR value | Converted into Typst |
/// | ---------- | ---------------------- |
/// | integer | [`int`] (or [`float`]) |
/// | bytes | [`bytes`] |
/// | float | [`float`] |
/// | text | [`str`] |
/// | bool | [`bool`] |
/// | null | `{none}` |
/// | array | [`array`] |
/// | map | [`dictionary`] |
///
/// | Typst value | Converted into CBOR |
/// | ------------------------------------- | ---------------------------- |
/// | types that can be converted from CBOR | corresponding CBOR value |
/// | [`symbol`] | text |
/// | [`content`] | a map describing the content |
/// | other types ([`length`], etc.) | text via [`repr`] |
///
/// ## Notes
///
/// - Be aware that CBOR integers larger than 2<sup>63</sup>-1 or smaller than
/// -2<sup>63</sup> will be converted to floating point numbers, which may
/// result in an approximative value.
///
/// - CBOR tags are not supported, and an error will be thrown.
///
/// - The `repr` function is [for debugging purposes only]($repr/#debugging-only),
/// and its output is not guaranteed to be stable across Typst versions.
#[func(scope, title = "CBOR")]
pub fn cbor(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a CBOR file or raw CBOR bytes.
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
ciborium::from_reader(loaded.data.as_slice())
.map_err(|err| eco_format!("failed to parse CBOR ({err})"))
.at(source.span)
}
#[scope]
impl cbor {
/// Reads structured data from CBOR bytes.
#[func(title = "Decode CBOR")]
#[deprecated(
message = "`cbor.decode` is deprecated, directly pass bytes to `cbor` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// CBOR data.
data: Spanned<Bytes>,
) -> SourceResult<Value> {
cbor(engine, data.map(DataSource::Bytes))
}
/// Encode structured data into CBOR bytes.
#[func(title = "Encode CBOR")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
) -> SourceResult<Bytes> {
let Spanned { v: value, span } = value;
let mut res = Vec::new();
ciborium::into_writer(&value, &mut res)
.map(|_| Bytes::new(res))
.map_err(|err| eco_format!("failed to encode value as CBOR ({err})"))
.at(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/loading/mod.rs | crates/typst-library/src/loading/mod.rs | //! Data loading.
#[path = "cbor.rs"]
mod cbor_;
#[path = "csv.rs"]
mod csv_;
#[path = "json.rs"]
mod json_;
#[path = "read.rs"]
mod read_;
#[path = "toml.rs"]
mod toml_;
#[path = "xml.rs"]
mod xml_;
#[path = "yaml.rs"]
mod yaml_;
use comemo::Tracked;
use ecow::EcoString;
use typst_syntax::{FileId, Spanned};
pub use self::cbor_::*;
pub use self::csv_::*;
pub use self::json_::*;
pub use self::read_::*;
pub use self::toml_::*;
pub use self::xml_::*;
pub use self::yaml_::*;
use crate::World;
use crate::diag::{At, SourceResult};
use crate::foundations::OneOrMultiple;
use crate::foundations::{Bytes, Scope, Str, cast};
/// Hook up all `data-loading` definitions.
pub(super) fn define(global: &mut Scope) {
global.start_category(crate::Category::DataLoading);
global.define_func::<read>();
global.define_func::<csv>();
global.define_func::<json>();
global.define_func::<toml>();
global.define_func::<yaml>();
global.define_func::<cbor>();
global.define_func::<xml>();
global.reset_category();
}
/// Something we can retrieve byte data from.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum DataSource {
/// A path to a file.
Path(EcoString),
/// Raw bytes.
Bytes(Bytes),
}
cast! {
DataSource,
self => match self {
Self::Path(v) => v.into_value(),
Self::Bytes(v) => v.into_value(),
},
v: EcoString => Self::Path(v),
v: Bytes => Self::Bytes(v),
}
/// Loads data from a path or provided bytes.
pub trait Load {
/// Bytes or a list of bytes (if there are multiple sources).
type Output;
/// Load the bytes.
fn load(&self, world: Tracked<dyn World + '_>) -> SourceResult<Self::Output>;
}
impl Load for Spanned<DataSource> {
type Output = Loaded;
fn load(&self, world: Tracked<dyn World + '_>) -> SourceResult<Self::Output> {
self.as_ref().load(world)
}
}
impl Load for Spanned<&DataSource> {
type Output = Loaded;
fn load(&self, world: Tracked<dyn World + '_>) -> SourceResult<Self::Output> {
match &self.v {
DataSource::Path(path) => {
let file_id = self.span.resolve_path(path).at(self.span)?;
let data = world.file(file_id).at(self.span)?;
let source = Spanned::new(LoadSource::Path(file_id), self.span);
Ok(Loaded::new(source, data))
}
DataSource::Bytes(data) => {
let source = Spanned::new(LoadSource::Bytes, self.span);
Ok(Loaded::new(source, data.clone()))
}
}
}
}
impl Load for Spanned<OneOrMultiple<DataSource>> {
type Output = Vec<Loaded>;
fn load(&self, world: Tracked<dyn World + '_>) -> SourceResult<Self::Output> {
self.as_ref().load(world)
}
}
impl Load for Spanned<&OneOrMultiple<DataSource>> {
type Output = Vec<Loaded>;
fn load(&self, world: Tracked<dyn World + '_>) -> SourceResult<Self::Output> {
self.v
.0
.iter()
.map(|source| Spanned::new(source, self.span).load(world))
.collect()
}
}
/// Data loaded from a [`DataSource`].
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Loaded {
/// Details about where `data` was loaded from.
pub source: Spanned<LoadSource>,
/// The loaded data.
pub data: Bytes,
}
impl Loaded {
pub fn new(source: Spanned<LoadSource>, bytes: Bytes) -> Self {
Self { source, data: bytes }
}
}
/// A loaded [`DataSource`].
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum LoadSource {
Path(FileId),
Bytes,
}
/// A value that can be read from a file.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Readable {
/// A decoded string.
Str(Str),
/// Raw bytes.
Bytes(Bytes),
}
impl Readable {
pub fn into_bytes(self) -> Bytes {
match self {
Self::Bytes(v) => v,
Self::Str(v) => Bytes::from_string(v),
}
}
pub fn into_source(self) -> DataSource {
DataSource::Bytes(self.into_bytes())
}
}
cast! {
Readable,
self => match self {
Self::Str(v) => v.into_value(),
Self::Bytes(v) => v.into_value(),
},
v: Str => Self::Str(v),
v: Bytes => Self::Bytes(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/loading/yaml.rs | crates/typst-library/src/loading/yaml.rs | use ecow::eco_format;
use typst_syntax::Spanned;
use crate::diag::{At, LineCol, LoadError, LoadedWithin, ReportPos, SourceResult};
use crate::engine::Engine;
use crate::foundations::{Str, Value, func, scope};
use crate::loading::{DataSource, Load, Readable};
/// Reads structured data from a YAML file.
///
/// The file must contain a valid YAML object or array. The YAML values will be
/// converted into corresponding Typst values as listed in the
/// [table below](#conversion).
///
/// The function returns a dictionary, an array or, depending on the YAML file,
/// another YAML data type.
///
/// The YAML files in the example contain objects with authors as keys,
/// each with a sequence of their own submapping with the keys
/// "title" and "published".
///
/// # Example
/// ```example
/// #let bookshelf(contents) = {
/// for (author, works) in contents {
/// author
/// for work in works [
/// - #work.title (#work.published)
/// ]
/// }
/// }
///
/// #bookshelf(
/// yaml("scifi-authors.yaml")
/// )
/// ```
///
/// # Conversion details { #conversion }
///
/// | YAML value | Converted into Typst |
/// | -------------------------------------- | -------------------- |
/// | null-values (`null`, `~` or empty ` `) | `{none}` |
/// | boolean | [`bool`] |
/// | number | [`float`] or [`int`] |
/// | string | [`str`] |
/// | sequence | [`array`] |
/// | mapping | [`dictionary`] |
///
/// | Typst value | Converted into YAML |
/// | ------------------------------------- | -------------------------------- |
/// | types that can be converted from YAML | corresponding YAML value |
/// | [`bytes`] | string via [`repr`] |
/// | [`symbol`] | string |
/// | [`content`] | a mapping describing the content |
/// | other types ([`length`], etc.) | string via [`repr`] |
///
/// ## Notes
/// - In most cases, YAML numbers will be converted to floats or integers
/// depending on whether they are whole numbers. However, be aware that
/// integers larger than 2<sup>63</sup>-1 or smaller than -2<sup>63</sup> will
/// be converted to floating-point numbers, which may result in an
/// approximative value.
///
/// - Custom YAML tags are ignored, though the loaded value will still be present.
///
/// - Bytes are not encoded as YAML sequences for performance and readability
/// reasons. Consider using [`cbor.encode`] for binary data.
///
/// - The `repr` function is [for debugging purposes only]($repr/#debugging-only),
/// and its output is not guaranteed to be stable across Typst versions.
#[func(scope, title = "YAML")]
pub fn yaml(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a YAML file or raw YAML bytes.
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
serde_yaml::from_slice(loaded.data.as_slice())
.map_err(format_yaml_error)
.within(&loaded)
}
#[scope]
impl yaml {
/// Reads structured data from a YAML string/bytes.
#[func(title = "Decode YAML")]
#[deprecated(
message = "`yaml.decode` is deprecated, directly pass bytes to `yaml` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// YAML data.
data: Spanned<Readable>,
) -> SourceResult<Value> {
yaml(engine, data.map(Readable::into_source))
}
/// Encode structured data into a YAML string.
#[func(title = "Encode YAML")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
serde_yaml::to_string(&value)
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as YAML ({err})"))
.at(span)
}
}
/// Format the user-facing YAML error message.
pub fn format_yaml_error(error: serde_yaml::Error) -> LoadError {
let pos = error
.location()
.map(|loc| {
let line_col = LineCol::one_based(loc.line(), loc.column());
let range = loc.index()..loc.index();
ReportPos::full(range, line_col)
})
.unwrap_or_default();
LoadError::new(pos, "failed to parse YAML", 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/loading/csv.rs | crates/typst-library/src/loading/csv.rs | use az::SaturatingAs;
use typst_syntax::Spanned;
use crate::diag::{LineCol, LoadError, LoadedWithin, ReportPos, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{Array, Dict, IntoValue, Type, Value, cast, func, scope};
use crate::loading::{DataSource, Load, Readable};
/// Reads structured data from a CSV file.
///
/// The CSV file will be read and parsed into a 2-dimensional array of strings:
/// Each row in the CSV file will be represented as an array of strings, and all
/// rows will be collected into a single array. Header rows will not be
/// stripped.
///
/// # Example
/// ```example
/// #let results = csv("example.csv")
///
/// #table(
/// columns: 2,
/// [*Condition*], [*Result*],
/// ..results.flatten(),
/// )
/// ```
#[func(scope, title = "CSV")]
pub fn csv(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a CSV file or raw CSV bytes.
source: Spanned<DataSource>,
/// The delimiter that separates columns in the CSV file.
/// Must be a single ASCII character.
#[named]
#[default]
delimiter: Delimiter,
/// How to represent the file's rows.
///
/// - If set to `array`, each row is represented as a plain array of
/// strings.
/// - If set to `dictionary`, each row is represented as a dictionary
/// mapping from header keys to strings. This option only makes sense when
/// a header row is present in the CSV file.
#[named]
#[default(RowType::Array)]
row_type: RowType,
) -> SourceResult<Array> {
let loaded = source.load(engine.world)?;
let mut builder = ::csv::ReaderBuilder::new();
let has_headers = row_type == RowType::Dict;
builder.has_headers(has_headers);
builder.delimiter(delimiter.0 as u8);
// Counting lines from 1 by default.
let mut line_offset: usize = 1;
let mut reader = builder.from_reader(loaded.data.as_slice());
let mut headers: Option<::csv::StringRecord> = None;
if has_headers {
// Counting lines from 2 because we have a header.
line_offset += 1;
headers = Some(
reader
.headers()
.cloned()
.map_err(|err| format_csv_error(err, 1))
.within(&loaded)?,
);
}
let mut array = Array::new();
for (line, result) in reader.records().enumerate() {
// Original solution was to use line from error, but that is
// incorrect with `has_headers` set to `false`. See issue:
// https://github.com/BurntSushi/rust-csv/issues/184
let line = line + line_offset;
let row = result.map_err(|err| format_csv_error(err, line)).within(&loaded)?;
let item = if let Some(headers) = &headers {
let mut dict = Dict::new();
for (field, value) in headers.iter().zip(&row) {
dict.insert(field.into(), value.into_value());
}
dict.into_value()
} else {
let sub = row.into_iter().map(|field| field.into_value()).collect();
Value::Array(sub)
};
array.push(item);
}
Ok(array)
}
#[scope]
impl csv {
/// Reads structured data from a CSV string/bytes.
#[func(title = "Decode CSV")]
#[deprecated(
message = "`csv.decode` is deprecated, directly pass bytes to `csv` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// CSV data.
data: Spanned<Readable>,
/// The delimiter that separates columns in the CSV file.
/// Must be a single ASCII character.
#[named]
#[default]
delimiter: Delimiter,
/// How to represent the file's rows.
///
/// - If set to `array`, each row is represented as a plain array of
/// strings.
/// - If set to `dictionary`, each row is represented as a dictionary
/// mapping from header keys to strings. This option only makes sense
/// when a header row is present in the CSV file.
#[named]
#[default(RowType::Array)]
row_type: RowType,
) -> SourceResult<Array> {
csv(engine, data.map(Readable::into_source), delimiter, row_type)
}
}
/// The delimiter to use when parsing CSV files.
pub struct Delimiter(char);
impl Default for Delimiter {
fn default() -> Self {
Self(',')
}
}
cast! {
Delimiter,
self => self.0.into_value(),
c: char => if c.is_ascii() {
Self(c)
} else {
bail!("delimiter must be an ASCII character")
},
}
/// The type of parsed rows.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum RowType {
Array,
Dict,
}
cast! {
RowType,
self => match self {
Self::Array => Type::of::<Array>(),
Self::Dict => Type::of::<Dict>(),
}.into_value(),
ty: Type => {
if ty == Type::of::<Array>() {
Self::Array
} else if ty == Type::of::<Dict>() {
Self::Dict
} else {
bail!("expected `array` or `dictionary`");
}
},
}
/// Format the user-facing CSV error message.
fn format_csv_error(err: ::csv::Error, line: usize) -> LoadError {
let msg = "failed to parse CSV";
let pos = (err.kind().position())
.map(|pos| {
let start = pos.byte().saturating_as();
ReportPos::from(start..start)
})
.unwrap_or(LineCol::one_based(line, 1).into());
match err.kind() {
::csv::ErrorKind::Utf8 { .. } => {
LoadError::new(pos, msg, "file is not valid UTF-8")
}
::csv::ErrorKind::UnequalLengths { expected_len, len, .. } => {
let err =
format!("found {len} instead of {expected_len} fields in line {line}");
LoadError::new(pos, msg, err)
}
_ => LoadError::new(pos, "failed to parse CSV", 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/loading/read.rs | crates/typst-library/src/loading/read.rs | use ecow::EcoString;
use typst_syntax::Spanned;
use crate::diag::{LoadedWithin, SourceResult};
use crate::engine::Engine;
use crate::foundations::{Cast, func};
use crate::loading::{DataSource, Load, Readable};
/// Reads plain text or data from a file.
///
/// By default, the file will be read as UTF-8 and returned as a [string]($str).
///
/// If you specify `{encoding: none}`, this returns raw [bytes] instead.
///
/// # Example
/// ```example
/// An example for a HTML file: \
/// #let text = read("example.html")
/// #raw(text, block: true, lang: "html")
///
/// Raw bytes:
/// #read("tiger.jpg", encoding: none)
/// ```
#[func]
pub fn read(
engine: &mut Engine,
/// Path to a file.
///
/// For more details, see the [Paths section]($syntax/#paths).
path: Spanned<EcoString>,
/// The encoding to read the file with.
///
/// If set to `{none}`, this function returns raw bytes.
#[named]
#[default(Some(Encoding::Utf8))]
encoding: Option<Encoding>,
) -> SourceResult<Readable> {
let loaded = path.map(DataSource::Path).load(engine.world)?;
Ok(match encoding {
None => Readable::Bytes(loaded.data),
Some(Encoding::Utf8) => Readable::Str(loaded.data.to_str().within(&loaded)?),
})
}
/// An encoding of a file.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum Encoding {
/// The Unicode UTF-8 encoding.
Utf8,
}
| 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/loading/toml.rs | crates/typst-library/src/loading/toml.rs | use ecow::eco_format;
use typst_syntax::Spanned;
use crate::diag::{At, LoadError, LoadedWithin, ReportPos, SourceResult};
use crate::engine::Engine;
use crate::foundations::{Dict, Str, func, scope};
use crate::loading::{DataSource, Load, Readable};
/// Reads structured data from a TOML file.
///
/// The file must contain a valid TOML table. The TOML values will be converted
/// into corresponding Typst values as listed in the [table below](#conversion).
///
/// The function returns a dictionary representing the TOML table.
///
/// The TOML file in the example consists of a table with the keys `title`,
/// `version`, and `authors`.
///
/// # Example
/// ```example
/// #let details = toml("details.toml")
///
/// Title: #details.title \
/// Version: #details.version \
/// Authors: #(details.authors
/// .join(", ", last: " and "))
/// ```
///
/// # Conversion details { #conversion }
///
/// First of all, TOML documents are tables. Other values must be put in a table
/// to be encoded or decoded.
///
/// | TOML value | Converted into Typst |
/// | ---------- | -------------------- |
/// | string | [`str`] |
/// | integer | [`int`] |
/// | float | [`float`] |
/// | boolean | [`bool`] |
/// | datetime | [`datetime`] |
/// | array | [`array`] |
/// | table | [`dictionary`] |
///
/// | Typst value | Converted into TOML |
/// | ------------------------------------- | ------------------------------ |
/// | types that can be converted from TOML | corresponding TOML value |
/// | `{none}` | ignored |
/// | [`bytes`] | string via [`repr`] |
/// | [`symbol`] | string |
/// | [`content`] | a table describing the content |
/// | other types ([`length`], etc.) | string via [`repr`] |
///
/// ## Notes
/// - Be aware that TOML integers larger than 2<sup>63</sup>-1 or smaller
/// than -2<sup>63</sup> cannot be represented losslessly in Typst, and an
/// error will be thrown according to the
/// [specification](https://toml.io/en/v1.0.0#integer).
///
/// - Bytes are not encoded as TOML arrays for performance and readability
/// reasons. Consider using [`cbor.encode`] for binary data.
///
/// - The `repr` function is [for debugging purposes only]($repr/#debugging-only),
/// and its output is not guaranteed to be stable across Typst versions.
#[func(scope, title = "TOML")]
pub fn toml(
engine: &mut Engine,
/// A [path]($syntax/#paths) to a TOML file or raw TOML bytes.
source: Spanned<DataSource>,
) -> SourceResult<Dict> {
let loaded = source.load(engine.world)?;
let raw = loaded.data.as_str().within(&loaded)?;
::toml::from_str(raw).map_err(format_toml_error).within(&loaded)
}
#[scope]
impl toml {
/// Reads structured data from a TOML string/bytes.
#[func(title = "Decode TOML")]
#[deprecated(
message = "`toml.decode` is deprecated, directly pass bytes to `toml` instead",
until = "0.15.0"
)]
pub fn decode(
engine: &mut Engine,
/// TOML data.
data: Spanned<Readable>,
) -> SourceResult<Dict> {
toml(engine, data.map(Readable::into_source))
}
/// Encodes structured data into a TOML string.
#[func(title = "Encode TOML")]
pub fn encode(
/// Value to be encoded.
///
/// TOML documents are tables. Therefore, only dictionaries are suitable.
value: Spanned<Dict>,
/// Whether to pretty-print the resulting TOML.
#[named]
#[default(true)]
pretty: bool,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
if pretty { ::toml::to_string_pretty(&value) } else { ::toml::to_string(&value) }
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as TOML ({err})"))
.at(span)
}
}
/// Format the user-facing TOML error message.
fn format_toml_error(error: ::toml::de::Error) -> LoadError {
let pos = error.span().map(ReportPos::from).unwrap_or_default();
LoadError::new(pos, "failed to parse TOML", error.message())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst/src/lib.rs | crates/typst/src/lib.rs | //! The compiler for the _Typst_ markup language.
//!
//! # Steps
//! - **Parsing:**
//! The compiler first transforms a plain string into an iterator of [tokens].
//! This token stream is [parsed] into a [syntax tree]. The tree itself is
//! untyped, but the [AST] module provides a typed layer over it.
//! - **Evaluation:**
//! The next step is to [evaluate] the markup. This produces a [module],
//! consisting of a scope of values that were exported by the code and
//! [content], a hierarchical, styled representation of what was written in
//! the source file. The elements of the content tree are well structured and
//! order-independent and thus much better suited for further processing than
//! the raw markup.
//! - **Layouting:**
//! Next, the content is [laid out] into a [`PagedDocument`] containing one
//! [frame] per page with items at fixed positions.
//! - **Exporting:**
//! These frames can finally be exported into an output format (currently PDF,
//! PNG, SVG, and HTML).
//!
//! [tokens]: typst_syntax::SyntaxKind
//! [parsed]: typst_syntax::parse
//! [syntax tree]: typst_syntax::SyntaxNode
//! [AST]: typst_syntax::ast
//! [evaluate]: typst_eval::eval
//! [module]: crate::foundations::Module
//! [content]: crate::foundations::Content
//! [laid out]: typst_layout::layout_document
//! [frame]: crate::layout::Frame
pub extern crate comemo;
pub extern crate ecow;
pub use typst_library::*;
#[doc(inline)]
pub use typst_syntax as syntax;
#[doc(inline)]
pub use typst_utils as utils;
use std::sync::LazyLock;
use arrayvec::ArrayVec;
use comemo::{Track, Tracked};
use ecow::{EcoString, EcoVec, eco_format, eco_vec};
use rustc_hash::FxHashSet;
use typst_html::HtmlDocument;
use typst_library::diag::{
FileError, SourceDiagnostic, SourceResult, Warned, bail, warning,
};
use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{NativeRuleMap, StyleChain, Styles, Value};
use typst_library::introspection::{ITER_NAMES, Introspector, MAX_ITERS};
use typst_library::layout::PagedDocument;
use typst_library::routines::Routines;
use typst_syntax::{FileId, Span};
use typst_timing::{TimingScope, timed};
use typst_utils::Protected;
use crate::foundations::{Target, TargetElem};
use crate::model::DocumentInfo;
/// Compile sources into a fully layouted document.
///
/// - Returns `Ok(document)` if there were no fatal errors.
/// - Returns `Err(errors)` if there were fatal errors.
#[typst_macros::time]
pub fn compile<D>(world: &dyn World) -> Warned<SourceResult<D>>
where
D: Document,
{
let mut sink = Sink::new();
let output = compile_impl::<D>(world.track(), Traced::default().track(), &mut sink)
.map_err(deduplicate);
Warned { output, warnings: sink.warnings() }
}
/// Compiles sources and returns all values and styles observed at the given
/// `span` during compilation.
#[typst_macros::time]
pub fn trace<D>(world: &dyn World, span: Span) -> EcoVec<(Value, Option<Styles>)>
where
D: Document,
{
let mut sink = Sink::new();
let traced = Traced::new(span);
compile_impl::<D>(world.track(), traced.track(), &mut sink).ok();
sink.values()
}
/// The internal implementation of `compile` with a bit lower-level interface
/// that is also used by `trace`.
fn compile_impl<D: Document>(
world: Tracked<dyn World + '_>,
traced: Tracked<Traced>,
sink: &mut Sink,
) -> SourceResult<D> {
if D::target() == Target::Html {
warn_or_error_for_html(world, sink)?;
}
let library = world.library();
let base = StyleChain::new(&library.styles);
let target = TargetElem::target.set(D::target()).wrap();
let styles = base.chain(&target);
let empty_introspector = Introspector::default();
// Fetch the main source file once.
let main = world.main();
let main = world
.source(main)
.map_err(|err| hint_invalid_main_file(world, err, main))?;
// First evaluate the main source file into a module.
let content = typst_eval::eval(
&ROUTINES,
world,
traced,
sink.track_mut(),
Route::default().track(),
&main,
)?
.content();
let mut history: ArrayVec<D, { MAX_ITERS - 1 }> = ArrayVec::new();
let mut document: D;
// Relayout until all introspections stabilize.
// If that doesn't happen within five attempts, we give up.
loop {
let _scope = TimingScope::new(ITER_NAMES[history.len()]);
let introspector = history
.last()
.map(|doc| doc.introspector())
.unwrap_or(&empty_introspector);
let constraint = comemo::Constraint::new();
let mut subsink = Sink::new();
let mut engine = Engine {
world,
introspector: Protected::new(introspector.track_with(&constraint)),
traced,
sink: subsink.track_mut(),
route: Route::default(),
routines: &ROUTINES,
};
document = D::create(&mut engine, &content, styles)?;
if timed!("check stabilized", constraint.validate(document.introspector())) {
sink.extend_from_sink(subsink);
break;
}
if history.is_full() {
let mut introspectors = [&empty_introspector; MAX_ITERS + 1];
for i in 1..MAX_ITERS {
introspectors[i] = history[i - 1].introspector();
}
introspectors[MAX_ITERS] = document.introspector();
let warnings = typst_library::introspection::analyze(
world,
&ROUTINES,
introspectors,
subsink.introspections(),
);
sink.extend_from_sink(subsink);
for warning in warnings {
sink.warn(warning);
}
break;
}
history.push(document);
}
// Promote delayed errors.
let delayed = sink.delayed();
if !delayed.is_empty() {
return Err(delayed);
}
Ok(document)
}
/// Deduplicate diagnostics.
fn deduplicate(mut diags: EcoVec<SourceDiagnostic>) -> EcoVec<SourceDiagnostic> {
let mut unique = FxHashSet::default();
diags.retain(|diag| {
let hash = typst_utils::hash128(&(&diag.span, &diag.message));
unique.insert(hash)
});
diags
}
/// Adds useful hints when the main source file couldn't be read
/// and returns the final diagnostic.
fn hint_invalid_main_file(
world: Tracked<dyn World + '_>,
file_error: FileError,
input: FileId,
) -> EcoVec<SourceDiagnostic> {
let is_utf8_error = matches!(file_error, FileError::InvalidUtf8);
let mut diagnostic =
SourceDiagnostic::error(Span::detached(), EcoString::from(file_error));
// Attempt to provide helpful hints for UTF-8 errors. Perhaps the user
// mistyped the filename. For example, they could have written "file.pdf"
// instead of "file.typ".
if is_utf8_error {
let path = input.vpath();
let extension = path.as_rootless_path().extension();
if extension.is_some_and(|extension| extension == "typ") {
// No hints if the file is already a .typ file.
// The file is indeed just invalid.
return eco_vec![diagnostic];
}
match extension {
Some(extension) => {
diagnostic.hint(eco_format!(
"a file with the `.{}` extension is not usually a Typst file",
extension.to_string_lossy()
));
}
None => {
diagnostic
.hint("a file without an extension is not usually a Typst file");
}
};
if world.source(input.with_extension("typ")).is_ok() {
diagnostic.hint("check if you meant to use the `.typ` extension instead");
}
}
eco_vec![diagnostic]
}
/// HTML export will warn or error depending on whether the feature flag is enabled.
fn warn_or_error_for_html(
world: Tracked<dyn World + '_>,
sink: &mut Sink,
) -> SourceResult<()> {
const ISSUE: &str = "https://github.com/typst/typst/issues/5512";
if world.library().features.is_enabled(Feature::Html) {
sink.warn(warning!(
Span::detached(),
"html export is under active development and incomplete";
hint: "its behaviour may change at any time";
hint: "do not rely on this feature for production use cases";
hint: "see {ISSUE} for more information";
));
} else {
bail!(
Span::detached(),
"html export is only available when `--features html` is passed";
hint: "html export is under active development and incomplete";
hint: "see {ISSUE} for more information";
);
}
Ok(())
}
/// A document is what results from compilation.
pub trait Document: sealed::Sealed {
/// Get the document's metadata.
fn info(&self) -> &DocumentInfo;
/// Get the document's introspector.
fn introspector(&self) -> &Introspector;
}
impl Document for PagedDocument {
fn info(&self) -> &DocumentInfo {
&self.info
}
fn introspector(&self) -> &Introspector {
&self.introspector
}
}
impl Document for HtmlDocument {
fn info(&self) -> &DocumentInfo {
&self.info
}
fn introspector(&self) -> &Introspector {
&self.introspector
}
}
/// A trait for accepting an arbitrary kind of document as input.
///
/// Can be used to accept a reference to
/// - any kind of sized type that implements [`Document`], or
/// - the trait object [`&dyn Document`].
///
/// Should be used as `impl AsDocument` rather than `&impl AsDocument`.
///
/// # Why is this needed?
/// Unfortunately, `&impl Document` can't be turned into `&dyn Document` in a
/// generic function. Directly accepting `&dyn Document` is of course also
/// possible, but is less convenient, especially in cases where the document is
/// optional.
///
/// See also
/// <https://users.rust-lang.org/t/converting-from-generic-unsized-parameter-to-trait-object/72376>
pub trait AsDocument {
/// Turns the reference into the trait object.
fn as_document(&self) -> &dyn Document;
}
impl AsDocument for &dyn Document {
fn as_document(&self) -> &dyn Document {
*self
}
}
impl<D: Document> AsDocument for &D {
fn as_document(&self) -> &dyn Document {
*self
}
}
mod sealed {
use typst_library::foundations::{Content, Target};
use super::*;
pub trait Sealed {
fn target() -> Target
where
Self: Sized;
fn create(
engine: &mut Engine,
content: &Content,
styles: StyleChain,
) -> SourceResult<Self>
where
Self: Sized;
}
impl Sealed for PagedDocument {
fn target() -> Target {
Target::Paged
}
fn create(
engine: &mut Engine,
content: &Content,
styles: StyleChain,
) -> SourceResult<Self> {
typst_layout::layout_document(engine, content, styles)
}
}
impl Sealed for HtmlDocument {
fn target() -> Target {
Target::Html
}
fn create(
engine: &mut Engine,
content: &Content,
styles: StyleChain,
) -> SourceResult<Self> {
typst_html::html_document(engine, content, styles)
}
}
}
/// Provides ways to construct a [`Library`].
pub trait LibraryExt {
/// Creates the default library.
fn default() -> Library;
/// Creates a builder for configuring a library.
fn builder() -> LibraryBuilder;
}
impl LibraryExt for Library {
fn default() -> Library {
Self::builder().build()
}
fn builder() -> LibraryBuilder {
LibraryBuilder::from_routines(&ROUTINES)
}
}
/// 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 static ROUTINES: LazyLock<Routines> = LazyLock::new(|| Routines {
rules: {
let mut rules = NativeRuleMap::new();
typst_layout::register(&mut rules);
typst_html::register(&mut rules);
rules
},
eval_string: typst_eval::eval_string,
eval_closure: typst_eval::eval_closure,
realize: typst_realize::realize,
layout_frame: typst_layout::layout_frame,
html_module: typst_html::module,
html_span_filled: typst_html::html_span_filled,
});
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/build.rs | crates/typst-cli/build.rs | use std::env;
use std::fs::{File, create_dir_all};
use std::path::Path;
use clap::{CommandFactory, ValueEnum};
use clap_complete::{Shell, generate_to};
use clap_mangen::Man;
#[path = "src/args.rs"]
#[allow(dead_code)]
mod args;
fn main() {
// https://stackoverflow.com/a/51311222/11494565
println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap());
println!("cargo:rerun-if-env-changed=GEN_ARTIFACTS");
if let Some(dir) = env::var_os("GEN_ARTIFACTS") {
let out = &Path::new(&dir);
create_dir_all(out).unwrap();
let cmd = &mut args::CliArguments::command();
Man::new(cmd.clone())
.render(&mut File::create(out.join("typst.1")).unwrap())
.unwrap();
for subcmd in cmd.get_subcommands() {
let name = format!("typst-{}", subcmd.get_name());
Man::new(subcmd.clone().name(&name))
.render(&mut File::create(out.join(format!("{name}.1"))).unwrap())
.unwrap();
}
for shell in Shell::value_variants() {
generate_to(*shell, cmd, "typst", out).unwrap();
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/timings.rs | crates/typst-cli/src/timings.rs | use std::fs::File;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use typst::World;
use typst::diag::{HintedStrResult, bail};
use typst::syntax::Span;
use crate::args::{CliArguments, Command};
use crate::world::SystemWorld;
/// Allows to record timings of function executions.
pub struct Timer {
/// Where to save the recorded timings of each compilation step.
path: Option<PathBuf>,
/// The current watch iteration.
index: usize,
}
impl Timer {
/// Initializes the timing system and returns a timer that can be used to
/// record timings for a specific function invocation.
pub fn new(args: &CliArguments) -> Timer {
let record = match &args.command {
Command::Compile(command) => command.args.timings.clone(),
Command::Watch(command) => command.args.timings.clone(),
_ => None,
};
// Enable event collection.
if record.is_some() {
typst_timing::enable();
}
let path =
record.map(|path| path.unwrap_or_else(|| PathBuf::from("record-{n}.json")));
Timer { path, index: 0 }
}
/// Records all timings in `f` and writes them to disk.
pub fn record<T>(
&mut self,
world: &mut SystemWorld,
f: impl FnOnce(&mut SystemWorld) -> T,
) -> HintedStrResult<T> {
let Some(path) = &self.path else {
return Ok(f(world));
};
typst_timing::clear();
let string = path.to_str().unwrap_or_default();
let numbered = string.contains("{n}");
if !numbered && self.index > 0 {
bail!("cannot export multiple recordings without `{{n}}` in path");
}
let storage;
let path = if numbered {
storage = string.replace("{n}", &self.index.to_string());
Path::new(&storage)
} else {
path.as_path()
};
let output = f(world);
self.index += 1;
let file =
File::create(path).map_err(|e| format!("failed to create file: {e}"))?;
let writer = BufWriter::with_capacity(1 << 20, file);
typst_timing::export_json(writer, |span| {
resolve_span(world, Span::from_raw(span))
.unwrap_or_else(|| ("unknown".to_string(), 0))
})?;
Ok(output)
}
}
/// Turns a span into a (file, line) pair.
fn resolve_span(world: &SystemWorld, span: Span) -> Option<(String, u32)> {
let id = span.id()?;
let source = world.source(id).ok()?;
let range = source.range(span)?;
let line = source.lines().byte_to_line(range.start)?;
Some((format!("{id:?}"), line as u32 + 1))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/download.rs | crates/typst-cli/src/download.rs | use std::fmt::Display;
use std::io;
use std::io::Write;
use std::time::{Duration, Instant};
use codespan_reporting::term;
use codespan_reporting::term::termcolor::WriteColor;
use typst::utils::format_duration;
use typst_kit::download::{DownloadState, Downloader, Progress};
use crate::ARGS;
use crate::terminal::{self, TermOut};
/// Prints download progress by writing `downloading {0}` followed by repeatedly
/// updating the last terminal line.
pub struct PrintDownload<T>(pub T);
impl<T: Display> Progress for PrintDownload<T> {
fn print_start(&mut self) {
// Print that a package downloading is happening.
let styles = term::Styles::default();
let mut out = terminal::out();
let _ = out.set_color(&styles.header_help);
let _ = write!(out, "downloading");
let _ = out.reset();
let _ = writeln!(out, " {}", self.0);
}
fn print_progress(&mut self, state: &DownloadState) {
let mut out = terminal::out();
let _ = out.clear_last_line();
let _ = display_download_progress(&mut out, state);
}
fn print_finish(&mut self, state: &DownloadState) {
let mut out = terminal::out();
let _ = display_download_progress(&mut out, state);
let _ = writeln!(out);
}
}
/// Returns a new downloader.
pub fn downloader() -> Downloader {
let user_agent = format!("typst/{}", typst::utils::version().raw());
match ARGS.cert.clone() {
Some(cert) => Downloader::with_path(user_agent, cert),
None => Downloader::new(user_agent),
}
}
/// Compile and format several download statistics and make and attempt at
/// displaying them on standard error.
pub fn display_download_progress(
out: &mut TermOut,
state: &DownloadState,
) -> io::Result<()> {
let sum: usize = state.bytes_per_second.iter().sum();
let len = state.bytes_per_second.len();
let speed = if len > 0 { sum / len } else { state.content_len.unwrap_or(0) };
let total_downloaded = as_bytes_unit(state.total_downloaded);
let speed_h = as_throughput_unit(speed);
let elapsed = Instant::now().saturating_duration_since(state.start_time);
match state.content_len {
Some(content_len) => {
let percent = (state.total_downloaded as f64 / content_len as f64) * 100.;
let remaining = content_len - state.total_downloaded;
let download_size = as_bytes_unit(content_len);
let eta = Duration::from_secs(if speed == 0 {
0
} else {
(remaining / speed) as u64
});
writeln!(
out,
"{total_downloaded} / {download_size} ({percent:3.0} %) \
{speed_h} in {elapsed} ETA: {eta}",
elapsed = format_duration(elapsed),
eta = format_duration(eta),
)?;
}
None => writeln!(
out,
"Total downloaded: {total_downloaded} \
Speed: {speed_h} \
Elapsed: {elapsed}",
elapsed = format_duration(elapsed),
)?,
};
Ok(())
}
/// Format a given size as a unit of time. Setting `include_suffix` to true
/// appends a '/s' (per second) suffix.
fn as_bytes_unit(size: usize) -> String {
const KI: f64 = 1024.0;
const MI: f64 = KI * KI;
const GI: f64 = KI * KI * KI;
let size = size as f64;
if size >= GI {
format!("{:5.1} GiB", size / GI)
} else if size >= MI {
format!("{:5.1} MiB", size / MI)
} else if size >= KI {
format!("{:5.1} KiB", size / KI)
} else {
format!("{size:3} B")
}
}
fn as_throughput_unit(size: usize) -> String {
as_bytes_unit(size) + "/s"
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/world.rs | crates/typst-cli/src/world.rs | use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, OnceLock};
use std::{fmt, fs, io, mem};
use chrono::{DateTime, Datelike, FixedOffset, Local, Utc};
use ecow::{EcoString, eco_format};
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime, Dict, IntoValue};
use typst::syntax::{FileId, Lines, Source, VirtualPath};
use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, LibraryExt, World};
use typst_kit::fonts::Fonts;
use typst_kit::package::PackageStorage;
use typst_timing::timed;
use crate::args::{Feature, FontArgs, Input, ProcessArgs, WorldArgs};
use crate::download::PrintDownload;
use crate::package;
/// Static `FileId` allocated for stdin.
/// This is to ensure that a file is read in the correct way.
static STDIN_ID: LazyLock<FileId> =
LazyLock::new(|| FileId::new_fake(VirtualPath::new("<stdin>")));
/// Static `FileId` allocated for empty/no input at all.
/// This is to ensure that we can create a [SystemWorld] based on no main file or stdin at all.
static EMPTY_ID: LazyLock<FileId> =
LazyLock::new(|| FileId::new_fake(VirtualPath::new("<empty>")));
/// A world that provides access to the operating system.
pub struct SystemWorld {
/// The working directory.
workdir: Option<PathBuf>,
/// The root relative to which absolute paths are resolved.
root: PathBuf,
/// The input path.
main: FileId,
/// Typst's standard library.
library: LazyHash<Library>,
/// Metadata about discovered fonts and lazily loaded fonts.
fonts: LazyLock<Fonts, Box<dyn Fn() -> Fonts + Send + Sync>>,
/// Maps file ids to source files and buffers.
slots: Mutex<FxHashMap<FileId, FileSlot>>,
/// Holds information about where packages are stored.
package_storage: PackageStorage,
/// The current datetime if requested. This is stored here to ensure it is
/// always the same within one compilation.
/// Reset between compilations if not [`Now::Fixed`].
now: Now,
}
impl SystemWorld {
/// Create a new system world.
pub fn new(
input: Option<&Input>,
world_args: &'static WorldArgs,
process_args: &ProcessArgs,
) -> Result<Self, WorldCreationError> {
// Set up the thread pool.
if let Some(jobs) = process_args.jobs {
rayon::ThreadPoolBuilder::new()
.num_threads(jobs)
.use_current_thread()
.build_global()
.ok();
}
// Resolve the system-global input path.
let input_path = match input {
Some(Input::Path(path)) => {
Some(path.canonicalize().map_err(|err| match err.kind() {
io::ErrorKind::NotFound => {
WorldCreationError::InputNotFound(path.clone())
}
_ => WorldCreationError::Io(err),
})?)
}
_ => None,
};
// Resolve the system-global root directory.
let root = {
let path = world_args
.root
.as_deref()
.or_else(|| input_path.as_deref().and_then(|i| i.parent()))
.unwrap_or(Path::new("."));
path.canonicalize().map_err(|err| match err.kind() {
io::ErrorKind::NotFound => {
WorldCreationError::RootNotFound(path.to_path_buf())
}
_ => WorldCreationError::Io(err),
})?
};
let main = if let Some(path) = &input_path {
// Resolve the virtual path of the main file within the project root.
let main_path = VirtualPath::within_root(path, &root)
.ok_or(WorldCreationError::InputOutsideRoot)?;
FileId::new(None, main_path)
} else if matches!(input, Some(Input::Stdin)) {
// Return the special id of STDIN.
*STDIN_ID
} else {
// Return the special id of EMPTY/no input at all otherwise.
*EMPTY_ID
};
let library = {
// Convert the input pairs to a dictionary.
let inputs: Dict = world_args
.inputs
.iter()
.map(|(k, v)| (k.as_str().into(), v.as_str().into_value()))
.collect();
let features = process_args
.features
.iter()
.map(|&feature| match feature {
Feature::Html => typst::Feature::Html,
Feature::A11yExtras => typst::Feature::A11yExtras,
})
.collect();
Library::builder().with_inputs(inputs).with_features(features).build()
};
let now = match world_args.creation_timestamp {
Some(time) => Now::Fixed(time),
None => Now::System(OnceLock::new()),
};
Ok(Self {
workdir: std::env::current_dir().ok(),
root,
main,
library: LazyHash::new(library),
fonts: LazyLock::new(Box::new(|| scan_fonts(&world_args.font))),
slots: Mutex::new(FxHashMap::default()),
package_storage: package::storage(&world_args.package),
now,
})
}
/// The id of the main source file.
pub fn main(&self) -> FileId {
self.main
}
/// The root relative to which absolute paths are resolved.
pub fn root(&self) -> &Path {
&self.root
}
/// The current working directory.
pub fn workdir(&self) -> &Path {
self.workdir.as_deref().unwrap_or(Path::new("."))
}
/// Return all paths the last compilation depended on.
pub fn dependencies(&mut self) -> impl Iterator<Item = PathBuf> + '_ {
self.slots
.get_mut()
.values()
.filter(|slot| slot.accessed())
.filter_map(|slot| {
system_path(&self.root, slot.id, &self.package_storage).ok()
})
}
/// Reset the compilation state in preparation of a new compilation.
pub fn reset(&mut self) {
#[allow(clippy::iter_over_hash_type, reason = "order does not matter")]
for slot in self.slots.get_mut().values_mut() {
slot.reset();
}
if let Now::System(time_lock) = &mut self.now {
time_lock.take();
}
}
/// Lookup line metadata for a file by id.
#[track_caller]
pub fn lookup(&self, id: FileId) -> Lines<String> {
self.slot(id, |slot| {
if let Some(source) = slot.source.get() {
let source = source.as_ref().expect("file is not valid");
source.lines().clone()
} else if let Some(bytes) = slot.file.get() {
let bytes = bytes.as_ref().expect("file is not valid");
Lines::try_from(bytes).expect("file is not valid UTF-8")
} else {
panic!("file id does not point to any source file");
}
})
}
/// Forcibly scan fonts instead of doing it lazily upon the first access.
///
/// Does nothing if the fonts were already scanned.
pub fn scan_fonts(&mut self) {
LazyLock::force(&self.fonts);
}
}
impl World for SystemWorld {
fn library(&self) -> &LazyHash<Library> {
&self.library
}
fn book(&self) -> &LazyHash<FontBook> {
&self.fonts.book
}
fn main(&self) -> FileId {
self.main
}
fn source(&self, id: FileId) -> FileResult<Source> {
self.slot(id, |slot| slot.source(&self.root, &self.package_storage))
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
self.slot(id, |slot| slot.file(&self.root, &self.package_storage))
}
fn font(&self, index: usize) -> Option<Font> {
// comemo's validation may invoke this function with an invalid index.
// This is impossible in typst-cli but possible if a custom tool mutates
// the fonts.
self.fonts.slots.get(index)?.get()
}
fn today(&self, offset: Option<i64>) -> Option<Datetime> {
let now = match &self.now {
Now::Fixed(time) => time,
Now::System(time) => time.get_or_init(Utc::now),
};
// The time with the specified UTC offset, or within the local time zone.
let with_offset = match offset {
None => now.with_timezone(&Local).fixed_offset(),
Some(hours) => {
let seconds = i32::try_from(hours).ok()?.checked_mul(3600)?;
now.with_timezone(&FixedOffset::east_opt(seconds)?)
}
};
Datetime::from_ymd(
with_offset.year(),
with_offset.month().try_into().ok()?,
with_offset.day().try_into().ok()?,
)
}
}
impl SystemWorld {
/// Access the canonical slot for the given file id.
fn slot<F, T>(&self, id: FileId, f: F) -> T
where
F: FnOnce(&mut FileSlot) -> T,
{
let mut map = self.slots.lock();
f(map.entry(id).or_insert_with(|| FileSlot::new(id)))
}
}
/// Holds the processed data for a file ID.
///
/// Both fields can be populated if the file is both imported and read().
struct FileSlot {
/// The slot's file id.
id: FileId,
/// The lazily loaded and incrementally updated source file.
source: SlotCell<Source>,
/// The lazily loaded raw byte buffer.
file: SlotCell<Bytes>,
}
impl FileSlot {
/// Create a new file slot.
fn new(id: FileId) -> Self {
Self { id, file: SlotCell::new(), source: SlotCell::new() }
}
/// Whether the file was accessed in the ongoing compilation.
fn accessed(&self) -> bool {
self.source.accessed() || self.file.accessed()
}
/// Marks the file as not yet accessed in preparation of the next
/// compilation.
fn reset(&mut self) {
self.source.reset();
self.file.reset();
}
/// Retrieve the source for this file.
fn source(
&mut self,
project_root: &Path,
package_storage: &PackageStorage,
) -> FileResult<Source> {
self.source.get_or_init(
|| read(self.id, project_root, package_storage),
|data, prev| {
let text = decode_utf8(&data)?;
if let Some(mut prev) = prev {
prev.replace(text);
Ok(prev)
} else {
Ok(Source::new(self.id, text.into()))
}
},
)
}
/// Retrieve the file's bytes.
fn file(
&mut self,
project_root: &Path,
package_storage: &PackageStorage,
) -> FileResult<Bytes> {
self.file.get_or_init(
|| read(self.id, project_root, package_storage),
|data, _| Ok(Bytes::new(data)),
)
}
}
/// Lazily processes data for a file.
struct SlotCell<T> {
/// The processed data.
data: Option<FileResult<T>>,
/// A hash of the raw file contents / access error.
fingerprint: u128,
/// Whether the slot has been accessed in the current compilation.
accessed: bool,
}
impl<T: Clone> SlotCell<T> {
/// Creates a new, empty cell.
fn new() -> Self {
Self { data: None, fingerprint: 0, accessed: false }
}
/// Whether the cell was accessed in the ongoing compilation.
fn accessed(&self) -> bool {
self.accessed
}
/// Marks the cell as not yet accessed in preparation of the next
/// compilation.
fn reset(&mut self) {
self.accessed = false;
}
/// Gets the contents of the cell.
fn get(&self) -> Option<&FileResult<T>> {
self.data.as_ref()
}
/// Gets the contents of the cell or initialize them.
fn get_or_init(
&mut self,
load: impl FnOnce() -> FileResult<Vec<u8>>,
f: impl FnOnce(Vec<u8>, Option<T>) -> FileResult<T>,
) -> FileResult<T> {
// If we accessed the file already in this compilation, retrieve it.
if mem::replace(&mut self.accessed, true)
&& let Some(data) = &self.data
{
return data.clone();
}
// Read and hash the file.
let result = timed!("loading file", load());
let fingerprint = timed!("hashing file", typst::utils::hash128(&result));
// If the file contents didn't change, yield the old processed data.
if mem::replace(&mut self.fingerprint, fingerprint) == fingerprint
&& let Some(data) = &self.data
{
return data.clone();
}
let prev = self.data.take().and_then(Result::ok);
let value = result.and_then(|data| f(data, prev));
self.data = Some(value.clone());
value
}
}
/// Discovers the fonts as specified by the CLI flags.
#[typst_macros::time(name = "scan fonts")]
fn scan_fonts(args: &FontArgs) -> Fonts {
let mut fonts = Fonts::searcher();
fonts.include_system_fonts(!args.ignore_system_fonts);
#[cfg(feature = "embed-fonts")]
fonts.include_embedded_fonts(!args.ignore_embedded_fonts);
fonts.search_with(&args.font_paths)
}
/// Resolves the path of a file id on the system, downloading a package if
/// necessary.
fn system_path(
project_root: &Path,
id: FileId,
package_storage: &PackageStorage,
) -> FileResult<PathBuf> {
// Determine the root path relative to which the file path
// will be resolved.
let buf;
let mut root = project_root;
if let Some(spec) = id.package() {
buf = package_storage.prepare_package(spec, &mut PrintDownload(&spec))?;
root = &buf;
}
// Join the path to the root. If it tries to escape, deny
// access. Note: It can still escape via symlinks.
id.vpath().resolve(root).ok_or(FileError::AccessDenied)
}
/// Reads a file from a `FileId`.
///
/// - If the ID represents stdin it will read from standard input.
/// - If it represents empty/no input at all it will return an empty vector.
/// - Otherwise, it gets the file path of the ID and reads the file from disk.
fn read(
id: FileId,
project_root: &Path,
package_storage: &PackageStorage,
) -> FileResult<Vec<u8>> {
match id {
id if id == *EMPTY_ID => Ok(Vec::new()),
id if id == *STDIN_ID => read_from_stdin(),
_ => read_from_disk(&system_path(project_root, id, package_storage)?),
}
}
/// Read a file from disk.
fn read_from_disk(path: &Path) -> FileResult<Vec<u8>> {
let f = |e| FileError::from_io(e, path);
if fs::metadata(path).map_err(f)?.is_dir() {
Err(FileError::IsDirectory)
} else {
fs::read(path).map_err(f)
}
}
/// Read from stdin.
fn read_from_stdin() -> FileResult<Vec<u8>> {
let mut buf = Vec::new();
let result = io::stdin().read_to_end(&mut buf);
match result {
Ok(_) => (),
Err(err) if err.kind() == io::ErrorKind::BrokenPipe => (),
Err(err) => return Err(FileError::from_io(err, Path::new("<stdin>"))),
}
Ok(buf)
}
/// Decode UTF-8 with an optional BOM.
fn decode_utf8(buf: &[u8]) -> FileResult<&str> {
// Remove UTF-8 BOM.
Ok(std::str::from_utf8(buf.strip_prefix(b"\xef\xbb\xbf").unwrap_or(buf))?)
}
/// The current date and time.
enum Now {
/// The date and time if the environment `SOURCE_DATE_EPOCH` is set.
/// Used for reproducible builds.
Fixed(DateTime<Utc>),
/// The current date and time if the time is not externally fixed.
System(OnceLock<DateTime<Utc>>),
}
/// An error that occurs during world construction.
#[derive(Debug)]
pub enum WorldCreationError {
/// The input file does not appear to exist.
InputNotFound(PathBuf),
/// The input file is not contained within the root folder.
InputOutsideRoot,
/// The root directory does not appear to exist.
RootNotFound(PathBuf),
/// Another type of I/O error.
Io(io::Error),
}
impl fmt::Display for WorldCreationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WorldCreationError::InputNotFound(path) => {
write!(f, "input file not found (searched at {})", path.display())
}
WorldCreationError::InputOutsideRoot => {
write!(f, "source file must be contained in project root")
}
WorldCreationError::RootNotFound(path) => {
write!(f, "root directory not found (searched at {})", path.display())
}
WorldCreationError::Io(err) => write!(f, "{err}"),
}
}
}
impl From<WorldCreationError> for EcoString {
fn from(err: WorldCreationError) -> Self {
eco_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-cli/src/update.rs | crates/typst-cli/src/update.rs | use std::io::{Cursor, Read, Write};
use std::path::PathBuf;
use std::{env, fs};
use ecow::eco_format;
use semver::Version;
use serde::Deserialize;
use tempfile::NamedTempFile;
use typst::diag::{StrResult, bail};
use typst_kit::download::Downloader;
use xz2::bufread::XzDecoder;
use zip::ZipArchive;
use crate::args::UpdateCommand;
use crate::download::{self, PrintDownload};
const TYPST_GITHUB_ORG: &str = "typst";
const TYPST_REPO: &str = "typst";
/// Determine the asset to download based on the target platform.
///
/// See `.github/workflows/release.yml` for the list of prebuilt assets.
macro_rules! determine_asset {
() => {
// For some platforms, only some targets are prebuilt in the release.
determine_asset!(__impl: {
"x86_64-unknown-linux-gnu" => "x86_64-unknown-linux-musl",
"aarch64-unknown-linux-gnu" => "aarch64-unknown-linux-musl",
"armv7-unknown-linux-gnueabi" => "armv7-unknown-linux-musleabi",
"riscv64gc-unknown-linux-musl" => "riscv64gc-unknown-linux-gnu",
})
};
(__impl: { $($origin:literal => $target:literal),* $(,)? }) => {
match env!("TARGET") {
$($origin => concat!("typst-", $target),)*
_ => concat!("typst-", env!("TARGET")),
}
};
}
/// Self update the Typst CLI binary.
///
/// Fetches a target release or the latest release (if no version was specified)
/// from GitHub, unpacks it and self replaces the current binary with the
/// pre-compiled asset from the downloaded release.
pub fn update(command: &UpdateCommand) -> StrResult<()> {
if let Some(ref version) = command.version {
let current_tag = typst::utils::version().raw().parse().unwrap();
if version < &Version::new(0, 8, 0) {
eprintln!(
"note: versions older than 0.8.0 will not have \
the update command available."
);
}
if !command.force && version < ¤t_tag {
bail!(
"downgrading requires the --force flag: \
`typst update <VERSION> --force`",
);
}
}
// Full path to the backup file.
let backup_path = command.backup_path.clone().map(Ok).unwrap_or_else(backup_path)?;
if let Some(backup_dir) = backup_path.parent() {
fs::create_dir_all(backup_dir)
.map_err(|err| eco_format!("failed to create backup directory ({err})"))?;
}
if command.revert {
if !backup_path.exists() {
bail!(
"unable to revert, no backup found (searched at {})",
backup_path.display(),
);
}
return self_replace::self_replace(&backup_path)
.and_then(|_| fs::remove_file(&backup_path))
.map_err(|err| eco_format!("failed to revert to backup ({err})"));
}
let current_exe = env::current_exe().map_err(|err| {
eco_format!("failed to locate path of the running executable ({err})")
})?;
fs::copy(current_exe, &backup_path)
.map_err(|err| eco_format!("failed to create backup ({err})"))?;
let downloader = download::downloader();
let release = Release::from_tag(command.version.as_ref(), &downloader)?;
if !update_needed(&release)? && !command.force {
eprintln!("Already up-to-date.");
return Ok(());
}
let binary_data = release.download_binary(determine_asset!(), &downloader)?;
let mut temp_exe = NamedTempFile::new()
.map_err(|err| eco_format!("failed to create temporary file ({err})"))?;
temp_exe
.write_all(&binary_data)
.map_err(|err| eco_format!("failed to write binary data ({err})"))?;
self_replace::self_replace(&temp_exe).map_err(|err| {
fs::remove_file(&temp_exe).ok();
eco_format!("failed to self-replace running executable ({err})")
})
}
/// Assets belonging to a GitHub release.
///
/// Primarily used to download pre-compiled Typst CLI binaries.
#[derive(Debug, Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// A GitHub release.
#[derive(Debug, Deserialize)]
struct Release {
tag_name: String,
assets: Vec<Asset>,
}
impl Release {
/// Download the target release, or latest if version is `None`, from the
/// Typst repository.
pub fn from_tag(
tag: Option<&Version>,
downloader: &Downloader,
) -> StrResult<Release> {
let url = match tag {
Some(tag) => format!(
"https://api.github.com/repos/{TYPST_GITHUB_ORG}/{TYPST_REPO}/releases/tags/v{tag}"
),
None => format!(
"https://api.github.com/repos/{TYPST_GITHUB_ORG}/{TYPST_REPO}/releases/latest",
),
};
match downloader.download(&url) {
Ok(response) => response.into_json().map_err(|err| {
eco_format!("failed to parse release information ({err})")
}),
Err(ureq::Error::Status(404, _)) => {
bail!("release not found (searched at {url})")
}
Err(err) => bail!("failed to download release ({err})"),
}
}
/// Download the binary from a given [`Release`] and select the
/// corresponding asset for this target platform, returning the raw binary
/// data.
pub fn download_binary(
&self,
asset_name: &str,
downloader: &Downloader,
) -> StrResult<Vec<u8>> {
let asset = self.assets.iter().find(|a| a.name.starts_with(asset_name)).ok_or(
eco_format!(
"could not find prebuilt binary `{}` for your platform",
asset_name
),
)?;
let data = match downloader.download_with_progress(
&asset.browser_download_url,
&mut PrintDownload("release"),
) {
Ok(data) => data,
Err(ureq::Error::Status(404, _)) => {
bail!("asset not found (searched for {})", asset.name);
}
Err(err) => bail!("failed to download asset ({err})"),
};
if asset_name.contains("windows") {
extract_binary_from_zip(&data, asset_name)
} else {
extract_binary_from_tar_xz(&data)
}
}
}
/// Extract the Typst binary from a ZIP archive.
fn extract_binary_from_zip(data: &[u8], asset_name: &str) -> StrResult<Vec<u8>> {
let mut archive = ZipArchive::new(Cursor::new(data))
.map_err(|err| eco_format!("failed to extract ZIP archive ({err})"))?;
let mut file =
archive.by_name(&format!("{asset_name}/typst.exe")).map_err(|err| {
eco_format!("failed to extract Typst binary from ZIP archive ({err})")
})?;
let mut buffer = vec![];
file.read_to_end(&mut buffer).map_err(|err| {
eco_format!("failed to read binary data from ZIP archive ({err})")
})?;
Ok(buffer)
}
/// Extract the Typst binary from a `.tar.xz` archive.
fn extract_binary_from_tar_xz(data: &[u8]) -> StrResult<Vec<u8>> {
let mut archive = tar::Archive::new(XzDecoder::new(Cursor::new(data)));
let mut file = archive
.entries()
.map_err(|err| eco_format!("failed to extract tar.xz archive ({err})"))?
.filter_map(Result::ok)
.find(|e| e.path().unwrap_or_default().ends_with("typst"))
.ok_or("tar.xz archive did not contain Typst binary")?;
let mut buffer = vec![];
file.read_to_end(&mut buffer).map_err(|err| {
eco_format!("failed to read binary data from tar.xz archive ({err})")
})?;
Ok(buffer)
}
/// Compare the release version to the CLI version to see if an update is needed.
fn update_needed(release: &Release) -> StrResult<bool> {
let current_tag: Version = typst::utils::version().raw().parse().unwrap();
let new_tag: Version = release
.tag_name
.strip_prefix('v')
.unwrap_or(&release.tag_name)
.parse()
.map_err(|_| "release tag not in semver format")?;
Ok(new_tag > current_tag)
}
/// Path to a potential backup file in the system.
///
/// The backup will be placed as `typst_backup.part` in one of the following
/// directories, depending on the platform:
/// - `$XDG_STATE_HOME` or `~/.local/state` on Linux
/// - `$XDG_DATA_HOME` or `~/.local/share` if the above path isn't available
/// - `~/Library/Application Support` on macOS
/// - `%APPDATA%` on Windows
///
/// If a custom backup path is provided via the environment variable
/// `TYPST_UPDATE_BACKUP_PATH`, it will be used instead of the default
/// directories determined by the platform. In that case, this function
/// shouldn't be called.
fn backup_path() -> StrResult<PathBuf> {
#[cfg(target_os = "linux")]
let root_backup_dir = dirs::state_dir()
.or_else(dirs::data_dir)
.ok_or("unable to locate local data or state directory")?;
#[cfg(not(target_os = "linux"))]
let root_backup_dir =
dirs::data_dir().ok_or("unable to locate local data directory")?;
Ok(root_backup_dir.join("typst").join("typst_backup.part"))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/compile.rs | crates/typst-cli/src/compile.rs | use std::ffi::OsStr;
use std::path::Path;
use chrono::{DateTime, Datelike, Timelike, Utc};
use codespan_reporting::diagnostic::{Diagnostic, Label};
use codespan_reporting::term;
use ecow::eco_format;
use parking_lot::RwLock;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use typst::WorldExt;
use typst::diag::{
At, HintedStrResult, HintedString, Severity, SourceDiagnostic, SourceResult,
StrResult, Warned, bail,
};
use typst::foundations::{Datetime, Smart};
use typst::layout::{Page, PageRanges, PagedDocument};
use typst::syntax::{FileId, Lines, Span};
use typst_html::HtmlDocument;
use typst_pdf::{PdfOptions, PdfStandards, Timestamp};
use crate::args::{
CompileArgs, CompileCommand, DepsFormat, DiagnosticFormat, Input, Output,
OutputFormat, PdfStandard, WatchCommand,
};
use crate::deps::write_deps;
#[cfg(feature = "http-server")]
use crate::server::HtmlServer;
use crate::timings::Timer;
use crate::watch::Status;
use crate::world::SystemWorld;
use crate::{set_failed, terminal};
type CodespanResult<T> = Result<T, CodespanError>;
type CodespanError = codespan_reporting::files::Error;
/// Execute a compilation command.
pub fn compile(
timer: &mut Timer,
command: &'static CompileCommand,
) -> HintedStrResult<()> {
let mut config = CompileConfig::new(command)?;
let mut world = SystemWorld::new(
Some(&command.args.input),
&command.args.world,
&command.args.process,
)
.map_err(|err| eco_format!("{err}"))?;
timer.record(&mut world, |world| compile_once(world, &mut config))?
}
/// A preprocessed `CompileCommand`.
pub struct CompileConfig {
/// Static warnings to emit after compilation.
pub warnings: Vec<HintedString>,
/// Whether we are watching.
pub watching: bool,
/// Path to input Typst file or stdin.
pub input: Input,
/// Path to output file (PDF, PNG, SVG, or HTML).
pub output: Output,
/// The format of the output file.
pub output_format: OutputFormat,
/// Which pages to export.
pub pages: Option<PageRanges>,
/// The document's creation date formatted as a UNIX timestamp, with UTC suffix.
pub creation_timestamp: Option<DateTime<Utc>>,
/// The format to emit diagnostics in.
pub diagnostic_format: DiagnosticFormat,
/// Opens the output file with the default viewer or a specific program after
/// compilation.
pub open: Option<Option<String>>,
/// A list of standards the PDF should conform to.
pub pdf_standards: PdfStandards,
/// Whether to write PDF (accessibility) tags.
pub tagged: bool,
/// A destination to write a list of dependencies to.
pub deps: Option<Output>,
/// The format to use for dependencies.
pub deps_format: DepsFormat,
/// The PPI (pixels per inch) to use for PNG export.
pub ppi: f32,
/// The export cache for images, used for caching output files in `typst
/// watch` sessions with images.
pub export_cache: ExportCache,
/// Server for `typst watch` to HTML.
#[cfg(feature = "http-server")]
pub server: Option<HtmlServer>,
}
impl CompileConfig {
/// Preprocess a `CompileCommand`, producing a compilation config.
pub fn new(command: &CompileCommand) -> HintedStrResult<Self> {
Self::new_impl(&command.args, None)
}
/// Preprocess a `WatchCommand`, producing a compilation config.
pub fn watching(command: &WatchCommand) -> HintedStrResult<Self> {
Self::new_impl(&command.args, Some(command))
}
/// The shared implementation of [`CompileConfig::new`] and
/// [`CompileConfig::watching`].
fn new_impl(
args: &CompileArgs,
watch: Option<&WatchCommand>,
) -> HintedStrResult<Self> {
let mut warnings = Vec::new();
let input = args.input.clone();
let output_format = if let Some(specified) = args.format {
specified
} else if let Some(Output::Path(output)) = &args.output {
match output.extension() {
Some(ext) if ext.eq_ignore_ascii_case("pdf") => OutputFormat::Pdf,
Some(ext) if ext.eq_ignore_ascii_case("png") => OutputFormat::Png,
Some(ext) if ext.eq_ignore_ascii_case("svg") => OutputFormat::Svg,
Some(ext) if ext.eq_ignore_ascii_case("html") => OutputFormat::Html,
_ => bail!(
"could not infer output format for path {}.\n\
consider providing the format manually with `--format/-f`",
output.display(),
),
}
} else {
OutputFormat::Pdf
};
let output = args.output.clone().unwrap_or_else(|| {
let Input::Path(path) = &input else {
panic!("output must be specified when input is from stdin, as guarded by the CLI");
};
Output::Path(path.with_extension(
match output_format {
OutputFormat::Pdf => "pdf",
OutputFormat::Png => "png",
OutputFormat::Svg => "svg",
OutputFormat::Html => "html",
},
))
});
let pages = args.pages.as_ref().map(|export_ranges| {
PageRanges::new(export_ranges.iter().map(|r| r.0.clone()).collect())
});
let tagged = !args.no_pdf_tags && pages.is_none();
if output_format == OutputFormat::Pdf && pages.is_some() && !args.no_pdf_tags {
warnings.push(
HintedString::from("using --pages implies --no-pdf-tags").with_hints([
"the resulting PDF will be inaccessible".into(),
"add --no-pdf-tags to silence this warning".into(),
]),
);
}
if !tagged {
const ACCESSIBLE: &[(PdfStandard, &str)] = &[
(PdfStandard::A_1a, "PDF/A-1a"),
(PdfStandard::A_2a, "PDF/A-2a"),
(PdfStandard::A_3a, "PDF/A-3a"),
(PdfStandard::UA_1, "PDF/UA-1"),
];
for (standard, name) in ACCESSIBLE {
if args.pdf_standard.contains(standard) {
if args.no_pdf_tags {
bail!("cannot disable PDF tags when exporting a {name} document");
} else {
bail!(
"cannot disable PDF tags when exporting a {name} document";
hint: "using --pages implies --no-pdf-tags";
);
}
}
}
}
let pdf_standards = PdfStandards::new(
&args.pdf_standard.iter().copied().map(Into::into).collect::<Vec<_>>(),
)?;
#[cfg(feature = "http-server")]
let server = match watch {
Some(command)
if output_format == OutputFormat::Html && !command.server.no_serve =>
{
Some(HtmlServer::new(&input, &command.server)?)
}
_ => None,
};
let mut deps = args.deps.clone();
let mut deps_format = args.deps_format;
if let Some(path) = &args.make_deps
&& deps.is_none()
{
deps = Some(Output::Path(path.clone()));
deps_format = DepsFormat::Make;
warnings.push(
"--make-deps is deprecated, use --deps and --deps-format instead".into(),
);
}
match (&output, &deps, watch) {
(Output::Stdout, _, Some(_)) => {
bail!("cannot write document to stdout in watch mode");
}
(_, Some(Output::Stdout), Some(_)) => {
bail!("cannot write dependencies to stdout in watch mode")
}
(Output::Stdout, Some(Output::Stdout), _) => {
bail!("cannot write both output and dependencies to stdout")
}
_ => {}
}
Ok(Self {
warnings,
watching: watch.is_some(),
input,
output,
output_format,
pages,
pdf_standards,
tagged,
creation_timestamp: args.world.creation_timestamp,
ppi: args.ppi,
diagnostic_format: args.process.diagnostic_format,
open: args.open.clone(),
export_cache: ExportCache::new(),
deps,
deps_format,
#[cfg(feature = "http-server")]
server,
})
}
}
/// Compile a single time.
///
/// Returns whether it compiled without errors.
#[typst_macros::time(name = "compile once")]
pub fn compile_once(
world: &mut SystemWorld,
config: &mut CompileConfig,
) -> HintedStrResult<()> {
let start = std::time::Instant::now();
if config.watching {
Status::Compiling.print(config).unwrap();
}
let Warned { output, mut warnings } = compile_and_export(world, config);
// Add static warnings (for deprecated CLI flags and such).
for warning in config.warnings.iter() {
warnings.push(
SourceDiagnostic::warning(Span::detached(), warning.message())
.with_hints(warning.hints().iter().map(Into::into)),
);
}
match &output {
// Print success message and possibly warnings.
Ok(_) => {
let duration = start.elapsed();
if config.watching {
if warnings.is_empty() {
Status::Success(duration).print(config).unwrap();
} else {
Status::PartialSuccess(duration).print(config).unwrap();
}
}
print_diagnostics(world, &[], &warnings, config.diagnostic_format)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
open_output(config)?;
}
// Print failure message and diagnostics.
Err(errors) => {
set_failed();
if config.watching {
Status::Error.print(config).unwrap();
}
print_diagnostics(world, errors, &warnings, config.diagnostic_format)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
}
}
if let Some(dest) = &config.deps {
write_deps(world, dest, config.deps_format, output.as_deref().ok())
.map_err(|err| eco_format!("failed to create dependency file ({err})"))?;
}
Ok(())
}
/// Compile and then export the document.
fn compile_and_export(
world: &mut SystemWorld,
config: &mut CompileConfig,
) -> Warned<SourceResult<Vec<Output>>> {
match config.output_format {
OutputFormat::Html => {
let Warned { output, warnings } = typst::compile::<HtmlDocument>(world);
let result = output.and_then(|document| export_html(&document, config));
Warned {
output: result.map(|()| vec![config.output.clone()]),
warnings,
}
}
_ => {
let Warned { output, warnings } = typst::compile::<PagedDocument>(world);
let result = output.and_then(|document| export_paged(&document, config));
Warned { output: result, warnings }
}
}
}
/// Export to HTML.
fn export_html(document: &HtmlDocument, config: &CompileConfig) -> SourceResult<()> {
let html = typst_html::html(document)?;
let result = config.output.write(html.as_bytes());
#[cfg(feature = "http-server")]
if let Some(server) = &config.server {
server.update(html);
}
result
.map_err(|err| eco_format!("failed to write HTML file ({err})"))
.at(Span::detached())
}
/// Export to a paged target format.
fn export_paged(
document: &PagedDocument,
config: &CompileConfig,
) -> SourceResult<Vec<Output>> {
match config.output_format {
OutputFormat::Pdf => {
export_pdf(document, config).map(|()| vec![config.output.clone()])
}
OutputFormat::Png => {
export_image(document, config, ImageExportFormat::Png).at(Span::detached())
}
OutputFormat::Svg => {
export_image(document, config, ImageExportFormat::Svg).at(Span::detached())
}
OutputFormat::Html => unreachable!(),
}
}
/// Export to a PDF.
fn export_pdf(document: &PagedDocument, config: &CompileConfig) -> SourceResult<()> {
// If the timestamp is provided through the CLI, use UTC suffix,
// else, use the current local time and timezone.
let timestamp = match config.creation_timestamp {
Some(timestamp) => convert_datetime(timestamp).map(Timestamp::new_utc),
None => {
let local_datetime = chrono::Local::now();
convert_datetime(local_datetime).and_then(|datetime| {
Timestamp::new_local(
datetime,
local_datetime.offset().local_minus_utc() / 60,
)
})
}
};
let options = PdfOptions {
ident: Smart::Auto,
timestamp,
page_ranges: config.pages.clone(),
standards: config.pdf_standards.clone(),
tagged: config.tagged,
};
let buffer = typst_pdf::pdf(document, &options)?;
config
.output
.write(&buffer)
.map_err(|err| eco_format!("failed to write PDF file ({err})"))
.at(Span::detached())?;
Ok(())
}
/// Convert [`chrono::DateTime`] to [`Datetime`]
fn convert_datetime<Tz: chrono::TimeZone>(
date_time: chrono::DateTime<Tz>,
) -> Option<Datetime> {
Datetime::from_ymd_hms(
date_time.year(),
date_time.month().try_into().ok()?,
date_time.day().try_into().ok()?,
date_time.hour().try_into().ok()?,
date_time.minute().try_into().ok()?,
date_time.second().try_into().ok()?,
)
}
/// An image format to export in.
#[derive(Copy, Clone)]
enum ImageExportFormat {
Png,
Svg,
}
/// Export to one or multiple images.
fn export_image(
document: &PagedDocument,
config: &CompileConfig,
fmt: ImageExportFormat,
) -> StrResult<Vec<Output>> {
// Determine whether we have indexable templates in output
let can_handle_multiple = match config.output {
Output::Stdout => false,
Output::Path(ref output) => {
output_template::has_indexable_template(output.to_str().unwrap_or_default())
}
};
let exported_pages = document
.pages
.iter()
.enumerate()
.filter(|(i, _)| {
config.pages.as_ref().is_none_or(|exported_page_ranges| {
exported_page_ranges.includes_page_index(*i)
})
})
.collect::<Vec<_>>();
if !can_handle_multiple && exported_pages.len() > 1 {
let err = match config.output {
Output::Stdout => "to stdout",
Output::Path(_) => {
"without a page number template ({p}, {0p}) in the output path"
}
};
bail!("cannot export multiple images {err}");
}
// The results are collected in a `Vec<()>` which does not allocate.
exported_pages
.par_iter()
.map(|(i, page)| {
// Use output with converted path.
let output = match &config.output {
Output::Path(path) => {
let storage;
let path = if can_handle_multiple {
storage = output_template::format(
path.to_str().unwrap_or_default(),
i + 1,
document.pages.len(),
);
Path::new(&storage)
} else {
path
};
// If we are not watching, don't use the cache.
// If the frame is in the cache, skip it.
// If the file does not exist, always create it.
if config.watching
&& config.export_cache.is_cached(*i, page)
&& path.exists()
{
return Ok(Output::Path(path.to_path_buf()));
}
Output::Path(path.to_owned())
}
Output::Stdout => Output::Stdout,
};
export_image_page(config, page, &output, fmt)?;
Ok(output)
})
.collect::<StrResult<Vec<Output>>>()
}
mod output_template {
const INDEXABLE: [&str; 3] = ["{p}", "{0p}", "{n}"];
pub fn has_indexable_template(output: &str) -> bool {
INDEXABLE.iter().any(|template| output.contains(template))
}
pub fn format(output: &str, this_page: usize, total_pages: usize) -> String {
// Find the base 10 width of number `i`
fn width(i: usize) -> usize {
1 + i.checked_ilog10().unwrap_or(0) as usize
}
let other_templates = ["{t}"];
INDEXABLE.iter().chain(other_templates.iter()).fold(
output.to_string(),
|out, template| {
let replacement = match *template {
"{p}" => format!("{this_page}"),
"{0p}" | "{n}" => format!("{:01$}", this_page, width(total_pages)),
"{t}" => format!("{total_pages}"),
_ => unreachable!("unhandled template placeholder {template}"),
};
out.replace(template, replacement.as_str())
},
)
}
}
/// Export single image.
fn export_image_page(
config: &CompileConfig,
page: &Page,
output: &Output,
fmt: ImageExportFormat,
) -> StrResult<()> {
match fmt {
ImageExportFormat::Png => {
let pixmap = typst_render::render(page, config.ppi / 72.0);
let buf = pixmap
.encode_png()
.map_err(|err| eco_format!("failed to encode PNG file ({err})"))?;
output
.write(&buf)
.map_err(|err| eco_format!("failed to write PNG file ({err})"))?;
}
ImageExportFormat::Svg => {
let svg = typst_svg::svg(page);
output
.write(svg.as_bytes())
.map_err(|err| eco_format!("failed to write SVG file ({err})"))?;
}
}
Ok(())
}
/// Caches exported files so that we can avoid re-exporting them if they haven't
/// changed.
///
/// This is done by having a list of size `files.len()` that contains the hashes
/// of the last rendered frame in each file. If a new frame is inserted, this
/// will invalidate the rest of the cache, this is deliberate as to decrease the
/// complexity and memory usage of such a cache.
pub struct ExportCache {
/// The hashes of last compilation's frames.
pub cache: RwLock<Vec<u128>>,
}
impl ExportCache {
/// Creates a new export cache.
pub fn new() -> Self {
Self { cache: RwLock::new(Vec::with_capacity(32)) }
}
/// Returns true if the entry is cached and appends the new hash to the
/// cache (for the next compilation).
pub fn is_cached(&self, i: usize, page: &Page) -> bool {
let hash = typst::utils::hash128(page);
let mut cache = self.cache.upgradable_read();
if i >= cache.len() {
cache.with_upgraded(|cache| cache.push(hash));
return false;
}
cache.with_upgraded(|cache| std::mem::replace(&mut cache[i], hash) == hash)
}
}
/// Opens the output if desired.
fn open_output(config: &mut CompileConfig) -> StrResult<()> {
let Some(viewer) = config.open.take() else { return Ok(()) };
#[cfg(feature = "http-server")]
if let Some(server) = &config.server {
let url = format!("http://{}", server.addr());
return open_path(OsStr::new(&url), viewer.as_deref());
}
// Can't open stdout.
let Output::Path(path) = &config.output else { return Ok(()) };
// Some resource openers require the path to be canonicalized.
let path = path
.canonicalize()
.map_err(|err| eco_format!("failed to canonicalize path ({err})"))?;
open_path(path.as_os_str(), viewer.as_deref())
}
/// Opens the given file using:
///
/// - The default file viewer if `app` is `None`.
/// - The given viewer provided by `app` if it is `Some`.
fn open_path(path: &OsStr, viewer: Option<&str>) -> StrResult<()> {
if let Some(viewer) = viewer {
open::with_detached(path, viewer)
.map_err(|err| eco_format!("failed to open file with {} ({})", viewer, err))
} else {
open::that_detached(path).map_err(|err| {
let openers = open::commands(path)
.iter()
.map(|command| command.get_program().to_string_lossy())
.collect::<Vec<_>>()
.join(", ");
eco_format!(
"failed to open file with any of these resource openers: {} ({})",
openers,
err,
)
})
}
}
/// Print diagnostic messages to the terminal.
pub fn print_diagnostics(
world: &SystemWorld,
errors: &[SourceDiagnostic],
warnings: &[SourceDiagnostic],
diagnostic_format: DiagnosticFormat,
) -> Result<(), codespan_reporting::files::Error> {
let mut config = term::Config { tab_width: 2, ..Default::default() };
if diagnostic_format == DiagnosticFormat::Short {
config.display_style = term::DisplayStyle::Short;
}
for diagnostic in warnings.iter().chain(errors) {
let diag = match diagnostic.severity {
Severity::Error => Diagnostic::error(),
Severity::Warning => Diagnostic::warning(),
}
.with_message(diagnostic.message.clone())
.with_notes(
diagnostic
.hints
.iter()
.filter(|s| s.span.is_detached())
.map(|s| (eco_format!("hint: {}", s.v)).into())
.collect(),
)
.with_labels(
label(world, diagnostic.span)
.into_iter()
.chain(diagnostic.hints.iter().filter_map(|hint| {
let id = hint.span.id()?;
let range = world.range(hint.span)?;
Some(Label::secondary(id, range).with_message(&hint.v))
}))
.collect(),
);
term::emit(&mut terminal::out(), &config, world, &diag)?;
// Stacktrace-like helper diagnostics.
for point in &diagnostic.trace {
let message = point.v.to_string();
let help = Diagnostic::help()
.with_message(message)
.with_labels(label(world, point.span).into_iter().collect());
term::emit(&mut terminal::out(), &config, world, &help)?;
}
}
Ok(())
}
/// Create a label for a span.
fn label(world: &SystemWorld, span: Span) -> Option<Label<FileId>> {
Some(Label::primary(span.id()?, world.range(span)?))
}
impl<'a> codespan_reporting::files::Files<'a> for SystemWorld {
type FileId = FileId;
type Name = String;
type Source = Lines<String>;
fn name(&'a self, id: FileId) -> CodespanResult<Self::Name> {
let vpath = id.vpath();
Ok(if let Some(package) = id.package() {
format!("{package}{}", vpath.as_rooted_path().display())
} else {
// Try to express the path relative to the working directory.
vpath
.resolve(self.root())
.and_then(|abs| pathdiff::diff_paths(abs, self.workdir()))
.as_deref()
.unwrap_or_else(|| vpath.as_rootless_path())
.to_string_lossy()
.into()
})
}
fn source(&'a self, id: FileId) -> CodespanResult<Self::Source> {
Ok(self.lookup(id))
}
fn line_index(&'a self, id: FileId, given: usize) -> CodespanResult<usize> {
let source = self.lookup(id);
source
.byte_to_line(given)
.ok_or_else(|| CodespanError::IndexTooLarge {
given,
max: source.len_bytes(),
})
}
fn line_range(
&'a self,
id: FileId,
given: usize,
) -> CodespanResult<std::ops::Range<usize>> {
let source = self.lookup(id);
source
.line_to_range(given)
.ok_or_else(|| CodespanError::LineTooLarge { given, max: source.len_lines() })
}
fn column_number(
&'a self,
id: FileId,
_: usize,
given: usize,
) -> CodespanResult<usize> {
let source = self.lookup(id);
source.byte_to_column(given).ok_or_else(|| {
let max = source.len_bytes();
if given <= max {
CodespanError::InvalidCharBoundary { given }
} else {
CodespanError::IndexTooLarge { given, max }
}
})
}
}
impl From<PdfStandard> for typst_pdf::PdfStandard {
fn from(standard: PdfStandard) -> Self {
match standard {
PdfStandard::V_1_4 => typst_pdf::PdfStandard::V_1_4,
PdfStandard::V_1_5 => typst_pdf::PdfStandard::V_1_5,
PdfStandard::V_1_6 => typst_pdf::PdfStandard::V_1_6,
PdfStandard::V_1_7 => typst_pdf::PdfStandard::V_1_7,
PdfStandard::V_2_0 => typst_pdf::PdfStandard::V_2_0,
PdfStandard::A_1b => typst_pdf::PdfStandard::A_1b,
PdfStandard::A_1a => typst_pdf::PdfStandard::A_1a,
PdfStandard::A_2b => typst_pdf::PdfStandard::A_2b,
PdfStandard::A_2u => typst_pdf::PdfStandard::A_2u,
PdfStandard::A_2a => typst_pdf::PdfStandard::A_2a,
PdfStandard::A_3b => typst_pdf::PdfStandard::A_3b,
PdfStandard::A_3u => typst_pdf::PdfStandard::A_3u,
PdfStandard::A_3a => typst_pdf::PdfStandard::A_3a,
PdfStandard::A_4 => typst_pdf::PdfStandard::A_4,
PdfStandard::A_4f => typst_pdf::PdfStandard::A_4f,
PdfStandard::A_4e => typst_pdf::PdfStandard::A_4e,
PdfStandard::UA_1 => typst_pdf::PdfStandard::Ua_1,
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/fonts.rs | crates/typst-cli/src/fonts.rs | use typst::text::FontVariant;
use typst_kit::fonts::Fonts;
use crate::args::FontsCommand;
/// Execute a font listing command.
pub fn fonts(command: &FontsCommand) {
let mut fonts = Fonts::searcher();
fonts.include_system_fonts(!command.font.ignore_system_fonts);
#[cfg(feature = "embed-fonts")]
fonts.include_embedded_fonts(!command.font.ignore_embedded_fonts);
let fonts = fonts.search_with(&command.font.font_paths);
for (name, infos) in fonts.book.families() {
println!("{name}");
if command.variants {
for info in infos {
let FontVariant { style, weight, stretch } = info.variant;
println!("- Style: {style:?}, Weight: {weight:?}, Stretch: {stretch:?}");
}
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/args.rs | crates/typst-cli/src/args.rs | // This module is imported both from the `typst-cli` crate itself
// and from its build script. In this module, you can only import from crates
// that are both runtime and build dependencies of this crate, or else
// Rust will give a confusing error message about a missing crate.
use std::fmt::{self, Display, Formatter};
use std::io::Write;
use std::num::NonZeroUsize;
use std::ops::RangeInclusive;
use std::path::PathBuf;
use std::str::FromStr;
use chrono::{DateTime, Utc};
use clap::builder::styling::{AnsiColor, Effects};
use clap::builder::{Styles, TypedValueParser, ValueParser};
use clap::{ArgAction, Args, ColorChoice, Parser, Subcommand, ValueEnum, ValueHint};
use clap_complete::Shell;
use semver::Version;
use serde::Serialize;
/// The character typically used to separate path components
/// in environment variables.
const ENV_PATH_SEP: char = if cfg!(windows) { ';' } else { ':' };
/// The overall structure of the help.
#[rustfmt::skip]
const HELP_TEMPLATE: &str = "\
Typst {version}
{usage-heading} {usage}
{all-args}{after-help}\
";
/// Adds a list of useful links after the normal help.
#[rustfmt::skip]
const AFTER_HELP: &str = color_print::cstr!("\
<s><u>Resources:</></>
<s>Tutorial:</> https://typst.app/docs/tutorial/
<s>Reference documentation:</> https://typst.app/docs/reference/
<s>Templates & Packages:</> https://typst.app/universe/
<s>Forum for questions:</> https://forum.typst.app/
");
const STYLES: Styles = Styles::styled()
.literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))
.placeholder(AnsiColor::Blue.on_default());
/// The Typst compiler.
#[derive(Debug, Clone, Parser)]
#[clap(
name = "typst",
version = format!(
"{} ({})",
typst_utils::version().raw(),
typst_utils::display_commit(typst_utils::version().commit()),
),
author,
help_template = HELP_TEMPLATE,
after_help = AFTER_HELP,
max_term_width = 80,
styles = STYLES,
)]
pub struct CliArguments {
/// The command to run.
#[command(subcommand)]
pub command: Command,
/// Whether to use color. When set to `auto` if the terminal to supports it.
#[clap(long, default_value_t = ColorChoice::Auto, default_missing_value = "always")]
pub color: ColorChoice,
/// Path to a custom CA certificate to use when making network requests.
#[clap(long, env = "TYPST_CERT")]
pub cert: Option<PathBuf>,
}
/// What to do.
#[derive(Debug, Clone, Subcommand)]
#[command()]
pub enum Command {
/// Compiles an input file into a supported output format.
#[command(visible_alias = "c")]
Compile(CompileCommand),
/// Watches an input file and recompiles on changes.
#[command(visible_alias = "w")]
Watch(WatchCommand),
/// Initializes a new project from a template.
Init(InitCommand),
/// Processes an input file to extract provided metadata (deprecated, use `eval` instead).
#[command(hide = true)]
Query(QueryCommand),
/// Evaluates a piece of Typst code, optionally in the context of a document.
Eval(EvalCommand),
/// Lists all discovered fonts in system and custom font paths.
Fonts(FontsCommand),
/// Self update the Typst CLI.
#[cfg_attr(not(feature = "self-update"), clap(hide = true))]
Update(UpdateCommand),
/// Generates shell completion scripts.
Completions(CompletionsCommand),
/// Displays debugging information about Typst.
Info(InfoCommand),
}
/// Compiles an input file into a supported output format.
#[derive(Debug, Clone, Parser)]
pub struct CompileCommand {
/// Arguments for compilation.
#[clap(flatten)]
pub args: CompileArgs,
}
/// Compiles an input file into a supported output format.
#[derive(Debug, Clone, Parser)]
pub struct WatchCommand {
/// Arguments for compilation.
#[clap(flatten)]
pub args: CompileArgs,
/// Arguments for the HTTP server.
#[cfg(feature = "http-server")]
#[clap(flatten)]
pub server: ServerArgs,
}
/// Initializes a new project from a template.
#[derive(Debug, Clone, Parser)]
pub struct InitCommand {
/// The template to use, e.g. `@preview/charged-ieee`.
///
/// You can specify the version by appending e.g. `:0.1.0`. If no version is
/// specified, Typst will default to the latest version.
///
/// Supports both local and published templates.
pub template: String,
/// The project directory, defaults to the template's name.
pub dir: Option<String>,
/// Arguments related to storage of packages in the system.
#[clap(flatten)]
pub package: PackageArgs,
}
/// Processes an input file to extract provided metadata (deprecated, use `eval` instead).
#[derive(Debug, Clone, Parser)]
pub struct QueryCommand {
/// Path to input Typst file. Use `-` to read input from stdin.
#[clap(value_parser = input_value_parser(), value_hint = ValueHint::FilePath)]
pub input: Input,
/// Defines which elements to retrieve.
pub selector: String,
/// Extracts just one field from all retrieved elements.
#[clap(long = "field")]
pub field: Option<String>,
/// Expects and retrieves exactly one element.
#[clap(long = "one", default_value = "false")]
pub one: bool,
/// The format to serialize in.
#[clap(long = "format", default_value_t)]
pub format: SerializationFormat,
/// Whether to pretty-print the serialized output.
///
/// Only applies to JSON format.
#[clap(long)]
pub pretty: bool,
/// The target to compile for.
#[clap(long, default_value_t)]
pub target: Target,
/// World arguments.
#[clap(flatten)]
pub world: WorldArgs,
/// Processing arguments.
#[clap(flatten)]
pub process: ProcessArgs,
}
/// Evaluates a piece of Typst code, optionally in the context of a document.
#[derive(Debug, Clone, Parser)]
pub struct EvalCommand {
/// The piece of Typst code to evaluate.
pub expression: String,
/// A file in whose context to evaluate the code. Can be used to
/// introspect the document. Use `-` to read input from stdin.
#[clap(long = "in", value_hint = ValueHint::FilePath, value_parser = input_value_parser())]
pub r#in: Option<Input>,
/// The target to compile for.
#[clap(long, default_value_t)]
pub target: Target,
/// The format to serialize in.
#[clap(long = "format", default_value_t)]
pub format: SerializationFormat,
/// Whether to pretty-print the serialized output.
///
/// Only applies to JSON format.
#[clap(long)]
pub pretty: bool,
/// The world arguments.
#[clap(flatten)]
pub world: WorldArgs,
/// The processing arguments.
#[clap(flatten)]
pub process: ProcessArgs,
}
/// Lists all discovered fonts in system and custom font paths.
#[derive(Debug, Clone, Parser)]
pub struct FontsCommand {
/// Common font arguments.
#[clap(flatten)]
pub font: FontArgs,
/// Also lists style variants of each font family.
#[arg(long)]
pub variants: bool,
}
/// Update the CLI using a pre-compiled binary from a Typst GitHub release.
#[derive(Debug, Clone, Parser)]
pub struct UpdateCommand {
/// Which version to update to (defaults to latest).
pub version: Option<Version>,
/// Forces a downgrade to an older version (required for downgrading).
#[clap(long, default_value_t = false)]
pub force: bool,
/// Reverts to the version from before the last update (only possible if
/// `typst update` has previously ran).
#[clap(
long,
default_value_t = false,
conflicts_with = "version",
conflicts_with = "force"
)]
pub revert: bool,
/// Custom path to the backup file created on update and used by `--revert`,
/// defaults to system-dependent location
#[clap(long = "backup-path", env = "TYPST_UPDATE_BACKUP_PATH", value_name = "FILE")]
pub backup_path: Option<PathBuf>,
}
/// Generates shell completion scripts.
#[derive(Debug, Clone, Parser)]
pub struct CompletionsCommand {
/// The shell to generate completions for.
#[arg(value_enum)]
pub shell: Shell,
}
/// Displays environment variables and default values Typst uses.
#[derive(Debug, Clone, Parser)]
pub struct InfoCommand {
/// The format to serialize in, if it should be machine-readable.
///
/// If no format is passed the output is displayed human-readable. Note that
/// human-readable format truncates the build commit hash value.
#[arg(long = "format", short = 'f')]
pub format: Option<SerializationFormat>,
/// Whether to pretty-print the serialized output.
///
/// Only applies to JSON format.
#[clap(long)]
pub pretty: bool,
}
/// Arguments for compilation and watching.
#[derive(Debug, Clone, Args)]
pub struct CompileArgs {
/// Path to input Typst file. Use `-` to read input from stdin.
#[clap(value_parser = input_value_parser(), value_hint = ValueHint::FilePath)]
pub input: Input,
/// Path to output file (PDF, PNG, SVG, or HTML). Use `-` to write output to
/// stdout.
///
/// For output formats emitting one file per page (PNG & SVG), a page number
/// template must be present if the source document renders to multiple
/// pages. Use `{p}` for page numbers, `{0p}` for zero padded page numbers
/// and `{t}` for page count. For example, `page-{0p}-of-{t}.png` creates
/// `page-01-of-10.png`, `page-02-of-10.png`, and so on.
#[clap(
required_if_eq("input", "-"),
value_parser = output_value_parser(),
value_hint = ValueHint::FilePath,
)]
pub output: Option<Output>,
/// The format of the output file, inferred from the extension by default.
#[arg(long = "format", short = 'f')]
pub format: Option<OutputFormat>,
/// World arguments.
#[clap(flatten)]
pub world: WorldArgs,
/// Which pages to export. When unspecified, all pages are exported.
///
/// Pages to export are separated by commas, and can be either simple page
/// numbers (e.g. '2,5' to export only pages 2 and 5) or page ranges (e.g.
/// '2,3-6,8-' to export page 2, pages 3 to 6 (inclusive), page 8 and any
/// pages after it).
///
/// Page numbers are one-indexed and correspond to physical page numbers in
/// the document (therefore not being affected by the document's page
/// counter).
#[arg(long = "pages", value_delimiter = ',')]
pub pages: Option<Vec<Pages>>,
/// One (or multiple comma-separated) PDF standards that Typst will enforce
/// conformance with.
#[arg(long = "pdf-standard", value_delimiter = ',')]
pub pdf_standard: Vec<PdfStandard>,
/// By default, even when not producing a `PDF/UA-1` document, a tagged PDF
/// document is written to provide a baseline of accessibility. In some
/// circumstances (for example when trying to reduce the size of a document)
/// it can be desirable to disable tagged PDF.
#[arg(long = "no-pdf-tags")]
pub no_pdf_tags: bool,
/// The PPI (pixels per inch) to use for PNG export.
#[arg(long = "ppi", default_value_t = 144.0)]
pub ppi: f32,
/// File path to which a Makefile with the current compilation's
/// dependencies will be written.
#[clap(long = "make-deps", value_name = "PATH", hide = true)]
pub make_deps: Option<PathBuf>,
/// File path to which a list of current compilation's dependencies will be
/// written. Use `-` to write to stdout.
#[clap(
long,
value_name = "PATH",
value_parser = output_value_parser(),
value_hint = ValueHint::FilePath,
)]
pub deps: Option<Output>,
/// File format to use for dependencies.
#[clap(long, default_value_t)]
pub deps_format: DepsFormat,
/// Processing arguments.
#[clap(flatten)]
pub process: ProcessArgs,
/// Opens the output file with the default viewer or a specific program
/// after compilation. Ignored if output is stdout.
#[arg(long = "open", value_name = "VIEWER")]
pub open: Option<Option<String>>,
/// Produces performance timings of the compilation process. (experimental)
///
/// The resulting JSON file can be loaded into a tracing tool such as
/// https://ui.perfetto.dev. It does not contain any sensitive information
/// apart from file names and line numbers.
#[arg(long = "timings", value_name = "OUTPUT_JSON")]
pub timings: Option<Option<PathBuf>>,
}
/// Arguments for the construction of a world. Shared by compile, watch, eval, and
/// query.
#[derive(Debug, Clone, Args)]
pub struct WorldArgs {
/// Configures the project root (for absolute paths).
#[clap(long = "root", env = "TYPST_ROOT", value_name = "DIR")]
pub root: Option<PathBuf>,
/// Add a string key-value pair visible through `sys.inputs`.
#[clap(
long = "input",
value_name = "key=value",
action = ArgAction::Append,
value_parser = ValueParser::new(parse_sys_input_pair),
)]
pub inputs: Vec<(String, String)>,
/// Common font arguments.
#[clap(flatten)]
pub font: FontArgs,
/// Arguments related to storage of packages in the system.
#[clap(flatten)]
pub package: PackageArgs,
/// The document's creation date formatted as a UNIX timestamp.
///
/// For more information, see <https://reproducible-builds.org/specs/source-date-epoch/>.
#[clap(
long = "creation-timestamp",
env = "SOURCE_DATE_EPOCH",
value_name = "UNIX_TIMESTAMP",
value_parser = parse_source_date_epoch,
)]
pub creation_timestamp: Option<DateTime<Utc>>,
}
/// Arguments for configuration the process of compilation itself.
#[derive(Debug, Clone, Args)]
pub struct ProcessArgs {
/// Number of parallel jobs spawned during compilation. Defaults to number
/// of CPUs. Setting it to 1 disables parallelism.
#[clap(long, short)]
pub jobs: Option<usize>,
/// Enables in-development features that may be changed or removed at any
/// time.
#[arg(long = "features", value_delimiter = ',', env = "TYPST_FEATURES")]
pub features: Vec<Feature>,
/// The format to emit diagnostics in.
#[clap(long, default_value_t)]
pub diagnostic_format: DiagnosticFormat,
}
/// Arguments related to where packages are stored in the system.
#[derive(Debug, Clone, Args)]
pub struct PackageArgs {
/// Custom path to local packages, defaults to system-dependent location.
#[clap(long = "package-path", env = "TYPST_PACKAGE_PATH", value_name = "DIR")]
pub package_path: Option<PathBuf>,
/// Custom path to package cache, defaults to system-dependent location.
#[clap(
long = "package-cache-path",
env = "TYPST_PACKAGE_CACHE_PATH",
value_name = "DIR"
)]
pub package_cache_path: Option<PathBuf>,
}
/// Common arguments to customize available fonts.
#[derive(Debug, Clone, Parser)]
pub struct FontArgs {
/// Adds additional directories that are recursively searched for fonts.
///
/// If multiple paths are specified, they are separated by the system's path
/// separator (`:` on Unix-like systems and `;` on Windows).
#[clap(
long = "font-path",
env = "TYPST_FONT_PATHS",
value_name = "DIR",
value_delimiter = ENV_PATH_SEP,
)]
pub font_paths: Vec<PathBuf>,
/// Ensures system fonts won't be searched, unless explicitly included via
/// `--font-path`.
#[arg(long, env = "TYPST_IGNORE_SYSTEM_FONTS")]
pub ignore_system_fonts: bool,
/// Ensures fonts embedded into Typst won't be considered.
#[cfg(feature = "embed-fonts")]
#[arg(long, env = "TYPST_IGNORE_EMBEDDED_FONTS")]
pub ignore_embedded_fonts: bool,
}
/// Arguments for the HTTP server.
#[cfg(feature = "http-server")]
#[derive(Debug, Clone, Parser)]
pub struct ServerArgs {
/// Disables the built-in HTTP server for HTML export.
#[clap(long)]
pub no_serve: bool,
/// Disables the injected live reload script for HTML export. The HTML that
/// is written to disk isn't affected either way.
#[clap(long)]
pub no_reload: bool,
/// The port where HTML is served.
///
/// Defaults to the first free port in the range 3000-3005.
#[clap(long)]
pub port: Option<u16>,
}
macro_rules! display_possible_values {
($ty:ty) => {
impl Display for $ty {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}
};
}
/// An input that is either stdin or a real path.
#[derive(Debug, Clone)]
pub enum Input {
/// Stdin, represented by `-`.
Stdin,
/// A non-empty path.
Path(PathBuf),
}
impl Display for Input {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Input::Stdin => f.pad("stdin"),
Input::Path(path) => path.display().fmt(f),
}
}
}
/// An output that is either stdout or a real path.
#[derive(Debug, Clone)]
pub enum Output {
/// Stdout, represented by `-`.
Stdout,
/// A non-empty path.
Path(PathBuf),
}
impl Output {
/// Write data to the output.
pub fn write(&self, buffer: &[u8]) -> std::io::Result<()> {
match self {
Output::Stdout => std::io::stdout().write_all(buffer),
Output::Path(path) => std::fs::write(path, buffer),
}
}
/// Open the output for writing.
pub fn open(&self) -> std::io::Result<OpenOutput<'_>> {
match self {
Self::Stdout => Ok(OpenOutput::Stdout(std::io::stdout().lock())),
Self::Path(path) => std::fs::File::create(path).map(OpenOutput::File),
}
}
}
impl Display for Output {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Output::Stdout => f.pad("stdout"),
Output::Path(path) => path.display().fmt(f),
}
}
}
/// A step-by-step writable version of [`Output`].
#[derive(Debug)]
pub enum OpenOutput<'a> {
Stdout(std::io::StdoutLock<'a>),
File(std::fs::File),
}
impl Write for OpenOutput<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self {
OpenOutput::Stdout(v) => v.write(buf),
OpenOutput::File(v) => v.write(buf),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
OpenOutput::Stdout(v) => v.flush(),
OpenOutput::File(v) => v.flush(),
}
}
}
/// Which format to use for the generated output file.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, ValueEnum)]
pub enum OutputFormat {
Pdf,
Png,
Svg,
Html,
}
impl OutputFormat {
/// Whether this format results in a `PagedDocument`.
pub fn is_paged(&self) -> bool {
matches!(self, Self::Pdf | Self::Png | Self::Svg)
}
}
display_possible_values!(OutputFormat);
/// Which format to use for a generated dependency file.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, ValueEnum)]
pub enum DepsFormat {
/// Encodes as JSON, failing for non-Unicode paths.
#[default]
Json,
/// Separates paths with NULL bytes and can express all paths.
Zero,
/// Emits in Make format, omitting inexpressible paths.
Make,
}
display_possible_values!(DepsFormat);
/// The target to compile for.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, ValueEnum)]
pub enum Target {
/// PDF and image formats.
#[default]
Paged,
/// HTML.
Html,
}
display_possible_values!(Target);
/// Which format to use for diagnostics.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, ValueEnum)]
pub enum DiagnosticFormat {
#[default]
Human,
Short,
}
display_possible_values!(DiagnosticFormat);
/// An in-development feature that may be changed or removed at any time.
#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum, Serialize)]
pub enum Feature {
Html,
A11yExtras,
}
display_possible_values!(Feature);
/// A PDF standard that Typst can enforce conformance with.
#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum)]
#[allow(non_camel_case_types)]
pub enum PdfStandard {
/// PDF 1.4.
#[value(name = "1.4")]
V_1_4,
/// PDF 1.5.
#[value(name = "1.5")]
V_1_5,
/// PDF 1.6.
#[value(name = "1.6")]
V_1_6,
/// PDF 1.7.
#[value(name = "1.7")]
V_1_7,
/// PDF 2.0.
#[value(name = "2.0")]
V_2_0,
/// PDF/A-1b.
#[value(name = "a-1b")]
A_1b,
/// PDF/A-1a.
#[value(name = "a-1a")]
A_1a,
/// PDF/A-2b.
#[value(name = "a-2b")]
A_2b,
/// PDF/A-2u.
#[value(name = "a-2u")]
A_2u,
/// PDF/A-2a.
#[value(name = "a-2a")]
A_2a,
/// PDF/A-3b.
#[value(name = "a-3b")]
A_3b,
/// PDF/A-3u.
#[value(name = "a-3u")]
A_3u,
/// PDF/A-3a.
#[value(name = "a-3a")]
A_3a,
/// PDF/A-4.
#[value(name = "a-4")]
A_4,
/// PDF/A-4f.
#[value(name = "a-4f")]
A_4f,
/// PDF/A-4e.
#[value(name = "a-4e")]
A_4e,
/// PDF/UA-1.
#[value(name = "ua-1")]
UA_1,
}
display_possible_values!(PdfStandard);
/// Output file format for query and info commands
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, ValueEnum)]
pub enum SerializationFormat {
#[default]
Json,
Yaml,
}
display_possible_values!(SerializationFormat);
/// Implements parsing of page ranges (`1-3`, `4`, `5-`, `-2`), used by the
/// `CompileCommand.pages` argument, through the `FromStr` trait instead of a
/// value parser, in order to generate better errors.
///
/// See also: https://github.com/clap-rs/clap/issues/5065
#[derive(Debug, Clone)]
pub struct Pages(pub RangeInclusive<Option<NonZeroUsize>>);
impl FromStr for Pages {
type Err = &'static str;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.split('-').map(str::trim).collect::<Vec<_>>().as_slice() {
[] | [""] => Err("page export range must not be empty"),
[single_page] => {
let page_number = parse_page_number(single_page)?;
Ok(Pages(Some(page_number)..=Some(page_number)))
}
["", ""] => Err("page export range must have start or end"),
[start, ""] => Ok(Pages(Some(parse_page_number(start)?)..=None)),
["", end] => Ok(Pages(None..=Some(parse_page_number(end)?))),
[start, end] => {
let start = parse_page_number(start)?;
let end = parse_page_number(end)?;
if start > end {
Err("page export range must end at a page after the start")
} else {
Ok(Pages(Some(start)..=Some(end)))
}
}
[_, _, _, ..] => Err("page export range must have a single hyphen"),
}
}
}
/// Parses a single page number.
fn parse_page_number(value: &str) -> Result<NonZeroUsize, &'static str> {
if value == "0" {
Err("page numbers start at one")
} else {
NonZeroUsize::from_str(value).map_err(|_| "not a valid page number")
}
}
/// The clap value parser used by `SharedArgs.input`
fn input_value_parser() -> impl TypedValueParser<Value = Input> {
clap::builder::OsStringValueParser::new().try_map(|value| {
if value.is_empty() {
Err(clap::Error::new(clap::error::ErrorKind::InvalidValue))
} else if value == "-" {
Ok(Input::Stdin)
} else {
Ok(Input::Path(value.into()))
}
})
}
/// The clap value parser used by `CompileCommand.output`
fn output_value_parser() -> impl TypedValueParser<Value = Output> {
clap::builder::OsStringValueParser::new().try_map(|value| {
// Empty value also handled by clap for `Option<Output>`
if value.is_empty() {
Err(clap::Error::new(clap::error::ErrorKind::InvalidValue))
} else if value == "-" {
Ok(Output::Stdout)
} else {
Ok(Output::Path(value.into()))
}
})
}
/// Parses key/value pairs split by the first equal sign.
///
/// This function will return an error if the argument contains no equals sign
/// or contains the key (before the equals sign) is empty.
fn parse_sys_input_pair(raw: &str) -> Result<(String, String), String> {
let (key, val) = raw
.split_once('=')
.ok_or("input must be a key and a value separated by an equal sign")?;
let key = key.trim().to_owned();
if key.is_empty() {
return Err("the key was missing or empty".to_owned());
}
let val = val.trim().to_owned();
Ok((key, val))
}
/// Parses a UNIX timestamp according to <https://reproducible-builds.org/specs/source-date-epoch/>
fn parse_source_date_epoch(raw: &str) -> Result<DateTime<Utc>, String> {
let timestamp: i64 = raw
.parse()
.map_err(|err| format!("timestamp must be decimal integer ({err})"))?;
DateTime::from_timestamp(timestamp, 0)
.ok_or_else(|| "timestamp out of range".to_string())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/greet.rs | crates/typst-cli/src/greet.rs | use std::io::{self, Read};
/// This is shown to users who just type `typst` the first time.
#[rustfmt::skip]
const GREETING: &str = color_print::cstr!("\
<s>Welcome to Typst, we are glad to have you here!</> ❤️
If you are new to Typst, <s>start with the tutorial</> at \
<u>https://typst.app/docs/tutorial/</>. To get a quick start with your first \
project, <s>choose a template</> on <u>https://typst.app/universe/</>.
Here are the <s>most important commands</> you will be using:
- Compile a file once: <c!>typst compile file.typ</>
- Compile a file on every change: <c!>typst watch file.typ</>
- Set up a project from a template: <c!>typst init @preview/<<TEMPLATE>></>
Learn more about these commands by running <c!>typst help</>.
If you have a question, we and our community would be glad to help you out on \
the <s>Typst Forum</> at <u>https://forum.typst.app/</>.
Happy Typsting!
");
/// Greets (and exists) if not yet greeted.
pub fn greet() {
let Some(data_dir) = dirs::data_dir() else { return };
let path = data_dir.join("typst").join("greeted");
let version = typst::utils::version().raw();
let prev_greet = std::fs::read_to_string(&path).ok();
if prev_greet.as_deref() == Some(version) {
return;
};
std::fs::write(&path, version).ok();
print_and_exit(GREETING);
}
/// Prints a colorized and line-wrapped message.
fn print_and_exit(message: &'static str) -> ! {
// Abuse clap for line wrapping ...
let err = clap::Command::new("typst")
.max_term_width(80)
.help_template("{about}")
.about(message)
.try_get_matches_from(["typst", "--help"])
.unwrap_err();
let _ = err.print();
// Windows users might have double-clicked the .exe file and have no chance
// to read it before the terminal closes.
if cfg!(windows) {
pause();
}
std::process::exit(err.exit_code());
}
/// Waits for the user.
#[allow(clippy::unused_io_amount)]
fn pause() {
eprintln!();
eprintln!("Press enter to continue...");
io::stdin().lock().read(&mut [0]).unwrap();
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/info.rs | crates/typst-cli/src/info.rs | use std::env::VarError;
use std::fmt::Display;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use clap::builder::{FalseyValueParser, TypedValueParser};
use clap::{CommandFactory, ValueEnum};
use codespan_reporting::term::termcolor::{Color, ColorSpec, WriteColor};
use ecow::eco_format;
use serde::Serialize;
use typst::diag::StrResult;
use crate::CliArguments;
use crate::args::{Feature, InfoCommand};
use crate::terminal::{self, TermOut};
/// A struct holding the machine readable output of the environment command.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct Info {
/// The Typst version.
version: &'static str,
/// Build info about Typst.
build: Build,
/// The runtime features from `TYPST_FEATURES`.
features: Features,
/// Font configuration.
fonts: Fonts,
/// Package configuration.
packages: Packages,
/// The environment variables that are of interest to Typst.
env: Environment,
}
/// Build info about Typst.
#[derive(Default, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Build {
/// The commit this binary was compiled from. May be `None` if unknown.
commit: Option<&'static str>,
/// The platform this binary was compiled for.
platform: Platform,
/// Compile time settings.
settings: Settings,
}
/// The platform this binary was compiled for.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct Platform {
/// Operating system this binary was compiled for.
os: &'static str,
/// The instruction set architecture this binary was compiled for.
arch: &'static str,
}
impl Platform {
/// Create a new platform using compile time constants.
const fn new() -> Self {
Self {
os: std::env::consts::OS,
arch: std::env::consts::ARCH,
}
}
}
impl Default for Platform {
fn default() -> Self {
Self::new()
}
}
/// Compile time settings.
#[derive(Default, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Settings {
/// Whether the `self-update` compile-time feature is enabled.
self_update: bool,
/// Whether the `http-server` compile-time feature is enabled.
http_server: bool,
}
impl Settings {
/// Return the compile features with human readable information.
fn compile_features(&self) -> impl Iterator<Item = KeyValDesc<'_>> {
let Self { self_update, http_server } = self;
[
("self-update", self_update, "Update Typst via `typst update`"),
("http-server", http_server, "Serve HTML via `typst watch`"),
]
.into_iter()
.map(|(key, val, desc)| KeyValDesc { key, val: Value::Bool(*val), desc })
}
}
/// The runtime features from `TYPST_FEATURES`.
#[derive(Default, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Features {
html: bool,
a11y_extras: bool,
}
impl Features {
/// Return the runtime features with human readable information.
fn features(&self) -> impl Iterator<Item = KeyValDesc<'_>> {
let Self { html, a11y_extras } = self;
[
("html", html, "Experimental HTML support"),
("a11y-extras", a11y_extras, "Experimental accessibility additions"),
]
.into_iter()
.map(|(key, val, desc)| KeyValDesc { key, val: Value::Bool(*val), desc })
}
}
/// Font configuration.
#[derive(Default, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Fonts {
/// The font paths from `TYPST_FONT_PATHS`.
paths: Vec<PathBuf>,
/// Whether system fonts were included in the search.
system: bool,
/// Whether embedded fonts were included in the search.
embedded: bool,
}
impl Fonts {
/// Return the custom font paths.
fn custom_paths(&self) -> impl Iterator<Item = Value<'_>> {
self.paths.iter().map(|p| Value::Path(p))
}
/// Return whether system and embedded fonts are included.
fn included(&self) -> impl Iterator<Item = (&'static str, Value<'_>)> {
let Self { paths: _, system, embedded } = self;
[("System fonts", system), ("Embedded fonts", embedded)]
.into_iter()
.map(|(key, val)| (key, Value::Bool(*val)))
}
}
/// Package configuration.
#[derive(Default, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Packages {
/// The resolved package path.
package_path: Option<PathBuf>,
/// The resolved package cache path.
package_cache_path: Option<PathBuf>,
}
impl Packages {
/// Return the resolved package paths.
fn paths(&self) -> impl Iterator<Item = (&'static str, Value<'_>)> {
let Self { package_path, package_cache_path } = self;
[("Package path", package_path), ("Package cache path", package_cache_path)]
.into_iter()
.map(|(k, v)| (k, v.as_deref().map(Value::Path).unwrap_or(Value::Unset)))
}
}
/// The environment variables that are of interest to Typst.
#[derive(Default, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
struct Environment {
typst_cert: Option<String>,
typst_features: Option<String>,
typst_font_paths: Option<String>,
typst_ignore_system_fonts: Option<String>,
typst_ignore_embedded_fonts: Option<String>,
typst_package_cache_path: Option<String>,
typst_package_path: Option<String>,
typst_root: Option<String>,
typst_update_backup_path: Option<String>,
source_date_epoch: Option<String>,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
xdg_cache_home: Option<String>,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
xdg_data_home: Option<String>,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios",)))]
fontconfig_file: Option<String>,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
openssl_conf: Option<String>,
no_color: Option<String>,
no_proxy: Option<String>,
http_proxy: Option<String>,
https_proxy: Option<String>,
all_proxy: Option<String>,
}
impl Environment {
fn vars(&self) -> impl Iterator<Item = (&'static str, Value<'_>)> {
let Environment {
typst_cert,
typst_features,
typst_font_paths,
typst_ignore_system_fonts,
typst_ignore_embedded_fonts,
typst_package_cache_path,
typst_package_path,
typst_root,
typst_update_backup_path,
source_date_epoch,
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
xdg_cache_home,
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
xdg_data_home,
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
fontconfig_file,
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
openssl_conf,
no_color,
no_proxy,
http_proxy,
https_proxy,
all_proxy,
} = self;
[
("TYPST_CERT", typst_cert),
("TYPST_FEATURES", typst_features),
("TYPST_FONT_PATHS", typst_font_paths),
("TYPST_IGNORE_SYSTEM_FONTS", typst_ignore_system_fonts),
("TYPST_IGNORE_EMBEDDED_FONTS", typst_ignore_embedded_fonts),
("TYPST_PACKAGE_CACHE_PATH", typst_package_cache_path),
("TYPST_PACKAGE_PATH", typst_package_path),
("TYPST_ROOT", typst_root),
("TYPST_UPDATE_BACKUP_PATH", typst_update_backup_path),
("SOURCE_DATE_EPOCH", source_date_epoch),
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
("XDG_CACHE_HOME", xdg_cache_home),
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
("XDG_DATA_HOME", xdg_data_home),
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
("FONTCONFIG_FILE", fontconfig_file),
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
)))]
("OPENSSL_CONF", openssl_conf),
("NO_COLOR", no_color),
("NO_PROXY", no_proxy),
("HTTP_PROXY", http_proxy),
("HTTPS_PROXY", https_proxy),
("ALL_PROXY", all_proxy),
]
.into_iter()
.map(|(k, v)| (k, v.as_deref().map(Value::String).unwrap_or(Value::Unset)))
}
}
pub fn info(command: &InfoCommand) -> StrResult<()> {
let cmd = CliArguments::command();
let env = get_vars()?;
let runtime_features =
parse_features(env.typst_features.as_deref().unwrap_or_default())?;
let font_paths = env
.typst_font_paths
.as_deref()
.unwrap_or_default()
.split(':')
.filter(|s| !s.is_empty())
.map(PathBuf::from)
.collect::<_>();
let boolish = |v: &String| {
// This is only an error if `v` is not valid UTF-8, which it
// always is.
FalseyValueParser::new().parse_ref(&cmd, None, v.as_ref()).ok()
};
let version = typst::utils::version();
let value = Info {
version: version.raw(),
build: Build {
commit: version.commit(),
platform: Platform::new(),
settings: Settings {
self_update: cfg!(feature = "self-update"),
http_server: cfg!(feature = "http-server"),
},
},
features: runtime_features,
fonts: Fonts {
paths: font_paths,
system: !env
.typst_ignore_system_fonts
.as_ref()
.and_then(boolish)
.unwrap_or(false),
embedded: !env
.typst_ignore_embedded_fonts
.as_ref()
.and_then(boolish)
.unwrap_or(false),
},
packages: Packages {
package_path: env
.typst_package_path
.as_ref()
.map(PathBuf::from)
.or_else(typst_kit::package::default_package_path),
package_cache_path: env
.typst_package_cache_path
.as_ref()
.map(PathBuf::from)
.or_else(typst_kit::package::default_package_cache_path),
},
env,
};
if let Some(format) = command.format {
let serialized = crate::serialize(&value, format, command.pretty)?;
println!("{serialized}");
} else {
format_human_readable(&value).map_err(|e| eco_format!("{e}"))?;
}
Ok(())
}
/// Retrieves all relevant environment variables.
fn get_vars() -> StrResult<Environment> {
fn get_var(key: &'static str) -> StrResult<Option<String>> {
match std::env::var(key) {
Ok(val) => Ok(Some(val)),
Err(VarError::NotPresent) => Ok(None),
Err(VarError::NotUnicode(_)) => {
crate::set_failed();
crate::print_error(&format!(
"the environment variable `{key}` was not valid UTF-8"
))
.map_err(|e| eco_format!("{e}"))?;
Ok(None)
}
}
}
Ok(Environment {
typst_cert: get_var("TYPST_CERT")?,
typst_features: get_var("TYPST_FEATURES")?,
typst_font_paths: get_var("TYPST_FONT_PATHS")?,
typst_ignore_system_fonts: get_var("TYPST_IGNORE_SYSTEM_FONTS")?,
typst_ignore_embedded_fonts: get_var("TYPST_IGNORE_EMBEDDED_FONTS")?,
typst_package_cache_path: get_var("TYPST_PACKAGE_CACHE_PATH")?,
typst_package_path: get_var("TYPST_PACKAGE_PATH")?,
typst_root: get_var("TYPST_ROOT")?,
typst_update_backup_path: get_var("TYPST_UPDATE_BACKUP_PATH")?,
source_date_epoch: get_var("SOURCE_DATE_EPOCH")?,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
xdg_cache_home: get_var("XDG_CACHE_HOME")?,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
xdg_data_home: get_var("XDG_DATA_HOME")?,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
fontconfig_file: get_var("FONTCONFIG_FILE")?,
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
openssl_conf: get_var("OPENSSL_CONF")?,
no_color: get_var("NO_COLOR")?,
no_proxy: get_var("NO_PROXY")?,
http_proxy: get_var("HTTP_PROXY")?,
https_proxy: get_var("HTTPS_PROXY")?,
all_proxy: get_var("ALL_PROXY")?,
})
}
/// Turns a comma separated list of feature names into a well typed struct of
/// feature flags.
fn parse_features(feature_list: &str) -> StrResult<Features> {
let mut features = Features { html: false, a11y_extras: false };
for feature in feature_list.split(',').filter(|s| !s.is_empty()) {
match Feature::from_str(feature, true) {
Ok(feature) => match feature {
Feature::Html => features.html = true,
Feature::A11yExtras => features.a11y_extras = true,
},
Err(_) => {
crate::print_error(&format!("Unknown runtime feature: `{feature}`"))
.map_err(|e| eco_format!("{e}"))?;
continue;
}
}
}
Ok(features)
}
/// A for formatting human readable key-value-description triplets.
struct KeyValDesc<'a> {
key: &'static str,
val: Value<'a>,
desc: &'static str,
}
impl KeyValDesc<'_> {
/// Formatted this as `<key> <val> (<desc>)` with optional right padding for
/// key and value.
fn format(
&self,
out: &mut TermOut,
key_pad: Option<usize>,
val_pad: Option<usize>,
) -> io::Result<()> {
write!(out, " ")?;
write_key(out, self.key, key_pad)?;
write!(out, " ")?;
self.val.format(out, val_pad)?;
write!(out, " ({})", self.desc)?;
Ok(())
}
}
/// A value for colorful human readable formatting.
enum Value<'a> {
Unset,
Bool(bool),
Path(&'a Path),
String(&'a str),
}
impl Value<'_> {
/// Formats this value with optional right padding.
fn format(&self, out: &mut TermOut, pad: Option<usize>) -> io::Result<()> {
match self {
Value::Unset => write_value_special(out, "<unset>", pad),
Value::Bool(true) => write_value_special(out, "on", pad),
Value::Bool(false) => write_value_special(out, "off", pad),
Value::Path(val) => write_value_simple(out, val.display(), pad),
Value::String(val) => write_value_simple(out, val, pad),
}
}
}
/// Writes a key in cyan with optional right padding.
fn write_key(out: &mut TermOut, key: impl Display, pad: Option<usize>) -> io::Result<()> {
out.set_color(ColorSpec::new().set_fg(Some(Color::Cyan)))?;
if let Some(pad) = pad {
write!(out, "{key: <pad$}")?;
} else {
write!(out, "{key}")?;
}
out.reset()?;
Ok(())
}
/// Writes a value in green with optional right padding.
fn write_value_simple(
out: &mut TermOut,
val: impl Display,
pad: Option<usize>,
) -> io::Result<()> {
out.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
if let Some(pad) = pad {
write!(out, "{val: <pad$}")?;
} else {
write!(out, "{val}")?;
}
out.reset()?;
Ok(())
}
/// Writes a special value in blue with optional right padding.
fn write_value_special(
out: &mut TermOut,
val: impl Display,
pad: Option<usize>,
) -> io::Result<()> {
out.set_color(ColorSpec::new().set_fg(Some(Color::Blue)))?;
if let Some(pad) = pad {
write!(out, "{val: <pad$}")?;
} else {
write!(out, "{val}")?;
}
out.reset()?;
Ok(())
}
fn format_human_readable(value: &Info) -> io::Result<()> {
let mut out = terminal::out();
write_key(&mut out, "Version", None)?;
write!(out, " ")?;
write_value_simple(&mut out, value.version, None)?;
write!(out, " (")?;
write_value_simple(&mut out, typst_utils::display_commit(value.build.commit), None)?;
write!(out, ", ")?;
write_value_simple(&mut out, value.build.platform.os, None)?;
write!(out, " on ")?;
write_value_simple(&mut out, value.build.platform.arch, None)?;
writeln!(out, ")\n")?;
writeln!(out, "Build settings")?;
let key_pad = value.build.settings.compile_features().map(|f| f.key.len()).max();
for feature in value.build.settings.compile_features() {
feature.format(&mut out, key_pad, Some(3))?;
writeln!(out)?;
}
writeln!(out)?;
writeln!(out, "Features")?;
let key_pad = value.features.features().map(|f| f.key.len()).max();
for feature in value.features.features() {
feature.format(&mut out, key_pad, Some(3))?;
writeln!(out)?;
}
writeln!(out)?;
writeln!(out, "Fonts")?;
write!(out, " ")?;
write_key(&mut out, "Custom font paths", None)?;
if value.fonts.paths.is_empty() {
write!(out, " ")?;
write_value_special(&mut out, "<none>", None)?;
writeln!(out)?;
} else {
writeln!(out)?;
for path in value.fonts.custom_paths() {
write!(out, " - ")?;
path.format(&mut out, None)?;
writeln!(out)?;
}
}
let key_pad = value.fonts.included().map(|(key, _)| key.len()).max();
for (key, val) in value.fonts.included() {
write!(out, " ")?;
write_key(&mut out, key, key_pad)?;
write!(out, " ")?;
val.format(&mut out, None)?;
writeln!(out)?;
}
writeln!(out)?;
writeln!(out, "Packages")?;
let key_pad = value.packages.paths().map(|(name, _)| name.len()).max();
for (key, val) in value.packages.paths() {
write!(out, " ")?;
write_key(&mut out, key, key_pad)?;
write!(out, " ")?;
val.format(&mut out, None)?;
writeln!(out)?;
}
writeln!(out)?;
writeln!(out, "Environment variables")?;
let key_pad = value.env.vars().map(|(name, _)| name.len()).max();
for (key, val) in value.env.vars() {
write!(out, " ")?;
write_key(&mut out, key, key_pad)?;
write!(out, " ")?;
val.format(&mut out, None)?;
writeln!(out)?;
}
Ok(())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/deps.rs | crates/typst-cli/src/deps.rs | use std::io::{self, Write};
use std::path::PathBuf;
use serde::Serialize;
use crate::args::{DepsFormat, Output};
use crate::world::SystemWorld;
/// Writes dependencies in the given format.
pub fn write_deps(
world: &mut SystemWorld,
dest: &Output,
format: DepsFormat,
outputs: Option<&[Output]>,
) -> io::Result<()> {
match format {
DepsFormat::Json => write_deps_json(world, dest, outputs)?,
DepsFormat::Zero => write_deps_zero(world, dest)?,
DepsFormat::Make => {
if let Some(outputs) = outputs {
write_deps_make(world, dest, outputs)?;
}
}
}
Ok(())
}
/// Writes dependencies in JSON format.
fn write_deps_json(
world: &mut SystemWorld,
dest: &Output,
outputs: Option<&[Output]>,
) -> io::Result<()> {
let to_string = |dep: PathBuf, kind| {
dep.into_os_string().into_string().map_err(|dep| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("{kind} {dep:?} is not valid UTF-8"),
)
})
};
let inputs = relative_dependencies(world)?
.map(|dep| to_string(dep, "input"))
.collect::<Result<_, _>>()?;
let outputs = outputs
.map(|outputs| {
outputs
.iter()
.filter_map(|output| {
match output {
Output::Path(path) => Some(to_string(path.clone(), "output")),
// Skip stdout
Output::Stdout => None,
}
})
.collect::<Result<_, _>>()
})
.transpose()?;
#[derive(Serialize)]
struct Deps {
inputs: Vec<String>,
outputs: Option<Vec<String>>,
}
serde_json::to_writer(dest.open()?, &Deps { inputs, outputs })?;
Ok(())
}
/// Writes dependencies in the Zero / Text0 format.
fn write_deps_zero(world: &mut SystemWorld, dest: &Output) -> io::Result<()> {
let mut dest = dest.open()?;
for dep in relative_dependencies(world)? {
dest.write_all(dep.as_os_str().as_encoded_bytes())?;
dest.write_all(b"\0")?;
}
Ok(())
}
/// Writes dependencies in the Make format.
fn write_deps_make(
world: &mut SystemWorld,
dest: &Output,
outputs: &[Output],
) -> io::Result<()> {
let mut buffer = Vec::new();
for (i, output) in outputs.iter().enumerate() {
let path = match output {
Output::Path(path) => path.as_os_str(),
Output::Stdout => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"make dependencies contain the output path, \
but the output was stdout",
));
}
};
// Silently skip paths that aren't valid Unicode so we still
// produce a rule that will work for the other paths that can be
// processed.
let Some(string) = path.to_str() else { continue };
if i != 0 {
buffer.write_all(b" ")?;
}
buffer.write_all(munge(string).as_bytes())?;
}
// Only create the deps file in case of valid output paths.
let mut dest = dest.open()?;
dest.write_all(&buffer)?;
dest.write_all(b":")?;
for dep in relative_dependencies(world)? {
// See above.
let Some(string) = dep.to_str() else { continue };
dest.write_all(b" ")?;
dest.write_all(munge(string).as_bytes())?;
}
dest.write_all(b"\n")?;
Ok(())
}
// Based on `munge` in libcpp/mkdeps.cc from the GCC source code. This isn't
// perfect as some special characters can't be escaped.
fn munge(s: &str) -> String {
let mut res = String::with_capacity(s.len());
let mut slashes = 0;
for c in s.chars() {
match c {
'\\' => slashes += 1,
'$' => {
res.push('$');
slashes = 0;
}
':' => {
res.push('\\');
slashes = 0;
}
' ' | '\t' => {
// `munge`'s source contains a comment here that says: "A
// space or tab preceded by 2N+1 backslashes represents N
// backslashes followed by space..."
for _ in 0..slashes + 1 {
res.push('\\');
}
slashes = 0;
}
'#' => {
res.push('\\');
slashes = 0;
}
_ => slashes = 0,
};
res.push(c);
}
res
}
/// Extracts the current compilation's dependencies as paths relative to the
/// current directory.
fn relative_dependencies(
world: &mut SystemWorld,
) -> io::Result<impl Iterator<Item = PathBuf>> {
let root = world.root().to_owned();
let current_dir = std::env::current_dir()?;
let relative_root =
pathdiff::diff_paths(&root, ¤t_dir).unwrap_or_else(|| root.clone());
Ok(world.dependencies().map(move |dependency| {
dependency
.strip_prefix(&root)
.map_or_else(|_| dependency.clone(), |x| relative_root.join(x))
}))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/watch.rs | crates/typst-cli/src/watch.rs | use std::io::{self, Write};
use std::iter;
use std::path::PathBuf;
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};
use codespan_reporting::term::termcolor::WriteColor;
use codespan_reporting::term::{self, termcolor};
use ecow::eco_format;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher as _};
use rustc_hash::{FxHashMap, FxHashSet};
use same_file::is_same_file;
use typst::diag::{HintedStrResult, StrResult, bail, warning};
use typst::syntax::Span;
use typst::utils::format_duration;
use crate::args::{Input, Output, WatchCommand};
use crate::compile::{CompileConfig, compile_once, print_diagnostics};
use crate::timings::Timer;
use crate::world::{SystemWorld, WorldCreationError};
use crate::{print_error, terminal};
/// Execute a watching compilation command.
pub fn watch(timer: &mut Timer, command: &'static WatchCommand) -> HintedStrResult<()> {
let mut config = CompileConfig::watching(command)?;
let Output::Path(output) = &config.output else {
bail!("cannot write document to stdout in watch mode");
};
// Create a file system watcher.
let mut watcher = Watcher::new(output.clone())?;
// Create the world that serves sources, files, and fonts.
// Additionally, if any files do not exist, wait until they do.
let mut world = loop {
match SystemWorld::new(
Some(&command.args.input),
&command.args.world,
&command.args.process,
) {
Ok(world) => break world,
Err(
ref err @ (WorldCreationError::InputNotFound(ref path)
| WorldCreationError::RootNotFound(ref path)),
) => {
watcher.update([path.clone()])?;
Status::Error.print(&config).unwrap();
print_error(&err.to_string()).unwrap();
watcher.wait()?;
}
Err(err) => return Err(err.into()),
}
};
// Eagerly scan fonts if we expect to need them so that it's not counted as
// part of the displayed compilation time. The duration of font scanning is
// heavily system-dependant, so it could result in confusion why compilation
// is so much faster/slower.
if config.output_format.is_paged() {
world.scan_fonts();
}
// Perform initial compilation.
timer.record(&mut world, |world| compile_once(world, &mut config))??;
// Print warning when trying to watch stdin.
if matches!(&config.input, Input::Stdin) {
warn_watching_std(&world, &config)?;
}
// Recompile whenever something relevant happens.
loop {
// Watch all dependencies of the most recent compilation.
watcher.update(world.dependencies())?;
// Wait until anything relevant happens.
watcher.wait()?;
// Reset all dependencies.
world.reset();
// Recompile.
timer.record(&mut world, |world| compile_once(world, &mut config))??;
// Evict the cache.
comemo::evict(10);
}
}
/// Watches file system activity.
struct Watcher {
/// The output file. We ignore any events for it.
output: PathBuf,
/// The underlying watcher.
watcher: RecommendedWatcher,
/// Notify event receiver.
rx: Receiver<notify::Result<Event>>,
/// Keeps track of which paths are watched via `watcher`. The boolean is
/// used during updating for mark-and-sweep garbage collection of paths we
/// should unwatch.
watched: FxHashMap<PathBuf, bool>,
/// A set of files that should be watched, but don't exist. We manually poll
/// for those.
missing: FxHashSet<PathBuf>,
}
impl Watcher {
/// How long to wait for a shortly following file system event when
/// watching.
const BATCH_TIMEOUT: Duration = Duration::from_millis(100);
/// The maximum time we spend batching events before quitting wait().
const STARVE_TIMEOUT: Duration = Duration::from_millis(500);
/// The interval in which we poll when falling back to poll watching
/// due to missing files.
const POLL_INTERVAL: Duration = Duration::from_millis(300);
/// Create a new, blank watcher.
fn new(output: PathBuf) -> StrResult<Self> {
// Setup file watching.
let (tx, rx) = std::sync::mpsc::channel();
// Set the poll interval to something more eager than the default. That
// default seems a bit excessive for our purposes at around 30s.
// Depending on feedback, some tuning might still be in order. Note that
// this only affects a tiny number of systems. Most do not use the
// [`notify::PollWatcher`].
let config = notify::Config::default().with_poll_interval(Self::POLL_INTERVAL);
let watcher = RecommendedWatcher::new(tx, config)
.map_err(|err| eco_format!("failed to setup file watching ({err})"))?;
Ok(Self {
output,
rx,
watcher,
watched: FxHashMap::default(),
missing: FxHashSet::default(),
})
}
/// Update the watching to watch exactly the listed files.
///
/// Files that are not yet watched will be watched. Files that are already
/// watched, but don't need to be watched anymore, will be unwatched.
fn update(&mut self, iter: impl IntoIterator<Item = PathBuf>) -> StrResult<()> {
// Mark all files as not "seen" so that we may unwatch them if they
// aren't in the dependency list.
#[allow(clippy::iter_over_hash_type, reason = "order does not matter")]
for seen in self.watched.values_mut() {
*seen = false;
}
// Reset which files are missing.
self.missing.clear();
// Retrieve the dependencies of the last compilation and watch new paths
// that weren't watched yet.
for path in iter {
// We can't watch paths that don't exist with notify-rs. Instead, we
// add those to a `missing` set and fall back to manual poll
// watching.
if !path.exists() {
self.missing.insert(path);
continue;
}
// Watch the path if it's not already watched.
if !self.watched.contains_key(&path) {
self.watcher
.watch(&path, RecursiveMode::NonRecursive)
.map_err(|err| eco_format!("failed to watch {path:?} ({err})"))?;
}
// Mark the file as "seen" so that we don't unwatch it.
self.watched.insert(path, true);
}
// Unwatch old paths that don't need to be watched anymore.
self.watched.retain(|path, &mut seen| {
if !seen {
self.watcher.unwatch(path).ok();
}
seen
});
Ok(())
}
/// Wait until there is a change to a watched path.
fn wait(&mut self) -> StrResult<()> {
loop {
// Wait for an initial event. If there are missing files, we need to
// poll those regularly to check whether they are created, so we
// wait with a smaller timeout.
let first = self.rx.recv_timeout(if self.missing.is_empty() {
Duration::MAX
} else {
Self::POLL_INTERVAL
});
// Watch for file system events. If multiple events happen
// consecutively all within a certain duration, then they are
// bunched up without a recompile in-between. This helps against
// some editors' remove & move behavior. Events are also only
// watched until a certain point, to hinder a barrage of events from
// preventing recompilations.
let mut relevant = false;
let batch_start = Instant::now();
for event in first
.into_iter()
.chain(iter::from_fn(|| self.rx.recv_timeout(Self::BATCH_TIMEOUT).ok()))
.take_while(|_| batch_start.elapsed() <= Self::STARVE_TIMEOUT)
{
let event = event
.map_err(|err| eco_format!("failed to watch dependencies ({err})"))?;
if !is_relevant_event_kind(&event.kind) {
continue;
}
// Workaround for notify-rs' implicit unwatch on remove/rename
// (triggered by some editors when saving files) with the
// inotify backend. By keeping track of the potentially
// unwatched files, we can allow those we still depend on to be
// watched again later on.
if matches!(
event.kind,
notify::EventKind::Remove(notify::event::RemoveKind::File)
| notify::EventKind::Modify(notify::event::ModifyKind::Name(
notify::event::RenameMode::From
))
) {
for path in &event.paths {
// Remove affected path from the watched map to restart
// watching on it later again.
self.watcher.unwatch(path).ok();
self.watched.remove(path);
}
}
// Don't recompile because the output file changed.
// FIXME: This doesn't work properly for multifile image export.
if event
.paths
.iter()
.all(|path| is_same_file(path, &self.output).unwrap_or(false))
{
continue;
}
relevant = true;
}
// If we found a relevant event or if any of the missing files now
// exists, stop waiting.
if relevant || self.missing.iter().any(|path| path.exists()) {
return Ok(());
}
}
}
}
/// Whether a kind of watch event is relevant for compilation.
fn is_relevant_event_kind(kind: ¬ify::EventKind) -> bool {
match kind {
notify::EventKind::Any => true,
notify::EventKind::Access(_) => false,
notify::EventKind::Create(_) => true,
notify::EventKind::Modify(kind) => match kind {
notify::event::ModifyKind::Any => true,
notify::event::ModifyKind::Data(_) => true,
notify::event::ModifyKind::Metadata(_) => false,
notify::event::ModifyKind::Name(_) => true,
notify::event::ModifyKind::Other => false,
},
notify::EventKind::Remove(_) => true,
notify::EventKind::Other => false,
}
}
/// The status in which the watcher can be.
pub enum Status {
Compiling,
Success(std::time::Duration),
PartialSuccess(std::time::Duration),
Error,
}
impl Status {
/// Clear the terminal and render the status message.
pub fn print(&self, config: &CompileConfig) -> io::Result<()> {
let timestamp = chrono::offset::Local::now().format("%H:%M:%S");
let color = self.color();
let mut out = terminal::out();
out.clear_screen()?;
out.set_color(&color)?;
write!(out, "watching")?;
out.reset()?;
match &config.input {
Input::Stdin => writeln!(out, " <stdin>"),
Input::Path(path) => writeln!(out, " {}", path.display()),
}?;
out.set_color(&color)?;
write!(out, "writing to")?;
out.reset()?;
writeln!(out, " {}", config.output)?;
#[cfg(feature = "http-server")]
if let Some(server) = &config.server {
out.set_color(&color)?;
write!(out, "serving at")?;
out.reset()?;
writeln!(out, " http://{}", server.addr())?;
}
writeln!(out)?;
writeln!(out, "[{timestamp}] {}", self.message())?;
writeln!(out)?;
out.flush()
}
fn message(&self) -> String {
match *self {
Self::Compiling => "compiling ...".into(),
Self::Success(duration) => {
format!("compiled successfully in {}", format_duration(duration))
}
Self::PartialSuccess(duration) => {
format!("compiled with warnings in {}", format_duration(duration))
}
Self::Error => "compiled with errors".into(),
}
}
fn color(&self) -> termcolor::ColorSpec {
let styles = term::Styles::default();
match self {
Self::Error => styles.header_error,
Self::PartialSuccess(_) => styles.header_warning,
_ => styles.header_note,
}
}
}
/// Emits a warning when trying to watch stdin.
fn warn_watching_std(world: &SystemWorld, config: &CompileConfig) -> StrResult<()> {
let warning = warning!(
Span::detached(),
"cannot watch changes for stdin";
hint: "to recompile on changes, watch a regular file instead";
hint: "to compile once and exit, please use `typst compile` instead";
);
print_diagnostics(world, &[], &[warning], config.diagnostic_format)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/terminal.rs | crates/typst-cli/src/terminal.rs | use std::io::{self, IsTerminal, Write};
use codespan_reporting::term::termcolor;
use termcolor::{ColorChoice, WriteColor};
use typst::utils::singleton;
use crate::ARGS;
/// Returns a handle to the optionally colored terminal output.
pub fn out() -> TermOut {
TermOut {
inner: singleton!(TermOutInner, TermOutInner::new()),
}
}
/// A utility that allows users to write colored terminal output.
/// If colors are not supported by the terminal, they are disabled.
/// This type also allows for deletion of previously written lines.
#[derive(Clone)]
pub struct TermOut {
inner: &'static TermOutInner,
}
impl TermOut {
/// Clears the entire screen.
pub fn clear_screen(&mut self) -> io::Result<()> {
// We don't want to clear anything that is not a TTY.
if self.inner.stream.supports_color() {
let mut stream = self.inner.stream.lock();
// Clear the screen and then move the cursor to the top left corner.
write!(stream, "\x1B[2J\x1B[1;1H")?;
stream.flush()?;
}
Ok(())
}
/// Clears the previously written line.
pub fn clear_last_line(&mut self) -> io::Result<()> {
// We don't want to clear anything that is not a TTY.
if self.inner.stream.supports_color() {
// First, move the cursor up `lines` lines.
// Then, clear everything between the cursor to end of screen.
let mut stream = self.inner.stream.lock();
write!(stream, "\x1B[1F\x1B[0J")?;
stream.flush()?;
}
Ok(())
}
}
impl Write for TermOut {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.stream.lock().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.stream.lock().flush()
}
}
impl WriteColor for TermOut {
fn supports_color(&self) -> bool {
self.inner.stream.supports_color()
}
fn set_color(&mut self, spec: &termcolor::ColorSpec) -> io::Result<()> {
self.inner.stream.lock().set_color(spec)
}
fn reset(&mut self) -> io::Result<()> {
self.inner.stream.lock().reset()
}
}
/// The stuff that has to be shared between instances of [`TermOut`].
struct TermOutInner {
stream: termcolor::StandardStream,
}
impl TermOutInner {
fn new() -> Self {
let color_choice = match ARGS.color {
clap::ColorChoice::Auto if std::io::stderr().is_terminal() => {
ColorChoice::Auto
}
clap::ColorChoice::Always => ColorChoice::Always,
_ => ColorChoice::Never,
};
let stream = termcolor::StandardStream::stderr(color_choice);
TermOutInner { stream }
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/init.rs | crates/typst-cli/src/init.rs | use std::io::Write;
use std::path::Path;
use codespan_reporting::term::termcolor::{Color, ColorSpec, WriteColor};
use ecow::eco_format;
use fs_extra::dir::CopyOptions;
use typst::diag::{FileError, StrResult, bail};
use typst::syntax::package::{
PackageManifest, PackageSpec, TemplateInfo, VersionlessPackageSpec,
};
use crate::args::InitCommand;
use crate::download::PrintDownload;
use crate::package;
/// Execute an initialization command.
pub fn init(command: &InitCommand) -> StrResult<()> {
let package_storage = package::storage(&command.package);
// Parse the package specification. If the user didn't specify the version,
// we try to figure it out automatically by downloading the package index
// or searching the disk.
let spec: PackageSpec = command.template.parse().or_else(|err| {
// Try to parse without version, but prefer the error message of the
// normal package spec parsing if it fails.
let spec: VersionlessPackageSpec = command.template.parse().map_err(|_| err)?;
let version = package_storage.determine_latest_version(&spec)?;
StrResult::Ok(spec.at(version))
})?;
// Find or download the package.
let package_path =
package_storage.prepare_package(&spec, &mut PrintDownload(&spec))?;
// Parse the manifest.
let manifest = parse_manifest(&package_path)?;
manifest.validate(&spec)?;
// Ensure that it is indeed a template.
let Some(template) = &manifest.template else {
bail!("package {spec} is not a template");
};
// Determine the directory at which we will create the project.
let project_dir = Path::new(command.dir.as_deref().unwrap_or(&manifest.package.name));
// Set up the project.
scaffold_project(project_dir, &package_path, template)?;
// Print the summary.
print_summary(spec, project_dir, template).unwrap();
Ok(())
}
/// Parses the manifest of the package located at `package_path`.
fn parse_manifest(package_path: &Path) -> StrResult<PackageManifest> {
let toml_path = package_path.join("typst.toml");
let string = std::fs::read_to_string(&toml_path).map_err(|err| {
eco_format!(
"failed to read package manifest ({})",
FileError::from_io(err, &toml_path)
)
})?;
toml::from_str(&string)
.map_err(|err| eco_format!("package manifest is malformed ({})", err.message()))
}
/// Creates the project directory with the template's contents and returns the
/// path at which it was created.
fn scaffold_project(
project_dir: &Path,
package_path: &Path,
template: &TemplateInfo,
) -> StrResult<()> {
if project_dir.exists() {
bail!("project directory already exists (at {})", project_dir.display());
}
let template_dir = package_path.join(template.path.as_str());
if !template_dir.exists() {
bail!("template directory does not exist (at {})", template_dir.display());
}
fs_extra::dir::copy(
&template_dir,
project_dir,
&CopyOptions::new().content_only(true),
)
.map_err(|err| eco_format!("failed to create project directory ({err})"))?;
Ok(())
}
/// Prints a summary after successful initialization.
fn print_summary(
spec: PackageSpec,
project_dir: &Path,
template: &TemplateInfo,
) -> std::io::Result<()> {
let mut gray = ColorSpec::new();
gray.set_fg(Some(Color::White));
gray.set_dimmed(true);
let mut out = crate::terminal::out();
writeln!(out, "Successfully created new project from {spec} 🎉")?;
writeln!(out, "To start writing, run:")?;
out.set_color(&gray)?;
write!(out, "> ")?;
out.reset()?;
writeln!(
out,
"cd {}",
shell_escape::escape(project_dir.display().to_string().into()),
)?;
out.set_color(&gray)?;
write!(out, "> ")?;
out.reset()?;
writeln!(
out,
"typst watch {}",
shell_escape::escape(template.entrypoint.to_string().into()),
)?;
writeln!(out)?;
Ok(())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/completions.rs | crates/typst-cli/src/completions.rs | use std::io::stdout;
use clap::CommandFactory;
use clap_complete::generate;
use crate::args::{CliArguments, CompletionsCommand};
/// Execute the completions command.
pub fn completions(command: &CompletionsCommand) {
let mut cmd = CliArguments::command();
let bin_name = cmd.get_name().to_string();
generate(command.shell, &mut cmd, bin_name, &mut stdout());
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/eval.rs | crates/typst-cli/src/eval.rs | use comemo::Track;
use ecow::eco_format;
use typst::diag::{HintedStrResult, SourceResult, Warned};
use typst::foundations::{Context, Scope, StyleChain, Value};
use typst::syntax::{Span, SyntaxMode};
use typst::{World, engine::Sink, introspection::Introspector, layout::PagedDocument};
use typst_eval::eval_string;
use typst_html::HtmlDocument;
use crate::args::{EvalCommand, Target};
use crate::compile::print_diagnostics;
use crate::set_failed;
use crate::world::SystemWorld;
/// Execute a query command.
pub fn eval(command: &'static EvalCommand) -> HintedStrResult<()> {
let mut world =
SystemWorld::new(command.r#in.as_ref(), &command.world, &command.process)?;
// Reset everything and ensure that the main file is present.
world.reset();
world.source(world.main()).map_err(|err| err.to_string())?;
// Compile the main file and get the introspector.
let Warned { output, mut warnings } = match command.target {
Target::Paged => typst::compile::<PagedDocument>(&world)
.map(|output| output.map(|document| document.introspector)),
Target::Html => typst::compile::<HtmlDocument>(&world)
.map(|output| output.map(|document| document.introspector)),
};
match output {
// Retrieve and print evaluation results.
Ok(introspector) => {
let mut sink = Sink::new();
let eval_result = evaluate_expression(
command.expression.clone(),
&mut sink,
&world,
&introspector,
);
let errors = match &eval_result {
Err(errors) => errors.as_slice(),
Ok(value) => {
let serialized =
crate::serialize(value, command.format, command.pretty)?;
println!("{serialized}");
&[]
}
};
// Collect additional warnings from evaluating the expression.
warnings.extend(sink.warnings());
print_diagnostics(
&world,
errors,
&warnings,
command.process.diagnostic_format,
)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
}
// Print diagnostics.
Err(errors) => {
set_failed();
print_diagnostics(
&world,
&errors,
&warnings,
command.process.diagnostic_format,
)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
}
}
Ok(())
}
/// Evaluates the expression with code syntax mode and no scope.
fn evaluate_expression(
expression: String,
sink: &mut Sink,
world: &dyn World,
introspector: &Introspector,
) -> SourceResult<Value> {
eval_string(
&typst::ROUTINES,
world.track(),
sink.track_mut(),
introspector.track(),
Context::new(None, Some(StyleChain::new(&world.library().styles))).track(),
&expression,
Span::detached(),
SyntaxMode::Code,
Scope::default(),
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/server.rs | crates/typst-cli/src/server.rs | use std::io::{self, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::sync::Arc;
use ecow::eco_format;
use parking_lot::{Condvar, Mutex, MutexGuard};
use tiny_http::{Header, Request, Response, StatusCode};
use typst::diag::{StrResult, bail};
use crate::args::{Input, ServerArgs};
/// Serves HTML with live reload.
pub struct HtmlServer {
addr: SocketAddr,
bucket: Arc<Bucket<String>>,
}
impl HtmlServer {
/// Create a new HTTP server that serves live HTML.
pub fn new(input: &Input, args: &ServerArgs) -> StrResult<Self> {
let reload = !args.no_reload;
let (addr, server) = start_server(args.port)?;
let placeholder = PLACEHOLDER_HTML.replace("{INPUT}", &input.to_string());
let bucket = Arc::new(Bucket::new(placeholder));
let bucket2 = bucket.clone();
std::thread::spawn(move || {
for req in server.incoming_requests() {
let _ = handle(req, reload, &bucket2);
}
});
Ok(Self { addr, bucket })
}
/// The address that we serve the HTML on.
pub fn addr(&self) -> SocketAddr {
self.addr
}
/// Updates the HTML, triggering a reload all connected browsers.
pub fn update(&self, html: String) {
self.bucket.put(html);
}
}
/// Starts a local HTTP server.
///
/// Uses the specified port or tries to find a free port in the range
/// `3000..=3005`.
fn start_server(port: Option<u16>) -> StrResult<(SocketAddr, tiny_http::Server)> {
const BASE_PORT: u16 = 3000;
let mut addr;
let mut retries = 0;
let listener = loop {
addr = SocketAddr::new(
IpAddr::V4(Ipv4Addr::LOCALHOST),
port.unwrap_or(BASE_PORT + retries),
);
match TcpListener::bind(addr) {
Ok(listener) => break listener,
Err(err) if err.kind() == io::ErrorKind::AddrInUse => {
if let Some(port) = port {
bail!("port {port} is already in use")
} else if retries < 5 {
// If the port is in use, try the next one.
retries += 1;
} else {
bail!("could not find free port for HTTP server");
}
}
Err(err) => bail!("failed to start TCP server: {err}"),
}
};
let server = tiny_http::Server::from_listener(listener, None)
.map_err(|err| eco_format!("failed to start HTTP server: {err}"))?;
Ok((addr, server))
}
/// Handles a request.
fn handle(req: Request, reload: bool, bucket: &Arc<Bucket<String>>) -> io::Result<()> {
let path = req.url();
match path {
"/" => handle_root(req, reload, bucket),
"/events" => handle_events(req, bucket.clone()),
_ => req.respond(Response::new_empty(StatusCode(404))),
}
}
/// Handles for the `/` route. Serves the compiled HTML.
fn handle_root(req: Request, reload: bool, bucket: &Bucket<String>) -> io::Result<()> {
let mut html = bucket.get().clone();
if reload {
inject_live_reload_script(&mut html);
}
req.respond(Response::new(
StatusCode(200),
vec![Header::from_bytes("Content-Type", "text/html").unwrap()],
html.as_bytes(),
Some(html.len()),
None,
))
}
/// Handler for the `/events` route.
fn handle_events(req: Request, bucket: Arc<Bucket<String>>) -> io::Result<()> {
std::thread::spawn(move || {
// When this returns an error, the client is disconnected and we can
// terminate the thread.
let _ = handle_events_blocking(req, &bucket);
});
Ok(())
}
/// Event stream for the `/events` route.
fn handle_events_blocking(req: Request, bucket: &Bucket<String>) -> io::Result<()> {
let mut writer = req.into_writer();
let writer: &mut dyn Write = &mut *writer;
// We need to write the header manually because `tiny-http` defaults to
// `Transfer-Encoding: chunked` when no `Content-Length` is provided, which
// Chrome & Safari dislike for `Content-Type: text/event-stream`.
write!(writer, "HTTP/1.1 200 OK\r\n")?;
write!(writer, "Content-Type: text/event-stream\r\n")?;
write!(writer, "Cache-Control: no-cache\r\n")?;
write!(writer, "\r\n")?;
writer.flush()?;
// If the user closes the browser tab, this loop will terminate once it
// tries to write to the dead socket for the first time.
loop {
bucket.wait();
// Trigger a server-sent event. The browser is listening to it via
// an `EventSource` listener` (see `inject_script`).
write!(writer, "event: reload\ndata:\n\n")?;
writer.flush()?;
}
}
/// Injects the live reload script into a string of HTML.
fn inject_live_reload_script(html: &mut String) {
let pos = html.rfind("</html>").unwrap_or(html.len());
html.insert_str(pos, LIVE_RELOAD_SCRIPT);
}
/// Holds data and notifies consumers when it's updated.
struct Bucket<T> {
mutex: Mutex<T>,
condvar: Condvar,
}
impl<T> Bucket<T> {
/// Creates a new bucket with initial data.
fn new(init: T) -> Self {
Self { mutex: Mutex::new(init), condvar: Condvar::new() }
}
/// Retrieves the current data in the bucket.
fn get(&self) -> MutexGuard<'_, T> {
self.mutex.lock()
}
/// Puts new data into the bucket and notifies everyone who's currently
/// [waiting](Self::wait).
fn put(&self, data: T) {
*self.mutex.lock() = data;
self.condvar.notify_all();
}
/// Waits for new data in the bucket.
fn wait(&self) {
self.condvar.wait(&mut self.mutex.lock());
}
}
/// The initial HTML before compilation is finished.
const PLACEHOLDER_HTML: &str = "\
<!DOCTYPE html>
<html>
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<title>Waiting for {INPUT}</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
color: #565565;
background: #eff0f3;
}
body > main > div {
margin-block: 16px;
text-align: center;
}
</style>
</head>
<body>
<main>
<div>Waiting for output…</div>
<div><code>typst watch {INPUT}</code></div>
</main>
</body>
</html>
";
/// Reloads the page whenever it receives a "reload" server-sent event
/// on the `/events` route.
const LIVE_RELOAD_SCRIPT: &str = "\
<script>\
new EventSource(\"/events\")\
.addEventListener(\"reload\", () => location.reload())\
</script>\
";
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/query.rs | crates/typst-cli/src/query.rs | use std::fmt::Write;
use comemo::Track;
use ecow::{EcoString, eco_format};
use typst::World;
use typst::diag::{HintedStrResult, SourceDiagnostic, StrResult, Warned, bail};
use typst::engine::Sink;
use typst::foundations::{Content, Context, IntoValue, LocatableSelector, Repr, Scope};
use typst::introspection::Introspector;
use typst::layout::PagedDocument;
use typst::syntax::{Span, SyntaxMode};
use typst_eval::eval_string;
use typst_html::HtmlDocument;
use crate::args::{Input, QueryCommand, Target};
use crate::compile::print_diagnostics;
use crate::set_failed;
use crate::world::SystemWorld;
/// Execute a query command.
pub fn query(command: &'static QueryCommand) -> HintedStrResult<()> {
let mut world =
SystemWorld::new(Some(&command.input), &command.world, &command.process)?;
// Reset everything and ensure that the main file is present.
world.reset();
world.source(world.main()).map_err(|err| err.to_string())?;
let Warned { output, mut warnings } = match command.target {
Target::Paged => typst::compile::<PagedDocument>(&world)
.map(|output| output.map(|document| document.introspector)),
Target::Html => typst::compile::<HtmlDocument>(&world)
.map(|output| output.map(|document| document.introspector)),
};
// Add deprecation warning.
warnings.push(deprecation_warning(command));
match output {
// Retrieve and print query results.
Ok(introspector) => {
let data = retrieve(&world, command, &introspector)?;
let serialized = format(data, command)?;
println!("{serialized}");
print_diagnostics(&world, &[], &warnings, command.process.diagnostic_format)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
}
// Print diagnostics.
Err(errors) => {
set_failed();
print_diagnostics(
&world,
&errors,
&warnings,
command.process.diagnostic_format,
)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
}
}
Ok(())
}
/// Retrieve the matches for the selector.
fn retrieve(
world: &dyn World,
command: &QueryCommand,
introspector: &Introspector,
) -> HintedStrResult<Vec<Content>> {
let selector = eval_string(
&typst::ROUTINES,
world.track(),
// TODO: propagate warnings
Sink::new().track_mut(),
Introspector::default().track(),
Context::none().track(),
&command.selector,
Span::detached(),
SyntaxMode::Code,
Scope::default(),
)
.map_err(|errors| {
let mut message = EcoString::from("failed to evaluate selector");
for (i, error) in errors.into_iter().enumerate() {
message.push_str(if i == 0 { ": " } else { ", " });
message.push_str(&error.message);
}
message
})?
.cast::<LocatableSelector>()?;
Ok(introspector.query(&selector.0).into_iter().collect::<Vec<_>>())
}
/// Format the query result in the output format.
fn format(elements: Vec<Content>, command: &QueryCommand) -> StrResult<String> {
if command.one && elements.len() != 1 {
bail!("expected exactly one element, found {}", elements.len());
}
let mapped: Vec<_> = elements
.into_iter()
.filter_map(|c| match &command.field {
Some(field) => c.get_by_name(field).ok(),
_ => Some(c.into_value()),
})
.collect();
if command.one {
let Some(value) = mapped.first() else {
bail!("no such field found for element");
};
crate::serialize(value, command.format, command.pretty)
} else {
crate::serialize(&mapped, command.format, command.pretty)
}
}
/// Format the deprecation warning with the specific invocation of `typst eval` needed to replace `typst query`.
fn deprecation_warning(command: &QueryCommand) -> SourceDiagnostic {
let query = {
let mut buf = format!("query({})", command.selector);
let access = |field: &str| {
if typst::syntax::is_ident(field) {
eco_format!(".{field}")
} else {
eco_format!(".at({})", field.repr())
}
};
match (command.one, &command.field) {
(false, None) => {}
(false, Some(field)) => {
write!(buf, ".map(it => it{})", access(field)).unwrap()
}
(true, None) => write!(buf, ".first()").unwrap(),
(true, Some(field)) => write!(buf, ".first(){}", access(field)).unwrap(),
}
shell_escape::escape(buf.into())
};
let eval_command = match &command.input {
Input::Path(path) => {
eco_format!("typst eval {query} --in {}", path.display())
}
Input::Stdin => eco_format!("typst eval {query}"),
};
SourceDiagnostic::warning(
Span::detached(),
"the `typst query` subcommand is deprecated",
)
.with_hint(eco_format!("use `{}` instead", eval_command))
}
| 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.