feat: initial commit

This commit is contained in:
johannes committed 2026-07-26 11:45:34 +02:00
commit a83e1a806e
454 files changed
+52429

No files matched your search

@@ -0,0 +1,149 @@
# Context
Sometimes, we want to create content that reacts to its location in the document. This could be a localized phrase that depends on the configured text language or something as simple as a heading number which prints the right value based on how many headings came before it. However, Typst code isn't directly aware of its location in the document. Some code at the beginning of the source text could yield content that ends up at the back of the document.
To produce content that is reactive to its surroundings, we must thus specifically instruct Typst: We do this with the `context` keyword, which precedes an expression and ensures that it is computed with knowledge of its environment. In return, the context expression itself ends up opaque. We cannot directly access whatever results from it in our code, precisely because it is contextual: There is no one correct result, there may be multiple results in different places of the document. For this reason, everything that depends on the contextual data must happen inside of the context expression.
Aside from explicit context expressions, context is also established implicitly in some places that are also aware of their location in the document: [Show rules](/docs/reference/styling/#show-rules) provide context[1](#1) and numberings in the outline, for instance, also provide the proper context to resolve counters.
## Style context
With set rules, we can adjust style properties for parts or the whole of our document. We cannot access these without a known context, as they may change throughout the course of the document. When context is available, we can retrieve them simply by accessing them as fields on the respective element function.
```typst
#set text(lang: "de")
#context text.lang
```
As explained above, a context expression is reactive to the different environments it is placed into. In the example below, we create a single context expression, store it in the `value` variable and use it multiple times. Each use properly reacts to the current surroundings.
```typst
#let value = context text.lang
#value
#set text(lang: "de")
#value
#set text(lang: "fr")
#value
```
Crucially, upon creation, `value` becomes opaque [content](/docs/reference/foundations/content/) that we cannot peek into. It can only be resolved when placed somewhere because only then the context is known. The body of a context expression may be evaluated zero, one, or multiple times, depending on how many different places it is put into.
## Location context
We've already seen that context gives us access to set rule values. But it can do more: It also lets us know _where_ in the document we currently are, relative to other elements, and absolutely on the pages. We can use this information to create very flexible interactions between different document parts. This underpins features like heading numbering, the table of contents, or page headers dependent on section headings.
Some functions like [`counter.get`](/docs/reference/introspection/counter/#definitions-get) implicitly access the current location. In the example below, we want to retrieve the value of the heading counter. Since it changes throughout the document, we need to first enter a context expression. Then, we use `get` to retrieve the counter's current value. This function accesses the current location from the context to resolve the counter value. Counters have multiple levels and `get` returns an array with the resolved numbers. Thus, we get the following result:
```typst
#set heading(numbering: "1.")
= Introduction
#lorem(5)
#context counter(heading).get()
= Background
#lorem(5)
#context counter(heading).get()
```
For more flexibility, we can also use the [`here`](/docs/reference/introspection/here/) function to directly extract the current [location](/docs/reference/introspection/location/) from the context. The example below demonstrates this:
- We first have `counter(heading).get()`, which resolves to `(2,)` as before.
- We then use the more powerful [`counter.at`](/docs/reference/introspection/counter/#definitions-at) with [`here`](/docs/reference/introspection/here/), which in combination is equivalent to `get`, and thus get `(2,)`.
- Finally, we use `at` with a [label](/docs/reference/foundations/label/) to retrieve the value of the counter at a _different_ location in the document, in our case that of the introduction heading. This yields `(1,)`. Typst's context system gives us time travel abilities and lets us retrieve the values of any counters and states at _any_ location in the document.
```typst
#set heading(numbering: "1.")
= Introduction <intro>
#lorem(5)
= Background <back>
#lorem(5)
#context [
#counter(heading).get() \
#counter(heading).at(here()) \
#counter(heading).at(<intro>)
]
```
As mentioned before, we can also use context to get the physical position of elements on the pages. We do this with the [`locate`](/docs/reference/introspection/locate/) function, which works similarly to `counter.at`: It takes a location or other [selector](/docs/reference/foundations/selector/) that resolves to a unique element (could also be a label) and returns the position on the pages for that element.
```typst
Background is at: \
#context locate(<back>).position()
= Introduction <intro>
#lorem(5)
#pagebreak()
= Background <back>
#lorem(5)
```
There are other functions that make use of the location context, most prominently [`query`](/docs/reference/introspection/query/). Take a look at the [introspection](/docs/reference/introspection/) category for more details on those.
## Nested contexts
Context is also accessible from within function calls nested in context blocks. In the example below, `foo` itself becomes a contextual function, just like [`to-absolute`](/docs/reference/layout/length/#definitions-to-absolute) is.
```typst
#let foo() = 1em.to-absolute()
#context {
foo() == text.size
}
```
Context blocks can be nested. Contextual code will then always access the innermost context. The example below demonstrates this: The first `text.lang` will access the outer context block's styles and as such, it will **not** see the effect of `set text(lang: "fr")`. The nested context block around the second `text.lang`, however, starts after the set rule and will thus show its effect.
```typst
#set text(lang: "de")
#context [
#set text(lang: "fr")
#text.lang \
#context text.lang
]
```
You might wonder why Typst ignores the French set rule when computing the first `text.lang` in the example above. The reason is that, in the general case, Typst cannot know all the styles that will apply as set rules can be applied to content after it has been constructed. Below, `text.lang` is already computed when the template function is applied. As such, it cannot possibly be aware of the language change to French in the template.
```typst
#let template(body) = {
set text(lang: "fr")
upper(body)
}
#set text(lang: "de")
#context [
#show: template
#text.lang \
#context text.lang
]
```
The second `text.lang`, however, _does_ react to the language change because evaluation of its surrounding context block is deferred until the styles for it are known. This illustrates the importance of picking the right insertion point for a context to get access to precisely the right styles.
The same also holds true for the location context. Below, the first `c.display()` call will access the outer context block and will thus not see the effect of `c.update(2)` while the second `c.display()` accesses the inner context and will thus see it.
```typst
#let c = counter("mycounter")
#c.update(1)
#context [
#c.update(2)
#c.display() \
#context c.display()
]
```
## Compiler iterations
To resolve contextual interactions, the Typst compiler processes your document multiple times. For instance, to resolve a `locate` call, Typst first provides a placeholder position, layouts your document and then recompiles with the known position from the finished layout. The same approach is taken to resolve counters, states, and queries. In certain cases, Typst may even need more than two iterations to resolve everything. While that's sometimes a necessity, it may also be a sign of misuse of contextual functions (e.g. of [state](/docs/reference/introspection/state/#caution)). If Typst cannot resolve everything within five attempts, it will stop and output the warning "layout did not converge within 5 attempts."
A very careful reader might have noticed that not all of the functions presented above actually make use of the current location. While `counter(heading).get()` definitely depends on it, `counter(heading).at(<intro>)`, for instance, does not. However, it still requires context. While its value is always the same _within_ one compilation iteration, it may change over the course of multiple compiler iterations. If one could call it directly at the top level of a module, the whole module and its exports could change over the course of multiple compiler iterations, which would not be desirable.
[^1]: Currently, all show rules provide [style context](#style-context), but only show rules on [locatable](/docs/reference/introspection/location/#locatable) elements provide a [location context](#location-context).
@@ -0,0 +1,86 @@
# CBOR
# cbor
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
| CBOR value | Converted into Typst |
| --- | --- |
| integer | [`int`](/docs/reference/foundations/int/) (or [`float`](/docs/reference/foundations/float/)) |
| bytes | [`bytes`](/docs/reference/foundations/bytes/) |
| float | [`float`](/docs/reference/foundations/float/) |
| text | [`str`](/docs/reference/foundations/str/) |
| bool | [`bool`](/docs/reference/foundations/bool/) |
| null | `none` |
| array | [`array`](/docs/reference/foundations/array/) |
| map | [`dictionary`](/docs/reference/foundations/dictionary/) |
| Typst value | Converted into CBOR |
| --- | --- |
| types that can be converted from CBOR | corresponding CBOR value |
| [`symbol`](/docs/reference/foundations/symbol/) | text |
| [`content`](/docs/reference/foundations/content/) | a map describing the content |
| other types ([`length`](/docs/reference/layout/length/), etc.) | text via [`repr`](/docs/reference/foundations/repr/) |
### Notes
- Be aware that CBOR integers larger than 263-1 or smaller than -263 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](/docs/reference/foundations/repr/#debugging-only), and its output is not guaranteed to be stable across Typst versions.
```typst
#cbor(
source
) -> any
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a CBOR file or raw CBOR bytes.
- type: str | bytes
- default: None
## Definitions
### cbor.decode
Reads structured data from CBOR bytes.
```typst
#cbor.decode(
data
) -> any
```
#### Parameters
- data:
- description: CBOR data.
- type: bytes
- default: None
### cbor.encode
Encode structured data into CBOR bytes.
```typst
#cbor.encode(
value
) -> bytes
```
#### Parameters
- value:
- description: Value to be encoded.
- type: any
- default: None
@@ -0,0 +1,73 @@
# CSV
# csv
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
```typst
#let results = csv("example.csv")
#table(
columns: 2,
[*Condition*], [*Result*],
..results.flatten(),
)
```
```typst
#csv(
source,
delimiter: str,
row-type: type
) -> array
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a CSV file or raw CSV bytes.
- type: str | bytes
- default: None
- delimiter:
- description: The delimiter that separates columns in the CSV file. Must be a single ASCII character.
- type: str
- default: ","
- row-type:
- description: 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.
- type: type
- default: array
## Definitions
### csv.decode
Reads structured data from a CSV string/bytes.
```typst
#csv.decode(
data,
delimiter: str,
row-type: type
) -> array
```
#### Parameters
- data:
- description: CSV data.
- type: str | bytes
- default: None
- delimiter:
- description: The delimiter that separates columns in the CSV file. Must be a single ASCII character.
- type: str
- default: ","
- row-type:
- description: 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.
- type: type
- default: array
@@ -0,0 +1,24 @@
# Data Loading
Data loading from external files.
These functions help you with loading and embedding data, for example from the results of an experiment.
## Encoding
Some of the functions are also capable of encoding, e.g. [`cbor.encode`](/docs/reference/data-loading/cbor/#definitions-encode). They facilitate passing structured data to [plugins](/docs/reference/foundations/plugin/).
However, each data format has its own native types. Therefore, for an arbitrary Typst value, the encode-to-decode roundtrip might be lossy. In general, numbers, strings, and [arrays](/docs/reference/foundations/array/) or [dictionaries](/docs/reference/foundations/dictionary/) composed of them can be reliably converted, while other types may fall back to strings via [`repr`](/docs/reference/foundations/repr/), which is [for debugging purposes only](/docs/reference/foundations/repr/#debugging-only). Please refer to the page of each data format for details.
## Definitions
| Name | Description |
| --- | --- |
| [`cbor`](/reference/data-loading/cbor/) | Reads structured data from a CBOR file. |
| [`csv`](/reference/data-loading/csv/) | Reads structured data from a CSV file. |
| [`json`](/reference/data-loading/json/) | Reads structured data from a JSON file. |
| [`read`](/reference/data-loading/read/) | Reads plain text or data from a file. |
| [`toml`](/reference/data-loading/toml/) | Reads structured data from a TOML file. |
| [`xml`](/reference/data-loading/xml/) | Reads structured data from an XML file. |
| [`yaml`](/reference/data-loading/yaml/) | Reads structured data from a YAML file. |
@@ -0,0 +1,118 @@
# JSON
# json
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
```typst
#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
| JSON value | Converted into Typst |
| --- | --- |
| `null` | `none` |
| bool | [`bool`](/docs/reference/foundations/bool/) |
| number | [`float`](/docs/reference/foundations/float/) or [`int`](/docs/reference/foundations/int/) |
| string | [`str`](/docs/reference/foundations/str/) |
| array | [`array`](/docs/reference/foundations/array/) |
| object | [`dictionary`](/docs/reference/foundations/dictionary/) |
| Typst value | Converted into JSON |
| --- | --- |
| types that can be converted from JSON | corresponding JSON value |
| [`bytes`](/docs/reference/foundations/bytes/) | string via [`repr`](/docs/reference/foundations/repr/) |
| [`symbol`](/docs/reference/foundations/symbol/) | string |
| [`content`](/docs/reference/foundations/content/) | an object describing the content |
| other types ([`length`](/docs/reference/layout/length/), etc.) | string via [`repr`](/docs/reference/foundations/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 263-1 or smaller than -263 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`](/docs/reference/data-loading/cbor/#definitions-encode) for binary data.
- The `repr` function is [for debugging purposes only](/docs/reference/foundations/repr/#debugging-only), and its output is not guaranteed to be stable across Typst versions.
```typst
#json(
source
) -> any
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a JSON file or raw JSON bytes.
- type: str | bytes
- default: None
## Definitions
### json.decode
Reads structured data from a JSON string/bytes.
```typst
#json.decode(
data
) -> any
```
#### Parameters
- data:
- description: JSON data.
- type: str | bytes
- default: None
### json.encode
Encodes structured data into a JSON string.
```typst
#json.encode(
value,
pretty: bool
) -> str
```
#### Parameters
- value:
- description: Value to be encoded.
- type: any
- default: None
- pretty:
- description: Whether to pretty print the JSON with newlines and indentation.
- type: bool
- default: true
@@ -0,0 +1,40 @@
# Read
# read
Reads plain text or data from a file.
By default, the file will be read as UTF-8 and returned as a [string](/docs/reference/foundations/str/).
If you specify `encoding: none`, this returns raw [bytes](/docs/reference/foundations/bytes/) instead.
## Example
```typst
An example for a HTML file: \
#let text = read("example.html")
#raw(text, block: true, lang: "html")
Raw bytes:
#read("tiger.jpg", encoding: none)
```
```typst
#read(
path,
encoding: none | str
) -> str bytes
```
## Parameters
- path:
- description: Path to a file. For more details, see the [Paths section](/docs/reference/syntax/#paths).
- type: str
- default: None
- encoding:
- description: The encoding to read the file with. If set to `none`, this function returns raw bytes.
- type: none | str
- default: "utf8"
@@ -0,0 +1,107 @@
# TOML
# toml
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
```typst
#let details = toml("details.toml")
Title: #details.title \
Version: #details.version \
Authors: #(details.authors
.join(", ", last: " and "))
```
## Conversion details
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`](/docs/reference/foundations/str/) |
| integer | [`int`](/docs/reference/foundations/int/) |
| float | [`float`](/docs/reference/foundations/float/) |
| boolean | [`bool`](/docs/reference/foundations/bool/) |
| datetime | [`datetime`](/docs/reference/foundations/datetime/) |
| array | [`array`](/docs/reference/foundations/array/) |
| table | [`dictionary`](/docs/reference/foundations/dictionary/) |
| Typst value | Converted into TOML |
| --- | --- |
| types that can be converted from TOML | corresponding TOML value |
| `none` | ignored |
| [`bytes`](/docs/reference/foundations/bytes/) | string via [`repr`](/docs/reference/foundations/repr/) |
| [`symbol`](/docs/reference/foundations/symbol/) | string |
| [`content`](/docs/reference/foundations/content/) | a table describing the content |
| other types ([`length`](/docs/reference/layout/length/), etc.) | string via [`repr`](/docs/reference/foundations/repr/) |
### Notes
- Be aware that TOML integers larger than 263-1 or smaller than -263 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`](/docs/reference/data-loading/cbor/#definitions-encode) for binary data.
- The `repr` function is [for debugging purposes only](/docs/reference/foundations/repr/#debugging-only), and its output is not guaranteed to be stable across Typst versions.
```typst
#toml(
source
) -> dictionary
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a TOML file or raw TOML bytes.
- type: str | bytes
- default: None
## Definitions
### toml.decode
Reads structured data from a TOML string/bytes.
```typst
#toml.decode(
data
) -> dictionary
```
#### Parameters
- data:
- description: TOML data.
- type: str | bytes
- default: None
### toml.encode
Encodes structured data into a TOML string.
```typst
#toml.encode(
value,
pretty: bool
) -> str
```
#### Parameters
- value:
- description: Value to be encoded. TOML documents are tables. Therefore, only dictionaries are suitable.
- type: dictionary
- default: None
- pretty:
- description: Whether to pretty-print the resulting TOML.
- type: bool
- default: true
@@ -0,0 +1,82 @@
# XML
# xml
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
```typst
#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)
}
}
```
```typst
#xml(
source
) -> any
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to an XML file or raw XML bytes.
- type: str | bytes
- default: None
## Definitions
### xml.decode
Reads structured data from an XML string/bytes.
```typst
#xml.decode(
data
) -> any
```
#### Parameters
- data:
- description: XML data.
- type: str | bytes
- default: None
@@ -0,0 +1,105 @@
# YAML
# yaml
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
```typst
#let bookshelf(contents) = {
for (author, works) in contents {
author
for work in works [
- #work.title (#work.published)
]
}
}
#bookshelf(
yaml("scifi-authors.yaml")
)
```
## Conversion details
| YAML value | Converted into Typst |
| --- | --- |
| null-values (`null`, `~` or empty ``) | `none` |
| boolean | [`bool`](/docs/reference/foundations/bool/) |
| number | [`float`](/docs/reference/foundations/float/) or [`int`](/docs/reference/foundations/int/) |
| string | [`str`](/docs/reference/foundations/str/) |
| sequence | [`array`](/docs/reference/foundations/array/) |
| mapping | [`dictionary`](/docs/reference/foundations/dictionary/) |
| Typst value | Converted into YAML |
| --- | --- |
| types that can be converted from YAML | corresponding YAML value |
| [`bytes`](/docs/reference/foundations/bytes/) | string via [`repr`](/docs/reference/foundations/repr/) |
| [`symbol`](/docs/reference/foundations/symbol/) | string |
| [`content`](/docs/reference/foundations/content/) | a mapping describing the content |
| other types ([`length`](/docs/reference/layout/length/), etc.) | string via [`repr`](/docs/reference/foundations/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 263-1 or smaller than -263 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`](/docs/reference/data-loading/cbor/#definitions-encode) for binary data.
- The `repr` function is [for debugging purposes only](/docs/reference/foundations/repr/#debugging-only), and its output is not guaranteed to be stable across Typst versions.
```typst
#yaml(
source
) -> any
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a YAML file or raw YAML bytes.
- type: str | bytes
- default: None
## Definitions
### yaml.decode
Reads structured data from a YAML string/bytes.
```typst
#yaml.decode(
data
) -> any
```
#### Parameters
- data:
- description: YAML data.
- type: str | bytes
- default: None
### yaml.encode
Encode structured data into a YAML string.
```typst
#yaml.encode(
value
) -> str
```
#### Parameters
- value:
- description: Value to be encoded.
- type: any
- default: None
@@ -0,0 +1,92 @@
# Arguments
Captured arguments to a function.
## Argument Sinks
Like built-in functions, custom functions can also take a variable number of arguments. You can specify an _argument sink_ which collects all excess arguments as `..sink`. The resulting `sink` value is of the `arguments` type. It exposes methods to access the positional and named arguments.
```typst
#let format(title, ..authors) = {
let by = authors
.pos()
.join(", ", last: " and ")
[*#title* \ _Written by #by;_]
}
#format("ArtosFlow", "Jane", "Joe")
```
## Spreading
Inversely to an argument sink, you can _spread_ arguments, arrays and dictionaries into a function call with the `..spread` operator:
```typst
#let array = (2, 3, 5)
#calc.min(..array)
#let dict = (fill: blue)
#text(..dict)[Hello]
```
## Constructor
## arguments
Construct spreadable arguments in place.
This function behaves like `let args(..sink) = sink`.
```typst
#let args = arguments(stroke: red, inset: 1em, [Body])
#box(..args)
```
```typst
#arguments(
arguments
) -> arguments
```
### Parameters
- arguments:
- description: The arguments to construct.
- type: any
- default: None
## Methods
## arguments.at
Returns the positional argument at the specified index, or the named argument with the specified name.
If the key is an [integer](/docs/reference/foundations/int/), this is equivalent to first calling [`pos`](/docs/reference/foundations/arguments/#definitions-pos) and then [`array.at`](/docs/reference/foundations/array/#definitions-at). If it is a [string](/docs/reference/foundations/str/), this is equivalent to first calling [`named`](/docs/reference/foundations/arguments/#definitions-named) and then [`dictionary.at`](/docs/reference/foundations/dictionary/#definitions-at).
```typst
#arguments.at(
key,
default: any
) -> any
```
### Parameters
- key:
- description: The index or name of the argument to get.
- type: int | str
- default: None
- default:
- description: A default value to return if the key is invalid.
- type: any
- default: None
## arguments.pos
Returns the captured positional arguments as an array.
## arguments.named
Returns the captured named arguments as a dictionary.
@@ -0,0 +1,717 @@
# Array
A sequence of values.
You can construct an array by enclosing a comma-separated sequence of values in parentheses. The values do not have to be of the same type.
You can access and update array items with the `.at()` method. Indices are zero-based and negative indices wrap around to the end of the array. You can iterate over an array using a [for loop](/docs/reference/scripting/#loops). Arrays can be added together with the `+` operator, [joined together](/docs/reference/scripting/#blocks) and multiplied with integers.
**Note:** An array of length one needs a trailing comma, as in `(1,)`. This is to disambiguate from a simple parenthesized expressions like `(1 + 2) * 3`. An empty array is written as `()`.
## Example
```typst
#let values = (1, 7, 4, -3, 2)
#values.at(0) \
#(values.at(0) = 3)
#values.at(-1) \
#values.find(calc.even) \
#values.filter(calc.odd) \
#values.map(calc.abs) \
#values.rev() \
#(1, (2, 3)).flatten() \
#(("A", "B", "C")
.join(", ", last: " and "))
```
## Constructor
## array
Converts a value to an array.
Note that this function is only intended for conversion of a collection-like value to an array, not for creation of an array from individual items. Use the array syntax `(1, 2, 3)` (or `(1,)` for a single-element array) instead.
```typst
#let hi = "Hello 😃"
#array(bytes(hi))
```
```typst
#array(
value
) -> array
```
### Parameters
- value:
- description: The value that should be converted to an array.
- type: bytes | array | version
- default: None
## Methods
## array.len
The number of values in the array.
## array.first
Returns the first item in the array. May be used on the left-hand side an assignment. Returns the default value if the array is empty or fails with an error is no default value was specified.
```typst
#array.first(
default: any
) -> any
```
### Parameters
- default:
- description: A default value to return if the array is empty.
- type: any
- default: None
## array.last
Returns the last item in the array. May be used on the left-hand side of an assignment. Returns the default value if the array is empty or fails with an error is no default value was specified.
```typst
#array.last(
default: any
) -> any
```
### Parameters
- default:
- description: A default value to return if the array is empty.
- type: any
- default: None
## array.at
Returns the item at the specified index in the array. May be used on the left-hand side of an assignment. Returns the default value if the index is out of bounds or fails with an error if no default value was specified.
```typst
#array.at(
index,
default: any
) -> any
```
### Parameters
- index:
- description: The index at which to retrieve the item. If negative, indexes from the back.
- type: int
- default: None
- default:
- description: A default value to return if the index is out of bounds.
- type: any
- default: None
## array.push
Adds a value to the end of the array.
```typst
#array.push(
value
) ->
```
### Parameters
- value:
- description: The value to insert at the end of the array.
- type: any
- default: None
## array.pop
Removes the last item from the array and returns it. Fails with an error if the array is empty.
## array.insert
Inserts a value into the array at the specified index, shifting all subsequent elements to the right. Fails with an error if the index is out of bounds.
To replace an element of an array, use [`at`](/docs/reference/foundations/array/#definitions-at).
```typst
#array.insert(
index,
value
) ->
```
### Parameters
- index:
- description: The index at which to insert the item. If negative, indexes from the back.
- type: int
- default: None
- value:
- description: The value to insert into the array.
- type: any
- default: None
## array.remove
Removes the value at the specified index from the array and return it.
```typst
#array.remove(
index,
default: any
) -> any
```
### Parameters
- index:
- description: The index at which to remove the item. If negative, indexes from the back.
- type: int
- default: None
- default:
- description: A default value to return if the index is out of bounds.
- type: any
- default: None
## array.slice
Extracts a subslice of the array. Fails with an error if the start or end index is out of bounds.
```typst
#array.slice(
start,
end,
count: int
) -> array
```
### Parameters
- start:
- description: The start index (inclusive). If negative, indexes from the back.
- type: int
- default: None
- end:
- description: The end index (exclusive). If omitted, the whole slice until the end of the array is extracted. If negative, indexes from the back.
- type: none | int
- default: none
- count:
- description: The number of items to extract. This is equivalent to passing `start + count` as the `end` position. Mutually exclusive with `end`.
- type: int
- default: None
## array.contains
Whether the array contains the specified value.
This method also has dedicated syntax: You can write `2 in (1, 2, 3)` instead of `(1, 2, 3).contains(2)`.
```typst
#array.contains(
value
) -> bool
```
### Parameters
- value:
- description: The value to search for.
- type: any
- default: None
## array.find
Searches for an item for which the given function returns `true` and returns the first match or `none` if there is no match.
```typst
#array.find(
searcher
) -> any none
```
### Parameters
- searcher:
- description: The function to apply to each item. Must return a boolean.
- type: function
- default: None
## array.position
Searches for an item for which the given function returns `true` and returns the index of the first match or `none` if there is no match.
```typst
#array.position(
searcher
) -> none int
```
### Parameters
- searcher:
- description: The function to apply to each item. Must return a boolean.
- type: function
- default: None
## array.range
Create an array consisting of a sequence of numbers.
If you pass just one positional parameter, it is interpreted as the `end` of the range. If you pass two, they describe the `start` and `end` of the range.
This function is available both in the array function's scope and globally.
```typst
#range(5) \
#range(2, 5) \
#range(20, step: 4) \
#range(21, step: 4) \
#range(5, 2, step: -1)
```
```typst
#array.range(
start,
end,
step: int
) -> array
```
### Parameters
- start:
- description: The start of the range (inclusive).
- type: int
- default: 0
- end:
- description: The end of the range (exclusive).
- type: int
- default: None
- step:
- description: The distance between the generated numbers.
- type: int
- default: 1
## array.filter
Produces a new array with only the items from the original one for which the given function returns true.
```typst
#array.filter(
test
) -> array
```
### Parameters
- test:
- description: The function to apply to each item. Must return a boolean.
- type: function
- default: None
## array.map
Produces a new array in which all items from the original one were transformed with the given function.
```typst
#array.map(
mapper
) -> array
```
### Parameters
- mapper:
- description: The function to apply to each item.
- type: function
- default: None
## array.enumerate
Returns a new array with the values alongside their indices.
The returned array consists of `(index, value)` pairs in the form of length-2 arrays. These can be [destructured](/docs/reference/scripting/#bindings) with a let binding or for loop.
```typst
#for (i, value) in ("A", "B", "C").enumerate() {
[#i: #value \ ]
}
#("A", "B", "C").enumerate(start: 1)
```
```typst
#array.enumerate(
start: int
) -> array
```
### Parameters
- start:
- description: The index returned for the first pair of the returned list.
- type: int
- default: 0
## array.zip
Zips the array with other arrays.
Returns an array of arrays, where the `i`th inner array contains all the `i`th elements from each original array.
If the arrays to be zipped have different lengths, they are zipped up to the last element of the shortest array and all remaining elements are ignored.
This function is variadic, meaning that you can zip multiple arrays together at once: `(1, 2).zip(("A", "B"), (10, 20))` yields `((1, "A", 10), (2, "B", 20))`.
```typst
#array.zip(
exact: bool,
others
) -> array
```
### Parameters
- exact:
- description: Whether all arrays have to have the same length. For example, `(1, 2).zip((1, 2, 3), exact: true)` produces an error.
- type: bool
- default: false
- others:
- description: The arrays to zip with.
- type: array
- default: None
## array.fold
Folds all items into a single value using an accumulator function.
```typst
#let array = (1, 2, 3, 4)
#array.fold(0, (acc, x) => acc + x)
```
```typst
#array.fold(
init,
folder
) -> any
```
### Parameters
- init:
- description: The initial value to start with.
- type: any
- default: None
- folder:
- description: The folding function. Must have two parameters: One for the accumulated value and one for an item.
- type: function
- default: None
## array.sum
Sums all items (works for all types that can be added).
```typst
#array.sum(
default: any
) -> any
```
### Parameters
- default:
- description: What to return if the array is empty. Must be set if the array can be empty.
- type: any
- default: None
## array.product
Calculates the product of all items (works for all types that can be multiplied).
```typst
#array.product(
default: any
) -> any
```
### Parameters
- default:
- description: What to return if the array is empty. Must be set if the array can be empty.
- type: any
- default: None
## array.any
Whether the given function returns `true` for any item in the array.
```typst
#array.any(
test
) -> bool
```
### Parameters
- test:
- description: The function to apply to each item. Must return a boolean.
- type: function
- default: None
## array.all
Whether the given function returns `true` for all items in the array.
```typst
#array.all(
test
) -> bool
```
### Parameters
- test:
- description: The function to apply to each item. Must return a boolean.
- type: function
- default: None
## array.flatten
Combine all nested arrays into a single flat one.
## array.rev
Return a new array with the same items, but in reverse order.
## array.split
Split the array at occurrences of the specified value.
```typst
#(1, 1, 2, 3, 2, 4, 5).split(2)
```
```typst
#array.split(
at
) -> array
```
### Parameters
- at:
- description: The value to split at.
- type: any
- default: None
## array.join
Combine all items in the array into one.
```typst
#array.join(
separator,
last: any,
default: any | none
) -> any
```
### Parameters
- separator:
- description: A value to insert between each item of the array.
- type: any | none
- default: none
- last:
- description: An alternative separator between the last two items.
- type: any
- default: None
- default:
- description: What to return if the array is empty.
- type: any | none
- default: none
## array.intersperse
Returns an array with a copy of the separator value placed between adjacent elements.
```typst
#("A", "B", "C").intersperse("-")
```
```typst
#array.intersperse(
separator
) -> array
```
### Parameters
- separator:
- description: The value that will be placed between each adjacent element.
- type: any
- default: None
## array.chunks
Splits an array into non-overlapping chunks, starting at the beginning, ending with a single remainder chunk.
All chunks but the last have `chunk-size` elements. If `exact` is set to `true`, the remainder is dropped if it contains less than `chunk-size` elements.
```typst
#let array = (1, 2, 3, 4, 5, 6, 7, 8)
#array.chunks(3) \
#array.chunks(3, exact: true)
```
```typst
#array.chunks(
chunk-size,
exact: bool
) -> array
```
### Parameters
- chunk-size:
- description: How many elements each chunk may at most contain.
- type: int
- default: None
- exact:
- description: Whether to keep the remainder if its size is less than `chunk-size`.
- type: bool
- default: false
## array.windows
Returns sliding windows of `window-size` elements over an array.
If the array length is less than `window-size`, this will return an empty array.
```typst
#let array = (1, 2, 3, 4, 5, 6, 7, 8)
#array.windows(5)
```
```typst
#array.windows(
window-size
) -> array
```
### Parameters
- window-size:
- description: How many elements each window will contain.
- type: int
- default: None
## array.sorted
Return a sorted version of this array, optionally by a given key function. The sorting algorithm used is stable.
Returns an error if a pair of values selected for comparison could not be compared, or if the key or comparison function (if given) yield an error.
To sort according to multiple criteria at once, e.g. in case of equality between some criteria, the key function can return an array. The results are in lexicographic order.
```typst
#let array = (
(a: 2, b: 4),
(a: 1, b: 5),
(a: 2, b: 3),
)
#array.sorted(key: it => (it.a, it.b))
```
```typst
#array.sorted(
key: function,
by: function
) -> array
```
### Parameters
- key:
- description: If given, applies this function to each element in the array to determine the keys to sort by.
- type: function
- default: None
- by:
- description: If given, uses this function to compare every two elements in the array. The function will receive two elements in the array for comparison, and should return a boolean indicating their order: `true` indicates that the elements are in order, while `false` indicates that they should be swapped. To keep the sort stable, if the two elements are equal, the function should return `true`. If this function does not order the elements properly (e.g., by returning `false` for both `(x, y)` and `(y, x)`, or for `(x, x)`), the resulting array will be in unspecified order. When used together with `key`, `by` will be passed the keys instead of the elements. ```typst #( "sorted", "by", "decreasing", "length", ).sorted( key: s => s.len(), by: (l, r) => l >= r, ) ```
- type: function
- default: None
## array.dedup
Deduplicates all items in the array.
Returns a new array with all duplicate items removed. Only the first element of each duplicate is kept.
```typst
#(3, 3, 1, 2, 3).dedup()
```
```typst
#array.dedup(
key: function
) -> array
```
### Parameters
- key:
- description: If given, applies this function to each element in the array to determine the keys to deduplicate by. ```typst #("apple", "banana", " apple ").dedup(key: s => s.trim()) ```
- type: function
- default: None
## array.to-dict
Converts an array of pairs into a dictionary. The first value of each pair is the key, the second the value.
If the same key occurs multiple times, the last value is selected.
```typst
#(
("apples", 2),
("peaches", 3),
("apples", 5),
).to-dict()
```
## array.reduce
Reduces the elements to a single one, by repeatedly applying a reducing operation.
If the array is empty, returns `none`, otherwise, returns the result of the reduction.
The reducing function is a closure with two arguments: an "accumulator", and an element.
For arrays with at least one element, this is the same as [`array.fold`](/docs/reference/foundations/array/#definitions-fold) with the first element of the array as the initial accumulator value, folding every subsequent element into it.
```typst
#let array = (2, 1, 4, 3)
#array.reduce((acc, x) => calc.max(acc, x))
```
```typst
#array.reduce(
reducer
) -> any
```
### Parameters
- reducer:
- description: The reducing function. Must have two parameters: One for the accumulated value and one for an item.
- type: function
- default: None
@@ -0,0 +1,103 @@
# Assert
# assert
Ensures that a condition is fulfilled.
Fails with an error if the condition is not fulfilled. Does not produce any output in the document.
If you wish to test equality between two values, see [`assert.eq`](/docs/reference/foundations/assert/#definitions-eq) and [`assert.ne`](/docs/reference/foundations/assert/#definitions-ne).
## Example
```typst
#assert(1 < 2, message: "math broke")
```
```typst
#assert(
condition,
message: str
) ->
```
## Parameters
- condition:
- description: The condition that must be true for the assertion to pass.
- type: bool
- default: None
- message:
- description: The error message when the assertion fails.
- type: str
- default: None
## Definitions
### assert.eq
Ensures that two values are equal.
Fails with an error if the first value is not equal to the second. Does not produce any output in the document.
```typst
#assert.eq(10, 10)
```
```typst
#assert.eq(
left,
right,
message: str
) ->
```
#### Parameters
- left:
- description: The first value to compare.
- type: any
- default: None
- right:
- description: The second value to compare.
- type: any
- default: None
- message:
- description: An optional message to display on error instead of the representations of the compared values.
- type: str
- default: None
### assert.ne
Ensures that two values are not equal.
Fails with an error if the first value is equal to the second. Does not produce any output in the document.
```typst
#assert.ne(3, 4)
```
```typst
#assert.ne(
left,
right,
message: str
) ->
```
#### Parameters
- left:
- description: The first value to compare.
- type: any
- default: None
- right:
- description: The second value to compare.
- type: any
- default: None
- message:
- description: An optional message to display on error instead of the representations of the compared values.
- type: str
- default: None
@@ -0,0 +1,9 @@
# Auto
A value that indicates a smart default.
The auto type has exactly one value: `auto`.
Parameters that support the `auto` value have some smart default or contextual behaviour. A good example is the [text direction](/docs/reference/text/text/#parameters-dir) parameter. Setting it to `auto` lets Typst automatically determine the direction from the [text language](/docs/reference/text/text/#parameters-lang).
@@ -0,0 +1,15 @@
# Boolean
A type with two states.
The boolean type has two values: `true` and `false`. It denotes whether something is active or enabled.
## Example
```typst
#false \
#true \
#(1 < 2)
```
@@ -0,0 +1,111 @@
# Bytes
A sequence of bytes.
This is conceptually similar to an array of [integers](/docs/reference/foundations/int/) between `0` and `255`, but represented much more efficiently. You can iterate over it using a [for loop](/docs/reference/scripting/#loops).
You can convert
- a [string](/docs/reference/foundations/str/) or an [array](/docs/reference/foundations/array/) of integers to bytes with the [`bytes`](/docs/reference/foundations/bytes/) constructor
- bytes to a string with the [`str`](/docs/reference/foundations/str/) constructor, with UTF-8 encoding
- bytes to an array of integers with the [`array`](/docs/reference/foundations/array/) constructor
When [reading](/docs/reference/data-loading/read/) data from a file, you can decide whether to load it as a string or as raw bytes.
```typst
#bytes((123, 160, 22, 0)) \
#bytes("Hello 😃")
#let data = read(
"rhino.png",
encoding: none,
)
// Magic bytes.
#array(data.slice(0, 4)) \
#str(data.slice(1, 4))
```
## Constructor
## bytes
Converts a value to bytes.
- Strings are encoded in UTF-8.
- Arrays of integers between `0` and `255` are converted directly. The dedicated byte representation is much more efficient than the array representation and thus typically used for large byte buffers (e.g. image data).
```typst
#bytes("Hello 😃") \
#bytes((123, 160, 22, 0))
```
```typst
#bytes(
value
) -> bytes
```
### Parameters
- value:
- description: The value that should be converted to bytes.
- type: str | bytes | array
- default: None
## Methods
## bytes.len
The length in bytes.
## bytes.at
Returns the byte at the specified index. Returns the default value if the index is out of bounds or fails with an error if no default value was specified.
```typst
#bytes.at(
index,
default: any
) -> any
```
### Parameters
- index:
- description: The index at which to retrieve the byte.
- type: int
- default: None
- default:
- description: A default value to return if the index is out of bounds.
- type: any
- default: None
## bytes.slice
Extracts a subslice of the bytes. Fails with an error if the start or end index is out of bounds.
```typst
#bytes.slice(
start,
end,
count: int
) -> bytes
```
### Parameters
- start:
- description: The start index (inclusive).
- type: int
- default: None
- end:
- description: The end index (exclusive). If omitted, the whole slice until the end is extracted.
- type: none | int
- default: none
- count:
- description: The number of items to extract. This is equivalent to passing `start + count` as the `end` position. Mutually exclusive with `end`.
- type: int
- default: None
@@ -0,0 +1,984 @@
# Calculation
Module for calculations and processing of numeric values.
These definitions are part of the `calc` module and not imported by default. In addition to the functions listed below, the `calc` module also defines the constants `pi`, `tau`, `e`, and `inf`.
# calc.abs
Calculates the absolute value of a numeric value.
```typst
#calc.abs(-5) \
#calc.abs(5pt - 2cm) \
#calc.abs(2fr) \
#calc.abs(decimal("-342.440"))
```
```typst
#calc.abs(
value
) -> any
```
## Parameters
- value:
- description: The value whose absolute value to calculate.
- type: int | float | length | angle | ratio | fraction | decimal
- default: None
# calc.pow
Raises a value to some exponent.
```typst
#calc.pow(2, 3) \
#calc.pow(decimal("2.5"), 2)
```
```typst
#calc.pow(
base,
exponent
) -> int float decimal
```
## Parameters
- base:
- description: The base of the power. If this is a [`decimal`](/docs/reference/foundations/decimal/), the exponent can only be an [integer](/docs/reference/foundations/int/).
- type: int | float | decimal
- default: None
- exponent:
- description: The exponent of the power.
- type: int | float
- default: None
# calc.exp
Raises a value to some exponent of e.
```typst
#calc.exp(1)
```
```typst
#calc.exp(
exponent
) -> float
```
## Parameters
- exponent:
- description: The exponent of the power.
- type: int | float
- default: None
# calc.sqrt
Calculates the square root of a number.
```typst
#calc.sqrt(16) \
#calc.sqrt(2.5)
```
```typst
#calc.sqrt(
value
) -> float
```
## Parameters
- value:
- description: The number whose square root to calculate. Must be non-negative.
- type: int | float
- default: None
# calc.root
Calculates the real nth root of a number.
If the number is negative, then n must be odd.
```typst
#calc.root(16.0, 4) \
#calc.root(27.0, 3)
```
```typst
#calc.root(
radicand,
index
) -> float
```
## Parameters
- radicand:
- description: The expression to take the root of.
- type: float
- default: None
- index:
- description: Which root of the radicand to take.
- type: int
- default: None
# calc.sin
Calculates the sine of an angle.
When called with an integer or a float, they will be interpreted as radians.
```typst
#calc.sin(1.5) \
#calc.sin(90deg)
```
```typst
#calc.sin(
angle
) -> float
```
## Parameters
- angle:
- description: The angle whose sine to calculate.
- type: int | float | angle
- default: None
# calc.cos
Calculates the cosine of an angle.
When called with an integer or a float, they will be interpreted as radians.
```typst
#calc.cos(1.5) \
#calc.cos(90deg)
```
```typst
#calc.cos(
angle
) -> float
```
## Parameters
- angle:
- description: The angle whose cosine to calculate.
- type: int | float | angle
- default: None
# calc.tan
Calculates the tangent of an angle.
When called with an integer or a float, they will be interpreted as radians.
```typst
#calc.tan(1.5) \
#calc.tan(90deg)
```
```typst
#calc.tan(
angle
) -> float
```
## Parameters
- angle:
- description: The angle whose tangent to calculate.
- type: int | float | angle
- default: None
# calc.asin
Calculates the arcsine of a number.
```typst
#calc.asin(0) \
#calc.asin(1)
```
```typst
#calc.asin(
value
) -> angle
```
## Parameters
- value:
- description: The number whose arcsine to calculate. Must be between -1 and 1.
- type: int | float
- default: None
# calc.acos
Calculates the arccosine of a number.
```typst
#calc.acos(0) \
#calc.acos(1)
```
```typst
#calc.acos(
value
) -> angle
```
## Parameters
- value:
- description: The number whose arccosine to calculate. Must be between -1 and 1.
- type: int | float
- default: None
# calc.atan
Calculates the arctangent of a number.
```typst
#calc.atan(0) \
#calc.atan(1)
```
```typst
#calc.atan(
value
) -> angle
```
## Parameters
- value:
- description: The number whose arctangent to calculate.
- type: int | float
- default: None
# calc.atan2
Calculates the four-quadrant arctangent of a coordinate.
The arguments are `(x, y)`, not `(y, x)`.
```typst
#calc.atan2(1, 1) \
#calc.atan2(-2, -3)
```
```typst
#calc.atan2(
x,
y
) -> angle
```
## Parameters
- x:
- description: The X coordinate.
- type: int | float
- default: None
- y:
- description: The Y coordinate.
- type: int | float
- default: None
# calc.sinh
Calculates the hyperbolic sine of a hyperbolic angle.
```typst
#calc.sinh(0) \
#calc.sinh(1.5)
```
```typst
#calc.sinh(
value
) -> float
```
## Parameters
- value:
- description: The hyperbolic angle whose hyperbolic sine to calculate.
- type: float
- default: None
# calc.cosh
Calculates the hyperbolic cosine of a hyperbolic angle.
```typst
#calc.cosh(0) \
#calc.cosh(1.5)
```
```typst
#calc.cosh(
value
) -> float
```
## Parameters
- value:
- description: The hyperbolic angle whose hyperbolic cosine to calculate.
- type: float
- default: None
# calc.tanh
Calculates the hyperbolic tangent of a hyperbolic angle.
```typst
#calc.tanh(0) \
#calc.tanh(1.5)
```
```typst
#calc.tanh(
value
) -> float
```
## Parameters
- value:
- description: The hyperbolic angle whose hyperbolic tangent to calculate.
- type: float
- default: None
# calc.log
Calculates the logarithm of a number.
If the base is not specified, the logarithm is calculated in base 10.
```typst
#calc.log(100)
```
```typst
#calc.log(
value,
base: float
) -> float
```
## Parameters
- value:
- description: The number whose logarithm to calculate. Must be strictly positive.
- type: int | float
- default: None
- base:
- description: The base of the logarithm. May not be zero.
- type: float
- default: 10.0
# calc.ln
Calculates the natural logarithm of a number.
```typst
#calc.ln(calc.e)
```
```typst
#calc.ln(
value
) -> float
```
## Parameters
- value:
- description: The number whose logarithm to calculate. Must be strictly positive.
- type: int | float
- default: None
# calc.fact
Calculates the factorial of a number.
```typst
#calc.fact(5)
```
```typst
#calc.fact(
number
) -> int
```
## Parameters
- number:
- description: The number whose factorial to calculate. Must be non-negative.
- type: int
- default: None
# calc.perm
Calculates a permutation.
Returns the `k`-permutation of `n`, or the number of ways to choose `k` items from a set of `n` with regard to order.
```typst
$ "perm"(n, k) &= n!/((n - k)!) \
"perm"(5, 3) &= #calc.perm(5, 3) $
```
```typst
#calc.perm(
base,
numbers
) -> int
```
## Parameters
- base:
- description: The base number. Must be non-negative.
- type: int
- default: None
- numbers:
- description: The number of permutations. Must be non-negative.
- type: int
- default: None
# calc.binom
Calculates a binomial coefficient.
Returns the `k`-combination of `n`, or the number of ways to choose `k` items from a set of `n` without regard to order.
```typst
#calc.binom(10, 5)
```
```typst
#calc.binom(
n,
k
) -> int
```
## Parameters
- n:
- description: The upper coefficient. Must be non-negative.
- type: int
- default: None
- k:
- description: The lower coefficient. Must be non-negative.
- type: int
- default: None
# calc.gcd
Calculates the greatest common divisor of two integers.
This will error if the result of integer division would be larger than the maximum 64-bit signed integer.
```typst
#calc.gcd(7, 42)
```
```typst
#calc.gcd(
a,
b
) -> int
```
## Parameters
- a:
- description: The first integer.
- type: int
- default: None
- b:
- description: The second integer.
- type: int
- default: None
# calc.lcm
Calculates the least common multiple of two integers.
```typst
#calc.lcm(96, 13)
```
```typst
#calc.lcm(
a,
b
) -> int
```
## Parameters
- a:
- description: The first integer.
- type: int
- default: None
- b:
- description: The second integer.
- type: int
- default: None
# calc.floor
Rounds a number down to the nearest integer.
If the number is already an integer, it is returned unchanged.
Note that this function will always return an [integer](/docs/reference/foundations/int/), and will error if the resulting [`float`](/docs/reference/foundations/float/) or [`decimal`](/docs/reference/foundations/decimal/) is larger than the maximum 64-bit signed integer or smaller than the minimum for that type.
```typst
#calc.floor(500.1)
#assert(calc.floor(3) == 3)
#assert(calc.floor(3.14) == 3)
#assert(calc.floor(decimal("-3.14")) == -4)
```
```typst
#calc.floor(
value
) -> int
```
## Parameters
- value:
- description: The number to round down.
- type: int | float | decimal
- default: None
# calc.ceil
Rounds a number up to the nearest integer.
If the number is already an integer, it is returned unchanged.
Note that this function will always return an [integer](/docs/reference/foundations/int/), and will error if the resulting [`float`](/docs/reference/foundations/float/) or [`decimal`](/docs/reference/foundations/decimal/) is larger than the maximum 64-bit signed integer or smaller than the minimum for that type.
```typst
#calc.ceil(500.1)
#assert(calc.ceil(3) == 3)
#assert(calc.ceil(3.14) == 4)
#assert(calc.ceil(decimal("-3.14")) == -3)
```
```typst
#calc.ceil(
value
) -> int
```
## Parameters
- value:
- description: The number to round up.
- type: int | float | decimal
- default: None
# calc.trunc
Returns the integer part of a number.
If the number is already an integer, it is returned unchanged.
Note that this function will always return an [integer](/docs/reference/foundations/int/), and will error if the resulting [`float`](/docs/reference/foundations/float/) or [`decimal`](/docs/reference/foundations/decimal/) is larger than the maximum 64-bit signed integer or smaller than the minimum for that type.
```typst
#calc.trunc(15.9)
#assert(calc.trunc(3) == 3)
#assert(calc.trunc(-3.7) == -3)
#assert(calc.trunc(decimal("8493.12949582390")) == 8493)
```
```typst
#calc.trunc(
value
) -> int
```
## Parameters
- value:
- description: The number to truncate.
- type: int | float | decimal
- default: None
# calc.fract
Returns the fractional part of a number.
If the number is an integer, returns `0`.
```typst
#calc.fract(-3.1)
#assert(calc.fract(3) == 0)
#assert(calc.fract(decimal("234.23949211")) == decimal("0.23949211"))
```
```typst
#calc.fract(
value
) -> int float decimal
```
## Parameters
- value:
- description: The number to truncate.
- type: int | float | decimal
- default: None
# calc.round
Rounds a number to the nearest integer.
Half-integers are rounded away from zero.
Optionally, a number of decimal places can be specified. If negative, its absolute value will indicate the amount of significant integer digits to remove before the decimal point.
Note that this function will return the same type as the operand. That is, applying `round` to a [`float`](/docs/reference/foundations/float/) will return a `float`, and to a [`decimal`](/docs/reference/foundations/decimal/), another `decimal`. You may explicitly convert the output of this function to an integer with [`int`](/docs/reference/foundations/int/), but note that such a conversion will error if the `float` or `decimal` is larger than the maximum 64-bit signed integer or smaller than the minimum integer.
In addition, this function can error if there is an attempt to round beyond the maximum or minimum integer or `decimal`. If the number is a `float`, such an attempt will cause `float.inf` or `-float.inf` to be returned for maximum and minimum respectively.
```typst
#calc.round(3.1415, digits: 2)
#assert(calc.round(3) == 3)
#assert(calc.round(3.14) == 3)
#assert(calc.round(3.5) == 4.0)
#assert(calc.round(3333.45, digits: -2) == 3300.0)
#assert(calc.round(-48953.45, digits: -3) == -49000.0)
#assert(calc.round(3333, digits: -2) == 3300)
#assert(calc.round(-48953, digits: -3) == -49000)
#assert(calc.round(decimal("-6.5")) == decimal("-7"))
#assert(calc.round(decimal("7.123456789"), digits: 6) == decimal("7.123457"))
#assert(calc.round(decimal("3333.45"), digits: -2) == decimal("3300"))
#assert(calc.round(decimal("-48953.45"), digits: -3) == decimal("-49000"))
```
```typst
#calc.round(
value,
digits: int
) -> int float decimal
```
## Parameters
- value:
- description: The number to round.
- type: int | float | decimal
- default: None
- digits:
- description: If positive, the number of decimal places. If negative, the number of significant integer digits that should be removed before the decimal point.
- type: int
- default: 0
# calc.clamp
Clamps a number between a minimum and maximum value.
```typst
#calc.clamp(5, 0, 4)
#assert(calc.clamp(5, 0, 10) == 5)
#assert(calc.clamp(5, 6, 10) == 6)
#assert(calc.clamp(decimal("5.45"), 2, decimal("45.9")) == decimal("5.45"))
#assert(calc.clamp(decimal("5.45"), decimal("6.75"), 12) == decimal("6.75"))
```
```typst
#calc.clamp(
value,
min,
max
) -> int float decimal
```
## Parameters
- value:
- description: The number to clamp.
- type: int | float | decimal
- default: None
- min:
- description: The inclusive minimum value.
- type: int | float | decimal
- default: None
- max:
- description: The inclusive maximum value.
- type: int | float | decimal
- default: None
# calc.min
Determines the minimum of a sequence of values.
```typst
#calc.min(1, -3, -5, 20, 3, 6) \
#calc.min("typst", "is", "cool")
```
```typst
#calc.min(
values
) -> any
```
## Parameters
- values:
- description: The sequence of values from which to extract the minimum. Must not be empty.
- type: any
- default: None
# calc.max
Determines the maximum of a sequence of values.
```typst
#calc.max(1, -3, -5, 20, 3, 6) \
#calc.max("typst", "is", "cool")
```
```typst
#calc.max(
values
) -> any
```
## Parameters
- values:
- description: The sequence of values from which to extract the maximum. Must not be empty.
- type: any
- default: None
# calc.even
Determines whether an integer is even.
```typst
#calc.even(4) \
#calc.even(5) \
#range(10).filter(calc.even)
```
```typst
#calc.even(
value
) -> bool
```
## Parameters
- value:
- description: The number to check for evenness.
- type: int
- default: None
# calc.odd
Determines whether an integer is odd.
```typst
#calc.odd(4) \
#calc.odd(5) \
#range(10).filter(calc.odd)
```
```typst
#calc.odd(
value
) -> bool
```
## Parameters
- value:
- description: The number to check for oddness.
- type: int
- default: None
# calc.rem
Calculates the remainder of two numbers.
The value `calc.rem(x, y)` always has the same sign as `x`, and is smaller in magnitude than `y`.
This can error if given a [`decimal`](/docs/reference/foundations/decimal/) input and the dividend is too small in magnitude compared to the divisor.
```typst
#calc.rem(7, 3) \
#calc.rem(7, -3) \
#calc.rem(-7, 3) \
#calc.rem(-7, -3) \
#calc.rem(1.75, 0.5)
```
```typst
#calc.rem(
dividend,
divisor
) -> int float decimal
```
## Parameters
- dividend:
- description: The dividend of the remainder.
- type: int | float | decimal
- default: None
- divisor:
- description: The divisor of the remainder.
- type: int | float | decimal
- default: None
# calc.div-euclid
Performs euclidean division of two numbers.
The result of this computation is that of a division rounded to the integer `n` such that the dividend is greater than or equal to `n` times the divisor.
This can error if the resulting number is larger than the maximum value or smaller than the minimum value for its type.
```typst
#calc.div-euclid(7, 3) \
#calc.div-euclid(7, -3) \
#calc.div-euclid(-7, 3) \
#calc.div-euclid(-7, -3) \
#calc.div-euclid(1.75, 0.5) \
#calc.div-euclid(decimal("1.75"), decimal("0.5"))
```
```typst
#calc.div-euclid(
dividend,
divisor
) -> int float decimal
```
## Parameters
- dividend:
- description: The dividend of the division.
- type: int | float | decimal
- default: None
- divisor:
- description: The divisor of the division.
- type: int | float | decimal
- default: None
# calc.rem-euclid
This calculates the least nonnegative remainder of a division.
Warning: Due to a floating point round-off error, the remainder may equal the absolute value of the divisor if the dividend is much smaller in magnitude than the divisor and the dividend is negative. This only applies for floating point inputs.
In addition, this can error if given a [`decimal`](/docs/reference/foundations/decimal/) input and the dividend is too small in magnitude compared to the divisor.
```typst
#calc.rem-euclid(7, 3) \
#calc.rem-euclid(7, -3) \
#calc.rem-euclid(-7, 3) \
#calc.rem-euclid(-7, -3) \
#calc.rem-euclid(1.75, 0.5) \
#calc.rem-euclid(decimal("1.75"), decimal("0.5"))
```
```typst
#calc.rem-euclid(
dividend,
divisor
) -> int float decimal
```
## Parameters
- dividend:
- description: The dividend of the remainder.
- type: int | float | decimal
- default: None
- divisor:
- description: The divisor of the remainder.
- type: int | float | decimal
- default: None
# calc.quo
Calculates the quotient (floored division) of two numbers.
Note that this function will always return an [integer](/docs/reference/foundations/int/), and will error if the resulting number is larger than the maximum 64-bit signed integer or smaller than the minimum for that type.
```typst
$ "quo"(a, b) &= floor(a/b) \
"quo"(14, 5) &= #calc.quo(14, 5) \
"quo"(3.46, 0.5) &= #calc.quo(3.46, 0.5) $
```
```typst
#calc.quo(
dividend,
divisor
) -> int
```
## Parameters
- dividend:
- description: The dividend of the quotient.
- type: int | float | decimal
- default: None
- divisor:
- description: The divisor of the quotient.
- type: int | float | decimal
- default: None
# calc.norm
Calculates the p-norm of a sequence of values.
```typst
#calc.norm(1, 2, -3, 0.5) \
#calc.norm(p: 3, 1, 2)
```
```typst
#calc.norm(
p: float,
values
) -> float
```
## Parameters
- p:
- description: The p value to calculate the p-norm of.
- type: float
- default: 2.0
- values:
- description: The sequence of values from which to calculate the p-norm. Returns `0.0` if empty.
- type: float
- default: None
@@ -0,0 +1,89 @@
# Content
A piece of document content.
This type is at the heart of Typst. All markup you write and most [functions](/docs/reference/foundations/function/) you call produce content values. You can create a content value by enclosing markup in square brackets. This is also how you pass content to functions.
## Example
```typst
Type of *Hello!* is
#type([*Hello!*])
```
Content can be added with the `+` operator, [joined together](/docs/reference/scripting/#blocks) and multiplied with integers. Wherever content is expected, you can also pass a [string](/docs/reference/foundations/str/) or `none`.
## Representation
Content consists of elements with fields. When constructing an element with its _element function,_ you provide these fields as arguments and when you have a content value, you can access its fields with [field access syntax](/docs/reference/scripting/#field-access).
Some fields are required: These must be provided when constructing an element and as a consequence, they are always available through field access on content of that type. Required fields are marked as such in the documentation.
Most fields are optional: Like required fields, they can be passed to the element function to configure them for a single element. However, these can also be configured with [set rules](/docs/reference/styling/#set-rules) to apply them to all elements within a scope. Optional fields are only available with field access syntax when they were explicitly passed to the element function, not when they result from a set rule.
Each element has a default appearance. However, you can also completely customize its appearance with a [show rule](/docs/reference/styling/#show-rules). The show rule is passed the element. It can access the element's field and produce arbitrary content from it.
In the web app, you can hover over a content variable to see exactly which elements the content is composed of and what fields they have. Alternatively, you can inspect the output of the [`repr`](/docs/reference/foundations/repr/) function.
## Methods
## content.func
The content's element function. This function can be used to create the element contained in this content. It can be used in set and show rules for the element. Can be compared with global functions to check whether you have a specific kind of element.
## content.has
Whether the content has the specified field.
```typst
#content.has(
field
) -> bool
```
### Parameters
- field:
- description: The field to look for.
- type: str
- default: None
## content.at
Access the specified field on the content. Returns the default value if the field does not exist or fails with an error if no default value was specified.
```typst
#content.at(
field,
default: any
) -> any
```
### Parameters
- field:
- description: The field to access.
- type: str
- default: None
- default:
- description: A default value to return if the field does not exist.
- type: any
- default: None
## content.fields
Returns the fields of this content.
```typst
#rect(
width: 10cm,
height: 10cm,
).fields()
```
## content.location
The location of the content. This is only available on content returned by [query](/docs/reference/introspection/query/) or provided by a [show rule](/docs/reference/styling/#show-rules), for other content it will be `none`. The resulting location can be used with [counters](/docs/reference/introspection/counter/), [state](/docs/reference/introspection/state/) and [queries](/docs/reference/introspection/query/).
@@ -0,0 +1,231 @@
# Datetime
Represents a date, a time, or a combination of both.
Can be created by either specifying a custom datetime using this type's constructor function or getting the current date with [`datetime.today`](/docs/reference/foundations/datetime/#definitions-today).
## Example
```typst
#let date = datetime(
year: 2020,
month: 10,
day: 4,
)
#date.display() \
#date.display(
"y:[year repr:last_two]"
)
#let time = datetime(
hour: 18,
minute: 2,
second: 23,
)
#time.display() \
#time.display(
"h:[hour repr:12][period]"
)
```
## Datetime and Duration
You can get a [duration](/docs/reference/foundations/duration/) by subtracting two datetime:
```typst
#let first-of-march = datetime(day: 1, month: 3, year: 2024)
#let first-of-jan = datetime(day: 1, month: 1, year: 2024)
#let distance = first-of-march - first-of-jan
#distance.hours()
```
You can also add/subtract a datetime and a duration to retrieve a new, offset datetime:
```typst
#let date = datetime(day: 1, month: 3, year: 2024)
#let two-days = duration(days: 2)
#let two-days-earlier = date - two-days
#let two-days-later = date + two-days
#date.display() \
#two-days-earlier.display() \
#two-days-later.display()
```
## Format
You can specify a customized formatting using the [`display`](/docs/reference/foundations/datetime/#definitions-display) method. The format of a datetime is specified by providing _components_ with a specified number of _modifiers_. A component represents a certain part of the datetime that you want to display, and with the help of modifiers you can define how you want to display that component. In order to display a component, you wrap the name of the component in square brackets (e.g. `[year]` will display the year). In order to add modifiers, you add a space after the component name followed by the name of the modifier, a colon and the value of the modifier (e.g. `[month repr:short]` will display the short representation of the month).
The possible combination of components and their respective modifiers is as follows:
- `year`: Displays the year of the datetime.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the year is padded.
- `repr` Can be either `full` in which case the full year is displayed or `last_two` in which case only the last two digits are displayed.
- `sign`: Can be either `automatic` or `mandatory`. Specifies when the sign should be displayed.
- `month`: Displays the month of the datetime.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the month is padded.
- `repr`: Can be either `numerical`, `long` or `short`. Specifies if the month should be displayed as a number or a word. Unfortunately, when choosing the word representation, it can currently only display the English version. In the future, it is planned to support localization.
- `day`: Displays the day of the datetime.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the day is padded.
- `week_number`: Displays the week number of the datetime.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the week number is padded.
- `repr`: Can be either `ISO`, `sunday` or `monday`. In the case of `ISO`, week numbers are between 1 and 53, while the other ones are between 0 and 53.
- `weekday`: Displays the weekday of the date.
- `repr` Can be either `long`, `short`, `sunday` or `monday`. In the case of `long` and `short`, the corresponding English name will be displayed (same as for the month, other languages are currently not supported). In the case of `sunday` and `monday`, the numerical value will be displayed (assuming Sunday and Monday as the first day of the week, respectively).
- `one_indexed`: Can be either `true` or `false`. Defines whether the numerical representation of the week starts with 0 or 1.
- `hour`: Displays the hour of the date.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the hour is padded.
- `repr`: Can be either `24` or `12`. Changes whether the hour is displayed in the 24-hour or 12-hour format.
- `period`: The AM/PM part of the hour
- `case`: Can be `lower` to display it in lower case and `upper` to display it in upper case.
- `minute`: Displays the minute of the date.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the minute is padded.
- `second`: Displays the second of the date.
- `padding`: Can be either `zero`, `space` or `none`. Specifies how the second is padded.
Keep in mind that not always all components can be used. For example, if you create a new datetime with `datetime(year: 2023, month: 10, day: 13)`, it will be stored as a plain date internally, meaning that you cannot use components such as `hour` or `minute`, which would only work on datetimes that have a specified time.
## Constructor
## datetime
Creates a new datetime.
You can specify the [datetime](/docs/reference/foundations/datetime/) using a year, month, day, hour, minute, and second.
_Note_: Depending on which components of the datetime you specify, Typst will store it in one of the following three ways:
- If you specify year, month and day, Typst will store just a date.
- If you specify hour, minute and second, Typst will store just a time.
- If you specify all of year, month, day, hour, minute and second, Typst will store a full datetime.
Depending on how it is stored, the [`display`](/docs/reference/foundations/datetime/#definitions-display) method will choose a different formatting by default.
```typst
#datetime(
year: 2012,
month: 8,
day: 3,
).display()
```
```typst
#datetime(
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int
) -> datetime
```
### Parameters
- year:
- description: The year of the datetime.
- type: int
- default: None
- month:
- description: The month of the datetime.
- type: int
- default: None
- day:
- description: The day of the datetime.
- type: int
- default: None
- hour:
- description: The hour of the datetime.
- type: int
- default: None
- minute:
- description: The minute of the datetime.
- type: int
- default: None
- second:
- description: The second of the datetime.
- type: int
- default: None
## Methods
## datetime.today
Returns the current date.
In the CLI, this can be overridden with the `--creation-timestamp` argument or by setting the [`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/specs/source-date-epoch/) environment variable. In both cases, the value should be given as a UNIX timestamp.
```typst
Today's date is
#datetime.today().display().
```
```typst
#datetime.today(
offset: auto | int
) -> datetime
```
### Parameters
- offset:
- description: An offset to apply to the current UTC date. If set to `auto`, the offset will be the local offset.
- type: auto | int
- default: auto
## datetime.display
Displays the datetime in a specified format.
Depending on whether you have defined just a date, a time or both, the default format will be different. If you specified a date, it will be `[year]-[month]-[day]`. If you specified a time, it will be `[hour]:[minute]:[second]`. In the case of a datetime, it will be `[year]-[month]-[day] [hour]:[minute]:[second]`.
See the [format syntax](/docs/reference/foundations/datetime/#format) for more information.
```typst
#datetime.display(
pattern
) -> str
```
### Parameters
- pattern:
- description: The format used to display the datetime.
- type: auto | str
- default: auto
## datetime.year
The year if it was specified, or `none` for times without a date.
## datetime.month
The month if it was specified, or `none` for times without a date.
## datetime.weekday
The weekday (counting Monday as 1) or `none` for times without a date.
## datetime.day
The day if it was specified, or `none` for times without a date.
## datetime.hour
The hour if it was specified, or `none` for dates without a time.
## datetime.minute
The minute if it was specified, or `none` for dates without a time.
## datetime.second
The second if it was specified, or `none` for dates without a time.
## datetime.ordinal
The ordinal (day of the year), or `none` for times without a date.
@@ -0,0 +1,69 @@
# Decimal
A fixed-point decimal number type.
This type should be used for precise arithmetic operations on numbers represented in base 10. A typical use case is representing currency.
## Example
```typst
Decimal: #(decimal("0.1") + decimal("0.2")) \
Float: #(0.1 + 0.2)
```
## Construction and casts
To create a decimal number, use the `decimal(string)` constructor, such as in `decimal("3.141592653")` **(note the double quotes!)**. This constructor preserves all given fractional digits, provided they are representable as per the limits specified below (otherwise, an error is raised).
You can also convert any [integer](/docs/reference/foundations/int/) to a decimal with the `decimal(int)` constructor, e.g. `decimal(59)`. However, note that constructing a decimal from a [floating-point number](/docs/reference/foundations/float/), while supported, **is an imprecise conversion and therefore discouraged.** A warning will be raised if Typst detects that there was an accidental `float` to `decimal` cast through its constructor, e.g. if writing `decimal(3.14)` (note the lack of double quotes, indicating this is an accidental `float` cast and therefore imprecise). It is recommended to use strings for constant decimal values instead (e.g. `decimal("3.14")`).
The precision of a `float` to `decimal` cast can be slightly improved by rounding the result to 15 digits with [`calc.round`](/docs/reference/foundations/calc/#functions-round), but there are still no precision guarantees for that kind of conversion.
## Operations
Basic arithmetic operations are supported on two decimals and on pairs of decimals and integers.
Built-in operations between `float` and `decimal` are not supported in order to guard against accidental loss of precision. They will raise an error instead.
Certain `calc` functions, such as trigonometric functions and power between two real numbers, are also only supported for `float` (although raising `decimal` to integer exponents is supported). You can opt into potentially imprecise operations with the `float(decimal)` constructor, which casts the `decimal` number into a `float`, allowing for operations without precision guarantees.
## Displaying decimals
To display a decimal, simply insert the value into the document. To only display a certain number of digits, [round](/docs/reference/foundations/calc/#functions-round) the decimal first. Localized formatting of decimals and other numbers is not yet supported, but planned for the future.
You can convert decimals to strings using the [`str`](/docs/reference/foundations/str/) constructor. This way, you can post-process the displayed representation, e.g. to replace the period with a comma (as a stand-in for proper built-in localization to languages that use the comma).
## Precision and limits
A `decimal` number has a limit of 28 to 29 significant base-10 digits. This includes the sum of digits before and after the decimal point. As such, numbers with more fractional digits have a smaller range. The maximum and minimum `decimal` numbers have a value of `79228162514264337593543950335` and `-79228162514264337593543950335` respectively. In contrast with [`float`](/docs/reference/foundations/float/), this type does not support infinity or NaN, so overflowing or underflowing operations will raise an error.
Typical operations between `decimal` numbers, such as addition, multiplication, and [power](/docs/reference/foundations/calc/#functions-pow) to an integer, will be highly precise due to their fixed-point representation. Note, however, that multiplication and division may not preserve all digits in some edge cases: while they are considered precise, digits past the limits specified above are rounded off and lost, so some loss of precision beyond the maximum representable digits is possible. Note that this behavior can be observed not only when dividing, but also when multiplying by numbers between 0 and 1, as both operations can push a number's fractional digits beyond the limits described above, leading to rounding. When those two operations do not surpass the digit limits, they are fully precise.
## Constructor
## decimal
Converts a value to a `decimal`.
It is recommended to use a string to construct the decimal number, or an [integer](/docs/reference/foundations/int/) (if desired). The string must contain a number in the format `"3.14159"` (or `"-3.141519"` for negative numbers). The fractional digits are fully preserved; if that's not possible due to the limit of significant digits (around 28 to 29) having been reached, an error is raised as the given decimal number wouldn't be representable.
While this constructor can be used with [floating-point numbers](/docs/reference/foundations/float/) to cast them to `decimal`, doing so is **discouraged** as **this cast is
inherently imprecise.** It is easy to accidentally perform this cast by writing `decimal(1.234)` (note the lack of double quotes), which is why Typst will emit a warning in that case. Please write `decimal("1.234")` instead for that particular case (initialization of a constant decimal). Also note that floats that are NaN or infinite cannot be cast to decimals and will raise an error.
```typst
#decimal("1.222222222222222")
```
```typst
#decimal(
value
) -> decimal
```
### Parameters
- value:
- description: The value that should be converted to a decimal.
- type: bool | int | float | str | decimal
- default: None
@@ -0,0 +1,144 @@
# Dictionary
A map from string keys to values.
You can construct a dictionary by enclosing comma-separated `key: value` pairs in parentheses. The values do not have to be of the same type. Since empty parentheses already yield an empty array, you have to use the special `(:)` syntax to create an empty dictionary.
A dictionary is conceptually similar to an [array](/docs/reference/foundations/array/), but it is indexed by strings instead of integers. You can access and create dictionary entries with the `.at()` method. If you know the key statically, you can alternatively use [field access notation](/docs/reference/scripting/#fields) (`.key`) to access the value. To check whether a key is present in the dictionary, use the `in` keyword.
You can iterate over the pairs in a dictionary using a [for loop](/docs/reference/scripting/#loops). This will iterate in the order the pairs were inserted / declared initially.
Dictionaries can be added with the `+` operator and [joined together](/docs/reference/scripting/#blocks). They can also be [spread](/docs/reference/foundations/arguments/#spreading) into a function call or another dictionary[1](#1) with the `..spread` operator. In each case, if a key appears multiple times, the last value will override the others.
## Example
```typst
#let dict = (
name: "Typst",
born: 2019,
)
#dict.name \
#(dict.launch = 20)
#dict.len() \
#dict.keys() \
#dict.values() \
#dict.at("born") \
#dict.insert("city", "Berlin")
#("name" in dict)
```
[^1]: When spreading into a dictionary, if all items between the parentheses are spread, you have to use the special `(:..spread)` syntax. Otherwise, it will spread into an array.
## Constructor
## dictionary
Converts a value into a dictionary.
Note that this function is only intended for conversion of a dictionary-like value to a dictionary, not for creation of a dictionary from individual pairs. Use the dictionary syntax `(key: value)` instead.
```typst
#dictionary(sys).at("version")
```
```typst
#dictionary(
value
) -> dictionary
```
### Parameters
- value:
- description: The value that should be converted to a dictionary.
- type: module
- default: None
## Methods
## dictionary.len
The number of pairs in the dictionary.
## dictionary.at
Returns the value associated with the specified key in the dictionary. May be used on the left-hand side of an assignment if the key is already present in the dictionary. Returns the default value if the key is not part of the dictionary or fails with an error if no default value was specified.
```typst
#dictionary.at(
key,
default: any
) -> any
```
### Parameters
- key:
- description: The key at which to retrieve the item.
- type: str
- default: None
- default:
- description: A default value to return if the key is not part of the dictionary.
- type: any
- default: None
## dictionary.insert
Inserts a new pair into the dictionary. If the dictionary already contains this key, the value is updated.
To insert multiple pairs at once, you can just alternatively another dictionary with the `+=` operator.
```typst
#dictionary.insert(
key,
value
) ->
```
### Parameters
- key:
- description: The key of the pair that should be inserted.
- type: str
- default: None
- value:
- description: The value of the pair that should be inserted.
- type: any
- default: None
## dictionary.remove
Removes a pair from the dictionary by key and return the value.
```typst
#dictionary.remove(
key,
default: any
) -> any
```
### Parameters
- key:
- description: The key of the pair to remove.
- type: str
- default: None
- default:
- description: A default value to return if the key does not exist.
- type: any
- default: None
## dictionary.keys
Returns the keys of the dictionary as an array in insertion order.
## dictionary.values
Returns the values of the dictionary as an array in insertion order.
## dictionary.pairs
Returns the keys and values of the dictionary as an array of pairs. Each pair is represented as an array of length two.
@@ -0,0 +1,85 @@
# Duration
Represents a positive or negative span of time.
## Constructor
## duration
Creates a new duration.
You can specify the [duration](/docs/reference/foundations/duration/) using weeks, days, hours, minutes and seconds. You can also get a duration by subtracting two [datetimes](/docs/reference/foundations/datetime/).
```typst
#duration(
days: 3,
hours: 12,
).hours()
```
```typst
#duration(
seconds: int,
minutes: int,
hours: int,
days: int,
weeks: int
) -> duration
```
### Parameters
- seconds:
- description: The number of seconds.
- type: int
- default: 0
- minutes:
- description: The number of minutes.
- type: int
- default: 0
- hours:
- description: The number of hours.
- type: int
- default: 0
- days:
- description: The number of days.
- type: int
- default: 0
- weeks:
- description: The number of weeks.
- type: int
- default: 0
## Methods
## duration.seconds
The duration expressed in seconds.
This function returns the total duration represented in seconds as a floating-point number rather than the second component of the duration.
## duration.minutes
The duration expressed in minutes.
This function returns the total duration represented in minutes as a floating-point number rather than the second component of the duration.
## duration.hours
The duration expressed in hours.
This function returns the total duration represented in hours as a floating-point number rather than the second component of the duration.
## duration.days
The duration expressed in days.
This function returns the total duration represented in days as a floating-point number rather than the second component of the duration.
## duration.weeks
The duration expressed in weeks.
This function returns the total duration represented in weeks as a floating-point number rather than the second component of the duration.
@@ -0,0 +1,40 @@
# Evaluate
# eval
Evaluates a string as Typst code.
This function should only be used as a last resort.
## Example
```typst
#eval("1 + 1") \
#eval("(1, 2, 3, 4)").len() \
#eval("*Markup!*", mode: "markup") \
```
```typst
#eval(
source,
mode: str,
scope: dictionary
) -> any
```
## Parameters
- source:
- description: A string of Typst code to evaluate.
- type: str
- default: None
- mode:
- description: The [syntactical mode](/docs/reference/syntax/#modes) in which the string is parsed. ```typst #eval("= Heading", mode: "markup") #eval("1_2^3", mode: "math") ```
- type: str
- default: "code"
- scope:
- description: A scope of definitions that are made available. ```typst #eval("x + 1", scope: (x: 2)) \\ #eval( "abc/xyz", mode: "math", scope: ( abc: $a + b + c$, xyz: $x + y + z$, ), ) ```
- type: dictionary
- default: (:)
@@ -0,0 +1,147 @@
# Float
A floating-point number.
A limited-precision representation of a real number. Typst uses 64 bits to store floats. Wherever a float is expected, you can also pass an [integer](/docs/reference/foundations/int/).
You can convert a value to a float with this type's constructor.
NaN and positive infinity are available as `float.nan` and `float.inf` respectively.
## Example
```typst
#3.14 \
#1e4 \
#(10 / 4)
```
## Constructor
## float
Converts a value to a float.
- Booleans are converted to `0.0` or `1.0`.
- Integers are converted to the closest 64-bit float. For integers with absolute value less than `calc.pow(2, 53)`, this conversion is exact.
- Ratios are divided by 100%.
- Strings are parsed in base 10 to the closest 64-bit float. Exponential notation is supported.
```typst
#float(false) \
#float(true) \
#float(4) \
#float(40%) \
#float("2.7") \
#float("1e5")
```
```typst
#float(
value
) -> float
```
### Parameters
- value:
- description: The value that should be converted to a float.
- type: bool | int | float | ratio | str | decimal
- default: None
## Methods
## float.is-nan
Checks if a float is not a number.
In IEEE 754, more than one bit pattern represents a NaN. This function returns `true` if the float is any of those bit patterns.
```typst
#float.is-nan(0) \
#float.is-nan(1) \
#float.is-nan(float.nan)
```
## float.is-infinite
Checks if a float is infinite.
Floats can represent positive infinity and negative infinity. This function returns `true` if the float is an infinity.
```typst
#float.is-infinite(0) \
#float.is-infinite(1) \
#float.is-infinite(float.inf)
```
## float.signum
Calculates the sign of a floating point number.
- If the number is positive (including `+0.0`), returns `1.0`.
- If the number is negative (including `-0.0`), returns `-1.0`.
- If the number is NaN, returns `float.nan`.
```typst
#(5.0).signum() \
#(-5.0).signum() \
#(0.0).signum() \
#float.nan.signum()
```
## float.from-bytes
Interprets bytes as a float.
```typst
#float.from-bytes(bytes((0, 0, 0, 0, 0, 0, 240, 63))) \
#float.from-bytes(bytes((63, 240, 0, 0, 0, 0, 0, 0)), endian: "big")
```
```typst
#float.from-bytes(
bytes,
endian: str
) -> float
```
### Parameters
- bytes:
- description: The bytes that should be converted to a float. Must have a length of either 4 or 8. The bytes are then interpreted in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)\'s binary32 (single-precision) or binary64 (double-precision) format depending on the length of the bytes.
- type: bytes
- default: None
- endian:
- description: The endianness of the conversion.
- type: str
- default: "little"
## float.to-bytes
Converts a float to bytes.
```typst
#array(1.0.to-bytes(endian: "big")) \
#array(1.0.to-bytes())
```
```typst
#float.to-bytes(
endian: str,
size: int
) -> bytes
```
### Parameters
- endian:
- description: The endianness of the conversion.
- type: str
- default: "little"
- size:
- description: The size of the resulting bytes. This must be either 4 or 8. The call will return the representation of this float in either [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)\'s binary32 (single-precision) or binary64 (double-precision) format depending on the provided size.
- type: int
- default: 8
@@ -0,0 +1,127 @@
# 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 block arguments to a function _after_ the normal argument list. If the normal argument list would become empty, it can be omitted. Typst supports positional and named arguments. The former are identified by position and type, while the latter are written as `name: value`.
Within math mode, function calls have special behaviour. See the [math documentation](/docs/reference/math/) for more details.
## Example
```typst
// 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](/docs/reference/styling/#set-rules) and [show](/docs/reference/styling/#show-rules) rules to learn about additional ways you can work with functions in Typst.
## Element functions
Some functions are associated with _elements_ like [headings](/docs/reference/model/heading/) or [tables](/docs/reference/model/table/). When called, these create an element of their respective kind. In contrast to normal functions, they can further be used in [set rules](/docs/reference/styling/#set-rules), [show rules](/docs/reference/styling/#show-rules), and [selectors](/docs/reference/foundations/selector/).
## Function scopes
Functions can hold related definitions in their own scope, similar to a [module](/docs/reference/scripting/#modules). Examples of this are [`assert.eq`](/docs/reference/foundations/assert/#definitions-eq) or [`list.item`](/docs/reference/model/list/#definitions-item). However, this feature is currently only available for built-in functions.
## Defining functions
You can define your own function with a [let binding](/docs/reference/scripting/#bindings) that has a parameter list after the binding's name. The parameter list can contain mandatory positional parameters, named parameters with default values and [argument sinks](/docs/reference/foundations/arguments/).
The right-hand side of a function binding is the function body, which can be a block or any other expression. It defines the function's return value and can depend on the parameters. If the function body is a [code block](/docs/reference/scripting/#blocks), the return value is the result of joining the values of each expression in the block.
Within a function body, the `return` keyword can be used to exit early and optionally specify a return value. If no explicit return value is given, the body evaluates to the result of joining all expressions preceding the `return`.
Functions that don't return any meaningful value return [`none`](/docs/reference/foundations/none/) instead. The return type of such functions is not explicitly specified in the documentation. (An example of this is [`array.push`](/docs/reference/foundations/array/#definitions-push)).
```typst
#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`](/docs/reference/scripting/#modules)) into another using `import`. For example, assume that we have defined the `alert` function from the previous example in a file called `foo.typ`. We can import it into another file by writing `import "foo.typ": alert`.
## Unnamed functions
You can also create an unnamed function without creating a binding by specifying a parameter list followed by `=>` and the function body. If your function has just one parameter, the parentheses around the parameter list are optional. Unnamed functions are mainly useful for show rules, but also for settable properties that take functions like the page function's [`footer`](/docs/reference/layout/page/#parameters-footer) property.
```typst
#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)`](/docs/reference/foundations/array/#definitions-push). These can modify the values they are called on.
## Methods
## function.with
Returns a new function that has the given arguments pre-applied.
```typst
#function.with(
arguments
) -> function
```
### Parameters
- arguments:
- description: The arguments to apply to the function.
- type: any
- default: None
## function.where
Returns a selector that filters for elements belonging to this function whose fields have the values of the given arguments.
```typst
#show heading.where(level: 2): set text(blue)
= Section
== Subsection
=== Sub-subsection
```
```typst
#function.where(
fields
) -> selector
```
### Parameters
- fields:
- description: The fields to filter for.
- type: any
- default: None
@@ -0,0 +1,42 @@
# Foundations
Foundational types and functions.
Here, you'll find documentation for basic data types like [integers](/docs/reference/foundations/int/) and [strings](/docs/reference/foundations/str/) as well as details about core computational functions.
## Definitions
| Name | Description |
| --- | --- |
| [`arguments`](/reference/foundations/arguments/) | Captured arguments to a function. |
| [`array`](/reference/foundations/array/) | A sequence of values. |
| [`assert`](/reference/foundations/assert/) | Ensures that a condition is fulfilled. |
| [`auto`](/reference/foundations/auto/) | A value that indicates a smart default. |
| [`bool`](/reference/foundations/bool/) | A type with two states. |
| [`bytes`](/reference/foundations/bytes/) | A sequence of bytes. |
| [`calc`](/reference/foundations/calc/) | Module for calculations and processing of numeric values. |
| [`content`](/reference/foundations/content/) | A piece of document content. |
| [`datetime`](/reference/foundations/datetime/) | Represents a date, a time, or a combination of both. |
| [`decimal`](/reference/foundations/decimal/) | A fixed-point decimal number type. |
| [`dictionary`](/reference/foundations/dictionary/) | A map from string keys to values. |
| [`duration`](/reference/foundations/duration/) | Represents a positive or negative span of time. |
| [`eval`](/reference/foundations/eval/) | Evaluates a string as Typst code. |
| [`float`](/reference/foundations/float/) | A floating-point number. |
| [`function`](/reference/foundations/function/) | A mapping from argument values to a return value. |
| [`int`](/reference/foundations/int/) | A whole number. |
| [`label`](/reference/foundations/label/) | A label for an element. |
| [`module`](/reference/foundations/module/) | A collection of variables and functions that are commonly related to a single theme. |
| [`none`](/reference/foundations/none/) | A value that indicates the absence of any other value. |
| [`panic`](/reference/foundations/panic/) | Fails with an error. |
| [`plugin`](/reference/foundations/plugin/) | Loads a WebAssembly module. |
| [`regex`](/reference/foundations/regex/) | A regular expression. |
| [`repr`](/reference/foundations/repr/) | Returns the string representation of a value. |
| [`selector`](/reference/foundations/selector/) | A filter for selecting elements within the document. |
| [`std`](/reference/foundations/std/) | A module that contains all globally accessible items. |
| [`str`](/reference/foundations/str/) | A sequence of Unicode codepoints. |
| [`symbol`](/reference/foundations/symbol/) | A Unicode symbol. |
| [`sys`](/reference/foundations/sys/) | Module for system interactions. |
| [`target`](/reference/foundations/target/) | Returns the current export target. |
| [`type`](/reference/foundations/type/) | Describes a kind of value. |
| [`version`](/reference/foundations/version/) | A version with an arbitrary number of components. |
@@ -0,0 +1,263 @@
# Integer
A whole number.
The number can be negative, zero, or positive. As Typst uses 64 bits to store integers, integers cannot be smaller than `-9223372036854775808` or larger than `9223372036854775807`. Integer literals are always positive, so a negative integer such as `-1` is semantically the negation `-` of the positive literal `1`. A positive integer greater than the maximum value and a negative integer less than or equal to the minimum value cannot be represented as an integer literal, and are instead parsed as a `float`. The minimum integer value can still be obtained through integer arithmetic.
The number can also be specified as hexadecimal, octal, or binary by starting it with a zero followed by either `x`, `o`, or `b`.
You can convert a value to an integer with this type's constructor.
## Example
```typst
#(1 + 2) \
#(2 - 5) \
#(3 + 4 < 8)
#0xff \
#0o10 \
#0b1001
```
## Constructor
## int
Converts a value to an integer. Raises an error if there is an attempt to produce an integer larger than the maximum 64-bit signed integer or smaller than the minimum 64-bit signed integer.
- Booleans are converted to `0` or `1`.
- Floats and decimals are rounded to the next 64-bit integer towards zero.
- Strings are parsed in base 10.
```typst
#int(false) \
#int(true) \
#int(2.7) \
#int(decimal("3.8")) \
#(int("27") + int("4"))
```
```typst
#int(
value
) -> int
```
### Parameters
- value:
- description: The value that should be converted to an integer.
- type: bool | int | float | str | decimal
- default: None
## Methods
## int.signum
Calculates the sign of an integer.
- If the number is positive, returns `1`.
- If the number is negative, returns `-1`.
- If the number is zero, returns `0`.
```typst
#(5).signum() \
#(-5).signum() \
#(0).signum()
```
## int.bit-not
Calculates the bitwise NOT of an integer.
For the purposes of this function, the operand is treated as a signed integer of 64 bits.
```typst
#4.bit-not() \
#(-1).bit-not()
```
## int.bit-and
Calculates the bitwise AND between two integers.
For the purposes of this function, the operands are treated as signed integers of 64 bits.
```typst
#128.bit-and(192)
```
```typst
#int.bit-and(
rhs
) -> int
```
### Parameters
- rhs:
- description: The right-hand operand of the bitwise AND.
- type: int
- default: None
## int.bit-or
Calculates the bitwise OR between two integers.
For the purposes of this function, the operands are treated as signed integers of 64 bits.
```typst
#64.bit-or(32)
```
```typst
#int.bit-or(
rhs
) -> int
```
### Parameters
- rhs:
- description: The right-hand operand of the bitwise OR.
- type: int
- default: None
## int.bit-xor
Calculates the bitwise XOR between two integers.
For the purposes of this function, the operands are treated as signed integers of 64 bits.
```typst
#64.bit-xor(96)
```
```typst
#int.bit-xor(
rhs
) -> int
```
### Parameters
- rhs:
- description: The right-hand operand of the bitwise XOR.
- type: int
- default: None
## int.bit-lshift
Shifts the operand's bits to the left by the specified amount.
For the purposes of this function, the operand is treated as a signed integer of 64 bits. An error will occur if the result is too large to fit in a 64-bit integer.
```typst
#33.bit-lshift(2) \
#(-1).bit-lshift(3)
```
```typst
#int.bit-lshift(
shift
) -> int
```
### Parameters
- shift:
- description: The amount of bits to shift. Must not be negative.
- type: int
- default: None
## int.bit-rshift
Shifts the operand's bits to the right by the specified amount. Performs an arithmetic shift by default (extends the sign bit to the left, such that negative numbers stay negative), but that can be changed by the `logical` parameter.
For the purposes of this function, the operand is treated as a signed integer of 64 bits.
```typst
#64.bit-rshift(2) \
#(-8).bit-rshift(2) \
#(-8).bit-rshift(2, logical: true)
```
```typst
#int.bit-rshift(
shift,
logical: bool
) -> int
```
### Parameters
- shift:
- description: The amount of bits to shift. Must not be negative. Shifts larger than 63 are allowed and will cause the return value to saturate. For non-negative numbers, the return value saturates at `0`, while, for negative numbers, it saturates at `-1` if `logical` is set to `false`, or `0` if it is `true`. This behavior is consistent with just applying this operation multiple times. Therefore, the shift will always succeed.
- type: int
- default: None
- logical:
- description: Toggles whether a logical (unsigned) right shift should be performed instead of arithmetic right shift. If this is `true`, negative operands will not preserve their sign bit, and bits which appear to the left after the shift will be `0`. This parameter has no effect on non-negative operands.
- type: bool
- default: false
## int.from-bytes
Converts bytes to an integer.
```typst
#int.from-bytes(bytes((0, 0, 0, 0, 0, 0, 0, 1))) \
#int.from-bytes(bytes((1, 0, 0, 0, 0, 0, 0, 0)), endian: "big")
```
```typst
#int.from-bytes(
bytes,
endian: str,
signed: bool
) -> int
```
### Parameters
- bytes:
- description: The bytes that should be converted to an integer. Must be of length at most 8 so that the result fits into a 64-bit signed integer.
- type: bytes
- default: None
- endian:
- description: The endianness of the conversion.
- type: str
- default: "little"
- signed:
- description: Whether the bytes should be treated as a signed integer. If this is `true` and the most significant bit is set, the resulting number will negative.
- type: bool
- default: true
## int.to-bytes
Converts an integer to bytes.
```typst
#array(10000.to-bytes(endian: "big")) \
#array(10000.to-bytes(size: 4))
```
```typst
#int.to-bytes(
endian: str,
size: int
) -> bytes
```
### Parameters
- endian:
- description: The endianness of the conversion.
- type: str
- default: "little"
- size:
- description: The size in bytes of the resulting bytes (must be at least zero). If the integer is too large to fit in the specified size, the conversion will truncate the remaining bytes based on the endianness. To keep the same resulting value, if the endianness is big-endian, the truncation will happen at the rightmost bytes. Otherwise, if the endianness is little-endian, the truncation will happen at the leftmost bytes. Be aware that if the integer is negative and the size is not enough to make the number fit, when passing the resulting bytes to `int.from-bytes`, the resulting number might be positive, as the most significant bit might not be set to 1.
- type: int
- default: 8
@@ -0,0 +1,55 @@
# Label
A label for an element.
Inserting a label into content attaches it to the closest preceding element that is not a space. The preceding element must be in the same scope as the label, which means that `Hello #[<label>]`, for instance, wouldn't work.
A labelled element can be [referenced](/docs/reference/model/ref/), [queried](/docs/reference/introspection/query/) for, and [styled](/docs/reference/styling/) through its label.
Once constructed, you can get the name of a label using [`str`](/docs/reference/foundations/str/#constructor).
## Example
```typst
#show <a>: set text(blue)
#show label("b"): set text(red)
= Heading <a>
*Strong* #label("b")
```
## Syntax
This function also has dedicated syntax: You can create a label by enclosing its name in angle brackets. This works both in markup and code. A label's name can contain letters, numbers, `_`, `-`, `:`, and `.`. A label cannot be empty.
Note that there is a syntactical difference when using the dedicated syntax for this function. In the code below, the `<a>` terminates the heading and thus attaches to the heading itself, whereas the `#label("b")` is part of the heading and thus attaches to the heading's text.
```typst
// Equivalent to `#heading[Introduction] <a>`.
= Introduction <a>
// Equivalent to `#heading[Conclusion #label("b")]`.
= Conclusion #label("b")
```
Currently, labels can only be attached to elements in markup mode, not in code mode. This might change in the future.
## Constructor
## label
Creates a label from a string.
```typst
#label(
name
) -> label
```
### Parameters
- name:
- description: The name of the label. Unlike the [dedicated syntax](#syntax), this constructor accepts any non-empty string, including names with special characters.
- type: str
- default: None
@@ -0,0 +1,31 @@
# Module
A collection of variables and functions that are commonly related to a single theme.
A module can
- be built-in
- stem from a [file import](/docs/reference/scripting/#modules)
- stem from a [package import](/docs/reference/scripting/#packages) (and thus indirectly its entrypoint file)
- result from a call to the [plugin](/docs/reference/foundations/plugin/) function
You can access definitions from the module using [field access notation](/docs/reference/scripting/#fields) and interact with it using the [import and include syntaxes](/docs/reference/scripting/#modules).
```typst
#import "utils.typ"
#utils.add(2, 5)
#import utils: sub
#sub(1, 4)
```
You can check whether a definition is present in a module using the `in` operator, with a string on the left-hand side. This can be useful to [conditionally access](/docs/reference/foundations/std/#conditional-access) definitions in a module.
```typst
#("table" in std) \
#("nope" in std)
```
Alternatively, it is possible to convert a module to a dictionary, and therefore access its contents dynamically, using the [dictionary constructor](/docs/reference/foundations/dictionary/#constructor).
@@ -0,0 +1,15 @@
# None
A value that indicates the absence of any other value.
The none type has exactly one value: `none`.
When inserted into the document, it is not visible. This is also the value that is produced by empty code blocks. It can be [joined](/docs/reference/scripting/#blocks) with any value, yielding the other value.
## Example
```typst
Not visible: #none
```
@@ -0,0 +1,30 @@
# Panic
# panic
Fails with an error.
Arguments are displayed to the user (not rendered in the document) as strings, converting with `repr` if necessary.
## Example
The code below produces the error `panicked with: "this is wrong"`.
```typst
#panic("this is wrong")
```
```typst
#panic(
values
) ->
```
## Parameters
- values:
- description: The values to panic with and display to the user.
- type: any
- default: None
@@ -0,0 +1,135 @@
# Plugin
# plugin
Loads a WebAssembly module.
The resulting [module](/docs/reference/foundations/module/) will contain one Typst [function](/docs/reference/foundations/function/) for each function export of the loaded WebAssembly module.
Typst WebAssembly plugins need to follow a specific [protocol](/docs/reference/foundations/plugin/#protocol). To run as a plugin, a program needs to be compiled to a 32-bit shared WebAssembly library. Plugin functions may accept multiple [byte buffers](/docs/reference/foundations/bytes/) as arguments and return a single byte buffer. They should typically be wrapped in idiomatic Typst functions that perform the necessary conversions between native Typst types and bytes by leveraging [`str`](/docs/reference/foundations/str/#constructor), [`bytes`](/docs/reference/foundations/bytes/#constructor), and [data loading functions](/docs/reference/data-loading/).
For security reasons, plugins run in isolation from your system. This means that printing, reading files, or similar things are not supported.
## Example
```typst
#let myplugin = plugin("hello.wasm")
#let concat(a, b) = str(
myplugin.concatenate(
bytes(a),
bytes(b),
)
)
#concat("hello", "world")
```
Since the plugin function returns a module, it can be used with import syntax:
```typst
#import plugin("hello.wasm"): concatenate
```
## Purity
Plugin functions **must be pure:** A plugin function call must not have any observable side effects on future plugin calls and given the same arguments, it must always return the same value.
The reason for this is that Typst functions must be pure (which is quite fundamental to the language design) and, since Typst function can call plugin functions, this requirement is inherited. In particular, if a plugin function is called twice with the same arguments, Typst might cache the results and call your function only once. Moreover, Typst may run multiple instances of your plugin in multiple threads, with no state shared between them.
Typst does not enforce plugin function purity (for efficiency reasons), but calling an impure function will lead to unpredictable and irreproducible results and must be avoided.
That said, mutable operations _can be_ useful for plugins that require costly runtime initialization. Due to the purity requirement, such initialization cannot be performed through a normal function call. Instead, Typst exposes a [plugin transition API](/docs/reference/foundations/plugin/#definitions-transition), which executes a function call and then creates a derived module with new functions which will observe the side effects produced by the transition call. The original plugin remains unaffected.
## Plugins and Packages
Any Typst code can make use of a plugin simply by including a WebAssembly file and loading it. However, because the byte-based plugin interface is quite low-level, plugins are typically exposed through a package containing the plugin and idiomatic wrapper functions.
## WASI
Many compilers will use the [WASI ABI](https://wasi.dev/) by default or as their only option (e.g. emscripten), which allows printing, reading files, etc. This ABI will not directly work with Typst. You will either need to compile to a different target or [stub all functions](https://github.com/astrale-sharp/wasm-minimal-protocol/tree/master/crates/wasi-stub).
## Protocol
To be used as a plugin, a WebAssembly module must conform to the following protocol:
### Exports
A plugin module can export functions to make them callable from Typst. To conform to the protocol, an exported function should:
- Take `n` 32-bit integer arguments `a_1`, `a_2`, ..., `a_n` (interpreted as lengths, so `usize/size_t` may be preferable), and return one 32-bit integer.
- The function should first allocate a buffer `buf` of length `a_1 + a_2 + ... + a_n`, and then call `wasm_minimal_protocol_write_args_to_buffer(buf.ptr)`.
- The `a_1` first bytes of the buffer now constitute the first argument, the `a_2` next bytes the second argument, and so on.
- The function can now do its job with the arguments and produce an output buffer. Before returning, it should call `wasm_minimal_protocol_send_result_to_host` to send its result back to the host.
- To signal success, the function should return `0`.
- To signal an error, the function should return `1`. The written buffer is then interpreted as an UTF-8 encoded error message.
### Imports
Plugin modules need to import two functions that are provided by the runtime. (Types and functions are described using WAT syntax.)
- `(import "typst_env" "wasm_minimal_protocol_write_args_to_buffer" (func (param i32)))` Writes the arguments for the current function into a plugin-allocated buffer. When a plugin function is called, it [receives the lengths](#exports) of its input buffers as arguments. It should then allocate a buffer whose capacity is at least the sum of these lengths. It should then call this function with a `ptr` to the buffer to fill it with the arguments, one after another.
- `(import "typst_env" "wasm_minimal_protocol_send_result_to_host" (func (param i32 i32)))` Sends the output of the current function to the host (Typst). The first parameter shall be a pointer to a buffer (`ptr`), while the second is the length of that buffer (`len`). The memory pointed at by `ptr` can be freed immediately after this function returns. If the message should be interpreted as an error message, it should be encoded as UTF-8.
## Resources
For more resources, check out the [wasm-minimal-protocol repository](https://github.com/astrale-sharp/wasm-minimal-protocol). It contains:
- A list of example plugin implementations and a test runner for these examples
- Wrappers to help you write your plugin in Rust (Zig wrapper in development)
- A stubber for WASI
```typst
#plugin(
source
) -> module
```
## Parameters
- source:
- description: A [path](/docs/reference/syntax/#paths) to a WebAssembly file or raw WebAssembly bytes.
- type: str | bytes
- default: None
## Definitions
### plugin.transition
Calls a plugin function that has side effects and returns a new module with plugin functions that are guaranteed to have observed the results of the mutable call.
Note that calling an impure function through a normal function call (without use of the transition API) is forbidden and leads to unpredictable behaviour. Read the [section on purity](/docs/reference/foundations/plugin/#purity) for more details.
In the example below, we load the plugin `hello-mut.wasm` which exports two functions: The `get()` function retrieves a global array as a string. The `add(value)` function adds a value to the global array.
We call `add` via the transition API. The call `mutated.get()` on the derived module will observe the addition. Meanwhile the original module remains untouched as demonstrated by the `base.get()` call.
_Note:_ Due to limitations in the internal WebAssembly implementation, the transition API can only guarantee to reflect changes in the plugin's memory, not in WebAssembly globals. If your plugin relies on changes to globals being visible after transition, you might want to avoid use of the transition API for now. We hope to lift this limitation in the future.
```typst
#let base = plugin("hello-mut.wasm")
#assert.eq(base.get(), "[]")
#let mutated = plugin.transition(base.add, "hello")
#assert.eq(base.get(), "[]")
#assert.eq(mutated.get(), "[hello]")
```
```typst
#plugin.transition(
func,
arguments
) -> module
```
#### Parameters
- func:
- description: The plugin function to call.
- type: function
- default: None
- arguments:
- description: The byte buffers to call the function with.
- type: bytes
- default: None
@@ -0,0 +1,39 @@
# Regex
A regular expression.
Can be used as a [show rule selector](/docs/reference/styling/#show-rules) and with [string methods](/docs/reference/foundations/str/) like `find`, `split`, and `replace`.
[See here](https://docs.rs/regex/latest/regex/#syntax) for a specification of the supported syntax.
## Example
```typst
// Works with string methods.
#"a,b;c".split(regex("[,;]"))
// Works with show rules.
#show regex("\\d+"): set text(red)
The numbers 1 to 10.
```
## Constructor
## regex
Create a regular expression from a string.
```typst
#regex(
regex
) -> regex
```
### Parameters
- regex:
- description: The regular expression as a string. Both Typst strings and regular expressions use backslashes for escaping. To produce a regex escape sequence that is also valid in Typst, you need to escape the backslash itself (e.g., writing `regex("\\\\\\\\")` for the regex `\\\\`). Regex escape sequences that are not valid Typst escape sequences (e.g., `\\d` and `\\b`) can be entered into strings directly, but it\'s good practice to still escape them to avoid ambiguity (i.e., `regex("\\\\b\\\\d")`). See the [list of valid string escape sequences](/docs/reference/foundations/str/#escapes). If you need many escape sequences, you can also create a raw element and extract its text to use it for your regular expressions: `regex(`\\d+\\.\\d+\\.\\d+`.text)`.
- type: str
- default: None
@@ -0,0 +1,44 @@
# Representation
# repr
Returns the string representation of a value.
When inserted into content, most values are displayed as this representation in monospace with syntax-highlighting. The exceptions are `none`, integers, floats, strings, content, and functions.
## Example
```typst
#none vs #repr(none) \
#"hello" vs #repr("hello") \
#(1, 2) vs #repr((1, 2)) \
#[*Hi*] vs #repr([*Hi*])
```
## For debugging purposes only
This function is for debugging purposes. Its output should not be considered stable and may change at any time.
To be specific, having the same `repr` does not guarantee that values are equivalent, and `repr` is not a strict inverse of [`eval`](/docs/reference/foundations/eval/). In the following example, for readability, the [`length`](/docs/reference/layout/length/) is rounded to two significant digits and the parameter list and body of the [unnamed `function`](/docs/reference/foundations/function/#unnamed) are omitted.
```typst
#assert(2pt / 3 < 0.67pt)
#repr(2pt / 3)
#repr(x => x + 1)
```
```typst
#repr(
value
) -> str
```
## Parameters
- value:
- description: The value whose string representation to produce.
- type: any
- default: None
@@ -0,0 +1,138 @@
# Selector
A filter for selecting elements within the document.
To construct a selector you can:
- use an [element function](/docs/reference/foundations/function/#element-functions)
- filter for an element function with [specific fields](/docs/reference/foundations/function/#definitions-where)
- use a [string](/docs/reference/foundations/str/) or [regular expression](/docs/reference/foundations/regex/)
- use a [`<label>`](/docs/reference/foundations/label/)
- use a [`location`](/docs/reference/introspection/location/)
- call the [`selector`](/docs/reference/foundations/selector/) constructor to convert any of the above types into a selector value and use the methods below to refine it
Selectors are used to [apply styling rules](/docs/reference/styling/#show-rules) to elements. You can also use selectors to [query](/docs/reference/introspection/query/) the document for certain types of elements.
Furthermore, you can pass a selector to several of Typst's built-in functions to configure their behaviour. One such example is the [outline](/docs/reference/model/outline/) where it can be used to change which elements are listed within the outline.
Multiple selectors can be combined using the methods shown below. However, not all kinds of selectors are supported in all places, at the moment.
## Example
```typst
#context query(
heading.where(level: 1)
.or(heading.where(level: 2))
)
= This will be found
== So will this
=== But this will not.
```
## Constructor
## selector
Turns a value into a selector. The following values are accepted:
- An element function like a `heading` or `figure`.
- A [string](/docs/reference/foundations/str/) or [regular expression](/docs/reference/foundations/regex/).
- A `<label>`.
- A [`location`](/docs/reference/introspection/location/).
- A more complex selector like `heading.where(level: 1)`.
```typst
#selector(
target
) -> selector
```
### Parameters
- target:
- description: Can be an element function like a `heading` or `figure`, a `<label>` or a more complex selector like `heading.where(level: 1)`.
- type: str | regex | label | selector | location | function
- default: None
## Methods
## selector.or
Selects all elements that match this or any of the other selectors.
```typst
#selector.or(
others
) -> selector
```
### Parameters
- others:
- description: The other selectors to match on.
- type: str | regex | label | selector | location | function
- default: None
## selector.and
Selects all elements that match this and all of the other selectors.
```typst
#selector.and(
others
) -> selector
```
### Parameters
- others:
- description: The other selectors to match on.
- type: str | regex | label | selector | location | function
- default: None
## selector.before
Returns a modified selector that will only match elements that occur before the first match of `end`.
```typst
#selector.before(
end,
inclusive: bool
) -> selector
```
### Parameters
- end:
- description: The original selection will end at the first match of `end`.
- type: label | selector | location | function
- default: None
- inclusive:
- description: Whether `end` itself should match or not. This is only relevant if both selectors match the same type of element. Defaults to `true`.
- type: bool
- default: true
## selector.after
Returns a modified selector that will only match elements that occur after the first match of `start`.
```typst
#selector.after(
start,
inclusive: bool
) -> selector
```
### Parameters
- start:
- description: The original selection will start at the first match of `start`.
- type: label | selector | location | function
- default: None
- inclusive:
- description: Whether `start` itself should match or not. This is only relevant if both selectors match the same type of element. Defaults to `true`.
- type: bool
- default: true
@@ -0,0 +1,34 @@
# Standard Library
A module that contains all globally accessible items.
## Using "shadowed" definitions
The `std` module is useful whenever you overrode a name from the global scope (this is called _shadowing_). For instance, you might have used the name `text` for a parameter. To still access the `text` element, write `std.text`.
```typst
#let par = [My special paragraph.]
#let special(text) = {
set std.text(style: "italic")
set std.par.line(numbering: "1")
text
}
#special(par)
#lorem(10)
```
## Conditional access
You can also use this in combination with the [dictionary constructor](/docs/reference/foundations/dictionary/) to conditionally access global definitions. This can, for instance, be useful to use new or experimental functionality when it is available, while falling back to an alternative implementation if used on an older Typst version. In particular, this allows us to create [polyfills](https://en.wikipedia.org/wiki/Polyfill_(programming)).
This can be as simple as creating an alias to prevent warning messages, for example, conditionally using `pattern` in Typst version 0.12, but using [`tiling`](/docs/reference/visualize/tiling/) in newer versions. Since the parameters accepted by the `tiling` function match those of the older `pattern` function, using the `tiling` function when available and falling back to `pattern` otherwise will unify the usage across all versions. Note that, when creating a polyfill, [`sys.version`](/docs/reference/foundations/sys/) can also be very useful.
```typst
#let tiling = if "tiling" in std { tiling } else { pattern }
...
```
@@ -0,0 +1,465 @@
# String
A sequence of Unicode codepoints.
You can iterate over the grapheme clusters of the string using a [for loop](/docs/reference/scripting/#loops). Grapheme clusters are basically characters but keep together things that belong together, e.g. multiple codepoints that together form a flag emoji. Strings can be added with the `+` operator, [joined together](/docs/reference/scripting/#blocks) and multiplied with integers.
Typst provides utility methods for string manipulation. Many of these methods (e.g., [`split`](/docs/reference/foundations/str/#definitions-split), [`trim`](/docs/reference/foundations/str/#definitions-trim) and [`replace`](/docs/reference/foundations/str/#definitions-replace)) operate on _patterns:_ A pattern can be either a string or a [regular expression](/docs/reference/foundations/regex/). This makes the methods quite versatile.
All lengths and indices are expressed in terms of UTF-8 bytes. Indices are zero-based and negative indices wrap around to the end of the string.
You can convert a value to a string with this type's constructor.
## Example
```typst
#"hello world!" \
#"\"hello\n world\"!" \
#"1 2 3".split() \
#"1,2;3".split(regex("[,;]")) \
#(regex("\\d+") in "ten euros") \
#(regex("\\d+") in "10 euros")
```
## Escape sequences
Just like in markup, you can escape a few symbols in strings:
- `\\` for a backslash
- `\"` for a quote
- `\n` for a newline
- `\r` for a carriage return
- `\t` for a tab
- `\u\{1f600\}` for a hexadecimal Unicode escape sequence
## Constructor
## str
Converts a value to a string.
- Integers are formatted in base 10. This can be overridden with the optional `base` parameter.
- Floats are formatted in base 10 and never in exponential notation.
- Negative integers and floats are formatted with the Unicode minus sign ("−" U+2212) instead of the ASCII minus sign ("-" U+002D).
- From labels the name is extracted.
- Bytes are decoded as UTF-8.
If you wish to convert from and to Unicode code points, see the [`to-unicode`](/docs/reference/foundations/str/#definitions-to-unicode) and [`from-unicode`](/docs/reference/foundations/str/#definitions-from-unicode) functions.
```typst
#str(10) \
#str(4000, base: 16) \
#str(2.7) \
#str(1e8) \
#str(<intro>)
```
```typst
#str(
value,
base: int
) -> str
```
### Parameters
- value:
- description: The value that should be converted to a string.
- type: int | float | str | bytes | label | decimal | version | type
- default: None
- base:
- description: The base (radix) to display integers in, between 2 and 36.
- type: int
- default: 10
## Methods
## str.len
The length of the string in UTF-8 encoded bytes.
## str.first
Extracts the first grapheme cluster of the string.
Returns the provided default value if the string is empty or fails with an error if no default value was specified.
```typst
#str.first(
default: str
) -> str
```
### Parameters
- default:
- description: A default value to return if the string is empty.
- type: str
- default: None
## str.last
Extracts the last grapheme cluster of the string.
Returns the provided default value if the string is empty or fails with an error if no default value was specified.
```typst
#str.last(
default: str
) -> str
```
### Parameters
- default:
- description: A default value to return if the string is empty.
- type: str
- default: None
## str.at
Extracts the first grapheme cluster after the specified index. Returns the default value if the index is out of bounds or fails with an error if no default value was specified.
```typst
#str.at(
index,
default: any
) -> any
```
### Parameters
- index:
- description: The byte index. If negative, indexes from the back.
- type: int
- default: None
- default:
- description: A default value to return if the index is out of bounds.
- type: any
- default: None
## str.slice
Extracts a substring of the string. Fails with an error if the start or end index is out of bounds.
```typst
#str.slice(
start,
end,
count: int
) -> str
```
### Parameters
- start:
- description: The start byte index (inclusive). If negative, indexes from the back.
- type: int
- default: None
- end:
- description: The end byte index (exclusive). If omitted, the whole slice until the end of the string is extracted. If negative, indexes from the back.
- type: none | int
- default: none
- count:
- description: The number of bytes to extract. This is equivalent to passing `start + count` as the `end` position. Mutually exclusive with `end`.
- type: int
- default: None
## str.clusters
Returns the grapheme clusters of the string as an array of substrings.
## str.codepoints
Returns the Unicode codepoints of the string as an array of substrings.
## str.to-unicode
Converts a character into its corresponding code point.
```typst
#"a".to-unicode() \
#("a\u{0300}"
.codepoints()
.map(str.to-unicode))
```
```typst
#str.to-unicode(
character
) -> int
```
### Parameters
- character:
- description: The character that should be converted.
- type: str
- default: None
## str.from-unicode
Converts a unicode code point into its corresponding string.
```typst
#str.from-unicode(97)
```
```typst
#str.from-unicode(
value
) -> str
```
### Parameters
- value:
- description: The code point that should be converted.
- type: int
- default: None
## str.normalize
Normalizes the string to the given Unicode normal form.
This is useful when manipulating strings containing Unicode combining characters.
```typst
#assert.eq("é".normalize(form: "nfd"), "e\u{0301}")
#assert.eq("ſ́".normalize(form: "nfkc"), "ś")
```
```typst
#str.normalize(
form: str
) -> str
```
### Parameters
- form:
- description:
- type: str
- default: "nfc"
## str.contains
Whether the string contains the specified pattern.
This method also has dedicated syntax: You can write `"bc" in "abcd"` instead of `"abcd".contains("bc")`.
```typst
#str.contains(
pattern
) -> bool
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
## str.starts-with
Whether the string starts with the specified pattern.
```typst
#str.starts-with(
pattern
) -> bool
```
### Parameters
- pattern:
- description: The pattern the string might start with.
- type: str | regex
- default: None
## str.ends-with
Whether the string ends with the specified pattern.
```typst
#str.ends-with(
pattern
) -> bool
```
### Parameters
- pattern:
- description: The pattern the string might end with.
- type: str | regex
- default: None
## str.find
Searches for the specified pattern in the string and returns the first match as a string or `none` if there is no match.
```typst
#str.find(
pattern
) -> none str
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
## str.position
Searches for the specified pattern in the string and returns the index of the first match as an integer or `none` if there is no match.
```typst
#str.position(
pattern
) -> none int
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
## str.match
Searches for the specified pattern in the string and returns a dictionary with details about the first match or `none` if there is no match.
The returned dictionary has the following keys:
- `start`: The start offset of the match
- `end`: The end offset of the match
- `text`: The text that matched.
- `captures`: An array containing a string for each matched capturing group. The first item of the array contains the first matched capturing, not the whole match! This is empty unless the `pattern` was a regex with capturing groups.
```typst
#let pat = regex("not (a|an) (apple|cat)")
#"I'm a doctor, not an apple.".match(pat) \
#"I am not a cat!".match(pat)
```
```typst
#assert.eq("Is there a".match("for this?"), none)
#"The time of my life.".match(regex("[mit]+e"))
```
```typst
#str.match(
pattern
) -> none dictionary
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
## str.matches
Searches for the specified pattern in the string and returns an array of dictionaries with details about all matches. For details about the returned dictionaries, see [above](/docs/reference/foundations/str/#definitions-match).
```typst
#"Day by Day.".matches("Day")
```
```typst
#str.matches(
pattern
) -> array
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
## str.replace
Replace at most `count` occurrences of the given pattern with a replacement string or function (beginning from the start). If no count is given, all occurrences are replaced.
```typst
#str.replace(
pattern,
replacement,
count: int
) -> str
```
### Parameters
- pattern:
- description: The pattern to search for.
- type: str | regex
- default: None
- replacement:
- description: The string to replace the matches with or a function that gets a dictionary for each match and can return individual replacement strings. The dictionary passed to the function has the same shape as the dictionary returned by [`match`](/docs/reference/foundations/str/#definitions-match).
- type: str | function
- default: None
- count:
- description: If given, only the first `count` matches of the pattern are placed.
- type: int
- default: None
## str.trim
Removes matches of a pattern from one or both sides of the string, once or repeatedly and returns the resulting string.
```typst
#str.trim(
pattern,
at: alignment,
repeat: bool
) -> str
```
### Parameters
- pattern:
- description: The pattern to search for. If `none`, trims white spaces.
- type: none | str | regex
- default: none
- at:
- description: Can be `start` or `end` to only trim the start or end of the string. If omitted, both sides are trimmed.
- type: alignment
- default: None
- repeat:
- description: Whether to repeatedly removes matches of the pattern or just once. Defaults to `true`.
- type: bool
- default: true
## str.split
Splits a string at matches of a specified pattern and returns an array of the resulting parts.
When the empty string is used as a separator, it separates every character (i.e., Unicode code point) in the string, along with the beginning and end of the string. In practice, this means that the resulting list of parts will contain the empty string at the start and end of the list.
```typst
#str.split(
pattern
) -> array
```
### Parameters
- pattern:
- description: The pattern to split at. Defaults to whitespace.
- type: none | str | regex
- default: none
## str.rev
Reverse the string.
@@ -0,0 +1,61 @@
# Symbol
A Unicode symbol.
Typst defines common symbols so that they can easily be written with standard keyboards. The symbols are defined in modules, from which they can be accessed using [field access notation](/docs/reference/scripting/#fields):
- General symbols are defined in the [`sym` module](/docs/reference/symbols/sym/) and are accessible without the `sym.` prefix in math mode.
- Emoji are defined in the [`emoji` module](/docs/reference/symbols/emoji/)
Moreover, you can define custom symbols with this type's constructor function.
```typst
#sym.arrow.r \
#sym.gt.eq.not \
$gt.eq.not$ \
#emoji.face.halo
```
Many symbols have different variants, which can be selected by appending the modifiers with dot notation. The order of the modifiers is not relevant. Visit the documentation pages of the symbol modules and click on a symbol to see its available variants.
```typst
$arrow.l$ \
$arrow.r$ \
$arrow.t.quad$
```
## Constructor
## symbol
Create a custom symbol with modifiers.
```typst
#let envelope = symbol(
"🖂",
("stamped", "🖃"),
("stamped.pen", "🖆"),
("lightning", "🖄"),
("fly", "🖅"),
)
#envelope
#envelope.stamped
#envelope.stamped.pen
#envelope.lightning
#envelope.fly
```
```typst
#symbol(
variants
) -> symbol
```
### Parameters
- variants:
- description: The variants of the symbol. Can be a just a string consisting of a single character for the modifierless variant or an array with two strings specifying the modifiers and the symbol. Individual modifiers should be separated by dots. When displaying a symbol, Typst selects the first from the variants that have all attached modifiers and the minimum number of other modifiers.
- type: str | array
- default: None
@@ -0,0 +1,10 @@
# System
Module for system interactions.
This module defines the following items:
- The `sys.version` constant (of type [`version`](/docs/reference/foundations/version/)) that specifies the currently active Typst compiler version.
- The `sys.inputs` [dictionary](/docs/reference/foundations/dictionary/), which makes external inputs available to the project. An input specified in the command line as `--input key=value` becomes available under `sys.inputs.key` as `"value"`. To include spaces in the value, it may be enclosed with single or double quotes. The value is always of type [string](/docs/reference/foundations/str/). More complex data may be parsed manually using functions like [`json`](/docs/reference/data-loading/json/).
@@ -0,0 +1,45 @@
# Target
# target
Returns the current export target.
This function returns either
- `"paged"` (for PDF, PNG, and SVG export), or
- `"html"` (for HTML export).
The design of this function is not yet finalized and for this reason it is guarded behind the `html` feature. Visit the [HTML documentation page](/docs/reference/html/) for more details.
## When to use it
This function allows you to format your document properly across both HTML and paged export targets. It should primarily be used in templates and show rules, rather than directly in content. This way, the document's contents can be fully agnostic to the export target and content can be shared between PDF and HTML export.
## Varying targets
This function is [contextual](/docs/reference/context/) as the target can vary within a single compilation: When exporting to HTML, the target will be `"paged"` while within an [`html.frame`](/docs/reference/html/frame/).
## Example
```typst
#let kbd(it) = context {
if target() == "html" {
html.elem("kbd", it)
} else {
set text(fill: rgb("#1f2328"))
let r = 3pt
box(
fill: rgb("#f6f8fa"),
stroke: rgb("#d1d9e0b3"),
outset: (y: r),
inset: (x: r),
radius: r,
raw(it)
)
}
}
Press #kbd("F1") for help.
```
@@ -0,0 +1,69 @@
# Type
Describes a kind of value.
To style your document, you need to work with values of different kinds: Lengths specifying the size of your elements, colors for your text and shapes, and more. Typst categorizes these into clearly defined _types_ and tells you where it expects which type of value.
Apart from basic types for numeric values and [typical](/docs/reference/foundations/int/) [types](/docs/reference/foundations/float/) [known](/docs/reference/foundations/str/) [from](/docs/reference/foundations/array/) [programming](/docs/reference/foundations/dictionary/) languages, Typst provides a special type for [_content._](/docs/reference/foundations/content/) A value of this type can hold anything that you can enter into your document: Text, elements like headings and shapes, and style information.
## Example
```typst
#let x = 10
#if type(x) == int [
#x is an integer!
] else [
#x is another value...
]
An image is of type
#type(image("glacier.jpg")).
```
The type of `10` is `int`. Now, what is the type of `int` or even `type`?
```typst
#type(int) \
#type(type)
```
Unlike other types like `int`, [none](/docs/reference/foundations/none/) and [auto](/docs/reference/foundations/auto/) do not have a name representing them. To test if a value is one of these, compare your value to them directly, e.g:
```typst
#let val = none
#if val == none [
Yep, it's none.
]
```
Note that `type` will return [`content`](/docs/reference/foundations/content/) for all document elements. To programmatically determine which kind of content you are dealing with, see [`content.func`](/docs/reference/foundations/content/#definitions-func).
## Constructor
## type
Determines a value's type.
```typst
#type(12) \
#type(14.7) \
#type("hello") \
#type(<glacier>) \
#type([Hi]) \
#type(x => x + 1) \
#type(type)
```
```typst
#type(
value
) -> type
```
### Parameters
- value:
- description: The value whose type\'s to determine.
- type: any
- default: None
@@ -0,0 +1,71 @@
# Version
A version with an arbitrary number of components.
The first three components have names that can be used as fields: `major`, `minor`, `patch`. All following components do not have names.
The list of components is semantically extended by an infinite list of zeros. This means that, for example, `0.8` is the same as `0.8.0`. As a special case, the empty version (that has no components at all) is the same as `0`, `0.0`, `0.0.0`, and so on.
The current version of the Typst compiler is available as `sys.version`.
You can convert a version to an array of explicitly given components using the [`array`](/docs/reference/foundations/array/) constructor.
## Constructor
## version
Creates a new version.
It can have any number of components (even zero).
```typst
#version() \
#version(1) \
#version(1, 2, 3, 4) \
#version((1, 2, 3, 4)) \
#version((1, 2), 3)
```
As a practical use case, this allows comparing the current version ([`sys.version`](/docs/reference/foundations/version/)) to a specific one.
```typst
Current version: #sys.version \
#(sys.version >= version(0, 14, 0)) \
#(version(3, 2, 0) > version(4, 1, 0))
```
```typst
#version(
components
) -> version
```
### Parameters
- components:
- description: The components of the version (array arguments are flattened)
- type: int | array
- default: None
## Methods
## version.at
Retrieves a component of a version.
The returned integer is always non-negative. Returns `0` if the version isn't specified to the necessary length.
```typst
#version.at(
index
) -> int
```
### Parameters
- index:
- description: The index at which to retrieve the component. If negative, indexes from the back of the explicitly given components.
- type: int
- default: None
@@ -0,0 +1,42 @@
# Elem
# html.elem
An HTML element that can contain Typst content.
Typst's HTML export automatically generates the appropriate tags for most elements. However, sometimes, it is desirable to retain more control. For example, when using Typst to generate your blog, you could use this function to wrap each article in an `<article>` tag.
Typst is aware of what is valid HTML. A tag and its attributes must form syntactically valid HTML. Some tags, like `meta` do not accept content. Hence, you must not provide a body for them. We may add more checks in the future, so be sure that you are generating valid HTML when using this function.
Normally, Typst will generate `html`, `head`, and `body` tags for you. If you instead create them with this function, Typst will omit its own tags.
```typst
#html.elem("div", attrs: (style: "background: aqua"))[
A div with _Typst content_ inside!
]
```
```typst
#html.elem(
tag,
attrs: dictionary,
body
) -> content
```
## Parameters
- tag:
- description: The element\'s tag.
- type: str
- default: None
- attrs:
- description: The element\'s HTML attributes.
- type: dictionary
- default: (:)
- body:
- description: The contents of the HTML element. The body can be arbitrary Typst content.
- type: none | content
- default: none
@@ -0,0 +1,24 @@
# Frame
# html.frame
An element that lays out its content as an inline SVG.
Sometimes, converting Typst content to HTML is not desirable. This can be the case for plots and other content that relies on positioning and styling to convey its message.
This function allows you to use the Typst layout engine that would also be used for PDF, SVG, and PNG export to render a part of your document exactly how it would appear when exported in one of these formats. It embeds the content as an inline SVG.
```typst
#html.frame(
body
) -> content
```
## Parameters
- body:
- description: The content that shall be laid out.
- type: content
- default: None
@@ -0,0 +1,42 @@
# HTML
> Typst's HTML export is currently under active development. The feature is still very incomplete and only available for experimentation behind a feature flag. Do not use this feature for production use cases. In the CLI, you can experiment with HTML export by passing `--features html` or setting the `TYPST_FEATURES` environment variables to `html`. In the web app, HTML export is not available at this time. Visit the [tracking issue](https://github.com/typst/typst/issues/5512) to follow progress on HTML export and learn more about planned features.
HTML files describe a document structurally. The aim of Typst's HTML export is to capture the structure of an input document and produce semantically rich HTML that retains this structure. The resulting HTML should be accessible, human-readable, and editable by hand and downstream tools.
PDF, PNG, and SVG export, in contrast, all produce _visual_ representations of a fully-laid out document. This divergence in the formats' intents means that Typst cannot simply produce perfect HTML for your existing Typst documents. It cannot always know what the best semantic HTML representation of your content is.
Instead, it gives _you_ full control: You can check the current export format through the [`target`](/docs/reference/foundations/target/) function and when it is set to HTML, generate [raw HTML elements](/docs/reference/html/elem/). The primary intended use of these elements is in templates and show rules. This way, the document's contents can be fully agnostic to the export target and content can be shared between PDF and HTML export.
Currently, Typst will always output a single HTML file. Support for outputting directories with multiple HTML documents and assets, as well as support for outputting fragments that can be integrated into other HTML documents is planned.
Typst currently does not output CSS style sheets, instead focussing on emitting semantic markup. You can of course write your own CSS styles and still benefit from sharing your _content_ between PDF and HTML. For the future, we plan to give you the option of automatically emitting CSS, taking more of your existing set rules into account.
## Exporting as HTML
### Command Line
Pass `--format html` to the `compile` or `watch` subcommand or provide an output file name that ends with `.html`. Note that you must also pass `--features html` or set `TYPST_FEATURES=html` to enable this experimental export target.
When using `typst watch`, Typst will spin up a live-reloading HTTP server. You can configure it as follows:
- Pass `--port` to change the port. (Defaults to the first free port in the range 3000-3005.)
- Pass `--no-reload` to disable injection of a live reload script. (The HTML that is written to disk isn't affected either way.)
- Pass `--no-serve` to disable the server altogether.
### Web App
Not currently available.
## HTML-specific functionality
Typst exposes HTML-specific functionality in the global `html` module. See below for the definitions it contains.
## Definitions
| Name | Description |
| --- | --- |
| [`elem`](/reference/html/elem/) | An HTML element that can contain Typst content. |
| [`frame`](/reference/html/frame/) | An element that lays out its content as an inline SVG. |
| [`typed`](/reference/html/typed/) | A typed layer over raw HTML elements. |
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,13 @@
# Reference
This reference documentation is a comprehensive guide to all of Typst's syntax, concepts, types, and functions. If you are completely new to Typst, we recommend starting with the [tutorial](/docs/tutorial/) and then coming back to the reference to learn more about Typst's features as you need them.
## Language
The reference starts with a language part that gives an overview over [Typst's syntax](/docs/reference/syntax/) and contains information about concepts involved in [styling documents,](/docs/reference/styling/) using [Typst's scripting capabilities.](/docs/reference/scripting/)
## Functions
The second part includes chapters on all functions used to insert, style, transform, and layout content in Typst documents. Each function is documented with a description of its purpose, a list of its parameters, and examples of how to use it.
The final part of the reference explains all functions that are used within Typst's code mode to manipulate and transform data. Just as in the previous part, each function is documented with a description of its purpose, a list of its parameters, and examples of how to use it.
@@ -0,0 +1,261 @@
# Counter
Counts through pages, elements, and more.
With the counter function, you can access and modify counters for pages, headings, figures, and more. Moreover, you can define custom counters for other things you want to count.
Since counters change throughout the course of the document, their current value is _contextual._ It is recommended to read the chapter on [context](/docs/reference/context/) before continuing here.
## Accessing a counter
To access the raw value of a counter, we can use the [`get`](/docs/reference/introspection/counter/#definitions-get) function. This function returns an [array](/docs/reference/foundations/array/): Counters can have multiple levels (in the case of headings for sections, subsections, and so on), and each item in the array corresponds to one level.
```typst
#set heading(numbering: "1.")
= Introduction
Raw value of heading counter is
#context counter(heading).get()
```
## Displaying a counter
Often, we want to display the value of a counter in a more human-readable way. To do that, we can call the [`display`](/docs/reference/introspection/counter/#definitions-display) function on the counter. This function retrieves the current counter value and formats it either with a provided or with an automatically inferred [numbering](/docs/reference/model/numbering/).
```typst
#set heading(numbering: "1.")
= Introduction
Some text here.
= Background
The current value is: #context {
counter(heading).display()
}
Or in roman numerals: #context {
counter(heading).display("I")
}
```
## Modifying a counter
To modify a counter, you can use the `step` and `update` methods:
- The `step` method increases the value of the counter by one. Because counters can have multiple levels , it optionally takes a `level` argument. If given, the counter steps at the given depth.
- The `update` method allows you to arbitrarily modify the counter. In its basic form, you give it an integer (or an array for multiple levels). For more flexibility, you can instead also give it a function that receives the current value and returns a new value.
The heading counter is stepped before the heading is displayed, so `Analysis` gets the number seven even though the counter is at six after the second update.
```typst
#set heading(numbering: "1.")
= Introduction
#counter(heading).step()
= Background
#counter(heading).update(3)
#counter(heading).update(n => n * 2)
= Analysis
Let's skip 7.1.
#counter(heading).step(level: 2)
== Analysis
Still at #context {
counter(heading).display()
}
```
## Page counter
The page counter is special. It is automatically stepped at each pagebreak. But like other counters, you can also step it manually. For example, you could have Roman page numbers for your preface, then switch to Arabic page numbers for your main content and reset the page counter to one.
```typst
#set page(numbering: "(i)")
= Preface
The preface is numbered with
roman numerals.
#set page(numbering: "1 / 1")
#counter(page).update(1)
= Main text
Here, the counter is reset to one.
We also display both the current
page and total number of pages in
Arabic numbers.
```
## Custom counters
To define your own counter, call the `counter` function with a string as a key. This key identifies the counter globally.
```typst
#let mine = counter("mycounter")
#context mine.display() \
#mine.step()
#context mine.display() \
#mine.update(c => c * 3)
#context mine.display()
```
## How to step
When you define and use a custom counter, in general, you should first step the counter and then display it. This way, the stepping behaviour of a counter can depend on the element it is stepped for. If you were writing a counter for, let's say, theorems, your theorem's definition would thus first include the counter step and only then display the counter and the theorem's contents.
```typst
#let c = counter("theorem")
#let theorem(it) = block[
#c.step()
*Theorem #context c.display():*
#it
]
#theorem[$1 = 1$]
#theorem[$2 < 3$]
```
The rationale behind this is best explained on the example of the heading counter: An update to the heading counter depends on the heading's level. By stepping directly before the heading, we can correctly step from `1` to `1.1` when encountering a level 2 heading. If we were to step after the heading, we wouldn't know what to step to.
Because counters should always be stepped before the elements they count, they always start at zero. This way, they are at one for the first display (which happens after the first step).
## Time travel
Counters can travel through time! You can find out the final value of the counter before it is reached and even determine what the value was at any particular location in the document.
```typst
#let mine = counter("mycounter")
= Values
#context [
Value here: #mine.get() \
At intro: #mine.at(<intro>) \
Final value: #mine.final()
]
#mine.update(n => n + 3)
= Introduction <intro>
#lorem(10)
#mine.step()
#mine.step()
```
## Other kinds of state
The `counter` type is closely related to [state](/docs/reference/introspection/state/) type. Read its documentation for more details on state management in Typst and why it doesn't just use normal variables for counters.
## Constructor
## counter
Create a new counter identified by a key.
```typst
#counter(
key
) -> counter
```
### Parameters
- key:
- description: The key that identifies this counter globally. - If it is a string, creates a custom counter that is only affected by manual updates, - If it is the [`page`](/docs/reference/layout/page/) function, counts through pages, - If it is a [selector](/docs/reference/foundations/selector/), counts through elements that match the selector. For example, - provide an element function: counts elements of that type, - provide a [`where`](/docs/reference/foundations/function/#definitions-where) selector: counts a type of element with specific fields, - provide a [`<label>`](/docs/reference/foundations/label/): counts elements with that label.
- type: str | label | selector | location | function
- default: None
## Methods
## counter.get
Retrieves the value of the counter at the current location. Always returns an array of integers, even if the counter has just one number.
This is equivalent to `counter.at(here())`.
## counter.display
Displays the current value of the counter with a numbering and returns the formatted output.
```typst
#counter.display(
numbering,
both: bool
) -> any
```
### Parameters
- numbering:
- description: A [numbering pattern or a function](/docs/reference/model/numbering/), which specifies how to display the counter. If given a function, that function receives each number of the counter as a separate argument. If the amount of numbers varies, e.g. for the heading argument, you can use an [argument sink](/docs/reference/foundations/arguments/). If this is omitted or set to `auto`, displays the counter with the numbering style for the counted element or with the pattern `"1.1"` if no such style exists.
- type: auto | str | function
- default: auto
- both:
- description: If enabled, displays the current and final top-level count together. Both can be styled through a single numbering pattern. This is used by the page numbering property to display the current and total number of pages when a pattern like `"1 / 1"` is given.
- type: bool
- default: false
## counter.at
Retrieves the value of the counter at the given location. Always returns an array of integers, even if the counter has just one number.
The `selector` must match exactly one element in the document. The most useful kinds of selectors for this are [labels](/docs/reference/foundations/label/) and [locations](/docs/reference/introspection/location/).
```typst
#counter.at(
selector
) -> int array
```
### Parameters
- selector:
- description: The place at which the counter\'s value should be retrieved.
- type: label | selector | location | function
- default: None
## counter.final
Retrieves the value of the counter at the end of the document. Always returns an array of integers, even if the counter has just one number.
## counter.step
Increases the value of the counter by one.
The update will be in effect at the position where the returned content is inserted into the document. If you don't put the output into the document, nothing happens! This would be the case, for example, if you write `let _ = counter(page).step()`. Counter updates are always applied in layout order and in that case, Typst wouldn't know when to step the counter.
```typst
#counter.step(
level: int
) -> content
```
### Parameters
- level:
- description: The depth at which to step the counter. Defaults to `1`.
- type: int
- default: 1
## counter.update
Updates the value of the counter.
Just like with `step`, the update only occurs if you put the resulting content into the document.
```typst
#counter.update(
update
) -> content
```
### Parameters
- update:
- description: If given an integer or array of integers, sets the counter to that value. If given a function, that function receives the previous counter value (with each number as a separate argument) and has to return the new value (integer or array).
- type: int | array | function
- default: None
@@ -0,0 +1,41 @@
# Here
# here
Provides the current location in the document.
You can think of `here` as a low-level building block that directly extracts the current location from the active [context](/docs/reference/context/). Some other functions use it internally: For instance, `counter.get()` is equivalent to `counter.at(here())`.
Within show rules on [locatable](/docs/reference/introspection/location/#locatable) elements, `here()` will match the location of the shown element.
If you want to display the current page number, refer to the documentation of the [`counter`](/docs/reference/introspection/counter/) type. While `here` can be used to determine the physical page number, typically you want the logical page number that may, for instance, have been reset after a preface.
## Examples
Determining the current position in the document in combination with the [`position`](/docs/reference/introspection/location/#definitions-position) method:
```typst
#context [
I am located at
#here().position()
]
```
Running a [query](/docs/reference/introspection/query/) for elements before the current position:
```typst
= Introduction
= Background
There are
#context query(
selector(heading).before(here())
).len()
headings before me.
= Conclusion
```
Refer to the [`selector`](/docs/reference/foundations/selector/) type for more details on before/after selectors.
@@ -0,0 +1,20 @@
# Introspection
Interactions between document parts.
This category is home to Typst's introspection capabilities: With the `counter` function, you can access and manipulate page, section, figure, and equation counters or create custom ones. Meanwhile, the `query` function lets you search for elements in the document to construct things like a list of figures or headers which show the current chapter title.
Most of the functions are _contextual._ It is recommended to read the chapter on [context](/docs/reference/context/) before continuing here.
## Definitions
| Name | Description |
| --- | --- |
| [`counter`](/reference/introspection/counter/) | Counts through pages, elements, and more. |
| [`here`](/reference/introspection/here/) | Provides the current location in the document. |
| [`locate`](/reference/introspection/locate/) | Determines the location of an element in the document. |
| [`location`](/reference/introspection/location/) | Identifies an element in the document. |
| [`metadata`](/reference/introspection/metadata/) | Exposes a value to the query system without producing visible content. |
| [`query`](/reference/introspection/query/) | Finds elements in the document. |
| [`state`](/reference/introspection/state/) | Manages stateful parts of your document. |
@@ -0,0 +1,35 @@
# Locate
# locate
Determines the location of an element in the document.
Takes a selector that must match exactly one element and returns that element's [`location`](/docs/reference/introspection/location/). This location can, in particular, be used to retrieve the physical [`page`](/docs/reference/introspection/location/#definitions-page) number and [`position`](/docs/reference/introspection/location/#definitions-position) (page, x, y) for that element.
## Examples
Locating a specific element:
```typst
#context [
Introduction is at: \
#locate(<intro>).position()
]
= Introduction <intro>
```
```typst
#locate(
selector
) -> location
```
## Parameters
- selector:
- description: A selector that should match exactly one element. This element will be located. Especially useful in combination with - [`here`](/docs/reference/introspection/here/) to locate the current context, - a [`location`](/docs/reference/introspection/location/) retrieved from some queried element via the [`location()`](/docs/reference/foundations/content/#definitions-location) method on content.
- type: label | selector | location | function
- default: None
@@ -0,0 +1,52 @@
# Location
Identifies an element in the document.
A location uniquely identifies an element in the document and lets you access its absolute position on the pages. You can retrieve the current location with the [`here`](/docs/reference/introspection/here/) function and the location of a queried or shown element with the [`location()`](/docs/reference/foundations/content/#definitions-location) method on content.
## Locatable elements
Elements that are automatically assigned a location are called _locatable._ For efficiency reasons, not all elements are locatable.
- In the [Model category](/docs/reference/model/), most elements are locatable. This is because semantic elements like [headings](/docs/reference/model/heading/) and [figures](/docs/reference/model/figure/) are often used with introspection.
- In the [Text category](/docs/reference/text/), the [`raw`](/docs/reference/text/raw/) element, and the decoration elements [`underline`](/docs/reference/text/underline/), [`overline`](/docs/reference/text/overline/), [`strike`](/docs/reference/text/strike/), and [`highlight`](/docs/reference/text/highlight/) are locatable as these are also quite semantic in nature.
- In the [Introspection category](/docs/reference/introspection/), the [`metadata`](/docs/reference/introspection/metadata/) element is locatable as being queried for is its primary purpose.
- In the other categories, most elements are not locatable. Exceptions are [`math.equation`](/docs/reference/math/equation/) and [`image`](/docs/reference/visualize/image/).
To find out whether a specific element is locatable, you can try to [`query`](/docs/reference/introspection/query/) for it.
Note that you can still observe elements that are not locatable in queries through other means, for instance, when they have a label attached to them.
## Methods
## location.page
Returns the page number for this location.
Note that this does not return the value of the [page counter](/docs/reference/introspection/counter/) at this location, but the true page number (starting from one).
If you want to know the value of the page counter, use `counter(page).at(loc)` instead.
Can be used with [`here`](/docs/reference/introspection/here/) to retrieve the physical page position of the current context:
```typst
#context [
I am located on
page #here().page()
]
```
## location.position
Returns a dictionary with the page number and the x, y position for this location. The page number starts at one and the coordinates are measured from the top-left of the page.
If you only need the page number, use `page()` instead as it allows Typst to skip unnecessary work.
## location.page-numbering
Returns the page numbering pattern of the page at this location. This can be used when displaying the page counter in order to obtain the local numbering. This is useful if you are building custom indices or outlines.
If the page numbering is set to `none` at that location, this function returns `none`.
@@ -0,0 +1,34 @@
# Metadata
# metadata
Exposes a value to the query system without producing visible content.
This element can be retrieved with the [`query`](/docs/reference/introspection/query/) function and from the command line with [`typst query`](/docs/reference/introspection/query/#command-line-queries). Its purpose is to expose an arbitrary value to the introspection system. To identify a metadata value among others, you can attach a [`label`](/docs/reference/foundations/label/) to it and query for that label.
The `metadata` element is especially useful for command line queries because it allows you to expose arbitrary values to the outside world.
```typst
// Put metadata somewhere.
#metadata("This is a note") <note>
// And find it from anywhere else.
#context {
query(<note>).first().value
}
```
```typst
#metadata(
value
) -> content
```
## Parameters
- value:
- description: The value to embed into the document.
- type: any
- default: None
@@ -0,0 +1,127 @@
# Query
# query
Finds elements in the document.
The `query` function lets you search your document for elements of a particular type or with a particular label. To use it, you first need to ensure that [context](/docs/reference/context/) is available.
## Finding elements
In the example below, we manually create a table of contents instead of using the [`outline`](/docs/reference/model/outline/) function.
To do this, we first query for all headings in the document at level 1 and where `outlined` is true. Querying only for headings at level 1 ensures that, for the purpose of this example, sub-headings are not included in the table of contents. The `outlined` field is used to exclude the "Table of Contents" heading itself.
Note that we open a `context` to be able to use the `query` function.
```typst
#set page(numbering: "1")
#heading(outlined: false)[
Table of Contents
]
#context {
let chapters = query(
heading.where(
level: 1,
outlined: true,
)
)
for chapter in chapters {
let loc = chapter.location()
let nr = numbering(
loc.page-numbering(),
..counter(page).at(loc),
)
[#chapter.body #h(1fr) #nr \ ]
}
}
= Introduction
#lorem(10)
#pagebreak()
== Sub-Heading
#lorem(8)
= Discussion
#lorem(18)
```
To get the page numbers, we first get the location of the elements returned by `query` with [`location`](/docs/reference/foundations/content/#definitions-location). We then also retrieve the [page numbering](/docs/reference/introspection/location/#definitions-page-numbering) and [page counter](/docs/reference/introspection/counter/#page-counter) at that location and apply the numbering to the counter.
## A word of caution
To resolve all your queries, Typst evaluates and layouts parts of the document multiple times. However, there is no guarantee that your queries can actually be completely resolved. If you aren't careful a query can affect itself—leading to a result that never stabilizes.
In the example below, we query for all headings in the document. We then generate as many headings. In the beginning, there's just one heading, titled `Real`. Thus, `count` is `1` and one `Fake` heading is generated. Typst sees that the query's result has changed and processes it again. This time, `count` is `2` and two `Fake` headings are generated. This goes on and on. As we can see, the output has a finite amount of headings. This is because Typst simply gives up after a few attempts.
In general, you should try not to write queries that affect themselves. The same words of caution also apply to other introspection features like [counters](/docs/reference/introspection/counter/) and [state](/docs/reference/introspection/state/).
```typst
= Real
#context {
let elems = query(heading)
let count = elems.len()
count * [= Fake]
}
```
## Command line queries
You can also perform queries from the command line with the `typst query` command. This command executes an arbitrary query on the document and returns the resulting elements in serialized form. Consider the following `example.typ` file which contains some invisible [metadata](/docs/reference/introspection/metadata/):
```typst
#metadata("This is a note") <note>
```
You can execute a query on it as follows using Typst's CLI:
```typst
$ typst query example.typ "<note>"
[
{
"func": "metadata",
"value": "This is a note",
"label": "<note>"
}
]
```
### Retrieving a specific field
Frequently, you're interested in only one specific field of the resulting elements. In the case of the `metadata` element, the `value` field is the interesting one. You can extract just this field with the `--field` argument.
```typst
$ typst query example.typ "<note>" --field value
["This is a note"]
```
If you are interested in just a single element, you can use the `--one` flag to extract just it.
```typst
$ typst query example.typ "<note>" --field value --one
"This is a note"
```
### Querying for a specific export target
In case you need to query a document when exporting for a specific target, you can use the `--target` argument. Valid values are `paged`, and `html` (if the [`html`](/docs/reference/html/) feature is enabled).
```typst
#query(
target
) -> array
```
## Parameters
- target:
- description: Can be - an element function like a `heading` or `figure`, - a `<label>`, - a more complex selector like `heading.where(level: 1)`, - or `selector(heading).before(here())`. Only [locatable](/docs/reference/introspection/location/#locatable) element functions are supported.
- type: label | selector | location | function
- default: None
@@ -0,0 +1,203 @@
# State
Manages stateful parts of your document.
Let's say you have some computations in your document and want to remember the result of your last computation to use it in the next one. You might try something similar to the code below and expect it to output 10, 13, 26, and 21. However this **does not work** in Typst. If you test this code, you will see that Typst complains with the following error message: _Variables from
outside the function are read-only and cannot be modified._
```typst
// This doesn't work!
#let star = 0
#let compute(expr) = {
star = eval(
expr.replace("⭐", str(star))
)
[New value is #star.]
}
#compute("10") \
#compute("⭐ + 3") \
#compute("⭐ * 2") \
#compute("⭐ - 5")
```
## State and document markup
Why does it do that? Because, in general, this kind of computation with side effects is problematic in document markup and Typst is upfront about that. For the results to make sense, the computation must proceed in the same order in which the results will be laid out in the document. In our simple example, that's the case, but in general it might not be.
Let's look at a slightly different, but similar kind of state: The heading numbering. We want to increase the heading counter at each heading. Easy enough, right? Just add one. Well, it's not that simple. Consider the following example:
```typst
#set heading(numbering: "1.")
#let template(body) = [
= Outline
...
#body
]
#show: template
= Introduction
...
```
Here, Typst first processes the body of the document after the show rule, sees the `Introduction` heading, then passes the resulting content to the `template` function and only then sees the `Outline`. Just counting up would number the `Introduction` with `1` and the `Outline` with `2`.
## Managing state in Typst
So what do we do instead? We use Typst's state management system. Calling the `state` function with an identifying string key and an optional initial value gives you a state value which exposes a few functions. The two most important ones are `get` and `update`:
- The [`get`](/docs/reference/introspection/state/#definitions-get) function retrieves the current value of the state. Because the value can vary over the course of the document, it is a _contextual_ function that can only be used when [context](/docs/reference/context/) is available.
- The [`update`](/docs/reference/introspection/state/#definitions-update) function modifies the state. You can give it any value. If given a non-function value, it sets the state to that value. If given a function, that function receives the previous state and has to return the new state.
Our initial example would now look like this:
```typst
#let star = state("star", 0)
#let compute(expr) = {
star.update(old =>
eval(expr.replace("⭐", str(old)))
)
[New value is #context star.get().]
}
#compute("10") \
#compute("⭐ + 3") \
#compute("⭐ * 2") \
#compute("⭐ - 5")
```
State managed by Typst is always updated in layout order, not in evaluation order. The `update` method returns content and its effect occurs at the position where the returned content is inserted into the document.
As a result, we can now also store some of the computations in variables, but they still show the correct results:
```typst
...
#let more = [
#compute("⭐ * 2") \
#compute("⭐ - 5")
]
#compute("10") \
#compute("⭐ + 3") \
#more
```
This example is of course a bit silly, but in practice this is often exactly what you want! A good example are heading counters, which is why Typst's [counting system](/docs/reference/introspection/counter/) is very similar to its state system.
## Time Travel
By using Typst's state management system you also get time travel capabilities! We can find out what the value of the state will be at any position in the document from anywhere else. In particular, the `at` method gives us the value of the state at any particular location and the `final` methods gives us the value of the state at the end of the document.
```typst
...
Value at `<here>` is
#context star.at(<here>)
#compute("10") \
#compute("⭐ + 3") \
*Here.* <here> \
#compute("⭐ * 2") \
#compute("⭐ - 5")
```
## A word of caution
To resolve the values of all states, Typst evaluates parts of your code multiple times. However, there is no guarantee that your state manipulation can actually be completely resolved.
For instance, if you generate state updates depending on the final value of a state, the results might never converge. The example below illustrates this. We initialize our state with `1` and then update it to its own final value plus 1. So it should be `2`, but then its final value is `2`, so it should be `3`, and so on. This example displays a finite value because Typst simply gives up after a few attempts.
```typst
// This is bad!
#let x = state("key", 1)
#context x.update(x.final() + 1)
#context x.get()
```
In general, you should try not to generate state updates from within context expressions. If possible, try to express your updates as non-contextual values or functions that compute the new value from the previous value. Sometimes, it cannot be helped, but in those cases it is up to you to ensure that the result converges.
## Constructor
## state
Create a new state identified by a key.
```typst
#state(
key,
init
) -> state
```
### Parameters
- key:
- description: The key that identifies this state. Any [updates](/docs/reference/introspection/state/#definitions-update) to the state will be identified with the string key. If you construct multiple states with the same `key`, then updating any one will affect all of them.
- type: str
- default: None
- init:
- description: The initial value of the state. If you construct multiple states with the same `key` but different `init` values, they will each use their own initial value but share updates. Specifically, the value of a state at some location in the document will be computed from that state\'s initial value and all preceding updates for the state\'s key. ```typst #let banana = state("key", "🍌") #let broccoli = state("key", "🥦") #banana.update(it => it + "😋") #context [ - #state("key", "🍎").get() - #banana.get() - #broccoli.get() ] ```
- type: any
- default: none
## Methods
## state.get
Retrieves the value of the state at the current location.
This is equivalent to `state.at(here())`.
## state.at
Retrieves the value of the state at the given selector's unique match.
The `selector` must match exactly one element in the document. The most useful kinds of selectors for this are [labels](/docs/reference/foundations/label/) and [locations](/docs/reference/introspection/location/).
```typst
#state.at(
selector
) -> any
```
### Parameters
- selector:
- description: The place at which the state\'s value should be retrieved.
- type: label | selector | location | function
- default: None
## state.final
Retrieves the value of the state at the end of the document.
## state.update
Updates the value of the state.
Returns an invisible piece of [content](/docs/reference/foundations/content/) that must be inserted into the document to take effect. This invisible content tells Typst that the specified update should take place wherever the content is inserted into the document.
State is a part of your document and runs like a thread embedded in the document content. The value of a state is the result of all state updates that happened in the document up until that point.
That's why `state.update` returns an invisible sliver of content that you need to return and include in the document — a state update that is not "placed" in the document does not happen, and "when" it happens is determined by where you place it. That's also why you need [context](/docs/reference/context/) to read state: You need to use the current document position to know where on the state's "thread" you are.
Storing a state update in a variable (e.g. `let my-update = state("key").update(c => c * 2)`) will have no effect by itself. Only once you insert the variable `#my-update` somewhere into the document content, the update will take effect — at the position where it was inserted. You can also use `#my-update` multiple times at different positions. Then, the update will take effect multiple times as well.
In contrast to [`get`](/docs/reference/introspection/state/#definitions-get), [`at`](/docs/reference/introspection/state/#definitions-at), and [`final`](/docs/reference/introspection/state/#definitions-final), this function does not require [context](/docs/reference/context/). This is because, to create the state update, we do not need to know where in the document we are. We only need this information to resolve the state's value.
```typst
#state.update(
update
) -> content
```
### Parameters
- update:
- description: A value to update to or a function to update with. - If given a non-function value, sets the state to that value. - If given a function, that function receives the state\'s previous value and has to return the state\'s new value. When updating the state based on its previous value, you should prefer the function form instead of retrieving the previous value from the [context](/docs/reference/context/). This allows the compiler to resolve the final state efficiently, minimizing the number of [layout iterations](/docs/reference/context/#compiler-iterations) required. In the following example, `fill.update(f => not f)` will paint odd [items in the bullet list](/docs/reference/model/list/#definitions-item) as expected. However, if it\'s replaced with `context fill.update(not fill.get())`, then layout will not converge within 5 attempts, as each update will take one additional iteration to propagate. ```typst #let fill = state("fill", false) #show list.item: it => { fill.update(f => not f) context { set text(fill: fuchsia) if fill.get() it } } #lorem(5).split().map(list.item).join() ```
- type: any | function
- default: None
@@ -0,0 +1,88 @@
# Align
# align
Aligns content horizontally and vertically.
## Example
Let's start with centering our content horizontally:
```typst
#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:
```typst
#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:
```typst
#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:
```typst
#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](/docs/reference/layout/h/) instead:
```typst
Start #h(1fr) End
```
```typst
#align(
alignment,
body
) -> content
```
## Parameters
- alignment:
- description: The [alignment](/docs/reference/layout/alignment/) along both axes. ```typst #set page(height: 6cm) #set text(lang: "ar") مثال #align( end + horizon, rect(inset: 12pt)[ركن] ) ```
- type: alignment
- default: start + top
- body:
- description: The content to align.
- type: content
- default: None
@@ -0,0 +1,69 @@
# Alignment
Where to align something along an axis.
Possible values are:
- `start`: Aligns at the [start](/docs/reference/layout/direction/#definitions-start) of the [text direction](/docs/reference/text/text/#parameters-dir).
- `end`: Aligns at the [end](/docs/reference/layout/direction/#definitions-end) of the [text direction](/docs/reference/text/text/#parameters-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:
```typst
#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.
```typst
#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`.
```typst
#(top + right).x \
#left.x \
#left.y (none)
```
## Methods
## alignment.axis
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
```typst
#left.axis() \
#bottom.axis()
```
## alignment.inv
The inverse alignment.
```typst
#top.inv() \
#left.inv() \
#center.inv() \
#(left + bottom).inv()
```
@@ -0,0 +1,27 @@
# Angle
An angle describing a rotation.
Typst supports the following angular units:
- Degrees: `180deg`
- Radians: `3.14rad`
## Example
```typst
#rotate(10deg)[Hello there!]
```
## Methods
## angle.rad
Converts this angle to radians.
## angle.deg
Converts this angle to degrees.
@@ -0,0 +1,115 @@
# Block
# block
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](/docs/reference/model/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.
```typst
#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.
```typst
#show heading: it => it.body
= Blockless
More text.
#show heading: it => block(it.body)
= Blocky
More text.
```
```typst
#block(
width: auto | relative,
height: auto | relative | fraction,
breakable: bool,
fill: none | color | gradient | tiling,
stroke: none | length | color | gradient | stroke | tiling | dictionary,
radius: relative | dictionary,
inset: relative | dictionary,
outset: relative | dictionary,
spacing: relative | fraction,
above: auto | relative | fraction,
below: auto | relative | fraction,
clip: bool,
sticky: bool,
body
) -> content
```
## Parameters
- width:
- description: The block\'s width. ```typst #set align(center) #block( width: 60%, inset: 8pt, fill: silver, lorem(10), ) ```
- type: auto | relative
- default: auto
- height:
- description: The block\'s height. When the height is larger than the remaining space on a page and [`breakable`](/docs/reference/layout/block/#parameters-breakable) is `true`, the block will continue on the next page with the remaining height. ```typst #set page(height: 80pt) #set align(center) #block( width: 80%, height: 150%, fill: aqua, ) ```
- type: auto | relative | fraction
- default: auto
- breakable:
- description: Whether the block can be broken and continue on the next page. ```typst #set page(height: 80pt) The following block will jump to its own page. #block( breakable: false, lorem(15), ) ```
- type: bool
- default: true
- fill:
- description: The block\'s background color. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-fill) for more details.
- type: none | color | gradient | tiling
- default: none
- stroke:
- description: The block\'s border color. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-stroke) for more details.
- type: none | length | color | gradient | stroke | tiling | dictionary
- default: (:)
- radius:
- description: How much to round the block\'s corners. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-radius) for more details.
- type: relative | dictionary
- default: (:)
- inset:
- description: How much to pad the block\'s content. See the [box\'s documentation](/docs/reference/layout/box/#parameters-inset) for more details.
- type: relative | dictionary
- default: (:)
- outset:
- description: How much to expand the block\'s size without affecting the layout. See the [box\'s documentation](/docs/reference/layout/box/#parameters-outset) for more details.
- type: relative | dictionary
- default: (:)
- spacing:
- description: The spacing around the block. When `auto`, inherits the paragraph [`spacing`](/docs/reference/model/par/#parameters-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`](/docs/reference/model/par/#parameters-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](/docs/reference/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. ```typst #set align(center) #show math.equation: set block(above: 8pt, below: 16pt) This sum of $x$ and $y$: $ x + y = z $ A second paragraph. ```
- type: relative | fraction
- default: 1.2em
- above:
- description: The spacing between this block and its predecessor.
- type: auto | relative | fraction
- default: auto
- below:
- description: The spacing between this block and its successor.
- type: auto | relative | fraction
- default: auto
- clip:
- description: 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. ```typst #block( width: 50pt, height: 50pt, clip: true, image("tiger.jpg", width: 100pt, height: 100pt) ) ```
- type: bool
- default: false
- sticky:
- description: 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. ```typst // Disable stickiness of headings. #show heading: set block(sticky: false) #lorem(20) = Chapter #lorem(10) ```
- type: bool
- default: false
- body:
- description: The contents of the block.
- type: none | content
- default: none
@@ -0,0 +1,78 @@
# Box
# box
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](/docs/reference/model/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
```typst
Refer to the docs
#box(
height: 9pt,
image("docs.svg")
)
for more information.
```
```typst
#box(
width: auto | relative | fraction,
height: auto | relative,
baseline: relative,
fill: none | color | gradient | tiling,
stroke: none | length | color | gradient | stroke | tiling | dictionary,
radius: relative | dictionary,
inset: relative | dictionary,
outset: relative | dictionary,
clip: bool,
body
) -> content
```
## Parameters
- width:
- description: The width of the box. Boxes can have [fractional](/docs/reference/layout/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. ```typst Line in #box(width: 1fr, line(length: 100%)) between. ```
- type: auto | relative | fraction
- default: auto
- height:
- description: The height of the box.
- type: auto | relative
- default: auto
- baseline:
- description: An amount to shift the box\'s baseline by. ```typst Image: #box(baseline: 40%, image("tiger.jpg", width: 2cm)). ```
- type: relative
- default: 0 % + 0pt
- fill:
- description: The box\'s background color. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-fill) for more details.
- type: none | color | gradient | tiling
- default: none
- stroke:
- description: The box\'s border color. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-stroke) for more details.
- type: none | length | color | gradient | stroke | tiling | dictionary
- default: (:)
- radius:
- description: How much to round the box\'s corners. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-radius) for more details.
- type: relative | dictionary
- default: (:)
- inset:
- description: 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](/docs/reference/layout/relative/) for this parameter are relative to the box size excluding [outset](/docs/reference/layout/box/#parameters-outset). Note that relative insets and outsets are different from relative [widths](/docs/reference/layout/box/#parameters-width) and [heights](/docs/reference/layout/box/#parameters-height), which are relative to the container. _Note:_ When the box contains text, its exact size depends on the current [text edges](/docs/reference/text/text/#parameters-top-edge). ```typst #rect(inset: 0pt)[Tight] ```
- type: relative | dictionary
- default: (:)
- outset:
- description: 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](/docs/reference/layout/relative/) for this parameter are relative to the box size excluding outset. See the documentation for [inset](/docs/reference/layout/box/#parameters-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](/docs/reference/text/raw/#parameters-block). ```typst An inline #box( fill: luma(235), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, )[rectangle]. ```
- type: relative | dictionary
- default: (:)
- clip:
- description: 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. ```typst #box( width: 50pt, height: 50pt, clip: true, image("tiger.jpg", width: 100pt, height: 100pt) ) ```
- type: bool
- default: false
- body:
- description: The contents of the box.
- type: none | content
- default: none
@@ -0,0 +1,41 @@
# Column Break
# colbreak
Forces a column break.
The function will behave like a [page break](/docs/reference/layout/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
```typst
#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.
```
```typst
#colbreak(
weak: bool
) -> content
```
## Parameters
- weak:
- description: If `true`, the column break is skipped if the current column is already empty.
- type: bool
- default: false
@@ -0,0 +1,71 @@
# Columns
# columns
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`](/docs/reference/layout/colbreak/) to explicitly continue in the next column.
## Example
```typst
#columns(2, gutter: 8pt)[
This text is in the
first column.
#colbreak()
This text is in the
second column.
]
```
## Page-level columns
If you need to insert columns across your whole document, use the `page` function's [`columns` parameter](/docs/reference/layout/page/#parameters-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](/docs/reference/layout/pagebreak/), [footnotes](/docs/reference/model/footnote/), and [line numbers](/docs/reference/model/par/#definitions-line) will continue to work as expected. For more information, also read the [relevant part of the page setup guide](/docs/guides/page-setup/#columns).
## Breaking out of columns
To temporarily break out of columns (e.g. for a paper's title), use parent-scoped floating placement:
```typst
#set page(columns: 2, height: 150pt)
#place(
top + center,
scope: "parent",
float: true,
text(1.4em, weight: "bold")[
My document
],
)
#lorem(40)
```
```typst
#columns(
count,
gutter: relative,
body
) -> content
```
## Parameters
- count:
- description: The number of columns.
- type: int
- default: 2
- gutter:
- description: The size of the gutter space between each column.
- type: relative
- default: 4 % + 0pt
- body:
- description: The content that should be layouted into the columns.
- type: content
- default: None
@@ -0,0 +1,123 @@
# Direction
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:
```typst
#stack(dir: rtl)[A][B][C]
#stack(dir: direction.rtl)[A][B][C]
```
## Methods
## direction.from
Returns a direction from a starting point.
```typst
#direction.from(left) \
#direction.from(right) \
#direction.from(top) \
#direction.from(bottom)
```
```typst
#direction.from(
side
) -> direction
```
### Parameters
- side:
- description:
- type: alignment
- default: None
## direction.to
Returns a direction from an end point.
```typst
#direction.to(left) \
#direction.to(right) \
#direction.to(top) \
#direction.to(bottom)
```
```typst
#direction.to(
side
) -> direction
```
### Parameters
- side:
- description:
- type: alignment
- default: None
## direction.axis
The axis this direction belongs to, either `"horizontal"` or `"vertical"`.
```typst
#ltr.axis() \
#ttb.axis()
```
## direction.sign
The corresponding sign, for use in calculations.
```typst
#ltr.sign() \
#rtl.sign() \
#ttb.sign() \
#btt.sign()
```
## direction.start
The start point of this direction, as an alignment.
```typst
#ltr.start() \
#rtl.start() \
#ttb.start() \
#btt.start()
```
## direction.end
The end point of this direction, as an alignment.
```typst
#ltr.end() \
#rtl.end() \
#ttb.end() \
#btt.end()
```
## direction.inv
The inverse direction.
```typst
#ltr.inv() \
#rtl.inv() \
#ttb.inv() \
#btt.inv()
```
@@ -0,0 +1,15 @@
# Fraction
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](/docs/reference/layout/h/) and [v](/docs/reference/layout/v/) functions and the [grid function](/docs/reference/layout/grid/).
## Example
```typst
Left #h(1fr) Left-ish #h(2fr) Right
```
@@ -0,0 +1,399 @@
# Grid
# grid
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`](/docs/reference/model/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](/docs/reference/layout/grid/#accessibility) to learn how grids and tables are presented to users of Assistive Technology (AT) like screen readers.
## Sizing the tracks
A grid's sizing is determined by the track sizes specified in the arguments. There are multiple sizing parameters: [`columns`](/docs/reference/layout/grid/#parameters-columns), [`rows`](/docs/reference/layout/grid/#parameters-rows) and [`gutter`](/docs/reference/layout/grid/#parameters-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`](/docs/reference/layout/grid/#definitions-cell) to make an individual cell span two grid tracks.
```typst
// 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](/docs/reference/foundations/arguments/#spreading) an array of strings or content into a grid to populate its cells.
```typst
#grid(
columns: 5,
gutter: 5pt,
..range(25).map(str)
)
```
## Styling the grid
The grid and table elements work similarly. For a hands-on explanation, refer to the [Table Guide](/docs/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`](/docs/reference/layout/grid/#parameters-align) to change how cells are aligned
- [`inset`](/docs/reference/layout/grid/#parameters-inset) to optionally add internal padding to cells
- [`fill`](/docs/reference/layout/grid/#parameters-fill) to give cells a background
- [`stroke`](/docs/reference/layout/grid/#parameters-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`](/docs/reference/layout/grid/#definitions-cell) element. Likewise, you can override individual grid lines with the [`grid.hline`](/docs/reference/layout/grid/#definitions-hline) and [`grid.vline`](/docs/reference/layout/grid/#definitions-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.
```typst
#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](/docs/reference/styling/) to [`grid`](/docs/reference/layout/grid/) and [`grid.cell`](/docs/reference/layout/grid/#definitions-cell). Especially, the [`x`](/docs/reference/layout/grid/#definitions-cell-x) and [`y`](/docs/reference/layout/grid/#definitions-cell-y) fields of `grid.cell` can be used in a [`where`](/docs/reference/foundations/function/#definitions-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](/docs/reference/layout/grid/#definitions-cell-stroke), by using [`grid.hline`](/docs/reference/layout/grid/#definitions-hline) and [`grid.vline`](/docs/reference/layout/grid/#definitions-vline), or by setting the [`grid`'s `stroke` field](/docs/reference/layout/grid/#parameters-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`](/docs/reference/model/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](/docs/reference/layout/grid/#definitions-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.
```typst
#grid(
columns: auto | int | relative | fraction | array,
rows: auto | int | relative | fraction | array,
gutter: auto | int | relative | fraction | array,
column-gutter: auto | int | relative | fraction | array,
row-gutter: auto | int | relative | fraction | array,
inset: relative | array | dictionary | function,
align: auto | array | alignment | function,
fill: none | color | gradient | array | tiling | function,
stroke: none | length | color | gradient | array | stroke | tiling | dictionary | function,
children
) -> content
```
## Parameters
- columns:
- description: 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.
- type: auto | int | relative | fraction | array
- default: ()
- rows:
- description: 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.
- type: auto | int | relative | fraction | array
- default: ()
- gutter:
- description: The gaps between rows and columns. This is a shorthand to set [`column-gutter`](/docs/reference/layout/grid/#parameters-column-gutter) and [`row-gutter`](/docs/reference/layout/grid/#parameters-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.
- type: auto | int | relative | fraction | array
- default: ()
- column-gutter:
- description: The gaps between columns.
- type: auto | int | relative | fraction | array
- default: ()
- row-gutter:
- description: The gaps between rows.
- type: auto | int | relative | fraction | array
- default: ()
- inset:
- description: 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](/docs/reference/layout/box/#parameters-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`](/docs/reference/model/table/#parameters-inset) parameter.
- type: relative | array | dictionary | function
- default: (:)
- align:
- description: 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`](/docs/reference/model/table/#parameters-align) parameter.
- type: auto | array | alignment | function
- default: auto
- fill:
- description: 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. ```typst #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], ) ```
- type: none | color | gradient | array | tiling | function
- default: none
- stroke:
- description: How to [stroke](/docs/reference/visualize/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`](/docs/reference/layout/grid/#parameters-gutter) option, or to override the stroke between multiple specific cells, consider specifying one or more of [`grid.hline`](/docs/reference/layout/grid/#definitions-hline) and [`grid.vline`](/docs/reference/layout/grid/#definitions-vline) alongside your grid cells. To specify the same stroke for all cells, you can use a single [stroke](/docs/reference/visualize/stroke/) for all sides, or a dictionary of [strokes](/docs/reference/visualize/stroke/) for individual sides. See the [rectangle\'s documentation](/docs/reference/visualize/rect/#parameters-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. ```typst #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)] ], ) ``` ```typst #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], ), ) ```
- type: none | length | color | gradient | array | stroke | tiling | dictionary | function
- default: (:)
- children:
- description: The contents of the grid cells, plus any extra grid lines specified with the [`grid.hline`](/docs/reference/layout/grid/#definitions-hline) and [`grid.vline`](/docs/reference/layout/grid/#definitions-vline) elements. The cells are populated in row-major order.
- type: content
- default: None
## Definitions
### grid.cell
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:
```typst
#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`](/docs/reference/model/table/#definitions-cell) element to learn more about this.
```typst
#grid.cell(
body,
x: auto | int,
y: auto | int,
colspan: int,
rowspan: int,
inset: auto | relative | dictionary,
align: auto | alignment,
fill: none | auto | color | gradient | tiling,
stroke: none | length | color | gradient | stroke | tiling | dictionary,
breakable: auto | bool
) -> content
```
#### Parameters
- body:
- description: The cell\'s body.
- type: content
- default: None
- x:
- description: 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). ```typst #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), ) ```
- type: auto | int
- default: auto
- y:
- description: 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. ```typst #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)) ) ```
- type: auto | int
- default: auto
- colspan:
- description: The amount of columns spanned by this cell.
- type: int
- default: 1
- rowspan:
- description: The amount of rows spanned by this cell.
- type: int
- default: 1
- inset:
- description: The cell\'s [inset](/docs/reference/layout/grid/#parameters-inset) override.
- type: auto | relative | dictionary
- default: auto
- align:
- description: The cell\'s [alignment](/docs/reference/layout/grid/#parameters-align) override.
- type: auto | alignment
- default: auto
- fill:
- description: The cell\'s [fill](/docs/reference/layout/grid/#parameters-fill) override.
- type: none | auto | color | gradient | tiling
- default: auto
- stroke:
- description: The cell\'s [stroke](/docs/reference/layout/grid/#parameters-stroke) override.
- type: none | length | color | gradient | stroke | tiling | dictionary
- default: (:)
- breakable:
- description: 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.
- type: auto | bool
- default: auto
### grid.hline
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`](/docs/reference/model/table/#definitions-hline) element.
```typst
#grid.hline(
y: auto | int,
start: int,
end: none | int,
stroke: none | length | color | gradient | stroke | tiling | dictionary,
position: alignment
) -> content
```
#### Parameters
- y:
- description: 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`](/docs/reference/layout/grid/#definitions-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.
- type: auto | int
- default: auto
- start:
- description: The column at which the horizontal line starts (zero-indexed, inclusive).
- type: int
- default: 0
- end:
- description: 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.
- type: none | int
- default: none
- stroke:
- description: The line\'s stroke. Specifying `none` removes any lines previously placed across this line\'s range, including hlines or per-cell stroke below it.
- type: none | length | color | gradient | stroke | tiling | dictionary
- default: 1pt + black
- position:
- description: 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.
- type: alignment
- default: top
### grid.vline
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.
```typst
#grid.vline(
x: auto | int,
start: int,
end: none | int,
stroke: none | length | color | gradient | stroke | tiling | dictionary,
position: alignment
) -> content
```
#### Parameters
- x:
- description: 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`](/docs/reference/layout/grid/#definitions-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).
- type: auto | int
- default: auto
- start:
- description: The row at which the vertical line starts (zero-indexed, inclusive).
- type: int
- default: 0
- end:
- description: 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.
- type: none | int
- default: none
- stroke:
- description: The line\'s stroke. Specifying `none` removes any lines previously placed across this line\'s range, including vlines or per-cell stroke below it.
- type: none | length | color | gradient | stroke | tiling | dictionary
- default: 1pt + black
- position:
- description: 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.
- type: alignment
- default: start
### grid.header
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`](/docs/reference/model/table/#definitions-header) element and the [`grid.stroke`](/docs/reference/layout/grid/#parameters-stroke) parameter.
```typst
#grid.header(
repeat: bool,
level: int,
children
) -> content
```
#### Parameters
- repeat:
- description: Whether this header should be repeated across pages.
- type: bool
- default: true
- level:
- description: 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).
- type: int
- default: 1
- children:
- description: The cells and lines within the header.
- type: content
- default: None
### grid.footer
A repeatable grid footer.
Just like the [`grid.header`](/docs/reference/layout/grid/#definitions-header) element, the footer can repeat itself on every page of the grid.
No other grid cells may be placed after the footer.
```typst
#grid.footer(
repeat: bool,
children
) -> content
```
#### Parameters
- repeat:
- description: Whether this footer should be repeated across pages.
- type: bool
- default: true
- children:
- description: The cells and lines within the footer.
- type: content
- default: None
@@ -0,0 +1,48 @@
# Spacing (H)
# h
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
```typst
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`](/docs/reference/layout/align/) would). Each fractionally sized element gets space based on the ratio of its fraction to the sum of all fractions.
```typst
First #h(1fr) Second \
First #h(1fr) Second #h(1fr) Third \
First #h(2fr) Second #h(1fr) Third
```
## Mathematical Spacing
In [mathematical formulas](/docs/reference/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).
```typst
#h(
amount,
weak: bool
) -> content
```
## Parameters
- amount:
- description: How much spacing to insert.
- type: relative | fraction
- default: None
- weak:
- description: 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. ```typst #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. ```
- type: bool
- default: false
@@ -0,0 +1,35 @@
# Hide
# hide
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
```typst
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.
```typst
#hide(
body
) -> content
```
## Parameters
- body:
- description: The content to hide.
- type: content
- default: None
@@ -0,0 +1,39 @@
# Layout
Arranging elements on the page in different ways.
By combining layout functions, you can create complex and automatic layouts.
## Definitions
| Name | Description |
| --- | --- |
| [`align`](/reference/layout/align/) | Aligns content horizontally and vertically. |
| [`alignment`](/reference/layout/alignment/) | Where to align something along an axis. |
| [`angle`](/reference/layout/angle/) | An angle describing a rotation. |
| [`block`](/reference/layout/block/) | A block-level container. |
| [`box`](/reference/layout/box/) | An inline-level container that sizes content. |
| [`colbreak`](/reference/layout/colbreak/) | Forces a column break. |
| [`columns`](/reference/layout/columns/) | Separates a region into multiple equally sized columns. |
| [`direction`](/reference/layout/direction/) | The four directions into which content can be laid out. |
| [`fraction`](/reference/layout/fraction/) | Defines how the remaining space in a layout is distributed. |
| [`grid`](/reference/layout/grid/) | Arranges content in a grid. |
| [`h`](/reference/layout/h/) | Inserts horizontal spacing into a paragraph. |
| [`hide`](/reference/layout/hide/) | Hides content without affecting layout. |
| [`layout`](/reference/layout/layout/) | Provides access to the current outer container's (or page's, if none) dimensions (width and height). |
| [`length`](/reference/layout/length/) | A size or distance, possibly expressed with contextual units. |
| [`measure`](/reference/layout/measure/) | Measures the layouted size of content. |
| [`move`](/reference/layout/move/) | Moves content without affecting layout. |
| [`pad`](/reference/layout/pad/) | Adds spacing around content. |
| [`page`](/reference/layout/page/) | Layouts its child onto one or multiple pages. |
| [`pagebreak`](/reference/layout/pagebreak/) | A manual page break. |
| [`place`](/reference/layout/place/) | Places content relatively to its parent container. |
| [`ratio`](/reference/layout/ratio/) | A ratio of a whole. |
| [`relative`](/reference/layout/relative/) | A length in relation to some known length. |
| [`repeat`](/reference/layout/repeat/) | Repeats content to the available space. |
| [`rotate`](/reference/layout/rotate/) | Rotates content without affecting layout. |
| [`scale`](/reference/layout/scale/) | Scales content without affecting layout. |
| [`skew`](/reference/layout/skew/) | Skews content. |
| [`stack`](/reference/layout/stack/) | Arranges content and spacing horizontally or vertically. |
| [`v`](/reference/layout/v/) | Inserts vertical spacing into a flow of blocks. |
@@ -0,0 +1,62 @@
# Layout
# layout
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`](/docs/reference/layout/length/). The function is provided [context](/docs/reference/context/), meaning you don't need to use it in combination with the `context` keyword. This is why [`measure`](/docs/reference/layout/measure/) can be called in the example below.
```typst
#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](/docs/reference/layout/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](/docs/reference/layout/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](/docs/reference/layout/fraction/) documentation for more details).
```typst
#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`](/docs/reference/layout/ratio/) to a fixed length. This might come in handy if you're building your own layout abstractions.
```typst
#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`.
```typst
#layout(
func
) -> content
```
## Parameters
- func:
- description: 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](/docs/reference/foundations/dictionary/) with the keys `width` and `height`, both of type [`length`](/docs/reference/layout/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.
- type: function
- default: None
@@ -0,0 +1,80 @@
# Length
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
```typst
#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](/docs/reference/foundations/float/).
## Methods
## length.pt
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).
## length.mm
Converts this length to millimeters.
Fails with an error if this length has non-zero `em` units. See the [`pt`](/docs/reference/layout/length/#definitions-pt) method for more details.
## length.cm
Converts this length to centimeters.
Fails with an error if this length has non-zero `em` units. See the [`pt`](/docs/reference/layout/length/#definitions-pt) method for more details.
## length.inches
Converts this length to inches.
Fails with an error if this length has non-zero `em` units. See the [`pt`](/docs/reference/layout/length/#definitions-pt) method for more details.
## length.to-absolute
Resolve this length to an absolute length.
```typst
#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()
]
```
@@ -0,0 +1,57 @@
# Measure
# measure
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`](/docs/reference/layout/layout/).
## Example
The same content can have a different size depending on the [context](/docs/reference/context/) that it is placed into. In the example below, the `#content` is of course bigger when we increase the font size.
```typst
#let content = [Hello!]
#content
#set text(14pt)
#content
```
For this reason, you can only measure when context is available.
```typst
#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`](/docs/reference/layout/length/).
```typst
#measure(
width: auto | length,
height: auto | length,
content
) -> dictionary
```
## Parameters
- width:
- description: 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`](/docs/reference/layout/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. ```typst #context measure(lorem(100), width: 400pt) #context measure(block(lorem(100), width: 400pt)) ```
- type: auto | length
- default: auto
- height:
- description: The height available to layout the content. Setting this to `auto` indicates infinite available height.
- type: auto | length
- default: auto
- content:
- description: The content whose size to measure.
- type: content
- default: None
@@ -0,0 +1,50 @@
# Move
# move
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
```typst
#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`](/docs/reference/pdf/artifact/).
```typst
#move(
dx: relative,
dy: relative,
body
) -> content
```
## Parameters
- dx:
- description: The horizontal displacement of the content.
- type: relative
- default: 0 % + 0pt
- dy:
- description: The vertical displacement of the content.
- type: relative
- default: 0 % + 0pt
- body:
- description: The content to move.
- type: content
- default: None
@@ -0,0 +1,67 @@
# Padding
# pad
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
```typst
#set align(center)
#pad(x: 16pt, image("typing.jpg"))
_Typing speeds can be
measured in words per minute._
```
```typst
#pad(
left: relative,
top: relative,
right: relative,
bottom: relative,
x: relative,
y: relative,
rest: relative,
body
) -> content
```
## Parameters
- left:
- description: The padding at the left side.
- type: relative
- default: 0 % + 0pt
- top:
- description: The padding at the top side.
- type: relative
- default: 0 % + 0pt
- right:
- description: The padding at the right side.
- type: relative
- default: 0 % + 0pt
- bottom:
- description: The padding at the bottom side.
- type: relative
- default: 0 % + 0pt
- x:
- description: A shorthand to set `left` and `right` to the same value.
- type: relative
- default: 0 % + 0pt
- y:
- description: A shorthand to set `top` and `bottom` to the same value.
- type: relative
- default: 0 % + 0pt
- rest:
- description: A shorthand to set all four sides to the same value.
- type: relative
- default: 0 % + 0pt
- body:
- description: The content to pad at the sides.
- type: content
- default: None
@@ -0,0 +1,123 @@
# Page
# page
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](/docs/guides/page-setup/) explains how to use this and related functions to set up a document with many examples.
## Example
```typst
#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.
```typst
#page(
paper: str,
width: auto | length,
height: auto | length,
flipped: bool,
margin: auto | relative | dictionary,
binding: auto | alignment,
columns: int,
fill: none | auto | color | gradient | tiling,
numbering: none | str | function,
supplement: none | auto | content,
number-align: alignment,
header: none | auto | content,
header-ascent: relative,
footer: none | auto | content,
footer-descent: relative,
background: none | content,
foreground: none | content,
body: content
) -> content
```
## Parameters
- paper:
- description: 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.
- type: str
- default: "a4"
- width:
- description: The width of the page. ```typst #set page( width: 3cm, margin: (x: 0cm), ) #for i in range(3) { box(square(width: 1cm)) } ```
- type: auto | length
- default: 595.28pt
- height:
- description: The height of the page. If this is set to `auto`, page breaks can only be triggered manually by inserting a [page break](/docs/reference/layout/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.
- type: auto | length
- default: 841.89pt
- flipped:
- description: Whether the page is flipped into landscape orientation. ```typst #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 ```
- type: bool
- default: false
- margin:
- description: 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](/docs/reference/layout/page/#parameters-binding) is). - `outside`: The margin at the outer side of the page (opposite to the [binding](/docs/reference/layout/page/#parameters-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`. ```typst #set page( width: 3cm, height: 4cm, margin: (x: 8pt, y: 4pt), ) #rect( width: 100%, height: 100%, fill: aqua, ) ```
- type: auto | relative | dictionary
- default: auto
- binding:
- description: On which side the pages will be bound. - `auto`: Equivalent to `left` if the [text direction](/docs/reference/text/text/#parameters-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.
- type: auto | alignment
- default: auto
- columns:
- description: 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](/docs/reference/layout/columns/). ```typst #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. ```
- type: int
- default: 1
- fill:
- description: 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. ```typst #set page(fill: rgb("444352")) #set text(fill: rgb("fdfdfd")) *Dark mode enabled.* ```
- type: none | auto | color | gradient | tiling
- default: auto
- numbering:
- description: How to number the pages. You can refer to the Page Setup Guide for [customizing page numbers](/docs/guides/page-setup/#page-numbers). Accepts a [numbering pattern or function](/docs/reference/model/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](/docs/reference/introspection/counter/#definitions-get) and the [final](/docs/reference/introspection/counter/#definitions-final) value of `counter(page)`. See the [`counter`](/docs/reference/introspection/counter/#page-counter) documentation for more details. If an explicit [`footer`](/docs/reference/layout/page/#parameters-footer) (or [`header`](/docs/reference/layout/page/#parameters-header) for [top-aligned](/docs/reference/layout/page/#parameters-number-align) numbering) is given, the numbering is ignored. ```typst #set page( height: 100pt, margin: (top: 16pt, bottom: 24pt), numbering: "1 / 1", ) #lorem(48) ```
- type: none | str | function
- default: none
- supplement:
- description: A supplement for the pages. For page references, this is added before the page number. ```typst #set page(numbering: "1.", supplement: [p.]) = Introduction <intro> We are on #ref(<intro>, form: "page")! ```
- type: none | auto | content
- default: auto
- number-align:
- description: 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. ```typst #set page( margin: (top: 16pt, bottom: 24pt), numbering: "1", number-align: right, ) #lorem(30) ```
- type: alignment
- default: center + bottom
- header:
- description: 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`](/docs/reference/layout/page/#parameters-numbering) is set and [`number-align`](/docs/reference/layout/page/#parameters-number-align) is `top`. - `none`: Suppresses the header. ```typst #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) ```
- type: none | auto | content
- default: auto
- header-ascent:
- description: The amount the header is raised into the top margin.
- type: relative
- default: 30 % + 0pt
- footer:
- description: 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`](/docs/reference/layout/page/#parameters-numbering) is set and [`number-align`](/docs/reference/layout/page/#parameters-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](/docs/reference/introspection/counter/). ```typst #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) ```
- type: none | auto | content
- default: auto
- footer-descent:
- description: The amount the footer is lowered into the bottom margin.
- type: relative
- default: 30 % + 0pt
- background:
- description: 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. ```typst #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). ```
- type: none | content
- default: none
- foreground:
- description: Content in the page\'s foreground. This content will overlay the page\'s body. ```typst #set page(foreground: text(24pt)[🤓]) Reviewer 2 has marked our paper "Weak Reject" because they did not understand our approach... ```
- type: none | content
- default: none
- body:
- description: 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.
- type: content
- default: []
@@ -0,0 +1,42 @@
# Page Break
# pagebreak
A manual page break.
Must not be used inside any containers.
## Example
```typst
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](/docs/reference/layout/page/#parameters-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`](/docs/reference/text/text/#parameters-costs) parameter to disable this behavior.
```typst
#pagebreak(
weak: bool,
to: none | str
) -> content
```
## Parameters
- weak:
- description: If `true`, the page break is skipped if the current page is already empty.
- type: bool
- default: false
- to:
- description: If given, ensures that the next page will be an even/odd page, with an empty page in between if necessary. ```typst #set page(height: 30pt) First. #pagebreak(to: "odd") Third. ```
- type: none | str
- default: none
@@ -0,0 +1,118 @@
# Place
# place
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`](/docs/reference/layout/place/#parameters-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`](/docs/reference/layout/place/#parameters-dx) and [`dy`](/docs/reference/layout/place/#parameters-dy) offsets without affecting the layout.
The parent can be any container such as a [`block`](/docs/reference/layout/block/), [`box`](/docs/reference/layout/box/), [`rect`](/docs/reference/visualize/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`](/docs/reference/layout/place/#parameters-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`](/docs/reference/layout/page/#parameters-foreground) or [`page.background`](/docs/reference/layout/page/#parameters-background).
## Examples
```typst
#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
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`](/docs/reference/layout/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:
```typst
#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.
```typst
#place(
alignment,
scope: str,
float: bool,
clearance: length,
dx: relative,
dy: relative,
body
) -> content
```
## Parameters
- alignment:
- description: 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.
- type: auto | alignment
- default: start
- scope:
- description: 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](/docs/reference/model/figure/#parameters-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](/docs/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. ```typst #set page(height: 150pt, columns: 2) #place( top + center, scope: "parent", float: true, rect(width: 80%, fill: aqua), ) #lorem(25) ```
- type: str
- default: "column"
- float:
- description: 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`](/docs/reference/layout/place/#definitions-flush) element. ```typst #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) ```
- type: bool
- default: false
- clearance:
- description: The spacing between the placed element and other elements in a floating layout. Has no effect if `float` is `false`.
- type: length
- default: 1.5em
- dx:
- description: The horizontal displacement of the placed content. ```typst #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`](/docs/reference/layout/move/) element.
- type: relative
- default: 0 % + 0pt
- dy:
- description: 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`](/docs/reference/layout/move/) element.
- type: relative
- default: 0 % + 0pt
- body:
- description: The content to place.
- type: content
- default: None
## Definitions
### place.flush
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.
```typst
#lorem(15)
#figure(
rect(width: 100%, height: 50pt),
placement: auto,
caption: [A rectangle],
)
#place.flush()
This text appears after the figure.
```
@@ -0,0 +1,29 @@
# Ratio
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](/docs/reference/layout/relative/), to specify the size of some layout element relative to the page or some container.
```typst
#rect(width: 25%)
```
However, they can also describe any other property that is relative to some base, e.g. an amount of [horizontal scaling](/docs/reference/layout/scale/#parameters-x) or the [height of parentheses](/docs/reference/math/lr/#functions-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`](/docs/reference/layout/ratio/) | `27% * 10%` | `2.7%` |
| [`length`](/docs/reference/layout/length/) | `27% * 100pt` | `27pt` |
| [`relative`](/docs/reference/layout/relative/) | `27% * (10% + 100pt)` | `2.7% + 27pt` |
| [`angle`](/docs/reference/layout/angle/) | `27% * 100deg` | `27deg` |
| [`int`](/docs/reference/foundations/int/) | `27% * 2` | `54%` |
| [`float`](/docs/reference/foundations/float/) | `27% * 0.37037` | `10%` |
| [`fraction`](/docs/reference/layout/fraction/) | `27% * 3fr` | `0.81fr` |
When ratios are [displayed](/docs/reference/foundations/repr/) in the document, they are rounded to two significant digits for readability.
@@ -0,0 +1,54 @@
# Relative Length
A length in relation to some known length.
This type is a combination of a [length](/docs/reference/layout/length/) with a [ratio](/docs/reference/layout/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](/docs/reference/layout/block/), [rect](/docs/reference/visualize/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).
```typst
#rect(width: 25%)
```
Bare lengths or ratios are always valid where relative lengths are expected, but the two can also be freely mixed:
```typst
#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](/docs/reference/layout/page/#parameters-background) or [foreground](/docs/reference/layout/page/#parameters-foreground) field as those don't take margins into account (note that it will render the content outside of the document flow, see [place](/docs/reference/layout/place/) to control the content position)
## Relative to a container
When a layout element (e.g. a [rect](/docs/reference/visualize/rect/)) is nested in another layout container (e.g. a [block](/docs/reference/layout/block/)) instead of being a direct descendant of the page, relative widths become relative to the container:
```typst
#block(
width: 100pt,
fill: aqua,
rect(width: 50%),
)
```
## Scripting
You can multiply relative lengths by [ratios](/docs/reference/layout/ratio/), [integers](/docs/reference/foundations/int/), and [floats](/docs/reference/foundations/float/).
A relative length has the following fields:
- `length`: Its [length](/docs/reference/layout/length/) component.
- `ratio`: Its [ratio](/docs/reference/layout/ratio/) component.
```typst
#(100% - 50pt).length \
#(100% - 50pt).ratio
```
@@ -0,0 +1,53 @@
# Repeat
# repeat
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`](/docs/reference/layout/repeat/#parameters-justify) parameter accordingly.
Errors if there are no bounds on the available space, as it would create infinite content.
## Example
```typst
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](/docs/reference/pdf/artifact/) and hidden from Assistive Technology (AT). Do not use this function to create content that contributes to the meaning of your document.
```typst
#repeat(
body,
gap: length,
justify: bool
) -> content
```
## Parameters
- body:
- description: The content to repeat.
- type: content
- default: None
- gap:
- description: The gap between each instance of the body.
- type: length
- default: 0pt
- justify:
- description: Whether to increase the gap between instances to completely fill the available space.
- type: bool
- default: true
@@ -0,0 +1,48 @@
# Rotate
# rotate
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
```typst
#stack(
dir: ltr,
spacing: 1fr,
..range(16)
.map(i => rotate(24deg * i)[X]),
)
```
```typst
#rotate(
angle,
origin: alignment,
reflow: bool,
body
) -> content
```
## Parameters
- angle:
- description: The amount of rotation. ```typst #rotate(-1.571rad)[Space!] ```
- type: angle
- default: 0deg
- origin:
- description: 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. ```typst #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())) ```
- type: alignment
- default: center + horizon
- reflow:
- description: 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. ```typst Hello #rotate(90deg, reflow: true)[World]! ```
- type: bool
- default: false
- body:
- description: The content to rotate.
- type: content
- default: None
@@ -0,0 +1,55 @@
# Scale
# scale
Scales content without affecting layout.
Lets you mirror content by specifying a negative scale on a single axis.
## Example
```typst
#set align(center)
#scale(x: -100%)[This is mirrored.]
#scale(x: -100%, reflow: true)[This is mirrored.]
```
```typst
#scale(
factor: auto | length | ratio,
x: auto | length | ratio,
y: auto | length | ratio,
origin: alignment,
reflow: bool,
body
) -> content
```
## Parameters
- factor:
- description: 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.
- type: auto | length | ratio
- default: 100 %
- x:
- description: The horizontal scaling factor. The body will be mirrored horizontally if the parameter is negative.
- type: auto | length | ratio
- default: 100 %
- y:
- description: The vertical scaling factor. The body will be mirrored vertically if the parameter is negative.
- type: auto | length | ratio
- default: 100 %
- origin:
- description: The origin of the transformation. ```typst A#box(scale(75%)[A])A \\ B#box(scale(75%, origin: bottom + left)[B])B ```
- type: alignment
- default: center + horizon
- reflow:
- description: 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. ```typst Hello #scale(x: 20%, y: 40%, reflow: true)[World]! ```
- type: bool
- default: false
- body:
- description: The content to scale.
- type: content
- default: None
@@ -0,0 +1,50 @@
# Skew
# skew
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
```typst
#skew(ax: -12deg)[
This is some fake italic text.
]
```
```typst
#skew(
ax: angle,
ay: angle,
origin: alignment,
reflow: bool,
body
) -> content
```
## Parameters
- ax:
- description: The horizontal skewing angle. ```typst #skew(ax: 30deg)[Skewed] ```
- type: angle
- default: 0deg
- ay:
- description: The vertical skewing angle. ```typst #skew(ay: 30deg)[Skewed] ```
- type: angle
- default: 0deg
- origin:
- description: The origin of the skew transformation. The origin will stay fixed during the operation. ```typst 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 ```
- type: alignment
- default: center + horizon
- reflow:
- description: 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. ```typst Hello #skew(ay: 30deg, reflow: true, "World")! ```
- type: bool
- default: false
- body:
- description: The content to skew.
- type: content
- default: None
@@ -0,0 +1,47 @@
# Stack
# stack
Arranges content and spacing horizontally or vertically.
The stack places a list of items along an axis, with optional spacing between each item.
## Example
```typst
#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.
```typst
#stack(
dir: direction,
spacing: none | relative | fraction,
children
) -> content
```
## Parameters
- dir:
- description: 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`.
- type: direction
- default: ttb
- spacing:
- description: Spacing to insert between items where no explicit spacing was provided.
- type: none | relative | fraction
- default: none
- children:
- description: The children to stack along the axis.
- type: relative | fraction | content
- default: None
@@ -0,0 +1,43 @@
# Spacing (V)
# v
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
```typst
#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],
)
```
```typst
#v(
amount,
weak: bool
) -> content
```
## Parameters
- amount:
- description: How much spacing to insert.
- type: relative | fraction
- default: None
- weak:
- description: 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. ```typst 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: ```
- type: bool
- default: false
@@ -0,0 +1,43 @@
# Accent
# math.accent
Attaches an accent to a base.
## Example
```typst
$grave(a) = accent(a, `)$ \
$arrow(a) = accent(a, arrow)$ \
$tilde(a) = accent(a, \u{0303})$
```
```typst
#math.accent(
base,
accent,
size: relative,
dotless: bool
) -> content
```
## Parameters
- base:
- description: The base to which the accent is applied. May consist of multiple letters. ```typst $arrow(A B C)$ ```
- type: content
- default: None
- accent:
- description: The accent to apply to the base. Supported accents include: | Accent | Name | Codepoint | | --- | --- | --- | | Grave | `grave` | ``` | | Acute | `acute` | `´` | | Circumflex | `hat` | `^` | | Tilde | `tilde` | `~` | | Macron | `macron` | `¯` | | Dash | `dash` | `‾` | | Breve | `breve` | `˘` | | Dot | `dot` | `.` | | Double dot, Diaeresis | `dot.double`, `diaer` | `¨` | | Triple dot | `dot.triple` | `⃛` | | Quadruple dot | `dot.quad` | `⃜` | | 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` | `↼` |
- type: str | content
- default: None
- size:
- description: The size of the accent, relative to the width of the base. ```typst $dash(A, size: #150%)$ ```
- type: relative
- default: 100 % + 0pt
- dotless:
- description: Whether to remove the dot on top of lowercase i and j when adding a top accent. This enables the `dtls` OpenType feature. ```typst $hat(dotless: #false, i)$ ```
- type: bool
- default: true
@@ -0,0 +1,120 @@
# Attach
Subscript, superscripts, and limits.
Attachments can be displayed either as sub/superscripts, or limits. Typst automatically decides which is more suitable depending on the base, but you can also control this manually with the `scripts` and `limits` functions.
If you want the base to stretch to fit long top and bottom attachments (for example, an arrow with text above it), use the [`stretch`](/docs/reference/math/stretch/) function.
## Example
```typst
$ sum_(i=0)^n a_i = 2^(1+i) $
```
## Syntax
This function also has dedicated syntax for attachments after the base: Use the underscore (`_`) to indicate a subscript i.e. bottom attachment and the hat (`^`) to indicate a superscript i.e. top attachment.
# math.attach
A base with optional attachments.
```typst
$ attach(
Pi, t: alpha, b: beta,
tl: 1, tr: 2+3, bl: 4+5, br: 6,
) $
```
```typst
#math.attach(
base,
t: none | content,
b: none | content,
tl: none | content,
bl: none | content,
tr: none | content,
br: none | content
) -> content
```
## Parameters
- base:
- description: The base to which things are attached.
- type: content
- default: None
- t:
- description: 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.
- type: none | content
- default: none
- b:
- description: 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.
- type: none | content
- default: none
- tl:
- description: The top-left attachment (before the base).
- type: none | content
- default: none
- bl:
- description: The bottom-left attachment (before base).
- type: none | content
- default: none
- tr:
- description: The top-right attachment (after the base).
- type: none | content
- default: none
- br:
- description: The bottom-right attachment (after the base).
- type: none | content
- default: none
# math.scripts
Forces a base to display attachments as scripts.
```typst
$ scripts(sum)_1^2 != sum_1^2 $
```
```typst
#math.scripts(
body
) -> content
```
## Parameters
- body:
- description: The base to attach the scripts to.
- type: content
- default: None
# math.limits
Forces a base to display attachments as limits.
```typst
$ limits(A)_1^2 != A_1^2 $
```
```typst
#math.limits(
body,
inline: bool
) -> content
```
## Parameters
- body:
- description: The base to attach the limits to.
- type: content
- default: None
- inline:
- description: 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.
- type: bool
- default: true
@@ -0,0 +1,32 @@
# Binomial
# math.binom
A binomial expression.
## Example
```typst
$ binom(n, k) $
$ binom(n, k_1, k_2, k_3, ..., k_m) $
```
```typst
#math.binom(
upper,
lower
) -> content
```
## Parameters
- upper:
- description: The binomial\'s upper index.
- type: content
- default: None
- lower:
- description: The binomial\'s lower index.
- type: content
- default: None
@@ -0,0 +1,55 @@
# Cancel
# math.cancel
Displays a diagonal line over a part of an equation.
This is commonly used to show the elimination of a term.
## Example
```typst
Here, we can simplify:
$ (a dot b dot cancel(x)) /
cancel(x) $
```
```typst
#math.cancel(
body,
length: relative,
inverted: bool,
cross: bool,
angle: auto | angle | function,
stroke: length | color | gradient | stroke | tiling | dictionary
) -> content
```
## Parameters
- body:
- description: The content over which the line should be placed.
- type: content
- default: None
- length:
- description: 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. ```typst $ a + cancel(x, length: #200%) - cancel(x, length: #200%) $ ```
- type: relative
- default: 100 % + 3pt
- inverted:
- description: 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. ```typst $ (a cancel((b + c), inverted: #true)) / cancel(b + c, inverted: #true) $ ```
- type: bool
- default: false
- cross:
- description: Whether two opposing cancel lines should be drawn, forming a cross over the element. Overrides `inverted`. ```typst $ cancel(Pi, cross: #true) $ ```
- type: bool
- default: false
- angle:
- description: 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. ```typst $ 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)) $ ```
- type: auto | angle | function
- default: auto
- stroke:
- description: How to [stroke](/docs/reference/visualize/stroke/) the cancel line. ```typst $ cancel( sum x, stroke: #( paint: red, thickness: 1.5pt, dash: "dashed", ), ) $ ```
- type: length | color | gradient | stroke | tiling | dictionary
- default: 0.5pt
@@ -0,0 +1,48 @@
# Cases
# math.cases
A case distinction.
Content across different branches can be aligned with the `&` symbol.
## Example
```typst
$ f(x, y) := cases(
1 "if" (x dot y)/2 <= 0,
2 "if" x "is even",
3 "if" x in NN,
4 "else",
) $
```
```typst
#math.cases(
delim: none | str | array | symbol,
reverse: bool,
gap: relative,
children
) -> content
```
## Parameters
- delim:
- description: 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. ```typst #set math.cases(delim: "[") $ x = cases(1, 2) $ ```
- type: none | str | array | symbol
- default: ("{", "}")
- reverse:
- description: Whether the direction of cases should be reversed. ```typst #set math.cases(reverse: true) $ cases(1, 2) = x $ ```
- type: bool
- default: false
- gap:
- description: The gap between branches. ```typst #set math.cases(gap: 1em) $ x = cases(1, 2) $ ```
- type: relative
- default: 0 % + 0.2em
- children:
- description: The branches of the case distinction.
- type: content
- default: None
@@ -0,0 +1,38 @@
# Class
# math.class
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`](/docs/reference/math/attach/#functions-limits) and [`scripts`](/docs/reference/math/attach/#functions-scripts).
## Example
```typst
#let loves = math.class(
"relation",
sym.suit.heart,
)
$x loves y and y loves 5$
```
```typst
#math.class(
class,
body
) -> content
```
## Parameters
- class:
- description: The class to apply to the content.
- type: str
- default: None
- body:
- description: The content to which the class is applied.
- type: content
- default: None
@@ -0,0 +1,67 @@
# Equation
# math.equation
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
```typst
#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](/docs/reference/math/).
```typst
#math.equation(
block: bool,
numbering: none | str | function,
number-align: alignment,
supplement: none | auto | content | function,
alt: none | str,
body
) -> content
```
## Parameters
- block:
- description: Whether the equation is displayed as a separate block.
- type: bool
- default: false
- numbering:
- description: How to number block-level equations. Accepts a [numbering pattern or function](/docs/reference/model/numbering/) taking a single number. ```typst #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) $ ```
- type: none | str | function
- default: none
- number-align:
- description: 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`. ```typst #set math.equation(numbering: "(1)", number-align: bottom) We can calculate: $ E &= sqrt(m_0^2 + p^2) \\ &approx 125 "GeV" $ ```
- type: alignment
- default: end + horizon
- supplement:
- description: 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. ```typst #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) $ ```
- type: none | auto | content | function
- default: auto
- alt:
- description: 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](/docs/guides/accessibility/#textual-representations). ```typst #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 $, ) ```
- type: none | str
- default: none
- body:
- description: The contents of the equation.
- type: content
- default: None
@@ -0,0 +1,41 @@
# Fraction
# math.frac
A mathematical fraction.
## Example
```typst
$ 1/2 < (x+1)/2 $
$ ((x+1)) / 2 = frac(a, b) $
```
## Syntax
This function also has dedicated syntax: Use a slash to turn neighbouring expressions into a fraction. Multiple atoms can be grouped into a single expression using round grouping parentheses. Such parentheses are removed from the output, but you can nest multiple to force them.
```typst
#math.frac(
num,
denom,
style: str
) -> content
```
## Parameters
- num:
- description: The fraction\'s numerator.
- type: content
- default: None
- denom:
- description: The fraction\'s denominator.
- type: content
- default: None
- style:
- description: How the fraction should be laid out. ```typst $ frac(x, y, style: "vertical") $ $ frac(x, y, style: "skewed") $ $ frac(x, y, style: "horizontal") $ ``` ```typst #set math.frac(style: "skewed") $ a / b $ ``` ```typst // Grouping parentheses are removed. #set math.frac(style: "vertical") $ (a + b) / b $ // Grouping parentheses are removed. #set math.frac(style: "skewed") $ (a + b) / b $ // Grouping parentheses are retained. #set math.frac(style: "horizontal") $ (a + b) / b $ ``` ```typst // This changes the style for inline equations only. #show math.equation.where(block: false): set math.frac(style: "horizontal") This $(x-y)/z = 3$ is inline math, and this is block math: $ (x-y)/z = 3 $ ```
- type: str
- default: "vertical"
@@ -0,0 +1,119 @@
# Math
Typst has special [syntax](/docs/reference/syntax/#math) and library functions to typeset mathematical formulas. Math formulas can be displayed inline with text or as separate blocks. They will be typeset into their own block if they start and end with at least one space (e.g. `$ x^2 $`).
## Variables
In math, single letters are always displayed as is. Multiple letters, however, are interpreted as variables and functions. To display multiple letters verbatim, you can place them into quotes and to access single letter variables, you can use the [hash syntax](/docs/reference/scripting/#expressions).
```typst
$ A = pi r^2 $
$ "area" = pi dot "radius"^2 $
$ cal(A) :=
{ x in RR | x "is natural" } $
#let x = 5
$ #x < 17 $
```
## Symbols
Math mode makes a wide selection of [symbols](/docs/reference/symbols/sym/) like `pi`, `dot`, or `RR` available. Many mathematical symbols are available in different variants. You can select between different variants by applying [modifiers](/docs/reference/foundations/symbol/) to the symbol. Typst further recognizes a number of shorthand sequences like `=>` that approximate a symbol. When such a shorthand exists, the symbol's documentation lists it.
```typst
$ x < y => x gt.eq.not y $
```
## Line Breaks
Formulas can also contain line breaks. Each line can contain one or multiple _alignment points_ (`&`) which are then aligned.
```typst
$ sum_(k=0)^n k
&= 1 + ... + n \
&= (n(n+1)) / 2 $
```
## Function calls
Math mode supports special function calls without the hash prefix. In these "math calls", the argument list works a little differently than in code:
- Within them, Typst is still in "math mode". Thus, you can write math directly into them, but need to use hash syntax to pass code expressions (except for strings, which are available in the math syntax).
- They support positional and named arguments, as well as argument spreading.
- They don't support trailing content blocks.
- They provide additional syntax for 2-dimensional argument lists. The semicolon (`;`) merges preceding arguments separated by commas into an array argument.
```typst
$ frac(a^2, 2) $
$ vec(1, 2, delim: "[") $
$ mat(1, 2; 3, 4) $
$ mat(..#range(1, 5).chunks(2)) $
$ lim_x =
op("lim", limits: #true)_x $
```
To write a verbatim comma or semicolon in a math call, escape it with a backslash. The colon on the other hand is only recognized in a special way if directly preceded by an identifier, so to display it verbatim in those cases, you can just insert a space before it.
Functions calls preceded by a hash are normal code function calls and not affected by these rules.
## Alignment
When equations include multiple _alignment points_ (`&`), this creates blocks of alternatingly right- and left-aligned columns. In the example below, the expression `(3x + y) / 7` is right-aligned and `= 9` is left-aligned. The word "given" is also left-aligned because `&&` creates two alignment points in a row, alternating the alignment twice. `& &` and `&&` behave exactly the same way. Meanwhile, "multiply by 7" is right-aligned because just one `&` precedes it. Each alignment point simply alternates between right-aligned/left-aligned.
```typst
$ (3x + y) / 7 &= 9 && "given" \
3x + y &= 63 & "multiply by 7" \
3x &= 63 - y && "subtract y" \
x &= 21 - y/3 & "divide by 3" $
```
## Math fonts
You can set the math font by with a [show-set rule](/docs/reference/styling/#show-rules) as demonstrated below. Note that only special OpenType math fonts are suitable for typesetting maths.
```typst
#show math.equation: set text(font: "Fira Math")
$ sum_(i in NN) 1 + i $
```
## Math module
All math functions are part of the `math` [module](/docs/reference/scripting/#modules), which is available by default in equations. Outside of equations, they can be accessed with the `math.` prefix.
## Accessibility
To make math accessible, you must provide alternative descriptions of equations in natural language using the [`alt` parameter of `math.equation`](/docs/reference/math/equation/#parameters-alt). For more information, see the [Textual Representations section of the Accessibility Guide](/docs/guides/accessibility/#textual-representations).
```typst
#math.equation(
alt: "d S equals delta q divided by T",
block: true,
$ dif S = (delta q) / T $,
)
```
In the future, Typst will automatically make equations without alternative descriptions accessible in HTML and PDF 2.0 export.
## Definitions
| Name | Description |
| --- | --- |
| [`accent`](/reference/math/accent/) | Attaches an accent to a base. |
| [`attach`](/reference/math/attach/) | Subscript, superscripts, and limits. |
| [`binom`](/reference/math/binom/) | A binomial expression. |
| [`cancel`](/reference/math/cancel/) | Displays a diagonal line over a part of an equation. |
| [`cases`](/reference/math/cases/) | A case distinction. |
| [`class`](/reference/math/class/) | Forced use of a certain math class. |
| [`equation`](/reference/math/equation/) | A mathematical equation. |
| [`frac`](/reference/math/frac/) | A mathematical fraction. |
| [`lr`](/reference/math/lr/) | Delimiter matching. |
| [`mat`](/reference/math/mat/) | A matrix. |
| [`op`](/reference/math/op/) | A text operator in an equation. |
| [`primes`](/reference/math/primes/) | Grouped primes. |
| [`roots`](/reference/math/roots/) | Square and non-square roots. |
| [`sizes`](/reference/math/sizes/) | Forced size styles for expressions within formulas. |
| [`stretch`](/reference/math/stretch/) | Stretches a glyph. |
| [`styles`](/reference/math/styles/) | Alternate letterforms within formulas. |
| [`underover`](/reference/math/underover/) | Delimiters above or below parts of an equation. |
| [`variants`](/reference/math/variants/) | Alternate typefaces within formulas. |
| [`vec`](/reference/math/vec/) | A column vector. |
@@ -0,0 +1,195 @@
# Left/Right
Delimiter matching.
The `lr` function allows you to match two delimiters and scale them with the content they contain. While this also happens automatically for delimiters that match syntactically, `lr` allows you to match two arbitrary delimiters and control their size exactly. Apart from the `lr` function, Typst provides a few more functions that create delimiter pairings for absolute, ceiled, and floored values as well as norms.
To prevent a delimiter from being matched by Typst, and thus auto-scaled, escape it with a backslash. To instead disable auto-scaling completely, use `set math.lr(size: 1em)`.
## Example
```typst
$ [a, b/2] $
$ lr(]sum_(x=1)^n], size: #50%) x $
$ abs((x + y) / 2) $
$ \{ (x / y) \} $
#set math.lr(size: 1em)
$ { (a / b), a, b in (0; 1/2] } $
```
# math.lr
Scales delimiters.
While matched delimiters scale by default, this can be used to scale unmatched delimiters and to control the delimiter scaling more precisely.
```typst
#math.lr(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: 100 % + 0pt
- body:
- description: The delimited content, including the delimiters.
- type: content
- default: None
# math.mid
Scales delimiters vertically to the nearest surrounding `lr()` group.
```typst
$ { x mid(|) sum_(i=1)^n w_i|f_i (x)| < 1 } $
```
```typst
#math.mid(
body
) -> content
```
## Parameters
- body:
- description: The content to be scaled.
- type: content
- default: None
# math.abs
Takes the absolute value of an expression.
```typst
$ abs(x/2) $
```
```typst
#math.abs(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: None
- body:
- description: The expression to take the absolute value of.
- type: content
- default: None
# math.norm
Takes the norm of an expression.
```typst
$ norm(x/2) $
```
```typst
#math.norm(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: None
- body:
- description: The expression to take the norm of.
- type: content
- default: None
# math.floor
Floors an expression.
```typst
$ floor(x/2) $
```
```typst
#math.floor(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: None
- body:
- description: The expression to floor.
- type: content
- default: None
# math.ceil
Ceils an expression.
```typst
$ ceil(x/2) $
```
```typst
#math.ceil(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: None
- body:
- description: The expression to ceil.
- type: content
- default: None
# math.round
Rounds an expression.
```typst
$ round(x/2) $
```
```typst
#math.round(
size: relative,
body
) -> content
```
## Parameters
- size:
- description: The size of the brackets, relative to the height of the wrapped content.
- type: relative
- default: None
- body:
- description: The expression to round.
- type: content
- default: None
@@ -0,0 +1,65 @@
# Matrix
# math.mat
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`](/docs/reference/math/mat/#parameters-align) parameter, or content in cells that are in the same row can be aligned with the `&` symbol.
## Example
```typst
$ mat(
1, 2, ..., 10;
2, 2, ..., 10;
dots.v, dots.v, dots.down, dots.v;
10, 10, ..., 10;
) $
```
```typst
#math.mat(
delim: none | str | array | symbol,
align: alignment,
augment: none | int | dictionary,
gap: relative,
row-gap: relative,
column-gap: relative,
rows
) -> content
```
## Parameters
- delim:
- description: 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. ```typst #set math.mat(delim: "[") $ mat(1, 2; 3, 4) $ ```
- type: none | str | array | symbol
- default: ("(", ")")
- align:
- description: The horizontal alignment that each cell should have. ```typst #set math.mat(align: right) $ mat(-1, 1, 1; 1, -1, 1; 1, 1, -1) $ ```
- type: alignment
- default: center
- augment:
- description: 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](/docs/reference/visualize/stroke/) the line. If set to `auto`, takes on a thickness of 0.05 em and square line caps. ```typst $ mat(1, 0, 1; 0, 1, 2; augment: #2) $ // Equivalent to: $ mat(1, 0, 1; 0, 1, 2; augment: #(-1)) $ ``` ```typst $ mat(0, 0, 0; 1, 1, 1; augment: #(hline: 1, stroke: 2pt + green)) $ ```
- type: none | int | dictionary
- default: none
- gap:
- description: The gap between rows and columns. This is a shorthand to set `row-gap` and `column-gap` to the same value. ```typst #set math.mat(gap: 1em) $ mat(1, 2; 3, 4) $ ```
- type: relative
- default: 0 % + 0pt
- row-gap:
- description: The gap between rows. ```typst #set math.mat(row-gap: 1em) $ mat(1, 2; 3, 4) $ ```
- type: relative
- default: 0 % + 0.2em
- column-gap:
- description: The gap between columns. ```typst #set math.mat(column-gap: 1em) $ mat(1, 2; 3, 4) $ ```
- type: relative
- default: 0 % + 0.5em
- rows:
- description: An array of arrays with the rows of the matrix. ```typst #let data = ((1, 2, 3), (4, 5, 6)) #let matrix = math.mat(..data) $ v := matrix $ ```
- type: array
- default: None
@@ -0,0 +1,37 @@
# Text Operator
# math.op
A text operator in an equation.
## Example
```typst
$ tan x = (sin x)/(cos x) $
$ op("custom",
limits: #true)_(n->oo) n $
```
## Predefined Operators
Typst predefines the operators `arccos`, `arcsin`, `arctan`, `arg`, `cos`, `cosh`, `cot`, `coth`, `csc`, `csch`, `ctg`, `deg`, `det`, `dim`, `exp`, `gcd`, `lcm`, `hom`, `id`, `im`, `inf`, `ker`, `lg`, `lim`, `liminf`, `limsup`, `ln`, `log`, `max`, `min`, `mod`, `Pr`, `sec`, `sech`, `sin`, `sinc`, `sinh`, `sup`, `tan`, `tanh`, `tg` and `tr`.
```typst
#math.op(
text,
limits: bool
) -> content
```
## Parameters
- text:
- description: The operator\'s text.
- type: content
- default: None
- limits:
- description: Whether the operator should show attachments as limits in display mode.
- type: bool
- default: false
@@ -0,0 +1,28 @@
# Primes
# math.primes
Grouped primes.
```typst
$ 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.
```typst
#math.primes(
count
) -> content
```
## Parameters
- count:
- description: The number of grouped primes.
- type: int
- default: None
@@ -0,0 +1,59 @@
# Roots
Square and non-square roots.
## Example
```typst
$ sqrt(3 - 2 sqrt(2)) = sqrt(2) - 1 $
$ root(3, x) $
```
# math.root
A general root.
```typst
$ root(3, x) $
```
```typst
#math.root(
index,
radicand
) -> content
```
## Parameters
- index:
- description: Which root of the radicand to take.
- type: none | content
- default: none
- radicand:
- description: The expression to take the root of.
- type: content
- default: None
# math.sqrt
A square root.
```typst
$ sqrt(3 - 2 sqrt(2)) = sqrt(2) - 1 $
```
```typst
#math.sqrt(
radicand
) -> content
```
## Parameters
- radicand:
- description: The expression to take the square root of.
- type: content
- default: None
@@ -0,0 +1,120 @@
# Sizes
Forced size styles for expressions within formulas.
These functions allow manual configuration of the size of equation elements to make them look as in a display/inline equation or as if used in a root or sub/superscripts.
# math.display
Forced display style in math.
This is the normal size for block equations.
```typst
$sum_i x_i/2 = display(sum_i x_i/2)$
```
```typst
#math.display(
body,
cramped: bool
) -> content
```
## Parameters
- body:
- description: The content to size.
- type: content
- default: None
- cramped:
- description: Whether to impose a height restriction for exponents, like regular sub- and superscripts do.
- type: bool
- default: false
# math.inline
Forced inline (text) style in math.
This is the normal size for inline equations.
```typst
$ sum_i x_i/2
= inline(sum_i x_i/2) $
```
```typst
#math.inline(
body,
cramped: bool
) -> content
```
## Parameters
- body:
- description: The content to size.
- type: content
- default: None
- cramped:
- description: Whether to impose a height restriction for exponents, like regular sub- and superscripts do.
- type: bool
- default: false
# math.script
Forced script style in math.
This is the smaller size used in powers or sub- or superscripts.
```typst
$sum_i x_i/2 = script(sum_i x_i/2)$
```
```typst
#math.script(
body,
cramped: bool
) -> content
```
## Parameters
- body:
- description: The content to size.
- type: content
- default: None
- cramped:
- description: Whether to impose a height restriction for exponents, like regular sub- and superscripts do.
- type: bool
- default: true
# math.sscript
Forced second script style in math.
This is the smallest size, used in second-level sub- and superscripts (script of the script).
```typst
$sum_i x_i/2 = sscript(sum_i x_i/2)$
```
```typst
#math.sscript(
body,
cramped: bool
) -> content
```
## Parameters
- body:
- description: The content to size.
- type: content
- default: None
- cramped:
- description: Whether to impose a height restriction for exponents, like regular sub- and superscripts do.
- type: bool
- default: true
@@ -0,0 +1,36 @@
# Stretch
# math.stretch
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.
```typst
$ H stretch(=)^"define" U + p V $
$ f : X stretch(->>, size: #150%)_"surjective" Y $
$ x stretch(harpoons.ltrb, size: #3em) y
stretch(\[, size: #150%) z $
```
```typst
#math.stretch(
body,
size: relative
) -> content
```
## Parameters
- body:
- description: The glyph to stretch.
- type: content
- default: None
- size:
- description: The size to stretch to, relative to the maximum size of the glyph and its attachments.
- type: relative
- default: 100 % + 0pt
@@ -0,0 +1,68 @@
# Styles
Alternate letterforms within formulas.
These functions are distinct from the [`text`](/docs/reference/text/text/) function because math fonts contain multiple variants of each letter.
# math.upright
Upright (non-italic) font style in math.
```typst
$ upright(A) != A $
```
```typst
#math.upright(
body
) -> content
```
## Parameters
- body:
- description: The content to style.
- type: content
- default: None
# math.italic
Italic font style in math.
For roman letters and greek lowercase letters, this is already the default.
```typst
#math.italic(
body
) -> content
```
## Parameters
- body:
- description: The content to style.
- type: content
- default: None
# math.bold
Bold font style in math.
```typst
$ bold(A) := B^+ $
```
```typst
#math.bold(
body
) -> content
```
## Parameters
- body:
- description: The content to style.
- type: content
- default: None
Loaded 100 of 454 files, more files were not shown because too many files have changed in this diff. Show more