Is there a way to list all labels without a reference? For example, using typst query? I would like to have a shell script that checks if my document contains figures that are not yet referenced in the text. Otherwise, just some scripting in the text is fine too.
If you have a list of all labels in the documents, you could probably use parts of the code example from the Typst examples book. So is there a way to list all labels in the document?
I don’t think there’s a way to get all labels, but you can query for all elements of a particular type and see which label they have, so you can do something like this:
#set math.equation(numbering: "1.")
#let check-labels() = context {
let targets = query(ref).map(x => x.target)
let unreferenced = query(selector.or(
figure,
math.equation,
// ... add other referencable elements here
)).map(x => x.at("label", default: none))
.filter(x => x != none and x not in targets)
if unreferenced.len() > 0 {
set text(red)
[
Unreferenced labels: #unreferenced.map(str).join(", ").
#metadata(unreferenced)<unreferenced-labels>
]
}
}
#check-labels()
$ x $<eq1>
$ y $<eq2>
$ z $<eq3>
See @eq2.
Woow, that looks awesome! Thanks, it errors for me though, with the error “internal error when accessing field “label” in figure – this is a bug”. Full error:
error: internal error when accessing field "label" in figure – this is a bug
┌─ thesis.typ:54:16
│
54 │ )).map(x => x.label).filter(x => x != none and x not in targets)
│ ^^^^^
It seems that equations have a label field even when no label is defined (so it was working in my example) but figures not. (Edit: ah no I just hadn’t tested the case without label!)