Skip to main content

latexml_post/
split.rs

1//! Document splitting processor.
2//!
3//! Port of `LaTeXML::Post::Split`.
4//! Splits a document into multiple pages based on an XPath expression
5//! that identifies section-level elements to extract as separate documents.
6
7use 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/// Page naming strategy for split documents.
16#[derive(Debug, Clone)]
17pub enum SplitNaming {
18  /// Use xml:id attribute
19  Id,
20  /// Use xml:id, relative to parent
21  IdRelative,
22  /// Use labels attribute
23  Label,
24  /// Use labels, relative to parent
25  LabelRelative,
26}
27
28/// A tree node used to track the hierarchy of pages during splitting.
29struct 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
38/// Split post-processor: splits a document into multiple pages.
39///
40/// Port of `LaTeXML::Post::Split`.
41pub struct Split {
42  name:          String,
43  /// XPath expression to find elements that become pages.
44  split_xpath:   String,
45  /// Whether to suppress navigation links.
46  no_navigation: bool,
47  /// Names the pages: Perl's `splitnaming` and `unnamed_page_counter`.
48  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  /// Get the nodes that will become separate pages, via the limit-safe
62  /// [`PostDocument::find_split_pages`] walk (not XPath, which silently splits
63  /// nothing on very large documents). A hidden element (`ltx_nodisplay`, such as the bibliography only a
64  /// `\fullcite` reads) stays in its parent's page: a page of its own would show nothing.
65  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  /// Sort pages into a tree hierarchy.
78  ///
79  /// Port of Perl `presortPages`.
80  /// If a page is a descendant of another page, it becomes a child in the tree.
81  fn presort_pages(
82    tree: &mut PageEntry,
83    haschildren: &mut HashMap<String, bool>,
84    pages: Vec<Node>,
85  ) {
86    // We track the "current" position in the tree by maintaining a path of ancestors.
87    // Since we can't have mutable borrows at multiple tree levels simultaneously,
88    // we use an index-based approach to walk the tree.
89    let mut path: Vec<usize> = Vec::new(); // indices into children arrays
90
91    for page in pages {
92      // Walk back up the tree until we find an ancestor of `page`
93      loop {
94        let current_node = Self::get_node_at(tree, &path);
95        if is_child(&page, &current_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(&current_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      // Add as child of current position
120      let parent = Self::get_entry_at_mut(tree, &path);
121      parent.children.push(entry);
122      let new_idx = parent.children.len() - 1;
123
124      // Go "down" — following pages may be children of this one
125      path.push(new_idx);
126    }
127  }
128
129  /// Get the node at a given path in the tree.
130  fn get_node_at(tree: &PageEntry, path: &[usize]) -> Node {
131    let mut current = tree;
132    for &idx in path {
133      current = &current.children[idx];
134    }
135    current.node.clone()
136  }
137
138  /// Get a mutable reference to the entry at a given path.
139  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  /// Compute destination pathnames for each page in the tree.
148  ///
149  /// Port of Perl `prenamePages`.
150  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    // Each page before its children, so on a collision the earlier page in document order keeps the name.
158    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  /// Process a sequence of page entries, removing them from the document
169  /// and generating sub-documents for each.
170  ///
171  /// Port of Perl `processPages`.
172  fn process_pages(
173    &mut self,
174    doc: &mut PostDocument,
175    entries: &mut Vec<PageEntry>,
176    nav_holders: &[Node],
177  ) -> Vec<PostDocument> {
178    // Before any document surgery, copy inheritable attributes.
179    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      // Copy xml:lang and backgroundcolor from ancestors (Perl Split.pm's
188      // inheritable-attribute loop). `get_attribute("xml:lang")` alone can
189      // miss the namespaced form (`xml:` attributes live in the XML
190      // namespace — the same trap `get_xml_id` guards), which silently
191      // skipped the copy: the XPath found the ancestor, the read returned
192      // None, and split pages lost their inherited language. Caught by the
193      // streaming-split parity gate (118_streaming_split_parity).
194      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      // Remove page & ALL following siblings (backwards).
221      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      // Build TOC from adjacent nodes being extracted.
237      let mut toc: Vec<NodeData> = Vec::new();
238
239      // Process a sequence of adjacent pages that share the same parent.
240      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 any pages go in toc, assume siblings should too
245        if intoc && !page.has_attribute("inlist") {
246          let mut page_mut = page.clone();
247          page_mut.set_attribute("inlist", "toc").ok();
248        }
249
250        // Remove this page from the removed list and from the document's ID cache
251        let removed_node = removed.remove(0);
252        doc.remove_nodes(&[removed_node]);
253
254        // Build TOC entry
255        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        // Process children pages BEFORE this page (Perl: "Due to the way document building works")
272        let mut child_docs = self.process_pages(doc, &mut entry.children, nav_holders);
273
274        // Create sub-document from the extracted page
275        let subdoc = doc.new_document(page.clone(), &entry.name, entry.upid.clone());
276        // The page now lives in its copy; free the source subtree (Perl's GC does at
277        // the last reference). Left unlinked, every page leaked: the whole source DOM
278        // stayed live through post, 818 MB of C heap by page 1024 of a 1,600-subsection
279        // book. A page holding a navigation stays: the nav may use its namespaces.
280        if !nav_holders.contains(&page) {
281          doc.discard_subtree(page);
282        }
283        entry.document = Some(subdoc);
284        // Take the document out to push to the results
285        docs.push(entry.document.take().unwrap());
286        docs.append(&mut child_docs);
287      }
288
289      // Add TOC to reflect the extracted pages
290      if !toc.is_empty() {
291        // Only add if parent doesn't already have a TOC with lists='toc'
292        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      // Re-add remaining siblings
314      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  /// Add navigation elements to all documents in the tree.
323  ///
324  /// Port of Perl `addNavigation`.
325  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  /// Compute the destination pathname for a page.
341  ///
342  /// Port of `Split::getPageName`, through [`PageNamer`].
343  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/// A page's `labels` and `xml:id`, the keys `Split::getPageName` names a page and its parent by.
373#[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  /// The first key of `attr` less `LABEL:` (`Split.pm` L164-166, L177-179).
381  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
394/// Why a page cannot have the pathname its key gives.
395enum Refusal {
396  /// Outside the destination's directory.
397  Outside,
398  /// Issued to another page (`None`: the document's own).
399  Taken(Option<String>),
400}
401
402/// Perl `Split::getPageName` (`Split.pm` L158-191) for both split paths, and the pathnames one split has issued.
403pub(crate) struct PageNamer {
404  /// Perl's `splitnaming`.
405  naming:                SplitNaming,
406  /// Perl's `unnamed_page_counter`, which no split resets.
407  unnamed_page_counter:  u32,
408  /// The destination's directory, which every page lies in.
409  destination_directory: String,
410  /// Each pathname issued in this split, absolute, with what named it (`None`: the document's own page).
411  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  /// Start the split of a document written to `destination`.
425  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  /// Perl `generateUnnamedPageName`.
434  fn generate_unnamed_page_name(&mut self) -> String {
435    self.unnamed_page_counter += 1;
436    format!("FOO{}", self.unnamed_page_counter)
437  }
438
439  /// A page with no usable `attr` key takes its `xml:id`, and is then named relative to its parent's `xml:id`
440  /// (`Split.pm` L167-171); without one, a generated name.
441  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  /// The pathname for `page`, a child of `parent` written to `parent_path`. A page that would leave the destination's
449  /// directory (an Error, as Perl's site check `Post.pm` L700-704) or take an issued pathname (a Warning) takes its
450  /// fallback name instead (OD #1164).
451  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    // The first pathname refused, the key that named it, and why.
477    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        // Paths relative to the destination's directory, as its pages see them.
501        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            // Perl's `$dir || '.'` (`Post.pm` L697).
516            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  /// The pathname of a page named `name` by `attr` (`Split.pm` L176-191), and whether the name climbs out of its
542  /// parent's folder (a leading `..`). Such a pathname is resolved, lexically (`out/FOO1/../up.html` is
543  /// `out/up.html`): the page's links are made from it.
544  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
572/// `pathname` with its `.` and empty segments dropped and each `name/..` pair collapsed, as [`page_name_segments`],
573/// its leading separators kept: no `~` expansion and no link resolved.
574fn 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
583/// A label as a page name: its path segments as Perl's `pathname_canonical` leaves them (`Pathname.pm` L126-128) — no
584/// empty or `.` segment, a `name/..` pair collapsed (`./x`, `a//b`, `a/../b` are `x`, `a/b`, `b`), a leading `..` kept —
585/// but with no `~` expansion and no root (OD #1164). A name of separators alone is empty, so it takes the unnamed page's
586/// fallback (`Split.pm` L167-175). `\` separates only on Windows.
587pub(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
601/// A relative page name: the name less its parent's and at least one `.`, `_` or `:` after it, Perl's
602/// `/^\Q$pname\E(\.|_|:)+(.*)$/` (`Split.pm` L180-181), as [`page_name_segments`]; `None` keeps the whole name.
603pub(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
610/// Every run of `:` in a page name as one `_`, Perl's `s/:+/_/g` (`Split.pm` L183).
611pub(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
623/// A page's pathname beside its parent's, or (`as_dir`) as `index` in a folder of its name: Perl `Split::getPageName`'s
624/// `pathname_make` (`Split.pm` L185-191) over a name of [`page_name_segments`] (issue 1006, OD #1164).
625pub(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  // The parent's directory as written: the parent is the canonical destination or a page named here, and
636  // canonicalizing it again would expand a label's `~`.
637  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    // Ensure root has an ID (Writer will remove TEMPORARY_DOCUMENT_ID)
656    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    // Filter out the root node itself (Perl: grep { $_->parentNode->parentNode })
665    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    // Save and remove navigation elements
676    let nav_nodes: Vec<Node> = doc.findnodes("descendant::ltx:navigation");
677    // The navs are copied back after the split, so their ancestors are never freed:
678    // a namespace a nav uses may be declared on (or inside) a page.
679    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    // Build the page tree
688    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    // Take doc out so we can pass &PostDocument and &mut tree without borrow conflict
704    let doc_tmp = tree.document.take().unwrap();
705    self.prename_pages(&doc_tmp, &mut tree, &haschildren);
706    tree.document = Some(doc_tmp);
707
708    // Process pages: extract and create sub-documents
709    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    // Restore navigation to all documents
714    if !nav_nodes.is_empty() && !self.no_navigation {
715      // Put doc back into tree for navigation distribution
716      tree.document = Some(doc);
717      Self::add_navigation(&mut tree, &nav_nodes);
718      doc = tree.document.take().unwrap();
719
720      // Also add nav to child docs
721      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
751/// Check if `child` is a descendant of `ancestor`.
752fn 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  /// A label becomes a page name as Perl's `Split::getPageName` and `pathname_canonical` make it (`Split.pm` L180-183,
768  /// `Pathname.pm` L126-128), less the `~` expansion and the root (OD #1164).
769  #[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}