1use 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
20pub const DEFAULT_INDEX_LIST: &str = "idx";
24
25pub 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
36fn 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#[derive(Debug)]
47struct SeeAlso {
48 name: Option<String>,
50 text: String,
52 node: Option<Node>,
54}
55
56#[derive(Debug, Clone)]
60struct PhraseRef {
61 key: String,
62 text: String,
63 node: Option<Node>,
64}
65
66#[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
98pub 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
102struct GlossaryEntry {
104 key: String,
106 id: String,
108 parent: Option<String>,
109 initial: String,
110 sort_key: String,
111 group: Vec<NodeData>,
113 formatted: NodeData,
114}
115
116pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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()), 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 fn make_index_ref(&self, id: &str, styles: &HashMap<String, bool>) -> NodeData {
527 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 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 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 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 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 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 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 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 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".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 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 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 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 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 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
836fn 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
882fn 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 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 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 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 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
1009fn 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 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 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 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 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
1109fn 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
1135fn 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
1151fn 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
1198fn 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
1208fn 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
1226fn 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
1237fn 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#[derive(Debug, Clone)]
1257struct SeeChunk {
1258 key: String,
1259 xml: Vec<NodeData>,
1260}
1261
1262fn seealso_partition(see: &Node) -> Vec<SeeChunk> {
1266 let parts = seealso_partition_aux(see);
1267 if parts.is_empty() {
1268 return parts;
1269 }
1270 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 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
1307fn 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 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 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 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
1389fn 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
1406fn 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; }
1416 rest = trimmed;
1417 }
1418 rest = rest.strip_prefix(word)?;
1419 }
1420 match rest.chars().next() {
1422 Some(c) if c.is_alphanumeric() || c == '_' => None,
1423 _ => Some(rest),
1424 }
1425}
1426
1427fn 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
1438fn 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
1448fn 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
1455fn 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 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 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 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
1493fn 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
1533fn 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
1552fn 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
1577fn 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 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 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}