Skip to main content

mini_cite/
lib.rs

1//! BibTeX-backed inline citations and footnotes for Markdown.
2//!
3//! Pairs a directory of `.bib` files with `[@key]`-style inline citations in a
4//! Markdown body, rewriting each citation into a numbered footnote reference and
5//! appending a matching footnote block.
6//!
7//! ```no_run
8//! # fn main() -> Result<(), mini_cite::CiteError> {
9//! let bibliography = mini_cite::Bibliography::load_dir("bib")?;
10//! let style = mini_cite::CiteStyle::default();
11//! let html = mini_cite::process("Small things matter [@smith2020].", &bibliography, &style)?;
12//! # Ok(())
13//! # }
14//! ```
15//!
16//! The emitted classes and the back-link's glyph are configurable through
17//! [`CiteStyle`]; the markup's structure and its `fn-N`/`fnref-N` ids are not.
18
19mod bibliography;
20mod format;
21mod parser;
22mod rewrite;
23mod style;
24
25use std::fmt;
26use std::path::PathBuf;
27
28pub use bibliography::Bibliography;
29pub use format::format_citation;
30pub use parser::{parse_entries, Entry};
31pub use rewrite::rewrite;
32pub use style::CiteStyle;
33
34use style::class_attr;
35
36/// Errors that can occur while loading a bibliography or processing citations.
37///
38/// This error type is non-exhaustive and may gain new variants in future releases.
39///
40/// # Variants
41///
42/// - `Parse`: a `.bib` file's contents are malformed. `file` is `None` when the
43///   parser was handed a string directly rather than a file on disk.
44/// - `DuplicateKey`: one citation key is defined by two `.bib` files in the same
45///   directory, so which entry a citation refers to is ambiguous.
46/// - `UnknownCitation`: a `[@key]` citation names a key no loaded `.bib` file defines.
47/// - `Io`: a `.bib` file or its directory could not be read.
48#[derive(Debug)]
49#[non_exhaustive]
50pub enum CiteError {
51    /// Malformed `.bib` contents. `file` is `None` when parsing a bare string.
52    Parse {
53        /// The `.bib` file the malformed content came from, when it came from one.
54        file: Option<PathBuf>,
55        /// What was malformed.
56        message: String,
57    },
58    /// One citation key defined by two files in the same bibliography directory.
59    DuplicateKey {
60        /// The key defined twice.
61        key: String,
62        /// The file that defined it first.
63        first_file: PathBuf,
64        /// The file that redefined it.
65        second_file: PathBuf,
66    },
67    /// A citation naming a key no loaded `.bib` file defines.
68    UnknownCitation {
69        /// The undefined key, as written in the citation.
70        key: String,
71    },
72    /// A `.bib` file or bibliography directory could not be read.
73    Io {
74        /// The path that could not be read.
75        path: PathBuf,
76        /// The underlying I/O failure.
77        source: std::io::Error,
78    },
79}
80
81impl fmt::Display for CiteError {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            CiteError::Parse {
85                file: Some(path),
86                message,
87            } => write!(f, "invalid bibtex in {}: {message}", path.display()),
88            CiteError::Parse {
89                file: None,
90                message,
91            } => write!(f, "invalid bibtex: {message}"),
92            CiteError::DuplicateKey {
93                key,
94                first_file,
95                second_file,
96            } => write!(
97                f,
98                "citation key `{key}` defined in both {} and {}",
99                first_file.display(),
100                second_file.display()
101            ),
102            CiteError::UnknownCitation { key } => {
103                write!(f, "no bibtex entry for citation key `{key}`")
104            }
105            CiteError::Io { path, source } => {
106                write!(f, "could not read {}: {source}", path.display())
107            }
108        }
109    }
110}
111
112impl std::error::Error for CiteError {
113    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
114        match self {
115            CiteError::Io { source, .. } => Some(source),
116            _ => None,
117        }
118    }
119}
120
121/// Result alias for fallible `mini-cite` operations.
122pub type Result<T> = std::result::Result<T, CiteError>;
123
124/// Separates the appended footnote block from the body it follows.
125///
126/// CommonMark only begins a new raw-HTML block after a blank line. Without this
127/// separator the appended markup is parsed as trailing inline HTML on the document's
128/// last paragraph instead of standing as its own block.
129const FOOTNOTE_BLOCK_SEPARATOR: &str = "\n\n";
130
131/// Rewrites every `[@key]` citation in `body` into a numbered footnote reference and
132/// appends the matching footnote block.
133///
134/// Citations are numbered by first appearance, and a key cited more than once keeps
135/// its first number rather than claiming a second footnote. Citations written inside
136/// fenced code blocks or inline code spans are left exactly as they appear.
137///
138/// A body containing no citations is returned unchanged, byte for byte — no
139/// separator, no empty footnote block.
140///
141/// The returned string is Markdown with raw HTML embedded in it, not finished HTML:
142/// the caller still renders it. The emitted markup uses only `<sup>`, `<a>`, `<hr>`,
143/// `<ol>`, and `<li>` with `id`/`href`/`class` attributes. A default-policy `ammonia`
144/// clean keeps the elements and the ids but drops the classes — see [`CiteStyle`].
145///
146/// `style` names the emitted classes and the back-link's label;
147/// [`CiteStyle::default()`] is the plain choice.
148///
149/// # Errors
150///
151/// Returns [`CiteError::UnknownCitation`] on the first citation naming a key
152/// `bibliography` does not define.
153pub fn process(body: &str, bibliography: &Bibliography, style: &CiteStyle) -> Result<String> {
154    let (rewritten, cited_keys) = rewrite(body, bibliography, style)?;
155
156    if cited_keys.is_empty() {
157        debug_assert_eq!(rewritten, body, "a body with no citations must not change");
158        return Ok(rewritten);
159    }
160
161    Ok(rewritten + FOOTNOTE_BLOCK_SEPARATOR + &footnote_block(&cited_keys, bibliography, style))
162}
163
164/// Renders the ordered footnote list for `cited_keys`.
165///
166/// Every key is already known to resolve — [`rewrite`] fails before returning a key
167/// the bibliography does not define — so a lookup miss here is an internal
168/// inconsistency, not user input, and falls back to the bare key rather than failing
169/// a build over an unreachable state.
170fn footnote_block(cited_keys: &[String], bibliography: &Bibliography, style: &CiteStyle) -> String {
171    let item_class = class_attr(&style.item_class);
172    let backlink_class = class_attr(&style.backlink_class);
173    let label = &style.backlink_label;
174
175    let items = cited_keys
176        .iter()
177        .enumerate()
178        .map(|(index, key)| {
179            let number = index + 1;
180            let citation = match bibliography.get(key) {
181                Some(entry) => format_citation(key, entry),
182                None => key.clone(),
183            };
184            format!(
185                r##"<li id="fn-{number}"{item_class}>{citation} <a href="#fnref-{number}"{backlink_class}>{label}</a></li>"##
186            )
187        })
188        .collect::<Vec<_>>()
189        .join("\n");
190
191    let separator_class = class_attr(&style.separator_class);
192    let list_class = class_attr(&style.list_class);
193
194    format!("<hr{separator_class}>\n<ol{list_class}>\n{items}\n</ol>")
195}