I want every math block in my document to be labled automatically. For that, I wrote the following code:
#set heading(numbering: "1.")
#set math.equation(numbering: n => context [
(#counter(heading).get().slice(0, 2).map(str).join(".").#n)
])
#show math.equation.where(block: true): it => [
#let hs = counter(heading).get().slice(0, 2).map(str).join(".")
#let n = counter(math.equation).get().at(0)
#let labelName = "eq:"+hs+"."+str(n)
#it #label(labelName)
#labelName
]
#show heading.where(level: 1): it => [
#it
#context counter(math.equation).update(0)
]
#show heading.where(level: 2): it => [
#it
#context counter(math.equation).update(0)
]
= Test
== First Heading
$a = b$
$ a^2 + b^2 = c^2 $
#lorem(10)
$ a^2 = c^2 - b^2 $
== Second Heading
=== Third heading
Using #ref(label("eq:1.1.2")):
$ a = plus.minus sqrt(c^2 - b^2) $
But the second last line #ref(label("eq:1.1.2")) throws me an error saying “label <eq:1.1.2> does not exist in the document”. I printed the label name to the document to double check and the name exists.
It’s not possible this way because a show rule can’t add a label to an existing element, it is “too late”. What you can do is to use a show rule on ref to change how these references are resolved, and resolve them to the correct equation based on the number. Use str on the label to get its string and parse the string to the equation counter. (It’s been done before, but I didn’t find the previous code for that.)
@a3r do you mind sharing your use case? As @Raul_Durand already mentioned this basically defeates the purpose of Typst’s cross-referencing. If you insert a new equation in the middle of the text all references that follow will be wrong.
The only advantage I came up with for this vs. simply writing the references manually is the automatic linking between the reference and the equation.
Thanks.