Skip to main content

latexml_post/
document.rs

1//! Post-processing document wrapper with XML/DOM, ID management, and caching.
2//!
3//! Port of `LaTeXML::Post::Document`.
4//! Wraps an `XML::LibXML::Document` (via the `libxml` crate) and provides:
5//! - Namespace management
6//! - ID tracking (idcache, reusable, reserved)
7//! - XPath queries with registered namespaces
8//! - Node manipulation (addNodes, removeNodes, cloneNode, etc.)
9//! - Persistent cache (key-value store)
10
11use std::path::Path;
12
13use latexml_core::common::{
14  xml::{compiled_xpath, name_is},
15  xml_walk::WalkQuery,
16};
17use libxml::{
18  parser::Parser as XmlParser,
19  readonly::RoNode,
20  tree::{Document, Namespace, Node, NodeType},
21  xpath::{Context as XPathContext, Expression, XPathError},
22};
23use rustc_hash::{FxHashMap as HashMap, FxHashSet};
24use unicode_normalization::UnicodeNormalization;
25
26use crate::radix::radix_alpha;
27
28/// libxml2's `XML_ERR_NO_MEMORY` (`xmlParserErrors`).
29const XML_ERR_NO_MEMORY: i32 = 2;
30
31/// Whether an XPath evaluation failed because libxml2 could not allocate: `XML_ERR_NO_MEMORY` with no message, where a
32/// malformed expression always carries one ("Invalid expression", code 1207). It is glibc's malloc spent in a reused
33/// cortex child whose Rust heap still serves (libxml2 2.9.14 and 2.15 alike; 68m step 1,
34/// `scratch_356a0c47/68m_step1/RESULTS.md`).
35fn is_libxml_oom(e: &XPathError) -> bool { e.message.is_none() && e.code == XML_ERR_NO_MEMORY }
36
37/// An XPath evaluation libxml2 could not allocate for ([`is_libxml_oom`]) is the process's allocation failure, not a
38/// failure of this node's lookup: it ends through the binary's allocation-failure hook — one `Fatal:oom`, the child
39/// recycled and the paper retried (ruling 2026-10-15) — where an Error per node ran on to `TooManyErrors` (runs
40/// 362/363: 87-501 per paper; 1008.4986, 1712.03782, 1910.13564, 2101.04438, 2208.07188, 2305.17269, 2401.10096,
41/// 2609.06115). The context line goes out allocation-free before the hook's own.
42fn end_on_libxml_oom(xpath: &str, e: &XPathError) {
43  if is_libxml_oom(e) {
44    latexml_core::watchdog::write_stderr_unlocked(format_args!(
45      "Warning:post:xpath libxml2 could not allocate evaluating `{xpath}` (XML_ERR_NO_MEMORY): ending as an \
46       allocation failure\n"
47    ));
48    latexml_core::watchdog::alloc_failed(std::alloc::Layout::new::<u8>());
49  }
50}
51
52const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
53
54/// Get the xml:id attribute value from a node.
55/// Handles both namespace-aware and plain attribute access.
56pub fn get_xml_id(node: &Node) -> Option<String> {
57  node
58    .get_attribute_ns("id", XML_NS)
59    .or_else(|| node.get_attribute("xml:id"))
60    .or_else(|| {
61      // Fallback: the properties map's "id" key (any namespace, the last such wins), built only when `xmlHasProp`
62      // finds an `id` at all: most nodes have none, and the map copied every attribute of each.
63      if node.has_property("id") {
64        node.get_properties().get("id").cloned()
65      } else {
66        None
67      }
68    })
69}
70
71/// Remap a cloned node's `fragid` after its `xml:id` was uniquified.
72///
73/// Port of Perl `Post::Document::cloneNode` (`Post.pm` L1268-1270):
74/// `fragid => substr($newid, length($id) - length($fragid))`. The fragid is
75/// the reference-visible tail of the id (equal to the whole id for a top-level
76/// object), so we take the corresponding tail of the new id. IDs are ASCII, so
77/// byte and character offsets coincide.
78fn remap_fragid(id: &str, new_id: &str, fragid: &str) -> String {
79  let offset = id.len().saturating_sub(fragid.len());
80  new_id.get(offset..).unwrap_or(fragid).to_string()
81}
82
83/// The LaTeXML namespace URI.
84pub const LTX_NSURI: &str = "http://dlmf.nist.gov/LaTeXML";
85
86/// The crate-default leniency (recover, noerror, nowarning) plus
87/// `XML_PARSE_HUGE` — see [`PostDocument::new_from_file`] for why post's
88/// parses must relax libxml2's hard limits.
89fn huge_parse_options() -> libxml::parser::ParserOptions<'static> {
90  libxml::parser::ParserOptions {
91    huge: true,
92    ..Default::default()
93  }
94}
95
96/// Replace every entity reference in a document carrying a DTD by the entity's content, as libxml2's
97/// `XML_PARSE_NOENT` (XML::LibXML's `expand_entities`, Perl's default before XML::LibXML 2.0206) does at parse; the
98/// libxml crate offers no such flag, so the parsed references are expanded here (DG 2026-11-15, row DTDENT). A
99/// reference with no parsed content, to an external entity (never read) or an undeclared one (the external DTD is not
100/// read), is removed with its text lost: one Warning per entity name, and a page spilled and read again has none left.
101///
102/// The walk reads through `RoNode`, which does not fill the document's node cache; only a reference it expands is
103/// wrapped as a `Node`.
104fn expand_entity_references(doc: &Document) {
105  let Some(root) = doc.get_root_readonly() else {
106    return;
107  };
108  let mut top = root.get_parent().and_then(|d| d.get_first_child());
109  let (mut has_dtd, mut declares_entities) = (false, false);
110  while let Some(node) = top {
111    if node.get_type() == Some(NodeType::DTDNode) {
112      has_dtd = true;
113      let mut decl = node.get_first_child();
114      while let Some(d) = decl {
115        declares_entities |= d.get_type() == Some(NodeType::EntityDecl);
116        decl = d.get_next_sibling();
117      }
118    }
119    top = node.get_next_sibling();
120  }
121  if !has_dtd {
122    return;
123  }
124  let mut lost = LostEntities::default();
125  let mut stack = vec![root];
126  while let Some(node) = stack.pop() {
127    // (libxml2 drops an undeclared reference in an attribute value at parse: only a declared one is left there)
128    if declares_entities {
129      expand_attribute_entities(doc, node, &mut lost);
130    }
131    let mut cursor = node.get_first_child();
132    while let Some(child) = cursor {
133      let next = child.get_next_sibling();
134      match child.get_type() {
135        Some(NodeType::EntityRefNode) => {},
136        Some(NodeType::ElementNode) => {
137          stack.push(child);
138          cursor = next;
139          continue;
140        },
141        _ => {
142          cursor = next;
143          continue;
144        },
145      }
146      // An entity reference's child is its declaration, whose children are the parsed content.
147      let content = child
148        .get_first_child()
149        .map(RoNode::get_child_nodes)
150        .unwrap_or_default();
151      if content.is_empty() {
152        lost.note(doc, child);
153      }
154      // The copies are walked next, so a reference in the content is expanded in turn (libxml2 refuses a
155      // self-referring entity at parse: it has no content).
156      let mut reference = doc.node_from_readonly(child);
157      let mut first = None;
158      for part in content {
159        if let Ok(mut copy) = doc.copy_node(&doc.node_from_readonly(part))
160          && reference.add_prev_sibling(&mut copy).is_ok()
161        {
162          first.get_or_insert(copy.as_readonly());
163        }
164      }
165      reference.unlink_node();
166      cursor = first.or(next);
167    }
168  }
169  lost.warn();
170}
171
172/// An attribute value holding entity references is read expanded (`xmlNodeListGetString`) but would be written back
173/// with them: set it to its expanded text.
174fn expand_attribute_entities(doc: &Document, element: RoNode, lost: &mut LostEntities) {
175  let mut expanded: Vec<(String, Option<String>, String)> = Vec::new();
176  element.for_each_property_ns(|name, href, value| {
177    let attr = match href {
178      Some(href) => element.get_property_node_ns(name, href),
179      None => element.get_property_node_no_ns(name),
180    };
181    let mut part = attr.and_then(RoNode::get_first_child);
182    let mut has_ref = false;
183    while let Some(node) = part {
184      if node.get_type() == Some(NodeType::EntityRefNode) {
185        has_ref = true;
186        if node
187          .get_first_child()
188          .is_none_or(|decl| decl.get_first_child().is_none())
189        {
190          lost.note(doc, node);
191        }
192      }
193      part = node.get_next_sibling();
194    }
195    if has_ref {
196      expanded.push((name.to_owned(), href.map(str::to_owned), value.to_owned()));
197    }
198  });
199  if expanded.is_empty() {
200    return;
201  }
202  let mut element = doc.node_from_readonly(element);
203  for (name, href, value) in expanded {
204    let _ = match href.and_then(|href| element.get_property_node_ns(&name, &href)) {
205      Some(attr) => match attr.get_namespace() {
206        Some(ns) => element.set_property_ns(&name, &value, &ns),
207        None => element.set_property(&name, &value),
208      },
209      None => element.set_property(&name, &value),
210    };
211  }
212}
213
214/// The references whose text is lost, counted per entity name, so a repeated one costs one Warning.
215#[derive(Default)]
216struct LostEntities {
217  /// name -> (references, declared): a declared one is external; an undeclared one is declared nowhere we read.
218  names: std::collections::BTreeMap<String, (usize, bool)>,
219}
220
221impl LostEntities {
222  /// Count `reference`, which has no parsed content, unless it names a declared internal entity (a quoted value):
223  /// empty, or content libxml2 refused in part, which is left to its recover mode (row XMLRECOVERSILENT).
224  fn note(&mut self, doc: &Document, reference: RoNode) {
225    let declared = match reference.get_first_child() {
226      None => false,
227      Some(decl) => {
228        // `<!ENTITY name "">` holds nothing to lose; an ExternalID (`SYSTEM`/`PUBLIC`) is never read.
229        let text = doc.ronode_to_string(&decl);
230        let value = text.trim_start_matches("<!ENTITY").trim_start();
231        let value = value
232          .trim_start_matches(|c: char| !c.is_whitespace())
233          .trim_start();
234        if value.starts_with(['"', '\'']) {
235          return;
236        }
237        true
238      },
239    };
240    self
241      .names
242      .entry(reference.get_name())
243      .or_insert((0, declared))
244      .0 += 1;
245  }
246
247  fn warn(self) {
248    for (name, (count, declared)) in self.names {
249      if declared {
250        Warn!(
251          "unexpected",
252          format!("&{name};"),
253          format!(
254            "{count} reference(s) to an external entity: it is not read, so its text is lost"
255          )
256        );
257      } else {
258        Warn!(
259          "unexpected",
260          format!("&{name};"),
261          format!(
262            "{count} reference(s) to an entity the document does not declare: its text is lost"
263          )
264        );
265      }
266    }
267  }
268}
269
270/// True when `node` is an element in the LaTeXML (`ltx:`) namespace.
271///
272/// The namespace lookup wraps a `Namespace`, so callers should gate it behind a
273/// cheaper localname check on the hot path (see [`collect_split_pages`]).
274pub(crate) fn is_ltx(node: &Node) -> bool {
275  node
276    .get_namespace()
277    .map(|ns| ns.get_href() == LTX_NSURI)
278    .unwrap_or(false)
279}
280
281/// Limit-safe pre-order walk collecting every element's `xml:id` and every
282/// `latexml` PI, in document order. Pass the *document* node so PIs preceding
283/// the root element are visited too.
284///
285/// This is the "limit-safe" pattern the post-processing queries share: a
286/// full-document `//X` (or `//X[pred]`) XPath makes libxml2 materialize
287/// `descendant-or-self::node()`, which past 10M nodes overflows the hardcoded
288/// `XPATH_MAX_NODESET_LENGTH`, returns NULL, and — formerly silently — yields an
289/// empty result. A direct DOM walk has no node-set and no such ceiling.
290fn scan_ids_and_pis(document: &Node, ids: &mut Vec<(String, Node)>, pis: &mut Vec<String>) {
291  // The walk is read-only and wraps only the elements with an id as `Node`s: a wrapper is a registry entry kept until
292  // the document drops (PERF2 R5). A DTD can default an `xml:id` that `get_xml_id` reads, so then every element is asked.
293  let ro = document.as_readonly();
294  let has_dtd = ro
295    .get_child_nodes()
296    .iter()
297    .any(|c| c.get_type() == Some(NodeType::DTDNode));
298  scan_ids_and_pis_from(document, ro, has_dtd, ids, pis);
299}
300
301fn scan_ids_and_pis_from(
302  document: &Node,
303  node: RoNode,
304  has_dtd: bool,
305  ids: &mut Vec<(String, Node)>,
306  pis: &mut Vec<String>,
307) {
308  let mut child = node.get_first_child();
309  while let Some(c) = child {
310    match c.get_type() {
311      Some(NodeType::ElementNode) => {
312        // (without a DTD, `get_xml_id` finds an id only on a property named `id` or `xml:id`)
313        let mut named_id = has_dtd;
314        if !named_id {
315          c.for_each_property(|name, _| named_id |= name == "id" || name == "xml:id");
316        }
317        if named_id {
318          let element = document.node_from_readonly(c);
319          if let Some(id) = get_xml_id(&element) {
320            ids.push((id, element));
321          }
322        }
323        scan_ids_and_pis_from(document, c, has_dtd, ids, pis);
324      },
325      Some(NodeType::PiNode) if c.with_name(|name| name == "latexml") => {
326        pis.push(c.with_content(str::to_owned));
327      },
328      _ => {},
329    }
330    child = c.get_next_sibling();
331  }
332}
333
334/// One arm of a `--splitat` page union: an `ltx:` element localname plus an
335/// optional disjunctive predicate. Mirrors the arms `make_splitpaths` emits.
336pub(crate) struct SplitArm {
337  /// `ltx:` element localname (e.g. `"section"`, `"index"`).
338  pub(crate) element: String,
339  /// Disjunction of conditions; empty ⇒ the element is unconditionally a page.
340  pub(crate) any_of:  Vec<SplitCond>,
341}
342
343/// A single predicate condition inside a [`SplitArm`] — the only two forms
344/// `make_splitpaths` ever generates.
345pub(crate) enum SplitCond {
346  /// `preceding-sibling::ltx:NAME`
347  PrecedingSibling(String),
348  /// `parent::ltx:NAME`
349  Parent(String),
350}
351
352/// Parse the `make_splitpaths` union (`//ltx:X | //ltx:Y[preceding-sibling::…
353/// or parent::…] | …`) into structured arms. Returns `None` if any arm is
354/// outside this narrow grammar, so the caller can fall back to raw XPath for a
355/// custom `--splitpaths` (which only matters on small documents, where XPath is
356/// limit-safe anyway).
357pub(crate) fn parse_split_union(union_xpath: &str) -> Option<Vec<SplitArm>> {
358  let mut arms = Vec::new();
359  for raw in union_xpath.split('|') {
360    let arm = raw.trim();
361    let rest = arm.strip_prefix("//ltx:")?;
362    let (name, pred) = match rest.split_once('[') {
363      Some((n, p)) => (n.trim(), Some(p.strip_suffix(']')?.trim())),
364      None => (rest.trim(), None),
365    };
366    if name.is_empty()
367      || !name
368        .chars()
369        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
370    {
371      return None;
372    }
373    let mut any_of = Vec::new();
374    if let Some(pred) = pred {
375      for cond in pred.split(" or ") {
376        let cond = cond.trim();
377        if let Some(n) = cond.strip_prefix("preceding-sibling::ltx:") {
378          any_of.push(SplitCond::PrecedingSibling(n.trim().to_string()));
379        } else {
380          // Only `parent::ltx:NAME` remains in the make_splitpaths grammar;
381          // any other predicate is unsupported, so `?` returns `None` here and
382          // the caller falls back to raw XPath.
383          let n = cond.strip_prefix("parent::ltx:")?;
384          any_of.push(SplitCond::Parent(n.trim().to_string()));
385        }
386      }
387    }
388    arms.push(SplitArm {
389      element: name.to_string(),
390      any_of,
391    });
392  }
393  if arms.is_empty() { None } else { Some(arms) }
394}
395
396/// Evaluate one predicate condition against `node` (Rust equivalent of the
397/// `preceding-sibling::ltx:NAME` / `parent::ltx:NAME` XPath primitives).
398pub(crate) fn cond_matches(cond: &SplitCond, node: &Node) -> bool {
399  match cond {
400    SplitCond::PrecedingSibling(name) => {
401      let mut sib = node.get_prev_sibling();
402      while let Some(s) = sib {
403        if s.get_type() == Some(NodeType::ElementNode) && s.get_name() == *name && is_ltx(&s) {
404          return true;
405        }
406        sib = s.get_prev_sibling();
407      }
408      false
409    },
410    SplitCond::Parent(name) => node
411      .get_parent()
412      .map(|p| p.get_name() == *name && is_ltx(&p))
413      .unwrap_or(false),
414  }
415}
416
417/// True when `node` satisfies `arm` (an unconditional arm always matches).
418pub(crate) fn arm_matches(arm: &SplitArm, node: &Node) -> bool {
419  arm.any_of.is_empty() || arm.any_of.iter().any(|c| cond_matches(c, node))
420}
421
422/// Limit-safe pre-order walk collecting the page nodes selected by `arms`, in
423/// document order (no duplicates: each element is tested and pushed at most
424/// once). Replaces XPath evaluation of the split union.
425pub(crate) fn collect_split_pages(node: &Node, arms: &[SplitArm], out: &mut Vec<Node>) {
426  let mut child = node.get_first_child();
427  while let Some(c) = child {
428    if c.get_type() == Some(NodeType::ElementNode) {
429      let name = c.get_name();
430      // Cheap localname gate first; only confirm the `ltx:` namespace and run
431      // the (rare) predicate checks for elements that could actually be pages.
432      if arms.iter().any(|a| a.element == name)
433        && is_ltx(&c)
434        && arms.iter().any(|a| a.element == name && arm_matches(a, &c))
435      {
436        out.push(c.clone());
437      }
438      collect_split_pages(&c, arms, out);
439    }
440    child = c.get_next_sibling();
441  }
442}
443
444/// Post-processing document: wraps an XML document with ID management,
445/// namespace tracking, XPath helpers, and a persistent cache.
446///
447/// Port of `LaTeXML::Post::Document`.
448pub struct PostDocument {
449  /// The underlying XML document.
450  document:                    Document,
451  /// Destination file path for this document.
452  pub destination:             Option<String>,
453  /// Destination directory (derived from destination).
454  pub destination_directory:   Option<String>,
455  /// Site root directory.
456  pub site_directory:          Option<String>,
457  /// Source file path.
458  pub source:                  Option<String>,
459  /// Source directory.
460  pub source_directory:        Option<String>,
461  /// Search paths for resources.
462  pub searchpaths:             Vec<String>,
463  /// Namespace prefix → URI mapping.
464  pub namespaces:              HashMap<String, String>,
465  /// URI → prefix reverse mapping.
466  pub namespace_uris:          HashMap<String, String>,
467  /// ID cache: xml:id → node.
468  idcache:                     HashMap<String, Node>,
469  /// IDs marked as reusable (will be removed later).
470  idcache_reusable:            HashMap<String, bool>,
471  /// IDs reserved but not yet recorded.
472  idcache_reserve:             HashMap<String, bool>,
473  /// Clash counters for uniquifyID.
474  idcache_clashes:             HashMap<String, u32>,
475  /// Processing instructions from the document.
476  pub processing_instructions: Vec<String>,
477  /// Parent document (for split sub-documents).
478  pub parent_document:         Option<Box<PostDocument>>,
479  /// ID of document we were split from.
480  pub split_from_id:           Option<String>,
481  /// The id of the page this one was split out of (Perl `$$doc{parent_id}`, set by `Split`
482  /// from the page entry's `upid`); `Scan` files the page's root under it.
483  pub parent_id:               Option<String>,
484  /// Whether to validate the document.
485  pub validate:                bool,
486  /// Perl's document cache (its DB_File tied hash, `LaTeXML.cache`): [`DocCache`], shared by every page of a run.
487  cache:                       DocCache,
488  /// Whether caching is disabled.
489  pub nocache:                 bool,
490  /// XMath subtrees queued for deferred unlink. Parallel-format
491  /// processors (pmml + cmml) BOTH need the original XMath for their
492  /// per-format `convert_node` pass; if the first processor unlinks
493  /// the subtree, the second's `mark_xm_node_visibility` walks
494  /// stale `XMRef` targets and emits `Error:expected:id Cannot find
495  /// a node with xml:id=…`. Mirrors Perl `Post.pm` L373-393's
496  /// "XMath will be removed (LATER!), but mark its ids as reusable"
497  /// pattern: each per-math `process_math_node` call queues the
498  /// XMath here (and registers its xml:ids as reusable via
499  /// `preremove_nodes`), and a final post-pipeline pass — see
500  /// `drain_pending_unlinks` — does the actual unlink once all
501  /// math-format passes have completed.
502  pending_xmath_unlinks:       Vec<Node>,
503  /// Per-document memo for [`Self::add_navigation`]. The `ltx:navigation`
504  /// element, and the `(rel, idref)` pairs already under it.
505  ///
506  /// Perl `Post.pm:1409-1414` answers both questions with a whole-document
507  /// XPath on EVERY call — a `format!`-built duplicate probe (so it is
508  /// re-COMPILED each time) plus a `//ltx:navigation` walk. That is fine at
509  /// Perl's scale and ruinous at ours: `CrossRef::fill_in_relations` calls this
510  /// once per related page, measured at **406 calls per page** on the
511  /// 40,201-page witness — 16.3 M calls, 32.6 M XPath evaluations, and the
512  /// probe is O(refs already added) so it is quadratic *within* a page too.
513  /// Post-stage self-time profiling is dominated by exactly that: libxml2 XPath
514  /// machinery plus allocator churn (see `KNOWN_PERL_ERRORS.md` #69).
515  ///
516  /// The memo answers identically — it is seeded from the element's own `ltx:ref`
517  /// children, which is what `//ltx:navigation/ltx:ref` selects given the single
518  /// navigation element Perl's own `findnode` assumes.
519  nav_memo:                    Option<NavigationMemo>,
520  /// Each XPath expression compiled once, for every evaluation of this document's queries — compiled expressions
521  /// hold no context, so the per-call contexts share them (`latexml_core::common::xml::compiled_xpath`;
522  /// docs/performance/PERFORMANCE.md P10).
523  compiled_xpath:              std::cell::RefCell<HashMap<Box<str>, Expression>>,
524}
525
526/// Memoized navigation state for one document — see [`PostDocument::nav_memo`].
527struct NavigationMemo {
528  /// The `ltx:navigation` element, revalidated cheaply before reuse.
529  element: Option<Node>,
530  /// `(rel, idref)` pairs already present, standing in for Perl's XPath probe.
531  refs:    FxHashSet<(String, String)>,
532}
533
534impl Drop for PostDocument {
535  /// Rationalize Node lifetime between post-processing components.
536  /// `idcache` entries are Node *handles* into the C-owned libxml
537  /// Document tree — the Document owns the lifetime, Node wrappers
538  /// are lookup references.
539  ///
540  /// libxml 0.3.9's `_Node::drop` fires `xmlFreeNode(ptr)` whenever
541  /// the wrapper's internal `unlinked` flag is true. Math processing
542  /// calls `unlink_node()` on nodes as it replaces XMath subtrees
543  /// with MathML, flipping that flag for nodes still held by
544  /// `idcache`. The resulting drop sequence is:
545  ///   1. `document: Document` (declared first) → `xmlFreeDoc` walks the full tree including
546  ///      still-reachable nodes that share memory with idcache entries; freed.
547  ///   2. `idcache: HashMap<String, Node>` → each Node with `unlinked=true` fires `xmlFreeNode` on
548  ///      already-freed memory → SIGSEGV inside `xmlFreeNodeList`.
549  ///
550  /// Fix: hand each idcache entry to `DocOwnedNode` (see
551  /// `crate::doc_owned_node`), which suppresses the inner Rc's Drop
552  /// so `xmlFreeNode` never fires on already-freed memory.
553  /// `xmlFreeDoc` remains the sole owner of the C node memory.
554  /// Per-entry Rc control block leaks (~24 B) — bounded by
555  /// per-document idcache size and reclaimed at process exit.
556  /// Proper upstream fix: a public `set_linked()` setter on the
557  /// `libxml` crate's `Node`, which would let us relink before drop
558  /// rather than leaking.
559  fn drop(&mut self) {
560    for (_, node) in std::mem::take(&mut self.idcache) {
561      // The document owns the C memory; the wrapper must not free it even if
562      // intermediate processing `unlink_node`ed this entry. `set_linked`
563      // (libxml 0.3.20) declares exactly that, replacing the historical
564      // `DocOwnedNode` leak-wrapper (~100+ bytes per id-cache entry per
565      // document — a real term at 115k documents per process). Entries whose
566      // subtree was `free_subtree`d are already-neutralized no-ops here.
567      node.set_linked();
568    }
569  }
570}
571
572impl PostDocument {
573  /// Create a new PostDocument wrapping an existing XML document.
574  ///
575  /// Port of `Post::Document::new`.
576  pub fn new(doc: Document, options: PostDocumentOptions) -> Self {
577    // Node-mutation aliasing is enforced by libxml's `Node::node_ptr_mut`
578    // (`RefCell::try_borrow_mut`, libxml >= 0.3.14), which ignores benign clone
579    // count, so the former `set_node_rc_guard(128)` band-aid (post-processing
580    // holds many shared id-cache / XPath-result handles) is no longer needed.
581    let mut pd = Self::new_internal(doc, options);
582    pd.set_document_internal();
583    pd
584  }
585
586  /// Wrap a terminal XSLT output document (HTML5/XHTML/JATS/TEI) without
587  /// walking the entire DOM to populate `idcache` or scan `<?latexml?>` PIs —
588  /// no downstream processor queries `idcache` on XSLT output, only root
589  /// namespace declarations are needed for `--whatsout=fragment|math`.
590  pub fn new_transformed(doc: Document, options: PostDocumentOptions) -> Self {
591    let mut pd = Self::new_internal(doc, options);
592    pd.register_root_namespaces();
593    pd
594  }
595
596  fn new_internal(doc: Document, options: PostDocumentOptions) -> Self {
597    let mut dest_dir = options.destination_directory.clone();
598    if options.destination.is_some() && dest_dir.is_none() {
599      if let Some(ref dest) = options.destination {
600        if let Some(parent) = Path::new(dest).parent() {
601          let parent_str = parent.to_string_lossy().to_string();
602          // Empty parent (e.g., from "paper.html") means current directory — use "." not ""
603          if parent_str.is_empty() {
604            dest_dir = Some(".".to_string());
605          } else {
606            dest_dir = Some(parent_str);
607          }
608        }
609      }
610    }
611
612    let site_dir = if let Some(ref sd) = options.site_directory {
613      Some(sd.clone())
614    } else {
615      dest_dir.clone()
616    };
617
618    let mut namespaces = HashMap::default();
619    namespaces.insert("ltx".to_string(), LTX_NSURI.to_string());
620    let mut namespace_uris = HashMap::default();
621    namespace_uris.insert(LTX_NSURI.to_string(), "ltx".to_string());
622
623    PostDocument {
624      document: doc,
625      destination: options.destination,
626      destination_directory: dest_dir,
627      site_directory: site_dir,
628      source: options.source,
629      source_directory: options.source_directory,
630      searchpaths: options.searchpaths.unwrap_or_default(),
631      namespaces,
632      namespace_uris,
633      idcache: HashMap::default(),
634      idcache_reusable: HashMap::default(),
635      idcache_reserve: HashMap::default(),
636      idcache_clashes: HashMap::default(),
637      processing_instructions: Vec::new(),
638      parent_document: None,
639      split_from_id: None,
640      parent_id: None,
641      validate: options.validate,
642      cache: options
643        .cache
644        .unwrap_or_else(|| DocCache::new(options.nocache)),
645      nocache: options.nocache,
646      pending_xmath_unlinks: Vec::new(),
647      nav_memo: None,
648      compiled_xpath: std::cell::RefCell::default(),
649    }
650  }
651
652  /// Record namespace declarations from the root element (O(1) on the root).
653  fn register_root_namespaces(&mut self) {
654    if let Some(root) = self.document.get_root_element() {
655      let ns_decls = root.get_namespace_declarations();
656      for ns in ns_decls {
657        let prefix = ns.get_prefix();
658        if !prefix.is_empty() {
659          let href = ns.get_href();
660          self
661            .namespaces
662            .entry(prefix.clone())
663            .or_insert_with(|| href.clone());
664          self.namespace_uris.entry(href).or_insert(prefix);
665        }
666      }
667    }
668  }
669
670  /// Initialize document internals: scan IDs, extract namespaces and PIs.
671  fn set_document_internal(&mut self) {
672    // Record every `xml:id` and `<?latexml …?>` PI in one limit-safe walk (see
673    // `scan_ids_and_pis`), replacing the `//*[@xml:id]` and
674    // `.//processing-instruction('latexml')` queries that returned NULL past the
675    // 10M node-set ceiling — silently building an empty idcache (breaking every
676    // cross-reference) and dropping the searchpath PIs. Walk from the document
677    // node so PIs preceding the root are caught.
678    let mut ids: Vec<(String, Node)> = Vec::new();
679    let mut pis: Vec<String> = Vec::new();
680    scan_ids_and_pis(&self.document.as_node(), &mut ids, &mut pis);
681    for (id, node) in ids {
682      self.idcache.insert(id, node);
683    }
684    self.processing_instructions = pis;
685
686    // Extract namespaces from root element
687    self.register_root_namespaces();
688
689    // Extract search paths from PIs
690    static SP_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
691      regex::Regex::new(r#"^\s*searchpaths\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap()
692    });
693    let sp_re = &*SP_RE;
694    let mut paths = self.searchpaths.clone();
695    for pi_text in &self.processing_instructions {
696      if let Some(cap) = sp_re.captures(pi_text) {
697        for p in cap[1].split(',') {
698          paths.push(p.trim().to_string());
699        }
700      }
701    }
702    paths.push(".".to_string());
703    self.searchpaths = paths;
704  }
705
706  // ======================================================================
707  // Constructors from various sources
708
709  /// Create from an XML file.
710  ///
711  /// Port of `Post::Document::newFromFile`.
712  ///
713  /// Parses with `XML_PARSE_HUGE` (on top of the crate's default
714  /// recover/noerror/nowarning): without it, libxml2's hard limits corrupt a
715  /// multi-GB parse well before any real malformation — the per-document
716  /// dictionary cap poisons the ID table (hundreds of thousands of bogus
717  /// "ID X already defined" reports for ids that occur exactly once,
718  /// witnessed at ~1.47 GB into the 131 MB book's core XML) and the parse
719  /// dies outright at ~1.71 GB. Post input is our own core serialization,
720  /// not attacker-authored XML, so relaxing the limits is safe.
721  pub fn new_from_file(path: &str, options: PostDocumentOptions) -> Result<Self, String> {
722    let parser = XmlParser::default();
723    let doc = parser
724      .parse_file_with_options(path, huge_parse_options())
725      .map_err(|e| format!("Failed to parse '{}': {}", path, e))?;
726    expand_entity_references(&doc);
727    Ok(Self::new(doc, Self::file_options(path, options)))
728  }
729
730  /// The options [`Self::new_from_file`] gives a document read from `path`: `source` is the file and
731  /// `source_directory` its directory, unless already set.
732  pub fn file_options(path: &str, options: PostDocumentOptions) -> PostDocumentOptions {
733    let mut opts = options;
734    if opts.source.is_none() {
735      opts.source = Some(path.to_string());
736    }
737    if opts.source_directory.is_none() {
738      if let Some(parent) = Path::new(path).parent() {
739        opts.source_directory = Some(parent.to_string_lossy().to_string());
740      }
741    }
742    opts
743  }
744
745  /// Give up this wrapper and return its XML document, as [`Self::new`] received it plus any changes made
746  /// since; the wrapper's caches (ids, namespaces, memos) are dropped with it.
747  pub fn into_document(mut self) -> Document {
748    std::mem::replace(
749      &mut self.document,
750      Document::new().expect("libxml2 could not allocate an empty document"),
751    )
752  }
753
754  /// Create from an XML string.
755  ///
756  /// Port of `Post::Document::newFromString`.
757  pub fn new_from_string(xml: &str, options: PostDocumentOptions) -> Result<Self, String> {
758    let parser = XmlParser::default();
759    let doc = parser
760      .parse_string_with_options(xml, huge_parse_options())
761      .map_err(|e| format!("Failed to parse XML string: {}", e))?;
762    expand_entity_references(&doc);
763    let mut opts = options;
764    if opts.source_directory.is_none() {
765      opts.source_directory = Some(".".to_string());
766    }
767    Ok(Self::new(doc, opts))
768  }
769
770  /// Create a new sub-document from an element node.
771  ///
772  /// Port of Perl `Post::Document::newDocument`.
773  /// The element is imported into a fresh XML document.
774  /// Resources, processing instructions, and class attributes are copied from the parent.
775  /// `parent_id` is Perl's `parent_id` option (Split.pm:132-133). Perl's Element-root default
776  /// (Post.pm:833-834, `ancestor::*[@id]`) is not ported: Split has unlinked the page by then.
777  pub fn new_document(&self, root: Node, destination: &str, parent_id: Option<String>) -> Self {
778    use libxml::tree::Document as XmlDocument;
779    // Create a fresh XML document that owns a deep copy of `root`'s
780    // subtree as its root element.
781    //
782    // Perl Post.pm L831-839: `XML::LibXML::Document->new(...)` then
783    // `setDocumentElement($doc->importNode($root))`. importNode COPIES
784    // the subtree into the new doc; the new doc and the source no
785    // longer share C-side state.
786    //
787    // We use libxml-rs's `Document::dup_node_into_new_doc` (added in
788    // KWARC/rust-libxml `clone-document` branch). The earlier
789    // `import_node` route had two pitfalls that made it unusable for
790    // the Split.process_pages loop:
791    //   1. `import_node` gates on `Node::is_unlinked()`, a wrapper- side flag with no public
792    //      setter; the gate leaks `false` across iterations because the previous call's
793    //      set_linked() mutated the wrapper Rc, forcing every page after the first to Err.
794    //   2. Direct `xmlDocCopyNode(src, dst, 1)` returns NULL on the second sibling page — the first
795    //      recursive copy dirties dict/ns state on the source doc such that subsequent recursive
796    //      copies fail their child-copy phase (verified: extended=2 still works, isolating the
797    //      failure to recursive descent).
798    // dup_node_into_new_doc avoids both: it does
799    // `xmlCopyNode(node, 1)` (orphan deep copy, no source-doc state
800    // mutation), plants the copy into a freshly created xmlDoc, fixes
801    // up doc pointers via xmlSetTreeDoc, and reconciles namespaces.
802    // The returned Document shares zero C-side state with the source.
803    //
804    // SCOPE: this method is only called from `Split::process_pages`, which
805    // frees `root` once it is copied (unless it holds a navigation); non-split
806    // flows do not pay the deep-copy cost.
807    let new_xml_doc: XmlDocument = XmlDocument::dup_node_into_new_doc(&root)
808      .expect("dup_node_into_new_doc returned NULL while creating split sub-document");
809    let _ = root;
810
811    let opts = PostDocumentOptions {
812      destination: Some(destination.to_string()),
813      // CRITICAL: inherit the parent's site_directory so the sub-doc's
814      // `site_relative_destination` carries any intermediate split
815      // directory (e.g. "Ch1/schema.scholarly-ltx.html") into DB
816      // location strings. Without this, every sub-doc defaults
817      // site_directory to its own destination_directory, which makes
818      // every per-doc `location` resolve to just the basename and
819      // CrossRef::generate_url then produces broken in-page anchors
820      // instead of the cross-doc relative URLs that the rendered TOC
821      // is supposed to walk.
822      site_directory: self.site_directory.clone(),
823      source: self.source.clone(),
824      source_directory: self.source_directory.clone(),
825      searchpaths: Some(self.searchpaths.clone()),
826      // The parent's cache, as Perl's `new_internal` clones it (`Post.pm` L687-690).
827      nocache: self.nocache,
828      cache: Some(self.cache.clone()),
829      ..PostDocumentOptions::default()
830    };
831    let mut subdoc = Self::new_internal(new_xml_doc, opts);
832    subdoc.parent_id = parent_id;
833
834    // Copy namespaces
835    subdoc.namespaces = self.namespaces.clone();
836    subdoc.namespace_uris = self.namespace_uris.clone();
837
838    // Record IDs
839    for node in subdoc.findnodes("//*[@xml:id]") {
840      if let Some(id) = get_xml_id(&node) {
841        subdoc.idcache.insert(id, node);
842      }
843    }
844
845    // Record the parent document's root ID
846    if let Some(ref root_el) = self.get_document_element() {
847      if let Some(root_id) = get_xml_id(root_el) {
848        subdoc.split_from_id = Some(root_id);
849      }
850    }
851
852    // Copy processing instructions (Perl Post.pm L766-767).
853    // ABSOLUTE `//…`: `findnodes` with no context node can't evaluate a relative
854    // axis (see `findnodes_at`) — a `.//processing-instruction(...)` here matched
855    // nothing and split children lost the `<?latexml …?>` PIs (#341). Made afresh, not
856    // `import_node`d: that refuses a linked node, so every page lost them again (#795).
857    // Before the root, as on the main page; Perl appends them after it (`appendChild`).
858    if let Some(mut root) = subdoc.document.get_root_element() {
859      for pi in self.findnodes("//processing-instruction('latexml')") {
860        if let Ok(mut copy) = subdoc
861          .document
862          .create_processing_instruction(&pi.get_name(), &pi.get_content())
863        {
864          root.add_prev_sibling(&mut copy).ok();
865        }
866      }
867    }
868
869    // Copy resource elements (Perl Post.pm L770-771: addNodes for ltx:resource).
870    // ABSOLUTE `//ltx:resource` for the same reason as the PIs above — the old
871    // `descendant::ltx:resource` matched nothing, so split children dropped the
872    // default `LaTeXML.css`/`ltx-book.css` `<link>`s (#341).
873    let resources: Vec<NodeData> = self
874      .findnodes("//ltx:resource")
875      .iter()
876      .map(|r| NodeData::XmlNode(r.clone()))
877      .collect();
878    if !resources.is_empty() {
879      if let Some(mut doc_root) = subdoc.get_document_element() {
880        subdoc.add_nodes(&mut doc_root, &resources);
881      }
882    }
883
884    // If the new document has no date, copy the parent's (Perl Post.pm L774 →
885    // `addDate`, L866-873): when the child's document element has no direct
886    // `ltx:date` child, copy the parent document element's direct `ltx:date`
887    // children. `ltx:date` is a relative (child-axis) path, so it MUST be
888    // evaluated with the document element as an explicit context node —
889    // `findnodes` with no context node can't do relative axes (see above).
890    if let Some(sub_root) = subdoc.get_document_element() {
891      if subdoc.findnodes_at("ltx:date", Some(&sub_root)).is_empty() {
892        if let Some(parent_root) = self.get_document_element() {
893          let dates: Vec<NodeData> = self
894            .findnodes_at("ltx:date", Some(&parent_root))
895            .iter()
896            .map(|d| NodeData::XmlNode(d.clone()))
897            .collect();
898          if !dates.is_empty() {
899            let mut sub_root_mut = sub_root;
900            subdoc.add_nodes(&mut sub_root_mut, &dates);
901          }
902        }
903      }
904    }
905
906    // Copy class from top-level document element (Perl Post.pm L779-782).
907    if let Some(parent_root) = self.get_document_element() {
908      if let Some(pclass) = parent_root.get_attribute("class") {
909        if let Some(mut doc_root) = subdoc.get_document_element() {
910          let existing = doc_root.get_attribute("class").unwrap_or_default();
911          if existing.is_empty() {
912            doc_root.set_attribute("class", &pclass).ok();
913          } else {
914            doc_root
915              .set_attribute("class", &format!("{} {}", existing, pclass))
916              .ok();
917          }
918        }
919      }
920    }
921
922    subdoc
923  }
924
925  // ======================================================================
926  // Accessors
927
928  /// Get a reference to the underlying XML document.
929  pub fn get_document(&self) -> &Document { &self.document }
930
931  /// Get a mutable reference to the underlying XML document.
932  pub fn get_document_mut(&mut self) -> &mut Document { &mut self.document }
933
934  /// Get the document's root element.
935  pub fn get_document_element(&self) -> Option<Node> { self.document.get_root_element() }
936
937  /// Get the source path.
938  pub fn get_source(&self) -> Option<&str> { self.source.as_deref() }
939
940  /// Get the source directory.
941  pub fn get_source_directory(&self) -> &str { self.source_directory.as_deref().unwrap_or(".") }
942
943  /// Get search paths.
944  pub fn get_search_paths(&self) -> &[String] { &self.searchpaths }
945
946  /// Get the destination path.
947  pub fn get_destination(&self) -> Option<&str> { self.destination.as_deref() }
948
949  /// Get the destination directory.
950  pub fn get_destination_directory(&self) -> Option<&str> { self.destination_directory.as_deref() }
951
952  /// Get the site directory.
953  pub fn get_site_directory(&self) -> Option<&str> { self.site_directory.as_deref() }
954
955  /// Return destination relative to site directory.
956  ///
957  /// Port of `siteRelativeDestination`.
958  pub fn site_relative_destination(&self) -> Option<String> {
959    if let (Some(dest), Some(site)) = (&self.destination, &self.site_directory) {
960      Some(pathdiff(dest, site))
961    } else {
962      self.destination.clone()
963    }
964  }
965
966  /// Return a pathname relative to the site directory.
967  pub fn site_relative_pathname(&self, pathname: &str) -> Option<String> {
968    self
969      .site_directory
970      .as_ref()
971      .map(|site| pathdiff(pathname, site))
972  }
973
974  /// Get the destination file extension.
975  pub fn get_destination_extension(&self) -> Option<String> {
976    self.destination.as_ref().and_then(|d| {
977      Path::new(d)
978        .extension()
979        .map(|e| e.to_string_lossy().to_string())
980    })
981  }
982
983  /// Serialize the document to an XML string.
984  pub fn to_xml_string(&self) -> String { self.document.to_string() }
985
986  /// Serialize a single node (and its subtree) to an XML string. Used to
987  /// re-derive raw-string features (e.g. SVG-fragment extraction) from the DOM
988  /// for file-parsed input without ever materializing the whole document.
989  pub fn node_to_string(&self, node: &Node) -> String { self.document.node_to_string(node) }
990
991  /// The `<?latexml …?>` processing instructions collected at parse time
992  /// (searchpaths, loaded packages/classes, RelaxNG schema, …). Used to
993  /// re-derive package-presence sniffs (e.g. `package="ar5iv"`) from the parsed
994  /// document when the raw XML string is not held in memory.
995  pub fn processing_instructions(&self) -> &[String] { &self.processing_instructions }
996
997  pub fn stringify(&self) -> String {
998    format!(
999      "Post::Document[{}]",
1000      self
1001        .site_relative_destination()
1002        .unwrap_or_else(|| "?".to_string())
1003    )
1004  }
1005
1006  // ======================================================================
1007  // XPath queries
1008
1009  /// Find nodes matching an XPath expression.
1010  ///
1011  /// Port of `Post::Document::findnodes`.
1012  pub fn findnodes(&self, xpath: &str) -> Vec<Node> { self.findnodes_at(xpath, None) }
1013
1014  /// Find nodes matching an XPath expression, relative to a given context node.
1015  pub fn findnodes_at(&self, xpath: &str, context_node: Option<&Node>) -> Vec<Node> {
1016    // Bind the XPath context to the CONTEXT NODE's own document when one is
1017    // given — matching XML::LibXML's `XPathContext->findnodes($xpath, $refnode)`,
1018    // which resets `ctx->doc = refnode->doc` and so evaluates in the refnode's
1019    // document. rust-libxml's `xmlXPathNodeEval` instead REQUIRES
1020    // `node->doc == ctx->doc` and returns NULL otherwise (via `xmlXPathSetContextNode`),
1021    // so a context node from a *different* document — e.g. an `ltx:bibentry`
1022    // loaded from an external `.bib.xml` in MakeBibliography — made
1023    // `node_evaluate_checked` report a spurious "XPath evaluation failed" for
1024    // every `ltx:bib-name[...]/ltx:surname` probe: a post:xpath warning flood,
1025    // *and* the surnames were never matched (the old plain-eval path silently
1026    // swallowed the NULL as no-match). `Context::from_node` evaluates in the
1027    // node's own document, exactly as Perl does. Same-document callers are
1028    // unaffected (from_node then binds to self.document).
1029    // Whole-document and subtree `NAME[pred]` shapes are answered by a read-only walk (`xml_walk`), never by a
1030    // materialized node-set: as XPath they cost O(document) memory and trip libxml2's 10M node-set ceiling, which
1031    // returns NULL (measured: six such queries failed on a 614 MB core XML and post wrote a 0-byte file while
1032    // exiting 0). A shape outside the walk's grammar, or a context in another document, is evaluated below.
1033    if let Some(query) = WalkQuery::parse(xpath)
1034      && let Some(found) = query.find(&self.document, context_node)
1035    {
1036      return found;
1037    }
1038    let ctx = match context_node {
1039      Some(node) => XPathContext::from_node(node),
1040      None => XPathContext::new(&self.document),
1041    };
1042    let ctx = match ctx {
1043      Ok(c) => c,
1044      Err(_) => return vec![],
1045    };
1046
1047    // Register all known namespaces
1048    for (prefix, uri) in &self.namespaces {
1049      let _ = ctx.register_namespace(prefix, uri);
1050    }
1051
1052    // *_checked so a NULL result — libxml2 aborting, typically a `//X[pred]`
1053    // query overflowing the 10M node-set ceiling on a huge document — is logged
1054    // instead of silently becoming an empty `vec![]` that corrupts downstream
1055    // passes. An empty match set is still `Ok`, so this fires only on a real
1056    // abort (CLAUDE.md: fail toward flagging errors).
1057
1058    // (the borrow of the compiled table ends with the evaluation, before any diagnostic below)
1059    let result = {
1060      let mut compiled = self.compiled_xpath.borrow_mut();
1061      let expression = compiled_xpath(&mut compiled, xpath);
1062      let at_node = |node: &Node| match expression {
1063        Some(expression) => ctx.node_evaluate_compiled(expression, node),
1064        None => ctx.node_evaluate_checked(xpath, node),
1065      };
1066      if let Some(node) = context_node {
1067        at_node(node)
1068      } else {
1069        // Perl `$doc->findnodes($xpath)` (no ref node) evaluates from the DOCUMENT
1070        // NODE, so RELATIVE location paths (`descendant::…`, `.//…`, `child::…`)
1071        // resolve against the whole tree. rust-libxml's bare `evaluate_checked`
1072        // leaves the XPath context node UNSET, so relative axes silently matched
1073        // NOTHING (only absolute `//…`/`/…` worked) — which broke, among others,
1074        // `new_document`'s split-page resource/PI copy (#341), `Split`'s
1075        // `descendant::ltx:navigation`, and CrossRef's `descendant::ltx:glossaryref`.
1076        // We cannot bind the document node itself: rust-libxml's `node_evaluate`
1077        // SIGSEGVs on a document-node context (an unguarded FFI path in the fork).
1078        // The root ELEMENT is a safe context and makes relative axes resolve for
1079        // everything inside the tree. NOTE: nodes OUTSIDE the root element — i.e.
1080        // `<?latexml …?>` PIs that precede it — are not descendants of the root, so
1081        // a relative PI query still needs the absolute `//processing-instruction()`
1082        // form; absolute paths are unaffected by the context node either way.
1083        match self.document.get_root_element() {
1084          Some(root) => at_node(&root),
1085          None => match expression {
1086            Some(expression) => ctx.evaluate_compiled(expression),
1087            None => ctx.evaluate_checked(xpath),
1088          },
1089        }
1090      }
1091    };
1092
1093    match result {
1094      Ok(obj) => obj.get_nodes_as_vec(),
1095      Err(e) => {
1096        end_on_libxml_oom(xpath, &e);
1097        // NOT a warning, and NOT "no matches": an evaluation that could not be
1098        // answered is a failure to know, and downstream passes that treat it as
1099        // an empty set silently drop content (CLAUDE.md: fail toward flagging
1100        // errors). Raising it as an Error puts it in the tally and the exit
1101        // code, so a run like the 0-byte-HTML one cannot report success.
1102        Error!(
1103          "post",
1104          "xpath",
1105          "XPath evaluation failed for `{}`: {} — results are INCOMPLETE for this pass",
1106          xpath,
1107          e
1108        );
1109        vec![]
1110      },
1111    }
1112  }
1113
1114  /// Limit-safe evaluation of a `--splitat` page union.
1115  ///
1116  /// `make_splitpaths` emits `//ltx:X` and
1117  /// `//ltx:X[preceding-sibling::ltx:Y or parent::ltx:Z]` arms. As XPath on a
1118  /// huge document the predicated arms overflow the 10M node-set ceiling (see
1119  /// `scan_ids_and_pis`), the union returns NULL, and nothing splits — the
1120  /// whole document stays one page and the downstream XSLT then dies on the same
1121  /// ceiling. Instead we parse the arms and select pages with one limit-safe
1122  /// walk, applying the predicates in Rust: same nodes, document order, no
1123  /// duplicates, as an XPath union.
1124  ///
1125  /// Falls back to raw XPath for unions outside that grammar (custom
1126  /// `--splitpaths`), which only run on small, limit-safe documents.
1127  pub fn find_split_pages(&self, union_xpath: &str) -> Vec<Node> {
1128    let arms = match parse_split_union(union_xpath) {
1129      Some(a) => a,
1130      None => return self.findnodes(union_xpath),
1131    };
1132    let mut pages = Vec::new();
1133    collect_split_pages(&self.document.as_node(), &arms, &mut pages);
1134    pages
1135  }
1136
1137  /// Find the first node matching an XPath expression.
1138  pub fn findnode(&self, xpath: &str) -> Option<Node> {
1139    if let Some(first) = WalkQuery::parse(xpath).and_then(|q| q.find_first(&self.document, None)) {
1140      return first;
1141    }
1142    self.findnodes(xpath).into_iter().next()
1143  }
1144
1145  /// Find the first node matching an XPath expression, relative to a context node.
1146  pub fn findnode_at(&self, xpath: &str, context_node: &Node) -> Option<Node> {
1147    if let Some(first) =
1148      WalkQuery::parse(xpath).and_then(|q| q.find_first(&self.document, Some(context_node)))
1149    {
1150      return first;
1151    }
1152    self
1153      .findnodes_at(xpath, Some(context_node))
1154      .into_iter()
1155      .next()
1156  }
1157
1158  /// Evaluate an XPath expression and return the string value.
1159  pub fn findvalue(&self, xpath: &str) -> Option<String> {
1160    let ctx = XPathContext::new(&self.document).ok()?;
1161    for (prefix, uri) in &self.namespaces {
1162      let _ = ctx.register_namespace(prefix, uri);
1163    }
1164    let mut compiled = self.compiled_xpath.borrow_mut();
1165    match compiled_xpath(&mut compiled, xpath) {
1166      Some(expression) => ctx.evaluate_compiled(expression).ok(),
1167      None => ctx.evaluate(xpath).ok(),
1168    }
1169    .map(|obj| obj.to_string())
1170  }
1171
1172  /// XPath query relative to a node of any document — Perl's
1173  /// `$XPATH->findnodes($path, $node)` (Post.pm:1019-1021), with the `ltx`
1174  /// prefix bound. Like [`Self::findnodes_at`], it evaluates in the node's own
1175  /// document (a bibentry of a loaded `.bib.xml`), so every XPath form
1176  /// applies, including MakeBibliography's
1177  /// `ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]` fields
1178  /// (MakeBibliography.pm:732) and `.//ltx:ERROR[@class='sort']`. An
1179  /// evaluation that fails is an Error, not an empty match.
1180  pub fn findnodes_foreign(xpath: &str, node: &Node) -> Vec<Node> {
1181    let ctx = match XPathContext::from_node(node) {
1182      Ok(c) => c,
1183      Err(_) => return vec![],
1184    };
1185    let _ = ctx.register_namespace("ltx", LTX_NSURI);
1186    match ctx.node_evaluate_checked(xpath, node) {
1187      Ok(obj) => obj.get_nodes_as_vec(),
1188      Err(e) => {
1189        end_on_libxml_oom(xpath, &e);
1190        Error!(
1191          "post",
1192          "xpath",
1193          "XPath evaluation failed for `{}`: {} — results are INCOMPLETE for this pass",
1194          xpath,
1195          e
1196        );
1197        vec![]
1198      },
1199    }
1200  }
1201
1202  // ======================================================================
1203  // Namespace management
1204
1205  /// Register a new namespace prefix → URI mapping.
1206  ///
1207  /// Port of `Post::Document::addNamespace`.
1208  pub fn add_namespace(&mut self, prefix: &str, nsuri: &str) {
1209    let dominated = self
1210      .namespaces
1211      .get(prefix)
1212      .map(|u| u == nsuri)
1213      .unwrap_or(false);
1214    if !dominated {
1215      self
1216        .namespaces
1217        .insert(prefix.to_string(), nsuri.to_string());
1218      self
1219        .namespace_uris
1220        .insert(nsuri.to_string(), prefix.to_string());
1221      // Declare the namespace on the root element (without changing its own namespace).
1222      // Namespace::new() creates the declaration; we do NOT call set_namespace()
1223      // which would change the root element's own namespace.
1224      if let Some(mut root) = self.document.get_root_element() {
1225        let _ = Namespace::new(prefix, nsuri, &mut root);
1226      }
1227    }
1228  }
1229
1230  /// Get the qualified name (prefix:localname) for a node.
1231  ///
1232  /// Port of `Post::Document::getQName`.
1233  pub fn get_qname(&self, node: &Node) -> Option<String> {
1234    if node.get_type() != Some(NodeType::ElementNode) {
1235      return None;
1236    }
1237    let node = node.as_readonly();
1238    node.with_name(|localname| {
1239      node.with_namespace_href(|href| match href {
1240        Some(nsuri) => {
1241          if let Some(prefix) = self.namespace_uris.get(nsuri) {
1242            Some(format!("{}:{}", prefix, localname))
1243          } else {
1244            // Auto-generate a prefix for unknown namespaces
1245            let n = self
1246              .namespaces
1247              .keys()
1248              .filter(|k| k.starts_with("_ns"))
1249              .count()
1250              + 1;
1251            Some(format!("_ns{}:{}", n, localname))
1252          }
1253        },
1254        None => Some(localname.to_owned()),
1255      })
1256    })
1257  }
1258
1259  /// Resolve a node's namespace URI to its registered prefix without
1260  /// allocating a combined "prefix:localname". Returns the prefix as an
1261  /// owned `String` (a copy of the entry in `namespace_uris`); callers
1262  /// can then match on `node.get_name()` separately. Useful in hot
1263  /// dispatch code where the `format!` in `get_qname` is the cost.
1264  pub fn qname_prefix(&self, node: &Node) -> Option<String> {
1265    if node.get_type() != Some(NodeType::ElementNode) {
1266      return None;
1267    }
1268    node
1269      .as_readonly()
1270      .with_namespace_href(|href| href.and_then(|nsuri| self.namespace_uris.get(nsuri).cloned()))
1271  }
1272
1273  /// Check whether a node's qualified name equals a fixed "prefix:localname"
1274  /// string without allocating a `String`. Fast-path for hot comparisons
1275  /// like `is_qname(node, "ltx:XMApp")` — avoids the `format!` in
1276  /// `get_qname` when the caller only needs a boolean answer. Falls back
1277  /// to allocating comparison (via `get_qname`) for unknown-namespace
1278  /// cases so semantics exactly match `get_qname(node).as_deref() == Some(...)`.
1279  pub fn is_qname(&self, node: &Node, expected: &str) -> bool {
1280    if node.get_type() != Some(NodeType::ElementNode) {
1281      return false;
1282    }
1283    let (expected_prefix, expected_local) = match expected.split_once(':') {
1284      Some((p, l)) => (Some(p), l),
1285      None => (None, expected),
1286    };
1287    let node = node.as_readonly();
1288    if !node.with_name(|localname| localname == expected_local) {
1289      return false;
1290    }
1291    node.with_namespace_href(|href| match (href, expected_prefix) {
1292      (Some(nsuri), Some(ep)) => self
1293        .namespace_uris
1294        .get(nsuri)
1295        .map(|p| p == ep)
1296        .unwrap_or(false),
1297      (None, None) => true,
1298      _ => false,
1299    })
1300  }
1301
1302  // ======================================================================
1303  // ID management
1304
1305  /// Record an ID → node mapping.
1306  ///
1307  /// Port of `Post::Document::recordID`.
1308  pub fn record_id(&mut self, id: &str, node: Node) {
1309    self.idcache.insert(id.to_string(), node);
1310    self.idcache_reserve.remove(id);
1311    self.idcache_reusable.remove(id);
1312  }
1313
1314  /// Take `node`'s `xml:id` off it and out of the idcache, freeing the id for
1315  /// another element. Returns the id it had.
1316  pub fn release_id(&mut self, node: &mut Node) -> Option<String> {
1317    let id = get_xml_id(node)?;
1318    self.idcache.remove(&id);
1319    let _ = node.remove_attribute_ns("id", "http://www.w3.org/XML/1998/namespace");
1320    Some(id)
1321  }
1322
1323  /// Find a node by its xml:id.
1324  ///
1325  /// Port of `Post::Document::findNodeByID`.
1326  pub fn find_node_by_id(&self, id: &str) -> Option<&Node> { self.idcache.get(id) }
1327
1328  /// Number of id-bearing nodes registered in this document's idcache.
1329  /// This is exactly the node set Perl's `//@xml:id` iterates.
1330  pub fn idcache_len(&self) -> usize { self.idcache.len() }
1331
1332  /// Iterate `(id, node)` for every id-bearing node in this document, in
1333  /// arbitrary order. Mirrors Perl's `//@xml:id` traversal (per-document,
1334  /// so bounded by the page size rather than the global ObjectDB).
1335  pub fn idcache_iter(&self) -> impl Iterator<Item = (&String, &Node)> { self.idcache.iter() }
1336
1337  /// Generate a unique ID based on `baseid`, optionally applying a suffix.
1338  ///
1339  /// If the resulting ID is already used (and not marked reusable),
1340  /// appends alphabetic suffixes (a, b, c, ...) until unique.
1341  ///
1342  /// Port of `Post::Document::uniquifyID`.
1343  pub fn uniquify_id(&mut self, baseid: &str, suffix: Option<&str>) -> String {
1344    let apply_suffix = |id: &str, sfx: Option<&str>| -> String {
1345      if let Some(s) = sfx {
1346        format!("{}{}", id, s)
1347      } else {
1348        id.to_string()
1349      }
1350    };
1351
1352    let mut id = apply_suffix(baseid, suffix);
1353    let cachekey = id.clone();
1354
1355    while (self.idcache.contains_key(&id) || self.idcache_reserve.contains_key(&id))
1356      && !self.idcache_reusable.contains_key(&id)
1357    {
1358      let clash_count = self.idcache_clashes.entry(cachekey.clone()).or_insert(0);
1359      *clash_count += 1;
1360      id = apply_suffix(&format!("{}{}", baseid, radix_alpha(*clash_count)), suffix);
1361    }
1362
1363    self.idcache_reusable.remove(&id);
1364    self.idcache_reserve.insert(id.clone(), true);
1365    id
1366  }
1367
1368  /// Generate, add, and register an xml:id for a node.
1369  ///
1370  /// Creates a structured ID relative to the nearest parent with an ID.
1371  ///
1372  /// Port of `Post::Document::generateNodeID`.
1373  pub fn generate_node_id(
1374    &mut self,
1375    node: &mut Node,
1376    prefix: &str,
1377    reusable: bool,
1378  ) -> Option<String> {
1379    if let Some(id) = get_xml_id(node) {
1380      return Some(id);
1381    }
1382
1383    // Find the closest parent with an ID (NS-aware — the bare read always
1384    // missed, so generated ids silently lost their parent prefix, e.g.
1385    // "fn1" instead of "S2.fn1")
1386    let mut parent_node = node.get_parent();
1387    let mut pid = String::new();
1388    while let Some(ref p) = parent_node {
1389      if let Some(id) = get_xml_id(p) {
1390        pid = id;
1391        break;
1392      }
1393      parent_node = p.get_parent();
1394    }
1395
1396    if !pid.is_empty() {
1397      pid.push('.');
1398    }
1399
1400    // Find the next unused ID
1401    let mut n = 1u32;
1402    let id = loop {
1403      let candidate = format!("{}{}{}", pid, prefix, n);
1404      if !self.idcache.contains_key(&candidate) && !self.idcache_reserve.contains_key(&candidate) {
1405        break candidate;
1406      }
1407      n += 1;
1408    };
1409
1410    node.set_attribute("xml:id", &id).ok();
1411    let node_copy = node.clone();
1412    self.idcache.insert(id.clone(), node_copy);
1413    if reusable {
1414      self.idcache_reusable.insert(id.clone(), true);
1415    }
1416
1417    // If the parent has a fragid, create one here too
1418    if let Some(ref p) = parent_node {
1419      if p.has_attribute("fragid") {
1420        let new_fragid = format!("{}.{}{}", p.get_attribute("fragid").unwrap(), prefix, n);
1421        node.set_attribute("fragid", &new_fragid).ok();
1422      }
1423    }
1424
1425    Some(id)
1426  }
1427
1428  // ======================================================================
1429  // Node manipulation
1430
1431  /// Add nodes to `parent` using the recursive representation.
1432  ///
1433  /// Port of `Post::Document::addNodes`.
1434  pub fn add_nodes(&mut self, parent: &mut Node, data: &[NodeData]) {
1435    for child in data {
1436      match child {
1437        NodeData::Text(text) => {
1438          parent.append_text(text).ok();
1439        },
1440        NodeData::Element { tag, attributes, children } => {
1441          // Belt-and-suspenders invariant: never materialize an empty
1442          // `<mi></mi>`. `<mi>` is a semantic assertion ("here is an
1443          // identifier") with no defined meaning when empty — renderers
1444          // vary, screen readers announce "blank", search/indexing
1445          // tools pollute their indexes. The right placeholder is
1446          // `<mrow></mrow>` (presentational, no semantic claim).
1447          // Catches any future code path that re-introduces the
1448          // antipattern via a different route. Task #264.
1449          debug_assert!(
1450            !((tag == "m:mi" || tag == "mi") && children.is_empty()),
1451            "Empty <mi></mi> detected at materialization — use <mrow></mrow> \
1452             scaffolding instead; see task #264 in docs/SYNC_STATUS.md"
1453          );
1454          if tag == "_Fragment_" {
1455            self.add_nodes(parent, children);
1456          } else if let Some((prefix, localname)) = tag.split_once(':') {
1457            let nsuri = self.namespaces.get(prefix).cloned();
1458            if nsuri.is_none() {
1459              Warn!("malformed", "namespace", "No namespace on '{}'", tag);
1460            }
1461            // Find or create namespace for this prefix.
1462            // Prefer the default namespace (empty prefix) if it matches the target URI,
1463            // so elements like ltx:ref are created as <ref> not <ltx:ref>.
1464            let ns = nsuri.and_then(|uri| {
1465              // First check if the default namespace matches — prefer it to avoid ltx: prefix
1466              parent
1467                .get_namespace_declarations()
1468                .into_iter()
1469                .find(|ns| ns.get_prefix().is_empty() && ns.get_href() == uri)
1470                .or_else(|| {
1471                  parent
1472                    .get_namespaces(&self.document)
1473                    .into_iter()
1474                    .find(|ns| ns.get_prefix().is_empty() && ns.get_href() == uri)
1475                })
1476                // Fall back to matching prefix
1477                .or_else(|| {
1478                  parent
1479                    .get_namespace_declarations()
1480                    .into_iter()
1481                    .find(|ns| ns.get_prefix() == prefix)
1482                })
1483                .or_else(|| {
1484                  parent
1485                    .get_namespaces(&self.document)
1486                    .into_iter()
1487                    .find(|ns| ns.get_prefix() == prefix)
1488                })
1489                .or_else(|| {
1490                  // Create a new declaration
1491                  Namespace::new(prefix, &uri, parent).ok()
1492                })
1493            });
1494            if let Ok(mut new_node) = parent.new_child(ns, localname) {
1495              // Set attributes
1496              if let Some(attrs) = attributes {
1497                let mut sorted_keys: Vec<_> = attrs.keys().collect();
1498                sorted_keys.sort();
1499                for key in sorted_keys {
1500                  let value = &attrs[key];
1501                  if key.starts_with('_') {
1502                    continue;
1503                  }
1504                  if key == "xml:id" {
1505                    let id = if self.idcache.contains_key(value.as_str()) {
1506                      self.uniquify_id(value, None)
1507                    } else {
1508                      value.clone()
1509                    };
1510                    self.record_id(&id, new_node.clone());
1511                    new_node.set_attribute("xml:id", &id).ok();
1512                  } else {
1513                    new_node.set_attribute(key, value).ok();
1514                  }
1515                }
1516              }
1517              self.add_nodes(&mut new_node, children);
1518            }
1519          } else {
1520            Warn!(
1521              "malformed",
1522              "namespace",
1523              "Tag '{}' has no namespace prefix",
1524              tag
1525            );
1526          }
1527        },
1528        NodeData::XmlNode(source_node) => {
1529          self.append_clone(parent, source_node);
1530        },
1531      }
1532    }
1533  }
1534
1535  /// Deep-clone an existing node subtree and append it under `parent`, giving
1536  /// the copy fresh (non-clashing) ids — the faithful equivalent of Perl
1537  /// `Post::Document::cloneNode` + insert.
1538  ///
1539  /// [`clone_subtree`](Self::clone_subtree) does the structural deep copy and
1540  /// uniquifies every `xml:id` inline (remapping each node's own `fragid`),
1541  /// recording old→new in `idmap`. This pass then remaps `idref` attributes
1542  /// through that map and drops `labels`, mirroring Perl `cloneNode`
1543  /// (`Post.pm` L1256-1287). Uniquification matters because the source stays
1544  /// in the tree: e.g. a section-title `<ltx:Math xml:id=…>` cloned into the
1545  /// table of contents must not duplicate the body copy's id (issue #356) —
1546  /// the HTML `id` is emitted from `fragid` by the XSLT `add_id` template, so
1547  /// `fragid` must be remapped too.
1548  fn append_clone(&mut self, parent: &mut Node, source: &Node) {
1549    let mut idmap: HashMap<String, String> = HashMap::default();
1550    let Some(root) = self.clone_subtree(parent, source, &mut idmap) else {
1551      return;
1552    };
1553    if !idmap.is_empty() {
1554      for mut n in self.findnodes_at("descendant-or-self::*[@idref]", Some(&root)) {
1555        if let Some(idref) = n.get_attribute("idref") {
1556          if let Some(newid) = idmap.get(&idref) {
1557            n.set_attribute("idref", newid).ok();
1558          }
1559        }
1560      }
1561    }
1562    for mut n in self.findnodes_at("descendant-or-self::*[@labels]", Some(&root)) {
1563      let _ = n.remove_attribute("labels");
1564    }
1565  }
1566
1567  /// Structural half of [`append_clone`](Self::append_clone): recursively deep
1568  /// copy `source` under `parent`, uniquifying each element's `xml:id` inline
1569  /// (so the tree never carries a transient duplicate id) and remapping its
1570  /// `fragid`. Records each old→new id in `idmap` for the caller's `idref`
1571  /// remap. Returns the new element root (for the caller's post-pass), or
1572  /// `None` for text/fragment sources.
1573  fn clone_subtree(
1574    &mut self,
1575    parent: &mut Node,
1576    source: &Node,
1577    idmap: &mut HashMap<String, String>,
1578  ) -> Option<Node> {
1579    match source.get_type() {
1580      Some(NodeType::ElementNode) => {
1581        let localname = source.get_name();
1582        // Resolve the namespace in the TARGET document. Reusing `source`'s own
1583        // `Namespace` (which belongs to the SOURCE document's tree) in
1584        // `new_child` plants a cross-document `xmlNs` pointer, which SIGSEGVs /
1585        // corrupts the tree once either document is freed — the crash that hit
1586        // `newDocument`'s cross-doc `ltx:resource` copy for split pages (#341).
1587        // Mirror the `NodeData::Element` path: find or create a namespace with
1588        // the same URI (preferring the default/empty prefix) on the target
1589        // parent's own document.
1590        let ns = source.get_namespace().and_then(|src_ns| {
1591          let uri = src_ns.get_href();
1592          let prefix = src_ns.get_prefix();
1593          parent
1594            .get_namespace_declarations()
1595            .into_iter()
1596            .find(|n| n.get_prefix().is_empty() && n.get_href() == uri)
1597            .or_else(|| {
1598              parent
1599                .get_namespaces(&self.document)
1600                .into_iter()
1601                .find(|n| n.get_prefix().is_empty() && n.get_href() == uri)
1602            })
1603            .or_else(|| {
1604              parent
1605                .get_namespace_declarations()
1606                .into_iter()
1607                .find(|n| n.get_prefix() == prefix)
1608            })
1609            .or_else(|| {
1610              parent
1611                .get_namespaces(&self.document)
1612                .into_iter()
1613                .find(|n| n.get_prefix() == prefix)
1614            })
1615            .or_else(|| Namespace::new(&prefix, &uri, parent).ok())
1616        });
1617        let mut new_node = parent.new_child(ns, &localname).ok()?;
1618
1619        // The namespaced `xml:id` is the ONE id LaTeXML uses (there is no bare
1620        // non-namespaced `id` in the model); `get_properties` surfaces it under
1621        // its localname "id", so read it namespace-aware via `get_xml_id`.
1622        let src_xmlid = get_xml_id(source);
1623        let src_fragid = source.get_attribute("fragid");
1624        let new_xmlid = src_xmlid.as_ref().map(|id| {
1625          let newid = if self.idcache.contains_key(id.as_str()) {
1626            self.uniquify_id(id, None)
1627          } else {
1628            id.clone()
1629          };
1630          idmap.insert(id.clone(), newid.clone());
1631          self.record_id(&newid, new_node.clone());
1632          newid
1633        });
1634        // Perl `cloneNode`: `fragid => substr($newid, length($id) - length($fragid))`.
1635        let new_fragid = match (&src_xmlid, &new_xmlid, &src_fragid) {
1636          (Some(id), Some(newid), Some(fragid)) => Some(remap_fragid(id, newid, fragid)),
1637          _ => src_fragid.clone(),
1638        };
1639
1640        // Copy the remaining attributes verbatim; the xml:id and fragid are set
1641        // explicitly (above/below) from their remapped values. In KEY ORDER:
1642        // `get_properties` hands back a HashMap, and libxml appends each
1643        // `set_attribute` at the end, so iterating it serialized a cloned
1644        // `.bib` field's `<ref class= href= font=>` in a different order on
1645        // every run (all six permutations seen). Perl's `Post.pm:1259`
1646        // `cloneNode(1)` keeps the source DOM order, which the core builder had
1647        // emitted sorted (`open_element_at`), so sorted = Perl's order.
1648        let mut props: Vec<(String, String)> = source.get_properties().into_iter().collect();
1649        props.sort();
1650        for (key, value) in &props {
1651          if key.starts_with('_') || key == "fragid" {
1652            continue;
1653          }
1654          let is_xmlid = key == "xml:id" || (key == "id" && src_xmlid.as_deref() == Some(value));
1655          if is_xmlid {
1656            continue;
1657          }
1658          // `get_properties` names an `xml:` attribute bare: the copy of a `\foreignlanguage` title in a TOC entry
1659          // came out `lang="de"`, which the schema refuses (63k review).
1660          if source
1661            .get_attribute_ns(key, latexml_core::common::xml::XML_NS)
1662            .is_some()
1663          {
1664            new_node.set_attribute(&format!("xml:{key}"), value).ok();
1665            continue;
1666          }
1667          new_node.set_attribute(key, value).ok();
1668        }
1669        if let Some(newid) = &new_xmlid {
1670          new_node.set_attribute("xml:id", newid).ok();
1671        }
1672        if let Some(fragid) = &new_fragid {
1673          new_node.set_attribute("fragid", fragid).ok();
1674        }
1675
1676        // Recurse into children, sharing the id map.
1677        let mut child = source.get_first_child();
1678        while let Some(c) = child {
1679          self.clone_subtree(&mut new_node, &c, idmap);
1680          child = c.get_next_sibling();
1681        }
1682        Some(new_node)
1683      },
1684      Some(NodeType::TextNode) => {
1685        parent.append_text(&source.get_content()).ok();
1686        None
1687      },
1688      Some(NodeType::DocumentFragNode) => {
1689        let mut child = source.get_first_child();
1690        while let Some(c) = child {
1691          self.clone_subtree(parent, &c, idmap);
1692          child = c.get_next_sibling();
1693        }
1694        None
1695      },
1696      _ => None,
1697    }
1698  }
1699
1700  /// Remove nodes from the document, cleaning up ID caches.
1701  ///
1702  /// Port of `Post::Document::removeNodes`.
1703  pub fn remove_nodes(&mut self, nodes: &[Node]) {
1704    fn collect_ids_of_subtree(node: &Node, out: &mut Vec<String>) {
1705      if node.get_type() != Some(NodeType::ElementNode) {
1706        return;
1707      }
1708      if let Some(id) = get_xml_id(node) {
1709        out.push(id);
1710      }
1711      let mut child = node.get_first_child();
1712      while let Some(c) = child {
1713        collect_ids_of_subtree(&c, out);
1714        child = c.get_next_sibling();
1715      }
1716    }
1717
1718    for node in nodes {
1719      if node.get_type() == Some(NodeType::ElementNode) {
1720        // Walk the subtree directly to enumerate xml:id descendants.
1721        let mut ids = Vec::new();
1722        collect_ids_of_subtree(node, &mut ids);
1723        for id in ids {
1724          self.idcache.remove(&id);
1725        }
1726      }
1727      let mut n = node.clone();
1728      n.unlink_node();
1729    }
1730  }
1731
1732  /// Free a garbage subtree's C memory now, the post-side twin of the core's
1733  /// `Document::discard_subtree`. An unlinked node whose `node->doc` is still
1734  /// set is freed by nobody (rust-libxml's `Drop`; `xmlFreeDoc` cannot reach
1735  /// it), so Perl's GC-at-last-reference has to be done by hand. The cached
1736  /// handles into the subtree are dropped first; `free_subtree` neutralizes
1737  /// every other registered wrapper.
1738  ///
1739  /// The caller's contract: the subtree's ids are already out of the id cache
1740  /// ([`remove_nodes`](Self::remove_nodes)), and no handle into it is used
1741  /// afterwards.
1742  pub fn discard_subtree(&mut self, node: Node) {
1743    use latexml_core::common::xml::is_descendant_or_self;
1744    if let Some(memo) = self.nav_memo.as_mut()
1745      && memo
1746        .element
1747        .as_ref()
1748        .is_some_and(|nav| is_descendant_or_self(nav, &node))
1749    {
1750      memo.element = None;
1751    }
1752    self
1753      .pending_xmath_unlinks
1754      .retain(|xmath| !is_descendant_or_self(xmath, &node));
1755    node.free_subtree();
1756  }
1757
1758  /// Mark nodes as "will be removed later" — their IDs become reusable.
1759  ///
1760  /// Port of `Post::Document::preremoveNodes`.
1761  pub fn preremove_nodes(&mut self, nodes: &[Node]) {
1762    for node in nodes {
1763      if node.get_type() == Some(NodeType::ElementNode) {
1764        for idd in self.findnodes_at("descendant-or-self::*[@xml:id]", Some(node)) {
1765          // NS-aware read — the bare form always returned None, so no id
1766          // was ever marked reusable and generate_node_id skipped reuse.
1767          if let Some(id) = get_xml_id(&idd) {
1768            self.idcache_reusable.insert(id, true);
1769          }
1770        }
1771      }
1772    }
1773  }
1774
1775  /// Queue an XMath subtree for unlinking at the end of post-processing.
1776  ///
1777  /// Mirrors Perl `Post.pm` L373-393's "XMath will be removed (LATER!),
1778  /// but mark its ids as reusable" pattern. The actual unlink happens
1779  /// in [`drain_pending_xmath_unlinks`](Self::drain_pending_xmath_unlinks),
1780  /// which the post-pipeline
1781  /// invokes once *all* math-format processors have completed. Without
1782  /// the defer, parallel-format chains (pmml + cmml) lose the XMath
1783  /// subtree on the first processor's unlink and the second
1784  /// processor's `mark_xm_node_visibility` walks stale `XMRef`
1785  /// targets, emitting `Error:expected:id Cannot find a node with
1786  /// xml:id=…`.
1787  pub fn defer_xmath_unlink(&mut self, node: Node) { self.pending_xmath_unlinks.push(node); }
1788
1789  /// Drain the deferred XMath unlinks: actually detach each subtree
1790  /// from the document. Idempotent against multiple processors
1791  /// queueing the same node — the second `unlink_node` is a no-op on
1792  /// an already-detached subtree. The deferred subtrees are wrapped
1793  /// in `DocOwnedNode` to suppress libxml's `_Node::drop` →
1794  /// `xmlFreeNode` chain; the enclosing Document remains the sole
1795  /// owner. See `math_processor::process_math_node` for the prior
1796  /// in-place wrapping pattern.
1797  pub fn drain_pending_xmath_unlinks(&mut self) {
1798    let pending = std::mem::take(&mut self.pending_xmath_unlinks);
1799    for node in pending {
1800      // Detach AND FREE the subtree (`free_subtree` unlinks first; it also
1801      // neutralizes every registered wrapper into the subtree, id-cache
1802      // entries included, so no stale handle can double-free). The previous
1803      // `DocOwnedNode` wrapper only suppressed the wrapper's drop — the
1804      // detached XMath C subtree itself was left unreachable-but-mapped,
1805      // i.e. LEAKED per formula per page: a leading term of the measured
1806      // ~152 KB/page render retention on the math-dense 131 MB witness.
1807      node.free_subtree();
1808    }
1809  }
1810
1811  /// Remove blank (whitespace-only) text nodes that are direct children of `node`.
1812  ///
1813  /// Port of `Post::Document::removeBlankNodes`.
1814  pub fn remove_blank_nodes(&self, node: &Node) -> u32 {
1815    let mut count = 0;
1816    if let Some(child) = node.get_first_child() {
1817      let mut current = Some(child);
1818      while let Some(ref mut c) = current {
1819        let next = c.get_next_sibling();
1820        if c.get_type() == Some(NodeType::TextNode) {
1821          let text = c.get_content();
1822          if text.trim().is_empty() {
1823            c.unlink_node();
1824            count += 1;
1825          }
1826        }
1827        current = next;
1828      }
1829    }
1830    count
1831  }
1832
1833  /// Replace `node` with `replacements` in the document.
1834  ///
1835  /// Port of `Post::Document::replaceNode`.
1836  pub fn replace_node(&mut self, old_node: &Node, replacements: &[NodeData]) {
1837    if let Some(mut parent) = old_node.get_parent() {
1838      // Save following siblings
1839      let mut save = Vec::new();
1840      while let Some(mut last) = parent.get_last_child() {
1841        if last == *old_node {
1842          break;
1843        }
1844        last.unlink_node();
1845        save.insert(0, last);
1846      }
1847
1848      // Remove the old node
1849      self.remove_nodes(&[old_node.clone()]);
1850
1851      // Add replacements
1852      self.add_nodes(&mut parent, replacements);
1853
1854      // Re-append saved siblings
1855      for mut s in save {
1856        parent.add_child(&mut s).ok();
1857      }
1858    }
1859  }
1860
1861  /// Replace `node` by its children, which keep their ids (moved, not copied), and remove it as [`remove_nodes`]
1862  /// does.
1863  ///
1864  /// [`remove_nodes`]: Self::remove_nodes
1865  pub fn unwrap_node(&mut self, node: &Node) {
1866    let mut wrapper = node.clone();
1867    for mut child in wrapper.get_child_nodes() {
1868      child.unlink_node();
1869      wrapper.add_prev_sibling(&mut child).ok();
1870    }
1871    self.remove_nodes(&[wrapper]);
1872  }
1873
1874  /// Prepend `nodes` as the first children of `parent`.
1875  ///
1876  /// Port of `Post::Document::prependNodes`.
1877  pub fn prepend_nodes(&mut self, parent: &mut Node, nodes: &[NodeData]) {
1878    // Save all existing children
1879    let mut save = Vec::new();
1880    while let Some(mut last) = parent.get_last_child() {
1881      last.unlink_node();
1882      save.insert(0, last);
1883    }
1884
1885    // Add new nodes first
1886    self.add_nodes(parent, nodes);
1887
1888    // Re-append original children
1889    for mut s in save {
1890      parent.add_child(&mut s).ok();
1891    }
1892  }
1893
1894  // The faithful `Post::Document::cloneNode` port lives in
1895  // [`append_clone`](Self::append_clone) / [`clone_subtree`](Self::clone_subtree),
1896  // which deep-copy into a parent (rust-libxml's `Node::clone` is only a
1897  // reference copy, so an in-place remap would corrupt the source).
1898
1899  // ======================================================================
1900  // CSS class and style management
1901
1902  /// Add space-separated values to an attribute, deduplicating and sorting.
1903  ///
1904  /// Port of `Post::Document::addSSValues`.
1905  pub fn add_ss_values(node: &mut Node, key: &str, values: &str) {
1906    if values.is_empty() {
1907      return;
1908    }
1909    let new_values: Vec<&str> = values.split_whitespace().collect();
1910    if let Some(old_values_str) = node.get_attribute(key) {
1911      let mut all: Vec<String> = old_values_str
1912        .split_whitespace()
1913        .map(String::from)
1914        .collect();
1915      for v in &new_values {
1916        if !all.iter().any(|o| o == v) {
1917          all.push(v.to_string());
1918        }
1919      }
1920      all.sort();
1921      node.set_attribute(key, &all.join(" ")).ok();
1922    } else {
1923      let mut sorted: Vec<&str> = new_values;
1924      sorted.sort_unstable();
1925      node.set_attribute(key, &sorted.join(" ")).ok();
1926    }
1927  }
1928
1929  /// Add CSS class(es) to a node.
1930  ///
1931  /// Port of `Post::Document::addClass`.
1932  pub fn add_class(node: &mut Node, class: &str) { Self::add_ss_values(node, "class", class); }
1933
1934  // ======================================================================
1935  // XMath visibility marking
1936
1937  /// Mark XMath node visibility (content vs presentation branches).
1938  ///
1939  /// Port of `Post::Document::markXMNodeVisibility`.
1940  pub fn mark_xm_node_visibility(&self) {
1941    for mut math_child in self.findnodes("//ltx:XMath/*") {
1942      self.mark_xm_node_visibility_aux(&mut math_child, true, true);
1943    }
1944  }
1945
1946  fn mark_xm_node_visibility_aux(&self, node: &mut Node, cvis: bool, pvis: bool) {
1947    let qname = match self.get_qname(node) {
1948      Some(q) => q,
1949      None => return,
1950    };
1951
1952    let has_cvis = node.has_attribute("_cvis");
1953    let has_pvis = node.has_attribute("_pvis");
1954    if (!cvis || has_cvis) && (!pvis || has_pvis) {
1955      return;
1956    }
1957
1958    if cvis {
1959      node.set_attribute("_cvis", "1").ok();
1960    }
1961    if pvis {
1962      node.set_attribute("_pvis", "1").ok();
1963    }
1964
1965    if qname == "ltx:XMDual" {
1966      let mut children = element_children(node);
1967      if children.len() >= 2 {
1968        if cvis {
1969          self.mark_xm_node_visibility_aux(&mut children[0], true, false);
1970        }
1971        if pvis {
1972          self.mark_xm_node_visibility_aux(&mut children[1], false, true);
1973        }
1974      }
1975    } else if qname == "ltx:XMRef" {
1976      if let Some(idref) = node.get_attribute("idref") {
1977        if let Some(target) = self.find_node_by_id(&idref) {
1978          let mut target_mut = target.clone();
1979          self.mark_xm_node_visibility_aux(&mut target_mut, cvis, pvis);
1980        } else {
1981          // Perl Post.pm:1444 — Error('expected', 'id', undef,
1982          //   "Cannot find a node with xml:id='$id'")
1983          Error!(
1984            "expected",
1985            "id",
1986            "Cannot find a node with xml:id='{}'",
1987            idref
1988          );
1989        }
1990      }
1991    } else {
1992      for mut child in element_children(node) {
1993        self.mark_xm_node_visibility_aux(&mut child, cvis, pvis);
1994      }
1995    }
1996  }
1997
1998  /// Realize an XMRef/XMDual node along a branch — Perl `realizeXMNode($node,
1999  /// $branch)` (`Post.pm` L1436-1450), the two-argument form.
2000  ///
2001  /// Unlike the branchless [`realize_xm_node`](Self::realize_xm_node) below,
2002  /// this **loops**: an `XMRef` is followed to its target, an `XMDual` is
2003  /// descended into the requested branch, and either may expose the other, so
2004  /// resolution repeats until the node is neither. A dangling `idref` reports
2005  /// the same `expected:id` error and yields `None`.
2006  pub fn realize_xm_node_branch(&self, node: &Node, branch: XMBranch) -> Option<Node> {
2007    let mut node = node.clone();
2008    loop {
2009      if self.is_qname(&node, "ltx:XMRef") {
2010        let idref = node.get_attribute("idref")?;
2011        match self.find_node_by_id(&idref) {
2012          Some(target) => node = target.clone(),
2013          None => {
2014            Error!(
2015              "expected",
2016              "id",
2017              "Cannot find a node with xml:id='{}'",
2018              idref
2019            );
2020            return None;
2021          },
2022        }
2023      } else if self.is_qname(&node, "ltx:XMDual") {
2024        // Perl `my ($content, $presentation) = element_nodes($node)` — the two
2025        // branches in that order. A malformed dual with a missing branch leaves
2026        // Perl with an undef `$node`, ending the loop; `None` says the same.
2027        let children = element_children(&node);
2028        node = children.get(branch as usize)?.clone();
2029      } else {
2030        return Some(node);
2031      }
2032    }
2033  }
2034
2035  /// Realize an XMRef node: follow the reference to get the "real" node.
2036  ///
2037  /// Port of `Post::Document::realizeXMNode`'s one-argument form (`Post.pm`
2038  /// L1451-1456) — a single `XMRef` hop, leaving an `XMDual` alone. Callers that
2039  /// need a specific branch want [`realize_xm_node_branch`](Self::realize_xm_node_branch).
2040  pub fn realize_xm_node(&self, node: &Node) -> Option<Node> {
2041    if self.is_qname(node, "ltx:XMRef") {
2042      let idref = node.get_attribute("idref")?;
2043      let realized = self.find_node_by_id(&idref).cloned();
2044      if realized.is_none() {
2045        // Perl Post.pm:1456 — Error('expected', 'id', undef,
2046        //   "Cannot find a node with xml:id='$id'")
2047        Error!(
2048          "expected",
2049          "id",
2050          "Cannot find a node with xml:id='{}'",
2051          idref
2052        );
2053      }
2054      realized
2055    } else {
2056      Some(node.clone())
2057    }
2058  }
2059
2060  // ======================================================================
2061  // Utility methods
2062
2063  /// Join a list of nodes with a conjunction.
2064  ///
2065  /// Port of `Post::Document::conjoin`.
2066  pub fn conjoin(conjunction: Conjunction, nodes: Vec<NodeData>) -> Vec<NodeData> {
2067    let n = nodes.len();
2068    if n < 2 {
2069      return nodes;
2070    }
2071
2072    let (comma, and) = match conjunction {
2073      Conjunction::Simple(s) => (s.clone(), s),
2074      Conjunction::Pair(c, a) => (c, a),
2075    };
2076
2077    let mut result = Vec::new();
2078    let mut iter = nodes.into_iter();
2079    result.push(iter.next().unwrap());
2080
2081    let mut remaining: Vec<_> = iter.collect();
2082    while remaining.len() > 1 {
2083      result.push(NodeData::Text(comma.clone()));
2084      result.push(remaining.remove(0));
2085    }
2086    result.push(NodeData::Text(and));
2087    result.push(remaining.remove(0));
2088    result
2089  }
2090
2091  /// Find the initial letter for sorting.
2092  ///
2093  /// Port of `Post::Document::initial`.
2094  pub fn initial(string: &str, force: bool) -> String {
2095    let decomposed: String = string.nfd().collect();
2096    let trimmed = decomposed.trim_start();
2097    let s = if force {
2098      trimmed.trim_start_matches(|c: char| !c.is_ascii_alphabetic())
2099    } else {
2100      trimmed
2101    };
2102    match s.chars().next() {
2103      Some(c) if c.is_ascii_alphabetic() => c.to_uppercase().to_string(),
2104      _ => "*".to_string(),
2105    }
2106  }
2107
2108  /// Trim leading/trailing whitespace text nodes from a node's children.
2109  ///
2110  /// Port of `Post::Document::trimChildNodes`.
2111  pub fn trim_child_nodes(node: &Node) -> Vec<Node> {
2112    let mut children: Vec<Node> = Vec::new();
2113    if let Some(child) = node.get_first_child() {
2114      let mut current = Some(child);
2115      while let Some(ref c) = current {
2116        children.push(c.clone());
2117        current = c.get_next_sibling();
2118      }
2119    }
2120
2121    if children.is_empty() {
2122      return children;
2123    }
2124
2125    // Trim leading whitespace
2126    if let Some(first) = children.first_mut() {
2127      if first.get_type() == Some(NodeType::TextNode) {
2128        let text = first.get_content();
2129        let trimmed = text.trim_start();
2130        if trimmed.is_empty() {
2131          children.remove(0);
2132        } else if trimmed != text {
2133          first.set_content(trimmed).ok();
2134        }
2135      }
2136    }
2137
2138    // Trim trailing whitespace
2139    if let Some(last) = children.last_mut() {
2140      if last.get_type() == Some(NodeType::TextNode) {
2141        let text = last.get_content();
2142        let trimmed = text.trim_end();
2143        if trimmed.is_empty() {
2144          children.pop();
2145        } else if trimmed != text {
2146          last.set_content(trimmed).ok();
2147        }
2148      }
2149    }
2150
2151    children
2152  }
2153
2154  /// Add a navigation reference.
2155  ///
2156  /// Port of `Post::Document::addNavigation`.
2157  pub fn add_navigation(&mut self, relation: &str, id: &str) {
2158    // Perl `Post.pm:1409` probes for the duplicate with a whole-document XPath
2159    // built by string interpolation. The memo answers the same question — see
2160    // the `nav_memo` field docs for why the XPath form cannot stand at
2161    // 16.3 M calls. `insert` returning false means the pair is already
2162    // present, which is Perl's early `return`.
2163    if self.navigation_ref_present(relation, id) {
2164      return;
2165    }
2166
2167    let ref_node = NodeData::Element {
2168      tag:        "ltx:ref".to_string(),
2169      attributes: Some(HashMap::from_iter([
2170        ("idref".to_string(), id.to_string()),
2171        ("rel".to_string(), relation.to_string()),
2172        ("show".to_string(), "toctitle".to_string()),
2173      ])),
2174      children:   vec![],
2175    };
2176
2177    match self.navigation_element() {
2178      Some(mut nav) => {
2179        self.add_nodes(&mut nav, &[ref_node]);
2180        self.record_navigation_ref(relation, id);
2181      },
2182      _ => {
2183        if let Some(mut root) = self.get_document_element() {
2184          let nav_node = NodeData::Element {
2185            tag:        "ltx:navigation".to_string(),
2186            attributes: None,
2187            children:   vec![ref_node],
2188          };
2189          self.add_nodes(&mut root, &[nav_node]);
2190          // Adopt the element just created, so the next of this page's ~406
2191          // calls does not re-walk the document looking for it.
2192          let found = self.findnode("//ltx:navigation");
2193          if let Some(memo) = self.nav_memo.as_mut() {
2194            memo.element = found;
2195          }
2196          self.record_navigation_ref(relation, id);
2197        }
2198        // No document element: nothing was added, so nothing is recorded —
2199        // a later call must be free to retry, exactly as re-running Perl's
2200        // XPath probe would.
2201      },
2202    }
2203  }
2204
2205  /// The document's `ltx:navigation` element, memoized (Perl re-runs
2206  /// `findnode('//ltx:navigation')` per call — `Post.pm:1411`).
2207  ///
2208  /// The cached handle is revalidated before reuse: a node that has been
2209  /// unlinked from the tree has no parent, and reusing it would append into a
2210  /// detached subtree that never reaches the output. That check is one FFI
2211  /// call against a full descendant-axis walk.
2212  fn navigation_element(&mut self) -> Option<Node> {
2213    if let Some(memo) = self.nav_memo.as_ref()
2214      && let Some(nav) = memo.element.as_ref()
2215      && nav.get_parent().is_some()
2216    {
2217      return Some(nav.clone());
2218    }
2219    let found = self.findnode("//ltx:navigation");
2220    if let Some(memo) = self.nav_memo.as_mut() {
2221      memo.element = found.clone();
2222    }
2223    found
2224  }
2225
2226  /// Is this `(rel, idref)` pair already under a navigation element?
2227  ///
2228  /// Stands in for Perl's per-call duplicate XPath (`Post.pm:1409`), and must
2229  /// answer identically. Three details earn their keep:
2230  ///
2231  /// * The seed reads **every** `ltx:navigation` element, because `//` in the
2232  ///   Perl probe does — while insertion targets the FIRST, because Perl's
2233  ///   `findnode` (`Post.pm:1411`) does. A page can arrive with navigation
2234  ///   already populated: `Split` strips the source's navigation and copies it
2235  ///   into each page (`split.rs:465`, `Split::add_navigation`).
2236  /// * `ltx:ref` is namespace-qualified, so a `ref` in some other namespace
2237  ///   must NOT seed the set.
2238  /// * `ltx:TOC` / `ltx:title` also live under navigation and are not refs.
2239  fn seed_navigation_memo(&mut self) {
2240    if self.nav_memo.is_some() {
2241      return;
2242    }
2243    let mut refs = FxHashSet::default();
2244    let elements = self.findnodes("//ltx:navigation");
2245    for nav in &elements {
2246      for child in nav.get_child_nodes() {
2247        if !name_is(&child, "ref") {
2248          continue;
2249        }
2250        // Strict: an unnamespaced `<ref>` does not match `ltx:ref` in XPath
2251        // either, so it must not seed the set.
2252        let in_ltx = child
2253          .get_namespace()
2254          .is_some_and(|ns| ns.get_href() == LTX_NSURI);
2255        if !in_ltx {
2256          continue;
2257        }
2258        if let (Some(rel), Some(idref)) = (child.get_attribute("rel"), child.get_attribute("idref"))
2259        {
2260          refs.insert((rel, idref));
2261        }
2262      }
2263    }
2264    self.nav_memo = Some(NavigationMemo {
2265      element: elements.into_iter().next(),
2266      refs,
2267    });
2268  }
2269
2270  fn navigation_ref_present(&mut self, relation: &str, id: &str) -> bool {
2271    self.seed_navigation_memo();
2272    self
2273      .nav_memo
2274      .as_ref()
2275      .is_some_and(|memo| memo.refs.contains(&(relation.to_string(), id.to_string())))
2276  }
2277
2278  /// Record a pair only once it has actually been added to the tree.
2279  fn record_navigation_ref(&mut self, relation: &str, id: &str) {
2280    if let Some(memo) = self.nav_memo.as_mut() {
2281      memo.refs.insert((relation.to_string(), id.to_string()));
2282    }
2283  }
2284
2285  // ======================================================================
2286  // Validation
2287
2288  /// Validate the document against its declared schema.
2289  ///
2290  /// Port of `Post::Document::validate`.
2291  pub fn validate(&self) -> Result<(), String> {
2292    static RNG_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
2293      regex::Regex::new(r#"^\s*RelaxNGSchema\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap()
2294    });
2295    let rng_re = &*RNG_RE;
2296    for pi_text in &self.processing_instructions {
2297      if let Some(cap) = rng_re.captures(pi_text) {
2298        let schema = &cap[1];
2299        Info!(
2300          "validate",
2301          "schema",
2302          "Would validate against RelaxNG schema: {}",
2303          schema
2304        );
2305        return Ok(());
2306      }
2307    }
2308    // Perl Post.pm:973 — Error('I/O', $schema, undef, "Failed to load
2309    //   RelaxNG schema $schema") when no usable schema; here we don't
2310    //   even have a path. Reporting at warn (no schema = nothing to
2311    //   validate, often a benign config) with the structured target.
2312    Warn!(
2313      "missing_file",
2314      "schema",
2315      "No schema found for document validation"
2316    );
2317    Ok(())
2318  }
2319
2320  /// Check ID consistency.
2321  ///
2322  /// Port of `Post::Document::idcheck`.
2323  pub fn idcheck(&self) {
2324    let mut doc_ids: HashMap<String, bool> = HashMap::default();
2325    let mut dups = Vec::new();
2326
2327    for node in self.findnodes("//*[@xml:id]") {
2328      if let Some(id) = get_xml_id(&node) {
2329        if doc_ids.contains_key(&id) {
2330          dups.push(id.clone());
2331        }
2332        doc_ids.insert(id, true);
2333      }
2334    }
2335
2336    // The cached ids the document lacks, sorted: Perl Post.pm:1006-1014 lists them in hash `keys` order, random
2337    // from run to run (det354 C4).
2338    let mut missing = Vec::new();
2339    for id in self.idcache.keys() {
2340      if !doc_ids.contains_key(id) {
2341        missing.push(id.clone());
2342      }
2343    }
2344    missing.sort_unstable();
2345
2346    if !dups.is_empty() {
2347      Warn!(
2348        "malformed",
2349        "id",
2350        "Duplicate IDs for {}: {}",
2351        self.site_relative_destination().unwrap_or_default(),
2352        dups.join(", ")
2353      );
2354    }
2355    if !missing.is_empty() {
2356      Warn!(
2357        "expected",
2358        "id",
2359        "Cached IDs not in document for {}: {}",
2360        self.site_relative_destination().unwrap_or_default(),
2361        missing.join(", ")
2362      );
2363    }
2364  }
2365
2366  // ======================================================================
2367  // Cache support
2368
2369  /// Look up a value in the persistent cache (Perl `cacheLookup`, `Post.pm` L1517-1521).
2370  pub fn cache_lookup(&self, key: &str) -> Option<String> {
2371    self
2372      .cache
2373      .lookup(self.destination_directory.as_deref(), key)
2374  }
2375
2376  /// Store a value in the persistent cache (Perl `cacheStore`, `Post.pm` L1523-1531).
2377  pub fn cache_store(&mut self, key: &str, value: &str) {
2378    self
2379      .cache
2380      .store(self.destination_directory.as_deref(), key, Some(value));
2381  }
2382
2383  /// Remove a value from the persistent cache.
2384  pub fn cache_remove(&mut self, key: &str) {
2385    self
2386      .cache
2387      .store(self.destination_directory.as_deref(), key, None);
2388  }
2389
2390  /// The document's cache, shared by the pages of a run.
2391  pub fn cache(&self) -> &DocCache { &self.cache }
2392}
2393
2394/// The cache's file name in a destination directory: Perl's `LaTeXML.cache` (`Post.pm` L1537) is a DB_File, which a
2395/// Perl run into the same directory keeps reading, so ours, SQLite, has a name of its own.
2396pub const CACHE_FILE: &str = "LaTeXML-oxide.cache";
2397
2398/// Whether `basename` is the cache file or one of its SQLite side files, which no package carries.
2399pub fn is_cache_file(basename: &str) -> bool {
2400  basename
2401    .strip_prefix(CACHE_FILE)
2402    .is_some_and(|rest| matches!(rest, "" | "-wal" | "-shm" | "-journal"))
2403}
2404
2405/// Perl's document cache (`Post.pm` L1510-1548): a key-value store per destination directory, persisted there as
2406/// [`CACHE_FILE`] (`kv(key, value)`, Perl's keys and values) unless `nocache` (Perl's option, `Post.pm` L678; the
2407/// cortex worker, whose every paper gets a fresh directory) or the document has no destination directory (the API):
2408/// then in memory. Opened lazily, at the first lookup; every page of a run shares one ([`PostDocumentOptions::cache`])
2409/// as Perl's split pages share their parent's (`new_internal` clones it, L687-690).
2410#[derive(Clone, Default)]
2411pub struct DocCache(std::rc::Rc<std::cell::RefCell<DocCacheStores>>);
2412
2413#[derive(Default)]
2414struct DocCacheStores {
2415  nocache: bool,
2416  /// Destination directory (`""`: none) → its store.
2417  stores:  HashMap<String, crate::sqlite_store::SqliteStore>,
2418}
2419
2420const DOC_CACHE_SCHEMA: &str =
2421  "CREATE TABLE IF NOT EXISTS kv(key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
2422
2423impl std::fmt::Debug for DocCache {
2424  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("DocCache") }
2425}
2426
2427impl DocCache {
2428  /// A cache of its own; `nocache` keeps it in memory.
2429  pub fn new(nocache: bool) -> Self {
2430    DocCache(std::rc::Rc::new(std::cell::RefCell::new(DocCacheStores {
2431      nocache,
2432      stores: HashMap::default(),
2433    })))
2434  }
2435
2436  /// Run `f` on the store of `dir` (opened now when it is the first use).
2437  pub fn with_store<T>(
2438    &self,
2439    dir: Option<&str>,
2440    f: impl FnOnce(&mut crate::sqlite_store::SqliteStore) -> T,
2441  ) -> T {
2442    let mut inner = self.0.borrow_mut();
2443    let persist = !inner.nocache;
2444    // One store per directory however it is spelled (`out`, `./out`).
2445    let key = dir.map_or_else(String::new, latexml_core::util::pathname::absolute);
2446    let store = inner.stores.entry(key).or_insert_with(|| {
2447      let file = dir.filter(|_| persist).map(|dir| {
2448        // Perl's `checkDestination` makes the directory (`Post.pm` L941-949): the cache is opened before any page
2449        // is written into a new `--dest` directory.
2450        let _ = std::fs::create_dir_all(dir);
2451        Path::new(dir).join(CACHE_FILE)
2452      });
2453      crate::sqlite_store::SqliteStore::open(file.as_deref(), DOC_CACHE_SCHEMA, 1)
2454    });
2455    f(store)
2456  }
2457
2458  /// The value under `key` in `dir`'s store.
2459  pub fn lookup(&self, dir: Option<&str>, key: &str) -> Option<String> {
2460    self.with_store(dir, |store| store.read(|conn| kv_get(conn, key)).flatten())
2461  }
2462
2463  /// Store `value` under `key` in `dir`'s store (remove it for `None`), in a transaction of its own.
2464  pub fn store(&self, dir: Option<&str>, key: &str, value: Option<&str>) {
2465    self.with_store(dir, |store| store.immediate(|tx, _| kv_put(tx, key, value)));
2466  }
2467
2468  /// Close every store (Perl's `closeCache`, `Post.pm` L1543-1548): its database checkpointed, no side file left for
2469  /// a package to pick up.
2470  pub fn close(&self) { self.0.borrow_mut().stores.clear(); }
2471
2472  /// Close the stores that run on their file, reopened at their next use: before other processes open it (the render
2473  /// workers), the file checkpointed and no handle held across. A store in memory keeps its entries.
2474  pub fn close_files(&self) {
2475    self
2476      .0
2477      .borrow_mut()
2478      .stores
2479      .retain(|_, store| store.file().is_none());
2480  }
2481}
2482
2483/// The value under `key`.
2484pub fn kv_get(conn: &rusqlite::Connection, key: &str) -> rusqlite::Result<Option<String>> {
2485  use rusqlite::OptionalExtension;
2486  conn
2487    .prepare_cached("SELECT value FROM kv WHERE key = ?1")?
2488    .query_row([key], |row| row.get(0))
2489    .optional()
2490}
2491
2492/// Store `value` under `key` (remove it for `None`).
2493pub fn kv_put(conn: &rusqlite::Connection, key: &str, value: Option<&str>) -> rusqlite::Result<()> {
2494  match value {
2495    Some(value) => conn
2496      .prepare_cached("INSERT OR REPLACE INTO kv(key, value) VALUES (?1, ?2)")?
2497      .execute([key, value]),
2498    None => conn
2499      .prepare_cached("DELETE FROM kv WHERE key = ?1")?
2500      .execute([key]),
2501  }
2502  .map(drop)
2503}
2504
2505// ======================================================================
2506// Supporting types
2507
2508/// Options for creating a PostDocument.
2509#[derive(Debug, Default, Clone)]
2510pub struct PostDocumentOptions {
2511  pub destination:           Option<String>,
2512  pub destination_directory: Option<String>,
2513  pub site_directory:        Option<String>,
2514  pub source:                Option<String>,
2515  pub source_directory:      Option<String>,
2516  pub searchpaths:           Option<Vec<String>>,
2517  pub validate:              bool,
2518  pub nocache:               bool,
2519  /// The run's cache, shared by every page made with these options ([`DocCache`]); `None`: one of its own.
2520  pub cache:                 Option<DocCache>,
2521}
2522
2523/// Recursive representation for building XML nodes.
2524///
2525/// Port of the Perl `data = string | [$tag, {attrs}, @children]` convention.
2526#[derive(Debug, Clone)]
2527pub enum NodeData {
2528  /// A text node.
2529  Text(String),
2530  /// An element node with tag (prefix:localname), optional attributes, and children.
2531  Element {
2532    tag:        String,
2533    attributes: Option<HashMap<String, String>>,
2534    children:   Vec<NodeData>,
2535  },
2536  /// A reference to an existing XML node (will be cloned when added).
2537  XmlNode(Node),
2538}
2539
2540/// Which branch of an `ltx:XMDual` to follow — Perl's `$branch` string argument
2541/// to `realizeXMNode`, which is only ever `'content'` or `'presentation'`.
2542///
2543/// The discriminants are the child positions Perl's
2544/// `my ($content, $presentation) = element_nodes($node)` unpacks, so the enum
2545/// indexes the children directly.
2546#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2547pub enum XMBranch {
2548  /// The semantic branch — the first child.
2549  Content = 0,
2550  /// The visual branch — the second child.
2551  Presentation = 1,
2552}
2553
2554/// Conjunction for joining node lists.
2555pub enum Conjunction {
2556  /// A single separator used everywhere.
2557  Simple(String),
2558  /// (comma, and) — comma between items, 'and' before the last.
2559  Pair(String, String),
2560}
2561
2562// ======================================================================
2563// Helper functions
2564
2565/// Get element children of a node (skipping text, comments, etc.).
2566pub fn element_children(node: &Node) -> Vec<Node> {
2567  let mut result = Vec::new();
2568  if let Some(child) = node.get_first_child() {
2569    let mut current = Some(child);
2570    while let Some(ref c) = current {
2571      if c.get_type() == Some(NodeType::ElementNode) {
2572        result.push(c.clone());
2573      }
2574      current = c.get_next_sibling();
2575    }
2576  }
2577  result
2578}
2579
2580/// Iterator version of `element_children` — walks the sibling chain lazily.
2581/// Prefer this in hot paths that only need to read or filter children
2582/// without materializing a Vec. Callers that need len() or random access
2583/// still want the Vec version.
2584pub fn element_children_iter(node: &Node) -> impl Iterator<Item = Node> + use<> {
2585  let first = node.get_first_child();
2586  std::iter::successors(first, |c| c.get_next_sibling())
2587    .filter(|c| c.get_type() == Some(NodeType::ElementNode))
2588}
2589
2590/// Escape a string for XML **text content or a double-quoted attribute value**.
2591///
2592/// The one escaper for markup this crate still assembles as a string. It used to
2593/// be three byte-identical private copies: `make_bibliography.rs::xml_escape`
2594/// went away with the `.bib` string route, `manifest/epub.rs::escape_xml` went
2595/// away when the OPF moved onto the DOM, and `schema_docs.rs::html_escape` — the
2596/// dev-facing RelaxNG doc site, the last string-assembled markup here — is what
2597/// remains. Duplicated escapers drift; that is issue 386's premise, and the
2598/// reason to keep exactly one even now that it has a single caller.
2599///
2600/// **`'` is deliberately not escaped.** It is legal raw in text content, and both
2601/// callers emit double-quoted attributes, where only `"` must go. Escaping it
2602/// would change output without fixing anything.
2603///
2604/// **`latexml_core::document`'s `serialize_string`/`serialize_attr` are NOT
2605/// folded in here, and must not be.** They look like a fourth copy with a
2606/// missing `"`, but they are a correct pair: `serialize_string` escapes text
2607/// nodes and comments, and `serialize_attr` layers `"`, `\n` and `\t` on top for
2608/// attribute values. Escaping `"` in a text node would be *wrong* XML, not safer
2609/// XML.
2610pub fn escape_xml(s: &str) -> String {
2611  s.replace('&', "&amp;")
2612    .replace('<', "&lt;")
2613    .replace('>', "&gt;")
2614    .replace('"', "&quot;")
2615}
2616
2617/// Compute a relative path from `base` to `path`.
2618fn pathdiff(path: &str, base: &str) -> String {
2619  let p = Path::new(path);
2620  let b = Path::new(base);
2621  if let Ok(rel) = p.strip_prefix(b) {
2622    rel.to_string_lossy().to_string()
2623  } else {
2624    path.to_string()
2625  }
2626}
2627
2628#[cfg(test)]
2629mod tests {
2630  use super::*;
2631
2632  fn make_test_doc(xml: &str) -> PostDocument {
2633    PostDocument::new_from_string(xml, PostDocumentOptions::default()).unwrap()
2634  }
2635
2636  /// The traversal path must return EXACTLY what XPath returns — same nodes,
2637  /// same document order — for every shape it claims. Compared against
2638  /// libxml2 on a document small enough for XPath to answer reliably, so a
2639  /// grammar slip shows up as a mismatch rather than as silently different
2640  /// post-processing on large inputs.
2641  /// `add_navigation` memoizes the navigation element and the `(rel, idref)`
2642  /// pairs instead of re-running Perl's per-call XPath probe
2643  /// (`Post.pm:1409-1414`). The dedup must stay EXACTLY Perl's, including for a
2644  /// document that already carries navigation refs when it arrives — the case
2645  /// the memo has to seed rather than assume empty.
2646  #[test]
2647  fn add_navigation_dedupes_including_preexisting_refs() {
2648    let mut doc = make_test_doc(
2649      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2650         <navigation>\
2651           <ref rel='chapter' idref='Ch1' show='toctitle'/>\
2652           <title>ignored — not an ltx:ref</title>\
2653         </navigation>\
2654       </document>",
2655    );
2656
2657    doc.add_navigation("chapter", "Ch1"); // already present -> no-op
2658    doc.add_navigation("section", "S1"); // new
2659    doc.add_navigation("section", "S1"); // duplicate of the one just added
2660    doc.add_navigation("sidebar", "Ch1"); // same id, DIFFERENT rel -> distinct
2661
2662    let refs = doc.findnodes("//ltx:navigation/ltx:ref");
2663    let mut pairs: Vec<(String, String)> = refs
2664      .iter()
2665      .map(|n| {
2666        (
2667          n.get_attribute("rel").unwrap_or_default(),
2668          n.get_attribute("idref").unwrap_or_default(),
2669        )
2670      })
2671      .collect();
2672    pairs.sort();
2673    assert_eq!(pairs, vec![
2674      ("chapter".to_string(), "Ch1".to_string()),
2675      ("section".to_string(), "S1".to_string()),
2676      ("sidebar".to_string(), "Ch1".to_string()),
2677    ]);
2678    assert_eq!(
2679      doc.findnodes("//ltx:navigation").len(),
2680      1,
2681      "the existing navigation element must be reused, not duplicated"
2682    );
2683  }
2684
2685  /// The same dedup, but starting from a document with NO navigation element:
2686  /// the first call must create it and the memo must then adopt what it created.
2687  /// D1: the Perl probe is `//ltx:navigation/ltx:ref[…]` — `//`, so refs under
2688  /// a SECOND navigation element count as present too. `Split` really does put
2689  /// navigation into pages (`split.rs:465`), so this shape is reachable.
2690  /// Insertion still targets the FIRST element, as Perl's `findnode` does.
2691  #[test]
2692  fn add_navigation_sees_refs_under_every_navigation_element() {
2693    let mut doc = make_test_doc(
2694      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2695         <navigation><ref rel='chapter' idref='Ch1'/></navigation>\
2696         <section><navigation><ref rel='section' idref='S9'/></navigation></section>\
2697       </document>",
2698    );
2699
2700    doc.add_navigation("section", "S9"); // present under the SECOND element
2701    doc.add_navigation("chapter", "Ch1"); // present under the FIRST
2702
2703    assert_eq!(
2704      doc.findnodes("//ltx:navigation/ltx:ref").len(),
2705      2,
2706      "neither pair may be re-added; `//` spans both navigation elements"
2707    );
2708
2709    doc.add_navigation("appendix", "A1"); // genuinely new
2710    let first_nav_refs = doc.findnodes("//ltx:navigation").first().map(|n| {
2711      n.get_child_nodes()
2712        .iter()
2713        .filter(|c| name_is(c, "ref"))
2714        .count()
2715    });
2716    assert_eq!(
2717      first_nav_refs,
2718      Some(2),
2719      "a new ref lands under the FIRST navigation element (Perl's findnode)"
2720    );
2721  }
2722
2723  /// D2: `ltx:ref` is namespace-qualified. A `<ref>` in a foreign namespace
2724  /// does not match the Perl probe, so it must not suppress a real insert.
2725  #[test]
2726  fn add_navigation_ignores_a_foreign_namespace_ref_when_seeding() {
2727    let mut doc = make_test_doc(
2728      "<document xmlns='http://dlmf.nist.gov/LaTeXML' xmlns:other='http://example.org/other'>\
2729         <navigation><other:ref rel='chapter' idref='Ch1'/></navigation>\
2730       </document>",
2731    );
2732
2733    doc.add_navigation("chapter", "Ch1");
2734
2735    assert_eq!(
2736      doc.findnodes("//ltx:navigation/ltx:ref").len(),
2737      1,
2738      "the foreign-namespace ref is not an ltx:ref, so the real one must be added"
2739    );
2740  }
2741
2742  /// The memo must agree with the ORIGINAL XPath probe on every pair, for a
2743  /// document that mixes pre-existing refs, foreign namespaces, and non-ref
2744  /// children — this is the differential the refactor has to survive.
2745  #[test]
2746  fn navigation_memo_agrees_with_the_original_xpath_probe() {
2747    let mut doc = make_test_doc(
2748      "<document xmlns='http://dlmf.nist.gov/LaTeXML' xmlns:other='http://example.org/other'>\
2749         <navigation>\
2750           <ref rel='chapter' idref='Ch1'/>\
2751           <title>t</title>\
2752           <other:ref rel='section' idref='S1'/>\
2753         </navigation>\
2754       </document>",
2755    );
2756
2757    for (rel, id) in [
2758      ("chapter", "Ch1"), // present -> XPath finds it
2759      ("section", "S1"),  // only in a FOREIGN ns -> XPath does NOT find it
2760      ("title", "t"),     // not a ref at all
2761      ("section", "S2"),  // absent
2762    ] {
2763      // The probe Perl runs, verbatim (Post.pm:1409).
2764      let probe = format!("//ltx:navigation/ltx:ref[@rel='{}'][@idref='{}']", rel, id);
2765      let xpath_says_present = doc.findnode(&probe).is_some();
2766      let memo_says_present = doc.navigation_ref_present(rel, id);
2767      assert_eq!(
2768        memo_says_present, xpath_says_present,
2769        "memo and XPath disagree about ({rel}, {id})"
2770      );
2771    }
2772  }
2773
2774  #[test]
2775  fn add_navigation_creates_then_reuses_the_navigation_element() {
2776    let mut doc = make_test_doc("<document xmlns='http://dlmf.nist.gov/LaTeXML'><p/></document>");
2777
2778    doc.add_navigation("section", "S1");
2779    doc.add_navigation("section", "S2");
2780    doc.add_navigation("section", "S1"); // duplicate
2781
2782    assert_eq!(
2783      doc.findnodes("//ltx:navigation").len(),
2784      1,
2785      "exactly one navigation element must be created"
2786    );
2787    assert_eq!(doc.findnodes("//ltx:navigation/ltx:ref").len(), 2);
2788  }
2789
2790  #[test]
2791  fn test_new_from_string() {
2792    let doc = make_test_doc("<document xmlns='http://dlmf.nist.gov/LaTeXML'/>");
2793    assert!(doc.get_document_element().is_some());
2794  }
2795
2796  #[test]
2797  fn test_findnodes() {
2798    let doc = make_test_doc(
2799      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2800         <section xml:id='s1'/>\
2801         <section xml:id='s2'/>\
2802       </document>",
2803    );
2804    let sections = doc.findnodes("//ltx:section");
2805    assert_eq!(sections.len(), 2);
2806  }
2807
2808  /// SYNC row XP: a detail-less `XML_ERR_NO_MEMORY` is libxml2's allocation failure; a failure with a message (a
2809  /// malformed expression) or another code is not.
2810  #[test]
2811  fn libxml_oom_is_told_from_an_xpath_error() {
2812    let oom = XPathError {
2813      message: None,
2814      code:    2,
2815      domain:  12,
2816    };
2817    let syntax = XPathError {
2818      message: Some("Invalid expression".into()),
2819      code:    1207,
2820      domain:  12,
2821    };
2822    let unknown = XPathError {
2823      message: None,
2824      code:    0,
2825      domain:  0,
2826    };
2827    assert!(is_libxml_oom(&oom));
2828    assert!(!is_libxml_oom(&syntax));
2829    assert!(!is_libxml_oom(&unknown));
2830  }
2831
2832  /// `findnodes` with no context node must resolve RELATIVE location paths
2833  /// (`descendant::…`, `.//…`) against the tree — matching XML::LibXML's
2834  /// `$doc->findnodes` (which evaluates from the document node) — not silently
2835  /// return nothing. Regression guard for the split-page resource/PI copy (#341):
2836  /// the fix binds the root element as the context node. Before-root PIs still
2837  /// need the absolute `//processing-instruction()` form (documented in
2838  /// `findnodes_at`), verified here too.
2839  #[test]
2840  fn findnodes_resolves_relative_axes_without_context_node() {
2841    let doc = make_test_doc(
2842      "<?latexml class='book'?>\
2843       <document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2844         <resource src='a.css' type='text/css'/>\
2845         <section xml:id='s1'/>\
2846       </document>",
2847    );
2848    assert_eq!(doc.findnodes("//ltx:resource").len(), 1, "absolute");
2849    assert_eq!(
2850      doc.findnodes("descendant::ltx:resource").len(),
2851      1,
2852      "descendant:: axis must resolve without an explicit context node"
2853    );
2854    assert_eq!(
2855      doc.findnodes(".//ltx:resource").len(),
2856      1,
2857      ".// axis must resolve without an explicit context node"
2858    );
2859    // Before-root PIs: absolute form finds them, relative-from-root does not.
2860    assert_eq!(
2861      doc.findnodes("//processing-instruction('latexml')").len(),
2862      1,
2863      "absolute PI query finds the before-root <?latexml?>"
2864    );
2865  }
2866
2867  /// The exact `--splitat=section` union `make_splitpaths` emits (the shape the
2868  /// limit-safe `find_split_pages` walk must reproduce).
2869  const SECTION_UNION: &str = "//ltx:section | \
2870    //ltx:bibliography[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2871    //ltx:appendix[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2872    //ltx:index[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2873    //ltx:part | \
2874    //ltx:bibliography[preceding-sibling::ltx:part] | \
2875    //ltx:appendix[preceding-sibling::ltx:part] | \
2876    //ltx:index[preceding-sibling::ltx:part] | \
2877    //ltx:chapter | \
2878    //ltx:bibliography[preceding-sibling::ltx:chapter or parent::ltx:part] | \
2879    //ltx:appendix[preceding-sibling::ltx:chapter or parent::ltx:part] | \
2880    //ltx:index[preceding-sibling::ltx:chapter or parent::ltx:part]";
2881
2882  fn split_doc() -> PostDocument {
2883    make_test_doc(
2884      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2885         <part xml:id='P1'>\
2886           <chapter xml:id='C1'>\
2887             <section xml:id='S1'/>\
2888             <section xml:id='S2'/>\
2889             <index xml:id='I1'/>\
2890           </chapter>\
2891           <bibliography xml:id='B1'/>\
2892         </part>\
2893         <section xml:id='S3'/>\
2894         <index xml:id='I2'/>\
2895       </document>",
2896    )
2897  }
2898
2899  /// The limit-safe DOM walk must select exactly the nodes (and order) the raw
2900  /// XPath union selects on a small document where XPath is limit-safe.
2901  #[test]
2902  fn test_find_split_pages_matches_xpath() {
2903    let doc = split_doc();
2904    let ids = |nodes: Vec<Node>| -> Vec<String> { nodes.iter().filter_map(get_xml_id).collect() };
2905    let via_walk = ids(doc.find_split_pages(SECTION_UNION));
2906    let via_xpath = ids(doc.findnodes(SECTION_UNION));
2907    assert_eq!(
2908      via_walk,
2909      vec!["P1", "C1", "S1", "S2", "I1", "B1", "S3", "I2"],
2910      "walk selected the wrong pages / order"
2911    );
2912    assert_eq!(via_walk, via_xpath, "walk diverged from XPath union");
2913  }
2914
2915  /// A union outside the recognized grammar falls back to raw XPath (unchanged
2916  /// behavior for custom `--splitpaths`).
2917  #[test]
2918  fn test_find_split_pages_fallback() {
2919    let doc = split_doc();
2920    // `descendant::` is not in the make_splitpaths grammar → fallback path.
2921    let via = doc.find_split_pages("//ltx:chapter/descendant::ltx:section");
2922    let ids: Vec<String> = via.iter().filter_map(get_xml_id).collect();
2923    assert_eq!(ids, vec!["S1", "S2"]);
2924  }
2925
2926  /// The id scan must populate the idcache for every `xml:id` (the walk replaces
2927  /// the `//*[@xml:id]` query that overflows libxml2 on huge documents).
2928  #[test]
2929  fn test_scan_ids_populates_idcache() {
2930    let doc = split_doc();
2931    for id in ["P1", "C1", "S1", "S2", "I1", "B1", "S3", "I2"] {
2932      assert!(
2933        doc.find_node_by_id(id).is_some(),
2934        "missing id {id} in idcache"
2935      );
2936    }
2937    assert!(doc.find_node_by_id("nope").is_none());
2938  }
2939
2940  /// #795: every split page carries the parent's `<?latexml …?>` PIs (Perl Post.pm L766-767),
2941  /// before its root, as the main page does, so a custom XSLT sees them on each page.
2942  #[test]
2943  fn split_pages_carry_the_document_pis() {
2944    let doc = make_test_doc(
2945      "<?latexml class=\"article\"?><?latexml RelaxNGSchema=\"LaTeXML\"?>\
2946       <document xmlns='http://dlmf.nist.gov/LaTeXML'><section xml:id='S1'/><section xml:id='S2'/></document>",
2947    );
2948    for id in ["S1", "S2"] {
2949      let page = doc.new_document(
2950        doc.find_node_by_id(id).unwrap().clone(),
2951        &format!("{id}.html"),
2952        None,
2953      );
2954      let xml = page.to_xml_string();
2955      assert!(
2956        xml.contains(
2957          "<?latexml class=\"article\"?>\n<?latexml RelaxNGSchema=\"LaTeXML\"?>\n<section"
2958        ),
2959        "{xml}"
2960      );
2961    }
2962  }
2963
2964  /// A document-level `<?latexml searchpaths=…?>` PI (a sibling of the root
2965  /// element) must still be collected by the walk and its searchpaths applied.
2966  #[test]
2967  fn test_scan_collects_doclevel_pi_searchpaths() {
2968    let doc = make_test_doc(
2969      "<?latexml searchpaths=\"alpha,beta\"?>\
2970       <document xmlns='http://dlmf.nist.gov/LaTeXML'><section xml:id='s1'/></document>",
2971    );
2972    let paths = doc.get_search_paths();
2973    assert!(paths.iter().any(|p| p == "alpha"), "searchpaths: {paths:?}");
2974    assert!(paths.iter().any(|p| p == "beta"), "searchpaths: {paths:?}");
2975  }
2976
2977  #[test]
2978  fn test_uniquify_id() {
2979    let doc = make_test_doc(
2980      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2981         <p xml:id='p1'/>\
2982       </document>",
2983    );
2984    let mut doc = doc;
2985    // First call reserves a unique id based on "p1"
2986    let id1 = doc.uniquify_id("p1", None);
2987    // Second call with same base must produce a different id
2988    let id2 = doc.uniquify_id("p1", None);
2989    assert_ne!(id1, id2);
2990    // Both should start with p1
2991    assert!(id1.starts_with("p1"));
2992    assert!(id2.starts_with("p1"));
2993  }
2994
2995  #[test]
2996  fn test_initial() {
2997    assert_eq!(PostDocument::initial("Hello", false), "H");
2998    assert_eq!(PostDocument::initial("  world", false), "W");
2999    assert_eq!(PostDocument::initial("123abc", true), "A");
3000    assert_eq!(PostDocument::initial("!@#", false), "*");
3001    assert_eq!(PostDocument::initial("\u{00E9}cole", false), "E"); // é NFD-decomposes to e + combining accent
3002  }
3003
3004  #[test]
3005  fn test_add_class() {
3006    let doc = make_test_doc(
3007      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
3008         <p xml:id='p1'/>\
3009       </document>",
3010    );
3011    let mut node = doc.findnode("//ltx:p").unwrap();
3012    PostDocument::add_class(&mut node, "foo bar");
3013    let class = node.get_attribute("class").unwrap();
3014    assert!(class.contains("bar"));
3015    assert!(class.contains("foo"));
3016
3017    // Adding again should not duplicate
3018    PostDocument::add_class(&mut node, "foo");
3019    let class = node.get_attribute("class").unwrap();
3020    let count = class.matches("foo").count();
3021    assert_eq!(count, 1);
3022  }
3023}