Skip to content

Instantly share code, notes, and snippets.

@YDX-2147483647
Last active July 17, 2025 05:27
Show Gist options
  • Select an option

  • Save YDX-2147483647/4196137b5eaa7779d8ddd114ec5f70fb to your computer and use it in GitHub Desktop.

Select an option

Save YDX-2147483647/4196137b5eaa7779d8ddd114ec5f70fb to your computer and use it in GitHub Desktop.
Make equations numbered by chapters in Typst.
/// Make equations numbered by chapters (heading level 1)
///
/// Only works if headings are numbered.
///
/// # Usage
///
/// ```
/// #show: equation-numbering-rules
/// #set heading(numbering: "1.")
///
/// $ sin x $ <eq:sin>
///
/// @eq:sin
/// ```
///
/// # Credit
///
/// Modified from Anton Wetzel's comment:
/// https://github.com/typst/typst/issues/1768#issuecomment-1921081584
///
/// https://gist.github.com/YDX-2147483647/4196137b5eaa7779d8ddd114ec5f70fb
#let equation-numbering-rules(body) = {
let equation-label(heading, equation) = [(#heading#sym.dash.en#equation)]
// Define the `numbering` of `equation`s
set math.equation(
numbering: equation => locate(
// Locate where we are in the document
loc => {
// Get the heading index at the location at offset 0 for heading level 1
let heading-index = counter(heading).at(loc).at(0)
equation-label(heading-index, equation)
},
),
)
// Overwrite how a `ref` is displayed
show ref: it => {
// Skip if the label has no corresponding element
// or it is not an `equation`.
if it.element == none or it.element.func() != math.equation {
return it
}
locate(
loc => {
// location of the `equation` that the `ref` points to
let equation-location = query(it.target, loc).first().location()
let heading-index = counter(heading).at(equation-location).at(0)
let equation-index = counter(math.equation).at(equation-location).at(0)
it.element.supplement + [ ] + equation-label(heading-index, equation-index)
},
)
}
// Reset `equation`'s counter if a new chapter starts
show heading.where(level: 1): it => {
counter(math.equation).update(0)
// display the heading without changes
it
}
body
}
@YDX-2147483647
Copy link
Author

YDX-2147483647 commented Apr 26, 2024

Example

#import "where-you-save-it.typ": equation-numbering-rules

#set page(width: auto, height: auto)

#show: equation-numbering-rules

// Only works if headings are numbered.
#set heading(numbering: "1.")

$ sin x $ <eq:sin>

@eq:sin is the sine function.

= Chapter

$ cos x $

@YDX-2147483647
Copy link
Author

YDX-2147483647 commented Apr 26, 2024

Alternatives

Relevant issues

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