1use std::path::Path;
12
13use latexml_core::common::{
14 xml::{compiled_xpath, name_is},
15 xml_walk::WalkQuery,
16};
17use libxml::{
18 parser::Parser as XmlParser,
19 readonly::RoNode,
20 tree::{Document, Namespace, Node, NodeType},
21 xpath::{Context as XPathContext, Expression, XPathError},
22};
23use rustc_hash::{FxHashMap as HashMap, FxHashSet};
24use unicode_normalization::UnicodeNormalization;
25
26use crate::radix::radix_alpha;
27
28const XML_ERR_NO_MEMORY: i32 = 2;
30
31fn is_libxml_oom(e: &XPathError) -> bool { e.message.is_none() && e.code == XML_ERR_NO_MEMORY }
36
37fn end_on_libxml_oom(xpath: &str, e: &XPathError) {
43 if is_libxml_oom(e) {
44 latexml_core::watchdog::write_stderr_unlocked(format_args!(
45 "Warning:post:xpath libxml2 could not allocate evaluating `{xpath}` (XML_ERR_NO_MEMORY): ending as an \
46 allocation failure\n"
47 ));
48 latexml_core::watchdog::alloc_failed(std::alloc::Layout::new::<u8>());
49 }
50}
51
52const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
53
54pub fn get_xml_id(node: &Node) -> Option<String> {
57 node
58 .get_attribute_ns("id", XML_NS)
59 .or_else(|| node.get_attribute("xml:id"))
60 .or_else(|| {
61 if node.has_property("id") {
64 node.get_properties().get("id").cloned()
65 } else {
66 None
67 }
68 })
69}
70
71fn remap_fragid(id: &str, new_id: &str, fragid: &str) -> String {
79 let offset = id.len().saturating_sub(fragid.len());
80 new_id.get(offset..).unwrap_or(fragid).to_string()
81}
82
83pub const LTX_NSURI: &str = "http://dlmf.nist.gov/LaTeXML";
85
86fn huge_parse_options() -> libxml::parser::ParserOptions<'static> {
90 libxml::parser::ParserOptions {
91 huge: true,
92 ..Default::default()
93 }
94}
95
96fn expand_entity_references(doc: &Document) {
105 let Some(root) = doc.get_root_readonly() else {
106 return;
107 };
108 let mut top = root.get_parent().and_then(|d| d.get_first_child());
109 let (mut has_dtd, mut declares_entities) = (false, false);
110 while let Some(node) = top {
111 if node.get_type() == Some(NodeType::DTDNode) {
112 has_dtd = true;
113 let mut decl = node.get_first_child();
114 while let Some(d) = decl {
115 declares_entities |= d.get_type() == Some(NodeType::EntityDecl);
116 decl = d.get_next_sibling();
117 }
118 }
119 top = node.get_next_sibling();
120 }
121 if !has_dtd {
122 return;
123 }
124 let mut lost = LostEntities::default();
125 let mut stack = vec![root];
126 while let Some(node) = stack.pop() {
127 if declares_entities {
129 expand_attribute_entities(doc, node, &mut lost);
130 }
131 let mut cursor = node.get_first_child();
132 while let Some(child) = cursor {
133 let next = child.get_next_sibling();
134 match child.get_type() {
135 Some(NodeType::EntityRefNode) => {},
136 Some(NodeType::ElementNode) => {
137 stack.push(child);
138 cursor = next;
139 continue;
140 },
141 _ => {
142 cursor = next;
143 continue;
144 },
145 }
146 let content = child
148 .get_first_child()
149 .map(RoNode::get_child_nodes)
150 .unwrap_or_default();
151 if content.is_empty() {
152 lost.note(doc, child);
153 }
154 let mut reference = doc.node_from_readonly(child);
157 let mut first = None;
158 for part in content {
159 if let Ok(mut copy) = doc.copy_node(&doc.node_from_readonly(part))
160 && reference.add_prev_sibling(&mut copy).is_ok()
161 {
162 first.get_or_insert(copy.as_readonly());
163 }
164 }
165 reference.unlink_node();
166 cursor = first.or(next);
167 }
168 }
169 lost.warn();
170}
171
172fn expand_attribute_entities(doc: &Document, element: RoNode, lost: &mut LostEntities) {
175 let mut expanded: Vec<(String, Option<String>, String)> = Vec::new();
176 element.for_each_property_ns(|name, href, value| {
177 let attr = match href {
178 Some(href) => element.get_property_node_ns(name, href),
179 None => element.get_property_node_no_ns(name),
180 };
181 let mut part = attr.and_then(RoNode::get_first_child);
182 let mut has_ref = false;
183 while let Some(node) = part {
184 if node.get_type() == Some(NodeType::EntityRefNode) {
185 has_ref = true;
186 if node
187 .get_first_child()
188 .is_none_or(|decl| decl.get_first_child().is_none())
189 {
190 lost.note(doc, node);
191 }
192 }
193 part = node.get_next_sibling();
194 }
195 if has_ref {
196 expanded.push((name.to_owned(), href.map(str::to_owned), value.to_owned()));
197 }
198 });
199 if expanded.is_empty() {
200 return;
201 }
202 let mut element = doc.node_from_readonly(element);
203 for (name, href, value) in expanded {
204 let _ = match href.and_then(|href| element.get_property_node_ns(&name, &href)) {
205 Some(attr) => match attr.get_namespace() {
206 Some(ns) => element.set_property_ns(&name, &value, &ns),
207 None => element.set_property(&name, &value),
208 },
209 None => element.set_property(&name, &value),
210 };
211 }
212}
213
214#[derive(Default)]
216struct LostEntities {
217 names: std::collections::BTreeMap<String, (usize, bool)>,
219}
220
221impl LostEntities {
222 fn note(&mut self, doc: &Document, reference: RoNode) {
225 let declared = match reference.get_first_child() {
226 None => false,
227 Some(decl) => {
228 let text = doc.ronode_to_string(&decl);
230 let value = text.trim_start_matches("<!ENTITY").trim_start();
231 let value = value
232 .trim_start_matches(|c: char| !c.is_whitespace())
233 .trim_start();
234 if value.starts_with(['"', '\'']) {
235 return;
236 }
237 true
238 },
239 };
240 self
241 .names
242 .entry(reference.get_name())
243 .or_insert((0, declared))
244 .0 += 1;
245 }
246
247 fn warn(self) {
248 for (name, (count, declared)) in self.names {
249 if declared {
250 Warn!(
251 "unexpected",
252 format!("&{name};"),
253 format!(
254 "{count} reference(s) to an external entity: it is not read, so its text is lost"
255 )
256 );
257 } else {
258 Warn!(
259 "unexpected",
260 format!("&{name};"),
261 format!(
262 "{count} reference(s) to an entity the document does not declare: its text is lost"
263 )
264 );
265 }
266 }
267 }
268}
269
270pub(crate) fn is_ltx(node: &Node) -> bool {
275 node
276 .get_namespace()
277 .map(|ns| ns.get_href() == LTX_NSURI)
278 .unwrap_or(false)
279}
280
281fn scan_ids_and_pis(document: &Node, ids: &mut Vec<(String, Node)>, pis: &mut Vec<String>) {
291 let ro = document.as_readonly();
294 let has_dtd = ro
295 .get_child_nodes()
296 .iter()
297 .any(|c| c.get_type() == Some(NodeType::DTDNode));
298 scan_ids_and_pis_from(document, ro, has_dtd, ids, pis);
299}
300
301fn scan_ids_and_pis_from(
302 document: &Node,
303 node: RoNode,
304 has_dtd: bool,
305 ids: &mut Vec<(String, Node)>,
306 pis: &mut Vec<String>,
307) {
308 let mut child = node.get_first_child();
309 while let Some(c) = child {
310 match c.get_type() {
311 Some(NodeType::ElementNode) => {
312 let mut named_id = has_dtd;
314 if !named_id {
315 c.for_each_property(|name, _| named_id |= name == "id" || name == "xml:id");
316 }
317 if named_id {
318 let element = document.node_from_readonly(c);
319 if let Some(id) = get_xml_id(&element) {
320 ids.push((id, element));
321 }
322 }
323 scan_ids_and_pis_from(document, c, has_dtd, ids, pis);
324 },
325 Some(NodeType::PiNode) if c.with_name(|name| name == "latexml") => {
326 pis.push(c.with_content(str::to_owned));
327 },
328 _ => {},
329 }
330 child = c.get_next_sibling();
331 }
332}
333
334pub(crate) struct SplitArm {
337 pub(crate) element: String,
339 pub(crate) any_of: Vec<SplitCond>,
341}
342
343pub(crate) enum SplitCond {
346 PrecedingSibling(String),
348 Parent(String),
350}
351
352pub(crate) fn parse_split_union(union_xpath: &str) -> Option<Vec<SplitArm>> {
358 let mut arms = Vec::new();
359 for raw in union_xpath.split('|') {
360 let arm = raw.trim();
361 let rest = arm.strip_prefix("//ltx:")?;
362 let (name, pred) = match rest.split_once('[') {
363 Some((n, p)) => (n.trim(), Some(p.strip_suffix(']')?.trim())),
364 None => (rest.trim(), None),
365 };
366 if name.is_empty()
367 || !name
368 .chars()
369 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
370 {
371 return None;
372 }
373 let mut any_of = Vec::new();
374 if let Some(pred) = pred {
375 for cond in pred.split(" or ") {
376 let cond = cond.trim();
377 if let Some(n) = cond.strip_prefix("preceding-sibling::ltx:") {
378 any_of.push(SplitCond::PrecedingSibling(n.trim().to_string()));
379 } else {
380 let n = cond.strip_prefix("parent::ltx:")?;
384 any_of.push(SplitCond::Parent(n.trim().to_string()));
385 }
386 }
387 }
388 arms.push(SplitArm {
389 element: name.to_string(),
390 any_of,
391 });
392 }
393 if arms.is_empty() { None } else { Some(arms) }
394}
395
396pub(crate) fn cond_matches(cond: &SplitCond, node: &Node) -> bool {
399 match cond {
400 SplitCond::PrecedingSibling(name) => {
401 let mut sib = node.get_prev_sibling();
402 while let Some(s) = sib {
403 if s.get_type() == Some(NodeType::ElementNode) && s.get_name() == *name && is_ltx(&s) {
404 return true;
405 }
406 sib = s.get_prev_sibling();
407 }
408 false
409 },
410 SplitCond::Parent(name) => node
411 .get_parent()
412 .map(|p| p.get_name() == *name && is_ltx(&p))
413 .unwrap_or(false),
414 }
415}
416
417pub(crate) fn arm_matches(arm: &SplitArm, node: &Node) -> bool {
419 arm.any_of.is_empty() || arm.any_of.iter().any(|c| cond_matches(c, node))
420}
421
422pub(crate) fn collect_split_pages(node: &Node, arms: &[SplitArm], out: &mut Vec<Node>) {
426 let mut child = node.get_first_child();
427 while let Some(c) = child {
428 if c.get_type() == Some(NodeType::ElementNode) {
429 let name = c.get_name();
430 if arms.iter().any(|a| a.element == name)
433 && is_ltx(&c)
434 && arms.iter().any(|a| a.element == name && arm_matches(a, &c))
435 {
436 out.push(c.clone());
437 }
438 collect_split_pages(&c, arms, out);
439 }
440 child = c.get_next_sibling();
441 }
442}
443
444pub struct PostDocument {
449 document: Document,
451 pub destination: Option<String>,
453 pub destination_directory: Option<String>,
455 pub site_directory: Option<String>,
457 pub source: Option<String>,
459 pub source_directory: Option<String>,
461 pub searchpaths: Vec<String>,
463 pub namespaces: HashMap<String, String>,
465 pub namespace_uris: HashMap<String, String>,
467 idcache: HashMap<String, Node>,
469 idcache_reusable: HashMap<String, bool>,
471 idcache_reserve: HashMap<String, bool>,
473 idcache_clashes: HashMap<String, u32>,
475 pub processing_instructions: Vec<String>,
477 pub parent_document: Option<Box<PostDocument>>,
479 pub split_from_id: Option<String>,
481 pub parent_id: Option<String>,
484 pub validate: bool,
486 cache: DocCache,
488 pub nocache: bool,
490 pending_xmath_unlinks: Vec<Node>,
503 nav_memo: Option<NavigationMemo>,
520 compiled_xpath: std::cell::RefCell<HashMap<Box<str>, Expression>>,
524}
525
526struct NavigationMemo {
528 element: Option<Node>,
530 refs: FxHashSet<(String, String)>,
532}
533
534impl Drop for PostDocument {
535 fn drop(&mut self) {
560 for (_, node) in std::mem::take(&mut self.idcache) {
561 node.set_linked();
568 }
569 }
570}
571
572impl PostDocument {
573 pub fn new(doc: Document, options: PostDocumentOptions) -> Self {
577 let mut pd = Self::new_internal(doc, options);
582 pd.set_document_internal();
583 pd
584 }
585
586 pub fn new_transformed(doc: Document, options: PostDocumentOptions) -> Self {
591 let mut pd = Self::new_internal(doc, options);
592 pd.register_root_namespaces();
593 pd
594 }
595
596 fn new_internal(doc: Document, options: PostDocumentOptions) -> Self {
597 let mut dest_dir = options.destination_directory.clone();
598 if options.destination.is_some() && dest_dir.is_none() {
599 if let Some(ref dest) = options.destination {
600 if let Some(parent) = Path::new(dest).parent() {
601 let parent_str = parent.to_string_lossy().to_string();
602 if parent_str.is_empty() {
604 dest_dir = Some(".".to_string());
605 } else {
606 dest_dir = Some(parent_str);
607 }
608 }
609 }
610 }
611
612 let site_dir = if let Some(ref sd) = options.site_directory {
613 Some(sd.clone())
614 } else {
615 dest_dir.clone()
616 };
617
618 let mut namespaces = HashMap::default();
619 namespaces.insert("ltx".to_string(), LTX_NSURI.to_string());
620 let mut namespace_uris = HashMap::default();
621 namespace_uris.insert(LTX_NSURI.to_string(), "ltx".to_string());
622
623 PostDocument {
624 document: doc,
625 destination: options.destination,
626 destination_directory: dest_dir,
627 site_directory: site_dir,
628 source: options.source,
629 source_directory: options.source_directory,
630 searchpaths: options.searchpaths.unwrap_or_default(),
631 namespaces,
632 namespace_uris,
633 idcache: HashMap::default(),
634 idcache_reusable: HashMap::default(),
635 idcache_reserve: HashMap::default(),
636 idcache_clashes: HashMap::default(),
637 processing_instructions: Vec::new(),
638 parent_document: None,
639 split_from_id: None,
640 parent_id: None,
641 validate: options.validate,
642 cache: options
643 .cache
644 .unwrap_or_else(|| DocCache::new(options.nocache)),
645 nocache: options.nocache,
646 pending_xmath_unlinks: Vec::new(),
647 nav_memo: None,
648 compiled_xpath: std::cell::RefCell::default(),
649 }
650 }
651
652 fn register_root_namespaces(&mut self) {
654 if let Some(root) = self.document.get_root_element() {
655 let ns_decls = root.get_namespace_declarations();
656 for ns in ns_decls {
657 let prefix = ns.get_prefix();
658 if !prefix.is_empty() {
659 let href = ns.get_href();
660 self
661 .namespaces
662 .entry(prefix.clone())
663 .or_insert_with(|| href.clone());
664 self.namespace_uris.entry(href).or_insert(prefix);
665 }
666 }
667 }
668 }
669
670 fn set_document_internal(&mut self) {
672 let mut ids: Vec<(String, Node)> = Vec::new();
679 let mut pis: Vec<String> = Vec::new();
680 scan_ids_and_pis(&self.document.as_node(), &mut ids, &mut pis);
681 for (id, node) in ids {
682 self.idcache.insert(id, node);
683 }
684 self.processing_instructions = pis;
685
686 self.register_root_namespaces();
688
689 static SP_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
691 regex::Regex::new(r#"^\s*searchpaths\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap()
692 });
693 let sp_re = &*SP_RE;
694 let mut paths = self.searchpaths.clone();
695 for pi_text in &self.processing_instructions {
696 if let Some(cap) = sp_re.captures(pi_text) {
697 for p in cap[1].split(',') {
698 paths.push(p.trim().to_string());
699 }
700 }
701 }
702 paths.push(".".to_string());
703 self.searchpaths = paths;
704 }
705
706 pub fn new_from_file(path: &str, options: PostDocumentOptions) -> Result<Self, String> {
722 let parser = XmlParser::default();
723 let doc = parser
724 .parse_file_with_options(path, huge_parse_options())
725 .map_err(|e| format!("Failed to parse '{}': {}", path, e))?;
726 expand_entity_references(&doc);
727 Ok(Self::new(doc, Self::file_options(path, options)))
728 }
729
730 pub fn file_options(path: &str, options: PostDocumentOptions) -> PostDocumentOptions {
733 let mut opts = options;
734 if opts.source.is_none() {
735 opts.source = Some(path.to_string());
736 }
737 if opts.source_directory.is_none() {
738 if let Some(parent) = Path::new(path).parent() {
739 opts.source_directory = Some(parent.to_string_lossy().to_string());
740 }
741 }
742 opts
743 }
744
745 pub fn into_document(mut self) -> Document {
748 std::mem::replace(
749 &mut self.document,
750 Document::new().expect("libxml2 could not allocate an empty document"),
751 )
752 }
753
754 pub fn new_from_string(xml: &str, options: PostDocumentOptions) -> Result<Self, String> {
758 let parser = XmlParser::default();
759 let doc = parser
760 .parse_string_with_options(xml, huge_parse_options())
761 .map_err(|e| format!("Failed to parse XML string: {}", e))?;
762 expand_entity_references(&doc);
763 let mut opts = options;
764 if opts.source_directory.is_none() {
765 opts.source_directory = Some(".".to_string());
766 }
767 Ok(Self::new(doc, opts))
768 }
769
770 pub fn new_document(&self, root: Node, destination: &str, parent_id: Option<String>) -> Self {
778 use libxml::tree::Document as XmlDocument;
779 let new_xml_doc: XmlDocument = XmlDocument::dup_node_into_new_doc(&root)
808 .expect("dup_node_into_new_doc returned NULL while creating split sub-document");
809 let _ = root;
810
811 let opts = PostDocumentOptions {
812 destination: Some(destination.to_string()),
813 site_directory: self.site_directory.clone(),
823 source: self.source.clone(),
824 source_directory: self.source_directory.clone(),
825 searchpaths: Some(self.searchpaths.clone()),
826 nocache: self.nocache,
828 cache: Some(self.cache.clone()),
829 ..PostDocumentOptions::default()
830 };
831 let mut subdoc = Self::new_internal(new_xml_doc, opts);
832 subdoc.parent_id = parent_id;
833
834 subdoc.namespaces = self.namespaces.clone();
836 subdoc.namespace_uris = self.namespace_uris.clone();
837
838 for node in subdoc.findnodes("//*[@xml:id]") {
840 if let Some(id) = get_xml_id(&node) {
841 subdoc.idcache.insert(id, node);
842 }
843 }
844
845 if let Some(ref root_el) = self.get_document_element() {
847 if let Some(root_id) = get_xml_id(root_el) {
848 subdoc.split_from_id = Some(root_id);
849 }
850 }
851
852 if let Some(mut root) = subdoc.document.get_root_element() {
859 for pi in self.findnodes("//processing-instruction('latexml')") {
860 if let Ok(mut copy) = subdoc
861 .document
862 .create_processing_instruction(&pi.get_name(), &pi.get_content())
863 {
864 root.add_prev_sibling(&mut copy).ok();
865 }
866 }
867 }
868
869 let resources: Vec<NodeData> = self
874 .findnodes("//ltx:resource")
875 .iter()
876 .map(|r| NodeData::XmlNode(r.clone()))
877 .collect();
878 if !resources.is_empty() {
879 if let Some(mut doc_root) = subdoc.get_document_element() {
880 subdoc.add_nodes(&mut doc_root, &resources);
881 }
882 }
883
884 if let Some(sub_root) = subdoc.get_document_element() {
891 if subdoc.findnodes_at("ltx:date", Some(&sub_root)).is_empty() {
892 if let Some(parent_root) = self.get_document_element() {
893 let dates: Vec<NodeData> = self
894 .findnodes_at("ltx:date", Some(&parent_root))
895 .iter()
896 .map(|d| NodeData::XmlNode(d.clone()))
897 .collect();
898 if !dates.is_empty() {
899 let mut sub_root_mut = sub_root;
900 subdoc.add_nodes(&mut sub_root_mut, &dates);
901 }
902 }
903 }
904 }
905
906 if let Some(parent_root) = self.get_document_element() {
908 if let Some(pclass) = parent_root.get_attribute("class") {
909 if let Some(mut doc_root) = subdoc.get_document_element() {
910 let existing = doc_root.get_attribute("class").unwrap_or_default();
911 if existing.is_empty() {
912 doc_root.set_attribute("class", &pclass).ok();
913 } else {
914 doc_root
915 .set_attribute("class", &format!("{} {}", existing, pclass))
916 .ok();
917 }
918 }
919 }
920 }
921
922 subdoc
923 }
924
925 pub fn get_document(&self) -> &Document { &self.document }
930
931 pub fn get_document_mut(&mut self) -> &mut Document { &mut self.document }
933
934 pub fn get_document_element(&self) -> Option<Node> { self.document.get_root_element() }
936
937 pub fn get_source(&self) -> Option<&str> { self.source.as_deref() }
939
940 pub fn get_source_directory(&self) -> &str { self.source_directory.as_deref().unwrap_or(".") }
942
943 pub fn get_search_paths(&self) -> &[String] { &self.searchpaths }
945
946 pub fn get_destination(&self) -> Option<&str> { self.destination.as_deref() }
948
949 pub fn get_destination_directory(&self) -> Option<&str> { self.destination_directory.as_deref() }
951
952 pub fn get_site_directory(&self) -> Option<&str> { self.site_directory.as_deref() }
954
955 pub fn site_relative_destination(&self) -> Option<String> {
959 if let (Some(dest), Some(site)) = (&self.destination, &self.site_directory) {
960 Some(pathdiff(dest, site))
961 } else {
962 self.destination.clone()
963 }
964 }
965
966 pub fn site_relative_pathname(&self, pathname: &str) -> Option<String> {
968 self
969 .site_directory
970 .as_ref()
971 .map(|site| pathdiff(pathname, site))
972 }
973
974 pub fn get_destination_extension(&self) -> Option<String> {
976 self.destination.as_ref().and_then(|d| {
977 Path::new(d)
978 .extension()
979 .map(|e| e.to_string_lossy().to_string())
980 })
981 }
982
983 pub fn to_xml_string(&self) -> String { self.document.to_string() }
985
986 pub fn node_to_string(&self, node: &Node) -> String { self.document.node_to_string(node) }
990
991 pub fn processing_instructions(&self) -> &[String] { &self.processing_instructions }
996
997 pub fn stringify(&self) -> String {
998 format!(
999 "Post::Document[{}]",
1000 self
1001 .site_relative_destination()
1002 .unwrap_or_else(|| "?".to_string())
1003 )
1004 }
1005
1006 pub fn findnodes(&self, xpath: &str) -> Vec<Node> { self.findnodes_at(xpath, None) }
1013
1014 pub fn findnodes_at(&self, xpath: &str, context_node: Option<&Node>) -> Vec<Node> {
1016 if let Some(query) = WalkQuery::parse(xpath)
1034 && let Some(found) = query.find(&self.document, context_node)
1035 {
1036 return found;
1037 }
1038 let ctx = match context_node {
1039 Some(node) => XPathContext::from_node(node),
1040 None => XPathContext::new(&self.document),
1041 };
1042 let ctx = match ctx {
1043 Ok(c) => c,
1044 Err(_) => return vec![],
1045 };
1046
1047 for (prefix, uri) in &self.namespaces {
1049 let _ = ctx.register_namespace(prefix, uri);
1050 }
1051
1052 let result = {
1060 let mut compiled = self.compiled_xpath.borrow_mut();
1061 let expression = compiled_xpath(&mut compiled, xpath);
1062 let at_node = |node: &Node| match expression {
1063 Some(expression) => ctx.node_evaluate_compiled(expression, node),
1064 None => ctx.node_evaluate_checked(xpath, node),
1065 };
1066 if let Some(node) = context_node {
1067 at_node(node)
1068 } else {
1069 match self.document.get_root_element() {
1084 Some(root) => at_node(&root),
1085 None => match expression {
1086 Some(expression) => ctx.evaluate_compiled(expression),
1087 None => ctx.evaluate_checked(xpath),
1088 },
1089 }
1090 }
1091 };
1092
1093 match result {
1094 Ok(obj) => obj.get_nodes_as_vec(),
1095 Err(e) => {
1096 end_on_libxml_oom(xpath, &e);
1097 Error!(
1103 "post",
1104 "xpath",
1105 "XPath evaluation failed for `{}`: {} — results are INCOMPLETE for this pass",
1106 xpath,
1107 e
1108 );
1109 vec![]
1110 },
1111 }
1112 }
1113
1114 pub fn find_split_pages(&self, union_xpath: &str) -> Vec<Node> {
1128 let arms = match parse_split_union(union_xpath) {
1129 Some(a) => a,
1130 None => return self.findnodes(union_xpath),
1131 };
1132 let mut pages = Vec::new();
1133 collect_split_pages(&self.document.as_node(), &arms, &mut pages);
1134 pages
1135 }
1136
1137 pub fn findnode(&self, xpath: &str) -> Option<Node> {
1139 if let Some(first) = WalkQuery::parse(xpath).and_then(|q| q.find_first(&self.document, None)) {
1140 return first;
1141 }
1142 self.findnodes(xpath).into_iter().next()
1143 }
1144
1145 pub fn findnode_at(&self, xpath: &str, context_node: &Node) -> Option<Node> {
1147 if let Some(first) =
1148 WalkQuery::parse(xpath).and_then(|q| q.find_first(&self.document, Some(context_node)))
1149 {
1150 return first;
1151 }
1152 self
1153 .findnodes_at(xpath, Some(context_node))
1154 .into_iter()
1155 .next()
1156 }
1157
1158 pub fn findvalue(&self, xpath: &str) -> Option<String> {
1160 let ctx = XPathContext::new(&self.document).ok()?;
1161 for (prefix, uri) in &self.namespaces {
1162 let _ = ctx.register_namespace(prefix, uri);
1163 }
1164 let mut compiled = self.compiled_xpath.borrow_mut();
1165 match compiled_xpath(&mut compiled, xpath) {
1166 Some(expression) => ctx.evaluate_compiled(expression).ok(),
1167 None => ctx.evaluate(xpath).ok(),
1168 }
1169 .map(|obj| obj.to_string())
1170 }
1171
1172 pub fn findnodes_foreign(xpath: &str, node: &Node) -> Vec<Node> {
1181 let ctx = match XPathContext::from_node(node) {
1182 Ok(c) => c,
1183 Err(_) => return vec![],
1184 };
1185 let _ = ctx.register_namespace("ltx", LTX_NSURI);
1186 match ctx.node_evaluate_checked(xpath, node) {
1187 Ok(obj) => obj.get_nodes_as_vec(),
1188 Err(e) => {
1189 end_on_libxml_oom(xpath, &e);
1190 Error!(
1191 "post",
1192 "xpath",
1193 "XPath evaluation failed for `{}`: {} — results are INCOMPLETE for this pass",
1194 xpath,
1195 e
1196 );
1197 vec![]
1198 },
1199 }
1200 }
1201
1202 pub fn add_namespace(&mut self, prefix: &str, nsuri: &str) {
1209 let dominated = self
1210 .namespaces
1211 .get(prefix)
1212 .map(|u| u == nsuri)
1213 .unwrap_or(false);
1214 if !dominated {
1215 self
1216 .namespaces
1217 .insert(prefix.to_string(), nsuri.to_string());
1218 self
1219 .namespace_uris
1220 .insert(nsuri.to_string(), prefix.to_string());
1221 if let Some(mut root) = self.document.get_root_element() {
1225 let _ = Namespace::new(prefix, nsuri, &mut root);
1226 }
1227 }
1228 }
1229
1230 pub fn get_qname(&self, node: &Node) -> Option<String> {
1234 if node.get_type() != Some(NodeType::ElementNode) {
1235 return None;
1236 }
1237 let node = node.as_readonly();
1238 node.with_name(|localname| {
1239 node.with_namespace_href(|href| match href {
1240 Some(nsuri) => {
1241 if let Some(prefix) = self.namespace_uris.get(nsuri) {
1242 Some(format!("{}:{}", prefix, localname))
1243 } else {
1244 let n = self
1246 .namespaces
1247 .keys()
1248 .filter(|k| k.starts_with("_ns"))
1249 .count()
1250 + 1;
1251 Some(format!("_ns{}:{}", n, localname))
1252 }
1253 },
1254 None => Some(localname.to_owned()),
1255 })
1256 })
1257 }
1258
1259 pub fn qname_prefix(&self, node: &Node) -> Option<String> {
1265 if node.get_type() != Some(NodeType::ElementNode) {
1266 return None;
1267 }
1268 node
1269 .as_readonly()
1270 .with_namespace_href(|href| href.and_then(|nsuri| self.namespace_uris.get(nsuri).cloned()))
1271 }
1272
1273 pub fn is_qname(&self, node: &Node, expected: &str) -> bool {
1280 if node.get_type() != Some(NodeType::ElementNode) {
1281 return false;
1282 }
1283 let (expected_prefix, expected_local) = match expected.split_once(':') {
1284 Some((p, l)) => (Some(p), l),
1285 None => (None, expected),
1286 };
1287 let node = node.as_readonly();
1288 if !node.with_name(|localname| localname == expected_local) {
1289 return false;
1290 }
1291 node.with_namespace_href(|href| match (href, expected_prefix) {
1292 (Some(nsuri), Some(ep)) => self
1293 .namespace_uris
1294 .get(nsuri)
1295 .map(|p| p == ep)
1296 .unwrap_or(false),
1297 (None, None) => true,
1298 _ => false,
1299 })
1300 }
1301
1302 pub fn record_id(&mut self, id: &str, node: Node) {
1309 self.idcache.insert(id.to_string(), node);
1310 self.idcache_reserve.remove(id);
1311 self.idcache_reusable.remove(id);
1312 }
1313
1314 pub fn release_id(&mut self, node: &mut Node) -> Option<String> {
1317 let id = get_xml_id(node)?;
1318 self.idcache.remove(&id);
1319 let _ = node.remove_attribute_ns("id", "http://www.w3.org/XML/1998/namespace");
1320 Some(id)
1321 }
1322
1323 pub fn find_node_by_id(&self, id: &str) -> Option<&Node> { self.idcache.get(id) }
1327
1328 pub fn idcache_len(&self) -> usize { self.idcache.len() }
1331
1332 pub fn idcache_iter(&self) -> impl Iterator<Item = (&String, &Node)> { self.idcache.iter() }
1336
1337 pub fn uniquify_id(&mut self, baseid: &str, suffix: Option<&str>) -> String {
1344 let apply_suffix = |id: &str, sfx: Option<&str>| -> String {
1345 if let Some(s) = sfx {
1346 format!("{}{}", id, s)
1347 } else {
1348 id.to_string()
1349 }
1350 };
1351
1352 let mut id = apply_suffix(baseid, suffix);
1353 let cachekey = id.clone();
1354
1355 while (self.idcache.contains_key(&id) || self.idcache_reserve.contains_key(&id))
1356 && !self.idcache_reusable.contains_key(&id)
1357 {
1358 let clash_count = self.idcache_clashes.entry(cachekey.clone()).or_insert(0);
1359 *clash_count += 1;
1360 id = apply_suffix(&format!("{}{}", baseid, radix_alpha(*clash_count)), suffix);
1361 }
1362
1363 self.idcache_reusable.remove(&id);
1364 self.idcache_reserve.insert(id.clone(), true);
1365 id
1366 }
1367
1368 pub fn generate_node_id(
1374 &mut self,
1375 node: &mut Node,
1376 prefix: &str,
1377 reusable: bool,
1378 ) -> Option<String> {
1379 if let Some(id) = get_xml_id(node) {
1380 return Some(id);
1381 }
1382
1383 let mut parent_node = node.get_parent();
1387 let mut pid = String::new();
1388 while let Some(ref p) = parent_node {
1389 if let Some(id) = get_xml_id(p) {
1390 pid = id;
1391 break;
1392 }
1393 parent_node = p.get_parent();
1394 }
1395
1396 if !pid.is_empty() {
1397 pid.push('.');
1398 }
1399
1400 let mut n = 1u32;
1402 let id = loop {
1403 let candidate = format!("{}{}{}", pid, prefix, n);
1404 if !self.idcache.contains_key(&candidate) && !self.idcache_reserve.contains_key(&candidate) {
1405 break candidate;
1406 }
1407 n += 1;
1408 };
1409
1410 node.set_attribute("xml:id", &id).ok();
1411 let node_copy = node.clone();
1412 self.idcache.insert(id.clone(), node_copy);
1413 if reusable {
1414 self.idcache_reusable.insert(id.clone(), true);
1415 }
1416
1417 if let Some(ref p) = parent_node {
1419 if p.has_attribute("fragid") {
1420 let new_fragid = format!("{}.{}{}", p.get_attribute("fragid").unwrap(), prefix, n);
1421 node.set_attribute("fragid", &new_fragid).ok();
1422 }
1423 }
1424
1425 Some(id)
1426 }
1427
1428 pub fn add_nodes(&mut self, parent: &mut Node, data: &[NodeData]) {
1435 for child in data {
1436 match child {
1437 NodeData::Text(text) => {
1438 parent.append_text(text).ok();
1439 },
1440 NodeData::Element { tag, attributes, children } => {
1441 debug_assert!(
1450 !((tag == "m:mi" || tag == "mi") && children.is_empty()),
1451 "Empty <mi></mi> detected at materialization — use <mrow></mrow> \
1452 scaffolding instead; see task #264 in docs/SYNC_STATUS.md"
1453 );
1454 if tag == "_Fragment_" {
1455 self.add_nodes(parent, children);
1456 } else if let Some((prefix, localname)) = tag.split_once(':') {
1457 let nsuri = self.namespaces.get(prefix).cloned();
1458 if nsuri.is_none() {
1459 Warn!("malformed", "namespace", "No namespace on '{}'", tag);
1460 }
1461 let ns = nsuri.and_then(|uri| {
1465 parent
1467 .get_namespace_declarations()
1468 .into_iter()
1469 .find(|ns| ns.get_prefix().is_empty() && ns.get_href() == uri)
1470 .or_else(|| {
1471 parent
1472 .get_namespaces(&self.document)
1473 .into_iter()
1474 .find(|ns| ns.get_prefix().is_empty() && ns.get_href() == uri)
1475 })
1476 .or_else(|| {
1478 parent
1479 .get_namespace_declarations()
1480 .into_iter()
1481 .find(|ns| ns.get_prefix() == prefix)
1482 })
1483 .or_else(|| {
1484 parent
1485 .get_namespaces(&self.document)
1486 .into_iter()
1487 .find(|ns| ns.get_prefix() == prefix)
1488 })
1489 .or_else(|| {
1490 Namespace::new(prefix, &uri, parent).ok()
1492 })
1493 });
1494 if let Ok(mut new_node) = parent.new_child(ns, localname) {
1495 if let Some(attrs) = attributes {
1497 let mut sorted_keys: Vec<_> = attrs.keys().collect();
1498 sorted_keys.sort();
1499 for key in sorted_keys {
1500 let value = &attrs[key];
1501 if key.starts_with('_') {
1502 continue;
1503 }
1504 if key == "xml:id" {
1505 let id = if self.idcache.contains_key(value.as_str()) {
1506 self.uniquify_id(value, None)
1507 } else {
1508 value.clone()
1509 };
1510 self.record_id(&id, new_node.clone());
1511 new_node.set_attribute("xml:id", &id).ok();
1512 } else {
1513 new_node.set_attribute(key, value).ok();
1514 }
1515 }
1516 }
1517 self.add_nodes(&mut new_node, children);
1518 }
1519 } else {
1520 Warn!(
1521 "malformed",
1522 "namespace",
1523 "Tag '{}' has no namespace prefix",
1524 tag
1525 );
1526 }
1527 },
1528 NodeData::XmlNode(source_node) => {
1529 self.append_clone(parent, source_node);
1530 },
1531 }
1532 }
1533 }
1534
1535 fn append_clone(&mut self, parent: &mut Node, source: &Node) {
1549 let mut idmap: HashMap<String, String> = HashMap::default();
1550 let Some(root) = self.clone_subtree(parent, source, &mut idmap) else {
1551 return;
1552 };
1553 if !idmap.is_empty() {
1554 for mut n in self.findnodes_at("descendant-or-self::*[@idref]", Some(&root)) {
1555 if let Some(idref) = n.get_attribute("idref") {
1556 if let Some(newid) = idmap.get(&idref) {
1557 n.set_attribute("idref", newid).ok();
1558 }
1559 }
1560 }
1561 }
1562 for mut n in self.findnodes_at("descendant-or-self::*[@labels]", Some(&root)) {
1563 let _ = n.remove_attribute("labels");
1564 }
1565 }
1566
1567 fn clone_subtree(
1574 &mut self,
1575 parent: &mut Node,
1576 source: &Node,
1577 idmap: &mut HashMap<String, String>,
1578 ) -> Option<Node> {
1579 match source.get_type() {
1580 Some(NodeType::ElementNode) => {
1581 let localname = source.get_name();
1582 let ns = source.get_namespace().and_then(|src_ns| {
1591 let uri = src_ns.get_href();
1592 let prefix = src_ns.get_prefix();
1593 parent
1594 .get_namespace_declarations()
1595 .into_iter()
1596 .find(|n| n.get_prefix().is_empty() && n.get_href() == uri)
1597 .or_else(|| {
1598 parent
1599 .get_namespaces(&self.document)
1600 .into_iter()
1601 .find(|n| n.get_prefix().is_empty() && n.get_href() == uri)
1602 })
1603 .or_else(|| {
1604 parent
1605 .get_namespace_declarations()
1606 .into_iter()
1607 .find(|n| n.get_prefix() == prefix)
1608 })
1609 .or_else(|| {
1610 parent
1611 .get_namespaces(&self.document)
1612 .into_iter()
1613 .find(|n| n.get_prefix() == prefix)
1614 })
1615 .or_else(|| Namespace::new(&prefix, &uri, parent).ok())
1616 });
1617 let mut new_node = parent.new_child(ns, &localname).ok()?;
1618
1619 let src_xmlid = get_xml_id(source);
1623 let src_fragid = source.get_attribute("fragid");
1624 let new_xmlid = src_xmlid.as_ref().map(|id| {
1625 let newid = if self.idcache.contains_key(id.as_str()) {
1626 self.uniquify_id(id, None)
1627 } else {
1628 id.clone()
1629 };
1630 idmap.insert(id.clone(), newid.clone());
1631 self.record_id(&newid, new_node.clone());
1632 newid
1633 });
1634 let new_fragid = match (&src_xmlid, &new_xmlid, &src_fragid) {
1636 (Some(id), Some(newid), Some(fragid)) => Some(remap_fragid(id, newid, fragid)),
1637 _ => src_fragid.clone(),
1638 };
1639
1640 let mut props: Vec<(String, String)> = source.get_properties().into_iter().collect();
1649 props.sort();
1650 for (key, value) in &props {
1651 if key.starts_with('_') || key == "fragid" {
1652 continue;
1653 }
1654 let is_xmlid = key == "xml:id" || (key == "id" && src_xmlid.as_deref() == Some(value));
1655 if is_xmlid {
1656 continue;
1657 }
1658 if source
1661 .get_attribute_ns(key, latexml_core::common::xml::XML_NS)
1662 .is_some()
1663 {
1664 new_node.set_attribute(&format!("xml:{key}"), value).ok();
1665 continue;
1666 }
1667 new_node.set_attribute(key, value).ok();
1668 }
1669 if let Some(newid) = &new_xmlid {
1670 new_node.set_attribute("xml:id", newid).ok();
1671 }
1672 if let Some(fragid) = &new_fragid {
1673 new_node.set_attribute("fragid", fragid).ok();
1674 }
1675
1676 let mut child = source.get_first_child();
1678 while let Some(c) = child {
1679 self.clone_subtree(&mut new_node, &c, idmap);
1680 child = c.get_next_sibling();
1681 }
1682 Some(new_node)
1683 },
1684 Some(NodeType::TextNode) => {
1685 parent.append_text(&source.get_content()).ok();
1686 None
1687 },
1688 Some(NodeType::DocumentFragNode) => {
1689 let mut child = source.get_first_child();
1690 while let Some(c) = child {
1691 self.clone_subtree(parent, &c, idmap);
1692 child = c.get_next_sibling();
1693 }
1694 None
1695 },
1696 _ => None,
1697 }
1698 }
1699
1700 pub fn remove_nodes(&mut self, nodes: &[Node]) {
1704 fn collect_ids_of_subtree(node: &Node, out: &mut Vec<String>) {
1705 if node.get_type() != Some(NodeType::ElementNode) {
1706 return;
1707 }
1708 if let Some(id) = get_xml_id(node) {
1709 out.push(id);
1710 }
1711 let mut child = node.get_first_child();
1712 while let Some(c) = child {
1713 collect_ids_of_subtree(&c, out);
1714 child = c.get_next_sibling();
1715 }
1716 }
1717
1718 for node in nodes {
1719 if node.get_type() == Some(NodeType::ElementNode) {
1720 let mut ids = Vec::new();
1722 collect_ids_of_subtree(node, &mut ids);
1723 for id in ids {
1724 self.idcache.remove(&id);
1725 }
1726 }
1727 let mut n = node.clone();
1728 n.unlink_node();
1729 }
1730 }
1731
1732 pub fn discard_subtree(&mut self, node: Node) {
1743 use latexml_core::common::xml::is_descendant_or_self;
1744 if let Some(memo) = self.nav_memo.as_mut()
1745 && memo
1746 .element
1747 .as_ref()
1748 .is_some_and(|nav| is_descendant_or_self(nav, &node))
1749 {
1750 memo.element = None;
1751 }
1752 self
1753 .pending_xmath_unlinks
1754 .retain(|xmath| !is_descendant_or_self(xmath, &node));
1755 node.free_subtree();
1756 }
1757
1758 pub fn preremove_nodes(&mut self, nodes: &[Node]) {
1762 for node in nodes {
1763 if node.get_type() == Some(NodeType::ElementNode) {
1764 for idd in self.findnodes_at("descendant-or-self::*[@xml:id]", Some(node)) {
1765 if let Some(id) = get_xml_id(&idd) {
1768 self.idcache_reusable.insert(id, true);
1769 }
1770 }
1771 }
1772 }
1773 }
1774
1775 pub fn defer_xmath_unlink(&mut self, node: Node) { self.pending_xmath_unlinks.push(node); }
1788
1789 pub fn drain_pending_xmath_unlinks(&mut self) {
1798 let pending = std::mem::take(&mut self.pending_xmath_unlinks);
1799 for node in pending {
1800 node.free_subtree();
1808 }
1809 }
1810
1811 pub fn remove_blank_nodes(&self, node: &Node) -> u32 {
1815 let mut count = 0;
1816 if let Some(child) = node.get_first_child() {
1817 let mut current = Some(child);
1818 while let Some(ref mut c) = current {
1819 let next = c.get_next_sibling();
1820 if c.get_type() == Some(NodeType::TextNode) {
1821 let text = c.get_content();
1822 if text.trim().is_empty() {
1823 c.unlink_node();
1824 count += 1;
1825 }
1826 }
1827 current = next;
1828 }
1829 }
1830 count
1831 }
1832
1833 pub fn replace_node(&mut self, old_node: &Node, replacements: &[NodeData]) {
1837 if let Some(mut parent) = old_node.get_parent() {
1838 let mut save = Vec::new();
1840 while let Some(mut last) = parent.get_last_child() {
1841 if last == *old_node {
1842 break;
1843 }
1844 last.unlink_node();
1845 save.insert(0, last);
1846 }
1847
1848 self.remove_nodes(&[old_node.clone()]);
1850
1851 self.add_nodes(&mut parent, replacements);
1853
1854 for mut s in save {
1856 parent.add_child(&mut s).ok();
1857 }
1858 }
1859 }
1860
1861 pub fn unwrap_node(&mut self, node: &Node) {
1866 let mut wrapper = node.clone();
1867 for mut child in wrapper.get_child_nodes() {
1868 child.unlink_node();
1869 wrapper.add_prev_sibling(&mut child).ok();
1870 }
1871 self.remove_nodes(&[wrapper]);
1872 }
1873
1874 pub fn prepend_nodes(&mut self, parent: &mut Node, nodes: &[NodeData]) {
1878 let mut save = Vec::new();
1880 while let Some(mut last) = parent.get_last_child() {
1881 last.unlink_node();
1882 save.insert(0, last);
1883 }
1884
1885 self.add_nodes(parent, nodes);
1887
1888 for mut s in save {
1890 parent.add_child(&mut s).ok();
1891 }
1892 }
1893
1894 pub fn add_ss_values(node: &mut Node, key: &str, values: &str) {
1906 if values.is_empty() {
1907 return;
1908 }
1909 let new_values: Vec<&str> = values.split_whitespace().collect();
1910 if let Some(old_values_str) = node.get_attribute(key) {
1911 let mut all: Vec<String> = old_values_str
1912 .split_whitespace()
1913 .map(String::from)
1914 .collect();
1915 for v in &new_values {
1916 if !all.iter().any(|o| o == v) {
1917 all.push(v.to_string());
1918 }
1919 }
1920 all.sort();
1921 node.set_attribute(key, &all.join(" ")).ok();
1922 } else {
1923 let mut sorted: Vec<&str> = new_values;
1924 sorted.sort_unstable();
1925 node.set_attribute(key, &sorted.join(" ")).ok();
1926 }
1927 }
1928
1929 pub fn add_class(node: &mut Node, class: &str) { Self::add_ss_values(node, "class", class); }
1933
1934 pub fn mark_xm_node_visibility(&self) {
1941 for mut math_child in self.findnodes("//ltx:XMath/*") {
1942 self.mark_xm_node_visibility_aux(&mut math_child, true, true);
1943 }
1944 }
1945
1946 fn mark_xm_node_visibility_aux(&self, node: &mut Node, cvis: bool, pvis: bool) {
1947 let qname = match self.get_qname(node) {
1948 Some(q) => q,
1949 None => return,
1950 };
1951
1952 let has_cvis = node.has_attribute("_cvis");
1953 let has_pvis = node.has_attribute("_pvis");
1954 if (!cvis || has_cvis) && (!pvis || has_pvis) {
1955 return;
1956 }
1957
1958 if cvis {
1959 node.set_attribute("_cvis", "1").ok();
1960 }
1961 if pvis {
1962 node.set_attribute("_pvis", "1").ok();
1963 }
1964
1965 if qname == "ltx:XMDual" {
1966 let mut children = element_children(node);
1967 if children.len() >= 2 {
1968 if cvis {
1969 self.mark_xm_node_visibility_aux(&mut children[0], true, false);
1970 }
1971 if pvis {
1972 self.mark_xm_node_visibility_aux(&mut children[1], false, true);
1973 }
1974 }
1975 } else if qname == "ltx:XMRef" {
1976 if let Some(idref) = node.get_attribute("idref") {
1977 if let Some(target) = self.find_node_by_id(&idref) {
1978 let mut target_mut = target.clone();
1979 self.mark_xm_node_visibility_aux(&mut target_mut, cvis, pvis);
1980 } else {
1981 Error!(
1984 "expected",
1985 "id",
1986 "Cannot find a node with xml:id='{}'",
1987 idref
1988 );
1989 }
1990 }
1991 } else {
1992 for mut child in element_children(node) {
1993 self.mark_xm_node_visibility_aux(&mut child, cvis, pvis);
1994 }
1995 }
1996 }
1997
1998 pub fn realize_xm_node_branch(&self, node: &Node, branch: XMBranch) -> Option<Node> {
2007 let mut node = node.clone();
2008 loop {
2009 if self.is_qname(&node, "ltx:XMRef") {
2010 let idref = node.get_attribute("idref")?;
2011 match self.find_node_by_id(&idref) {
2012 Some(target) => node = target.clone(),
2013 None => {
2014 Error!(
2015 "expected",
2016 "id",
2017 "Cannot find a node with xml:id='{}'",
2018 idref
2019 );
2020 return None;
2021 },
2022 }
2023 } else if self.is_qname(&node, "ltx:XMDual") {
2024 let children = element_children(&node);
2028 node = children.get(branch as usize)?.clone();
2029 } else {
2030 return Some(node);
2031 }
2032 }
2033 }
2034
2035 pub fn realize_xm_node(&self, node: &Node) -> Option<Node> {
2041 if self.is_qname(node, "ltx:XMRef") {
2042 let idref = node.get_attribute("idref")?;
2043 let realized = self.find_node_by_id(&idref).cloned();
2044 if realized.is_none() {
2045 Error!(
2048 "expected",
2049 "id",
2050 "Cannot find a node with xml:id='{}'",
2051 idref
2052 );
2053 }
2054 realized
2055 } else {
2056 Some(node.clone())
2057 }
2058 }
2059
2060 pub fn conjoin(conjunction: Conjunction, nodes: Vec<NodeData>) -> Vec<NodeData> {
2067 let n = nodes.len();
2068 if n < 2 {
2069 return nodes;
2070 }
2071
2072 let (comma, and) = match conjunction {
2073 Conjunction::Simple(s) => (s.clone(), s),
2074 Conjunction::Pair(c, a) => (c, a),
2075 };
2076
2077 let mut result = Vec::new();
2078 let mut iter = nodes.into_iter();
2079 result.push(iter.next().unwrap());
2080
2081 let mut remaining: Vec<_> = iter.collect();
2082 while remaining.len() > 1 {
2083 result.push(NodeData::Text(comma.clone()));
2084 result.push(remaining.remove(0));
2085 }
2086 result.push(NodeData::Text(and));
2087 result.push(remaining.remove(0));
2088 result
2089 }
2090
2091 pub fn initial(string: &str, force: bool) -> String {
2095 let decomposed: String = string.nfd().collect();
2096 let trimmed = decomposed.trim_start();
2097 let s = if force {
2098 trimmed.trim_start_matches(|c: char| !c.is_ascii_alphabetic())
2099 } else {
2100 trimmed
2101 };
2102 match s.chars().next() {
2103 Some(c) if c.is_ascii_alphabetic() => c.to_uppercase().to_string(),
2104 _ => "*".to_string(),
2105 }
2106 }
2107
2108 pub fn trim_child_nodes(node: &Node) -> Vec<Node> {
2112 let mut children: Vec<Node> = Vec::new();
2113 if let Some(child) = node.get_first_child() {
2114 let mut current = Some(child);
2115 while let Some(ref c) = current {
2116 children.push(c.clone());
2117 current = c.get_next_sibling();
2118 }
2119 }
2120
2121 if children.is_empty() {
2122 return children;
2123 }
2124
2125 if let Some(first) = children.first_mut() {
2127 if first.get_type() == Some(NodeType::TextNode) {
2128 let text = first.get_content();
2129 let trimmed = text.trim_start();
2130 if trimmed.is_empty() {
2131 children.remove(0);
2132 } else if trimmed != text {
2133 first.set_content(trimmed).ok();
2134 }
2135 }
2136 }
2137
2138 if let Some(last) = children.last_mut() {
2140 if last.get_type() == Some(NodeType::TextNode) {
2141 let text = last.get_content();
2142 let trimmed = text.trim_end();
2143 if trimmed.is_empty() {
2144 children.pop();
2145 } else if trimmed != text {
2146 last.set_content(trimmed).ok();
2147 }
2148 }
2149 }
2150
2151 children
2152 }
2153
2154 pub fn add_navigation(&mut self, relation: &str, id: &str) {
2158 if self.navigation_ref_present(relation, id) {
2164 return;
2165 }
2166
2167 let ref_node = NodeData::Element {
2168 tag: "ltx:ref".to_string(),
2169 attributes: Some(HashMap::from_iter([
2170 ("idref".to_string(), id.to_string()),
2171 ("rel".to_string(), relation.to_string()),
2172 ("show".to_string(), "toctitle".to_string()),
2173 ])),
2174 children: vec![],
2175 };
2176
2177 match self.navigation_element() {
2178 Some(mut nav) => {
2179 self.add_nodes(&mut nav, &[ref_node]);
2180 self.record_navigation_ref(relation, id);
2181 },
2182 _ => {
2183 if let Some(mut root) = self.get_document_element() {
2184 let nav_node = NodeData::Element {
2185 tag: "ltx:navigation".to_string(),
2186 attributes: None,
2187 children: vec![ref_node],
2188 };
2189 self.add_nodes(&mut root, &[nav_node]);
2190 let found = self.findnode("//ltx:navigation");
2193 if let Some(memo) = self.nav_memo.as_mut() {
2194 memo.element = found;
2195 }
2196 self.record_navigation_ref(relation, id);
2197 }
2198 },
2202 }
2203 }
2204
2205 fn navigation_element(&mut self) -> Option<Node> {
2213 if let Some(memo) = self.nav_memo.as_ref()
2214 && let Some(nav) = memo.element.as_ref()
2215 && nav.get_parent().is_some()
2216 {
2217 return Some(nav.clone());
2218 }
2219 let found = self.findnode("//ltx:navigation");
2220 if let Some(memo) = self.nav_memo.as_mut() {
2221 memo.element = found.clone();
2222 }
2223 found
2224 }
2225
2226 fn seed_navigation_memo(&mut self) {
2240 if self.nav_memo.is_some() {
2241 return;
2242 }
2243 let mut refs = FxHashSet::default();
2244 let elements = self.findnodes("//ltx:navigation");
2245 for nav in &elements {
2246 for child in nav.get_child_nodes() {
2247 if !name_is(&child, "ref") {
2248 continue;
2249 }
2250 let in_ltx = child
2253 .get_namespace()
2254 .is_some_and(|ns| ns.get_href() == LTX_NSURI);
2255 if !in_ltx {
2256 continue;
2257 }
2258 if let (Some(rel), Some(idref)) = (child.get_attribute("rel"), child.get_attribute("idref"))
2259 {
2260 refs.insert((rel, idref));
2261 }
2262 }
2263 }
2264 self.nav_memo = Some(NavigationMemo {
2265 element: elements.into_iter().next(),
2266 refs,
2267 });
2268 }
2269
2270 fn navigation_ref_present(&mut self, relation: &str, id: &str) -> bool {
2271 self.seed_navigation_memo();
2272 self
2273 .nav_memo
2274 .as_ref()
2275 .is_some_and(|memo| memo.refs.contains(&(relation.to_string(), id.to_string())))
2276 }
2277
2278 fn record_navigation_ref(&mut self, relation: &str, id: &str) {
2280 if let Some(memo) = self.nav_memo.as_mut() {
2281 memo.refs.insert((relation.to_string(), id.to_string()));
2282 }
2283 }
2284
2285 pub fn validate(&self) -> Result<(), String> {
2292 static RNG_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
2293 regex::Regex::new(r#"^\s*RelaxNGSchema\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap()
2294 });
2295 let rng_re = &*RNG_RE;
2296 for pi_text in &self.processing_instructions {
2297 if let Some(cap) = rng_re.captures(pi_text) {
2298 let schema = &cap[1];
2299 Info!(
2300 "validate",
2301 "schema",
2302 "Would validate against RelaxNG schema: {}",
2303 schema
2304 );
2305 return Ok(());
2306 }
2307 }
2308 Warn!(
2313 "missing_file",
2314 "schema",
2315 "No schema found for document validation"
2316 );
2317 Ok(())
2318 }
2319
2320 pub fn idcheck(&self) {
2324 let mut doc_ids: HashMap<String, bool> = HashMap::default();
2325 let mut dups = Vec::new();
2326
2327 for node in self.findnodes("//*[@xml:id]") {
2328 if let Some(id) = get_xml_id(&node) {
2329 if doc_ids.contains_key(&id) {
2330 dups.push(id.clone());
2331 }
2332 doc_ids.insert(id, true);
2333 }
2334 }
2335
2336 let mut missing = Vec::new();
2339 for id in self.idcache.keys() {
2340 if !doc_ids.contains_key(id) {
2341 missing.push(id.clone());
2342 }
2343 }
2344 missing.sort_unstable();
2345
2346 if !dups.is_empty() {
2347 Warn!(
2348 "malformed",
2349 "id",
2350 "Duplicate IDs for {}: {}",
2351 self.site_relative_destination().unwrap_or_default(),
2352 dups.join(", ")
2353 );
2354 }
2355 if !missing.is_empty() {
2356 Warn!(
2357 "expected",
2358 "id",
2359 "Cached IDs not in document for {}: {}",
2360 self.site_relative_destination().unwrap_or_default(),
2361 missing.join(", ")
2362 );
2363 }
2364 }
2365
2366 pub fn cache_lookup(&self, key: &str) -> Option<String> {
2371 self
2372 .cache
2373 .lookup(self.destination_directory.as_deref(), key)
2374 }
2375
2376 pub fn cache_store(&mut self, key: &str, value: &str) {
2378 self
2379 .cache
2380 .store(self.destination_directory.as_deref(), key, Some(value));
2381 }
2382
2383 pub fn cache_remove(&mut self, key: &str) {
2385 self
2386 .cache
2387 .store(self.destination_directory.as_deref(), key, None);
2388 }
2389
2390 pub fn cache(&self) -> &DocCache { &self.cache }
2392}
2393
2394pub const CACHE_FILE: &str = "LaTeXML-oxide.cache";
2397
2398pub fn is_cache_file(basename: &str) -> bool {
2400 basename
2401 .strip_prefix(CACHE_FILE)
2402 .is_some_and(|rest| matches!(rest, "" | "-wal" | "-shm" | "-journal"))
2403}
2404
2405#[derive(Clone, Default)]
2411pub struct DocCache(std::rc::Rc<std::cell::RefCell<DocCacheStores>>);
2412
2413#[derive(Default)]
2414struct DocCacheStores {
2415 nocache: bool,
2416 stores: HashMap<String, crate::sqlite_store::SqliteStore>,
2418}
2419
2420const DOC_CACHE_SCHEMA: &str =
2421 "CREATE TABLE IF NOT EXISTS kv(key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
2422
2423impl std::fmt::Debug for DocCache {
2424 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("DocCache") }
2425}
2426
2427impl DocCache {
2428 pub fn new(nocache: bool) -> Self {
2430 DocCache(std::rc::Rc::new(std::cell::RefCell::new(DocCacheStores {
2431 nocache,
2432 stores: HashMap::default(),
2433 })))
2434 }
2435
2436 pub fn with_store<T>(
2438 &self,
2439 dir: Option<&str>,
2440 f: impl FnOnce(&mut crate::sqlite_store::SqliteStore) -> T,
2441 ) -> T {
2442 let mut inner = self.0.borrow_mut();
2443 let persist = !inner.nocache;
2444 let key = dir.map_or_else(String::new, latexml_core::util::pathname::absolute);
2446 let store = inner.stores.entry(key).or_insert_with(|| {
2447 let file = dir.filter(|_| persist).map(|dir| {
2448 let _ = std::fs::create_dir_all(dir);
2451 Path::new(dir).join(CACHE_FILE)
2452 });
2453 crate::sqlite_store::SqliteStore::open(file.as_deref(), DOC_CACHE_SCHEMA, 1)
2454 });
2455 f(store)
2456 }
2457
2458 pub fn lookup(&self, dir: Option<&str>, key: &str) -> Option<String> {
2460 self.with_store(dir, |store| store.read(|conn| kv_get(conn, key)).flatten())
2461 }
2462
2463 pub fn store(&self, dir: Option<&str>, key: &str, value: Option<&str>) {
2465 self.with_store(dir, |store| store.immediate(|tx, _| kv_put(tx, key, value)));
2466 }
2467
2468 pub fn close(&self) { self.0.borrow_mut().stores.clear(); }
2471
2472 pub fn close_files(&self) {
2475 self
2476 .0
2477 .borrow_mut()
2478 .stores
2479 .retain(|_, store| store.file().is_none());
2480 }
2481}
2482
2483pub fn kv_get(conn: &rusqlite::Connection, key: &str) -> rusqlite::Result<Option<String>> {
2485 use rusqlite::OptionalExtension;
2486 conn
2487 .prepare_cached("SELECT value FROM kv WHERE key = ?1")?
2488 .query_row([key], |row| row.get(0))
2489 .optional()
2490}
2491
2492pub fn kv_put(conn: &rusqlite::Connection, key: &str, value: Option<&str>) -> rusqlite::Result<()> {
2494 match value {
2495 Some(value) => conn
2496 .prepare_cached("INSERT OR REPLACE INTO kv(key, value) VALUES (?1, ?2)")?
2497 .execute([key, value]),
2498 None => conn
2499 .prepare_cached("DELETE FROM kv WHERE key = ?1")?
2500 .execute([key]),
2501 }
2502 .map(drop)
2503}
2504
2505#[derive(Debug, Default, Clone)]
2510pub struct PostDocumentOptions {
2511 pub destination: Option<String>,
2512 pub destination_directory: Option<String>,
2513 pub site_directory: Option<String>,
2514 pub source: Option<String>,
2515 pub source_directory: Option<String>,
2516 pub searchpaths: Option<Vec<String>>,
2517 pub validate: bool,
2518 pub nocache: bool,
2519 pub cache: Option<DocCache>,
2521}
2522
2523#[derive(Debug, Clone)]
2527pub enum NodeData {
2528 Text(String),
2530 Element {
2532 tag: String,
2533 attributes: Option<HashMap<String, String>>,
2534 children: Vec<NodeData>,
2535 },
2536 XmlNode(Node),
2538}
2539
2540#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2547pub enum XMBranch {
2548 Content = 0,
2550 Presentation = 1,
2552}
2553
2554pub enum Conjunction {
2556 Simple(String),
2558 Pair(String, String),
2560}
2561
2562pub fn element_children(node: &Node) -> Vec<Node> {
2567 let mut result = Vec::new();
2568 if let Some(child) = node.get_first_child() {
2569 let mut current = Some(child);
2570 while let Some(ref c) = current {
2571 if c.get_type() == Some(NodeType::ElementNode) {
2572 result.push(c.clone());
2573 }
2574 current = c.get_next_sibling();
2575 }
2576 }
2577 result
2578}
2579
2580pub fn element_children_iter(node: &Node) -> impl Iterator<Item = Node> + use<> {
2585 let first = node.get_first_child();
2586 std::iter::successors(first, |c| c.get_next_sibling())
2587 .filter(|c| c.get_type() == Some(NodeType::ElementNode))
2588}
2589
2590pub fn escape_xml(s: &str) -> String {
2611 s.replace('&', "&")
2612 .replace('<', "<")
2613 .replace('>', ">")
2614 .replace('"', """)
2615}
2616
2617fn pathdiff(path: &str, base: &str) -> String {
2619 let p = Path::new(path);
2620 let b = Path::new(base);
2621 if let Ok(rel) = p.strip_prefix(b) {
2622 rel.to_string_lossy().to_string()
2623 } else {
2624 path.to_string()
2625 }
2626}
2627
2628#[cfg(test)]
2629mod tests {
2630 use super::*;
2631
2632 fn make_test_doc(xml: &str) -> PostDocument {
2633 PostDocument::new_from_string(xml, PostDocumentOptions::default()).unwrap()
2634 }
2635
2636 #[test]
2647 fn add_navigation_dedupes_including_preexisting_refs() {
2648 let mut doc = make_test_doc(
2649 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2650 <navigation>\
2651 <ref rel='chapter' idref='Ch1' show='toctitle'/>\
2652 <title>ignored — not an ltx:ref</title>\
2653 </navigation>\
2654 </document>",
2655 );
2656
2657 doc.add_navigation("chapter", "Ch1"); doc.add_navigation("section", "S1"); doc.add_navigation("section", "S1"); doc.add_navigation("sidebar", "Ch1"); let refs = doc.findnodes("//ltx:navigation/ltx:ref");
2663 let mut pairs: Vec<(String, String)> = refs
2664 .iter()
2665 .map(|n| {
2666 (
2667 n.get_attribute("rel").unwrap_or_default(),
2668 n.get_attribute("idref").unwrap_or_default(),
2669 )
2670 })
2671 .collect();
2672 pairs.sort();
2673 assert_eq!(pairs, vec![
2674 ("chapter".to_string(), "Ch1".to_string()),
2675 ("section".to_string(), "S1".to_string()),
2676 ("sidebar".to_string(), "Ch1".to_string()),
2677 ]);
2678 assert_eq!(
2679 doc.findnodes("//ltx:navigation").len(),
2680 1,
2681 "the existing navigation element must be reused, not duplicated"
2682 );
2683 }
2684
2685 #[test]
2692 fn add_navigation_sees_refs_under_every_navigation_element() {
2693 let mut doc = make_test_doc(
2694 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2695 <navigation><ref rel='chapter' idref='Ch1'/></navigation>\
2696 <section><navigation><ref rel='section' idref='S9'/></navigation></section>\
2697 </document>",
2698 );
2699
2700 doc.add_navigation("section", "S9"); doc.add_navigation("chapter", "Ch1"); assert_eq!(
2704 doc.findnodes("//ltx:navigation/ltx:ref").len(),
2705 2,
2706 "neither pair may be re-added; `//` spans both navigation elements"
2707 );
2708
2709 doc.add_navigation("appendix", "A1"); let first_nav_refs = doc.findnodes("//ltx:navigation").first().map(|n| {
2711 n.get_child_nodes()
2712 .iter()
2713 .filter(|c| name_is(c, "ref"))
2714 .count()
2715 });
2716 assert_eq!(
2717 first_nav_refs,
2718 Some(2),
2719 "a new ref lands under the FIRST navigation element (Perl's findnode)"
2720 );
2721 }
2722
2723 #[test]
2726 fn add_navigation_ignores_a_foreign_namespace_ref_when_seeding() {
2727 let mut doc = make_test_doc(
2728 "<document xmlns='http://dlmf.nist.gov/LaTeXML' xmlns:other='http://example.org/other'>\
2729 <navigation><other:ref rel='chapter' idref='Ch1'/></navigation>\
2730 </document>",
2731 );
2732
2733 doc.add_navigation("chapter", "Ch1");
2734
2735 assert_eq!(
2736 doc.findnodes("//ltx:navigation/ltx:ref").len(),
2737 1,
2738 "the foreign-namespace ref is not an ltx:ref, so the real one must be added"
2739 );
2740 }
2741
2742 #[test]
2746 fn navigation_memo_agrees_with_the_original_xpath_probe() {
2747 let mut doc = make_test_doc(
2748 "<document xmlns='http://dlmf.nist.gov/LaTeXML' xmlns:other='http://example.org/other'>\
2749 <navigation>\
2750 <ref rel='chapter' idref='Ch1'/>\
2751 <title>t</title>\
2752 <other:ref rel='section' idref='S1'/>\
2753 </navigation>\
2754 </document>",
2755 );
2756
2757 for (rel, id) in [
2758 ("chapter", "Ch1"), ("section", "S1"), ("title", "t"), ("section", "S2"), ] {
2763 let probe = format!("//ltx:navigation/ltx:ref[@rel='{}'][@idref='{}']", rel, id);
2765 let xpath_says_present = doc.findnode(&probe).is_some();
2766 let memo_says_present = doc.navigation_ref_present(rel, id);
2767 assert_eq!(
2768 memo_says_present, xpath_says_present,
2769 "memo and XPath disagree about ({rel}, {id})"
2770 );
2771 }
2772 }
2773
2774 #[test]
2775 fn add_navigation_creates_then_reuses_the_navigation_element() {
2776 let mut doc = make_test_doc("<document xmlns='http://dlmf.nist.gov/LaTeXML'><p/></document>");
2777
2778 doc.add_navigation("section", "S1");
2779 doc.add_navigation("section", "S2");
2780 doc.add_navigation("section", "S1"); assert_eq!(
2783 doc.findnodes("//ltx:navigation").len(),
2784 1,
2785 "exactly one navigation element must be created"
2786 );
2787 assert_eq!(doc.findnodes("//ltx:navigation/ltx:ref").len(), 2);
2788 }
2789
2790 #[test]
2791 fn test_new_from_string() {
2792 let doc = make_test_doc("<document xmlns='http://dlmf.nist.gov/LaTeXML'/>");
2793 assert!(doc.get_document_element().is_some());
2794 }
2795
2796 #[test]
2797 fn test_findnodes() {
2798 let doc = make_test_doc(
2799 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2800 <section xml:id='s1'/>\
2801 <section xml:id='s2'/>\
2802 </document>",
2803 );
2804 let sections = doc.findnodes("//ltx:section");
2805 assert_eq!(sections.len(), 2);
2806 }
2807
2808 #[test]
2811 fn libxml_oom_is_told_from_an_xpath_error() {
2812 let oom = XPathError {
2813 message: None,
2814 code: 2,
2815 domain: 12,
2816 };
2817 let syntax = XPathError {
2818 message: Some("Invalid expression".into()),
2819 code: 1207,
2820 domain: 12,
2821 };
2822 let unknown = XPathError {
2823 message: None,
2824 code: 0,
2825 domain: 0,
2826 };
2827 assert!(is_libxml_oom(&oom));
2828 assert!(!is_libxml_oom(&syntax));
2829 assert!(!is_libxml_oom(&unknown));
2830 }
2831
2832 #[test]
2840 fn findnodes_resolves_relative_axes_without_context_node() {
2841 let doc = make_test_doc(
2842 "<?latexml class='book'?>\
2843 <document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2844 <resource src='a.css' type='text/css'/>\
2845 <section xml:id='s1'/>\
2846 </document>",
2847 );
2848 assert_eq!(doc.findnodes("//ltx:resource").len(), 1, "absolute");
2849 assert_eq!(
2850 doc.findnodes("descendant::ltx:resource").len(),
2851 1,
2852 "descendant:: axis must resolve without an explicit context node"
2853 );
2854 assert_eq!(
2855 doc.findnodes(".//ltx:resource").len(),
2856 1,
2857 ".// axis must resolve without an explicit context node"
2858 );
2859 assert_eq!(
2861 doc.findnodes("//processing-instruction('latexml')").len(),
2862 1,
2863 "absolute PI query finds the before-root <?latexml?>"
2864 );
2865 }
2866
2867 const SECTION_UNION: &str = "//ltx:section | \
2870 //ltx:bibliography[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2871 //ltx:appendix[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2872 //ltx:index[preceding-sibling::ltx:section or parent::ltx:part or parent::ltx:chapter] | \
2873 //ltx:part | \
2874 //ltx:bibliography[preceding-sibling::ltx:part] | \
2875 //ltx:appendix[preceding-sibling::ltx:part] | \
2876 //ltx:index[preceding-sibling::ltx:part] | \
2877 //ltx:chapter | \
2878 //ltx:bibliography[preceding-sibling::ltx:chapter or parent::ltx:part] | \
2879 //ltx:appendix[preceding-sibling::ltx:chapter or parent::ltx:part] | \
2880 //ltx:index[preceding-sibling::ltx:chapter or parent::ltx:part]";
2881
2882 fn split_doc() -> PostDocument {
2883 make_test_doc(
2884 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2885 <part xml:id='P1'>\
2886 <chapter xml:id='C1'>\
2887 <section xml:id='S1'/>\
2888 <section xml:id='S2'/>\
2889 <index xml:id='I1'/>\
2890 </chapter>\
2891 <bibliography xml:id='B1'/>\
2892 </part>\
2893 <section xml:id='S3'/>\
2894 <index xml:id='I2'/>\
2895 </document>",
2896 )
2897 }
2898
2899 #[test]
2902 fn test_find_split_pages_matches_xpath() {
2903 let doc = split_doc();
2904 let ids = |nodes: Vec<Node>| -> Vec<String> { nodes.iter().filter_map(get_xml_id).collect() };
2905 let via_walk = ids(doc.find_split_pages(SECTION_UNION));
2906 let via_xpath = ids(doc.findnodes(SECTION_UNION));
2907 assert_eq!(
2908 via_walk,
2909 vec!["P1", "C1", "S1", "S2", "I1", "B1", "S3", "I2"],
2910 "walk selected the wrong pages / order"
2911 );
2912 assert_eq!(via_walk, via_xpath, "walk diverged from XPath union");
2913 }
2914
2915 #[test]
2918 fn test_find_split_pages_fallback() {
2919 let doc = split_doc();
2920 let via = doc.find_split_pages("//ltx:chapter/descendant::ltx:section");
2922 let ids: Vec<String> = via.iter().filter_map(get_xml_id).collect();
2923 assert_eq!(ids, vec!["S1", "S2"]);
2924 }
2925
2926 #[test]
2929 fn test_scan_ids_populates_idcache() {
2930 let doc = split_doc();
2931 for id in ["P1", "C1", "S1", "S2", "I1", "B1", "S3", "I2"] {
2932 assert!(
2933 doc.find_node_by_id(id).is_some(),
2934 "missing id {id} in idcache"
2935 );
2936 }
2937 assert!(doc.find_node_by_id("nope").is_none());
2938 }
2939
2940 #[test]
2943 fn split_pages_carry_the_document_pis() {
2944 let doc = make_test_doc(
2945 "<?latexml class=\"article\"?><?latexml RelaxNGSchema=\"LaTeXML\"?>\
2946 <document xmlns='http://dlmf.nist.gov/LaTeXML'><section xml:id='S1'/><section xml:id='S2'/></document>",
2947 );
2948 for id in ["S1", "S2"] {
2949 let page = doc.new_document(
2950 doc.find_node_by_id(id).unwrap().clone(),
2951 &format!("{id}.html"),
2952 None,
2953 );
2954 let xml = page.to_xml_string();
2955 assert!(
2956 xml.contains(
2957 "<?latexml class=\"article\"?>\n<?latexml RelaxNGSchema=\"LaTeXML\"?>\n<section"
2958 ),
2959 "{xml}"
2960 );
2961 }
2962 }
2963
2964 #[test]
2967 fn test_scan_collects_doclevel_pi_searchpaths() {
2968 let doc = make_test_doc(
2969 "<?latexml searchpaths=\"alpha,beta\"?>\
2970 <document xmlns='http://dlmf.nist.gov/LaTeXML'><section xml:id='s1'/></document>",
2971 );
2972 let paths = doc.get_search_paths();
2973 assert!(paths.iter().any(|p| p == "alpha"), "searchpaths: {paths:?}");
2974 assert!(paths.iter().any(|p| p == "beta"), "searchpaths: {paths:?}");
2975 }
2976
2977 #[test]
2978 fn test_uniquify_id() {
2979 let doc = make_test_doc(
2980 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
2981 <p xml:id='p1'/>\
2982 </document>",
2983 );
2984 let mut doc = doc;
2985 let id1 = doc.uniquify_id("p1", None);
2987 let id2 = doc.uniquify_id("p1", None);
2989 assert_ne!(id1, id2);
2990 assert!(id1.starts_with("p1"));
2992 assert!(id2.starts_with("p1"));
2993 }
2994
2995 #[test]
2996 fn test_initial() {
2997 assert_eq!(PostDocument::initial("Hello", false), "H");
2998 assert_eq!(PostDocument::initial(" world", false), "W");
2999 assert_eq!(PostDocument::initial("123abc", true), "A");
3000 assert_eq!(PostDocument::initial("!@#", false), "*");
3001 assert_eq!(PostDocument::initial("\u{00E9}cole", false), "E"); }
3003
3004 #[test]
3005 fn test_add_class() {
3006 let doc = make_test_doc(
3007 "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
3008 <p xml:id='p1'/>\
3009 </document>",
3010 );
3011 let mut node = doc.findnode("//ltx:p").unwrap();
3012 PostDocument::add_class(&mut node, "foo bar");
3013 let class = node.get_attribute("class").unwrap();
3014 assert!(class.contains("bar"));
3015 assert!(class.contains("foo"));
3016
3017 PostDocument::add_class(&mut node, "foo");
3019 let class = node.get_attribute("class").unwrap();
3020 let count = class.matches("foo").count();
3021 assert_eq!(count, 1);
3022 }
3023}