Format BibTeX entries like unsrtnat

Rewrite author names as First Last (with Oxford-comma lists), use plain titles
and italic journal/booktitle with In, order the bibliography by first citation,
carry the 2014a/b suffix into the reference text, and fix page/publisher
punctuation. The valid TeX-oracle score rises from 0.8605 to 0.8958.

Add two formatter tests; the workspace now has 1086 tests.
This commit is contained in:
gloamxun committed 2026-10-28 13:43:24 +08:00
1 parent b7a8637835
commit ba61faf142
7 files changed
+181 -26

No files matched your search

+172 -17
View File
@@ -1241,6 +1241,15 @@ fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id:
output.push_str(names);
output.push('}');
} else {
// unsrtnat orders the bibliography by first citation, not by the
// order entries happen to appear in the .bib file.
let citations = citation_key_order(source);
entries.sort_by_key(|(key, _, _)| {
citations
.iter()
.position(|citation| citation == key)
.unwrap_or(usize::MAX)
});
let labels = disambiguate_bib_labels(&entries);
output.push_str("\\begin{thebibliography}{99}\n");
for ((key, entry, _), label) in entries.iter().zip(labels) {
@@ -1249,7 +1258,7 @@ fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id:
output.push_str("]{");
output.push_str(key);
output.push_str("} ");
output.push_str(entry);
output.push_str(&bib_entry_with_year_suffix(entry, &label));
output.push('\n');
}
output.push_str("\\end{thebibliography}\n");
@@ -1260,6 +1269,61 @@ fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id:
output
}
/// Collect citation keys in first-appearance order, including multi-key
/// `\citep{a,b}` groups.
fn citation_key_order(source: &str) -> Vec<String> {
let mut keys = Vec::new();
let mut rest = source;
while let Some(index) = rest.find("\\cite") {
let after = &rest[index + "\\cite".len()..];
let mut after = after;
if let Some(close) = after.find(']') {
let prefix = &after[..close];
if prefix.starts_with('[') {
after = &after[close + 1..];
}
}
let Some(open) = after.find('{') else {
rest = after;
continue;
};
let after_open = &after[open + 1..];
let Some(close) = after_open.find('}') else {
break;
};
for key in after_open[..close].split(',') {
let key = key.trim();
if !key.is_empty() && !keys.iter().any(|known| known == key) {
keys.push(key.to_string());
}
}
rest = &after_open[close + 1..];
}
keys
}
/// `unsrtnat` prints 2014a/2014b in the reference list; carry the citation
/// label's disambiguation suffix into the entry text.
fn bib_entry_with_year_suffix(entry: &str, label: &str) -> String {
let year = label
.rsplit(", ")
.next()
.unwrap_or("")
.trim_end_matches(')')
.trim();
let Some(suffix) = year
.chars()
.last()
.filter(|character| character.is_ascii_alphabetic())
else {
return entry.to_string();
};
let base = &year[..year.len() - suffix.len_utf8()];
let needle = format!(", {base}.");
let replacement = format!(", {year}.");
entry.replacen(&needle, &replacement, 1)
}
/// Parse the small BibTeX subset used by paper templates: entries with
/// braced or quoted field values. Unknown entry types are skipped.
fn parse_bib_entries(text: &str) -> Vec<(String, String, String)> {
@@ -1316,7 +1380,7 @@ fn parse_bib_entries(text: &str) -> Vec<(String, String, String)> {
continue;
}
let fields = parse_bib_fields(&body[comma + 1..]);
if let Some(entry) = format_bib_entry(&fields) {
if let Some(entry) = format_bib_entry(&fields, &kind) {
entries.push((key.to_string(), entry, bib_label(&fields)));
}
}
@@ -1438,7 +1502,38 @@ fn disambiguate_bib_labels(entries: &[(String, String, String)]) -> Vec<String>
.collect()
}
fn format_bib_entry(fields: &[(String, String)]) -> Option<String> {
fn format_bib_authors(raw: &str) -> String {
let names: Vec<String> = raw
.split(" and ")
.filter_map(|author| {
let author = author.trim();
if author.is_empty() {
return None;
}
Some(match author.split_once(',') {
Some((last, first)) => format!("{} {}", first.trim(), last.trim()),
None => author.to_string(),
})
})
.collect();
match names.as_slice() {
[] => String::new(),
[one] => one.clone(),
[one, two] => format!("{one} and {two}"),
[first, middle @ .., last] => {
let mut joined = first.clone();
for name in middle {
joined.push_str(", ");
joined.push_str(name);
}
joined.push_str(", and ");
joined.push_str(last);
joined
}
}
}
fn format_bib_entry(fields: &[(String, String)], kind: &str) -> Option<String> {
let field = |name: &str| {
fields
.iter()
@@ -1446,35 +1541,41 @@ fn format_bib_entry(fields: &[(String, String)]) -> Option<String> {
.map(|(_, value)| value.as_str())
};
let title = field("title")?;
let author = field("author").unwrap_or("").replace(" and ", ", ");
let authors = format_bib_authors(field("author").unwrap_or(""));
let mut entry = String::new();
if !author.is_empty() {
entry.push_str(&author);
if !authors.is_empty() {
entry.push_str(&authors);
entry.push_str(". ");
}
entry.push_str("\\emph{");
entry.push_str(title);
entry.push_str("}.");
if let Some(container) = field("journal").or_else(|| field("booktitle")) {
entry.push(' ');
entry.push_str(container);
entry.push_str(title.trim_end_matches('.'));
entry.push('.');
if let Some(journal) = field("journal") {
entry.push_str(" \\emph{");
entry.push_str(journal.trim_end_matches('.'));
entry.push('}');
} else if let Some(booktitle) = field("booktitle") {
entry.push_str(" In \\emph{");
entry.push_str(booktitle.trim_end_matches('.'));
entry.push('}');
}
if let Some(pages) = field("pages") {
entry.push_str(", ");
entry.push_str(", pages ");
entry.push_str(pages);
}
if let Some(publisher) = field("publisher").or_else(|| field("organization")) {
entry.push_str(". ");
entry.push_str(publisher.trim_end_matches('.'));
}
if let Some(year) = field("year") {
entry.push_str(", ");
entry.push_str(year);
}
if let Some(publisher) = field("publisher").or_else(|| field("organization")) {
entry.push_str(", ");
entry.push_str(publisher);
}
if let Some(doi) = field("doi") {
entry.push_str(". doi:");
entry.push_str(doi);
}
entry.push('.');
let _ = kind;
Some(entry)
}
@@ -1916,3 +2017,57 @@ mod class_option_tests {
);
}
}
#[cfg(test)]
mod bib_format_tests {
use super::{citation_key_order, format_bib_authors, format_bib_entry};
fn fields(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect()
}
#[test]
fn bib_authors_and_conference_entry_follow_natbib() {
assert_eq!(
format_bib_authors("Kour, George and Saabne, Raid"),
"George Kour and Raid Saabne"
);
assert_eq!(
format_bib_authors("Keshet, Renato and Maor, Alina and Kour, George"),
"Renato Keshet, Alina Maor, and George Kour"
);
let entry = format_bib_entry(
&fields(&[
("author", "Kour, George and Saabne, Raid"),
("title", "Real-time segmentation"),
("booktitle", "Frontiers in Handwriting Recognition"),
("pages", "417--422"),
("publisher", "IEEE"),
("year", "2014"),
]),
"inproceedings",
)
.expect("entry");
assert!(entry.starts_with("George Kour and Raid Saabne."), "{entry}");
assert!(
entry.contains("In \\emph{Frontiers in Handwriting Recognition},"),
"{entry}"
);
assert!(entry.contains("pages 417--422. IEEE, 2014."), "{entry}");
assert!(!entry.contains("on.,"), "{entry}");
}
#[test]
fn citation_keys_follow_first_appearance() {
let order = citation_key_order(
"\\citep{kour2014real, keshet2016prediction} and \\citet{kour2014fast}",
);
assert_eq!(
order,
["kour2014real", "keshet2016prediction", "kour2014fast"]
);
}
}