TypstDocumentation

function

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 later 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]
Preview

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.

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 positional parameters, named parameters with default values and argument sinks. The right-hand side of the binding can be a block or any other expression. It defines the function's return value and can depend on the parameters.

#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
]
Preview

Unnamed functions

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?
Preview

Notable fact

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.

Methods
Question mark

with method

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

value.with(
...any
) -> function

arguments
anyVariadic
Question mark

The named and positional arguments to apply.

where method

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

value.where() -> selector

fields
anyVariadic
Question mark

The field values to filter by.