Skip to content

Ability to freeze state #1841

Open
Open

Description

@edgarogh

Context / use-case

Slideshow with "fragments" or "pauses"

I would like to create a template for PDF slideshows, with a #fragment[] function that allows me to hide an element at first and reveal it later on a duplicate page (like reveal.js fragments or Beamer's \pauses).

Student quizz / multiple choice question with permuted answers

Described later here (scroll).

Description

To do so, I'd need the ability to duplicate a page, freezing almost all state (including state() variables, heading numbering, page number, etc.), except for one "iteration variable" that tells me which copy I'm laying out currently.

Essentially, I'm looking for a function that would "instantiate" a content at a specific location (regarding state) in a way that resolves/freezes implicit and explicit state inside it, so that any attempt to lay it out multiple times results in the same state materialization.

Possible implementation 1: freeze(content, exclude: list or state)

#let idx = state("idx", 0)
#let body = [= Heading #idx.display() #idx.update(v => v+1)] // depends on implicit heading state

#let body_frozen = freeze(body, exclude: (idx,))

// Headings have the same number
body_frozen
body_frozen
body_frozen

Here, we explicitly exclude a state variable from the freezing, so it can be used and mutated inside.

Note: if a heading is inserted between the call to freeze and the layouts of body_frozen (L5), we would expect the numbering to be in the wrong order, which I guess would be a feature?

Possible implementation 2: clone(content, count: number, exclude: list or state)

This approach would be more "managed" and tailored to my specific case, leading to less room for weird behavior such as unordered numbering:

#let idx = state("idx", 0)
#let body = [= Heading #idx.display() #idx.update(v => v+1)]

clone(body, exclude: (idx,), count: 3) // Creates 3 copies of body, with only "idx" being mutated

Another possible approach would be to provide an map-like usage:

#let idx = state("idx", 0)
#let body = [= Heading #idx.display()]

clone(body, list: (0, 1, 2), state: idx)

Here, the list elements would be mapped to the body, passing their values through the idx state variable. The state variable could maybe have its original value stored and restored after the iteration, so that it isn't observable outside?

Soundness

I must admit, I haven't thought that much about the "soundness" of such a feature, and how it would interact with all the weird "meta" Typst features (locate, query, etc.).

Last note

Maybe this idea is a bad solution to the project I have initially (XY problem). Maybe it should be restricted in other ways. Or made even more generic. Maybe my initial problem should just be a Typst builtin.

