1use libxml::tree::Node;
8use rustc_hash::FxHashMap as HashMap;
9
10use crate::{
11 document::{NodeData, PostDocument, get_xml_id},
12 processor::{ProcessResult, Processor},
13};
14
15#[derive(Debug, Clone)]
17pub enum SplitNaming {
18 Id,
20 IdRelative,
22 Label,
24 LabelRelative,
26}
27
28struct PageEntry {
30 node: Node,
31 id: Option<String>,
32 upid: Option<String>,
33 name: String,
34 children: Vec<PageEntry>,
35 document: Option<PostDocument>,
36}
37
38pub struct Split {
42 name: String,
43 split_xpath: String,
45 no_navigation: bool,
47 namer: PageNamer,
49}
50
51impl Split {
52 pub fn new(split_xpath: &str, split_naming: SplitNaming, no_navigation: bool) -> Self {
53 Split {
54 name: "Split".to_string(),
55 split_xpath: split_xpath.to_string(),
56 no_navigation,
57 namer: PageNamer::new(split_naming),
58 }
59 }
60
61 fn get_pages(&self, doc: &PostDocument) -> Vec<Node> {
66 doc
67 .find_split_pages(&self.split_xpath)
68 .into_iter()
69 .filter(|page| {
70 !page
71 .get_attribute("class")
72 .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_nodisplay"))
73 })
74 .collect()
75 }
76
77 fn presort_pages(
82 tree: &mut PageEntry,
83 haschildren: &mut HashMap<String, bool>,
84 pages: Vec<Node>,
85 ) {
86 let mut path: Vec<usize> = Vec::new(); for page in pages {
92 loop {
94 let current_node = Self::get_node_at(tree, &path);
95 if is_child(&page, ¤t_node) {
96 break;
97 }
98 if path.is_empty() {
99 break;
100 }
101 path.pop();
102 }
103
104 let current_node = Self::get_node_at(tree, &path);
105 let current_id = get_xml_id(¤t_node);
106 let localname = current_node.get_name();
107 haschildren.insert(localname, true);
108
109 let page_id = get_xml_id(&page);
110 let entry = PageEntry {
111 node: page,
112 id: page_id,
113 upid: current_id,
114 name: String::new(),
115 children: Vec::new(),
116 document: None,
117 };
118
119 let parent = Self::get_entry_at_mut(tree, &path);
121 parent.children.push(entry);
122 let new_idx = parent.children.len() - 1;
123
124 path.push(new_idx);
126 }
127 }
128
129 fn get_node_at(tree: &PageEntry, path: &[usize]) -> Node {
131 let mut current = tree;
132 for &idx in path {
133 current = ¤t.children[idx];
134 }
135 current.node.clone()
136 }
137
138 fn get_entry_at_mut<'a>(tree: &'a mut PageEntry, path: &[usize]) -> &'a mut PageEntry {
140 let mut current = tree;
141 for &idx in path {
142 current = &mut current.children[idx];
143 }
144 current
145 }
146
147 fn prename_pages(
151 &mut self,
152 doc: &PostDocument,
153 tree: &mut PageEntry,
154 haschildren: &HashMap<String, bool>,
155 ) {
156 let (parent_name, parent_node) = (tree.name.clone(), tree.node.clone());
157 for child in &mut tree.children {
159 let recursive = haschildren
160 .get(&child.node.get_name())
161 .copied()
162 .unwrap_or(false);
163 child.name = self.get_page_name(doc, &child.node, &parent_node, &parent_name, recursive);
164 self.prename_pages(doc, child, haschildren);
165 }
166 }
167
168 fn process_pages(
173 &mut self,
174 doc: &mut PostDocument,
175 entries: &mut Vec<PageEntry>,
176 nav_holders: &[Node],
177 ) -> Vec<PostDocument> {
178 let mut intoc = false;
180 for entry in entries.iter() {
181 let node = &entry.node;
182 if let Some(inlist) = node.get_attribute("inlist") {
183 if inlist.contains("toc") {
184 intoc = true;
185 }
186 }
187 for attr in &["xml:lang", "backgroundcolor"] {
195 let xpath = format!("ancestor-or-self::*[@{}][1]", attr);
196 if let Some(anc) = doc.findnode_at(&xpath, node) {
197 let val = anc.get_attribute(attr).or_else(|| {
198 attr
199 .strip_prefix("xml:")
200 .and_then(|local| anc.get_attribute_ns(local, "http://www.w3.org/XML/1998/namespace"))
201 });
202 if let Some(val) = val {
203 let mut node_mut = node.clone();
204 node_mut.set_attribute(attr, &val).ok();
205 }
206 }
207 }
208 }
209
210 let mut docs = Vec::new();
211 while !entries.is_empty() {
212 let parent = match entries[0].node.get_parent() {
213 Some(p) => p,
214 None => {
215 entries.remove(0);
216 continue;
217 },
218 };
219
220 let mut removed: Vec<Node> = Vec::new();
222 loop {
223 let last = parent.get_last_child();
224 match last {
225 Some(mut sib) => {
226 sib.unlink_node();
227 removed.insert(0, sib.clone());
228 if sib == entries[0].node {
229 break;
230 }
231 },
232 None => break,
233 }
234 }
235
236 let mut toc: Vec<NodeData> = Vec::new();
238
239 while !entries.is_empty() && !removed.is_empty() && entries[0].node == removed[0] {
241 let mut entry = entries.remove(0);
242 let page = entry.node.clone();
243
244 if intoc && !page.has_attribute("inlist") {
246 let mut page_mut = page.clone();
247 page_mut.set_attribute("inlist", "toc").ok();
248 }
249
250 let removed_node = removed.remove(0);
252 doc.remove_nodes(&[removed_node]);
253
254 if let Some(id) = get_xml_id(&page) {
256 let mut toc_attrs = HashMap::default();
257 toc_attrs.insert("idref".to_string(), id);
258 toc_attrs.insert("show".to_string(), "toctitle".to_string());
259 let tocentry = NodeData::Element {
260 tag: "ltx:tocentry".to_string(),
261 attributes: None,
262 children: vec![NodeData::Element {
263 tag: "ltx:ref".to_string(),
264 attributes: Some(toc_attrs),
265 children: vec![],
266 }],
267 };
268 toc.push(tocentry);
269 }
270
271 let mut child_docs = self.process_pages(doc, &mut entry.children, nav_holders);
273
274 let subdoc = doc.new_document(page.clone(), &entry.name, entry.upid.clone());
276 if !nav_holders.contains(&page) {
281 doc.discard_subtree(page);
282 }
283 entry.document = Some(subdoc);
284 docs.push(entry.document.take().unwrap());
286 docs.append(&mut child_docs);
287 }
288
289 if !toc.is_empty() {
291 let has_toc = !doc
293 .findnodes_at("descendant::ltx:TOC[@lists='toc']", Some(&parent))
294 .is_empty();
295 if !has_toc {
296 let parent_type = parent.get_name();
297 let mut toclist_attrs = HashMap::default();
298 toclist_attrs.insert("class".to_string(), format!("ltx_toclist_{}", parent_type));
299 let toc_node = NodeData::Element {
300 tag: "ltx:TOC".to_string(),
301 attributes: None,
302 children: vec![NodeData::Element {
303 tag: "ltx:toclist".to_string(),
304 attributes: Some(toclist_attrs),
305 children: toc,
306 }],
307 };
308 let mut parent_mut = parent.clone();
309 doc.add_nodes(&mut parent_mut, &[toc_node]);
310 }
311 }
312
313 let mut parent_mut = parent;
315 for mut child in removed {
316 parent_mut.add_child(&mut child).ok();
317 }
318 }
319 docs
320 }
321
322 fn add_navigation(entry: &mut PageEntry, nav_nodes: &[Node]) {
326 if let Some(ref mut doc) = entry.document {
327 if let Some(mut root) = doc.get_document_element() {
328 let nav_data: Vec<NodeData> = nav_nodes
329 .iter()
330 .map(|n| NodeData::XmlNode(n.clone()))
331 .collect();
332 doc.add_nodes(&mut root, &nav_data);
333 }
334 }
335 for child in &mut entry.children {
336 Self::add_navigation(child, nav_nodes);
337 }
338 }
339
340 fn get_page_name(
344 &mut self,
345 doc: &PostDocument,
346 page: &Node,
347 parent: &Node,
348 parent_path: &str,
349 recursive: bool,
350 ) -> String {
351 let (labels, id) = (page.get_attribute("labels"), get_xml_id(page));
352 let (parent_labels, parent_id) = (parent.get_attribute("labels"), get_xml_id(parent));
353 let ext = doc
354 .get_destination_extension()
355 .unwrap_or_else(|| "xml".to_string());
356 self.namer.page_name(
357 PageKeys {
358 labels: labels.as_deref(),
359 id: id.as_deref(),
360 },
361 PageKeys {
362 labels: parent_labels.as_deref(),
363 id: parent_id.as_deref(),
364 },
365 parent_path,
366 &ext,
367 recursive,
368 )
369 }
370}
371
372#[derive(Clone, Copy)]
374pub(crate) struct PageKeys<'a> {
375 pub(crate) labels: Option<&'a str>,
376 pub(crate) id: Option<&'a str>,
377}
378
379impl PageKeys<'_> {
380 fn key(&self, attr: &str) -> &str {
382 let value = if attr == "labels" {
383 self.labels
384 } else {
385 self.id
386 };
387 let first = value
388 .and_then(|v| v.split_whitespace().next())
389 .unwrap_or("");
390 first.strip_prefix("LABEL:").unwrap_or(first)
391 }
392}
393
394enum Refusal {
396 Outside,
398 Taken(Option<String>),
400}
401
402pub(crate) struct PageNamer {
404 naming: SplitNaming,
406 unnamed_page_counter: u32,
408 destination_directory: String,
410 issued: HashMap<String, Option<String>>,
412}
413
414impl PageNamer {
415 pub(crate) fn new(naming: SplitNaming) -> Self {
416 PageNamer {
417 naming,
418 unnamed_page_counter: 0,
419 destination_directory: String::new(),
420 issued: HashMap::default(),
421 }
422 }
423
424 pub(crate) fn start(&mut self, destination: &str) {
426 self.destination_directory = latexml_core::util::pathname::directory(destination);
427 self.issued.clear();
428 self
429 .issued
430 .insert(latexml_core::util::pathname::absolute(destination), None);
431 }
432
433 fn generate_unnamed_page_name(&mut self) -> String {
435 self.unnamed_page_counter += 1;
436 format!("FOO{}", self.unnamed_page_counter)
437 }
438
439 fn fallback_name(&mut self, page: PageKeys, attr: &'static str) -> (&'static str, String) {
442 match page.id.filter(|_| attr == "labels") {
443 Some(id) => ("xml:id", id.to_string()),
444 None => (attr, self.generate_unnamed_page_name()),
445 }
446 }
447
448 pub(crate) fn page_name(
452 &mut self,
453 page: PageKeys,
454 parent: PageKeys,
455 parent_path: &str,
456 ext: &str,
457 recursive: bool,
458 ) -> String {
459 use latexml_core::util::pathname;
460 let mut attr = match self.naming {
461 SplitNaming::Id | SplitNaming::IdRelative => "xml:id",
462 SplitNaming::Label | SplitNaming::LabelRelative => "labels",
463 };
464 let mut name = page_name_segments(page.key(attr));
465 if name.is_empty() {
466 let missing = attr;
467 (attr, name) = self.fallback_name(page, attr);
468 Info!(
469 "split",
470 "pathname",
471 "Using '{}' to create page pathname, instead of missing '{}'",
472 name,
473 missing
474 );
475 }
476 let mut refused: Option<(String, String, Refusal)> = None;
478 loop {
479 let (pathname, climbs) = self.pathname(attr, &name, parent, parent_path, ext, recursive);
480 let key = pathname::absolute(&pathname);
481 let by = match page.key(attr) {
482 "" => format!("'{name}'"),
483 key if attr == "labels" => format!("label '{key}'"),
484 key => format!("id '{key}'"),
485 };
486 let refusal = if climbs
487 && pathname::is_contained(&pathname::directory(&key), &self.destination_directory).is_none()
488 {
489 Some(Refusal::Outside)
490 } else {
491 self.issued.get(&key).cloned().map(Refusal::Taken)
492 };
493 if let Some(refusal) = refusal {
494 refused.get_or_insert((pathname, by, refusal));
495 (attr, name) = self.fallback_name(page, attr);
496 continue;
497 }
498 self.issued.insert(key, Some(by));
499 if let Some((refused, by, refusal)) = refused {
500 let shown = |path: &str| {
502 pathname::relative(
503 &pathname::absolute(path),
504 &pathname::absolute(&self.destination_directory),
505 )
506 };
507 let (refused, written) = (shown(&refused), shown(&pathname));
508 match refusal {
509 Refusal::Outside => Error!(
510 "unexpected",
511 &refused,
512 "The page of {} ({}) must be within the destination directory ({}); it is written to {} instead",
513 by,
514 refused,
515 if self.destination_directory.is_empty() {
517 "."
518 } else {
519 &self.destination_directory
520 },
521 written
522 ),
523 Refusal::Taken(owner) => Warn!(
524 "unexpected",
525 &refused,
526 "The page of {} would overwrite {} ({}); it is written to {} instead",
527 by,
528 owner.map_or_else(
529 || "the document's own page".to_string(),
530 |owner| format!("the page of {owner}")
531 ),
532 refused,
533 written
534 ),
535 }
536 }
537 return pathname;
538 }
539 }
540
541 fn pathname(
545 &self,
546 attr: &str,
547 name: &str,
548 parent: PageKeys,
549 parent_path: &str,
550 ext: &str,
551 recursive: bool,
552 ) -> (String, bool) {
553 let mut name = name.to_string();
554 let as_dir = match self.naming {
555 SplitNaming::IdRelative | SplitNaming::LabelRelative => {
556 if let Some(rest) = strip_parent_name(&name, &page_name_segments(parent.key(attr))) {
557 name = rest;
558 }
559 recursive
560 },
561 _ => false,
562 };
563 let pathname = page_pathname(parent_path, &colons_to_underscore(&name), ext, as_dir);
564 if name.split('/').next() == Some("..") {
565 (lexical_pathname(&pathname), true)
566 } else {
567 (pathname, false)
568 }
569 }
570}
571
572fn lexical_pathname(pathname: &str) -> String {
575 let rest = pathname.trim_start_matches(std::path::is_separator);
576 format!(
577 "{}{}",
578 &pathname[..pathname.len() - rest.len()],
579 page_name_segments(rest)
580 )
581}
582
583pub(crate) fn page_name_segments(name: &str) -> String {
588 let mut segments: Vec<&str> = Vec::new();
589 for segment in name.split(std::path::is_separator) {
590 match segment {
591 "" | "." => {},
592 ".." if segments.last().is_some_and(|last| *last != "..") => {
593 segments.pop();
594 },
595 _ => segments.push(segment),
596 }
597 }
598 segments.join("/")
599}
600
601pub(crate) fn strip_parent_name(name: &str, parent: &str) -> Option<String> {
604 let rest = name
605 .strip_prefix(parent)
606 .filter(|rest| !parent.is_empty() && rest.starts_with(['.', '_', ':']))?;
607 Some(page_name_segments(rest.trim_start_matches(['.', '_', ':']))).filter(|rest| !rest.is_empty())
608}
609
610pub(crate) fn colons_to_underscore(name: &str) -> String {
612 let mut out = String::with_capacity(name.len());
613 for (i, c) in name.char_indices() {
614 if c != ':' {
615 out.push(c);
616 } else if !name[..i].ends_with(':') {
617 out.push('_');
618 }
619 }
620 out
621}
622
623pub(crate) fn page_pathname(parent_path: &str, name: &str, ext: &str, as_dir: bool) -> String {
626 debug_assert!(
627 !name.is_empty() && !name.starts_with(std::path::is_separator),
628 "page name {name:?}"
629 );
630 let file = if as_dir {
631 format!("{name}/index.{ext}")
632 } else {
633 format!("{name}.{ext}")
634 };
635 match std::path::Path::new(parent_path)
638 .parent()
639 .and_then(|dir| dir.to_str())
640 {
641 Some(dir) if !dir.is_empty() => format!("{dir}/{file}"),
642 _ => file,
643 }
644}
645
646impl Processor for Split {
647 fn get_name(&self) -> &str { &self.name }
648
649 fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
650 let root = match nodes.into_iter().next() {
651 Some(r) => r,
652 None => return Ok(vec![doc]),
653 };
654
655 let mut root_mut = root;
657 if get_xml_id(&root_mut).is_none() {
658 root_mut
659 .set_attribute("xml:id", "TEMPORARY_DOCUMENT_ID")
660 .ok();
661 }
662
663 let pages = self.get_pages(&doc);
664 let pages: Vec<Node> = pages
666 .into_iter()
667 .filter(|p| p.get_parent().and_then(|pp| pp.get_parent()).is_some())
668 .collect();
669
670 if pages.is_empty() {
671 Info!("split", "result", "[not split]");
672 return Ok(vec![doc]);
673 }
674
675 let nav_nodes: Vec<Node> = doc.findnodes("descendant::ltx:navigation");
677 let nav_holders: Vec<Node> = nav_nodes
680 .iter()
681 .flat_map(|nav| std::iter::successors(nav.get_parent(), Node::get_parent))
682 .collect();
683 if !nav_nodes.is_empty() {
684 doc.remove_nodes(&nav_nodes);
685 }
686
687 let root_id = get_xml_id(&root_mut);
689 let root_dest = doc.get_destination().unwrap_or("").to_string();
690 let mut tree = PageEntry {
691 node: root_mut,
692 id: root_id,
693 upid: None,
694 name: root_dest,
695 children: Vec::new(),
696 document: Some(doc),
697 };
698
699 let mut haschildren = HashMap::default();
700 Self::presort_pages(&mut tree, &mut haschildren, pages);
701 self.namer.start(&tree.name);
702
703 let doc_tmp = tree.document.take().unwrap();
705 self.prename_pages(&doc_tmp, &mut tree, &haschildren);
706 tree.document = Some(doc_tmp);
707
708 let mut doc = tree.document.take().unwrap();
710 let mut docs = vec![];
711 let mut child_docs = self.process_pages(&mut doc, &mut tree.children, &nav_holders);
712
713 if !nav_nodes.is_empty() && !self.no_navigation {
715 tree.document = Some(doc);
717 Self::add_navigation(&mut tree, &nav_nodes);
718 doc = tree.document.take().unwrap();
719
720 for child_doc in &mut child_docs {
722 if let Some(mut root) = child_doc.get_document_element() {
723 let nav_data: Vec<NodeData> = nav_nodes
724 .iter()
725 .map(|n| NodeData::XmlNode(n.clone()))
726 .collect();
727 child_doc.add_nodes(&mut root, &nav_data);
728 }
729 }
730 }
731
732 docs.insert(0, doc);
733 docs.append(&mut child_docs);
734
735 let n = docs.len();
736 Info!(
737 "split",
738 "result",
739 "{}",
740 if n > 1 {
741 format!(" [Split into {} pages]", n)
742 } else {
743 "[not split]".to_string()
744 }
745 );
746
747 Ok(docs)
748 }
749}
750
751fn is_child(child: &Node, ancestor: &Node) -> bool {
753 let mut parent = child.get_parent();
754 while let Some(ref p) = parent {
755 if *p == *ancestor {
756 return true;
757 }
758 parent = p.get_parent();
759 }
760 false
761}
762
763#[cfg(test)]
764mod page_name_tests {
765 use super::*;
766
767 #[test]
770 fn page_names_take_perls_segments_strip_and_colons() {
771 for (label, name) in [
772 ("/x", "x"),
773 ("./x", "x"),
774 ("a//b/", "a/b"),
775 ("a/./b", "a/b"),
776 ("a/../b", "b"),
777 ("a/../..", ".."),
778 ("../esc", "../esc"),
779 ("../../x", "../../x"),
780 ("a/..", ""),
781 ("/", ""),
782 ("~one", "~one"),
783 ] {
784 assert_eq!(page_name_segments(label), name, "{label}");
785 }
786 assert_eq!(
787 page_name_segments("a\\b"),
788 if cfg!(windows) { "a/b" } else { "a\\b" }
789 );
790 assert_eq!(strip_parent_name("section", "sec"), None);
791 assert_eq!(
792 strip_parent_name("sec:./dot", "sec").as_deref(),
793 Some("dot")
794 );
795 assert_eq!(strip_parent_name("sec._x", "sec").as_deref(), Some("x"));
796 assert_eq!(strip_parent_name("sec:", "sec"), None);
797 assert_eq!(strip_parent_name("x", ""), None);
798 assert_eq!(colons_to_underscore("sec:::1:a"), "sec_1_a");
799 for (pathname, resolved) in [
800 ("out/FOO1/../up.html", "out/up.html"),
801 ("/w/out/a/../../b/index.html", "/w/b/index.html"),
802 ("~one/../up.html", "up.html"),
803 ("../x/../../y.html", "../../y.html"),
804 ] {
805 assert_eq!(lexical_pathname(pathname), resolved, "{pathname}");
806 }
807 }
808}