tinymist_query/
bib.rs

1use hayagriva::{
2    BibliographyDriver, BibliographyRequest, BufWriteFormat, CitationItem, CitationRequest,
3    ElemChildren,
4};
5
6use crate::analysis::BibInfo;
7
8pub(crate) struct RenderedBibCitation {
9    pub citation: String,
10    pub bib_item: String,
11}
12
13/// Render the citation string in the bib with given CSL style.
14pub(crate) fn render_citation_string(
15    bib_info: &BibInfo,
16    key: &str,
17    support_html: bool,
18) -> Option<RenderedBibCitation> {
19    let entry = bib_info.entries.get(key)?;
20    let raw_entry = entry.raw_entry.as_ref()?;
21
22    let mut driver = BibliographyDriver::new();
23
24    let locales = &[];
25    driver.citation(CitationRequest::from_items(
26        vec![CitationItem::with_entry(raw_entry)],
27        bib_info.csl_style.get(),
28        locales,
29    ));
30
31    let result = driver.finish(BibliographyRequest {
32        style: bib_info.csl_style.get(),
33        locale: None, // todo: get locale from CiteElem
34        locale_files: locales,
35    });
36    let rendered_bib = result.bibliography?;
37
38    let format_elem = |elem: &ElemChildren| {
39        let mut buf = String::new();
40        elem.write_buf(
41            &mut buf,
42            if support_html {
43                BufWriteFormat::Html
44            } else {
45                BufWriteFormat::Plain
46            },
47        )
48        .ok()?;
49        Some(buf)
50    };
51
52    Some(RenderedBibCitation {
53        citation: format_elem(&result.citations.first()?.citation)?,
54        bib_item: format_elem(&rendered_bib.items.first()?.content)?,
55    })
56}