1use latexml_core::common::xml::name_is;
9use libxml::tree::{Node, NodeType};
10use rustc_hash::FxHashMap as HashMap;
11
12use crate::{
13 document::{PostDocument, is_ltx},
14 object_db::{ObjectDB, Value},
15 processor::{ProcessResult, Processor},
16};
17
18pub struct Scan {
22 name: String,
23 pub db: ObjectDB,
25 page_id: Option<String>,
27 label_ids: bool,
29 db_status_due_at: usize,
35 page_needs_index: bool,
40 page_needs_bib: bool,
42}
43
44struct ScannedProps {
46 props: Vec<(String, Value)>,
48 labels: Vec<String>,
50 id: Option<String>,
52}
53
54impl ScannedProps {
55 fn push(&mut self, key: &str, val: Value) { self.props.push((key.to_string(), val)); }
56}
57
58impl Scan {
59 pub fn new(db: ObjectDB) -> Self {
60 Scan {
61 name: "Scan".to_string(),
62 db,
63 page_id: None,
64 label_ids: false,
65 db_status_due_at: 1,
66 page_needs_index: false,
67 page_needs_bib: false,
68 }
69 }
70
71 pub fn with_label_ids(mut self, label_ids: bool) -> Self {
74 self.label_ids = label_ids;
75 self
76 }
77
78 pub fn last_page_placeholders(&self) -> (bool, bool) {
81 (self.page_needs_index, self.page_needs_bib)
82 }
83
84 pub fn scan(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
88 if let Some(qname) = doc.get_qname(node) {
89 self.dispatch(doc, node, &qname, parent_id);
90 }
91 }
92
93 fn dispatch(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
95 match tag {
96 "ltx:document" | "ltx:part" | "ltx:chapter" | "ltx:section" | "ltx:appendix"
97 | "ltx:subsection" | "ltx:subsubsection" | "ltx:paragraph" | "ltx:subparagraph"
98 | "ltx:bibliography" | "ltx:index" | "ltx:glossary" | "ltx:theorem" | "ltx:proof" => {
99 match tag {
100 "ltx:bibliography" => self.page_needs_bib = true,
101 "ltx:index" if !self.page_needs_index && !has_ltx_element_child(node, "indexlist") => {
102 self.page_needs_index = true;
103 },
104 "ltx:glossary"
105 if !self.page_needs_index && !has_ltx_element_child(node, "glossarylist") =>
106 {
107 self.page_needs_index = true;
108 },
109 _ => {},
110 }
111 self.section_handler(doc, node, tag, parent_id)
112 },
113 "ltx:abstract" => self.named_handler(doc, node, tag, parent_id, "Abstract"),
117 "ltx:acknowledgements" => self.named_handler(doc, node, tag, parent_id, "Acknowledgements"),
118 "ltx:table" | "ltx:figure" | "ltx:float" | "ltx:listing" => {
119 self.captioned_handler(doc, node, tag, parent_id)
120 },
121 "ltx:equation" | "ltx:equationgroup" | "ltx:item" | "ltx:listingline" => {
122 self.labelled_handler(doc, node, tag, parent_id)
123 },
124 "ltx:anchor" => self.anchor_handler(doc, node, tag, parent_id),
125 "ltx:Math" => {
139 let id = get_xml_id(node);
140 if let Some(ref id_str) = id {
141 let sp = self.collect_common(doc, node, tag, parent_id);
142 let key = format!("ID:{}", id_str);
143 self.register_scanned(&key, sp);
144 self.add_as_child(id_str, parent_id);
145 }
146 },
148 "ltx:note" => self.note_handler(doc, node, tag, parent_id),
149 "ltx:bibitem" => self.bibitem_handler(doc, node, parent_id),
150 "ltx:bibentry" => {},
151 "ltx:indexmark" => self.indexmark_handler(doc, node, parent_id),
152 "ltx:glossaryentry" | "ltx:glossarydefinition" => {
153 self.glossaryentry_handler(doc, node, tag, parent_id)
154 },
155 "ltx:ref" => self.ref_handler(doc, node, tag, parent_id),
156 "ltx:bibref" => self.bibref_handler(doc, node, tag, parent_id),
157 "ltx:glossaryref" => self.glossaryref_handler(doc, node, tag, parent_id),
158 "ltx:navigation" | "ltx:rawhtml" => {},
159 "ltx:rdf" => self.rdf_handler(node, parent_id),
160 "ltx:declare" => self.declare_handler(doc, node, tag, parent_id),
161 "ltx:description" => {
162 if !self.page_needs_index
163 && node
164 .get_attribute("class")
165 .is_some_and(|c| c.split(' ').any(|cls| cls == "ltx_nomenclature"))
166 && !has_ltx_element_child(node, "item")
167 {
168 self.page_needs_index = true;
169 }
170 self.default_handler(doc, node, tag, parent_id)
171 },
172 _ => self.default_handler(doc, node, tag, parent_id),
173 }
174 }
175
176 pub fn scan_children(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
178 let children = collect_element_children(node);
179 for child in &children {
180 self.scan(doc, child, parent_id);
181 }
182 }
183
184 fn page_id(&self, doc: &PostDocument) -> Option<String> {
186 self.page_id.clone().or_else(|| {
187 doc
188 .get_document_element()
189 .and_then(|root| get_xml_id(&root))
190 })
191 }
192
193 fn in_page_id(&self, doc: &PostDocument, node: &Node) -> Option<String> {
197 let mut id = get_xml_id(node);
198 let mut base_id = self.page_id(doc).unwrap_or_default();
199 if self.label_ids {
201 if let Some(label) = first_label(node.get_attribute("labels").as_deref()) {
202 id = Some(label);
203 if let Some(base_label) = doc
204 .get_document_element()
205 .and_then(|root| first_label(root.get_attribute("labels").as_deref()))
206 {
207 base_id = base_label;
208 }
209 }
210 }
211 let id = id?;
212 if id == base_id {
213 None
214 } else if !base_id.is_empty() {
215 if let Some(rest) = id.strip_prefix(&base_id).and_then(|r| r.strip_prefix('.')) {
216 Some(rest.to_string())
217 } else {
218 Some(id)
219 }
220 } else {
221 Some(id)
222 }
223 }
224
225 fn collect_common(
228 &mut self,
229 doc: &PostDocument,
230 node: &Node,
231 tag: &str,
232 parent_id: Option<&str>,
233 ) -> ScannedProps {
234 let id = get_xml_id(node);
235 let labels_str = node.get_attribute("labels");
236 let labels: Vec<String> = labels_str
237 .map(|s| s.split_whitespace().map(String::from).collect())
238 .unwrap_or_default();
239
240 let mut sp = ScannedProps { props: Vec::new(), labels, id };
241
242 sp.push("type", Value::from(tag));
243 if let Some(ref id_str) = sp.id {
244 sp.push("id", Value::from(id_str.as_str()));
245 }
246 if let Some(pid) = parent_id {
247 sp.push("parent", Value::from(pid));
248 }
249 if !sp.labels.is_empty() {
250 sp.push("labels", Value::from(sp.labels.clone()));
251 }
252 if let Some(loc) = doc.site_relative_destination() {
253 sp.push("location", Value::from(loc));
254 }
255 if let Some(pageid) = self.page_id(doc) {
256 sp.push("pageid", Value::from(pageid));
257 }
258 if sp.id.is_some() {
259 if let Some(fragid) = self.in_page_id(doc, node) {
260 sp.push("fragid", Value::from(fragid));
261 }
262 }
263
264 if let Some(listnames) = node.get_attribute("inlist") {
266 let mut inlist = HashMap::default();
267 for name in listnames.split_whitespace() {
268 inlist.insert(name.to_string(), Value::Bool(true));
269 }
270 sp.push("inlist", Value::Hash(inlist));
271 }
272
273 let mut has_refnum = false;
275 for tagnode in child_tag_nodes(node) {
276 let key = if let Some(role) = tagnode.get_attribute("role") {
277 if role.ends_with("refnum") {
278 role
279 } else {
280 format!("tag:{}", role)
281 }
282 } else {
283 "refnum".to_string()
284 };
285 if key == "refnum" {
286 has_refnum = true;
287 }
288 let value = if has_markup(&tagnode) {
294 self.clean_node(doc, &tagnode)
295 } else {
296 Value::from(clean_text_content(&tagnode))
297 };
298 sp.push(&key, value);
299 }
300
301 if tag == "ltx:equation" && !sp.labels.is_empty() && !has_refnum {
313 if let Some(inherited) = group_sibling_refnum(node) {
314 sp.push("refnum", Value::from(inherited));
315 }
316 }
317
318 sp
319 }
320
321 fn register_scanned(&mut self, db_key: &str, sp: ScannedProps) {
323 if let Some(ref id) = sp.id {
325 for label in &sp.labels {
326 self
327 .db
328 .register(label, vec![("id", Value::from(id.as_str()))]);
329 }
330 }
331 let owned_props: Vec<(&str, Value)> = Vec::new();
333 let entry = self.db.register(db_key, owned_props);
334 for (k, v) in sp.props {
335 entry.set_value(&k, v);
336 }
337 }
338
339 fn add_as_child(&mut self, id: &str, parent_id: Option<&str>) {
341 let mut current_parent = parent_id.map(String::from);
342 while let Some(ref pid) = current_parent {
343 let key = format!("ID:{}", pid);
344 let has_children = self
345 .db
346 .lookup(&key)
347 .map(|e| e.has_value("children"))
348 .unwrap_or(false);
349 if has_children {
350 if let Some(entry_mut) = self.db.lookup_mut(&key) {
351 entry_mut.push_new("children", vec![Value::from(id)]);
352 }
353 return;
354 }
355 let parent = self
356 .db
357 .lookup(&key)
358 .and_then(|e| e.get_string("parent").map(String::from));
359 current_parent = parent;
360 }
361 }
362
363 fn default_handler(
367 &mut self,
368 doc: &PostDocument,
369 node: &Node,
370 tag: &str,
371 parent_id: Option<&str>,
372 ) {
373 let id = get_xml_id(node);
381 if let Some(ref id_str) = id {
382 let sp = self.collect_common(doc, node, tag, parent_id);
383 let key = format!("ID:{}", id_str);
384 self.register_scanned(&key, sp);
385 }
390 let effective_id = id.as_deref().or(parent_id);
391 self.scan_children(doc, node, effective_id);
392 }
393
394 fn clean_node(&mut self, doc: &PostDocument, node: &Node) -> Value {
406 let has_marks = doc.findnode_at(".//ltx:indexmark", node).is_some();
409 match self.db.adopt_xml(node) {
410 Some(Value::Xml(copy)) => {
411 if has_marks {
412 let mut marks = Vec::new();
413 collect_indexmarks(©, &mut marks);
414 for mark in marks {
415 mark.free_subtree();
416 }
417 }
418 Value::Xml(copy)
419 },
420 Some(other) => other,
421 None => Value::from(title_text_content(doc, node).as_str()),
422 }
423 }
424
425 fn section_handler(
426 &mut self,
427 doc: &PostDocument,
428 node: &Node,
429 tag: &str,
430 parent_id: Option<&str>,
431 ) {
432 let mut sp = self.collect_common(doc, node, tag, parent_id);
433 let id = sp.id.clone();
434 if let Some(ref id_str) = id {
435 sp.push("primary", Value::Bool(true));
436 sp.push("children", Value::List(Vec::new()));
437 if let Some(title_node) = doc.findnode_at("ltx:title", node) {
447 let value = self.clean_node(doc, &title_node);
448 sp.push("title", value);
449 }
450 if let Some(toctitle_node) = doc.findnode_at("ltx:toctitle", node) {
451 let value = self.clean_node(doc, &toctitle_node);
452 sp.push("toctitle", value);
453 }
454 if let Some(stub) = node.get_attribute("stub") {
455 sp.push("stub", Value::from(stub));
456 }
457 let key = format!("ID:{}", id_str);
458 self.register_scanned(&key, sp);
459 self.add_as_child(id_str, parent_id);
460 }
461 let effective_id = id.as_deref().or(parent_id);
462 self.scan_children(doc, node, effective_id);
463 }
464
465 fn named_handler(
472 &mut self,
473 doc: &PostDocument,
474 node: &Node,
475 tag: &str,
476 parent_id: Option<&str>,
477 default_name: &str,
478 ) {
479 let mut sp = self.collect_common(doc, node, tag, parent_id);
480 let id = sp.id.clone();
481 if let Some(ref id_str) = id {
482 let name = node
483 .get_attribute("name")
484 .unwrap_or_else(|| default_name.to_string());
485 sp.push("primary", Value::Bool(true));
486 sp.push("children", Value::List(Vec::new()));
487 sp.push("title", Value::from(name.as_str()));
488 sp.push("toctitle", Value::from(name.as_str()));
489 let key = format!("ID:{}", id_str);
490 self.register_scanned(&key, sp);
491 self.add_as_child(id_str, parent_id);
492 }
493 let effective_id = id.as_deref().or(parent_id);
494 self.scan_children(doc, node, effective_id);
495 }
496
497 fn captioned_handler(
498 &mut self,
499 doc: &PostDocument,
500 node: &Node,
501 tag: &str,
502 parent_id: Option<&str>,
503 ) {
504 let mut sp = self.collect_common(doc, node, tag, parent_id);
505 let id = sp.id.clone();
506 if let Some(ref id_str) = id {
507 if let Some(role) = node.get_attribute("role") {
508 sp.push("role", Value::from(role));
509 }
510 let caption = doc
511 .findnode_at("child::ltx:caption", node)
512 .or_else(|| doc.findnode_at("descendant::ltx:caption", node));
513 if let Some(ref cap) = caption {
516 let value = self.clean_node(doc, cap);
517 sp.push("caption", value);
518 }
519 let toccaption = doc
520 .findnode_at("child::ltx:toccaption", node)
521 .or_else(|| doc.findnode_at("descendant::ltx:toccaption", node));
522 if let Some(ref tc) = toccaption {
523 let value = self.clean_node(doc, tc);
524 sp.push("toccaption", value);
525 }
526 let key = format!("ID:{}", id_str);
527 self.register_scanned(&key, sp);
528 self.add_as_child(id_str, parent_id);
529 }
530 let effective_id = id.as_deref().or(parent_id);
531 self.scan_children(doc, node, effective_id);
532 }
533
534 fn labelled_handler(
535 &mut self,
536 doc: &PostDocument,
537 node: &Node,
538 tag: &str,
539 parent_id: Option<&str>,
540 ) {
541 let mut sp = self.collect_common(doc, node, tag, parent_id);
542 let id = sp.id.clone();
543 if let Some(ref id_str) = id {
544 if let Some(role) = node.get_attribute("role") {
545 sp.push("role", Value::from(role));
546 }
547 let key = format!("ID:{}", id_str);
548 self.register_scanned(&key, sp);
549 self.add_as_child(id_str, parent_id);
550 }
551 let effective_id = id.as_deref().or(parent_id);
552 self.scan_children(doc, node, effective_id);
553 }
554
555 fn anchor_handler(
556 &mut self,
557 doc: &PostDocument,
558 node: &Node,
559 tag: &str,
560 parent_id: Option<&str>,
561 ) {
562 let mut sp = self.collect_common(doc, node, tag, parent_id);
563 let id = sp.id.clone();
564 if let Some(ref id_str) = id {
565 sp.push("title", Value::from(clean_text_content(node)));
567 let key = format!("ID:{}", id_str);
568 self.register_scanned(&key, sp);
569 self.add_as_child(id_str, parent_id);
570 }
571 let effective_id = id.as_deref().or(parent_id);
572 self.scan_children(doc, node, effective_id);
573 }
574
575 fn note_handler(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
576 let mut sp = self.collect_common(doc, node, tag, parent_id);
577 let id = sp.id.clone();
578 if let Some(ref id_str) = id {
579 if let Some(role) = node.get_attribute("role") {
580 sp.push("role", Value::from(role));
581 }
582 let mut note = String::new();
586 let mut child = node.get_first_child();
587 while let Some(c) = child {
588 if !(is_ltx(&c) && name_is(&c, "tags")) {
589 note.push_str(&clean_text_content(&c));
590 }
591 child = c.get_next_sibling();
592 }
593 sp.push("note", Value::from(note));
594 let key = format!("ID:{}", id_str);
595 self.register_scanned(&key, sp);
596 self.add_as_child(id_str, parent_id);
597 }
598 let effective_id = id.as_deref().or(parent_id);
599 self.scan_children(doc, node, effective_id);
600 }
601
602 fn bibitem_handler(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
603 let id = match get_xml_id(node) {
604 Some(id) => id,
605 None => {
606 self.scan_children(doc, node, parent_id);
607 return;
608 },
609 };
610
611 let key = node.get_attribute("key");
612 let bib = doc.findnode_at("ancestor-or-self::ltx:bibliography", node);
613 let lists_str = bib
614 .and_then(|b| b.get_attribute("lists"))
615 .unwrap_or_else(|| "bibliography".to_string());
616
617 if let Some(ref bibkey) = key {
619 for list in lists_str.split_whitespace() {
620 let label_key = format!("BIBLABEL:{}:{}", list, bibkey);
621 self
622 .db
623 .register(&label_key, vec![("id", Value::from(id.as_str()))]);
624 }
625 }
626
627 let mut props: Vec<(String, Value)> = Vec::new();
629 props.push(("id".to_string(), Value::from(id.as_str())));
630 props.push(("type".to_string(), Value::from("ltx:bibitem")));
631 if let Some(pid) = parent_id {
632 props.push(("parent".to_string(), Value::from(pid)));
633 }
634 if let Some(ref k) = key {
635 props.push(("bibkey".to_string(), Value::from(k.as_str())));
636 }
637 if let Some(loc) = doc.site_relative_destination() {
638 props.push(("location".to_string(), Value::from(loc)));
639 }
640 if let Some(pageid) = self.page_id(doc) {
641 props.push(("pageid".to_string(), Value::from(pageid)));
642 }
643 if let Some(fragid) = self.in_page_id(doc, node) {
644 props.push(("fragid".to_string(), Value::from(fragid)));
645 }
646
647 props.extend(bibitem_tag_props(doc, node));
648
649 let db_key = format!("ID:{}", id);
650 let entry = self.db.register(&db_key, vec![]);
651 for (k, v) in props {
652 entry.set_value(&k, v);
653 }
654
655 self.scan_children(doc, node, Some(&id));
656 }
657
658 fn ref_handler(&mut self, doc: &PostDocument, node: &Node, tag: &str, parent_id: Option<&str>) {
659 if let Some(label) = node.get_attribute("labelref") {
660 let in_toc = !doc
661 .findnodes_at(
662 "ancestor::ltx:tocentry | ancestor::ltx:bibblock[contains(@class,'ltx_bib_cited')]",
663 Some(node),
664 )
665 .is_empty();
666 if !in_toc {
667 self.db.register(&label, vec![]);
668 if let Some(pid) = parent_id {
669 if let Some(entry) = self.db.lookup_mut(&label) {
670 entry.note_association(&["referrers", pid]);
671 }
672 }
673 }
674 }
675 self.default_handler(doc, node, tag, parent_id);
676 }
677
678 fn bibref_handler(
679 &mut self,
680 doc: &PostDocument,
681 node: &Node,
682 tag: &str,
683 parent_id: Option<&str>,
684 ) {
685 let in_cited = !doc
686 .findnodes_at(
687 "ancestor::ltx:bibblock[contains(@class,'ltx_bib_cited')]",
688 Some(node),
689 )
690 .is_empty();
691 if !in_cited {
692 if node
695 .get_attribute("show")
696 .is_some_and(|show| show.to_ascii_lowercase().contains("fullentry"))
697 {
698 self.db.register("FULLENTRY", vec![]);
699 }
700 if let Some(keys) = node.get_attribute("bibrefs") {
701 let inlist = node.get_attribute("inlist").unwrap_or_default();
702 let mut lists: Vec<&str> = inlist.split_whitespace().collect();
703 lists.push("bibliography");
704 let label_keys: Vec<String> = keys
705 .split(',')
706 .filter(|k| !k.is_empty())
707 .flat_map(|bibkey| {
708 lists
709 .iter()
710 .map(move |list| format!("BIBLABEL:{}:{}", list, bibkey))
711 })
712 .collect();
713 for label_key in &label_keys {
714 self.db.register(label_key, vec![]);
715 }
716 if let Some(pid) = parent_id {
717 for label_key in &label_keys {
718 if let Some(entry) = self.db.lookup_mut(label_key) {
719 entry.note_association(&["referrers", pid]);
720 }
721 }
722 }
723 }
724 }
725 self.default_handler(doc, node, tag, parent_id);
726 }
727
728 fn glossaryref_handler(
729 &mut self,
730 doc: &PostDocument,
731 node: &Node,
732 tag: &str,
733 parent_id: Option<&str>,
734 ) {
735 if let (Some(k), Some(l)) = (node.get_attribute("key"), node.get_attribute("inlist")) {
736 let gkey = format!("GLOSSARY:{}:{}", l, k);
737 self.db.register(&gkey, vec![]);
738 if let Some(pid) = parent_id {
739 if let Some(entry) = self.db.lookup_mut(&gkey) {
740 entry.note_association(&["referrers", pid]);
741 }
742 }
743 }
744 self.default_handler(doc, node, tag, parent_id);
745 }
746
747 fn indexmark_handler(&mut self, doc: &PostDocument, node: &Node, parent_id: Option<&str>) {
748 let phrases = doc.findnodes_at("ltx:indexphrase", Some(node));
749 let see_also = doc.findnodes_at("ltx:indexsee", Some(node));
750
751 let key_parts: Vec<String> = phrases
752 .iter()
753 .filter_map(|p| p.get_attribute("key"))
754 .collect();
755
756 let inlist = node.get_attribute("inlist").map(|listnames| {
757 let mut h = HashMap::default();
758 for name in listnames.split_whitespace() {
759 h.insert(name.to_string(), Value::Bool(true));
760 }
761 Value::Hash(h)
762 });
763 let lists: Vec<String> = node
769 .get_attribute("inlist")
770 .map(|names| names.split_whitespace().map(str::to_string).collect())
771 .filter(|names: &Vec<String>| !names.is_empty())
772 .unwrap_or_else(|| vec![crate::make_index::DEFAULT_INDEX_LIST.to_string()]);
773 for list in &lists {
774 let key = crate::make_index::index_db_key(list, &key_parts);
775 self.register_indexmark(&key, &phrases, &see_also, inlist.clone(), node, parent_id);
776 }
777 }
778
779 fn register_indexmark(
782 &mut self,
783 key: &str,
784 phrases: &[Node],
785 see_also: &[Node],
786 inlist: Option<Value>,
787 node: &Node,
788 parent_id: Option<&str>,
789 ) {
790 let exists = self.db.lookup(key).is_some();
791 if !exists {
792 let adopted: Vec<Value> = phrases
800 .iter()
801 .map(|n| {
802 self
803 .db
804 .adopt_xml(n)
805 .unwrap_or_else(|| Value::from(n.get_content().as_str()))
806 })
807 .collect();
808 let mut props = vec![("phrases", Value::List(adopted))];
809 if let Some(il) = inlist {
810 props.push(("inlist", il));
811 }
812 self.db.register(key, props);
813 }
814
815 if !see_also.is_empty() {
816 let nodes: Vec<Value> = see_also
821 .iter()
822 .map(|n| {
823 self
824 .db
825 .adopt_xml(n)
826 .unwrap_or_else(|| Value::from(n.get_content().as_str()))
827 })
828 .collect();
829 if let Some(entry) = self.db.lookup_mut(key) {
830 entry.push_new("see_also", nodes);
831 }
832 } else if let Some(pid) = parent_id {
833 let style = node
834 .get_attribute("style")
835 .unwrap_or_else(|| "normal".to_string());
836 if let Some(entry) = self.db.lookup_mut(key) {
837 entry.note_association(&["referrers", pid, &style]);
838 }
839 }
840 }
841
842 fn glossaryentry_handler(
843 &mut self,
844 doc: &PostDocument,
845 node: &Node,
846 tag: &str,
847 parent_id: Option<&str>,
848 ) {
849 let id = if tag == "ltx:glossaryentry" {
850 get_xml_id(node)
851 } else {
852 None
853 };
854 let lists = node.get_attribute("inlist").unwrap_or_else(|| {
855 doc
856 .findnode_at(
857 "ancestor::ltx:glossarylist[@lists] | ancestor::ltx:glossary[@lists]",
858 node,
859 )
860 .and_then(|p| p.get_attribute("lists"))
861 .unwrap_or_else(|| "glossary".to_string())
862 });
863 let key = node.get_attribute("key").unwrap_or_default();
864 let phrases = doc.findnodes_at("ltx:glossaryphrase", Some(node));
865
866 for list in lists.split_whitespace() {
867 let gkey = format!("GLOSSARY:{}:{}", list, key);
868 let values: Vec<(String, Value)> = phrases
874 .iter()
875 .map(|phrase| {
876 let role = phrase
877 .get_attribute("role")
878 .unwrap_or_else(|| "label".to_string());
879 let value = self
880 .db
881 .adopt_xml(phrase)
882 .unwrap_or_else(|| Value::from(phrase.get_content()));
883 (format!("phrase:{role}"), value)
884 })
885 .collect();
886 let entry = self.db.register(&gkey, vec![]);
887 for (prop_key, value) in values {
888 entry.set_value(&prop_key, value);
889 }
890 if let Some(ref id_str) = id {
891 entry.set_value("id", Value::from(id_str.as_str()));
892 }
893 }
894
895 if let Some(ref id_str) = id {
896 let sp = self.collect_common(doc, node, tag, parent_id);
897 let db_key = format!("ID:{}", id_str);
898 self.register_scanned(&db_key, sp);
899 }
900 let effective_id = id.as_deref().or(parent_id);
901 self.scan_children(doc, node, effective_id);
902 }
903
904 fn rdf_handler(&mut self, node: &Node, parent_id: Option<&str>) {
905 let mut id = node.get_attribute("about");
906 if let Some(ref about) = id {
907 if let Some(stripped) = about.strip_prefix('#') {
908 id = Some(stripped.to_string());
909 }
910 }
911 let id = id.or_else(|| parent_id.map(String::from));
912 let property = node.get_attribute("property");
913 let value = node
914 .get_attribute("resource")
915 .or_else(|| node.get_attribute("content"));
916
917 if let (Some(prop), Some(val), Some(id_str)) = (property, value, id) {
918 let db_key = format!("ID:{}", id_str);
919 let entry = self.db.register(&db_key, vec![]);
920 entry.set_value(&prop, Value::from(val));
921 }
922 }
923
924 fn declare_handler(
925 &mut self,
926 doc: &PostDocument,
927 node: &Node,
928 tag: &str,
929 parent_id: Option<&str>,
930 ) {
931 let decl_type = node.get_attribute("type");
932 let sort = node.get_attribute("sortkey");
933 let decl_id = get_xml_id(node);
934 let definiens = node.get_attribute("definiens");
935
936 let term = doc.findnode_at("child::ltx:tags/ltx:tag[@role='term']", node);
939 let description = doc.findnode_at("child::ltx:text", node);
940
941 if decl_type.as_deref() == Some("definition") {
942 let mut def = definiens.clone();
943 if def.is_none() {
944 if let Some(ref term_node) = term {
945 let syms: Vec<Node> = doc
946 .findnodes_at("descendant-or-self::ltx:XMTok[@meaning]", Some(term_node))
947 .into_iter()
948 .filter(|sym| !in_indexmark_below(sym, term_node))
949 .collect();
950 let mut non_rel = Vec::new();
951 let mut rel = Vec::new();
952 for sym in &syms {
953 let meaning = sym.get_attribute("meaning").unwrap_or_default();
954 if meaning.starts_with("delimited-") {
955 continue;
956 }
957 if sym.with_attribute(c"role", |v| v == "RELOP") == Some(true) {
958 rel.push(meaning);
959 } else {
960 non_rel.push(meaning);
961 }
962 }
963 non_rel.extend(rel);
964 def = non_rel.into_iter().next();
965 }
966 }
967 if let Some(ref def_name) = def {
968 let dkey = format!("DECLARATION:global:{}", def_name);
969 let mut sp = self.collect_common(doc, node, tag, parent_id);
970 if let Some(ref desc) = description {
971 sp.push("description", Value::from(clean_text_content(desc)));
972 }
973 self.register_scanned(&dkey, sp);
974 }
975 } else if decl_type.is_none() && parent_id.is_some() {
976 if let Some(ref did) = decl_id {
977 let has_content =
978 description.is_some() || doc.findnode_at("ltx:tags/ltx:tag", node).is_some();
979 if has_content {
980 let dkey = format!("DECLARATION:local:{}", did);
981 let mut sp = self.collect_common(doc, node, tag, parent_id);
982 if let Some(ref desc) = description {
983 sp.push("description", Value::from(clean_text_content(desc)));
984 }
985 self.register_scanned(&dkey, sp);
986 }
987 }
988 }
989
990 if let Some(ref sk) = sort {
991 let name = definiens.as_deref().or(decl_id.as_deref()).unwrap_or(sk);
992 let nkey = format!("NOTATION:{}", name);
993 let mut sp = self.collect_common(doc, node, tag, parent_id);
994 sp.push("sortkey", Value::from(sk.as_str()));
995 if let Some(ref desc) = description {
996 sp.push("description", Value::from(clean_text_content(desc)));
997 }
998 self.register_scanned(&nkey, sp);
999 }
1000 }
1001}
1002
1003fn first_label(labels: Option<&str>) -> Option<String> {
1005 let first = labels?.split_whitespace().next()?;
1006 Some(first.strip_prefix("LABEL:").unwrap_or(first).to_string())
1007}
1008
1009impl Processor for Scan {
1010 fn get_name(&self) -> &str { &self.name }
1011
1012 fn process(&mut self, doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
1013 self.page_needs_index = false;
1014 self.page_needs_bib = false;
1015
1016 let root = match doc.get_document_element() {
1017 Some(r) => r,
1018 None => return Ok(vec![doc]),
1019 };
1020
1021 let id = get_xml_id(&root).unwrap_or_else(|| {
1022 let mut root_mut = root.clone();
1023 root_mut.set_attribute("xml:id", "Document").ok();
1024 "Document".to_string()
1025 });
1026
1027 if self.db.lookup("SITE_ROOT").is_none() {
1028 self
1029 .db
1030 .register("SITE_ROOT", vec![("id", Value::from(id.as_str()))]);
1031 }
1032
1033 self.page_id = Some(id.clone());
1034 self.scan(&doc, &root, doc.parent_id.as_deref());
1039 self.page_id = None;
1040
1041 let loc = doc.site_relative_destination().unwrap_or_default();
1042 let doc_key = format!("DOCUMENT:{}", loc);
1043 self
1044 .db
1045 .register(&doc_key, vec![("id", Value::from(id.as_str()))]);
1046
1047 let site_id = self
1053 .db
1054 .lookup("SITE_ROOT")
1055 .and_then(|e| e.get_string("id").map(String::from))
1056 .unwrap_or_default();
1057 let id_key = format!("ID:{}", id);
1058 let needs_parent = self
1059 .db
1060 .lookup(&id_key)
1061 .map(|e| !e.has_value("parent"))
1062 .unwrap_or(false);
1063 if !site_id.is_empty() && id != site_id && needs_parent {
1064 let mut parent_id: Option<String> = None;
1066 let mut upid = id.clone();
1067 while let Some(dot) = upid.rfind('.') {
1068 upid.truncate(dot);
1069 if !upid.is_empty() && self.db.lookup(&format!("ID:{}", upid)).is_some() {
1070 parent_id = Some(upid.clone());
1071 break;
1072 }
1073 }
1074 if parent_id.is_none() {
1076 parent_id = Some(site_id);
1077 }
1078 if let Some(pid) = parent_id {
1079 if pid != id {
1080 if let Some(entry_mut) = self.db.lookup_mut(&id_key) {
1081 entry_mut.set_values(vec![("parent", Value::from(pid.as_str()))]);
1082 }
1083 self.add_as_child(&id, Some(&pid));
1084 }
1085 }
1086 }
1087
1088 if self.db.len() >= self.db_status_due_at {
1091 Info!("scan", "db_status", "Scan: DBStatus: {}", self.db.status());
1092 self.db_status_due_at = (self.db.len() + 1).next_power_of_two();
1093 }
1094 Ok(vec![doc])
1095 }
1096}
1097
1098pub fn bibitem_tag_props(doc: &PostDocument, node: &Node) -> Vec<(String, Value)> {
1111 let mut props = Vec::new();
1112 for role in &[
1113 "authors",
1114 "fullauthors",
1115 "year",
1116 "number",
1117 "refnum",
1118 "title",
1119 "key",
1120 "bibtype",
1121 ] {
1122 let xpath = format!("ltx:tags/ltx:tag[@role='{}']", role);
1123 if let Some(tagnode) = doc.findnode_at(&xpath, node) {
1124 let prop_name = match *role {
1125 "key" => "keytag",
1126 "bibtype" => "typetag",
1127 _ => *role,
1128 };
1129 props.push((prop_name.to_string(), Value::from(tagnode.get_content())));
1130 }
1131 }
1132 props
1133}
1134
1135fn collect_element_children(node: &Node) -> Vec<Node> {
1136 let mut result = Vec::new();
1137 if let Some(child) = node.get_first_child() {
1138 let mut current = Some(child);
1139 while let Some(ref c) = current {
1140 if c.get_type() == Some(NodeType::ElementNode) {
1141 result.push(c.clone());
1142 }
1143 current = c.get_next_sibling();
1144 }
1145 }
1146 result
1147}
1148
1149fn equation_refnum_text(node: &Node) -> Option<String> {
1153 for t in child_tag_nodes(node) {
1154 if t.with_attribute(c"role", |v| v == "refnum") == Some(true) {
1155 let txt = clean_text_content(&t);
1157 if !txt.trim().is_empty() {
1158 return Some(txt);
1159 }
1160 }
1161 }
1162 None
1163}
1164
1165fn group_sibling_refnum(node: &Node) -> Option<String> {
1172 let parent = node.get_parent()?;
1173 if !name_is(&parent, "equationgroup") {
1174 return None;
1175 }
1176 let is_equation =
1177 |n: &Node| n.get_type() == Some(NodeType::ElementNode) && name_is(n, "equation");
1178 let mut fwd = node.get_next_sibling();
1179 while let Some(sib) = fwd {
1180 if is_equation(&sib) {
1181 if let Some(r) = equation_refnum_text(&sib) {
1182 return Some(r);
1183 }
1184 }
1185 fwd = sib.get_next_sibling();
1186 }
1187 let mut back = node.get_prev_sibling();
1188 while let Some(sib) = back {
1189 if is_equation(&sib) {
1190 if let Some(r) = equation_refnum_text(&sib) {
1191 return Some(r);
1192 }
1193 }
1194 back = sib.get_prev_sibling();
1195 }
1196 None
1197}
1198
1199fn child_tag_nodes(node: &Node) -> Vec<Node> {
1200 let mut result = Vec::new();
1201 let mut child = node.get_first_child();
1202 while let Some(c) = child {
1203 if c.get_type() == Some(NodeType::ElementNode) && name_is(&c, "tags") {
1204 let mut tag_child = c.get_first_child();
1205 while let Some(t) = tag_child {
1206 if t.get_type() == Some(NodeType::ElementNode) && name_is(&t, "tag") {
1207 result.push(t.clone());
1208 }
1209 tag_child = t.get_next_sibling();
1210 }
1211 }
1212 child = c.get_next_sibling();
1213 }
1214 result
1215}
1216
1217fn is_indexmark(node: &Node) -> bool {
1219 node.get_type() == Some(NodeType::ElementNode) && name_is(node, "indexmark") && is_ltx(node)
1220}
1221
1222fn collect_indexmarks(node: &Node, marks: &mut Vec<Node>) {
1225 let mut child = node.get_first_child();
1226 while let Some(c) = child {
1227 if is_indexmark(&c) {
1228 marks.push(c.clone());
1229 } else {
1230 collect_indexmarks(&c, marks);
1231 }
1232 child = c.get_next_sibling();
1233 }
1234}
1235
1236fn in_indexmark_below(node: &Node, top: &Node) -> bool {
1239 let mut current = (node != top).then(|| node.get_parent()).flatten();
1240 while let Some(n) = current {
1241 if n == *top {
1242 return false;
1243 }
1244 if is_indexmark(&n) {
1245 return true;
1246 }
1247 current = n.get_parent();
1248 }
1249 false
1250}
1251
1252fn clean_text_content(node: &Node) -> String {
1259 let mut text = String::new();
1260 push_clean_text(node, &mut text);
1261 text
1262}
1263
1264fn has_markup(node: &Node) -> bool {
1267 std::iter::successors(node.get_first_child(), |child| child.get_next_sibling()).any(|child| {
1268 child.get_type() == Some(NodeType::ElementNode)
1269 && !is_indexmark(&child)
1270 && !clean_text_content(&child).trim().is_empty()
1271 })
1272}
1273
1274fn push_clean_text(node: &Node, text: &mut String) {
1275 match node.get_type() {
1276 Some(NodeType::TextNode) | Some(NodeType::CDataSectionNode) | Some(NodeType::EntityRefNode) => {
1277 text.push_str(&node.get_content());
1278 },
1279 Some(NodeType::ElementNode) if !is_indexmark(node) => {
1280 let mut child = node.get_first_child();
1281 while let Some(c) = child {
1282 push_clean_text(&c, text);
1283 child = c.get_next_sibling();
1284 }
1285 },
1286 _ => {},
1287 }
1288}
1289
1290fn has_ltx_element_child(node: &Node, local: &str) -> bool {
1293 let mut child = node.get_first_child();
1294 while let Some(c) = child {
1295 if c.get_type() == Some(NodeType::ElementNode) && is_ltx(&c) && name_is(&c, local) {
1296 return true;
1297 }
1298 child = c.get_next_sibling();
1299 }
1300 false
1301}
1302
1303fn get_xml_id(node: &Node) -> Option<String> {
1305 node
1306 .get_attribute("xml:id")
1307 .or_else(|| node.get_attribute_ns("id", "http://www.w3.org/XML/1998/namespace"))
1308}
1309
1310pub(crate) fn title_text_content(doc: &PostDocument, node: &Node) -> String {
1329 let mut result = String::new();
1330 let mut child = node.get_first_child();
1331 while let Some(c) = child {
1332 result.push_str(&title_node_text(doc, &c));
1333 child = c.get_next_sibling();
1334 }
1335 result
1336}
1337
1338pub(crate) fn title_node_text(doc: &PostDocument, c: &Node) -> String {
1340 match c.get_type() {
1341 Some(NodeType::TextNode) => c.get_content(),
1342 Some(NodeType::ElementNode) if is_indexmark(c) => String::new(),
1345 Some(NodeType::ElementNode) => {
1346 let name = c.get_name();
1347 if name == "tag" {
1348 let mut result = c.get_attribute("open").unwrap_or_default();
1354 result.push_str(&title_text_content(doc, c));
1355 if let Some(close) = c.get_attribute("close") {
1356 result.push_str(&close);
1357 }
1358 result
1359 } else if name == "Math" {
1360 crate::unicode_math::unicodemath(doc, c)
1365 } else {
1366 title_text_content(doc, c)
1367 }
1368 },
1369 _ => String::new(),
1370 }
1371}
1372
1373#[cfg(test)]
1384mod tests {
1385 use super::*;
1386 use crate::document::PostDocumentOptions;
1387
1388 #[test]
1389 fn scan_tracks_page_placeholders_identically_to_xpath() {
1390 let cases = [
1391 (
1392 "plain",
1393 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D1"><section xml:id="S1"><p>Hello</p></section></document>"#,
1394 (false, false),
1395 ),
1396 (
1397 "empty_index",
1398 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D2"><index xml:id="I1"/></document>"#,
1399 (true, false),
1400 ),
1401 (
1402 "filled_index",
1403 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D3"><index xml:id="I2"><indexlist/></index></document>"#,
1404 (false, false),
1405 ),
1406 (
1407 "empty_glossary",
1408 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D4"><glossary xml:id="G1"/></document>"#,
1409 (true, false),
1410 ),
1411 (
1412 "filled_glossary",
1413 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D5"><glossary xml:id="G2"><glossarylist/></glossary></document>"#,
1414 (false, false),
1415 ),
1416 (
1417 "empty_nomenclature",
1418 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D6"><description class="ltx_nomenclature"/></document>"#,
1419 (true, false),
1420 ),
1421 (
1422 "filled_nomenclature",
1423 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D7"><description class="foo ltx_nomenclature"><item/></description></document>"#,
1424 (false, false),
1425 ),
1426 (
1427 "bibliography",
1428 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D8"><bibliography xml:id="B1" files="refs"/></document>"#,
1429 (false, true),
1430 ),
1431 (
1432 "both",
1433 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="D9"><index xml:id="I3"/><bibliography xml:id="B2" files="refs"/></document>"#,
1434 (true, true),
1435 ),
1436 ];
1437 let mut scanner = Scan::new(ObjectDB::new());
1438 for (name, xml, expected) in cases {
1439 let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default()).expect(name);
1440 let nodes = scanner.to_process(&doc);
1441 let out = scanner.process(doc, nodes).expect(name);
1442 let xpath = (
1443 !out[0].findnodes(crate::make_index::PLACEHOLDERS).is_empty(),
1444 !out[0].findnodes("//ltx:bibliography").is_empty(),
1445 );
1446 assert_eq!(scanner.last_page_placeholders(), expected, "case {name}");
1447 assert_eq!(
1448 scanner.last_page_placeholders(),
1449 xpath,
1450 "xpath parity {name}"
1451 );
1452 }
1453 }
1454}