Skip to main content

latexml_post/
scan.rs

1//! Document structure scanning processor.
2//!
3//! Port of `LaTeXML::Post::Scan`.
4//! Scans the document for structural elements (sections, figures, equations, etc.)
5//! and records their IDs, labels, titles, and relationships in the ObjectDB.
6//! This data is used by later processors (CrossRef, MakeIndex, etc.).
7
8use latexml_core::common::xml::name_is;
9use libxml::tree::{Node, NodeType};
10use rustc_hash::FxHashMap as HashMap;
11
12use crate::{
13  document::{PostDocument, is_ltx},
14  object_db::{ObjectDB, Value},
15  processor::{ProcessResult, Processor},
16};
17
18/// Scan post-processor: collects structural information into ObjectDB.
19///
20/// Port of `LaTeXML::Post::Scan`.
21pub struct Scan {
22  name:             String,
23  /// Reference to the shared ObjectDB.
24  pub db:           ObjectDB,
25  /// Root document id for the current scan.
26  page_id:          Option<String>,
27  /// Perl's `labelids`: fragment ids are taken from the element's first label (`--splitnaming=label*`).
28  label_ids:        bool,
29  /// Object-count threshold at which the next `Scan: DBStatus:` line is due —
30  /// the line logs when the count PASSES a power of two, not per page. A
31  /// per-page line (Perl's verbosity-gated `NoteProgressDetailed`) wrote
32  /// 115k+ near-identical lines on a book-scale split; exponential backoff
33  /// keeps the growth curve visible in ~20 lines (user directive 2026-08-03).
34  db_status_due_at: usize,
35  /// Whether the most recently scanned page contains a MakeIndex / glossary /
36  /// nomenclature placeholder (`make_index::PLACEHOLDERS`). Recorded during
37  /// Scan's own DOM walk so the driver avoids two redundant full-page XPath
38  /// queries per page on large splits.
39  page_needs_index: bool,
40  /// Whether the most recently scanned page contains an `ltx:bibliography`.
41  page_needs_bib:   bool,
42}
43
44/// Collected properties for a scanned element, ready for DB registration.
45struct ScannedProps {
46  /// Properties to register.
47  props:  Vec<(String, Value)>,
48  /// Labels to register separately.
49  labels: Vec<String>,
50  /// The xml:id of the scanned element.
51  id:     Option<String>,
52}
53
54impl ScannedProps {
55  fn push(&mut self, key: &str, val: Value) { self.props.push((key.to_string(), val)); }
56}
57
58impl Scan {
59  pub fn new(db: ObjectDB) -> Self {
60    Scan {
61      name: "Scan".to_string(),
62      db,
63      page_id: None,
64      label_ids: false,
65      db_status_due_at: 1,
66      page_needs_index: false,
67      page_needs_bib: false,
68    }
69  }
70
71  /// Perl `Scan->new(labelids => …)`, set from `--splitnaming=label*` (`LaTeXML.pm` L462,
72  /// `latexmlpost` L422).
73  pub fn with_label_ids(mut self, label_ids: bool) -> Self {
74    self.label_ids = label_ids;
75    self
76  }
77
78  /// Placeholder flags observed during the most recent `process()` call:
79  /// `(needs_index_or_glossary_or_nomenclature, needs_bibliography)`.
80  pub fn last_page_placeholders(&self) -> (bool, bool) {
81    (self.page_needs_index, self.page_needs_bib)
82  }
83
84  /// Recursively scan a node and its children.
85  ///
86  /// Port of `Scan::scan`.
87  pub fn scan(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
88    if let Some(qname) = doc.get_qname(node) {
89      self.dispatch(doc, node, &qname, parent_id);
90    }
91  }
92
93  /// Dispatch to the appropriate handler based on tag name.
94  fn dispatch(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
95    match tag {
96      "ltx:document" | "ltx:part" | "ltx:chapter" | "ltx:section" | "ltx:appendix"
97      | "ltx:subsection" | "ltx:subsubsection" | "ltx:paragraph" | "ltx:subparagraph"
98      | "ltx:bibliography" | "ltx:index" | "ltx:glossary" | "ltx:theorem" | "ltx:proof" => {
99        match tag {
100          "ltx:bibliography" => self.page_needs_bib = true,
101          "ltx:index" if !self.page_needs_index && !has_ltx_element_child(node, "indexlist") => {
102            self.page_needs_index = true;
103          },
104          "ltx:glossary"
105            if !self.page_needs_index && !has_ltx_element_child(node, "glossarylist") =>
106          {
107            self.page_needs_index = true;
108          },
109          _ => {},
110        }
111        self.section_handler(doc, node, tag, parent_id)
112      },
113      // arXiv-fork (Post/Scan.pm abstract_handler / ack_handler): register
114      // abstract + acknowledgements as primary TOC-able entries whose title
115      // comes from @name (or a default) since they carry no ltx:title.
116      "ltx:abstract" => self.named_handler(doc, node, tag, parent_id, "Abstract"),
117      "ltx:acknowledgements" => self.named_handler(doc, node, tag, parent_id, "Acknowledgements"),
118      "ltx:table" | "ltx:figure" | "ltx:float" | "ltx:listing" => {
119        self.captioned_handler(doc, node, tag, parent_id)
120      },
121      "ltx:equation" | "ltx:equationgroup" | "ltx:item" | "ltx:listingline" => {
122        self.labelled_handler(doc, node, tag, parent_id)
123      },
124      "ltx:anchor" => self.anchor_handler(doc, node, tag, parent_id),
125      // Math subtrees contain thousands of XMTok/XMApp/XMRef/XMWrap/XMDual
126      // nodes with xml:ids that serve only local math-tree navigation —
127      // they're not targets for cross-reference and do not need to appear
128      // in the Scan ObjectDB. Register the outer Math element's id,
129      // then skip descent. This drops Scan time on arXiv:0705.0790
130      // from 11.4 s → <1 s (the 65K XM* nodes were dominating).
131      //
132      // Rust-side intentional divergence from Perl Scan.pm, which
133      // descends blindly — but Perl doesn't emit xml:id on XM*
134      // descendants in the first place, so its default_handler short-
135      // circuits naturally. The ar5iv.sty preload in Rust populates
136      // xml:id everywhere via _ID_counter__, making this skip necessary
137      // for performance parity with Perl.
138      "ltx:Math" => {
139        let id = get_xml_id(node);
140        if let Some(ref id_str) = id {
141          let sp = self.collect_common(doc, node, tag, parent_id);
142          let key = format!("ID:{}", id_str);
143          self.register_scanned(&key, sp);
144          self.add_as_child(id_str, parent_id);
145        }
146        // No scan_children — XM* descendants are skipped.
147      },
148      "ltx:note" => self.note_handler(doc, node, tag, parent_id),
149      "ltx:bibitem" => self.bibitem_handler(doc, node, parent_id),
150      "ltx:bibentry" => {},
151      "ltx:indexmark" => self.indexmark_handler(doc, node, parent_id),
152      "ltx:glossaryentry" | "ltx:glossarydefinition" => {
153        self.glossaryentry_handler(doc, node, tag, parent_id)
154      },
155      "ltx:ref" => self.ref_handler(doc, node, tag, parent_id),
156      "ltx:bibref" => self.bibref_handler(doc, node, tag, parent_id),
157      "ltx:glossaryref" => self.glossaryref_handler(doc, node, tag, parent_id),
158      "ltx:navigation" | "ltx:rawhtml" => {},
159      "ltx:rdf" => self.rdf_handler(node, parent_id),
160      "ltx:declare" => self.declare_handler(doc, node, tag, parent_id),
161      "ltx:description" => {
162        if !self.page_needs_index
163          && node
164            .get_attribute("class")
165            .is_some_and(|c| c.split(' ').any(|cls| cls == "ltx_nomenclature"))
166          && !has_ltx_element_child(node, "item")
167        {
168          self.page_needs_index = true;
169        }
170        self.default_handler(doc, node, tag, parent_id)
171      },
172      _ => self.default_handler(doc, node, tag, parent_id),
173    }
174  }
175
176  /// Scan all element children of a node.
177  pub fn scan_children(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
178    let children = collect_element_children(node);
179    for child in &children {
180      self.scan(doc, child, parent_id);
181    }
182  }
183
184  /// Compute the page ID for the current document.
185  fn page_id(&self, doc: &PostDocument) -> Option<String> {
186    self.page_id.clone().or_else(|| {
187      doc
188        .get_document_element()
189        .and_then(|root| get_xml_id(&root))
190    })
191  }
192
193  /// Compute the fragment ID for a node within its page: Perl `inPageID` (`Scan.pm` L171-194).
194  /// With `labelids` a labelled node's id is its first label, relative to the page root's first
195  /// label; a label is used as is (no NCName cleaning, no clash check — Perl the same).
196  fn in_page_id(&self, doc: &PostDocument, node: &Node) -> Option<String> {
197    let mut id = get_xml_id(node);
198    let mut base_id = self.page_id(doc).unwrap_or_default();
199    // Perl L176-185: label-based ids in the target document.
200    if self.label_ids {
201      if let Some(label) = first_label(node.get_attribute("labels").as_deref()) {
202        id = Some(label);
203        if let Some(base_label) = doc
204          .get_document_element()
205          .and_then(|root| first_label(root.get_attribute("labels").as_deref()))
206        {
207          base_id = base_label;
208        }
209      }
210    }
211    let id = id?;
212    if id == base_id {
213      None
214    } else if !base_id.is_empty() {
215      if let Some(rest) = id.strip_prefix(&base_id).and_then(|r| r.strip_prefix('.')) {
216        Some(rest.to_string())
217      } else {
218        Some(id)
219      }
220    } else {
221      Some(id)
222    }
223  }
224
225  /// Build common properties for a scanned element WITHOUT mutating self.
226  /// Labels and tag nodes are collected but not yet registered.
227  fn collect_common(
228    &mut self,
229    doc: &PostDocument,
230    node: &Node,
231    tag: &str,
232    parent_id: Option<&str>,
233  ) -> ScannedProps {
234    let id = get_xml_id(node);
235    let labels_str = node.get_attribute("labels");
236    let labels: Vec<String> = labels_str
237      .map(|s| s.split_whitespace().map(String::from).collect())
238      .unwrap_or_default();
239
240    let mut sp = ScannedProps { props: Vec::new(), labels, id };
241
242    sp.push("type", Value::from(tag));
243    if let Some(ref id_str) = sp.id {
244      sp.push("id", Value::from(id_str.as_str()));
245    }
246    if let Some(pid) = parent_id {
247      sp.push("parent", Value::from(pid));
248    }
249    if !sp.labels.is_empty() {
250      sp.push("labels", Value::from(sp.labels.clone()));
251    }
252    if let Some(loc) = doc.site_relative_destination() {
253      sp.push("location", Value::from(loc));
254    }
255    if let Some(pageid) = self.page_id(doc) {
256      sp.push("pageid", Value::from(pageid));
257    }
258    if sp.id.is_some() {
259      if let Some(fragid) = self.in_page_id(doc, node) {
260        sp.push("fragid", Value::from(fragid));
261      }
262    }
263
264    // inlist
265    if let Some(listnames) = node.get_attribute("inlist") {
266      let mut inlist = HashMap::default();
267      for name in listnames.split_whitespace() {
268        inlist.insert(name.to_string(), Value::Bool(true));
269      }
270      sp.push("inlist", Value::Hash(inlist));
271    }
272
273    // tag nodes (refnum, typerefnum, etc.)
274    let mut has_refnum = false;
275    for tagnode in child_tag_nodes(node) {
276      let key = if let Some(role) = tagnode.get_attribute("role") {
277        if role.ends_with("refnum") {
278          role
279        } else {
280          format!("tag:{}", role)
281        }
282      } else {
283        "refnum".to_string()
284      };
285      if key == "refnum" {
286        has_refnum = true;
287      }
288      // Perl `Scan.pm` L269: the tag is stored as its `cleanNode` copy, which a reference deep-copies. A tag of text
289      // alone is stored as that text (the same content, no copy); one with markup as its copy, so that a reference
290      // prints a `\tag{$\mathrm{P_1}$}`'s math as math, "(P1)" where the flattened text read "( P 1 )" with the
291      // formula's whitespace (2609.28438, 1905.03839, 2510.06152). Guard
292      // `perfect_kernel_batch78j::cleveref_document_format_with_math_in_the_tag`.
293      let value = if has_markup(&tagnode) {
294        self.clean_node(doc, &tagnode)
295      } else {
296        Value::from(clean_text_content(&tagnode))
297      };
298      sp.push(&key, value);
299    }
300
301    // pdflatex parity (surpass-Perl): a `\label` placed at `\begin{eqnarray}` (or
302    // on a `\nonumber` row) captures the equation counter value at that point.
303    // LaTeX steps `equation` once at `\begin`, so `\@currentlabel` is "1" before
304    // any `\nonumber` retraction, and `\ref` yields "1" — the number the group's
305    // numbered row shows. LaTeXML binds the label to that unnumbered row, which
306    // carries no refnum, so `\ref` fell through to the document title (shared bug
307    // with Perl; witness arXiv 2308.06222 / html_feedback#94). When a *labelled*
308    // equation row inside an `<ltx:equationgroup>` has no refnum of its own,
309    // inherit it from the nearest numbered sibling — following-first (the counter
310    // points at the next number to be shown), else preceding. Only the ObjectDB
311    // entry gains the refnum; the row still shows no number in the document.
312    if tag == "ltx:equation" && !sp.labels.is_empty() && !has_refnum {
313      if let Some(inherited) = group_sibling_refnum(node) {
314        sp.push("refnum", Value::from(inherited));
315      }
316    }
317
318    sp
319  }
320
321  /// Register a ScannedProps into the DB, including labels.
322  fn register_scanned(&mut self, db_key: &str, sp: ScannedProps) {
323    // Register labels
324    if let Some(ref id) = sp.id {
325      for label in &sp.labels {
326        self
327          .db
328          .register(label, vec![("id", Value::from(id.as_str()))]);
329      }
330    }
331    // Register main entry
332    let owned_props: Vec<(&str, Value)> = Vec::new();
333    let entry = self.db.register(db_key, owned_props);
334    for (k, v) in sp.props {
335      entry.set_value(&k, v);
336    }
337  }
338
339  /// Add an ID as a child of a parent entry.
340  fn add_as_child(&mut self, id: &str, parent_id: Option<&str>) {
341    let mut current_parent = parent_id.map(String::from);
342    while let Some(ref pid) = current_parent {
343      let key = format!("ID:{}", pid);
344      let has_children = self
345        .db
346        .lookup(&key)
347        .map(|e| e.has_value("children"))
348        .unwrap_or(false);
349      if has_children {
350        if let Some(entry_mut) = self.db.lookup_mut(&key) {
351          entry_mut.push_new("children", vec![Value::from(id)]);
352        }
353        return;
354      }
355      let parent = self
356        .db
357        .lookup(&key)
358        .and_then(|e| e.get_string("parent").map(String::from));
359      current_parent = parent;
360    }
361  }
362
363  // ======================================================================
364  // Handlers
365
366  fn default_handler(
367    &mut self,
368    doc: &PostDocument,
369    node: &Node,
370    tag: &str,
371    parent_id: Option<&str>,
372  ) {
373    // Mirror Perl Scan.pm default_handler (L272-283): only build ScannedProps
374    // when the node actually carries an xml:id. For typical papers with large
375    // <Math> subtrees, the XMTok/XMApp/XMRef/XMWrap/XMDual descendants have
376    // no id and `collect_common`'s attribute fetches + labels parsing are
377    // pure waste. arXiv:0705.0790 has 65K nodes (37K XMTok alone) and only
378    // ~1K carry ids — skipping collect_common on the other 64K drops Scan
379    // from 11.4 s → sub-second on that paper.
380    let id = get_xml_id(node);
381    if let Some(ref id_str) = id {
382      let sp = self.collect_common(doc, node, tag, parent_id);
383      let key = format!("ID:{}", id_str);
384      self.register_scanned(&key, sp);
385      // Keep the ID entry addressable for refs/URLs, but do not add generic
386      // layout/math/text nodes to section children. TOCs only need primary
387      // structural children, and adding tens of thousands of table cells here
388      // turns Scan into quadratic duplicate checking.
389    }
390    let effective_id = id.as_deref().or(parent_id);
391    self.scan_children(doc, node, effective_id);
392  }
393
394  /// Port of Perl `Scan::cleanNode` (`Scan.pm` L206-214) for an object stored
395  /// as a node: copy `node` into the ObjectDB, then remove every
396  /// `.//ltx:indexmark` from the copy. An `\index` or `\glossary` mark is an
397  /// entry for its list, not text of the title that carries it; left in, its
398  /// phrase reaches the section's `title=` tooltip ("1 Title isec").
399  ///
400  /// `adopt_xml`, not a bare handle: the stored node must outlive this page's
401  /// DOM (freed per-page under streaming). A failed copy degrades to the
402  /// flattened text of `node`, which leaves the marks out too — a poorer TOC
403  /// entry, never a dangling one. Guard
404  /// `doc_changes_index::index_marks_stay_out_of_stored_titles_and_captions`.
405  fn clean_node(&mut self, doc: &PostDocument, node: &Node) -> Value {
406    // Most titles carry no mark: ask the source first, so their copies are
407    // not walked.
408    let has_marks = doc.findnode_at(".//ltx:indexmark", node).is_some();
409    match self.db.adopt_xml(node) {
410      Some(Value::Xml(copy)) => {
411        if has_marks {
412          let mut marks = Vec::new();
413          collect_indexmarks(&copy, &mut marks);
414          for mark in marks {
415            mark.free_subtree();
416          }
417        }
418        Value::Xml(copy)
419      },
420      Some(other) => other,
421      None => Value::from(title_text_content(doc, node).as_str()),
422    }
423  }
424
425  fn section_handler(
426    &mut self,
427    doc: &PostDocument,
428    node: &Node,
429    tag: &str,
430    parent_id: Option<&str>,
431  ) {
432    let mut sp = self.collect_common(doc, node, tag, parent_id);
433    let id = sp.id.clone();
434    if let Some(ref id_str) = id {
435      sp.push("primary", Value::Bool(true));
436      sp.push("children", Value::List(Vec::new()));
437      // Store the title/toctitle NODES (not flattened text), mirroring Perl
438      // Scan (`$$entry{title} = $node`). CrossRef later deep-clones them into
439      // `<ltx:ref>` content via `prepRefText`, so math/markup in a section
440      // title survives into the table of contents (issue #356). The string
441      // form used for the page `<title>`/tooltip is derived on demand via
442      // `title_text_content` in CrossRef::generate_title.
443      // Both are cleaned first (Perl `cleanNode`, `Scan.pm` L290-291; see
444      // `clean_node`), so an `\index`/`\glossary` mark in the title stays out
445      // of the tooltip.
446      if let Some(title_node) = doc.findnode_at("ltx:title", node) {
447        let value = self.clean_node(doc, &title_node);
448        sp.push("title", value);
449      }
450      if let Some(toctitle_node) = doc.findnode_at("ltx:toctitle", node) {
451        let value = self.clean_node(doc, &toctitle_node);
452        sp.push("toctitle", value);
453      }
454      if let Some(stub) = node.get_attribute("stub") {
455        sp.push("stub", Value::from(stub));
456      }
457      let key = format!("ID:{}", id_str);
458      self.register_scanned(&key, sp);
459      self.add_as_child(id_str, parent_id);
460    }
461    let effective_id = id.as_deref().or(parent_id);
462    self.scan_children(doc, node, effective_id);
463  }
464
465  /// arXiv-fork Scan.pm `abstract_handler`/`ack_handler` (one body, two
466  /// defaults): register the element as a primary entry titled from its
467  /// `name` attribute (set by the frontmatter machinery, e.g. "Abstract" /
468  /// "Acknowledgments") or the given default. Unlike the fork we still
469  /// scan children, so labels/ids inside the abstract keep registering
470  /// (the fork's handlers skip descent — an apparent oversight there).
471  fn named_handler(
472    &mut self,
473    doc: &PostDocument,
474    node: &Node,
475    tag: &str,
476    parent_id: Option<&str>,
477    default_name: &str,
478  ) {
479    let mut sp = self.collect_common(doc, node, tag, parent_id);
480    let id = sp.id.clone();
481    if let Some(ref id_str) = id {
482      let name = node
483        .get_attribute("name")
484        .unwrap_or_else(|| default_name.to_string());
485      sp.push("primary", Value::Bool(true));
486      sp.push("children", Value::List(Vec::new()));
487      sp.push("title", Value::from(name.as_str()));
488      sp.push("toctitle", Value::from(name.as_str()));
489      let key = format!("ID:{}", id_str);
490      self.register_scanned(&key, sp);
491      self.add_as_child(id_str, parent_id);
492    }
493    let effective_id = id.as_deref().or(parent_id);
494    self.scan_children(doc, node, effective_id);
495  }
496
497  fn captioned_handler(
498    &mut self,
499    doc: &PostDocument,
500    node: &Node,
501    tag: &str,
502    parent_id: Option<&str>,
503  ) {
504    let mut sp = self.collect_common(doc, node, tag, parent_id);
505    let id = sp.id.clone();
506    if let Some(ref id_str) = id {
507      if let Some(role) = node.get_attribute("role") {
508        sp.push("role", Value::from(role));
509      }
510      let caption = doc
511        .findnode_at("child::ltx:caption", node)
512        .or_else(|| doc.findnode_at("descendant::ltx:caption", node));
513      // Perl `Scan.pm` L311-314 stores the `cleanNode` copies: the list-of-figures entry keeps the caption's math,
514      // citations and tag (`fill_in_bibrefs` fills a copied bibref), and an index mark stays out.
515      if let Some(ref cap) = caption {
516        let value = self.clean_node(doc, cap);
517        sp.push("caption", value);
518      }
519      let toccaption = doc
520        .findnode_at("child::ltx:toccaption", node)
521        .or_else(|| doc.findnode_at("descendant::ltx:toccaption", node));
522      if let Some(ref tc) = toccaption {
523        let value = self.clean_node(doc, tc);
524        sp.push("toccaption", value);
525      }
526      let key = format!("ID:{}", id_str);
527      self.register_scanned(&key, sp);
528      self.add_as_child(id_str, parent_id);
529    }
530    let effective_id = id.as_deref().or(parent_id);
531    self.scan_children(doc, node, effective_id);
532  }
533
534  fn labelled_handler(
535    &mut self,
536    doc: &PostDocument,
537    node: &Node,
538    tag: &str,
539    parent_id: Option<&str>,
540  ) {
541    let mut sp = self.collect_common(doc, node, tag, parent_id);
542    let id = sp.id.clone();
543    if let Some(ref id_str) = id {
544      if let Some(role) = node.get_attribute("role") {
545        sp.push("role", Value::from(role));
546      }
547      let key = format!("ID:{}", id_str);
548      self.register_scanned(&key, sp);
549      self.add_as_child(id_str, parent_id);
550    }
551    let effective_id = id.as_deref().or(parent_id);
552    self.scan_children(doc, node, effective_id);
553  }
554
555  fn anchor_handler(
556    &mut self,
557    doc: &PostDocument,
558    node: &Node,
559    tag: &str,
560    parent_id: Option<&str>,
561  ) {
562    let mut sp = self.collect_common(doc, node, tag, parent_id);
563    let id = sp.id.clone();
564    if let Some(ref id_str) = id {
565      // Perl `Scan.pm` L353: the title is the `cleanNode` copy of the anchor.
566      sp.push("title", Value::from(clean_text_content(node)));
567      let key = format!("ID:{}", id_str);
568      self.register_scanned(&key, sp);
569      self.add_as_child(id_str, parent_id);
570    }
571    let effective_id = id.as_deref().or(parent_id);
572    self.scan_children(doc, node, effective_id);
573  }
574
575  fn note_handler(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
576    let mut sp = self.collect_common(doc, node, tag, parent_id);
577    let id = sp.id.clone();
578    if let Some(ref id_str) = id {
579      if let Some(role) = node.get_attribute("role") {
580        sp.push("role", Value::from(role));
581      }
582      // Store note text content, not XML node reference (avoids dangling refs).
583      // Perl `Scan.pm` L336-337: the `cleanNode` copy, less its `ltx:tags`
584      // (`removeChild`, so only a child `ltx:tags` goes).
585      let mut note = String::new();
586      let mut child = node.get_first_child();
587      while let Some(c) = child {
588        if !(is_ltx(&c) && name_is(&c, "tags")) {
589          note.push_str(&clean_text_content(&c));
590        }
591        child = c.get_next_sibling();
592      }
593      sp.push("note", Value::from(note));
594      let key = format!("ID:{}", id_str);
595      self.register_scanned(&key, sp);
596      self.add_as_child(id_str, parent_id);
597    }
598    let effective_id = id.as_deref().or(parent_id);
599    self.scan_children(doc, node, effective_id);
600  }
601
602  fn bibitem_handler(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
603    let id = match get_xml_id(node) {
604      Some(id) => id,
605      None => {
606        self.scan_children(doc, node, parent_id);
607        return;
608      },
609    };
610
611    let key = node.get_attribute("key");
612    let bib = doc.findnode_at("ancestor-or-self::ltx:bibliography", node);
613    let lists_str = bib
614      .and_then(|b| b.get_attribute("lists"))
615      .unwrap_or_else(|| "bibliography".to_string());
616
617    // Register BIBLABEL entries
618    if let Some(ref bibkey) = key {
619      for list in lists_str.split_whitespace() {
620        let label_key = format!("BIBLABEL:{}:{}", list, bibkey);
621        self
622          .db
623          .register(&label_key, vec![("id", Value::from(id.as_str()))]);
624      }
625    }
626
627    // Build props for bibitem
628    let mut props: Vec<(String, Value)> = Vec::new();
629    props.push(("id".to_string(), Value::from(id.as_str())));
630    props.push(("type".to_string(), Value::from("ltx:bibitem")));
631    if let Some(pid) = parent_id {
632      props.push(("parent".to_string(), Value::from(pid)));
633    }
634    if let Some(ref k) = key {
635      props.push(("bibkey".to_string(), Value::from(k.as_str())));
636    }
637    if let Some(loc) = doc.site_relative_destination() {
638      props.push(("location".to_string(), Value::from(loc)));
639    }
640    if let Some(pageid) = self.page_id(doc) {
641      props.push(("pageid".to_string(), Value::from(pageid)));
642    }
643    if let Some(fragid) = self.in_page_id(doc, node) {
644      props.push(("fragid".to_string(), Value::from(fragid)));
645    }
646
647    props.extend(bibitem_tag_props(doc, node));
648
649    let db_key = format!("ID:{}", id);
650    let entry = self.db.register(&db_key, vec![]);
651    for (k, v) in props {
652      entry.set_value(&k, v);
653    }
654
655    self.scan_children(doc, node, Some(&id));
656  }
657
658  fn ref_handler(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
659    if let Some(label) = node.get_attribute("labelref") {
660      let in_toc = !doc
661        .findnodes_at(
662          "ancestor::ltx:tocentry | ancestor::ltx:bibblock[contains(@class,'ltx_bib_cited')]",
663          Some(node),
664        )
665        .is_empty();
666      if !in_toc {
667        self.db.register(&label, vec![]);
668        if let Some(pid) = parent_id {
669          if let Some(entry) = self.db.lookup_mut(&label) {
670            entry.note_association(&["referrers", pid]);
671          }
672        }
673      }
674    }
675    self.default_handler(doc, node, tag, parent_id);
676  }
677
678  fn bibref_handler(
679    &mut self,
680    doc: &PostDocument,
681    node: &Node,
682    tag: &str,
683    parent_id: Option<&str>,
684  ) {
685    let in_cited = !doc
686      .findnodes_at(
687        "ancestor::ltx:bibblock[contains(@class,'ltx_bib_cited')]",
688        Some(node),
689      )
690      .is_empty();
691    if !in_cited {
692      // A citation that prints its entry whole (show `FullEntry`, biblatex's `\fullcite`): MakeBibliography keeps a
693      // copy of every entry for it (`FULLENTRY` marks the document set, whatever page cites).
694      if node
695        .get_attribute("show")
696        .is_some_and(|show| show.to_ascii_lowercase().contains("fullentry"))
697      {
698        self.db.register("FULLENTRY", vec![]);
699      }
700      if let Some(keys) = node.get_attribute("bibrefs") {
701        let inlist = node.get_attribute("inlist").unwrap_or_default();
702        let mut lists: Vec<&str> = inlist.split_whitespace().collect();
703        lists.push("bibliography");
704        let label_keys: Vec<String> = keys
705          .split(',')
706          .filter(|k| !k.is_empty())
707          .flat_map(|bibkey| {
708            lists
709              .iter()
710              .map(move |list| format!("BIBLABEL:{}:{}", list, bibkey))
711          })
712          .collect();
713        for label_key in &label_keys {
714          self.db.register(label_key, vec![]);
715        }
716        if let Some(pid) = parent_id {
717          for label_key in &label_keys {
718            if let Some(entry) = self.db.lookup_mut(label_key) {
719              entry.note_association(&["referrers", pid]);
720            }
721          }
722        }
723      }
724    }
725    self.default_handler(doc, node, tag, parent_id);
726  }
727
728  fn glossaryref_handler(
729    &mut self,
730    doc: &PostDocument,
731    node: &Node,
732    tag: &str,
733    parent_id: Option<&str>,
734  ) {
735    if let (Some(k), Some(l)) = (node.get_attribute("key"), node.get_attribute("inlist")) {
736      let gkey = format!("GLOSSARY:{}:{}", l, k);
737      self.db.register(&gkey, vec![]);
738      if let Some(pid) = parent_id {
739        if let Some(entry) = self.db.lookup_mut(&gkey) {
740          entry.note_association(&["referrers", pid]);
741        }
742      }
743    }
744    self.default_handler(doc, node, tag, parent_id);
745  }
746
747  fn indexmark_handler(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
748    let phrases = doc.findnodes_at("ltx:indexphrase", Some(node));
749    let see_also = doc.findnodes_at("ltx:indexsee", Some(node));
750
751    let key_parts: Vec<String> = phrases
752      .iter()
753      .filter_map(|p| p.get_attribute("key"))
754      .collect();
755
756    let inlist = node.get_attribute("inlist").map(|listnames| {
757      let mut h = HashMap::default();
758      for name in listnames.split_whitespace() {
759        h.insert(name.to_string(), Value::Bool(true));
760      }
761      Value::Hash(h)
762    });
763    // One entry per list the mark is in, as the `GLOSSARY:<list>:<key>`
764    // entries are: `\glossary`'s `glo` marks must neither merge into nor
765    // leak out of the `idx` index. Perl (Scan.pm:409-414) registers ONE
766    // `INDEX:<keys>` entry per phrase sequence and keeps the first mark's
767    // `inlist`, so a second list's mark with the same phrases joined the first.
768    let lists: Vec<String> = node
769      .get_attribute("inlist")
770      .map(|names| names.split_whitespace().map(str::to_string).collect())
771      .filter(|names: &Vec<String>| !names.is_empty())
772      .unwrap_or_else(|| vec![crate::make_index::DEFAULT_INDEX_LIST.to_string()]);
773    for list in &lists {
774      let key = crate::make_index::index_db_key(list, &key_parts);
775      self.register_indexmark(&key, &phrases, &see_also, inlist.clone(), node, parent_id);
776    }
777  }
778
779  /// Record one `ltx:indexmark` under its list's `INDEX` key: the phrases
780  /// on first sight, then either its see-also phrases or its referrer.
781  fn register_indexmark(
782    &mut self,
783    key: &str,
784    phrases: &[Node],
785    see_also: &[Node],
786    inlist: Option<Value>,
787    node: &Node,
788    parent_id: Option<&str>,
789  ) {
790    let exists = self.db.lookup(key).is_some();
791    if !exists {
792      // Perl registers `phrases => [@phrases]` — the ltx:indexphrase
793      // NODES — so MakeIndex can key the tree off their `key`
794      // attributes and re-render the phrases with their markup
795      // (math inside an index phrase survives into the index).
796      // Adopted BEFORE `register` borrows the entry: `adopt_xml` needs the
797      // DB itself, and the copies must outlive this page's DOM anyway. A
798      // failed copy degrades to the phrase's flattened text.
799      let adopted: Vec<Value> = phrases
800        .iter()
801        .map(|n| {
802          self
803            .db
804            .adopt_xml(n)
805            .unwrap_or_else(|| Value::from(n.get_content().as_str()))
806        })
807        .collect();
808      let mut props = vec![("phrases", Value::List(adopted))];
809      if let Some(il) = inlist {
810        props.push(("inlist", il));
811      }
812      self.db.register(key, props);
813    }
814
815    if !see_also.is_empty() {
816      // Store the ltx:indexsee NODES (not their flattened text): MakeIndex
817      // needs the `name` attribute ("see"/"see also") and the phrase's inline
818      // markup to render the cross-reference. Adopted for the same
819      // lifetime reason as the phrases above.
820      let nodes: Vec<Value> = see_also
821        .iter()
822        .map(|n| {
823          self
824            .db
825            .adopt_xml(n)
826            .unwrap_or_else(|| Value::from(n.get_content().as_str()))
827        })
828        .collect();
829      if let Some(entry) = self.db.lookup_mut(key) {
830        entry.push_new("see_also", nodes);
831      }
832    } else if let Some(pid) = parent_id {
833      let style = node
834        .get_attribute("style")
835        .unwrap_or_else(|| "normal".to_string());
836      if let Some(entry) = self.db.lookup_mut(key) {
837        entry.note_association(&["referrers", pid, &style]);
838      }
839    }
840  }
841
842  fn glossaryentry_handler(
843    &mut self,
844    doc: &PostDocument,
845    node: &Node,
846    tag: &str,
847    parent_id: Option<&str>,
848  ) {
849    let id = if tag == "ltx:glossaryentry" {
850      get_xml_id(node)
851    } else {
852      None
853    };
854    let lists = node.get_attribute("inlist").unwrap_or_else(|| {
855      doc
856        .findnode_at(
857          "ancestor::ltx:glossarylist[@lists] | ancestor::ltx:glossary[@lists]",
858          node,
859        )
860        .and_then(|p| p.get_attribute("lists"))
861        .unwrap_or_else(|| "glossary".to_string())
862    });
863    let key = node.get_attribute("key").unwrap_or_default();
864    let phrases = doc.findnodes_at("ltx:glossaryphrase", Some(node));
865
866    for list in lists.split_whitespace() {
867      let gkey = format!("GLOSSARY:{}:{}", list, key);
868      // Perl Scan.pm:442 stores each phrase NODE, so MakeIndex and CrossRef
869      // re-render it with its markup: a nomenclature symbol is math, and its
870      // flattened text content (the XMath token text) is not the symbol.
871      // Adopted before `register` borrows the entry (as the index phrases
872      // above); a failed copy degrades to the flattened text.
873      let values: Vec<(String, Value)> = phrases
874        .iter()
875        .map(|phrase| {
876          let role = phrase
877            .get_attribute("role")
878            .unwrap_or_else(|| "label".to_string());
879          let value = self
880            .db
881            .adopt_xml(phrase)
882            .unwrap_or_else(|| Value::from(phrase.get_content()));
883          (format!("phrase:{role}"), value)
884        })
885        .collect();
886      let entry = self.db.register(&gkey, vec![]);
887      for (prop_key, value) in values {
888        entry.set_value(&prop_key, value);
889      }
890      if let Some(ref id_str) = id {
891        entry.set_value("id", Value::from(id_str.as_str()));
892      }
893    }
894
895    if let Some(ref id_str) = id {
896      let sp = self.collect_common(doc, node, tag, parent_id);
897      let db_key = format!("ID:{}", id_str);
898      self.register_scanned(&db_key, sp);
899    }
900    let effective_id = id.as_deref().or(parent_id);
901    self.scan_children(doc, node, effective_id);
902  }
903
904  fn rdf_handler(&mut self, node: &Node, parent_id: Option<&str>) {
905    let mut id = node.get_attribute("about");
906    if let Some(ref about) = id {
907      if let Some(stripped) = about.strip_prefix('#') {
908        id = Some(stripped.to_string());
909      }
910    }
911    let id = id.or_else(|| parent_id.map(String::from));
912    let property = node.get_attribute("property");
913    let value = node
914      .get_attribute("resource")
915      .or_else(|| node.get_attribute("content"));
916
917    if let (Some(prop), Some(val), Some(id_str)) = (property, value, id) {
918      let db_key = format!("ID:{}", id_str);
919      let entry = self.db.register(&db_key, vec![]);
920      entry.set_value(&prop, Value::from(val));
921    }
922  }
923
924  fn declare_handler(
925    &mut self,
926    doc: &PostDocument,
927    node: &Node,
928    tag: &str,
929    parent_id: Option<&str>,
930  ) {
931    let decl_type = node.get_attribute("type");
932    let sort = node.get_attribute("sortkey");
933    let decl_id = get_xml_id(node);
934    let definiens = node.get_attribute("definiens");
935
936    // Perl `Scan.pm` L503-504: the term and the description are `cleanNode`
937    // copies, so the definiens search below skips a mark's tokens.
938    let term = doc.findnode_at("child::ltx:tags/ltx:tag[@role='term']", node);
939    let description = doc.findnode_at("child::ltx:text", node);
940
941    if decl_type.as_deref() == Some("definition") {
942      let mut def = definiens.clone();
943      if def.is_none() {
944        if let Some(ref term_node) = term {
945          let syms: Vec<Node> = doc
946            .findnodes_at("descendant-or-self::ltx:XMTok[@meaning]", Some(term_node))
947            .into_iter()
948            .filter(|sym| !in_indexmark_below(sym, term_node))
949            .collect();
950          let mut non_rel = Vec::new();
951          let mut rel = Vec::new();
952          for sym in &syms {
953            let meaning = sym.get_attribute("meaning").unwrap_or_default();
954            if meaning.starts_with("delimited-") {
955              continue;
956            }
957            if sym.with_attribute(c"role", |v| v == "RELOP") == Some(true) {
958              rel.push(meaning);
959            } else {
960              non_rel.push(meaning);
961            }
962          }
963          non_rel.extend(rel);
964          def = non_rel.into_iter().next();
965        }
966      }
967      if let Some(ref def_name) = def {
968        let dkey = format!("DECLARATION:global:{}", def_name);
969        let mut sp = self.collect_common(doc, node, tag, parent_id);
970        if let Some(ref desc) = description {
971          sp.push("description", Value::from(clean_text_content(desc)));
972        }
973        self.register_scanned(&dkey, sp);
974      }
975    } else if decl_type.is_none() && parent_id.is_some() {
976      if let Some(ref did) = decl_id {
977        let has_content =
978          description.is_some() || doc.findnode_at("ltx:tags/ltx:tag", node).is_some();
979        if has_content {
980          let dkey = format!("DECLARATION:local:{}", did);
981          let mut sp = self.collect_common(doc, node, tag, parent_id);
982          if let Some(ref desc) = description {
983            sp.push("description", Value::from(clean_text_content(desc)));
984          }
985          self.register_scanned(&dkey, sp);
986        }
987      }
988    }
989
990    if let Some(ref sk) = sort {
991      let name = definiens.as_deref().or(decl_id.as_deref()).unwrap_or(sk);
992      let nkey = format!("NOTATION:{}", name);
993      let mut sp = self.collect_common(doc, node, tag, parent_id);
994      sp.push("sortkey", Value::from(sk.as_str()));
995      if let Some(ref desc) = description {
996        sp.push("description", Value::from(clean_text_content(desc)));
997      }
998      self.register_scanned(&nkey, sp);
999    }
1000  }
1001}
1002
1003/// The first of a `labels` attribute's labels, its `LABEL:` prefix dropped (Perl `Scan.pm` L178-179).
1004fn first_label(labels: Option<&str>) -> Option<String> {
1005  let first = labels?.split_whitespace().next()?;
1006  Some(first.strip_prefix("LABEL:").unwrap_or(first).to_string())
1007}
1008
1009impl Processor for Scan {
1010  fn get_name(&self) -> &str { &self.name }
1011
1012  fn process(&mut self, doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
1013    self.page_needs_index = false;
1014    self.page_needs_bib = false;
1015
1016    let root = match doc.get_document_element() {
1017      Some(r) => r,
1018      None => return Ok(vec![doc]),
1019    };
1020
1021    let id = get_xml_id(&root).unwrap_or_else(|| {
1022      let mut root_mut = root.clone();
1023      root_mut.set_attribute("xml:id", "Document").ok();
1024      "Document".to_string()
1025    });
1026
1027    if self.db.lookup("SITE_ROOT").is_none() {
1028      self
1029        .db
1030        .register("SITE_ROOT", vec![("id", Value::from(id.as_str()))]);
1031    }
1032
1033    self.page_id = Some(id.clone());
1034    // Perl Scan.pm:99: a split page is filed under the page Split took it from; the guesses
1035    // below are only for a document without one (an id renumbered by `\@addtoreset{chapter}{part}`
1036    // defeats the id-prefix guess: `Ch1.S1` under Part II's `Ch1a`; witness: issue 777's book, 9,262
1037    // of 115,519 pages).
1038    self.scan(&doc, &root, doc.parent_id.as_deref());
1039    self.page_id = None;
1040
1041    let loc = doc.site_relative_destination().unwrap_or_default();
1042    let doc_key = format!("DOCUMENT:{}", loc);
1043    self
1044      .db
1045      .register(&doc_key, vec![("id", Value::from(id.as_str()))]);
1046
1047    // Perl Post::Scan L108-133: a doc that is not the site root and whose entry still has no
1048    // parent (one Split did not produce: Split's pages got theirs from `parent_id` above)
1049    // infers one, the nearest id-prefix ancestor already scanned, else the site root. Perl's
1050    // other guess, an `index.xml` in a containing directory (Scan.pm:117-124), matters only
1051    // for multi-document sites and is not ported.
1052    let site_id = self
1053      .db
1054      .lookup("SITE_ROOT")
1055      .and_then(|e| e.get_string("id").map(String::from))
1056      .unwrap_or_default();
1057    let id_key = format!("ID:{}", id);
1058    let needs_parent = self
1059      .db
1060      .lookup(&id_key)
1061      .map(|e| !e.has_value("parent"))
1062      .unwrap_or(false);
1063    if !site_id.is_empty() && id != site_id && needs_parent {
1064      // 1) Strip ".suffix" iteratively to find an ancestor id already in DB.
1065      let mut parent_id: Option<String> = None;
1066      let mut upid = id.clone();
1067      while let Some(dot) = upid.rfind('.') {
1068        upid.truncate(dot);
1069        if !upid.is_empty() && self.db.lookup(&format!("ID:{}", upid)).is_some() {
1070          parent_id = Some(upid.clone());
1071          break;
1072        }
1073      }
1074      // 2) Fallback to the site root.
1075      if parent_id.is_none() {
1076        parent_id = Some(site_id);
1077      }
1078      if let Some(pid) = parent_id {
1079        if pid != id {
1080          if let Some(entry_mut) = self.db.lookup_mut(&id_key) {
1081            entry_mut.set_values(vec![("parent", Value::from(pid.as_str()))]);
1082          }
1083          self.add_as_child(&id, Some(&pid));
1084        }
1085      }
1086    }
1087
1088    // Exponential backoff: log only when the object count passes the next
1089    // power of two (see the `db_status_due_at` field docs).
1090    if self.db.len() >= self.db_status_due_at {
1091      Info!("scan", "db_status", "Scan: DBStatus: {}", self.db.status());
1092      self.db_status_due_at = (self.db.len() + 1).next_power_of_two();
1093    }
1094    Ok(vec![doc])
1095  }
1096}
1097
1098// ======================================================================
1099// Helpers
1100
1101/// Read a `<ltx:bibitem>`'s `<ltx:tags>/<ltx:tag role="…">` children into the
1102/// ObjectDB props CrossRef's fill phase (`make_bibcite`) reads: `authors`,
1103/// `fullauthors`, `year`, `number`, `refnum`, `title`, plus `keytag` (role
1104/// `key`) and `typetag` (role `bibtype`). Port of Perl `Scan::bibitem_handler`
1105/// (Scan.pm L475-483). Shared by `Scan::bibitem_handler` (the initial scan of
1106/// authored `\bibitem`s) and `MakeBibliography`'s rescan of the bibitems it
1107/// generates from `.bib`/`.bbl` — the same values, from whichever pass first
1108/// produced the formatted entry, so an author-year inline citation resolves to
1109/// the SAME author-year label the References list shows.
1110pub fn bibitem_tag_props(doc: &PostDocument, node: &Node) -> Vec<(String, Value)> {
1111  let mut props = Vec::new();
1112  for role in &[
1113    "authors",
1114    "fullauthors",
1115    "year",
1116    "number",
1117    "refnum",
1118    "title",
1119    "key",
1120    "bibtype",
1121  ] {
1122    let xpath = format!("ltx:tags/ltx:tag[@role='{}']", role);
1123    if let Some(tagnode) = doc.findnode_at(&xpath, node) {
1124      let prop_name = match *role {
1125        "key" => "keytag",
1126        "bibtype" => "typetag",
1127        _ => *role,
1128      };
1129      props.push((prop_name.to_string(), Value::from(tagnode.get_content())));
1130    }
1131  }
1132  props
1133}
1134
1135fn collect_element_children(node: &Node) -> Vec<Node> {
1136  let mut result = Vec::new();
1137  if let Some(child) = node.get_first_child() {
1138    let mut current = Some(child);
1139    while let Some(ref c) = current {
1140      if c.get_type() == Some(NodeType::ElementNode) {
1141        result.push(c.clone());
1142      }
1143      current = c.get_next_sibling();
1144    }
1145  }
1146  result
1147}
1148
1149/// The plain `refnum` text of an equation row (its `<ltx:tag role="refnum">`),
1150/// if it carries one. Used to let a labelled but unnumbered eqnarray row inherit
1151/// its group's number (html_feedback#94).
1152fn equation_refnum_text(node: &Node) -> Option<String> {
1153  for t in child_tag_nodes(node) {
1154    if t.with_attribute(c"role", |v| v == "refnum") == Some(true) {
1155      // Cleaned, as the row's own refnum is (`collect_common`).
1156      let txt = clean_text_content(&t);
1157      if !txt.trim().is_empty() {
1158        return Some(txt);
1159      }
1160    }
1161  }
1162  None
1163}
1164
1165/// For a labelled `<ltx:equation>` with no refnum of its own, find the number it
1166/// should reference: the nearest numbered sibling equation in the same
1167/// `<ltx:equationgroup>`, scanning following siblings first (the equation
1168/// counter, captured at `\label` time, points at the next number to be shown),
1169/// then preceding. Returns None when the parent is not an equationgroup or no
1170/// sibling is numbered. See `collect_common` (html_feedback#94).
1171fn group_sibling_refnum(node: &Node) -> Option<String> {
1172  let parent = node.get_parent()?;
1173  if !name_is(&parent, "equationgroup") {
1174    return None;
1175  }
1176  let is_equation =
1177    |n: &Node| n.get_type() == Some(NodeType::ElementNode) && name_is(n, "equation");
1178  let mut fwd = node.get_next_sibling();
1179  while let Some(sib) = fwd {
1180    if is_equation(&sib) {
1181      if let Some(r) = equation_refnum_text(&sib) {
1182        return Some(r);
1183      }
1184    }
1185    fwd = sib.get_next_sibling();
1186  }
1187  let mut back = node.get_prev_sibling();
1188  while let Some(sib) = back {
1189    if is_equation(&sib) {
1190      if let Some(r) = equation_refnum_text(&sib) {
1191        return Some(r);
1192      }
1193    }
1194    back = sib.get_prev_sibling();
1195  }
1196  None
1197}
1198
1199fn child_tag_nodes(node: &Node) -> Vec<Node> {
1200  let mut result = Vec::new();
1201  let mut child = node.get_first_child();
1202  while let Some(c) = child {
1203    if c.get_type() == Some(NodeType::ElementNode) && name_is(&c, "tags") {
1204      let mut tag_child = c.get_first_child();
1205      while let Some(t) = tag_child {
1206        if t.get_type() == Some(NodeType::ElementNode) && name_is(&t, "tag") {
1207          result.push(t.clone());
1208        }
1209        tag_child = t.get_next_sibling();
1210      }
1211    }
1212    child = c.get_next_sibling();
1213  }
1214  result
1215}
1216
1217/// Is `node` an `ltx:indexmark` — what Perl `Scan::cleanNode` removes?
1218fn is_indexmark(node: &Node) -> bool {
1219  node.get_type() == Some(NodeType::ElementNode) && name_is(node, "indexmark") && is_ltx(node)
1220}
1221
1222/// Every `ltx:indexmark` below `node`, outermost first; a mark nested in a
1223/// mark goes with it.
1224fn collect_indexmarks(node: &Node, marks: &mut Vec<Node>) {
1225  let mut child = node.get_first_child();
1226  while let Some(c) = child {
1227    if is_indexmark(&c) {
1228      marks.push(c.clone());
1229    } else {
1230      collect_indexmarks(&c, marks);
1231    }
1232    child = c.get_next_sibling();
1233  }
1234}
1235
1236/// Does `node` lie inside an `ltx:indexmark` below `top` — would Perl's
1237/// `cleanNode` copy of `top` have lost it?
1238fn in_indexmark_below(node: &Node, top: &Node) -> bool {
1239  let mut current = (node != top).then(|| node.get_parent()).flatten();
1240  while let Some(n) = current {
1241    if n == *top {
1242      return false;
1243    }
1244    if is_indexmark(&n) {
1245      return true;
1246    }
1247    current = n.get_parent();
1248  }
1249  false
1250}
1251
1252/// The text content of Perl `Scan::cleanNode`'s copy of `node` (`Scan.pm`
1253/// L206-214): `node`'s text with every `ltx:indexmark` subtree left out. The
1254/// entries this port stores as strings (tags, notes, anchor titles) take it
1255/// where Perl stores the cleaned node. Text, CDATA and entity-reference nodes
1256/// count, as in libxml2's `xmlNodeGetContent`; nothing is copied. Guard
1257/// `doc_changes_index::index_marks_stay_out_of_stored_titles_and_captions`.
1258fn clean_text_content(node: &Node) -> String {
1259  let mut text = String::new();
1260  push_clean_text(node, &mut text);
1261  text
1262}
1263
1264/// Whether `node` holds markup: an element child with text, other than an `ltx:indexmark` (which a stored copy leaves
1265/// out). An empty one (a name's `<ltx:text/>` from a group that typeset nothing) adds nothing to the text.
1266fn has_markup(node: &Node) -> bool {
1267  std::iter::successors(node.get_first_child(), |child| child.get_next_sibling()).any(|child| {
1268    child.get_type() == Some(NodeType::ElementNode)
1269      && !is_indexmark(&child)
1270      && !clean_text_content(&child).trim().is_empty()
1271  })
1272}
1273
1274fn push_clean_text(node: &Node, text: &mut String) {
1275  match node.get_type() {
1276    Some(NodeType::TextNode) | Some(NodeType::CDataSectionNode) | Some(NodeType::EntityRefNode) => {
1277      text.push_str(&node.get_content());
1278    },
1279    Some(NodeType::ElementNode) if !is_indexmark(node) => {
1280      let mut child = node.get_first_child();
1281      while let Some(c) = child {
1282        push_clean_text(&c, text);
1283        child = c.get_next_sibling();
1284      }
1285    },
1286    _ => {},
1287  }
1288}
1289
1290/// True iff `node` has a direct `ltx:<local>` element child (mirrors XPath
1291/// `ltx:indexlist` / `ltx:glossarylist` / `ltx:item` child predicates).
1292fn has_ltx_element_child(node: &Node, local: &str) -> bool {
1293  let mut child = node.get_first_child();
1294  while let Some(c) = child {
1295    if c.get_type() == Some(NodeType::ElementNode) && is_ltx(&c) && name_is(&c, local) {
1296      return true;
1297    }
1298    child = c.get_next_sibling();
1299  }
1300  false
1301}
1302
1303/// Get xml:id from a node, trying both attribute forms.
1304fn get_xml_id(node: &Node) -> Option<String> {
1305  node
1306    .get_attribute("xml:id")
1307    .or_else(|| node.get_attribute_ns("id", "http://www.w3.org/XML/1998/namespace"))
1308}
1309
1310/// Extract text content from a node tree, honoring `open`/`close` attributes on `ltx:tag`.
1311///
1312/// Perl uses cloneNode(1) + full DOM rendering, so `<tag close=" ">A</tag>GPT-4o`
1313/// renders as "A GPT-4o". Our get_content() would give "AGPT-4o".
1314/// This function inserts the `open`/`close` attribute values around tag elements.
1315///
1316/// This is the derived STRING form of a title (page `<title>`, `title=`
1317/// tooltip). The rich node form is kept in the ObjectDB (`Value::Xml`) so
1318/// CrossRef can deep-clone it into `<ltx:ref>` content. Mirrors Perl
1319/// `CrossRef::getTextContent_rec` (`CrossRef.pm` L861-879): `ltx:tag` open/close
1320/// handling, plus the `ltx:Math → unicodemath` branch — a title's math renders
1321/// as presentation-order infix Unicode (`sin𝑥=𝑥`), NOT the raw content-tree
1322/// token text, which is operator-first and whitespace-laden (issue #761).
1323///
1324/// Whitespace collapse is applied by the caller ([`value_text`] =
1325/// `getTextContent`), matching Perl's split of the two functions.
1326///
1327/// [`value_text`]: crate::crossref
1328pub(crate) fn title_text_content(doc: &PostDocument, node: &Node) -> String {
1329  let mut result = String::new();
1330  let mut child = node.get_first_child();
1331  while let Some(c) = child {
1332    result.push_str(&title_node_text(doc, &c));
1333    child = c.get_next_sibling();
1334  }
1335  result
1336}
1337
1338/// The text one node of a title contributes to [`title_text_content`].
1339pub(crate) fn title_node_text(doc: &PostDocument, c: &Node) -> String {
1340  match c.get_type() {
1341    Some(NodeType::TextNode) => c.get_content(),
1342    // A mark adds no text: stored titles are `cleanNode` copies already,
1343    // and `Scan::clean_node`'s fallback reads the live title.
1344    Some(NodeType::ElementNode) if is_indexmark(c) => String::new(),
1345    Some(NodeType::ElementNode) => {
1346      let name = c.get_name();
1347      if name == "tag" {
1348        // Honor open/close attributes on <ltx:tag> (Perl `CrossRef.pm` L866-870).
1349        // Perl reads the tag's `textContent`, a formula's bare tokens with its
1350        // fonts and scripts dropped (`latexmlc`: `\tag{$\mathrm{P_1}$}` "P1",
1351        // `^\mathcal{S}` "S"); we read it as the rest of the title, its math as
1352        // UnicodeMath ("P₁", "^𝒮"). OXIDIZED_DESIGN_DIVERGENCES #1094.
1353        let mut result = c.get_attribute("open").unwrap_or_default();
1354        result.push_str(&title_text_content(doc, c));
1355        if let Some(close) = c.get_attribute("close") {
1356          result.push_str(&close);
1357        }
1358        result
1359      } else if name == "Math" {
1360        // Perl `CrossRef.pm` L872-873: `return unicodemath($doc, $node)` — the
1361        // presentation branch of the math, in reading order. Without this a
1362        // math title flattened to its XMApp/XMDual content tree (operator
1363        // first: `= sin x x`) with every inter-token newline preserved.
1364        crate::unicode_math::unicodemath(doc, c)
1365      } else {
1366        title_text_content(doc, c)
1367      }
1368    },
1369    _ => String::new(),
1370  }
1371}
1372
1373// NOTE: Perl uses cloneNode(1) for deep DOM copies. Every node stored in the
1374// ObjectDB is ADOPTED first (`ObjectDB::adopt_xml` — a deep copy into a
1375// DB-owned document), so stored values live exactly as long as the DB and
1376// never dangle into a page document that streaming has freed. Consumers still
1377// deep-copy on materialization (`PostDocument::add_xml_node`, with cross-doc
1378// namespace reconciliation + xml:id uniquification). Section titles are kept
1379// as nodes (see `section_handler`); the derived string form is
1380// `title_text_content`. Index `phrases`/`see_also` values are also stored as
1381// (adopted) `Value::Xml`.
1382
1383#[cfg(test)]
1384mod tests {
1385  use super::*;
1386  use crate::document::PostDocumentOptions;
1387
1388  #[test]
1389  fn scan_tracks_page_placeholders_identically_to_xpath() {
1390    let cases = [
1391      (
1392        "plain",
1393        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D1"><section xml:id="S1"><p>Hello</p></section></document>"#,
1394        (false, false),
1395      ),
1396      (
1397        "empty_index",
1398        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D2"><index xml:id="I1"/></document>"#,
1399        (true, false),
1400      ),
1401      (
1402        "filled_index",
1403        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D3"><index xml:id="I2"><indexlist/></index></document>"#,
1404        (false, false),
1405      ),
1406      (
1407        "empty_glossary",
1408        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D4"><glossary xml:id="G1"/></document>"#,
1409        (true, false),
1410      ),
1411      (
1412        "filled_glossary",
1413        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D5"><glossary xml:id="G2"><glossarylist/></glossary></document>"#,
1414        (false, false),
1415      ),
1416      (
1417        "empty_nomenclature",
1418        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D6"><description class="ltx_nomenclature"/></document>"#,
1419        (true, false),
1420      ),
1421      (
1422        "filled_nomenclature",
1423        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D7"><description class="foo ltx_nomenclature"><item/></description></document>"#,
1424        (false, false),
1425      ),
1426      (
1427        "bibliography",
1428        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D8"><bibliography xml:id="B1" files="refs"/></document>"#,
1429        (false, true),
1430      ),
1431      (
1432        "both",
1433        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D9"><index xml:id="I3"/><bibliography xml:id="B2" files="refs"/></document>"#,
1434        (true, true),
1435      ),
1436    ];
1437    let mut scanner = Scan::new(ObjectDB::new());
1438    for (name, xml, expected) in cases {
1439      let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default()).expect(name);
1440      let nodes = scanner.to_process(&doc);
1441      let out = scanner.process(doc, nodes).expect(name);
1442      let xpath = (
1443        !out[0].findnodes(crate::make_index::PLACEHOLDERS).is_empty(),
1444        !out[0].findnodes("//ltx:bibliography").is_empty(),
1445      );
1446      assert_eq!(scanner.last_page_placeholders(), expected, "case {name}");
1447      assert_eq!(
1448        scanner.last_page_placeholders(),
1449        xpath,
1450        "xpath parity {name}"
1451      );
1452    }
1453  }
1454}