Skip to main content

latexml_core/document/
helpers.rs

1use libxml::tree::Node;
2
3use super::{Document, get_node_qname};
4use crate::common::{error::*, xml::XML_NS};
5
6/// Does an `ltx:para` element immediately precede `node`? Both `prune_empty_para`
7/// (to decide `ltx_pruned_first`) and the first-paragraph `ltx_noindent` stamp
8/// (`tex_paragraph.rs`, OXIDIZED_DESIGN #143) ask this: a paragraph with no
9/// preceding `ltx:para` sibling is the first paragraph of its parent, structurally
10/// — a signal robust to how many stray `\par`s fired before it (which varies by
11/// TeX Live year / dump vs no-dump).
12pub fn preceding_para_sibling(node: &Node) -> bool {
13  node
14    .get_prev_element_sibling()
15    .is_some_and(|prev| is_para(&prev))
16}
17
18/// Is `node` an `ltx:para`, or the streaming placeholder of a run that ends with one?
19pub fn is_para(node: &Node) -> bool {
20  if node.get_name() == "_spilled_" {
21    // Streaming pass 1: earlier siblings were spilled; the placeholder
22    // records the LAST spilled node's qname (see `spill_run`) so this
23    // test matches what the eager walk would have seen.
24    node.get_attribute("last").as_deref() == Some("ltx:para")
25  } else {
26    get_node_qname(node) == crate::pin!("ltx:para")
27  }
28}
29
30/// In some cases we could have e.g. a \noindent followed by a {table},
31/// in which case we end up with an empty ltx:para which we can prune.
32pub fn prune_empty_para(document: &mut Document, node: &mut Node) -> Result<()> {
33  let children = node.get_child_elements();
34  if children.is_empty() {
35    let prev_is_para = preceding_para_sibling(node);
36    if !prev_is_para {
37      // If `node` WAS the 1st child
38      document.add_class(&mut node.get_parent().unwrap(), "ltx_pruned_first")?;
39    }
40    // Decrement the ID counter on the ancestor that generated this node's id,
41    // so that the pruned para's id slot gets reused by the next para.
42    if let Some(id) = node.get_attribute_ns("id", XML_NS) {
43      // Extract the prefix from the id (e.g. "p7" → prefix "p", counter "7")
44      if let Some(pos) = id.rfind('.') {
45        let suffix = &id[pos + 1..];
46        let prefix: String = suffix.chars().take_while(|c| !c.is_ascii_digit()).collect();
47        // Perl `Package.pm:939` — empty prefix uses `_ID_counter_` (single
48        // trailing underscore), not `_ID_counter__`.
49        let ctrkey = if prefix.is_empty() {
50          "_ID_counter_".to_string()
51        } else {
52          format!("_ID_counter_{}_", prefix)
53        };
54        if let Some(mut ancestor) = node.get_parent()
55          && let Some(ctr_str) = ancestor.get_attribute(&ctrkey)
56          && let Ok(ctr) = ctr_str.parse::<u32>()
57          && ctr > 0
58        {
59          ancestor.set_attribute(&ctrkey, &(ctr - 1).to_string())?;
60        }
61      } else {
62        // No dot — top-level id like "p7"
63        let prefix: String = id.chars().take_while(|c| !c.is_ascii_digit()).collect();
64        // Perl `Package.pm:939` — empty prefix uses `_ID_counter_` (single
65        // trailing underscore), not `_ID_counter__`.
66        let ctrkey = if prefix.is_empty() {
67          "_ID_counter_".to_string()
68        } else {
69          format!("_ID_counter_{}_", prefix)
70        };
71        // Find the ancestor with the counter (root element)
72        if let Some(root) = document.get_document().get_root_element() {
73          let mut root = root;
74          if let Some(ctr_str) = root.get_attribute(&ctrkey)
75            && let Ok(ctr) = ctr_str.parse::<u32>()
76            && ctr > 0
77          {
78            root.set_attribute(&ctrkey, &(ctr - 1).to_string())?;
79          }
80        }
81      }
82      document.unrecord_id(&id);
83    }
84    node.unlink();
85  }
86  Ok(())
87}
88
89/// Whether a list (`ltx:itemize`, `ltx:enumerate`, `ltx:description`) or an inline sectional block
90/// (`ltx:inline-sectional-block`) is open between the insertion point and the paragraph (`ltx:para`) that holds it: a
91/// `\par` or a skip there ends no paragraph (`\lx@normal@par`, `\vskip`), since closing that paragraph would end the
92/// list or the block too. Only a list that can auto-close is affected — a `\trivlist`'s (`_autoclose`, latex_constructs
93/// sect06.rs); the others never closed this way. The block is the paragraph-bridged one a sectioning unit opens in a
94/// list item (document.rs `AUTO_OPEN_BRIDGES`, OXIDIZED_DESIGN #189), whose end is the item's or the list's: a blank
95/// line between the `\bibitem`s of a bibliography in it closed the bridge paragraph, the block, its section and the
96/// bibliography, and every later entry was misplaced (1805.06896, 2304.12197, 2307.13461, hep-ex0406049, 0705.0894,
97/// 2511.04367). Perl opens no paragraph above a section, so its `\par` finds none there.
98pub fn list_or_block_open_inside_para(document: &Document) -> bool {
99  let mut node = Some(document.get_node().clone());
100  while let Some(n) = node {
101    let qname = get_node_qname(&n);
102    if qname == crate::pin!("ltx:para") {
103      return false;
104    }
105    if qname == crate::pin!("ltx:itemize")
106      || qname == crate::pin!("ltx:enumerate")
107      || qname == crate::pin!("ltx:description")
108      || qname == crate::pin!("ltx:inline-sectional-block")
109    {
110      return true;
111    }
112    node = n.get_parent();
113  }
114  false
115}