How to get the current header depth?

I’m interested in creating a function that can insert a ‘template’, such that:

= Hello
#template()
== there
#template()

would ultimately act something like this:

= Hello
== template header
template content

== there
=== template header
template content

I thought about using context but ran into difficulties. I feel like I’m missing something obvious, so forgive my ignorance!

Hey @kaimera, welcome to the forum! I’ve changed your question post’s title to better fit our guidelines: How to post in the Questions category

For future posts, please make sure your title is a question you’d ask to a friend about Typst. Also, don’t forget to add some tags related to your post! :wink:

You should be using query() to retrieve the latest heading. It does ultimately require being in a context block, but in general you will only add the context block around the code where you actually need that information, so no need to be too hasty with it. In other words, don’t write let x = context { query() }; let y = func(x); y as you wouldn’t be able to access what query() returns (This would be an error); write context { let x = query(); let y = func(x); y } instead.

Here’s a full example:

#let template() = context {
  let headings = query(selector(heading).before(here()))
  let level = if headings.len() > 0 { headings.last().level } else { 0 }
  heading(level: level + 1)[Template title]
  [Some more stuff]
}

// Demo
#set heading(numbering: "1.")

#outline()

= My heading
#template()

== Other heading
#template()

(Note: you should set heading(depth: ...) instead of level if you’d like to use #set heading(offset: ...) later.)

1 Like