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;
#[derive(Debug)]
#[non_exhaustive]
pub enum CiteError {
Parse {
file: Option<PathBuf>,
message: String,
},
DuplicateKey {
key: String,
first_file: PathBuf,
second_file: PathBuf,
},
UnknownCitation {
key: String,
},
Io {
path: PathBuf,
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,
}
}
}
pub type Result<T> = std::result::Result<T, CiteError>;
const FOOTNOTE_BLOCK_SEPARATOR: &str = "\n\n";
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))
}
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>")
}