typst::foundations

Struct Func

source
pub struct Func { /* private fields */ }
Expand description

A mapping from argument values to a return value.

You can call a function by writing a comma-separated list of function arguments enclosed in parentheses directly after the function name. Additionally, you can pass any number of trailing content blocks arguments to a function after the normal argument list. If the normal argument list would become empty, it can be omitted. Typst supports positional and named arguments. The former are identified by position and type, while the latter are written as name: value.

Within math mode, function calls have special behaviour. See the math documentation for more details.

§Example

// Call a function.
#list([A], [B])

// Named arguments and trailing
// content blocks.
#enum(start: 2)[A][B]

// Version without parentheses.
#list[A][B]

Functions are a fundamental building block of Typst. Typst provides functions for a variety of typesetting tasks. Moreover, the markup you write is backed by functions and all styling happens through functions. This reference lists all available functions and how you can use them. Please also refer to the documentation about set and show rules to learn about additional ways you can work with functions in Typst.

§Element functions

Some functions are associated with elements like headings or tables. When called, these create an element of their respective kind. In contrast to normal functions, they can further be used in set rules, show rules, and selectors.

§Function scopes

Functions can hold related definitions in their own scope, similar to a module. Examples of this are assert.eq or list.item. However, this feature is currently only available for built-in functions.

§Defining functions

You can define your own function with a let binding that has a parameter list after the binding’s name. The parameter list can contain mandatory positional parameters, named parameters with default values and argument sinks.

The right-hand side of a function binding is the function body, which can be a block or any other expression. It defines the function’s return value and can depend on the parameters. If the function body is a code block, the return value is the result of joining the values of each expression in the block.

Within a function body, the return keyword can be used to exit early and optionally specify a return value. If no explicit return value is given, the body evaluates to the result of joining all expressions preceding the return.

Functions that don’t return any meaningful value return [none] instead. The return type of such functions is not explicitly specified in the documentation. (An example of this is [array.push]).

#let alert(body, fill: red) = {
  set text(white)
  set align(center)
  rect(
    fill: fill,
    inset: 8pt,
    radius: 4pt,
    [*Warning:\ #body*],
  )
}

#alert[
  Danger is imminent!
]

#alert(fill: blue)[
  KEEP OFF TRACKS
]

§Importing functions

Functions can be imported from one file (module) into another using {import}. For example, assume that we have defined the alert function from the previous example in a file called foo.typ. We can import it into another file by writing {import "foo.typ": alert}.

§Unnamed functions { #unnamed }

You can also created an unnamed function without creating a binding by specifying a parameter list followed by => and the function body. If your function has just one parameter, the parentheses around the parameter list are optional. Unnamed functions are mainly useful for show rules, but also for settable properties that take functions like the page function’s footer property.

#show "once?": it => [#it #it]
once?

§Note on function purity

In Typst, all functions are pure. This means that for the same arguments, they always return the same result. They cannot “remember” things to produce another value when they are called a second time.

The only exception are built-in methods like array.push(value). These can modify the values they are called on.

Implementations§

source§

impl Func

source

pub fn name(&self) -> Option<&str>

The function’s name (e.g. min).

Returns None if this is an anonymous closure.

source

pub fn title(&self) -> Option<&'static str>

The function’s title case name, for use in documentation (e.g. Minimum).

Returns None if this is a closure.

source

pub fn docs(&self) -> Option<&'static str>

Documentation for the function (as Markdown).

source

pub fn contextual(&self) -> Option<bool>

Whether the function is known to be contextual.

source

pub fn params(&self) -> Option<&'static [ParamInfo]>

Get details about this function’s parameters if available.

source

pub fn param(&self, name: &str) -> Option<&'static ParamInfo>

Get the parameter info for a parameter with the given name if it exist.

source

pub fn returns(&self) -> Option<&'static CastInfo>

Get details about the function’s return type.

source

pub fn keywords(&self) -> &'static [&'static str]

Search keywords for the function.

source

pub fn scope(&self) -> Option<&'static Scope>

The function’s associated scope of sub-definition.

source

pub fn field(&self, field: &str) -> StrResult<&'static Value>

