mini-cite 0.2.0

BibTeX-backed inline citations and footnotes for the mini-* family.
Documentation
//! Finds `[@key]` citations in a Markdown body and rewrites them into numbered
//! footnote references.

use std::collections::BTreeMap;
use std::ops::Range;

use pulldown_cmark::{Event, Options, Parser, Tag};

use crate::bibliography::Bibliography;
use crate::style::{class_attr, CiteStyle};
use crate::{CiteError, Result};

/// The opening delimiter of a citation marker.
const MARKER_OPEN: &[u8] = b"[@";
/// The closing delimiter of a citation marker.
const MARKER_CLOSE: u8 = b']';
/// Separates citation keys sharing one marker: `[@first;second]`.
const KEY_SEPARATOR: char = ';';

/// One citation marker found in the body: the byte span it occupies and the keys it names.
#[derive(Debug)]
struct Marker {
    span: Range<usize>,
    keys: Vec<String>,
}

/// Rewrites every `[@key]` citation in `body` into a numbered footnote reference,
/// returning the rewritten body and the cited keys in first-appearance order.
///
/// Footnotes are numbered by first appearance, and a key cited more than once keeps
/// its original number rather than claiming a second footnote. Each *occurrence*
/// still gets a distinct `id` (`fnref-1`, then `fnref-1-2`, `fnref-1-3`) — HTML ids
/// must be unique, and the footnote's back-link targets the first occurrence.
///
/// Citations inside fenced code blocks and inline code spans are left exactly as
/// written: a code sample demonstrating this very syntax must survive it.
///
/// `style` supplies the class on each emitted `<sup>`; see [`CiteStyle`].
///
/// # Errors
///
/// Returns [`CiteError::UnknownCitation`] on the first key `bibliography` does not
/// define, without scanning for further unknown keys — a build stops at the first bad
/// citation rather than accumulating a report.
pub fn rewrite(
    body: &str,
    bibliography: &Bibliography,
    style: &CiteStyle,
) -> Result<(String, Vec<String>)> {
    let markers = find_markers(body, &code_ranges(body));

    let mut numbers: BTreeMap<String, usize> = BTreeMap::new();
    let mut ordered_keys: Vec<String> = Vec::new();
    let mut uses: BTreeMap<String, usize> = BTreeMap::new();

    let mut out = String::with_capacity(body.len());
    let mut copied_to = 0;

    for marker in &markers {
        out.push_str(&body[copied_to..marker.span.start]);

        for key in &marker.keys {
            if bibliography.get(key).is_none() {
                return Err(CiteError::UnknownCitation { key: key.clone() });
            }

            let next_number = ordered_keys.len() + 1;
            let number = *numbers.entry(key.clone()).or_insert_with(|| {
                ordered_keys.push(key.clone());
                next_number
            });

            let use_count = uses.entry(key.clone()).and_modify(|n| *n += 1).or_insert(1);
            out.push_str(&reference_html(number, *use_count, style));
        }

        copied_to = marker.span.end;
    }
    out.push_str(&body[copied_to..]);

    debug_assert_eq!(
        ordered_keys.len(),
        numbers.len(),
        "every numbered key must appear exactly once in first-appearance order"
    );

    Ok((out, ordered_keys))
}

/// Renders the inline footnote reference for the `use_count`-th appearance of the
/// citation numbered `number`.
fn reference_html(number: usize, use_count: usize, style: &CiteStyle) -> String {
    let id = match use_count {
        1 => format!("fnref-{number}"),
        n => format!("fnref-{number}-{n}"),
    };
    let class = class_attr(&style.reference_class);

    format!(r##"<sup id="{id}"{class}><a href="#fn-{number}">{number}</a></sup>"##)
}

/// Returns the byte ranges of every inline code span and fenced/indented code block
/// in `body`.
///
/// Parsed with the same options `mini-docs` renders with, so what counts as code here
/// is what will count as code downstream.
fn code_ranges(body: &str) -> Vec<Range<usize>> {
    Parser::new_ext(body, Options::empty())
        .into_offset_iter()
        .filter(|(event, _)| {
            matches!(event, Event::Code(_)) || matches!(event, Event::Start(Tag::CodeBlock(_)))
        })
        .map(|(_, range)| range)
        .collect()
}

/// Scans `body` for citation markers lying outside `code_ranges`.
///
/// Scanning runs over the original, immutable `body` — the same string `code_ranges`
/// was computed from — so the spans stay valid. The caller splices from `body` rather
/// than mutating it, which is what keeps them valid through the rewrite.
fn find_markers(body: &str, code_ranges: &[Range<usize>]) -> Vec<Marker> {
    let bytes = body.as_bytes();
    let mut markers = Vec::new();
    let mut cursor = 0;

    while cursor < bytes.len() {
        let Some(start) = find_subslice(bytes, MARKER_OPEN, cursor) else {
            break;
        };
        let Some(close) = find_byte(bytes, MARKER_CLOSE, start) else {
            break;
        };

        // Advance past this `[@` regardless of whether it turns out to be a citation,
        // so a non-citation bracket can never re-enter the scan.
        cursor = start + MARKER_OPEN.len();

        if is_in_code(start, code_ranges) {
            continue;
        }

        let keys = parse_keys(&body[start + MARKER_OPEN.len()..close]);
        if keys.is_empty() {
            continue;
        }

        markers.push(Marker {
            span: start..close + 1,
            keys,
        });
        cursor = close + 1;
    }

    markers
}

/// Splits a marker's interior into citation keys.
///
/// Accepts `[@a;b]` and the spaced, repeated-sigil form `[@a; @b]` alike — the `@` is
/// part of the marker's opening, not of the key. Returns no keys if any segment is
/// empty or contains whitespace, which makes a bracket like `[@ ]` ordinary text
/// rather than a malformed citation.
fn parse_keys(inner: &str) -> Vec<String> {
    let mut keys = Vec::new();

    for segment in inner.split(KEY_SEPARATOR) {
        let key = segment.trim().trim_start_matches('@').trim();
        if key.is_empty() || key.contains(char::is_whitespace) {
            return Vec::new();
        }
        keys.push(key.to_string());
    }

    keys
}

fn is_in_code(index: usize, code_ranges: &[Range<usize>]) -> bool {
    code_ranges.iter().any(|range| range.contains(&index))
}

fn find_subslice(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
    haystack[from..]
        .windows(needle.len())
        .position(|window| window == needle)
        .map(|i| from + i)
}

fn find_byte(haystack: &[u8], needle: u8, from: usize) -> Option<usize> {
    haystack[from..].iter().position(|&b| b == needle).map(|i| from + i)
}

#[cfg(test)]
#[path = "../tests/unit/rewrite.rs"]
mod tests;