Emit author-year labels for project BibTeX

The project .bib inliner now derives author-year labels (with a/b
disambiguation for duplicate author-years) and writes them as optional
\bibitem labels. The route-D citation pass uses those labels only when they
look like author-year labels: \citep gets parentheses, \citet becomes
Author (Year), and reference entries lose their numeric brackets. Inline
thebibliography entries without such labels remain numeric.

The arXiv sample now prints (Kour and Saabne, 2014a; Keshet et al., 2016) and
Kour and Saabne (2014b), matching natbib semantics more closely. Test count
stays 1073.
This commit is contained in:
gloamxun committed 2026-10-27 23:07:00 +08:00
1 parent d2f0fe97c5
commit c2310d85ac
5 files changed
+96 -13

No files matched your search

+56 -6
View File
@@ -1241,12 +1241,15 @@ fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id:
output.push_str(names);
output.push('}');
} else {
let labels = disambiguate_bib_labels(&entries);
output.push_str("\\begin{thebibliography}{99}\n");
for (key, entry) in entries {
output.push_str("\\bibitem{");
output.push_str(&key);
for ((key, entry, _), label) in entries.iter().zip(labels) {
output.push_str("\\bibitem[");
output.push_str(&label);
output.push_str("]{");
output.push_str(key);
output.push_str("} ");
output.push_str(&entry);
output.push_str(entry);
output.push('\n');
}
output.push_str("\\end{thebibliography}\n");
@@ -1259,7 +1262,7 @@ fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id:
/// 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)> {
fn parse_bib_entries(text: &str) -> Vec<(String, String, String)> {
let mut entries = Vec::new();
let mut cursor = 0usize;
while let Some(relative) = text[cursor..].find('@') {
@@ -1314,7 +1317,7 @@ fn parse_bib_entries(text: &str) -> Vec<(String, String)> {
}
let fields = parse_bib_fields(&body[comma + 1..]);
if let Some(entry) = format_bib_entry(&fields) {
entries.push((key.to_string(), entry));
entries.push((key.to_string(), entry, bib_label(&fields)));
}
}
entries
@@ -1388,6 +1391,53 @@ fn parse_bib_fields(text: &str) -> Vec<(String, String)> {
fields
}
/// Author-year label for a BibTeX entry, e.g. `Kour and Saabne, 2014`.
fn bib_label(fields: &[(String, String)]) -> String {
let field = |name: &str| {
fields
.iter()
.find(|(field, _)| field == name)
.map(|(_, value)| value.as_str())
};
let authors: Vec<&str> = field("author")
.unwrap_or("")
.split(" and ")
.map(|author| author.split(',').next().unwrap_or(author).trim())
.filter(|author| !author.is_empty())
.collect();
let names = match authors.as_slice() {
[] => "Anon.".to_string(),
[one] => (*one).to_string(),
[one, two] => format!("{one} and {two}"),
[one, ..] => format!("{one} et al."),
};
match field("year") {
Some(year) => format!("{names}, {year}"),
None => names,
}
}
/// Append a/b suffixes when two entries share the same author-year label.
fn disambiguate_bib_labels(entries: &[(String, String, String)]) -> Vec<String> {
let mut totals: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for (_, _, label) in entries {
*totals.entry(label.as_str()).or_default() += 1;
}
let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
entries
.iter()
.map(|(_, _, label)| {
if totals.get(label.as_str()).copied().unwrap_or(0) <= 1 {
return label.clone();
}
let index = seen.entry(label.as_str()).or_default();
let suffix = char::from(b'a' + (*index).min(25) as u8);
*index += 1;
format!("{label}{suffix}")
})
.collect()
}
fn format_bib_entry(fields: &[(String, String)]) -> Option<String> {
let field = |name: &str| {
fields
+33 -2
View File
@@ -7119,6 +7119,12 @@ fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String
rest = "";
break;
};
let author_year = bibliography.iter().any(|(_, entry)| {
entry
.strip_prefix('\u{E030}')
.and_then(|rest| rest.split_once('\u{E031}'))
.is_some_and(|(label, _)| label.contains(", "))
});
let numbers: Vec<String> = body
.split(',')
.map(|key| {
@@ -7135,7 +7141,24 @@ fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String
(position + 1).to_string()
})
.collect();
let _ = write!(text, "[{}]", numbers.join(", "));
if author_year {
if command == r"\citep" {
let _ = write!(text, "({})", numbers.join("; "));
} else if command == r"\citet" {
let labels: Vec<String> = numbers
.iter()
.map(|label| match label.split_once(", ") {
Some((author, year)) => format!("{author} ({year})"),
None => label.clone(),
})
.collect();
text.push_str(&labels.join("; "));
} else {
text.push_str(&numbers.join("; "));
}
} else {
let _ = write!(text, "[{}]", numbers.join(", "));
}
rest = &after[consumed..];
}
text.push_str(rest);
@@ -13274,6 +13297,10 @@ fn append_bibliography(
.unwrap_or_else(|| format!("{}", index + 1)),
None => format!("{}", index + 1),
};
let labelled = entry
.strip_prefix('\u{E030}')
.and_then(|rest| rest.split_once('\u{E031}'))
.is_some_and(|(label, _)| label.contains(", "));
let body = entry
.split_once('\u{E031}')
.map(|(_, body)| body)
@@ -13284,7 +13311,11 @@ fn append_bibliography(
list_depth: None,
list_label: 0,
right_skip: 0,
text: format!("[{marker}] {body}"),
text: if labelled {
body.to_string()
} else {
format!("[{marker}] {body}")
},
page_break: false,
centered: false,
right_aligned: false,