mini-cite 0.2.0

BibTeX-backed inline citations and footnotes for the mini-* family.
Documentation
//! BibTeX-backed inline citations and footnotes for Markdown.
//!
//! Pairs a directory of `.bib` files with `[@key]`-style inline citations in a
//! Markdown body, rewriting each citation into a numbered footnote reference and
//! appending a matching footnote block.
//!
//! ```no_run
//! # fn main() -> Result<(), mini_cite::CiteError> {
//! let bibliography = mini_cite::Bibliography::load_dir("bib")?;
//! let style = mini_cite::CiteStyle::default();
//! let html = mini_cite::process("Small things matter [@smith2020].", &bibliography, &style)?;
//! # Ok(())
//! # }
//! ```
//!
//! The emitted classes and the back-link's glyph are configurable through
//! [`CiteStyle`]; the markup's structure and its `fn-N`/`fnref-N` ids are not.

mod bibliography;
mod format;
mod parser;
mod rewrite;
mod style;

use std::fmt;
use std::path::PathBuf;

pub use bibliography::Bibliography;
pub use format::format_citation;
pub use parser::{parse_entries, Entry};
pub use rewrite::rewrite;
pub use style::CiteStyle;

use style::class_attr;

/// Errors that can occur while loading a bibliography or processing citations.
///
/// This error type is non-exhaustive and may gain new variants in future releases.
///
/// # Variants
///
/// - `Parse`: a `.bib` file's contents are malformed. `file` is `None` when the
///   parser was handed a string directly rather than a file on disk.
/// - `DuplicateKey`: one citation key is defined by two `.bib` files in the same
///   directory, so which entry a citation refers to is ambiguous.
/// - `UnknownCitation`: a `[@key]` citation names a key no loaded `.bib` file defines.
/// - `Io`: a `.bib` file or its directory could not be read.
#[derive(Debug)]
#[non_exhaustive]
pub enum CiteError {
    /// Malformed `.bib` contents. `file` is `None` when parsing a bare string.
    Parse {
        /// The `.bib` file the malformed content came from, when it came from one.
        file: Option<PathBuf>,
        /// What was malformed.
        message: String,
    },
    /// One citation key defined by two files in the same bibliography directory.
    DuplicateKey {
        /// The key defined twice.
        key: String,
        /// The file that defined it first.
        first_file: PathBuf,
        /// The file that redefined it.
        second_file: PathBuf,
    },
    /// A citation naming a key no loaded `.bib` file defines.
    UnknownCitation {
        /// The undefined key, as written in the citation.
        key: String,
    },
    /// A `.bib` file or bibliography directory could not be read.
    Io {
        /// The path that could not be read.
        path: PathBuf,
        /// The underlying I/O failure.
        source: std::io::Error,
    },
}

impl fmt::Display for CiteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CiteError::Parse {
                file: Some(path),
                message,
            } => write!(f, "invalid bibtex in {}: {message}", path.display()),
            CiteError::Parse {
                file: None,
                message,
            } => write!(f, "invalid bibtex: {message}"),
            CiteError::DuplicateKey {
                key,
                first_file,
                second_file,
            } => write!(
                f,
                "citation key `{key}` defined in both {} and {}",
                first_file.display(),
                second_file.display()
            ),
            CiteError::UnknownCitation { key } => {
                write!(f, "no bibtex entry for citation key `{key}`")
            }
            CiteError::Io { path, source } => {
                write!(f, "could not read {}: {source}", path.display())
            }
        }
    }
}

impl std::error::Error for CiteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CiteError::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Result alias for fallible `mini-cite` operations.
pub type Result<T> = std::result::Result<T, CiteError>;

/// Separates the appended footnote block from the body it follows.
///
/// CommonMark only begins a new raw-HTML block after a blank line. Without this
/// separator the appended markup is parsed as trailing inline HTML on the document's
/// last paragraph instead of standing as its own block.
const FOOTNOTE_BLOCK_SEPARATOR: &str = "\n\n";

/// Rewrites every `[@key]` citation in `body` into a numbered footnote reference and
/// appends the matching footnote block.
///
/// Citations are numbered by first appearance, and a key cited more than once keeps
/// its first number rather than claiming a second footnote. Citations written inside
/// fenced code blocks or inline code spans are left exactly as they appear.
///
/// A body containing no citations is returned unchanged, byte for byte — no
/// separator, no empty footnote block.
///
/// The returned string is Markdown with raw HTML embedded in it, not finished HTML:
/// the caller still renders it. The emitted markup uses only `<sup>`, `<a>`, `<hr>`,
/// `<ol>`, and `<li>` with `id`/`href`/`class` attributes. A default-policy `ammonia`
/// clean keeps the elements and the ids but drops the classes — see [`CiteStyle`].
///
/// `style` names the emitted classes and the back-link's label;
/// [`CiteStyle::default()`] is the plain choice.
///
/// # Errors
///
/// Returns [`CiteError::UnknownCitation`] on the first citation naming a key
/// `bibliography` does not define.
pub fn process(body: &str, bibliography: &Bibliography, style: &CiteStyle) -> Result<String> {
    let (rewritten, cited_keys) = rewrite(body, bibliography, style)?;

    if cited_keys.is_empty() {
        debug_assert_eq!(rewritten, body, "a body with no citations must not change");
        return Ok(rewritten);
    }

    Ok(rewritten + FOOTNOTE_BLOCK_SEPARATOR + &footnote_block(&cited_keys, bibliography, style))
}

/// Renders the ordered footnote list for `cited_keys`.
///
/// Every key is already known to resolve — [`rewrite`] fails before returning a key
/// the bibliography does not define — so a lookup miss here is an internal
/// inconsistency, not user input, and falls back to the bare key rather than failing
/// a build over an unreachable state.
fn footnote_block(cited_keys: &[String], bibliography: &Bibliography, style: &CiteStyle) -> String {
    let item_class = class_attr(&style.item_class);
    let backlink_class = class_attr(&style.backlink_class);
    let label = &style.backlink_label;

    let items = cited_keys
        .iter()
        .enumerate()
        .map(|(index, key)| {
            let number = index + 1;
            let citation = match bibliography.get(key) {
                Some(entry) => format_citation(key, entry),
                None => key.clone(),
            };
            format!(
                r##"<li id="fn-{number}"{item_class}>{citation} <a href="#fnref-{number}"{backlink_class}>{label}</a></li>"##
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    let separator_class = class_attr(&style.separator_class);
    let list_class = class_attr(&style.list_class);

    format!("<hr{separator_class}>\n<ol{list_class}>\n{items}\n</ol>")
}