Skip to main content

latexml_post/
make_bibliography.rs

1//! Bibliography generation processor.
2//!
3//! Port of `LaTeXML::Post::MakeBibliography` (818 lines of Perl).
4//! Collects bibliographic entries from `.bib.xml` files and the ObjectDB,
5//! formats them according to the bibliography style (numeric, author-year, alpha),
6//! and fills in `ltx:bibliography` elements with `ltx:biblist` + `ltx:bibitem`.
7//!
8//! Pipeline:
9//! 1. Find bibliography sources (xml files, bib files, literals)
10//! 2. Scan bibentry elements for cited keys (via BIBLABEL:* in ObjectDB)
11//! 3. Transitively include entries cited from within included entries
12//! 4. Extract names, dates, titles for sorting
13//! 5. Detect duplicate author+year pairs → assign suffixes (a, b, c...)
14//! 6. Format each entry into ltx:bibitem with ltx:tags + ltx:bibblock sections
15//! 7. Optionally split by initial letter
16
17use latexml_core::common::{cleaners::substr, xml::name_is};
18use libxml::tree::Node;
19use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
20
21use crate::{
22  document::{NodeData, PostDocument, PostDocumentOptions},
23  object_db::ObjectDB,
24  processor::{ProcessResult, Processor, find_documentclass_and_packages},
25  radix::radix_alpha,
26};
27
28// ================================================================================
29// The injected raw-`.bib` converter
30// ================================================================================
31
32/// A raw bibliography source that still needs converting.
33///
34/// Perl accumulates these across all `\bibliography{}` names and converts them
35/// in ONE pass (`MakeBibliography.pm` L146-165), so an `@string` macro defined in
36/// the first file is in scope for the last.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum RawBibSource {
39  /// A resolved path to a `.bib` file on disk.
40  Path(String),
41  /// Literal BibTeX data, without the `literal:` protocol prefix.
42  Literal(String),
43}
44
45/// Everything the recursive BibTeX session needs, gathered post-side.
46///
47/// Port of the inputs `convertBibliography` (`MakeBibliography.pm` L180-242)
48/// assembles before calling `LaTeXML->get_converter`.
49#[derive(Debug, Clone)]
50pub struct BibConversionRequest {
51  /// The raw sources, in document order.
52  pub sources:      Vec<RawBibSource>,
53  /// `$$doc{searchpaths}` — the inner session's `paths`.
54  pub search_paths: Vec<String>,
55  /// `[options]name.cls` / `[options]name.sty` specs recovered from the
56  /// document's `<?latexml?>` processing instructions (Perl L186-199): the
57  /// bibliography's fields are the article's TeX, so they need the article's
58  /// class and packages to mean anything.
59  pub preloads:     Vec<String>,
60  /// The keys the document cites, or `None` to convert every entry.
61  ///
62  /// A `.bib` is a library: the converter should digest the cited entries (and
63  /// their `crossref`/`\cite` closure) rather than the whole file, exactly as
64  /// `bibtex(1)` does from the `.aux`'s `\citation` records. `None` means no
65  /// citation record was available, or the document said `\nocite{*}`.
66  pub wanted_keys:  Option<Vec<String>>,
67}
68
69/// Convert raw BibTeX into a document containing `ltx:bibentry` elements.
70///
71/// `latexml_post` cannot run this itself: a conversion needs the model loader
72/// and `convert_document`, which live in `latexml_oxide` (depending the other
73/// way would be a cycle). The orchestrating binary installs an implementation
74/// with [`set_bib_converter`] before running the pipeline.
75pub type BibConverterFn = fn(&BibConversionRequest) -> Option<PostDocument>;
76
77thread_local! {
78  static BIB_CONVERTER: std::cell::Cell<Option<BibConverterFn>> =
79    const { std::cell::Cell::new(None) };
80  /// Whether the bibliography being formatted prints its URLs
81  /// ([`style_prints_urls`]); set per `ltx:bibliography`, read by `format_links`.
82  static URLS_AS_TEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
83  /// How the bibliography being formatted prints given names
84  /// ([`style_given_name_form`]); set per `ltx:bibliography`, read by [`do_name`].
85  static GIVEN_NAME_FORM: std::cell::Cell<GivenNameForm> =
86    const { std::cell::Cell::new(GivenNameForm::Initials) };
87  /// Which marks already end a unit for the bibliography being formatted
88  /// ([`PeriodRule`]); set per `ltx:bibliography`, read by `format_blocks`.
89  static PERIOD_RULE: std::cell::Cell<PeriodRule> =
90    const { std::cell::Cell::new(PeriodRule::AddPeriod) };
91  /// Whether the bibliography being formatted is biblatex's (its `bibstyle` is
92  /// one the biblatex binding records): its drivers print rows a `.bst` does not.
93  static BIBLATEX_BIBLIOGRAPHY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
94}
95
96/// Which marks already end a unit, so that the period a row adds after it
97/// (a `post` or `punct` of "." or ". ") is not printed twice: "What is X?
98/// A survey", not "What is X?. A survey". Perl's `formatBibEntry`
99/// (MakeBibliography.pm:527-531) pushes every `$punct` and `$post`
100/// unconditionally, so a title ending in a mark prints "?." there; both
101/// bibliography engines skip the period, each by its own rule, which the
102/// style decides. Beyond Perl; guards
103/// `cluster_package_guards::bibliography_names_fields` (`title_mark_*`).
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum PeriodRule {
106  /// BibTeX's `add.period$`: a period is added "if the last non-`}`
107  /// character isn't a `.`, `?`, or `!`" (btxhak.tex:326-329) — every
108  /// `.bst`, and the rule when the style is unknown.
109  AddPeriod,
110  /// biblatex's punctuation tracker ([`ends_with_punctuation`]).
111  Tracker,
112}
113
114/// Whether the bibliography being formatted is biblatex's.
115fn is_biblatex_bibliography() -> bool { BIBLATEX_BIBLIOGRAPHY.with(std::cell::Cell::get) }
116
117/// The editor names that stand in for missing authors in a label or sort key,
118/// found by `find` (`tail` selects inside each, e.g. `/ltx:surname`). In a
119/// biblatex bibliography that is biblatex's `editor` field wherever the reader
120/// filed it: an in-book entry's (`@incollection`, `@inreference` and
121/// `@bookinbook` once aliased) is under its host, where it comes first — biber
122/// "Grabowski (2022)", biblatex-apa-test — and any other entry's is its own. The
123/// two are tried in order, not joined: an untyped `editora` is also an own
124/// `editor` name and is not in biblatex's label. A `.bst` labels only by the
125/// entry's own editor (Perl), an incollection by author or key.
126fn label_editors(tail: &str, find: impl Fn(&str) -> Vec<Node>) -> Vec<Node> {
127  if is_biblatex_bibliography() {
128    let host = find(&format!(
129      "ltx:bib-related[@role='host']/ltx:bib-name[@role='editor']{tail}"
130    ));
131    if !host.is_empty() {
132      return host;
133    }
134  }
135  find(&format!("ltx:bib-name[@role='editor']{tail}"))
136}
137
138impl PeriodRule {
139  /// The rule of the style an `ltx:bibliography` records in `bibstyle`:
140  /// the biblatex binding records `biblatex` or `biblatex-giveninits`
141  /// ([`style_given_name_form`]); any other name is a `.bst`.
142  fn of_style(bibstyle: Option<&str>) -> Self {
143    if bibstyle.is_some_and(|style| style.starts_with("biblatex")) {
144      PeriodRule::Tracker
145    } else {
146      PeriodRule::AddPeriod
147    }
148  }
149
150  /// Whether `text` already ends in a mark that takes the place of a period.
151  fn absorbs_period(self, text: &str) -> bool {
152    match self {
153      PeriodRule::AddPeriod => text.trim_end().ends_with(['.', '?', '!']),
154      PeriodRule::Tracker => ends_with_punctuation(text),
155    }
156  }
157}
158
159/// How a bibliography style prints an author's given names.
160///
161/// Perl's `do_name` (MakeBibliography.pm:555-566) always abbreviates, and its
162/// :557 NOTE says this "should be a formatting option". The style decides in
163/// pdflatex: the `.bst` name template (plain.bst:191 `{ff~}` spells them out,
164/// abbrv.bst:191 `{f.~}` abbreviates) or biblatex's `giveninits` option
165/// (default false). Beyond Perl; guards
166/// `cluster_package_guards::bibliography_names_fields` (witnesses
167/// bookshelf/spines, windycity, biblatex-chicago cms-*-sample, biblatex-fiwi).
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169enum GivenNameForm {
170  /// Initials, each whitespace-separated given name reduced to its first
171  /// character plus "." — Perl's form, and the fallback whenever the style
172  /// is unknown or its template unreadable.
173  Initials,
174  /// The given names as written.
175  Full,
176}
177
178/// Install the recursive-BibTeX-session implementation for this thread.
179pub fn set_bib_converter(convert: BibConverterFn) {
180  BIB_CONVERTER.with(|slot| slot.set(Some(convert)));
181}
182
183fn bib_converter() -> Option<BibConverterFn> { BIB_CONVERTER.with(|slot| slot.get()) }
184
185/// Citation style.
186#[derive(Debug, Clone, PartialEq)]
187pub enum CitationStyle {
188  /// Numeric: `[1]`, `[2]`, ...
189  Numbers,
190  /// Author-Year: Author (Year)
191  AuthorYear,
192  /// Alphabetic: `[ABC24]`
193  Alpha,
194}
195
196/// A collected bibliography entry with metadata.
197///
198/// Port of the `%entries` hash entries in `getBibEntries`.
199#[derive(Debug)]
200struct BibEntryData {
201  bib_key:      String,
202  cited_key:    Option<String>,
203  sort_key:     String,
204  initial:      String,
205  author_year:  String,
206  suffix:       Option<String>,
207  /// Sort-form of author names.
208  sort_names:   String,
209  year:         String,
210  /// BibTeX type (article, book, inproceedings, etc.).
211  entry_type:   String,
212  /// Reference style (number within bibliography): its place in the list.
213  number:       u32,
214  /// The number its backend gave it ([`given_number`]), printed instead of [`Self::number`] ([`Self::shown_number`]).
215  label_number: Option<u32>,
216  /// IDs that cite this entry (from outside bibliography).
217  referrers:    HashSet<String>,
218  /// Bib keys that cite this entry (from other bib entries).
219  bibreferrers: HashSet<String>,
220  /// Keys cited from within this entry.
221  citations:    Vec<String>,
222  /// The bibentry XML node (from .bib.xml), if available.
223  bibentry:     Option<Node>,
224  /// The entry's position in the database (`.bib` order; `usize::MAX` when it has none): BibTeX's order for the
225  /// entries no citation places in an unsorted style ([`order_entry_keys`]).
226  db_index:     usize,
227}
228
229impl BibEntryData {
230  /// Get the normalized bibliography type for CSS class.
231  fn bib_type(&self) -> &str {
232    if self.entry_type.is_empty() {
233      "misc"
234    } else {
235      &self.entry_type
236    }
237  }
238
239  /// Get the canonical format type (for FMT_SPEC mapping).
240  ///
241  /// Port of `%FMT_SPEC` aliases.
242  fn format_type(&self) -> &str {
243    match self.entry_type.as_str() {
244      "article" => "article",
245      "book" | "periodical" | "collection" | "proceedings" | "manual" | "misc" | "unpublished"
246      | "booklet" => "book",
247      "incollection"
248      | "collection.article"
249      | "proceedings.article"
250      | "inproceedings"
251      | "inbook" => "incollection",
252      "report" | "techreport" => "report",
253      "thesis" | "mastersthesis" | "phdthesis" => "thesis",
254      "website" | "online" => "website",
255      "software" => "software",
256      _ => "book", // Default fallback
257    }
258  }
259}
260
261/// MakeBibliography post-processor.
262///
263/// Port of `LaTeXML::Post::MakeBibliography`.
264pub struct MakeBibliography {
265  name:           String,
266  pub db:         ObjectDB,
267  split:          bool,
268  bibliographies: Vec<String>,
269  /// An author-year entry's first-block year, left to its label (`drop_first_year`), by bibitem id: the entry
270  /// printed whole (CrossRef's `FullEntry`) carries it again.
271  dropped_years:  std::cell::RefCell<HashMap<String, String>>,
272}
273
274impl MakeBibliography {
275  pub fn new(db: ObjectDB, split: bool) -> Self {
276    MakeBibliography {
277      name: "MakeBibliography".to_string(),
278      db,
279      split,
280      bibliographies: Vec::new(),
281      dropped_years: Default::default(),
282    }
283  }
284
285  pub fn set_bibliographies(&mut self, bibs: Vec<String>) { self.bibliographies = bibs; }
286
287  /// Load bibliography source documents.
288  ///
289  /// Port of `getBibliographies`.
290  /// Locates .bib.xml files from:
291  ///   - Command-line options (overrides)
292  ///   - the `@files` of `bib_node`, the `ltx:bibliography` being processed
293  ///
294  /// `wanted_keys` is forwarded to the recursive raw-`.bib` conversion so it
295  /// digests only the cited entries; see [`BibConversionRequest::wanted_keys`].
296  fn get_bibliographies(
297    &self,
298    doc: &PostDocument,
299    bib_node: &Node,
300    wanted_keys: Option<&Vec<String>>,
301  ) -> Vec<PostDocument> {
302    let mut bibnames: Vec<String> = Vec::new();
303    let mut from_bibliography = false;
304
305    // Use command-line bibliographies if explicitly given
306    if !self.bibliographies.is_empty() {
307      bibnames = self.bibliographies.clone();
308    } else {
309      // Otherwise, read the files of the bibliography being processed, then
310      // its parent's (Perl's `!!!!!` fallback), then the first bibliography
311      // that names any. Perl MakeBibliography.pm:101 reads the FIRST
312      // `//ltx:bibliography` for every one, so an inline `{thebibliography}`
313      // before `\bibliography{refs}` (no `@files`) left the real one empty,
314      // "Missing bibkeys" for every citation (lshort-german/l2kurz,
315      // latex-via-exemplos; KNOWN_PERL_ERRORS #277). A bibliography naming no
316      // files of its own — biblatex's second `\printbibliography` after the
317      // first took the resource list (biblatex_sty.rs) — still reads the
318      // first one's.
319      // Perl's `||` skips an empty value as well as an absent one. A list the
320      // document wrote itself (an empty `{thebibliography}`, a `.bbl`'s
321      // entries) holds an `ltx:biblist` and names no files: it borrows none.
322      let files_of = |node: &Node| node.get_attribute("files").filter(|f| !f.is_empty());
323      let files = files_of(bib_node)
324        .or_else(|| bib_node.get_parent().as_ref().and_then(files_of))
325        .or_else(|| {
326          if !doc.findnodes_at("ltx:biblist", Some(bib_node)).is_empty() {
327            return None;
328          }
329          doc
330            .findnodes("//ltx:bibliography[@files]")
331            .iter()
332            .find_map(files_of)
333        });
334      if let Some(f) = files {
335        from_bibliography = true;
336        bibnames = f.split(',').map(|s| s.trim().to_string()).collect();
337      }
338    }
339
340    let search_paths = doc.get_search_paths();
341    let mut bibs: Vec<PostDocument> = Vec::new();
342    // Raw sources accumulate rather than converting one-by-one, so that a
343    // single recursive session sees them all (Perl L110, L146-165): `@string`
344    // macros are file-scoped in BibTeX but shared across a combined payload,
345    // and one session is also far cheaper than N.
346    let mut rawbibs: Vec<RawBibSource> = Vec::new();
347
348    for bib in &bibnames {
349      let mut loaded = false;
350      // Perl reaches the raw-`.bib` lookup only from inside the
351      // `.bib`/`\bibliography` branch (`MakeBibliography.pm` L126-140), and it
352      // is that branch alone whose failure is an `Error`. Hoisting the lookup
353      // out of the branch (below) is what lost the raise, so carry the branch
354      // condition along instead.
355      let is_bib_style = bib.ends_with(".bib") || bib.ends_with(".bib.xml") || from_bibliography;
356
357      // Literal BibTeX handed in on the command line (Perl L121-123).
358      if let Some(data) = bib.strip_prefix("literal:") {
359        rawbibs.push(RawBibSource::Literal(data.to_string()));
360        continue;
361      }
362
363      // Try as .xml file
364      if bib.ends_with(".xml") {
365        if let Some(path) = find_file(bib, search_paths) {
366          match PostDocument::new_from_file(&path, PostDocumentOptions {
367            source_directory: Some(".".to_string()),
368            ..PostDocumentOptions::default()
369          }) {
370            Ok(bibdoc) => {
371              bibs.push(bibdoc);
372              loaded = true;
373            },
374            Err(e) => Warn!("I/O", bib, "Failed to load bibliography '{}': {}", bib, e),
375          }
376        }
377      }
378      // Try as .bib or from \bibliography command
379      else if is_bib_style {
380        let xmlbib = if from_bibliography && !bib.ends_with(".bib") {
381          format!("{}.bib", bib)
382        } else {
383          bib.clone()
384        };
385        // Look for pre-compiled .bib.xml
386        let xml_candidate = if xmlbib.ends_with(".xml") {
387          xmlbib.clone()
388        } else {
389          format!("{}.xml", xmlbib)
390        };
391        if let Some(path) = find_file(&xml_candidate, search_paths) {
392          match PostDocument::new_from_file(&path, PostDocumentOptions {
393            source_directory: Some(".".to_string()),
394            ..PostDocumentOptions::default()
395          }) {
396            Ok(bibdoc) => {
397              bibs.push(bibdoc);
398              loaded = true;
399            },
400            Err(e) => Warn!("I/O", path, "Failed to load bibliography '{}': {}", path, e),
401          }
402        }
403      }
404
405      // If not loaded yet, queue the raw `.bib` for the recursive session.
406      // `kpsewhich` is the last resort, matching Perl's
407      // `pathname_find(...) || pathname_kpsewhich($bib)` (L133-134) — a `.bib`
408      // installed in the host texmf tree (revtex's `apsrev`, say) resolves
409      // there and nowhere else.
410      if !loaded {
411        let bib_file = if from_bibliography && !bib.ends_with(".bib") {
412          format!("{}.bib", bib)
413        } else {
414          bib.clone()
415        };
416        // A `.bib` written by `filecontents` lives in the session's virtual
417        // file store, never on disk (Perl admits the gap at
418        // MakeBibliography.pm:92-93 — `pathname_find` only). Serve it as
419        // literal data, as `\input` does for such a file (docsurvey, chet,
420        // xreview, koma-moderncvclassic, rub-kunstgeschichte, chemplants).
421        // Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #231). Guard:
422        // `06_cluster_bibliography::filecontents_bib_feeds_the_bibliography`.
423        if let Some(contents) = latexml_core::binding::virtual_files::vfs_read(&bib_file) {
424          rawbibs.push(RawBibSource::Literal(contents));
425          loaded = true;
426        } else if let Some(bib_path) =
427          // (one lookup of the `.bib` the document named, a refusal named as the engine's lookup names it)
428          latexml_core::util::pathname::requested_as(&bib_file, || {
429              bib_lookup_candidates(&bib_file).iter().find_map(|c| {
430                find_file(c, search_paths)
431                  .or_else(|| latexml_core::util::pathname::kpsewhich(&[c.as_str()]))
432              })
433            })
434        {
435          rawbibs.push(RawBibSource::Path(bib_path));
436          loaded = true;
437        } else if is_bib_style {
438          // Perl L138-140 raises this BEFORE falling through to the Info
439          // below, and both reach the log. Dropping it is what let a whole
440          // family of lost bibliographies report telemetry `ok`: the shipped
441          // `bu1.bbl`/`bu2.bbl` of a bibunits paper are never consulted, the
442          // named `.bib` does not exist, and the only trace was an Info.
443          // 14 silent papers in the 2605+2606 sandboxes, 691 corpus-wide;
444          // witness 2606.04416 (same loss under Perl, which DOES raise here).
445          // Audit `docs/parity/BIB_ABSENCE_AUDIT_2026-07-29.md` family F2.
446          Error!(
447            "missing_file",
448            bib,
449            "Couldn't find Bibliography '{}'\nSearchpaths were {}",
450            bib,
451            search_paths.join(",")
452          );
453        }
454      }
455
456      if !loaded {
457        Info!(
458          "bibliography",
459          "missing",
460          "Couldn't find usable bibliography for '{}'",
461          bib
462        );
463      }
464    }
465
466    // Lastly, if we found any raw .bib files / literal data, convert them —
467    // in ONE pass (Perl L146-165).
468    if !rawbibs.is_empty() {
469      match bib_converter() {
470        Some(convert) => {
471          let (class, packages) = find_documentclass_and_packages(doc);
472          // Perl L188-199: `[$classoptions]$class.cls` then `[$options]$pkg.sty`.
473          let mut preloads = Vec::with_capacity(1 + packages.len());
474          preloads.push(if class.options.is_empty() {
475            format!("{}.cls", class.name)
476          } else {
477            format!("[{}]{}.cls", class.options, class.name)
478          });
479          for pkg in &packages {
480            preloads.push(if pkg.options.is_empty() {
481              format!("{}.sty", pkg.name)
482            } else {
483              format!("[{}]{}.sty", pkg.options, pkg.name)
484            });
485          }
486          let request = BibConversionRequest {
487            sources: rawbibs,
488            search_paths: search_paths.to_vec(),
489            preloads,
490            wanted_keys: wanted_keys.cloned(),
491          };
492          match convert(&request) {
493            Some(bibdoc) => bibs.push(bibdoc),
494            None => Error!(
495              "bibliography",
496              "convert",
497              "Recursive BibTeX conversion produced no bibliography"
498            ),
499          }
500        },
501        // Never silently drop the sources: an uninstalled converter would
502        // otherwise render an empty References section with no diagnostic,
503        // which is the exact fail-open shape this codebase forbids.
504        None => Error!(
505          "bibliography",
506          "converter",
507          "No BibTeX converter installed; cannot convert {} raw bibliography source(s) \
508           (call make_bibliography::set_bib_converter before post-processing)",
509          rawbibs.len()
510        ),
511      }
512    }
513
514    Info!(
515      "bibliography",
516      "using",
517      "MakeBibliography: using {} bibliographies",
518      bibs.len()
519    );
520    bibs
521  }
522
523  /// Collect all cited bibliography entries.
524  ///
525  /// Port of `getBibEntries`.
526  /// Scans BIBLABEL:* entries in ObjectDB, resolves to ID:* entries,
527  /// extracts author/year/title, transitively includes cited-from-cited entries,
528  /// assigns suffixes for duplicate author+year pairs.
529  /// Fold every `ltx:bibentry` of one source document into `entries`, keyed by
530  /// the lowercased bibkey. Later sources win for a repeated key, matching the
531  /// upstream `getBibEntries` loop.
532  fn scan_bibentries(entries: &mut HashMap<String, BibEntryData>, srcdoc: &PostDocument) {
533    for bibentry in srcdoc.findnodes("//ltx:bibentry") {
534      let bibkey = match bibentry.get_attribute("key") {
535        Some(k) => k,
536        None => continue,
537      };
538      let lc_key = bibkey.to_lowercase();
539      let citations = Self::entry_citations(srcdoc, &bibentry);
540
541      // A key repeated in a later source keeps its first position (bibtex keeps the first entry, "Repeated
542      // entry"), its content from the later source as Perl.
543      // Two entries whose keys differ only in case are one key here (lowercased, as Perl's `lc` and bibtex's
544      // case-insensitive keys), so one of them is lost: bibtex reports it as an error ("Repeated entry"), and amsrefs,
545      // whose keys are case-sensitive, prints both — an honest Error naming the entry that is replaced.
546      if let Some(previous) = entries.get(&lc_key)
547        && previous.bib_key != bibkey
548      {
549        Error!(
550          "unexpected",
551          &bibkey,
552          "Bibliography entries '{}' and '{}' differ only in case: they share one key and the entry '{}' is replaced",
553          previous.bib_key,
554          bibkey,
555          previous.bib_key
556        );
557      }
558      let db_index = entries.get(&lc_key).map_or(entries.len(), |e| e.db_index);
559      entries.insert(lc_key, BibEntryData {
560        bib_key: bibkey,
561        cited_key: None,
562        sort_key: String::new(),
563        initial: String::new(),
564        author_year: String::new(),
565        suffix: None,
566        sort_names: String::new(),
567        year: String::new(),
568        entry_type: String::new(),
569        number: 0,
570        label_number: None,
571        referrers: HashSet::default(),
572        bibreferrers: HashSet::default(),
573        citations,
574        bibentry: Some(bibentry.clone()),
575        db_index,
576      });
577    }
578  }
579
580  /// The keys the citations inside `bibentry` cite.
581  fn entry_citations(srcdoc: &PostDocument, bibentry: &Node) -> Vec<String> {
582    srcdoc
583      .findnodes_at(".//@bibrefs", Some(bibentry))
584      .iter()
585      .filter_map(|n| {
586        let val = n.get_content();
587        if val.is_empty() { None } else { Some(val) }
588      })
589      .flat_map(|s| s.split(',').map(String::from).collect::<Vec<_>>())
590      .filter(|s| !s.is_empty())
591      .collect()
592  }
593
594  /// The bib keys this document cites, for the recursive raw-`.bib` conversion
595  /// to digest instead of the whole library.
596  ///
597  /// Reads the same `BIBLABEL:<list>:<key>` ObjectDB records that Step 2 of
598  /// [`Self::get_bib_entries`] scans — they are written during the document
599  /// conversion, so they are already complete by the time post-processing asks.
600  /// Returns `None` (= convert everything) for `\nocite{*}`, and also when no
601  /// `BIBLABEL` record exists at all: an empty filter and "no citation data"
602  /// are indistinguishable here, and dropping every entry on a missing record
603  /// would be a silent, unrecoverable loss.
604  fn cited_keys(&self, lists: &[&str]) -> Option<Vec<String>> {
605    let mut keys: Vec<String> = Vec::new();
606    for db_key in self.db.get_keys() {
607      let Some(rest) = db_key.strip_prefix("BIBLABEL:") else {
608        continue;
609      };
610      let Some((list, bibkey)) = rest.split_once(':') else {
611        continue;
612      };
613      if !lists.contains(&list) {
614        continue;
615      }
616      if bibkey == "*" {
617        return None; // `\nocite{*}` — the document wants the whole library.
618      }
619      keys.push(bibkey.to_string());
620    }
621    (!keys.is_empty()).then_some(keys)
622  }
623
624  fn get_bib_entries(
625    &self,
626    doc: &PostDocument,
627    bib_node: &Node,
628  ) -> (HashMap<String, BibEntryData>, Vec<PostDocument>) {
629    let lists_str = bib_node
630      .get_attribute("lists")
631      .unwrap_or_else(|| "bibliography".to_string());
632    let lists: Vec<&str> = lists_str.split_whitespace().collect();
633
634    // Step 1: Scan bibliography source documents for ltx:bibentry elements.
635    // Build a map: lc(bibkey) → { bibkey, bibentry, citations }
636    // Import bibentry nodes into the main document so that XPath queries
637    // (which use the main document's namespace context) work correctly.
638    let mut entries: HashMap<String, BibEntryData> = HashMap::default();
639    let bib_docs = self.get_bibliographies(doc, bib_node, self.cited_keys(&lists).as_ref());
640    for bibdoc in &bib_docs {
641      Self::scan_bibentries(&mut entries, bibdoc);
642    }
643    // Also scan the MAIN document for INLINE `ltx:bibentry` elements.
644    // OXIDIZED_DESIGN #57 (beyond-Perl). amsrefs writes its bibliography
645    // straight into the document — `\begin{bibdiv}\begin{biblist}
646    // \bib{key}{article}{...}` — instead of into an external `.bib`, so the
647    // entries are already children of `ltx:biblist` and there is no `@files`
648    // for `getBibliographies` to resolve. Upstream `getBibEntries` only ever
649    // scans `getBibliographies()`, and `process` then deletes every
650    // `//ltx:bibentry`, so an amsrefs bibliography is silently dropped WHOLE:
651    // empty References plus every `\cite` left dangling, with zero errors
652    // reported. Confirmed identical on installed AND vendored Perl 0.8.8
653    // (rev 51fea96a) — a shared upstream bug (KNOWN_PERL_ERRORS #49), fixed
654    // here rather than reproduced. Papers with an external `.bib` carry no
655    // inline `ltx:bibentry`, so this scan is a no-op for them.
656    // Witness 2605.01646 (AIPFa.tex, 23 entries), 2605.00783, 2605.03852.
657    Self::scan_bibentries(&mut entries, doc);
658    // A key several bibliographies list inline is formatted from this bibliography's own entry: the scan above kept
659    // the document's last copy, another list's — its data and its `labelnumber` ([`given_number`]). biblatex's
660    // refsections each print their own list, numbered on their own (probe r1: refsection 1's list read [3] Knuth,
661    // [2] Lamport where pdflatex prints [1], [2]; arXiv 2308.00515, 2406.01695).
662    for own in doc.findnodes_at(".//ltx:bibentry", Some(bib_node)) {
663      let Some(key) = own.get_attribute("key") else {
664        continue;
665      };
666      if let Some(entry) = entries.get_mut(&key.to_lowercase())
667        && entry.bib_key == key
668      {
669        entry.citations = Self::entry_citations(doc, &own);
670        entry.bibentry = Some(own);
671      }
672    }
673    // This bibliography's own entries (an amsrefs `biblist`) are its References as written: amsrefs typesets every
674    // `\bib` of a biblist, cited or not, where a `.bib` is a library to take the cited entries from (1012.2719: 34
675    // entries, 29 cited, the PDF lists 34). Each bibliography prints its own (two `bibdiv`s, two lists).
676    // An entry an amsrefs `\bibselect` read from its database (`class="ltx_bib_library"`) is a library entry:
677    // printed when cited, as amsrefs.sty:1291 selects them (1904.05225).
678    let mut inline_keys: Vec<String> = doc
679      .findnodes_at(".//ltx:bibentry", Some(bib_node))
680      .iter()
681      .filter(|entry| {
682        !entry
683          .get_attribute("class")
684          .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_bib_library"))
685      })
686      .filter_map(|entry| entry.get_attribute("key"))
687      .collect();
688    inline_keys.sort();
689    // An inline entry inside ANOTHER bibliography (a second `bibdiv`) is that one's, even when cited from here; an entry
690    // in no bibliography (a lone `biblist`) stays anyone's.
691    let own_id = crate::document::get_xml_id(bib_node);
692    let foreign_keys: HashSet<String> = doc
693      .findnodes("//ltx:bibentry")
694      .iter()
695      .filter(|entry| {
696        let mut up = entry.get_parent();
697        while let Some(node) = up {
698          if name_is(&node, "bibliography") {
699            return crate::document::get_xml_id(&node) != own_id;
700          }
701          up = node.get_parent();
702        }
703        false
704      })
705      .filter_map(|entry| entry.get_attribute("key"))
706      .map(|key| key.to_lowercase())
707      .filter(|key| !inline_keys.iter().any(|own| own.to_lowercase() == *key))
708      .collect();
709
710    // Step 2: Collect all cited bibliography keys from BIBLABEL entries in ObjectDB.
711    // Note referrers (from outside the bibliography).
712    let cite_star = lists
713      .iter()
714      .any(|list| self.db.lookup(&format!("BIBLABEL:{}:*", list)).is_some());
715
716    let mut queue: Vec<String> = Vec::new();
717    for db_key in self.db.get_keys() {
718      if !db_key.starts_with("BIBLABEL:") {
719        continue;
720      }
721      let parts: Vec<&str> = db_key.splitn(3, ':').collect();
722      if parts.len() < 3 {
723        continue;
724      }
725      let (list, bibkey) = (parts[1], parts[2]);
726      if !lists.contains(&list) {
727        continue;
728      }
729
730      let lc_key = bibkey.to_lowercase();
731      if let Some(bentry) = self.db.lookup(db_key) {
732        let has_refs = bentry
733          .get_value("referrers")
734          .map(|v| v.is_truthy())
735          .unwrap_or(false);
736        if has_refs {
737          // Filter referrers: walk up parent chain, skip if inside ltx:bibitem
738          if let Some(crate::object_db::Value::Hash(refs)) = bentry.get_value("referrers") {
739            for ref_id in refs.keys() {
740              let mut rid = ref_id.clone();
741              let mut is_from_bib = false;
742              while let Some(entry) = self.db.lookup(&format!("ID:{}", rid)) {
743                let entry_type = entry.get_string("type").unwrap_or("");
744                if entry_type == "ltx:bibitem" {
745                  is_from_bib = true;
746                  break;
747                }
748                match entry.get_string("parent").map(String::from) {
749                  Some(parent) => rid = parent,
750                  None => break,
751                }
752              }
753              if !is_from_bib {
754                // Check for case mismatch
755                if let Some(existing) = entries.get(&lc_key) {
756                  if let Some(ref prev_key) = existing.cited_key {
757                    if prev_key != bibkey {
758                      Warn!(
759                        "bibliography",
760                        "case_mismatch",
761                        "Case mismatch in bib key '{}' vs '{}'",
762                        prev_key,
763                        bibkey
764                      );
765                    }
766                  }
767                }
768                let entry = entries
769                  .entry(lc_key.clone())
770                  .or_insert_with(|| BibEntryData {
771                    bib_key:      bibkey.to_string(),
772                    cited_key:    None,
773                    sort_key:     String::new(),
774                    initial:      String::new(),
775                    author_year:  String::new(),
776                    suffix:       None,
777                    sort_names:   String::new(),
778                    year:         String::new(),
779                    entry_type:   String::new(),
780                    number:       0,
781                    label_number: None,
782                    referrers:    HashSet::default(),
783                    bibreferrers: HashSet::default(),
784                    citations:    Vec::new(),
785                    bibentry:     None,
786                    db_index:     usize::MAX,
787                  });
788                entry.cited_key = Some(bibkey.to_string());
789                entry.referrers.insert(ref_id.clone());
790              }
791            }
792          }
793          if entries
794            .get(&lc_key)
795            .map(|e| !e.referrers.is_empty())
796            .unwrap_or(false)
797          {
798            queue.push(bibkey.to_string());
799          }
800        }
801      }
802    }
803
804    // `\nocite{*}` asks for the WHOLE library — that is bibtex's own semantic
805    // for the star key, and `cited_keys` above already returns None for it so
806    // every entry is read. Queue them all.
807    //
808    // Queueing per BIBLABEL record cannot do this: in a document whose only
809    // citation is `\nocite{*}` the sole record IS `*`, Step 3 skips that key by
810    // name, and the result was "N bibentries, **0 cited**" over an empty
811    // References list — while `pdflatex`+`bibtex` on the same source prints the
812    // full list. 7 papers of the 2605+2606 residual are `\nocite{*}`-only;
813    // 6-line reproducer: `\nocite{*}` + `\bibliography{t}` with a 2-entry
814    // `.bib` gave 0 items against bibtex's 2. Perl skips the star key the same
815    // way (`MakeBibliography.pm` L279-313), so this is deliberately BEYOND Perl.
816    if cite_star {
817      let mut all: Vec<String> = entries.values().map(|e| e.bib_key.clone()).collect();
818      all.sort();
819      queue.extend(all);
820    }
821    // an inline key already queued under another case (`\cite{able}` for `\bib{Able}`) is the same entry
822    let queued: HashSet<String> = queue.iter().map(|key| key.to_lowercase()).collect();
823    queue.extend(
824      inline_keys
825        .into_iter()
826        .filter(|key| !queued.contains(&key.to_lowercase())),
827    );
828    // A backend's listing ([`given_listing`]) is the entry list: the backend
829    // already selected what the document cites (and reported what it could not
830    // find — biblatex_sty.rs `\blx@bbl@missing`), so it is printed whole and a
831    // citation outside it is not looked for again.
832    if let Some(listing) = given_listing(doc, bib_node) {
833      let listed: HashSet<String> = listing.iter().map(|key| key.to_lowercase()).collect();
834      queue.retain(|key| listed.contains(&key.to_lowercase()));
835      queue.extend(listing);
836    }
837
838    // Step 3: Process queue — transitively include cited entries.
839    // For each key, extract names/year/title from bibentry XML.
840    let mut seen: HashSet<String> = HashSet::default();
841    let mut included: HashMap<String, BibEntryData> = HashMap::default();
842    let mut missing_keys: Vec<String> = Vec::new();
843
844    while let Some(bibkey) = queue.pop() {
845      if seen.contains(&bibkey) || bibkey == "*" || foreign_keys.contains(&bibkey.to_lowercase()) {
846        continue;
847      }
848      seen.insert(bibkey.clone());
849      let lc_key = bibkey.to_lowercase();
850
851      match entries.remove(&lc_key) {
852        Some(mut entry) => {
853          // Extract metadata from bibentry XML node (if available)
854          if let Some(ref bibentry) = entry.bibentry {
855            // Perl L318-328 computes TWO name strings and uses them for
856            // different things: `$sortnames` (every "Surname Givenname",
857            // joined) keys the sort, while `$names` (the SHORT form — "A and
858            // B", "A et al") keys `{ay}` and `{initial}`. `extract_names`
859            // already carries Perl's bib-key → bib-title fallback (both
860            // strings then hold the same text), so no second fallback chain is
861            // needed here.
862            let (sort_names, short_names, _full_names) = extract_names(doc, bibentry);
863            entry.sort_names = sort_names.clone();
864
865            // Year
866            let date_content =
867              PostDocument::findnodes_foreign("ltx:bib-date[@role='publication']", bibentry)
868                .into_iter()
869                .next()
870                .map(|n| n.get_content())
871                .unwrap_or_default();
872            let year = extract_four_digit_year(&date_content);
873            entry.year = year.clone();
874
875            // The {ay}/sortkey date is the publication date ALONE, on purpose.
876            // Perl L330 unions it with `ltx:bib-type`
877            // (`ltx:bib-date[@role="publication"] | ltx:bib-type`, whichever
878            // comes first in document order); querying the two separately is a
879            // settled decision here, so that a `type` field cannot displace the
880            // year — see BIBLIOGRAPHY_WORKLIST, "bib-type is safe to emit".
881            // A "date else type" stand-in was written while porting the sortkey
882            // and REMOVED on review: it contradicts that decision, it is not
883            // Perl's rule anyway for an entry carrying both, and it would move
884            // sort keys (and with them numbering) with no test or witness.
885
886            // Title
887            let title = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
888              .into_iter()
889              .next()
890              .map(|n| n.get_content())
891              .unwrap_or_default();
892
893            // Type
894            let entry_type = bibentry
895              .get_attribute("type")
896              .unwrap_or_else(|| "misc".to_string());
897            entry.entry_type = entry_type;
898
899            // Author+year for suffix detection — Perl L336 `"$names.$date"`,
900            // i.e. the SHORT names. Using the full sort-names here silently
901            // disabled disambiguation for every 3+-author paper: two entries
902            // that Perl groups as "Smith et al.1999" carry different coauthor
903            // lists, so their full-name keys never collide and neither entry
904            // ever got its `a`/`b` suffix.
905            entry.author_year = format!("{}.{}", short_names, year);
906            entry.initial = PostDocument::initial(&short_names, true);
907
908            // Sort key — Perl L338, from the FULL sort-names.
909            let sort_key = format!("{}.{}.{}.{}", sort_names, year, title, bibkey).to_lowercase();
910            entry.sort_key = sort_key.clone();
911
912            // Enqueue transitive citations
913            let citations = entry.citations.clone();
914            for c in &citations {
915              queue.push(c.clone());
916            }
917            included.insert(sort_key, entry);
918          } else {
919            // A cited key with no entry in this bibliography's files is
920            // missing here (Perl MakeBibliography.pm:342-343), also when
921            // another list holds its item — a `{thebibliography}`, or an
922            // earlier bibliography of a multi-bibliography document, each read
923            // from its own `@files` since batch 56jt; bibtex warns for such a
924            // `\citation` too. A pseudo-item built from that other item's
925            // ObjectDB record read "[n] Cited by: …" with no content and took
926            // over the citation's link (arXiv 2605.06049: five, for the keys
927            // of its supplement's `{thebibliography}`).
928            missing_keys.push(bibkey);
929          }
930        },
931        _ => {
932          // Not found in entries map
933          missing_keys.push(bibkey);
934        },
935      }
936    }
937
938    if !missing_keys.is_empty() {
939      Warn!(
940        "bibliography",
941        "missing_keys",
942        "Missing bibkeys: {}",
943        missing_keys.join(", ")
944      );
945    }
946
947    // Step 4: Note bibreferrers — for each included entry's citations,
948    // mark the cited entry as having this entry as a bibreferrer.
949    let citations_map: Vec<(String, Vec<String>)> = included
950      .values()
951      .map(|e| (e.bib_key.clone(), e.citations.clone()))
952      .collect();
953    for (bibkey, citations) in &citations_map {
954      for cited in citations {
955        let lc = cited.to_lowercase();
956        // Find which sort_key corresponds to this lc bibkey
957        for entry in included.values_mut() {
958          if entry.bib_key.to_lowercase() == lc {
959            entry.bibreferrers.insert(bibkey.clone());
960          }
961        }
962      }
963    }
964
965    Info!(
966      "bibliography",
967      "count",
968      "MakeBibliography: {} bibentries, {} cited",
969      entries.len() + included.len(),
970      included.len()
971    );
972
973    // Step 5: Sort and detect duplicate author+year → assign suffixes.
974    // Perl L357 `$doc->unisort(keys %$included)`.
975    let mut sorted_keys: Vec<String> = included.keys().cloned().collect();
976    unisort(&mut sorted_keys);
977
978    // Port of suffix detection: track by author_year, assign suffixes when duplicated.
979    let mut ay_last: HashMap<String, String> = HashMap::default(); // ay → last sort_key with this ay
980    for key in &sorted_keys {
981      if let Some(entry) = included.get(key) {
982        let ay = entry.author_year.clone();
983        if let Some(prev_key) = ay_last.get(&ay) {
984          let prev_key = prev_key.clone();
985          // Previous entry with same ay needs a suffix too
986          if let Some(prev) = included.get_mut(&prev_key) {
987            if prev.suffix.is_none() {
988              prev.suffix = Some(radix_alpha(1));
989            }
990          }
991          let prev_counter = included
992            .get(&prev_key)
993            .and_then(|p| p.suffix.as_ref())
994            .map(|s| suffix_to_counter(s))
995            .unwrap_or(1);
996          if let Some(e) = included.get_mut(key) {
997            e.suffix = Some(radix_alpha(prev_counter + 1));
998          }
999        }
1000        ay_last.insert(ay, key.clone());
1001      }
1002    }
1003
1004    // Step 6: Remove sort ERROR nodes from bibentries
1005    for entry in included.values() {
1006      if let Some(ref bibentry) = entry.bibentry {
1007        let sort_errors = PostDocument::findnodes_foreign(".//ltx:ERROR[@class='sort']", bibentry);
1008        for mut sortnode in sort_errors {
1009          sortnode.unlink();
1010        }
1011      }
1012    }
1013
1014    // Numbering is NOT done here: Perl assigns it in FORMAT order
1015    // (`++$NUMBER` inside `formatBibEntry` L418), which is initial-major once
1016    // `--splitbibliography` is on. It happens in `process`, alongside the walk
1017    // that builds the biblists.
1018
1019    (included, bib_docs)
1020  }
1021
1022  /// Format a bibliography list.
1023  ///
1024  /// Port of `makeBibliographyList`.
1025  fn make_bibliography_list(
1026    &self,
1027    doc: &PostDocument,
1028    bib_id: &str,
1029    initial: Option<&str>,
1030    entries: &HashMap<String, BibEntryData>,
1031    style: &CitationStyle,
1032  ) -> NodeData {
1033    let id = if let Some(init) = initial {
1034      format!("{}.L1.{}", bib_id, init)
1035    } else {
1036      format!("{}.L1", bib_id)
1037    };
1038
1039    // Order the rendered list by the number already assigned in `process`. Perl
1040    // re-`unisort`s here (L398), but the number was likewise assigned in
1041    // `unisort` order, so for a sorted style the result is identical; for a
1042    // citation-order style (`sort='false'`, html_feedback #6294) the number
1043    // carries the citation order and the list must follow it, not re-alphabetize.
1044    // Keying on the number makes "list order == numbering order" an invariant.
1045    let mut ordered: Vec<&BibEntryData> = entries.values().collect();
1046    ordered.sort_by_key(|e| e.number);
1047    // Every entry here has its `ltx:bibentry`: `get_bib_entries` includes only
1048    // those, and a cited key without one is missing (Perl MakeBibliography.pm:342).
1049    let items: Vec<NodeData> = ordered
1050      .iter()
1051      .filter_map(|entry| {
1052        debug_assert!(
1053          entry.bibentry.is_some(),
1054          "included entry {} has no bibentry",
1055          entry.bib_key
1056        );
1057        let bibentry = entry.bibentry.as_ref()?;
1058        Some(self.format_bib_entry(doc, bib_id, entry, bibentry, style))
1059      })
1060      .collect();
1061
1062    NodeData::Element {
1063      tag:        "ltx:biblist".to_string(),
1064      attributes: Some(HashMap::from_iter([("xml:id".to_string(), id)])),
1065      children:   items,
1066    }
1067  }
1068
1069  /// Format a single bibentry into a bibitem.
1070  ///
1071  /// Port of `formatBibEntry`.
1072  fn format_bib_entry(
1073    &self,
1074    doc: &PostDocument,
1075    bib_id: &str,
1076    entry: &BibEntryData,
1077    bibentry: &Node,
1078    style: &CitationStyle,
1079  ) -> NodeData {
1080    // ID generation: match Perl's $id =~ s/^bib//; $id = $bibid . $id;
1081    // (MakeBibliography.pm L407-415; NS-aware read — the bare form always
1082    // returned None, so every bibitem fell to the .bibN numbering fallback)
1083    let id = bibitem_id(bib_id, entry, bibentry);
1084
1085    let cited_key = entry.cited_key.as_deref().unwrap_or(&entry.bib_key);
1086    let mut children = Vec::new();
1087
1088    // --- Tags ---
1089    let mut tags = Vec::new();
1090
1091    // Number tag — except for an entry its backend labelled
1092    // ([`entry_given_label`]), which, like a `\bibitem[label]`, has none: its
1093    // citations print the label.
1094    let given_label = entry_given_label(entry, style);
1095    if given_label.is_none() {
1096      tags.push(NodeData::Element {
1097        tag:        "ltx:tag".to_string(),
1098        attributes: Some(HashMap::from_iter([
1099          ("role".to_string(), "number".to_string()),
1100          ("class".to_string(), "ltx_bib_number".to_string()),
1101        ])),
1102        children:   vec![NodeData::Text(entry.shown_number().to_string())],
1103      });
1104    }
1105
1106    // Authors/fullauthors tags — extracted from bibentry XML if available
1107    let (author_tag_nodes, has_names, has_key, has_year, has_typetag) =
1108      self.build_author_year_tags(doc, entry, bibentry);
1109    tags.extend(author_tag_nodes);
1110
1111    // Refnum tag: depends on citation style
1112    let mut effective_style = style.clone();
1113    // Perl: $style = 'numbers' unless (@names || $keytag) && (@year || $typetag)
1114    if !((has_names || has_key) && (has_year || has_typetag)) {
1115      effective_style = CitationStyle::Numbers;
1116    }
1117
1118    let mut skip_first_block = false;
1119    // Author-year only: keep the first block but drop its (redundant) year field.
1120    let mut drop_first_block_year = false;
1121    match effective_style {
1122      _ if given_label.is_some() => {
1123        tags.push(NodeData::Element {
1124          tag:        "ltx:tag".to_string(),
1125          attributes: Some(HashMap::from_iter([
1126            ("role".to_string(), "refnum".to_string()),
1127            ("class".to_string(), "ltx_bib_abbrv".to_string()),
1128            ("open".to_string(), "[".to_string()),
1129            ("close".to_string(), "]".to_string()),
1130          ])),
1131          children:   vec![NodeData::Text(given_label.unwrap_or_default())],
1132        });
1133      },
1134      CitationStyle::Numbers => {
1135        tags.push(NodeData::Element {
1136          tag:        "ltx:tag".to_string(),
1137          attributes: Some(HashMap::from_iter([
1138            ("role".to_string(), "refnum".to_string()),
1139            ("class".to_string(), "ltx_bib_key".to_string()),
1140            ("open".to_string(), "[".to_string()),
1141            ("close".to_string(), "]".to_string()),
1142          ])),
1143          children:   vec![NodeData::Text(entry.shown_number().to_string())],
1144        });
1145      },
1146      CitationStyle::Alpha => {
1147        // AY-style: abbreviation from author names + 2-digit year
1148        let aa = self.make_alpha_label(doc, entry, bibentry);
1149        let yy = alpha_label_year(&entry.year);
1150        let suffix = entry.suffix.as_deref().unwrap_or("");
1151        tags.push(NodeData::Element {
1152          tag:        "ltx:tag".to_string(),
1153          attributes: Some(HashMap::from_iter([
1154            ("role".to_string(), "refnum".to_string()),
1155            ("class".to_string(), "ltx_bib_abbrv".to_string()),
1156            ("open".to_string(), "[".to_string()),
1157            ("close".to_string(), "]".to_string()),
1158          ])),
1159          children:   vec![NodeData::Text(format!("{aa}{yy}{suffix}"))],
1160        });
1161      },
1162      CitationStyle::AuthorYear => {
1163        // Author-year refnum. Perl (MakeBibliography.pm else-branch L505-517)
1164        // builds this label from `do_authors`→`do_names`, i.e. EVERY author,
1165        // with "et al." only for a literal BibTeX "and others"; and it then
1166        // drops the first block ("Skip redundant 1st block!!") because the
1167        // authors are already in the label.
1168        //
1169        // We use the SHORT form instead — intentional divergence
1170        // OXIDIZED_DESIGN #71. On a collaboration paper Perl's rule yields a
1171        // 5104-character citation label (witness arXiv 2607.21432, reported as
1172        // arXiv/html_feedback#6797) and, with the block skipped, that label is
1173        // essentially the whole entry.
1174        //
1175        // pdflatex is the ground truth for the shape. `aa.bst` over the witness
1176        // emits
1177        //   \bibitem[{Abitbol {et~al.}(2025)Abitbol, Abril-Cabezas, …}]{…}
1178        //   Abitbol, M., Abril-Cabezas, I., Adachi, S., {et~al.} 2025, JCAP …
1179        // — natbib's SHORT form is the citation label, the long surname list is
1180        // only natbib's optional full-author form (never printed), and the
1181        // authors live in the entry BODY. So: short label, and keep the block.
1182        //
1183        // Perl already carries the right helper — `do_names_short`
1184        // (MakeBibliography.pm L586) — defined and never called; `do_names_short`
1185        // below is its port. Perl's own role="authors" tag likewise truncates at
1186        // >2 (L433-437), so the full-list label was internally inconsistent.
1187        skip_first_block = false;
1188        drop_first_block_year = true;
1189        let suffix = entry.suffix.as_deref().unwrap_or("");
1190        let authors = PostDocument::findnodes_foreign("ltx:bib-name[@role='author']", bibentry);
1191        let mut refnum_children: Vec<NodeData> = if !authors.is_empty() {
1192          do_names_short(authors)
1193        } else {
1194          let editors = label_editors("", |x| PostDocument::findnodes_foreign(x, bibentry));
1195          if !editors.is_empty() {
1196            do_editors_a(editors)
1197          } else {
1198            // Perl: $keytag->childNodes.
1199            let key = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
1200              .into_iter()
1201              .next()
1202              .map(|k| k.get_content())
1203              .unwrap_or_else(|| entry.bib_key.clone());
1204            vec![NodeData::Text(key)]
1205          }
1206        };
1207        // Perl always wraps the year part in " ( … )": @year+suffix, else the
1208        // type tag (the L482 style guard guarantees one of them is present).
1209        let year_text = if !entry.year.is_empty() {
1210          format!("{}{}", entry.year, suffix)
1211        } else {
1212          PostDocument::findnodes_foreign("ltx:bib-type", bibentry)
1213            .into_iter()
1214            .next()
1215            .map(|t| t.get_content())
1216            .unwrap_or_default()
1217        };
1218        refnum_children.push(NodeData::Text(format!(" ({})", year_text)));
1219        tags.push(NodeData::Element {
1220          tag:        "ltx:tag".to_string(),
1221          attributes: Some(HashMap::from_iter([
1222            ("role".to_string(), "refnum".to_string()),
1223            ("class".to_string(), "ltx_bib_author-year".to_string()),
1224          ])),
1225          children:   refnum_children,
1226        });
1227      },
1228    }
1229
1230    if !tags.is_empty() {
1231      children.push(NodeData::Element {
1232        tag:        "ltx:tags".to_string(),
1233        attributes: None,
1234        children:   tags,
1235      });
1236    }
1237
1238    // --- Content blocks ---
1239    let mut dropped_year = None;
1240    let blocks = self.format_blocks(
1241      doc,
1242      entry,
1243      bibentry,
1244      skip_first_block,
1245      drop_first_block_year,
1246      &mut dropped_year,
1247    );
1248    if let Some(year) = dropped_year {
1249      self.dropped_years.borrow_mut().insert(id.clone(), year);
1250    }
1251    children.extend(blocks);
1252
1253    // --- Cited-by block ---
1254    let mut citedby: Vec<NodeData> = Vec::new();
1255    let mut sorted_referrers: Vec<&String> = entry.referrers.iter().collect();
1256    sorted_referrers.sort();
1257    for ref_id in &sorted_referrers {
1258      citedby.push(NodeData::Element {
1259        tag:        "ltx:ref".to_string(),
1260        attributes: Some(HashMap::from_iter([
1261          ("idref".to_string(), (*ref_id).clone()),
1262          ("show".to_string(), "typerefnum".to_string()),
1263        ])),
1264        children:   vec![],
1265      });
1266    }
1267    if !entry.bibreferrers.is_empty() {
1268      let mut sorted_bibrefs: Vec<&String> = entry.bibreferrers.iter().collect();
1269      sorted_bibrefs.sort();
1270      citedby.push(NodeData::Element {
1271        tag:        "ltx:bibref".to_string(),
1272        attributes: Some(HashMap::from_iter([
1273          (
1274            "bibrefs".to_string(),
1275            sorted_bibrefs
1276              .iter()
1277              .map(|s| s.as_str())
1278              .collect::<Vec<_>>()
1279              .join(","),
1280          ),
1281          ("show".to_string(), "refnum".to_string()),
1282        ])),
1283        children:   vec![],
1284      });
1285    }
1286    if !citedby.is_empty() {
1287      let conjoined = PostDocument::conjoin(
1288        crate::document::Conjunction::Simple(",\n".to_string()),
1289        citedby,
1290      );
1291      let mut block_children = vec![NodeData::Text("Cited by: ".to_string())];
1292      block_children.extend(conjoined);
1293      block_children.push(NodeData::Text(".".to_string()));
1294      children.push(NodeData::Element {
1295        tag:        "ltx:bibblock".to_string(),
1296        attributes: Some(HashMap::from_iter([(
1297          "class".to_string(),
1298          "ltx_bib_cited".to_string(),
1299        )])),
1300        children:   block_children,
1301      });
1302    }
1303
1304    NodeData::Element {
1305      tag: "ltx:bibitem".to_string(),
1306      attributes: Some(HashMap::from_iter([
1307        ("xml:id".to_string(), id),
1308        ("key".to_string(), cited_key.to_string()),
1309        ("type".to_string(), entry.entry_type.clone()),
1310        ("class".to_string(), format!("ltx_bib_{}", entry.bib_type())),
1311      ])),
1312      children,
1313    }
1314  }
1315
1316  /// Build author/year/key/title/type tags from bibentry XML.
1317  ///
1318  /// Returns: (tag nodes, has_names, has_key, has_year, has_typetag)
1319  fn build_author_year_tags(
1320    &self,
1321    doc: &PostDocument,
1322    entry: &BibEntryData,
1323    bibentry: &Node,
1324  ) -> (Vec<NodeData>, bool, bool, bool, bool) {
1325    let mut tags = Vec::new();
1326    let mut has_names = false;
1327    let mut has_key = false;
1328    let mut has_year = false;
1329    let mut has_typetag = false;
1330
1331    // Author surnames from bibentry XML
1332    let mut surnames: Vec<Node> =
1333      doc.findnodes_at("ltx:bib-name[@role='author']/ltx:surname", Some(bibentry));
1334    if surnames.is_empty() {
1335      surnames = label_editors("/ltx:surname", |x| doc.findnodes_at(x, Some(bibentry)));
1336    }
1337
1338    if surnames.len() > 2 {
1339      has_names = true;
1340      // Short: first author + et al.
1341      let first_text = surnames[0].get_content();
1342      tags.push(NodeData::Element {
1343        tag:        "ltx:tag".to_string(),
1344        attributes: Some(HashMap::from_iter([
1345          ("role".to_string(), "authors".to_string()),
1346          ("class".to_string(), "ltx_bib_author".to_string()),
1347        ])),
1348        children:   vec![NodeData::Text(first_text), NodeData::Element {
1349          tag:        "ltx:text".to_string(),
1350          attributes: Some(HashMap::from_iter([(
1351            "class".to_string(),
1352            "ltx_bib_etal".to_string(),
1353          )])),
1354          children:   vec![NodeData::Text(" et al.".to_string())],
1355        }],
1356      });
1357      // Full: all names
1358      let mut full_children: Vec<NodeData> = Vec::new();
1359      for (i, surname) in surnames.iter().enumerate() {
1360        if i > 0 && i < surnames.len() - 1 {
1361          full_children.push(NodeData::Text(", ".to_string()));
1362        } else if i == surnames.len() - 1 {
1363          full_children.push(NodeData::Text(" and ".to_string()));
1364        }
1365        full_children.push(NodeData::Text(surname.get_content()));
1366      }
1367      tags.push(NodeData::Element {
1368        tag:        "ltx:tag".to_string(),
1369        attributes: Some(HashMap::from_iter([
1370          ("role".to_string(), "fullauthors".to_string()),
1371          ("class".to_string(), "ltx_bib_author".to_string()),
1372        ])),
1373        children:   full_children,
1374      });
1375    } else if surnames.len() == 2 {
1376      has_names = true;
1377      tags.push(NodeData::Element {
1378        tag:        "ltx:tag".to_string(),
1379        attributes: Some(HashMap::from_iter([
1380          ("role".to_string(), "authors".to_string()),
1381          ("class".to_string(), "ltx_bib_author".to_string()),
1382        ])),
1383        children:   vec![
1384          NodeData::Text(surnames[0].get_content()),
1385          NodeData::Text(" and ".to_string()),
1386          NodeData::Text(surnames[1].get_content()),
1387        ],
1388      });
1389    } else if !surnames.is_empty() {
1390      has_names = true;
1391      tags.push(NodeData::Element {
1392        tag:        "ltx:tag".to_string(),
1393        attributes: Some(HashMap::from_iter([
1394          ("role".to_string(), "authors".to_string()),
1395          ("class".to_string(), "ltx_bib_author".to_string()),
1396        ])),
1397        children:   vec![NodeData::Text(surnames[0].get_content())],
1398      });
1399    }
1400
1401    // Key tag
1402    if let Some(key_node) = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
1403      .into_iter()
1404      .next()
1405    {
1406      has_key = true;
1407      tags.push(NodeData::Element {
1408        tag:        "ltx:tag".to_string(),
1409        attributes: Some(HashMap::from_iter([
1410          ("role".to_string(), "key".to_string()),
1411          ("class".to_string(), "ltx_bib_key".to_string()),
1412        ])),
1413        children:   vec![NodeData::Text(key_node.get_content())],
1414      });
1415    }
1416
1417    // Year tag
1418    if let Some(date_node) =
1419      PostDocument::findnodes_foreign("ltx:bib-date[@role='publication']", bibentry)
1420        .into_iter()
1421        .next()
1422    {
1423      has_year = true;
1424      let year_text = extract_four_digit_year(&date_node.get_content());
1425      let suffix = entry.suffix.as_deref().unwrap_or("");
1426      tags.push(NodeData::Element {
1427        tag:        "ltx:tag".to_string(),
1428        attributes: Some(HashMap::from_iter([
1429          ("role".to_string(), "year".to_string()),
1430          ("class".to_string(), "ltx_bib_year".to_string()),
1431        ])),
1432        children:   vec![NodeData::Text(format!("{}{}", year_text, suffix))],
1433      });
1434    }
1435
1436    // Type tag
1437    if let Some(type_node) = PostDocument::findnodes_foreign("ltx:bib-type", bibentry)
1438      .into_iter()
1439      .next()
1440    {
1441      has_typetag = true;
1442      tags.push(NodeData::Element {
1443        tag:        "ltx:tag".to_string(),
1444        attributes: Some(HashMap::from_iter([
1445          ("role".to_string(), "bibtype".to_string()),
1446          ("class".to_string(), "ltx_bib_type".to_string()),
1447        ])),
1448        children:   vec![NodeData::Text(type_node.get_content())],
1449      });
1450    }
1451
1452    // Title tag
1453    if let Some(title_node) = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
1454      .into_iter()
1455      .next()
1456    {
1457      tags.push(NodeData::Element {
1458        tag:        "ltx:tag".to_string(),
1459        attributes: Some(HashMap::from_iter([
1460          ("role".to_string(), "title".to_string()),
1461          ("class".to_string(), "ltx_bib_title".to_string()),
1462        ])),
1463        children:   vec![NodeData::Text(title_node.get_content())],
1464      });
1465    }
1466
1467    (tags, has_names, has_key, has_year, has_typetag)
1468  }
1469
1470  /// Generate alphabetic label for AY/alpha citation style.
1471  ///
1472  /// Port of the alpha refnum logic in `formatBibEntry`.
1473  fn make_alpha_label(&self, doc: &PostDocument, entry: &BibEntryData, bibentry: &Node) -> String {
1474    let mut surnames: Vec<Node> =
1475      doc.findnodes_at("ltx:bib-name[@role='author']/ltx:surname", Some(bibentry));
1476    if surnames.is_empty() {
1477      surnames = label_editors("/ltx:surname", |x| doc.findnodes_at(x, Some(bibentry)));
1478    }
1479    if surnames.len() > 1 {
1480      // Perl L497-500: `join('', map { substr($_->textContent, 0, 1) })`,
1481      // truncated to `substr($aa, 0, 3) . "+"` past three. Both are
1482      // CHARACTER operations, and neither uppercases — only the single-name
1483      // branch below carries Perl's `uc`. Byte indexing here used to panic
1484      // outright on a multi-byte initial (`Ångström`), which the citestyle
1485      // repair makes reachable for every `\bibliographystyle{alpha}`
1486      // document rather than the handful that spelled the style `alpha`.
1487      let initials: Vec<char> = surnames
1488        .iter()
1489        .map(|n| n.get_content().chars().next().unwrap_or('?'))
1490        .collect();
1491      if initials.len() > 3 {
1492        format!("{}+", initials[..3].iter().collect::<String>())
1493      } else {
1494        initials.iter().collect::<String>()
1495      }
1496    } else if !surnames.is_empty() {
1497      let text = surnames[0].get_content();
1498      substr(&text, 0, 3).to_uppercase()
1499    } else {
1500      entry
1501        .bib_key
1502        .chars()
1503        .take(3)
1504        .collect::<String>()
1505        .to_uppercase()
1506    }
1507  }
1508
1509  /// Format content blocks using the FMT_SPEC table.
1510  ///
1511  /// Port of the block formatting loop in `formatBibEntry` + `%FMT_SPEC`.
1512  fn format_blocks(
1513    &self,
1514    doc: &PostDocument,
1515    entry: &BibEntryData,
1516    bibentry: &Node,
1517    skip_first: bool,
1518    drop_first_year: bool,
1519    dropped_year: &mut Option<String>,
1520  ) -> Vec<NodeData> {
1521    let format_type = entry.format_type();
1522    let block_specs = get_fmt_spec(format_type);
1523    let mut blocks = Vec::new();
1524    let mut year_left_out: Option<String> = None;
1525
1526    for (i, block_spec) in block_specs.iter().enumerate() {
1527      if skip_first && i == 0 {
1528        continue;
1529      }
1530
1531      let mut items: Vec<NodeData> = Vec::new();
1532      for field_spec in block_spec {
1533        // Author-year: the refnum label already reads "Author (Year)", so the
1534        // first block repeating the year would print it twice in the one entry.
1535        // Perl avoids that by dropping the whole block (and with it the author
1536        // list); we keep the block and drop only the redundant field. Matches
1537        // the biblatex author-year path already shipped here, whose entries
1538        // render as `[Smith (2020)]  John Smith  “A study of things” …` —
1539        // label carries the year, author block does not. See OXIDIZED_DESIGN #71.
1540        if drop_first_year && i == 0 && field_spec.class == "year" {
1541          let nodes = PostDocument::findnodes_foreign(
1542            field_spec.xpath.trim_start_matches('!').trim(),
1543            bibentry,
1544          );
1545          if !nodes.is_empty() {
1546            year_left_out = Some(node_data_text(&apply_formatter(
1547              doc,
1548              field_spec.formatter,
1549              &nodes,
1550            )));
1551          }
1552          continue;
1553        }
1554        let (nodes_found, negated) = {
1555          let xpath = field_spec.xpath.trim_start_matches('!').trim();
1556          let negated = field_spec.xpath.starts_with('!');
1557          if xpath == "true" {
1558            (true, false)
1559          } else {
1560            let found = !PostDocument::findnodes_foreign(xpath, bibentry).is_empty();
1561            (found, negated)
1562          }
1563        };
1564
1565        // Check condition
1566        if field_spec.xpath != "true" {
1567          if negated {
1568            if nodes_found {
1569              continue;
1570            }
1571          } else {
1572            if !nodes_found {
1573              continue;
1574            }
1575          }
1576        }
1577
1578        // Add punctuation if there are preceding items
1579        if !field_spec.punct.is_empty() && !items.is_empty() {
1580          push_unit_text(&mut items, field_spec.punct);
1581        }
1582        // Pre-text
1583        if !field_spec.pre.is_empty() {
1584          items.push(NodeData::Text(field_spec.pre.to_string()));
1585        }
1586        // Content (wrapped in ltx:text with class)
1587        if !field_spec.class.is_empty() {
1588          let xpath = field_spec.xpath.trim_start_matches('!').trim();
1589          let content = if xpath == "true" {
1590            Vec::new()
1591          } else {
1592            let nodes = PostDocument::findnodes_foreign(xpath, bibentry);
1593            apply_formatter(doc, field_spec.formatter, &nodes)
1594          };
1595          if !content.is_empty() {
1596            items.push(NodeData::Element {
1597              tag:        "ltx:text".to_string(),
1598              attributes: Some(HashMap::from_iter([(
1599                "class".to_string(),
1600                format!("ltx_bib_{}", field_spec.class),
1601              )])),
1602              children:   content,
1603            });
1604          }
1605        }
1606        // Post-text
1607        if !field_spec.post.is_empty() {
1608          push_unit_text(&mut items, field_spec.post);
1609        }
1610      }
1611
1612      if !items.is_empty() {
1613        blocks.push(make_bibblock("", &items));
1614        // The left-out year follows the first block with content: the author's, else (no author or editor) the
1615        // title's.
1616        if dropped_year.is_none()
1617          && items
1618            .iter()
1619            .any(|item| matches!(item, NodeData::Element { .. }))
1620        {
1621          *dropped_year = year_left_out.take();
1622        }
1623      }
1624    }
1625
1626    // Note + External Links are part of every type's FMT_SPEC via the
1627    // `meta_block` appended in get_fmt_spec, so the loop above already emits
1628    // them. (A second, hard-coded copy here previously duplicated every
1629    // entry's final Note/External-Links bibblock.)
1630
1631    blocks
1632  }
1633}
1634
1635impl Processor for MakeBibliography {
1636  fn get_name(&self) -> &str { &self.name }
1637
1638  fn to_process(&self, doc: &PostDocument) -> Vec<Node> { doc.findnodes("//ltx:bibliography") }
1639
1640  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
1641    // An inline `ltx:bibentry` (amsrefs' `\bib`, a biblatex `.bbl`,
1642    // biblatex_sty.rs) is the document's own element, and its id — `bib.bib1`,
1643    // from the `@bibitem` counter — is the one the bibitem made from it is
1644    // given (`format_bib_entry`, `bib.bib<number>` once released). Held by the
1645    // entry, which is removed only after formatting, it made the bibitem's id
1646    // clash: the bibitem was renamed `bib.bib1a`, while its citations and the
1647    // ObjectDB point at `bib.bib1`, so the list item lost its HTML id and every
1648    // link to it dangled. An external `.bib`'s entries live in their own
1649    // document. Beyond Perl, which reads no inline entries (KNOWN_PERL_ERRORS #49).
1650    for mut entry in doc.findnodes("//ltx:bibentry[@xml:id]") {
1651      doc.release_id(&mut entry);
1652    }
1653    for bib in &nodes {
1654      // Set before the entries are read: their sort names consult it.
1655      let biblatex = bib
1656        .get_attribute("bibstyle")
1657        .is_some_and(|style| style.starts_with("biblatex"));
1658      BIBLATEX_BIBLIOGRAPHY.with(|flag| flag.set(biblatex));
1659      // Skip if already populated
1660      if !doc.findnodes_at(".//ltx:bibitem", Some(bib)).is_empty() {
1661        continue;
1662      }
1663
1664      // Read citation style from element attributes
1665      // Perl L481 is `$STYLE{citestyle} || 'numbers'`, and `||` is falsy on the
1666      // EMPTY string as well as on absent — so an empty attribute must reach
1667      // `numbers`, not the `else` branch. Before the mapping repair below an
1668      // empty value fell through to `_ => Numbers` by luck; with `_` now
1669      // meaning author-year it has to be excluded explicitly, or the repair
1670      // would introduce an unfaithfulness of its own. Our own engine cannot
1671      // emit `citestyle=""` (`Document::set_attribute` skips empty values), but
1672      // `latexml_post` also consumes XML it did not produce.
1673      let citestyle_str = bib
1674        .get_attribute("citestyle")
1675        .filter(|s| !s.is_empty())
1676        .unwrap_or_else(|| "numbers".to_string());
1677      // Perl L481-517 branches on exactly three cases, and the mapping was
1678      // inverted here: `AY` is the ABBREVIATED `[AS64]` label (L485, class
1679      // `ltx_bib_abbrv`), NOT the spelled-out author-year one, and ANY other
1680      // non-`numbers` value takes the author-year `else` branch rather than
1681      // falling back to numbers. `\bibliographystyle{alpha}` sets
1682      // `CITE_STYLE=AY` (`latex_constructs.rs::lookup_bibstyle_params`, Perl
1683      // `$BIBSTYLES` L3953-3961), so every alpha-styled document was getting
1684      // author-year refnums where Perl — and the `.bst` the author chose —
1685      // give `[AS64]`.
1686      let style = match citestyle_str.as_str() {
1687        "numbers" => CitationStyle::Numbers,
1688        "AY" => CitationStyle::Alpha,
1689        _ => CitationStyle::AuthorYear,
1690      };
1691
1692      // bib_docs must be kept alive as long as entries (bibentry Nodes reference them)
1693      let (mut entries, _bib_docs) = self.get_bib_entries(&doc, bib);
1694      if entries.is_empty() {
1695        Info!(
1696          "bibliography",
1697          "empty",
1698          "MakeBibliography: no entries to process"
1699        );
1700        continue;
1701      }
1702
1703      // Perl MakeBibliography.pm L393-394: bib's id, else the document
1704      // element's id, else the literal 'bib'. NS-aware reads — the bare
1705      // forms always fell through to the literal.
1706      let bib_id = crate::document::get_xml_id(bib)
1707        .or_else(|| {
1708          doc
1709            .get_document_element()
1710            .as_ref()
1711            .and_then(crate::document::get_xml_id)
1712        })
1713        .unwrap_or_else(|| "bib".to_string());
1714
1715      // Perl `local $LaTeXML::Post::MakeBibliography::NUMBER = 0` (L55) —
1716      // reset per `ltx:bibliography`, then incremented once per entry as it is
1717      // FORMATTED (L418). Under `--splitbibliography` that walk is
1718      // initial-major, so the counter follows the initial groups rather than
1719      // the document-global sortkey order; the two coincide whenever an
1720      // entry's `initial` is the first letter of its sortkey, which is the
1721      // common case but not guaranteed (`initial` skips leading non-letters).
1722      //
1723      // NOTE ON REACH: `self.split` is currently always false — `post.rs`
1724      // constructs this processor with `split = false` and
1725      // `--splitbibliography` sits in the deferred CLI cluster. So moving the
1726      // counter here changes NO production output today; the non-split walk
1727      // numbers in the same order the old in-`get_bib_entries` pass did. It is
1728      // done for when that flag lands, and because the counter belongs with
1729      // the walk it counts.
1730      let mut number = 0u32;
1731      // The numbers the list prints ([`number_entry`]): an entry its backend labelled takes none.
1732      let mut shown = 0u32;
1733
1734      // Citation-order numbering for an UNSORTED style: the References are
1735      // numbered by first citation, not alphabetically — matching the `.bst` and
1736      // the published PDF (html_feedback #6294). Perl always `unisort`s (it reads
1737      // the sort flag into `%STYLE` but ignores it), so this is a deliberate
1738      // surpass-Perl. Read from the node's `sort`, which the engine writes from the
1739      // style (`CITE_SORT`; OXIDIZED_DESIGN_DIVERGENCES #116).
1740      // Only the non-split walk uses it; `--splitbibliography` is inherently
1741      // initial-major (alphabetical) and never combines with it.
1742      //
1743      // Gated on a NUMERIC list: an author-year bibliography is always ordered
1744      // alphabetically by author regardless of the `.bst` sort flag, so a numeric
1745      // style is a precondition. This matters for the natbib/revtex arm
1746      // (#5930/#6095): natbib now records `bibstyle` even when it stays in
1747      // author-year mode (no `[numbers]`), and reordering that list by citation
1748      // would be wrong. An absent `citestyle` defaults to numeric (Perl L481).
1749      let is_numeric = bib
1750        .get_attribute("citestyle")
1751        .as_deref()
1752        .map(|s| s.is_empty() || s == "numbers")
1753        .unwrap_or(true);
1754      let unsorted_style = bib.with_attribute(c"sort", |v| v == "false") == Some(true);
1755      let cite_order = (is_numeric && unsorted_style).then(|| citation_order(&doc));
1756      // A listing in the document keeps its own order in every style: biber applied the style's sorting scheme (the
1757      // `.bbl` order is the PDF's) and biblatex numbers in list order; amsrefs prints each `\bib` where it stands.
1758      let cite_order = given_listing(&doc, bib)
1759        .or_else(|| inline_listing(&doc, bib))
1760        .map(|listing| {
1761          let mut order: HashMap<String, usize> = HashMap::default();
1762          for key in listing {
1763            let next = order.len();
1764            order.entry(key.to_lowercase()).or_insert(next);
1765          }
1766          order
1767        })
1768        .or(cite_order);
1769      let prints_urls = bib
1770        .get_attribute("bibstyle")
1771        .as_deref()
1772        .is_some_and(style_prints_urls);
1773      URLS_AS_TEXT.with(|flag| flag.set(prints_urls));
1774      let given_names = bib
1775        .get_attribute("bibstyle")
1776        .map_or(GivenNameForm::Initials, |style| {
1777          style_given_name_form(&style, doc.get_search_paths())
1778        });
1779      GIVEN_NAME_FORM.with(|form| form.set(given_names));
1780      let period_rule = PeriodRule::of_style(bib.get_attribute("bibstyle").as_deref());
1781      PERIOD_RULE.with(|rule| rule.set(period_rule));
1782
1783      if self.split {
1784        // Split by initial letter
1785        let mut by_initial: HashMap<String, Vec<String>> = HashMap::default();
1786        for (key, entry) in &entries {
1787          by_initial
1788            .entry(entry.initial.clone())
1789            .or_default()
1790            .push(key.clone());
1791        }
1792        let mut initials: Vec<String> = by_initial.keys().cloned().collect();
1793        initials.sort();
1794        for group in by_initial.values_mut() {
1795          unisort(group);
1796        }
1797        for initial in &initials {
1798          // Number this group, then format it — the order Perl's single
1799          // `++$NUMBER`-as-you-format walk produces.
1800          // The keys came out of `entries` a few lines above, so a miss is a
1801          // logic error, not input-dependent — `debug_assert` makes it loud in
1802          // dev/test without risking a production abort (`maxperf` sets
1803          // `panic = "abort"`). Incrementing INSIDE the lookup also means a
1804          // miss could never silently burn a number and shift the whole list.
1805          for key in &by_initial[initial] {
1806            debug_assert!(entries.contains_key(key), "grouped key {key} left entries");
1807            if let Some(entry) = entries.get_mut(key) {
1808              number_entry(entry, &mut number, &mut shown, &style);
1809            }
1810          }
1811          // Build a subset HashMap for this initial
1812          let subset: HashMap<String, BibEntryData> = by_initial[initial]
1813            .iter()
1814            .filter_map(|k| entries.get(k).map(|e| (k.clone(), clone_entry(e))))
1815            .collect();
1816          let biblist = self.make_bibliography_list(&doc, &bib_id, Some(initial), &subset, &style);
1817          let mut bib_mut = bib.clone();
1818          doc.add_nodes(&mut bib_mut, &[biblist]);
1819        }
1820      } else {
1821        let sorted_keys = order_entry_keys(&entries, cite_order.as_ref());
1822        for key in &sorted_keys {
1823          debug_assert!(entries.contains_key(key), "sorted key {key} left entries");
1824          if let Some(entry) = entries.get_mut(key) {
1825            number_entry(entry, &mut number, &mut shown, &style);
1826          }
1827        }
1828        let biblist = self.make_bibliography_list(&doc, &bib_id, None, &entries, &style);
1829        let mut bib_mut = bib.clone();
1830        doc.add_nodes(&mut bib_mut, &[biblist]);
1831      }
1832
1833      Info!(
1834        "bibliography",
1835        "formatted",
1836        "MakeBibliography: formatted {} entries",
1837        entries.len()
1838      );
1839
1840      // Register formatted bibitems in ObjectDB so CrossRef can resolve citations.
1841      // Port of Perl's approach where bibitems are registered during Scan,
1842      // but here we must register them after MakeBibliography creates them.
1843      let lists_str = bib
1844        .get_attribute("lists")
1845        .unwrap_or_else(|| "bibliography".to_string());
1846      for entry in entries.values() {
1847        let cited_key = entry.cited_key.as_deref().unwrap_or(&entry.bib_key);
1848        // The id format_bib_entry gave its bibitem.
1849        debug_assert!(
1850          entry.bibentry.is_some(),
1851          "included entry {} has no bibentry",
1852          entry.bib_key
1853        );
1854        let Some(bibentry) = entry.bibentry.as_ref() else {
1855          continue;
1856        };
1857        let bibitem_id = bibitem_id(&bib_id, entry, bibentry);
1858
1859        // Register BIBLABEL:{list}:{key} → id
1860        for list in lists_str.split_whitespace() {
1861          let label_key = format!("BIBLABEL:{}:{}", list, cited_key);
1862          self.db.register(&label_key, vec![(
1863            "id",
1864            crate::object_db::Value::from(bibitem_id.as_str()),
1865          )]);
1866        }
1867
1868        // Register ID:{id} with type, location, and number for CrossRef URL
1869        // generation. The author-year metadata (`authors`/`year`/`refnum`/…) the
1870        // fill phase needs is registered by the rescan below, read from the
1871        // bibitem's own `<ltx:tag>` children — see the rescan comment.
1872        let location = doc.site_relative_destination().unwrap_or_default();
1873        let mut values = vec![
1874          ("type", crate::object_db::Value::from("ltx:bibitem")),
1875          ("location", crate::object_db::Value::from(location.as_str())),
1876          ("fragid", crate::object_db::Value::from(bibitem_id.as_str())),
1877        ];
1878        // A labelled entry is cited by its label (its refnum), not a number.
1879        if entry_given_label(entry, &style).is_none() {
1880          values.push((
1881            "number",
1882            crate::object_db::Value::from(entry.shown_number().to_string().as_str()),
1883          ));
1884        }
1885        self.db.register(&format!("ID:{}", bibitem_id), values);
1886      }
1887    }
1888
1889    // Stand in for Perl's rescan of the generated subtree.
1890    //
1891    // Perl `Collector::rescan` (Collector.pm L97) re-runs the WHOLE Scan over
1892    // the post-MakeBibliography document (called at MakeBibliography.pm L71,
1893    // L78), so every id-bearing node in the generated bibliography — the
1894    // enclosing `ltx:biblist`, and any id'd markup CLONED IN from a bibentry
1895    // (an `ltx:Math` in a title, a styled `ltx:text`, …) — lands in the
1896    // ObjectDB. That entry is what `CrossRef::fill_in_frags` ("Any nodes with
1897    // an ID will get a fragid", CrossRef.pm L312-324) needs before it will
1898    // stamp `fragid`, and the HTML5 XSLT's `add_id` emits the HTML `id` from
1899    // `@fragid` ALONE. So an unregistered node reaches HTML with NO id.
1900    //
1901    // This port hand-registers the bibitems just above (Perl's Scan is what
1902    // registers them there) but nothing else, so both classes were lost:
1903    // Perl's `<ul id="bib.L1">` was a bare `<ul>` here, and a `$…$` inside a
1904    // bib title lost the `bib.bib1.m1a` id Perl emits (measured on same-host
1905    // 0.8.8). Registering the whole generated subtree covers both.
1906    //
1907    // Deliberately narrower than Perl's rescan: this restores the id/fragid
1908    // half only. It does NOT re-derive `labels`, relations or the richer
1909    // per-type values a full Scan would, and it never overwrites an entry
1910    // that already exists — the bibitem registrations above (which carry
1911    // `type`/`number`) win. Wiring a real `Collector::rescan` is tracked in
1912    // SYNC_STATUS.
1913    let location = doc.site_relative_destination().unwrap_or_default();
1914    for node in doc.findnodes("//ltx:bibliography//*[@xml:id]") {
1915      let Some(id) = crate::document::get_xml_id(&node) else {
1916        continue;
1917      };
1918      let key = format!("ID:{}", id);
1919      let qname = doc
1920        .get_qname(&node)
1921        .unwrap_or_else(|| "ltx:text".to_string());
1922      if qname == "ltx:bibitem" {
1923        // Faithful to Perl's rescan (MakeBibliography.pm L78 re-runs Scan, whose
1924        // `bibitem_handler` reads the bibitem's `<ltx:tag role="…">` children
1925        // into the DB): augment this bibitem's already-registered ID entry with
1926        // its author-year metadata, read from its OWN generated tags via the
1927        // handler oxide's Scan also uses. CrossRef's fill phase (make_bibcite /
1928        // `fill_in_bibrefs`) then renders an author-year inline citation matching
1929        // the References list; without these values it fell back to the bare
1930        // number (`\cite{beta}` → `2` vs the list's `Beta (2002)`).
1931        // html_feedback #6276/#6302 (inline-vs-list label mismatch).
1932        let props = crate::scan::bibitem_tag_props(&doc, &node);
1933        // The entry as set, for a citation that prints it whole (CrossRef's `FullEntry`, biblatex's `\fullcite`;
1934        // Scan marks `FULLENTRY` when one exists): a copy that outlives this page, so a citation on another split page
1935        // finds it.
1936        let copy = if self.db.lookup("FULLENTRY").is_some() {
1937          self.db.adopt_xml(&node)
1938        } else {
1939          None
1940        };
1941        let year = self.dropped_years.borrow_mut().remove(&id);
1942        if !props.is_empty() || copy.is_some() {
1943          let entry = self.db.register(&key, vec![]);
1944          for (k, v) in props {
1945            entry.set_value(&k, v);
1946          }
1947          if let Some(copy) = copy {
1948            entry.set_value("fullentry", copy);
1949          }
1950          if let Some(year) = year {
1951            entry.set_value("droppedyear", crate::object_db::Value::from(year.as_str()));
1952          }
1953        }
1954      } else if self.db.lookup(&key).is_none() {
1955        // A non-bibitem id-bearing node (an ltx:Math in a title, a styled
1956        // ltx:text, …) cloned into the generated bibliography: register its
1957        // id/fragid so CrossRef can stamp it (Perl's rescan covers these too).
1958        self.db.register(&key, vec![
1959          ("type", crate::object_db::Value::from(qname.as_str())),
1960          ("location", crate::object_db::Value::from(location.as_str())),
1961          ("fragid", crate::object_db::Value::from(id.as_str())),
1962        ]);
1963      }
1964    }
1965
1966    // Remove any remaining bibentry elements (they've been converted to bibitems)
1967    let bibentries = doc.findnodes("//ltx:bibentry");
1968    if !bibentries.is_empty() {
1969      doc.remove_nodes(&bibentries);
1970    }
1971
1972    // Remove empty biblists
1973    let biblists = doc.findnodes("//ltx:biblist");
1974    let empty_lists: Vec<Node> = biblists
1975      .into_iter()
1976      .filter(|n| {
1977        n.get_first_child()
1978          .map(|c| {
1979            let mut has_element = false;
1980            let mut current = Some(c);
1981            while let Some(ref node) = current {
1982              if node.get_type() == Some(libxml::tree::NodeType::ElementNode) {
1983                has_element = true;
1984                break;
1985              }
1986              current = node.get_next_sibling();
1987            }
1988            !has_element
1989          })
1990          .unwrap_or(true)
1991      })
1992      .collect();
1993    if !empty_lists.is_empty() {
1994      doc.remove_nodes(&empty_lists);
1995    }
1996
1997    Ok(vec![doc])
1998  }
1999}
2000
2001// ======================================================================
2002// FMT_SPEC table — defines the block structure for each bibliography type.
2003//
2004// Port of the `%FMT_SPEC` table from MakeBibliography.pm.
2005// Each type has a sequence of blocks.
2006// Each block has a sequence of field specifications.
2007
2008/// A field specification for bibliography formatting.
2009#[derive(Clone)]
2010struct FieldSpec {
2011  /// XPath expression (or "true" for unconditional). Prefix "!" for negation.
2012  xpath:     &'static str,
2013  /// Punctuation to insert before this field (if preceding content exists).
2014  punct:     &'static str,
2015  /// Text prefix.
2016  pre:       &'static str,
2017  /// CSS class (without ltx_bib_ prefix).
2018  class:     &'static str,
2019  /// Formatter function name.
2020  formatter: Formatter,
2021  /// Text suffix.
2022  post:      &'static str,
2023}
2024
2025#[derive(Clone, Copy)]
2026enum Formatter {
2027  Any,
2028  /// Each matched field a unit of its own, joined by biblatex's
2029  /// `\newunitpunct` ". ": the rows of `ltx:bib-subtitle`, which holds both a
2030  /// title's `subtitle` and its `titleaddon` (bibtex.rs; `booksubtitle` and
2031  /// `booktitleaddon`, `mainsubtitle` and `maintitleaddon` likewise). biblatex
2032  /// prints the subtitle inside the title unit and the addon after `\newunit`
2033  /// (biblatex.def:3159-3171 `title`, :3173-3185 `booktitle`, :3187-3199
2034  /// `maintitle`): "Relativistic groups and analyticity. Proceedings of the
2035  /// Eighth Nobel Symposium" (biblatex-examples.bib `salam`). The fields keep
2036  /// their `.bib` order.
2037  Units,
2038  Authors,
2039  EditorsA,
2040  EditorsB,
2041  OtherNames,
2042  Year,
2043  Type,
2044  Title,
2045  ThesisType,
2046  Edition,
2047  Pages,
2048  CrossRef,
2049  Links,
2050  None,
2051}
2052
2053/// Get the FMT_SPEC block specifications for a bibliography type.
2054fn get_fmt_spec(format_type: &str) -> Vec<Vec<FieldSpec>> {
2055  let meta_block: Vec<Vec<FieldSpec>> = vec![
2056    // A translator (bibtex.rs `\bib@field@default@translator`) is read into
2057    // `ltx:bib-name[@role='translator']` and was never printed (Perl's
2058    // FMT_SPEC has no row either); biblatex's standard styles print
2059    // "Trans. by …" (OXIDIZED_DESIGN_DIVERGENCES #289).
2060    vec![FieldSpec {
2061      xpath:     "ltx:bib-name[@role='translator']",
2062      punct:     "",
2063      pre:       "Translated by ",
2064      class:     "translator",
2065      formatter: Formatter::Authors,
2066      post:      "",
2067    }],
2068    // biblatex's `editora`-`editorc` under their `editor[abc]type` roles
2069    // (bibtex.rs `\bib@field@default@editora`): "Karl Kilo (compiler)" where
2070    // biblatex prints "Comp. by Karl Kilo" (biblatex.def:2999-3017). The
2071    // formatter selects the names the rows above do not print.
2072    vec![FieldSpec {
2073      xpath:     "ltx:bib-name",
2074      punct:     "",
2075      pre:       "",
2076      class:     "editor",
2077      formatter: Formatter::OtherNames,
2078      post:      "",
2079    }],
2080    // biblatex's event (`eventtitle`, `venue`, `eventdate`; bibtex.rs
2081    // `\bib@field@default@eventtitle`): "Delta Symposium (Echo City),
2082    // 2002-05-06." (biblatex.def `event+venue+date`).
2083    vec![
2084      FieldSpec {
2085        xpath:     "ltx:bib-related[@type='event']/ltx:bib-title",
2086        punct:     "",
2087        pre:       "",
2088        class:     "event",
2089        formatter: Formatter::Title,
2090        post:      "",
2091      },
2092      FieldSpec {
2093        xpath:     "ltx:bib-related[@type='event']/ltx:bib-subtitle",
2094        punct:     ". ",
2095        pre:       "",
2096        class:     "subtitle",
2097        formatter: Formatter::Units,
2098        post:      "",
2099      },
2100      FieldSpec {
2101        xpath:     "ltx:bib-related[@type='event']/ltx:bib-place",
2102        punct:     " ",
2103        pre:       "(",
2104        class:     "place",
2105        formatter: Formatter::Any,
2106        post:      ")",
2107      },
2108      FieldSpec {
2109        xpath:     "ltx:bib-related[@type='event']/ltx:bib-date",
2110        punct:     ", ",
2111        pre:       "",
2112        class:     "date",
2113        formatter: Formatter::Any,
2114        post:      "",
2115      },
2116      FieldSpec {
2117        xpath:     "true",
2118        punct:     ".",
2119        pre:       "",
2120        class:     "",
2121        formatter: Formatter::None,
2122        post:      "",
2123      },
2124    ],
2125    // A `@periodical`'s issue (an article's is in the journal block).
2126    vec![
2127      FieldSpec {
2128        xpath:     "ltx:bib-related[@type='issue']/ltx:bib-title",
2129        punct:     "",
2130        pre:       "",
2131        class:     "issuetitle",
2132        formatter: Formatter::Title,
2133        post:      "",
2134      },
2135      FieldSpec {
2136        xpath:     "ltx:bib-related[@type='issue']/ltx:bib-subtitle",
2137        punct:     ". ",
2138        pre:       "",
2139        class:     "subtitle",
2140        formatter: Formatter::Units,
2141        post:      "",
2142      },
2143      FieldSpec {
2144        xpath:     "true",
2145        punct:     ".",
2146        pre:       "",
2147        class:     "",
2148        formatter: Formatter::None,
2149        post:      "",
2150      },
2151    ],
2152    // An entry's notes — `note`, `howpublished` and `addendum` are all
2153    // `ltx:bib-note` (bibtex.rs) — are units of their own, as BibTeX's
2154    // `new.block` and biblatex's `\newunit` print them: "Note: Novemberhow.
2155    // Limanote. Mikeaddendum". Perl's `do_any` (MakeBibliography.pm:688) ran
2156    // them together (KNOWN_PERL_ERRORS #280; witness
2157    // biblatex-chicago/cms-notes-sample).
2158    vec![FieldSpec {
2159      xpath:     "ltx:bib-note",
2160      punct:     "",
2161      pre:       "Note: ",
2162      class:     "note",
2163      formatter: Formatter::Units,
2164      post:      "",
2165    }],
2166    // biblatex's `urldate` (bibtex.rs `\bib@field@default@urldate`).
2167    vec![FieldSpec {
2168      xpath:     "ltx:bib-date[@role='accessed']",
2169      punct:     "",
2170      pre:       "Accessed: ",
2171      class:     "accessed",
2172      formatter: Formatter::Any,
2173      post:      "",
2174    }],
2175    vec![FieldSpec {
2176      xpath:     "ltx:bib-links | ltx:bib-review | ltx:bib-identifier | ltx:bib-url",
2177      punct:     "",
2178      pre:       "External Links: ",
2179      class:     "links",
2180      formatter: Formatter::Links,
2181      post:      "",
2182    }],
2183  ];
2184
2185  let mut blocks = match format_type {
2186    "article" => vec![
2187      // Block 1: authors + year
2188      vec![
2189        FieldSpec {
2190          xpath:     "ltx:bib-name[@role='author']",
2191          punct:     "",
2192          pre:       "",
2193          class:     "author",
2194          formatter: Formatter::Authors,
2195          post:      "",
2196        },
2197        FieldSpec {
2198          xpath:     "ltx:bib-date[@role='publication']",
2199          punct:     "",
2200          pre:       "",
2201          class:     "year",
2202          formatter: Formatter::Year,
2203          post:      "",
2204        },
2205      ],
2206      // Block 2: title
2207      vec![
2208        FieldSpec {
2209          xpath:     "ltx:bib-title",
2210          punct:     "",
2211          pre:       "",
2212          class:     "title",
2213          formatter: Formatter::Title,
2214          post:      ".",
2215        },
2216        FieldSpec {
2217          xpath:     "ltx:bib-subtitle",
2218          punct:     " ",
2219          pre:       "",
2220          class:     "subtitle",
2221          formatter: Formatter::Units,
2222          post:      ".",
2223        },
2224      ],
2225      // Block 3: journal details
2226      vec![
2227        FieldSpec {
2228          xpath:     "ltx:bib-part[@role='part']",
2229          punct:     "",
2230          pre:       "",
2231          class:     "part",
2232          formatter: Formatter::Any,
2233          post:      "",
2234        },
2235        // The journal host's title: an article's only titled related object
2236        // until biblatex's main title (`mvbook`) and event (bibtex.rs
2237        // `\bib@field@default@maintitle` / `@eventtitle`) became two more.
2238        FieldSpec {
2239          xpath:     "ltx:bib-related[@type='journal']/ltx:bib-title",
2240          punct:     ", ",
2241          pre:       "",
2242          class:     "journal",
2243          formatter: Formatter::Any,
2244          post:      "",
2245        },
2246        FieldSpec {
2247          xpath:     "ltx:bib-part[@role='volume']",
2248          punct:     " ",
2249          pre:       "",
2250          class:     "volume",
2251          formatter: Formatter::Any,
2252          post:      "",
2253        },
2254        FieldSpec {
2255          xpath:     "ltx:bib-part[@role='number']",
2256          punct:     " ",
2257          pre:       "(",
2258          class:     "number",
2259          formatter: Formatter::Any,
2260          post:      ")",
2261        },
2262        // biblatex's issue title, a part of the journal host: "Journal Name
2263        // (2003): Foxtrot Special Issue" (biblatex.def:3230-3240 `issue`).
2264        FieldSpec {
2265          xpath:     "ltx:bib-related/ltx:bib-related[@type='issue']/ltx:bib-title",
2266          punct:     ": ",
2267          pre:       "",
2268          class:     "issuetitle",
2269          formatter: Formatter::Title,
2270          post:      "",
2271        },
2272        FieldSpec {
2273          xpath:     "ltx:bib-related/ltx:bib-related[@type='issue']/ltx:bib-subtitle",
2274          punct:     ". ",
2275          pre:       "",
2276          class:     "subtitle",
2277          formatter: Formatter::Units,
2278          post:      "",
2279        },
2280        FieldSpec {
2281          xpath:     "ltx:bib-status",
2282          punct:     ", ",
2283          pre:       "(",
2284          class:     "status",
2285          formatter: Formatter::Any,
2286          post:      ")",
2287        },
2288        FieldSpec {
2289          xpath:     "ltx:bib-part[@role='pages']",
2290          punct:     ", ",
2291          pre:       "",
2292          class:     "pages",
2293          formatter: Formatter::Pages,
2294          post:      "",
2295        },
2296        FieldSpec {
2297          xpath:     "ltx:bib-language",
2298          punct:     " ",
2299          pre:       "(",
2300          class:     "language",
2301          formatter: Formatter::Any,
2302          post:      ")",
2303        },
2304        FieldSpec {
2305          xpath:     "true",
2306          punct:     ".",
2307          pre:       "",
2308          class:     "",
2309          formatter: Formatter::None,
2310          post:      "",
2311        },
2312      ],
2313    ],
2314    "book" => vec![
2315      vec![
2316        FieldSpec {
2317          xpath:     "ltx:bib-name[@role='author']",
2318          punct:     "",
2319          pre:       "",
2320          class:     "author",
2321          formatter: Formatter::Authors,
2322          post:      "",
2323        },
2324        // ", " after the author, as the editor follows other fields
2325        // (`do_editorsB` rows); Perl's "" glued "HandelAtlanta Symphony (Ed.)"
2326        // (MakeBibliography.pm:708, :752, :769, :783; KNOWN_PERL_ERRORS #280;
2327        // witness biblatex-chicago/cms-notes-sample).
2328        FieldSpec {
2329          xpath:     "ltx:bib-name[@role='editor']",
2330          punct:     ", ",
2331          pre:       "",
2332          class:     "editor",
2333          formatter: Formatter::EditorsA,
2334          post:      "",
2335        },
2336        FieldSpec {
2337          xpath:     "ltx:bib-date[@role='publication']",
2338          punct:     "",
2339          pre:       "",
2340          class:     "year",
2341          formatter: Formatter::Year,
2342          post:      "",
2343        },
2344      ],
2345      vec![
2346        FieldSpec {
2347          xpath:     "ltx:bib-title",
2348          punct:     "",
2349          pre:       "",
2350          class:     "title",
2351          formatter: Formatter::Title,
2352          post:      ".",
2353        },
2354        FieldSpec {
2355          xpath:     "ltx:bib-subtitle",
2356          punct:     " ",
2357          pre:       "",
2358          class:     "subtitle",
2359          formatter: Formatter::Units,
2360          post:      ".",
2361        },
2362      ],
2363      vec![
2364        FieldSpec {
2365          xpath:     "ltx:bib-type",
2366          punct:     "",
2367          pre:       "",
2368          class:     "type",
2369          formatter: Formatter::Any,
2370          post:      "",
2371        },
2372        FieldSpec {
2373          xpath:     "ltx:bib-edition",
2374          punct:     ", ",
2375          pre:       "",
2376          class:     "edition",
2377          formatter: Formatter::Edition,
2378          post:      "",
2379        },
2380        FieldSpec {
2381          xpath:     "ltx:bib-part[@role='series']",
2382          punct:     ", ",
2383          pre:       "",
2384          class:     "series",
2385          formatter: Formatter::Any,
2386          post:      "",
2387        },
2388        FieldSpec {
2389          xpath:     "ltx:bib-part[@role='volume']",
2390          punct:     ", ",
2391          pre:       "Vol. ",
2392          class:     "volume",
2393          formatter: Formatter::Any,
2394          post:      "",
2395        },
2396        FieldSpec {
2397          xpath:     "ltx:bib-part[@role='part']",
2398          punct:     ", ",
2399          pre:       "Part ",
2400          class:     "part",
2401          formatter: Formatter::Any,
2402          post:      "",
2403        },
2404        FieldSpec {
2405          xpath:     "ltx:bib-publisher",
2406          punct:     ", ",
2407          pre:       " ",
2408          class:     "publisher",
2409          formatter: Formatter::Any,
2410          post:      "",
2411        },
2412        FieldSpec {
2413          xpath:     "ltx:bib-organization",
2414          punct:     ", ",
2415          pre:       " ",
2416          class:     "publisher",
2417          formatter: Formatter::Any,
2418          post:      "",
2419        },
2420        FieldSpec {
2421          xpath:     "ltx:bib-place",
2422          punct:     ", ",
2423          pre:       "",
2424          class:     "place",
2425          formatter: Formatter::Any,
2426          post:      "",
2427        },
2428        FieldSpec {
2429          xpath:     "ltx:bib-status",
2430          punct:     " ",
2431          pre:       "(",
2432          class:     "status",
2433          formatter: Formatter::Any,
2434          post:      ")",
2435        },
2436        FieldSpec {
2437          xpath:     "ltx:bib-language",
2438          punct:     " ",
2439          pre:       "(",
2440          class:     "language",
2441          formatter: Formatter::Any,
2442          post:      ")",
2443        },
2444        FieldSpec {
2445          xpath:     "true",
2446          punct:     ".",
2447          pre:       "",
2448          class:     "",
2449          formatter: Formatter::None,
2450          post:      "",
2451        },
2452      ],
2453    ],
2454    "incollection" => vec![
2455      vec![
2456        FieldSpec {
2457          xpath:     "ltx:bib-name[@role='author']",
2458          punct:     "",
2459          pre:       "",
2460          class:     "author",
2461          formatter: Formatter::Authors,
2462          post:      "",
2463        },
2464        FieldSpec {
2465          xpath:     "ltx:bib-date[@role='publication']",
2466          punct:     "",
2467          pre:       "",
2468          class:     "year",
2469          formatter: Formatter::Year,
2470          post:      "",
2471        },
2472      ],
2473      vec![
2474        FieldSpec {
2475          xpath:     "ltx:bib-title",
2476          punct:     "",
2477          pre:       "",
2478          class:     "title",
2479          formatter: Formatter::Title,
2480          post:      ".",
2481        },
2482        FieldSpec {
2483          xpath:     "ltx:bib-subtitle",
2484          punct:     " ",
2485          pre:       "",
2486          class:     "subtitle",
2487          formatter: Formatter::Units,
2488          post:      ".",
2489        },
2490      ],
2491      vec![
2492        FieldSpec {
2493          xpath:     "ltx:bib-type",
2494          punct:     "",
2495          pre:       "",
2496          class:     "type",
2497          formatter: Formatter::Any,
2498          post:      "",
2499        },
2500        FieldSpec {
2501          xpath:     "ltx:bib-related[@bibrefs]",
2502          punct:     " ",
2503          pre:       "See ",
2504          class:     "crossref",
2505          formatter: Formatter::CrossRef,
2506          post:      ",",
2507        },
2508        // "In <main title>. <main subtitle>. <book title>, <book subtitle>,":
2509        // biblatex's main title is the host of the book, nested in it (bibtex.rs
2510        // `\bib@field@inbook@maintitle`), and precedes it (biblatex.def
2511        // `maintitle+booktitle`, standard.bbx:260). The "In " is its own row so
2512        // that whichever title comes first carries it; an entry without a
2513        // main title prints exactly Perl's row (MakeBibliography.pm:720-721).
2514        FieldSpec {
2515          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-title",
2516          punct:     " ",
2517          pre:       "In ",
2518          class:     "",
2519          formatter: Formatter::None,
2520          post:      "",
2521        },
2522        FieldSpec {
2523          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@role='host']/ltx:bib-title",
2524          punct:     "",
2525          pre:       "",
2526          class:     "maintitle",
2527          formatter: Formatter::Title,
2528          post:      ". ",
2529        },
2530        FieldSpec {
2531          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@role='host']/ltx:bib-subtitle",
2532          punct:     "",
2533          pre:       "",
2534          class:     "subtitle",
2535          formatter: Formatter::Units,
2536          post:      ". ",
2537        },
2538        FieldSpec {
2539          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-title",
2540          punct:     "",
2541          pre:       "",
2542          class:     "inbook",
2543          formatter: Formatter::Title,
2544          post:      ",",
2545        },
2546        // biblatex's `booksubtitle`/`booktitleaddon` (bibtex.rs
2547        // `\bib@field@default@booksubtitle`).
2548        FieldSpec {
2549          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-subtitle",
2550          punct:     " ",
2551          pre:       "",
2552          class:     "subtitle",
2553          formatter: Formatter::Units,
2554          post:      ",",
2555        },
2556        // The event of the proceedings (biblatex's `eventtitle`/`venue`/
2557        // `eventdate` of an `@inproceedings`, bibtex.rs
2558        // `\bib@field@inproceedings@eventtitle`): "Delta Symposium (Echo City),
2559        // 2002-05-06" (biblatex.def `event+venue+date`).
2560        FieldSpec {
2561          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-title",
2562          punct:     " ",
2563          pre:       "",
2564          class:     "event",
2565          formatter: Formatter::Title,
2566          post:      "",
2567        },
2568        FieldSpec {
2569          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-subtitle",
2570          punct:     ". ",
2571          pre:       "",
2572          class:     "subtitle",
2573          formatter: Formatter::Units,
2574          post:      "",
2575        },
2576        FieldSpec {
2577          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-place",
2578          punct:     " ",
2579          pre:       "(",
2580          class:     "place",
2581          formatter: Formatter::Any,
2582          post:      ")",
2583        },
2584        FieldSpec {
2585          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-date",
2586          punct:     ", ",
2587          pre:       "",
2588          class:     "date",
2589          formatter: Formatter::Any,
2590          post:      "",
2591        },
2592        FieldSpec {
2593          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-name[@role='editor']",
2594          punct:     " ",
2595          pre:       " ",
2596          class:     "editor",
2597          formatter: Formatter::EditorsA,
2598          post:      ",",
2599        },
2600      ],
2601      vec![
2602        // The host's edition: `\bib@field@inbook@edition` and
2603        // `\bib@field@incollection@edition` (bibtex.rs) file it under the host
2604        // `bib-related`, where no row read it — an in-book/in-collection entry lost
2605        // its edition, as `@inreference`/`@bookinbook` do once aliased (Oxford
2606        // English Dictionary "2nd ed.", cms-notes-sample).
2607        FieldSpec {
2608          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-edition",
2609          punct:     "",
2610          pre:       "",
2611          class:     "edition",
2612          formatter: Formatter::Edition,
2613          post:      "",
2614        },
2615        FieldSpec {
2616          xpath:     "ltx:bib-edition",
2617          punct:     "",
2618          pre:       "",
2619          class:     "edition",
2620          formatter: Formatter::Edition,
2621          post:      "",
2622        },
2623        FieldSpec {
2624          xpath:     "ltx:bib-name[@role='editor']",
2625          punct:     ", ",
2626          pre:       "",
2627          class:     "editor",
2628          formatter: Formatter::EditorsB,
2629          post:      "",
2630        },
2631        FieldSpec {
2632          xpath:     "ltx:bib-related/ltx:bib-part[@role='series']",
2633          punct:     ", ",
2634          pre:       "",
2635          class:     "series",
2636          formatter: Formatter::Any,
2637          post:      "",
2638        },
2639        FieldSpec {
2640          xpath:     "ltx:bib-related/ltx:bib-part[@role='volume']",
2641          punct:     ", ",
2642          pre:       "Vol. ",
2643          class:     "volume",
2644          formatter: Formatter::Any,
2645          post:      "",
2646        },
2647        FieldSpec {
2648          xpath:     "ltx:bib-related/ltx:bib-part[@role='part']",
2649          punct:     ", ",
2650          pre:       "Part ",
2651          class:     "part",
2652          formatter: Formatter::Any,
2653          post:      "",
2654        },
2655        FieldSpec {
2656          xpath:     "ltx:bib-publisher",
2657          punct:     ", ",
2658          pre:       " ",
2659          class:     "publisher",
2660          formatter: Formatter::Any,
2661          post:      "",
2662        },
2663        // The host's publisher and place: the `.bib` reader files them under
2664        // `ltx:bib-related` for `@inbook`/`@incollection`/`@inproceedings`
2665        // (bibtex.rs `\bib@field@incollection@publisher`, BibTeX.pool.ltxml:402),
2666        // which the direct-child specs never reached. Perl's formatter
2667        // (MakeBibliography.pm:742-744) reads only the direct children too, so it
2668        // drops the host's publisher and place (DIVERGENCES #286): the biblatex
2669        // manuals' "New York: Springer-Verlag" (sweep 120). Gated like Perl's
2670        // other host rows (:732-734): a crossref'd entry shows "See [parent]"
2671        // instead, as plain.bst's `format.incoll.inproc.crossref` does.
2672        FieldSpec {
2673          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-publisher",
2674          punct:     ", ",
2675          pre:       " ",
2676          class:     "publisher",
2677          formatter: Formatter::Any,
2678          post:      "",
2679        },
2680        FieldSpec {
2681          xpath:     "ltx:bib-organization",
2682          punct:     ", ",
2683          pre:       "",
2684          class:     "publisher",
2685          formatter: Formatter::Any,
2686          post:      "",
2687        },
2688        FieldSpec {
2689          xpath:     "ltx:bib-place",
2690          punct:     ", ",
2691          pre:       "",
2692          class:     "place",
2693          formatter: Formatter::Any,
2694          post:      "",
2695        },
2696        FieldSpec {
2697          xpath:     "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-place",
2698          punct:     ", ",
2699          pre:       "",
2700          class:     "place",
2701          formatter: Formatter::Any,
2702          post:      "",
2703        },
2704        FieldSpec {
2705          xpath:     "ltx:bib-part[@role='pages']",
2706          punct:     ", ",
2707          pre:       "",
2708          class:     "pages",
2709          formatter: Formatter::Pages,
2710          post:      "",
2711        },
2712        FieldSpec {
2713          xpath:     "ltx:bib-status",
2714          punct:     " ",
2715          pre:       "(",
2716          class:     "status",
2717          formatter: Formatter::Any,
2718          post:      ")",
2719        },
2720        FieldSpec {
2721          xpath:     "ltx:bib-language",
2722          punct:     " ",
2723          pre:       "(",
2724          class:     "language",
2725          formatter: Formatter::Any,
2726          post:      ")",
2727        },
2728        FieldSpec {
2729          xpath:     "true",
2730          punct:     ".",
2731          pre:       "",
2732          class:     "",
2733          formatter: Formatter::None,
2734          post:      "",
2735        },
2736      ],
2737    ],
2738    "report" => vec![
2739      vec![
2740        FieldSpec {
2741          xpath:     "ltx:bib-name[@role='author']",
2742          punct:     "",
2743          pre:       "",
2744          class:     "author",
2745          formatter: Formatter::Authors,
2746          post:      "",
2747        },
2748        // ", " after the author, as the editor follows other fields
2749        // (`do_editorsB` rows); Perl's "" glued "HandelAtlanta Symphony (Ed.)"
2750        // (MakeBibliography.pm:708, :752, :769, :783; KNOWN_PERL_ERRORS #280;
2751        // witness biblatex-chicago/cms-notes-sample).
2752        FieldSpec {
2753          xpath:     "ltx:bib-name[@role='editor']",
2754          punct:     ", ",
2755          pre:       "",
2756          class:     "editor",
2757          formatter: Formatter::EditorsA,
2758          post:      "",
2759        },
2760        FieldSpec {
2761          xpath:     "ltx:bib-date[@role='publication']",
2762          punct:     "",
2763          pre:       "",
2764          class:     "year",
2765          formatter: Formatter::Year,
2766          post:      "",
2767        },
2768      ],
2769      vec![
2770        FieldSpec {
2771          xpath:     "ltx:bib-title",
2772          punct:     "",
2773          pre:       "",
2774          class:     "title",
2775          formatter: Formatter::Title,
2776          post:      ".",
2777        },
2778        FieldSpec {
2779          xpath:     "ltx:bib-subtitle",
2780          punct:     " ",
2781          pre:       "",
2782          class:     "subtitle",
2783          formatter: Formatter::Units,
2784          post:      ".",
2785        },
2786      ],
2787      vec![FieldSpec {
2788        xpath:     "ltx:bib-type",
2789        punct:     "",
2790        pre:       "",
2791        class:     "type",
2792        formatter: Formatter::Any,
2793        post:      "",
2794      }],
2795      vec![
2796        FieldSpec {
2797          xpath:     "ltx:bib-part[@role='number']",
2798          punct:     "",
2799          pre:       "Technical Report ",
2800          class:     "number",
2801          formatter: Formatter::Any,
2802          post:      "",
2803        },
2804        FieldSpec {
2805          xpath:     "ltx:bib-part[@role='series']",
2806          punct:     ", ",
2807          pre:       "",
2808          class:     "series",
2809          formatter: Formatter::Any,
2810          post:      "",
2811        },
2812        FieldSpec {
2813          xpath:     "ltx:bib-part[@role='volume']",
2814          punct:     ", ",
2815          pre:       "Vol. ",
2816          class:     "volume",
2817          formatter: Formatter::Any,
2818          post:      "",
2819        },
2820        FieldSpec {
2821          xpath:     "ltx:bib-part[@role='part']",
2822          punct:     ", ",
2823          pre:       "Part ",
2824          class:     "part",
2825          formatter: Formatter::Any,
2826          post:      "",
2827        },
2828        FieldSpec {
2829          xpath:     "ltx:bib-publisher",
2830          punct:     ", ",
2831          pre:       " ",
2832          class:     "publisher",
2833          formatter: Formatter::Any,
2834          post:      "",
2835        },
2836        FieldSpec {
2837          xpath:     "ltx:bib-organization",
2838          punct:     ", ",
2839          pre:       " ",
2840          class:     "publisher",
2841          formatter: Formatter::Any,
2842          post:      "",
2843        },
2844        FieldSpec {
2845          xpath:     "ltx:bib-place",
2846          punct:     ", ",
2847          pre:       " ",
2848          class:     "place",
2849          formatter: Formatter::Any,
2850          post:      "",
2851        },
2852        FieldSpec {
2853          xpath:     "ltx:bib-status",
2854          punct:     ", ",
2855          pre:       "(",
2856          class:     "status",
2857          formatter: Formatter::Any,
2858          post:      ")",
2859        },
2860        FieldSpec {
2861          xpath:     "ltx:bib-language",
2862          punct:     " ",
2863          pre:       "(",
2864          class:     "language",
2865          formatter: Formatter::Any,
2866          post:      ")",
2867        },
2868        FieldSpec {
2869          xpath:     "true",
2870          punct:     ".",
2871          pre:       "",
2872          class:     "",
2873          formatter: Formatter::None,
2874          post:      "",
2875        },
2876      ],
2877    ],
2878    "thesis" => vec![
2879      vec![
2880        FieldSpec {
2881          xpath:     "ltx:bib-name[@role='author']",
2882          punct:     "",
2883          pre:       "",
2884          class:     "author",
2885          formatter: Formatter::Authors,
2886          post:      "",
2887        },
2888        // ", " after the author, as the editor follows other fields
2889        // (`do_editorsB` rows); Perl's "" glued "HandelAtlanta Symphony (Ed.)"
2890        // (MakeBibliography.pm:708, :752, :769, :783; KNOWN_PERL_ERRORS #280;
2891        // witness biblatex-chicago/cms-notes-sample).
2892        FieldSpec {
2893          xpath:     "ltx:bib-name[@role='editor']",
2894          punct:     ", ",
2895          pre:       "",
2896          class:     "editor",
2897          formatter: Formatter::EditorsA,
2898          post:      "",
2899        },
2900        FieldSpec {
2901          xpath:     "ltx:bib-date[@role='publication']",
2902          punct:     "",
2903          pre:       "",
2904          class:     "year",
2905          formatter: Formatter::Year,
2906          post:      "",
2907        },
2908      ],
2909      vec![
2910        FieldSpec {
2911          xpath:     "ltx:bib-title",
2912          punct:     "",
2913          pre:       "",
2914          class:     "title",
2915          formatter: Formatter::Title,
2916          post:      ".",
2917        },
2918        FieldSpec {
2919          xpath:     "ltx:bib-subtitle",
2920          punct:     " ",
2921          pre:       "",
2922          class:     "subtitle",
2923          formatter: Formatter::Units,
2924          post:      ".",
2925        },
2926      ],
2927      vec![
2928        FieldSpec {
2929          xpath:     "ltx:bib-type",
2930          punct:     " ",
2931          pre:       "",
2932          class:     "type",
2933          formatter: Formatter::ThesisType,
2934          post:      "",
2935        },
2936        FieldSpec {
2937          xpath:     "ltx:bib-part[@role='part']",
2938          punct:     ", ",
2939          pre:       "Part ",
2940          class:     "part",
2941          formatter: Formatter::Any,
2942          post:      "",
2943        },
2944        FieldSpec {
2945          xpath:     "ltx:bib-publisher",
2946          punct:     ", ",
2947          pre:       "",
2948          class:     "publisher",
2949          formatter: Formatter::Any,
2950          post:      "",
2951        },
2952        FieldSpec {
2953          xpath:     "ltx:bib-organization",
2954          punct:     ", ",
2955          pre:       "",
2956          class:     "publisher",
2957          formatter: Formatter::Any,
2958          post:      "",
2959        },
2960        FieldSpec {
2961          xpath:     "ltx:bib-place",
2962          punct:     ", ",
2963          pre:       "",
2964          class:     "place",
2965          formatter: Formatter::Any,
2966          post:      "",
2967        },
2968        FieldSpec {
2969          xpath:     "ltx:bib-status",
2970          punct:     ", ",
2971          pre:       "(",
2972          class:     "status",
2973          formatter: Formatter::Any,
2974          post:      ")",
2975        },
2976        FieldSpec {
2977          xpath:     "ltx:bib-language",
2978          punct:     ", ",
2979          pre:       "(",
2980          class:     "language",
2981          formatter: Formatter::Any,
2982          post:      ")",
2983        },
2984        FieldSpec {
2985          xpath:     "true",
2986          punct:     ".",
2987          pre:       "",
2988          class:     "",
2989          formatter: Formatter::None,
2990          post:      "",
2991        },
2992      ],
2993    ],
2994    "website" => vec![
2995      vec![
2996        FieldSpec {
2997          xpath:     "ltx:bib-name[@role='author']",
2998          punct:     "",
2999          pre:       "",
3000          class:     "author",
3001          formatter: Formatter::Authors,
3002          post:      "",
3003        },
3004        // ", " after the author, as the editor follows other fields
3005        // (`do_editorsB` rows); Perl's "" glued "HandelAtlanta Symphony (Ed.)"
3006        // (MakeBibliography.pm:708, :752, :769, :783; KNOWN_PERL_ERRORS #280;
3007        // witness biblatex-chicago/cms-notes-sample).
3008        FieldSpec {
3009          xpath:     "ltx:bib-name[@role='editor']",
3010          punct:     ", ",
3011          pre:       "",
3012          class:     "editor",
3013          formatter: Formatter::EditorsA,
3014          post:      "",
3015        },
3016        FieldSpec {
3017          xpath:     "ltx:bib-date[@role='publication']",
3018          punct:     "",
3019          pre:       "",
3020          class:     "year",
3021          formatter: Formatter::Year,
3022          post:      "",
3023        },
3024        // The website's title and type share the name block (Perl
3025        // MakeBibliography.pm:781-787), all with "" punctuation: "V.
3026        // JacobsonModified TCP…(Website)". The title follows the name and year
3027        // after a space, as a title's block follows theirs in every other type,
3028        // and the type after a space, as Perl's other parenthesized rows
3029        // (`status`, `language`) do (KNOWN_PERL_ERRORS #280; witness
3030        // biblatex-ieee/biblatex-ieee).
3031        FieldSpec {
3032          xpath:     "ltx:bib-title",
3033          punct:     " ",
3034          pre:       "",
3035          class:     "title",
3036          formatter: Formatter::Any,
3037          post:      "",
3038        },
3039        FieldSpec {
3040          xpath:     "ltx:bib-subtitle",
3041          punct:     " ",
3042          pre:       "",
3043          class:     "subtitle",
3044          formatter: Formatter::Units,
3045          post:      "",
3046        },
3047        FieldSpec {
3048          xpath:     "ltx:bib-type",
3049          punct:     " ",
3050          pre:       "",
3051          class:     "type",
3052          formatter: Formatter::Any,
3053          post:      "",
3054        },
3055        FieldSpec {
3056          xpath:     "! ltx:bib-type",
3057          punct:     " ",
3058          pre:       "",
3059          class:     "type",
3060          formatter: Formatter::None,
3061          post:      "(Website)",
3062        },
3063      ],
3064      vec![
3065        FieldSpec {
3066          xpath:     "ltx:bib-organization",
3067          punct:     ", ",
3068          pre:       " ",
3069          class:     "publisher",
3070          formatter: Formatter::Any,
3071          post:      "",
3072        },
3073        FieldSpec {
3074          xpath:     "ltx:bib-place",
3075          punct:     ", ",
3076          pre:       "",
3077          class:     "place",
3078          formatter: Formatter::Any,
3079          post:      "",
3080        },
3081        FieldSpec {
3082          xpath:     "true",
3083          punct:     ".",
3084          pre:       "",
3085          class:     "",
3086          formatter: Formatter::None,
3087          post:      "",
3088        },
3089      ],
3090    ],
3091    "software" => vec![
3092      vec![
3093        FieldSpec {
3094          xpath:     "ltx:bib-key",
3095          punct:     "",
3096          pre:       "",
3097          class:     "key",
3098          formatter: Formatter::Any,
3099          post:      "",
3100        },
3101        // "(Type)" after the key with a space (Perl MakeBibliography.pm:794
3102        // has ""), as the website's type (KNOWN_PERL_ERRORS #280).
3103        FieldSpec {
3104          xpath:     "ltx:bib-type",
3105          punct:     " ",
3106          pre:       "",
3107          class:     "type",
3108          formatter: Formatter::Type,
3109          post:      "",
3110        },
3111      ],
3112      vec![
3113        FieldSpec {
3114          xpath:     "ltx:bib-title",
3115          punct:     "",
3116          pre:       "",
3117          class:     "title",
3118          formatter: Formatter::Any,
3119          post:      "",
3120        },
3121        FieldSpec {
3122          xpath:     "ltx:bib-subtitle",
3123          punct:     " ",
3124          pre:       "",
3125          class:     "subtitle",
3126          formatter: Formatter::Units,
3127          post:      "",
3128        },
3129      ],
3130      vec![
3131        FieldSpec {
3132          xpath:     "ltx:bib-organization",
3133          punct:     ", ",
3134          pre:       " ",
3135          class:     "publisher",
3136          formatter: Formatter::Any,
3137          post:      "",
3138        },
3139        FieldSpec {
3140          xpath:     "ltx:bib-place",
3141          punct:     ", ",
3142          pre:       "",
3143          class:     "place",
3144          formatter: Formatter::Any,
3145          post:      "",
3146        },
3147        FieldSpec {
3148          xpath:     "true",
3149          punct:     ".",
3150          pre:       "",
3151          class:     "",
3152          formatter: Formatter::None,
3153          post:      "",
3154        },
3155      ],
3156    ],
3157    _ => vec![
3158      // Default: same as book
3159      vec![
3160        FieldSpec {
3161          xpath:     "ltx:bib-name[@role='author']",
3162          punct:     "",
3163          pre:       "",
3164          class:     "author",
3165          formatter: Formatter::Authors,
3166          post:      "",
3167        },
3168        FieldSpec {
3169          xpath:     "ltx:bib-date[@role='publication']",
3170          punct:     "",
3171          pre:       "",
3172          class:     "year",
3173          formatter: Formatter::Year,
3174          post:      "",
3175        },
3176      ],
3177      vec![
3178        FieldSpec {
3179          xpath:     "ltx:bib-title",
3180          punct:     "",
3181          pre:       "",
3182          class:     "title",
3183          formatter: Formatter::Title,
3184          post:      ".",
3185        },
3186        FieldSpec {
3187          xpath:     "ltx:bib-subtitle",
3188          punct:     " ",
3189          pre:       "",
3190          class:     "subtitle",
3191          formatter: Formatter::Units,
3192          post:      ".",
3193        },
3194      ],
3195    ],
3196  };
3197  // biblatex's main title, the multi-volume work (an entry's own `mvbook` host
3198  // unless the entry is a part, whose book host carries it; bibtex.rs
3199  // `\bib@field@default@maintitle`), precedes the title in every format:
3200  // "Hotel Collected Papers. Golf Letters." (standard.bbx:211 `maintitle+title`).
3201  for block in &mut blocks {
3202    if let Some(at) = block.iter().position(|spec| spec.xpath == "ltx:bib-title") {
3203      let main_title = [
3204        FieldSpec {
3205          xpath:     "ltx:bib-related[@type='mvbook']/ltx:bib-title",
3206          punct:     "",
3207          pre:       "",
3208          class:     "maintitle",
3209          formatter: Formatter::Title,
3210          post:      ". ",
3211        },
3212        FieldSpec {
3213          xpath:     "ltx:bib-related[@type='mvbook']/ltx:bib-subtitle",
3214          punct:     "",
3215          pre:       "",
3216          class:     "subtitle",
3217          formatter: Formatter::Units,
3218          post:      ". ",
3219        },
3220      ];
3221      block.splice(at..at, main_title);
3222      break;
3223    }
3224  }
3225  // biblatex's article driver prints the editors after the journal and before
3226  // the pages (standard.bbx:46-48 `byeditor+others` then `note+pages`: "In:
3227  // Chronicle. Ed. by Clare Naudziunas, pp. 12–14."); a `.bst`'s `article`
3228  // prints none (plain.bst), so the row is biblatex's only. Witnesses
3229  // biblatex-chicago cms-notes/dates/trad-sample.
3230  if format_type == "article"
3231    && is_biblatex_bibliography()
3232    && let Some(block) = blocks.iter_mut().find(|block| {
3233      block
3234        .iter()
3235        .any(|f| f.xpath == "ltx:bib-part[@role='pages']")
3236    })
3237    && let Some(at) = block
3238      .iter()
3239      .position(|f| f.xpath == "ltx:bib-part[@role='pages']")
3240  {
3241    block.insert(at, FieldSpec {
3242      xpath:     "ltx:bib-name[@role='editor']",
3243      punct:     ". ",
3244      pre:       "Edited by ",
3245      class:     "editor",
3246      formatter: Formatter::Authors,
3247      post:      "",
3248    });
3249  }
3250  blocks.extend(meta_block);
3251  blocks
3252}
3253
3254// ======================================================================
3255// Formatting helpers
3256
3257/// The renderable content of one bibliography field node.
3258///
3259/// Perl's field formatters are all `do_any`-shaped — they receive
3260/// `$doc->cloneNodes(@nodes)` and return the CLONED NODES (`MakeBibliography.pm`
3261/// L525-531, L550-552), so an `ltx:ref`/`ltx:emph`/`ltx:Math` inside a field
3262/// reaches the bibitem intact. Taking `get_content()` here instead threw all of
3263/// that away and kept only the text, which is how `note = {\url{...}}` rendered
3264/// as dead text even once the field XML carried a proper link.
3265///
3266/// Fields whose content is plain text — the overwhelming majority — keep
3267/// returning a single `Text` node, so their output is byte-identical to before;
3268/// only a field that actually holds markup takes the cloning path. (Perl clones
3269/// the field element itself and lets the XSLT render it transparently; we clone
3270/// its CHILDREN, which yields the same HTML without changing our flatter
3271/// intermediate shape.)
3272fn field_content(node: &Node) -> Vec<NodeData> {
3273  let mut children = Vec::new();
3274  let mut child = node.get_first_child();
3275  let mut has_element = false;
3276  while let Some(n) = child {
3277    has_element |= n.get_type() == Some(libxml::tree::NodeType::ElementNode);
3278    child = n.get_next_sibling();
3279    children.push(n);
3280  }
3281  if has_element {
3282    children.into_iter().map(NodeData::XmlNode).collect()
3283  } else {
3284    vec![NodeData::Text(node.get_content())]
3285  }
3286}
3287
3288/// biblatex's punctuation tracker (biblatex.sty:2118-2130 `\blx@addpunct`):
3289/// `\addperiod` adds nothing after a text that already ends in a mark, since
3290/// `\DeclarePunctuationPairs{period}{}` (:2026) pairs the period with none of
3291/// them. Closing brackets and quotes are transparent (space-factor code 0,
3292/// biblatex.sty:549, :1749-1754). pdflatex + biber print "What is X? A
3293/// survey", "Second (2nd ed.) Addon", "In the U.S.A. Addon", "Ends with colon:
3294/// Addon".
3295fn ends_with_punctuation(text: &str) -> bool {
3296  text
3297    .trim_end()
3298    .trim_end_matches([')', ']', '>', '\'', '`', '’', '”', '"'])
3299    .ends_with(['.', '?', '!', ',', ';', ':', '…'])
3300}
3301
3302/// The fields `nodes` in order, `separator` between two of them: after a field
3303/// whose printed text already ends in a mark ([`node_trailing_text`],
3304/// [`ends_with_punctuation`]) only its space, and a blank field prints nothing.
3305/// A field is blank when it has neither text nor an element — a
3306/// `note = {\citet{knuth}}` holds an `ltx:bibref` CrossRef fills only later
3307/// (as `crossref.rs` `fill_in_glossaryrefs` tests emptiness); such a reference,
3308/// like a formula, ends in no mark.
3309fn join_fields(nodes: &[Node], separator: &str) -> Vec<NodeData> {
3310  let space = separator.trim_start_matches(|c: char| !c.is_whitespace());
3311  let mut result = Vec::new();
3312  // Whether a field was printed, and whether it ended in a mark.
3313  let mut previous: Option<bool> = None;
3314  for node in nodes {
3315    if node.get_content().trim().is_empty() && node.get_first_element_child().is_none() {
3316      continue;
3317    }
3318    if let Some(ends_in_mark) = previous {
3319      let joint = if ends_in_mark { space } else { separator };
3320      result.push(NodeData::Text(joint.to_string()));
3321    }
3322    result.extend(field_content(node));
3323    previous = Some(node_trailing_text(node).is_some_and(|text| ends_with_punctuation(&text)));
3324  }
3325  result
3326}
3327
3328/// Push a row's `punct` or `post` text onto the block's `items`. A leading
3329/// period ("." ending a unit, ". " separating two) is dropped when the text
3330/// before it already ends in a mark, by the style's [`PeriodRule`].
3331fn push_unit_text(items: &mut Vec<NodeData>, text: &str) {
3332  let text = match text.strip_prefix('.') {
3333    Some(rest)
3334      if trailing_text(items)
3335        .is_some_and(|last| PERIOD_RULE.with(std::cell::Cell::get).absorbs_period(&last)) =>
3336    {
3337      rest
3338    },
3339    _ => text,
3340  };
3341  if !text.is_empty() {
3342    items.push(NodeData::Text(text.to_string()));
3343  }
3344}
3345
3346/// The last non-blank text of `items`, as it will print. A formula ends in
3347/// no mark — "$n!$" ends in math: after `$` BibTeX's `add.period$` sees no
3348/// mark, and the space factor biblatex's tracker reads is reset — and
3349/// neither does a reference whose text the cross-referencer fills in later;
3350/// both read as the empty text.
3351fn trailing_text(items: &[NodeData]) -> Option<String> {
3352  items.iter().rev().find_map(|item| match item {
3353    NodeData::Text(text) => (!text.trim().is_empty()).then(|| text.clone()),
3354    NodeData::Element { tag, children, .. } => {
3355      element_trailing_text(tag, || trailing_text(children))
3356    },
3357    NodeData::XmlNode(node) => node_trailing_text(node),
3358  })
3359}
3360
3361fn node_trailing_text(node: &Node) -> Option<String> {
3362  match node.get_type() {
3363    Some(libxml::tree::NodeType::ElementNode) => element_trailing_text(&node.get_name(), || {
3364      let mut child = node.get_last_child();
3365      while let Some(n) = child {
3366        if let Some(text) = node_trailing_text(&n) {
3367          return Some(text);
3368        }
3369        child = n.get_prev_sibling();
3370      }
3371      None
3372    }),
3373    Some(libxml::tree::NodeType::TextNode) | Some(libxml::tree::NodeType::CDataSectionNode) => {
3374      let text = node.get_content();
3375      (!text.trim().is_empty()).then_some(text)
3376    },
3377    _ => None,
3378  }
3379}
3380
3381/// [`trailing_text`] of an element named `tag` (qualified or not), whose
3382/// children give `children_text`.
3383fn element_trailing_text(
3384  tag: &str,
3385  children_text: impl FnOnce() -> Option<String>,
3386) -> Option<String> {
3387  match tag.rsplit(':').next().unwrap_or(tag) {
3388    "Math" => Some(String::new()),
3389    "ref" | "bibref" | "cite" => children_text().or(Some(String::new())),
3390    _ => children_text(),
3391  }
3392}
3393
3394/// Apply a formatter function to the given nodes.
3395///
3396/// Port of the various `do_*` functions.
3397fn apply_formatter(doc: &PostDocument, formatter: Formatter, nodes: &[Node]) -> Vec<NodeData> {
3398  match formatter {
3399    // Several fields read into one element (`organization` and `institution`
3400    // are both `ltx:bib-organization`, bibtex.rs) form a list, ", " between
3401    // its items as between the fields of a block; Perl's `do_any`
3402    // (MakeBibliography.pm:550) ran them together, "OscarorgCobaltinstitution"
3403    // (KNOWN_PERL_ERRORS #280).
3404    Formatter::Any => join_fields(nodes, ", "),
3405    // biblatex's `\newunit` between the units of one title: `\newunitpunct`
3406    // is `\addperiod\space` (biblatex.def:173), which the punctuation tracker
3407    // drops after a unit that already ends in a mark ([`ends_with_punctuation`]).
3408    Formatter::Units => join_fields(nodes, ". "),
3409    Formatter::Authors => do_names(nodes.to_vec()),
3410    Formatter::EditorsA => do_editors_a(nodes.to_vec()),
3411    Formatter::EditorsB => {
3412      let mut result = vec![NodeData::Text("(".to_string())];
3413      result.extend(do_names(nodes.to_vec()));
3414      let suffix = if nodes.len() > 1 { " Eds.)" } else { " Ed.)" };
3415      result.push(NodeData::Text(suffix.to_string()));
3416      result
3417    },
3418    Formatter::OtherNames => {
3419      // The names in a role other than the author, editor and translator the
3420      // specs print: one `do_names` list per role, in order of appearance, each
3421      // followed by its role; biblatex-chicago's `none` type prints no role.
3422      let mut groups: Vec<(String, Vec<Node>)> = Vec::new();
3423      for node in nodes {
3424        let role = node.get_attribute("role").unwrap_or_default();
3425        if matches!(role.as_str(), "author" | "editor" | "translator") {
3426          continue;
3427        }
3428        match groups.iter_mut().find(|(r, _)| *r == role) {
3429          Some((_, group)) => group.push(node.clone()),
3430          None => groups.push((role, vec![node.clone()])),
3431        }
3432      }
3433      let mut result = Vec::new();
3434      for (role, names) in groups {
3435        if !result.is_empty() {
3436          result.push(NodeData::Text("; ".to_string()));
3437        }
3438        result.extend(do_names(names));
3439        if role != "none" {
3440          result.push(NodeData::Text(format!(" ({role})")));
3441        }
3442      }
3443      result
3444    },
3445    Formatter::Year => {
3446      // NO disambiguation suffix here, deliberately — see KNOWN_PERL_ERRORS
3447      // #67. Perl `do_year` (L613-615) reads `@…::SUFFIX`, the ARRAY, while
3448      // `formatBibEntry` L417 binds `$…::SUFFIX`, the SCALAR: two different
3449      // Perl variables, so the array is always empty and the letter never
3450      // reaches the entry body. Measured, not assumed — same-host Perl 0.8.8
3451      // on `bib_alpha_style.tex` prints `[SBC99a]` as the label and ` (1999)`
3452      // as the body year. `alpha.bst` agrees, so this is the right output and
3453      // there is no gap to close; the audit item that flagged one was read off
3454      // the sigil.
3455      let suffix = "";
3456      let content: Vec<NodeData> = nodes
3457        .iter()
3458        .map(|n| {
3459          let text = n.get_content();
3460          let year = extract_four_digit_year(&text);
3461          NodeData::Text(year)
3462        })
3463        .collect();
3464      let mut result = vec![NodeData::Text(" (".to_string())];
3465      result.extend(content);
3466      result.push(NodeData::Text(format!("{})", suffix)));
3467      result
3468    },
3469    Formatter::Type => {
3470      let mut result = vec![NodeData::Text("(".to_string())];
3471      result.extend(nodes.iter().flat_map(field_content));
3472      result.push(NodeData::Text(")".to_string()));
3473      result
3474    },
3475    Formatter::Title => nodes.iter().flat_map(field_content).collect(),
3476    Formatter::ThesisType => nodes.iter().flat_map(field_content).collect(),
3477    Formatter::Edition => {
3478      let mut result: Vec<NodeData> = nodes.iter().flat_map(field_content).collect();
3479      result.push(NodeData::Text(" edition".to_string()));
3480      result
3481    },
3482    Formatter::Pages => {
3483      let mut result = vec![NodeData::Text("pp.\u{00A0}".to_string())]; // Non-breaking space
3484      result.extend(nodes.iter().flat_map(field_content));
3485      result
3486    },
3487    Formatter::CrossRef => {
3488      // Port of do_crossref
3489      if let Some(node) = nodes.first() {
3490        if let Some(bibrefs) = node.get_attribute("bibrefs") {
3491          return vec![NodeData::Element {
3492            tag:        "ltx:cite".to_string(),
3493            attributes: None,
3494            children:   vec![NodeData::Element {
3495              tag:        "ltx:bibref".to_string(),
3496              attributes: Some(HashMap::from_iter([
3497                ("bibrefs".to_string(), bibrefs),
3498                ("show".to_string(), "title, author".to_string()),
3499              ])),
3500              children:   vec![],
3501            }],
3502          }];
3503        }
3504      }
3505      Vec::new()
3506    },
3507    Formatter::Links => format_links(doc, nodes),
3508    Formatter::None => Vec::new(),
3509  }
3510}
3511
3512/// Format external links.
3513///
3514/// Port of `do_links`.
3515fn format_links(doc: &PostDocument, nodes: &[Node]) -> Vec<NodeData> {
3516  let mut links: Vec<NodeData> = Vec::new();
3517
3518  for node in nodes {
3519    let tag = doc.get_qname(node).unwrap_or_default();
3520    let scheme = node.get_attribute("scheme").unwrap_or_default();
3521    let href = node.get_attribute("href");
3522    // TeX prints the field as written (`\url` reads it verbatim), so a printed URL keeps its escapes.
3523    let printed_url = href.as_deref().map(force_absolute_url);
3524    let content_text = node.get_content();
3525
3526    // General rule (user, 2026-07-04): bibliography links are EXTERNAL.
3527    // DOIs always resolve via https://doi.org/, and scheme-less hrefs are
3528    // an authoring mistake that would resolve relative to the article —
3529    // normalize here so every source path (post .bib conversion,
3530    // .bbl-borne XML, pre-compiled .bib.xml) gets absolute links.
3531    let href = href.map(|h| unescape_tex_url(&h));
3532    let href = match (&href, scheme.as_str()) {
3533      (None, "doi") if !content_text.trim().is_empty() && content_text.contains('/') => {
3534        Some(doi_href(&content_text))
3535      },
3536      (Some(h), "doi") if !h.contains("://") => Some(doi_href(h.trim_start_matches('/'))),
3537      (Some(h), _) => Some(force_absolute_url(h)),
3538      (None, _) => None,
3539    };
3540    // Perl `MakeBibliography.pm:do_links` L655-667 uses
3541    // `$doc->cloneNodes($node->childNodes)` as the child list in EVERY branch —
3542    // it copies the marked-up children, it does not flatten them. Taking
3543    // `get_content()` (a plain-text collapse) instead silently dropped any
3544    // nested element: an amsrefs `review={\MR{849427}}` digests to
3545    // `<ltx:bib-review>Review <ltx:ref class="ltx_mathreviews" href="…">
3546    // MathReviews</ltx:ref></ltx:bib-review>`, and the flattening rendered a
3547    // dead "Review MathReviews" with the MathSciNet link gone. Witness
3548    // arXiv 2508.17585.
3549    let children: Vec<NodeData> = node
3550      .get_child_nodes()
3551      .into_iter()
3552      .map(NodeData::XmlNode)
3553      .collect();
3554    match tag.as_str() {
3555      "ltx:bib-identifier" | "ltx:bib-review" => {
3556        if let Some(href) = href {
3557          links.push(NodeData::Element {
3558            tag: "ltx:ref".to_string(),
3559            attributes: Some(HashMap::from_iter([
3560              ("href".to_string(), href),
3561              ("class".to_string(), format!("{} ltx_bib_external", scheme)),
3562            ])),
3563            children,
3564          });
3565        } else {
3566          links.push(NodeData::Element {
3567            tag: "ltx:text".to_string(),
3568            attributes: Some(HashMap::from_iter([(
3569              "class".to_string(),
3570              format!("{} ltx_bib_external", scheme),
3571            )])),
3572            children,
3573          });
3574        }
3575      },
3576      "ltx:bib-links" => {
3577        links.push(NodeData::Element {
3578          tag: "ltx:text".to_string(),
3579          attributes: Some(HashMap::from_iter([(
3580            "class".to_string(),
3581            "ltx_bib_external".to_string(),
3582          )])),
3583          children,
3584        });
3585      },
3586      "ltx:bib-url" => {
3587        if let Some(href) = href {
3588          // A style that prints its URLs (biblatex, the natbib `*nat` styles)
3589          // shows the address itself where the reader's `Link` placeholder
3590          // stands (bibtex.rs `\bib@field@default@url`; Perl always prints
3591          // `Link`). OXIDIZED_DESIGN_DIVERGENCES #289.
3592          let children = if URLS_AS_TEXT.with(|flag| flag.get()) && content_text.trim() == "Link" {
3593            vec![NodeData::Text(printed_url.unwrap_or_else(|| href.clone()))]
3594          } else {
3595            children
3596          };
3597          links.push(NodeData::Element {
3598            tag: "ltx:ref".to_string(),
3599            attributes: Some(HashMap::from_iter([
3600              ("href".to_string(), href),
3601              ("class".to_string(), "ltx_bib_external".to_string()),
3602            ])),
3603            children,
3604          });
3605        }
3606      },
3607      _ => {},
3608    }
3609  }
3610
3611  // Join with ",\n"
3612  if links.len() > 1 {
3613    let mut result = Vec::new();
3614    for (i, link) in links.into_iter().enumerate() {
3615      if i > 0 {
3616        result.push(NodeData::Text(",\n".to_string()));
3617      }
3618      result.push(link);
3619    }
3620    result
3621  } else {
3622    links
3623  }
3624}
3625
3626// ======================================================================
3627// Utility functions
3628
3629/// Sort bibliography sort-keys the way Perl's `Post::unisort` does.
3630///
3631/// Perl (`Post.pm` L1399-1403) hands the keys to a `Unicode::Collate::Locale`
3632/// built with `variable => 'non-ignorable'` and `upper_before_lower => 1` — a
3633/// full UCA collation, so `Šmith` lands next to `Smith` rather than after every
3634/// ASCII letter, which is what a plain codepoint `sort()` produces.
3635///
3636/// **Documented approximation** (OXIDIZED_DESIGN #84): we reproduce UCA's
3637/// PRIMARY level for Latin script only — NFD-decompose, drop the combining
3638/// marks, case-fold — and break ties on the raw string. That is exact for
3639/// accented Latin (the input this actually sees: author surnames and titles).
3640/// Perl's `upper_before_lower` needs no counterpart because it is MOOT: the
3641/// sort keys are `to_lowercase()`d when built, so no comparison here can see a
3642/// case difference. It diverges from Perl for script-crossing orders,
3643/// non-decomposable letters (`Ø`, `Æ`, `Ł`) and locale tailorings — none of
3644/// which a DUCET table could be added for without a new dependency carrying
3645/// embedded collation data. `Post.pm` L123-128 shows Perl itself falling back
3646/// to a codepoint `DumbCollator` when `Unicode::Collate` is unavailable, so a
3647/// documented approximation stays inside the range of behaviours Perl ships.
3648///
3649/// The sort is otherwise total and deterministic: equal primary keys fall back
3650/// to the raw key, and the raw keys are the (unique) hash keys of the entry
3651/// map.
3652fn unisort(keys: &mut [String]) {
3653  keys.sort_by_cached_key(|k| (collation_primary_key(k), k.clone()));
3654}
3655
3656/// Whether a bibliography style prints an entry's `url` field. biblatex's
3657/// standard styles do (`url=true`, the biblatex binding records `biblatex` —
3658/// or `biblatex-giveninits`, [`style_given_name_form`] — as the style), and so
3659/// do natbib's `plainnat`/`abbrvnat`/`unsrtnat` ("URL …", plainnat.bst
3660/// `format.url`), and abnTeX2's ("Disponível em: …", abntex2-num.bst
3661/// `format.url` :993-1001); the classic `plain`/`alpha`/`unsrt` know no `url`
3662/// field. Other url-printing `.bst`s (IEEEtran, achemso, …) keep the "Link"
3663/// placeholder until they are listed here.
3664fn style_prints_urls(bibstyle: &str) -> bool {
3665  bibstyle.starts_with("biblatex")
3666    || matches!(
3667      bibstyle,
3668      "plainnat" | "abbrvnat" | "unsrtnat" | "abntex2-num" | "abntex2-alf"
3669    )
3670}
3671
3672/// First-citation order of bib keys (lowercased) → 0-based rank, read from the
3673/// document's inline `<ltx:bibref>`s in reading order.
3674///
3675/// This is bibtex's `\citation`-record order for `\cite`: an UNSORTED `.bst`
3676/// (`unsrt`/`unsrtnat`/`ieeetr`/`IEEEtran`) numbers the References by it. bibrefs
3677/// INSIDE the bibliography (a `\bibitem` crossref, the "Cited by" back-links)
3678/// are excluded via `not(ancestor::ltx:bibliography)` so only real in-text
3679/// citations count. Verified key-for-key against pdflatex+bibtex on witness
3680/// arXiv 2510.05438.
3681///
3682/// `\nocite` emits its bibref too, but BOTH engines defer it to end-of-document
3683/// (`\nocite`→`@at@end@document`), so a mid-document `\nocite` ranks after the
3684/// cited entries rather than at bibtex's `\nocite` position — a documented
3685/// shared-Perl residual (OXIDIZED_DESIGN #116), not exact bibtex parity.
3686fn citation_order(doc: &PostDocument) -> HashMap<String, usize> {
3687  let mut order: HashMap<String, usize> = HashMap::default();
3688  let mut next = 0usize;
3689  for node in doc.findnodes("//ltx:bibref[not(ancestor::ltx:bibliography)]") {
3690    let Some(refs) = node.get_attribute("bibrefs") else {
3691      continue;
3692    };
3693    for key in refs.split(',') {
3694      let k = key.trim().to_lowercase();
3695      if k.is_empty() {
3696        continue;
3697      }
3698      order.entry(k).or_insert_with(|| {
3699        let i = next;
3700        next += 1;
3701        i
3702      });
3703    }
3704  }
3705  order
3706}
3707
3708/// The order to number entries in. With `cite_order = Some(..)` (a `sort='false'`
3709/// style) cited entries come first in first-citation order, and any entry not
3710/// directly cited — pulled in transitively (a crossref) or via `\nocite{*}` —
3711/// follows in database order, as an unsorted BibTeX style lists them (no SORT:
3712/// `\nocite{*}` takes the `.bib` order; figbib.bst, unsrt.bst); Perl and earlier
3713/// Rust put them alphabetically. Residual: BibTeX keeps citation order only for
3714/// the citations before the `*` and lists everything else, later `\cite`s too, in
3715/// database order (`\nocite{*}` at the start is pure `.bib` order); the deferred
3716/// `\nocite` leaves no position for the `*`, so later citations keep theirs here.
3717/// Otherwise plain `unisort` (Perl's always-alphabetical).
3718fn order_entry_keys(
3719  entries: &HashMap<String, BibEntryData>,
3720  cite_order: Option<&HashMap<String, usize>>,
3721) -> Vec<String> {
3722  match cite_order {
3723    Some(order) => {
3724      let mut cited: Vec<(usize, String)> = Vec::new();
3725      let mut uncited: Vec<String> = Vec::new();
3726      for (sort_key, entry) in entries {
3727        match order.get(&entry.bib_key.to_lowercase()) {
3728          Some(&idx) => cited.push((idx, sort_key.clone())),
3729          None => uncited.push(sort_key.clone()),
3730        }
3731      }
3732      cited.sort_by_key(|(idx, _)| *idx);
3733      uncited.sort_by(|a, b| {
3734        entries[a]
3735          .db_index
3736          .cmp(&entries[b].db_index)
3737          .then_with(|| a.cmp(b))
3738      });
3739      cited.into_iter().map(|(_, k)| k).chain(uncited).collect()
3740    },
3741    None => {
3742      let mut keys: Vec<String> = entries.keys().cloned().collect();
3743      unisort(&mut keys);
3744      keys
3745    },
3746  }
3747}
3748
3749/// The entries of a backend's listing, in its order: the `ltx:bibentry`s a
3750/// biblatex bibliography holds when it says `sort='false'` — a biber `.bbl`
3751/// read by biblatex_sty.rs (`bbl_flush`), whose list biber already selected
3752/// and sorted by the style's scheme. `None` for any other bibliography: an
3753/// external `.bib` under an unsorted style takes its order from the
3754/// citations, and amsrefs' inline entries are all printed
3755/// (OXIDIZED_DESIGN_DIVERGENCES #57) in their [`inline_listing`] order.
3756fn given_listing(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3757  if bib.with_attribute(c"sort", |v| v == "false") != Some(true)
3758    || !bib
3759      .get_attribute("bibstyle")
3760      .is_some_and(|style| style.starts_with("biblatex"))
3761  {
3762    return None;
3763  }
3764  entry_keys(doc, bib)
3765}
3766
3767/// The keys of an amsrefs bibliography's `ltx:bibentry`s (class `ltx_bibliography_inline`, amsrefs_sty.rs), in
3768/// document order: the `\bib`s of its `biblist` (and those its `\bibselect` took, in database order), which
3769/// amsrefs.sty:810 `\bib@print` typesets and numbers where they stand, whatever the `sorted` option or
3770/// `\bibliographystyle` (arXiv 2402.14969). `None` for any other bibliography: a `.bib`'s entries, also one converted
3771/// on its own or by another converter, are a database, sorted.
3772fn inline_listing(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3773  if !bib.get_attribute("class").is_some_and(|class| {
3774    class
3775      .split_whitespace()
3776      .any(|c| c == "ltx_bibliography_inline")
3777  }) {
3778    return None;
3779  }
3780  entry_keys(doc, bib)
3781}
3782
3783/// The keys of the `ltx:bibentry`s a bibliography holds, in document order; `None` when it holds none.
3784fn entry_keys(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3785  let keys: Vec<String> = doc
3786    .findnodes_at(".//ltx:bibentry", Some(bib))
3787    .iter()
3788    .filter_map(|entry| entry.get_attribute("key"))
3789    .collect();
3790  (!keys.is_empty()).then_some(keys)
3791}
3792
3793/// The label a backend gave the entry, as its style prints it: biber's
3794/// `labelalpha` and `extraalpha`, which a `.bbl`'s entries carry
3795/// (biblatex_sty.rs) — alphabetic.bbx:22-25 prints
3796/// `\printfield{labelalpha}\printfield{extraalpha}`, the latter through
3797/// `\mknumalph` (biblatex.def:476): "Knu84", "Knu84a". Perl has no such
3798/// label; its alphabetic refnum is its own (`make_alpha_label`).
3799///
3800/// In a biblatex bibliography an entry's `shorthand` is its label in every style that labels (biblatex.sty:8920
3801/// `\let\abx@field@labelnumber\abx@field@shorthand`; biber's default labelalpha template starts with it): such an
3802/// entry takes no number (arXiv 2406.00136's `[SAG]`, `[HTT]` beside [1]-[17]).
3803///
3804/// Only a biblatex bibliography's: under natbib/BibTeX a `.bib` field `labelalpha`, `extraalpha` or `shorthand` is
3805/// data the `.bst` never prints, and the entry keeps its number (`labelalpha={Knu84}` under natbib numbers prints
3806/// `[1]`, cited `[1]`; it printed `[Knu84]`, cited `[, 1]`). Guard
3807/// `06_cluster_bibliography::natbib_labelalpha_field_is_no_label`.
3808fn given_label(bibentry: &Node) -> Option<String> {
3809  if !is_biblatex_bibliography() {
3810    return None;
3811  }
3812  let field = |role: &str| {
3813    PostDocument::findnodes_foreign(&format!("ltx:bib-data[@role='{role}']"), bibentry)
3814      .first()
3815      .map(|node| node.get_content().trim().to_string())
3816      .filter(|text| !text.is_empty())
3817  };
3818  if let Some(shorthand) = field("shorthand") {
3819    return Some(shorthand);
3820  }
3821  let mut label = field("labelalpha")?;
3822  if let Some(extra) = field("extraalpha").and_then(|n| n.parse::<u32>().ok()) {
3823    label.push_str(&mknumalph(extra));
3824  }
3825  Some(label)
3826}
3827
3828/// The number a backend gave the entry: biblatex's `labelnumber`, which a `.bbl`'s entries carry (biblatex_sty.rs
3829/// `\biblatex@bbl@number`) — its place in its refsection's datalist, the same in every list of that refsection
3830/// (biblatex numbers each refsection on its own, biblatex.sty:8891-8923), or with `defernumbers=true` the one it got
3831/// where it was first printed. Read from this bibliography's own copy of the entry ([`MakeBibliography::get_bib_entries`]):
3832/// another refsection's list numbers the key apart. MakeBibliography's own number restarts at 1 in each
3833/// `ltx:bibliography`, so the filtered lists of one `.bbl` (`\printbibliography[type=…]`) gave two entries one label.
3834/// Only a biblatex bibliography's: a `.bib` field `labelnumber` under natbib is no label. Witnesses arXiv 2406.00136,
3835/// 2308.00515, 2406.01695.
3836fn given_number(entry: &BibEntryData) -> Option<u32> {
3837  if !is_biblatex_bibliography() {
3838    return None;
3839  }
3840  let bibentry = entry.bibentry.as_ref()?;
3841  PostDocument::findnodes_foreign("ltx:bib-data[@role='labelnumber']", bibentry)
3842    .first()
3843    .and_then(|node| node.get_content().trim().parse().ok())
3844}
3845
3846/// Numbers the next entry of the list: [`BibEntryData::number`], its place (its id, `bib.bib<number>`), and the
3847/// number it prints, [`BibEntryData::label_number`]: the one its backend gave it ([`given_number`]), else its place
3848/// among the entries that print a number — one with a label of its own ([`entry_given_label`], a biblatex `shorthand`
3849/// or alphabetic label) takes none, as biblatex gives a `shorthand` entry no `labelnumber` (biblatex.sty:8920). On a
3850/// `.bib` read without a `.bbl` the list of `balbes` (`shorthand={Balbes \& Dwinger}`) and four others printed
3851/// `[Balbes & Dwinger] [2] [3] [4] [5]`; pdflatex prints [1]-[4]. Guard
3852/// `06_cluster_bibliography::biblatex_bib_route_shorthand_takes_no_number`.
3853fn number_entry(
3854  entry: &mut BibEntryData,
3855  number: &mut u32,
3856  shown: &mut u32,
3857  style: &CitationStyle,
3858) {
3859  *number += 1;
3860  entry.number = *number;
3861  entry.label_number = given_number(entry);
3862  if entry_given_label(entry, style).is_none() {
3863    *shown += 1;
3864    if entry.label_number.is_none() && *shown != *number {
3865      entry.label_number = Some(*shown);
3866    }
3867  }
3868}
3869
3870/// [`given_label`] of an entry of a bibliography cited in `style`: an
3871/// author-year bibliography labels by author and year instead.
3872fn entry_given_label(entry: &BibEntryData, style: &CitationStyle) -> Option<String> {
3873  if matches!(style, CitationStyle::AuthorYear) {
3874    return None;
3875  }
3876  entry.bibentry.as_ref().and_then(given_label)
3877}
3878
3879/// biblatex's `\mknumalph` (biblatex.sty:13285-13303): 1-26 as "a"-"z",
3880/// 27-702 as two letters ("aa" … "zz"), beyond that the number.
3881fn mknumalph(n: u32) -> String {
3882  let letter = |i: u32| char::from(b'a' + (i - 1) as u8);
3883  match n {
3884    1..=26 => letter(n).to_string(),
3885    27..=702 => {
3886      let first = (n - 1) / 26;
3887      format!("{}{}", letter(first), letter(n - first * 26))
3888    },
3889    _ => n.to_string(),
3890  }
3891}
3892
3893/// The primary-level collation weight of a sort-key: NFD, combining marks
3894/// dropped, case-folded. See [`unisort`].
3895fn collation_primary_key(s: &str) -> String {
3896  use unicode_normalization::{UnicodeNormalization, char::is_combining_mark};
3897  s.nfd()
3898    .filter(|c| !is_combining_mark(*c))
3899    .flat_map(char::to_lowercase)
3900    .collect()
3901}
3902
3903/// Extract author names from a bibentry node.
3904///
3905/// Port of the name extraction logic in `getBibEntries`.
3906/// Returns (sort_names, short_names, full_names).
3907fn extract_names(doc: &PostDocument, bibentry: &Node) -> (String, String, String) {
3908  let mut name_nodes: Vec<Node> =
3909    PostDocument::findnodes_foreign("ltx:bib-name[@role='author']", bibentry);
3910  if name_nodes.is_empty() {
3911    name_nodes = label_editors("", |x| PostDocument::findnodes_foreign(x, bibentry));
3912  }
3913
3914  if name_nodes.is_empty() {
3915    // Try bib-key
3916    if let Some(key_node) = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
3917      .into_iter()
3918      .next()
3919    {
3920      let text = key_node.get_content();
3921      return (text.clone(), text.clone(), text);
3922    }
3923    // Try bib-title
3924    if let Some(title_node) = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
3925      .into_iter()
3926      .next()
3927    {
3928      let text = title_node.get_content();
3929      return (text.clone(), text.clone(), text);
3930    }
3931    return (String::new(), String::new(), String::new());
3932  }
3933
3934  // Sort names: "Surname Givenname" for each
3935  let sort_names: String = name_nodes
3936    .iter()
3937    .map(|n| get_name_text(doc, n))
3938    .collect::<Vec<_>>()
3939    .join(" ");
3940
3941  // Short names: surnames only, with "et al" for >2
3942  let surnames: Vec<String> = name_nodes
3943    .iter()
3944    .filter_map(|n| {
3945      PostDocument::findnodes_foreign("ltx:surname", n)
3946        .into_iter()
3947        .next()
3948        .map(|s| s.get_content())
3949    })
3950    .collect();
3951
3952  let short_names = if surnames.len() > 2 {
3953    format!("{} et al", surnames[0])
3954  } else if surnames.len() == 2 {
3955    format!("{} and {}", surnames[0], surnames[1])
3956  } else if !surnames.is_empty() {
3957    surnames[0].clone()
3958  } else {
3959    String::new()
3960  };
3961
3962  let full_names = surnames.join(", ");
3963  (sort_names, short_names, full_names)
3964}
3965
3966/// Perl MakeBibliography `do_name` (L555-566): the given name, in the
3967/// style's [`GivenNameForm`], followed by the surname — givenname "Aaron D." +
3968/// surname "Ames" gives "A. D. Ames" (initials) or "Aaron D. Ames" (full). For
3969/// initials, each whitespace-split given-name word already ending in "." is
3970/// kept verbatim (+ space); otherwise its first char + ". " is used. The one
3971/// name renderer: the `ltx:bib-name` formatters ([`do_name_node`]) come here.
3972/// (We flatten the surname to text, consistent with the rest of this file's
3973/// name handling; Perl clones the surname's child nodes to preserve any markup,
3974/// which bibliography surnames essentially never carry.)
3975fn do_name(given: Option<&str>, surname: &str) -> String {
3976  let mut out = String::new();
3977  if let Some(given) = given {
3978    match GIVEN_NAME_FORM.with(std::cell::Cell::get) {
3979      GivenNameForm::Full => {
3980        for word in given.split_whitespace() {
3981          out.push_str(word);
3982          out.push(' ');
3983        }
3984      },
3985      GivenNameForm::Initials => {
3986        for word in given.split_whitespace() {
3987          if word.ends_with('.') {
3988            out.push_str(word);
3989            out.push(' ');
3990          } else if let Some(c) = word.chars().next() {
3991            out.push(c);
3992            out.push_str(". ");
3993          }
3994        }
3995      },
3996    }
3997  }
3998  out.push_str(surname);
3999  out
4000}
4001
4002/// [`do_name`] for one `ltx:bib-name` node.
4003fn do_name_node(namenode: &Node) -> String {
4004  let first_text = |xpath: &str| {
4005    PostDocument::findnodes_foreign(xpath, namenode)
4006      .into_iter()
4007      .next()
4008      .map(|n| n.get_content())
4009  };
4010  let given = first_text("ltx:givenname");
4011  let surname = first_text("ltx:surname").unwrap_or_default();
4012  do_name(given.as_deref(), &surname)
4013}
4014
4015/// The given-name form of the style an `ltx:bibliography` records in its
4016/// `bibstyle` attribute. The biblatex binding records `biblatex`, or
4017/// `biblatex-giveninits` when the `giveninits`/`firstinits` option is on
4018/// (biblatex_sty.rs `\biblatex@printbibliography`; biblatex's default is
4019/// full names). Any other name is a `.bst`, found beside the document or through
4020/// kpsewhich as a `.bib` is ([`bst_given_name_form`]).
4021fn style_given_name_form(bibstyle: &str, search_paths: &[String]) -> GivenNameForm {
4022  match bibstyle {
4023    "biblatex" => GivenNameForm::Full,
4024    "biblatex-giveninits" => GivenNameForm::Initials,
4025    _ => {
4026      let bst = if bibstyle.ends_with(".bst") {
4027        bibstyle.to_string()
4028      } else {
4029        format!("{bibstyle}.bst")
4030      };
4031      find_file(&bst, search_paths)
4032        .or_else(|| latexml_core::util::pathname::kpsewhich(&[bst.as_str()]))
4033        .and_then(|path| std::fs::read(path).ok())
4034        .map_or(GivenNameForm::Initials, |bytes| {
4035          bst_given_name_form(&String::from_utf8_lossy(&bytes))
4036        })
4037    },
4038  }
4039}
4040
4041/// The given-name form a `.bst` asks for, read off the name template of its
4042/// author list: plain.bst:191 `"{ff~}{vv~}{ll}{, jj}" format.name$` spells the
4043/// given names out (`ff`), abbrv.bst:191 `"{f.~}{vv~}{ll}{, jj}"` abbreviates
4044/// them (`f`, as do `{f~}`, `{f}` and apalike.bst:215 `{, f.}`): "Within
4045/// each piece a double letter tells BibTeX to use whole tokens, and a single
4046/// letter, to abbreviate them (these letters must be at brace-level 1)"
4047/// (btxhak.tex:580-581).
4048///
4049/// The walk takes the `format.name$` calls in file order, skipping literal
4050/// templates without a given-name part (a label's `"{vv~}{ll}"`) and calls
4051/// whose result is compared with `"others"`, and stops at the first that has
4052/// one. A template held in a variable (IEEEtran.bst:1213
4053/// `name.format.string`, apsrev4-2.bst:1469) is unreadable, and so is a style
4054/// with no template at all: both give Perl's initials. Stopping there, rather
4055/// than reading on, keeps the later sort templates (plain.bst's
4056/// `sort.format.names` `"{vv{ } }{ll{ }}{  ff{ }}{  jj{ }}"`, which every
4057/// base style carries) from deciding.
4058///
4059/// One family decides before the walk: the abnTeX `.bst`s read `{, ff}` and
4060/// abbreviate in their own code, so their `#0`/`#1 'abnt.full.initials :=`
4061/// default (abntex2-num.bst:2045) is the form (unbtex-example "L. C. Araujo").
4062fn bst_given_name_form(bst: &str) -> GivenNameForm {
4063  let code: String = bst
4064    .lines()
4065    .map(strip_bst_comment)
4066    .collect::<Vec<_>>()
4067    .join("\n");
4068  // The abnTeX family (abntex2-*.bst, unbtex-*.bst, fcavtex.bst, …) reads the whole given names
4069  // (`{, ff}`, abntex2-num.bst:448) and abbreviates them in its own code, as its
4070  // `abnt.full.initials` variable says: `#0 'abnt.full.initials :=` (the default, :2045) gives
4071  // "FARIA, J. E.", `#1` the names as written.
4072  // (The option's own assignment, `abnt-full-initials "yes" = 'abnt.full.initials :=` at :1476,
4073  // is not the default: only a literal `#0`/`#1` is.)
4074  for (at, _) in code.match_indices("'abnt.full.initials :=") {
4075    match code[..at].trim_end().rsplit(char::is_whitespace).next() {
4076      Some("#0") => return GivenNameForm::Initials,
4077      Some("#1") => return GivenNameForm::Full,
4078      _ => {},
4079    }
4080  }
4081  let mut rest = code.as_str();
4082  while let Some(at) = rest.find("format.name$") {
4083    let before = rest[..at].trim_end();
4084    rest = &rest[at + "format.name$".len()..];
4085    // A name compared with "others" is the "et al." test, not the printed
4086    // form (achemso.bst:514 `"{ff }{vv }{ll}{ jj}" format.name$ "others" =`,
4087    // which prints `{,~f.}` at :874; biochem.bst:514 likewise).
4088    if rest.trim_start().starts_with("\"others\"") {
4089      continue;
4090    }
4091    // The template is the string literal right before the call.
4092    let Some(open) = before.strip_suffix('"').and_then(|body| body.rfind('"')) else {
4093      return GivenNameForm::Initials;
4094    };
4095    let template = &before[open + 1..before.len() - 1];
4096    if let Some(form) = template_given_name_form(template) {
4097      return form;
4098    }
4099  }
4100  GivenNameForm::Initials
4101}
4102
4103/// A `.bst` line without its `%` comment (a `%` inside a string literal is
4104/// data).
4105fn strip_bst_comment(line: &str) -> &str {
4106  let mut in_string = false;
4107  for (i, c) in line.char_indices() {
4108    match c {
4109      '"' => in_string = !in_string,
4110      '%' if !in_string => return &line[..i],
4111      _ => {},
4112    }
4113  }
4114  line
4115}
4116
4117/// The given-name part of one `format.name$` template: the brace-level-1
4118/// piece whose name-part letters start with `f`. `None` when the template
4119/// prints no given names.
4120fn template_given_name_form(template: &str) -> Option<GivenNameForm> {
4121  let mut depth = 0usize;
4122  let mut letters = String::new();
4123  // This piece's letters are read (any later letter in it is verbatim text).
4124  let mut read = false;
4125  for c in template.chars() {
4126    if depth == 1 && !read {
4127      if c.is_ascii_alphabetic() {
4128        letters.push(c);
4129        continue;
4130      }
4131      if !letters.is_empty() {
4132        read = true;
4133        if letters.starts_with('f') {
4134          return Some(if letters == "ff" {
4135            GivenNameForm::Full
4136          } else {
4137            GivenNameForm::Initials
4138          });
4139        }
4140      }
4141    }
4142    match c {
4143      '{' => {
4144        depth += 1;
4145        if depth == 1 {
4146          letters.clear();
4147          read = false;
4148        }
4149      },
4150      '}' => depth = depth.saturating_sub(1),
4151      _ => {},
4152    }
4153  }
4154  None
4155}
4156
4157/// The SHORT author form used for the author-year citation label: surnames
4158/// only, `>2` collapsing to "First et al.".
4159///
4160/// Port of Perl's `do_names_short` (MakeBibliography.pm L586-593) — which is
4161/// **defined there and never called**; Perl's author-year refnum uses the full
4162/// `do_names` instead, producing labels thousands of characters long on
4163/// collaboration papers. See OXIDIZED_DESIGN #71 for why we call it, and
4164/// `cluster_bib_long_author_list_refnum` for the guard.
4165///
4166/// Beyond Perl's version: a trailing BibTeX `others` is dropped and forces the
4167/// "et al." form, so `Smith and others` reads "Smith et al." rather than
4168/// "Smith and others". Perl's unused helper has no `others` handling at all;
4169/// `do_names` (its called sibling) does, so this keeps the two consistent.
4170fn do_names_short(mut names: Vec<Node>) -> Vec<NodeData> {
4171  let surname_text = |n: &Node| -> String {
4172    PostDocument::findnodes_foreign("ltx:surname", n)
4173      .into_iter()
4174      .next()
4175      .map(|s| s.get_content())
4176      .unwrap_or_else(|| n.get_content())
4177      .trim()
4178      .to_string()
4179  };
4180  let mut etal = names
4181    .last()
4182    .map(|n| n.get_content().trim() == "others")
4183    .unwrap_or(false);
4184  if etal {
4185    names.pop();
4186  }
4187  if names.len() > 2 {
4188    etal = true;
4189  }
4190  let etal_span = || NodeData::Element {
4191    tag:        "ltx:text".to_string(),
4192    attributes: Some(HashMap::from_iter([(
4193      "class".to_string(),
4194      "ltx_bib_etal".to_string(),
4195    )])),
4196    children:   vec![NodeData::Text("et al.".to_string())],
4197  };
4198  match (names.len(), etal) {
4199    (0, _) => Vec::new(),
4200    (_, true) => vec![
4201      NodeData::Text(surname_text(&names[0])),
4202      NodeData::Text(" ".to_string()),
4203      etal_span(),
4204    ],
4205    (1, false) => vec![NodeData::Text(surname_text(&names[0]))],
4206    (_, false) => vec![
4207      NodeData::Text(surname_text(&names[0])),
4208      NodeData::Text(" and ".to_string()),
4209      NodeData::Text(surname_text(&names[1])),
4210    ],
4211  }
4212}
4213
4214/// Perl MakeBibliography `do_names` (L568-584) / `do_authors` (L595-597): the
4215/// full author list for the author-year refnum. Each name is rendered via
4216/// `do_name` (initials + surname) and joined with ", " (>2 names) or " " (≤2),
4217/// with "and " before the last; a trailing BibTeX "others" (from "and others")
4218/// collapses to a trailing "et al." span instead.
4219fn do_names(mut names: Vec<Node>) -> Vec<NodeData> {
4220  let sep = if names.len() > 2 { ", " } else { " " };
4221  let mut etal = false;
4222  if names
4223    .last()
4224    .map(|n| n.get_content().trim() == "others")
4225    .unwrap_or(false)
4226  {
4227    names.pop();
4228    etal = true;
4229  }
4230  let last = names.len().saturating_sub(1);
4231  let mut out: Vec<NodeData> = Vec::new();
4232  for (i, name) in names.iter().enumerate() {
4233    if !out.is_empty() {
4234      out.push(NodeData::Text(sep.to_string()));
4235      if !etal && i == last {
4236        out.push(NodeData::Text("and ".to_string()));
4237      }
4238    }
4239    out.push(NodeData::Text(do_name_node(name)));
4240  }
4241  if etal {
4242    out.push(NodeData::Text(sep.to_string()));
4243    out.push(NodeData::Element {
4244      tag:        "ltx:text".to_string(),
4245      attributes: Some(HashMap::from_iter([(
4246        "class".to_string(),
4247        "ltx_bib_etal".to_string(),
4248      )])),
4249      children:   vec![NodeData::Text("et al.".to_string())],
4250    });
4251  }
4252  out
4253}
4254
4255/// Perl MakeBibliography `do_editorsA` (L599-604): `do_names` plus a trailing
4256/// " (Eds.)" (more than one editor) or " (Ed.)" (a single editor).
4257fn do_editors_a(names: Vec<Node>) -> Vec<NodeData> {
4258  let n = names.len();
4259  let mut out = do_names(names);
4260  if n > 1 {
4261    out.push(NodeData::Text(" (Eds.)".to_string()));
4262  } else if n == 1 {
4263    out.push(NodeData::Text(" (Ed.)".to_string()));
4264  }
4265  out
4266}
4267
4268/// Get sort-friendly name text from a bib-name node.
4269///
4270/// Port of `getNameText`.
4271fn get_name_text(_doc: &PostDocument, namenode: &Node) -> String {
4272  let surname = PostDocument::findnodes_foreign("ltx:surname", namenode)
4273    .into_iter()
4274    .next()
4275    .map(|n| n.get_content());
4276  let givenname = PostDocument::findnodes_foreign("ltx:givenname", namenode)
4277    .into_iter()
4278    .next()
4279    .map(|n| n.get_content());
4280  match (surname, givenname) {
4281    (Some(s), Some(g)) => format!("{} {}", s, g),
4282    (Some(s), None) => s,
4283    (None, Some(g)) => g,
4284    (None, None) => String::new(),
4285  }
4286}
4287
4288/// Extract a 4-digit year from a date string.
4289fn extract_four_digit_year(text: &str) -> String {
4290  if let Some(start) = text.find(|c: char| c.is_ascii_digit()) {
4291    let digits: String = text[start..]
4292      .chars()
4293      .take_while(|c| c.is_ascii_digit())
4294      .collect();
4295    if digits.len() >= 4 {
4296      return digits[..4].to_string();
4297    }
4298  }
4299  text.to_string()
4300}
4301
4302/// The year part of an alpha label: alpha.bst:1047 `year field.or.null purify$ #-1 #2 substring$`, the last two
4303/// characters of the purified year, as BibTeX labels it (`{99}` → `99`, `{in press}` → `ss`, `{1--250, 2023}`
4304/// → `23`, 2308.14725). Perl's `substr($yrtext, 2, 2)` (MakeBibliography.pm:501) drops a short year (KNOWN_PERL_ERRORS
4305/// #1288). `year` is the date's four-digit year where it has one, as Perl's year tag (:462): a date the `year` field's
4306/// `month` extended (`1999-05`), an amsrefs `date={2010nov}` or `{200401}` (2308.14725), and a lettered `{2023a}`.
4307fn alpha_label_year(year: &str) -> String {
4308  let purified: Vec<char> = purify(year).chars().collect();
4309  purified[purified.len().saturating_sub(2)..]
4310    .iter()
4311    .collect()
4312}
4313
4314/// BibTeX's `purify$` (bibtex.web §431) on digested text: a letter or digit is kept, white space and the
4315/// `sep_char`s `-` `~` become a space (as do the dashes and the tie `--`/`~` digest to), any other character goes.
4316fn purify(text: &str) -> String {
4317  text
4318    .chars()
4319    .filter_map(|c| match c {
4320      c if c.is_alphanumeric() => Some(c),
4321      c if c.is_whitespace() || matches!(c, '-' | '~' | '\u{2010}'..='\u{2015}') => Some(' '),
4322      _ => None,
4323    })
4324    .collect()
4325}
4326
4327/// Convert a suffix string back to a counter value.
4328fn suffix_to_counter(suffix: &str) -> u32 {
4329  let mut n = 0u32;
4330  for c in suffix.chars() {
4331    n = n * 26 + (c as u32 - 'a' as u32 + 1);
4332  }
4333  n
4334}
4335
4336/// The id of `entry`'s bibitem in the bibliography `bib_id`: Perl's
4337/// `$id =~ s/^bib//; $id = $bibid . $id` (MakeBibliography.pm L407-415), or
4338/// `<bib_id>.bib<number>` for a bibentry with no `xml:id` (a raw `.bib`).
4339fn bibitem_id(bib_id: &str, entry: &BibEntryData, bibentry: &Node) -> String {
4340  let orig_id = crate::document::get_xml_id(bibentry).unwrap_or_default();
4341  if orig_id.is_empty() {
4342    format!("{}.bib{}", bib_id, entry.number)
4343  } else {
4344    let stripped = orig_id.strip_prefix("bib").unwrap_or(&orig_id);
4345    format!("{}{}", bib_id, stripped)
4346  }
4347}
4348
4349impl BibEntryData {
4350  /// The number its label prints: the one its backend gave it, else its place in the list.
4351  fn shown_number(&self) -> u32 { self.label_number.unwrap_or(self.number) }
4352}
4353
4354/// Clone a BibEntryData (for split operation).
4355fn clone_entry(e: &BibEntryData) -> BibEntryData {
4356  BibEntryData {
4357    bib_key:      e.bib_key.clone(),
4358    cited_key:    e.cited_key.clone(),
4359    sort_key:     e.sort_key.clone(),
4360    initial:      e.initial.clone(),
4361    author_year:  e.author_year.clone(),
4362    suffix:       e.suffix.clone(),
4363    sort_names:   e.sort_names.clone(),
4364    year:         e.year.clone(),
4365    entry_type:   e.entry_type.clone(),
4366    number:       e.number,
4367    label_number: e.label_number,
4368    referrers:    e.referrers.clone(),
4369    bibreferrers: e.bibreferrers.clone(),
4370    citations:    e.citations.clone(),
4371    bibentry:     e.bibentry.clone(),
4372    db_index:     e.db_index,
4373  }
4374}
4375
4376/// Create a bibblock element with xml:space="preserve".
4377/// The text of formatted content (a field's `apply_formatter` result), elements flattened.
4378fn node_data_text(nodes: &[NodeData]) -> String {
4379  nodes
4380    .iter()
4381    .map(|node| match node {
4382      NodeData::Text(text) => text.clone(),
4383      NodeData::Element { children, .. } => node_data_text(children),
4384      NodeData::XmlNode(node) => node.get_content(),
4385    })
4386    .collect()
4387}
4388
4389fn make_bibblock(class: &str, content: &[NodeData]) -> NodeData {
4390  let mut attrs = HashMap::default();
4391  attrs.insert("xml:space".to_string(), "preserve".to_string());
4392  if !class.is_empty() {
4393    attrs.insert("class".to_string(), class.to_string());
4394  }
4395  NodeData::Element {
4396    tag:        "ltx:bibblock".to_string(),
4397    attributes: Some(attrs),
4398    children:   content.to_vec(),
4399  }
4400}
4401
4402/// Find a file in the given search paths.
4403/// Resolve a bibliography source file (`.bib`/`.bbl`/`.bib.xml`).
4404///
4405/// Delegates to the core `pathname::find`, the faithful translation of Perl's
4406/// `pathname_find` (`LaTeXML/Util/Pathname.pm`): a strict-case search over `.`
4407/// plus the search paths, falling back to a CASE-INSENSITIVE directory scan when
4408/// no strict match exists (Perl's `return @paths ? @paths : @nocase_paths`).
4409/// The bibliography path previously used a bespoke case-SENSITIVE lookup, so an
4410/// author on a case-insensitive filesystem citing `\bibliography{EvoFlock.bib}`
4411/// against an on-disk `Evoflock.bib` (arXiv:2606.25280) lost the ENTIRE
4412/// reference list on Linux — a parity gap, since Perl's `pathname_find` resolves
4413/// it. Delegating restores parity (Perl resolves it silently too; no warning,
4414/// matching how the engine already resolves e.g. `PASJ95.STY`).
4415fn find_file(name: &str, search_paths: &[String]) -> Option<String> {
4416  latexml_core::util::pathname::find(name, latexml_core::util::pathname::PathnameFindOptions {
4417    paths: Some(search_paths.to_vec()),
4418    ..Default::default()
4419  })
4420}
4421
4422/// Percent-encode a DOI into its canonical absolute resolver URL.
4423/// Mirrors the engine's `\bib@field@default@doi` (bibtex.rs; Perl
4424/// BibTeX.pool L750-756): `[^0-9a-zA-Z./\-+]` chars are %-encoded.
4425fn doi_href(doi: &str) -> String {
4426  let mut href = String::from("https://doi.org/");
4427  for c in doi.trim().chars() {
4428    if c.is_ascii_alphanumeric() || matches!(c, '.' | '/' | '-' | '+') {
4429      href.push(c);
4430    } else {
4431      let mut buf = [0u8; 4];
4432      for &b in c.encode_utf8(&mut buf).as_bytes() {
4433        href.push_str(&format!("%{:02X}", b));
4434      }
4435    }
4436  }
4437  href
4438}
4439
4440/// A bibliography href without TeX's escapes: `\_ \% \# \& \$ \~ \{ \}` read as the character (`\~{}` as `~`), since
4441/// a backslash is never valid in a URL (issue 808; a `url` field is Verbatim, BibTeX.pool.ltxml:740). Any other
4442/// backslash is left alone. OXIDIZED_DESIGN_DIVERGENCES #1039.
4443fn unescape_tex_url(href: &str) -> String {
4444  let mut out = String::with_capacity(href.len());
4445  let mut rest = href;
4446  while let Some(at) = rest.find('\\') {
4447    out.push_str(&rest[..at]);
4448    rest = &rest[at + 1..];
4449    match rest.chars().next() {
4450      Some(c @ ('_' | '%' | '#' | '&' | '$' | '~' | '{' | '}')) => {
4451        out.push(c);
4452        rest = &rest[1..];
4453        if c == '~' {
4454          rest = rest.strip_prefix("{}").unwrap_or(rest);
4455        }
4456      },
4457      _ => out.push('\\'),
4458    }
4459  }
4460  out.push_str(rest);
4461  out
4462}
4463
4464/// Bibliography links are external: a scheme-less href would resolve
4465/// relative to the article. Prepend https:// when no scheme is present.
4466fn force_absolute_url(url: &str) -> String {
4467  let u = url.trim();
4468  if u.is_empty() || u.contains("://") || u.starts_with("mailto:") {
4469    u.to_string()
4470  } else {
4471    format!("https://{}", u)
4472  }
4473}
4474
4475/// The names a biblatex/bibtex resource is looked up under, in order — the
4476/// exact name first, so it always wins: (1) as given; (2) with `.bib` when it
4477/// carries no extension (biber tries the name, then `name.bib`; a legacy
4478/// `\begin{refsection}[refs]` names its resources that way,
4479/// biblatex-apa6-test.tex:444); (3)/(4) the same two by basename when the
4480/// name has a directory — `\addglobalbib{../bibtex/bib/biblatex-apa-test-
4481/// references.bib}` (biblatex-apa-test.tex:69) mirrors the TeX Live SOURCE
4482/// tree while the `.bib` ships beside the `.tex`, and no search path can
4483/// climb out of the document directory. Perl's `pathname_find` fails the
4484/// same way (SHARED at the file layer); beyond Perl. The whole 283-entry
4485/// apa bibliography hinged on it (16 % recall).
4486fn bib_lookup_candidates(bib_file: &str) -> Vec<String> {
4487  let mut out = vec![bib_file.to_string()];
4488  let base = latexml_core::util::pathname::file_name(bib_file);
4489  let extensionless = !base.contains('.');
4490  if extensionless {
4491    out.push(format!("{bib_file}.bib"));
4492  }
4493  if !base.is_empty() && base != bib_file && bib_file.contains('/') {
4494    out.push(base.clone());
4495    if extensionless {
4496      out.push(format!("{base}.bib"));
4497    }
4498  }
4499  out
4500}
4501
4502#[cfg(test)]
4503mod tests {
4504  use super::*;
4505
4506  /// TeX's escapes leave a bibliography href; any other backslash, and a URL without one, stays (issue 808).
4507  #[test]
4508  fn unescape_tex_url_drops_only_tex_escapes() {
4509    for (raw, href) in [
4510      (
4511        r"https://x.org/a\_b\%20c\#f\&q=1\$\{\}",
4512        "https://x.org/a_b%20c#f&q=1${}",
4513      ),
4514      (r"https://x.org/\~{}u/\~v", "https://x.org/~u/~v"),
4515      (r"https://x.org/a_b%20c", "https://x.org/a_b%20c"),
4516      (r"C:\dir\file\", r"C:\dir\file\"),
4517    ] {
4518      assert_eq!(unescape_tex_url(raw), href, "{raw}");
4519    }
4520  }
4521
4522  /// `join_fields` judges the joint by the text a field prints: after a field
4523  /// ending in a formula (whose own content ends in ".") or in a reference
4524  /// CrossRef fills later, the full separator; after "Ends." only the space.
4525  #[test]
4526  fn join_fields_reads_the_printed_text() {
4527    let xml = r#"<r xmlns="http://dlmf.nist.gov/LaTeXML"><bib-note>Bounds on <Math><XMath><XMTok>n!.</XMTok></XMath></Math></bib-note><bib-note>See <bibref bibrefs="k"/></bib-note><bib-note>Ends.</bib-note><bib-note>Last</bib-note></r>"#;
4528    let doc = libxml::parser::Parser::default()
4529      .parse_string(xml)
4530      .expect("parse");
4531    let nodes = doc.get_root_element().expect("root").get_child_elements();
4532    let printed: String = join_fields(&nodes, ". ")
4533      .iter()
4534      .map(|item| match item {
4535        NodeData::Text(text) => text.clone(),
4536        NodeData::XmlNode(node) if node.get_type() == Some(libxml::tree::NodeType::ElementNode) => {
4537          format!("[{}]", node.get_name())
4538        },
4539        NodeData::XmlNode(node) => node.get_content(),
4540        NodeData::Element { tag, .. } => format!("[{tag}]"),
4541      })
4542      .collect();
4543    assert_eq!(printed, "Bounds on [Math]. See [bibref]. Ends. Last");
4544  }
4545
4546  #[test]
4547  fn test_extract_four_digit_year() {
4548    assert_eq!(extract_four_digit_year("2024"), "2024");
4549    assert_eq!(
4550      extract_four_digit_year("Published in 2024, January"),
4551      "2024"
4552    );
4553    assert_eq!(extract_four_digit_year("99"), "99");
4554    assert_eq!(extract_four_digit_year(""), "");
4555  }
4556
4557  #[test]
4558  fn test_find_file_case_insensitive_bib() {
4559    // An author on a case-insensitive filesystem cites `\bibliography{EvoFlock.bib}`
4560    // but the file on disk is `Evoflock.bib` (arXiv:2606.25280). `find_file`
4561    // delegates to the core pathname resolver, which mirrors Perl's
4562    // case-insensitive fallback, so the reference list is recovered on
4563    // case-sensitive Linux too — a parity fix (Perl's pathname_find resolves it).
4564    let dir = std::env::temp_dir().join("lxo_bib_case_test");
4565    let _ = std::fs::create_dir_all(&dir);
4566    let on_disk = dir.join("Evoflock.bib");
4567    std::fs::write(&on_disk, "@article{k, title={T}}\n").unwrap();
4568    let dirs = vec![dir.to_str().unwrap().to_string()];
4569    // Exact-case still resolves.
4570    assert!(find_file("Evoflock.bib", &dirs).is_some());
4571    // Case-mismatched request resolves via the pathname fallback.
4572    let hit = find_file("EvoFlock.bib", &dirs);
4573    assert!(
4574      hit.is_some(),
4575      "case-mismatched bib filename should resolve via the pathname fallback"
4576    );
4577    assert!(hit.unwrap().to_lowercase().ends_with("evoflock.bib"));
4578    // A genuinely-absent file still returns None (no phantom match).
4579    assert!(find_file("NoSuchBib.bib", &dirs).is_none());
4580    let _ = std::fs::remove_dir_all(&dir);
4581  }
4582
4583  #[test]
4584  fn test_suffix_to_counter() {
4585    assert_eq!(suffix_to_counter("a"), 1);
4586    assert_eq!(suffix_to_counter("b"), 2);
4587    assert_eq!(suffix_to_counter("z"), 26);
4588    assert_eq!(suffix_to_counter("aa"), 27);
4589  }
4590
4591  #[test]
4592  fn test_period_rule() {
4593    use PeriodRule::{AddPeriod, Tracker};
4594    assert_eq!(PeriodRule::of_style(None), AddPeriod);
4595    assert_eq!(PeriodRule::of_style(Some("plainnat")), AddPeriod);
4596    assert_eq!(PeriodRule::of_style(Some("biblatex-giveninits")), Tracker);
4597    // add.period$: `.`, `?`, `!` only; a closer or quote is not skipped.
4598    for text in ["What is X?", "Stop!", "Pub, Inc.", "Inc. "] {
4599      assert!(AddPeriod.absorbs_period(text), "{text}");
4600    }
4601    for text in ["Title", "Ends with colon:", "Second (2nd ed.)", "“Quoted.”"] {
4602      assert!(!AddPeriod.absorbs_period(text), "{text}");
4603    }
4604    // biblatex's tracker: every mark, seen through closers and quotes.
4605    for text in [
4606      "What is X?",
4607      "Ends with colon:",
4608      "Second (2nd ed.)",
4609      "“Quoted.”",
4610    ] {
4611      assert!(Tracker.absorbs_period(text), "{text}");
4612    }
4613    assert!(!Tracker.absorbs_period("Title"));
4614    // A formula ends in no mark; neither does a reference filled in later.
4615    let items = vec![
4616      NodeData::Text("Bounds on ".to_string()),
4617      NodeData::Element {
4618        tag:        "ltx:Math".to_string(),
4619        attributes: None,
4620        children:   vec![NodeData::Text("n!".to_string())],
4621      },
4622    ];
4623    assert_eq!(trailing_text(&items).as_deref(), Some(""));
4624    let items = vec![NodeData::Text("What?".to_string()), NodeData::Element {
4625      tag:        "ltx:bibref".to_string(),
4626      attributes: None,
4627      children:   vec![],
4628    }];
4629    assert_eq!(trailing_text(&items).as_deref(), Some(""));
4630  }
4631
4632  #[test]
4633  fn test_do_name() {
4634    assert_eq!(do_name(Some("John"), "Smith"), "J. Smith");
4635    assert_eq!(do_name(Some("J."), "Smith"), "J. Smith");
4636    assert_eq!(do_name(Some("John Robert"), "Smith"), "J. R. Smith");
4637    assert_eq!(do_name(None, "Smith"), "Smith");
4638  }
4639
4640  #[test]
4641  fn test_do_name_full_given_names() {
4642    GIVEN_NAME_FORM.with(|form| form.set(GivenNameForm::Full));
4643    assert_eq!(do_name(Some("John Robert"), "Smith"), "John Robert Smith");
4644    assert_eq!(do_name(Some("J."), "Smith"), "J. Smith");
4645    assert_eq!(do_name(None, "Smith"), "Smith");
4646    GIVEN_NAME_FORM.with(|form| form.set(GivenNameForm::Initials));
4647    assert_eq!(do_name(Some("John Robert"), "Smith"), "J. R. Smith");
4648  }
4649
4650  #[test]
4651  fn test_bst_given_name_form() {
4652    use GivenNameForm::{Full, Initials};
4653    let call = |template: &str| format!("{{ s nameptr \"{template}\" format.name$ 't := }}");
4654    // plain.bst:191, abbrv.bst:191, bookshelf.bst:29, asmeconf.bst:689,
4655    // apalike.bst:215, splncs04.bst:471.
4656    assert_eq!(bst_given_name_form(&call("{ff~}{vv~}{ll}{, jj}")), Full);
4657    assert_eq!(bst_given_name_form(&call("{f.~}{vv~}{ll}{, jj}")), Initials);
4658    assert_eq!(
4659      bst_given_name_form(&call("{ff{ } }{vv{ } }{ll{ }}{, jj}")),
4660      Full
4661    );
4662    assert_eq!(bst_given_name_form(&call("{vv~}{ll}{, ff}{, jj}")), Full);
4663    assert_eq!(
4664      bst_given_name_form(&call("{vv~}{ll}{, jj}{, f.}")),
4665      Initials
4666    );
4667    assert_eq!(
4668      bst_given_name_form(&call("{vv~}{ll}{, jj}{, f{.}.}")),
4669      Initials
4670    );
4671    assert_eq!(bst_given_name_form(&call("{f}{ll}")), Initials);
4672    // The abnTeX family: its literal `abnt.full.initials` default decides over the name template
4673    // (abntex2-num.bst:448, :2045); the option's own assignment (:1476) does not. Each row's
4674    // template reads the other way, so only the default can give the expected form.
4675    let abnt = |template: &str, default: &str| {
4676      format!(
4677        "{}\n{{ abnt-full-initials \"yes\" = 'abnt.full.initials := }}\n{{ {default} 'abnt.full.initials := }}",
4678        call(template)
4679      )
4680    };
4681    assert_eq!(
4682      bst_given_name_form(&abnt("{vv }{ll}{, jj}{, ff}", "#0")),
4683      Initials
4684    );
4685    assert_eq!(
4686      bst_given_name_form(&abnt("{vv }{ll}{, jj}{, f.}", "#1")),
4687      Full
4688    );
4689    let option_only = format!(
4690      "{}\n{{ abnt-full-initials \"yes\" = 'abnt.full.initials := }}",
4691      call("{f.~}{ll}")
4692    );
4693    assert_eq!(bst_given_name_form(&option_only), Initials);
4694    // A label template without given names is skipped; the author list's decides.
4695    let label_first = format!("{}\n{}", call("{vv~}{ll}"), call("{ff~}{ll}"));
4696    assert_eq!(bst_given_name_form(&label_first), Full);
4697    // A comment is not a template.
4698    let commented = format!("% \"{{ff~}}{{ll}}\" format.name$\n{}", call("{f.~}{ll}"));
4699    assert_eq!(bst_given_name_form(&commented), Initials);
4700    // A template held in a variable (IEEEtran.bst:1213) is unreadable: Perl's
4701    // initials, and the later sort template (`{  ff{ }}`) does not decide.
4702    let variable = format!(
4703      "{{ s nameptr name.format.string format.name$ }}\n{}",
4704      call("{vv{ } }{ll{ }}{  ff{ }}{  jj{ }}")
4705    );
4706    assert_eq!(bst_given_name_form(&variable), Initials);
4707    assert_eq!(bst_given_name_form("ENTRY { author } {} {}"), Initials);
4708    // The "et al." test is not the printed form (achemso.bst:514, :874).
4709    let others_test = format!(
4710      "{{ names.str #2 \"{{ff }}{{vv }}{{ll}}{{ jj}}\" format.name$\n  \"others\" = }}\n{}",
4711      call("{vv~}{ll}{,~f.}{,~jj}")
4712    );
4713    assert_eq!(bst_given_name_form(&others_test), Initials);
4714  }
4715
4716  #[test]
4717  fn test_fmt_spec_coverage() {
4718    // Ensure all format types produce non-empty specs
4719    for fmt in &[
4720      "article",
4721      "book",
4722      "incollection",
4723      "report",
4724      "thesis",
4725      "website",
4726      "software",
4727    ] {
4728      let specs = get_fmt_spec(fmt);
4729      assert!(
4730        !specs.is_empty(),
4731        "FMT_SPEC for '{}' should not be empty",
4732        fmt
4733      );
4734    }
4735  }
4736}