Skip to main content

latexml_post/
stream_split.rs

1//! Streaming split: partition a huge core XML **file** into per-page spill
2//! files without ever building the whole-document DOM.
3//!
4//! The DOM `Split` processor ([`crate::split::Split`], port of Perl
5//! `Post::Split`) needs the entire document parsed first — measured at ~16 GB
6//! for a 614 MB core XML, and past what a 32 GB host can parse at all for the
7//! 131 MB book witness's 2.68 GB core XML (OOM before Split, zero pages
8//! written; laptop UAT 2026-07-31). This module is the
9//! `STREAMING_POST_DESIGN_2026-07-06.md` §3 front-end: a
10//! [`libxml::reader::TextReader`] pull-parse over the file, materializing one
11//! *non-page* subtree at a time, assembling each page's XML as text and
12//! spilling it the moment the page closes. Peak memory is the open ancestor
13//! chain plus one content subtree.
14//!
15//! # Fidelity contract
16//!
17//! The spill files must re-parse into the same per-page DOMs the whole-DOM
18//! pipeline (parse → `Split::process` → per-page spill) produces — the parity
19//! gate is byte-equality of the final rendered pages across the two paths
20//! (guard: `latexml_oxide/tests/118_streaming_split_parity.rs`). Every quirk
21//! of `Split::process_pages` is replicated deliberately:
22//!
23//! * **Run adjacency.** A TOC (`<ltx:TOC><ltx:toclist class="ltx_toclist_X">`)
24//!   is emitted per maximal run of *adjacent* page siblings; ANY intervening
25//!   sibling node — whitespace text included — breaks a run, exactly as the
26//!   `entries[0].node == removed[0]` check does. (`ltx:navigation` siblings do
27//!   NOT break runs: the DOM path excises them before any page surgery.)
28//! * **TOC suppression probe.** A run's TOC is suppressed iff an
29//!   `ltx:TOC[@lists='toc']` (exact match — generated TOCs carry no `lists`)
30//!   already occurs among the parent's descendants *at flush time*, i.e. in
31//!   content preceding the run.
32//! * **`inlist="toc"` propagation** is per *tree level* (all page children of
33//!   one page, across different DOM parents), with the DOM path's substring
34//!   semantics (`inlist.contains("toc")`). It needs lookahead, so the
35//!   attribute is patched into already-written spill files afterwards
36//!   (`Splitter::patch_inlist_toc`).
37//! * **`new_document` template copies**: every page gets the `<?latexml …?>`
38//!   PIs, the document's `ltx:resource` elements, the root's direct
39//!   `ltx:date` children (only when the page has no direct `ltx:date`), the
40//!   root `class` merged into its own — in exactly that order — then the
41//!   saved `ltx:navigation` elements.
42//! * **Inherited attributes** (`xml:lang`, `backgroundcolor`): nearest
43//!   ancestor-or-self value, copied onto each page root.
44//! * **Naming** ports `Split::{presort,prename,get_page_name}` including the
45//!   `FOO{n}` unnamed-page counter and its document-order naming.
46//! * The root page gets `xml:id="TEMPORARY_DOCUMENT_ID"` when it has no id
47//!   (the Writer removes it later), and pre-order spill order is the DOM
48//!   path's docs order (root first, each page before its descendants).
49//!
50//! # Wrapper descent
51//!
52//! A non-page subtree that *contains* page matches (e.g. a back-matter
53//! wrapper holding `ltx:appendix` pages) or `ltx:navigation` elements cannot
54//! be bulk-copied: it is expanded to an owned mini-document
55//! ([`TextReader::expand_to_document`]) and the same split surgery runs on
56//! that DOM — page matches are pre-collected on the intact subtree (the DOM
57//! path evaluates its predicates before any surgery), nested pages are
58//! unlinked and written, TOC elements are inserted in place, and the
59//! remaining shell is serialized into the enclosing page. Detection is a
60//! conservative substring probe (`Splitter::needs_dom_descent`) —
61//! over-triggering costs one expand+copy, never correctness.
62//!
63//! # Out of scope (fail loud, not wrong)
64//!
65//! * Documents whose `ltx` namespace mapping cannot be resolved from the
66//!   declaration stack error out with a pointer to
67//!   `LATEXML_POST_STREAM_SPLIT=0` (the whole-DOM path); the driver takes that
68//!   path itself, with an Info, for an input under 1 GiB.
69//! * `ltx:resource`, root `ltx:date` and `ltx:navigation` elements and
70//!   `<?latexml?>` PIs first appearing *after* a page has been written cannot
71//!   retroactively reach it (the DOM path copies them into every page). With
72//!   `late_template_fails` the split then fails, so the driver can take the
73//!   whole-DOM path; without it a `Warn` flags the case. A navigation inside a
74//!   page arrives late (navigation reaches post only from `--input xml`;
75//!   guard `112_fragment_yield::split_keeps_pages_whose_namespaces_a_navigation_uses`).
76//!   An `ltx:resource` nested inside content never reaches the templates,
77//!   early or late; it is handled the same way.
78
79use std::{
80  io::Write,
81  path::{Path, PathBuf},
82};
83
84use latexml_core::common::xml::name_is;
85use libxml::{
86  reader::{ReaderEvent, TextReader},
87  tree::{Document, Namespace, Node, NodeType},
88};
89use rustc_hash::{FxHashMap as HashMap, FxHashSet};
90
91use crate::{
92  document::{LTX_NSURI, SplitArm, SplitCond, collect_split_pages, is_ltx, parse_split_union},
93  split::{PageKeys, PageNamer, SplitNaming},
94};
95
96/// One spilled page, in pre-order (index 0 is the root page).
97pub struct StreamedSplitPage {
98  /// Spill file holding the page's XML.
99  pub path:        PathBuf,
100  /// The page's destination pathname (`Split::get_page_name` result; the
101  /// original `--dest` for the root page).
102  pub destination: String,
103  /// The id of the enclosing page (Perl Split's `upid`, the `parent_id` Scan files the page
104  /// under); `None` for the root page.
105  pub parent_id:   Option<String>,
106}
107
108/// Result of a successful streaming split.
109pub struct StreamSplitOutcome {
110  /// Pages in pre-order; `[0]` is the root page.
111  pub pages:       Vec<StreamedSplitPage>,
112  /// Bodies of every `<?latexml …?>` PI (for the ar5iv literal-intent sniff).
113  pub latexml_pis: Vec<String>,
114}
115
116/// Can this `--splitpath` union be evaluated by the streaming split? (The
117/// `make_splitpaths` grammar parses; a custom hand-written XPath may not.)
118/// The driver gates on this so a genuine mid-stream failure can be told apart
119/// from "not applicable".
120pub fn supports_union(union_xpath: &str) -> bool { parse_split_union(union_xpath).is_some() }
121
122/// Split a core-XML file into per-page spill files, streaming.
123///
124/// Returns `Ok(None)` when the union selected no pages (the "\[not split\]"
125/// case) — the caller should use the whole-DOM pipeline. `Err` means the
126/// stream could not be processed faithfully (malformed XML, unresolvable
127/// namespace shape, I/O failure); the caller decides whether to fall back.
128pub fn stream_split(
129  source_path: &str,
130  union_xpath: &str,
131  naming: SplitNaming,
132  destination: Option<&str>,
133  spill_dir: &Path,
134  late_template_fails: bool,
135) -> Result<Option<StreamSplitOutcome>, String> {
136  let arms = parse_split_union(union_xpath)
137    .ok_or_else(|| format!("split union not streamable: {union_xpath}"))?;
138  // Leniency flags as in `XmlParser::default().parse_file` (recover + noerror
139  // + nowarning), PLUS `huge`: without XML_PARSE_HUGE, libxml2's hard limits
140  // corrupt a multi-GB parse long before any real malformation — measured on
141  // the 131 MB witness's 2.68 GB core XML, the per-document dictionary cap
142  // poisons the ID table from ~1.47 GB on (237,732 bogus "ID X already
143  // defined" reports for ids that each occur exactly once) and the parse
144  // dies outright at ~1.71 GB ("outer_xml failed mid-stream", same byte in
145  // every run). `xmllint --stream` reproduces both; `--huge` clears both.
146  const OPTIONS: i32 = 1 /* recover */ + 32 /* noerror */ + 64 /* nowarning */
147    + 524_288 /* huge */;
148  let reader = TextReader::from_file(source_path, OPTIONS)
149    .map_err(|()| format!("cannot open '{source_path}' for streaming"))?;
150  let mut splitter = Splitter::new(arms, naming, destination, spill_dir);
151  splitter.late_template_fails = late_template_fails;
152  splitter.run(reader)?;
153  if splitter.has_dtd {
154    // (row DTDENT: `PostDocument::new_from_file` expands the entities a page spill would lose)
155    Info!(
156      "split",
157      "dtd",
158      "a DTD-bearing input is split on the whole-DOM path"
159    );
160    return Ok(None);
161  }
162  if late_template_fails && let Some(why) = splitter.late_template {
163    return Err(format!("{why}; the staged pages would not carry it"));
164  }
165  if splitter.metas.len() <= 1 {
166    // No page matched: mirror the DOM path's `[not split]` outcome and let
167    // the caller run the ordinary pipeline (the root spill alone would be a
168    // needless re-serialization of the whole document).
169    Info!("split", "result", "[not split]");
170    for meta in &splitter.metas {
171      let _ = std::fs::remove_file(&meta.file);
172    }
173    return Ok(None);
174  }
175  splitter.prename();
176  splitter.patch_inlist_toc()?;
177  let n = splitter.metas.len();
178  Info!("split", "result", " [Split into {} pages]", n);
179  let Splitter { metas, latexml_pis, .. } = splitter;
180  let mut parent_ids = vec![None; metas.len()];
181  for meta in &metas {
182    for &child in &meta.children {
183      parent_ids[child] = meta.xml_id.clone();
184    }
185  }
186  let pages = metas
187    .into_iter()
188    .zip(parent_ids)
189    .map(|(m, parent_id)| StreamedSplitPage {
190      path: m.file,
191      destination: m.name,
192      parent_id,
193    })
194    .collect();
195  Ok(Some(StreamSplitOutcome { pages, latexml_pis }))
196}
197
198/// Metadata for one page, mirroring `Split`'s `PageEntry` plus what the
199/// deferred naming/patching passes need.
200struct PageMeta {
201  /// Spill file (named by pre-order index at creation).
202  file:           PathBuf,
203  /// Tree children (pages whose nearest enclosing page is this one), in
204  /// document order.
205  children:       Vec<usize>,
206  localname:      String,
207  xml_id:         Option<String>,
208  labels:         Option<String>,
209  inlist:         Option<String>,
210  /// The root `class` was *appended* as a new attribute (rather than merged
211  /// into an existing one) — the `inlist="toc"` patch must insert *before*
212  /// it to reproduce the DOM path's attribute order (inherit → inlist →
213  /// class).
214  class_appended: bool,
215  /// Destination pathname; filled by [`Splitter::prename`].
216  name:           String,
217}
218
219/// One open level of the stream: the root document element or an open page.
220/// (Wrappers never open a reader level — they are handled wholesale by the
221/// DOM descent.)
222struct Level {
223  kind:            LevelKind,
224  localname:       String,
225  ltx:             bool,
226  /// Serialized children accumulated so far (after the open tag).
227  content:         String,
228  /// `ltx:` element-children localnames seen so far — the streaming
229  /// evaluation of the `preceding-sibling::ltx:NAME` split predicate.
230  seen_ltx:        FxHashSet<String>,
231  /// The `xml:id`s of the current adjacent page run (a tocentry each).
232  run_toc:         Vec<String>,
233  run_active:      bool,
234  /// An `ltx:TOC[@lists='toc']` occurs among this element's descendants
235  /// streamed so far (the TOC-suppression probe).
236  has_lists_toc:   bool,
237  /// A direct `ltx:date` child was appended (suppresses the date copy).
238  has_direct_date: bool,
239  /// `(qname, value)` attributes from the source, document order.
240  attrs:           Vec<(String, String)>,
241  /// Effective inherited `xml:lang` / `backgroundcolor` (self-or-ancestor).
242  lang:            Option<String>,
243  bg:              Option<String>,
244  /// prefix → namespace-URI declarations introduced ON this element
245  /// (`""` = default).
246  ns_decls:        Vec<(String, String)>,
247}
248
249enum LevelKind {
250  Root,
251  /// Index into [`Splitter::metas`].
252  Page(usize),
253}
254
255struct Splitter {
256  arms:                Vec<SplitArm>,
257  /// Names the pages, as `Split` does.
258  namer:               PageNamer,
259  root_destination:    String,
260  spill_dir:           PathBuf,
261  levels:              Vec<Level>,
262  metas:               Vec<PageMeta>,
263  /// The root spill's prolog: pre-root PIs/comments, reconstructed verbatim.
264  root_prolog:         String,
265  /// Root page trailing misc (post-root comments/PIs).
266  root_tail:           String,
267  /// `<?latexml …?>` bodies, document order (ar5iv sniff + page templates).
268  latexml_pis:         Vec<String>,
269  /// Serialized `ltx:resource` elements (page template).
270  resources_xml:       Vec<String>,
271  /// Serialized root-direct `ltx:date` elements (page template).
272  dates_xml:           Vec<String>,
273  /// Serialized `ltx:navigation` elements, excised from content.
274  navs_xml:            Vec<String>,
275  /// Root element `class` attribute (merged into every page).
276  root_class:          Option<String>,
277  /// Concatenated `ltx:picture` serializations for SVG extraction.
278  first_page_spilled:  bool,
279  warned_late:         bool,
280  /// Why the staged pages miss a template item: the first one met after a
281  /// page was written, or a nested `ltx:resource`.
282  late_template:       Option<String>,
283  /// Fail on a late template instead of warning (see the module doc).
284  late_template_fails: bool,
285  /// The input has a DTD: its entity references are expanded by the whole-DOM parse only.
286  has_dtd:             bool,
287}
288
289impl Splitter {
290  fn new(
291    arms: Vec<SplitArm>,
292    naming: SplitNaming,
293    destination: Option<&str>,
294    spill_dir: &Path,
295  ) -> Self {
296    Splitter {
297      arms,
298      namer: PageNamer::new(naming),
299      root_destination: destination.unwrap_or("").to_string(),
300      spill_dir: spill_dir.to_path_buf(),
301      levels: Vec::new(),
302      metas: Vec::new(),
303      root_prolog: String::new(),
304      root_tail: String::new(),
305      latexml_pis: Vec::new(),
306      resources_xml: Vec::new(),
307      dates_xml: Vec::new(),
308      navs_xml: Vec::new(),
309      root_class: None,
310      first_page_spilled: false,
311      warned_late: false,
312      late_template: None,
313      late_template_fails: false,
314      has_dtd: false,
315    }
316  }
317
318  // ====================================================================
319  // Reader-level pump
320
321  fn run(&mut self, mut reader: TextReader) -> Result<(), String> {
322    let mut advanced = reader.read().map_err(|()| "XML parse error".to_string())?;
323    while advanced {
324      // A late template item dooms the stream to the whole-DOM split: stop spilling pages for it.
325      if self.late_template_fails && self.late_template.is_some() {
326        return Ok(());
327      }
328      match reader.event() {
329        ReaderEvent::Element => {
330          let localname = reader.local_name().unwrap_or_default();
331          let ns = reader.namespace_uri();
332          let ltx = ns.as_deref() == Some(LTX_NSURI);
333          let empty = reader.is_empty_element();
334          if self.levels.is_empty() {
335            if !self.metas.is_empty() {
336              // A second top-level element (recover-mode oddity): opening a
337              // "root" again would clobber the root spill's slot. Fail loud.
338              return Err("multiple root elements in stream".to_string());
339            }
340            // The root element (a root matching a split arm is NOT a page:
341            // the DOM path filters pages to those with a grandparent).
342            let attrs = reader.attributes_qname();
343            self.open_root(localname, ltx, attrs);
344            if empty {
345              self.close_top()?;
346            }
347          } else if ltx && self.is_page_here(&localname) {
348            let attrs = reader.attributes_qname();
349            self.open_page(localname, attrs);
350            if empty {
351              self.close_top()?;
352            }
353          } else {
354            self.top().seen_ltx_insert(ltx, &localname);
355            let outer = reader
356              .outer_xml()
357              .ok_or_else(|| "outer_xml failed mid-stream".to_string())?;
358            if ltx && localname == "navigation" {
359              // Excised BEFORE page surgery in the DOM path — deliberately
360              // does not break a page run.
361              self.warn_if_late("an ltx:navigation");
362              self.navs_xml.push(outer);
363            } else if self.needs_dom_descent(&outer) {
364              // A wrapper: its non-page content never reaches `append_bulk`.
365              self.probe_nested_resource(&outer);
366              let mut minidoc = reader
367                .expand_to_document()
368                .ok_or_else(|| "expand_to_document failed mid-stream".to_string())?;
369              self.descend_wrapper(&mut minidoc)?;
370            } else {
371              self.append_bulk(&outer, &localname, ltx);
372            }
373            // Skip the subtree; the reader is then positioned on the next
374            // event, so bypass the trailing read().
375            advanced = reader
376              .read_next()
377              .map_err(|()| "XML parse error".to_string())?;
378            continue;
379          }
380        },
381        ReaderEvent::EndElement => {
382          self.close_top()?;
383        },
384        ReaderEvent::Text
385        | ReaderEvent::SignificantWhitespace
386        | ReaderEvent::Whitespace
387        | ReaderEvent::CData => {
388          // CDATA is normalized to an escaped text node (identical parsed
389          // content; core XML carries no CDATA).
390          if !self.levels.is_empty() {
391            let text = reader.value().unwrap_or_default();
392            self.flush_run();
393            self.top().content.push_str(&text_escape(&text));
394          }
395          // Pre/post-root whitespace is layout-only; dropped.
396        },
397        ReaderEvent::Comment => {
398          let text = reader.value().unwrap_or_default();
399          let serialized = format!("<!--{text}-->");
400          self.append_misc(serialized);
401        },
402        ReaderEvent::ProcessingInstruction => {
403          let target = reader.local_name().unwrap_or_default();
404          let body = reader.value().unwrap_or_default();
405          let serialized = if body.is_empty() {
406            format!("<?{target}?>")
407          } else {
408            format!("<?{target} {body}?>")
409          };
410          if target == "latexml" {
411            self.template_pi(body);
412          }
413          self.append_misc(serialized);
414        },
415        ReaderEvent::DocumentType => {
416          self.has_dtd = true;
417          return Ok(());
418        },
419        ReaderEvent::EntityReference => {
420          return Err("unexpected unresolved entity reference in stream".to_string());
421        },
422        _ => {},
423      }
424      advanced = reader.read().map_err(|()| "XML parse error".to_string())?;
425    }
426    if !self.levels.is_empty() {
427      return Err("premature end of input (unclosed elements)".to_string());
428    }
429    if self.metas.is_empty() {
430      return Err("no root element found".to_string());
431    }
432    Ok(())
433  }
434
435  /// A comment/PI: into the current level's content, the pre-root prolog, or
436  /// the post-root tail.
437  fn append_misc(&mut self, serialized: String) {
438    if self.levels.is_empty() {
439      if self.metas.is_empty() {
440        self.root_prolog.push_str(&serialized);
441        self.root_prolog.push('\n');
442      } else {
443        self.root_tail.push_str(&serialized);
444        self.root_tail.push('\n');
445      }
446    } else {
447      self.flush_run();
448      self.top().content.push_str(&serialized);
449    }
450  }
451
452  /// Record a `<?latexml …?>` PI body for the page template + ar5iv sniff,
453  /// warning once if it arrives after a page has already been written.
454  fn template_pi(&mut self, body: String) {
455    self.warn_if_late("a <?latexml?> PI");
456    self.latexml_pis.push(body);
457  }
458
459  fn warn_if_late(&mut self, what: &'static str) {
460    if self.first_page_spilled && self.late_template.is_none() {
461      self.late_template = Some(format!("{what} appeared after the first page was written"));
462    }
463    if self.first_page_spilled && !self.late_template_fails && !self.warned_late {
464      self.warned_late = true;
465      Warn!(
466        "split",
467        "stream",
468        "{} appeared after the first page was written; already-staged pages do not carry it",
469        what
470      );
471    }
472  }
473
474  // ====================================================================
475  // Level operations
476
477  fn top(&mut self) -> &mut Level {
478    self
479      .levels
480      .last_mut()
481      .expect("level stack must be non-empty")
482  }
483
484  /// Streaming evaluation of the split union for an `ltx:` element opening
485  /// as a direct child of the current top level. Sibling/parent state is the
486  /// *intact* document's (extracted pages remain in `seen_ltx`), matching
487  /// the DOM path's evaluate-before-surgery order.
488  fn is_page_here(&self, localname: &str) -> bool {
489    let parent = self.levels.last().expect("checked non-empty");
490    self.arms.iter().any(|arm| {
491      arm.element == localname
492        && (arm.any_of.is_empty()
493          || arm.any_of.iter().any(|cond| match cond {
494            SplitCond::PrecedingSibling(name) => parent.seen_ltx.contains(name),
495            SplitCond::Parent(name) => parent.ltx && parent.localname == *name,
496          }))
497    })
498  }
499
500  fn open_root(&mut self, localname: String, ltx: bool, attrs: Vec<(String, String)>) {
501    self.root_class = attr_value(&attrs, "class");
502    let lang = attr_value(&attrs, "xml:lang");
503    let bg = attr_value(&attrs, "backgroundcolor");
504    let ns_decls = decl_attrs(&attrs);
505    self.metas.push(PageMeta {
506      file:           self.spill_dir.join("page-0000000.xml"),
507      children:       Vec::new(),
508      localname:      localname.clone(),
509      xml_id:         attr_value(&attrs, "xml:id"),
510      labels:         attr_value(&attrs, "labels"),
511      inlist:         attr_value(&attrs, "inlist"),
512      class_appended: false,
513      name:           self.root_destination.clone(),
514    });
515    self.levels.push(Level {
516      kind: LevelKind::Root,
517      localname,
518      ltx,
519      content: String::new(),
520      seen_ltx: FxHashSet::default(),
521      run_toc: Vec::new(),
522      run_active: false,
523      has_lists_toc: false,
524      has_direct_date: false,
525      attrs,
526      lang,
527      bg,
528      ns_decls,
529    });
530  }
531
532  fn open_page(&mut self, localname: String, attrs: Vec<(String, String)>) {
533    let parent_level = self.levels.last().expect("page under an open level");
534    let parent_meta = match parent_level.kind {
535      LevelKind::Root => 0,
536      LevelKind::Page(i) => i,
537    };
538    let lang = attr_value(&attrs, "xml:lang").or_else(|| parent_level.lang.clone());
539    let bg = attr_value(&attrs, "backgroundcolor").or_else(|| parent_level.bg.clone());
540    let idx = self.metas.len();
541    let xml_id = attr_value(&attrs, "xml:id");
542    if let Some(id) = xml_id.clone() {
543      self.top().run_toc.push(id);
544    }
545    self.top().run_active = true;
546    self.top().seen_ltx_insert(true, &localname);
547    self.metas.push(PageMeta {
548      file: self.spill_dir.join(format!("page-{idx:07}.xml")),
549      children: Vec::new(),
550      localname: localname.clone(),
551      xml_id,
552      labels: attr_value(&attrs, "labels"),
553      inlist: attr_value(&attrs, "inlist"),
554      class_appended: false,
555      name: String::new(),
556    });
557    self.metas[parent_meta].children.push(idx);
558    let ns_decls = decl_attrs(&attrs);
559    self.levels.push(Level {
560      kind: LevelKind::Page(idx),
561      localname,
562      ltx: true,
563      content: String::new(),
564      seen_ltx: FxHashSet::default(),
565      run_toc: Vec::new(),
566      run_active: false,
567      has_lists_toc: false,
568      has_direct_date: false,
569      attrs,
570      lang,
571      bg,
572      ns_decls,
573    });
574  }
575
576  /// Close the current level: flush its trailing run and write its spill.
577  fn close_top(&mut self) -> Result<(), String> {
578    self.flush_run();
579    let level = self.levels.pop().expect("close without an open level");
580    match level.kind {
581      LevelKind::Root => self.write_root_spill(level),
582      LevelKind::Page(idx) => self.write_page_spill(level, idx),
583    }
584  }
585
586  /// A non-page, non-wrapper subtree: append its serialization to the
587  /// current level's content, with the shared bookkeeping.
588  fn append_bulk(&mut self, outer: &str, localname: &str, ltx: bool) {
589    self.flush_run();
590    if ltx && localname == "date" {
591      if matches!(self.levels.last().map(|l| &l.kind), Some(LevelKind::Root)) {
592        self.warn_if_late("an ltx:date");
593        self.dates_xml.push(outer.to_string());
594      }
595      self.top().has_direct_date = true;
596    }
597    let is_resource = ltx && localname == "resource";
598    if is_resource {
599      self.warn_if_late("an ltx:resource");
600      self.resources_xml.push(outer.to_string());
601    }
602    self.bulk_probes(outer, is_resource);
603    self.top().content.push_str(outer);
604  }
605
606  /// Content probes shared by every bulk append: the TOC-suppression flag,
607  /// picture collection for SVG extraction, embedded `<?latexml?>` PI
608  /// bodies, and the nested-resource probe.
609  fn bulk_probes(&mut self, outer: &str, expected_resource: bool) {
610    if probe_lists_toc(outer) {
611      self.top().has_lists_toc = true;
612    }
613    // `expected_resource`: the subtree IS a direct-child ltx:resource that
614    // append_bulk already collected — its own serialization must not trip the
615    // nested-resource flag.
616    if !expected_resource {
617      self.probe_nested_resource(outer);
618    }
619    if outer.contains("<?latexml") {
620      for body in extract_pi_bodies(outer) {
621        self.latexml_pis.push(body);
622      }
623    }
624  }
625
626  /// An `ltx:resource` inside `outer`, a content subtree: the DOM split copies
627  /// every `//ltx:resource` into the page templates (Perl Post.pm L770-771,
628  /// `PostDocument::new_document`); the stream collects only the root's direct
629  /// ones.
630  fn probe_nested_resource(&mut self, outer: &str) {
631    if !contains_element_probe(outer, "resource") {
632      return;
633    }
634    if self.late_template_fails {
635      if self.late_template.is_none() {
636        self.late_template = Some("a nested ltx:resource is not in the page templates".into());
637      }
638    } else if !self.warned_late {
639      self.warned_late = true;
640      Warn!(
641        "split",
642        "stream",
643        "an ltx:resource nested inside content is not propagated to page templates by the streaming split"
644      );
645    }
646  }
647
648  /// Flush the current adjacent-page run: emit its TOC (unless the
649  /// suppression probe fired) at the current content position.
650  fn flush_run(&mut self) {
651    let level = self.top();
652    if !level.run_active {
653      return;
654    }
655    level.run_active = false;
656    if level.run_toc.is_empty() {
657      return;
658    }
659    let entries = std::mem::take(&mut level.run_toc);
660    if level.has_lists_toc {
661      return;
662    }
663    let parent_type = level.localname.clone();
664    let toc = self.toc_xml(&parent_type, &entries);
665    self.top().content.push_str(&toc);
666  }
667
668  fn toc_xml(&self, parent_type: &str, ids: &[String]) -> String {
669    let te = self.ltx_qname("tocentry");
670    let re = self.ltx_qname("ref");
671    let entries: String = ids
672      .iter()
673      .map(|id| {
674        format!(
675          "<{te}><{re} idref=\"{id}\" show=\"toctitle\"/></{te}>",
676          id = attr_escape(id)
677        )
678      })
679      .collect();
680    format!(
681      "<{toc}><{list} class=\"ltx_toclist_{ptype}\">{entries}</{list}></{toc}>",
682      toc = self.ltx_qname("TOC"),
683      list = self.ltx_qname("toclist"),
684      ptype = attr_escape(parent_type),
685    )
686  }
687
688  // ====================================================================
689  // Spill assembly
690
691  /// The serialized qname for an `ltx:` element in this document's
692  /// vocabulary (empty prefix when ltx is the default namespace — the
693  /// standard core-XML shape).
694  fn ltx_qname(&self, localname: &str) -> String {
695    for level in &self.levels {
696      for (prefix, uri) in &level.ns_decls {
697        if uri == LTX_NSURI {
698          return if prefix.is_empty() {
699            localname.to_string()
700          } else {
701            format!("{prefix}:{localname}")
702          };
703        }
704      }
705    }
706    localname.to_string()
707  }
708
709  /// The qname for a level's own element, resolved against its declarations
710  /// plus the enclosing stack.
711  fn qname_for(&self, level: &Level) -> String {
712    if level.ltx {
713      for (p, u) in decl_attrs(&level.attrs) {
714        if u == LTX_NSURI {
715          return if p.is_empty() {
716            level.localname.clone()
717          } else {
718            format!("{}:{}", p, level.localname)
719          };
720        }
721      }
722      self.ltx_qname(&level.localname)
723    } else {
724      // Non-ltx roots keep their serialized shape via their own attrs; pages
725      // are always ltx (the split union is ltx-only).
726      level.localname.clone()
727    }
728  }
729
730  /// The namespace declarations in scope from the OPEN levels (root first),
731  /// first declaration per prefix winning — what a standalone page file must
732  /// re-declare for its content to re-parse identically.
733  fn enclosing_decls(&self) -> Vec<(String, String)> {
734    let mut decls: Vec<(String, String)> = Vec::new();
735    for lvl in &self.levels {
736      for (p, u) in &lvl.ns_decls {
737        if !decls.iter().any(|(dp, _)| dp == p) {
738          decls.push((p.clone(), u.clone()));
739        }
740      }
741    }
742    decls
743  }
744
745  fn write_page_spill(&mut self, level: Level, idx: usize) -> Result<(), String> {
746    let mut attrs = level.attrs.clone();
747    // Inherited attributes: nearest ancestor-or-self, appended when absent
748    // (the DOM path's `set_attribute` appends), xml:lang before
749    // backgroundcolor.
750    if attr_value(&attrs, "xml:lang").is_none()
751      && let Some(lang) = &level.lang
752    {
753      attrs.push(("xml:lang".to_string(), lang.clone()));
754    }
755    if attr_value(&attrs, "backgroundcolor").is_none()
756      && let Some(bg) = &level.bg
757    {
758      attrs.push(("backgroundcolor".to_string(), bg.clone()));
759    }
760    // Root class merge (Perl Post.pm L779-782 via `new_document`).
761    let mut class_appended = false;
762    if let Some(pclass) = &self.root_class {
763      match attrs.iter_mut().find(|(k, _)| k == "class") {
764        Some((_, existing)) if !existing.is_empty() => {
765          existing.push(' ');
766          existing.push_str(pclass);
767        },
768        Some((_, existing)) => *existing = pclass.clone(),
769        None => {
770          attrs.push(("class".to_string(), pclass.clone()));
771          class_appended = true;
772        },
773      }
774    }
775    self.metas[idx].class_appended = class_appended;
776    // The standalone page file must re-declare every namespace its content
777    // may reference: the enclosing declarations (root + open ancestors) the
778    // element does not redeclare itself.
779    let mut decls = self.enclosing_decls();
780    let own_decls = decl_attrs(&level.attrs);
781    decls.retain(|(p, _)| !own_decls.iter().any(|(op, _)| op == p));
782    let qname = self.qname_for(&level);
783    let mut content = level.content;
784    // `new_document` template: resources, then dates (when the page has no
785    // direct `ltx:date` child), then the saved navigation. Class was merged
786    // above; PIs go in the prolog.
787    for r in &self.resources_xml {
788      content.push_str(r);
789    }
790    if !level.has_direct_date {
791      for d in &self.dates_xml {
792        content.push_str(d);
793      }
794    }
795    for nav in &self.navs_xml {
796      content.push_str(nav);
797    }
798    let mut tag = String::with_capacity(qname.len() + 64);
799    tag.push('<');
800    tag.push_str(&qname);
801    for (p, u) in &decls {
802      if p.is_empty() {
803        tag.push_str(&format!(" xmlns=\"{}\"", attr_escape(u)));
804      } else {
805        tag.push_str(&format!(" xmlns:{}=\"{}\"", p, attr_escape(u)));
806      }
807    }
808    for (k, v) in &attrs {
809      tag.push_str(&format!(" {}=\"{}\"", k, attr_escape(v)));
810    }
811    let out = assemble_spill(&self.spill_prolog(), &tag, &qname, &content, "");
812    write_spill(&self.metas[idx].file, &out)?;
813    self.first_page_spilled = true;
814    Ok(())
815  }
816
817  fn write_root_spill(&mut self, level: Level) -> Result<(), String> {
818    let mut attrs = level.attrs.clone();
819    // `Split::process`: the root gets a placeholder id (the Writer removes
820    // it from the final output).
821    if attr_value(&attrs, "xml:id").is_none() {
822      attrs.push(("xml:id".to_string(), "TEMPORARY_DOCUMENT_ID".to_string()));
823      self.metas[0].xml_id = Some("TEMPORARY_DOCUMENT_ID".to_string());
824    }
825    let qname = self.qname_for(&level);
826    let mut content = level.content;
827    for nav in &self.navs_xml {
828      content.push_str(nav);
829    }
830    let mut tag = String::with_capacity(128);
831    tag.push('<');
832    tag.push_str(&qname);
833    for (k, v) in &attrs {
834      tag.push_str(&format!(" {}=\"{}\"", k, attr_escape(v)));
835    }
836    let prolog = format!(
837      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
838      self.root_prolog
839    );
840    let out = assemble_spill(&prolog, &tag, &qname, &content, &self.root_tail);
841    write_spill(&self.metas[0].file, &out)
842  }
843
844  /// The prolog every non-root page file starts with: XML declaration plus
845  /// the `<?latexml …?>` template PIs.
846  fn spill_prolog(&self) -> String {
847    let mut prolog = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
848    for body in &self.latexml_pis {
849      prolog.push_str(&format!("<?latexml {body}?>\n"));
850    }
851    prolog
852  }
853
854  // ====================================================================
855  // DOM descent (wrapper subtrees)
856
857  /// Conservative probe: does this serialized subtree contain anything that
858  /// requires real DOM surgery (a potential page match, or an
859  /// `ltx:navigation` to excise)? Over-triggering costs one expand+copy, not
860  /// correctness.
861  fn needs_dom_descent(&self, outer: &str) -> bool {
862    if contains_element_probe(outer, "navigation") {
863      return true;
864    }
865    self
866      .arms
867      .iter()
868      .any(|arm| contains_element_probe(outer, &arm.element))
869  }
870
871  /// Run the split surgery on an owned mini-document (a wrapper subtree):
872  /// excise `ltx:navigation`, pre-collect page matches on the intact tree
873  /// (the DOM path evaluates its predicates before any surgery), extract
874  /// them (writing their spills, TOCs inserted in place), then serialize the
875  /// remaining shell into the current level's content.
876  fn descend_wrapper(&mut self, minidoc: &mut Document) -> Result<(), String> {
877    let root = minidoc
878      .get_root_element()
879      .ok_or_else(|| "wrapper mini-document has no root".to_string())?;
880    // Navigation excision first, exactly as `Split::process` removes
881    // `descendant::ltx:navigation` before page surgery.
882    let mut navs: Vec<Node> = Vec::new();
883    collect_ltx_descendants(&root, "navigation", &mut navs);
884    for nav in &mut navs {
885      let s = minidoc.node_to_string(nav);
886      nav.unlink_node();
887      self.warn_if_late("an ltx:navigation");
888      self.navs_xml.push(s);
889    }
890    // Pre-collect page matches on the intact (nav-free) tree.
891    let mut page_nodes: Vec<Node> = Vec::new();
892    collect_split_pages(&root, &self.arms, &mut page_nodes);
893    let parent_level = self.levels.last().expect("wrapper under an open level");
894    let (lang, bg) = (parent_level.lang.clone(), parent_level.bg.clone());
895    self.descend_element(minidoc, &root, &page_nodes, lang, bg)?;
896    // The remaining shell (with TOCs in place of extracted runs) is ordinary
897    // content of the current level. Do NOT re-run the picture/PI probes —
898    // the per-child descent already collected them; only the enclosing
899    // TOC-suppression flag needs the shell.
900    let shell = minidoc.node_to_string(&root);
901    self.flush_run();
902    if probe_lists_toc(&shell) {
903      self.top().has_lists_toc = true;
904    }
905    self.top().content.push_str(&shell);
906    Ok(())
907  }
908
909  /// The DOM flavor of the reader pump: iterate `node`'s children, extract
910  /// page children (and their descendants), insert run TOCs in place.
911  /// `lang`/`bg` are the effective inherited attributes *above* `node`.
912  fn descend_element(
913    &mut self,
914    doc: &Document,
915    node: &Node,
916    page_nodes: &[Node],
917    lang: Option<String>,
918    bg: Option<String>,
919  ) -> Result<(), String> {
920    let lang = xml_ns_attr(node, "lang").or(lang);
921    let bg = node.get_attribute("backgroundcolor").or(bg);
922    let mut run_toc: Vec<String> = Vec::new();
923    let mut run_active = false;
924    // Incremental suppression probe: only content BEFORE a run counts, as in
925    // the DOM path (following siblings are unlinked before its probe runs).
926    let mut has_lists_toc = false;
927    let node_name = node.get_name();
928    let mut child_opt = node.get_first_child();
929    while let Some(child) = child_opt {
930      let next = child.get_next_sibling();
931      let is_page_child =
932        child.get_type() == Some(NodeType::ElementNode) && page_nodes.contains(&child);
933      if is_page_child {
934        run_active = true;
935        self.dom_extract_page(
936          doc,
937          &child,
938          page_nodes,
939          lang.clone(),
940          bg.clone(),
941          &mut run_toc,
942        )?;
943        let mut extracted = child;
944        extracted.unlink_node();
945      } else {
946        // Any other sibling breaks the run: flush its TOC *before* this
947        // child.
948        if run_active {
949          run_active = false;
950          if !run_toc.is_empty() && !has_lists_toc {
951            let entries = std::mem::take(&mut run_toc);
952            self.dom_insert_toc(doc, node, Some(&child), &node_name, &entries)?;
953          }
954          run_toc.clear(); // ids of a suppressed run are discarded, as in the DOM path
955        }
956        if child.get_type() == Some(NodeType::ElementNode) {
957          let serialized = doc.node_to_string(&child);
958          if self.needs_dom_descent(&serialized) {
959            self.descend_element(doc, &child, page_nodes, lang.clone(), bg.clone())?;
960          } else {
961            self.bulk_probes_dom(&serialized);
962          }
963          if has_lists_toc_node(&child) || has_lists_toc_descendant(&child) {
964            has_lists_toc = true;
965          }
966        }
967      }
968      child_opt = next;
969    }
970    if run_active && !run_toc.is_empty() && !has_lists_toc {
971      let entries = std::mem::take(&mut run_toc);
972      self.dom_insert_toc(doc, node, None, &node_name, &entries)?;
973    }
974    Ok(())
975  }
976
977  /// The picture/PI probes for DOM-descent bulk content (`has_lists_toc` is
978  /// tracked by the caller's incremental probe, and the shell append handles
979  /// the enclosing level's flag).
980  fn bulk_probes_dom(&mut self, serialized: &str) {
981    if serialized.contains("<?latexml") {
982      for body in extract_pi_bodies(serialized) {
983        self.latexml_pis.push(body);
984      }
985    }
986  }
987
988  /// Extract one page found during DOM descent: register its metadata, add
989  /// its tocentry to the enclosing run, recursively extract ITS page
990  /// descendants, then serialize + amend + write its spill.
991  fn dom_extract_page(
992    &mut self,
993    doc: &Document,
994    page: &Node,
995    page_nodes: &[Node],
996    lang: Option<String>,
997    bg: Option<String>,
998    run_toc: &mut Vec<String>,
999  ) -> Result<(), String> {
1000    let parent_meta = match self.levels.last().expect("open level").kind {
1001      LevelKind::Root => 0,
1002      LevelKind::Page(i) => i,
1003    };
1004    let idx = self.metas.len();
1005    let xml_id = crate::document::get_xml_id(page);
1006    if let Some(id) = &xml_id {
1007      run_toc.push(id.clone());
1008    }
1009    self.metas.push(PageMeta {
1010      file: self.spill_dir.join(format!("page-{idx:07}.xml")),
1011      children: Vec::new(),
1012      localname: page.get_name(),
1013      xml_id,
1014      labels: page.get_attribute("labels"),
1015      inlist: page.get_attribute("inlist"),
1016      class_appended: false,
1017      name: String::new(),
1018    });
1019    self.metas[parent_meta].children.push(idx);
1020    // Bookkeeping level so deeper extractions attach to this page in the
1021    // metadata tree (content stays in the live mini-DOM).
1022    self.levels.push(Level {
1023      kind:            LevelKind::Page(idx),
1024      localname:       page.get_name(),
1025      ltx:             true,
1026      content:         String::new(),
1027      seen_ltx:        FxHashSet::default(),
1028      run_toc:         Vec::new(),
1029      run_active:      false,
1030      has_lists_toc:   false,
1031      has_direct_date: false,
1032      attrs:           Vec::new(),
1033      lang:            lang.clone(),
1034      bg:              bg.clone(),
1035      ns_decls:        Vec::new(),
1036    });
1037    let descend_result = self.descend_element(doc, page, page_nodes, lang.clone(), bg.clone());
1038    self.levels.pop();
1039    descend_result?;
1040    // Serialize the (now child-page-free) page subtree; the serialization
1041    // preserves the original attribute order natively. Then amend the tag
1042    // with the inherited/class attributes and namespace re-declarations, and
1043    // splice the template trailer before the close tag.
1044    let mut serialized = doc.node_to_string(page);
1045    let has_direct_date = page
1046      .get_child_elements()
1047      .iter()
1048      .any(|c| name_is(c, "date") && is_ltx(c));
1049    let mut trailer = String::new();
1050    for r in &self.resources_xml {
1051      trailer.push_str(r);
1052    }
1053    if !has_direct_date {
1054      for d in &self.dates_xml {
1055        trailer.push_str(d);
1056      }
1057    }
1058    for nav in &self.navs_xml {
1059      trailer.push_str(nav);
1060    }
1061    let effective_lang = xml_ns_attr(page, "lang").or(lang);
1062    let effective_bg = page.get_attribute("backgroundcolor").or(bg);
1063    let mut extra_attrs: Vec<(String, String)> = Vec::new();
1064    if xml_ns_attr(page, "lang").is_none()
1065      && let Some(l) = &effective_lang
1066    {
1067      extra_attrs.push(("xml:lang".to_string(), l.clone()));
1068    }
1069    if !page.has_attribute("backgroundcolor")
1070      && let Some(b) = &effective_bg
1071    {
1072      extra_attrs.push(("backgroundcolor".to_string(), b.clone()));
1073    }
1074    let mut class_appended = false;
1075    let mut class_merge: Option<String> = None;
1076    if let Some(pclass) = &self.root_class {
1077      if page.has_attribute("class") {
1078        class_merge = Some(pclass.clone());
1079      } else {
1080        extra_attrs.push(("class".to_string(), pclass.clone()));
1081        class_appended = true;
1082      }
1083    }
1084    self.metas[idx].class_appended = class_appended;
1085    let decls = self.enclosing_decls();
1086    amend_serialized_page(
1087      &mut serialized,
1088      &decls,
1089      &extra_attrs,
1090      class_merge.as_deref(),
1091      &trailer,
1092    )?;
1093    let mut out = self.spill_prolog();
1094    out.push_str(&serialized);
1095    out.push('\n');
1096    write_spill(&self.metas[idx].file, &out)?;
1097    self.first_page_spilled = true;
1098    Ok(())
1099  }
1100
1101  /// Insert a generated TOC element into the live mini-DOM before `anchor`
1102  /// (or append, when the run ended at the element's close). Built with
1103  /// direct node construction (the `PostDocument::add_nodes` pattern: prefer
1104  /// the in-scope default ltx declaration so serialization matches the
1105  /// document's own vocabulary).
1106  fn dom_insert_toc(
1107    &mut self,
1108    doc: &Document,
1109    parent: &Node,
1110    anchor: Option<&Node>,
1111    parent_type: &str,
1112    ids: &[String],
1113  ) -> Result<(), String> {
1114    let mut parent = parent.clone();
1115    let ns = parent
1116      .get_namespaces(doc)
1117      .into_iter()
1118      .find(|ns| ns.get_href() == LTX_NSURI && ns.get_prefix().is_empty())
1119      .or_else(|| {
1120        parent
1121          .get_namespaces(doc)
1122          .into_iter()
1123          .find(|ns| ns.get_href() == LTX_NSURI)
1124      });
1125    let mut toc = parent
1126      .new_child(ns.clone(), "TOC")
1127      .map_err(|e| format!("cannot create TOC element: {e}"))?;
1128    let ns = ns.or_else(|| Namespace::new("", LTX_NSURI, &mut toc).ok());
1129    let mut toclist = toc
1130      .new_child(ns.clone(), "toclist")
1131      .map_err(|e| format!("cannot create toclist: {e}"))?;
1132    toclist
1133      .set_attribute("class", &format!("ltx_toclist_{parent_type}"))
1134      .map_err(|e| format!("cannot set toclist class: {e:?}"))?;
1135    for id in ids {
1136      let mut entry = toclist
1137        .new_child(ns.clone(), "tocentry")
1138        .map_err(|e| format!("cannot create tocentry: {e}"))?;
1139      let mut r = entry
1140        .new_child(ns.clone(), "ref")
1141        .map_err(|e| format!("cannot create ref: {e}"))?;
1142      r.set_attribute("idref", id)
1143        .map_err(|e| format!("cannot set idref: {e:?}"))?;
1144      r.set_attribute("show", "toctitle")
1145        .map_err(|e| format!("cannot set show: {e:?}"))?;
1146    }
1147    if let Some(a) = anchor {
1148      // `new_child` appended the TOC; move it to the run's position.
1149      a.clone()
1150        .add_prev_sibling(&mut toc)
1151        .map_err(|e| format!("cannot position TOC: {e:?}"))?;
1152    }
1153    Ok(())
1154  }
1155
1156  // ====================================================================
1157  // Deferred passes
1158
1159  /// Port of `Split::prename_pages` + `get_page_name` over the metadata tree:
1160  /// each child named, then its own children, in document order (the order the
1161  /// `FOO{n}` counter and a pathname collision depend on).
1162  fn prename(&mut self) {
1163    let ext = Path::new(&self.root_destination)
1164      .extension()
1165      .map(|e| e.to_string_lossy().to_string())
1166      .unwrap_or_else(|| "xml".to_string());
1167    // `haschildren`: keyed by the localname of any element with page
1168    // children (the root's included) — drives `*Relative` dir naming.
1169    let mut haschildren: HashMap<String, bool> = HashMap::default();
1170    for m in &self.metas {
1171      if !m.children.is_empty() {
1172        haschildren.insert(m.localname.clone(), true);
1173      }
1174    }
1175    self.namer.start(&self.root_destination);
1176    self.prename_rec(0, &ext, &haschildren);
1177  }
1178
1179  fn prename_rec(&mut self, node: usize, ext: &str, haschildren: &HashMap<String, bool>) {
1180    let children = self.metas[node].children.clone();
1181    for &child in &children {
1182      let recursive = haschildren
1183        .get(&self.metas[child].localname)
1184        .copied()
1185        .unwrap_or(false);
1186      let name = self.get_page_name(child, node, ext, recursive);
1187      self.metas[child].name = name;
1188      self.prename_rec(child, ext, haschildren);
1189    }
1190  }
1191
1192  /// Port of `Split::get_page_name` over metadata, through [`PageNamer`].
1193  fn get_page_name(&mut self, page: usize, parent: usize, ext: &str, recursive: bool) -> String {
1194    fn keys(meta: &PageMeta) -> PageKeys<'_> {
1195      PageKeys {
1196        labels: meta.labels.as_deref(),
1197        id:     meta.xml_id.as_deref(),
1198      }
1199    }
1200    let (page, parent) = (&self.metas[page], &self.metas[parent]);
1201    self
1202      .namer
1203      .page_name(keys(page), keys(parent), &parent.name, ext, recursive)
1204  }
1205
1206  /// The `inlist="toc"` lookahead pass: for each tree level where any page's
1207  /// `inlist` contains `"toc"` (substring semantics, mirroring the DOM
1208  /// path), patch `inlist="toc"` into the spilled root tag of every sibling
1209  /// page that has no `inlist` of its own.
1210  fn patch_inlist_toc(&mut self) -> Result<(), String> {
1211    for node in 0..self.metas.len() {
1212      let children = &self.metas[node].children;
1213      if children.is_empty() {
1214        continue;
1215      }
1216      let intoc = children.iter().any(|&c| {
1217        self.metas[c]
1218          .inlist
1219          .as_deref()
1220          .is_some_and(|il| il.contains("toc"))
1221      });
1222      if !intoc {
1223        continue;
1224      }
1225      let to_patch: Vec<usize> = children
1226        .iter()
1227        .copied()
1228        .filter(|&c| self.metas[c].inlist.is_none())
1229        .collect();
1230      for c in to_patch {
1231        patch_spill_root_tag(
1232          &self.metas[c].file,
1233          "inlist",
1234          "toc",
1235          self.metas[c].class_appended,
1236        )?;
1237        self.metas[c].inlist = Some("toc".to_string());
1238      }
1239    }
1240    Ok(())
1241  }
1242}
1243
1244impl Level {
1245  fn seen_ltx_insert(&mut self, ltx: bool, localname: &str) {
1246    if ltx {
1247      self.seen_ltx.insert(localname.to_string());
1248    }
1249  }
1250}
1251
1252// ======================================================================
1253// Text-level helpers
1254
1255/// Assemble one spill file: prolog, then the element (self-closed when it
1256/// has no content), then the tail.
1257fn assemble_spill(prolog: &str, tag: &str, qname: &str, content: &str, tail: &str) -> String {
1258  let mut out = String::with_capacity(prolog.len() + tag.len() + content.len() + tail.len() + 16);
1259  out.push_str(prolog);
1260  out.push_str(tag);
1261  if content.is_empty() {
1262    out.push_str("/>\n");
1263  } else {
1264    out.push('>');
1265    out.push_str(content);
1266    out.push_str("</");
1267    out.push_str(qname);
1268    out.push_str(">\n");
1269  }
1270  out.push_str(tail);
1271  out
1272}
1273
1274/// libxml-compatible attribute-value escaping (`xmlAttrSerializeTxtContent`).
1275fn attr_escape(value: &str) -> String {
1276  let mut out = String::with_capacity(value.len());
1277  for ch in value.chars() {
1278    match ch {
1279      '&' => out.push_str("&amp;"),
1280      '<' => out.push_str("&lt;"),
1281      '>' => out.push_str("&gt;"),
1282      '"' => out.push_str("&quot;"),
1283      '\n' => out.push_str("&#10;"),
1284      '\r' => out.push_str("&#13;"),
1285      '\t' => out.push_str("&#9;"),
1286      _ => out.push(ch),
1287    }
1288  }
1289  out
1290}
1291
1292/// libxml-compatible text-node escaping.
1293fn text_escape(value: &str) -> String {
1294  let mut out = String::with_capacity(value.len());
1295  for ch in value.chars() {
1296    match ch {
1297      '&' => out.push_str("&amp;"),
1298      '<' => out.push_str("&lt;"),
1299      '>' => out.push_str("&gt;"),
1300      '\r' => out.push_str("&#13;"),
1301      _ => out.push(ch),
1302    }
1303  }
1304  out
1305}
1306
1307fn attr_value(attrs: &[(String, String)], name: &str) -> Option<String> {
1308  attrs
1309    .iter()
1310    .find(|(k, _)| k == name)
1311    .map(|(_, v)| v.clone())
1312}
1313
1314/// The namespace declarations among an element's attributes, as
1315/// `(prefix, uri)` pairs (`""` = default).
1316fn decl_attrs(attrs: &[(String, String)]) -> Vec<(String, String)> {
1317  let mut out = Vec::new();
1318  for (k, v) in attrs {
1319    if k == "xmlns" {
1320      out.push((String::new(), v.clone()));
1321    } else if let Some(p) = k.strip_prefix("xmlns:") {
1322      out.push((p.to_string(), v.clone()));
1323    }
1324  }
1325  out
1326}
1327
1328/// Read an `xml:`-namespaced attribute from a DOM node. A plain
1329/// `get_attribute("xml:lang")` can miss the namespaced form (the same trap
1330/// `get_xml_id` guards against), so try the namespace-aware read first.
1331fn xml_ns_attr(node: &Node, localname: &str) -> Option<String> {
1332  const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
1333  node
1334    .get_attribute_ns(localname, XML_NS)
1335    .or_else(|| node.get_attribute(&format!("xml:{localname}")))
1336}
1337
1338/// Byte-level check for XML NCName characters that may appear in a namespace prefix.
1339fn is_xml_ncname_char(b: u8) -> bool {
1340  b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.') || b >= 0x80
1341}
1342
1343/// Conservative substring probe for "this serialized fragment may contain an
1344/// element with `localname`": matches `<localname` or `<pfx:localname`
1345/// followed by a name-boundary character, so `<indexmark` does NOT register
1346/// as `<index` (a real document's `\\index` markers would otherwise trigger a
1347/// mini-DOM descent per paragraph). Text content cannot introduce `<`
1348/// (escaped), so `<`-anchored matches are always element starts. A
1349/// `:localname` match counts only after `<` and a prefix: text such as
1350/// `urn:resource/1` is not escaped, and a false match costs a descent at best
1351/// and, for `resource`, a needless whole-DOM failover or a false Warning.
1352fn contains_element_probe(outer: &str, localname: &str) -> bool {
1353  let boundary = |rest: &str| {
1354    rest
1355      .as_bytes()
1356      .first()
1357      .is_none_or(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'>' | b'/'))
1358  };
1359  let bare = format!("<{localname}");
1360  for (at, _) in outer.match_indices(&bare) {
1361    if boundary(&outer[at + bare.len()..]) {
1362      return true;
1363    }
1364  }
1365  let prefixed = format!(":{localname}");
1366  let bytes = outer.as_bytes();
1367  for (at, _) in outer.match_indices(&prefixed) {
1368    if !boundary(&outer[at + prefixed.len()..]) {
1369      continue;
1370    }
1371    // Require a real XML start-tag `<prefix:localname` — not prose/URLs/code
1372    // such as `urn:resource/1` or `std::resource `, and not a close tag `</p:name>`.
1373    let mut i = at;
1374    while i > 0 && is_xml_ncname_char(bytes[i - 1]) {
1375      i -= 1;
1376    }
1377    if i < at && i > 0 && bytes[i - 1] == b'<' {
1378      return true;
1379    }
1380  }
1381  false
1382}
1383
1384/// Does this serialized fragment contain an `ltx:TOC` with `lists` exactly
1385/// `"toc"`? (The DOM probe is `@lists='toc'`, exact equality; generated TOCs
1386/// never match — they carry no `lists`.)
1387fn probe_lists_toc(outer: &str) -> bool {
1388  for (start, _) in outer
1389    .match_indices("<TOC")
1390    .chain(outer.match_indices(":TOC"))
1391  {
1392    let rest = &outer[start..];
1393    if let Some(end) = rest.find('>')
1394      && rest[..end].contains(" lists=\"toc\"")
1395    {
1396      return true;
1397    }
1398  }
1399  false
1400}
1401
1402/// Extract the bodies of `<?latexml …?>` PIs embedded in a serialized
1403/// fragment.
1404fn extract_pi_bodies(outer: &str) -> Vec<String> {
1405  let mut out = Vec::new();
1406  let mut from = 0;
1407  while let Some(rel) = outer[from..].find("<?latexml") {
1408    let start = from + rel + "<?latexml".len();
1409    if let Some(rel_end) = outer[start..].find("?>") {
1410      out.push(outer[start..start + rel_end].trim().to_string());
1411      from = start + rel_end + 2;
1412    } else {
1413      break;
1414    }
1415  }
1416  out
1417}
1418
1419/// Collect `ltx:` descendants named `localname` (pre-order, limit-safe walk).
1420fn collect_ltx_descendants(node: &Node, localname: &str, out: &mut Vec<Node>) {
1421  let mut child = node.get_first_child();
1422  while let Some(c) = child {
1423    if c.get_type() == Some(NodeType::ElementNode) {
1424      if name_is(&c, localname) && is_ltx(&c) {
1425        out.push(c.clone());
1426      }
1427      collect_ltx_descendants(&c, localname, out);
1428    }
1429    child = c.get_next_sibling();
1430  }
1431}
1432
1433/// The `descendant::ltx:TOC[@lists='toc']` probe, DOM flavor.
1434fn has_lists_toc_descendant(node: &Node) -> bool {
1435  let mut child = node.get_first_child();
1436  while let Some(c) = child {
1437    if c.get_type() == Some(NodeType::ElementNode)
1438      && (has_lists_toc_node(&c) || has_lists_toc_descendant(&c))
1439    {
1440      return true;
1441    }
1442    child = c.get_next_sibling();
1443  }
1444  false
1445}
1446
1447fn has_lists_toc_node(node: &Node) -> bool {
1448  node.get_type() == Some(NodeType::ElementNode)
1449    && name_is(node, "TOC")
1450    && is_ltx(node)
1451    && node.with_attribute(c"lists", |v| v == "toc") == Some(true)
1452}
1453
1454/// Find the end of the first tag in a well-formed serialized element: the
1455/// first `>` outside quoted attribute values (attribute values may legally
1456/// contain `>`).
1457fn first_tag_end(xml: &str) -> Option<usize> {
1458  let bytes = xml.as_bytes();
1459  let mut in_quote: Option<u8> = None;
1460  for (i, &b) in bytes.iter().enumerate() {
1461    match in_quote {
1462      Some(q) => {
1463        if b == q {
1464          in_quote = None;
1465        }
1466      },
1467      None => match b {
1468        b'"' | b'\'' => in_quote = Some(b),
1469        b'>' => return Some(i),
1470        _ => {},
1471      },
1472    }
1473  }
1474  None
1475}
1476
1477/// Amend a DOM-serialized page: inject namespace re-declarations and extra
1478/// attributes into the opening tag, optionally merge the root class into an
1479/// existing `class` attribute, and splice the template trailer before the
1480/// closing tag.
1481fn amend_serialized_page(
1482  serialized: &mut String,
1483  decls: &[(String, String)],
1484  extra_attrs: &[(String, String)],
1485  class_merge: Option<&str>,
1486  trailer: &str,
1487) -> Result<(), String> {
1488  let tag_end =
1489    first_tag_end(serialized).ok_or_else(|| "malformed page serialization".to_string())?;
1490  let self_closing = serialized[..tag_end].ends_with('/');
1491  let insert_at = if self_closing { tag_end - 1 } else { tag_end };
1492  let mut additions = String::new();
1493  for (p, u) in decls {
1494    let probe = if p.is_empty() {
1495      " xmlns=".to_string()
1496    } else {
1497      format!(" xmlns:{p}=")
1498    };
1499    if !serialized[..tag_end].contains(&probe) {
1500      if p.is_empty() {
1501        additions.push_str(&format!(" xmlns=\"{}\"", attr_escape(u)));
1502      } else {
1503        additions.push_str(&format!(" xmlns:{}=\"{}\"", p, attr_escape(u)));
1504      }
1505    }
1506  }
1507  for (k, v) in extra_attrs {
1508    additions.push_str(&format!(" {}=\"{}\"", k, attr_escape(v)));
1509  }
1510  serialized.insert_str(insert_at, &additions);
1511  if let Some(pclass) = class_merge {
1512    let tag_end = first_tag_end(serialized).ok_or("malformed tag")?;
1513    if let Some(cpos) = serialized[..tag_end].find(" class=\"") {
1514      let vstart = cpos + " class=\"".len();
1515      if let Some(vlen) = serialized[vstart..tag_end].find('"') {
1516        let existing = serialized[vstart..vstart + vlen].to_string();
1517        let merged = if existing.is_empty() {
1518          attr_escape(pclass)
1519        } else {
1520          format!("{} {}", existing, attr_escape(pclass))
1521        };
1522        serialized.replace_range(vstart..vstart + vlen, &merged);
1523      }
1524    }
1525  }
1526  if !trailer.is_empty() {
1527    let tag_end = first_tag_end(serialized).ok_or("malformed tag")?;
1528    if serialized[..=tag_end].ends_with("/>") {
1529      // `<x/>` → `<x>trailer</x>`: re-open the element.
1530      let qname_end = serialized
1531        .find(|c: char| c.is_whitespace() || c == '/' || c == '>')
1532        .unwrap_or(tag_end);
1533      let qname = serialized[1..qname_end].to_string();
1534      serialized.truncate(tag_end - 1);
1535      serialized.push('>');
1536      serialized.push_str(trailer);
1537      serialized.push_str(&format!("</{qname}>"));
1538    } else if let Some(close_at) = serialized.rfind("</") {
1539      serialized.insert_str(close_at, trailer);
1540    }
1541  }
1542  Ok(())
1543}
1544
1545/// Patch ` name="value"` into a spill file's root element tag, inserting
1546/// before the trailing `class` attribute when the class was appended by the
1547/// merge (reproducing the DOM path's attribute order: inherit → inlist →
1548/// class).
1549fn patch_spill_root_tag(
1550  file: &Path,
1551  name: &str,
1552  value: &str,
1553  before_appended_class: bool,
1554) -> Result<(), String> {
1555  let content = std::fs::read_to_string(file).map_err(|e| {
1556    format!(
1557      "cannot read staged page {} for patching: {e}",
1558      file.display()
1559    )
1560  })?;
1561  // Locate the root element: the first `<` not opening a PI or comment.
1562  let mut pos = 0;
1563  let root_start = loop {
1564    let rel = content[pos..]
1565      .find('<')
1566      .ok_or_else(|| "no root tag in spill".to_string())?;
1567    let at = pos + rel;
1568    if content[at..].starts_with("<?") {
1569      pos = at + content[at..].find("?>").ok_or("unterminated PI")? + 2;
1570    } else if content[at..].starts_with("<!--") {
1571      pos = at + content[at..].find("-->").ok_or("unterminated comment")? + 3;
1572    } else {
1573      break at;
1574    }
1575  };
1576  let tag_end = root_start
1577    + first_tag_end(&content[root_start..]).ok_or_else(|| "malformed root tag".to_string())?;
1578  let tag_self_close_adjust = if content[..tag_end].ends_with('/') {
1579    tag_end - 1
1580  } else {
1581    tag_end
1582  };
1583  let insert_at = if before_appended_class {
1584    content[root_start..tag_end]
1585      .rfind(" class=\"")
1586      .map(|rel| root_start + rel)
1587      .unwrap_or(tag_self_close_adjust)
1588  } else {
1589    tag_self_close_adjust
1590  };
1591  let mut patched = String::with_capacity(content.len() + 16);
1592  patched.push_str(&content[..insert_at]);
1593  patched.push_str(&format!(" {}=\"{}\"", name, attr_escape(value)));
1594  patched.push_str(&content[insert_at..]);
1595  std::fs::write(file, patched).map_err(|e| format!("cannot rewrite spill: {e}"))
1596}
1597
1598fn write_spill(path: &Path, content: &str) -> Result<(), String> {
1599  let mut f = std::fs::File::create(path)
1600    .map_err(|e| format!("cannot create spill {}: {e}", path.display()))?;
1601  f.write_all(content.as_bytes())
1602    .map_err(|e| format!("cannot write spill {}: {e}", path.display()))
1603}
1604
1605#[cfg(test)]
1606mod tests {
1607  use super::*;
1608
1609  #[test]
1610  fn escaping_matches_libxml() {
1611    assert_eq!(
1612      attr_escape("a<b>&\"c\"\nd\te\r"),
1613      "a&lt;b&gt;&amp;&quot;c&quot;&#10;d&#9;e&#13;"
1614    );
1615    assert_eq!(text_escape("a<b>&c\r"), "a&lt;b&gt;&amp;c&#13;");
1616  }
1617
1618  #[test]
1619  fn first_tag_end_skips_gt_inside_quotes() {
1620    assert_eq!(first_tag_end(r#"<x a="1>2">rest</x>"#), Some(10));
1621    assert_eq!(first_tag_end("<x/>"), Some(3));
1622    assert_eq!(first_tag_end("<never-closed"), None);
1623  }
1624
1625  #[test]
1626  fn probe_lists_toc_is_exact() {
1627    assert!(probe_lists_toc(r#"<p><TOC lists="toc"><t/></TOC></p>"#));
1628    assert!(probe_lists_toc(r#"<ltx:TOC lists="toc"/>"#));
1629    // Generated TOCs (no lists attribute) never match.
1630    assert!(!probe_lists_toc(r#"<TOC><toclist class="c"/></TOC>"#));
1631    // Exact equality: 'toc lof' does not match the @lists='toc' probe.
1632    assert!(!probe_lists_toc(r#"<TOC lists="toc lof"/>"#));
1633  }
1634
1635  #[test]
1636  fn amend_injects_attrs_and_trailer() {
1637    let mut s = r#"<section xml:id="S1"><p>t</p></section>"#.to_string();
1638    amend_serialized_page(
1639      &mut s,
1640      &[(String::new(), "urn:ns".to_string())],
1641      &[("xml:lang".to_string(), "en".to_string())],
1642      None,
1643      "<date>d</date>",
1644    )
1645    .unwrap();
1646    // Additions (declarations + attributes) append after the original
1647    // attributes; declaration position within a tag is semantically free.
1648    assert_eq!(
1649      s,
1650      r#"<section xml:id="S1" xmlns="urn:ns" xml:lang="en"><p>t</p><date>d</date></section>"#
1651    );
1652  }
1653
1654  #[test]
1655  fn amend_reopens_self_closed_page_for_trailer() {
1656    let mut s = "<chapter/>".to_string();
1657    amend_serialized_page(&mut s, &[], &[], None, "<x/>").unwrap();
1658    assert_eq!(s, "<chapter><x/></chapter>");
1659  }
1660
1661  #[test]
1662  fn amend_merges_class() {
1663    let mut s = r#"<section class="own"><p/></section>"#.to_string();
1664    amend_serialized_page(&mut s, &[], &[], Some("root"), "").unwrap();
1665    assert_eq!(s, r#"<section class="own root"><p/></section>"#);
1666  }
1667
1668  #[test]
1669  fn patch_inserts_before_appended_class() {
1670    let dir = std::env::temp_dir();
1671    let file = dir.join(format!("lxo-patch-test-{}.xml", std::process::id()));
1672    std::fs::write(
1673      &file,
1674      "<?xml version=\"1.0\"?>\n<?latexml p?>\n<section xml:id=\"S1\" class=\"root\"><p/></section>\n",
1675    )
1676    .unwrap();
1677    patch_spill_root_tag(&file, "inlist", "toc", true).unwrap();
1678    let out = std::fs::read_to_string(&file).unwrap();
1679    assert!(
1680      out.contains(r#"<section xml:id="S1" inlist="toc" class="root">"#),
1681      "patched tag order wrong: {out}"
1682    );
1683    // Without the appended-class flag, the attribute lands last.
1684    std::fs::write(
1685      &file,
1686      "<?xml version=\"1.0\"?>\n<section xml:id=\"S1\" class=\"own\"><p/></section>\n",
1687    )
1688    .unwrap();
1689    patch_spill_root_tag(&file, "inlist", "toc", false).unwrap();
1690    let out = std::fs::read_to_string(&file).unwrap();
1691    assert!(
1692      out.contains(r#"<section xml:id="S1" class="own" inlist="toc">"#),
1693      "patched tag order wrong: {out}"
1694    );
1695    std::fs::remove_file(&file).ok();
1696  }
1697
1698  /// End-to-end mini split: a wrapper (backmatter) page must carry the ltx
1699  /// namespace declaration in its spill, or the XSLT will not recognize it.
1700  #[test]
1701  fn wrapper_page_spill_is_namespaced() {
1702    let dir = tempfile::tempdir().unwrap();
1703    let src = dir.path().join("mini.xml");
1704    std::fs::write(
1705      &src,
1706      r#"<?xml version="1.0" encoding="UTF-8"?>
1707<document xmlns="http://dlmf.nist.gov/LaTeXML" class="rc">
1708  <title>T</title>
1709  <chapter xml:id="C1"><title>One</title><para xml:id="C1.p1"><p>x</p></para></chapter>
1710  <backmatter>
1711    <section xml:id="BM.S1"><title>BS</title></section>
1712    <appendix xml:id="A1"><title>App</title></appendix>
1713  </backmatter>
1714</document>
1715"#,
1716    )
1717    .unwrap();
1718    let spill = dir.path().join("spill");
1719    std::fs::create_dir(&spill).unwrap();
1720    let union = "//ltx:section | //ltx:chapter | //ltx:appendix[preceding-sibling::ltx:section or parent::ltx:chapter]";
1721    let outcome = stream_split(
1722      &src.to_string_lossy(),
1723      union,
1724      SplitNaming::Id,
1725      Some("out/mini.html"),
1726      &spill,
1727      true,
1728    )
1729    .expect("split runs")
1730    .expect("split produces pages");
1731    let names: Vec<&str> = outcome
1732      .pages
1733      .iter()
1734      .map(|p| p.destination.as_str())
1735      .collect();
1736    assert_eq!(
1737      names,
1738      vec![
1739        "out/mini.html",
1740        "out/C1.html",
1741        "out/BM.S1.html",
1742        "out/A1.html"
1743      ],
1744      "pre-order destinations"
1745    );
1746    for page in &outcome.pages[1..] {
1747      let content = std::fs::read_to_string(&page.path).unwrap();
1748      assert!(
1749        content.contains("xmlns=\"http://dlmf.nist.gov/LaTeXML\""),
1750        "page {} must declare the ltx namespace:\n{content}",
1751        page.destination
1752      );
1753      // Reparse: root element must be in the ltx namespace.
1754      let doc = libxml::parser::Parser::default()
1755        .parse_string(&content)
1756        .expect("page reparses");
1757      let root = doc.get_root_element().unwrap();
1758      assert_eq!(
1759        root.get_namespace().map(|n| n.get_href()),
1760        Some(LTX_NSURI.to_string()),
1761        "page {} root not in ltx namespace:\n{content}",
1762        page.destination
1763      );
1764    }
1765  }
1766
1767  #[test]
1768  fn element_probe_respects_name_boundaries() {
1769    // `<indexmark>` must NOT register as an `index` element…
1770    assert!(!contains_element_probe(
1771      "<p><indexmark k=\"x\"/></p>",
1772      "index"
1773    ));
1774    // …while real starts do, in every tag shape and prefixed form.
1775    assert!(contains_element_probe("<p><index r=\"1\"/></p>", "index"));
1776    assert!(contains_element_probe("<index>", "index"));
1777    assert!(contains_element_probe("<index/>", "index"));
1778    assert!(contains_element_probe("<ltx:index>x</ltx:index>", "index"));
1779    assert!(contains_element_probe(
1780      "<a-1.b_2:resource src=\"x\"/>",
1781      "resource"
1782    ));
1783    assert!(!contains_element_probe("<subsubsection>", "subsection"));
1784    assert!(!contains_element_probe("plain text", "section"));
1785    // Prose, URLs, attributes, code, and close tags containing `:name` must NOT
1786    // match as prefixed start tags (false positive aborts stream_split or emits
1787    // spurious nested-resource warnings).
1788    assert!(!contains_element_probe(
1789      "<p>urn:resource/1 and std::resource and a:resource </p>",
1790      "resource"
1791    ));
1792    assert!(!contains_element_probe(
1793      "<p about=\"ex:resource \">http://example.org/ns:resource/</p>",
1794      "resource"
1795    ));
1796    assert!(!contains_element_probe("</ltx:resource>", "resource"));
1797    assert!(!contains_element_probe("<:resource/>", "resource"));
1798  }
1799
1800  #[test]
1801  fn stream_split_ignores_colon_resource_in_prose_and_attrs() {
1802    let dir = tempfile::tempdir().unwrap();
1803    let src = dir.path().join("prose.xml");
1804    std::fs::write(
1805      &src,
1806      r#"<?xml version="1.0" encoding="UTF-8"?>
1807<document xmlns="http://dlmf.nist.gov/LaTeXML">
1808  <title>T</title>
1809  <section xml:id="S1"><title>One</title>
1810    <para xml:id="S1.p1"><p about="ex:resource ">See urn:resource/1 and std::resource and doc:section/a.</p></para>
1811  </section>
1812  <section xml:id="S2"><title>Two</title>
1813    <para xml:id="S2.p1"><p>Clean.</p></para>
1814  </section>
1815</document>
1816"#,
1817    )
1818    .unwrap();
1819    let spill = dir.path().join("spill");
1820    std::fs::create_dir(&spill).unwrap();
1821    let outcome = stream_split(
1822      &src.to_string_lossy(),
1823      "//ltx:section",
1824      SplitNaming::Id,
1825      Some("out/prose.html"),
1826      &spill,
1827      true,
1828    )
1829    .expect("prose containing :resource must not abort streaming split")
1830    .expect("split produces pages");
1831    assert_eq!(outcome.pages.len(), 3);
1832  }
1833
1834  /// A late template item (here an `ltx:resource` after the first page) fails the stream over to
1835  /// the whole-DOM split; the stream stops there instead of spilling the remaining pages.
1836  #[test]
1837  fn a_doomed_stream_stops_at_the_late_template() {
1838    let dir = tempfile::tempdir().unwrap();
1839    let src = dir.path().join("late.xml");
1840    let mut xml = String::from(
1841      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document xmlns=\"http://dlmf.nist.gov/LaTeXML\">\n<title>T</title>\n",
1842    );
1843    xml.push_str("<section xml:id=\"S1\"><title>1</title><para><p>x</p></para></section>\n");
1844    xml.push_str("<resource src=\"late.css\" type=\"text/css\"/>\n");
1845    for i in 2..=20 {
1846      xml.push_str(&format!(
1847        "<section xml:id=\"S{i}\"><title>{i}</title><para><p>x</p></para></section>\n"
1848      ));
1849    }
1850    xml.push_str("</document>\n");
1851    std::fs::write(&src, xml).unwrap();
1852    let spill = dir.path().join("spill");
1853    std::fs::create_dir(&spill).unwrap();
1854    let failed = stream_split(
1855      &src.to_string_lossy(),
1856      "//ltx:section",
1857      SplitNaming::Id,
1858      Some("out/late.html"),
1859      &spill,
1860      true,
1861    );
1862    assert!(
1863      failed
1864        .as_ref()
1865        .is_err_and(|why| why.contains("ltx:resource appeared after the first page")),
1866      "{:?}",
1867      failed.map(|o| o.map(|o| o.pages.len()))
1868    );
1869    let spilled = std::fs::read_dir(&spill).unwrap().count();
1870    assert!(spilled <= 2, "{spilled} pages spilled for a doomed stream");
1871  }
1872
1873  #[test]
1874  fn pi_bodies_extracted() {
1875    assert_eq!(
1876      extract_pi_bodies(r#"<a><?latexml package="x"?><?other y?><?latexml class="c"?></a>"#),
1877      vec![r#"package="x""#.to_string(), r#"class="c""#.to_string()]
1878    );
1879  }
1880}