Resolve citations from a thebibliography block

This commit is contained in:
gloamxun committed 2026-10-24 20:38:44 +08:00
1 parent d4efee043c
commit ea06e299d6
5 files changed
+150 -6

No files matched your search

+128 -2
View File
@@ -161,6 +161,8 @@ struct PageGeometry {
author: Option<String>,
/// `\date{...}` captured from the preamble.
date: Option<String>,
/// `thebibliography` entries: label key and entry text, in order.
bibliography: Vec<(String, String)>,
}
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/
@@ -512,13 +514,83 @@ fn table_reference(text: &str) -> Option<usize> {
/// Strip geometry assignments from the whole source (preamble included) and
/// return the LaTeX body with them removed.
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
let (stripped, geometry) = strip_page_geometry(source);
let (stripped, mut geometry) = strip_page_geometry(source);
// Removed assignments can leave blank lines at the edges; they are not
// paragraphs of their own.
let body = latex_body(&stripped).trim_matches('\n').to_string();
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
geometry.bibliography = extract_bibliography(&mut body);
(body, geometry)
}
/// Remove a `thebibliography` environment from the body and return its
/// `\bibitem{key}` entries in order.
fn extract_bibliography(body: &mut String) -> Vec<(String, String)> {
let begin = r"\begin{thebibliography}";
let end = r"\end{thebibliography}";
let Some(start) = body.find(begin) else {
return Vec::new();
};
let after_begin = start + begin.len();
let Some(offset) = body[after_begin..].find(end) else {
return Vec::new();
};
let inner_start = body[after_begin..]
.find('}')
.map_or(after_begin, |close| after_begin + close + 1);
let inner = body[inner_start..after_begin + offset].to_string();
body.replace_range(start..after_begin + offset + end.len(), "");
let mut entries = Vec::new();
let mut rest = inner.as_str();
while let Some(index) = rest.find(r"\bibitem") {
let after = rest[index + r"\bibitem".len()..].trim_start();
let after = match after.strip_prefix('[') {
Some(label) => match label.split_once(']') {
Some((_, tail)) => tail.trim_start(),
None => after,
},
None => after,
};
let Some((key, consumed)) = braced_group(after) else {
break;
};
let tail = &after[consumed..];
let next = tail.find(r"\bibitem").unwrap_or(tail.len());
entries.push((key.trim().to_string(), tail[..next].trim().to_string()));
rest = &tail[next..];
}
entries
}
/// Replace `\cite{...}` with `[n]`/`[n, m]` from the bibliography order.
fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String, String)]) {
let keys: Vec<&str> = bibliography.iter().map(|(key, _)| key.as_str()).collect();
for paragraph in paragraphs {
let mut text = String::with_capacity(paragraph.text.len());
let mut rest = paragraph.text.as_str();
while let Some(index) = rest.find(r"\cite") {
text.push_str(&rest[..index]);
let after = rest[index + r"\cite".len()..].trim_start();
let Some((body, consumed)) = braced_group(after) else {
text.push_str(&rest[index..]);
rest = "";
break;
};
let numbers: Vec<String> = body
.split(',')
.map(|key| {
keys.iter()
.position(|candidate| *candidate == key.trim())
.map_or_else(|| "?".to_string(), |position| (position + 1).to_string())
})
.collect();
let _ = write!(text, "[{}]", numbers.join(", "));
rest = &after[consumed..];
}
text.push_str(rest);
paragraph.text = text;
}
}
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
document.h_offset = geometry.origin.h_offset;
document.v_offset = geometry.origin.v_offset;
@@ -2273,11 +2345,41 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) {
}
}
/// Append `thebibliography` entries as numbered paragraphs.
fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(String, String)]) {
for (index, (_, entry)) in bibliography.iter().enumerate() {
paragraphs.push(SourceParagraph {
text: format!("[{}] {entry}", index + 1),
page_break: false,
centered: false,
right_aligned: false,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 0,
space_before: if index == 0 { 12 * SCALE } else { 4 * SCALE },
space_stretch: 2 * SCALE,
space_shrink: 0,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
font_size: None,
});
}
}
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
let mut paragraphs = expand_maketitle(paragraphs, geometry);
let section_labels = number_sections(&mut paragraphs);
resolve_section_refs(&mut paragraphs, &section_labels);
number_footnotes(&mut paragraphs);
resolve_citations(&mut paragraphs, &geometry.bibliography);
append_bibliography(&mut paragraphs, &geometry.bibliography);
let line_width = geometry.line_width.unwrap_or(480 * SCALE);
let base_units: Vec<Unit> = paragraphs
.iter()
@@ -2725,6 +2827,30 @@ mod source_tests {
}));
}
#[test]
fn bibliography_entries_resolve_citations() {
let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.bibliography.len(), 2);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
let sources: Vec<&str> = document
.units
.iter()
.map(|unit| unit.source.as_str())
.collect();
assert!(sources.contains(&"See [1] and [1, 2]."), "{sources:?}");
assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}");
assert!(sources.contains(&"[2] Beta entry."), "{sources:?}");
}
#[test]
fn missing_citations_print_a_question_mark() {
let blocks = paragraphs("See \\cite{missing}.").unwrap();
let document = build_document(&blocks, &PageGeometry::default());
assert_eq!(document.units[0].source, "See [?].");
}
#[test]
fn footnotes_number_across_paragraphs() {
let blocks = paragraphs("One\\footnote{A}\n\nTwo\\footnote{B}").unwrap();