Skip to main content

latexml_post/
make_index.rs

1//! Index generation processor.
2//!
3//! Port of `LaTeXML::Post::MakeIndex` (504 lines of Perl).
4//! Collects INDEX:* entries from the ObjectDB, builds a tree of index entries
5//! grouped by initial letter, and fills in `ltx:index` and `ltx:glossary` elements.
6//! Supports permuted indexes, splitting by initial, see-also references,
7//! range-style page references, and glossary entry formatting.
8
9use latexml_core::common::{cleaners::clean_class_name, xml::name_is};
10use libxml::tree::{Node, NodeType};
11use rustc_hash::FxHashMap as HashMap;
12use unicode_normalization::UnicodeNormalization;
13
14use crate::{
15  document::{NodeData, PostDocument},
16  object_db::{ObjectDB, Value},
17  processor::{ProcessResult, Processor},
18};
19
20/// The list an `ltx:indexmark` without `inlist` belongs to, and the list an
21/// `ltx:index` without `lists` collects: `\index` writes `\jobname.idx`
22/// (Perl MakeIndex.pm:77 `$defaultlistname`).
23pub const DEFAULT_INDEX_LIST: &str = "idx";
24
25/// The ObjectDB key of an index entry: `INDEX:<phrase keys>` in the default
26/// list (Perl's key, unchanged), `INDEX@<list>:<phrase keys>` in another —
27/// one entry per list, as `GLOSSARY:<list>:<key>`.
28pub fn index_db_key(list: &str, phrase_keys: &[String]) -> String {
29  if list == DEFAULT_INDEX_LIST {
30    format!("INDEX:{}", phrase_keys.join(":"))
31  } else {
32    format!("INDEX@{list}:{}", phrase_keys.join(":"))
33  }
34}
35
36/// The list of an index-entry key, and its phrase keys joined by `:` —
37/// the inverse of [`index_db_key`]; None for any other key.
38fn index_db_list(key: &str) -> Option<(&str, &str)> {
39  if let Some(phrases) = key.strip_prefix("INDEX:") {
40    return Some((DEFAULT_INDEX_LIST, phrases));
41  }
42  key.strip_prefix("INDEX@")?.split_once(':')
43}
44
45/// A see/see-also cross reference extracted from an `ltx:indexsee` node.
46#[derive(Debug)]
47struct SeeAlso {
48  /// The cross-reference word from the `name` attribute ("see", "see also").
49  name: Option<String>,
50  /// Normalized text content, used to resolve the target entry.
51  text: String,
52  /// The original node, for re-rendering the phrase with its markup.
53  node: Option<Node>,
54}
55
56/// One level of an index phrase, as collected by Scan: the sort/merge
57/// key plus the original `ltx:indexphrase` node (when available) for
58/// markup-preserving rendering.
59#[derive(Debug, Clone)]
60struct PhraseRef {
61  key:  String,
62  text: String,
63  node: Option<Node>,
64}
65
66/// Index tree node.
67#[derive(Debug)]
68struct IndexTree {
69  id:               String,
70  key:              Option<String>,
71  full_key:         Option<String>,
72  phrase:           Option<String>,
73  phrase_node:      Option<Node>,
74  phrase_text:      Option<String>,
75  full_phrase_text: Option<String>,
76  subtrees:         HashMap<String, IndexTree>,
77  referrers:        HashMap<String, HashMap<String, bool>>,
78  see_also:         Vec<SeeAlso>,
79}
80
81impl IndexTree {
82  fn new(id: &str) -> Self {
83    IndexTree {
84      id:               id.to_string(),
85      key:              None,
86      full_key:         None,
87      phrase:           None,
88      phrase_node:      None,
89      phrase_text:      None,
90      full_phrase_text: None,
91      subtrees:         HashMap::default(),
92      referrers:        HashMap::default(),
93      see_also:         Vec::new(),
94    }
95  }
96}
97
98/// The lists MakeIndex fills: an empty index or glossary, and nomencl's list in a box, a `description` (OD #1098).
99pub const PLACEHOLDERS: &str = "//ltx:index[not(ltx:indexlist)] | //ltx:glossary[not(ltx:glossarylist)] \
100   | //ltx:description[contains(concat(' ', @class, ' '), ' ltx_nomenclature ')][not(ltx:item)]";
101
102/// A glossary entry ready for rendering.
103struct GlossaryEntry {
104  /// The entry's key, and its parent's when it is listed under one (glossaries' `parent=`).
105  key:       String,
106  /// The listed entry's `xml:id`: `<glossary id>.<key>`.
107  id:        String,
108  parent:    Option<String>,
109  initial:   String,
110  sort_key:  String,
111  /// The makeindex group heading of the entry's initial (nomencl's `\nomgroup`), empty when there is none.
112  group:     Vec<NodeData>,
113  formatted: NodeData,
114}
115
116/// MakeIndex post-processor.
117///
118/// Port of `LaTeXML::Post::MakeIndex`.
119pub struct MakeIndex {
120  name:     String,
121  pub db:   ObjectDB,
122  permuted: bool,
123  split:    bool,
124}
125
126impl MakeIndex {
127  pub fn new(db: ObjectDB, split: bool, permuted: bool) -> Self {
128    MakeIndex {
129      name: "MakeIndex".to_string(),
130      db,
131      split,
132      permuted,
133    }
134  }
135
136  /// Build the index tree from the ObjectDB entries of `lists` (the
137  /// `ltx:index` element's `lists`).
138  ///
139  /// Port of `MakeIndex::build_tree`. Perl names the list but builds only
140  /// `idx` ("Eventually customizable for different indices?",
141  /// MakeIndex.pm:78), and its :89 test compares the scanned `inlist` HASH
142  /// with `idx`, so a mark with any list is skipped. Every `ltx:index` here
143  /// collects its own lists: the `.gls` stand-in's `glo` change history
144  /// beside the `idx` index (OXIDIZED_DESIGN_DIVERGENCES #318).
145  fn build_tree(
146    &self,
147    index_id: &str,
148    lists: &[&str],
149  ) -> Option<(IndexTree, HashMap<String, String>)> {
150    let keys: Vec<String> = self
151      .db
152      .get_keys()
153      .into_iter()
154      .filter(|k| index_db_list(k).is_some_and(|(list, _)| lists.contains(&list)))
155      .cloned()
156      .collect();
157    if keys.is_empty() {
158      return None;
159    }
160    Info!("make_index", "count", "MakeIndex: {} entries", keys.len());
161
162    let mut all_phrases: HashMap<String, String> = HashMap::default();
163    let mut tree = IndexTree::new(index_id);
164    // Perl's final rescan runs every generated id through uniquifyID;
165    // we dedup inline. Distinct phrases can strip to the same
166    // alphanumeric key id (e.g. "probability density, ε-biased" with
167    // and without the space → idx.probabilitydensityepsilonbiased),
168    // which would otherwise emit a duplicate HTML id. Seeded with the
169    // index root id so children can't collide with it.
170    let mut used_ids: HashMap<String, u32> = HashMap::default();
171    used_ids.insert(index_id.to_string(), 0);
172
173    for key in &keys {
174      if let Some(entry) = self.db.lookup(key) {
175        // Perl drives the tree off the scanned ltx:indexphrase NODES
176        // (`$entry->getValue('phrases')`): the `key` attribute is the
177        // sort/merge key, the node itself re-renders the phrase with
178        // its markup. Fall back to splitting the DB key for entries
179        // scanned without nodes.
180        let mut phrase_refs: Vec<PhraseRef> = Vec::new();
181        if let Some(Value::List(phrase_nodes)) = entry.get_value("phrases") {
182          for item in phrase_nodes {
183            if let Value::Xml(node) = item {
184              let nkey = node
185                .get_attribute("key")
186                .unwrap_or_else(|| get_index_content_key(&node.get_content()));
187              phrase_refs.push(PhraseRef {
188                key:  nkey,
189                text: get_index_content_key(&node.get_content()),
190                node: Some(node.clone()),
191              });
192            }
193          }
194        }
195        if phrase_refs.is_empty() {
196          phrase_refs = index_db_list(key)
197            .map_or("", |(_, phrases)| phrases)
198            .split(':')
199            .filter(|s| !s.is_empty())
200            .map(|s| PhraseRef {
201              key:  s.to_string(),
202              text: s.to_string(),
203              node: None,
204            })
205            .collect();
206        }
207        if phrase_refs.is_empty() {
208          Warn!("expected", key, "Missing phrases in indexmark: '{}'", key);
209          continue;
210        }
211
212        if self.permuted {
213          // Cyclic permutations of phrase keys
214          for perm in cyclic_permute(&phrase_refs) {
215            if self.split {
216              let init = initial_letter(&perm[0].key);
217              let subtree = tree.subtrees.entry(init.clone()).or_insert_with(|| {
218                let mut st = IndexTree::new(&tree.id);
219                st.phrase = Some(init);
220                st
221              });
222              add_tree_rec(subtree, &perm, &mut all_phrases, &mut used_ids, entry);
223            } else {
224              add_tree_rec(&mut tree, &perm, &mut all_phrases, &mut used_ids, entry);
225            }
226          }
227        } else if self.split {
228          let init = initial_letter(&phrase_refs[0].key);
229          let subtree = tree.subtrees.entry(init.clone()).or_insert_with(|| {
230            let mut st = IndexTree::new(&tree.id);
231            st.phrase = Some(init);
232            st
233          });
234          add_tree_rec(
235            subtree,
236            &phrase_refs,
237            &mut all_phrases,
238            &mut used_ids,
239            entry,
240          );
241        } else {
242          add_tree_rec(
243            &mut tree,
244            &phrase_refs,
245            &mut all_phrases,
246            &mut used_ids,
247            entry,
248          );
249        }
250      }
251    }
252    Some((tree, all_phrases))
253  }
254
255  /// Generate XML for an index list from a tree.
256  ///
257  /// `ancestor_phrases` carries the full_phrase_text of each enclosing
258  /// entry (outermost first) — Perl reaches the same context by walking
259  /// the tree's parent pointers in `lookupSeealsoPhrase`.
260  fn make_index_list(
261    &self,
262    all_phrases: &HashMap<String, String>,
263    tree: &IndexTree,
264    ancestor_phrases: &[String],
265  ) -> Option<NodeData> {
266    if tree.subtrees.is_empty() {
267      return None;
268    }
269    let mut sorted_keys: Vec<&String> = tree.subtrees.keys().collect();
270    sorted_keys.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()).then(a.cmp(b)));
271
272    let entries: Vec<NodeData> = sorted_keys
273      .iter()
274      .filter_map(|key| {
275        tree
276          .subtrees
277          .get(*key)
278          .map(|st| self.make_index_entry(all_phrases, st, ancestor_phrases))
279      })
280      .collect();
281    if entries.is_empty() {
282      return None;
283    }
284    Some(NodeData::Element {
285      tag:        "ltx:indexlist".to_string(),
286      attributes: None,
287      children:   entries,
288    })
289  }
290
291  /// Generate a single index entry with sub-entries, references, and see-also.
292  ///
293  /// Port of `MakeIndex::makeIndexEntry`.
294  fn make_index_entry(
295    &self,
296    all_phrases: &HashMap<String, String>,
297    tree: &IndexTree,
298    ancestor_phrases: &[String],
299  ) -> NodeData {
300    let mut children = Vec::new();
301
302    // Phrase: re-render the scanned ltx:indexphrase node when we have
303    // one (math and styled text inside the phrase survive); plain text
304    // otherwise. Perl: `$doc->trimChildNodes($$tree{phrase})`.
305    if tree.phrase.is_some() || tree.phrase_node.is_some() {
306      let phrase_children: Vec<NodeData> = match tree.phrase_node {
307        Some(ref n) => trimmed_child_nodes(n),
308        None => vec![NodeData::Text(tree.phrase.clone().unwrap_or_default())],
309      };
310      children.push(NodeData::Element {
311        tag:        "ltx:indexphrase".to_string(),
312        attributes: tree
313          .key
314          .as_ref()
315          .map(|k| HashMap::from_iter([("key".to_string(), k.clone())])),
316        children:   phrase_children,
317      });
318    }
319
320    // Referrer links (combined with range handling). Perl prefixes
321    // them with a one-space ltx:text separating phrase from refs.
322    let mut links = Vec::new();
323    if !tree.referrers.is_empty() {
324      links.push(NodeData::Element {
325        tag:        "ltx:text".to_string(),
326        attributes: None,
327        children:   vec![NodeData::Text(" ".to_string())],
328      });
329      links.extend(self.combine_index_entries(&tree.referrers));
330    }
331
332    // See/see-also cross references (Perl makeIndexEntry): each gets
333    // a ", " separator, the italic name word ("see", "see also") when
334    // present, and the phrase — resolved to a linked target entry via
335    // seealsoSearch when possible, with its original markup.
336    //
337    // Lookup context, innermost first (Perl walks parent pointers):
338    // this entry's full phrase, each ancestor's, then bare top-level.
339    let mut see_context: Vec<String> = Vec::new();
340    if let Some(ref fpt) = tree.full_phrase_text {
341      see_context.push(fpt.clone());
342    }
343    see_context.extend(ancestor_phrases.iter().rev().cloned());
344    see_context.push(String::new());
345
346    for see in &tree.see_also {
347      links.push(NodeData::Text(", ".to_string()));
348      if let Some(ref name) = see.name {
349        if !name.is_empty() {
350          links.push(NodeData::Element {
351            tag:        "ltx:text".to_string(),
352            attributes: Some(HashMap::from_iter([(
353              "font".to_string(),
354              "italic".to_string(),
355            )])),
356            children:   vec![NodeData::Text(format!("{} ", name))],
357          });
358        }
359      }
360      let parts: Vec<SeeChunk> = match see.node {
361        Some(ref n) => seealso_partition(n),
362        None => vec![SeeChunk {
363          key: see.text.clone(),
364          xml: vec![NodeData::Text(see.text.clone())],
365        }],
366      };
367      match seealso_search_rec(&parts, all_phrases, &see_context) {
368        Some(see_links) => {
369          links.extend(see_links);
370        },
371        _ => {
372          // Perl warns unless the see phrase already contains refs of
373          // its own, then falls back to the phrase's own markup.
374          let already_linked = see
375            .node
376            .as_ref()
377            .map(node_has_ref_descendant)
378            .unwrap_or(false);
379          if !already_linked {
380            Warn!(
381              "expected",
382              &see.text,
383              "Missing index see-also term '{}' (seen under {})",
384              see.text,
385              tree.full_key.as_deref().unwrap_or("?")
386            );
387          }
388          let content: Vec<NodeData> = match see.node {
389            Some(ref n) => n
390              .get_child_nodes()
391              .into_iter()
392              .map(NodeData::XmlNode)
393              .collect(),
394            None => vec![NodeData::Text(see.text.clone())],
395          };
396          links.push(NodeData::Element {
397            tag:        "ltx:text".to_string(),
398            attributes: None,
399            children:   content,
400          });
401        },
402      }
403    }
404
405    if !links.is_empty() {
406      children.push(NodeData::Element {
407        tag:        "ltx:indexrefs".to_string(),
408        attributes: None,
409        children:   links,
410      });
411    }
412
413    // Sub-entries: this entry's full phrase joins the ancestor context.
414    let mut child_ancestors: Vec<String> = ancestor_phrases.to_vec();
415    if let Some(ref fpt) = tree.full_phrase_text {
416      child_ancestors.push(fpt.clone());
417    }
418    if let Some(sublist) = self.make_index_list(all_phrases, tree, &child_ancestors) {
419      children.push(sublist);
420    }
421
422    NodeData::Element {
423      tag: "ltx:indexentry".to_string(),
424      attributes: if tree.id.is_empty() {
425        None
426      } else {
427        // fragid mirrors xml:id so the XSLT add_id template emits an
428        // HTML id for the <li> — same workaround as glossaryentry:
429        // these nodes are created after Scan ran, so CrossRef's
430        // fill_in_frags has no DB entry to source fragid from.
431        Some(HashMap::from_iter([
432          ("xml:id".to_string(), tree.id.clone()),
433          ("fragid".to_string(), tree.id.clone()),
434        ]))
435      },
436      children,
437    }
438  }
439
440  /// Register an `ID:` entry for every index entry just created, so
441  /// CrossRef can resolve the see/see-also `ltx:ref idref=idx.*` links
442  /// to hrefs. Perl gets this for free from `$self->rescan($doc)` at
443  /// the end of MakeIndex::process; we register the minimum CrossRef
444  /// needs (location + fragid) directly.
445  fn register_entry_ids(&mut self, tree: &IndexTree, location: &str) {
446    for subtree in tree.subtrees.values() {
447      if !subtree.id.is_empty() {
448        self.register_target_id(&subtree.id, location, &tree.id);
449      }
450      self.register_entry_ids(subtree, location);
451    }
452  }
453
454  /// Register `ID:<id>` for an entry MakeIndex created (an index or glossary entry), as Perl's rescan does
455  /// (Scan.pm `addCommon`): the location and fragid CrossRef's `generate_url` needs, and the parent its
456  /// `generate_title` context walk follows (a see-ref's tooltip becomes the enclosing index's title).
457  fn register_target_id(&mut self, id: &str, location: &str, parent: &str) {
458    let entry = self.db.register(&format!("ID:{id}"), vec![]);
459    entry.set_value("location", Value::from(location));
460    entry.set_value("fragid", Value::from(id));
461    entry.set_value("id", Value::from(id));
462    if !parent.is_empty() {
463      entry.set_value("parent", Value::from(parent));
464    }
465  }
466
467  /// Combine index entry referrers into a comma-separated list with range support.
468  ///
469  /// Port of `combineIndexEntries`.
470  fn combine_index_entries(&self, refs: &HashMap<String, HashMap<String, bool>>) -> Vec<NodeData> {
471    let mut ids: Vec<&String> = refs.keys().collect();
472    ids.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()).then(a.cmp(b)));
473
474    let mut links = Vec::new();
475    let mut i = 0;
476    while i < ids.len() {
477      if !links.is_empty() {
478        links.push(NodeData::Text(", ".to_string()));
479      }
480      let id = ids[i];
481      let styles = refs.get(id).unwrap();
482
483      // Check for range start. Perl pairs the start with the NEXT
484      // range marker of either kind ($lvl-- for rangestart AND
485      // rangeend): since ids are sorted alphabetically rather than
486      // by document order, no real nesting is possible, and a stray
487      // second start terminates the range rather than extending it.
488      if styles.contains_key("rangestart") {
489        let start_id = id;
490        let mut end_id = id;
491        let mut level = 1i32;
492        i += 1;
493        while i < ids.len() && level > 0 {
494          end_id = ids[i];
495          if let Some(s) = refs.get(end_id) {
496            if s.contains_key("rangestart") {
497              level -= 1;
498            }
499            if s.contains_key("rangeend") {
500              level -= 1;
501            }
502          }
503          i += 1;
504        }
505        // Range: start–end
506        links.push(NodeData::Element {
507          tag:        "ltx:text".to_string(),
508          attributes: None,
509          children:   vec![
510            self.make_index_ref(start_id, styles),
511            NodeData::Text("\u{2014}".to_string()), // em-dash
512            self.make_index_ref(end_id, refs.get(end_id).unwrap_or(styles)),
513          ],
514        });
515      } else {
516        links.push(self.make_index_ref(id, styles));
517        i += 1;
518      }
519    }
520    links
521  }
522
523  /// Make a single index reference link.
524  ///
525  /// Port of `makeIndexRefs`.
526  fn make_index_ref(&self, id: &str, styles: &HashMap<String, bool>) -> NodeData {
527    // Perl: `sort keys %$entry` then take the first — "sorted styles
528    // gives bold, italic, normal; let's just do the first". The sort
529    // is what makes the pick deterministic (and prefers bold).
530    let mut style: Vec<&String> = styles
531      .keys()
532      .filter(|s| *s != "rangestart" && *s != "rangeend")
533      .collect();
534    style.sort();
535    let primary_style = style.first().map(|s| s.as_str()).unwrap_or("normal");
536
537    let ref_node = NodeData::Element {
538      tag:        "ltx:ref".to_string(),
539      attributes: Some(HashMap::from_iter([
540        ("idref".to_string(), id.to_string()),
541        ("show".to_string(), "typerefnum".to_string()),
542      ])),
543      children:   vec![],
544    };
545
546    if primary_style != "normal" {
547      NodeData::Element {
548        tag:        "ltx:text".to_string(),
549        attributes: Some(HashMap::from_iter([(
550          "font".to_string(),
551          primary_style.to_string(),
552        )])),
553        children:   vec![ref_node],
554      }
555    } else {
556      ref_node
557    }
558  }
559
560  /// Get glossary entries from the ObjectDB.
561  ///
562  /// Port of `MakeIndex::getGlossaryEntries`.
563  /// `list_unreferenced`: a nomenclature (`<ltx:glossary role="nomenclature">`,
564  /// the nomencl binding) lists EVERY definition — its entries are written
565  /// lines that makeindex prints whole (nomencl.sty:227-245), with no
566  /// `\gls`-style reference; a glossary lists only the referenced ones
567  /// (Perl MakeIndex.pm:468 `next unless $refs && %{$refs}`).
568  /// `postdesc`: what the glossary's style prints after each description (glossaries' `\glspostdescription`).
569  fn get_glossary_entries(
570    &mut self,
571    lists: &str,
572    glossary_id: &str,
573    list_unreferenced: bool,
574    postdesc: &[NodeData],
575  ) -> Vec<GlossaryEntry> {
576    let list_set: rustc_hash::FxHashSet<&str> = lists.split(',').collect();
577    let mut entries = Vec::new();
578
579    // The definitions in this glossary's lists, by key (the first list that has one), and the ones listed: those
580    // referenced in any of the lists (Perl MakeIndex.pm:468 `next unless $refs && %{$refs}`), or every one of a
581    // nomenclature.
582    let mut defined: HashMap<String, String> = HashMap::default();
583    let mut pending: Vec<String> = Vec::new();
584    let mut db_keys: Vec<String> = self.db.get_keys().into_iter().cloned().collect();
585    db_keys.sort();
586    for db_key in db_keys {
587      let parts: Vec<&str> = db_key.splitn(3, ':').collect();
588      // (an entry needs its key: the glossary's own `ltx_glossary_postdescription` definition has none)
589      if parts.len() < 3
590        || parts[0] != "GLOSSARY"
591        || !list_set.contains(parts[1])
592        || parts[2].is_empty()
593      {
594        continue;
595      }
596      let key = parts[2].to_string();
597      let referenced = self
598        .db
599        .lookup(&db_key)
600        .and_then(|entry| entry.get_value("referrers"))
601        .is_some_and(|v| v.is_truthy());
602      if referenced || list_unreferenced {
603        pending.push(key.clone());
604      }
605      defined.entry(key).or_insert(db_key);
606    }
607    // makeglossaries lists the parent of every listed entry, its children under it (a `parent=` key, glossaries'
608    // `\subglossentry`), so a heading no `\gls` references is listed for its children: glosmathtools' "Latin
609    // symbols (Symboles latins)". Perl lists the referenced entries only, flat (KNOWN_PERL_ERRORS #442). A parent
610    // defined in another glossary is not listed (makeindex lists it in the child's glossary, its index key built
611    // from the parent's, glossaries.sty:3226-3236): the child is listed at the top level.
612    let mut included: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
613    while let Some(key) = pending.pop() {
614      if !included.insert(key.clone()) {
615        continue;
616      }
617      if let Some(parent) = self.glossary_parent(&defined[&key])
618        && defined.contains_key(&parent)
619      {
620        pending.push(parent);
621      }
622    }
623    let mut included: Vec<String> = included.into_iter().collect();
624    included.sort();
625    for key in &included {
626      let key = key.as_str();
627      let db_key = defined[key].as_str();
628      let parent = self
629        .glossary_parent(db_key)
630        .filter(|parent| parent != key && defined.contains_key(parent));
631      if let Some(entry) = self.db.lookup(db_key) {
632        // The sort phrase's text content is the sort key (Perl MakeIndex.pm:471
633        // `getValue('phrase:sort') || $key`); the phrase itself is now a node.
634        let sort_key = entry
635          .get_value("phrase:sort")
636          .map(Value::as_string)
637          .filter(|s| !s.is_empty())
638          .unwrap_or_else(|| key.to_string());
639        let initial = sort_key
640          .chars()
641          .next()
642          .filter(|c| c.is_ascii_alphabetic())
643          .map(|c| c.to_uppercase().to_string())
644          .unwrap_or_else(|| "*".to_string());
645        let id = format!("{}.{}", glossary_id, key);
646        // Perl MakeIndex.pm:477-480: the label and definition are CLONES of
647        // the stored phrase nodes' trimmed children, so math and styled
648        // text survive (a nomenclature symbol is math).
649        let phrase_children = |role: &str, default: &str| -> Vec<NodeData> {
650          match entry.get_value(role) {
651            Some(Value::Xml(node)) => trimmed_child_nodes(node),
652            Some(other) => vec![NodeData::Text(other.as_string())],
653            None => vec![NodeData::Text(default.to_string())],
654          }
655        };
656        let term = phrase_children("phrase:name", key);
657        let group = match entry.get_value("phrase:group") {
658          Some(Value::Xml(node)) => trimmed_child_nodes(node),
659          _ => Vec::new(),
660        };
661        let mut desc = phrase_children("phrase:description", "");
662        // A description ends with the glossary's post-description unless it holds `\nopostdesc`
663        // (glossaries.sty:1512-1518); an empty one too, as pdflatex prints it. OXIDIZED_DESIGN_DIVERGENCES #1180.
664        let nopostdesc = matches!(entry.get_value("phrase:description"), Some(Value::Xml(node))
665        if node.get_attribute("class").is_some_and(|class| {
666          class.split_whitespace().any(|class| class == "ltx_glossary_nopostdesc")
667        }));
668        if !nopostdesc {
669          desc.extend(postdesc.iter().cloned());
670        }
671        // nomencl's `nomentbl` entries carry `unit` and `note` columns
672        // (nomencl.sty:228-235, the binding's `unit`/`note` phrases). The list
673        // renders only a label and a definition, so they follow the
674        // description as classed text (`ltx_glossary_unit`/`_note`) rather than
675        // being dropped. Surpass (Perl has no nomencl list at all);
676        // OXIDIZED_DESIGN #234. The display keys a package adds (`\glsaddkey`: glosmathtools' `descseclang`),
677        // phrases the glossaries binding classes `ltx_glossary_userkey`, follow after them, sorted, in the same way.
678        let mut roles: Vec<&str> = entry
679          .attributes()
680          .filter_map(|attribute| attribute.strip_prefix("phrase:"))
681          .filter(|role| !matches!(*role, "unit" | "note"))
682          .filter(|role| {
683            matches!(entry.get_value(&format!("phrase:{role}")), Some(Value::Xml(node))
684            if node.get_attribute("class").is_some_and(|class| {
685              class.split_whitespace().any(|class| class == "ltx_glossary_userkey")
686            }))
687          })
688          .collect();
689        roles.sort();
690        roles.dedup();
691        for role in ["unit", "note"].into_iter().chain(roles) {
692          if let Some(value) = entry.get_value(&format!("phrase:{role}")) {
693            let children = match value {
694              Value::Xml(node) => trimmed_child_nodes(node),
695              other => vec![NodeData::Text(other.as_string())],
696            };
697            if !children.is_empty() {
698              desc.push(NodeData::Text(" ".to_string()));
699              desc.push(NodeData::Element {
700                tag: "ltx:text".to_string(),
701                attributes: Some(HashMap::from_iter([(
702                  "class".to_string(),
703                  format!("ltx_glossary_{}", clean_class_name(role)),
704                )])),
705                children,
706              });
707            }
708          }
709        }
710
711        entries.push(GlossaryEntry {
712          key: key.to_string(),
713          id: id.clone(),
714          parent,
715          initial,
716          sort_key,
717          group,
718          formatted: NodeData::Element {
719            tag:        "ltx:glossaryentry".to_string(),
720            attributes: Some(HashMap::from_iter([
721              ("lists".to_string(), lists.to_string()),
722              ("xml:id".to_string(), id.clone()),
723              // fragid mirrors xml:id so the XSLT `add_id` template emits
724              // `<dt id="glo.main.cabbage">`. Without fragid, the dt
725              // renders as `<dt class="..."/>` only. Scan ran before these
726              // entries existed; `process` registers their `ID:<id>` once the
727              // list is placed. Setting fragid eagerly here matches the end state.
728              ("fragid".to_string(), id.clone()),
729              ("key".to_string(), key.to_string()),
730            ])),
731            children:   vec![
732              NodeData::Element {
733                tag:        "ltx:glossaryphrase".to_string(),
734                attributes: Some(HashMap::from_iter([
735                  ("role".to_string(), "label".to_string()),
736                  ("key".to_string(), key.to_string()),
737                ])),
738                children:   term,
739              },
740              NodeData::Element {
741                tag:        "ltx:glossaryphrase".to_string(),
742                attributes: Some(HashMap::from_iter([(
743                  "role".to_string(),
744                  "definition".to_string(),
745                )])),
746                children:   desc,
747              },
748            ],
749          },
750        });
751        // Register the entry's id back in the DB so CrossRef's
752        // fill_in_glossaryrefs can resolve `<glossaryref key="X">` to
753        // the corresponding `<glossaryentry xml:id=…>`. Mirrors Perl
754        // MakeIndex.pm where the entry construction sets `id`.
755        if let Some(entry_mut) = self.db.lookup_mut(db_key) {
756          entry_mut.set_value("id", Value::from(id.clone()));
757        }
758      }
759    }
760    // Perl `MakeIndex.pm` L487: `$doc->unisort(keys %hash)` — Unicode-
761    // aware case-insensitive sort. For ASCII-Latin (which covers the
762    // test fixture and the vast majority of glossary entries), lowercase
763    // comparison matches the expected order: "Cabbage" sorts beside
764    // "cabbage" rather than before all lowercase letters. Each level is sorted, a child follows its parent
765    // (makeglossaries' `\subglossentry`), classed by its depth (`ltx_glossary_level_<n>`; the schema nests no list
766    // in an entry).
767    entries.sort_by_key(|a| a.sort_key.to_lowercase());
768    let mut ordered = Vec::with_capacity(entries.len());
769    let mut by_parent: HashMap<Option<String>, Vec<GlossaryEntry>> = HashMap::default();
770    for entry in entries {
771      by_parent
772        .entry(entry.parent.clone())
773        .or_default()
774        .push(entry);
775    }
776    place_glossary_children(None, 0, &mut by_parent, &mut ordered);
777    // An entry whose parent chain never reaches the top level (a cycle) keeps the flat order.
778    let mut unplaced: Vec<GlossaryEntry> = by_parent.into_values().flatten().collect();
779    unplaced.sort_by_key(|a| a.sort_key.to_lowercase());
780    ordered.append(&mut unplaced);
781    ordered
782  }
783
784  /// The key of a glossary definition's parent (glossaries' `parent=` key), if any.
785  fn glossary_parent(&self, db_key: &str) -> Option<String> {
786    self
787      .db
788      .lookup(db_key)
789      .and_then(|entry| entry.get_value("phrase:parent"))
790      .map(Value::as_string)
791      .map(|parent| parent.trim().to_string())
792      .filter(|parent| !parent.is_empty())
793  }
794
795  /// Generate a glossary list.
796  ///
797  /// Port of `MakeIndex::makeGlossaryList`.
798  ///
799  /// A top-level entry that opens a new initial and carries a group heading is preceded by the heading, as
800  /// makeindex's `lethead_flag` writes `\nomgroup{<letter>}` (nomencl.ist:36-38) before each letter's entries and
801  /// nomencl's `stdsubgroups` sets it as a label (nomencl.sty:247-272): "Latin letters", "Greek letters".
802  fn make_glossary_list(&self, entries: &[GlossaryEntry]) -> NodeData {
803    let mut children = Vec::with_capacity(entries.len());
804    let mut last_initial: Option<&str> = None;
805    for entry in entries {
806      if entry.parent.is_none() {
807        if !entry.group.is_empty() && last_initial != Some(entry.initial.as_str()) {
808          children.push(NodeData::Element {
809            tag:        "ltx:glossaryentry".to_string(),
810            attributes: Some(HashMap::from_iter([(
811              "class".to_string(),
812              "ltx_glossary_group".to_string(),
813            )])),
814            children:   vec![NodeData::Element {
815              tag:        "ltx:glossaryphrase".to_string(),
816              attributes: Some(HashMap::from_iter([(
817                "role".to_string(),
818                "label".to_string(),
819              )])),
820              children:   entry.group.clone(),
821            }],
822          });
823        }
824        last_initial = Some(entry.initial.as_str());
825      }
826      children.push(entry.formatted.clone());
827    }
828    NodeData::Element {
829      tag: "ltx:glossarylist".to_string(),
830      attributes: None,
831      children,
832    }
833  }
834}
835
836/// A formatted `ltx:glossaryentry` as an `ltx:item` of a description (its attributes kept): the `label` phrase is the
837/// item's tag, the `definition` phrase its paragraph — the schema holds a `glossarylist` in an `ltx:glossary` only.
838fn glossary_entry_as_item(entry: NodeData) -> NodeData {
839  let NodeData::Element { attributes, children, .. } = entry else {
840    return entry;
841  };
842  let mut item_children = Vec::new();
843  for phrase in children {
844    let NodeData::Element {
845      attributes: phrase_attributes,
846      children: phrase_children,
847      ..
848    } = phrase
849    else {
850      continue;
851    };
852    let role = phrase_attributes
853      .as_ref()
854      .and_then(|a| a.get("role"))
855      .map(String::as_str);
856    let (tag, inner) = match role {
857      Some("label") => ("ltx:tags", "ltx:tag"),
858      _ => ("ltx:para", "ltx:p"),
859    };
860    item_children.push(NodeData::Element {
861      tag:        tag.to_string(),
862      attributes: None,
863      children:   vec![NodeData::Element {
864        tag:        inner.to_string(),
865        attributes: None,
866        children:   phrase_children,
867      }],
868    });
869  }
870  let attributes = attributes.map(|mut a| {
871    a.remove("lists");
872    a.remove("key");
873    a
874  });
875  NodeData::Element {
876    tag: "ltx:item".to_string(),
877    attributes,
878    children: item_children,
879  }
880}
881
882/// Move the entries under `parent` (each level sorted) from `by_parent` to `ordered`, each followed by its own
883/// children; a child's `glossaryentry` is classed `ltx_glossary_level_<depth>`.
884fn place_glossary_children(
885  parent: Option<&str>,
886  depth: usize,
887  by_parent: &mut HashMap<Option<String>, Vec<GlossaryEntry>>,
888  ordered: &mut Vec<GlossaryEntry>,
889) {
890  let Some(children) = by_parent.remove(&parent.map(str::to_string)) else {
891    return;
892  };
893  for mut entry in children {
894    if depth > 0
895      && let NodeData::Element {
896        attributes: Some(attributes), ..
897      } = &mut entry.formatted
898    {
899      attributes.insert("class".to_string(), format!("ltx_glossary_level_{depth}"));
900    }
901    let key = entry.key.clone();
902    ordered.push(entry);
903    place_glossary_children(Some(&key), depth + 1, by_parent, ordered);
904  }
905}
906
907impl Processor for MakeIndex {
908  fn get_name(&self) -> &str { &self.name }
909
910  fn to_process(&self, doc: &PostDocument) -> Vec<Node> { doc.findnodes(PLACEHOLDERS) }
911
912  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
913    for node in &nodes {
914      let tag = doc.get_qname(node).unwrap_or_default();
915      // xml:id is namespace-bound: plain get_attribute misses it on
916      // engine-constructed nodes (it only happens to work on nodes
917      // round-tripped through serialization).
918      let id = crate::document::get_xml_id(node).unwrap_or_default();
919
920      if tag == "ltx:index" {
921        let lists = node
922          .get_attribute("lists")
923          .unwrap_or_else(|| DEFAULT_INDEX_LIST.to_string());
924        let lists: Vec<&str> = lists.split_whitespace().collect();
925        if let Some((tree, all_phrases)) = self.build_tree(&id, &lists) {
926          if let Some(index_list) = self.make_index_list(&all_phrases, &tree, &[]) {
927            let mut node_mut = node.clone();
928            doc.add_nodes(&mut node_mut, &[index_list]);
929            let location = doc.site_relative_destination().unwrap_or_default();
930            self.register_entry_ids(&tree, &location);
931          }
932        }
933      } else if tag == "ltx:glossary" {
934        let lists = node
935          .get_attribute("lists")
936          .unwrap_or_else(|| "glossary".to_string());
937        let list_unreferenced = node.with_attribute(c"role", |v| v == "nomenclature") == Some(true);
938        // The glossaries binding's post-description (`\lx@printglossary`), appended to each description: the inner
939        // text of its phrase, in the list's font (the outer text, which the descriptions do not carry), kept as a
940        // wrapper where the renewal has a font of its own (`\textbf{!}`). The carrier leaves the document, its ids the
941        // cache, before the list's ids are made; its nodes are copied without ids (Perl clones a glossary's phrases
942        // with `cloneNode($_, 'glo')`), and freed once copied.
943        let carrier = doc.findnode_at(
944          "ltx:glossarydefinition[contains(concat(' ', @class, ' '), ' ltx_glossary_postdescription ')]",
945          node,
946        );
947        let postdesc_text = carrier.as_ref().and_then(|carrier| {
948          doc.findnode_at(
949            "ltx:glossaryphrase[@role='postdescription']/ltx:text/ltx:text",
950            carrier,
951          )
952        });
953        if let Some(carrier) = &carrier {
954          doc.remove_nodes(std::slice::from_ref(carrier));
955        }
956        {
957          let postdesc = postdesc_text
958            .map(|mut text| {
959              strip_ids(&mut text);
960              if text
961                .get_properties()
962                .keys()
963                .any(|key| !key.starts_with('_'))
964              {
965                vec![NodeData::XmlNode(text)]
966              } else {
967                text
968                  .get_child_nodes()
969                  .into_iter()
970                  .map(NodeData::XmlNode)
971                  .collect()
972              }
973            })
974            .unwrap_or_default();
975          let entries = self.get_glossary_entries(&lists, &id, list_unreferenced, &postdesc);
976          if !entries.is_empty() {
977            let glist = self.make_glossary_list(&entries);
978            let mut node_mut = node.clone();
979            doc.add_nodes(&mut node_mut, &[glist]);
980            // Perl's rescan registers each listed entry (Scan.pm:427-445 `glossaryentry_handler`), so a
981            // `\gls` reference links to it (issue #1208).
982            let location = doc.site_relative_destination().unwrap_or_default();
983            for entry in &entries {
984              self.register_target_id(&entry.id, &location, &id);
985            }
986          }
987        }
988        if let Some(carrier) = carrier {
989          doc.discard_subtree(carrier);
990        }
991      } else if tag == "ltx:description" {
992        // nomencl's list in a box no glossary may open in (the binding's `ltx_nomenclature` description, OD #1098): the
993        // same entries, each an item whose tag is the symbol and whose paragraph is the description.
994        let entries = self.get_glossary_entries("nomenclature", &id, true, &[]);
995        let glist = self.make_glossary_list(&entries);
996        if let NodeData::Element { children, .. } = glist {
997          let items: Vec<NodeData> = children.into_iter().map(glossary_entry_as_item).collect();
998          if !items.is_empty() {
999            let mut node_mut = node.clone();
1000            doc.add_nodes(&mut node_mut, &items);
1001          }
1002        }
1003      }
1004    }
1005    Ok(vec![doc])
1006  }
1007}
1008
1009// ======================================================================
1010// Helpers
1011
1012fn add_tree_rec(
1013  tree: &mut IndexTree,
1014  phrases: &[PhraseRef],
1015  all_phrases: &mut HashMap<String, String>,
1016  used_ids: &mut HashMap<String, u32>,
1017  entry: &crate::object_db::Entry,
1018) {
1019  if phrases.is_empty() {
1020    // Leaf: record referrers and see_also.
1021    // Scan's note_association(["referrers", pid, style]) nests THREE
1022    // levels: referrers → {pid → {style → true}} (mirroring Perl's
1023    // $$entry{referrers}{$id}{$style}). The inner value is a Hash of
1024    // styles, not a scalar — reading it with to_string() used to
1025    // collapse every style to "" (Value's Display renders hashes as
1026    // the empty string), silently dropping bold/italic/etc. and
1027    // wrapping every index ref in an empty-font ltx:text.
1028    if let Some(Value::Hash(refs)) = entry.get_value("referrers") {
1029      for (k, v) in refs {
1030        let styles = tree.referrers.entry(k.clone()).or_default();
1031        if let Value::Hash(style_map) = v {
1032          for style in style_map.keys() {
1033            styles.insert(style.clone(), true);
1034          }
1035        }
1036      }
1037    }
1038    if let Some(Value::List(see_items)) = entry.get_value("see_also") {
1039      for item in see_items {
1040        // Stored as Value::Xml(ltx:indexsee) by Scan; keep the node
1041        // for markup-preserving rendering, plus its name attribute
1042        // ("see"/"see also") and normalized text for target lookup.
1043        if let Value::Xml(node) = item {
1044          tree.see_also.push(SeeAlso {
1045            name: node.get_attribute("name"),
1046            text: get_index_content_key(&node.get_content()),
1047            node: Some(node.clone()),
1048          });
1049        } else {
1050          tree.see_also.push(SeeAlso {
1051            name: None,
1052            text: get_index_content_key(&item.to_string()),
1053            node: None,
1054          });
1055        }
1056      }
1057    }
1058    return;
1059  }
1060  let phrase = &phrases[0];
1061  let rest = &phrases[1..];
1062  let key = &phrase.key;
1063  let key_id = get_index_key_id(key);
1064  let parent_key = tree.full_key.clone().unwrap_or_default();
1065  let full_key = if parent_key.is_empty() {
1066    key.to_string()
1067  } else {
1068    format!("{}.{}", parent_key, key)
1069  };
1070  // Perl: phrasetext (the normalized CONTENT, not the key) feeds the
1071  // see/see-also lookup table; multi-level phrases join with a space.
1072  let phrase_text = phrase.text.clone();
1073  let parent_phrase = tree.full_phrase_text.clone().unwrap_or_default();
1074  let full_phrase = if parent_phrase.is_empty() {
1075    phrase_text.clone()
1076  } else {
1077    format!("{} {}", parent_phrase, phrase_text)
1078  };
1079
1080  let tree_id = tree.id.clone();
1081  // Allocate the id BEFORE or_insert_with so we can uniquify against
1082  // ids already used by sibling phrases that strip to the same
1083  // key_id. Only done when the subtree is new (an existing subtree
1084  // keeps its id). Perl: uniquifyID appends radix_alpha(clashes).
1085  let needs_id = !tree.subtrees.contains_key(key.as_str());
1086  let id = if needs_id {
1087    Some(uniquify_id(&format!("{}.{}", tree_id, key_id), used_ids))
1088  } else {
1089    None
1090  };
1091  let subtree = tree.subtrees.entry(key.to_string()).or_insert_with(|| {
1092    let id = id.unwrap();
1093    all_phrases.insert(full_key.clone(), id.clone());
1094    all_phrases.insert(full_key.to_lowercase(), id.clone());
1095    all_phrases.insert(full_phrase.clone(), id.clone());
1096    all_phrases.insert(full_phrase.to_lowercase(), id.clone());
1097    let mut st = IndexTree::new(&id);
1098    st.key = Some(key.to_string());
1099    st.full_key = Some(full_key.clone());
1100    st.phrase = Some(phrase_text.clone());
1101    st.phrase_node = phrase.node.clone();
1102    st.phrase_text = Some(phrase_text);
1103    st.full_phrase_text = Some(full_phrase);
1104    st
1105  });
1106  add_tree_rec(subtree, rest, all_phrases, used_ids, entry);
1107}
1108
1109/// Perl Post::uniquifyID: return `base` if unused, else append
1110/// radix_alpha(n) (a, b, …) for the next free clash counter.
1111fn uniquify_id(base: &str, used: &mut HashMap<String, u32>) -> String {
1112  if !used.contains_key(base) {
1113    used.insert(base.to_string(), 0);
1114    return base.to_string();
1115  }
1116  loop {
1117    let n = used.get_mut(base).unwrap();
1118    *n += 1;
1119    let candidate = format!("{}{}", base, crate::radix::radix_alpha(*n));
1120    if !used.contains_key(&candidate) {
1121      used.insert(candidate.clone(), 0);
1122      return candidate;
1123    }
1124  }
1125}
1126
1127fn initial_letter(key: &str) -> String {
1128  let decomposed: String = key.nfd().collect();
1129  match decomposed.trim().chars().next() {
1130    Some(c) if c.is_ascii_alphabetic() => c.to_uppercase().to_string(),
1131    _ => "*".to_string(),
1132  }
1133}
1134
1135/// Perl getIndexKeyID: NFD-decompose, transliterate Greek letters to
1136/// their names (so math-bearing keys don't collapse to nothing), then
1137/// strip everything but ASCII alphanumerics.
1138fn get_index_key_id(key: &str) -> String {
1139  let decomposed: String = key.trim().nfd().collect();
1140  let mut out = String::with_capacity(decomposed.len());
1141  for c in decomposed.chars() {
1142    if let Some(name) = greek_ascii(c) {
1143      out.push_str(name);
1144    } else if c.is_ascii_alphanumeric() {
1145      out.push(c);
1146    }
1147  }
1148  out
1149}
1150
1151/// Perl %GREEK_ASCII_MAP.
1152fn greek_ascii(c: char) -> Option<&'static str> {
1153  Some(match c {
1154    '\u{03B1}' => "alpha",
1155    '\u{03B2}' => "beta",
1156    '\u{03B3}' => "gamma",
1157    '\u{03B4}' => "delta",
1158    '\u{03F5}' => "epsilon",
1159    '\u{03B5}' => "varepsilon",
1160    '\u{03B6}' => "zeta",
1161    '\u{03B7}' => "eta",
1162    '\u{03B8}' => "theta",
1163    '\u{03D1}' => "vartheta",
1164    '\u{03B9}' => "iota",
1165    '\u{03BA}' => "kappa",
1166    '\u{03BB}' => "lambda",
1167    '\u{03BC}' => "mu",
1168    '\u{03BD}' => "nu",
1169    '\u{03BE}' => "xi",
1170    '\u{03C0}' => "pi",
1171    '\u{03D6}' => "varpi",
1172    '\u{03C1}' => "rho",
1173    '\u{03F1}' => "varrho",
1174    '\u{03C3}' => "sigma",
1175    '\u{03C2}' => "varsigma",
1176    '\u{03C4}' => "tau",
1177    '\u{03C5}' => "upsilon",
1178    '\u{03D5}' => "phi",
1179    '\u{03C6}' => "varphi",
1180    '\u{03C7}' => "chi",
1181    '\u{03C8}' => "psi",
1182    '\u{03C9}' => "omega",
1183    '\u{0393}' => "Gamma",
1184    '\u{0394}' => "Delta",
1185    '\u{0398}' => "Theta",
1186    '\u{039B}' => "Lambda",
1187    '\u{039E}' => "Xi",
1188    '\u{03A0}' => "Pi",
1189    '\u{03A3}' => "Sigma",
1190    '\u{03A5}' => "Upsilon",
1191    '\u{03A6}' => "Phi",
1192    '\u{03A8}' => "Psi",
1193    '\u{03A9}' => "Omega",
1194    _ => return None,
1195  })
1196}
1197
1198/// Perl getIndexContentKey: trim, collapse internal whitespace,
1199/// strip trailing punctuation.
1200fn get_index_content_key(s: &str) -> String {
1201  let collapsed = s.split_whitespace().collect::<Vec<_>>().join(" ");
1202  collapsed
1203    .trim_end_matches(['.', ',', ';'])
1204    .trim_end()
1205    .to_string()
1206}
1207
1208/// Perl `$doc->trimChildNodes`: the node's children minus pure-whitespace
1209/// text nodes at either end (whitespace INSIDE the sequence is kept).
1210fn trimmed_child_nodes(node: &Node) -> Vec<NodeData> {
1211  let children = node.get_child_nodes();
1212  let is_ws =
1213    |n: &Node| n.get_type() == Some(NodeType::TextNode) && n.get_content().trim().is_empty();
1214  let start = children.iter().position(|n| !is_ws(n));
1215  let end = children.iter().rposition(|n| !is_ws(n));
1216  match (start, end) {
1217    (Some(s), Some(e)) => children[s..=e]
1218      .iter()
1219      .cloned()
1220      .map(NodeData::XmlNode)
1221      .collect(),
1222    _ => vec![],
1223  }
1224}
1225
1226/// Drop the `xml:id` and `fragid` of `node` and its descendants: a copy made where the original leaves the document.
1227fn strip_ids(node: &mut Node) {
1228  if node.get_type() == Some(NodeType::ElementNode) {
1229    let _ = node.remove_attribute_ns("id", latexml_core::common::xml::XML_NS);
1230    let _ = node.remove_attribute("fragid");
1231    for mut child in node.get_child_nodes() {
1232      strip_ids(&mut child);
1233    }
1234  }
1235}
1236
1237/// Does the node contain an ltx:ref descendant? (Perl checks
1238/// `descendant-or-self::ltx:ref` before warning about an unresolved
1239/// see-also phrase.)
1240fn node_has_ref_descendant(node: &Node) -> bool {
1241  if node.get_type() == Some(NodeType::ElementNode) && name_is(node, "ref") {
1242    return true;
1243  }
1244  node.get_child_nodes().iter().any(node_has_ref_descendant)
1245}
1246
1247// ======================================================================
1248// See & see-also resolution (Perl MakeIndex.pm "A LOTTA work, for such
1249// a little thing!"). A see phrase is partitioned into alternating
1250// candidate-term and candidate-delimiter chunks; the search then tries
1251// interpreting each delimiter as part of a longer phrase or as a
1252// separator between independent targets.
1253
1254/// One partition chunk: the normalized lookup key plus the XML pieces
1255/// it came from (used to fill the resulting ltx:ref).
1256#[derive(Debug, Clone)]
1257struct SeeChunk {
1258  key: String,
1259  xml: Vec<NodeData>,
1260}
1261
1262/// Perl seealsoPartition: chunk the phrase, then (pass 1) combine
1263/// adjacent chunks that are both-or-neither delimiters, and (pass 2)
1264/// fold pure-space chunks into their neighbours.
1265fn seealso_partition(see: &Node) -> Vec<SeeChunk> {
1266  let parts = seealso_partition_aux(see);
1267  if parts.is_empty() {
1268    return parts;
1269  }
1270  // Pass 1: combine adjacent conjunction/punctuation chunks.
1271  let mut iter = parts.into_iter();
1272  let mut result: Vec<SeeChunk> = vec![iter.next().unwrap()];
1273  for next in iter {
1274    let prev_is = is_delimiter_key(&result.last().unwrap().key);
1275    let next_is = starts_with_delimiter(&next.key);
1276    if prev_is == next_is {
1277      let last = result.last_mut().unwrap();
1278      last.key.push_str(&next.key);
1279      last.xml.extend(next.xml);
1280    } else {
1281      result.push(next);
1282    }
1283  }
1284  // Pass 2: a pure-space chunk merges its neighbours into one phrase.
1285  let mut iter = result.into_iter();
1286  let mut merged: Vec<SeeChunk> = vec![iter.next().unwrap()];
1287  let rest: Vec<SeeChunk> = iter.collect();
1288  let mut i = 0;
1289  while i < rest.len() {
1290    let next = rest[i].clone();
1291    if !next.key.is_empty() && next.key.trim().is_empty() && i + 1 < rest.len() {
1292      let after = rest[i + 1].clone();
1293      let last = merged.last_mut().unwrap();
1294      last.key.push_str(&next.key);
1295      last.key.push_str(&after.key);
1296      last.xml.extend(next.xml);
1297      last.xml.extend(after.xml);
1298      i += 2;
1299    } else {
1300      merged.push(next);
1301      i += 1;
1302    }
1303  }
1304  merged
1305}
1306
1307/// Perl seealsoPartition_aux: split into pure phrase/delimiter chunks.
1308fn seealso_partition_aux(node: &Node) -> Vec<SeeChunk> {
1309  let mut result = Vec::new();
1310  for ch in node.get_child_nodes() {
1311    match ch.get_type() {
1312      Some(NodeType::TextNode) => {
1313        let mut s = ch.get_content();
1314        while !s.is_empty() {
1315          if let Some((delim, rest)) = take_delimiter(&s) {
1316            result.push(SeeChunk {
1317              key: delim.clone(),
1318              xml: vec![NodeData::Text(delim)],
1319            });
1320            s = rest;
1321          } else {
1322            // ^([^,\.\s]+)
1323            let end = s
1324              .find(|c: char| c == ',' || c == '.' || c.is_whitespace())
1325              .unwrap_or(s.len());
1326            let (tok, rest) = s.split_at(end);
1327            result.push(SeeChunk {
1328              key: get_index_content_key(tok),
1329              xml: vec![NodeData::Text(tok.to_string())],
1330            });
1331            s = rest.to_string();
1332          }
1333        }
1334      },
1335      Some(NodeType::ElementNode) => {
1336        let name = ch.get_name();
1337        if name == "text" || name == "emph" {
1338          // Recurse, re-wrapping each sub-chunk in the styling element
1339          // so delimiters can split styled phrases (Perl does the same).
1340          // Drop the source node's id ("id" is how get_properties()
1341          // reports xml:id): the styling wrapper is CLONED once per
1342          // sub-chunk, and copying the id onto every clone would mint
1343          // schema-invalid duplicate xml:ids. The namespace probe keeps a
1344          // GENUINE plain `id` attribute (model-granted on a few bib
1345          // elements) from being dropped along with it.
1346          //
1347          // Perl copies the attributes here — or means to: its
1348          // `map { ($_ => $ch->getAttribute($_)) } $ch->attributes`
1349          // (MakeIndex.pm L445) keys the hash on attribute NODES, which
1350          // stringify to ` role="x"`-style junk with undef values, so it
1351          // copies nothing usable. We implement the intent, minus the ids.
1352          // KNOWN_PERL_ERRORS #72.
1353          let ch_has_xml_id = ch
1354            .get_attribute_ns("id", latexml_core::common::xml::XML_NS)
1355            .is_some();
1356          let attrs: HashMap<String, String> = ch
1357            .get_properties()
1358            .into_iter()
1359            .filter(|(k, _)| k != "xml:id" && k != "fragid" && !(k == "id" && ch_has_xml_id))
1360            .collect();
1361          for sub in seealso_partition_aux(&ch) {
1362            result.push(SeeChunk {
1363              key: sub.key,
1364              xml: vec![NodeData::Element {
1365                tag:        format!("ltx:{}", name),
1366                attributes: if attrs.is_empty() {
1367                  None
1368                } else {
1369                  Some(attrs.clone())
1370                },
1371                children:   sub.xml,
1372              }],
1373            });
1374          }
1375        } else {
1376          // Opaque element (math etc.): one phrase chunk.
1377          result.push(SeeChunk {
1378            key: get_index_content_key(&ch.get_content()),
1379            xml: vec![NodeData::XmlNode(ch.clone())],
1380          });
1381        }
1382      },
1383      _ => {},
1384    }
1385  }
1386  result
1387}
1388
1389/// Leading delimiter per Perl: `^(,|\.|\s+|and\s+also\b|and\b|or\b)`.
1390fn take_delimiter(s: &str) -> Option<(String, String)> {
1391  if s.starts_with(',') || s.starts_with('.') {
1392    return Some((s[..1].to_string(), s[1..].to_string()));
1393  }
1394  let ws_len = s.len() - s.trim_start().len();
1395  if ws_len > 0 {
1396    return Some((s[..ws_len].to_string(), s[ws_len..].to_string()));
1397  }
1398  for kw in ["and also", "and", "or"] {
1399    if let Some(rest) = strip_keyword(s, kw) {
1400      return Some((s[..s.len() - rest.len()].to_string(), rest.to_string()));
1401    }
1402  }
1403  None
1404}
1405
1406/// Match a keyword (with internal `\s+` flexibility for "and also")
1407/// at the start of `s`, requiring a word boundary after it.
1408fn strip_keyword<'a>(s: &'a str, kw: &str) -> Option<&'a str> {
1409  let mut rest = s;
1410  for (i, word) in kw.split(' ').enumerate() {
1411    if i > 0 {
1412      let trimmed = rest.trim_start();
1413      if trimmed.len() == rest.len() {
1414        return None; // needed \s+ between words
1415      }
1416      rest = trimmed;
1417    }
1418    rest = rest.strip_prefix(word)?;
1419  }
1420  // \b: next char must not be a word character
1421  match rest.chars().next() {
1422    Some(c) if c.is_alphanumeric() || c == '_' => None,
1423    _ => Some(rest),
1424  }
1425}
1426
1427/// Is this chunk key delimiter-shaped?
1428/// Perl: `^,?\s*(?:,|\.|\s+|\band\s+also|\band|\bor)\s*$`.
1429fn is_delimiter_key(key: &str) -> bool {
1430  let k = key.strip_prefix(',').unwrap_or(key).trim();
1431  if k.is_empty() || k == "," || k == "." || k == "and" || k == "or" {
1432    return true;
1433  }
1434  let words: Vec<&str> = k.split_whitespace().collect();
1435  words == ["and", "also"]
1436}
1437
1438/// Does this chunk key START with a delimiter?
1439/// Perl: `^(?:,|\.|\s+|and\b|or\b)`.
1440fn starts_with_delimiter(key: &str) -> bool {
1441  key.starts_with(',')
1442    || key.starts_with('.')
1443    || key.starts_with(|c: char| c.is_whitespace())
1444    || strip_keyword(key, "and").is_some()
1445    || strip_keyword(key, "or").is_some()
1446}
1447
1448/// Perl seealsoJoin: reassemble consecutive chunks into one candidate.
1449fn seealso_join(parts: &[SeeChunk]) -> SeeChunk {
1450  let key = get_index_content_key(&parts.iter().map(|p| p.key.as_str()).collect::<String>());
1451  let xml = parts.iter().flat_map(|p| p.xml.clone()).collect();
1452  SeeChunk { key, xml }
1453}
1454
1455/// Perl seealsoSearch_rec: parts alternate (potential) term and
1456/// (potential) delimiter. Try each delimiter first as phrase-internal
1457/// (joining its neighbours), then as a separator between targets.
1458fn seealso_search_rec(
1459  parts: &[SeeChunk],
1460  all_phrases: &HashMap<String, String>,
1461  context: &[String],
1462) -> Option<Vec<NodeData>> {
1463  if parts.is_empty() {
1464    return None;
1465  }
1466  if parts.len() < 3 {
1467    // Single term (with possible trailing punctuation): just look it up.
1468    let link = lookup_seealso_phrase(&parts[0], all_phrases, context)?;
1469    let mut out = vec![link];
1470    if parts.len() > 1 {
1471      out.extend(parts[1].xml.clone());
1472    }
1473    return Some(out);
1474  }
1475  // Try the first delimiter "literally" (term+delim+term as one phrase).
1476  let mut joined: Vec<SeeChunk> = vec![seealso_join(&parts[0..3])];
1477  joined.extend_from_slice(&parts[3..]);
1478  if let Some(links) = seealso_search_rec(&joined, all_phrases, context) {
1479    return Some(links);
1480  }
1481  // Try the delimiter as a separator between individual entries.
1482  if let Some(link) = lookup_seealso_phrase(&parts[0], all_phrases, context) {
1483    if let Some(rest) = seealso_search_rec(&parts[2..], all_phrases, context) {
1484      let mut out = vec![link];
1485      out.extend(parts[1].xml.clone());
1486      out.extend(rest);
1487      return Some(out);
1488    }
1489  }
1490  None
1491}
1492
1493/// Perl lookupSeealsoPhrase: try the phrase as-is, ignoring commas,
1494/// plurals, case, or treating commas as level separators — first within
1495/// the current entry's context (innermost first), then at top level.
1496fn lookup_seealso_phrase(
1497  chunk: &SeeChunk,
1498  all_phrases: &HashMap<String, String>,
1499  context: &[String],
1500) -> Option<NodeData> {
1501  let phrase = chunk.key.trim().to_string();
1502  if phrase.is_empty() {
1503    return None;
1504  }
1505  let pnc = comma_to_space(&phrase);
1506  let ps = strip_plurals(&phrase);
1507  let psnc = comma_to_space(&ps);
1508  let pnlvl = comma_to(&phrase, ".");
1509  let mut trials: Vec<String> = Vec::new();
1510  for t in [&phrase, &pnc, &ps, &psnc, &pnlvl] {
1511    trials.push((*t).clone());
1512    trials.push(t.to_lowercase());
1513  }
1514  for trial in &trials {
1515    for prefix in context {
1516      let lookup_key = if prefix.is_empty() {
1517        trial.clone()
1518      } else {
1519        format!("{} {}", prefix, trial)
1520      };
1521      if let Some(id) = all_phrases.get(&lookup_key) {
1522        return Some(NodeData::Element {
1523          tag:        "ltx:ref".to_string(),
1524          attributes: Some(HashMap::from_iter([("idref".to_string(), id.clone())])),
1525          children:   chunk.xml.clone(),
1526        });
1527      }
1528    }
1529  }
1530  None
1531}
1532
1533/// `s/,\s*/ /g`
1534fn comma_to_space(s: &str) -> String { comma_to(s, " ") }
1535
1536fn comma_to(s: &str, repl: &str) -> String {
1537  let mut out = String::with_capacity(s.len());
1538  let mut chars = s.chars().peekable();
1539  while let Some(c) = chars.next() {
1540    if c == ',' {
1541      out.push_str(repl);
1542      while chars.peek().is_some_and(|c| c.is_whitespace()) {
1543        chars.next();
1544      }
1545    } else {
1546      out.push(c);
1547    }
1548  }
1549  out
1550}
1551
1552/// `s/(\w+)s\b/$1/g` — strip a trailing "s" from every word.
1553fn strip_plurals(s: &str) -> String {
1554  let mut out = String::with_capacity(s.len());
1555  let mut word = String::new();
1556  for c in s.chars() {
1557    if c.is_alphanumeric() || c == '_' {
1558      word.push(c);
1559    } else {
1560      push_depluraled(&mut out, &word);
1561      word.clear();
1562      out.push(c);
1563    }
1564  }
1565  push_depluraled(&mut out, &word);
1566  out
1567}
1568
1569fn push_depluraled(out: &mut String, word: &str) {
1570  if word.len() > 1 && word.ends_with('s') {
1571    out.push_str(&word[..word.len() - 1]);
1572  } else {
1573    out.push_str(word);
1574  }
1575}
1576
1577/// Generate cyclic permutations of a slice.
1578fn cyclic_permute<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
1579  if items.len() <= 1 {
1580    return vec![items.to_vec()];
1581  }
1582  (0..items.len())
1583    .map(|i| {
1584      let mut perm = items[i..].to_vec();
1585      perm.extend_from_slice(&items[..i]);
1586      perm
1587    })
1588    .collect()
1589}
1590
1591#[cfg(test)]
1592mod tests {
1593  use super::*;
1594
1595  #[test]
1596  fn initial_letter_ascii_uppercases() {
1597    assert_eq!(initial_letter("alpha"), "A");
1598    assert_eq!(initial_letter("Zebra"), "Z");
1599  }
1600
1601  #[test]
1602  fn initial_letter_skips_leading_whitespace() {
1603    assert_eq!(initial_letter("  beta"), "B");
1604  }
1605
1606  #[test]
1607  fn initial_letter_nfd_decomposes_accents() {
1608    // NFD decomposes 'É' (U+00C9) into 'E' + combining accent — the first
1609    // char is then ASCII 'E'.
1610    assert_eq!(initial_letter("Éclair"), "E");
1611    assert_eq!(initial_letter("über"), "U");
1612  }
1613
1614  #[test]
1615  fn initial_letter_non_alpha_is_star() {
1616    assert_eq!(initial_letter("123abc"), "*");
1617    assert_eq!(initial_letter("#hash"), "*");
1618    assert_eq!(initial_letter(""), "*");
1619    assert_eq!(initial_letter("   "), "*");
1620  }
1621
1622  #[test]
1623  fn get_index_key_id_strips_non_alphanumeric() {
1624    assert_eq!(get_index_key_id("Foo Bar!"), "FooBar");
1625    assert_eq!(get_index_key_id("abc-123"), "abc123");
1626  }
1627
1628  #[test]
1629  fn get_index_key_id_nfd_drops_combining_marks() {
1630    // 'é' → 'e' + combining accent; combining mark isn't ASCII alphanumeric,
1631    // so it's dropped, leaving just "e".
1632    assert_eq!(get_index_key_id("é"), "e");
1633    assert_eq!(get_index_key_id("Éclair"), "Eclair");
1634  }
1635
1636  #[test]
1637  fn get_index_key_id_empty_input() {
1638    assert_eq!(get_index_key_id(""), "");
1639    assert_eq!(get_index_key_id("!!!"), "");
1640  }
1641
1642  #[test]
1643  fn cyclic_permute_empty_returns_single_empty() {
1644    let empty: Vec<i32> = vec![];
1645    assert_eq!(cyclic_permute::<i32>(&empty), vec![Vec::<i32>::new()]);
1646  }
1647
1648  #[test]
1649  fn cyclic_permute_single_element_returns_itself() {
1650    assert_eq!(cyclic_permute(&[42]), vec![vec![42]]);
1651  }
1652
1653  #[test]
1654  fn cyclic_permute_three_element_rotations() {
1655    let result = cyclic_permute(&["a", "b", "c"]);
1656    assert_eq!(result, vec![
1657      vec!["a", "b", "c"],
1658      vec!["b", "c", "a"],
1659      vec!["c", "a", "b"],
1660    ]);
1661  }
1662
1663  #[test]
1664  fn cyclic_permute_count_equals_input_len() {
1665    let result = cyclic_permute(&[1, 2, 3, 4, 5]);
1666    assert_eq!(result.len(), 5);
1667    for perm in &result {
1668      assert_eq!(perm.len(), 5);
1669    }
1670  }
1671}