How to find number of cited sources / number of Bibliography entries?

Is there a reliable way to determine the number of cited sources with a query or any other way which lets me put that number into a variable? Another way of phrasing the question would be: can I get the count of Bibliography entries?

I can’t directly count them from the BibTeX or YAML files since not all entries in there might be actually cited within the document and the number absolutely has to be accurate in all cases.

I’m aware of the following workaround for getting the amount of sources cited via the @-syntax:

#context query(ref.where(element:none)).len()

but this does not work for sources cited using #cite(). And since #cite() is not locateable I can’t query them.

But there must be a counter which is used for displaying the bibliography entries, but I haven’t found a way to access it from within Typst. (This is where a list of all available elements for counters might help), or is this currently not possible?

You can use typst’s CLI query:

typst query doc.typ ref | jq '[.[] | select(.element == null)] | unique'

This should give you all unique bibliography’s references. If you add a final length, it should give you the count of unique citations in the document, i.e.,

typst query doc.typ ref | jq '[.[] | select(.element == null)] | unique | length'

EDIT: As for cite, you can try a simple

grep "#cite" doc.typ

Unfortunately I can’t use external tools or the CLI. Also in my tests your query-example did not work for sources cited using #cite()

Ah indeed, my bad I think I misread your initial post. As you rightly say so, cite is not locatable. I can’t think of any way to do that entirely in Typst however, that wouldn’t involved using a global show rule and parsing the entire AST.

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

Make sure your title is a question you’d ask to a friend about Typst. :wink:

Maybe try this:

#let citation-counter = state("citation-counter", ())
#show cite: it => {
  it
  bib-count.update(((..c)) => (..c, it.key))
}
#let count = context citation-counter.final().dedup().len()

Edit: fixed typo

1 Like

This works, but you mixed up the variable names :grinning: Here’s the working code for anyone else interested:

#let bib-count = state("citation-counter", ())
#show cite: it => {
  it
  bib-count.update(((..c)) => (..c, it.key))
}
#let count = context bib-count.final().dedup().len()

It still feels like there should be an easier way, but for now I’m marking this as solved. Thanks again!

1 Like