List all labels (without reference)

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?

Hi, welcome to the Typst forum!

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.

And to retrieve the list from the command-line: typst query file.typ '<unreferenced-labels>

2 Likes

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)
   │                 ^^^^^

This is also for math.equation, not just figure.

I’m using typst 0.12.0. Any clue?

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!)

I have edited my code to handle this correctly.

1 Like

Alternatively, if you want to do that it’s probably more efficient better from outside Typst.

For people with a Linux environment, it’s probably doable with

grep -Eo '<(.*?)>' doc.typ | sed 's/[<>]//g' | xargs -I {} sh -c "printf {} && grep -o '@{}' doc.typ | wc -c | grep 0"

which will give you all labels with 0 references.

Thanks for your suggestion. I tried that route too, but I have some labels that get generated dynamically, so this wouldn’t work.

1 Like