tinymist_std::typst::foundations::func

Struct Func

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§

§

impl Func

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

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

Returns None if this is an anonymous closure.

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.

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

Documentation for the function (as Markdown).

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

Whether the function is known to be contextual.

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

Get details about this function’s parameters if available.

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

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

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

Get details about the function’s return type.

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

Search keywords for the function.

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

The function’s associated scope of sub-definition.

pub fn field( &self, field: &str, sink: impl DeprecationSink, ) -> Result<&'static Value, EcoString>

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

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

Extract the element function, if it is one.

pub fn to_plugin(&self) -> Option<&PluginFunc>

Extract the plugin function, if it is one.

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

Call the function with the given context and arguments.

pub fn span(&self) -> Span

The function’s span.

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

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

pub fn inner(&self) -> &Repr

The function’s repr

§

impl Func

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

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

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

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§

§

impl Clone for Func

§

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
§

impl Debug for Func

§

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

Formats the value using the given formatter. Read more
§

impl From<&'static NativeFuncData> for Func

§

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

Converts to this type from the input type.
§

impl From<Closure> for Func

§

fn from(closure: Closure) -> Func

Converts to this type from the input type.
§

impl From<Element> for Func

§

fn from(func: Element) -> Func

Converts to this type from the input type.
§

impl From<PluginFunc> for Func

§

fn from(func: PluginFunc) -> Func

Converts to this type from the input type.
§

impl From<Repr> for Func

§

fn from(repr: Repr) -> Func

Converts to this type from the input type.
§

impl FromValue for Func

§

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

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

impl Hash for Func

§

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

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
§

impl IntoValue for Func

§

fn into_value(self) -> Value

Cast this type into a value.
§

impl NativeScope for Func

§

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

The constructor function for the type, if any.
§

fn scope() -> Scope

Get the associated scope for the type.
§

impl NativeType for Func

§

const NAME: &'static str = "function"

The type’s name. Read more
§

fn data() -> &'static NativeTypeData

§

fn ty() -> Type

Get the type for the native Rust type.
§

impl PartialEq<&'static NativeFuncData> for Func

§

fn eq(&self, other: &&'static 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.
§

impl PartialEq for Func

§

fn eq(&self, other: &Func) -> 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.
§

impl Reflect for Func

§

fn input() -> CastInfo

Describe what can be cast into this value.
§

fn output() -> CastInfo

Describe what this value can be cast into.
§

fn castable(value: &Value) -> bool

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

fn error(found: &Value) -> HintedString

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

impl Repr for Func

§

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<S, T> ArcInto<T> for S
where Arc<S>: Into<T>,

Source§

fn arc_into(self: Arc<S>) -> T

Converts Arc<T> into Self.
§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
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
§

impl<T> CallHasher for T
where T: Hash + ?Sized,

§

fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64
where H: Hash + ?Sized, B: BuildHasher,

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 u8)

🔬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.
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D, ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
§

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

§

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.
§

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.
§

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.
§

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.
§

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

§

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.
§

impl<T> Filterable for T

§

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.
§

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

§

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
§

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

§

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.
§

impl<T> LayoutRaw for T

§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Gets the layout of the type.
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.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
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.
§

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

§

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.
§

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

§

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