Get a field from this function’s scope, if possible.

source

pub fn element(&self) -> Option<Element>

Extract the element function, if it is one.

source

pub fn call<A: IntoArgs>( &self, engine: &mut Engine<'_>, context: Tracked<'_, Context<'_>>, args: A, ) -> SourceResult<Value>

Call the function with the given context and arguments.

source

pub fn span(&self) -> Span

The function’s span.

source

pub fn spanned(self, span: Span) -> Self

Attach a span to this function if it doesn’t already have one.

source§

impl Func

source

pub fn with(self, args: &mut Args) -> Func

Returns a new function that has the given arguments pre-applied.

source

pub fn where_(self, args: &mut Args) -> StrResult<Selector>

Returns a selector that filters for elements belonging to this function whose fields have the values of the given arguments.

#show heading.where(level: 2): set text(blue)
= Section
== Subsection
=== Sub-subsection

Trait Implementations§

source§

impl Clone for Func

source§

fn clone(&self) -> Func

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Func

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<&'static NativeFuncData> for Func

source§

fn from(data: &'static NativeFuncData) -> Self

Converts to this type from the input type.
source§

impl From<Closure> for Func

source§

fn from(closure: Closure) -> Self

Converts to this type from the input type.
source§

impl From<Element> for Func

source§

fn from(func: Element) -> Self

Converts to this type from the input type.
source§

impl FromValue for Func

source§

fn from_value(value: Value) -> HintedStrResult<Self>

Try to cast the value into an instance of Self.
source§

impl Hash for Func

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl IntoValue for Func

source§

fn into_value(self) -> Value

Cast this type into a value.
source§

impl NativeScope for Func

source§

fn constructor() -> Option<&'static NativeFuncData>

The constructor function for the type, if any.
source§

fn scope() -> Scope

Get the associated scope for the type.
source§

impl NativeType for Func

source§

const NAME: &'static str = "function"

The type’s name. Read more
source§

fn data() -> &'static NativeTypeData

source§

fn ty() -> Type

Get the type for the native Rust type.
source§

impl PartialEq<&NativeFuncData> for Func

source§

fn eq(&self, other: &&NativeFuncData) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq for Func

source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Reflect for Func

source§

fn input() -> CastInfo

Describe what can be cast into this value.
source§

fn output() -> CastInfo

Describe what this value can be cast into.
source§

fn castable(value: &Value) -> bool

Whether the given value can be converted to T. Read more
source§

fn error(found: &Value) -> HintedString

Produce an error message for an unacceptable value type. Read more
source§

impl Repr for Func

source§

fn repr(&self) -> EcoString

Return the debug representation of the value.

Auto Trait Implementations§

§

impl Freeze for Func

§

impl !RefUnwindSafe for Func

§

impl Send for Func

§

impl Sync for Func

§

impl Unpin for Func

§

impl !UnwindSafe for Func

Blanket Implementations§

source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
source§

impl<T> Az for T

source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

source§

fn cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> CheckedAs for T

source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
source§

impl<T> Downcast for T
where T: Any,

source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> Filterable for T

source§

fn filterable( self, filter_name: &'static str, ) -> RequestFilterDataProvider<T, fn(_: DataRequest<'_>) -> bool>

Creates a filterable data provider with the given name for debugging. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromAngle<T> for T

source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
source§

impl<T> FromValue<Spanned<Value>> for T
where T: FromValue,

source§

fn from_value(value: Spanned<Value>) -> Result<T, HintedString>

Try to cast the value into an instance of Self.
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

source§

fn into_angle(self) -> U

Performs a conversion into T.
source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> IntoResult for T
where T: IntoValue,

source§

fn into_result(self, _: Span) -> Result<Value, EcoVec<SourceDiagnostic>>

Cast this type into a value.
source§

impl<T> IntoStimulus<T> for T

source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
source§

impl<T> OverflowingAs for T

source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
source§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> SaturatingAs for T

source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
source§

impl<T> UnwrappedAs for T

source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WrappingAs for T

source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> ErasedDestructor for T
where T: 'static,

source§

impl<T> MaybeSendSync for T
where T: Send + Sync,