Skip to content

Ergonomic numbering-by-section #1896

Open

Description

@damaxwell

Description

It's pretty standard to have equations/figures/tables/etc in academic work numbered by section or by chapter (i.e. the 23rd equation of section 5 is equation (5.23) ). While Typst makes a lot of things easier than the competition, arranging for numbering by section currently has a lot of friction. Ad-hoc solutions are starting to appear, but with varying amounts of fragility. It seems like numbering-by-section is a feature that should be built in to Typst, and easy to use out-of-the box.

This feature request is meant to less than an RFC, but a home for discussing solutions that might improve the user experience. In a perfect world, something like

set math.equation( numbering: "({h1}.1))", supplement: none)

would be enough to get equation numbers numbered by section, in parentheses, and at the same time have a reference @profound-eq yield (5.23) for equation 23 of section 5.

To make number-by-section happen currently for equations:

  1. A show rule for heading needs to be established to resent the equation counter when a new level 1 heading begins.
  2. A custom numbering function needs to be assigned to math.equation. Because numbering functions only receive counter values and no other info, the numbering function can only add the section number based on its call site using location. Also, the numbering function needs to be careful to format the section number so that if appendix numbering by A, B, C begins, then this is correctly detected, and so that if subsections aren't numbered we don't accidentially pick up a null numbering function if we forget to seek level 1 sections. I've seen both these bugs in the wild.
  3. Simultaneously, a show rule for ref (with nontrivial logic because of a null test and a type check) that gets along with the element function's numbering function needs to be set up. Because the numbering function for math.equation is location sensitive, it can't be fully recycled here and it seems like the ref show rule has to know separately the details of numbering by section. Shared code could be refactored, of course, but the point is the complexity.

All this can be made to work, but I hope this is just a temporary solution as Typst matures.

One could imagine a Gadget, managing a counter for an element function, that does the following kinds of tasks:

  1. Responds to a hook for updating the element's counter prior to an automatic bump. There is a hook already, the Count trait, but it's only available from rust. For numbering by section, the Gadget can look into the past to the last time the counter it manages was updated, grab the section number then, compare it to the section number now, and reset the managed counter if need be. The hook could also have greater responsibility, maybe replacing the Count trait, perhaps.
  2. Is responsible, given a location, for formatting the counter at that location. It can, e.g, look into the past for the last level 1 heading, use the heading's Gadget to format the heading counter at the past location, and then use the result in the formatting of the equation's number.
  3. Is the authority that references use (by default) for for formatting. The Gadget feels like the place that knows how references should be formatted; let it tell the references it's opinion on the subject.

I'm being deliberately vague about what a Gadget is. It could just be a few properties of an element function that are auto by default and are sensibly synthesized and wired-up based on a string "({h1}.1}" if needed. But it seems like it could be helpful to have a layer of abstraction sitting above or augmenting the current numbering mechanism.

Use Case

See above.

Activity

  1. added
    feature request
    on Aug 9, 2023
  2. DrGo commented on Aug 9, 2023

    @DrGo

    Agree that numbering of elements is ideally handled by the compiler. But wondering why it should be limited to equations as compared to other elements, e.g., figures, tables etc

  3. damaxwell commented on Aug 9, 2023

    @damaxwell
    ContributorAuthor

    I had meant equations only as a concrete example. Same mechanism, whatever it is, for figures (and their theorem cousins) etc.

  4. KronosTheLate commented on Sep 14, 2023

    @KronosTheLate
    Contributor

    +1 on this, would love numbering by section!

  5. added
    model
    and removed on Nov 24, 2023
  6. memeplex commented on Mar 19, 2024

    @memeplex

    As a workaround, I've been doing this for some simple documents. It's probably not perfect and my understanding of the problem is very limited compared to OP's, but seems to be working fine with references and doesn't require to explicitly deal with location or other context.

    #show heading: counter(math.equation).update(0)
    #set math.equation(numbering: num =>
      "(" + (counter(heading).get() + (num,)).map(str).join(".") + ")")
  7. laurmaedje commented on Mar 19, 2024

    @laurmaedje
    Member

    Yes, that this now works properly is actually new in 0.11 because the correct context for counter(heading).get() is provided to the numbering!

  8. memeplex commented on Mar 19, 2024

    @memeplex

    Great, it's impressive how easy it is to extend Typst.

    Is this because of what's mentioned in https://typst.app/docs/reference/context/ ?

    context is also established implicitly in some places that are also aware of their location in the document: show rules and numberings in the outline, for instance, also provide the proper context to resolve counters.

    It confused me at first that I didn't have to provide a context, even though the numbering function is for math.equation but the requested counter is for heading. So are all numbering arguments ultimately evaluating the numbering() function inside a context?

  9. laurmaedje commented on Mar 19, 2024

    @laurmaedje
    Member

    So are all numbering arguments ultimately evaluating the numbering() function inside a context?

    Exactly. The numbering functions are implicitly provided with the location in the document of the element in question, so that you can retrieve all sorts of counters there.

  10. PhyX-Meow commented on Apr 5, 2024

    @PhyX-Meow

    As a workaround, I've been doing this for some simple documents. It's probably not perfect and my understanding of the problem is very limited compared to OP's, but seems to be working fine with references and doesn't require to explicitly deal with location or other context.

    #show heading: counter(math.equation).update(0)
    #set math.equation(numbering: num =>
      "(" + (counter(heading).get() + (num,)).map(str).join(".") + ")")

    You should use

    #show heading: it => {
      counter(math.equation).update(0)
      it
    }
    #set math.equation(numbering: num =>
      "(" + (counter(heading).get() + (num,)).map(str).join(".") + ")")

    Otherwise the heading itself will disappear.

  11. KronosTheLate commented on May 21, 2024

    @KronosTheLate
    Contributor

    Starting from suggestions in this thread and some hacking about (and importantly realizing that figures have one global counter and one counter based on the kind of figure) I was able to put this together:

    show heading.where(level: 1): it => {
        counter(math.equation).update(0)
        counter(figure.where(kind: image)).update(0)
        counter(figure.where(kind: table)).update(0)
        counter(figure.where(kind: raw)).update(0)
        it
      }
      set math.equation(numbering: num => 
        "(" + (str(counter(heading).get().at(0)) + "." + str(num)) + ")"
      )
      set figure(numbering: num => 
        str(counter(heading).get().at(0)) + "." + str(num)
      ) 

    Improvements upon previous suggestions:

    • Works not only for equations, but also all 3 default kinds of figure
    • Shows only the topmost heading level, as opposed to resetting the counter for sections of any depth
  12. Andrew15-5 commented on May 21, 2024

    @Andrew15-5
    Contributor

    Here is a bit more optimized version (although I haven't tested it):

    #show heading.where(level: 1): it => {
      counter(math.equation).update(0)
      counter(figure.where(kind: image)).update(0)
      counter(figure.where(kind: table)).update(0)
      counter(figure.where(kind: raw)).update(0)
      it
    }
    #set math.equation(numbering: (..num) =>
      numbering("(1.1)", counter(heading).get().first(), num.pos().first())
    )
    #set figure(numbering: (..num) =>
      numbering("1.1", counter(heading).get().first(), num.pos().first())
    )
  13. Joelius300 commented on May 30, 2024

    @Joelius300

    i-figured seems to be an implementation of this (using nested figures) as Typst Package (see in universe).

  14. snaggen commented on Sep 5, 2024

    @snaggen

    I just want to point out that the above workarounds (and also the i-figured package, I think) will not correctly handle the case where you have regular chapters with "1" numbering, and then appendixes with "A" numbering. Figures in Appendixes should be referred to as A.1, but will instead be something like 8.1. So, it is important to use the actual heading number as displayed.

  15. Joelius300 commented on Sep 5, 2024

    @Joelius300

    I just want to point out that the above workarounds (and also the i-figured package, I think) will not correctly handle the case where you have regular chapters with "1" numbering, and then appendixes with "A" numbering. Figures in Appendixes should be referred to as A.1, but will instead be something like 8.1. So, it is important to use the actual heading number as displayed.

    i-figured can handle that just fine, if you pass it to the respective show-figure call. I used A.i numbering for figures in the appendix and regular chapters with 1 numbering. The eq thing is a workaround to apply the same thing to equations because I didn't figure out how to get i-figured to correctly number equations, it seemed to skip around weirdly. I can talk more about that if you want.

    // Restart heading numberings at A.i
    #let appendix-numbering = "A.i"
    #set heading(numbering: appendix-numbering, supplement: "Appendix")
    #counter(heading).update(0)
    
    // Make sure i-figured also uses the same numbering scheme as the Appendix headings
    #show figure: i-figured.show-figure.with(extra-prefixes: ("eq": "eq:"), numbering: appendix-numbering)
    #show math.equation: i-figured.show-equation.with(numbering: appendix-numbering)
    
    #include "chapters/99_appendix.typ"
  16. svandenhaute commented on Sep 12, 2024

    @svandenhaute

    Does anyone have an idea how to also modify the formatting of the caption when using custom numbering with the approach suggested earlier?
    I'd prefer to use the following show rule to format captions but this seems to mess with the numbering. Any idea what's going on?

      // this works without additional caption show rules
      #set figure(numbering: num =>
        str(counter(heading).get().at(0)) + "." + str(num)
      )
    
    
      #show figure.caption: it => {
        block(
          width: 90%,
          spacing: 0.9em,
          grid(
            columns: (auto, 1fr),
            gutter: 1.5mm,
            align: top + left,
            text(10pt, font: "linux biolinum", weight: 700,
              it.supplement + " " + it.counter.display(it.numbering) + ":"),  // this doesn't work for getting e.g. 1.1, 3.4
            par(leading: 0.3em, text(10pt, font: "linux biolinum", it.body))
          )
        )
      }
    

    my guess is that show rules don't always receive location context?

  17. 34j commented on Dec 14, 2024

    @34j
    #{
      show heading.where(level: 1): it => {
        counter(math.equation).update(0)
        counter(figure.where(kind: image)).update(0)
        counter(figure.where(kind: table)).update(0)
        counter(figure.where(kind: raw)).update(0)
        it
      }
      set math.equation(numbering: num =>
        numbering("(1.1)", counter(heading).get().first(), num)
      )
      set figure(numbering: num =>
        numbering("1.1", counter(heading).get().first(), num)
      )
    }

    I would just like to say that the advantage of this method over i-figured is that it is compatible with equate (numbering per line).

    #import "@preview/equate:0.2.1": equate
    #show: equate.with(breakable: true, sub-numbering: false)
    Minimal Example
    #import "@preview/equate:0.2.1": equate
    #set page(paper: "a9", flipped: true)
    #set heading(numbering: "1.1")
    #show heading.where(level: 1): it => {
      counter(math.equation).update(0)
      counter(figure.where(kind: image)).update(0)
      counter(figure.where(kind: table)).update(0)
      counter(figure.where(kind: raw)).update(0)
      it
    }
    #set math.equation(numbering: num =>
      numbering("(1.1)", counter(heading).get().first(), num)
    )
    #set figure(numbering: num =>
      numbering("1.1", counter(heading).get().first(), num)
    )
    #show: equate.with(breakable: true, sub-numbering: false)
    
    = section
    = another section
    $
      0 &= 1 - 1\
      &= 2 - 2
    $

    Example

  18. Andrew15-5 commented on Dec 14, 2024

    @Andrew15-5
    Contributor

    I need to point out that num => won't always work elsewhere, because of #2102, https://typst.app/docs/reference/model/numbering/.

    It's a best practice to stay consistent and write a numbering callback function like this:

    #set heading(numbering: "1.")
    #set figure(numbering: (n, ..) => {
      numbering("1.1", counter(heading).get().first(), n)
    })
  19. uwni commented on Jan 12, 2025

    @uwni
    Contributor

    How do you customise the caption while using this trick? for example, if I want the supplement and numbering part get italic or bold. A normal way is to make something like [*#it.supplement~#it.numbering~#it.separator* it.body]

  20. Andrew15-5 commented on Jan 12, 2025

    @Andrew15-5
    Contributor
    #set heading(numbering: "1.1")
    #set math.equation(numbering: (n, ..) => {
      numbering("(1.1)", counter(heading).get().first(), n)
    })
    #set figure(numbering: (n, ..) => {
      numbering("1.1", counter(heading).get().first(), n)
    })
    
    #show figure.caption: it => {
      let pattern = "^[^:]+" + sym.space.nobreak + "[\d.]+"
      show regex(pattern): strong
      show regex(pattern): emph
      // show regex(pattern): set text(weight: "bold")
      // show regex(pattern): set text(style: "italic")
      it
    }
    #show heading.where(level: 1): it => {
      counter(math.equation).update(0)
      counter(figure.where(kind: image)).update(0)
      counter(figure.where(kind: table)).update(0)
      counter(figure.where(kind: raw)).update(0)
      it
    }
    
    = Section
    
    #figure(rect[1], caption: [Rectangle 1])
    
    #figure(rect[2], caption: [Rectangle 2])
    
    = Section
    == Subsection
    == Subsection
    == Subsection
    
    #figure(rect[1], caption: [Rectangle 1])
    
    #figure(rect[2], caption: [Rectangle 2 Figure~2.2: test])

    image

  21. patrick-kidger commented on Nov 27, 2025

    @patrick-kidger

    For those who need a general solution to this problem, let me x-post from #2652 (comment):


    I've made tree-counters in typsy, and usable like so:

    #import "@preview/typsy:0.2.1": tree-counter
    
    // Set up counters
    // These `()=>{}` are a trick for generating unique counters.
    #let heading-counter = tree-counter(heading, level: 1)
    #let theorem-counter = (heading-counter.subcounter)(()=>{})
    #let corollary-counter = (theorem-counter.subcounter)(()=>{})
    
    // Usage
    #set heading(numbering: "1")
    #let theorem(doc) = [Theorem #(theorem-counter.take)(): #doc]
    #let corollary(doc) = [Corollary #(corollary-counter.take)(): #doc]
    
    = First Section
    #theorem[Let ...]  // Theorem 1.1: Let ...
    #theorem[Let ...]  // Theorem 1.2: Let ...
    #corollary[Let ...] // Corollary 1.2.1: Let ...
    = Second Section
    #theorem[Let ...] // Theorem 2.1: Let ...
  22. mohe2015 commented on Dec 23, 2025

    @mohe2015

    @patrick-kidger Can you show an example with automatic per-chapter figure numbering where ref does not increase the counter?

  23. kyzyl commented on Jul 31, 2026

    @kyzyl

    So I can't tell from the discussion above, what is the status of this feature as of mid 2026? Are we still supposed to DIY hack it ourselves? Is the typst team working on integrating a real solution? I've tried most of the solutions above, and packages like i-figured/equate/etc. As far as I can tell, none of the solutions actually work. I can't get controlled depth, per-section table/figure/equation numbering, with per-line labelling.

    Scientific literature really needs to be able to break stuff up by section, and authors need to be able to reference into equation blocks line-by-line. Per-block numbering lumps potentially many complicated expressions into one reference, and splitting each line into separate blocks has very poor ergonomics while breaking alignment and other things.

    The equate package solves the per-line labelling, but break per-section/sub-section numbering. I'm pretty new to typst scripting, but in my experiences thus far that applies even when attempting to extend equate with various hacks people have suggested.

    The i-figured package solves the per-section numbering, but is incompatible with equate. It's a similar story with other packages. Hacking it together myself similar to solutions above also has not been successful for me. There is always a couple of elements which don't quite work right, and it's hard to figure out why.

    It's going to be impossible for advocates to get their academic colleagues to adopt typst if stuff like this doesn't work. It's table stakes, no pun intended. I might as well be suggesting that they switch to emacs+org-mode+tangle+elisp. People don't want to configure their environment, they want to write their paper, and they are already behind on that.

    Anyhow sorry to complain. It's just frustrating when a tool solves a lot of your problems, but is then just out of reach for practical use. Hope this can get solved soon.

  24. mohe2015 commented on Jul 31, 2026

    @mohe2015

    @kyzyl Can you try https://typst.app/universe/package/numera/ please?
    I invested lots of time to try to fix the problems you mentioned and would be interested in feedback.

  25. jbirnick commented on Aug 1, 2026

    @jbirnick
    Contributor

    Also have a look at rich-counters. If you need theorems you can combine it with great-theorems. (I also wish there was a native solution though.)

  26. kyzyl commented on Aug 1, 2026

    @kyzyl

    @mohe2015 I did try it. It's a bit hard to tell if I'm using it wrong since I can only extrapolate from the examples, but like the other packages it seems to almost do the job. Take the following example:

    #import "@preview/equate:0.3.3": equate
    #import "@preview/numera:0.0.1": (
      display-numbering,
      get-numbering,
      my-numbering,
      normal-figure,
      numera
    )
    #set heading(numbering: "1.1")
    #set math.equation(supplement: "Eq.")
    #set figure(supplement: "Fig.")
    
    #show: equate.with(sub-numbering: false, number-mode: "line")
    #show: numera(level: 2)
    
    // Begin incantations.
    #show normal-figure: set figure(numbering: (ref: false, ..nums) => {
      let heading = display-numbering(heading, ref: ref)
      if heading != none {
        heading += "."
      }
      heading + my-numbering("1", ref: ref, ..nums)
    })
    
    #set math.equation(numbering: (ref: false, ..nums) => {
      let heading = display-numbering(heading, ref: ref)
      if heading != none {
        heading += "."
      }
      "(" + heading + my-numbering("1", ref: ref, ..nums) + ")"
    })
    // End incantations.
    
    = Chapter1
    See equations @eq1.1, @eq1.2, @eq1.3, @eq1.4, @eq1.5, @eq1.6, @eq1.7, @eq1.8
    
    See figures @fig1.1, @fig1.2, @fig1.3, @fig1.4, @fig1.5, @fig1.6, @fig1.7, @fig1.8
    
    Particular equation line: @this-line
    
    $ 
    E = m c^2 #<eq1.1> \
    F = m a #<this-line>
    $
    $ E = m c^2 $ <eq1.2>
    #figure("Content", caption: "About this content.") <fig1.1>
    #figure("Content", caption: "About this content.") <fig1.2>
    
    == Section1.1
    $ E = m c^2 $ <eq1.3>
    $ E = m c^2 $ <eq1.4>
    #figure("Content", caption: "About this content.") <fig1.3>
    #figure("Content", caption: "About this content.") <fig1.4>
    
    == Section1.2
    $ E = m c^2 $ <eq1.5>
    $ E = m c^2 $ <eq1.6>
    #figure("Content", caption: "About this content.") <fig1.5>
    #figure("Content", caption: "About this content.") <fig1.6>
    
    === Section1.2.1
    $ E = m c^2 $ <eq1.7>
    $ E = m c^2 $ <eq1.8>
    #figure("Content", caption: "About this content.") <fig1.7>
    #figure("Content", caption: "About this content.") <fig1.8>
    
    
    = Chapter2
    See equations @eq2.1, @eq2.2, @eq2.3, @eq2.4
    
    See figures @fig2.1, @fig2.2, @fig2.3, @fig2.4
    
    $ E = m c^2 $ <eq2.1>
    $ E = m c^2 $ <eq2.2>
    #figure("Content", caption: "About this content.") <fig2.1>
    #figure("Content", caption: "About this content.") <fig2.2>
    
    == Section2.1
    $ E = m c^2 $ <eq2.3>
    $ E = m c^2 $ <eq2.4>
    #figure("Content", caption: "About this content.") <fig2.3>
    #figure("Content", caption: "About this content.") <fig2.4>
    

    From my perspective, here is what it does correctly and is useful:

    • Figures and equations are numbered per-subsection
    • Using equate mostly works, allowing per-line labelling
    • I can control the level at which equation/figure counters are reset
    • I can change specific numbering to other formats like i/ii/iii, I/II/III, A/B/C, a/b/c, etc.

    And here is what isn't that useful or doesn't quite work:

    • Multipart figures. This might just be me or my field, but I've never needed this. Typically we just have all sub-figures in a single image and reference it like "As shown in @figure-blah (a), the resonance splitting is...". I can't think of a time where parts of figures would make sense automatically reordered, so once you have a stable way to refer to the figure you're done.
    • The level argument seems to only control the level at which the counters reset, not the prefixing level. In the example above with level: 2 I would expect the numbering to proceed (1.1), (1.2), (1.3), (1.1.1), (1.1.2), (1.2.1), (1.2.2), (1.2.3), (1.2.4), (2.1), ... Instead it resets the counter at level 2 but keeps the level 3 prefix 1.2.1.x. I can't think of a time where I don't want to fully number down to level 3, but I DO want to keep contiguous numbers for levels 3+. That seems like it would be a confusing paper to read.
    • Similarly, I would expect that entering level: 0 essentially means "no sub-numbering, just one contiguous count". Instead of (1), (2), (3), ... through all sub-sections, I get a contiguous count up but the prefixes stay (1.1), (1.2), ..., (1.2.1.8), etc. It's very common to need per-section numbering down to arbitrary levels (think numbering in a textbook), but it's also very common to decide to just have equations numbered sequentially in a short paper.
    • To get the right (#) formatting, I had to add explicit "(" and ")" to the incantations section. It seems like it should be a parameter as with math.equation(numbering: "(1)" ...). Moreover, having done that, those parentheses now appear in the references "Eq. (1.1)" meanwhile someone only want the parentheses in the margins, while the references read like "Eq. 1.1".
    • If I don't modify the incantations as above, I get strange numbering "1.1.(2)" and so forth.
    • If I use equate sub-numbering: true, I get strange labels like starting with (1.11), (1.12), (2). I suppose this is just a bad interaction between the packages but it is a bit confusing.
    • Ideally the stuff in the incantations section wouldn't exist. Not the end of the world but as a user who is not involved in the inner workings of the package it's hard to understand what is happening or what to change. Adding the parentheses being a good example. It seems like whatever parameters are being injected there ought to be going in the #show numera(level: 2, ...) block.

    In any case, thanks for the effort. It's probably as close as any solution has come :) I also maintain that this stuff really should be handled in Typst core, with sane defaults that can be overridden. 99.99% of users will not pursue a solution the folks in this thread have, they will just bail.

    @jbirnick I haven't checked out rich-counters yet. After a cursory look it isn't obvious how to apply it to get the behaviour I've described but I'll think about it.

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 requestmodel

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions