1use 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
96pub struct StreamedSplitPage {
98 pub path: PathBuf,
100 pub destination: String,
103 pub parent_id: Option<String>,
106}
107
108pub struct StreamSplitOutcome {
110 pub pages: Vec<StreamedSplitPage>,
112 pub latexml_pis: Vec<String>,
114}
115
116pub fn supports_union(union_xpath: &str) -> bool { parse_split_union(union_xpath).is_some() }
121
122pub 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 const OPTIONS: i32 = 1 + 32 + 64 + 524_288 ;
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 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 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
198struct PageMeta {
201 file: PathBuf,
203 children: Vec<usize>,
206 localname: String,
207 xml_id: Option<String>,
208 labels: Option<String>,
209 inlist: Option<String>,
210 class_appended: bool,
215 name: String,
217}
218
219struct Level {
223 kind: LevelKind,
224 localname: String,
225 ltx: bool,
226 content: String,
228 seen_ltx: FxHashSet<String>,
231 run_toc: Vec<String>,
233 run_active: bool,
234 has_lists_toc: bool,
237 has_direct_date: bool,
239 attrs: Vec<(String, String)>,
241 lang: Option<String>,
243 bg: Option<String>,
244 ns_decls: Vec<(String, String)>,
247}
248
249enum LevelKind {
250 Root,
251 Page(usize),
253}
254
255struct Splitter {
256 arms: Vec<SplitArm>,
257 namer: PageNamer,
259 root_destination: String,
260 spill_dir: PathBuf,
261 levels: Vec<Level>,
262 metas: Vec<PageMeta>,
263 root_prolog: String,
265 root_tail: String,
267 latexml_pis: Vec<String>,
269 resources_xml: Vec<String>,
271 dates_xml: Vec<String>,
273 navs_xml: Vec<String>,
275 root_class: Option<String>,
277 first_page_spilled: bool,
279 warned_late: bool,
280 late_template: Option<String>,
283 late_template_fails: bool,
285 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 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 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 return Err("multiple root elements in stream".to_string());
339 }
340 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 self.warn_if_late("an ltx:navigation");
362 self.navs_xml.push(outer);
363 } else if self.needs_dom_descent(&outer) {
364 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 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 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 },
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 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 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 fn top(&mut self) -> &mut Level {
478 self
479 .levels
480 .last_mut()
481 .expect("level stack must be non-empty")
482 }
483
484 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 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 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 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 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 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 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 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 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 level.localname.clone()
727 }
728 }
729
730 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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(); }
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 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 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 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 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 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 a.clone()
1150 .add_prev_sibling(&mut toc)
1151 .map_err(|e| format!("cannot position TOC: {e:?}"))?;
1152 }
1153 Ok(())
1154 }
1155
1156 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 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 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 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
1252fn 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
1274fn 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("&"),
1280 '<' => out.push_str("<"),
1281 '>' => out.push_str(">"),
1282 '"' => out.push_str("""),
1283 '\n' => out.push_str(" "),
1284 '\r' => out.push_str(" "),
1285 '\t' => out.push_str("	"),
1286 _ => out.push(ch),
1287 }
1288 }
1289 out
1290}
1291
1292fn 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("&"),
1298 '<' => out.push_str("<"),
1299 '>' => out.push_str(">"),
1300 '\r' => out.push_str(" "),
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
1314fn 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
1328fn 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
1338fn is_xml_ncname_char(b: u8) -> bool {
1340 b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.') || b >= 0x80
1341}
1342
1343fn 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 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
1384fn 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
1402fn 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
1419fn 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
1433fn 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
1454fn 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
1477fn 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 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
1545fn 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 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<b>&"c" d	e "
1614 );
1615 assert_eq!(text_escape("a<b>&c\r"), "a<b>&c ");
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 assert!(!probe_lists_toc(r#"<TOC><toclist class="c"/></TOC>"#));
1631 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 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 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 #[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 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 assert!(!contains_element_probe(
1771 "<p><indexmark k=\"x\"/></p>",
1772 "index"
1773 ));
1774 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 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 #[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}