Skip to main content

latexml_post/
crossref.rs

1//! Cross-reference resolution processor.
2//!
3//! Port of `LaTeXML::Post::CrossRef` (946 lines of Perl).
4//! Resolves cross-references (`ltx:ref`, `ltx:bibref`, etc.) by looking up
5//! referenced IDs in the ObjectDB and filling in the reference text,
6//! titles, and navigation links.
7
8use std::{
9  cell::{OnceCell, RefCell},
10  collections::VecDeque,
11  rc::Rc,
12  sync::LazyLock,
13};
14
15use latexml_core::common::xml::name_is;
16use libxml::tree::{Node, NodeType};
17use regex::Regex;
18use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
19
20use crate::{
21  document::{NodeData, PostDocument, get_xml_id},
22  object_db::{Entry, ObjectDB, Value},
23  processor::{ProcessResult, Processor},
24  scan::{title_node_text, title_text_content},
25};
26
27/// Perl CrossRef.pm `$normaltoctypes` (L202-206): the sectional element types
28/// used by `gentoc_context`'s UPWARD ancestor/sibling enclosure. This is NOT
29/// the normal `gen_toc` path — that filters purely by the TOC's
30/// `select`/`inlist` (issue #291). Deliberately excludes
31/// `ltx:abstract`/`ltx:acknowledgements` (matching Perl exactly) so frontmatter
32/// does not clutter the navigation breadcrumb's sibling rows.
33const NORMAL_TOC_TYPES: &[&str] = &[
34  "ltx:document",
35  "ltx:part",
36  "ltx:chapter",
37  "ltx:section",
38  "ltx:subsection",
39  "ltx:subsubsection",
40  "ltx:paragraph",
41  "ltx:subparagraph",
42  "ltx:index",
43  "ltx:bibliography",
44  "ltx:glossary",
45  "ltx:appendix",
46];
47
48/// Memoized result of `get_child_page_ids` for one ObjectDB entry: the
49/// distinct descendant page ids, plus a position index so
50/// `find_previous_page_id`/`find_next_page_id` can locate a sibling in O(1)
51/// instead of the Perl pop/shift scan.
52struct ChildPages {
53  ids:      Vec<String>,
54  index_of: HashMap<String, usize>,
55  /// The `(relation, pageid)` head links these pages contribute, filled on first use by
56  /// [`CrossRef::related_pages`].
57  related:  OnceCell<Vec<(&'static str, String)>>,
58}
59
60/// The page types whose sibling/child relation `fill_in_relations` keeps: the footer navigation of
61/// `LaTeXML-webpage-xhtml.xsl` reads `rel='bibliography'`/`'index'`/`'glossary'`. The sectional
62/// relations (`chapter`, `section`, …) and `sidebar` are read by nothing but the head-link copy
63/// (OXIDIZED_DESIGN_DIVERGENCES #1134).
64const KEPT_RELATIONS: &[&str] = &["bibliography", "index", "glossary"];
65
66/// Fallback fields when a requested ref show key is not found.
67fn ref_fallbacks(key: &str) -> &'static [&'static str] {
68  match key {
69    "typerefnum" => &["refnum"],
70    // cleveref's label format (cleveref_sty.rs `\lx@creflabel@@`), for a target numbered without its tag.
71    "creflabel" => &["refnum"],
72    "toctitle" => &["title", "toccaption"],
73    "title" => &["toccaption"],
74    "rawtoctitle" => &["toctitle", "title", "toccaption"],
75    "rawtitle" => &["title", "toccaption"],
76    _ => &[],
77  }
78}
79
80/// A stored tag's text in a tooltip: a tag with markup (Scan stores its copy) as [`value_text`] reads it, its math in
81/// reading order; a tag of text alone as it is.
82fn tag_text(doc: &PostDocument, val: &Value) -> String {
83  match val {
84    Value::Xml(_) => value_text(doc, val),
85    other => other.to_string(),
86  }
87}
88
89/// Derive the STRING form of a stored value (page `<title>`, `title=` tooltip).
90/// Perl `CrossRef::getTextContent` (`CrossRef.pm` L853-859). A `Value::Xml` title
91/// is flattened tag-aware and math-aware, the stored node itself first, as Perl's
92/// `getTextContent_rec($doc, $title)`: a stored `ltx:tag` (a `refnum`) reads as its
93/// plain text inside its `open`/`close` ([`title_node_text`]), an `ltx:title` by
94/// its children, with `ltx:Math` through `unicodemath`. Any other value uses its
95/// plain string form. Either way the result is whitespace-collapsed like Perl: trim
96/// both ends, then `s/\s+/ /g` — so a multi-line math serialization cannot bloat a
97/// `title=` tooltip (issue #761).
98fn value_text(doc: &PostDocument, val: &Value) -> String {
99  let raw = match val {
100    Value::Xml(node) if node.get_type() == Some(NodeType::ElementNode) => {
101      title_node_text(doc, node)
102    },
103    Value::Xml(node) => title_text_content(doc, node),
104    other => other.to_string(),
105  };
106  // Perl `getTextContent`: `s/^\s+//; s/\s+$//; s/\s+/ /g`. `split_whitespace`
107  // does exactly this (drops leading/trailing runs, collapses interior runs).
108  raw.split_whitespace().collect::<Vec<_>>().join(" ")
109}
110
111/// Build the child nodes of an `<ltx:ref>` from a stored value, as stored.
112///
113/// Port of Perl `CrossRef::prepRefText` = `cloneNodes(trimChildNodes($value))`
114/// without its `fillInTitle`, which [`CrossRef::ref_text_children`] adds:
115/// deep-clone the title's child nodes — `<ltx:Math>` included — trimming
116/// whitespace at the two edges. Element children become [`NodeData::XmlNode`]
117/// (deep-copied at materialization by `PostDocument::add_xml_node`, which
118/// uniquifies their `xml:id`s); text children become [`NodeData::Text`]. A
119/// plain-string value keeps the single flat-text child.
120fn ref_content_children(val: &Value) -> Vec<NodeData> {
121  match val {
122    Value::Xml(node) => trim_child_data(child_nodes_data(node)),
123    other => vec![NodeData::Text(other.to_string())],
124  }
125}
126
127/// Perl `Post::Document::trimChildNodes` on ref content: left-trim the first text child, right-trim the last; drop
128/// either if it becomes empty.
129fn trim_child_data(mut out: Vec<NodeData>) -> Vec<NodeData> {
130  if let Some(NodeData::Text(s)) = out.first_mut() {
131    let t = s.trim_start().to_string();
132    if t.is_empty() {
133      out.remove(0);
134    } else {
135      *s = t;
136    }
137  }
138  if let Some(NodeData::Text(s)) = out.last_mut() {
139    let t = s.trim_end().to_string();
140    if t.is_empty() {
141      out.pop();
142    } else {
143      *s = t;
144    }
145  }
146  out
147}
148
149/// Strip `fragid` from everything inside an `<ltx:ref>` (TOC entries, inline
150/// refs, navigation).
151///
152/// Reference content is a non-anchor DISPLAY copy of a title, so it must not
153/// carry a `fragid` — the XSLT `add_id` template emits the HTML `id` from
154/// `fragid`, and a display copy with an `id` would spuriously duplicate the
155/// real target's anchor. Perl gets this for free: its ref content is cloned
156/// from Scan's `cleanNode` snapshot, taken before `fragid` is assigned
157/// (`Scan.pm` L290 / `CrossRef.pm` fillInFrags). We clone the live (already
158/// `fragid`'d) title, so we drop `fragid` here to match (issue #356). The
159/// uniquified `xml:id` is kept, as in Perl's snapshot.
160fn strip_ref_display_fragids(doc: &PostDocument) {
161  for mut n in doc.findnodes("//ltx:ref//*[@fragid]") {
162    let _ = n.remove_attribute("fragid");
163  }
164}
165
166/// URL style for cross-references (Perl `--urlstyle`; `Config.pm` accepts
167/// `server`, `negotiated`, `file`). Selects how [`CrossRef`]'s URL generation
168/// rewrites a generated cross-reference URL for the serving environment.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum UrlStyle {
171  /// Keep the full `file.html#fragment` — nothing stripped. Correct for
172  /// `file://` viewing and servers that do not rewrite `index.html`.
173  File,
174  /// Strip a trailing `index.ext` so a directory index links as `dir/`
175  /// (Perl's `latexml` default; for servers that serve `dir/` → `dir/index.ext`).
176  Server,
177  /// Content negotiation: strip the `.ext` extension AND a trailing `index`
178  /// (for servers that hide the extension, e.g. BookML's `--urlstyle=negotiated`).
179  Negotiated,
180}
181
182impl UrlStyle {
183  /// Parse a CLI `--urlstyle` value. Returns `None` for an unrecognized value
184  /// (the caller reports it, mirroring Perl `_checkOptionValue`).
185  pub fn from_cli(s: &str) -> Option<Self> {
186    match s {
187      "file" => Some(UrlStyle::File),
188      "server" => Some(UrlStyle::Server),
189      "negotiated" => Some(UrlStyle::Negotiated),
190      _ => None,
191    }
192  }
193
194  /// The canonical CLI tag — round-trips through [`UrlStyle::from_cli`]. Used to
195  /// serialize the style across the parallel page-render worker manifest.
196  pub fn as_cli(self) -> &'static str {
197    match self {
198      UrlStyle::File => "file",
199      UrlStyle::Server => "server",
200      UrlStyle::Negotiated => "negotiated",
201    }
202  }
203}
204
205/// Rewrite a generated cross-reference `url` for the given [`UrlStyle`], mirroring
206/// Perl `CrossRef::generateURL` (CrossRef.pm L656-663) verbatim — including its
207/// `(^|\/)` path boundary: a trailing `index[.ext]` is stripped only at the very
208/// start of the URL or right after a `/`, so a filename like `myindex.html` is
209/// left intact. `extension` is the output file extension (e.g. `html`).
210fn apply_url_style(url: &str, style: UrlStyle, extension: &str) -> String {
211  match style {
212    // Perl: s/(^|\/)index.\Q$ext\E$/($1 ? $1 : '.\/')/e
213    UrlStyle::Server => {
214      let index_suffix = format!("index.{extension}");
215      if let Some(prefix) = url.strip_suffix(&index_suffix) {
216        if prefix.is_empty() {
217          return "./".to_string(); // matched at start ($1 empty → './')
218        } else if prefix.ends_with('/') {
219          return prefix.to_string(); // matched after '/' ($1 = '/', kept)
220        } // else: no path boundary before `index` → leave url unchanged
221      }
222      url.to_string()
223    },
224    // Perl: s/\.\Q$ext\E$// then s/(^|\/)index$/$1/
225    UrlStyle::Negotiated => {
226      let stripped = url.strip_suffix(&format!(".{extension}")).unwrap_or(url);
227      if stripped == "index" {
228        String::new() // matched at start ($1 empty)
229      } else if let Some(prefix) = stripped.strip_suffix("index") {
230        if prefix.ends_with('/') {
231          prefix.to_string() // matched after '/' ($1 = '/', kept)
232        } else {
233          stripped.to_string() // no path boundary → leave (e.g. `myindex`)
234        }
235      } else {
236        stripped.to_string()
237      }
238    },
239    UrlStyle::File => url.to_string(),
240  }
241}
242
243/// One memoized [`CrossRef::generate_ref`] content: its `show`, `is_nameref` and the content.
244type RefMemoEntry = (String, bool, Vec<NodeData>);
245
246/// One memoized [`CrossRef::generate_title`] entry for an ID: `(shown, title)`.
247/// Each ID only takes 1-2 `shown` values (`""`, `"title"`), so a tiny `Vec`
248/// avoids allocating an inner `HashMap` per page ID across 100K+ split pages.
249type TitleMemoEntry = (String, Option<String>);
250
251/// Upper bound on distinct IDs retained in `title_memo` / `ref_memo`. Hot
252/// ancestors (`start`, `up`, chapters) re-warm immediately after a clear while
253/// 100K+ one-shot leaf `prev`/`next` entries cannot grow RAM without bound.
254const MAX_MEMO_IDS: usize = 16_384;
255
256/// CrossRef post-processor.
257///
258/// Port of `LaTeXML::Post::CrossRef`.
259pub struct CrossRef {
260  name:           String,
261  /// Reference to the shared ObjectDB.
262  pub db:         ObjectDB,
263  /// URL style for cross-references.
264  url_style:      UrlStyle,
265  /// File extension used for output (e.g. "html", "xml").
266  extension:      String,
267  /// Default show format for TOC refs.
268  toc_show:       String,
269  /// Default show format for regular refs.
270  ref_show:       String,
271  /// Minimum useful content length for refs.
272  min_ref_length: usize,
273  /// Join string between parent+child ref text.
274  ref_join:       String,
275  /// Type of navigation TOC to add (e.g. "context").
276  navigation_toc: Option<String>,
277  /// Track missing references for reporting.
278  missing:        HashMap<String, HashMap<String, HashMap<String, u32>>>,
279  /// Memoized `get_child_page_ids` results, keyed by entry id. The ObjectDB
280  /// is read-only for the whole CrossRef pass, so a given entry's child pages
281  /// never change — caching them across all split pages turns the per-page
282  /// O(siblings) recomputation (Perl's unpruned `getChildPages`) into O(1)
283  /// lookups, eliminating the `fill_in_relations` O(n²).
284  child_pages:    RefCell<HashMap<String, Rc<ChildPages>>>,
285  /// The entries whose stored values are being filled in, innermost last: a value whose own refs lead back to its
286  /// entry (`\section{On \nameref{s}}\label{s}`) is used as stored the second time, where Perl's `fillInTitle`
287  /// recurses without end.
288  filling:        RefCell<Vec<String>>,
289  /// Memoized [`Self::generate_title`] results, keyed by id then `shown` (bounded by [`MAX_MEMO_IDS`]).
290  /// Only a title read from no math is kept: `unicodemath` realizes an `XMRef` against the page.
291  title_memo:     RefCell<HashMap<String, Vec<TitleMemoEntry>>>,
292  /// Memoized [`Self::generate_ref`] content by id, then (show, is_nameref) (bounded by [`MAX_MEMO_IDS`]):
293  /// it reads the ObjectDB alone.
294  ref_memo:       RefCell<HashMap<String, Vec<RefMemoEntry>>>,
295}
296
297/// One cited entry as Perl `make_bibcite` collects it (`CrossRef.pm` L516-562):
298/// the trimmed display parts each `show` role clones, and the attributes of
299/// every `<ltx:ref>` made for it.
300struct BibciteDatum {
301  key:         String,
302  authors:     Vec<NodeData>,
303  fullauthors: Vec<NodeData>,
304  /// Text of `authors || fullauthors` — the key that groups consecutive
305  /// same-author entries under one author label (L610). `''` without either,
306  /// and for a missing entry (whose undef compares `eq` to `''`).
307  authortext:  String,
308  year:        Vec<NodeData>,
309  /// The `(\d\d\d\d)(\w)` split of a suffixed year (`2001a`), so a same-author
310  /// run shows `2001a, b` (L613).
311  rawyear:     Option<String>,
312  suffix:      Option<String>,
313  number:      Vec<NodeData>,
314  refnum:      Vec<NodeData>,
315  title:       Vec<NodeData>,
316  /// The entry as the bibliography list sets it, inline: its bibitem's `ltx:bibblock`s but "Cited by" (`FullEntry`,
317  /// biblatex's `\fullcite`, biblatex.def:2481-2495, which typesets the entry's driver where it is cited).
318  fullentry:   Vec<NodeData>,
319  attr:        HashMap<String, String>,
320  /// A key with no bibliography entry (L559-561): one `ltx_missing_citation`
321  /// ref showing the key, whatever the `show`.
322  missing:     bool,
323  /// An entry with no name to print under a textual numeric `show` ([`nameless_numeric_show`]): its label keeps the
324  /// phrases and the number alone.
325  nameless:    bool,
326}
327
328impl BibciteDatum {
329  /// The entry's number, which a sorting citation orders by: its `number` (else `refnum`) when that is a whole
330  /// number, as natbib's `\NAT@ifcat@num` and cite.sty's `\@cite@posnumtest` take it; none for a missing entry.
331  fn entry_number(&self) -> Option<u64> {
332    let text = self.sort_label()?;
333    (!text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()))
334      .then(|| text.parse().ok())
335      .flatten()
336  }
337
338  /// The entry's sort number as cite.sty computes it ([`cite_sty_sort_key`]); none for a missing entry or a label it
339  /// cannot sort.
340  fn cite_sty_key(&self) -> Option<u64> { cite_sty_sort_key(&self.sort_label()?) }
341
342  /// The label a sorting citation reads: the entry's `number`, else its `refnum`, trimmed; none for a missing entry.
343  fn sort_label(&self) -> Option<String> {
344    if self.missing {
345      return None;
346    }
347    let label = if self.number.is_empty() {
348      &self.refnum
349    } else {
350      &self.number
351    };
352    Some(text_content(label).trim().to_string())
353  }
354}
355
356/// cite.sty's sort number of a citation label (cite.sty:127-222 `\@addto@cite@list`): a number `n` is `256n`; a
357/// `[prefix]number[suffix]` label, one character each, `(16384p + n)·256 + s` (the characters' codes, `p` zero
358/// without a prefix: "2a" sorts after 2, before 3); a number, a separator and a number (`1.2`) `((16384p + n)·256 +
359/// sep)·4096 + m`, while the part before `m` is below 262144. Any other label (`Knu84`) has none: cite.sty prints it
360/// at once, before the sorted ones (`\@cite@gobbledump@now`).
361fn cite_sty_sort_key(label: &str) -> Option<u64> {
362  let chars: Vec<char> = label.chars().collect();
363  if chars.is_empty() {
364    return None;
365  }
366  if chars.iter().all(char::is_ascii_digit) {
367    return label.parse::<u64>().ok().map(|n| n * 256);
368  }
369  let (prefix, rest) = if chars[0].is_ascii_digit() {
370    (0, &chars[..])
371  } else {
372    (u64::from(u32::from(chars[0])), &chars[1..])
373  };
374  let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
375  if digits == 0 {
376    return None;
377  }
378  let number: u64 = rest[..digits].iter().collect::<String>().parse().ok()?;
379  let mut key = (prefix * 16384 + number) * 256;
380  let Some((mark, tail)) = rest[digits..].split_first() else {
381    return Some(key);
382  };
383  key += u64::from(u32::from(*mark));
384  if tail.is_empty() {
385    return Some(key);
386  }
387  if tail.iter().all(char::is_ascii_digit) && key < 262144 {
388    let last: u64 = tail.iter().collect::<String>().parse().ok()?;
389    return Some(key * 4096 + last);
390  }
391  None
392}
393
394/// Perl `Post::Document::trimChildNodes` (`Post.pm` L1374-1397) of a stored
395/// bibitem tag value: its children with the leading whitespace of the first
396/// text child and the trailing whitespace of the last trimmed away, a child left
397/// empty dropped. A string value stands for the tag's text: trimmed, or nothing.
398fn trim_child_nodes(val: Option<&Value>) -> Vec<NodeData> {
399  match val {
400    None | Some(Value::Null) => Vec::new(),
401    Some(v @ Value::Xml(_)) => ref_content_children(v),
402    Some(v) => {
403      let s = v.to_string();
404      let t = s.trim();
405      if t.is_empty() {
406        Vec::new()
407      } else {
408        vec![NodeData::Text(t.to_string())]
409      }
410    },
411  }
412}
413
414/// A bibliography entry's text, inline (show `FullEntry`), as biblatex's `\fullcite` typesets the entry's driver
415/// where it cites (biblatex.def:2481-2495): the `ltx:bibblock`s of its `ltx:bibitem` but the "Cited by" one, one space
416/// apart. `dropped_year` is the year an author-year entry's first block left to its label (MakeBibliography
417/// `drop_first_year`); it comes back after the first block with content (the author's, else the title's), as a numeric
418/// entry's block carries it. The closing period
419/// goes: `\usedriver` lets `\finentry` set no punctuation (biblatex.sty:4135, :4245 `\blx@finentry@usedrv`);
420/// MakeBibliography sets it as a text node `.` of its own (field content is always in an `ltx:text`), and only such
421/// a node is dropped. Empty for a bibitem with no blocks.
422fn full_entry(bibitem: &Node, dropped_year: Option<&str>) -> Vec<NodeData> {
423  let mut text = Vec::new();
424  let blocks = crate::document::element_children(bibitem)
425    .into_iter()
426    .filter(|block| {
427      name_is(block, "bibblock")
428        && !block
429          .get_attribute("class")
430          .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_bib_cited"))
431    });
432  let mut dropped_year = dropped_year;
433  for (i, block) in blocks.enumerate() {
434    if i > 0 {
435      text.push(NodeData::Text(" ".to_string()));
436    }
437    text.extend(child_nodes_data(&block));
438    // After the first block with content, as MakeBibliography left it out (`format_blocks`).
439    if !crate::document::element_children(&block).is_empty()
440      && let Some(year) = dropped_year.take()
441    {
442      text.push(NodeData::Element {
443        tag:        "ltx:text".to_string(),
444        attributes: Some(HashMap::from_iter([(
445          "class".to_string(),
446          "ltx_bib_year".to_string(),
447        )])),
448        children:   vec![NodeData::Text(year.to_string())],
449      });
450    }
451  }
452  if matches!(text.last(), Some(NodeData::Text(last)) if last.trim() == ".") {
453    text.pop();
454  }
455  text
456}
457
458/// A node's children as insertable data, untrimmed: text by value, elements by
459/// reference (deep-copied on insertion). Perl hands `addNodes` the live
460/// `childNodes`, which it copies the same way.
461fn child_nodes_data(node: &Node) -> Vec<NodeData> {
462  let mut out: Vec<NodeData> = Vec::new();
463  let mut child = node.get_first_child();
464  while let Some(c) = child {
465    match c.get_type() {
466      Some(NodeType::TextNode) => out.push(NodeData::Text(c.get_content())),
467      Some(NodeType::ElementNode) => out.push(NodeData::XmlNode(c.clone())),
468      _ => {},
469    }
470    child = c.get_next_sibling();
471  }
472  out
473}
474
475/// Whether a stored title holds what Perl `CrossRef::fillInTitle` (CrossRef.pm:882-904) replaces before the title
476/// is reused: an `ltx:ref` never filled — Scan stored the title before CrossRef ran, so a `\ref`, `\eqref`,
477/// `\autoref`, `\cref` or `\nameref` in a section title is still empty there (1011.3492, 1111.3672) — or an
478/// `ltx:break`. Math is not entered: its copy keeps the ids its own references point to.
479fn needs_fill_in(node: &Node) -> bool {
480  let mut child = node.get_first_child();
481  while let Some(c) = child {
482    if c.get_type() == Some(NodeType::ElementNode) {
483      match c.get_name().as_str() {
484        "ref" if is_unfilled_ref(&c) => return true,
485        "break" => return true,
486        "Math" => {},
487        _ if needs_fill_in(&c) => return true,
488        _ => {},
489      }
490    }
491    child = c.get_next_sibling();
492  }
493  false
494}
495
496/// Does a stored value read the page it is shown on? Its math does (`unicodemath` realizes an `XMRef` against the
497/// page), and so may the targets of refs still to fill in it.
498fn value_reads_page(val: &Value) -> bool {
499  fn holds_math(node: &Node) -> bool {
500    let mut child = node.get_first_child();
501    while let Some(c) = child {
502      if c.get_type() == Some(NodeType::ElementNode) && (c.get_name() == "Math" || holds_math(&c)) {
503        return true;
504      }
505      child = c.get_next_sibling();
506    }
507    false
508  }
509  match val {
510    Value::Xml(node) => {
511      (node.get_type() == Some(NodeType::ElementNode) && node.get_name() == "Math")
512        || holds_math(node)
513        || needs_fill_in(node)
514    },
515    _ => false,
516  }
517}
518
519/// An `ltx:ref` naming its target (`idref`/`labelref`) whose text is still to be generated (Perl `next if
520/// $ref->textContent`).
521fn is_unfilled_ref(node: &Node) -> bool {
522  (node.has_attribute("idref") || node.has_attribute("labelref")) && node.get_content().is_empty()
523}
524
525/// The text of ref content as Perl `getTextContent` reads a filled title (`CrossRef.pm` L861-879): a tag with its
526/// `open`/`close`, math in its Unicode reading.
527fn node_data_text(doc: &PostDocument, data: &[NodeData]) -> String {
528  let mut out = String::new();
529  for datum in data {
530    match datum {
531      NodeData::Text(text) => out.push_str(text),
532      NodeData::XmlNode(node) => out.push_str(&title_node_text(doc, node)),
533      NodeData::Element { tag, attributes, children } => {
534        let attr = |key: &str| {
535          attributes
536            .as_ref()
537            .and_then(|attributes| attributes.get(key))
538            .map_or("", String::as_str)
539        };
540        let tagged = tag == "ltx:tag";
541        if tagged {
542          out.push_str(attr("open"));
543        }
544        out.push_str(&node_data_text(doc, children));
545        if tagged {
546          out.push_str(attr("close"));
547        }
548      },
549    }
550  }
551  out
552}
553
554/// `['ltx:ref', $attr, @children]`.
555fn bib_ref(attr: &HashMap<String, String>, children: Vec<NodeData>) -> NodeData {
556  NodeData::Element {
557    tag: "ltx:ref".to_string(),
558    attributes: Some(attr.clone()),
559    children,
560  }
561}
562
563/// Perl `make_bibcite`'s show walk (`CrossRef.pm` L564-643) for one cited
564/// entry, returning `(stuff, didref)`. The show string is a sequence of role
565/// words — lowercased with one trailing `s` stripped (L585), so `Authors`,
566/// `author` and `authors` are one role — among `{literal}` text, `~` (a
567/// no-break space), whitespace and other punctuation, which pass through.
568/// `author`/`fullauthor`/`title`/`refnum`/`phraseN` clone their values;
569/// `year`/`number`/`super` make the `<ltx:ref>` link themselves (`didref`),
570/// and absorb the following entries of the same authors when `checkdups`
571/// (`Smith (2001a, b)`). Without a link made inside, the caller wraps the
572/// whole label in one.
573fn bibcite_show_walk(
574  saveshow: &str,
575  datum: &BibciteDatum,
576  data: &mut VecDeque<BibciteDatum>,
577  preformatted: &[NodeData],
578  phrases: &[Node],
579  yysep: &str,
580  checkdups: bool,
581) -> (Vec<NodeData>, bool, Option<bool>) {
582  static YEAR_DELIM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(\w)year").unwrap());
583  static PHRASE_DELIM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(\w)phrase").unwrap());
584  static PHRASE_NUM_DELIM: LazyLock<Regex> =
585    LazyLock::new(|| Regex::new(r"(?i)phrase(\d)(\w)").unwrap());
586  static ROLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+").unwrap());
587  static LITERAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\{([^}]*)\}").unwrap());
588  static SPACES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s+").unwrap());
589  static PUNCT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\W+").unwrap());
590  static EMPTY_YEAR_PHRASE2: LazyLock<Regex> =
591    LazyLock::new(|| Regex::new(r"(?i)^\{\}year\{\}phrase2").unwrap());
592
593  let mut didref = false;
594  // The entry's form (issue #857): `Some(true)` when it printed only numbers or labels, `None` when no role.
595  let mut numeric: Option<bool> = None;
596  let mut stuff: Vec<NodeData> = Vec::new();
597  let mut show = saveshow;
598  if show == "none" && !preformatted.is_empty() {
599    stuff = preformatted.to_vec();
600    numeric = Some(false);
601    show = "";
602  } else if datum.missing {
603    stuff = vec![bib_ref(&datum.attr, vec![NodeData::Text(
604      datum.key.clone(),
605    )])];
606    didref = true;
607    show = "";
608  }
609  // Add delimiters for parsing (L579-582): `Phrase1Year` → `Phrase1{}year`.
610  let show = YEAR_DELIM.replace_all(show, "${1}{}year");
611  let show = PHRASE_DELIM.replace_all(&show, "${1}{}phrase");
612  let show = PHRASE_NUM_DELIM.replace_all(&show, "phrase${1}{}${2}");
613  let mut rest: &str = &show;
614  // The same-author run after `datum` (L610, L620, L627): the entries
615  // `year`/`number`/`super` absorb.
616  let same_authors = |data: &VecDeque<BibciteDatum>| {
617    data
618      .front()
619      .is_some_and(|n| n.authortext == datum.authortext)
620  };
621  while !rest.is_empty() {
622    if let Some(m) = ROLE.find(rest) {
623      let mut role = m.as_str().to_lowercase();
624      rest = &rest[m.end()..];
625      if role.ends_with('s') {
626        role.pop();
627      }
628      match role.as_str() {
629        "refnum" | "number" | "super" => numeric = Some(numeric.unwrap_or(true)),
630        "author" | "fullauthor" | "title" | "fullentry" | "year" => numeric = Some(false),
631        _ => {},
632      }
633      match role.as_str() {
634        "author" => stuff.extend(datum.authors.iter().cloned()),
635        "fullauthor" => stuff.extend(datum.fullauthors.iter().cloned()),
636        "title" => stuff.extend(datum.title.iter().cloned()),
637        "refnum" => stuff.extend(datum.refnum.iter().cloned()),
638        // An entry with no text to copy (no blocks) links its number instead, as `refnum` would.
639        "fullentry" if datum.fullentry.is_empty() => {
640          stuff.push(bib_ref(&datum.attr, datum.refnum.clone()));
641          didref = true;
642        },
643        "fullentry" => {
644          stuff.extend(datum.fullentry.iter().cloned());
645          didref = true;
646        },
647        "year" => {
648          // (L605-606's "Date for citation" warning is unreachable: the year
649          // list is always defined, possibly empty.)
650          if !datum.year.is_empty() {
651            stuff.push(bib_ref(&datum.attr, datum.year.clone()));
652            didref = true;
653            while checkdups && same_authors(data) {
654              let next = data.pop_front().unwrap();
655              stuff.push(NodeData::Text(yysep.to_string()));
656              stuff.push(NodeData::Text(" ".to_string()));
657              let same_year = datum.rawyear.as_deref().unwrap_or("no_year_1")
658                == next.rawyear.as_deref().unwrap_or("no_year_2");
659              match next.suffix {
660                Some(ref suffix) if same_year => {
661                  stuff.push(bib_ref(&next.attr, vec![NodeData::Text(suffix.clone())]))
662                },
663                _ => stuff.push(bib_ref(&next.attr, next.year.clone())),
664              }
665            }
666          }
667        },
668        "number" | "super" => {
669          let mut r = vec![bib_ref(&datum.attr, datum.number.clone())];
670          didref = true;
671          while checkdups && same_authors(data) {
672            let next = data.pop_front().unwrap();
673            r.push(NodeData::Text(yysep.to_string()));
674            r.push(NodeData::Text(" ".to_string()));
675            r.push(bib_ref(&next.attr, next.number.clone()));
676          }
677          if role == "super" {
678            stuff.push(NodeData::Element {
679              tag:        "ltx:sup".to_string(),
680              attributes: None,
681              children:   r,
682            });
683          } else {
684            stuff.extend(r);
685          }
686        },
687        _ => match role.strip_prefix("phrase").and_then(|d| {
688          let mut ds = d.chars();
689          ds.next()
690            .and_then(|c| c.to_digit(10))
691            .filter(|_| ds.next().is_none())
692        }) {
693          // L594-603. HACK (Perl's): an author-year show frozen before the
694          // entry had a year drops the empty `( )` of `Phrase1{}Year{}Phrase2`.
695          Some(n) => {
696            let short = |i: usize| {
697              phrases
698                .get(i)
699                .is_none_or(|p| p.get_content().chars().count() <= 1)
700            };
701            if n == 1
702              && datum.year.is_empty()
703              && short(0)
704              && short(1)
705              && let Some(m) = EMPTY_YEAR_PHRASE2.find(rest)
706            {
707              rest = &rest[m.end()..];
708            } else {
709              // `$phrases[$n - 1]`: `phrase0` is Perl's index -1, the last.
710              let phrase = match n {
711                0 => phrases.last(),
712                n => phrases.get(n as usize - 1),
713              };
714              if let Some(phrase) = phrase {
715                stuff.extend(child_nodes_data(phrase));
716              }
717            }
718          },
719          None => Info!("unexpected", role, "CITE ignoring show key '{}'", role),
720        },
721      }
722    } else if let Some(c) = LITERAL.captures(rest) {
723      // Pass-thru literal, quoted with {}.
724      if !c[1].is_empty() {
725        stuff.push(NodeData::Text(c[1].to_string()));
726      }
727      rest = &rest[c[0].len()..];
728    } else if let Some(r) = rest.strip_prefix('~') {
729      if !stuff.is_empty() {
730        stuff.push(NodeData::Text("\u{A0}".to_string()));
731      }
732      rest = r;
733    } else if let Some(m) = SPACES.find(rest) {
734      if !stuff.is_empty() {
735        stuff.push(NodeData::Text(m.as_str().to_string()));
736      }
737      rest = &rest[m.end()..];
738    } else if let Some(m) = PUNCT.find(rest) {
739      stuff.push(NodeData::Text(m.as_str().to_string()));
740      rest = &rest[m.end()..];
741    } else {
742      // Unreachable: every character is `\w` or `\W`.
743      break;
744    }
745  }
746  (stuff, didref, numeric)
747}
748
749impl CrossRef {
750  pub fn new(db: ObjectDB, url_style: UrlStyle, number_sections: bool) -> Self {
751    CrossRef {
752      name: "CrossRef".to_string(),
753      db,
754      url_style,
755      extension: "xml".to_string(),
756      toc_show: "toctitle".to_string(),
757      ref_show: if number_sections {
758        "refnum".to_string()
759      } else {
760        "title".to_string()
761      },
762      min_ref_length: 1,
763      ref_join: " \u{2023} ".to_string(), // TRIANGULAR BULLET
764      navigation_toc: None,
765      missing: HashMap::default(),
766      child_pages: RefCell::new(HashMap::default()),
767      filling: RefCell::new(Vec::new()),
768      title_memo: RefCell::new(HashMap::default()),
769      ref_memo: RefCell::new(HashMap::default()),
770    }
771  }
772
773  /// Set the file extension for URL generation.
774  pub fn set_extension(&mut self, ext: &str) { self.extension = ext.to_string(); }
775
776  /// Set the navigation TOC format.
777  pub fn set_navigation_toc(&mut self, format: &str) {
778    self.navigation_toc = Some(format.to_string());
779  }
780
781  /// Note a missing reference.
782  fn note_missing(&mut self, severity: &str, ref_type: &str, key: &str) {
783    self
784      .missing
785      .entry(severity.to_string())
786      .or_default()
787      .entry(ref_type.to_string())
788      .or_default()
789      .entry(key.to_string())
790      .and_modify(|c| *c += 1)
791      .or_insert(1);
792  }
793
794  /// Generate a URL for a referenced ID.
795  ///
796  /// Port of `CrossRef::generateURL`.
797  fn generate_url(&mut self, doc: &PostDocument, id: &str) -> Option<String> {
798    let entry = self.db.lookup(&format!("ID:{}", id))?;
799    let location = entry.get_string("location")?;
800
801    let doc_location = doc.site_relative_destination().unwrap_or_default();
802    let mut url = relative_url(location, &doc_location);
803
804    url = apply_url_style(&url, self.url_style, &self.extension);
805
806    if url.is_empty() {
807      url = ".".to_string();
808    }
809
810    // Add fragment ID
811    let fragid = entry.get_string("fragid").map(String::from);
812    let loc = location.to_string();
813    if let Some(fid) = fragid {
814      if url == "." || loc == doc_location {
815        url.clear();
816      }
817      url = format!("{}#{}", url, fid);
818    } else if loc == doc_location {
819      url.clear();
820    }
821
822    Some(url)
823  }
824
825  /// Generate a title string for a referenced ID, traversing parents for context.
826  ///
827  /// Port of `CrossRef::generateTitle`.
828  fn generate_title(&self, doc: &PostDocument, id: &str, shown: &str) -> Option<String> {
829    if let Some(title) = self.title_memo.borrow().get(id).and_then(|by_shown| {
830      by_shown
831        .iter()
832        .find(|(s, _)| s == shown)
833        .map(|(_, t)| t.clone())
834    }) {
835      return title;
836    }
837    let (title, reads_page) = self.generate_title_uncached(doc, id, shown);
838    if !reads_page {
839      let mut memo = self.title_memo.borrow_mut();
840      if memo.len() >= MAX_MEMO_IDS && !memo.contains_key(id) {
841        memo.clear();
842      }
843      let by_shown = memo.entry(id.to_string()).or_default();
844      by_shown.push((shown.to_string(), title.clone()));
845    }
846    title
847  }
848
849  /// [`Self::generate_title`] and whether the title read the page: a value with math (or with refs to fill, whose
850  /// targets may hold math) is read against `doc`.
851  fn generate_title_uncached(
852    &self,
853    doc: &PostDocument,
854    id: &str,
855    shown: &str,
856  ) -> (Option<String>, bool) {
857    let mut reads_page = false;
858    let mut current_id = id.to_string();
859    let mut result = String::new();
860    let mut prefix = String::new();
861    let mut shown_so_far = shown.to_string();
862
863    while let Some(entry) = self.db.lookup(&format!("ID:{}", current_id)) {
864      let mut pieces = Vec::new();
865      let mut is_dup = false;
866
867      // Try title, then typerefnum, then refnum
868      if let Some(title_val) = entry.get_value("title") {
869        if title_val.is_truthy() {
870          is_dup = shown_so_far.contains("title");
871          // The title is stored as a NODE (`Value::Xml`) for sections; derive
872          // its string form tag-aware (Perl `getTextContent`). A plain-string
873          // title (e.g. abstract/bibliography names) is used verbatim.
874          reads_page |= value_reads_page(title_val);
875          pieces.push(self.filled_value_text(doc, &current_id, title_val));
876        }
877      }
878      if pieces.is_empty() {
879        let has_type = entry
880          .get_value("tag:creftypecap")
881          .or_else(|| entry.get_value("tag:creftype"));
882        let has_refnum = entry.get_value("refnum");
883        // (cleveref's `creflabel` is the refnum in its label format: OXIDIZED_DESIGN_DIVERGENCES #845)
884        let shows_refnum = shown_so_far.contains("refnum") || shown_so_far.contains("creflabel");
885        if has_type.is_some() && has_refnum.is_some() {
886          is_dup = shown_so_far.contains("type") && shows_refnum;
887          if let Some(t) = has_type {
888            reads_page |= value_reads_page(t);
889            pieces.push(tag_text(doc, t));
890          }
891          if let Some(r) = has_refnum {
892            reads_page |= value_reads_page(r);
893            pieces.push(tag_text(doc, r));
894          }
895        } else if let Some(tr) = entry.get_value("typerefnum") {
896          is_dup = shown_so_far.contains("type") && shows_refnum;
897          reads_page |= value_reads_page(tr);
898          pieces.push(tag_text(doc, tr));
899        } else if let Some(r) = has_refnum {
900          is_dup = shows_refnum;
901          reads_page |= value_reads_page(r);
902          pieces.push(tag_text(doc, r));
903        }
904      }
905
906      if is_dup {
907        prefix = "In ".to_string();
908        shown_so_far.clear();
909      } else {
910        let title = pieces.join(" ");
911        let title = title.trim();
912        if !title.is_empty() {
913          result.push_str(&prefix);
914          prefix = self.ref_join.clone();
915          result.push_str(title);
916        }
917      }
918
919      // Walk to parent for more context
920      match entry.get_string("parent").map(String::from) {
921        Some(pid) => current_id = pid,
922        None => break,
923      }
924    }
925
926    let title = if result.is_empty() {
927      None
928    } else {
929      Some(result)
930    };
931    (title, reads_page)
932  }
933
934  /// Generate a title for the document itself.
935  ///
936  /// Port of `CrossRef::generateDocumentTitle`.
937  fn generate_document_title(&self, doc: &PostDocument) -> Option<String> {
938    // Try to generate from the document's root ID. Use `get_xml_id` so we
939    // pick up ids stored in the xml namespace (Scan's default placement)
940    // as well as the bare "xml:id" attribute form.
941    if let Some(docid) = doc.get_document_element().as_ref().and_then(get_xml_id) {
942      // Perl `generateDocumentTile` (CrossRef.pm L809) calls
943      // `generateTitle($doc, $docid)` with NO `$shown` arg → `$shown=''`. Passing
944      // "toctitle" here is WRONG: `generate_title`'s dup test is `shown.contains("title")`
945      // (Perl `$shown =~ /title/`), and "toctitle" contains "title", so the page's OWN
946      // (deepest) title is falsely flagged a duplicate and dropped — every split section
947      // page's <title> collapsed to "In <parent>" instead of "<section> ‣ <ancestors>".
948      let title = self.generate_title(doc, &docid, "");
949      if title.as_ref().map(|t| !t.is_empty()).unwrap_or(false) {
950        return title;
951      }
952    }
953    // Fallback: look for a title element in the document
954    if let Some(node) =
955      doc.findnode("//ltx:title | //ltx:toctitle | //ltx:caption | //ltx:toccaption")
956    {
957      let text = get_text_content_node(&node);
958      if !text.is_empty() {
959        return Some(text);
960      }
961    }
962    None
963  }
964
965  /// Generate content for a glossary reference.
966  ///
967  /// Port of `CrossRef::generateGlossaryRefTitle` (CrossRef.pm:906-925): the
968  /// entry's `phrase:<show>` — failing that, `<base>-plural` appends an `s` and
969  /// `<base>-indefinite` prefixes `a`/`an` to `phrase:<base>` — wrapped in an
970  /// `ltx_glossary_<show>` text, its content `prepRefText` (the stored node's
971  /// trimmed children, cloned: markup survives).
972  fn generate_glossary_ref_title(&self, entry_key: &str, show: &str) -> Vec<NodeData> {
973    let Some(entry) = self.db.lookup(entry_key) else {
974      return vec![];
975    };
976    let wrap = |children: Vec<NodeData>| {
977      vec![NodeData::Element {
978        tag: "ltx:text".to_string(),
979        attributes: Some(HashMap::from_iter([(
980          "class".to_string(),
981          format!("ltx_glossary_{show}"),
982        )])),
983        children,
984      }]
985    };
986    if let Some(val) = entry.get_value(&format!("phrase:{show}")) {
987      return wrap(self.entry_text_children(entry_key, val, false));
988    }
989    if let Some(base) = show.strip_suffix("-plural")
990      && let Some(val) = entry.get_value(&format!("phrase:{base}"))
991    {
992      let mut children = self.entry_text_children(entry_key, val, false);
993      children.push(NodeData::Text("s".to_string()));
994      return wrap(children);
995    }
996    if let Some(base) = show.strip_suffix("-indefinite")
997      && let Some(val) = entry.get_value(&format!("phrase:{base}"))
998    {
999      // Perl tests `$phrase->textContent` against `/^[aeiou]/i`.
1000      let article = if val
1001        .as_string()
1002        .starts_with(|c: char| "aeiouAEIOU".contains(c))
1003      {
1004        "an "
1005      } else {
1006        "a "
1007      };
1008      let mut children = vec![NodeData::Text(article.to_string())];
1009      children.extend(self.entry_text_children(entry_key, val, false));
1010      return wrap(children);
1011    }
1012    vec![]
1013  }
1014
1015  /// Copy linked resources (non-idref hrefs) to the destination.
1016  ///
1017  /// Port of `CrossRef::copy_resources`.
1018  fn copy_resources(&self, doc: &PostDocument) {
1019    let refs = doc.findnodes("//ltx:ref[@href and not(@idref) and not(@labelref)]");
1020    for ref_node in &refs {
1021      if let Some(url) = ref_node.get_attribute("href") {
1022        // Only copy relative URLs (no protocol, not absolute)
1023        if !url.contains("://") && !url.starts_with('/') {
1024          // Would copy resource from search path to destination
1025          log::trace!("CrossRef: would copy resource '{}'", url);
1026        }
1027      }
1028    }
1029  }
1030
1031  /// Perl `CrossRef::prepRefText` (CrossRef.pm:791-793), `cloneNodes(trimChildNodes(fillInTitle($value)))`, for the
1032  /// value from the entry `id`: its children with nested refs filled ([`Self::filled_children`]), trimmed. For
1033  /// a `\nameref` its leading `ltx:tag` goes (`generateRef_aux` L774-777, which unbinds it from the stored value
1034  /// itself; the copy loses it here, the stored title keeping its tag for the TOC).
1035  fn entry_text_children(&self, id: &str, val: &Value, is_nameref: bool) -> Vec<NodeData> {
1036    trim_child_data(self.entry_children(id, val, is_nameref))
1037  }
1038
1039  /// [`Self::entry_text_children`] untrimmed. A tag's copy (Scan stores a tag with markup as its copy) keeps its
1040  /// spaces, as a tag stored as text does: a document's multi format's second position `{ and~(#2#1#3)}` with math
1041  /// in its number is " and (P1)" after "Problems (P)" (2609.28438).
1042  fn entry_children(&self, id: &str, val: &Value, is_nameref: bool) -> Vec<NodeData> {
1043    let Value::Xml(node) = val else {
1044      return ref_content_children(val);
1045    };
1046    // (an entry whose own title refs lead back to it stops at the first return, whichever of its keys it shows)
1047    let mut out =
1048      if needs_fill_in(node) && !self.filling.borrow().iter().any(|filling| filling == id) {
1049        self.filling.borrow_mut().push(id.to_string());
1050        let filled = self.filled_children(node);
1051        self.filling.borrow_mut().pop();
1052        filled
1053      } else {
1054        child_nodes_data(node)
1055      };
1056    if is_nameref
1057      && let Some(at) = out
1058        .iter()
1059        .position(|datum| !matches!(datum, NodeData::Text(_)))
1060      && matches!(&out[at], NodeData::XmlNode(first) if name_is(first, "tag"))
1061    {
1062      out.remove(at);
1063    }
1064    out
1065  }
1066
1067  /// Perl `CrossRef::fillInTitle` (CrossRef.pm:882-904) on a copy of a stored value's children: a nested `ltx:ref`
1068  /// still empty becomes the content its target's entry generates for the ref's `show` (else the default), unlinked
1069  /// (`replaceNode($ref, generateRef_aux(...))`); an `ltx:break` becomes a space. Perl edits the stored title in
1070  /// place, once; here each use fills a copy and the ObjectDB stays read-only. A wrapper around a filled ref is
1071  /// rebuilt without its `xml:id`/`fragid`, display copies as in MakeIndex's see-also chunks. A nested
1072  /// `ltx:bibref` is left to `fill_in_bibrefs`, which fills the copy where it lands; a tooltip reads it empty.
1073  fn filled_children(&self, node: &Node) -> Vec<NodeData> {
1074    let mut out = Vec::new();
1075    let mut child = node.get_first_child();
1076    while let Some(c) = child {
1077      match c.get_type() {
1078        Some(NodeType::TextNode) => out.push(NodeData::Text(c.get_content())),
1079        Some(NodeType::ElementNode) => out.extend(self.filled_node(&c)),
1080        _ => {},
1081      }
1082      child = c.get_next_sibling();
1083    }
1084    out
1085  }
1086
1087  /// One element of [`Self::filled_children`].
1088  fn filled_node(&self, node: &Node) -> Vec<NodeData> {
1089    let in_ltx = node
1090      .get_namespace()
1091      .is_some_and(|ns| ns.get_href() == crate::document::LTX_NSURI);
1092    match node.get_name().as_str() {
1093      "ref" if in_ltx && is_unfilled_ref(node) => {
1094        let target = match node.get_attribute("idref") {
1095          Some(id) => Some(id),
1096          None => node.get_attribute("labelref").and_then(|label| {
1097            self
1098              .db
1099              .lookup(&label)
1100              .and_then(|entry| entry.get_string("id").map(String::from))
1101          }),
1102        };
1103        match target.filter(|id| self.db.lookup(&format!("ID:{id}")).is_some()) {
1104          Some(id) => {
1105            let show = node
1106              .get_attribute("show")
1107              .filter(|show| !show.is_empty())
1108              .unwrap_or_else(|| self.ref_show.clone());
1109            // A nested `\nameref` drops its target's number as one in the text does; Perl's `fillInTitle` passes no
1110            // `$is_nameref` and keeps it (KNOWN_PERL_ERRORS #531).
1111            let is_nameref = node
1112              .get_attribute("class")
1113              .is_some_and(|class| class.contains("ltx_refmacro_nameref"));
1114            self.generate_ref_aux(&id, &show, is_nameref)
1115          },
1116          None => vec![NodeData::XmlNode(node.clone())],
1117        }
1118      },
1119      "break" if in_ltx => vec![NodeData::Element {
1120        tag:        "ltx:text".to_string(),
1121        attributes: None,
1122        children:   vec![NodeData::Text(" ".to_string())],
1123      }],
1124      "Math" => vec![NodeData::XmlNode(node.clone())],
1125      name if in_ltx && needs_fill_in(node) => {
1126        // (its `xml:` attributes keep their namespace — `get_properties` names them bare — and a display copy carries
1127        // no `labels`, as `append_clone` drops them)
1128        let xml_ns = latexml_core::common::xml::XML_NS;
1129        let attributes: HashMap<String, String> = node
1130          .get_properties()
1131          .into_iter()
1132          .filter(|(k, _)| k != "fragid" && k != "labels")
1133          .filter_map(|(k, v)| match node.get_attribute_ns(&k, xml_ns) {
1134            Some(_) if k == "id" => None,
1135            Some(_) => Some((format!("xml:{k}"), v)),
1136            None => Some((k, v)),
1137          })
1138          .collect();
1139        vec![NodeData::Element {
1140          tag:        format!("ltx:{name}"),
1141          attributes: Some(attributes),
1142          children:   self.filled_children(node),
1143        }]
1144      },
1145      _ => vec![NodeData::XmlNode(node.clone())],
1146    }
1147  }
1148
1149  /// Perl `getTextContent($doc, fillInTitle($title))` (CrossRef.pm:846): the string form of a value of the entry `id`, nested refs filled, whitespace collapsed as [`value_text`] does.
1150  fn filled_value_text(&self, doc: &PostDocument, id: &str, val: &Value) -> String {
1151    match val {
1152      Value::Xml(node) if needs_fill_in(node) => {
1153        let children = self.entry_text_children(id, val, false);
1154        node_data_text(doc, &children)
1155          .split_whitespace()
1156          .collect::<Vec<_>>()
1157          .join(" ")
1158      },
1159      _ => value_text(doc, val),
1160    }
1161  }
1162
1163  /// Generate reference content for a given ID and show pattern; a `\nameref`'s (`is_nameref`) drops the titles'
1164  /// tags.
1165  ///
1166  /// Port of `CrossRef::generateRef`.
1167  fn generate_ref(
1168    &mut self,
1169    _doc: &PostDocument,
1170    req_id: &str,
1171    req_show: &str,
1172    is_nameref: bool,
1173  ) -> Vec<NodeData> {
1174    if let Some(stuff) = self.ref_memo.borrow().get(req_id).and_then(|by_show| {
1175      by_show
1176        .iter()
1177        .find(|(show, nameref, _)| show == req_show && *nameref == is_nameref)
1178        .map(|(_, _, stuff)| stuff.clone())
1179    }) {
1180      return stuff;
1181    }
1182    match self.generate_ref_uncached(req_id, req_show, is_nameref) {
1183      Some(stuff) => {
1184        let mut memo = self.ref_memo.borrow_mut();
1185        if memo.len() >= MAX_MEMO_IDS && !memo.contains_key(req_id) {
1186          memo.clear();
1187        }
1188        let by_show = memo.entry(req_id.to_string()).or_default();
1189        by_show.push((req_show.to_string(), is_nameref, stuff.clone()));
1190        stuff
1191      },
1192      // (not kept: each use is noted missing)
1193      None => {
1194        self.note_missing("info", "Usable title for ID", req_id);
1195        vec![NodeData::Text(req_id.to_string())]
1196      },
1197    }
1198  }
1199
1200  /// [`Self::generate_ref`]'s content, none where no entry up the chain has a usable one.
1201  fn generate_ref_uncached(
1202    &self,
1203    req_id: &str,
1204    req_show: &str,
1205    is_nameref: bool,
1206  ) -> Option<Vec<NodeData>> {
1207    // A format of the document's (a `|` show's alternative before the last, cleveref_sty.rs `cref_multi`) is the whole
1208    // reference as cleveref prints it: kept as it is when the target has it, with no context sought for a format
1209    // with no letter or digit in it — siamart's `\crefformat{equation}{\textup{#2(#1)#3}}` with `\tag{$\star$}`
1210    // prints "(⋆)", not "(⋆) ‣ section 1" (1905.03839). OXIDIZED_DESIGN_DIVERGENCES #845; guard
1211    // `perfect_kernel_batch78j::cleveref_symbol_format_stands_alone`.
1212    let alternatives = show_alternatives(req_show);
1213    if let Some((_default, formats)) = alternatives.split_last() {
1214      for format in formats {
1215        let stuff = self.generate_ref_aux(req_id, format, is_nameref);
1216        if !stuff.is_empty() {
1217          return Some(stuff);
1218        }
1219      }
1220    }
1221    let show_options = if !req_show.contains("title") {
1222      vec![req_show.to_string(), "title".to_string()]
1223    } else {
1224      vec![req_show.to_string(), "refnum".to_string()]
1225    };
1226
1227    for show in &show_options {
1228      let mut stuff = Vec::new();
1229      let mut id = req_id.to_string();
1230      let mut pending = String::new();
1231      loop {
1232        let entry_exists = self.db.lookup(&format!("ID:{}", id)).is_some();
1233        if !entry_exists {
1234          break;
1235        }
1236        let s = self.generate_ref_aux(&id, show, is_nameref);
1237        if !s.is_empty() {
1238          if !pending.is_empty() {
1239            stuff.push(NodeData::Text(pending.clone()));
1240          }
1241          stuff.extend(s);
1242          if self.check_ref_content(&stuff) {
1243            return Some(stuff);
1244          }
1245          pending = self.ref_join.clone();
1246        }
1247        let parent = self
1248          .db
1249          .lookup(&format!("ID:{}", id))
1250          .and_then(|e| e.get_string("parent").map(String::from));
1251        match parent {
1252          Some(pid) => id = pid,
1253          None => break,
1254        }
1255      }
1256      if !stuff.is_empty() {
1257        return Some(stuff);
1258      }
1259    }
1260    None
1261  }
1262
1263  /// Generate ref content from a single DB entry. A `show` of `|`-separated alternatives (outside `{…}` literals)
1264  /// prints the first the entry has: cleveref's format of the document's for the target's type, else its default
1265  /// (cleveref_sty.rs `cref_multi`; OXIDIZED_DESIGN_DIVERGENCES #845). Rust-only; Perl's shows have none.
1266  fn generate_ref_aux(&self, id: &str, show: &str, is_nameref: bool) -> Vec<NodeData> {
1267    let alternatives = show_alternatives(show);
1268    if alternatives.len() > 1 {
1269      return alternatives
1270        .into_iter()
1271        .map(|alternative| self.generate_ref_aux(id, alternative, is_nameref))
1272        .find(|stuff| !stuff.is_empty())
1273        .unwrap_or_default();
1274    }
1275    let entry = match self.db.lookup(&format!("ID:{}", id)) {
1276      Some(e) => e,
1277      None => return vec![],
1278    };
1279
1280    let mut stuff = Vec::new();
1281    let mut ok = false;
1282    let mut remaining = show.to_string();
1283
1284    while !remaining.is_empty() {
1285      if remaining.starts_with(|c: char| c.is_alphanumeric()) {
1286        let keyword: String = remaining
1287          .chars()
1288          .take_while(|c| c.is_alphanumeric())
1289          .collect();
1290        remaining = remaining[keyword.len()..].to_string();
1291        let key = keyword.to_lowercase();
1292        let class = if key.contains("title") {
1293          "ltx_ref_title"
1294        } else {
1295          "ltx_ref_tag"
1296        };
1297
1298        let mut keys_to_try = vec![key.clone(), format!("tag:{}", key)];
1299        keys_to_try.extend(ref_fallbacks(&key).iter().map(|s| s.to_string()));
1300
1301        for k in &keys_to_try {
1302          if let Some(val) = entry.get_value(k) {
1303            if val.is_truthy() {
1304              ok = true;
1305              // Perl `generateRef_aux` L779: `['ltx:text', {class}, prepRefText]`
1306              // where `prepRefText` = `cloneNodes(trimChildNodes($value))` — a
1307              // DEEP CLONE of the title's child nodes, `<ltx:Math>` included.
1308              // The CrossRef pass runs before the MathML pass, so the cloned
1309              // `<ltx:Math>` is later turned into `<math>` just like the body
1310              // copy (issue #356). A plain-string value keeps the flat-text
1311              // rendering.
1312              stuff.push(NodeData::Element {
1313                tag:        "ltx:text".to_string(),
1314                attributes: Some(HashMap::from_iter([(
1315                  "class".to_string(),
1316                  class.to_string(),
1317                )])),
1318                children:   if k.starts_with("tag:") || k.ends_with("refnum") {
1319                  self.entry_children(id, val, is_nameref)
1320                } else {
1321                  self.entry_text_children(id, val, is_nameref)
1322                },
1323              });
1324              break;
1325            }
1326          }
1327        }
1328      } else if remaining.starts_with('{') {
1329        if let Some(end) = remaining[1..].find('}') {
1330          let literal = &remaining[1..1 + end];
1331          if !literal.is_empty() {
1332            stuff.push(NodeData::Text(literal.to_string()));
1333          }
1334          remaining = remaining[2 + end..].to_string();
1335        } else {
1336          remaining.clear();
1337        }
1338      } else if remaining.starts_with('~') {
1339        remaining = remaining[1..].to_string();
1340        if !stuff.is_empty() {
1341          stuff.push(NodeData::Text("\u{00A0}".to_string()));
1342        }
1343      } else if remaining.starts_with(|c: char| c.is_whitespace()) {
1344        let ws: String = remaining
1345          .chars()
1346          .take_while(|c| c.is_whitespace())
1347          .collect();
1348        remaining = remaining[ws.len()..].to_string();
1349        if !stuff.is_empty() {
1350          stuff.push(NodeData::Text(ws));
1351        }
1352      } else {
1353        let sym: String = remaining
1354          .chars()
1355          .take_while(|c| !c.is_alphanumeric() && *c != '{' && *c != '~')
1356          .collect();
1357        remaining = remaining[sym.len()..].to_string();
1358        stuff.push(NodeData::Text(sym));
1359      }
1360    }
1361
1362    if ok { stuff } else { vec![] }
1363  }
1364
1365  /// Check if ref content is "good enough".
1366  fn check_ref_content(&self, stuff: &[NodeData]) -> bool {
1367    let text = text_content(stuff);
1368    let cleaned = text.replace("in ", "");
1369    cleaned.chars().any(|c| c.is_alphanumeric())
1370  }
1371
1372  // ======================================================================
1373  // Fill-in methods
1374
1375  fn fill_in_relations(&mut self, doc: &mut PostDocument) {
1376    // Same get_xml_id trick as generate_document_title: Scan stores ids
1377    // in the xml namespace by default; without this, sub-docs would skip
1378    // relation filling and never gain the prev/next/up navigation.
1379    let page_id = match doc.get_document_element().as_ref().and_then(get_xml_id) {
1380      Some(id) => id,
1381      None => return,
1382    };
1383
1384    // 1. up / "up up" / "up up up" — walk ancestors that have a title.
1385    let mut current_id = page_id.clone();
1386    let mut rel = "up".to_string();
1387    let mut topmost = current_id.clone();
1388    loop {
1389      let parent_id = self
1390        .db
1391        .lookup(&format!("ID:{}", current_id))
1392        .and_then(|e| e.get_string("parent").map(String::from));
1393      match parent_id {
1394        Some(pid) => {
1395          let has_title = self
1396            .db
1397            .lookup(&format!("ID:{}", pid))
1398            .and_then(|e| e.get_value("title"))
1399            .map(|v| v.is_truthy())
1400            .unwrap_or(false);
1401          if has_title {
1402            doc.add_navigation(&rel, &pid);
1403            rel = format!("{} up", rel);
1404          }
1405          current_id = pid.clone();
1406          topmost = pid;
1407        },
1408        None => break,
1409      }
1410    }
1411
1412    // 2. start — the topmost ancestor (root page), if different from us.
1413    if topmost != page_id {
1414      if let Some(top_pageid) = self
1415        .db
1416        .lookup(&format!("ID:{}", topmost))
1417        .and_then(|e| e.get_string("pageid").map(String::from))
1418      {
1419        doc.add_navigation("start", &top_pageid);
1420      }
1421    }
1422
1423    // 3. prev / next — walk the page tree.
1424    if let Some(prev) = self.find_previous_page_id(&page_id) {
1425      doc.add_navigation("prev", &prev);
1426    }
1427    if let Some(next) = self.find_next_page_id(&page_id) {
1428      doc.add_navigation("next", &next);
1429    }
1430
1431    // 4. Relation-typed links (Perl CrossRef.pm L105-130): the sibling pages of each
1432    // ancestor (walking up), then this page's own child pages, keyed by the page's
1433    // element name. Perl links every one ("this gets way too much. But how to prune?",
1434    // CrossRef.pm:110) — a quadratic set of head links, 66 % of a split book's bytes; we
1435    // keep only the relations something reads (KEPT_RELATIONS, OXIDIZED_DESIGN_DIVERGENCES #1134).
1436    let mut xentry = page_id.clone();
1437    while let Some(parent) = self.get_parent_page_id(&xentry) {
1438      for (rel, sib) in self.related_pages(&parent) {
1439        if sib != page_id {
1440          doc.add_navigation(rel, &sib);
1441        }
1442      }
1443      xentry = parent;
1444    }
1445    for (rel, child) in self.related_pages(&page_id) {
1446      doc.add_navigation(rel, &child);
1447    }
1448  }
1449
1450  /// The child pages of `entry_id` that `fill_in_relations` links, with their relation:
1451  /// primary pages whose element name (Perl `$type =~ s/^(\w+)://`) is in
1452  /// [`KEPT_RELATIONS`], in page order. Memoized on the entry's [`ChildPages`].
1453  fn related_pages(&self, entry_id: &str) -> Vec<(&'static str, String)> {
1454    let pages = self.child_pages(entry_id);
1455    let related = pages.related.get_or_init(|| {
1456      let mut related = Vec::new();
1457      for id in pages.ids.iter() {
1458        if !self.is_primary_page(id) {
1459          continue; // Perl's `sidebar` relation: unread, dropped.
1460        }
1461        let typ = self
1462          .db
1463          .lookup(&format!("ID:{}", id))
1464          .and_then(|e| e.get_string("type").map(String::from));
1465        let name = typ.as_deref().map(|t| t.rsplit(':').next().unwrap_or(t));
1466        if let Some(rel) = name.and_then(|n| KEPT_RELATIONS.iter().find(|k| **k == n)) {
1467          related.push((*rel, id.clone()));
1468        }
1469      }
1470      related
1471    });
1472    related.clone()
1473  }
1474
1475  /// Return whether the given xml:id is registered as a primary page.
1476  /// Port of `$entry->getValue('primary')`.
1477  fn is_primary_page(&self, page_id: &str) -> bool {
1478    self
1479      .db
1480      .lookup(&format!("ID:{}", page_id))
1481      .and_then(|e| e.get_value("primary"))
1482      .map(|v| v.is_truthy())
1483      .unwrap_or(false)
1484  }
1485
1486  /// Resolve `entry_id` to the pageid of the page that *contains* its
1487  /// parent. Port of Perl `CrossRef::getParentPage`.
1488  fn get_parent_page_id(&self, entry_id: &str) -> Option<String> {
1489    let entry = self.db.lookup(&format!("ID:{}", entry_id))?;
1490    let pageid = entry.get_string("pageid")?.to_string();
1491    let page_entry = self.db.lookup(&format!("ID:{}", pageid))?;
1492    let parent_id = page_entry.get_string("parent")?.to_string();
1493    let parent_entry = self.db.lookup(&format!("ID:{}", parent_id))?;
1494    Some(parent_entry.get_string("pageid")?.to_string())
1495  }
1496
1497  /// Memoized `get_child_page_ids`. The ObjectDB is immutable for the whole
1498  /// CrossRef pass, so a given entry's child-page list is stable and shared
1499  /// across every page (see the `child_pages` field). Also records each id's
1500  /// position so the sibling finders skip the Perl pop/shift scan.
1501  fn child_pages(&self, entry_id: &str) -> Rc<ChildPages> {
1502    if let Some(cached) = self.child_pages.borrow().get(entry_id) {
1503      return cached.clone();
1504    }
1505    let ids = self.compute_child_page_ids(entry_id);
1506    let mut index_of = HashMap::default();
1507    // Last occurrence wins, matching the Perl scan that peels from the end.
1508    for (i, id) in ids.iter().enumerate() {
1509      index_of.insert(id.clone(), i);
1510    }
1511    let rc = Rc::new(ChildPages {
1512      ids,
1513      index_of,
1514      related: OnceCell::new(),
1515    });
1516    self
1517      .child_pages
1518      .borrow_mut()
1519      .insert(entry_id.to_string(), rc.clone());
1520    rc
1521  }
1522
1523  /// Recursively collect distinct child page ids under `entry_id`.
1524  /// Port of Perl `CrossRef::getChildPages` (the uncached recursion body;
1525  /// recursion reuses the cache via [`child_pages`](Self::child_pages)).
1526  fn compute_child_page_ids(&self, entry_id: &str) -> Vec<String> {
1527    let entry = match self.db.lookup(&format!("ID:{}", entry_id)) {
1528      Some(e) => e,
1529      None => return Vec::new(),
1530    };
1531    let here_pageid = entry.get_string("pageid").map(String::from);
1532    let children = entry.get_children();
1533    let mut out = Vec::new();
1534    for ch in children {
1535      let ch_entry = match self.db.lookup(&format!("ID:{}", ch)) {
1536        Some(e) => e,
1537        None => continue,
1538      };
1539      let ch_pageid = match ch_entry.get_string("pageid") {
1540        Some(p) => p.to_string(),
1541        None => continue,
1542      };
1543      if here_pageid.as_deref() != Some(&ch_pageid) {
1544        out.push(ch_pageid);
1545      } else {
1546        out.extend(self.child_pages(&ch).ids.iter().cloned());
1547      }
1548    }
1549    out
1550  }
1551
1552  /// Page immediately preceding `page_id` in tree order, restricted to
1553  /// `primary` pages. Port of Perl `CrossRef::findPreviousPage`: previous
1554  /// sibling if any, drilled into rightmost descendant.
1555  fn find_previous_page_id(&self, page_id: &str) -> Option<String> {
1556    let parent_id = self.get_parent_page_id(page_id)?;
1557    let siblings = self.child_pages(&parent_id);
1558    // Our position among the parent's child pages (None = "broken database").
1559    let pos = *siblings.index_of.get(page_id)?;
1560    // Nearest primary sibling strictly before us (Perl: peel following sibs,
1561    // drop self, keep primaries, take the last one). If there is NONE, Perl's
1562    // `$pentry` is still the PARENT page, so the previous page is the parent
1563    // itself (e.g. the first `\section` of a `\chapter` → the chapter page).
1564    // The old `?` returned None here, dropping the `rel="prev"` link entirely.
1565    let mut current = match siblings.ids[..pos]
1566      .iter()
1567      .rev()
1568      .find(|s| self.is_primary_page(s))
1569    {
1570      Some(sib) => sib.clone(),
1571      None => return Some(parent_id),
1572    };
1573    // Drill into the rightmost primary descendant.
1574    loop {
1575      let kids = self.child_pages(&current);
1576      match kids.ids.iter().rev().find(|s| self.is_primary_page(s)) {
1577        Some(deepest) => current = deepest.clone(),
1578        None => break,
1579      }
1580    }
1581    Some(current)
1582  }
1583
1584  /// Page immediately following `page_id` in tree order, restricted to
1585  /// `primary` pages. Port of Perl `CrossRef::findNextPage`: first child,
1586  /// else walk up to find next sibling at progressively higher levels.
1587  fn find_next_page_id(&self, page_id: &str) -> Option<String> {
1588    // First primary child page, if any.
1589    if let Some(first) = self
1590      .child_pages(page_id)
1591      .ids
1592      .iter()
1593      .find(|s| self.is_primary_page(s))
1594    {
1595      return Some(first.clone());
1596    }
1597    let mut current = page_id.to_string();
1598    loop {
1599      let parent = self.get_parent_page_id(&current)?;
1600      let siblings = self.child_pages(&parent);
1601      // Our position among the parent's child pages (None = "broken database").
1602      let pos = *siblings.index_of.get(&current)?;
1603      // First primary sibling strictly after us.
1604      if let Some(first) = siblings.ids[pos + 1..]
1605        .iter()
1606        .find(|s| self.is_primary_page(s))
1607      {
1608        return Some(first.clone());
1609      }
1610      current = parent;
1611    }
1612  }
1613
1614  fn fill_in_tocs(&mut self, doc: &mut PostDocument) {
1615    // Perl Post.pm L946-948: Document::findnodes defaults the XPath
1616    // context to documentElement. oxide's `findnodes(None)` defaults to
1617    // the XML document node, where libxml2's `descendant::` axis evaluates
1618    // differently — `descendant::ltx:TOC` matches zero from the doc node
1619    // even though `//ltx:TOC` matches one. Pin the root explicitly so the
1620    // user's `\tableofcontents` placeholder is reachable.
1621    let tocs = match doc.get_document_element() {
1622      Some(root) => doc.findnodes_at("descendant::ltx:TOC[not(ltx:toclist)]", Some(&root)),
1623      None => Vec::new(),
1624    };
1625    for toc in &tocs {
1626      // Use the unified get_xml_id helper: Scan's `Document` fallback
1627      // assigns xml:id via the xml namespace, which is invisible to a
1628      // bare `get_attribute("xml:id")` lookup but is found by
1629      // `get_attribute_ns("id", XML_NS)` (which get_xml_id tries first).
1630      let mut id = doc
1631        .get_document_element()
1632        .as_ref()
1633        .and_then(get_xml_id)
1634        .unwrap_or_default();
1635      // `scope="global"` retargets the TOC to the root page. Perl
1636      // fill_in_tocs L227-231 resolves this via `getRootPage`, walking up the
1637      // *page* hierarchy (parent → its pageid → …) and taking the root page's
1638      // `pageid`. Default scope (`current` or absent) keeps the current-page id,
1639      // so the inline `\tableofcontents` placeholder stays page-local.
1640      // Any other scope is the xml:id of the unit whose children it lists (LaTeXML.rnc `TOC_attributes`: "otherwise
1641      // an xml:id"; etoc's `\localtableofcontents`, etoc_sty.rs; Perl reads only `global`).
1642      let scope = toc.get_attribute("scope").unwrap_or_default();
1643      let unit = match scope.as_str() {
1644        "global" => {
1645          id = self.get_root_page_id(&id);
1646          None
1647        },
1648        "" | "current" => None,
1649        unit => Some(unit),
1650      };
1651      let show = toc
1652        .get_attribute("show")
1653        .unwrap_or_else(|| self.toc_show.clone());
1654
1655      // Perl CrossRef.pm fill_in_tocs L213-233: the `select` attribute (built
1656      // by `\tableofcontents` from `tocdepth`) restricts which element types
1657      // reach the ToC; absent `select` ⇒ no type restriction. The `lists`
1658      // attribute names which inlist buckets to draw from (default `toc`;
1659      // `lof`/`lot` for the figure/table lists).
1660      let select_attr = toc.get_attribute("select");
1661      let types: Option<HashSet<&str>> = select_attr.as_deref().map(|s| {
1662        s.split('|')
1663          .map(str::trim)
1664          .filter(|t| !t.is_empty())
1665          .collect()
1666      });
1667      let lists_attr = toc.get_attribute("lists");
1668      let lists: HashSet<&str> = match lists_attr.as_deref() {
1669        Some(l) => l.split_whitespace().collect(),
1670        None => HashSet::from_iter(["toc"]),
1671      };
1672
1673      // Perl fill_in_tocs L232-236 dispatches on `format`: `normal` (or absent)
1674      // builds a plain downward TOC; `context` builds the navigation breadcrumb
1675      // (`gentoc_context`), which forces `lists={toc}`. Any other value yields
1676      // no toclist (Perl leaves `@list` empty).
1677      let format = toc.get_attribute("format").unwrap_or_default();
1678      let list = if let Some(unit) = unit {
1679        let children = self
1680          .db
1681          .lookup(&format!("ID:{unit}"))
1682          .map(|e| e.get_children().to_vec());
1683        children
1684          .unwrap_or_default()
1685          .iter()
1686          .flat_map(|child| self.gen_toc(child, &show, types.as_ref(), &lists, None, None))
1687          .collect()
1688      } else if format.is_empty() || format.starts_with("normal") {
1689        self.gen_toc(&id, &show, types.as_ref(), &lists, None, None)
1690      } else if format == "context" {
1691        let toc_lists: HashSet<&str> = HashSet::from_iter(["toc"]);
1692        self.gen_toc_context(&id, &show, types.as_ref(), &toc_lists)
1693      } else {
1694        Vec::new()
1695      };
1696      if !list.is_empty() {
1697        let toclist = NodeData::Element {
1698          tag:        "ltx:toclist".to_string(),
1699          attributes: None,
1700          children:   list,
1701        };
1702        let mut toc_mut = toc.clone();
1703        doc.add_nodes(&mut toc_mut, &[toclist]);
1704      }
1705    }
1706  }
1707
1708  /// Perl CrossRef.pm getRootPage L179-186 + its caller (fill_in_tocs L229):
1709  /// walk up the *page* hierarchy — `parent` → that parent's `pageid` → that
1710  /// page's `parent` → … — to the topmost page, and return its `pageid`. For a
1711  /// single-page document this resolves back to the document id.
1712  fn get_root_page_id(&self, start_id: &str) -> String {
1713    let mut root_id = start_id.to_string();
1714    let mut cursor = start_id.to_string();
1715    while let Some(page_id) = self.parent_page_of(&cursor) {
1716      root_id = page_id.clone();
1717      cursor = page_id;
1718    }
1719    // Caller reads `$root->getValue('pageid')`.
1720    self
1721      .db
1722      .lookup(&format!("ID:{}", root_id))
1723      .and_then(|e| e.get_string("pageid"))
1724      .map(String::from)
1725      .unwrap_or(root_id)
1726  }
1727
1728  /// One `getRootPage` step (Perl L182-184): the `pageid` of this entry's
1729  /// parent, provided that page entry exists. `None` ends the upward walk.
1730  fn parent_page_of(&self, id: &str) -> Option<String> {
1731    // $x = $x->getValue('parent')
1732    let parent_id = self
1733      .db
1734      .lookup(&format!("ID:{}", id))
1735      .and_then(|e| e.get_string("parent"))
1736      .filter(|s| !s.is_empty())?;
1737    // $x = lookup(parent)->getValue('pageid')
1738    let page_id = self
1739      .db
1740      .lookup(&format!("ID:{}", parent_id))
1741      .and_then(|e| e.get_string("pageid"))
1742      .filter(|s| !s.is_empty())?
1743      .to_string();
1744    // $x = lookup(pageid) — the page entry must exist to continue.
1745    self.db.lookup(&format!("ID:{}", page_id)).map(|_| page_id)
1746  }
1747
1748  /// Perl CrossRef.pm gentoc L246-262. Generate the TOC for `id` and its
1749  /// children. `localto` (when `Some`) restricts the downward recursion to
1750  /// entries on that page's `location` — the mechanism a context TOC uses to
1751  /// stop at the current page's boundary. `selfid` marks the matching entry
1752  /// with `ltx_ref_self` ("you are here").
1753  fn gen_toc(
1754    &self,
1755    id: &str,
1756    show: &str,
1757    types: Option<&HashSet<&str>>,
1758    lists: &HashSet<&str>,
1759    localto: Option<&str>,
1760    selfid: Option<&str>,
1761  ) -> Vec<NodeData> {
1762    let entry = match self.db.lookup(&format!("ID:{}", id)) {
1763      Some(e) => e,
1764      None => return vec![],
1765    };
1766
1767    // gentoc L250-252: recurse into children only when unrestricted, or this
1768    // entry lives on the target page.
1769    let recurse = match localto {
1770      None => true,
1771      Some(target) => entry.get_string("location").unwrap_or("") == target,
1772    };
1773    let kids: Vec<NodeData> = if recurse {
1774      entry
1775        .get_children()
1776        .iter()
1777        .flat_map(|child_id| self.gen_toc(child_id, show, types, lists, localto, selfid))
1778        .collect()
1779    } else {
1780      Vec::new()
1781    };
1782
1783    let entry_type = entry.get_string("type").unwrap_or("");
1784    // gentoc L255-256: include this entry iff its type passes the `select`
1785    // filter (no `select` ⇒ unrestricted) AND its `inlist` shares a list with
1786    // the TOC's `lists`. This is what makes `\setcounter{tocdepth}` (#291) take
1787    // effect — the level filter rides on `select`.
1788    let type_ok = types.map(|t| t.contains(entry_type)).unwrap_or(true);
1789    let in_toc = entry
1790      .get_value("inlist")
1791      .map(|v| match v {
1792        Value::Hash(h) => lists.iter().any(|l| h.contains_key(*l)),
1793        _ => false,
1794      })
1795      .unwrap_or(false);
1796
1797    if type_ok && in_toc {
1798      vec![self.gen_tocentry(entry, selfid, show, kids)]
1799    } else {
1800      kids
1801    }
1802  }
1803
1804  /// Perl CrossRef.pm gentocentry L268-283. Build one `ltx:tocentry` for an
1805  /// entry: the `before < show > after` split (`generateRef_simple` for the
1806  /// before/after halves), the `ltx:ref` body, the `ltx_ref_self` marker when
1807  /// this is the `selfid`, and a nested `ltx:toclist` of `children`.
1808  fn gen_tocentry(
1809    &self,
1810    entry: &Entry,
1811    selfid: Option<&str>,
1812    show: &str,
1813    children: Vec<NodeData>,
1814  ) -> NodeData {
1815    let id = entry
1816      .get_string("id")
1817      .or_else(|| entry.get_key().strip_prefix("ID:"))
1818      .unwrap_or("")
1819      .to_string();
1820    let entry_type = entry.get_string("type").unwrap_or("");
1821    let type_name = entry_type.strip_prefix("ltx:").unwrap_or(entry_type);
1822
1823    // gentocentry L272-273: `before < show > after`.
1824    let (mut before, mut after): (Option<&str>, Option<&str>) = (None, None);
1825    let mut show_mid = show;
1826    if let Some((b, rest)) = show_mid.split_once('<') {
1827      before = Some(b);
1828      show_mid = rest;
1829    }
1830    if let Some((mid, a)) = show_mid.split_once('>') {
1831      show_mid = mid;
1832      after = Some(a);
1833    }
1834
1835    let self_class = if selfid == Some(id.as_str()) {
1836      " ltx_ref_self"
1837    } else {
1838      ""
1839    };
1840
1841    let mut kids: Vec<NodeData> = Vec::new();
1842    if let Some(b) = before.filter(|b| !b.is_empty()) {
1843      kids.extend(self.generate_ref_simple(&id, b));
1844    }
1845    kids.push(NodeData::Element {
1846      tag:        "ltx:ref".to_string(),
1847      attributes: Some(HashMap::from_iter([
1848        ("show".to_string(), show_mid.to_string()),
1849        ("idref".to_string(), id.clone()),
1850      ])),
1851      children:   vec![],
1852    });
1853    if let Some(a) = after.filter(|a| !a.is_empty()) {
1854      kids.extend(self.generate_ref_simple(&id, a));
1855    }
1856    if !children.is_empty() {
1857      kids.push(NodeData::Element {
1858        tag: "ltx:toclist".to_string(),
1859        attributes: Some(HashMap::from_iter([(
1860          "class".to_string(),
1861          format!("ltx_toclist_{}", type_name),
1862        )])),
1863        children,
1864      });
1865    }
1866
1867    NodeData::Element {
1868      tag:        "ltx:tocentry".to_string(),
1869      attributes: Some(HashMap::from_iter([(
1870        "class".to_string(),
1871        format!("ltx_tocentry_{}{}", type_name, self_class),
1872      )])),
1873      children:   kids,
1874    }
1875  }
1876
1877  /// Perl CrossRef.pm generateRef_simple L...: look the entry up and, if found,
1878  /// render `req_show` against it. Used only by `gentocentry`'s before/after.
1879  fn generate_ref_simple(&self, req_id: &str, req_show: &str) -> Vec<NodeData> {
1880    if !req_show.is_empty()
1881      && !req_id.is_empty()
1882      && self.db.lookup(&format!("ID:{}", req_id)).is_some()
1883    {
1884      self.generate_ref_aux(req_id, req_show, false)
1885    } else {
1886      Vec::new()
1887    }
1888  }
1889
1890  /// Perl CrossRef.pm gentoc_context L288-311. A "context" TOC: the current
1891  /// page's own contents (downward, page-local), enclosed upward within its
1892  /// ancestors and their sibling sections — the navigation-bar breadcrumb.
1893  fn gen_toc_context(
1894    &self,
1895    id: &str,
1896    show: &str,
1897    types: Option<&HashSet<&str>>,
1898    lists: &HashSet<&str>,
1899  ) -> Vec<NodeData> {
1900    let start = match self.db.lookup(&format!("ID:{}", id)) {
1901      Some(e) => e,
1902      None => return vec![],
1903    };
1904
1905    // Downward TOC covering items WITHIN the current page (localto = this page's
1906    // location; selfid = this id so the current entry is marked ltx_ref_self).
1907    let location = start.get_string("location").unwrap_or("").to_string();
1908    let mut navtoc = self.gen_toc(id, show, types, lists, Some(&location), Some(id));
1909
1910    // Enclose it upward, along with siblings & ancestors. `came_from` is the id
1911    // of the child we ascended through; its slot in each parent's sibling row is
1912    // replaced by the accumulated `navtoc` subtree.
1913    let mut came_from = id.to_string();
1914    let mut parent_id = start.get_string("parent").map(String::from);
1915
1916    while let Some(pid) = parent_id {
1917      let parent = match self.db.lookup(&format!("ID:{}", pid)) {
1918        Some(e) => e,
1919        None => break,
1920      };
1921
1922      // gentoc_context L297-303: the parent's normal-type children become plain
1923      // tocentries, except the one we came from (spliced with `navtoc`).
1924      let mut row: Vec<NodeData> = Vec::new();
1925      for child_id in parent.get_children() {
1926        let child = match self.db.lookup(&format!("ID:{}", child_id)) {
1927          Some(e) => e,
1928          None => continue,
1929        };
1930        if !NORMAL_TOC_TYPES.contains(&child.get_string("type").unwrap_or("")) {
1931          continue;
1932        }
1933        let child_id_val = child.get_string("id").unwrap_or(&child_id);
1934        if child_id_val == came_from {
1935          row.append(&mut navtoc);
1936        } else {
1937          row.push(self.gen_tocentry(child, None, show, Vec::new()));
1938        }
1939      }
1940      navtoc = row;
1941
1942      // gentoc_context L304-306: wrap in the parent's own tocentry, but only if
1943      // the parent passes the type filter AND is itself nested (never wrap the
1944      // top-level document).
1945      let parent_type = parent.get_string("type").unwrap_or("");
1946      let parent_ok = types.map(|t| t.contains(parent_type)).unwrap_or(true);
1947      let parent_has_parent = parent
1948        .get_string("parent")
1949        .map(|s| !s.is_empty())
1950        .unwrap_or(false);
1951      if parent_ok && parent_has_parent {
1952        navtoc = vec![self.gen_tocentry(parent, None, show, navtoc)];
1953      }
1954
1955      came_from = pid;
1956      parent_id = parent.get_string("parent").map(String::from);
1957    }
1958
1959    navtoc
1960  }
1961
1962  fn fill_in_frags(&self, doc: &PostDocument) {
1963    // Perl (CrossRef.pm L312-324) walks the page's own `//@xml:id` nodes and
1964    // sets `fragid` on any that have a DB entry. Iterating the ObjectDB
1965    // instead (one lookup per DB key) wins ONLY when a single page has far
1966    // more id-nodes than the DB has entries (math-heavy single documents:
1967    // ~60K XM* ids vs ~1K DB entries). On a *split* document the DB holds
1968    // every page's entries (tens of thousands) while each page has a handful
1969    // of id-nodes, so that inverted loop is O(db_keys) per page = O(n²)
1970    // overall. Pick whichever loop is bounded by the smaller set — both
1971    // assign fragids to exactly the same nodes, so the output is identical.
1972    if doc.idcache_len() <= self.db.len() {
1973      // Perl semantics: iterate the page's id-nodes (bounded by page size).
1974      for (id, node) in doc.idcache_iter() {
1975        if let Some(entry) = self.db.lookup(&format!("ID:{}", id)) {
1976          if let Some(fragid) = entry.get_string("fragid") {
1977            let mut n = node.clone();
1978            n.set_attribute("fragid", fragid).ok();
1979          }
1980        }
1981      }
1982    } else {
1983      // Inverted loop: fewer DB entries than page id-nodes. `find_node_by_id`
1984      // restricts to this page's nodes, so only page-local fragids are set.
1985      for key in self.db.keys_iter() {
1986        let id = match key.strip_prefix("ID:") {
1987          Some(rest) => rest,
1988          None => continue,
1989        };
1990        let entry = match self.db.lookup(key) {
1991          Some(e) => e,
1992          None => continue,
1993        };
1994        let fragid = match entry.get_string("fragid") {
1995          Some(f) => f,
1996          None => continue,
1997        };
1998        if let Some(node) = doc.find_node_by_id(id) {
1999          let mut n = node.clone();
2000          n.set_attribute("fragid", fragid).ok();
2001        }
2002      }
2003    }
2004  }
2005
2006  fn fill_in_refs(&mut self, doc: &mut PostDocument) {
2007    let mut refs = doc.findnodes("//*[@idref]");
2008    refs.extend(doc.findnodes("//*[@labelref]"));
2009    for ref_node in &refs {
2010      let tag = doc.get_qname(ref_node).unwrap_or_default();
2011      // (a note's `idref` names the first copy of the note it repeats, OXIDIZED_DESIGN_DIVERGENCES #1059: a copy, no
2012      // reference to fill)
2013      if tag == "ltx:XMRef" || tag == "ltx:note" {
2014        continue;
2015      }
2016
2017      let mut ref_mut = ref_node.clone();
2018      let mut id = ref_node.get_attribute("idref");
2019      let show = ref_node
2020        .get_attribute("show")
2021        .unwrap_or_else(|| self.ref_show.clone());
2022
2023      if id.is_none() {
2024        if let Some(label) = ref_node.get_attribute("labelref") {
2025          if let Some(entry) = self.db.lookup(&label) {
2026            if let Some(resolved_id) = entry.get_string("id") {
2027              ref_mut.set_attribute("idref", resolved_id).ok();
2028              id = Some(resolved_id.to_string());
2029            }
2030          }
2031          // A reference printing the text xr imported for another document's label (`ltx_ref_external`, sect11.rs
2032          // `external_ref_properties`) is not missing; where this document holds the label after all, the text and the
2033          // class go and the reference is filled from the target here, as LaTeX's own `.aux` redefines the `\r@<label>`
2034          // xr made in the preamble.
2035          let classes = ref_node.get_attribute("class").unwrap_or_default();
2036          let external = classes
2037            .split_whitespace()
2038            .any(|class| class == "ltx_ref_external");
2039          if id.is_none() && !external {
2040            self.note_missing("warn", "Target for Label", &label);
2041            PostDocument::add_class(&mut ref_mut, "ltx_missing_label");
2042            // An empty reference shows its label key, `broken` (Perl CrossRef.pm:346-348); text "0" is not empty
2043            // (KNOWN_PERL_ERRORS #1360).
2044            if ref_mut.get_content().is_empty() {
2045              doc.add_nodes(&mut ref_mut, &[NodeData::Text(label.clone())]);
2046              ref_mut.set_attribute("broken", "1").ok();
2047            }
2048          } else if id.is_some() && external {
2049            let kept: Vec<&str> = classes
2050              .split_whitespace()
2051              .filter(|class| *class != "ltx_ref_external")
2052              .collect();
2053            if kept.is_empty() {
2054              ref_mut.remove_attribute("class").ok();
2055            } else {
2056              ref_mut.set_attribute("class", &kept.join(" ")).ok();
2057            }
2058            ref_mut.remove_attribute("href").ok();
2059            let children: Vec<Node> = ref_mut.get_child_nodes();
2060            doc.remove_nodes(&children);
2061          }
2062        }
2063      }
2064
2065      if let Some(ref id_str) = id {
2066        if !ref_mut.has_attribute("href") {
2067          if let Some(url) = self.generate_url(doc, id_str) {
2068            ref_mut.set_attribute("href", &url).ok();
2069          }
2070        }
2071        if !ref_mut.has_attribute("title") {
2072          if let Some(titlestring) = self.generate_title(doc, id_str, &show) {
2073            ref_mut.set_attribute("title", &titlestring).ok();
2074          }
2075          // Perl CrossRef.pm L358-361: a ref carrying a `rel` (a navigation ref)
2076          // ALSO gets a `fulltitle` — `generateTitle($doc, $id)` with an EMPTY
2077          // `show`, i.e. the full contextual breadcrumb with NO "In <context>"
2078          // dup-collapse (that collapse only fires for `show=~/title/`). The XSLT
2079          // `head-links` template prefers `@fulltitle` over `@title` for the head
2080          // `<link rel=… title=…>` entries, so without this split pages emitted
2081          // empty (or "In X") nav-link titles.
2082          if let Some(rel) = ref_mut.get_attribute("rel") {
2083            if !rel.is_empty() {
2084              if let Some(fulltitle) = self.generate_title(doc, id_str, "") {
2085                ref_mut.set_attribute("fulltitle", &fulltitle).ok();
2086              }
2087            }
2088          }
2089        }
2090        if ref_mut.get_first_child().is_none() && tag != "ltx:graphics" && tag != "ltx:picture" {
2091          // Perl CrossRef.pm:364
2092          let is_nameref = ref_node
2093            .get_attribute("class")
2094            .is_some_and(|class| class.contains("ltx_refmacro_nameref"));
2095          let content = self.generate_ref(doc, id_str, &show, is_nameref);
2096          doc.add_nodes(&mut ref_mut, &content);
2097        }
2098      }
2099    }
2100  }
2101
2102  /// The conjunctions between the references of a `\cref` list whose document set a multi-reference format
2103  /// (cleveref_sty.rs `\lx@cref@conjunction`): dropped before a reference that printed the document's format, which
2104  /// holds its own (cleveref.sty:1514-1519), and unwrapped elsewhere. OXIDIZED_DESIGN_DIVERGENCES #845.
2105  fn settle_cref_conjunctions(&mut self, doc: &mut PostDocument) {
2106    for conjunction in
2107      doc.findnodes("//ltx:text[contains(concat(' ', @class, ' '), ' ltx_cref_conjunction ')]")
2108    {
2109      let mut next = conjunction.get_next_sibling();
2110      while let Some(node) = next.as_ref().filter(|node| {
2111        node.get_type() == Some(NodeType::TextNode) && node.get_content().trim().is_empty()
2112      }) {
2113        next = node.get_next_sibling();
2114      }
2115      let formatted = next
2116        .filter(|node| name_is(node, "ref"))
2117        .and_then(|node| Some((node.get_attribute("idref")?, node.get_attribute("show")?)))
2118        .is_some_and(|(id, show)| {
2119          let alternatives = show_alternatives(&show);
2120          alternatives.len() > 1
2121            && !self
2122              .generate_ref_aux(&id, alternatives[0], false)
2123              .is_empty()
2124        });
2125      if formatted {
2126        doc.remove_nodes(&[conjunction]);
2127      } else {
2128        doc.unwrap_node(&conjunction);
2129      }
2130    }
2131  }
2132
2133  fn fill_in_glossaryrefs(&mut self, doc: &mut PostDocument) {
2134    // Port of Perl CrossRef.pm:454-482 fill_in_glossaryrefs: resolve each
2135    // `<ltx:glossaryref key=… inlist=… show=…>` against the GLOSSARY:list:key
2136    // entry registered by Scan (+ MakeIndex), set `idref` (a later fill_in_refs
2137    // pass turns it into `href`) and the `title` tooltip, and fill an EMPTY ref
2138    // with the entry's `show` phrase (acronym.sty's `\ac`/`\acs`/`\acl` emit
2139    // empty refs: without this they rendered as their key, "NN (NN)").
2140    for ref_node in &doc.findnodes("descendant::ltx:glossaryref") {
2141      let mut ref_mut = ref_node.clone();
2142      let key = ref_node.get_attribute("key").unwrap_or_default();
2143      let list = ref_node.get_attribute("inlist").unwrap_or_default();
2144      let show = ref_node
2145        .get_attribute("show")
2146        .filter(|s| !s.is_empty())
2147        .unwrap_or_else(|| "name".to_string());
2148      // `show="none"` is a location-only reference — glossaries' `\glsadd`
2149      // (glossaries_sty.rs), which lists its entry and prints no text: there
2150      // is nothing to fill and nothing missing. Rust-only; Perl emits none.
2151      if show == "none" {
2152        continue;
2153      }
2154      let is_empty = |n: &Node| n.get_content().is_empty() && n.get_first_element_child().is_none();
2155
2156      let gkey = format!("GLOSSARY:{}:{}", list, key);
2157      let found = self.db.lookup(&gkey).map(|entry| {
2158        // Perl L464-466: the tooltip is `phrase:definition`'s text (acronym's
2159        // role); glossaries and nomencl call it `phrase:description`, which the
2160        // Rust port has always used, so it stands as the fallback. The text is
2161        // `value_text`'s whitespace-collapsed, math-aware form (issue #761),
2162        // where Perl copies the raw `textContent`.
2163        let title = entry
2164          .get_value("phrase:definition")
2165          .or_else(|| entry.get_value("phrase:description"))
2166          .map(|val| value_text(doc, val))
2167          .filter(|t| !t.is_empty());
2168        (title, entry.get_string("id").map(str::to_string))
2169      });
2170      if let Some((title, id)) = found {
2171        if !ref_mut.has_attribute("title")
2172          && let Some(title) = title
2173        {
2174          ref_mut.set_attribute("title", &title).ok();
2175        }
2176        if let Some(id) = id {
2177          ref_mut.set_attribute("idref", &id).ok();
2178        }
2179        if is_empty(&ref_mut) {
2180          let stuff = self.generate_glossary_ref_title(&gkey, &show);
2181          if stuff.is_empty() {
2182            self.note_missing("warn", &format!("Glossary contents ({show}) for key"), &key);
2183            doc.add_nodes(&mut ref_mut, &[NodeData::Text(key.clone())]);
2184            PostDocument::add_class(&mut ref_mut, "ltx_missing");
2185          } else {
2186            doc.add_nodes(&mut ref_mut, &stuff);
2187          }
2188        }
2189      } else {
2190        self.note_missing("warn", "Glossary Entry for key", &key);
2191      }
2192
2193      if is_empty(&ref_mut) {
2194        doc.add_nodes(&mut ref_mut, &[NodeData::Text(key.clone())]);
2195        PostDocument::add_class(&mut ref_mut, "ltx_missing");
2196      }
2197    }
2198  }
2199
2200  /// Resolve the RDFa subject/object references — `aboutidref`/`aboutlabelref`
2201  /// into `about`, and `resourceidref`/`resourcelabelref` into `resource`.
2202  ///
2203  /// Port of `CrossRef.pm::fill_in_RDFa_refs` (L372-398), and runs in Perl's
2204  /// position: after `fill_in_refs`, before `fill_in_bibrefs`.
2205  ///
2206  /// `lxRDFa.sty` deliberately records an intra-document RDFa subject as an
2207  /// `…idref`/`…labelref` pair rather than a URL, because the URL is not knowable
2208  /// until the document has been split and paginated — see the
2209  /// `LaTeXML-common.rnc` L301 note, "it will be converted to `aboutidref` and
2210  /// `about` during post-processing". Without this pass that conversion never
2211  /// happened, so `\lxRDFa{about=#thm1}` produced an `aboutidref` that no
2212  /// consumer reads and **no `about` at all** — the RDFa triple lost its subject.
2213  /// Visible on math once `outer_wrapper` began copying `about` onto `<m:math>`:
2214  /// Perl emits `about="#thm1"` there and Rust emitted nothing.
2215  ///
2216  /// An id that the ObjectDB knows becomes a real (possibly cross-page) URL via
2217  /// `generate_url`; an id it does not know still becomes a bare `#id` fragment,
2218  /// because — as Perl's comment puts it — "RDF 'id' need not be real, valid,
2219  /// ids!!!": an author may name a subject that is not a document node at all.
2220  ///
2221  /// Perl also re-runs `set_RDFa_prefixes` at the end. Not ported, and it cannot
2222  /// matter here: this pass only ever writes `about`/`resource` values that are
2223  /// absolute URLs or `#id` fragments, never prefixed CURIEs, so there is no new
2224  /// prefix to declare. (Prefix management itself already happens core-side, in
2225  /// `latexml_core::document::set_rdfa_prefixes`, as it does in Perl's
2226  /// `Core/Document.pm:366`.)
2227  fn fill_in_rdfa_refs(&mut self, doc: &mut PostDocument) {
2228    for key in ["about", "resource"] {
2229      // One query with `or`, as Perl has it — two queries concatenated would
2230      // visit a node carrying BOTH attributes twice and in the wrong order.
2231      let refs = doc.findnodes(&format!("//*[@{key}idref or @{key}labelref]"));
2232      for ref_node in &refs {
2233        let mut ref_mut = ref_node.clone();
2234        let idref_attr = format!("{key}idref");
2235        // Perl's `if (!$id)` and `if ($id)` are truth tests, so an empty
2236        // `aboutidref=""` counts as absent rather than resolving to `about="#"`.
2237        let mut id = ref_node
2238          .get_attribute(&idref_attr)
2239          .filter(|v| !v.is_empty());
2240
2241        // A label reference resolves through the ObjectDB to an id, which is
2242        // written back so the `if let Some(id)` below treats both spellings
2243        // alike (Perl L379-387).
2244        if id.is_none()
2245          && let Some(label) = ref_node.get_attribute(&format!("{key}labelref"))
2246        {
2247          if let Some(entry) = self.db.lookup(&label)
2248            && let Some(resolved) = entry.get_string("id")
2249          {
2250            ref_mut.set_attribute(&idref_attr, resolved).ok();
2251            id = Some(resolved.to_string());
2252          }
2253          if id.is_none() {
2254            self.note_missing("warn", &format!("Target for {key} Label"), &label);
2255          }
2256        }
2257
2258        // Never overwrite an `about`/`resource` the author gave outright.
2259        if let Some(ref id_str) = id
2260          && ref_mut.get_attribute(key).is_none()
2261        {
2262          let value = if self.db.lookup(&format!("ID:{id_str}")).is_some() {
2263            self.generate_url(doc, id_str)
2264          } else {
2265            Some(format!("#{id_str}"))
2266          };
2267          if let Some(value) = value {
2268            ref_mut.set_attribute(key, &value).ok();
2269          }
2270        }
2271      }
2272    }
2273  }
2274
2275  /// Port of Perl `CrossRef::fill_in_bibrefs` (`CrossRef.pm` L486-493): every
2276  /// `<ltx:bibref>` is replaced by the citation
2277  /// [`make_bibcite`](Self::make_bibcite) builds for it — by nothing, when that
2278  /// is empty. An `<ltx:cite>` whose every bibref (at any depth) shows only numbers or labels
2279  /// gets the class `ltx_cite_numeric` (issue #857), which Perl drops with the bibref's `show`.
2280  /// A key-less citation keeps its notes and loses only its bare delimiters (OXIDIZED_DESIGN_DIVERGENCES #1216).
2281  fn fill_in_bibrefs(&mut self, doc: &mut PostDocument) {
2282    // A `FullEntry` copy of a bibliography entry brings the entry's own bibrefs (a crossref'd parent, a `\cite` in a
2283    // note), copied before they were filled: fill again until none is left. Bounded, for an entry that copies itself.
2284    for _ in 0..3 {
2285      let bibrefs = doc.findnodes("//ltx:bibref");
2286      if bibrefs.is_empty() {
2287        return;
2288      }
2289      let mut cites: HashMap<usize, (Node, bool)> = HashMap::default();
2290      let mut keyless_cites: Vec<(Node, [String; 2])> = Vec::new();
2291      for bibref in &bibrefs {
2292        let keyless = bibref
2293          .get_attribute("bibrefs")
2294          .unwrap_or_default()
2295          .split(',')
2296          .all(str::is_empty);
2297        let separators = bibref_separators(bibref);
2298        let (cite, numeric) = self.make_bibcite(doc, bibref);
2299        // The nearest `ltx:cite` ancestor: natbib `[super]` sets the bibref in a `<sup>` inside it.
2300        let mut ancestor = bibref.get_parent();
2301        while let Some(node) = ancestor.as_ref()
2302          && doc.get_qname(node).as_deref() != Some("ltx:cite")
2303        {
2304          ancestor = node.get_parent();
2305        }
2306        if let Some(parent) = ancestor {
2307          if keyless {
2308            keyless_cites.push((parent.clone(), separators));
2309          }
2310          cites
2311            .entry(parent.to_hashable())
2312            .or_insert((parent, true))
2313            .1 &= numeric;
2314        }
2315        doc.replace_node(bibref, &cite);
2316      }
2317      for (mut parent, _) in cites.into_values().filter(|(_, numeric)| *numeric) {
2318        PostDocument::add_class(&mut parent, "ltx_cite_numeric");
2319      }
2320      // A key-less citation left with only its delimiters (`\citep{}`'s "()") is emptied, so the stylesheet drops it.
2321      for (cite, separators) in keyless_cites {
2322        if !carries_a_note(&child_nodes_data(&cite), &separators) {
2323          for mut text in cite.get_child_nodes() {
2324            text.unlink_node();
2325          }
2326        }
2327      }
2328    }
2329    let left = doc.findnodes("//ltx:bibref").len();
2330    if left > 0 {
2331      Warn!(
2332        "unexpected",
2333        "bibref",
2334        "{left} citation(s) inside copied bibliography entries left unfilled (entries that print each other whole)"
2335      );
2336    }
2337  }
2338
2339  /// Port of Perl `CrossRef::make_bibcite` (`CrossRef.pm` L495-644): the links
2340  /// to a bibref's keys, each labelled by the bibref's `show` pattern filled
2341  /// with that entry's bibliography data (see [`bibcite_show_walk`]). Every link
2342  /// carries the entry's title as its `title` (L530-539, L555-557): the
2343  /// tooltip naming the work behind a bare `[1]`. The flag says the citation
2344  /// shows only numbers or labels (`[1]`, `[Kho00]`, `[1, Section 7]`).
2345  fn make_bibcite(&mut self, doc: &PostDocument, bibref: &Node) -> (Vec<NodeData>, bool) {
2346    let keys_str = bibref.get_attribute("bibrefs").unwrap_or_default();
2347    let keys: Vec<&str> = keys_str.split(',').filter(|k| !k.is_empty()).collect();
2348    let preformatted = child_nodes_data(bibref);
2349    let mut show = bibref
2350      .get_attribute("show")
2351      .filter(|s| !s.is_empty())
2352      .unwrap_or_else(|| "refnum".to_string());
2353    if show == "none" && preformatted.is_empty() {
2354      show = "refnum".to_string();
2355    }
2356    // Perl CrossRef.pm:507-508: `\nocite`'s bibref (`show='nothing'`,
2357    // latex_constructs.pool.ltxml:4214) only marks its keys for the
2358    // bibliography stage; `make_bibcite` returns nothing for it, so the node
2359    // is replaced by nothing. Filling it in printed the keys — for
2360    // `\nocite{*}` a visible `*` as a missing citation plus its warning.
2361    if show == "nothing" {
2362      return (Vec::new(), false);
2363    }
2364    let [sep, yysep] = bibref_separators(bibref);
2365    // The `<ltx:bibrefphrase>`s that `phraseN` selects.
2366    let phrases = crate::document::element_children(bibref);
2367    // No key (`\citet[see][p.~2]{}`, 2405.17989): natbib's loop over the keys prints nothing, the notes stay
2368    // (natbib.sty \NAT@citex). Keep the phrases, in the show's order, when they carry a note; Perl's loop drops them.
2369    if keys.is_empty() {
2370      return (keyless_phrases(&show, &phrases, &[sep, yysep]), false);
2371    }
2372    // The lists to search, most-specific first. Perl CrossRef.pm L515 reads
2373    // `inlist || 'bibliography'` — an *exclusive* choice, which strands every
2374    // citation of a document that loads `bibunits`/`chapterbib` but keeps a
2375    // single main `\bibliography`: Perl's `\cite` stamps CITE_UNIT=bu0 onto the
2376    // bibref, while the bibitems register under the default `bibliography`
2377    // list, so the unit-only lookup never matches (witness 2303.06077: 93
2378    // bibitems, 93 dangling keys, 0 links). Ours stamps only inside a unit
2379    // (KNOWN_PERL_ERRORS #1223); a unit's cite with no unit bibliography
2380    // still needs this fallback.
2381    //
2382    // Perl's own Scan.pm L379-380 spells the intended chain — unit lists
2383    // PLUS the main one ("Citation specifies main 'bibliography', as well as
2384    // any specific others (eg. per chapter)") — and registers the reference
2385    // under both. We follow Scan's convention here so the two agree; the unit
2386    // list still wins, since the search breaks on the first list that yields
2387    // an id. OXIDIZED_DESIGN #59, KNOWN_PERL_ERRORS #50.
2388    let inlist = bibref.get_attribute("inlist").unwrap_or_default();
2389    let mut lists: Vec<&str> = inlist.split_whitespace().collect();
2390    if !lists.contains(&"bibliography") {
2391      lists.push("bibliography");
2392    }
2393    // Each key's bibitem id: from the first list that has it.
2394    let ids: Vec<Option<String>> = keys
2395      .iter()
2396      .map(|key| {
2397        lists.iter().find_map(|list| {
2398          self
2399            .db
2400            .lookup(&format!("BIBLABEL:{}:{}", list, key))
2401            .and_then(|be| be.get_string("id"))
2402            .map(String::from)
2403        })
2404      })
2405      .collect();
2406    // \NAT@force@numbers (natbib): a numeric `.bbl` — plain `\bibitem{key}`
2407    // with no `[author(year)]` label — forces numbers mode globally, so every
2408    // `\cite` prints the bracketed number `[N]`/`[N, M]` even when a numeric
2409    // `\bibliographystyle{unsrt}` sits AFTER the cites (witness arXiv:2308.06262
2410    // / html_feedback#62). Single-pass LaTeXML froze this bibref's author-year
2411    // `show`; Perl `CrossRef.pm:542` keeps it because its `|| $keytag` guard is
2412    // always satisfied, so both engines render the raw key. When natbib's frozen
2413    // show (its capitalized `Authors`/`Year` keywords) wants author-year yet
2414    // EVERY cited entry is numeric-only (has a number, no real author/year),
2415    // collapse to natbib's numeric form. SURPASS-PERL: OXIDIZED_DESIGN #123,
2416    // KNOWN_PERL_ERRORS #89.
2417    let show_wants_ay = show.contains("Author") || show.contains("Year");
2418    let force_numeric = show_wants_ay
2419      && !ids.is_empty()
2420      && ids.iter().all(|id| {
2421        let Some(id) = id else {
2422          return false;
2423        };
2424        match self.db.lookup(&format!("ID:{}", id)) {
2425          Some(e) => {
2426            let nonempty = |k: &str| {
2427              e.get_value(k)
2428                .is_some_and(|v| !v.to_string().trim().is_empty())
2429            };
2430            !nonempty("authors")
2431              && !nonempty("fullauthors")
2432              && !nonempty("year")
2433              && (nonempty("number") || nonempty("refnum"))
2434          },
2435          None => false,
2436        }
2437      });
2438    // Do the frozen author-year delimiters sit INSIDE the bibref (a Phrase
2439    // after Year — `\cite`/`\citet` carry their own `( )`) or as sibling text
2440    // (`\citep`, whose macro adds the parens outside the bibref)? Only bracket
2441    // our numeric group in the former case, else `\citep`'s parens double up.
2442    let internal_delims = show
2443      .find("Year")
2444      .is_some_and(|yp| show[yp + "Year".len()..].contains("Phrase"));
2445
2446    let wants_fullentry = show.to_ascii_lowercase().contains("fullentry");
2447    // Collect all the data from the bibliography (L516-562).
2448    static SUFFIXED_YEAR: LazyLock<Regex> =
2449      LazyLock::new(|| Regex::new(r"^(\d\d\d\d)(\w)$").unwrap());
2450    let mut data: Vec<BibciteDatum> = Vec::new();
2451    for (key, id) in keys.iter().zip(ids) {
2452      let found = id.and_then(|id| {
2453        let entry = self.db.lookup(&format!("ID:{}", id))?;
2454        let val = |k: &str| entry.get_value(k).filter(|v| !matches!(v, Value::Null));
2455        let (authors, fauthors, keytag) = (val("authors"), val("fullauthors"), val("keytag"));
2456        let (year, typetag, title) = (val("year"), val("typetag"), val("title"));
2457        let titlestring = title
2458          .map(|t| {
2459            t.to_string()
2460              .split_whitespace()
2461              .collect::<Vec<_>>()
2462              .join(" ")
2463          })
2464          .filter(|s| !s.is_empty());
2465        let (rawyear, suffix) = year
2466          .and_then(|y| {
2467            let text = y.to_string();
2468            SUFFIXED_YEAR
2469              .captures(&text)
2470              .map(|c| (Some(c[1].to_string()), Some(c[2].to_string())))
2471          })
2472          .unwrap_or_default();
2473        // Disable the author-year format (L542) for an entry with nothing to
2474        // name it by. Perl's `$show` persists: the whole citation turns refnum.
2475        // A textual numeric citation (`Authors Phrase1NumberPhrase2`: biblatex's
2476        // numeric `\textcite`, natbib's numbers-mode `\citet`) instead keeps, for
2477        // that entry alone, its phrases around the number, as its style brackets
2478        // the number whatever the name: Perl's bare "2" for biblatex's "No Author
2479        // Misc [2]" (numeric.cbx:23-41, the labeltitle before the bracket) and
2480        // "2, 1" for natbib's "Smith [2], ano [1]" (plainnat's key-prefix label)
2481        // are "[2]" and "Smith [2], [1]" (OXIDIZED_DESIGN_DIVERGENCES #786).
2482        // Guards `perfect_kernel_batch78a::biblatex_numeric_textcite_without_author_keeps_its_brackets`,
2483        // `bibref_show::natbib_numbers_citet_merges_same_authors`.
2484        let nameless = !(show == "none"
2485          || show.eq_ignore_ascii_case("fullentry")
2486          || authors.is_some()
2487          || fauthors.is_some()
2488          || keytag.is_some());
2489        if nameless && nameless_numeric_show(&show).is_none() {
2490          show = "refnum".to_string();
2491        }
2492        let mut attr = HashMap::default();
2493        attr.insert("idref".to_string(), id.clone());
2494        if let Some(title) = titlestring {
2495          attr.insert("title".to_string(), title);
2496        }
2497        // MakeBibliography's copy of the bibitem (it outlives a split page), else a `\bibitem`'s own node.
2498        let fullentry = if wants_fullentry {
2499          let dropped_year = val("droppedyear").map(Value::to_string);
2500          match val("fullentry") {
2501            Some(Value::Xml(bibitem)) => full_entry(bibitem, dropped_year.as_deref()),
2502            _ => doc
2503              .find_node_by_id(&id)
2504              .map(|bibitem| full_entry(bibitem, dropped_year.as_deref()))
2505              .unwrap_or_default(),
2506          }
2507        } else {
2508          Vec::new()
2509        };
2510        Some((id, BibciteDatum {
2511          key: key.to_string(),
2512          authors: trim_child_nodes(authors.or(fauthors).or(keytag)),
2513          fullauthors: trim_child_nodes(fauthors.or(authors).or(keytag)),
2514          authortext: authors
2515            .or(fauthors)
2516            .map(Value::to_string)
2517            .unwrap_or_default(),
2518          year: trim_child_nodes(year.or(typetag)),
2519          rawyear,
2520          suffix,
2521          number: trim_child_nodes(val("number")),
2522          refnum: trim_child_nodes(val("refnum")),
2523          title: trim_child_nodes(title.or(keytag)),
2524          fullentry,
2525          attr,
2526          missing: false,
2527          nameless,
2528        }))
2529      });
2530      match found {
2531        Some((id, mut datum)) => {
2532          if let Some(url) = self.generate_url(doc, &id) {
2533            datum.attr.insert("href".to_string(), url);
2534          }
2535          data.push(datum);
2536        },
2537        None => {
2538          self.note_missing("warn", "Entry for citation", key);
2539          data.push(BibciteDatum {
2540            key:         key.to_string(),
2541            authors:     Vec::new(),
2542            fullauthors: Vec::new(),
2543            authortext:  String::new(),
2544            year:        Vec::new(),
2545            rawyear:     None,
2546            suffix:      None,
2547            number:      Vec::new(),
2548            refnum:      vec![NodeData::Text(key.to_string())],
2549            title:       vec![NodeData::Text(key.to_string())],
2550            fullentry:   vec![NodeData::Text(key.to_string())],
2551            attr:        HashMap::from_iter([
2552              ("idref".to_string(), key.to_string()),
2553              ("title".to_string(), key.to_string()),
2554              ("class".to_string(), "ltx_missing_citation".to_string()),
2555            ]),
2556            missing:     true,
2557            nameless:    false,
2558          });
2559        },
2560      }
2561    }
2562
2563    // The package's ordering (`ltx_cite_sort`/`ltx_cite_compress` on the bibref, sect11.rs `cite_order_class`): the
2564    // entries by number, those without one after them in their order (natbib.sty:1185-1200 `\NAT@sort@cites@`, its
2565    // `\NAT@nonsort@list`); a bare-number citation (`\citep`, `\cite`, a superscript one: natbib.sty:401 compresses
2566    // only in `\NAT@citexnum`'s parenthetical branch) joins a run of three or more consecutive numbers with an en dash,
2567    // a run of two with the separator (natbib.sty:401-421, cite.sty:272-297). KNOWN_PERL_ERRORS #1072.
2568    let order_classes = bibref.get_attribute("class").unwrap_or_default();
2569    let has_class = |name: &str| order_classes.split_whitespace().any(|c| c == name);
2570    // (cite.sty prints the keys with no number first, at once: cite.sty:225-230 `\@cite@gobbledump@now`,
2571    // `ltx_cite_unsorted_first`; natbib after them)
2572    // (cite.sty's sort numbers, `cite_sty_sort_key`, and its two kinds of run: consecutive numbers, 256 apart, or
2573    // consecutive suffixes of one number, 1 apart, cite.sty:266-297 `\@compress@cite`; natbib's whole numbers)
2574    let cite_sty = has_class("ltx_cite_unsorted_first");
2575    let sort_key = |datum: &BibciteDatum| {
2576      if cite_sty {
2577        datum.cite_sty_key()
2578      } else {
2579        datum.entry_number()
2580      }
2581    };
2582    let steps: &[u64] = if cite_sty { &[256, 1] } else { &[1] };
2583    if has_class("ltx_cite_sort") {
2584      let unsorted = if has_class("ltx_cite_unsorted_first") {
2585        0
2586      } else {
2587        2
2588      };
2589      data.sort_by_key(|datum| sort_key(datum).map_or((unsorted, 0), |n| (1, n)));
2590    }
2591    let bare_number = matches!(
2592      show.to_ascii_lowercase().as_str(),
2593      "number" | "refnum" | "super"
2594    );
2595    let joints = if has_class("ltx_cite_compress") && (force_numeric || bare_number) {
2596      compressed_joints(&data.iter().map(sort_key).collect::<Vec<_>>(), steps)
2597    } else {
2598      vec![CiteJoint::Separator; data.len()]
2599    };
2600    let mut refs: Vec<NodeData> = Vec::new();
2601    if force_numeric {
2602      // Numeric collapse (#123): each entry's number, joined with ", " (natbib
2603      // numbers mode), bracketed as a group ([1, 2]) unless `\citep`'s external
2604      // parens already enclose it.
2605      for (datum, joint) in data.iter().zip(&joints) {
2606        let label = [&datum.number, &datum.refnum]
2607          .into_iter()
2608          .find(|l| !l.is_empty())
2609          .cloned()
2610          .unwrap_or_else(|| vec![NodeData::Text(datum.key.clone())]);
2611        let item = vec![bib_ref(&datum.attr, label)];
2612        match joint {
2613          CiteJoint::Covered => {},
2614          CiteJoint::RangeEnd => append_range_end(&mut refs, item),
2615          CiteJoint::Separator => {
2616            if !refs.is_empty() {
2617              refs.push(NodeData::Text(", ".to_string()));
2618            }
2619            refs.extend(item);
2620          },
2621        }
2622      }
2623      if internal_delims && !refs.is_empty() {
2624        refs.insert(0, NodeData::Text("[".to_string()));
2625        refs.push(NodeData::Text("]".to_string()));
2626      }
2627      return (refs, true);
2628    }
2629    let lower = show.to_lowercase();
2630    let checkdups =
2631      lower.contains("author") && (lower.contains("year") || lower.contains("number"));
2632    let mut data: VecDeque<BibciteDatum> = data.into();
2633    // (a bare-number show absorbs no same-author entries, `checkdups`, so the joints stay aligned with the entries)
2634    let mut joints = joints.into_iter();
2635    let mut forms: Vec<Option<bool>> = Vec::new();
2636    while let Some(datum) = data.pop_front() {
2637      let joint = joints.next().unwrap_or(CiteJoint::Separator);
2638      if joint == CiteJoint::Covered {
2639        continue;
2640      }
2641      let nameless_show = datum
2642        .nameless
2643        .then(|| nameless_numeric_show(&show))
2644        .flatten();
2645      let (stuff, didref, numeric) = bibcite_show_walk(
2646        nameless_show.as_deref().unwrap_or(&show),
2647        &datum,
2648        &mut data,
2649        &preformatted,
2650        &phrases,
2651        &yysep,
2652        // Entries without names share no author label.
2653        checkdups && !datum.nameless,
2654      );
2655      forms.push(numeric);
2656      let item = if didref {
2657        stuff
2658      } else {
2659        vec![bib_ref(&datum.attr, stuff)]
2660      };
2661      if joint == CiteJoint::RangeEnd {
2662        append_range_end(&mut refs, item);
2663        continue;
2664      }
2665      if !refs.is_empty() {
2666        refs.push(NodeData::Text(sep.clone()));
2667        refs.push(NodeData::Text(" ".to_string()));
2668      }
2669      refs.extend(item);
2670    }
2671    let numeric = forms.contains(&Some(true)) && !forms.contains(&Some(false));
2672    (refs, numeric)
2673  }
2674
2675  fn fill_in_mathlinks(&mut self, doc: &PostDocument) {
2676    for sym in &doc.findnodes("descendant::*[@decl_id or @meaning]") {
2677      let tag = doc.get_qname(sym).unwrap_or_default();
2678      if tag == "ltx:XMRef" || sym.has_attribute("href") {
2679        continue;
2680      }
2681      let entry_key = sym
2682        .get_attribute("decl_id")
2683        .map(|did| format!("DECLARATION:local:{}", did))
2684        .or_else(|| {
2685          sym
2686            .get_attribute("meaning")
2687            .map(|m| format!("DECLARATION:global:{}", m))
2688        });
2689      let parent_id = entry_key
2690        .as_ref()
2691        .and_then(|ek| self.db.lookup(ek))
2692        .and_then(|entry| entry.get_string("parent").map(String::from));
2693      if let Some(pid) = parent_id {
2694        if let Some(url) = self.generate_url(doc, &pid) {
2695          let mut sym_mut = sym.clone();
2696          sym_mut.set_attribute("href", &url).ok();
2697        }
2698      }
2699    }
2700  }
2701
2702  /// Perl CrossRef.pm:64-76: the severities in the fixed order `error, warn, info`, the types of
2703  /// each sorted. The ids within a type are sorted too, where Perl's hash `keys` order is random,
2704  /// so the report does not follow the hash table's layout (det354 C1).
2705  fn report_missing(&self) {
2706    for severity in ["error", "warn", "info"] {
2707      let Some(types) = self.missing.get(severity) else {
2708        continue;
2709      };
2710      let mut type_names: Vec<&String> = types.keys().collect();
2711      type_names.sort_unstable();
2712      for ref_type in type_names {
2713        let mut keys: Vec<&str> = types[ref_type].keys().map(String::as_str).collect();
2714        keys.sort_unstable();
2715        let msg = format!("Missing {}: {}", ref_type, keys.join(","));
2716        // Perl CrossRef.pm L72-75: structured Error/Warn/Info with
2717        // class='expected', object='ids'. Use harness-friendly target.
2718        match severity {
2719          "error" => Error!("expected", "ids", "{}", msg),
2720          "warn" => Warn!("expected", "ids", "{}", msg),
2721          _ => Info!("expected", "ids", "{}", msg),
2722        }
2723      }
2724    }
2725  }
2726}
2727
2728impl Processor for CrossRef {
2729  fn get_name(&self) -> &str { &self.name }
2730
2731  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
2732    match doc.get_document_element() {
2733      Some(el) => vec![el],
2734      None => vec![],
2735    }
2736  }
2737
2738  fn process(&mut self, mut doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
2739    self.missing.clear();
2740
2741    // Generate document title and add navigation
2742    let doc_title = self.generate_document_title(&doc);
2743    let navtoc = self.navigation_toc.clone();
2744
2745    let mut nav = if navtoc.is_some() || doc_title.is_some() {
2746      match doc.findnode("//ltx:navigation") {
2747        Some(existing) => Some(existing),
2748        None => {
2749          if let Some(mut root) = doc.get_document_element() {
2750            doc.add_nodes(&mut root, &[NodeData::Element {
2751              tag:        "ltx:navigation".to_string(),
2752              attributes: None,
2753              children:   vec![],
2754            }]);
2755          }
2756          doc.findnode("//ltx:navigation")
2757        },
2758      }
2759    } else {
2760      None
2761    };
2762    if let Some(ref format) = navtoc
2763      && let Some(ref mut nav_node) = nav
2764    {
2765      // Perl CrossRef.pm L50: `['ltx:TOC', {format => $navtoc}]` — format
2766      // ONLY, no `scope`. `fill_in_tocs` then defaults scope to `current`, so
2767      // this TOC is built relative to THIS page's document element. On a split
2768      // document that yields a per-page navigation breadcrumb via
2769      // `gen_toc_context` (each page's own contents enclosed within its
2770      // ancestors + their siblings), rather than one identical global tree.
2771      doc.add_nodes(nav_node, &[NodeData::Element {
2772        tag:        "ltx:TOC".to_string(),
2773        attributes: Some(HashMap::from_iter([("format".to_string(), format.clone())])),
2774        children:   vec![],
2775      }]);
2776    }
2777    if let Some(ref title) = doc_title
2778      && let Some(ref mut nav_node) = nav
2779    {
2780      doc.add_nodes(nav_node, &[NodeData::Element {
2781        tag:        "ltx:title".to_string(),
2782        attributes: None,
2783        children:   vec![NodeData::Text(title.clone())],
2784      }]);
2785    }
2786
2787    self.fill_in_relations(&mut doc);
2788    self.fill_in_tocs(&mut doc);
2789    self.fill_in_frags(&doc);
2790    self.fill_in_glossaryrefs(&mut doc);
2791    self.fill_in_refs(&mut doc);
2792    self.settle_cref_conjunctions(&mut doc);
2793    self.fill_in_rdfa_refs(&mut doc);
2794    self.fill_in_bibrefs(&mut doc);
2795    self.fill_in_mathlinks(&doc);
2796    self.copy_resources(&doc);
2797    strip_ref_display_fragids(&doc);
2798    self.report_missing();
2799    Ok(vec![doc])
2800  }
2801}
2802
2803// ======================================================================
2804// Helpers
2805
2806fn relative_url(target: &str, base: &str) -> String {
2807  if target == base {
2808    return ".".to_string();
2809  }
2810  let target_parts: Vec<&str> = target.split('/').collect();
2811  let base_parts: Vec<&str> = base.split('/').collect();
2812  let common = target_parts
2813    .iter()
2814    .zip(base_parts.iter())
2815    .take_while(|(a, b)| a == b)
2816    .count();
2817  let mut result = String::new();
2818  for _ in common..base_parts.len().saturating_sub(1) {
2819    result.push_str("../");
2820  }
2821  result.push_str(&target_parts[common..].join("/"));
2822  if result.is_empty() {
2823    ".".to_string()
2824  } else {
2825    result
2826  }
2827}
2828
2829/// Get text content from an XML node, normalizing whitespace.
2830///
2831/// Port of `getTextContent`.
2832fn get_text_content_node(node: &Node) -> String {
2833  let text = node.get_content();
2834  let trimmed = text.trim();
2835  // Normalize whitespace
2836  trimmed.split_whitespace().collect::<Vec<_>>().join(" ")
2837}
2838
2839/// A key-less bibref's phrases in the order its `show` names them (`phrase0` the last, as in [`bibcite_show_walk`]), or
2840/// nothing when they hold only delimiters ([`carries_a_note`]).
2841fn keyless_phrases(show: &str, phrases: &[Node], separators: &[String]) -> Vec<NodeData> {
2842  static PHRASE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)phrase(\d)").unwrap());
2843  let stuff: Vec<NodeData> = PHRASE
2844    .captures_iter(show)
2845    .filter_map(|c| match c[1].parse::<usize>() {
2846      Ok(0) => phrases.last(),
2847      Ok(n) => phrases.get(n - 1),
2848      Err(_) => None,
2849    })
2850    .flat_map(child_nodes_data)
2851    .collect();
2852  if carries_a_note(&stuff, separators) {
2853    stuff
2854  } else {
2855    Vec::new()
2856  }
2857}
2858
2859/// A bibref's `separator` and `yyseparator`, "," when absent or empty.
2860fn bibref_separators(bibref: &Node) -> [String; 2] {
2861  ["separator", "yyseparator"].map(|name| {
2862    bibref
2863      .get_attribute(name)
2864      .filter(|s| !s.is_empty())
2865      .unwrap_or_else(|| ",".to_string())
2866  })
2867}
2868
2869/// Whether citation material holds more than its delimiters: an element, or a character other than a space, a bracket
2870/// or `,;` and the bibref's separators, so `\citep[][\S]{}`'s "§", "–" and "?" are notes, `\citep{}`'s "()" is not.
2871fn carries_a_note(nodes: &[NodeData], separators: &[String]) -> bool {
2872  if nodes.iter().any(|n| !matches!(n, NodeData::Text(_))) {
2873    return true;
2874  }
2875  let text = separators
2876    .iter()
2877    .map(|sep| sep.trim())
2878    .filter(|sep| !sep.is_empty())
2879    .fold(text_content(nodes), |text, sep| text.replace(sep, " "));
2880  text
2881    .chars()
2882    .any(|c| !c.is_whitespace() && !"()[]{}<>,;".contains(c))
2883}
2884
2885fn text_content(nodes: &[NodeData]) -> String {
2886  nodes
2887    .iter()
2888    .map(|n| match n {
2889      NodeData::Text(s) => s.clone(),
2890      NodeData::Element { children, .. } => text_content(children),
2891      NodeData::XmlNode(n) => n.get_content(),
2892    })
2893    .collect::<Vec<_>>()
2894    .join("")
2895}
2896
2897/// The `|`-separated alternatives of a ref's `show`, outside its `{…}` literals ([`CrossRef::generate_ref_aux`]).
2898fn show_alternatives(show: &str) -> Vec<&str> {
2899  let mut alternatives = Vec::new();
2900  let (mut depth, mut start) = (0usize, 0);
2901  for (at, c) in show.char_indices() {
2902    match c {
2903      '{' => depth += 1,
2904      '}' => depth = depth.saturating_sub(1),
2905      '|' if depth == 0 => {
2906        alternatives.push(&show[start..at]);
2907        start = at + 1;
2908      },
2909      _ => {},
2910    }
2911  }
2912  alternatives.push(&show[start..]);
2913  alternatives
2914}
2915
2916/// How a citation's entry joins the one printed before it ([`CrossRef::make_bibcite`]).
2917#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2918enum CiteJoint {
2919  /// After the separator (the first entry: alone).
2920  Separator,
2921  /// Inside a compressed range: not printed.
2922  Covered,
2923  /// The last of a compressed range: after an en dash.
2924  RangeEnd,
2925}
2926
2927/// The joints of a sorted citation's entries, by their numbers: each run of three or more consecutive numbers prints
2928/// its first and last joined by an en dash, natbib's `--` (natbib.sty:412-417) and cite.sty's `\citedash`
2929/// (cite.sty:288-290); a run of two keeps the separator, as both print "[1, 2]".
2930fn compressed_joints(numbers: &[Option<u64>], steps: &[u64]) -> Vec<CiteJoint> {
2931  let mut joints = vec![CiteJoint::Separator; numbers.len()];
2932  let follows = |at: usize, step: u64| matches!((numbers[at], numbers.get(at + 1).copied().flatten()), (Some(a), Some(b)) if b == a + step);
2933  let mut start = 0;
2934  while start < numbers.len() {
2935    let mut end = start;
2936    // (the run's step, the first its second number takes)
2937    if let Some(&step) = steps.iter().find(|&&step| follows(start, step)) {
2938      while end + 1 < numbers.len() && follows(end, step) {
2939        end += 1;
2940      }
2941    }
2942    if end >= start + 2 {
2943      joints[start + 1..end].fill(CiteJoint::Covered);
2944      joints[end] = CiteJoint::RangeEnd;
2945    }
2946    start = end + 1;
2947  }
2948  joints
2949}
2950
2951/// Append the last entry of a compressed range after an en dash: inside the superscript the range's first entry
2952/// opened, for a superscript citation ("¹⁻³"), else as text.
2953fn append_range_end(refs: &mut Vec<NodeData>, mut item: Vec<NodeData>) {
2954  let is_sup = |node: &NodeData| matches!(node, NodeData::Element { tag, .. } if tag == "ltx:sup");
2955  if item.len() == 1
2956    && is_sup(&item[0])
2957    && let Some(NodeData::Element { children, .. }) = refs.last_mut().filter(|last| is_sup(last))
2958  {
2959    if let Some(NodeData::Element { children: inner, .. }) = item.pop() {
2960      children.push(NodeData::Text("\u{2013}".to_string()));
2961      children.extend(inner);
2962    }
2963    return;
2964  }
2965  refs.push(NodeData::Text("\u{2013}".to_string()));
2966  refs.extend(item);
2967}
2968
2969/// The phrases-and-number part of a textual numeric `show` (`Authors Phrase1NumberPhrase2`, `FullAuthors …`): what
2970/// an entry with no name to print keeps of it ([`CrossRef::make_bibcite`]). `None` for any other form, which turns
2971/// the citation `refnum` as in Perl (CrossRef.pm:541).
2972fn nameless_numeric_show(show: &str) -> Option<String> {
2973  let lower = show.to_ascii_lowercase();
2974  let after_full = lower.strip_prefix("full").unwrap_or(&lower);
2975  let rest = after_full
2976    .strip_prefix("authors")
2977    .or_else(|| after_full.strip_prefix("author"))
2978    .map(|rest| show[show.len() - rest.len()..].trim_start())?;
2979  let rest_lower = rest.to_ascii_lowercase();
2980  (rest_lower.contains("number") && rest_lower.contains("phrase") && !rest_lower.contains("author"))
2981    .then(|| rest.to_string())
2982}
2983
2984#[cfg(test)]
2985mod tests {
2986  use super::*;
2987
2988  #[test]
2989  fn relative_url_identical_paths_is_dot() {
2990    assert_eq!(relative_url("a/b.html", "a/b.html"), ".");
2991  }
2992
2993  #[test]
2994  fn relative_url_same_dir() {
2995    // Both live under a/, so target becomes simply the sibling filename.
2996    assert_eq!(relative_url("a/other.html", "a/index.html"), "other.html");
2997  }
2998
2999  #[test]
3000  fn relative_url_sibling_dir() {
3001    // From a/index.html to b/x.html: up once, then down.
3002    assert_eq!(relative_url("b/x.html", "a/index.html"), "../b/x.html");
3003  }
3004
3005  #[test]
3006  fn relative_url_deeply_nested_base() {
3007    // Up past each intermediate dir of the base, then into the new path.
3008    assert_eq!(
3009      relative_url("top/sibling.html", "top/deep/nested/page.html"),
3010      "../../sibling.html"
3011    );
3012  }
3013
3014  #[test]
3015  fn relative_url_same_prefix_different_file() {
3016    assert_eq!(
3017      relative_url("a/b/c/target.html", "a/b/c/source.html"),
3018      "target.html"
3019    );
3020  }
3021
3022  #[test]
3023  fn ref_fallbacks_typerefnum_goes_to_refnum() {
3024    assert_eq!(ref_fallbacks("typerefnum"), &["refnum"]);
3025    assert_eq!(ref_fallbacks("creflabel"), &["refnum"]);
3026  }
3027
3028  #[test]
3029  fn compressed_joints_join_runs_of_three() {
3030    use CiteJoint::{Covered as C, RangeEnd as R, Separator as S};
3031    let joints = |numbers: &[Option<u64>]| compressed_joints(numbers, &[1]);
3032    assert_eq!(joints(&[Some(1), Some(2), Some(3)]), [S, C, R]);
3033    assert_eq!(joints(&[Some(1), Some(2)]), [S, S]);
3034    assert_eq!(
3035      joints(&[
3036        Some(1),
3037        Some(2),
3038        Some(3),
3039        Some(5),
3040        Some(6),
3041        Some(7),
3042        Some(8)
3043      ]),
3044      [S, C, R, S, C, C, R]
3045    );
3046    assert_eq!(joints(&[Some(1), Some(2), None, Some(3)]), [S, S, S, S]);
3047  }
3048
3049  #[test]
3050  fn cite_sty_sort_keys_and_runs() {
3051    use CiteJoint::{Covered as C, RangeEnd as R, Separator as S};
3052    // cite.sty:127-222: a number, `[prefix]number[suffix]`, number-separator-number; the rest unsortable
3053    assert_eq!(cite_sty_sort_key("7"), Some(7 * 256));
3054    assert_eq!(cite_sty_sort_key("2a"), Some(2 * 256 + 97));
3055    assert_eq!(cite_sty_sort_key("a2"), Some((97 * 16384 + 2) * 256));
3056    assert_eq!(cite_sty_sort_key("1.2"), Some((256 + 46) * 4096 + 2));
3057    assert_eq!(cite_sty_sort_key("Knu84"), None);
3058    assert_eq!(cite_sty_sort_key("2ab"), None);
3059    let mut labels = ["7", "2a", "1"];
3060    labels.sort_by_key(|label| cite_sty_sort_key(label));
3061    assert_eq!(labels, ["1", "2a", "7"]);
3062    // cite.sty:266-297: consecutive numbers (256 apart) or consecutive suffixes of one number (1 apart)
3063    let keys = |labels: &[&str]| {
3064      labels
3065        .iter()
3066        .map(|label| cite_sty_sort_key(label))
3067        .collect::<Vec<_>>()
3068    };
3069    assert_eq!(compressed_joints(&keys(&["1", "2", "3"]), &[256, 1]), [
3070      S, C, R
3071    ]);
3072    assert_eq!(compressed_joints(&keys(&["4a", "4b", "4c"]), &[256, 1]), [
3073      S, C, R
3074    ]);
3075    assert_eq!(compressed_joints(&keys(&["2a", "3", "4"]), &[256, 1]), [
3076      S, S, S
3077    ]);
3078  }
3079
3080  #[test]
3081  fn ref_fallbacks_title_chain() {
3082    assert_eq!(ref_fallbacks("title"), &["toccaption"]);
3083    assert_eq!(ref_fallbacks("toctitle"), &["title", "toccaption"]);
3084    assert_eq!(ref_fallbacks("rawtoctitle"), &[
3085      "toctitle",
3086      "title",
3087      "toccaption"
3088    ]);
3089    assert_eq!(ref_fallbacks("rawtitle"), &["title", "toccaption"]);
3090  }
3091
3092  #[test]
3093  fn ref_fallbacks_unknown_key_is_empty() {
3094    let empty: &[&str] = &[];
3095    assert_eq!(ref_fallbacks("nonexistent"), empty);
3096    assert_eq!(ref_fallbacks(""), empty);
3097  }
3098
3099  #[test]
3100  fn text_content_flattens_text() {
3101    let nodes = vec![
3102      NodeData::Text("hello ".to_string()),
3103      NodeData::Text("world".to_string()),
3104    ];
3105    assert_eq!(text_content(&nodes), "hello world");
3106  }
3107
3108  #[test]
3109  fn text_content_recurses_into_elements() {
3110    let nodes = vec![NodeData::Element {
3111      tag:        "span".to_string(),
3112      attributes: None,
3113      children:   vec![
3114        NodeData::Text("inner ".to_string()),
3115        NodeData::Text("text".to_string()),
3116      ],
3117    }];
3118    assert_eq!(text_content(&nodes), "inner text");
3119  }
3120
3121  #[test]
3122  fn text_content_empty_list_is_empty_string() {
3123    assert_eq!(text_content(&[]), "");
3124  }
3125
3126  #[test]
3127  fn text_content_mixed_text_and_nested_element() {
3128    let nodes = vec![
3129      NodeData::Text("outer ".to_string()),
3130      NodeData::Element {
3131        tag:        "em".to_string(),
3132        attributes: None,
3133        children:   vec![NodeData::Text("inner".to_string())],
3134      },
3135      NodeData::Text(" tail".to_string()),
3136    ];
3137    assert_eq!(text_content(&nodes), "outer inner tail");
3138  }
3139
3140  // --- URL-style transform (Perl CrossRef::generateURL L656-663) -------------
3141
3142  #[test]
3143  fn url_style_file_is_identity() {
3144    // `file` keeps the full path untouched, whatever it is.
3145    for url in ["a/b.html", "index.html", "sub/index.html", "index", ""] {
3146      assert_eq!(apply_url_style(url, UrlStyle::File, "html"), url);
3147    }
3148  }
3149
3150  #[test]
3151  fn url_style_server_strips_trailing_index() {
3152    // At start → "./"; after a slash → keep the directory (with slash).
3153    assert_eq!(
3154      apply_url_style("index.html", UrlStyle::Server, "html"),
3155      "./"
3156    );
3157    assert_eq!(
3158      apply_url_style("dir/index.html", UrlStyle::Server, "html"),
3159      "dir/"
3160    );
3161    assert_eq!(
3162      apply_url_style("a/b/index.html", UrlStyle::Server, "html"),
3163      "a/b/"
3164    );
3165    // A non-index page is untouched.
3166    assert_eq!(
3167      apply_url_style("dir/page.html", UrlStyle::Server, "html"),
3168      "dir/page.html"
3169    );
3170    // Boundary: `index.html` NOT preceded by start-or-`/` must NOT be stripped
3171    // (Perl's `(^|\/)`); the old `ends_with` check wrongly mangled this.
3172    assert_eq!(
3173      apply_url_style("myindex.html", UrlStyle::Server, "html"),
3174      "myindex.html"
3175    );
3176  }
3177
3178  #[test]
3179  fn url_style_negotiated_strips_extension_and_index() {
3180    // Extension goes; a plain page keeps its stem.
3181    assert_eq!(
3182      apply_url_style("dir/page.html", UrlStyle::Negotiated, "html"),
3183      "dir/page"
3184    );
3185    // Trailing `index` after the extension strip: at start → ""; after "/" → keep dir.
3186    assert_eq!(
3187      apply_url_style("index.html", UrlStyle::Negotiated, "html"),
3188      ""
3189    );
3190    assert_eq!(
3191      apply_url_style("dir/index.html", UrlStyle::Negotiated, "html"),
3192      "dir/"
3193    );
3194    // Boundary: a bare `index` NOT after start-or-`/` stays (Perl's `(^|\/)index$`).
3195    assert_eq!(
3196      apply_url_style("myindex.html", UrlStyle::Negotiated, "html"),
3197      "myindex"
3198    );
3199    // Honors a non-html extension.
3200    assert_eq!(
3201      apply_url_style("dir/index.xml", UrlStyle::Negotiated, "xml"),
3202      "dir/"
3203    );
3204  }
3205}