feat: initial commit

This commit is contained in:
johannes committed 2026-07-26 11:42:17 +02:00
commit b802ff49ab
454 files changed
+52429

No files matched your search

@@ -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