Activity

  1. sitandr commented on Aug 1, 2023

    @sitandr
    Contributor

    Have you looked into polylux package? It seems like a complete solution to your task.

  2. edgarogh commented on Aug 2, 2023

    @edgarogh
    Author

    I don't know how I didn't find about Polylux when Googling but that's do the job perfectly!


    However, it does indeed look like Polylux suffers from the exact problem I'm describing: if you add numbered headings to your slides, their number increases on each sub-slide, when you'd expect the slide to remain the same overall (apart from the overlays).

    Here's an example: https://typst.app/project/rxemPv9LmpjiDKVKTESxnb

  3. PgBiel commented on Aug 3, 2023

    @PgBiel
    Contributor

    As a workaround, you can likely store the original location in some write-once state and use it to retrieve counters with .at(loc), and, with that, build a custom "heading" (maybe having a real one show up only on the first slide for referencing purposes). Not a very optimal solution, though.

    Truth is, it would be weird to have multiple headings with the same number, as references "wouldn't work". But I think some sort of middle ground can be found here (maybe by only pointing to the first one, for example - although that might seem arbitrary).

  4. sitandr commented on Aug 3, 2023

    @sitandr
    Contributor

    I'm afraid there is mo easy solution that can solve that issue via some let or show issues. So for complex things (that can't be solved by using polylux counters for slides and subslides) to make it viable you need to go inside polylux code.

    Maybe it is worth trying to make an issue in Polylux repo, so the could decide what is the best fitting missing consistent Typst feature. It is easy to store the state for some given counters, but impossible for all automatically. Maybe we should add some exporting all the states into dicts and back, maybe something entirely else. I don't know what is the best solution there.

  5. ntjess commented on Aug 9, 2023

    @ntjess

    I realize that https://discord.com/channels/1054443721975922748/1138661247940821146 might solve this issue as well -- If content could be exported to an svg string, you can simply recall the frozen state with image.decode(svg-str)

    Pasting the question for reference:

    Many publishers require you to provide each figure as a separate file along with your text. With figures made in typst, this is difficult to isolate since outer scope show rules will change the behavior if drawn figures are pasted elsewhere. With the merger of #1729, would the mechanisms be in place to, say, let svg-str = export-svg(content)?

    The cli query system can then pull those svg strings and write them to a file, if they are e.g. saved to a metadata field

  6. edgarogh commented on Aug 29, 2023

    @edgarogh
    Author

    I'm coming back with another use-case that I randomly stumbled upon: printing student quizzes (MCQ) with randomised answer order.

    Example use

    Assume that template and question are defined. The following code creates a 30 page PDF containing the answer sheets of a multiple-choice question exam for 30 students. All of them have almost the same content, with the exception of question answers, which are pseudo-randomly permuted to make cheating harder.

    #show template.with(student-count: 30)
    
    = Exam
    
    #question(
      "What's the first letter of the alphabet?",
      right: "A",
      wrong: ("B", "C"),
    )
    

    To implement template(), you need to repeat the same content 30 times with just the PRNG seed being different. You don't want any title numbering or question numbering cascading to the following sheet. There are currently two solutions:

    • Manually reset any state or counter after each answer sheet. This is tedious, especially when counters and state from packages are involved.
    • Generate each answer sheet individually and merge them after. You loose a lot of performance on process invocation, PDF parsing, PDF encoding, and lack of memoization accross each student sheet. Also, any call to datetime.now() may result in different values between each answer sheet.

    The system I describe in this issue could solve this problem very trivially.

  7. added
    feature request
    styling
    on Sep 4, 2023
  8. changed the title [-]Element function to freeze state[/-] [+]Ability to freeze state[/+] on Nov 14, 2023
  9. added
    introspection
    and removed on Nov 24, 2023
  10. laurmaedje commented on Jan 15, 2024

    @laurmaedje
    Member
  11. memeplex commented on Aug 5, 2024

    @memeplex

    I've been reading the post and pondering on it. I would like to suggest an alternative angle to approach the issue. But at best I have a rough understanding of Typst architecture and internals, so what follows may be babbling.

    If I understand correctly, the problem can be illustrated like this (Excalidraw permalink):

    image

    We have defined some content that depends on some state and we instance that content at different places in the document.

    To produce its output each instance of the content must look at the sequence of updates of the state in document order, from the place where it's instantiated upwards.

    But this turns ambiguous to which instance we are referring during some operations when we just say "content". Worst, there may be no instance at all. We want to fix this. So far so good.

    Now a tentative solution has been expressed in terms of "frozen state":

    1. Somehow all instances of this content are actually the same instance (although instances of regular content aren't).
    2. More perplexing, parts of each instance may still change, like those depending on state2 in the diagram.

    From this perspective, both are features of the content, and IMO this is where things get hand-wavy and a bit philosophical about different instances that are actually the same but not quite so.

    Wouldn't it be more natural to express this at the instantiation point instead of at the definition point?

    For example, regular #content instantiations would by default mean something like #content<here>, while you could explicitly say #content<place1> if you wanted content to be be instantiated with the state existing at place1, or #content<place1, (state2,)> if wanted the same but with state2 taken from place here instead.

    Please note that this is not about the syntax (I don't care about it) nor about what places ultimately are (they may be simply labels, or perhaps contexts, I don't have enough knowledge to identify what's the closest underlying Typst concept, so I just called them places as well as I might have called them checkpoints).

  12. laurmaedje commented on Aug 5, 2024

    @laurmaedje
    Member

    @git001 Thanks for the heads-up. I made some changes the blog's build process. That broke things apparently. I'm rolling them back now. (edit: turns out it was because my GitHub student pro membership ran out and the repo was private ...)

  13. lordkekz commented on Dec 25, 2025

    @lordkekz

    Problem Analysis

    Wouldn't it be more natural to express this at the instantiation point instead of at the definition point?

    For example, regular #content instantiations would by default mean something like #content<here>, while you could explicitly say #content<place1> if you wanted content to be be instantiated with the state existing at place1, or #content<place1, (state2,)> if wanted the same but with state2 taken from place here instead.

    Please note that this is not about the syntax (I don't care about it) nor about what places ultimately are (they may be simply labels, or perhaps contexts, I don't have enough knowledge to identify what's the closest underlying Typst concept, so I just called them places as well as I might have called them checkpoints).

    I think this is getting at something important: the to-be-frozen content needs to be parameterized in many scenarios such as animations for slides. To understand what it means for content to be frozen, we should consider the various ways that content can be parameterized. I'm aware of three such mechanisms.

    Parameterization using Functions

    Commonly, functions are used to construct content based on parameters passed to the constructing function. Functions are pure and their parameters are explicit. Thus, functions parameters are in principle layout-independent, although within context expressions functions may be passed layout-dependent information that was previously extracted from the context.

    When content is frozen, multiple occurrences of the content could conceivably be constructed with different parameters (though Typst would of course consider the two return values to be different content).

    For example, the subslide index could be a parameter passed to a slide function. It makes sense to treat subslide indices as function parameters because one may choose to instantiate the same subslide at different locations within a document (i.e. to recap it later).

    Parameterization using State

    When layout-dependent information needs to be stored, this can be done by inserting state-accessing content. Currently, it is possible to write and read any particular named state and pass any location as a reference for this state. But it is not possible to enumerate all named states.

    When content is frozen and occurs multiple times in a document, exactly one snapshot of state must be used across all occurrences. Let's use the term primary occurrence to refer to the occurrence whose snapshot of state is used. In turn, let's refer to the occurrences which use the snapshot of state of the primary occurrence as secondary occurrences.

    For example, the slide/page number could be a state which is read and updated by the content of a slide. It makes sense to treat page numbers as state because one rarely wants to instantiate a page with the same page number a second time. If you were to repeat such a slide, you would have to ensure that immediately before the beginning of the secondary occurrence, all state exactly matches the snapshot of state at the beginning of the primary occurrence.

    Parameterization using Introspection / Labels

    For the sake of this discussion, the results of introspection such as queries or referencing labeled elements can also be considered a kind of parameterization because the content will vary depending on the observed query results.

    When content is frozen and occurs multiple times in a document, I'm not sure how to treat it. I can see reasons for either for considering only the primary occurrence, or for treating all occurrences normally.

    For example, a reference to a figure relies on the uniqueness of the label. It is not desirable that a second occurrence of semantically identical content leads to a duplicate label and thus breaks all references to either occurrence of that label.

    Solving Each Kind of Parameterization

    I think each of the three kinds of parameterization can and should be addressed and solved seperately:

    1. Functions can already be called with the same parameters multiple times and are already pure, so they do not pose a challenge.
    2. State cannot be frozen properly yet, and this is IMO the main topic of this issue.
    3. Introspection is difficult insofar as it is not obvious how to treat multiple occurrences of content, but I don't have a clear idea how to solve this yet.
  14. lordkekz commented on Dec 25, 2025

    @lordkekz

    Proposal

    I propose that instead of creating a freeze function to tackle all kinds of parameterization and even measure, a new builtin be introduced to address parameterization using state in particular: restore-state(selector) would tell the state evaluation algorithm to essentially ignore all state updates that come after selector and before the current context.

    For example:

    #state("key").update(2)
    #context state("key").get() // yields: 2
    
    #metadata(none) <my-label>
    
    #state("key").update(x => x + 1)
    #context state("key").get() // yields: 3
    
    #restore-state(<my-label>)
    #context state("key").get() // yields: 2
    
    #state("key").update(x => x * 2)
    #context state("key").get() // yields: 4
    
    #restore-state(<my-label>)
    #context state("key").get() // yields: 2
    
    #state("key").update(x => x - 2)
    #context state("key").get() // yields: 0

    How does this solve the problem?

    Essentially, we can write user code which shows some content with the snapshot of state observed at another location:

    #let use-state(selector, body) = [
      #let before-label = label("use-state-start-" + repr(selector) + repr(body))
      #metadata(none) #before-label
      #restore-state(selector)
      body
      #restore-state(before-label)
    ]
    
    #let my-slide(subslide, slide-label: none) = [
      #page[
        = My Slide Heading
        This is subslide #subslide.
        On slide #context counter(page).display().
      ] #if slide-label != none { label(slide-label) }
    ]
    
    #my-slide(1, slide-label: "my-slide-primary") // shows subslide 1, slide 1
    #use-state(<my-slide-primary>, my-slide(2))   // shows subslide 2, slide 1
    #use-state(<my-slide-primary>, my-slide(3))   // shows subslide 3, slide 1
    #page[This is slide #context counter(page).display().]    // shows slide 2
    #use-state(<my-slide-primary>, my-slide(2))   // shows subslide 2, slide 1
    #page[This is slide #context counter(page).display().]    // shows slide 3
    #page[This is slide #context counter(page).display().]    // shows slide 4

    Cyclic Data Dependencies of State

    restore-state is very similar to a goto instruction, except it modifies the movement performed by the state evaluation algorithm. Of course, if restoring a later state than the current location is allowed, this could cause infinite loops which would need to be detected and cause a panic. I still would like jumping in either direction to be allowed for use cases such as "restating" a theorem whose primary occurrence appears later. Infinite loops of restore-state can also be avoided easily in user code, as shown in the use-state function above.

    Excluding Some State from Resetting

    Sadly, this is not so easy to do in general. One could extend the use-state function to insert state.update right after each restore-state call to restore the value right before the restore-state call. This would work for simple kinds of state such as page counters, which always have the same initial value. But in general, at any snapshot, each state is really not just a single value, but rather a function taking an initial value (the state object's init). To really make it transparent, the use-state function would need to be able to produce a state update equivalent to the sequential execution of the relevant preceding state updates, which is not possible with the current builtins and also not possible with just the restore-state builtin. I think exposing such a function would be ugly, so if exclusion is really required, I'd rather add it as a parameter to restore-state directly.

  15. lordkekz commented on Mar 14, 2026

    @lordkekz

    @laurmaedje what are your thoughts on my above proposal? In #7735 you discussed the difficulty of isolating documents in a fine-grained manner and I think that my suggestion could help with that too.

  16. laurmaedje commented on Mar 19, 2026

    @laurmaedje
    Member

    @lordkekz A proper response would take a bit of time which I don't have right now, but I'll try to get back to this.

  17. laurmaedje commented on Apr 30, 2026

    @laurmaedje
    Member

    @lordkekz One observation on your suggestion: When I think about freezing, it's not just about state, but about any kind of introspection. Restoring just state might be too limited (e.g. already counters are different). (Personally, I actually think that query + metadata, or in the future custom elements, is often a better tool than state.)

    With the design I have in mind, all introspections would act as if the element was in a different place (let's call it the "primary place"). So if you do something like query(selector(heading).before(here())), all frozen copies would also observe just the headings before the primary place.

    What would not be frozen is the style context, so with custom elements you could do "parameterization via set rule" (to use your terminology). In instances where your parameterization lets the content diverge from what happens in the primary place in a structural way, the introspection would be able to observe differences, but as long as an equivalent in the primary place exists, it would latch onto that.

  18. lordkekz commented on Apr 30, 2026

    @lordkekz

    Thank you for your response!

    @lordkekz One observation on your suggestion: When I think about freezing, it's not just about state, but about any kind of introspection.

    I agree that freezing other kinds of introspection is also useful. I'm not sure if there is a good one-size-fits-all solution though.

    Restoring just state might be too limited (e.g. already counters are different).

    But my suggestion would work analogously for counters, no? So there could simple be two function reset-state and reset-counters.

    (Personally, I actually think that query + metadata, or in the future custom elements, is often a better tool than state.)

    Hm, I think I tend to agree. It should probably even be possible to implement state and counter with queries. Besides convenience and integration with the builtin elements, is there any benefit of the builtin state as opposed to a state/counter package that uses metadata internally?

    With the design I have in mind, all introspections would act as if the element was in a different place (let's call it the "primary place"). So if you do something like query(selector(heading).before(here())), all frozen copies would also observe just the headings before the primary place.

    Alright, that sounds reasonable. I thought about it and came up with a few questions about the details.

    Would secondary occurrences be observed by other queries?

    Example Code for Illustration

    For example, would the below code show "There are 2 headings!" or "There are 4 headings!"?

    #let (primary-copy, secondary-copy) = freeze[
      = My heading.
      This is heading #query(selector(heading).before(here())).len().
    ]
    
    = Hello World
    #primary-copy
    #secondary-copy
    #secondary-copy
    
    #line()
    There are #query(selector(heading)) headings!

    Also, if the frozen content contained a link to another location in the same frozen content, would the link rendered in frozen copies lead to the corresponding location inside that same frozen copy, or to the location in the primary occurrence?

    What would not be frozen is the style context, so with custom elements you could do "parameterization via set rule" (to use your terminology). In instances where your parameterization lets the content diverge from what happens in the primary place in a structural way, the introspection would be able to observe differences, but as long as an equivalent in the primary place exists, it would latch onto that.

    It sounds like your suggestion would basically be caching the results of queries from the primary occurrence and returning them for the corresponding queries from the second occurrence, similar to how convergence of layout attempts is detected. I'm not necessarily opposed to such a caching-based approach but I have a somewhat bad feeling about the risk of accidentally causing divergence. I would like to find more generalized semantics so the observed queries produce sensible results even if the structure of the frozen content diverges due to style context changes.

    Would observable differences only occur for queries which depend on the structurally diverged part of the frozen copy or would queries that didn't occur in the primary copy simply ignore freezing altogether? i.e. what would query(selector(heading).before(here())) return if my frozen copy contained no relevant headings but did diverge structurally in such a way the query cannot be matched to a query from the primary copy?

  19. laurmaedje commented on May 1, 2026

    @laurmaedje
    Member

    But my suggestion would work analogously for counters, no? So there could simple be two function reset-state and reset-counters.

    For sure. I just think that it might be more common to want to freeze everything instead of having to think about everything to reset individually.

    Hm, I think I tend to agree. It should probably even be possible to implement state and counter with queries.

    That's exactly how they are implemented in the compiler. :)

    Besides convenience and integration with the builtin elements, is there any benefit of the builtin state as opposed to a state/counter package that uses metadata internally?

    For counters, the integration is a big part. Otherwise, a native implementation is of course also more performant. State and counters use a different variation of queries that is more performant for their use case (the original, naive implementation had $O(n^2)$ running time).

    For counting, there definitely needs to be something built-in to support native numbering of elements. State could reasonably not be native though I'm not quite convinced that just metadata/queries is enough either. I don't want everybody to have to pull a package for very basic things.


    Interesting questions on the design!

    Maybe it would be helpful if I first clarify how the design would practically be realized because it's not that queries would be cached.

    To support introspections, Typst assigns IDs to every element. These are called locations on the user-facing side, but internally they are just opaque 128-bit numbers. In the absence of freezing and queries, Typst will ensure that every element gets a unique ID. If you ask for something like query(selector(heading).before(here())), Typst will resolve here() by fetching the ID assigned to the closest surrounding context and then ask the introspection subsystem something like "which headings are before the element with ID 1029845019284509218".

    Now, with freezing my rough idea would be to assign the same IDs across multiple subtrees. This is already what happens today when you re-add a queried element to the document:

    #set heading(numbering: "1.")
    = A <a>  // 1.
    = B      // 2.
    = C      // 3.
    
    #context query(<a>).first() // 1. again!

    In the example above, the query finds the "A" heading that already has an assigned ID and re-adds it to the document. The element retains its ID and for this reason, the counter resolves at the original location.

    However, this is currently shallow. If the heading contains any further elements these again get unique IDs. What I would try to implement both for re-adding and for freezing is to assign the same IDs across the whole subtree. This way, queries would naturally observe the elements in the primary place. (If there are multiple elements with the same ID, the introspection subsystem currently ignores all but the first.)


    Now on to your concrete questions:

    Would secondary occurrences be observed by other queries?

    No. It would show "There are 2 headings!", since the elements with the same ID in secondary place would be ignored.

    [W]ould the link rendered in frozen copies lead to the corresponding location inside that same frozen copy, or to the location in the primary occurrence?

    It would lead to the primary occurrance. This may or may not be desirable... for links probably typically not.

    Would observable differences only occur for queries which depend on the structurally diverged part of the frozen copy or would queries that didn't occur in the primary copy simply ignore freezing altogether?

    i.e. what would query(selector(heading).before(here())) return if my frozen copy contained no relevant headings but did diverge structurally in such a way the query cannot be matched to a query from the primary copy?

    If here() matches up with a location in the primary place, it would return all heading before there. If it didn't, then it would return all headings before the secondary place.


    Now, all of this is just the rough idea. I haven't really tested this concept and it's very possible that the design would need adjustments to work well in practice (e.g. the link thing you mentioned, though I'm not sure how big of a deal it is). That said, it feels to me like the general approach could work out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestintrospectionstyling

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions