How do I reset a counter if an element is in the next chapter?

Hello, I am trying to write a custom box for theorems, definitions etc. with a custom counter. Each theorem should be labeled as chapter.subchapter.counter and if either the chapter or the subchapter have gone up, the counter should be reset to 0.
So far I have come up with this code, which does not handle the reset after each (sub-)chapter break but instead counts up indefinitely.

#let thmbox = (body, type: none, title: none) => [
    // Counter
    #let c_thm = counter("definition")
    #let c_herl = counter("herleitung")
    #let c_satz = counter("satz")

    // Get current position in document
    #let chapter = {context counter(heading).get().at(0)}
    #let subchapter = {context counter(heading).get().at(1)}

    // Function that handles styling and counters of thmbox_title
    #let set_thmbox_title = (supplement: none, counter_: none) => [
        #counter_.step()
        #strong[#supplement
            #chapter.#subchapter.#context counter_.display()
        ] (#title)
    ]

    #showybox(
        title: {
            if type == "def" { set_thmbox_title(supplement: "Definition", counter_: c_def) }
            else if type == "herl" { set_thmbox_title(supplement: "Herleitung", counter_: c_herl) }
            else if type == "satz" { set_thmbox_title(supplement: "Satz", counter_: c_satz) }
            else [Nicht definiert]
        },
        frame: (
            title-color: black.lighten(70%),
            border-color: black.lighten(50%),
            body-color: black.lighten(90%),
            radius: 4pt,
        ),
        title-style: (
            color: black,
        ),
        breakable: true,
    )[#body]
]

I tried to extend this as such, but the code doesn’t work:

    #let set_thmbox_title = (supplement: none, counter_: none) => {
        if chapter > last_used_chapter {for c in counters {
            c.update(0)
        }}
        else if subchapter > last_used_subchapter {for c in counter {
            c.update(0)
        }}
    }[
        #counter_.step()
        #strong[#supplement
            #chapter.#subchapter.#context counter_.display()
        ] (#title)
    ]

Hi @engifar, if I understood your requirements correctly, resetting your custom counters at each level 1 or 2 heading, with a show rule, should do what you want.

#show heading.where(level: 1): it => {
  counter("definition").update(0)
  counter("herleitung").update(0)
  counter("satz").update(0)
  it
}
#show heading.where(level: 2): it => {
  ...
}
1 Like

Yes, that was it. Thank you very much :))