Skip to main content

latexml_post/
extract.rs

1//! Document-subtree extraction helpers — port of `LaTeXML::Util::Pack`'s
2//! `get_math` and `get_embeddable` (Perl Pack.pm L247-313).
3//!
4//! These are the implementations behind the `--whatsout fragment` and
5//! `--whatsout math` CLI modes. They run AFTER all post-processing on
6//! the final XML/HTML document and return the subtree the user actually
7//! wanted (an embeddable inline snippet, or just the math). The
8//! `--whatsout archive` mode keeps the full document (no extraction) but
9//! flags the caller to wrap it into a zip — see [`Whatsout::is_archive`]
10//! and [`crate::pack::pack_archive`].
11//!
12//! Companion modules:
13//! * [`crate::pack`] bundles the chosen output into a zip archive.
14//! * [`crate::writer`] serializes it to a file or stdout.
15//!
16//! ## What's not ported (intentional gaps)
17//!
18//! Perl `get_math` falls through to inline an SVG when the math node's
19//! `imagesrc` ends in `.svg` — for our pipeline the SVG is already a
20//! referenced resource bundled by `pack_archive`, so the inline path
21//! has no caller. Doc string flags the gap so a future visitor knows
22//! it's intentional.
23//!
24//! Perl `get_embeddable` copies namespace declarations and RDFa
25//! attributes from the document root onto the extracted node. libxml-rs
26//! exposes `Node::set_attribute` for the RDFa half cheaply; namespace
27//! re-binding requires FFI into `xmlSetNs` and is deferred (the
28//! extracted subtree usually inherits its namespaces fine as long as
29//! the consumer doesn't re-parse it standalone).
30
31use latexml_core::common::xml::name_is;
32use libxml::tree::Node;
33
34use crate::document::PostDocument;
35
36/// Output extraction mode — port of Perl `LaTeXML::Util::Pack`'s
37/// `whatsout` option (Pack.pm L320-345). Selects which subtree of the
38/// post-processed document to serialize and ship to the user.
39///
40/// * [`Whatsout::Document`] — full document, no extraction (default).
41/// * [`Whatsout::Fragment`] — embeddable HTML snippet via [`get_embeddable`].
42/// * [`Whatsout::Math`] — math subtree (or fallback) via [`get_math`].
43/// * [`Whatsout::Archive`] — full document, but bundled into a zip by [`crate::pack::pack_archive`]
44///   (Pack.pm L326-331 + `Pack/Zip.pm::get_archive`). Extraction is a no-op; the archiving happens
45///   in the binary's output stage.
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub enum Whatsout {
48  #[default]
49  Document,
50  Fragment,
51  Math,
52  Archive,
53}
54
55impl Whatsout {
56  /// Parse a CLI string into the matching variant. Returns `None` for
57  /// unrecognized values; callers typically fall back to `Document`.
58  /// Mirrors Perl `pack_collection`'s string-tag dispatch. Perl matches
59  /// archive with `/^archive/`, so the `archive::zip` /
60  /// `archive::zip::perl` long forms (Pack/Zip.pm L118-122) also map to
61  /// [`Whatsout::Archive`].
62  pub fn from_cli(s: &str) -> Option<Self> {
63    match s {
64      "document" => Some(Whatsout::Document),
65      "fragment" => Some(Whatsout::Fragment),
66      "math" => Some(Whatsout::Math),
67      _ if s.starts_with("archive") => Some(Whatsout::Archive),
68      _ => None,
69    }
70  }
71
72  /// The canonical CLI tag for this variant — round-trips through
73  /// [`Whatsout::from_cli`]. Used to serialize the mode across a process
74  /// boundary (the parallel page-render worker manifest).
75  pub fn as_cli(self) -> &'static str {
76    match self {
77      Whatsout::Document => "document",
78      Whatsout::Fragment => "fragment",
79      Whatsout::Math => "math",
80      Whatsout::Archive => "archive",
81    }
82  }
83
84  /// Whether this mode bundles the output into a zip archive (Perl
85  /// `pack_collection` `whatsout =~ /^archive/`). The binary's output
86  /// stage branches on this to call [`crate::pack::pack_archive`].
87  pub fn is_archive(self) -> bool { matches!(self, Whatsout::Archive) }
88
89  /// Whether selecting this mode forces post-processing. Perl
90  /// `Config.pm` L454: any `whatsout` other than `document` implies
91  /// `post = 1` (fragment/math need the extraction stage; archive needs
92  /// the full post-processed document to bundle).
93  pub fn requires_post(self) -> bool { !matches!(self, Whatsout::Document) }
94}
95
96/// Apply the requested [`Whatsout`] extraction to `doc` and return the
97/// serialized subtree. Returns the full document for
98/// [`Whatsout::Document`] (the default no-op) or when extraction finds
99/// no candidate node.
100///
101/// Wraps the two `get_*` helpers + libxml `node_to_string` so callers
102/// don't have to thread the inner [`libxml::tree::Document`] through.
103pub fn serialize_whatsout(doc: &PostDocument, mode: Whatsout) -> String {
104  match mode {
105    // Archive ships the FULL document; the zip wrapping is a separate
106    // output-stage concern (`pack::pack_archive`), not extraction.
107    Whatsout::Document | Whatsout::Archive => doc.to_xml_string(),
108    Whatsout::Fragment => get_embeddable(doc)
109      .map(|n| doc.get_document().node_to_string(&n))
110      .unwrap_or_else(|| doc.to_xml_string()),
111    Whatsout::Math => get_math(doc)
112      .map(|n| doc.get_document().node_to_string(&n))
113      .unwrap_or_else(|| doc.to_xml_string()),
114  }
115}
116
117/// XPath that matches the `<math>` (HTML5 / MathML) and `<Math>`
118/// (legacy LaTeXML pre-MathML) elements anywhere in the document,
119/// regardless of namespace prefix.
120const MATH_XPATH: &str = "//*[local-name()='math' or local-name()='Math']";
121
122/// XPath for math-as-image fallback: `<img class="ltx_Math …">`.
123const MATH_IMG_XPATH: &str = "//*[local-name()='img' and contains(@class,'ltx_Math')]";
124
125/// XPath for embeddable fragment root: `<div class="ltx_document">`.
126/// Perl literally uses `contains(@class, "ltx_document")` so any
127/// element whose `class` includes the substring matches.
128const EMBEDDABLE_XPATH: &str = "//*[contains(@class,'ltx_document')]";
129
130/// RDFa attributes that Perl `get_embeddable` copies from the document
131/// root onto the extracted node (Perl Pack.pm L309).
132const RDFA_ATTRS: &[&str] = &[
133  "prefix", "property", "content", "resource", "about", "typeof", "rel", "rev", "datatype",
134];
135
136/// Class-name pattern that a single-child `<div>` must match for the
137/// unwrap loop to descend into it. Perl regex `/^ltx_(page_(main|content)|document|para|header)$/`.
138fn is_unwrappable_div_class(class: &str) -> bool {
139  matches!(
140    class,
141    "ltx_page_main" | "ltx_page_content" | "ltx_document" | "ltx_para" | "ltx_header"
142  )
143}
144
145/// Local-name predicate for the "this <p> is purely inline content"
146/// check in `get_embeddable`: child names matching `math|text|span`.
147fn is_inline_child(name: &str) -> bool {
148  // Perl uses `=~ /math|text|span/` (substring match anywhere in the
149  // node name). Match the substring semantics exactly.
150  name.contains("math") || name.contains("text") || name.contains("span")
151}
152
153/// Extract the math subtree(s) from a post-processed document, mirroring
154/// Perl `LaTeXML::Util::Pack::get_math` (Pack.pm L247-280).
155///
156/// * If exactly one `<math>` (or `<Math>`) is present, return it.
157/// * If multiple, return their **least common ancestor** by walking up from the first one until its
158///   descendant-count matches the document's total. Unwraps trailing `<tr>` / `<td>` so the LCA
159///   isn't a table cell.
160/// * If no math nodes at all, fall through to a math-image (`<img class="ltx_Math">`) XPath; if
161///   that's also empty, fall through to [`get_embeddable`] so callers get a useful node either way.
162pub fn get_math(doc: &PostDocument) -> Option<Node> {
163  let math_nodes = doc.findnodes(MATH_XPATH);
164  let math_count = math_nodes.len();
165
166  if math_count == 0 {
167    let img_nodes = doc.findnodes(MATH_IMG_XPATH);
168    if img_nodes.is_empty() {
169      return get_embeddable(doc);
170    }
171    return img_nodes.into_iter().next();
172  }
173
174  let mut math = math_nodes.into_iter().next()?;
175  if math_count > 1 {
176    // Walk up until the subtree under `math` contains every math node.
177    // Perl re-runs the same XPath relative to the current candidate
178    // and adds 1 when the candidate itself is a math node, with
179    // context-scoped XPath (`findnodes_at`).
180    let descendant_math_xpath = format!(".{MATH_XPATH}");
181    let mut found = 0;
182    while found != math_count {
183      found = doc.findnodes_at(&descendant_math_xpath, Some(&math)).len();
184      if math.get_name().eq_ignore_ascii_case("math") {
185        found += 1;
186      }
187      if found != math_count {
188        match math.get_parent() {
189          Some(p) => math = p,
190          None => break,
191        }
192      }
193    }
194    // Don't anchor on a table cell — climb out of `<tr>` / `<td>`
195    // (Perl `while ($math->nodeName =~ '^t[rd]$')`).
196    while is_table_row_or_cell(&math.get_name()) {
197      match math.get_parent() {
198        Some(p) => math = p,
199        None => break,
200      }
201    }
202  }
203
204  Some(math)
205}
206
207/// Extract an embeddable HTML fragment from a post-processed document,
208/// mirroring Perl `LaTeXML::Util::Pack::get_embeddable` (Pack.pm L282-313).
209///
210/// * Find the first `<div class="ltx_document">`.
211/// * Unwrap as long as the current node is a `<div>` with exactly one child, an unwrappable wrapper
212///   class (`ltx_page_main`, `ltx_page_content`, `ltx_document`, `ltx_para`, `ltx_header`), and no
213///   inline `style` attribute.
214/// * If the resulting node is a `<p>` whose every child is inline- compatible (local-name contains
215///   `math` / `text` / `span`), rename it to `<span class="text">` so it stays inline-embeddable.
216/// * Copy RDFa attributes (`prefix`, `property`, `content`, `resource`, `about`, `typeof`, `rel`,
217///   `rev`, `datatype`) from the document root onto the extracted node so the snippet retains its
218///   semantic annotations.
219/// * Namespace declarations from the root are NOT propagated (libxml-rs gap — see module docs).
220///
221/// If no `ltx_document` element is found, returns the document root,
222/// matching Perl's `return $embeddable || $doc`.
223pub fn get_embeddable(doc: &PostDocument) -> Option<Node> {
224  let root = doc.get_document_element()?;
225  let mut embeddable = doc
226    .findnodes(EMBEDDABLE_XPATH)
227    .into_iter()
228    .next()
229    .unwrap_or_else(|| root.clone());
230
231  // Unwrap nested single-child div wrappers.
232  loop {
233    if !name_is(&embeddable, "div") {
234      break;
235    }
236    let children = embeddable.get_child_nodes();
237    if children.len() != 1 {
238      break;
239    }
240    let class = embeddable.get_attribute("class").unwrap_or_default();
241    if !is_unwrappable_div_class(&class) {
242      break;
243    }
244    if embeddable.has_attribute("style") {
245      break;
246    }
247    match embeddable.get_first_child() {
248      Some(c) => embeddable = c,
249      None => break,
250    }
251  }
252
253  // `<p>` with all-inline children → rename to `<span class="text">`.
254  if name_is(&embeddable, "p") {
255    let children = embeddable.get_child_nodes();
256    if !children.is_empty() && children.iter().all(|c| is_inline_child(&c.get_name())) {
257      let _ = embeddable.set_name("span");
258      let _ = embeddable.set_attribute("class", "text");
259    }
260  }
261
262  // Copy RDFa attributes from doc root.
263  for attr in RDFA_ATTRS {
264    if let Some(value) = root.get_attribute(attr) {
265      let _ = embeddable.set_attribute(attr, &value);
266    }
267  }
268
269  Some(embeddable)
270}
271
272fn is_table_row_or_cell(name: &str) -> bool { matches!(name, "tr" | "td" | "TR" | "TD") }
273
274#[cfg(test)]
275mod tests {
276  use super::*;
277  use crate::document::PostDocumentOptions;
278
279  fn doc(xml: &str) -> PostDocument {
280    PostDocument::new_from_string(xml, PostDocumentOptions::default()).expect("parse test fixture")
281  }
282
283  #[test]
284  fn get_embeddable_returns_root_when_no_ltx_document() {
285    let d = doc("<html><body><p>hello</p></body></html>");
286    let node = get_embeddable(&d).expect("some node");
287    assert_eq!(node.get_name(), "html");
288  }
289
290  // Fixtures use compact XML (no inter-element whitespace). libxml
291  // preserves whitespace text nodes as children, which would break
292  // the single-child unwrap check — Perl XML::LibXML behaves the same
293  // way, and real LaTeXML post-processing emits compact HTML by the
294  // time get_embeddable is called.
295
296  #[test]
297  fn get_embeddable_unwraps_single_child_wrappers_to_inline_span() {
298    // ltx_document (1 child div) → ltx_page_main (1 child p) → p
299    // (terminal: not in unwrap-class allowlist). The <p>'s single
300    // child is the text "Hello world" whose node-name is "text"
301    // (matches inline pattern) → final promotion to span.
302    let xml = r#"<html><body><div class="ltx_document"><div class="ltx_page_main"><p>Hello world</p></div></div></body></html>"#;
303    let d = doc(xml);
304    let node = get_embeddable(&d).expect("some node");
305    assert_eq!(node.get_name(), "span");
306    assert_eq!(node.get_attribute("class").as_deref(), Some("text"));
307  }
308
309  #[test]
310  fn get_embeddable_stops_at_multi_child() {
311    // ltx_document has TWO <p> children → unwrap halts; return it as-is.
312    let xml =
313      r#"<html><body><div class="ltx_document"><p>first</p><p>second</p></div></body></html>"#;
314    let d = doc(xml);
315    let node = get_embeddable(&d).expect("some node");
316    assert_eq!(node.get_name(), "div");
317    assert_eq!(node.get_attribute("class").as_deref(), Some("ltx_document"));
318  }
319
320  #[test]
321  fn get_embeddable_keeps_p_when_child_is_non_inline_block() {
322    // Single-child path lands on the <p>; child is a <table>, whose
323    // name doesn't match math|text|span → no promotion to span.
324    let xml = r#"<html><body><div class="ltx_document"><div class="ltx_para"><p><table>x</table></p></div></div></body></html>"#;
325    let d = doc(xml);
326    let node = get_embeddable(&d).expect("some node");
327    assert_eq!(node.get_name(), "p");
328  }
329
330  #[test]
331  fn get_math_returns_lone_math_node() {
332    let xml = r#"<html><body><p>some text</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math></body></html>"#;
333    let d = doc(xml);
334    let node = get_math(&d).expect("some node");
335    assert_eq!(node.get_name(), "math");
336  }
337
338  #[test]
339  fn get_math_returns_lca_for_multiple_math() {
340    let xml = r#"<html><body><div id="container"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>b</mi></math></div></body></html>"#;
341    let d = doc(xml);
342    let node = get_math(&d).expect("some node");
343    // Both math nodes are children of `<div id="container">` — the
344    // LCA should be that div.
345    assert_eq!(node.get_name(), "div");
346    assert_eq!(node.get_attribute("id").as_deref(), Some("container"));
347  }
348
349  #[test]
350  fn get_math_falls_through_to_img_when_no_math_elements() {
351    let xml = r#"<html><body><p>before</p><img class="ltx_Math" alt="x"/></body></html>"#;
352    let d = doc(xml);
353    let node = get_math(&d).expect("some node");
354    assert_eq!(node.get_name(), "img");
355  }
356
357  #[test]
358  fn get_math_falls_through_to_embeddable_when_no_math_at_all() {
359    // No math + no math-img → fall through to get_embeddable. The
360    // embeddable result for a single-text-child <p> is the promoted
361    // <span class="text">.
362    let xml = r#"<html><body><div class="ltx_document"><p>just prose</p></div></body></html>"#;
363    let d = doc(xml);
364    let node = get_math(&d).expect("some node");
365    assert_eq!(node.get_name(), "span");
366  }
367
368  #[test]
369  fn whatsout_from_cli_recognized() {
370    assert_eq!(Whatsout::from_cli("document"), Some(Whatsout::Document));
371    assert_eq!(Whatsout::from_cli("fragment"), Some(Whatsout::Fragment));
372    assert_eq!(Whatsout::from_cli("math"), Some(Whatsout::Math));
373    // `--whatsout=archive` (Perl Pack.pm `pack_collection` `whatsout`
374    // tag): bundle the full document into a zip. The `archive::zip`
375    // / `archive::zip::perl` long forms (Zip.pm L118-122) also count
376    // as archive — Perl matches `/^archive/`.
377    assert_eq!(Whatsout::from_cli("archive"), Some(Whatsout::Archive));
378    assert_eq!(Whatsout::from_cli("archive::zip"), Some(Whatsout::Archive));
379    assert_eq!(Whatsout::from_cli("nonsense"), None);
380  }
381
382  #[test]
383  fn whatsout_default_is_document() {
384    assert_eq!(Whatsout::default(), Whatsout::Document);
385  }
386
387  #[test]
388  fn whatsout_is_archive_predicate() {
389    assert!(Whatsout::Archive.is_archive());
390    assert!(!Whatsout::Document.is_archive());
391    assert!(!Whatsout::Fragment.is_archive());
392    assert!(!Whatsout::Math.is_archive());
393  }
394
395  #[test]
396  fn whatsout_requires_post_for_non_document() {
397    // Perl Config.pm L454: any non-`document` whatsout forces post=1.
398    assert!(!Whatsout::Document.requires_post());
399    assert!(Whatsout::Fragment.requires_post());
400    assert!(Whatsout::Math.requires_post());
401    assert!(Whatsout::Archive.requires_post());
402  }
403
404  #[test]
405  fn serialize_whatsout_archive_returns_full_document() {
406    // Archive bundles the FULL post-processed document into the zip;
407    // the serialized HTML payload is the whole document, identical to
408    // `Whatsout::Document`. The zip wrapping is `pack::pack_archive`'s
409    // job, not extraction's.
410    let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
411    let d = doc(xml);
412    let archive = serialize_whatsout(&d, Whatsout::Archive);
413    let full = serialize_whatsout(&d, Whatsout::Document);
414    assert_eq!(archive, full);
415    assert!(archive.contains("<html>") && archive.contains("</html>"));
416  }
417
418  #[test]
419  fn serialize_whatsout_document_matches_full_xml() {
420    let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
421    let d = doc(xml);
422    let full = serialize_whatsout(&d, Whatsout::Document);
423    assert!(full.contains("<html>") && full.contains("</html>"));
424  }
425
426  #[test]
427  fn serialize_whatsout_fragment_strips_html_wrapper() {
428    let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
429    let d = doc(xml);
430    let frag = serialize_whatsout(&d, Whatsout::Fragment);
431    // Fragment unwraps ltx_document and promotes the lone-text <p>
432    // to <span class="text"> — the result should NOT carry the
433    // <html>/<body> wrapper.
434    assert!(
435      !frag.contains("<html>"),
436      "frag contains html wrapper: {frag}"
437    );
438    assert!(frag.contains("hi"));
439  }
440
441  #[test]
442  fn serialize_whatsout_math_returns_math_subtree() {
443    let xml = r#"<html><body><p>txt</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>z</mi></math></body></html>"#;
444    let d = doc(xml);
445    let m = serialize_whatsout(&d, Whatsout::Math);
446    assert!(m.contains("<mi>z</mi>"));
447    assert!(!m.contains("<html>"), "math contains html wrapper: {m}");
448    assert!(
449      !m.contains("<p>txt</p>"),
450      "math contains unrelated text: {m}"
451    );
452  }
453
454  #[test]
455  fn get_embeddable_copies_rdfa_from_root() {
456    let xml = r#"<html prefix="dc: http://purl.org/dc/terms/" typeof="ScholarlyArticle"><body><div class="ltx_document"><p>text</p></div></body></html>"#;
457    let d = doc(xml);
458    let node = get_embeddable(&d).expect("some node");
459    // Unwrap reaches the <p>, then promotes to <span>; either way
460    // the RDFa attrs should land on the result.
461    assert_eq!(
462      node.get_attribute("prefix").as_deref(),
463      Some("dc: http://purl.org/dc/terms/")
464    );
465    assert_eq!(
466      node.get_attribute("typeof").as_deref(),
467      Some("ScholarlyArticle")
468    );
469  }
470
471  #[test]
472  fn whatsout_cli_tag_round_trips() {
473    for w in [
474      Whatsout::Document,
475      Whatsout::Fragment,
476      Whatsout::Math,
477      Whatsout::Archive,
478    ] {
479      assert_eq!(
480        Whatsout::from_cli(w.as_cli()),
481        Some(w),
482        "as_cli must round-trip through from_cli for {w:?}"
483      );
484    }
485  }
486}