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

+1 -1
View File
@@ -17,7 +17,7 @@ PDF is the best verified build; no unsafe layout experiment was kept.
- Workspace tests: **1084 passed / 0 failed**
- 438 engine / 451 core / 67 server / 71 v1 / 42 oracle / 10 route-D
integration / 4 / 1
- Fidelity harness: 3 vs 3 pages, 1243 vs 1251 words, ratio **0.8605** with a freshly compiled reference
- Fidelity harness: 3 vs 3 pages, 1243 vs 1262 words, ratio **0.8958** with a freshly compiled reference
- Formula band ink bbox:
- TeX `x=184..519, y=230..269`
- route-D `x=201..519, y=241..274`
+1 -1
View File
@@ -51,7 +51,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
prefer route-D with a v1 fallback). 1084 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 1086 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
+2 -2
View File
@@ -16,7 +16,7 @@ cargo test --workspace --offline
or run `./scripts/verify-route-d.sh`, which executes both.
The workspace currently passes **1084 tests**:
The workspace currently passes **1086 tests**:
| Suite | Tests |
| --- | --- |
@@ -29,7 +29,7 @@ The workspace currently passes **1084 tests**:
| engine/core unit | 4 + 1 |
Latest full run (web trial increment): `./scripts/verify-route-d.sh` passes
with fmt clean and **1084 tests** green.
with fmt clean and **1086 tests** green.
Latest live check (2026-10-27): the debug server served `examples/hello.tex`
from `target/debug/texrra serve`; `POST /preview` answered 200 with
+2 -2
View File
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 451 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1084 tests (451 core unit, 438 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 67 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
The crate currently has 451 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1086 tests (451 core unit, 440 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 67 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
### M0 incremental demo
@@ -524,7 +524,7 @@ deliberately open rather than approximated:
## Limits and remaining gaps
The suite currently stands at 1084 passing tests, with the workspace clean.
The suite currently stands at 1086 passing tests, with the workspace clean.
Route-D serves both flat `/preview` and project preview/PDF requests by default
(automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The
objective's areas are implemented to the limits below; complex-script shaping is
+2 -2
View File
@@ -30,8 +30,8 @@ The current arXiv template comparison reports:
```text
reference_pages 3, candidate_pages 3
reference_words 1243, candidate_words 1251
word_sequence_ratio 0.8605
reference_words 1243, candidate_words 1262
word_sequence_ratio 0.8958
page 1 ink bbox: TeX [72, 79, 540, 721] route-D [71, 79, 540, 724]
page 2 ink bbox: TeX [72, 36, 540, 748] route-D [71, 41, 540, 751]
page 3 ink bbox: TeX [72, 36, 540, 748] route-D [71, 41, 553, 751]
+1 -1
View File
@@ -46,7 +46,7 @@ now means route-D.
| Area | Route-D | Evidence / impact |
| --- | --- | --- |
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1084-test suite |
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1086-test suite |
| Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures |
| Floats, captions, tables, booktabs | Supported | table/math tests, corpus |
| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests; PDF XObjects use pixel dimensions and the SVG preview embeds a PNG data URI |
+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"]
);
}
}