latexml_core/document.rs
1pub mod helpers;
2pub mod resource;
3pub mod tag;
4
5use std::{
6 borrow::Cow,
7 collections::{BTreeSet, VecDeque},
8 rc::Rc,
9 sync::LazyLock,
10};
11
12use libxml::{
13 readonly::RoNode,
14 tree::{Document as XmlDoc, Namespace, Node, NodeType},
15};
16use regex::Regex;
17use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
18
19use crate::{
20 BoxOps, Digested, DigestedData, Tbox, TexMode,
21 common::{
22 arena::{self, SymHashMap, SymStr},
23 error::{emit_error, emit_warn, *},
24 font::{FONT_TEXT_DEFAULT, Font},
25 locator::Locator,
26 model,
27 numeric_ops::NumericOps,
28 object::Object,
29 store::Stored,
30 xml::{self, XML_NS, XPath, name_is},
31 },
32 definition::FontDirective,
33 document::{
34 resource::{BINDING_RESOURCE_CLASS, Resource, ResourceOrigin, is_remote},
35 tag::{TagConstructionClosure, TagOptionName},
36 },
37 ligature::{self, FontTestClosure, LigatureClosure, LigatureMatcher},
38 list::List,
39 pin, state,
40 util::radix::radix_alpha,
41};
42
43static HAS_NONSPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\S").unwrap());
44static ONLY_SPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s+$").unwrap());
45static DASHES_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\-\-+").unwrap());
46
47static NON_MERGEABLE_ATTRIBUTES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
48 HashSet::from_iter([
49 "about",
50 "aboutlabelref",
51 "aboutidref",
52 "resource",
53 "resourcelabelref",
54 "resourceidref",
55 "property",
56 "rel",
57 "rev",
58 "tyupeof",
59 "datatype",
60 "content",
61 "data",
62 "datamimetype",
63 "dataencoding",
64 ])
65});
66// When merging attributes of two nodes, some attributes should be combined
67// Merged space separated
68static MERGE_ATTRIBUTE_SPACEJOIN: LazyLock<HashSet<&'static str>> =
69 LazyLock::new(|| HashSet::from_iter(["class", "lists", "inlist", "labels"]));
70// Merged ";" separated
71static MERGE_ATTRIBUTE_SEMICOLONJOIN: LazyLock<HashSet<&'static str>> =
72 LazyLock::new(|| HashSet::from_iter(["cssstyle"]));
73// Summed lengths
74static MERGE_ATTRIBUTE_SUMLENGTH: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
75 HashSet::from_iter([
76 "xoffset",
77 "yoffset",
78 "lpadding",
79 "rpadding",
80 "xtranslate",
81 "ytranslate",
82 ])
83});
84
85pub static FONT_ELEMENT_NAME: &str = "ltx:text";
86pub static MATH_TOKEN_NAME: &str = "ltx:XMTok";
87pub static MATH_HINT_NAME: &str = "ltx:XMHint";
88
89/// Is `node` a phantom's hint holding its argument (`\phantom`, `\hphantom`, `\vphantom` in math, math_common.rs): a
90/// box of its content, not spacing (OXIDIZED_DESIGN_DIVERGENCES #1141)? An empty argument (`\phantom{}`) makes none:
91/// an empty `XMArg` before the parse, an `absent` token after it.
92pub fn is_phantom_box(node: &Node) -> bool {
93 node.get_name() == "XMHint"
94 && node
95 .get_attribute("name")
96 .is_some_and(|name| name.ends_with("phantom"))
97 && node
98 .get_child_elements()
99 .iter()
100 .any(|child| match child.get_name().as_str() {
101 "XMArg" => child.get_first_element_child().is_some(),
102 "XMTok" => child.get_attribute("meaning").as_deref() != Some("absent"),
103 _ => true,
104 })
105}
106
107/// The parsed item of a list (an `XMath`, or an `XMArg` slot) that keeps its edge phantoms beside it (the math parser's
108/// `parse_single`; OXIDIZED_DESIGN_DIVERGENCES #1141): its one element child but hints, when one of them is a phantom.
109/// Content, OpenMath and text read the list as that item; presentation draws the row. Any phantom, not only a box: once
110/// parsed, a phantom of spacing holds `absent` (`\sqrt{\phantom{\quad}x}`), and is still no item.
111pub fn item_beside_phantoms(node: &Node) -> Option<Node> {
112 let children = node.get_child_elements();
113 let is_phantom = |child: &Node| {
114 child.get_name() == "XMHint"
115 && child
116 .get_attribute("name")
117 .is_some_and(|name| name.ends_with("phantom"))
118 };
119 if !children.iter().any(is_phantom) {
120 return None;
121 }
122 let mut items = children
123 .into_iter()
124 .filter(|child| child.get_name() != "XMHint");
125 let item = items.next()?;
126 items.next().is_none().then_some(item)
127}
128
129/// How [`Document::close_element`] and its variants treat open descendants that do not
130/// auto-close.
131#[derive(Clone, Copy)]
132enum CloseDescendants {
133 /// An Error (`malformed`).
134 Strict,
135 /// An Info line: the source groups were abandoned and reported already.
136 Abandoned,
137}
138
139pub struct Document {
140 pub document: XmlDoc,
141 pub pending: Vec<Node>,
142 context: Option<XPath>,
143 pub node: Node,
144 pub node_boxes: HashMap<usize, Digested>, // used to be _box attribute
145 pub node_fonts: HashMap<u64, Font>, // used to be _font attribute
146 pub idstore: HashMap<String, Node>,
147 /// While `prune_xmduals` runs: the elements carrying each `idref` value, so a collapsed dual's references are renamed
148 /// without a whole-document `//*[@idref=…]` per dual (#802); `remove_node` and `merge_attributes` keep it current.
149 idref_index: Option<HashMap<String, Vec<Node>>>,
150 /// Streaming pass 1: every `xml:id` moved out of `idstore` by a spill.
151 /// The GLOBAL half of id-collision dedup — a later build-time minting of
152 /// the same id must rename exactly as eager would have (witness: the
153 /// 131 MB book restarts chapter numbering per part, and the second `Ch1`
154 /// collided only with a SPILLED chapter).
155 pub spilled_ids: rustc_hash::FxHashSet<String>,
156 /// Streaming pass 1: the ids spilled runs mint their top nodes' ids under (`SegmentMeta::anchor`) while those
157 /// elements stay resident; once one spills too, its `_ID_counter_*` attributes move to `spilled_anchor_counters`.
158 spill_anchors: rustc_hash::FxHashSet<String>,
159 spilled_anchor_counters: rustc_hash::FxHashMap<String, Vec<(String, String)>>,
160 /// Streaming pass 2: the segment's `SegmentMeta::anchor`. `generate_id` mints under it what eager mints under that
161 /// element, the parse wrapper holding its counters.
162 pub fragment_anchor_id: Option<String>,
163 /// Every SVG `id` (the svg schema's ID attribute, not `xml:id`) handed out
164 /// (`record_svg_ids`). Ids only, no nodes or addresses: whether an element was already walked
165 /// travels on the element itself (its `_svgid` mark), so a removed picture leaves nothing
166 /// dangling, and an id stays taken once given.
167 pub svg_ids: rustc_hash::FxHashSet<String>,
168 /// The next suffix to try per SVG id base (`record_svg_ids`), so the n-th copy of a picture
169 /// does not re-probe the n-1 suffixes before it.
170 pub svg_id_suffixes: rustc_hash::FxHashMap<String, i64>,
171 /// Streaming pass 1: every namespace PREFIX (`xlink`, `svg`, …) an element
172 /// or attribute of a spilled subtree used. `apply_document_namespace_
173 /// declarations` declares a prefix on the root only when it is used
174 /// (Perl behaviour) and scans the RESIDENT DOM; a prefix used solely inside
175 /// spilled segments (`xlink:href` on `svg:pattern`/`svg:use`) was serialized
176 /// unbound — six TikZ manuals flipped schema-invalid at the transition
177 /// watermark (atableau, circuitikzmanual, tikzlings-doc, tkz-grapheur-doc-en/
178 /// -fr, tzplot-doc; batch 56fr). Guard
179 /// `streaming_declares_namespaces_used_only_in_spilled_segments`.
180 pub spilled_ns_prefixes: rustc_hash::FxHashSet<String>,
181 // the rewrite labels used to be in each rewrite rule, but they make more sense in doc
182 pub rewrite_labels: HashMap<String, String>,
183 /// Document-wide labels SHARED by every streaming pass-2 fragment and the
184 /// spine, consulted only when `rewrite_labels` misses: the spilled content's
185 /// and the spine's id-bearing ones, built once before pass 2. Copying the
186 /// spilled index into each fragment's own map was quadratic in document size:
187 /// 28,068 labels × 459,579 segments on the 131 MB witness = 12.9 billion
188 /// String allocations. Frag-local labels still win.
189 pub rewrite_labels_shared: Option<Rc<HashMap<String, String>>>,
190 // the following are internal "local"-based declarations in Perl
191 localized_constructed_nodes: Vec<Vec<Node>>,
192 constructed_nodes: Vec<Node>,
193 /// Free-list of emptied `Vec<Node>` buffers, reused across `init_constructed_nodes`
194 /// / `close_constructed_nodes` cycles. The per-body constructed-nodes frame pushes
195 /// here after its elements are drained so the next `init_constructed_nodes` can pop
196 /// a buffer with pre-existing capacity instead of heap-allocating a fresh one.
197 /// Cuts the `Vec<Node>::from_iter` hotspot that dominated absorb profiles.
198 reusable_node_buffers: Vec<Vec<Node>>,
199 localized_boxes: Vec<(Option<Digested>, bool)>,
200 /// Whether `box_to_absorb` never ended ([`crate::stomach::UNENDED`]), read when it was set: an
201 /// alignment is absorbed while mutably borrowed.
202 box_unended: bool,
203 box_to_absorb: Option<Digested>, // local $LaTeXML::BOX;
204 /// Transient handoff from `open_text`'s verbatim-space exception to
205 /// `open_text_internal`: whitespace-only TYPEWRITER text (verbatim
206 /// indentation / space-only verbatim lines) must be INSERTED even where
207 /// the current node needs an auto-open to reach a `#PCDATA` context —
208 /// both whitespace gates would otherwise drop it. Consumed (reset) by
209 /// `open_text_internal`.
210 verbatim_space_pending: bool,
211 /// The font the open text node's runs were inserted with ([`Self::open_text`]), for the ligature test
212 /// when it closes. A run whose font changes only what the XML does not show — its encoding — opens no
213 /// element and would merge into a text node of another encoding: a Latin `\textLR{``q''}` run inside an
214 /// Arabic (LAE) paragraph took the paragraph's font, failed the OT1/T1 quote ligatures and kept its
215 /// grave/acute quote pairs (59r). Perl tests the parent's font (Document.pm `closeText_internal`); the
216 /// difference shows only where an encoding switch opens no element. The `usize` is the byte where the current run
217 /// starts in the node: `apply_text_ligatures` ligates from there, so a run's ligatures never reach an earlier run.
218 text_run_font: Option<(Node, Font, usize)>,
219 /// The text node `close_text_internal` last ligated and how many bytes of it: a return to that node (`set_node`
220 /// back after a `\label`'s float, which closed it) ligates only what is inserted after, as an open run would.
221 ligated_text: Option<(Node, usize)>,
222 /// Source-map (`--source-map`) cache: the current `box_to_absorb`'s
223 /// source range, captured as a plain `Copy` `Locator` at set time so
224 /// stamping never re-borrows the box's `RefCell` mid-absorb (which
225 /// panics for the mutably-borrowed `Alignment` path). Mirrors the
226 /// `box_to_absorb` save stack; `None` when source-map is off.
227 current_box_locator: Option<Locator>,
228 localized_box_locators: Vec<Option<Locator>>,
229 localized_fonts: Vec<Rc<Font>>,
230 /// Streaming mode only: the store holding processed spilled segments. Set
231 /// by the streaming driver after pass 2; `serialize_into` then splices each
232 /// segment's text where its `<_spilled_ ref="N"/>` placeholder sits. `None`
233 /// on the eager path and on fragment documents.
234 spill_store: Option<crate::sxml::SegmentStore>,
235 /// Streaming only: RDFa prefixes USED inside spilled (freed) content,
236 /// recorded at spill time — `set_rdfa_prefixes` scans the live DOM, and
237 /// spilled usages would otherwise vanish from the root's `prefix=`.
238 extra_rdfa_prefixes: Vec<String>,
239 /// Streaming: serialize spill placeholders LITERALLY (`<_spilled_ ref=…/>`)
240 /// instead of splicing the segment text. True during pass 1 (a spilling
241 /// ancestor must keep its children's placeholders — inlining them rebuilt
242 /// multi-GB segments: an 841 MB and a 1.85 GB one on the 131 MB witness,
243 /// and pass 2 died re-parsing them) and on pass-2 fragment docs (which
244 /// re-emit the placeholders they contain). False only at final assembly,
245 /// where the splice resolves placeholders RECURSIVELY.
246 pub literal_placeholders: bool,
247 /// Streaming: called on each subtree as it spills, while it is still in the live DOM, so a document-wide fact that
248 /// pass 2 needs before processing any segment can be gathered from content pass 1 no longer holds (the math
249 /// parser's `d`-token evidence, `latexml_math_parser::read_differential_evidence`).
250 pub spill_observer: Option<fn(&Document, &Node)>,
251 /// Serialize spill segments FLAT — no indentation, no decorative newlines.
252 ///
253 /// A spilled segment's text is an intermediate: pass 2 re-parses it,
254 /// processes it, and re-serializes with `serialize_aux` at the recorded
255 /// depth, and only THAT text reaches the output. The indentation pass 1 used
256 /// to emit was therefore generated, written to disk, read back, materialized
257 /// as libxml2 text nodes, deleted again by `strip_indentation_whitespace`,
258 /// and finally regenerated — pure round-trip tax.
259 ///
260 /// Measured on the 131 MB witness: **51.2% of serialized bytes are leading
261 /// whitespace + newlines** (189.4 MB of 381.5 MB sampled, 6,092,937 lines).
262 /// Over ~2.45 GB of segment text that is ~1.2 GB generated and written, read
263 /// back, and ~40M text nodes allocated in pass 2's parse — which
264 /// `strip_indentation_whitespace` then `unlink_node`s, and unlink does not
265 /// free, so they are orphaned for the fragment's lifetime.
266 ///
267 /// Set for pass 1 only. Fragment documents in pass 2 are separate `Document`s
268 /// and default to `false`, so the OUTPUT keeps its formatting exactly.
269 pub spill_flat: bool,
270 /// Streaming pass 2 only: the fragment's ancestor `xml:id`s at spill time
271 /// (SegmentMeta::ancestors). A `label:`/`id:`-scoped rewrite whose scope
272 /// resolves to one of these covers the WHOLE fragment.
273 pub fragment_ancestor_ids: rustc_hash::FxHashSet<String>,
274 /// The object that printed a raw counter step's number itself, by the step's serial
275 /// ([`note_raw_refstep_object`](Self::note_raw_refstep_object)): an algorithm2e line. A label after the step names
276 /// it wherever the label stands ([`float_to_label_scoped`](Self::float_to_label_scoped)).
277 raw_refstep_objects: HashMap<i64, Node>,
278 /// The keys a `\label` has placed ([`release_earlier_label_holders`](Self::release_earlier_label_holders)).
279 placed_labels: rustc_hash::FxHashSet<String>,
280 /// Streaming pass 2 only: the recorded qname of the fragment's REAL parent
281 /// (SegmentMeta::parent). `finalize_rec` substitutes it for the
282 /// `ltx:_lxfragment` parse wrapper in schema decisions, so top-level
283 /// fragment content is judged against the element it will splice back
284 /// under (e.g. the empty-`ltx:text` collapse needs
285 /// `can_contain(parent, grandchild)`).
286 pub fragment_parent_qname: Option<SymStr>,
287 /// Streaming pass 1 only: suppress the ROOT element's `after_open` hook
288 /// dispatch. Eager semantics guarantee every hook runs with digestion
289 /// COMPLETE (build starts after digestion ends); interleaving would fire
290 /// the root's hooks during fragment 1 instead — with harmful effects, not
291 /// just missed data: the frontmatter hook (`base_utilities.rs`,
292 /// `Tag!("ltx:document", after_open_late)`) would run `insert_frontmatter`
293 /// against still-EMPTY frontmatter state and mark it done, discarding the
294 /// document's abstract when the real content arrived. The streaming driver
295 /// dispatches the root's hooks exactly once, after digestion finishes.
296 defer_root_after_open: bool,
297 /// Size of `node_boxes` after the last sweep (lowered when a spill purges
298 /// below it); the streaming sweep gate measures growth from it.
299 pub last_swept_node_boxes_len: usize,
300 /// The open run of field ink (`FieldRun`): what is being absorbed was digested from a frontmatter field's stored
301 /// tokens (their out-of-band provenance, [`Token::prov`](crate::token::Token)).
302 field_run: Option<FieldRun>,
303 /// The serial of the last field-ink run opened (each run's two marks carry it).
304 field_run_serial: u32,
305 /// The nesting of [`Document::absorb`] calls while field ink is being marked (a run closes at the level it opened).
306 absorb_level: u32,
307 /// How many field-ink whatsits are being absorbed around the current point: what they absorb is their ink.
308 field_inherit: u32,
309 /// Set once the frontmatter placement settled the field ink (latexml_engine `lift_marked_field_ink`): no more
310 /// field marks after it.
311 pub field_ink_settled: bool,
312 /// A TeX box's constructor is being absorbed and has opened no element yet ([`FIELD_BOX_PROPERTY`]): the next
313 /// [`Document::open_element`] is its own and is marked; any absorb or text before it disarms the mark.
314 field_box_pending: bool,
315 /// The construction-time position marks made in this document ([`Document::insert_mark`]), by qualified name, each
316 /// once.
317 marks_made: Vec<String>,
318 /// The back matter floated out of a float or a heading ([`Document::float_backmatter_out_of_container`]): the
319 /// node it was built in, and the insertion point to return to when it closes.
320 floated_backmatter: Vec<(Node, Node)>,
321}
322impl Default for Document {
323 fn default() -> Self { Self::new() }
324}
325
326thread_local! {
327 /// Number of subtree runs spilled to disk this conversion (streaming mode;
328 /// telemetry + test probe). Thread-local like the engine itself.
329 static SPILLED_SEGMENTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
330}
331
332/// How many segment runs the current conversion has spilled (0 = eager).
333pub fn spilled_segment_count() -> usize { SPILLED_SEGMENTS.get() }
334
335thread_local! {
336 /// Segments spliced back from inside another segment at final assembly (a test probe, reset with
337 /// [`spilled_segment_count`]'s).
338 static NESTED_SPLICES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
339}
340
341/// How many nested segments the current conversion's assembly spliced back.
342pub fn nested_splice_count() -> usize { NESTED_SPLICES.get() }
343
344/// Reset the spill probe (the streaming driver calls this at conversion
345/// start; eager conversions never touch it).
346pub fn reset_spilled_segment_count() {
347 SPILLED_SEGMENTS.set(0);
348 NESTED_SPLICES.set(0);
349}
350
351/// The bookkeeping attribute on an `ltx:abstract` whose body was still open at `\end{document}` (sect02.rs
352/// `\lx@end@open@frontmatter`): it swallowed the main matter, so its theorems stay theorems (DG 2026-11-20; OD #1097).
353pub const ABSTRACT_OPEN_AT_END: &str = "_open_at_end";
354
355/// The bookkeeping attribute (dropped at the end, as every `_` attribute) on an object a raw counter step numbered:
356/// the step's serial ([`Document::take_raw_refstep_number`], OXIDIZED_DESIGN_DIVERGENCES #813).
357pub const RAW_REFSTEP_MARK: &str = "_raw_refstep";
358
359/// Whether `node` stands inside an `ltx:Math` (a box in an `ltx:XMText`: `\text{\begin{tcolorbox}…}`): math is
360/// rendered as one formula, so an id there names no object the HTML keeps and a label there would dangle
361/// ([`Document::float_to_label_for`]; review probes rev78g3 tbx.tex, tbx3.tex; repro
362/// `cross-references/math_box_label_climbs_to_the_display.tex`).
363fn within_math(node: &Node) -> bool {
364 let mut parent = node.get_parent();
365 while let Some(current) = parent {
366 if current.get_type() != Some(NodeType::ElementNode) {
367 return false;
368 }
369 if get_node_qname(¤t) == pin!("ltx:Math") {
370 return true;
371 }
372 parent = current.get_parent();
373 }
374 false
375}
376
377/// The target of the processing instructions marking a run of a frontmatter field's ink (`FieldRun`):
378/// construction-time scaffolding, never in the output (the engine's frontmatter placement removes them; the finalize
379/// drops a stray one).
380pub const FIELD_MARK_TARGET: &str = "ltx-field-mark";
381
382thread_local! {
383 /// Has this conversion stamped any token with a field provenance (latexml_engine `\lx@field@mark`)? Only a gate:
384 /// while false, [`Document::absorb`] does no field-ink work at all. Cleared at every conversion's start
385 /// ([`reset_field_provenance`]).
386 static FIELD_PROV_STAMPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
387}
388/// Note that a field's stored tokens now carry their provenance (`FIELD_PROV_STAMPED`).
389pub fn note_field_prov_stamped() { FIELD_PROV_STAMPED.set(true); }
390/// The `FIELD_PROV_STAMPED` gate as it stands (to put it back after a rehearsal the document never keeps,
391/// [`FieldLedgerScope`](crate::token::FieldLedgerScope)).
392pub fn field_prov_stamped() -> bool { FIELD_PROV_STAMPED.get() }
393/// Put the `FIELD_PROV_STAMPED` gate back as [`field_prov_stamped`] read it.
394pub fn restore_field_prov_stamped(stamped: bool) { FIELD_PROV_STAMPED.set(stamped); }
395/// Clear the `FIELD_PROV_STAMPED` gate (conversion start).
396pub fn reset_field_prov_stamped() { FIELD_PROV_STAMPED.set(false); }
397/// Reset every piece of a conversion's field-provenance thread state (OXIDIZED_DESIGN #715): the stamped gate, the
398/// field ledger and its settled flag, the pending cover. Run at the start of every conversion (the converter's
399/// `reset_conversion_state`, at `initialize_report`), whatever the thread converted before: a persistent `cortex_worker` thread, a streaming restart
400/// and the CLI's supplements convert on one thread without an engine reset, and a ledger settled by the previous
401/// document recorded nothing for the next one, which then lifted no print at all (review r4 finding 1).
402pub fn reset_field_provenance() {
403 reset_field_prov_stamped();
404 crate::token::reset_field_cover_pending();
405}
406
407/// The box property holding the field provenance of the token a box or whatsit was digested from (the stomach sets
408/// it, `invoke_token`; [`Token::prov`](crate::token::Token)).
409pub const FIELD_PROV_PROPERTY: &str = "fieldProv";
410/// The box property holding the serial of the box's cover in the field ledger
411/// ([`field_ledger_push`](crate::token::field_ledger_push): its own position, the arguments its invocation consumed, a
412/// boxless font switch before it).
413pub const FIELD_SERIAL_PROPERTY: &str = "fieldSerial";
414/// A formula's first position in a field, under a rehearsal's notes only (the engine's `field_notes`): the opening shift's, its
415/// box stamped by the closing one, whose invocation built it.
416pub const FIELD_FORMULA_START_PROPERTY: &str = "fieldFormulaStart";
417
418/// The whatsit property of a TeX box's constructor (OXIDIZED_DESIGN #715), set where it is digested while field ink
419/// is recorded ([`field_box_whatsit`]): a constructor whose declared mode is `restricted_horizontal` outside math
420/// (`\hbox`, `\mbox`, `\makebox`, `\raisebox`, `\fcolorbox`, `\scalebox`/`\resizebox`/`\rotatebox`/`\reflectbox`,
421/// core `Constructor::digest_to_whatsit`), `\framebox`/`\fbox` (its text branch), an environment whose begin code
422/// opens a box group (a minipage, `dialect::def_environment`). [`Document::absorb`] marks the first element its
423/// constructor opens ([`FIELD_BOX_ATTRIBUTE`]), before it absorbs anything; one that opens none marks nothing.
424pub const FIELD_BOX_PROPERTY: &str = "fieldBox";
425/// The bookkeeping attribute (stripped at finalize, as every `_` attribute) of the element a TeX box's constructor
426/// opened for its material ([`Document::mark_field_box`]).
427pub const FIELD_BOX_ATTRIBUTE: &str = "_fieldbox";
428/// The bookkeeping attribute of the capture of an aligning environment (`{center}`, `{flushleft}`, `{flushright}`)
429/// whose lines the engine sets (OXIDIZED_DESIGN_DIVERGENCES #1200): the whitespace [`Document::open_text`] drops there
430/// is kept on the piece before it ([`SPACE_AFTER_ATTRIBUTE`]).
431pub const ALIGNED_LINES_ATTRIBUTE: &str = "_alignedlines";
432/// The bookkeeping attribute of a line an aligning environment nested in another's lines aligned, which the outer one
433/// leaves as it is: the inner alignment is in force at the line's `\par` (OXIDIZED_DESIGN_DIVERGENCES #1200).
434pub const NESTED_LINE_ATTRIBUTE: &str = "_nestedline";
435/// The whitespace that followed a piece of an aligning environment's line ([`ALIGNED_LINES_ATTRIBUTE`]), the space
436/// between it and the next piece once they are one paragraph.
437pub const SPACE_AFTER_ATTRIBUTE: &str = "_spaceafter";
438
439/// The box property of a Warning that belongs to the box's print, not to its digestion ([`absorb_warning`]): raised
440/// when [`Document::absorb`] takes the box (a [`Tbox`] or a whatsit) into the document, once per key. A box digested and
441/// never absorbed — measured (`\settowidth`), saved and never used (`\sbox`), made by a rehearsal or a speculative
442/// digestion, or under a [`DiagnosticsHold`](crate::util::logger::DiagnosticsHold) it discards — raises nothing and
443/// leaves no key set, so the box the document prints still raises it. An undecodable math glyph's once-per-font
444/// Warning (latexml_engine sect08.rs `undecodable_math_slot`, OXIDIZED_DESIGN_DIVERGENCES #27).
445pub const ABSORB_WARNING_PROPERTY: &str = "absorbWarning";
446// `pin!` takes a literal: [`raise_absorb_warning`]'s lookup spells the name, tied to the constant here.
447const _: () = assert!(matches!(
448 ABSORB_WARNING_PROPERTY.as_bytes(),
449 b"absorbWarning"
450));
451/// The source position, recorded at digestion, at which a constructor's [`ABSORB_WARNING_PROPERTY`] Warning is raised:
452/// the gullet's as the constructor's arguments are read (core `dialect::transfer_common_constructor_options`), the
453/// position a [`Tbox`] carries as its locator. A whatsit's own locator is set only under `--source-map`.
454pub const ABSORB_WARNING_LOCATOR_PROPERTY: &str = "absorbWarningLocator";
455const _: () = assert!(matches!(
456 ABSORB_WARNING_LOCATOR_PROPERTY.as_bytes(),
457 b"absorbWarningLocator"
458));
459
460/// The [`ABSORB_WARNING_PROPERTY`] value of `Warning:<category>:<object> <message>`, raised once per `once_key`: the
461/// first absorbed box carrying the key raises it, the key is then set (a global state value, as the text side's once
462/// keys are), and every later one is silent.
463pub fn absorb_warning(once_key: &str, category: &str, object: &str, message: &str) -> Stored {
464 Stored::Strings(Rc::from([
465 arena::pin(once_key),
466 arena::pin(category),
467 arena::pin(object),
468 arena::pin(message),
469 ]))
470}
471
472/// Raise the [`ABSORB_WARNING_PROPERTY`] Warning `object` carries, if its key is not yet set; the one place the key is
473/// set. Looked up by its cached symbol and without a copy of the map: this runs for every box absorbed.
474fn raise_absorb_warning(object: &Digested) {
475 let Some((warning, recorded)) =
476 object.with_properties(|props| match props.get_sym(pin!("absorbWarning")) {
477 Some(Stored::Strings(warning)) => Some((
478 Rc::clone(warning),
479 match props.get_sym(pin!("absorbWarningLocator")) {
480 Some(Stored::Locator(locator)) => Some(**locator),
481 _ => None,
482 },
483 )),
484 _ => None,
485 })
486 else {
487 return;
488 };
489 let [key, category, name, message] = *warning else {
490 return;
491 };
492 if state::lookup_bool_sym(key) {
493 return;
494 }
495 state::assign_value(&arena::to_string(key), true, Some(state::Scope::Global));
496 // At the box's source position, where it was digested: a constructor's recorded one
497 // ([`ABSORB_WARNING_LOCATOR_PROPERTY`]), else the box's locator (a Tbox's). The gullet's, at build time, is the
498 // document's end.
499 let location = recorded
500 .or_else(|| object.get_locator())
501 .map_or_else(crate::gullet::get_location, |locator| s!("at {locator}"));
502 emit_warn(
503 &arena::to_string(category),
504 &arena::to_string(name),
505 &s!(
506 "{}\n\t{location}\n\tIn {}:{}:{}\n",
507 arena::to_string(message),
508 file!(),
509 line!(),
510 column!()
511 ),
512 );
513}
514
515/// Can a box digested now still matter to a frontmatter field's print (the field ledger not settled)? The gate of
516/// every digest-time field-box mark, checked before anything else is looked up. It does not wait for a field to be
517/// stamped: a header box may be digested before the document declares its `\title` (fms1 round-6 review finding 1);
518/// [`Document::mark_field_box`] applies the stamp at absorb time.
519#[inline]
520pub fn field_box_marks_live() -> bool { crate::token::field_ledger_live() }
521
522/// Mark `whatsit` as a TeX box's constructor ([`FIELD_BOX_PROPERTY`]), while a field's print can still be lifted.
523pub fn field_box_whatsit(whatsit: &mut crate::whatsit::Whatsit) {
524 if field_box_marks_live() {
525 whatsit.set_property(FIELD_BOX_PROPERTY, true);
526 }
527}
528
529/// The box property of an alignment's whatsit holding the field-ledger serials of the row-end markers its body
530/// consumed (a field value's `\\`, [`field_ink_taken_serials`]): taken when the document absorbs the whatsit.
531pub const FIELD_TAKEN_PROPERTY: &str = "fieldTaken";
532
533/// The field-ledger serials of the boxes in `digested` (an alignment's row-end marker, a value's `\\`, latexml_engine
534/// `digest_alignment_body`), pushed onto `serials`: the structure the print is set in consumes them, never absorbed.
535/// The alignment keeps them on its whatsit ([`FIELD_TAKEN_PROPERTY`]), and they are noted taken
536/// ([`field_ledger_take`](crate::token::field_ledger_take)) only when [`Document::absorb`] absorbs that whatsit, so
537/// the run of ink the row ends may cover them and no other run does; an alignment never shown (in an unused
538/// `\setbox`, `\sbox`, `{lrbox}`) takes nothing (OXIDIZED_DESIGN #715; review r4 finding 2, probes s25, s27, s28).
539pub fn field_ink_taken_serials(digested: &Digested, serials: &mut Vec<u32>) {
540 if !FIELD_PROV_STAMPED.get() || !crate::token::field_ledger_live() {
541 return;
542 }
543 for item in digested.unlist() {
544 if matches!(item.data(), DigestedData::List(_)) {
545 field_ink_taken_serials(&item, serials);
546 } else if let Some(serial) =
547 item.with_properties(|props| match props.get_sym(pin!("fieldSerial")) {
548 Some(Stored::Int(serial)) => u32::try_from(*serial).ok(),
549 _ => None,
550 })
551 {
552 serials.push(serial);
553 }
554 }
555}
556
557/// A run of one frontmatter field's ink being absorbed: boxes digested from that field's stored tokens, one after the
558/// other at one absorb level, in the order of the value (a box whose cover ends at or before the start of a box the run
559/// holds reads the value again and begins a new print: `\StrLeft{\@title}{3}\@title` is two runs). It opens with `<?ltx-field-mark begin <field> <id>?>`
560/// where its first box goes and closes with `<?ltx-field-mark end <field> <id> <serials>?>` after its last (`<serials>`:
561/// the field-ledger serials of the boxes it absorbed, `first:last` intervals joined by `,`,
562/// [`field_ledger_cover`](crate::token::field_ledger_cover), so the engine can tell a whole print from a fragment by
563/// every position of the value its own boxes consumed, its structure's tokens too). The two marks of a run carry its
564/// id: they pair by construction, never with another print's (OXIDIZED_DESIGN #715).
565#[derive(Debug, Clone)]
566struct FieldRun {
567 field: u16,
568 id: u32,
569 level: u32,
570 /// the serials of the boxes absorbed, as inclusive intervals in absorption order
571 serials: Vec<(u32, u32)>,
572 /// the highest position a box of the run starts at
573 max_start: u16,
574}
575
576impl FieldRun {
577 /// Note that the run absorbed the box recorded with `serial` (a box used twice is in each run that absorbs it).
578 fn take(&mut self, serial: u32) {
579 match self.serials.last_mut() {
580 Some((first, last)) if *first <= serial && serial <= *last + 1 => *last = (*last).max(serial),
581 _ => self.serials.push((serial, serial)),
582 }
583 }
584}
585
586/// Element names whose closed instances may be spilled from ROOT level.
587/// Leading non-sectional root children (title, creators, abstract, resources)
588/// must stay live: the frontmatter fallback and `maybe_promote_leading_title`
589/// operate on them at end-of-build (`base_utilities.rs`).
590/// Root-level children the frontmatter machinery keeps MUTATING after they
591/// close — the schema's `SectionalFrontMatter.class`/`FrontMatter.class`
592/// (LaTeXML-structure.rnc:666-672) plus the resource/RDF/capture nodes: a later
593/// `\maketitle` or `\lx@frontmatter@fallback` re-inserts, merges and retypes
594/// them (`insert_frontmatter`, the `_Capture_` wrapper, contact→note). Their
595/// content is never spilled, even the parts holding no prose (a `personname`
596/// spilled from under a resident `creator` left `\thanks` marks absorbing into
597/// a placeholder: sweep witnesses tests/cluster_regressions/frontmatter_spconf_name,
598/// tests/structure/amsarticle). Body wrappers (`ltx:para`, `ltx:quote`,
599/// `ltx:figure`, …) are closed for good and take `spill_prose_free_children`.
600const ROOT_FRONTMATTER: &[&str] = &[
601 "title",
602 "toctitle",
603 "subtitle",
604 "tags",
605 "creator",
606 "date",
607 "abstract",
608 "keywords",
609 "classification",
610 "pubnote",
611 "acknowledgements",
612 "resource",
613 "rdf",
614 "_Capture_",
615];
616
617const ROOT_SPILLABLE: &[&str] = &[
618 "section",
619 "chapter",
620 "part",
621 "appendix",
622 "subsection",
623 "subsubsection",
624 "paragraph",
625 "subparagraph",
626 "index",
627 "glossary",
628 "acknowledgements",
629 "pagination",
630];
631
632/// The placeholder element left in the live DOM where a spilled run sat.
633/// Never serialized: `serialize_into` splices the processed segment instead.
634pub(crate) const SPILL_PLACEHOLDER: &str = "_spilled_";
635
636/// The placeholder attribute of a spilled run that prints nothing ([`prints_nothing`]).
637const SPILLED_INKLESS: &str = "inkless";
638
639/// Is `node` the placeholder of a spilled run that prints nothing (`prints_nothing`)? Content-free to the frontmatter's
640/// cover reading as the run is (titlepage_layout.rs `node_is_content_free`), so a late abstract follows a cover holding
641/// article's `\newpage\null` (`\@maketitle`) at a small fragment budget as in the eager build
642/// (OXIDIZED_DESIGN_DIVERGENCES #903, #1149).
643pub fn is_spilled_inkless(node: &Node) -> bool {
644 node.get_name() == SPILL_PLACEHOLDER && node.has_attribute(SPILLED_INKLESS)
645}
646
647/// Does `node` print nothing: a page break, or a subtree of paragraphs, lines, breaks and `ltx:text` that can paint
648/// nothing (none of `framed`, `framecolor`, `backgroundcolor`, `class`, `cssstyle`), holding no text but whitespace? The
649/// frontmatter's reading of a content-free node (titlepage_layout.rs `node_is_content_free`,
650/// `subtree_elements_all_invisible`), for a run spilled out of its reach. (The attribute list is `text_is_ink_free`'s,
651/// titlepage_layout.rs: change both together.)
652fn prints_nothing(node: &Node) -> bool {
653 match node.get_type() {
654 Some(NodeType::TextNode) => node.get_content().trim().is_empty(),
655 Some(NodeType::ElementNode) => {
656 let q = get_node_qname(node);
657 if q == pin!("ltx:pagination") {
658 return true;
659 }
660 let ink_free_text = q == pin!("ltx:text")
661 && ![
662 "framed",
663 "framecolor",
664 "backgroundcolor",
665 "class",
666 "cssstyle",
667 ]
668 .iter()
669 .any(|attr| node.has_attribute(attr));
670 (ink_free_text || q == pin!("ltx:para") || q == pin!("ltx:p") || q == pin!("ltx:break"))
671 && node.get_child_nodes().iter().all(prints_nothing)
672 },
673 _ => true,
674 }
675}
676
677impl Object for Document {
678 fn get_locator(&self) -> Option<Locator> {
679 self
680 .get_node_box(&self.node)
681 .and_then(|tbox| tbox.get_locator())
682 }
683}
684
685/// Attachment policy for `Document::add_comment`. Kept module-local.
686enum Placement_ {
687 AppendChild,
688 PrevSibling,
689}
690
691/// Whether `node`'s subtree (itself included) holds a paragraph with visible
692/// text outside any picture: `descendant-or-self::ltx:p[not(ancestor::ltx:picture)]
693/// [.//text()[normalize-space()][not(ancestor::ltx:picture)]]`, walked with an
694/// early exit instead of collecting every match. The streaming spill asks it for
695/// every resident root child on every yield (roadmap stream C, 2026-09-25).
696fn subtree_holds_prose(node: &Node) -> bool {
697 fn is_ltx(node: &Node, local: &str) -> bool {
698 node.get_type() == Some(NodeType::ElementNode) && xml::is_ltx_element(node, local)
699 }
700 fn text_outside_pictures(node: &Node) -> bool {
701 let mut child = node.get_first_child();
702 while let Some(c) = child {
703 let holds = match c.get_type() {
704 // `normalize-space()` strips XML whitespace only (#x20 #x9 #xD #xA),
705 // so a no-break space is visible text.
706 Some(NodeType::TextNode | NodeType::CDataSectionNode) => c
707 .get_content()
708 .contains(|ch: char| !matches!(ch, ' ' | '\t' | '\r' | '\n')),
709 Some(NodeType::ElementNode) => !is_ltx(&c, "picture") && text_outside_pictures(&c),
710 _ => false,
711 };
712 if holds {
713 return true;
714 }
715 child = c.get_next_sibling();
716 }
717 false
718 }
719 fn walk(node: &Node) -> bool {
720 if node.get_type() != Some(NodeType::ElementNode) || is_ltx(node, "picture") {
721 return false;
722 }
723 if is_ltx(node, "p") && text_outside_pictures(node) {
724 return true;
725 }
726 let mut child = node.get_first_child();
727 while let Some(c) = child {
728 if walk(&c) {
729 return true;
730 }
731 child = c.get_next_sibling();
732 }
733 false
734 }
735 let mut up = node.get_parent();
736 while let Some(a) = up {
737 if is_ltx(&a, "picture") {
738 return false;
739 }
740 up = a.get_parent();
741 }
742 walk(node)
743}
744
745impl Document {
746 pub fn new() -> Self {
747 crate::ensure_libxml_init(); // Thread-safe libxml2 initialization
748 // Node-mutation aliasing is enforced by libxml's `Node::node_ptr_mut`
749 // (`RefCell::try_borrow_mut`, libxml >= 0.3.14): it rejects only an *active*
750 // re-entrant borrow, not a high `Rc::strong_count` from benign clones. The
751 // former `set_node_rc_guard(8192)` band-aid — which raised a clone-count
752 // threshold to stop spurious "shared Node" errors on deeply-shared docs
753 // (e.g. arxiv 0805.2376 dcpic) — is no longer needed. See WISDOM.md #46.
754 let doc_scaffold = XmlDoc::new().unwrap();
755 let root = match doc_scaffold.get_root_element() {
756 Some(root) => root,
757 None => doc_scaffold.as_node(), // when empty, set the document node as a node.
758 };
759 Self::from_parts(doc_scaffold, root, HashMap::default())
760 }
761
762 /// Build a `Document` around an existing `XmlDoc`, insertion point, and font
763 /// map without allocating a throwaway `XmlDoc` (Audit F4).
764 fn from_parts(document: XmlDoc, node: Node, node_fonts: HashMap<u64, Font>) -> Self {
765 Document {
766 document,
767 node,
768 node_boxes: HashMap::default(),
769 node_fonts,
770 idstore: HashMap::default(),
771 idref_index: None,
772 spilled_ids: rustc_hash::FxHashSet::default(),
773 spill_anchors: rustc_hash::FxHashSet::default(),
774 spilled_anchor_counters: rustc_hash::FxHashMap::default(),
775 fragment_anchor_id: None,
776 svg_ids: rustc_hash::FxHashSet::default(),
777 svg_id_suffixes: rustc_hash::FxHashMap::default(),
778 spilled_ns_prefixes: rustc_hash::FxHashSet::default(),
779 rewrite_labels: HashMap::default(),
780 rewrite_labels_shared: None,
781 pending: Vec::new(),
782 localized_constructed_nodes: Vec::new(),
783 constructed_nodes: Vec::new(),
784 reusable_node_buffers: Vec::new(),
785 box_to_absorb: None,
786 verbatim_space_pending: false,
787 text_run_font: None,
788 ligated_text: None,
789 current_box_locator: None,
790 localized_box_locators: Vec::new(),
791 context: None,
792 localized_boxes: Vec::new(),
793 box_unended: false,
794 localized_fonts: Vec::new(),
795 spill_store: None,
796 extra_rdfa_prefixes: Vec::new(),
797 literal_placeholders: false,
798 spill_observer: None,
799 spill_flat: false,
800 fragment_ancestor_ids: rustc_hash::FxHashSet::default(),
801 raw_refstep_objects: HashMap::default(),
802 placed_labels: rustc_hash::FxHashSet::default(),
803 fragment_parent_qname: None,
804 defer_root_after_open: false,
805 last_swept_node_boxes_len: 0,
806 field_run: None,
807 field_run_serial: 0,
808 absorb_level: 0,
809 field_inherit: 0,
810 field_ink_settled: false,
811 field_box_pending: false,
812 marks_made: Vec::new(),
813 floated_backmatter: Vec::new(),
814 }
815 }
816
817 /// Wrap an existing XML document (a streamed fragment from
818 /// [`crate::sxml::FragmentReader`]) as a `Document`, so the pass-2 phases —
819 /// rewrites, math parsing, per-fragment finalize — run on it with the same
820 /// machinery the eager path uses. The insertion point starts at the root;
821 /// the idstore is rebuilt from the fragment's own `xml:id`s; `node_fonts`
822 /// is seeded by the caller (the hash→Font table is conversion-global and
823 /// pointer-free, so sharing its contents is safe).
824 pub fn from_xml_document(doc: XmlDoc, node_fonts: HashMap<u64, Font>) -> Result<Self> {
825 crate::ensure_libxml_init();
826 let node = match doc.get_root_element() {
827 Some(root) => root,
828 None => doc.as_node(),
829 };
830 let mut document = Self::from_parts(doc, node, node_fonts);
831 if let Some(root) = document.document.get_root_element() {
832 document.record_node_ids(&root)?;
833 }
834 Ok(document)
835 }
836
837 /// Get the element at (or containing) the current insertion point.
838 pub fn get_element(&self) -> Option<Node> {
839 let mut node = &self.node;
840 let parent = node.get_parent();
841 if node.get_type() == Some(NodeType::TextNode) {
842 node = parent.as_ref().unwrap();
843 }
844 let final_type = node.get_type();
845 if final_type.is_none() || final_type == Some(NodeType::DocumentNode) {
846 None
847 } else {
848 Some(node.clone())
849 }
850 }
851
852 /// Find the nodes according to the given `xpath` expression,
853 /// the xpath is relative to $node (if given), otherwise to the document node.
854 pub fn findnodes(&mut self, xpath: &str, node_opt: Option<&Node>) -> Vec<Node> {
855 let node = match node_opt {
856 Some(node) => Cow::Borrowed(node),
857 None => match self.document.get_root_element() {
858 Some(root) => Cow::Owned(root),
859 None => return Vec::new(),
860 },
861 };
862 self.get_xpath();
863 let context = self.context.as_mut().expect("get_xpath made it");
864 match context.walk(&self.document, xpath, Some(&node)) {
865 Some(found) => found,
866 None => context.findnodes(xpath, Some(&node)),
867 }
868 }
869
870 /// Get an XPath context that knows about our namespace mappings.
871 pub fn get_xpath(&mut self) -> &mut XPath {
872 if let Some(ref mut ctxt) = self.context {
873 ctxt
874 } else {
875 let mut context = XPath::new(&self.document, HashMap::default());
876 model::with_code_namespaces(|code_ns| {
877 for (prefix, ns) in code_ns {
878 // TODO: Is this too slow? We may need to store an active context in the state as an
879 // alternative
880 arena::with2(*prefix, *ns, |p_str, ns_str| {
881 context
882 .register_namespace(p_str, ns_str)
883 .expect("register_namespace has no reason to fail during get_xpath?");
884 });
885 }
886 });
887 self.context = Some(context);
888 self.context.as_mut().unwrap()
889 }
890 }
891
892 /// The document's elements that `keep` accepts, in document order: `//*[pred]` as a walk, which cannot fail on a large
893 /// document as libxml2's node set does ([`xml::descendant_or_self_elements`], #802).
894 pub fn find_elements(&self, keep: impl FnMut(&Node) -> bool) -> Vec<Node> {
895 match self.document.get_root_element() {
896 Some(root) => xml::descendant_or_self_elements(&root, keep),
897 None => Vec::new(),
898 }
899 }
900
901 /// Like findnodes, but only returns the first matched node
902 pub fn findnode(&mut self, xpath: &str, node: Option<&Node>) -> Option<Node> {
903 self.get_xpath();
904 let context = self.context.as_mut().expect("get_xpath made it");
905 if let Some(node) = node
906 && let Some(first) = context.walk_first(&self.document, xpath, Some(node))
907 {
908 return first;
909 }
910 let mut nodes = context.findnodes(xpath, node);
911 if nodes.is_empty() {
912 None
913 } else {
914 Some(nodes.remove(0))
915 }
916 }
917
918 /// Like findnodes, but expects an xpath that evaluates to a literal value (e.g. for attributes)
919 pub fn findvalues(&mut self, xpath: &str, node_opt: Option<&Node>) -> Vec<String> {
920 match node_opt {
921 Some(node) => self.get_xpath().findvalues(xpath, Some(node)),
922 None => match self.document.get_root_element() {
923 Some(root) => self.get_xpath().findvalues(xpath, Some(&root)),
924 _ => Vec::new(),
925 },
926 }
927 }
928
929 /// The current insertion point: the node that absorbed content is appended
930 /// to, and the one [`open_element`](Self::open_element) opens beneath.
931 /// Perl's `$document->getNode`.
932 pub fn get_node(&self) -> &Node { &self.node }
933 pub fn get_node_mut(&mut self) -> &mut Node { &mut self.node }
934
935 pub fn get_document(&self) -> &XmlDoc { &self.document }
936 pub fn get_document_mut(&mut self) -> &mut XmlDoc { &mut self.document }
937
938 // **********************************************************************
939 // This should be called before returning the final XML::LibXML::Document to the
940 // outside world. It resolves the fonts for each node relative to it's
941 // ancestors. It removes the `helper' attributes that store fonts, source
942 // box, etc.
943 pub fn finalize(&mut self) -> Result<()> {
944 // Belt-and-suspenders idstore rebuild before prune_xmduals.
945 // Originally guarded a SIGSEGV on arxiv 1605.08055 where
946 // `mark_xmnode_visibility` dereferenced dangling lookup_id
947 // entries while recursing through XMRef nodes. Cycle 72 audited
948 // the 5 hazard call sites the earlier comment listed (math-parser
949 // `replace_tree` at parser.rs:456/690, `unbind_node` loops at
950 // parser.rs:639/856 and rewrite.rs:522); all 5 now have proper
951 // unrecord_node_ids / remove_node-cascade coverage. The rebuild
952 // call is retained as a safety net pending empirical
953 // 10k-sandbox verification on 1605.08055 — see SYNC_STATUS.md
954 // D3b [~] entry. A fresh DOM walk drops any surviving dangling
955 // entries; duplicates in DOM get modify_id via record_node_ids.
956 self.rebuild_idstore_from_dom()?;
957 // Sweep dangling XMRefs that were specifically created by
958 // amsmath::rearrange_ams_split (tagged with `_split_ref="1"`).
959 // The math parser later absorbs some XMArray cells (inserted
960 // MULOPs, etc.) and the parallel XMWrap refs end up pointing
961 // at vanished targets, cascading through Warning:expected:node
962 // (here) and Error:expected:id (post-process) for ~1500 wp3
963 // canvas papers. Restricting the sweep to `_split_ref` avoids
964 // breaking declare_test's renamed-id case (XMRefs pointing to
965 // `S1.Ex1.m1.1`-style ids that resolve through Perl-faithful
966 // idstore staleness; those don't carry the marker).
967 self.prune_dangling_split_xmrefs()?;
968 self.prune_xmduals()?;
969 if let Some(mut root) = self.document.get_root_element() {
970 self.set_local_font(Rc::new(Font::text_default()));
971 self.finalize_rec(&mut root)?;
972 self.set_rdfa_prefixes();
973 self.apply_document_namespace_declarations(&mut root);
974 self.expire_local_font();
975 }
976 Ok(())
977 }
978
979 /// [`finalize`](Self::finalize) restricted to one subtree: resolve fonts
980 /// against ancestors and strip the `_font`/`_autoopened`/… bookkeeping
981 /// attributes, without the document-level passes (idstore rebuild, XMDual
982 /// pruning, RDFa/namespace declarations) that only make sense for a complete
983 /// document.
984 ///
985 /// Used by `latexml_post::make_bibliography` to render a `.bib` field value
986 /// into an XML fragment through the real engine: it absorbs into a scratch
987 /// `ltx:text` wrapper and serializes that wrapper's children.
988 ///
989 /// Whole-document [`finalize`](Self::finalize) cannot serve that caller —
990 /// **not** because it errors (it returns `Ok`), but because running
991 /// `finalize_rec` from the ROOT legitimately UNWRAPS a redundant font-only
992 /// `ltx:text`: measured on such a scratch document, the content survives at
993 /// the root while the caller's wrapper handle is left detached and childless
994 /// (`wrapper_children 1 -> 0`, `parent = None`), so it serializes to nothing.
995 /// Starting the recursion AT the wrapper keeps it addressable.
996 pub fn finalize_subtree(&mut self, node: &mut Node) -> Result<()> {
997 self.finalize_subtree_in(node, Font::text_default())
998 }
999
1000 /// [`finalize_subtree`](Self::finalize_subtree) under `context`, the font declared around the subtree (a streamed
1001 /// segment's [`SegmentMeta::font`](crate::sxml::SegmentMeta)).
1002 pub fn finalize_subtree_in(&mut self, node: &mut Node, context: Font) -> Result<()> {
1003 self.set_local_font(Rc::new(context));
1004 let result = self.finalize_rec(node);
1005 self.expire_local_font();
1006 result
1007 }
1008
1009 /// Apply registered document namespace declarations to the root element.
1010 /// Perl's RegisterDocumentNamespace stores prefix→URI mappings in the model.
1011 /// These must appear as xmlns:prefix="URI" on the root element during serialization.
1012 /// Only emit namespaces that are actually used in the document (Perl behavior).
1013 fn apply_document_namespace_declarations(&self, root: &mut Node) {
1014 let prefixes = model::get_document_namespace_prefixes();
1015 // Collect which prefixes are actually used in the document
1016 let nsnodes = root.get_namespace_declarations();
1017 let existing_prefixes: Vec<String> = nsnodes.iter().map(|ns| ns.get_prefix()).collect();
1018 // Skip internal/default namespaces, namespaces containing "DEFAULT#" (internal model
1019 // entries), and prefixes already declared on root.
1020 let wanted = |prefix: &str, ns_uri: &str| {
1021 !(prefix.is_empty() || prefix == "ltx" || prefix == "xml")
1022 && !ns_uri.contains("DEFAULT#")
1023 && !existing_prefixes.iter().any(|p| p == prefix)
1024 };
1025 // Whether a descendant uses the prefix — on the resident DOM, or inside a subtree that
1026 // streaming pass 1 spilled to disk before this pass ran (`spilled_ns_prefixes`). One walk
1027 // answers for every prefix the spill does not.
1028 let to_find: Vec<&str> = prefixes
1029 .iter()
1030 .filter(|(prefix, ns_uri)| {
1031 wanted(prefix, ns_uri) && !self.spilled_ns_prefixes.contains(prefix)
1032 })
1033 .map(|(prefix, _)| prefix.as_str())
1034 .collect();
1035 let in_use = namespace_prefixes_in_use(root, &to_find);
1036 for (prefix, ns_uri) in &prefixes {
1037 if !wanted(prefix, ns_uri) {
1038 continue;
1039 }
1040 if self.spilled_ns_prefixes.contains(prefix) || in_use.contains(prefix.as_str()) {
1041 let attr_name = format!("xmlns:{prefix}");
1042 root.set_attribute(&attr_name, ns_uri).ok();
1043 }
1044 }
1045 }
1046
1047 /// Remove xml:ids from XMTok elements that aren't referenced by any idref.
1048 /// The Rust math parser generates xml:ids on XMTok nodes for internal XMRef linkage
1049 /// during parsing. After finalization (which includes prune_xmduals), some ids
1050 /// are no longer referenced. Perl's parser doesn't generate these ids.
1051 pub fn cleanup_unreferenced_xmtok_ids(&mut self) {
1052 use rustc_hash::FxHashSet as HashSet;
1053 let mut referenced_ids: HashSet<String> = HashSet::default();
1054 let xml_ns = "http://www.w3.org/XML/1998/namespace";
1055 // One walk for `descendant-or-self::*[@idref]` and `descendant-or-self::ltx:XMTok[@xml:id]` (#802).
1056 let toks = self.find_elements(|node| {
1057 if let Some(idref) = node.get_attribute_no_ns("idref") {
1058 referenced_ids.insert(idref);
1059 }
1060 xml::is_ltx_element(node, "XMTok") && node.get_attribute_ns("id", xml_ns).is_some()
1061 });
1062 for mut tok in toks {
1063 if let Some(id) = tok.get_attribute_ns("id", xml_ns)
1064 && !referenced_ids.contains(&id)
1065 {
1066 self.unrecord_id(&id);
1067 // Remove both the prefixed attribute and the ns attribute
1068 let _ = tok.remove_attribute("xml:id");
1069 let _ = tok.remove_attribute_ns("id", xml_ns);
1070 }
1071 }
1072 }
1073
1074 /// Iterative implementation of finalize_rec to avoid stack overflow.
1075 /// Uses an explicit heap-allocated work stack instead of call-stack recursion.
1076 /// Resolves fonts for each node relative to its ancestors, and removes
1077 /// helper attributes (_font, _standalone_font, etc).
1078 fn finalize_rec(&mut self, node: &mut Node) -> Result<()> {
1079 // Work items for the iterative traversal.
1080 // Enter: process font declarations and children (text children handled inline,
1081 // element children deferred to the stack).
1082 // PostElement: after finalizing an element child, check for font wrapper collapse.
1083 // PostWork: after all children processed, remove bookkeeping attrs and expire font.
1084 #[allow(clippy::enum_variant_names)]
1085 enum Work {
1086 Enter(Node),
1087 PostElement {
1088 child: Node,
1089 parent_qname: SymStr,
1090 was_forcefont: bool,
1091 },
1092 PostWork {
1093 node: Node,
1094 },
1095 }
1096
1097 let mut stack: Vec<Work> = Vec::new();
1098 // Track nodes that have no visible attributes after bookkeeping removal.
1099 // Used in PostElement to decide collapse without calling get_attributes()
1100 // (which can crash on corrupted libxml2 attribute lists after replace_node).
1101 let mut empty_attr_nodes: HashSet<usize> = HashSet::default();
1102 // Defer collapse operations to avoid libxml2 memory corruption.
1103 // Collapsing nodes during tree traversal corrupts attribute linked lists
1104 // of ancestor nodes. By collecting collapses and running them after
1105 // the entire traversal completes, we avoid accessing corrupted state.
1106 let mut deferred_collapses: Vec<(Node, SymStr)> = Vec::new();
1107 // The text font declared around each open `ltx:Math`, innermost last: an `XMText` in it is text, set in that font
1108 // (see the reset at `ltx:Math` below).
1109 let mut math_outer_fonts: Vec<Rc<Font>> = Vec::new();
1110 stack.push(Work::Enter(node.clone()));
1111
1112 while let Some(work) = stack.pop() {
1113 match work {
1114 Work::Enter(mut current) => {
1115 let raw_qname = get_node_qname(¤t);
1116 // Streaming pass 2: judge the fragment's parse wrapper as the REAL
1117 // parent it splices back under, so schema decisions for top-level
1118 // fragment content match the eager walk (see the field docs).
1119 let qname = match self.fragment_parent_qname {
1120 Some(parent) if raw_qname == pin!("ltx:_lxfragment") => parent,
1121 _ => raw_qname,
1122 };
1123 let local_font = self.get_local_font().unwrap();
1124 // _standalone_font is typically for metadata that gets extracted out of context
1125 let mut declared_font = if current.has_attribute("_standalone_font") {
1126 Cow::Borrowed(&*FONT_TEXT_DEFAULT)
1127 } else {
1128 Cow::Borrowed(&*local_font)
1129 };
1130 // An `XMText` (`\text`, `\mbox` in a formula) is set in the text font around the formula (amstext's `\text`
1131 // takes `\f@family`, `\f@series`, `\f@shape`), so its content is written against that, as Perl writes it.
1132 if qname == pin!("ltx:XMText")
1133 && let Some(outer) = math_outer_fonts.last()
1134 {
1135 let mut text_context = declared_font.into_owned();
1136 text_context.family.clone_from(&outer.family);
1137 text_context.series.clone_from(&outer.series);
1138 text_context.shape.clone_from(&outer.shape);
1139 declared_font = Cow::Owned(text_context);
1140 }
1141
1142 // TODO: _pre_comment / _comment insertion requires create_comment support in libxml
1143 // wrapper Perl: parent.insertBefore(XML::LibXML::Comment.new(comment), node)
1144 // Perl: parent.insertAfter(XML::LibXML::Comment.new(comment), node)
1145
1146 // Use boxed HashMap to reduce work item size — Font is ~500 bytes per entry
1147 let mut pending_declaration: Box<HashMap<String, (String, Font)>> = Box::default();
1148
1149 if self.has_node_font(¤t) {
1150 let desired_font = self.get_node_font(¤t);
1151 *pending_declaration = desired_font.relative_to(&declared_font);
1152 if (current.get_first_child().is_some() || current.has_attribute("_force_font"))
1153 && !pending_declaration.is_empty()
1154 {
1155 let mut keys_to_remove: Vec<SymStr> = Vec::new();
1156 let mut attrs_to_set: Vec<(SymStr, SymStr)> = Vec::new();
1157 for (key, (value, properties)) in pending_declaration.iter() {
1158 if model::can_have_attribute(qname, arena::pin(key)) {
1159 let key_sym = arena::pin(key);
1160 attrs_to_set.push((key_sym, arena::pin(value)));
1161 // Merge to set the font currently in effect
1162 declared_font = Cow::Owned(declared_font.merge_ref(properties));
1163 keys_to_remove.push(key_sym);
1164 }
1165 }
1166
1167 for (key, mut value) in attrs_to_set {
1168 if key == pin!("class") {
1169 // Merge and sort class values alphabetically, matching Perl's behavior
1170 if let Some(ovalue) = current.get_attribute("class") {
1171 let new_s = arena::with(value, |s| s.to_string());
1172 let mut classes: Vec<&str> = new_s
1173 .split_whitespace()
1174 .chain(ovalue.split_whitespace())
1175 .collect();
1176 classes.sort_unstable();
1177 classes.dedup();
1178 value = arena::pin(classes.join(" "));
1179 }
1180 }
1181 // Resolve to owned Strings before calling set_attribute,
1182 // to avoid holding an arena borrow while set_attribute may need arena::pin
1183 // for schema-based attribute filtering (canHaveAttribute check).
1184 let key_s = arena::with(key, |s| s.to_string());
1185 let value_s = arena::with(value, |s| s.to_string());
1186 self.set_attribute(&mut current, &key_s, &value_s)?;
1187 }
1188 for key in keys_to_remove {
1189 arena::with(key, |key_str| pending_declaration.remove(key_str));
1190 }
1191 }
1192 }
1193 // Optionally add ids to all nodes (AFTER all parsing, rearrangement, etc)
1194 // (gate on the RAW name: a fragment wrapper standing in for its
1195 // real parent must not mint an id — it is never serialized).
1196 if raw_qname != pin!("ltx:document")
1197 && raw_qname != pin!("ltx:_lxfragment")
1198 && state::lookup_bool("GENERATE_IDS")
1199 && !current.has_attribute("xml:id")
1200 && !current.has_attribute("id") // SVG elements with plain id don't need xml:id
1201 && arena::with(qname, |qname_str| can_have_attribute(qname_str, "xml:id"))
1202 {
1203 self.generate_id(&mut current, "")?;
1204 }
1205 // A measured foreignObject declares its font size: its style's `font-size` anchor (tex_box.rs), carried in
1206 // `_font_anchor`, so its content's `fontsize` is relative to that, not to the size declared around the
1207 // picture — a `\footnotesize` figure's node text was shrunk twice (KNOWN_PERL_ERRORS #439; witness
1208 // tests/tikz/consort-flowchart).
1209 if let Some(anchor) = current.get_attribute("_font_anchor") {
1210 let size = anchor.parse::<f64>().unwrap_or(10.0);
1211 declared_font = Cow::Owned(declared_font.merge_ref(&Font {
1212 size: Some(size),
1213 ..Font::default()
1214 }));
1215 pending_declaration.remove("fontsize");
1216 }
1217 // A formula's fonts are the math fonts (fontmath.ltx's math versions), never the text family, series or
1218 // shape around it: `$y$` in `\emph` of a sans document is CMMI10, `\mathsf{G}` in `\textit` CMSS10. So its
1219 // tokens are written relative to the text default's family, series and shape (size and colour do reach
1220 // math), not to the enclosing text element as Perl's finalize_rec does (Document.pm:385-410) — against
1221 // a `sansserif italic` `\emph` the italic `y` was written `font="serif"`, which MathML reads whole
1222 // (MathML.pm:677) as upright: 2608.14133 (1,890 letters), 2608.31026, 2605.03549, 2604.00146,
1223 // 2607.19982, 2606.05381, 2604.16675; `\textsf{\emph{$y$}}` in Perl too (KNOWN_PERL_ERRORS #1002). The
1224 // MathML side reads the context font from inside the formula only (`math_context_font`). An `XMText` in it
1225 // returns to the text font (above). OXIDIZED_DESIGN_DIVERGENCES #780; guards
1226 // `perfect_kernel_batch77u::math_fonts_*`.
1227 if qname == pin!("ltx:Math") {
1228 math_outer_fonts.push(Rc::new(declared_font.clone().into_owned()));
1229 let mut math_context = declared_font.into_owned();
1230 math_context.family.clone_from(&FONT_TEXT_DEFAULT.family);
1231 math_context.series.clone_from(&FONT_TEXT_DEFAULT.series);
1232 math_context.shape.clone_from(&FONT_TEXT_DEFAULT.shape);
1233 declared_font = Cow::Owned(math_context);
1234 }
1235 self.set_local_font(Rc::new(declared_font.into_owned()));
1236
1237 // Process children using the snapshot from get_child_nodes().
1238 // Element children are deferred to the stack; text children are handled inline.
1239 // PostWork is pushed first (runs after all children), then children in reverse.
1240 //
1241 // No attribute snapshot is taken here: PostWork deliberately
1242 // re-derives the bookkeeping set at its own time (see the comment
1243 // there — descendant `generate_id` calls write `_ID_counter_*` onto
1244 // this node AFTER Enter). Capturing it here cost a full
1245 // `get_attributes()` HashMap plus a String per attribute on every
1246 // node — ~10M nodes on the streaming witness — and the result was
1247 // never read.
1248 stack.push(Work::PostWork { node: current.clone() });
1249
1250 // Leftover `*_Capture_` wrappers/markers (`ltx:_Capture_`, the frontmatter
1251 // position marker `ltx:_Frontmatter_Capture_`) are construction-time
1252 // scaffolding that a document ending abnormally (a Fatal, `\end{document}`
1253 // swallowed by an unbalanced conditional, a streaming spill) can strand in
1254 // the tree; the schema admits them nowhere ("not allowed anywhere"). Unwrap
1255 // the ones with content, drop the empty ones, then snapshot the children.
1256 // ONE pass over the direct children only — no re-scan after an unwrap and
1257 // no `_CaptureBlock_`: under streaming a fragment is finalized MID-BUILD
1258 // (spill threshold 3 in `114_streaming_*`), when an `insert_frontmatter`
1259 // `_Capture_` wrapper or an `insert_block` box capture can be legitimately
1260 // live; chasing wrappers exposed by an unwrap re-ordered faketitlepage's
1261 // abstract above its titlepage. One `ends_with` per child on the common
1262 // no-scrap path (this is the streaming hot path — see the
1263 // `get_attributes` note above). `_lxfragment` is not one.
1264 // The engine's field marks (processing instructions, [`FIELD_MARK_TARGET`]) are scaffolding too.
1265 // (read-only: only a scrap is wrapped as a `Node`)
1266 let scraps: Vec<Node> = current
1267 .as_readonly()
1268 .get_child_nodes()
1269 .into_iter()
1270 .filter(|c| match c.get_type() {
1271 Some(NodeType::ElementNode) => c.with_name(|name| name.ends_with("_Capture_")),
1272 Some(NodeType::PiNode) => c.with_name(|name| name == FIELD_MARK_TARGET),
1273 _ => false,
1274 })
1275 .map(|c| current.node_from_readonly(c))
1276 .collect();
1277 for scrap in scraps {
1278 if scrap.get_type() == Some(NodeType::PiNode) {
1279 self.remove_node(scrap);
1280 } else if scrap.get_first_element_child().is_some()
1281 || !scrap.get_content().trim().is_empty()
1282 {
1283 self.unwrap_nodes(scrap)?;
1284 } else {
1285 self.remove_node(scrap);
1286 }
1287 }
1288 // (read-only; a child is wrapped as a `Node` where it becomes work)
1289 let children = current.as_readonly().get_child_nodes();
1290 // Collect work items forward, then push in reverse for left-to-right processing
1291 let mut child_work: Vec<Work> = Vec::new();
1292 for &ro_child in &children {
1293 let child_type = ro_child.get_type();
1294 if child_type == Some(NodeType::ElementNode) {
1295 let child = current.node_from_readonly(ro_child);
1296 let was_forcefont = child.has_attribute("_force_font");
1297 // Enter first, PostElement after (reversed when pushed to stack)
1298 child_work.push(Work::Enter(child.clone()));
1299 child_work.push(Work::PostElement {
1300 child: child.clone(),
1301 parent_qname: qname,
1302 was_forcefont,
1303 });
1304 } else if child_type == Some(NodeType::TextNode) {
1305 // Text node: wrap with font element if needed (handled inline)
1306 let mut text_keys_to_remove = Vec::new();
1307 for key in pending_declaration.keys() {
1308 if !can_have_attribute(FONT_ELEMENT_NAME, key) {
1309 text_keys_to_remove.push(key.clone());
1310 }
1311 }
1312 for key in text_keys_to_remove {
1313 pending_declaration.remove(&key);
1314 }
1315 if can_contain(¤t, FONT_ELEMENT_NAME)
1316 && !pending_declaration.is_empty()
1317 && let Some(mut text) = self.wrap_nodes(FONT_ELEMENT_NAME, vec![
1318 current.node_from_readonly(ro_child),
1319 ])?
1320 {
1321 for (key, (value, _properties)) in pending_declaration.iter() {
1322 self.set_attribute(&mut text, key, value)?;
1323 }
1324 // Text wrapper finalization is shallow (only text content), push to stack
1325 child_work.push(Work::Enter(text));
1326 }
1327 }
1328 }
1329 // Push in reverse so left-to-right processing order is maintained
1330 for work_item in child_work.into_iter().rev() {
1331 stack.push(work_item);
1332 }
1333 },
1334 Work::PostElement {
1335 child,
1336 parent_qname,
1337 was_forcefont,
1338 } => {
1339 // After finalizing a child element, check if it should be collapsed.
1340 // Use empty_attr_nodes set instead of child.get_attributes().is_empty()
1341 // to avoid traversing the attribute linked list, which can be corrupted
1342 // by prior replace_node operations in libxml2.
1343 // Defer the actual collapse to after the traversal completes, since
1344 // replace_node can corrupt ancestor attribute lists in libxml2.
1345 if (get_node_qname(&child) == pin!("ltx:text"))
1346 && !was_forcefont
1347 && empty_attr_nodes.contains(&child.to_hashable())
1348 {
1349 let grandchildren = child.get_child_nodes();
1350 if grandchildren
1351 .iter()
1352 .all(|gchild| can_contain_qsym(parent_qname, get_node_qname(gchild)))
1353 {
1354 deferred_collapses.push((child, parent_qname));
1355 }
1356 }
1357 },
1358 Work::PostWork { mut node } => {
1359 // Mirrors Perl `Document.pm:452`: at finalize time, ANY attribute
1360 // whose name starts with `_` is internal bookkeeping and gets
1361 // stripped. The set MUST be derived here, at PostWork time, and not
1362 // captured back at Enter, because descendant
1363 // `generate_id` calls can write `_ID_counter_<prefix>_` attributes
1364 // ONTO the current node (their nearest-id-bearing ancestor) during
1365 // child traversal — those late-added attrs were missing from the
1366 // Enter snapshot and would otherwise leak into the output XML,
1367 // causing duplicate xml:id collisions in the post-processing
1368 // libxml2 validator (1312.5864 cluster: 70× `S8.T5.m2241 already
1369 // defined`, where the Math element carried `_ID_counter__="1"`
1370 // populated post-Enter).
1371 //
1372 // EXCEPT the streaming pass-2 parse wrapper: it is never
1373 // serialized, and its `_ID_counter_*` attrs are how id numbering
1374 // carries ACROSS segments (read back after each segment — see
1375 // `streaming_pass2`).
1376 if get_node_qname(&node) != pin!("ltx:_lxfragment") {
1377 // Only a non-namespaced `_` attribute is bookkeeping (Perl matches the nodeName, so `xml:_a` stays).
1378 let mut has_visible = false;
1379 let mut bookkeeping_attrs: Vec<String> = Vec::new();
1380 node.as_readonly().for_each_property_ns(|name, href, _| {
1381 if href.is_none() && name.starts_with('_') {
1382 bookkeeping_attrs.push(name.to_owned());
1383 } else {
1384 has_visible = true;
1385 }
1386 });
1387 for name in &bookkeeping_attrs {
1388 let _ = node.remove_attribute_no_ns(name);
1389 }
1390 // If all attributes were bookkeeping, the node now has empty attrs.
1391 if !has_visible {
1392 empty_attr_nodes.insert(node.to_hashable());
1393 }
1394 }
1395 if get_node_qname(&node) == pin!("ltx:Math") {
1396 math_outer_fonts.pop();
1397 }
1398 self.expire_local_font();
1399 },
1400 }
1401 }
1402 // Execute deferred font wrapper collapses now that the entire tree has been
1403 // finalized. Process from deepest (last) to shallowest (first) to avoid
1404 // corrupting ancestor attribute lists during the replacement operations.
1405 // This deferred approach prevents libxml2 memory corruption that occurs
1406 // when replace_node runs during tree traversal.
1407 for (child, _parent_qname) in deferred_collapses.into_iter().rev() {
1408 let grandchildren = child.get_child_nodes();
1409 if grandchildren.is_empty() {
1410 // Empty font wrapper — just remove it
1411 self.remove_node(child);
1412 } else {
1413 Debug!(
1414 "will replace {} grandchildren nodes in finalize_rec (deferred)",
1415 grandchildren.len()
1416 );
1417 self.replace_node(child, grandchildren)?;
1418 }
1419 }
1420 Ok(())
1421 }
1422
1423 /// Document construction at the Current Insertion Point.
1424 ///
1425 /// absorb the given $box into the DOM (called from constructors).
1426 /// This will return a list of whatever nodes were created.
1427 /// Note that this may include nodes that are children of other nodes in the list
1428 /// or nodes that are no longer in the document.
1429 /// Also, note that when a text nodes is appended to, the complete text node is in the list,
1430 /// not just the portion that was added.
1431 /// [Note that recording the nodes being constructed isn't all that costly,
1432 /// but filtering them for parent/child relations IS, particularly since it usually isn't needed]
1433 ///
1434 /// A box that is a TBox, or List, or Whatsit, is responsible for carrying out
1435 /// its own insertion, but it should ultimately call methods of Document
1436 /// that will record the nodes that were created.
1437 /// $box can also be a plain string (Digested::Postponed)
1438 /// which will be inserted according to whatever
1439 /// font, mode, etc, are in %props.
1440 pub fn absorb(&mut self, object: &Digested, props_opt: Option<SymHashMap<Stored>>) -> Result<()> {
1441 // a box's constructor absorbing material before it opened an element of its own: none is its own
1442 self.field_box_pending = false;
1443 if !self.field_marking_live() {
1444 return self.absorb_boxes(object, props_opt);
1445 }
1446 self.absorb_level += 1;
1447 let result = self.absorb_boxes(object, props_opt);
1448 // a run of field ink ends with the absorb that opened it (a table cell's, an environment body's)
1449 if result.is_ok()
1450 && self.field_inherit == 0
1451 && self
1452 .field_run
1453 .as_ref()
1454 .is_some_and(|r| r.level >= self.absorb_level)
1455 {
1456 self.close_field_run()?;
1457 }
1458 self.absorb_level -= 1;
1459 result
1460 }
1461
1462 /// Is field ink being marked (`FieldRun`)? Not once the frontmatter placement settled it, not in a conversion
1463 /// that stamped no field.
1464 #[inline]
1465 fn field_marking_live(&self) -> bool { FIELD_PROV_STAMPED.get() && !self.field_ink_settled }
1466
1467 /// Mark `element`, opened by a TeX box's constructor for its material (an `\hbox`'s `ltx:text`, a
1468 /// `\vbox`/`\parbox`/minipage capture, an alignment's container), with [`FIELD_BOX_ATTRIBUTE`]: the text a box
1469 /// sets is no body text of the page for a field's print outside it (latexml_engine `field_runs_after_body_text`,
1470 /// OXIDIZED_DESIGN #715). Only the element the box's own constructor opened, at the point it opens it: material a
1471 /// box absorbs straight into its context (a `\vbox` in a `\vbox`, a capture unwrapped) marks nothing (review r5
1472 /// finding 1).
1473 pub fn mark_field_box(&mut self, element: &mut Node) {
1474 if self.field_marking_live() && element.get_type() == Some(NodeType::ElementNode) {
1475 let _ = element.set_attribute(FIELD_BOX_ATTRIBUTE, "true");
1476 }
1477 }
1478
1479 /// Arm [`Self::mark_field_box`] for the next element opened ([`Self::open_element`]), when it is the caller's own
1480 /// (an alignment's `open_container`); [`Self::disarm_field_box`] after it.
1481 pub fn arm_field_box(&mut self) { self.field_box_pending = self.field_marking_live(); }
1482 /// Disarm [`Self::arm_field_box`].
1483 pub fn disarm_field_box(&mut self) { self.field_box_pending = false; }
1484
1485 /// Before absorbing `object`: open, continue or close the run of field ink (`FieldRun`) by the field provenance
1486 /// the box was digested with ([`FIELD_PROV_PROPERTY`]). Returns whether `object` is a field-ink whatsit whose own
1487 /// absorption is its ink (the caller counts it in `field_inherit` meanwhile). Nothing in math: a formula is one box of
1488 /// the text around it, and what it holds (an `\mbox` of the field) is no print of the field.
1489 fn field_ink_before(&mut self, object: &Digested) -> Result<bool> {
1490 if !self.field_marking_live() {
1491 return Ok(false);
1492 }
1493 // an alignment shown: the row-end markers its body consumed are taken now ([`FIELD_TAKEN_PROPERTY`]); a TeX box's
1494 // constructor ([`FIELD_BOX_PROPERTY`]): the first element it opens is marked
1495 if matches!(object.data(), DigestedData::Whatsit(_)) {
1496 self.field_box_pending = object.with_properties(|props| {
1497 if let Some(Stored::VecDequeStored(serials)) = props.get_sym(pin!("fieldTaken")) {
1498 for serial in serials {
1499 if let Stored::Int(serial) = serial
1500 && let Ok(serial) = u32::try_from(*serial)
1501 {
1502 crate::token::field_ledger_take(serial);
1503 }
1504 }
1505 }
1506 props.get_sym(pin!("fieldBox")).is_some()
1507 });
1508 }
1509 // `fieldProv` ([`FIELD_PROV_PROPERTY`]), by its cached symbol and without a copy: this runs for every box
1510 let (prov, serial) = object.with_properties(|props| match props.get_sym(pin!("fieldProv")) {
1511 Some(Stored::Int(p)) => (*p as u16, match props.get_sym(pin!("fieldSerial")) {
1512 Some(Stored::Int(s)) => u32::try_from(*s).ok(),
1513 _ => None,
1514 }),
1515 _ => (0, None),
1516 });
1517 let field = crate::token::field_prov_field(prov);
1518 if self.field_inherit > 0 {
1519 // inside a field-ink whatsit: its ink, whatever provenance its parts have (a formula's characters count for the
1520 // run's extent: `Szabo$^3$` ends with the `3`)
1521 if prov != 0
1522 && let Some(run) = self.field_run.as_mut()
1523 && run.field == field
1524 && let Some(serial) = serial
1525 {
1526 run.take(serial);
1527 }
1528 return Ok(false);
1529 }
1530 // (the common case first: a box of no field, no run open — nothing to do)
1531 if prov == 0 {
1532 if self.field_run.is_some() && !self.in_math_node() {
1533 self.close_field_run()?;
1534 }
1535 return Ok(false);
1536 }
1537 if self.in_math_node() {
1538 return Ok(false);
1539 }
1540 let Some(serial) = serial else {
1541 // a box the full ledger holds no cover of: no whole print
1542 if self.field_run.is_some() {
1543 self.close_field_run()?;
1544 }
1545 return Ok(false);
1546 };
1547 let cover = crate::token::field_ledger_entry(serial).map_or_else(Default::default, |e| e.cover);
1548 match self.field_run.as_mut() {
1549 // the value read on in its order (the boxes of one macro's expansion all start at the macro's position; a
1550 // construct's own box, absorbed around what its argument made, covers it: `\textsc{One}`'s whatsit after `One`)
1551 Some(run) if run.field == field && cover.end > run.max_start => {
1552 run.take(serial);
1553 run.max_start = run.max_start.max(cover.start);
1554 },
1555 // another field's ink, or the value read again from before a position the run reached (`\StrLeft{\@title}{3}
1556 // \@title`: the second print's `T`): a print of its own
1557 _ => {
1558 if self.field_run.is_some() {
1559 self.close_field_run()?;
1560 }
1561 self.open_field_run(field, serial, cover.start)?;
1562 },
1563 }
1564 Ok(!matches!(object.data(), DigestedData::TBox(_)))
1565 }
1566
1567 /// Is the insertion point in math (inside an `ltx:Math`: a formula's tokens, an `\mbox` in it)?
1568 fn in_math_node(&self) -> bool {
1569 let mut node = if self.node.get_type() == Some(NodeType::ElementNode) {
1570 Some(self.node.clone())
1571 } else {
1572 self.node.get_parent()
1573 };
1574 while let Some(element) = node {
1575 if element.get_type() != Some(NodeType::ElementNode) {
1576 return false;
1577 }
1578 if arena::with(get_node_qname(&element), |q| {
1579 q.starts_with("ltx:XM") || q == "ltx:Math"
1580 }) {
1581 return true;
1582 }
1583 node = element.get_parent();
1584 }
1585 false
1586 }
1587
1588 /// Append a field mark (a [`FIELD_MARK_TARGET`] processing instruction) at the insertion point, the open text node
1589 /// closed first, so the ink on each side of it is in its own node. Returns false where no element takes it.
1590 fn append_field_mark(&mut self, content: &str) -> Result<bool> {
1591 let mut element = self.close_text_internal()?;
1592 if element.get_type() != Some(NodeType::ElementNode) {
1593 return Ok(false);
1594 }
1595 let Ok(mut mark) = self
1596 .document
1597 .create_processing_instruction(FIELD_MARK_TARGET, content)
1598 else {
1599 return Ok(false);
1600 };
1601 element.add_child(&mut mark)?;
1602 Ok(true)
1603 }
1604
1605 fn open_field_run(&mut self, field: u16, serial: u32, start: u16) -> Result<()> {
1606 let id = self.field_run_serial + 1;
1607 if self.append_field_mark(&s!("begin {field} {id}"))? {
1608 self.field_run_serial = id;
1609 self.field_run = Some(FieldRun {
1610 field,
1611 id,
1612 level: self.absorb_level,
1613 serials: vec![(serial, serial)],
1614 max_start: start,
1615 });
1616 }
1617 Ok(())
1618 }
1619
1620 fn close_field_run(&mut self) -> Result<()> {
1621 if let Some(run) = self.field_run.take() {
1622 let serials = run
1623 .serials
1624 .iter()
1625 .map(|(first, last)| s!("{first}:{last}"))
1626 .collect::<Vec<_>>()
1627 .join(",");
1628 self.append_field_mark(&s!("end {} {} {serials}", run.field, run.id))?;
1629 }
1630 Ok(())
1631 }
1632
1633 /// Close the open run of field ink, if any, and mark no more (`FieldRun`): the frontmatter placement settled it.
1634 /// The field ledger records no more either ([`field_ledger_settle`](crate::token::field_ledger_settle)).
1635 pub fn settle_field_ink(&mut self) -> Result<()> {
1636 if self.field_run.is_some() {
1637 self.close_field_run()?;
1638 }
1639 self.field_ink_settled = true;
1640 crate::token::field_ledger_settle();
1641 Ok(())
1642 }
1643
1644 fn absorb_boxes(
1645 &mut self,
1646 object: &Digested,
1647 props_opt: Option<SymHashMap<Stored>>,
1648 ) -> Result<()> {
1649 use DigestedData::*;
1650 let props = props_opt.unwrap_or_default();
1651 let mut boxes = vec![Cow::Borrowed(object)];
1652 while let Some(front_box) = boxes.pop() {
1653 // Cooperative guard tick — the SAME one the digestion loops run
1654 // (`stomach.rs`, three sites). Build had none, and Build is where a large
1655 // document actually peaks: measured 2026-07-29 on 800k words of plain
1656 // prose, digest ends under 2 GB while Build takes it to 6.4 GB (54 % of
1657 // wall, ~70 % of peak RSS). So `--max-memory` guarded only the cheap
1658 // phase, and what a user hit was the HARD watchdog: SIGKILL, exit 137, no
1659 // `Fatal:` line, no partial document — the 0-byte output reported against
1660 // rc4 on a 131 MB source. The tick makes the ceiling cooperative here
1661 // too, so an over-budget document degrades to a graceful Fatal that the
1662 // caller can salvage from (`core_interface::convert_document`).
1663 //
1664 // Cost is negligible: `check_timeout` only samples RSS every ~1024 calls,
1665 // and this loop already does far more work per iteration than a counter
1666 // increment.
1667 crate::stomach::check_timeout()?;
1668 match front_box.data() {
1669 List(list) => {
1670 // Simply unwind Lists to avoid unneccessary recursion; This occurs quite frequently!
1671 for tbox in list.borrow().unlist().into_iter().rev() {
1672 boxes.push(Cow::Owned(tbox));
1673 }
1674 },
1675 // A Proper Box or Whatsit? Absorb it.
1676 TBox(digested) => {
1677 raise_absorb_warning(&front_box);
1678 self.field_ink_before(&front_box)?;
1679 self.set_box_to_absorb(Some((*front_box).clone()));
1680 self.init_constructed_nodes();
1681 digested.borrow().be_absorbed(self)?;
1682 // record these for OUTER caller, but return only the most recent set
1683 self.close_constructed_nodes();
1684 self.expire_box_to_absorb();
1685 },
1686 Whatsit(digested) => {
1687 raise_absorb_warning(&front_box);
1688 let field_ink = self.field_ink_before(&front_box)?;
1689 self.field_inherit += u32::from(field_ink);
1690 self.set_box_to_absorb(Some((*front_box).clone()));
1691 self.init_constructed_nodes();
1692 let absorbed = digested.borrow().be_absorbed(self);
1693 self.field_box_pending = false;
1694 self.field_inherit -= u32::from(field_ink);
1695 absorbed?;
1696 self.close_constructed_nodes();
1697 self.expire_box_to_absorb();
1698 },
1699 Alignment(alignment) => {
1700 self.set_box_to_absorb(Some((*front_box).clone()));
1701 self.init_constructed_nodes();
1702 // A self-referential alignment (transitively contains itself) would
1703 // re-enter `borrow_mut` here and panic ("already borrowed"). Guard like
1704 // the size-computation traversal (digested.rs) and skip the re-entrant
1705 // absorption to break the cycle. Witness: astro-ph0310145 et al.
1706 match alignment.try_borrow_mut() {
1707 Ok(mut a) => {
1708 a.be_absorbed_mut(self)?;
1709 },
1710 Err(_) => {
1711 // Degrading MUST be loud (fail-toward-flagging): the whole
1712 // alignment's content is being dropped from the output.
1713 Error!(
1714 "unexpected",
1715 "self_referential_alignment",
1716 "Skipping absorption of a self-referential alignment (its content is lost)"
1717 );
1718 },
1719 }
1720 self.close_constructed_nodes();
1721 self.expire_box_to_absorb();
1722 },
1723 Comment(comment) => {
1724 comment.be_absorbed(self)?;
1725 },
1726 Postponed(tokens) => {
1727 let text_font_opt = if let Some(Stored::Font(prop_font)) = props.get("font") {
1728 Some(Rc::clone(prop_font))
1729 } else {
1730 match self.box_to_absorb {
1731 Some(ref thisbox) => thisbox.get_font()?,
1732 None => None,
1733 }
1734 };
1735 let text_font = text_font_opt.unwrap_or_default();
1736 if let Some(new_text) = self.open_text(&tokens.to_string(), &text_font)? {
1737 self.record_constructed_node(&new_text);
1738 }
1739 },
1740 KeyVals(kv) => {
1741 // When KeyVals appear in body absorption (e.g. #1 for RequiredKeyVals),
1742 // convert them to text representation matching Perl's stringify behavior.
1743 let text = kv.to_string();
1744 if !text.is_empty() {
1745 let text_font = match self.box_to_absorb {
1746 Some(ref thisbox) => thisbox.get_font()?.unwrap_or_default(),
1747 None => Rc::default(),
1748 };
1749 if let Some(new_text) = self.open_text(&text, &text_font)? {
1750 self.record_constructed_node(&new_text);
1751 }
1752 }
1753 },
1754 RegisterValue(_) => {
1755 // RegisterValue should not normally appear in the absorption pipeline.
1756 },
1757 }
1758 }
1759 Ok(())
1760 }
1761
1762 fn init_constructed_nodes(&mut self) {
1763 // Pop a buffer from the free-list (retaining its previously-grown capacity);
1764 // fall back to a fresh empty Vec if the pool is dry. Swap it in as the new
1765 // inner frame; the outgoing outer frame goes onto the save stack.
1766 let fresh = self.reusable_node_buffers.pop().unwrap_or_default();
1767 let prev = std::mem::replace(&mut self.constructed_nodes, fresh);
1768 self.localized_constructed_nodes.push(prev);
1769 }
1770
1771 /// Close the current constructed-nodes frame, restoring the outer frame and
1772 /// re-recording the inner frame's nodes into it. The drained inner buffer
1773 /// is returned to `reusable_node_buffers` (empty but with capacity intact)
1774 /// so the next `init_constructed_nodes` can reuse it without allocating.
1775 fn close_constructed_nodes(&mut self) {
1776 let outer = self.localized_constructed_nodes.pop().unwrap_or_default();
1777 let mut inner = std::mem::replace(&mut self.constructed_nodes, outer);
1778 for n in inner.drain(..) {
1779 self.record_constructed_node(&n);
1780 }
1781 // `inner` is now empty; its capacity is preserved. Return it to the pool.
1782 self.reusable_node_buffers.push(inner);
1783 }
1784 pub fn get_constructed_nodes(&self) -> &[Node] { &self.constructed_nodes }
1785
1786 /// This is a refactored `else` cases from the main absorb routine, to allow for better type
1787 /// hygiene
1788 pub fn absorb_string(
1789 &mut self,
1790 object: &str,
1791 props: &SymHashMap<Stored>,
1792 ) -> Result<Option<Node>> {
1793 // a box's constructor setting text before it opened an element of its own: none is its own
1794 self.field_box_pending = false;
1795 // Else, plain string in text mode.
1796 let ismath: bool = match props.get("isMath") {
1797 Some(v) => v.into(),
1798 None => false,
1799 };
1800 if !ismath {
1801 // Perf: avoid cloning Rc<Font> into owned Font in the common case.
1802 // We pull out the Rc (shared reference is fine since open_text only
1803 // borrows the Font, not self) and go through Cow<Font>.
1804 let font_opt: Option<Rc<Font>> = match props.get("font") {
1805 Some(Stored::Font(fnt)) => Some(Rc::clone(fnt)),
1806 Some(Stored::FontDirective(FontDirective::Asset(fnt))) => Some(Rc::clone(fnt)),
1807 _ => None,
1808 };
1809 if let Some(fnt) = font_opt {
1810 return self.open_text(object, &fnt);
1811 }
1812 if let Some(Stored::FontDirective(FontDirective::Closure(code))) = props.get("font") {
1813 let fnt = code(None)?;
1814 return self.open_text(object, &fnt);
1815 }
1816 // Fallback to box_to_absorb font.
1817 let fnt = self.box_to_absorb.as_ref().unwrap().get_font()?.unwrap();
1818 self.open_text(object, &fnt)
1819 } else if get_node_qname(&self.node) == pin!("ltx:XMTok") {
1820 // Or plain string in math mode.
1821 // Note text nodes can ONLY appear in <XMTok> or <text>!!!
1822 // Have we already opened an XMTok? Then insert into it.
1823 Ok(Some(self.open_math_text_internal(object)?))
1824 // Else create the XMTok now.
1825 } else {
1826 // Odd case: constructors that work in math & text can insert raw strings in Math mode.
1827 let font_math_opt = match props.get("font") {
1828 Some(Stored::Font(fnt)) => Some(Cow::Borrowed(&**fnt)),
1829 Some(Stored::FontDirective(FontDirective::Asset(fnt))) => Some(Cow::Borrowed(&**fnt)),
1830 Some(Stored::FontDirective(FontDirective::Closure(code))) => Some(Cow::Owned(code(None)?)),
1831 _ => None,
1832 };
1833 if let Some(font_math) = font_math_opt {
1834 Ok(Some(self.insert_math_token(
1835 object,
1836 HashMap::default(),
1837 Some(&font_math),
1838 )?))
1839 } else {
1840 Ok(Some(self.insert_math_token(
1841 object,
1842 HashMap::default(),
1843 None,
1844 )?))
1845 }
1846 }
1847 }
1848 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1849
1850 /// Perl: insertElementBefore — insert a new element before a given point node.
1851 /// Creates a new element with the given qname and attributes, inserts it
1852 /// before `point` in the DOM tree, and returns the new node.
1853 pub fn insert_element_before(
1854 &self,
1855 point: &Node,
1856 qname: &str,
1857 attrib: Option<HashMap<String, String>>,
1858 ) -> Result<Node> {
1859 // Create element in LTX namespace (matching Perl's setNamespace($LTX_NS,'',1))
1860 let mut new_node = Node::new(qname, None, &self.document)?;
1861 if let Some(attrs) = attrib {
1862 for (key, value) in attrs {
1863 let _ = new_node.set_attribute(&key, &value);
1864 }
1865 }
1866 // insertBefore: add new_node before point
1867 let mut point_mut = point.clone();
1868 point_mut.add_prev_sibling(&mut new_node).ok();
1869 Ok(new_node)
1870 }
1871
1872 /// Insert a construction-time position mark: an empty internal element (`*_Capture_`-suffixed, admitted anywhere by
1873 /// the model, never in the output) at the current point, as [`Document::insert_element`] does, its name recorded
1874 /// first. A mark of a name a pass gates on with [`Document::made_mark`] (`_Frontmatter_Capture_`,
1875 /// `_CoverTitleBegin_Capture_`, `_CoverTitleEnd_Capture_`) must be made only here (or copied from one made here), so a
1876 /// pass looking for marks of a name none was made of has none to find and skips its scan of the document; other marks
1877 /// (`insert_element`) are not recorded.
1878 pub fn insert_mark(
1879 &mut self,
1880 qname: &str,
1881 attrib: Option<HashMap<String, String>>,
1882 ) -> Result<Node> {
1883 if !self.made_mark(qname) {
1884 self.marks_made.push(qname.to_string());
1885 }
1886 self.insert_element(qname, Vec::new(), attrib)
1887 }
1888
1889 /// Was a position mark named `qname` ever made in this document ([`Document::insert_mark`])? False: none is in it.
1890 pub fn made_mark(&self, qname: &str) -> bool { self.marks_made.iter().any(|made| made == qname) }
1891
1892 /// Was a field mark ([`FIELD_MARK_TARGET`]) ever made in this document? False: none is in it — a field mark is made
1893 /// only where a run of field ink opens or closes, and a run's end mark only after its begin mark (a copy is copied
1894 /// from one).
1895 pub fn made_field_marks(&self) -> bool { self.field_run_serial > 0 }
1896
1897 /// Shorthand for open,absorb,close, but returns the new node.
1898 pub fn insert_element(
1899 &mut self,
1900 qname: &str,
1901 content: Vec<&Digested>,
1902 attrib: Option<HashMap<String, String>>,
1903 ) -> Result<Node> {
1904 // TODO: Quickly hacked together, needs a careful refactor with all .clone()
1905 // calls removed
1906 let node = self.open_element(qname, attrib, None)?;
1907 // Debug!("Inserting element {:?} with body: {:?}", qname, content);
1908 for digested in content {
1909 self.absorb(digested, None)?;
1910 }
1911
1912 // Walk up from the current insertion point to learn whether `node` is still
1913 // an open ancestor (so it can be closed below). `self.node` may be the
1914 // parentless document root, and an intermediate node may be detached — a
1915 // `None` parent there simply means `node` is NOT an ancestor (stop the walk),
1916 // so don't `.unwrap()`-panic on it. Witnesses: hep-th0201062, 1009.0637.
1917 let mut c = self.node.get_parent();
1918 while c.is_some()
1919 && c.as_ref() != Some(&node)
1920 && c.as_ref().unwrap().get_type() != Some(NodeType::DocumentNode)
1921 {
1922 c = match c.as_ref().unwrap().get_parent() {
1923 None => None,
1924 Some(parent) => match parent.get_type() {
1925 Some(NodeType::DocumentNode) | None => None,
1926 Some(_) => Some(parent),
1927 },
1928 };
1929 }
1930
1931 // In obscure situations, `node` may have already gotten closed?
1932 // close it if it is still open.
1933 if (self.node == node) || (c.as_ref() == Some(&node)) {
1934 self.close_element(qname)?;
1935 }
1936 Ok(node)
1937 }
1938
1939 /// Insert a ProcessingInstruction of the form <?op attr=value ...?>
1940 /// Does NOT move the current insertion point to the PI,
1941 /// but may move up past a text node.
1942 // Rust note: attrib would have been best as Vec<(String,String)> but
1943 // currently quote!() doesn't work out of the box on them
1944 pub fn insert_pi(
1945 &mut self,
1946 op: &str,
1947 attributes_opt: Option<HashMap<String, String>>,
1948 ) -> Result<()> {
1949 let data = attributes_opt.as_ref().map(pi_data).unwrap_or_default();
1950 // self.close_text_internal(); // Close any open text node
1951 let mut pi_node = self
1952 .document
1953 .create_processing_instruction(op, &data)
1954 .unwrap();
1955 // Perl (Core/Document.pm insertPI): a PI always lands before the root
1956 // element. When the root already exists — a mid-body or document-final PI
1957 // (#683's `<?latexml nominal-font-size?>` is emitted at finalization) —
1958 // insert directly before it, whatever the current insertion point. Only
1959 // when NO root has been opened yet (the usual pre-`\begin{document}` case)
1960 // queue the PI in `pending`, to be flushed the moment the root opens
1961 // (`open_element_at`). The old code keyed solely on the insertion point
1962 // being the DocumentNode and so re-queued a post-root PI into `pending`,
1963 // which drains once and never again — the PI was silently lost.
1964 if let Some(mut root) = self.document.get_root_element() {
1965 root.add_prev_sibling(&mut pi_node)?;
1966 } else if self.node.get_type() == Some(NodeType::DocumentNode) {
1967 self.pending.push(pi_node);
1968 } else {
1969 self.node.add_prev_sibling(&mut pi_node)?;
1970 }
1971 Ok(())
1972 }
1973
1974 /// Open a new `qname` element and make it the current insertion point.
1975 ///
1976 /// Where it opens is the model's decision, not the caller's: the insertion
1977 /// point is first moved by [`find_insertion_point`](Self::find_insertion_point),
1978 /// which auto-opens any element the schema requires in between and
1979 /// auto-closes any that cannot contain `qname`. So a binding may open a
1980 /// `ltx:para` without first checking what is currently open.
1981 ///
1982 /// See [`open_element_at`](Self::open_element_at) to open at an explicit node
1983 /// instead, and [`close_element`](Self::close_element) for the counterpart.
1984 pub fn open_element(
1985 &mut self,
1986 qname: &str,
1987 attributes: Option<HashMap<String, String>>,
1988 font_opt: Option<&Font>,
1989 ) -> Result<Node> {
1990 // NoteProgress('.') if (self.progress}++ % 25) == 0;
1991 // Debug!(
1992 // s!("Open element {:?} at {:?}",
1993 // qname,
1994 // self.with_node_qname(&self.node))
1995 // );
1996 // a TeX box's constructor opening its own element ([`FIELD_BOX_PROPERTY`]); not one auto-opened on the way
1997 let field_box = std::mem::take(&mut self.field_box_pending);
1998 let mut point = self.find_insertion_point(qname, None)?;
1999 // Perl Document.pm:792 `$attributes{_box} = $LaTeXML::BOX unless
2000 // $attributes{_box}`: an element opened at the insertion point is recorded
2001 // with the box being absorbed, ahead of the insertion point's own box
2002 // (which is what a bare `openElementAt` falls back to). Underscore
2003 // attributes such as `_box` and `_font` are bookkept in `node_boxes` /
2004 // `node_fonts` rather than as libxml attributes.
2005 let requested_box = self.box_to_absorb.clone();
2006 let mut newnode = self.open_element_at_with_box(
2007 &mut point,
2008 qname,
2009 attributes,
2010 font_opt.cloned(),
2011 requested_box,
2012 )?;
2013 // An element of a construct that never ended (its group abandoned, `stomach::UNENDED`)
2014 // auto-closes: Perl's per-node `_autoclose` (Document.pm `canAutoClose`). OXIDIZED_DESIGN #542.
2015 // So does an element auto-opened inside such an element (an implicit wrapper its parent's
2016 // close would close).
2017 let unended = self.absorbing_unended_box()
2018 || (newnode.has_attribute("_autoopened")
2019 && newnode
2020 .get_parent()
2021 .is_some_and(|parent| parent.has_attribute(UNENDED_ATTRIBUTE)));
2022 // `_noautoclose` (an `\fbox`'s `ltx:text`, 1210.0368) holds against font switches in a box
2023 // that ends; this one does not.
2024 if unended {
2025 let _ = newnode.remove_attribute("_noautoclose");
2026 let _ = newnode.set_attribute("_autoclose", "true");
2027 // Its closer finds it closed already when the structure after it closed it.
2028 let _ = newnode.set_attribute(UNENDED_ATTRIBUTE, "true");
2029 }
2030 if field_box {
2031 self.mark_field_box(&mut newnode);
2032 }
2033 self.set_node(&newnode);
2034
2035 Ok(newnode)
2036 }
2037
2038 /// Stamp a freshly-opened element with its source range as a
2039 /// `data-sourcepos` attribute, for the `--source-map` feature (issues
2040 /// #47/#92). The range comes from the construct currently being absorbed
2041 /// (`box_to_absorb`); the integer file `tag` is resolved through the
2042 /// document-level `sources` table (`state::source_tag`) so no path is
2043 /// inlined. See `docs/performance/SOURCE_PROVENANCE.md` §0/§2.
2044 ///
2045 /// Math is kept **opaque** per the MVP scope: the `ltx:Math` wrapper is
2046 /// stamped, but its `ltx:XM*` MathML internals are skipped (the Marpa
2047 /// math parser has no locator awareness — §7 A.3). Only invoked when the
2048 /// source-map switch is on (the caller gates it).
2049 fn stamp_source_locator(&mut self, node: &Node, qname: &str) {
2050 // Math internals: stamp only the leaf token elements (`ltx:XMTok` — the
2051 // operators / identifiers / numbers) when token-locators gives them a real
2052 // located box locator (the math char's source origin). This is the per-token
2053 // in-equation provenance step (§7 A.3). The structural XM* (XMApp/XMDual/
2054 // XMArray) are rebuilt by the Marpa parser — created directly, not via
2055 // `open_element` — so they never reach here; the remaining digestion-built
2056 // wrappers (XMArg/XMHint/XMText/XMRef/XMWrap) stay opaque. The `data:sourcepos`
2057 // rides the XMTok element through the parser's restructuring (attribute on a
2058 // reparented node) and through the XMath→MathML XSLT.
2059 //
2060 // Gated at compile time: feature-OFF keeps math fully opaque (the MVP scope
2061 // and the golden's math-opacity assertion); only the token-locators build
2062 // exposes the located XMTok leaves.
2063 #[cfg(not(feature = "token-locators"))]
2064 if qname.starts_with("ltx:XM") {
2065 return;
2066 }
2067 #[cfg(feature = "token-locators")]
2068 if qname.starts_with("ltx:XM") && qname != "ltx:XMTok" {
2069 return;
2070 }
2071 // Read the pre-captured Copy locator — never re-borrow the box here.
2072 let Some(loc) = self.current_box_locator else {
2073 return;
2074 };
2075 // Skip locators with no real source position (default/synthetic).
2076 if loc.from_line == 0 {
2077 return;
2078 }
2079 // User-source only (§7.B): emit a navigable locator only into an editable
2080 // user document — `.tex`/`.ltx`, plus the bibliography sources `.bbl` (the
2081 // BibTeX-generated, but author-editable, list of `\bibitem`s) and `.bib`
2082 // (BibTeX database entries). All four are files the editor may legitimately
2083 // scroll into. This skips both synthetic default locators (whose source is
2084 // `…/locator.rs`, from `Locator::default()`'s `file!()`) and foreign
2085 // package/class files (`.sty`/`.cls`/…) — the editor must never scroll into
2086 // those. Foreign/unstamped elements inherit their nearest user-source
2087 // ancestor's range client-side (DOM walk-up). (MVP heuristic; a tracked
2088 // user-input set would be more precise.)
2089 let src = loc.get_source();
2090 let is_user_source = arena::with(src, |s| {
2091 let s = s.to_ascii_lowercase();
2092 s.ends_with(".tex") || s.ends_with(".ltx") || s.ends_with(".bbl") || s.ends_with(".bib")
2093 });
2094 if !is_user_source {
2095 return;
2096 }
2097 let tag = state::source_tag(src);
2098 // Emit in LaTeXML's `data:` namespace (`http://dlmf.nist.gov/LaTeXML/data`,
2099 // registered in `base_schema.rs:19`). The post XSLT's `copy_foreign_attributes`
2100 // path converts a `data:`-prefixed *foreign-namespaced* attribute to the HTML
2101 // `data-sourcepos` attribute (`LaTeXML-common.xsl`: `data:` prefix → `data-…`
2102 // when `USE_DATA_ATTRIBUTES` = true, i.e. HTML5). Faithful to Perl LaTeXML's
2103 // foreign-attribute convention; no XSLT change needed. The general namespaced-
2104 // attribute binding lives in `set_attribute` (shared with `aria:` etc.).
2105 let mut n = node.clone();
2106 let _ = self.set_attribute(&mut n, "data:sourcepos", &loc.to_sourcepos(tag));
2107 }
2108
2109 /// Note: This closes the deepest open node of a given type.
2110 /// This can cause problems with auto-opened nodes, esp. ones for fontswitches!
2111 /// Since this is an "explicit request", we're currently skipping over those nodes,
2112 /// ie. we're automatically closing them, even if they're the same type as we're asking to
2113 /// close!!! This is kinda risky! Maybe we should try to request closing of specific nodes.
2114 /// `close_element`, but a no-op when no `qname` element is open on the
2115 /// current ancestor chain: the strict close (auto-closing or force-closing
2116 /// the intervening descendants) whenever the element is still open, and
2117 /// silence only when content that the element could not hold auto-closed
2118 /// it already. Used for a replacement's closing tag of an element the same
2119 /// replacement opened (OXIDIZED_DESIGN_DIVERGENCES #202).
2120 pub fn close_element_if_open(&mut self, qname: &str) -> Result<Option<Node>> {
2121 if self.is_open_on_chain(qname) {
2122 self.close_element(qname)
2123 } else {
2124 Debug!(
2125 "document",
2126 "close_element",
2127 s!("Element {:?} already closed by its content", qname)
2128 );
2129 Ok(None)
2130 }
2131 }
2132
2133 /// Close the `{quote}`, `{quotation}` or `{verse}` (`ltx:quote`, which does not auto-close) standing between the
2134 /// current point and a place that can hold one of `qsyms` — a display sectioning unit `\part`..`\subsubsection`
2135 /// (`find_insertion_point_qsym`; a run-in `\paragraph`/`\subparagraph` stays in the quote, `is_quote_closing_unit`)
2136 /// or a bibliography and the unit it stands as (latex_constructs `adjust_backmatter_element`). Each of these environments
2137 /// is LaTeX's unlabelled list `\list{}{…}\item\relax` (article.cls:389-408), a margin, no structure: the heading and
2138 /// what follows it are the document's own unit, typeset within the margin (latex.ltx `\@startsection`;
2139 /// `thebibliography` = `\section*` + `\list`, article.cls:565-584). The quotes in the way, from the innermost, are
2140 /// closed only when that alone (with the auto-closing elements between) makes the place reachable — a quote in a list
2141 /// item, or outside the `minipage` the point is in, stays open (probes b_qiq, b_qmq) and the caller reports as before — and each one left empty
2142 /// is dropped. The environment's end then finds its quote closed (`latex_constructs` sect06 `quote_environment`).
2143 /// Returns whether it closed any. User rulings 2026-10-16 (D1, bibliography) and 2026-10-17 (D5, sectioning units: as
2144 /// the item bridge's margin-list exemption), OXIDIZED_DESIGN_DIVERGENCES #677, #678; witnesses 2203.09193 1904.12066
2145 /// 1610.09996 2109.09861 2403.09260 1609.06434 astro-ph0410583 1504.06728 (bibliography), 0712.1985 (a title page in
2146 /// `{quotation}`). Guards `perfect_kernel_batch69a::{bibliography_in_a_quote_closes_the_quote,
2147 /// section_in_a_quotation_closes_it}`.
2148 pub fn close_quotes_blocking(&mut self, qsyms: &[SymStr]) -> Result<bool> {
2149 let mut node = if self.node.get_type() == Some(NodeType::TextNode) {
2150 self.node.get_parent()
2151 } else {
2152 Some(self.node.clone())
2153 };
2154 let mut quotes: Vec<Node> = Vec::new();
2155 // Whether the walk has left a box's capture (a `minipage`, a `\parbox`): it takes any content by the model, but a
2156 // bibliography in it is placed outside the box (`adjust_backmatter_element`), so the walk looks further up — and a
2157 // quote outside the box is not closed from within it (probe b_qmq; b_quote_in_minipage's own quote is closed).
2158 let mut left_box = false;
2159 loop {
2160 let Some(current) = node else {
2161 return Ok(false);
2162 };
2163 if current.get_type() != Some(NodeType::ElementNode) {
2164 return Ok(false);
2165 }
2166 if is_capture_block(¤t) {
2167 left_box = true;
2168 node = current.get_parent();
2169 continue;
2170 }
2171 let current_qname = get_node_qname(¤t);
2172 if qsyms.iter().any(|q| {
2173 sym_can_contain_somehow(current_qname, *q).is_some() && holds_in_quote_block(¤t, *q)
2174 }) {
2175 break;
2176 }
2177 if current_qname == pin!("ltx:quote") && !can_auto_close(¤t) && !left_box {
2178 quotes.push(current.clone());
2179 } else if !can_auto_close(¤t) {
2180 return Ok(false);
2181 }
2182 node = current.get_parent();
2183 }
2184 let Some(outermost) = quotes.last().cloned() else {
2185 return Ok(false);
2186 };
2187 self.close_node_internal(&outermost)?;
2188 for quote in quotes {
2189 let empty = quote.get_child_nodes().iter().all(|child| {
2190 child.get_type() == Some(NodeType::TextNode) && child.get_content().trim().is_empty()
2191 });
2192 if empty {
2193 self.remove_node(quote);
2194 }
2195 }
2196 Ok(true)
2197 }
2198
2199 /// A bibliography begun in a float or a heading (the nearest container that does not auto-close) is built after it, in
2200 /// the nearest open ancestor that can hold it (cond-mat0108156, hep-ph0004227; OXIDIZED_DESIGN_DIVERGENCES #1099).
2201 pub fn float_backmatter_out_of_container(&mut self, qname: &str) -> Result<bool> {
2202 let mut node = Some(self.node.clone());
2203 while let Some(current) = node {
2204 if current.get_type() == Some(NodeType::ElementNode) && !can_auto_close(¤t) {
2205 if !with_node_qname(¤t, |q| {
2206 matches!(q, "ltx:figure" | "ltx:table" | "ltx:float" | "ltx:title")
2207 }) {
2208 return Ok(false);
2209 }
2210 break;
2211 }
2212 node = current.get_parent();
2213 }
2214 let Some(saved) = self.float_to_element(qname, false)? else {
2215 return Ok(false);
2216 };
2217 let container = self.node.clone();
2218 self.floated_backmatter.push((container, saved));
2219 Ok(true)
2220 }
2221
2222 /// The close of back matter [`Document::float_backmatter_out_of_container`] floated: back to the point it left.
2223 pub fn restore_floated_backmatter(&mut self) {
2224 if self
2225 .floated_backmatter
2226 .last()
2227 .is_some_and(|(container, _)| *container == self.node)
2228 && let Some((_, saved)) = self.floated_backmatter.pop()
2229 {
2230 self.set_node(&saved);
2231 }
2232 }
2233
2234 /// A theorem or proof in an abstract, dissolved at its close (DG 2026-11-19: a theorem there is markup used for
2235 /// typesetting, the abstract is what stays): its title opens its first paragraph as a run-in `ltx:text`, as the PDF
2236 /// sets it; its paragraphs, lists, equations and quotes go into the abstract in its place. That paragraph takes the
2237 /// theorem's id only: neither `ltx:p` nor `ltx:block` carries `labels` or `ltx:tags` in the schema, so its label and
2238 /// number tags are dropped and a `\ref` to it is unresolved (DG 2026-11-20). Witnesses 1908.02189, math0111087
2239 /// (`\proclaim`), 0804.0728 (`\newtheorem*{keywords}`); OXIDIZED_DESIGN_DIVERGENCES #1097.
2240 fn dissolve_theorem_in_abstract(&mut self, theorem: &Node) -> Result<()> {
2241 let id = theorem.get_attribute_ns("id", XML_NS);
2242 let mut tags = None;
2243 let mut title = None;
2244 let mut body = Vec::new();
2245 for child in theorem.get_child_nodes() {
2246 let qname = if child.get_type() == Some(NodeType::ElementNode) {
2247 arena::to_string(get_node_qname(&child))
2248 } else {
2249 String::new()
2250 };
2251 match qname.as_str() {
2252 "ltx:tags" => tags = Some(child),
2253 "ltx:title" => title = Some(child),
2254 "ltx:toctitle" => self.remove_node(child),
2255 // A paragraph (Para.class) cannot stand in the abstract; its blocks can.
2256 "ltx:para" => body.extend(child.get_child_nodes()),
2257 _ => body.push(child),
2258 }
2259 }
2260 let starts_with_p = body.first().is_some_and(|n| name_is(n, "p"));
2261 let mut first_p = if starts_with_p {
2262 body[0].clone()
2263 } else if title.is_some() || id.is_some() {
2264 // A theorem opening on a display or a list: its title is a paragraph of its own.
2265 let mut parent = theorem
2266 .get_parent()
2267 .expect("a theorem to dissolve has a parent");
2268 let mut p = self.open_element_at(&mut parent, "ltx:p", None, None)?;
2269 p.unlink();
2270 body.insert(0, p.clone());
2271 p
2272 } else {
2273 return self.replace_node(theorem.clone(), body);
2274 };
2275 if let Some(mut title) = title {
2276 // `ltx:tag` is no inline element: the title's number becomes a text in its font, as the title itself.
2277 for tag in xml::element_nodes(&title) {
2278 if name_is(&tag, "tag") {
2279 let font = self.get_node_font(&tag).clone();
2280 let mut text = self.rename_node(tag, "ltx:text", false)?;
2281 self.set_node_font(&mut text, &font)?;
2282 }
2283 }
2284 let mut font = self.get_node_font(&title).clone();
2285 let class = title.get_attribute("class").unwrap_or_default();
2286 if !class.split_whitespace().any(|c| c == "ltx_runin") {
2287 // A display title (amsppt's `\proclaim`, math0111087) is a bold heading: bold when run in.
2288 if let Some(bold) = crate::common::font::lookup_font_series("b") {
2289 font = font.merge_ref(bold);
2290 }
2291 title.set_attribute(
2292 "class",
2293 class
2294 .split_whitespace()
2295 .chain(["ltx_runin"])
2296 .collect::<Vec<_>>()
2297 .join(" ")
2298 .as_str(),
2299 )?;
2300 }
2301 let mut runin = self.rename_node(title, "ltx:text", false)?;
2302 self.set_node_font(&mut runin, &font)?;
2303 runin.unlink();
2304 match first_p.get_first_child() {
2305 // libxml2 merges a text node added beside a text node: the space joins the text instead.
2306 Some(mut first) if first.get_type() == Some(NodeType::TextNode) => {
2307 first.add_prev_sibling(&mut runin)?;
2308 let content = first.get_content();
2309 first.set_content(&format!(" {}", content.trim_start()))?;
2310 },
2311 Some(mut first) => {
2312 first.add_prev_sibling(&mut runin)?;
2313 let mut space = Node::new_text(" ", &self.document)?;
2314 first.add_prev_sibling(&mut space)?;
2315 },
2316 None => first_p.add_child(&mut runin)?,
2317 }
2318 }
2319 if let Some(tags) = tags {
2320 // The printed number is in the run-in title already; the abstract admits no `ltx:tags`.
2321 self.remove_node(tags);
2322 }
2323 self.replace_node(theorem.clone(), body)?;
2324 if let Some(id) = id {
2325 if let Some(old) = first_p.get_attribute_ns("id", XML_NS) {
2326 self.unrecord_id(&old);
2327 }
2328 self.set_attribute(&mut first_p, "xml:id", &id)?;
2329 }
2330 Ok(())
2331 }
2332
2333 /// Whether a `qname` element is open on the current ancestor chain (a font-switch `ltx:text`
2334 /// does not count as an open `ltx:text`).
2335 fn is_open_on_chain(&self, qname: &str) -> bool {
2336 let qsym = arena::pin(qname);
2337 let mut node = if self.node.get_type() == Some(NodeType::TextNode) {
2338 self.node.get_parent()
2339 } else {
2340 Some(self.node.clone())
2341 };
2342 while let Some(n) = node {
2343 if n.get_type() != Some(NodeType::ElementNode) {
2344 break;
2345 }
2346 if get_node_qname(&n) == qsym && !(qsym == pin!("ltx:text") && n.has_attribute("_fontswitch"))
2347 {
2348 return true;
2349 }
2350 node = n.get_parent();
2351 }
2352 false
2353 }
2354
2355 /// Closes a still-open `qname` element whose source groups were ABANDONED (tex.web §1335: the
2356 /// groups open at `\end` are reported once, then dropped): every descendant still open closes
2357 /// with it — running each one's close-time hooks: the bare-`\bibitem` bibliography's heading
2358 /// absorption (repros boxes-groups/abandoned_document_close_runs_bibliography_hooks,
2359 /// …_invents_no_bibliography_title), the empty-para prune (jpnedumathsymbols-doc), the `ltx:p`
2360 /// whitespace trim (tikz-optics). The descendants that do not auto-close are listed in an Info
2361 /// line (biblatex-ms: `itemize`), not a Warning: the abandonment was reported already. A no-op
2362 /// when no `qname` element is open.
2363 pub fn close_abandoned_element(&mut self, qname: &str) -> Result<Option<Node>> {
2364 if self.is_open_on_chain(qname) {
2365 self.close_element_impl(qname, CloseDescendants::Abandoned)
2366 } else {
2367 Ok(None)
2368 }
2369 }
2370
2371 pub fn close_element(&mut self, qname: &str) -> Result<Option<Node>> {
2372 self.close_element_impl(qname, CloseDescendants::Strict)
2373 }
2374
2375 fn close_element_impl(
2376 &mut self,
2377 qname: &str,
2378 descendants: CloseDescendants,
2379 ) -> Result<Option<Node>> {
2380 Debug!(
2381 "document",
2382 "close_element",
2383 s!(
2384 "Close element {:?} at {:?}",
2385 qname,
2386 self.document.node_to_string(&self.node)
2387 )
2388 );
2389 let qsym = arena::pin(qname);
2390 self.close_text_internal()?;
2391 let mut node = self.node.clone();
2392 let mut cant_close = Vec::new();
2393 while node.get_type() != Some(NodeType::DocumentNode) {
2394 let t = get_node_qname(&node);
2395 // autoclose until node of same name BUT also close nodes opened' for font
2396 // switches!
2397 if t == qsym
2398 && !(t == pin!("ltx:text") && node.has_attribute("_fontswitch"))
2399 && !is_trivlist(&node)
2400 {
2401 break;
2402 }
2403 if !can_auto_close(&node) {
2404 cant_close.push(node.clone());
2405 }
2406 match node.get_parent() {
2407 Some(parent) => {
2408 node = parent;
2409 },
2410 None => break, // detached node — treat as not found
2411 }
2412 }
2413
2414 if node.get_type() == Some(NodeType::DocumentNode) {
2415 // Didn't find $qname at all!! Unless the construct closing it never ended: its element
2416 // auto-closed already, when the structure after it arrived (OXIDIZED_DESIGN #542).
2417 if self.absorbing_unended_box() {
2418 return Ok(None);
2419 }
2420 let qname_msg: String = match qname {
2421 "#PCDATA" => qname.to_owned(),
2422 _ => s!("</{qname}>"),
2423 };
2424 let message = s!(
2425 "Attempt to close {}, which isn't open. Currently in {}",
2426 qname_msg,
2427 self.get_insertion_context(None)?
2428 );
2429 Error!("malformed", qname, message);
2430 Ok(None)
2431 } else {
2432 // Found node.
2433 if !cant_close.is_empty() {
2434 // Intervening non-auto-closeable nodes!!
2435 let message = s!(
2436 "Closing tag {:?} whose open descendents do not auto-close. Descendants are {:?}",
2437 qname,
2438 cant_close
2439 .into_iter()
2440 .map(|n| n.get_name())
2441 .collect::<Vec<String>>()
2442 .join(",")
2443 );
2444 match descendants {
2445 CloseDescendants::Strict => Error!("malformed", qname, message),
2446 CloseDescendants::Abandoned => {
2447 Info!(
2448 "malformed",
2449 qname,
2450 s!("{message} (their groups were abandoned)")
2451 )
2452 },
2453 }
2454 }
2455 // So, now close up to the desired node.
2456 self.close_node_internal(&node)?;
2457 Ok(Some(node))
2458 }
2459 }
2460
2461 // Check whether it is possible to open $qname at this point,
2462 // possibly by autoOpen'ing & autoClosing other tags.
2463 pub fn is_openable(&self, test_qname: &str) -> bool {
2464 let mut node_opt = Some(self.node.clone());
2465 let test_sym = arena::pin(test_qname);
2466 while let Some(node) = node_opt {
2467 let node_qname = get_node_qname(&node);
2468 if sym_can_contain_somehow(node_qname, test_sym).is_some() {
2469 return true;
2470 } else if !can_auto_close(&node) {
2471 return false; // could close, then check if parent can contain
2472 } else {
2473 node_opt = node.get_parent();
2474 }
2475 }
2476 false
2477 }
2478
2479 /// Check whether it is possible to close each element in @tags,
2480 /// any intervening nodes must be autocloseable.
2481 /// returning the last Some(node) that would be closed if it is possible,
2482 /// otherwise None
2483 pub fn is_closeable<T: IntoVDQS>(&self, tags: T) -> Option<Node> {
2484 let mut tags: VecDeque<SymStr> = tags.into_vdqs();
2485 let mut node_opt = if self.node.get_type() == Some(NodeType::TextNode) {
2486 self.node.get_parent()
2487 } else {
2488 Some(self.node.clone())
2489 };
2490 while let Some(qname) = tags.pop_front() {
2491 'inner: loop {
2492 let node: &Node = match node_opt {
2493 None => break,
2494 Some(ref n) => n,
2495 };
2496 let node_type = node.get_type();
2497 if node_type == Some(NodeType::DocumentNode) || node_type.is_none() {
2498 return None;
2499 }
2500 let this_qname = get_node_qname(node);
2501 if this_qname == qname && !is_trivlist(node) {
2502 break 'inner;
2503 }
2504 if !can_auto_close(node) {
2505 Debug!(
2506 "It was impossible to autoclose node: {:?}",
2507 self.document.node_to_string(node)
2508 );
2509 return None;
2510 }
2511 node_opt = node.get_parent();
2512 }
2513 if !tags.is_empty()
2514 && let Some(node) = node_opt
2515 {
2516 node_opt = node.get_parent();
2517 }
2518 }
2519 node_opt
2520 }
2521
2522 /// Close `qname`, if it is closeable — the forgiving counterpart to
2523 /// [`close_element`](Self::close_element).
2524 ///
2525 /// Returns the closed node, or `None` when no such element is open (or it
2526 /// cannot be auto-closed from here). That "or nothing happens" is the point:
2527 /// it lets a binding close an element it *may* have opened without having to
2528 /// track whether it did, where `close_element` would report an error.
2529 pub fn maybe_close_element(&mut self, qname: &str) -> Result<Option<Node>> {
2530 match self.is_closeable(qname) {
2531 Some(node) => {
2532 self.close_node_internal(&node)?;
2533 Ok(Some(node))
2534 },
2535 _ => Ok(None),
2536 }
2537 }
2538
2539 /// Closes all nodes until $node becomes the current point.
2540 pub fn close_to_node(&mut self, node: &Node, ifopen: bool) -> Result<()> {
2541 let mut cant_close = Vec::new();
2542 let mut lastopen: Option<Node> = None;
2543 let mut n = self.node.clone();
2544 let mut n_type = n.get_type();
2545 // go up the tree from current node, till we find `node`
2546 while n_type != Some(NodeType::DocumentNode) && &n != node {
2547 if !can_auto_close(&n) {
2548 cant_close.push(n.clone());
2549 }
2550 lastopen = Some(n.clone());
2551 match n.get_parent() {
2552 Some(p) => {
2553 n = p;
2554 n_type = n.get_type();
2555 },
2556 _ => {
2557 break;
2558 },
2559 }
2560 }
2561 // A `ltx:_CaptureBlock_` is a completed BOX (`\parbox`/minipage/`\vbox`
2562 // capture, `insert_block`): tex.web's box completeness — nothing stays
2563 // open across a finished box — so its non-auto-closeable descendants are
2564 // closed BY the box, not reported (the close already happened below; the
2565 // Error was a spurious diagnostic over an identical tree, Perl the same:
2566 // testnumberedblock `numVblock` around `verbatim`, algpseudocodex and
2567 // coloredtheorem `algorithmic` lines in a minipage). Guard:
2568 // `perfect_kernel_batch54::capture_box_closes_its_descendants`.
2569 if is_capture_block(node) {
2570 cant_close.clear();
2571 }
2572 if n_type == Some(NodeType::DocumentNode) {
2573 // Didn't find $node at all!!
2574 // Perl: suppress error when $ifopen is true. Nor when the node's construct never ended:
2575 // it auto-closed already (OXIDIZED_DESIGN #542).
2576 if !ifopen && !node.has_attribute(UNENDED_ATTRIBUTE) {
2577 let message = s!("Attempt to close {:?}, which isn't open", node.get_name());
2578 arena::with(get_node_qname(node), |qname_str| {
2579 {
2580 Error!("malformed", qname_str, message)
2581 };
2582 Ok(())
2583 })?;
2584 }
2585 } else {
2586 // Found node.
2587 if !cant_close.is_empty() {
2588 // But found has intervening non-auto-closeable nodes!!
2589 let qname = get_node_qname(node);
2590 let message = s!(
2591 "Closing {:?} whose open descendents do not auto-close. Descendants are: {:?}",
2592 qname,
2593 cant_close
2594 .into_iter()
2595 .map(|n| n.get_name())
2596 .collect::<Vec<String>>()
2597 .join(",")
2598 );
2599 arena::with(qname, |qname_str| {
2600 {
2601 Error!("malformed", qname_str, message)
2602 };
2603 Ok(())
2604 })?;
2605 }
2606 if let Some(lastopen_node) = lastopen {
2607 self.close_node_internal(&lastopen_node)?;
2608 }
2609 }
2610 Ok(())
2611 }
2612
2613 /// Closes all nodes until $node is closed.
2614 pub fn close_node(&mut self, node: &Node) -> Result<()> {
2615 self.close_node_with_strictness(true, node)
2616 }
2617 /// Only if needed/possible: closes all nodes until $node is closed
2618 pub fn maybe_close_node(&mut self, node: &Node) -> Result<()> {
2619 self.close_node_with_strictness(false, node)
2620 }
2621
2622 pub fn close_node_with_strictness(&mut self, strict: bool, node: &Node) -> Result<()> {
2623 // Perl: my ($t, @cant_close) = (); ... while ((($t = $n->getType) != XML_DOCUMENT_NODE) ...
2624 let mut cant_close: Vec<Node> = Vec::new();
2625 let mut n = self.node.clone();
2626 let mut t = n.get_type(); // track walker node type, not target
2627 while t.is_some() && t != Some(NodeType::DocumentNode) && &n != node {
2628 if !can_auto_close(&n) {
2629 cant_close.push(n.clone());
2630 }
2631 match n.get_parent() {
2632 Some(parent) => {
2633 n = parent;
2634 t = n.get_type();
2635 },
2636 None => {
2637 t = None; // detached node — stop walking
2638 },
2639 }
2640 }
2641
2642 if is_capture_block(node) {
2643 cant_close.clear(); // box completeness, see `close_to_node`
2644 }
2645 if t == Some(NodeType::DocumentNode) || t.is_none() {
2646 // Didn't find $qname at all!! (A node whose construct never ended auto-closed already,
2647 // OXIDIZED_DESIGN #542.)
2648 if strict && !node.has_attribute(UNENDED_ATTRIBUTE) {
2649 let qname = get_node_qname(node);
2650 arena::with(qname, |qname_str| {
2651 let message = s!(
2652 "Attempt to close {}, which isn't open. Currently in {:?}",
2653 qname_str,
2654 self.get_insertion_context(None)?
2655 );
2656 {
2657 Error!("malformed", qname_str, message)
2658 };
2659 Ok(())
2660 })?;
2661 }
2662 } else {
2663 // Found node.
2664 // Intervening non-auto-closeable nodes!!
2665 if !cant_close.is_empty() {
2666 model::with_node_qname(node, |qname| {
2667 let message = s!(
2668 "Closing {} whose open descendents do not auto-close. Descendents are {}",
2669 qname,
2670 cant_close
2671 .iter()
2672 .map(Node::get_name)
2673 .collect::<Vec<String>>()
2674 .join(", ")
2675 );
2676 if strict {
2677 Error!("malformed", qname, message);
2678 } else {
2679 Info!("malformed", qname, message);
2680 }
2681 Ok(())
2682 })?;
2683 }
2684 self.close_node_internal(node)?;
2685 }
2686 Ok(())
2687 }
2688
2689 /// Like [`Self::get_tag_action_list`], but keeps the `_Late` bucket
2690 /// separate. Streaming needs the split: a root's early/normal hooks
2691 /// (structural — the pending-resource drain) run at open as usual, while
2692 /// its `_late` hooks (semantically "with digestion complete" — frontmatter
2693 /// placement, root classes) are deferred to end-of-digestion.
2694 pub fn get_tag_action_list_parts(
2695 &self,
2696 tag: SymStr,
2697 when: TagOptionName,
2698 ) -> (Vec<TagConstructionClosure>, Vec<TagConstructionClosure>) {
2699 use self::tag::TagOptionName::*;
2700 let (when_early, when_late) = match when {
2701 AfterOpen => (Some(AfterOpenEarly), Some(AfterOpenLate)),
2702 AfterClose => (Some(AfterCloseEarly), Some(AfterCloseLate)),
2703 _ => (None, None),
2704 };
2705 let mut prompt = Vec::new();
2706 let mut late = Vec::new();
2707 state::with_tag_property(tag, |tag_hash| {
2708 state::with_tag_property(pin!("ltx:*"), |all_hash| {
2709 let collect =
2710 |bucket: &mut Vec<TagConstructionClosure>, opts: Option<&tag::TagOptions>, key| {
2711 if let Some(v) = opts.and_then(|o| o.get(key)) {
2712 bucket.extend(v.iter().cloned());
2713 }
2714 };
2715 if let Some(when0) = &when_early {
2716 collect(&mut prompt, tag_hash, when0);
2717 collect(&mut prompt, all_hash, when0);
2718 }
2719 collect(&mut prompt, tag_hash, &when);
2720 collect(&mut prompt, all_hash, &when);
2721 if let Some(when1) = &when_late {
2722 collect(&mut late, tag_hash, when1);
2723 collect(&mut late, all_hash, when1);
2724 }
2725 });
2726 });
2727 (prompt, late)
2728 }
2729
2730 /// get the actions that should be performed on afterOpen or afterClose
2731 pub fn get_tag_action_list(
2732 &self,
2733 tag: SymStr,
2734 when: TagOptionName,
2735 ) -> Vec<TagConstructionClosure> {
2736 use self::tag::TagOptionName::*;
2737 // my ($p, $n) = (undef, $tag);
2738 // if ($tag =~ /^([^:]+):(.+)$/) {
2739 // ($p, $n) = ($1, $2); }
2740 let mut when_early = None;
2741 let mut when_late = None;
2742
2743 match when {
2744 AfterOpen => {
2745 when_early = Some(AfterOpenEarly);
2746 when_late = Some(AfterOpenLate);
2747 },
2748 AfterClose => {
2749 when_early = Some(AfterCloseEarly);
2750 when_late = Some(AfterCloseLate);
2751 },
2752 _ => {},
2753 };
2754
2755 let mut actions = Vec::new();
2756 // Borrow the per-tag and `ltx:*` option hashes in place instead of cloning
2757 // the whole `TagOptions` map twice per call (this runs on every element
2758 // open/close — ~8.8M calls across the witness corpus). We only need to copy
2759 // the matched action lists, and those hold `Rc<>` closures, so cloning each
2760 // is just a pointer + refcount bump. `with_tag_property` returns `None` for
2761 // an absent tag, equivalent to an empty `TagOptions` for a read (the only
2762 // difference vs `get_tag_property` is it skips vivifying an empty default,
2763 // which has no observable effect).
2764 state::with_tag_property(tag, |tag_hash| {
2765 state::with_tag_property(pin!("ltx:*"), |all_hash| {
2766 let mut collect = |opts: Option<&tag::TagOptions>, key: &TagOptionName| {
2767 if let Some(v) = opts.and_then(|o| o.get(key)) {
2768 actions.extend(v.iter().cloned());
2769 }
2770 };
2771 if let Some(when0) = when_early {
2772 collect(tag_hash, &when0);
2773 // ns_hash TODO
2774 collect(all_hash, &when0);
2775 }
2776 collect(tag_hash, &when);
2777 // ns_hash TODO
2778 collect(all_hash, &when);
2779 if let Some(when1) = when_late {
2780 collect(tag_hash, &when1);
2781 // ns_hash TODO
2782 collect(all_hash, &when1);
2783 }
2784 });
2785 });
2786 // return (
2787 // (($v = $$taghash{$when0}) ? @$v : ()),
2788 // (($v = $$nshash{$when0}) ? @$v : ()),
2789 // (($v = $$allhash{$when0}) ? @$v : ()),
2790 // (($v = $$taghash{$when}) ? @$v : ()),
2791 // (($v = $$nshash{$when}) ? @$v : ()),
2792 // (($v = $$allhash{$when}) ? @$v : ()),
2793 // (($v = $$taghash{$when1}) ? @$v : ()),
2794 // (($v = $$nshash{$when1}) ? @$v : ()),
2795 // (($v = $$allhash{$when1}) ? @$v : ()),
2796 // );
2797 actions
2798 }
2799
2800 pub fn serialize_to_string(&self) -> String {
2801 // This line is to use libxml2's built-in serializer w/indentation heuristic.
2802 // Apparently, libxml2 is giving us "binary" or byte strings which we'd prefer
2803 // to have as text. return decode('UTF-8',
2804 // $self->getDocument->toString($format)); } This uses our own serializer
2805 // emulating libxml2's heuristic indentation.
2806 // This uses our own serializer with the correct schema-based indentation rules:
2807 // noindent_children=true when the element can contain #PCDATA per the schema.
2808 let mut result = self.serialize_aux(&self.document.as_node(), 0, false, false);
2809 // Trim trailing newline in place (the root element adds \n after </document>
2810 // but Perl doesn't include it) without allocating a second document-sized String.
2811 let trimmed_len = result.trim_end_matches('\n').len();
2812 result.truncate(trimmed_len);
2813 result.push('\n');
2814 result
2815 }
2816
2817 /// [`Document::serialize_to_string`]'s bytes, written to a new file at `path` instead: a split run's core
2818 /// result goes to post through a file, and a document-sized `String` (2 GiB for Nasser's whole book, issue 777)
2819 /// would exist only to be written there. On a write error the partial file is removed. Returns the bytes written.
2820 pub fn serialize_to_file(&self, path: &std::path::Path) -> std::io::Result<u64> {
2821 let mut sink = FileSink::new(std::fs::File::create(path)?, 1 << 20);
2822 self.serialize_into(
2823 &mut sink,
2824 self.document.as_node().as_readonly(),
2825 0,
2826 false,
2827 false,
2828 );
2829 let result = sink.finish();
2830 if result.is_err() {
2831 let _ = std::fs::remove_file(path);
2832 }
2833 result
2834 }
2835
2836 /// We ought to try for something close to C14N (<http://www.w3.org/TR/xml-c14n>),
2837 /// but keep XML declaration, comments and don't convert empty elements.
2838 pub fn serialize_aux(
2839 &self,
2840 node: &Node,
2841 depth: usize,
2842 noindent: bool,
2843 heuristic: bool,
2844 ) -> String {
2845 let mut serialized = String::new();
2846 self.serialize_into(
2847 &mut serialized,
2848 node.as_readonly(),
2849 depth,
2850 noindent,
2851 heuristic,
2852 );
2853 serialized
2854 }
2855
2856 /// Splice a processed segment's text into `out`, resolving NESTED
2857 /// placeholders recursively (final assembly only). A segment spilled by a
2858 /// closing ancestor keeps its children's `<_spilled_ ref=…/>` markers as
2859 /// literal elements — inlining their text at spill time rebuilt multi-GB
2860 /// segments that pass 2 could not re-materialize. Each literal marker
2861 /// occupies either a full line (`indent + element + newline`, the
2862 /// indenting serialization) or an exact element span (noindent contexts);
2863 /// the inner segment text carries its own indentation/newline, so the
2864 /// marker's surrounding whitespace is dropped — but ONLY when the marker
2865 /// is line-positioned, so content spaces in noindent contexts survive.
2866 /// `<` is escaped everywhere in serialized text/attribute content, so the
2867 /// scan cannot match anything but real markers.
2868 fn splice_segment_text<S: SerializeSink>(&self, out: &mut S, text: &str) {
2869 let mut rest = text;
2870 while !out.failed()
2871 && let Some(pos) = rest.find("<_spilled_ ")
2872 {
2873 let (before, from) = rest.split_at(pos);
2874 let Some(elem_end) = from.find("/>").map(|e| e + 2) else {
2875 break; // malformed marker: emit as-is below
2876 };
2877 let elem = &from[..elem_end];
2878 let seg_opt = elem
2879 .split_once("ref=\"")
2880 .and_then(|(_, tail)| tail.split_once('"'))
2881 .and_then(|(num, _)| num.parse::<u32>().ok())
2882 .map(crate::sxml::SegmentId);
2883 let inner = seg_opt.and_then(|seg| {
2884 self
2885 .spill_store
2886 .as_ref()
2887 .and_then(|store| store.read_segment(seg).ok())
2888 });
2889 let Some(inner) = inner else {
2890 emit_error(
2891 "spill",
2892 "unresolved",
2893 &format!("a nested disk-staged segment could not be spliced back ({elem})"),
2894 );
2895 out.push_str(before);
2896 out.push_str("<!-- latexml-oxide: LOST staged segment -->\n");
2897 rest = &from[elem_end..];
2898 continue;
2899 };
2900 // Drop the marker's own line whitespace when line-positioned.
2901 let mut cut = before.len();
2902 while cut > 0 && before.as_bytes()[cut - 1] == b' ' {
2903 cut -= 1;
2904 }
2905 let line_positioned = cut == 0 || before.as_bytes()[cut - 1] == b'\n';
2906 if line_positioned {
2907 out.push_str(&before[..cut]);
2908 } else {
2909 out.push_str(before);
2910 }
2911 NESTED_SPLICES.set(NESTED_SPLICES.get() + 1);
2912 self.splice_segment_text(out, &inner);
2913 rest = &from[elem_end..];
2914 if line_positioned && rest.starts_with('\n') {
2915 rest = &rest[1..];
2916 }
2917 }
2918 out.push_str(rest);
2919 }
2920
2921 /// Buffer-threaded core of [`serialize_aux`]. Writes the subtree directly into
2922 /// `out` instead of building (and re-copying) a fresh `String` per node — the
2923 /// recursive return-a-String pattern was the single largest byte source in the
2924 /// allocation profile (~2.8 GB across the witness corpus). Output is identical. The walk is read-only, so it
2925 /// wraps no `Node`s: a wrapper is a registry entry kept until the document drops (PERF2 R5).
2926 fn serialize_into<S: SerializeSink>(
2927 &self,
2928 out: &mut S,
2929 node: RoNode,
2930 depth: usize,
2931 noindent: bool,
2932 heuristic: bool,
2933 ) {
2934 // Push `depth` levels of two-space indent without the `" ".repeat(depth)`
2935 // allocation the old code paid on every call (including text nodes).
2936 fn push_indent<S: SerializeSink>(out: &mut S, depth: usize) {
2937 for _ in 0..depth {
2938 out.push_str(" ");
2939 }
2940 }
2941 if out.failed() {
2942 return;
2943 }
2944 // `spill_flat` means "emit no decorative whitespace", which is exactly what
2945 // `noindent` already means at every emission site — so fold it in ONCE here
2946 // rather than testing it at each. It suppresses formatting only; the
2947 // schema-driven `noindent_children` still governs mixed content, whose
2948 // whitespace is meaningful and was never indented anyway.
2949 let noindent = noindent || self.spill_flat;
2950
2951 match node.get_type() {
2952 Some(NodeType::DocumentNode) => {
2953 out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2954 let mut child = node.get_first_child();
2955 while let Some(current) = child {
2956 self.serialize_into(out, current, depth, noindent, heuristic);
2957 child = current.get_next_sibling();
2958 }
2959 },
2960 Some(NodeType::ElementNode) => {
2961 // Get the qualified name (prefix:localname) for namespace-prefixed elements
2962 let local_name = node.with_name(str::to_owned);
2963 // Streaming assembly: a spill placeholder serializes as the processed
2964 // segment's text, spliced verbatim from disk (same depth/noindent by
2965 // construction — the segment was serialized with the exact values this
2966 // recursion carries here). A placeholder that cannot be resolved is
2967 // LOST CONTENT: flag it loudly in the log AND the output, never drop
2968 // it silently (fail toward flagging).
2969 if local_name == SPILL_PLACEHOLDER && !self.literal_placeholders {
2970 let resolved = self
2971 .spill_store
2972 .as_ref()
2973 .zip(node.get_attribute("ref"))
2974 .and_then(|(store, r)| {
2975 let seg = crate::sxml::SegmentId(r.parse::<u32>().ok()?);
2976 store.read_segment(seg).ok()
2977 });
2978 match resolved {
2979 Some(text) => self.splice_segment_text(out, &text),
2980 None => {
2981 // `Error!` can early-return and this serializer returns `()`,
2982 // so raise through the logger; the marker keeps the loss
2983 // visible in the output itself.
2984 emit_error(
2985 "spill",
2986 "unresolved",
2987 &format!(
2988 "a disk-staged segment could not be spliced back (ref={:?})",
2989 node.get_attribute("ref")
2990 ),
2991 );
2992 out.push_str("<!-- latexml-oxide: LOST staged segment -->\n");
2993 },
2994 }
2995 return;
2996 }
2997 // (a literal_placeholders doc falls through: the placeholder is an
2998 // ordinary childless element and serializes as itself)
2999 let tag = node.with_namespace_prefix(|prefix| match prefix {
3000 Some(prefix) if !prefix.is_empty() => s!("{}:{}", prefix, local_name),
3001 _ => local_name,
3002 });
3003 let children = node.get_child_nodes();
3004
3005 // Every attribute's local name, document qname and value, in libxml2's order; each is its own
3006 // attribute, keyed by its qname as Perl's `%atnodes` is (Document.pm:491), so `lang` beside `xml:lang`
3007 // or `id` beside `xml:id` keeps both. `document_qname` resolves the attribute's NAMESPACE: "xml:id" for
3008 // an `xml:id`, "id" for a genuine plain `id`, which the model really does declare (see
3009 // `LaTeXML-bib.rnc:335,353`: `ltx:bib-identifier/@id`, `ltx:bib-review/@id`; witness arXiv 2508.17585).
3010 // Ordering stays keyed on the local name, which is what the goldens encode (`xml:lang` files under
3011 // "lang", so it precedes `role`), with `xml:id` forced last; two attributes sharing a local name go in
3012 // qname order, as Perl's `sort keys`.
3013 let mut anodes: Vec<(String, SymStr, String)> = Vec::new();
3014 node.for_each_property_ns(|key, href, value| {
3015 anodes.push((
3016 key.to_owned(),
3017 model::document_qname(href, key),
3018 value.to_owned(),
3019 ));
3020 });
3021 // Rank: xmlns:* declarations first (matching Perl's output order), then
3022 // the ordinary attributes by local name, then xml:id last.
3023 let rank = |qname: SymStr, key: &String| -> u8 {
3024 if key.starts_with("xmlns:") {
3025 0
3026 } else if arena::with(qname, |q| q == "xml:id") {
3027 2
3028 } else {
3029 1
3030 }
3031 };
3032 anodes.sort_by(|(a_key, a_sym, _), (b_key, b_sym, _)| {
3033 rank(*a_sym, a_key)
3034 .cmp(&rank(*b_sym, b_key))
3035 .then_with(|| a_key.cmp(b_key))
3036 .then_with(|| arena::with(*a_sym, |a| arena::with(*b_sym, |b| a.cmp(b))))
3037 });
3038 let noindent_children: bool = if heuristic {
3039 // libxml2's heuristic: inline (noindent) if ANY direct child is a text node.
3040 // Crucially, this does NOT propagate the parent's noindent — each element
3041 // independently checks its own children for text nodes.
3042 children
3043 .iter()
3044 .any(|e| e.get_type() == Some(NodeType::TextNode))
3045 } else {
3046 // This is the "Correct" way to determine whether to add indentation
3047 let node_qname = model::get_ro_node_qname(node);
3048 model::can_contain_sym(node_qname, pin!("#PCDATA"))
3049 };
3050
3051 let noindent_children = noindent_children || self.spill_flat;
3052 if !noindent {
3053 push_indent(out, depth);
3054 }
3055 // The open tag, written in place: its namespace declarations, then the attributes, each value escaped.
3056 out.push('<');
3057 out.push_str(&tag);
3058 for ns in node.get_namespace_declarations() {
3059 let prefix = ns.get_prefix();
3060 out.push_str(" xmlns");
3061 if !prefix.is_empty() {
3062 out.push(':');
3063 out.push_str(&prefix);
3064 }
3065 out.push_str("=\"");
3066 out.push_str(&ns.get_href());
3067 out.push('"');
3068 }
3069 for (_, key_sym, value) in anodes {
3070 out.push(' ');
3071 arena::with(key_sym, |key_str| out.push_str(key_str));
3072 out.push_str("=\"");
3073 push_escaped_attr(out, &value);
3074 out.push('"');
3075 }
3076 // Perl serializes elements with children (including empty text nodes) as
3077 // <tag>...</tag>, and truly childless elements as <tag/>. Match this behavior.
3078 if !children.is_empty() {
3079 // with contents.
3080 out.push('>');
3081 if !noindent_children {
3082 out.push('\n');
3083 }
3084 for child in children {
3085 self.serialize_into(out, child, depth + 1, noindent_children, heuristic);
3086 }
3087 if !noindent_children {
3088 push_indent(out, depth);
3089 }
3090 out.push_str("</");
3091 out.push_str(&tag);
3092 out.push('>');
3093 } else {
3094 // empty element.
3095 out.push_str("/>");
3096 }
3097 if !noindent {
3098 out.push('\n');
3099 }
3100 },
3101 Some(NodeType::TextNode) => {
3102 node.with_content(|text| push_escaped_text(out, text));
3103 },
3104 Some(NodeType::PiNode) => {
3105 // should code this by hand, as well...
3106 if !noindent {
3107 push_indent(out, depth);
3108 }
3109 out.push_str(&self.document.ronode_to_string(&node));
3110 if !noindent {
3111 out.push('\n');
3112 }
3113 },
3114 Some(NodeType::CommentNode) => {
3115 out.push_str("<!-- ");
3116 node.with_content(|text| push_escaped_text(out, text));
3117 out.push_str("-->");
3118 },
3119 _ => {},
3120 }
3121 }
3122
3123 /// Move the current insertion point to `node` — Perl `Document.pm:setNode`
3124 /// L74-87.
3125 ///
3126 /// A document fragment is not itself an insertion point: as in Perl, a
3127 /// single-child fragment is descended into, and a fragment with several
3128 /// children is an error (reported, not fatal — see the body comment on why
3129 /// this returns `()`).
3130 pub fn set_node(&mut self, node: &Node) {
3131 // Perl Document.pm:setNode L74-76: close any open text node first, so its ligatures run — moving the insertion
3132 // point (a `^` float such as a footnote's `<ltx:note>` lifting to the paragraph) abandoned it unligated, and a
3133 // paragraph's text before a `\footnote` kept `‘‘a’’ b--c` (Perl and pdflatex “a” b–c). The error is libxml's
3134 // `set_content` on a live text node, as in every other close. Guard
3135 // `perfect_kernel_batch60::text_before_a_footnote_is_ligatured`. A `fontTest`'s Fatal stops the build's next step
3136 // (Perl dies here; rhai-bindings/fonttest_fatal_closed_by_set_node.tex).
3137 if let Err(e) = self.close_text_internal()
3138 && e.is_logged_fatal()
3139 {
3140 crate::stomach::stash_fatal(e);
3141 }
3142 // Perl Document.pm:setNode L77-87: if the candidate is a
3143 // DOCUMENT_FRAG_NODE, validate that it has exactly one child and
3144 // descend to that child. The original Rust port had this check
3145 // commented-out with a wrong-node-type marker (`DocumentNode`
3146 // instead of `DocumentFragNode`); revived with the correct enum.
3147 let mut chosen = node.clone();
3148 if chosen.get_type() == Some(NodeType::DocumentFragNode) {
3149 let children = chosen.get_child_nodes();
3150 // Wrap the Error!/note_status side-effects in an IIFE to swallow the
3151 // `Result<()>` the macro returns (it can early-return Err if the
3152 // MAX_ERRORS cap is hit). `set_node` returns `()` and is called from
3153 // 32 call-sites; threading `Result` through all of them is out of
3154 // scope for an audit-fix. The hot path stays the same; the rare
3155 // hit-the-cap case loses one escape attempt but the next Error!
3156 // anywhere else will trigger the cap regardless.
3157 let _ = (|| -> Result<()> {
3158 if children.len() > 1 {
3159 Error!(
3160 "unexpected",
3161 "multiple-nodes",
3162 "Cannot set insertion point to a DOCUMENT_FRAG_NODE"
3163 );
3164 } else if children.is_empty() {
3165 Error!(
3166 "unexpected",
3167 "empty-nodes",
3168 "Cannot set insertion point to an empty DOCUMENT_FRAG_NODE"
3169 );
3170 }
3171 Ok(())
3172 })();
3173 if let Some(first) = children.into_iter().next() {
3174 chosen = first;
3175 }
3176 }
3177 self.node = chosen;
3178 }
3179
3180 // Internals
3181 /// Scan for RDFa attributes in the document and set the `prefix` attribute
3182 /// on the root element based on which RDFa prefixes are actually used.
3183 fn set_rdfa_prefixes(&mut self) {
3184 // Collect the RDFa prefix mapping from state
3185 let prefix_map: HashMap<String, String> = state::with_mapping_keys("RDFa_prefixes", |keys| {
3186 let mut map = HashMap::default();
3187 for key_sym in keys {
3188 let key_str = arena::to_string(key_sym);
3189 if let Some(stored) = state::lookup_mapping("RDFa_prefixes", &key_str) {
3190 map.insert(key_str, stored.to_string());
3191 }
3192 }
3193 map
3194 });
3195 if prefix_map.is_empty() {
3196 return;
3197 }
3198
3199 let non_rdf_prefixes: HashSet<&str> = ["http", "https", "ftp"].iter().copied().collect();
3200 let rdf_term_attrs = [
3201 "about", "resource", "property", "typeof", "rel", "rev", "datatype",
3202 ];
3203
3204 // Build XPath to find elements with any RDFa term attribute
3205 let xpath = format!(
3206 "descendant::*[{}]",
3207 rdf_term_attrs
3208 .iter()
3209 .map(|a| format!("@{a}"))
3210 .collect::<Vec<_>>()
3211 .join(" or ")
3212 );
3213
3214 let mut used_prefixes: BTreeSet<String> = BTreeSet::new();
3215
3216 let nodes = self.findnodes(&xpath, None);
3217 for node in &nodes {
3218 for attr_name in &rdf_term_attrs {
3219 if let Some(value) = node.get_attribute(attr_name) {
3220 for term in value.split_whitespace() {
3221 if let Some(colon_pos) = term.find(':') {
3222 let prefix = &term[..colon_pos];
3223 if !non_rdf_prefixes.contains(prefix) && prefix_map.contains_key(prefix) {
3224 used_prefixes.insert(prefix.to_string());
3225 }
3226 }
3227 }
3228 }
3229 }
3230 }
3231
3232 for prefix in &self.extra_rdfa_prefixes {
3233 if !non_rdf_prefixes.contains(prefix.as_str()) && prefix_map.contains_key(prefix) {
3234 used_prefixes.insert(prefix.clone());
3235 }
3236 }
3237
3238 if !used_prefixes.is_empty()
3239 && let Some(mut root) = self.document.get_root_element()
3240 {
3241 let prefix_str = used_prefixes
3242 .iter()
3243 .map(|p| format!("{}: {}", p, prefix_map[p]))
3244 .collect::<Vec<_>>()
3245 .join(" ");
3246 let _ = root.set_attribute("prefix", &prefix_str);
3247 }
3248 }
3249
3250 pub fn insert_math_token(
3251 &mut self,
3252 text: &str,
3253 mut attributes: HashMap<String, String>,
3254 font_opt: Option<&Font>,
3255 ) -> Result<Node> {
3256 // Perf: avoid allocating the "role" String key unless the entry is missing.
3257 // HashMap::entry() takes an owned K, which forces allocation even on the
3258 // common path where "role" is already present.
3259 if !attributes.contains_key("role") {
3260 attributes.insert(String::from("role"), String::from("UNKNOWN"));
3261 }
3262 // Remove internal-only properties that should not become XML attributes.
3263 // In Perl, these are filtered by canHaveAttribute (model validation),
3264 // but we filter them explicitly here.
3265 attributes.remove("mode");
3266 attributes.remove("isMath");
3267 attributes.remove("cached_width");
3268 attributes.remove("cached_height");
3269 attributes.remove("cached_depth");
3270 attributes.remove(ABSORB_WARNING_PROPERTY);
3271 // attributes.remove("stretchy");
3272
3273 let is_space = attributes.contains_key("isSpace");
3274 let qname = if is_space {
3275 MATH_HINT_NAME
3276 } else {
3277 MATH_TOKEN_NAME
3278 };
3279 let cur_qname = get_node_qname(&self.node);
3280 let text = if is_space && !text.is_empty() && text.chars().all(|c| c.is_whitespace()) {
3281 "" // Make empty hint, of only spaces
3282 } else {
3283 text
3284 };
3285 if qname == MATH_TOKEN_NAME && cur_qname == pin!("ltx:XMTok") {
3286 // Already INSIDE a token!
3287 if !text.is_empty() {
3288 self.open_math_text_internal(text)?;
3289 }
3290 } else {
3291 let mut node = self.open_element(qname, Some(attributes), None)?;
3292 // let tbox = $attributes{_box} || $LaTeXML::BOX;
3293 let font = match font_opt {
3294 Some(f) => f.clone(),
3295 None => match self.box_to_absorb {
3296 Some(ref tbox) => match tbox.get_font()? {
3297 Some(f) => (*f).clone(),
3298 None => Font::math_default(), // should never happen?
3299 },
3300 None => Font::math_default(), // should never happen?
3301 },
3302 };
3303 self.set_node_font(&mut node, &font)?;
3304 if let Some(ref digested) = self.box_to_absorb {
3305 // TODO: The Rc<Digested> node boxes still have some way to go until they are fully
3306 // ergonomic...
3307 self.set_node_box(&node, digested.clone());
3308 }
3309 if !text.is_empty() {
3310 self.open_math_text_internal(text)?;
3311 }
3312 self.close_node_internal(&node)?; // Should be safe.
3313 }
3314 Ok(self.node.clone())
3315 }
3316
3317 /// Create a libxml2 comment node and attach it to `anchor` according to
3318 /// the supplied Placement. Called from `insert_comment`. Thin wrapper
3319 /// around the safe rust-libxml API (`Node::new_comment` +
3320 /// `add_child`/`add_prev_sibling`) — earlier versions of this method
3321 /// made direct FFI calls, which is now forbidden by the D3b policy.
3322 fn add_comment(document: &XmlDoc, anchor: &Node, comment_text: &str, placement: Placement_) {
3323 let Ok(mut comment) = Node::new_comment(comment_text, document) else {
3324 return;
3325 };
3326 let mut anchor = anchor.clone();
3327 match placement {
3328 Placement_::AppendChild => {
3329 let _ = anchor.add_child(&mut comment);
3330 },
3331 Placement_::PrevSibling => {
3332 let _ = anchor.add_prev_sibling(&mut comment);
3333 },
3334 }
3335 }
3336
3337 /// Insert a new comment, or append to previous comment.
3338 /// Does NOT move the current insertion point to the Comment,
3339 /// but may move up past a text node.
3340 /// Perl: Document.pm lines 678-698
3341 pub fn insert_comment(&mut self, text: &str) -> Result<Node> {
3342 let trimmed = text.trim_end();
3343 let clean = DASHES_RE.replace_all(trimmed, "__");
3344 // Perl does NOT close the text node here — it uses getElement() to find
3345 // the nearest element, then inserts the comment relative to element children.
3346 // This preserves self.node as the current text node, so subsequent text
3347 // appends correctly and ligatures fire on the full text run.
3348
3349 let comment_text = s!(" {} ", clean);
3350
3351 if self.node.get_type() == Some(NodeType::DocumentNode) {
3352 Self::add_comment(
3353 &self.document,
3354 &self.node,
3355 &comment_text,
3356 Placement_::AppendChild,
3357 );
3358 } else {
3359 if let Some(node) = self.get_element() {
3360 // Get the nearest element node (Perl: getElement)
3361 let prev = node.get_last_child();
3362 let prevtype = prev.as_ref().and_then(|n| n.get_type());
3363
3364 if prevtype == Some(NodeType::CommentNode) {
3365 // Merge with previous comment
3366 if let Some(mut prev_comment) = prev {
3367 let existing = prev_comment.get_content();
3368 let merged = s!("{}\n {} ", existing, clean);
3369 prev_comment.set_content(&merged).ok();
3370 }
3371 } else if prevtype == Some(NodeType::TextNode) {
3372 let prev_node = prev.unwrap();
3373 // If the node before the text is already a comment, just append new comment
3374 // Otherwise, insert before the text to avoid splitting text runs
3375 let before_text = prev_node.get_prev_sibling();
3376 let before_is_comment =
3377 before_text.as_ref().and_then(|n| n.get_type()) == Some(NodeType::CommentNode);
3378
3379 if before_is_comment {
3380 Self::add_comment(
3381 &self.document,
3382 &node,
3383 &comment_text,
3384 Placement_::AppendChild,
3385 );
3386 } else {
3387 Self::add_comment(
3388 &self.document,
3389 &prev_node,
3390 &comment_text,
3391 Placement_::PrevSibling,
3392 );
3393 }
3394 } else {
3395 Self::add_comment(
3396 &self.document,
3397 &node,
3398 &comment_text,
3399 Placement_::AppendChild,
3400 );
3401 }
3402 }
3403 }
3404 Ok(self.node.clone())
3405 }
3406
3407 // **********************************************************************
3408 // Middle level, mostly public, API.
3409 // Handlers for various construction operations.
3410 // General naming: 'open' opens a node at current pos and sets it to current,
3411 // 'close' closes current node(s), inserts opens & closes, ie. w/o moving
3412 // current
3413
3414 // Tricky: Insert some text in a particular font.
3415 // We need to find the current effective -- being the closest _declared_ font,
3416 // (ie. it will appear in the elements attributes). We may also want
3417 // to open/close some elements in such a way as to minimize the font switchiness.
3418 // I guess we should only open/close "text" elements, though.
3419 // [Actually, we'd like the user to _declare_ what element to use....
3420 // I don't like having "text" built in here!
3421 // AND, we've assumed that "font" names the relevant attribute!!!]
3422
3423 /// Perl `openText`'s whitespace rule (Document.pm:747-749): whitespace is dropped at the document
3424 /// start and in an element that cannot hold text.
3425 pub fn drops_whitespace_here(&self) -> bool {
3426 match self.node.get_type() {
3427 Some(NodeType::DocumentNode) => true,
3428 Some(NodeType::ElementNode) => !can_contain(&self.node, "#PCDATA"),
3429 _ => false,
3430 }
3431 }
3432
3433 pub fn open_text(&mut self, text: &str, font: &Font) -> Result<Option<Node>> {
3434 let node_type = self.node.get_type();
3435 {
3436 // Ignore initial whitespace
3437 if (text.is_empty() || ONLY_SPACE_RE.is_match(text)) && self.drops_whitespace_here() {
3438 // ...EXCEPT whitespace that is verbatim CONTENT rather than ignorable
3439 // lexical padding: (a) TYPEWRITER-font spaces — fancyvrb/fvextra map
3440 // every verbatim space to a digested space box (`\FV@Space` →
3441 // `\FV@SpaceCatTen`, a braced ordinary space), so the line-LEADING
3442 // indentation of a code block arrives here at a not-yet-opened
3443 // paragraph, and dropping it deleted JSON-schema indentation and
3444 // collapsed space-only verbatim lines out of the height budget
3445 // (2605.00468 Prompt boxes: flush-left schemas, 15-33px frame
3446 // spills); (b) an EXPLICIT control space `\ ` (Box name="space"),
3447 // which TeX always typesets. Line-leading cat-10 SOURCE spaces never
3448 // reach this point (the mouth's state-N skip eats them), so this
3449 // does not resurrect source-formatting whitespace. Same-host Perl
3450 // cannot convert the fancyvrb constructs at all (raw
3451 // fvextra+breaklines exceeds 7 min on a 6-line file) — surpass-Perl
3452 // scope, not a parity break. Fall through: the normal insertion
3453 // machinery auto-opens the paragraph and keeps the spaces as text.
3454 // Not inside SVG, where Perl's rule stands (DIVERGENCES #47): pgf pads
3455 // every protocol literal with a `\space` (pgfsysprotocol.code.tex:33),
3456 // which `\pgfsys@invoke` hands on to digestion (Perl's constructor
3457 // absorbs it the same way, pgfsys-latexml.def.ltxml:832-836), and
3458 // under `\ttfamily` each one opened a whitespace-only
3459 // `svg:foreignObject` — 185 in 2605.01517, 2605.07323, 2605.27124;
3460 // Perl none. A node text's leading `\ ` is dropped there too, as Perl
3461 // drops it; the rendered node is the same. Nor where no auto-opened element reaches text (Perl's rule there
3462 // too): an `{algorithmic}` set in `\ttfamily` (WileyNJDv5.cls:6953 `\algrenewcommand\ALG@beginalgorithmic
3463 // {\ttfamily}`) put the space before its first `\item` straight into the `ltx:listing`, whose model is
3464 // `listingline*` (2608.15322, 2602.03247, 2607.19926: schema-invalid).
3465 // In the `ltx:picture`/`ltx:g` drawing model only after a box or inline content, where it is text as a
3466 // letter would be (`$x$\ label`, `\psframebox{…}\ \ 1`: math0406190, cs0608104, 0801.0882); at the start or
3467 // after a shape it is dropped, as in Perl (Document.pm:747-749): a `\ ` between `\psline`s opened an
3468 // `ltx:text` the next one nested a picture in, 403 deep (0905.4216 `\PutGrid`).
3469 let drawing = |node: &Node| {
3470 let qname = get_node_qname(node);
3471 qname == arena::pin("ltx:picture") || qname == arena::pin("ltx:g")
3472 };
3473 let explicit_space = node_type == Some(NodeType::ElementNode)
3474 && !text.is_empty()
3475 && can_contain_node_somehow(&self.node, "#PCDATA").is_some()
3476 && (font.family.as_deref() == Some("typewriter")
3477 || self.box_to_absorb.as_ref().is_some_and(|b| {
3478 b.get_property("name")
3479 .is_some_and(|n| n.to_string() == "space")
3480 }))
3481 && !arena::with(get_node_qname(&self.node), |qname| {
3482 qname.starts_with("svg:")
3483 })
3484 && (!drawing(&self.node)
3485 || self.node.get_last_element_child().is_some_and(|prev| {
3486 drawing(&prev)
3487 || can_contain_qsym(arena::pin(FONT_ELEMENT_NAME), get_node_qname(&prev))
3488 }));
3489 if !explicit_space {
3490 if !text.is_empty()
3491 && self.node.get_attribute(ALIGNED_LINES_ATTRIBUTE).is_some()
3492 && let Some(mut piece) = self.node.get_last_element_child()
3493 && piece.get_attribute(SPACE_AFTER_ATTRIBUTE).is_none()
3494 {
3495 piece.set_attribute(SPACE_AFTER_ATTRIBUTE, text)?;
3496 }
3497 return Ok(None);
3498 }
3499 // open_text_internal has its own whitespace-only gate (mirroring
3500 // Perl L1146: insert only if `\S` or direct #PCDATA) — hand it the
3501 // decision so the spaces survive the auto-open.
3502 self.verbatim_space_pending = true;
3503 }
3504 }
3505 if matches!(&font.family.as_deref(), Some("nullfont")) {
3506 return Ok(None);
3507 };
3508 Debug!(
3509 "document",
3510 "open_text",
3511 s!(
3512 "Insert text {:?} at {:?}",
3513 text,
3514 self.document.node_to_string(&self.node)
3515 )
3516 );
3517
3518 // Get the desired font attributes, particularly the desired element
3519 // (usually ltx:text, but let Font override, eg for \emph)
3520 let declared_font = self.get_node_font(&self.node);
3521 let pending_declaration = font.relative_to(declared_font);
3522 let elementname = match pending_declaration.get("element") {
3523 Some((k, _v)) => k,
3524 None => FONT_ELEMENT_NAME,
3525 };
3526 let element_sym = arena::pin(elementname);
3527 // If not at document begin. And not appending text in same font.
3528 //
3529 // Defense-in-depth (issue #217): a current TextNode should always have a
3530 // parent element, so this used to be `self.node.get_parent().unwrap()`.
3531 // Match the `None` instead of unwrapping — if the current node were ever a
3532 // detached text node, skip this un-anchorable insert rather than panic.
3533 // (The macOS corruption that could produce such a node was root-caused
3534 // and fixed in open_text_internal's text-merge detection.)
3535 let text_same_font = if node_type == Some(NodeType::TextNode) {
3536 match self.node.get_parent() {
3537 Some(parent) => font.distance(self.get_node_font(&parent)) == 0,
3538 None => return Ok(None),
3539 }
3540 } else {
3541 false
3542 };
3543 if node_type != Some(NodeType::DocumentNode) && !text_same_font {
3544 // then we'll need to do some open/close to get fonts matched.
3545 let node = self.close_text_internal()?; // Close text node, if any.
3546 let mut bestdiff = 99;
3547 let rc_node = Rc::new(node);
3548 let mut closeto: Rc<Node> = Rc::clone(&rc_node);
3549 let mut n: Rc<Node> = Rc::clone(&rc_node);
3550 while n.get_type() != Some(NodeType::DocumentNode) {
3551 let node_font = self.get_node_font(&n);
3552 let d = font.distance(node_font);
3553 if d < bestdiff {
3554 bestdiff = d;
3555 closeto = n.clone();
3556 if d == 0 {
3557 break;
3558 }
3559 }
3560 // Stop if not a font element, or if marked _noautoclose, or if
3561 // this is an explicit (non-fontswitch) text wrapper. A constructor-
3562 // opened `<ltx:text class='...'>` (e.g. `\uline{...}`) MUST NOT be
3563 // closed-out-of by a font-distance heuristic just because the parent
3564 // happens to score better — that produces an empty wrapper and
3565 // siblings the inner content (driver: 2402.16319 `\uline{\textbf{2}}`
3566 // inside `\sc` tabular). Only auto-opened fontswitch wrappers are
3567 // safe to walk past.
3568 if get_node_qname(&n) != element_sym
3569 || n.has_attribute("_noautoclose")
3570 || !n.has_attribute("_fontswitch")
3571 {
3572 break;
3573 }
3574 match n.get_parent() {
3575 Some(p) => n = Rc::new(p),
3576 None => break,
3577 }
3578 }
3579
3580 // Move to best starting point for this text.
3581 if *closeto != *rc_node {
3582 self.close_to_node(&closeto, false)?;
3583 }
3584 if bestdiff > 0 {
3585 // Open if needed.
3586 self.open_element(
3587 elementname,
3588 Some(string_map!("_fontswitch" => "true", "_autoopened" => "true")),
3589 Some(font),
3590 )?;
3591 }
3592 }
3593
3594 // Finally, insert the darned text. Before a run in another encoding or family, the open text node's
3595 // ligatures are applied under its own runs' font (`text_run_font`); the node stays open — closing it would
3596 // let libxml merge the next text node into it, out of reach of the ligatures. Each run's ligatures reach only
3597 // that run, from its start in the node: TeX ligates only characters of one font, and a later run's (LMC's
3598 // `”о` → ө) took the closing quote of an earlier one (`a''{\mnr o}`, KNOWN_PERL_ERRORS #438; witness
3599 // montex/montex).
3600 let previous = self.node.clone();
3601 let ligated = self.ligated_text.take();
3602 let ligated_len = |node: &Node| match &ligated {
3603 Some((ligated_node, len)) if ligated_node == node => *len,
3604 _ => 0,
3605 };
3606 let mut run_start = ligated_len(&previous);
3607 if previous.get_type() == Some(NodeType::TextNode)
3608 && let Some((run_node, run_font, start)) = self.text_run_font.take()
3609 && run_node == previous
3610 {
3611 if run_font.get_encoding() != font.get_encoding()
3612 || run_font.get_family() != font.get_family()
3613 {
3614 self.apply_text_ligatures(&run_font, start)?;
3615 run_start = self.node.get_content().len();
3616 } else {
3617 run_start = start;
3618 }
3619 }
3620 let outnode = self.open_text_internal(text)?;
3621 if outnode.get_type() == Some(NodeType::TextNode) {
3622 // A closed text node the insertion re-entered (`swap_comment_text_if_needed` sets the node back on it) was
3623 // ligated up to where `close_text_internal` left it; a text sibling libxml merged the insertion into
3624 // (`open_text_internal`) holds this run at its end.
3625 let start = if outnode == previous {
3626 run_start
3627 } else {
3628 match &ligated {
3629 Some((ligated_node, len)) if *ligated_node == outnode => *len,
3630 _ => outnode
3631 .as_readonly()
3632 .with_content(str::len)
3633 .saturating_sub(text.len()),
3634 }
3635 };
3636 self.text_run_font = Some((outnode.clone(), font.clone(), start));
3637 }
3638 self.record_constructed_node(&outnode);
3639 Ok(Some(outnode))
3640 }
3641
3642 /// The text ligatures (`TEXT_LIGATURES`) whose font test accepts `font`, applied to the open text node from byte
3643 /// `start`, where the run set in `font` begins.
3644 fn apply_text_ligatures(&mut self, font: &Font, start: usize) -> Result<()> {
3645 // Characters set one per box form no ligature: a listing's code (listings' fixed columns, `_noligatures` on its
3646 // lines and inline listings, listings_sty.rs).
3647 let mut ancestor = self.node.get_parent();
3648 while let Some(element) = ancestor {
3649 if element.has_attribute("_noligatures") {
3650 return Ok(());
3651 }
3652 ancestor = element.get_parent();
3653 }
3654 let whole = self.node.get_content();
3655 // A start no longer in the node (its content rewritten before the run) falls back to the whole node.
3656 let start = if whole.is_char_boundary(start) {
3657 start
3658 } else {
3659 0
3660 };
3661 let mut head = whole;
3662 let ocontent = head.split_off(start);
3663 let mut content = Cow::Borrowed(&ocontent);
3664 let mut apply = |font_test: Option<&FontTestClosure>, code: &LigatureClosure| -> Result<()> {
3665 if let Some(font_test) = font_test
3666 && !font_test(font)?
3667 {
3668 return Ok(()); // if the font test fails, skip the ligature
3669 }
3670 content = Cow::Owned(code(&content));
3671 Ok(())
3672 };
3673 if ligature::script_ligatures() {
3674 // (a script's `fontTest` may assign values: the closures are taken out of the state first, Perl
3675 // Document.pm:1225-1228; rhai-bindings/fonttest_assigns_a_value.tex)
3676 let ligatures = state::with_value("TEXT_LIGATURES", |value_opt| match value_opt {
3677 Some(Stored::VecDequeStored(ligatures)) => ligatures
3678 .iter()
3679 .filter_map(|stored| match stored {
3680 Stored::Ligature(ligature) => {
3681 Some((ligature.font_test.clone(), ligature.code.clone()?))
3682 },
3683 _ => None,
3684 })
3685 .collect(),
3686 _ => Vec::new(),
3687 });
3688 for (font_test, code) in &ligatures {
3689 apply(font_test.as_ref(), code)?;
3690 }
3691 } else {
3692 state::with_value("TEXT_LIGATURES", |value_opt| -> Result<()> {
3693 if let Some(Stored::VecDequeStored(ligatures)) = value_opt {
3694 for stored in ligatures {
3695 if let Stored::Ligature(ligature) = stored
3696 && let Some(code) = &ligature.code
3697 {
3698 apply(ligature.font_test.as_ref(), code)?;
3699 }
3700 }
3701 }
3702 Ok(())
3703 })?;
3704 }
3705 if *content != ocontent {
3706 self.node.set_content(&format!("{head}{content}"))?;
3707 }
3708 Ok(())
3709 }
3710
3711 pub fn close_text_internal(&mut self) -> Result<Node> {
3712 if self.node.get_type() == Some(NodeType::TextNode) {
3713 // Current node is text? A detached one (a rename's reinsert, a rescue moving away from a dead point) has
3714 // nothing to close into.
3715 let Some(parent) = self.node.get_parent() else {
3716 return Ok(self.node.clone());
3717 };
3718 // The font its runs were inserted with (the last run's), else its parent's, as Perl
3719 // (Document.pm `closeText_internal`).
3720 // Only this node's run entry: a text node opened and closed while another is open (for example a rename's
3721 // reinsert) leaves the outer node's in place.
3722 let (font, start) = match self.text_run_font.take_if(|(node, ..)| *node == self.node) {
3723 Some((_, font, start)) => (font, start),
3724 _ => (self.get_node_font(&parent).clone(), 0),
3725 };
3726 self.apply_text_ligatures(&font, start)?;
3727 self.ligated_text = Some((
3728 self.node.clone(),
3729 self.node.as_readonly().with_content(str::len),
3730 ));
3731 self.node = parent.clone(); // Effectively closed (->setNode, but don't recurse)
3732 Ok(parent)
3733 } else {
3734 Ok(self.node.clone())
3735 }
3736 }
3737
3738 /// Close `node`, and any current nodes below it.
3739 /// No checking! Use this when you've already verified that `node` can be closed.
3740 /// and, of course, `node` must be current or some ancestor of it!!!
3741 pub fn close_node_internal(&mut self, node: &Node) -> Result<()> {
3742 let closeto = match node.get_parent() {
3743 Some(p) => p,
3744 None => {
3745 // Node has been detached — nothing to close up to.
3746 return Ok(());
3747 },
3748 };
3749 let mut n = self.close_text_internal()?; // Close any open text node.
3750 while n.get_type() == Some(NodeType::ElementNode) {
3751 self.close_element_at(&mut n)?;
3752 self.auto_collapse_children(&mut n)?;
3753 let parent = n.get_parent();
3754 if is_theorem_to_dissolve(&n) {
3755 self.dissolve_theorem_in_abstract(&n)?;
3756 }
3757 if *node == n {
3758 break;
3759 }
3760 match parent {
3761 Some(parent) => {
3762 n = parent;
3763 },
3764 None => {
3765 // Node was detached during close/collapse — bail out safely.
3766 break;
3767 },
3768 }
3769 }
3770 self.set_node(&closeto);
3771 Ok(())
3772 }
3773
3774 /// Avoid redundant nesting of font switching elements:
3775 /// If we're closing a node that can take font switches and it contains
3776 /// a single FONT_ELEMENT_NAME node; pull it up.
3777 fn auto_collapse_children(&mut self, node: &mut Node) -> Result<()> {
3778 let qname = get_node_qname(node);
3779 if qname != pin!("ltx:_Capture_") {
3780 let mut c = node.get_child_nodes();
3781 // with single child, AND, $node can have all the attributes that the child has (but at least
3782 // "font") BUT, it isn"t being forced somehow
3783 if c.len() == 1
3784 && (get_node_qname(&c[0]) == pin!("ltx:text"))
3785 && model::can_have_attribute(qname, pin!("font"))
3786 && c[0]
3787 .get_attributes()
3788 .keys()
3789 .filter(|x| !x.starts_with('_'))
3790 .all(|v| {
3791 model::can_have_attribute(qname, arena::pin(v))
3792 && !(NON_MERGEABLE_ATTRIBUTES.contains(v.as_str()))
3793 })
3794 && !c[0].has_attribute("_force_font")
3795 {
3796 let c_first = c.pop().unwrap();
3797 let c_first_font = self.get_node_font(&c_first).clone();
3798 self.set_node_font(node, &c_first_font)?;
3799 for mut gc in c_first.get_child_nodes().into_iter() {
3800 gc.unlink();
3801 node.add_child(&mut gc)?;
3802 }
3803 // Re-record ids once, after ALL grandchildren are moved. Calling this
3804 // per-grandchild inside the loop re-scanned the whole growing `node`
3805 // subtree each iteration — O(G²) `descendant-or-self::*[@xml:id]` XPath
3806 // scans per merge (115k scans / ~50% of build wall on a PiCTeX paper).
3807 // record_id_with_node is idempotent for already-correct nodes and the
3808 // final set/document-order is identical, so one post-loop call is
3809 // output-equivalent. See PERFORMANCE.md.
3810 self.record_node_ids(node)?;
3811 // Merge the attributes from the child onto $node
3812 self.merge_attributes(&c_first, node, None)?;
3813 // a TeX box's element merged up (an `\mbox` alone in its paragraph): all `node` holds is that box's material
3814 // (OXIDIZED_DESIGN #715; merge_attributes skips bookkeeping)
3815 if c_first.has_attribute(FIELD_BOX_ATTRIBUTE) {
3816 let _ = node.set_attribute(FIELD_BOX_ATTRIBUTE, "true");
3817 }
3818 self.remove_node(c_first);
3819 }
3820 }
3821 Ok(())
3822 }
3823
3824 pub fn merge_attributes(
3825 &mut self,
3826 from: &Node,
3827 to: &mut Node,
3828 force: Option<&HashSet<&'static str>>,
3829 ) -> Result<()> {
3830 // Key order, so the attributes merged onto `to` land deterministically.
3831 let mut attrs: Vec<(String, String)> = from.get_attributes().into_iter().collect();
3832 attrs.sort();
3833 for (key, val) in attrs.iter() {
3834 // Skip internal attributes
3835 if key.starts_with('_') {
3836 continue;
3837 }
3838 // Normalize key: get_attributes() returns "id" for xml:id attributes.
3839 // Check both "xml:id" and bare "id" with XML namespace for the special case.
3840 let is_xml_id = key.as_str() == "xml:id"
3841 || (key.as_str() == "id"
3842 && from
3843 .get_attribute_ns("id", "http://www.w3.org/XML/1998/namespace")
3844 .is_some());
3845 let effective_key = if is_xml_id { "xml:id" } else { key.as_str() };
3846 let is_forced = force.is_some_and(|f| f.contains(effective_key));
3847 // Special case attributes
3848 if is_xml_id {
3849 // Use the replacement id. record_id_with_node returns a
3850 // deduplicated id when a DIFFERENT node already claims the
3851 // same one; must use the return value, not the original `val`.
3852 let to_has_id = to.has_attribute("xml:id")
3853 || to
3854 .get_attribute_ns("id", "http://www.w3.org/XML/1998/namespace")
3855 .is_some();
3856 if !to_has_id || is_forced {
3857 self.unrecord_id(val);
3858 let deduped = self.record_id_with_node(val, to);
3859 to.set_attribute("xml:id", &deduped)?;
3860 }
3861 } else if MERGE_ATTRIBUTE_SPACEJOIN.contains(key.as_str()) {
3862 self.add_ss_values(to, key, val)?;
3863 } else if MERGE_ATTRIBUTE_SEMICOLONJOIN.contains(key.as_str()) {
3864 if let Some(existing) = to.get_attribute(key) {
3865 let merged = format!("{existing}; {val}");
3866 to.set_attribute(key, &merged)?;
3867 } else {
3868 to.set_attribute(key, val)?;
3869 }
3870 } else if MERGE_ATTRIBUTE_SUMLENGTH.contains(key.as_str()) {
3871 if let Some(val2) = to.get_attribute(key) {
3872 // Parse and sum pt values
3873 let v1 = val.trim_end_matches("pt").parse::<f64>().unwrap_or(0.0);
3874 let v2 = val2.trim_end_matches("pt").parse::<f64>().unwrap_or(0.0);
3875 to.set_attribute(key, &format!("{}pt", v1 + v2))?;
3876 } else {
3877 to.set_attribute(key, val)?;
3878 }
3879 } else if !to.has_attribute(key) || is_forced {
3880 // Else if attribute not present on $to, or if we specifically override it, just copy
3881 let reindex = key == "idref";
3882 if reindex {
3883 self.unindex_idref(to);
3884 }
3885 to.set_attribute(key, val)?;
3886 if reindex {
3887 self.index_idref(to);
3888 }
3889 }
3890 }
3891 Ok(())
3892 }
3893
3894 fn open_text_internal(&mut self, text: &str) -> Result<Node> {
3895 // Consume the verbatim-space handoff (see `verbatim_space_pending`);
3896 // taking it here keeps the flag from leaking into unrelated calls.
3897 let force_whitespace = std::mem::take(&mut self.verbatim_space_pending);
3898 if text.is_empty() {
3899 return Ok(self.node.clone());
3900 }
3901 // Sibling guard to open_math_text_internal: libxml's append_text uses
3902 // CString and panics on embedded NULs (forbidden in XML text per spec).
3903 // Strip them — and the rest of the XML-invalid control class — up-front
3904 // so all downstream append_text calls are safe and the output stays
3905 // well-formed (shared policy with `set_attribute`, see `xml_sanitize`).
3906 if let Cow::Owned(cleaned) = xml_sanitize(text) {
3907 self.verbatim_space_pending = force_whitespace; // re-arm for the recursion
3908 return self.open_text_internal(&cleaned);
3909 }
3910 if self.node.get_type() == Some(NodeType::TextNode) {
3911 // current node already is a text node.
3912 Debug!(
3913 "document",
3914 "open_text_internal",
3915 s!(
3916 "Appending text {:?} to {:?}",
3917 text,
3918 self.document.node_to_string(&self.node)
3919 )
3920 );
3921
3922 let parent = self.node.get_parent().unwrap();
3923 if self.box_to_absorb.is_some() && parent.has_attribute("_autoopened") {
3924 // Perl L1136-1137: appendNodeBox to accumulate boxes for autoopened elements
3925 let bta = self.box_to_absorb.clone().unwrap();
3926 self.append_node_box(&parent, &bta);
3927 }
3928 // K10: under the byte mouth every character reaches the document as
3929 // single-byte boxes (tex.web §1034: one char node per byte; pdfTeX's
3930 // subfont encoding turns the run back into a glyph). The text node is
3931 // that run: reassemble it here, once the new byte is on — the font
3932 // decoding step of a byte-mouth run.
3933 if state::lookup_bool("PDFTEX_BYTE_MOUTH")
3934 && text.chars().any(|c| ('\u{80}'..='\u{FF}').contains(&c))
3935 {
3936 // Only the pending tail (an incomplete sequence's bytes) plus the new
3937 // piece is decoded — re-decoding the whole node per byte was O(n²)
3938 // and, given a runaway feeding one node, a 2^32-byte String
3939 // (chinesechess, sweep 70).
3940 let content = self.node.get_content();
3941 let split = crate::mouth::byte_mouth_pending_tail(&content);
3942 let tail = s!("{}{}", &content[split..], text);
3943 let decoded = crate::mouth::decode_byte_mouth_runs(&tail);
3944 if split == content.len() {
3945 self.node.append_text(&decoded)?;
3946 } else {
3947 self
3948 .node
3949 .set_content(&s!("{}{}", &content[..split], decoded))?;
3950 }
3951 } else {
3952 self.node.append_text(text)?;
3953 }
3954 }
3955 // Perl lines 1139-1144: if lastChild is a comment node and its previous sibling is
3956 // a text node, swap them to avoid splitting text runs, then recurse.
3957 // This avoids libxml text-node merging which would bypass ligature processing.
3958 else if self.swap_comment_text_if_needed(text)? {
3959 // Handled by recursive call
3960 } else if HAS_NONSPACE_RE.is_match(text)
3961 || force_whitespace
3962 || can_contain(&self.node, "#PCDATA")
3963 {
3964 // or text allowed here
3965 let mut point = self.find_insertion_point("#PCDATA", None)?;
3966 // Perl L1149-1150: appendNodeBox for autoopened insertion points
3967 if self.box_to_absorb.is_some() && point.has_attribute("_autoopened") {
3968 let bta = self.box_to_absorb.clone().unwrap();
3969 self.append_node_box(&point, &bta);
3970 }
3971 Debug!(
3972 "document",
3973 "open_text_internal",
3974 s!(
3975 "Inserting text node for {:?} into {:?}",
3976 text,
3977 self.document.node_to_string(&point)
3978 )
3979 );
3980 let mut node = Node::new_text(text, &self.document)?;
3981 point.add_child(&mut node)?;
3982 // libxml2 MERGES adjacent text nodes: when `point`'s last child was
3983 // already a text node, `xmlAddChild` appends our content to it and
3984 // FREES the just-created `node`, leaving its wrapper dangling.
3985 //
3986 // The previous detection — `node.get_type().is_none()` — is a
3987 // use-after-free: it reads the freed node's `type` field. That is
3988 // *benign on glibc* (the freed slot still reads as the old/None type,
3989 // so the merge is detected), but **unsound on macOS libmalloc**, which
3990 // recycles/scribbles the freed slot so `get_type()` returns garbage
3991 // (EntityNode/ElementDecl/…) and the merge goes UNDETECTED — installing
3992 // a freed node as `self.node` and corrupting the current insertion
3993 // point (issue #217; the macOS-only worker-thread crashes).
3994 //
3995 // Detect the merge WITHOUT dereferencing the possibly-freed node:
3996 // after `add_child` our text is `point`'s last child in both cases
3997 // (the appended `node`, or the sibling it merged into). `Node`'s
3998 // `PartialEq` compares the stored `xmlNodePtr` values (no deref), so
3999 // this pointer-identity check is allocator-independent and UAF-safe.
4000 if point.get_last_child().as_ref() == Some(&node) {
4001 // `node` was appended (not merged) — it is live and current.
4002 self.set_node(&node);
4003 } else if let Some(merged) = point.get_last_child()
4004 && merged.get_type() == Some(NodeType::TextNode)
4005 {
4006 // `node` was merged into a text sibling and freed: that sibling holds the text now and is the current
4007 // node, as the appended node would be (Perl `setNode($node)`, Document.pm openText_internal), so its
4008 // close ligates what was inserted. Leaving the parent current kept the rest of the run out of every
4009 // ligature: text after a formula `cleanup_math` turns into spaces (`500$\,$hPa 1989--2008`) merges into
4010 // the spaces' text node (witnesses nucl-ex0511052, 2208.08472; guard
4011 // `perfect_kernel_batch78a::text_after_a_space_only_formula_is_ligatured`).
4012 self.set_node(&merged);
4013 } else {
4014 self.set_node(&point);
4015 }
4016 }
4017 Ok(self.node.clone())
4018 }
4019
4020 /// Perl lines 1139-1144: Avoid splitting text runs across comments.
4021 /// If the current node's lastChild is a comment and the previous sibling is a text node,
4022 /// swap them so the text node is last, set it as current, and recurse to append new text.
4023 /// Returns true if the swap+append was performed, false otherwise.
4024 fn swap_comment_text_if_needed(&mut self, text: &str) -> Result<bool> {
4025 if self.node.get_type() != Some(NodeType::ElementNode) {
4026 return Ok(false);
4027 }
4028 if let Some(last_child) = self.node.get_last_child()
4029 && last_child.get_type() == Some(NodeType::CommentNode)
4030 && let Some(mut prev_text) = last_child.get_prev_sibling()
4031 && prev_text.get_type() == Some(NodeType::TextNode)
4032 {
4033 // Swap: move text node after comment node
4034 let mut comment_node = last_child;
4035 comment_node.add_next_sibling(&mut prev_text)?;
4036 // Set current node to the moved text node and recurse. Use
4037 // pointer-identity, not the `prev_text` handle directly:
4038 // `add_next_sibling` of a text node can MERGE it into an adjacent
4039 // text sibling and FREE it (the same libxml2 hazard fixed in
4040 // open_text_internal — benign on glibc, a use-after-free on macOS
4041 // libmalloc, issue #217). The moved/merged text is `comment_node`'s
4042 // next sibling either way; if that is still `prev_text` it survived,
4043 // otherwise `prev_text` was freed — fall back to the live sibling.
4044 match comment_node.get_next_sibling() {
4045 Some(moved) => self.set_node(&moved),
4046 None => self.set_node(&prev_text),
4047 }
4048 self.open_text_internal(text)?;
4049 return Ok(true);
4050 }
4051 Ok(false)
4052 }
4053
4054 /// Perl `appendNodeBox` (Core/Document.pm:1685-1700): record `thisbox` as
4055 /// (part of) the box that created `node`, then do the same for each
4056 /// auto-opened ancestor in turn — an auto-opened node's box is the record of
4057 /// everything opened or written inside it, which is what an auto-opened
4058 /// `ltx:picture` or `svg:foreignObject` measures when it closes. Nothing is
4059 /// added where the box is already the node's, or the last of its
4060 /// `unlist` (Perl `eq`).
4061 ///
4062 /// Perl combines with `List($origbox, $box, mode => $origbox->getProperty
4063 /// ('mode'))` (List.pm:31-55): in horizontal mode one flat list, the boxes
4064 /// of any horizontal list among the two taken in its place; in any other
4065 /// mode a nested pair. A flat list this makes is the node's own
4066 /// (`node_box` property): while no one else holds it, the next box is pushed
4067 /// onto it in place (Perl builds a new list each time, O(n²) in a
4068 /// paragraph); while it is shared, a new one is built, as Perl does.
4069 /// OXIDIZED_DESIGN_DIVERGENCES #319.
4070 fn append_node_box(&mut self, node: &Node, thisbox: &Digested) {
4071 let mut node = node.clone();
4072 loop {
4073 let key = node.to_hashable();
4074 // Whether the node's box is held only here, read before our own clone.
4075 let (orig, owned) = match self.node_boxes.get(&key) {
4076 None => {
4077 self.node_boxes.insert(key, thisbox.clone());
4078 (None, false)
4079 },
4080 Some(orig) => {
4081 let owned = orig.strong_count() == 1;
4082 (Some(orig.clone()), owned)
4083 },
4084 };
4085 if let Some(orig) = orig {
4086 let already_there = same_box(thisbox, &orig)
4087 || unlist_last(&orig).is_some_and(|last| same_box(thisbox, &last));
4088 if !already_there {
4089 let mode = box_mode(&orig);
4090 if flattens(mode) {
4091 if !(owned && push_onto_node_box(&orig, thisbox)) {
4092 let mut boxes = flatten_horizontal(&orig);
4093 boxes.extend(flatten_horizontal(thisbox));
4094 self.node_boxes.insert(key, node_box_list(boxes, mode));
4095 }
4096 } else {
4097 let list = node_box_list(vec![orig, thisbox.clone()], mode);
4098 self.node_boxes.insert(key, list);
4099 }
4100 }
4101 }
4102 match node.get_parent() {
4103 Some(parent) if is_autoopened_element(&parent) => node = parent,
4104 _ => break,
4105 }
4106 }
4107 }
4108
4109 /// Perl `removeNodeBox` (Core/Document.pm:1704-1723): `thisbox`, the box of
4110 /// a node being removed from `node`, leaves the box of `node` and of each
4111 /// auto-opened ancestor in turn — the whole box if it is `thisbox`, else
4112 /// `thisbox` is dropped from its `unlist` (one level: a box nested deeper
4113 /// is not seen, as Perl notes).
4114 fn remove_node_box(&mut self, node: &Node, thisbox: &Digested) {
4115 let mut node = node.clone();
4116 loop {
4117 let key = node.to_hashable();
4118 if let Some(orig) = self.node_boxes.get(&key).cloned() {
4119 if same_box(&orig, thisbox) {
4120 self.node_boxes.remove(&key);
4121 } else {
4122 let members = unlist(&orig);
4123 if members.iter().any(|b| same_box(b, thisbox)) {
4124 let mode = box_mode(&orig);
4125 let rest: Vec<Digested> = members
4126 .into_iter()
4127 .filter(|b| !same_box(b, thisbox))
4128 .collect();
4129 // Perl `List(@rest, mode => $mode)`: one box of that mode is itself.
4130 let list = if rest.len() == 1 && mode.is_none_or(|m| box_mode(&rest[0]) == Some(m)) {
4131 rest.into_iter().next().unwrap()
4132 } else {
4133 node_box_list(rest, mode)
4134 };
4135 self.node_boxes.insert(key, list);
4136 }
4137 }
4138 }
4139 match node.get_parent() {
4140 Some(parent) if is_autoopened_element(&parent) => node = parent,
4141 _ => break,
4142 }
4143 }
4144 }
4145
4146 // Question: Why do I have math ligatures handled within openMathText_internal,
4147 // but text ligatures handled within closeText_internal ???
4148
4149 /// Needed externally only for the binding generation
4150 fn open_math_text_internal(&mut self, text: &str) -> Result<Node> {
4151 // And if there's already text???
4152 let mut node = self.node.clone();
4153 // my $font = $self->getNodeFont($node);
4154 // libxml's append_text uses CString and panics on embedded NULs. NUL is
4155 // forbidden in XML text per spec anyway, so strip it (and the rest of the
4156 // XML-invalid control class — shared policy with `set_attribute`, see
4157 // `xml_sanitize`). Witness: astro-ph0202376 (a paper that produces math
4158 // tokens with \char0 / NUL bytes embedded in their content). Matches
4159 // Perl's libxml behavior which silently drops NULs in text content.
4160 node.append_text(&xml_sanitize(text))?;
4161 // print STDERR "Trying Math Ligatures at \"$string\"\n";
4162 if !state::get_nomathparse_flag() {
4163 self.apply_math_ligatures(&mut node)?;
4164 }
4165 Ok(node)
4166 }
4167
4168 // New strategy (but inefficient): apply ligatures until one succeeds,
4169 // then remove it, and repeat until ALL (remaining) fail.
4170 fn apply_math_ligatures(&mut self, node: &mut Node) -> Result<()> {
4171 // (the matchers are taken out of the state first: a matcher may assign values or define ligatures, Perl
4172 // Document.pm:1174 `lookupValue`; rhai-bindings/math_ligature_matcher_defines_one.tex)
4173 let mut matchers = state::with_value("MATH_LIGATURES", |value| match value {
4174 Some(Stored::VecDequeStored(ligatures)) => ligatures
4175 .iter()
4176 .filter_map(|stored| match stored {
4177 Stored::Ligature(ligature) => ligature.matcher.clone(),
4178 _ => None,
4179 })
4180 .collect(),
4181 _ => Vec::new(),
4182 });
4183 // Apply the first that matches, drop it, and repeat until all the remaining ones fail (Perl Document.pm:1176-1183).
4184 while let Some(at) = self.first_math_ligature_match(node, &matchers)? {
4185 matchers.remove(at);
4186 }
4187 Ok(())
4188 }
4189
4190 fn first_math_ligature_match(
4191 &mut self,
4192 node: &mut Node,
4193 matchers: &[LigatureMatcher],
4194 ) -> Result<Option<usize>> {
4195 for (at, matcher) in matchers.iter().enumerate() {
4196 if self.apply_math_ligature(node, matcher)? {
4197 return Ok(Some(at));
4198 }
4199 }
4200 Ok(None)
4201 }
4202
4203 /// Apply ligature operation to `node`, presumed the last insertion into it's parent(?)
4204 fn apply_math_ligature(&mut self, node: &mut Node, matcher: &LigatureMatcher) -> Result<bool> {
4205 if let Some((nmatched, newstring, attr)) = matcher(self, node)? {
4206 let mut boxes = VecDeque::new();
4207 boxes.push_front(self.get_node_box(node).unwrap());
4208 node.get_first_child().unwrap().set_content(&newstring)?;
4209 // `nmatched - 1` (usize) underflows to usize::MAX if a matcher returns a
4210 // zero-length match, spinning `get_prev_sibling().unwrap()` until it
4211 // panics. Saturate: a 0/1-length match removes no prior siblings.
4212 // Perl Document.pm:1194-1199: a comment the matcher stepped over (and counted) stays.
4213 // Guard: `perfect_kernel_batch56::letters_ligature_joins_across_a_comment`.
4214 let mut prev = node.clone();
4215 for _idx in 0..nmatched.saturating_sub(1) {
4216 // The matcher can OVER-report nmatched past the actual sibling count
4217 // (the mirror of the zero-length underflow above) — stop instead of
4218 // panicking on the unwrap (PR_READINESS must-fix 5).
4219 let Some(remove) = prev.get_prev_sibling() else {
4220 Error!(
4221 "unexpected",
4222 "ligature",
4223 "Math ligature matched more siblings than exist; truncating the merge"
4224 );
4225 break;
4226 };
4227 if let Some(b) = self.get_node_box(&remove) {
4228 boxes.push_front(b);
4229 }
4230 // The merged token's box is taken out of no enclosing box: it lives on
4231 // in `node`'s composite box below. Perl's `removeNode` here
4232 // (Document.pm:1199) runs `removeNodeBox` on the token's parent, which
4233 // takes the `2` and `.` of a `2.414` out of an aligned cell's box
4234 // list, whose reversion is the cell Math's `tex` (Perl:
4235 // `tex="\displaystyle=414\times 0^{-3}"`; KNOWN_PERL_ERRORS #272).
4236 // Witnesses 2605.02288, 2605.00812; guard
4237 // `node_box_append::math_ligatures_keep_their_boxes`.
4238 if remove.get_type() == Some(NodeType::CommentNode) {
4239 prev = remove;
4240 } else {
4241 self.remove_node_keeping_box(remove);
4242 }
4243 }
4244 // This fragment replaces the node's box by the composite boxes it replaces
4245 // HOWEVER, this gets things out of sync because parent lists of boxes still
4246 // have the old ones. Unless we could recursively replace all of them, we'd better skip
4247 // it(??)
4248 if boxes.len() > 1 {
4249 // TODO: Cloning boxes is BAD. What is a better model?
4250 let mut list = List::new(boxes.into_iter().collect::<Vec<_>>());
4251 list.mode = Some(TexMode::Math);
4252 self.set_node_box(node, list.into());
4253 }
4254 for (key, value_opt) in attr.sorted_each() {
4255 if let Some(value) = value_opt {
4256 node.set_attribute(key, value)?;
4257 } else {
4258 node.remove_attribute(key)?;
4259 }
4260 }
4261 Ok(true)
4262 } else {
4263 Ok(false)
4264 }
4265 }
4266
4267 /// Note that a box has been absorbed creating `node`;
4268 /// This does book keeping so that we can return the sequence of nodes
4269 /// that were added by absorbing material.
4270 pub fn record_constructed_node(&mut self, node: &Node) {
4271 // if ((defined $LaTeXML::RECORDING_CONSTRUCTION) // If we're recording!
4272 let should_push = match self.constructed_nodes.last() {
4273 // and this node isn't already recorded
4274 None => true,
4275 Some(last_node) => last_node != node,
4276 };
4277 if should_push {
4278 self.constructed_nodes.push(node.clone());
4279 }
4280 }
4281
4282 pub fn filter_deletions(&self, nodes: Vec<Node>) -> Vec<Node> {
4283 // This test seems to successfully determine inclusion,
4284 // without requiring the (dangerous? & dubious?) unbindNode to be used.
4285 match self.document.get_root_element() {
4286 Some(root) => nodes
4287 .into_iter()
4288 .filter(|node| xml::is_descendant_or_self(node, &root))
4289 .collect(),
4290 _ => Vec::new(),
4291 }
4292 }
4293
4294 /// Given a list of nodes such as from ->absorb,
4295 /// filter out all the nodes that are children of other nodes in the list.
4296 pub fn filter_children(&self, mut nodes: Vec<Node>) -> Vec<Node> {
4297 if nodes.is_empty() {
4298 Vec::new()
4299 } else {
4300 let mut new = vec![nodes.remove(0)];
4301 for node in nodes {
4302 if new
4303 .iter()
4304 .all(|other| !xml::is_descendant_or_self(&node, other))
4305 {
4306 new.push(node)
4307 }
4308 }
4309 new
4310 }
4311 }
4312
4313 //**********************************************************************
4314 // Low level internal interface
4315
4316 /// Return a string indicating the path to the current insertion point in the document.
4317 /// if $levels is defined, show only that many levels
4318 pub fn get_insertion_context(&self, levels_opt: Option<usize>) -> Result<String> {
4319 let mut levels = match levels_opt {
4320 None => {
4321 // Default depth is based on verbosity
4322 if state::current_verbosity() <= 1 {
4323 Some(5)
4324 } else {
4325 None
4326 }
4327 },
4328 Some(t) => Some(t),
4329 };
4330 let mut node = self.node.clone();
4331 let node_type = node.get_type();
4332 if node_type != Some(NodeType::TextNode)
4333 && node_type != Some(NodeType::ElementNode)
4334 && node_type != Some(NodeType::DocumentNode)
4335 {
4336 let message = s!(
4337 "Insertion point is not an element, document or text: {:?}",
4338 self.document.node_to_string(&node)
4339 );
4340 Error!("internal", "context", message);
4341 return Ok(String::new());
4342 }
4343 // Build a context path like "<ltx:document><ltx:section><ltx:p>" by walking
4344 // ancestors and prepending each element's qname. Mirrors Perl's
4345 // `Stringify($node)` chain with a depth cap from `levels_opt`.
4346 //
4347 // Cap each qname at 80 chars. Pathological inputs (e.g. xy-pic
4348 // emitting unparsed `\fontdimen 17 \cmr10 at NNsp` strings that
4349 // become element names through a sequence of recovery errors)
4350 // can produce multi-MB qnames; walking 5+ ancestors and
4351 // `format!`-ing each yields a 3.25 GB allocation request that
4352 // OOM-kills the worker. Truncating preserves the diagnostic
4353 // signal ("first 80 chars + …") without the unbounded growth.
4354 // Witness papers: math0203082, math0402448 (R35.B, sandbox).
4355 const QNAME_CAP: usize = 80;
4356 let truncate_qname = |qname: &str| -> String {
4357 if qname.len() <= QNAME_CAP {
4358 qname.to_string()
4359 } else {
4360 let mut s: String = qname.chars().take(QNAME_CAP).collect();
4361 s.push('…');
4362 s
4363 }
4364 };
4365 let qn_for = |n: &Node| -> String {
4366 match n.get_type() {
4367 Some(NodeType::ElementNode) => {
4368 with_node_qname(n, |qname| format!("<{}>", truncate_qname(qname)))
4369 },
4370 Some(NodeType::TextNode) => "#text".to_string(),
4371 Some(NodeType::DocumentNode) => "#document".to_string(),
4372 _ => "?".to_string(),
4373 }
4374 };
4375 let mut path = qn_for(&node);
4376 while let Some(parent_node) = node.get_parent() {
4377 node = parent_node;
4378 if let Some(levels_val) = levels {
4379 levels = Some(levels_val - 1);
4380 if levels_val <= 1 {
4381 path = format!("...{path}");
4382 break;
4383 }
4384 }
4385 path = format!("{}{}", qn_for(&node), path);
4386 }
4387 Ok(path)
4388 }
4389
4390 /// Find the node where an element with qualified name `qname` can be inserted.
4391 /// This will move up the tree (closing auto-closable elements),
4392 /// or down (inserting auto-openable elements), as needed.
4393 pub fn find_insertion_point(
4394 &mut self,
4395 qname: &str,
4396 has_opened_opt: Option<SymStr>,
4397 ) -> Result<Node> {
4398 let qsym = arena::pin(qname);
4399 self.find_insertion_point_qsym(qsym, has_opened_opt)
4400 }
4401
4402 pub fn find_insertion_point_qsym(
4403 &mut self,
4404 qsym: SymStr,
4405 has_opened_opt: Option<SymStr>,
4406 ) -> Result<Node> {
4407 self.find_insertion_point_in(qsym, has_opened_opt, false)
4408 }
4409
4410 /// Sets the insertion point where TeX sets `qname` in place, inside its container: a wrap float in a box (a
4411 /// footnote, a `\parbox`, a cell; wrapfig.sty:104-107 `\ifinner`). These are [`Self::find_insertion_point`]'s routes,
4412 /// with the `ltx:inline-logical-block` bridge of a theorem (OXIDIZED_DESIGN_DIVERGENCES #689) open to it in a
4413 /// container that holds no Para.class (a note), so that a closing float marker (`^^`) then finds it held where it
4414 /// stands. Not in a frontmatter container (#689's exclusion): there the point stays and the marker floats it out
4415 /// (OXIDIZED_DESIGN_DIVERGENCES #1254).
4416 pub fn set_in_place(&mut self, qname: &str) -> Result<()> {
4417 if !outside_frontmatter_container(&self.node) {
4418 return Ok(());
4419 }
4420 let point = self.find_insertion_point_in(arena::pin(qname), None, true)?;
4421 self.set_node(&point);
4422 Ok(())
4423 }
4424
4425 /// [`Self::find_insertion_point_qsym`]; `in_place`: for [`Self::set_in_place`].
4426 fn find_insertion_point_in(
4427 &mut self,
4428 qsym: SymStr,
4429 has_opened_opt: Option<SymStr>,
4430 in_place: bool,
4431 ) -> Result<Node> {
4432 self.close_text_internal()?; // Close any current text node.
4433 let cur_qname = get_node_qname(&self.node);
4434 // If `qname` is allowed at the current point, we're done (a display unit at a quote's run-in block goes on to
4435 // close the quote, `holds_in_quote_block`).
4436 if can_contain_qsym(cur_qname, qsym) && holds_in_quote_block(&self.node, qsym) {
4437 return Ok(self.node.clone());
4438 // Else, if we can create an intermediate node that accepts $qname, we'll do
4439 // that.
4440 } else if let Some(inter) = can_contain_indirect(cur_qname, qsym)
4441 && (inter != qsym)
4442 && (inter != cur_qname)
4443 {
4444 // TODO: can we avoid the clone here? there is a mutability conflict...
4445 let node_font = self.get_node_font(&self.node).clone();
4446 // TODO: avoid this clone?
4447 let inter_string = arena::to_string(inter);
4448 self.open_element(
4449 &inter_string,
4450 Some(string_map!("_autoopened" => "true")),
4451 Some(&node_font),
4452 )?;
4453 // And retry insertion (should work now).
4454 return self.find_insertion_point_in(qsym, Some(inter), in_place);
4455 }
4456 if let Some(has_opened) = has_opened_opt {
4457 // out of options if already inside an auto-open chain
4458 let message: String =
4459 arena::with2(has_opened, cur_qname, |has_opened_str, cur_qname_str| {
4460 Ok::<String, Error>(format!(
4461 "failed auto-open through <{}> at inadmissible <{}>. Currently in {}",
4462 has_opened_str,
4463 cur_qname_str,
4464 self.get_insertion_context(None)?
4465 ))
4466 })?;
4467 Error!("malformed", arena::to_string(qsym), message);
4468 Ok(self.node.clone()) // But we'll do it anyway, unless Error => Fatal.
4469 } else {
4470 // Now we're getting more desparate...
4471 // Check if we can auto close some nodes, and _then_ insert the `qname`.
4472 let mut node = self.node.clone();
4473 let mut close_to = None;
4474 while (node.get_type() != Some(NodeType::DocumentNode)) && can_auto_close(&node) {
4475 let parent_opt = node.get_parent();
4476 let parent_name = match parent_opt {
4477 None => pin!(""),
4478 Some(ref p) => get_node_qname(p),
4479 };
4480 if sym_can_contain_somehow(parent_name, qsym).is_some()
4481 && parent_opt
4482 .as_ref()
4483 .is_none_or(|p| holds_in_quote_block(p, qsym))
4484 {
4485 close_to = Some(node);
4486 break;
4487 }
4488 // A sectioning unit nested in an unlabelled list item (a margin list's `\item[]`, which opens no inline
4489 // sectional block; an error below) is CLOSED by the next sectioning unit, which becomes its sibling inside the
4490 // item — latex.ltx's `\@startsection` ends the previous heading's scope but not the list (2201.06926; Perl
4491 // nests Y inside X with a second error). OD #189. Guard
4492 // `perfect_kernel_batch64::section_in_margin_list_keeps_bibliography`.
4493 if is_lenient_sectioning_unit(qsym)
4494 && is_lenient_sectioning_unit(get_node_qname(&node))
4495 && parent_name == pin!("ltx:item")
4496 {
4497 close_to = Some(node);
4498 break;
4499 }
4500 node = match parent_opt {
4501 Some(p) => p,
4502 None => break,
4503 };
4504 }
4505 if let Some(close_to_node) = close_to {
4506 self.close_node_internal(&close_to_node)?; // Close the auto closeable nodes.
4507 self.find_insertion_point_in(qsym, None, in_place) // Then retry, possibly w/auto open's
4508 } else if is_quote_closing_unit(qsym) && self.close_quotes_blocking(&[qsym])? {
4509 // A display sectioning unit in a `{quote}`, `{quotation}` or `{verse}` closed it (`close_quotes_blocking`).
4510 self.find_insertion_point_in(qsym, None, in_place)
4511 } else {
4512 // Cascading-rejection suppression (2026-05-01): when a math leaf
4513 // element (`<ltx:XMTok>`) tries to insert into a text-mode
4514 // container (`<ltx:p>`/`<ltx:text>`), it's almost always a
4515 // cascade from a previously-rejected math wrapper (XMApp /
4516 // XMDual) — Perl emits the wrapper's rejection error but
4517 // doesn't continue to log per-child cascade errors. Mirror
4518 // that to drop the redundant noise. The Δ=2 witnesses are
4519 // hep-th0101146 (`$$ ... \end{equation}` mismatch) and
4520 // nlin0211024 (`${\mbox M}^{...}$$` inside `\begin{center}`).
4521 // We still return self.node.clone() so the caller proceeds
4522 // (the XMTok still gets inserted illegally, but the schema
4523 // validator will reject the whole math construct on
4524 // serialization anyway — the noise was purely diagnostic).
4525 let qsym_str = arena::to_string(qsym);
4526 let cur_str = arena::to_string(cur_qname);
4527 let is_math_leaf = qsym_str == "ltx:XMTok" || qsym_str == "ltx:XMArg";
4528 // `ltx:emph` added 2026-05-01 after math0010241 triage:
4529 // 13 XMTok-in-emph + 1 (Building line) cascade noise drops
4530 // Rust from 33 → 19, exact parity with Perl=19.
4531 let is_text_container =
4532 cur_str == "ltx:p" || cur_str == "ltx:text" || cur_str == "ltx:emph";
4533 if is_math_leaf && is_text_container {
4534 // Cascading rejection — skip the error log (Perl-faithful).
4535 return Ok(self.node.clone());
4536 }
4537 // Sectioning-unit-in-frontmatter leniency (Perl-faithful). A
4538 // `\paragraph{Keywords.}` / `\paragraph{MSC.}` inside an `abstract`
4539 // (a common author idiom) produces `<ltx:paragraph>` inside
4540 // `<ltx:abstract>`. The RNG `abstract_model = Block.model` excludes
4541 // sectioning units, but Perl's builder inserts it WITHOUT erroring
4542 // (Perl 0 / Rust 2 on 2311.06870) — its output literally nests
4543 // `<ltx:paragraph inlist="toc">` in `<ltx:abstract>`. Mirror that
4544 // build-leniency for the narrow sectioning-into-frontmatter case so
4545 // we don't out-strict Perl. Same `return self.node` "insert anyway"
4546 // mechanism as the math-leaf cascade above.
4547 // A sectioning unit inside a list item or a float body is not lenient here: it opens an
4548 // `ltx:inline-sectional-block` (the bridges below; rulings 2026-10-06, 2026-10-09; OD #189).
4549 let is_sectioning_unit = is_lenient_sectioning_unit(qsym);
4550 // Container is either a frontmatter block (abstract/acknowledgements,
4551 // Block.model — no sectioning units) OR another sectioning unit that
4552 // can't hold it (a 2nd `\paragraph` nests inside the 1st when the
4553 // enclosing abstract can't auto-close to a section level). Perl's
4554 // builder produces exactly this nested `<ltx:paragraph><ltx:paragraph>`
4555 // shape inside `<ltx:abstract>` without erroring (2311.06870: Perl 0).
4556 let is_lenient_container = cur_str == "ltx:abstract"
4557 || cur_str == "ltx:acknowledgements"
4558 || cur_str == "ltx:paragraph"
4559 || cur_str == "ltx:subparagraph";
4560 if is_sectioning_unit && is_lenient_container {
4561 return Ok(self.node.clone());
4562 }
4563 // Auto-open bridges — ONE rule, tex.web has none: when a child cannot
4564 // go here, cannot be reached by any autoOpen path of the model
4565 // (Perl Document.pm:974-1010 `computeIndirectModel`) and the current
4566 // element cannot autoClose, open the container chain that the model
4567 // says would hold it, marked `_autoopened`/`_autoclose` so it closes
4568 // with what it wraps. Perl shares every one of these errors (its only
4569 // autoOpen tags are the model's); the bridges are the documented
4570 // surpasses, one table row each, in precedence order:
4571 //
4572 // Math: a math node arriving in an INLINE-model element opened
4573 // while in math mode — `\hyperref[l]{b}`/`\glsdisp{k}{k}` whose
4574 // content is math (glosmathtools.sty:74 `\ensuremath{\glsdisp…}`;
4575 // `<ltx:XMTok> isn't allowed in <ltx:glossaryref>`,
4576 // sample_glosmathtools ×2 53 errors; Perl TeX_Math.pool:42 autoOpens
4577 // only XMText). Wrapper = inline `ltx:Math`/`ltx:XMath`, the shape
4578 // `\text{$k$}` already has. Guard:
4579 // `perfect_kernel_batch54::math_content_in_a_ref_gets_an_inline_math`.
4580 //
4581 // inline-block: block content in an inline container that cannot
4582 // auto-close — a `{lstlisting}` in an `l`/`c`/`r` tabular cell or a
4583 // `{tabbing}` field (engtlc, lexref, expex-glossonly: `<ltx:listing>
4584 // isn't allowed in <ltx:td>`) — takes the shape the `p{}` column
4585 // already gives cell blocks (`insert_block`). Only when every direct,
4586 // auto-open and auto-close route above is exhausted, so a display
4587 // equation in a paragraph still closes the `ltx:p` (Document.pm:1008;
4588 // making `inline-block` an autoOpen tag globally would wrap
4589 // equations instead of closing paragraphs). PLANS P37. Guard:
4590 // `perfect_kernel_batch54::listing_in_a_tabular_cell_gets_an_inline_block`.
4591 //
4592 // foreignObject: block content inside an SVG group — a TikZ node
4593 // whose text holds a `\verb` or a paragraph (makeshape 22, optikz
4594 // 46: `<ltx:p> isn't allowed in <svg:g>`) — takes `svg:foreignObject`,
4595 // whose model is Flow (LaTeXML-misc.rnc `SVG.foreignObject.content`),
4596 // the same shape `\lxSVG@includegraphics` uses for non-SVG content
4597 // (pgfsys-latexml.def.ltxml:202 absorbs the node box into the group
4598 // directly). OXIDIZED_DESIGN #186, PLANS P37 (svg half). Guard:
4599 // `perfect_kernel_batch54::verbatim_in_a_tikz_node_gets_a_foreign_object`.
4600 //
4601 // itemize: a list item stranded outside its list — `\item` digested
4602 // inside a box whose body `insert_block` captures (`\parbox`/
4603 // `minipage`/`\vbox` inside a list item: tikz-ext-manual's
4604 // `{arrowtip}` puts `\tipCompat`'s `\item` in a `minipage` inside a
4605 // `\pgfmanualentryheadline` item; `<ltx:item> isn't allowed in
4606 // <ltx:_CaptureBlock_>`). The item is still the enclosing list's
4607 // `\@item` (latex.ltx's `\@parboxrestore` resets no list bindings),
4608 // and pdflatex typesets it as a labelled paragraph inside the box;
4609 // only `ltx:item` is autoOpen (latex_constructs.pool.ltxml:1277), so
4610 // `computeIndirectModel` has no `_CaptureBlock_`→`item` route.
4611 // Wrapper = the shape LaTeX gives an item outside its list, an
4612 // `ltx:itemize`; an item in an inline `\fbox` still reports. Guard:
4613 // `perfect_kernel_batch56::item_in_a_captured_box_gets_an_itemize`.
4614 //
4615 // A row applies when its own predicate holds, the current element can
4616 // hold the chain's first wrapper and the chain's last wrapper can hold
4617 // the child (both by the model, never by name).
4618 struct AutoOpenBridge {
4619 /// The wrapper chain, outermost first.
4620 chain: &'static [&'static str],
4621 /// The row's own predicate on (current element, arriving child).
4622 applies: fn(cur: &str, qsym: &str) -> bool,
4623 /// Extra attributes on the outermost wrapper.
4624 attrs: &'static [(&'static str, &'static str)],
4625 /// The row's predicate on the current node itself.
4626 holder: fn(node: &Node) -> bool,
4627 /// Whether the auto-closable elements around the current point close first, up to the outermost one whose
4628 /// parent holds the wrapper (the paragraph a `\trivlist` ends, latex.ltx `\@trivlist`'s `\par`).
4629 close_up: bool,
4630 /// Whether the row also takes an element a binding sets in place (`set_in_place`: a wrap float in a box).
4631 in_place: bool,
4632 }
4633 const AUTO_OPEN_BRIDGES: &[AutoOpenBridge] = &[
4634 AutoOpenBridge {
4635 chain: &["ltx:Math", "ltx:XMath"],
4636 applies: |_cur, qsym| qsym.starts_with("ltx:XM"),
4637 attrs: &[("mode", "inline")],
4638 holder: |_| true,
4639 close_up: false,
4640 in_place: false,
4641 },
4642 AutoOpenBridge {
4643 chain: &["ltx:inline-block"],
4644 applies: |_cur, qsym| qsym != "ltx:inline-block",
4645 attrs: &[],
4646 holder: |_| true,
4647 close_up: false,
4648 in_place: false,
4649 },
4650 AutoOpenBridge {
4651 chain: &["svg:foreignObject"],
4652 applies: |cur, qsym| cur.starts_with("svg:") && qsym != "svg:foreignObject",
4653 attrs: &[],
4654 holder: |_| true,
4655 close_up: false,
4656 in_place: false,
4657 },
4658 AutoOpenBridge {
4659 chain: &["ltx:itemize"],
4660 applies: |_cur, qsym| qsym == "ltx:item",
4661 attrs: &[],
4662 holder: |_| true,
4663 close_up: false,
4664 in_place: false,
4665 },
4666 // A sectioning unit in a float body (`\section` in a `figure`, `\subsection` in a `table`; 38 2609 papers,
4667 // 117 errors) opens an `ltx:inline-sectional-block` there: the heading keeps its number in the sequence,
4668 // its id and its labels, as the PDF prints it, and the float stays whole (user ruling 2026-10-06,
4669 // OXIDIZED_DESIGN_DIVERGENCES #189). The float's own id is fixed before the unit steps the counters it is
4670 // made within (`pin_float_id_before_its_sectioning`).
4671 AutoOpenBridge {
4672 chain: &["ltx:inline-sectional-block"],
4673 applies: |cur, qsym| {
4674 matches!(cur, "ltx:figure" | "ltx:table" | "ltx:float")
4675 && is_sectioning_unit_name(qsym)
4676 },
4677 attrs: &[],
4678 holder: |_| true,
4679 close_up: false,
4680 in_place: false,
4681 },
4682 // …and in a list item (an itemize, enumerate or description item, nested or not; 2304.10050, 2312.11556,
4683 // 2406.02069, 2411.15124, 2412.04099, 2501.07868, 2501.07938, 2511.00839; the TeX Live manuals ddphonism,
4684 // phonrule, prerex, pdfmarginpar) the same block, in a paragraph of the
4685 // item, since an item holds paragraphs only (LaTeXML-block.rnc:257 `item_model = tags?, Para.model`): the
4686 // list stays one list, a later `\item` or the list's end closes the block, and a second heading in the item
4687 // is the first's sibling in it (user ruling 2026-10-09, OXIDIZED_DESIGN_DIVERGENCES #189). Only a labelled
4688 // item: an unlabelled `\item[]` is a margin list's (`changemargin`, `\list{}{…}\item[]`, a whole paper in it:
4689 // 2201.06926, 2505.05767), no list but a margin, whose sections nest as Perl's do, its back matter in the last
4690 // of them — the block would leave the appendix, acknowledgements and bibliography no place. An item's id is
4691 // made when it is digested, before the heading steps any counter. Guards
4692 // `perfect_kernel_batch54::{sectioning_unit_inside_item_or_figure_opens_a_block,
4693 // next_sectioning_unit_in_an_item_is_a_sibling}`.
4694 AutoOpenBridge {
4695 chain: &["ltx:para", "ltx:inline-sectional-block"],
4696 applies: |cur, qsym| cur == "ltx:item" && is_sectioning_unit_name(qsym),
4697 attrs: &[],
4698 holder: item_has_label,
4699 close_up: false,
4700 in_place: false,
4701 },
4702 // …and a run-in `\paragraph` or `\subparagraph` in a `{quote}`, `{quotation}` or `{verse}`: pdflatex sets
4703 // the heading and the text after it, up to the environment's end, inside the quote's `\list` margins
4704 // (article.cls:389-408, `quote` = `\list{}{\rightmargin\leftmargin}\item\relax`), and the quote holds the
4705 // block directly (LaTeXML-block.rnc `quote_model` takes `Misc.class`); the quote's end closes it, and a later
4706 // display unit in the same quote closes the quote (`close_quotes_blocking` above). The display units
4707 // `\part`..`\subsubsection` open no block (`is_quote_closing_unit`; `\begin{quotation}\section*{}` around a
4708 // title page's abstract, 0712.1985). Main-session ruling 2026-10-17, OXIDIZED_DESIGN_DIVERGENCES #678;
4709 // witnesses 2607.27159 2505.18677 2305.11603 1809.03802 2208.14587. Guards `perfect_kernel_batch69a::{
4710 // paragraph_in_a_quote_stays_in_it, section_after_a_paragraph_in_a_quote_closes_it}`.
4711 AutoOpenBridge {
4712 chain: &["ltx:inline-sectional-block"],
4713 applies: |cur, qsym| cur == "ltx:quote" && is_run_in_unit_name(qsym),
4714 attrs: &[],
4715 holder: |_| true,
4716 close_up: false,
4717 in_place: false,
4718 },
4719 AutoOpenBridge {
4720 chain: &["ltx:item", "ltx:para"],
4721 applies: |cur, qsym| cur == qsym,
4722 attrs: &[],
4723 holder: |_| true,
4724 close_up: false,
4725 in_place: false,
4726 },
4727 // A theorem, a proof or a table of contents written inside a container whose model holds no Para.class (a
4728 // `{quote}`, a `\footnote`'s `ltx:note`, a `{wrapfigure}`, a font or color group's `ltx:text`, a tabular
4729 // cell): pdflatex sets it there, inside the container's own box, so it opens an `ltx:inline-logical-block`
4730 // (Misc.class, model Para.model: LaTeXML-para.rnc:77-90), the wrapper `\marginpar` already gives its note
4731 // body (sect09.rs `\lx@marginpar`) — the content stays in place and the schema is unchanged (main-session
4732 // ruling P1 2026-10-17; OXIDIZED_DESIGN #271 keeps the quote model as it is). The `\trivlist` that starts a
4733 // theorem ends the paragraph it meets (latex.ltx `\@trivlist`'s `\par`), so the auto-closable elements around
4734 // the point (the `ltx:p`, a font switch's `ltx:text`) close first, up to the outermost whose parent holds
4735 // the wrapper; a container that cannot auto-close (the note, a constructor's `ltx:text`) keeps it inside.
4736 // Perl shares every one of these errors (same schema, no such autoOpen). Not inside a frontmatter
4737 // container (`ltx:abstract`, `ltx:acknowledgements`, `ltx:keywords`, `ltx:classification`, `ltx:creator`, or
4738 // anything in one): there the "isn't allowed" Error stands, as in Perl (main-session ruling 2026-10-17), but
4739 // a theorem or proof in an abstract is dissolved into it (below, `dissolve_theorem_in_abstract`); a kernel
4740 // table of contents there goes after the container instead (`float_out_of_frontmatter`, OD #753).
4741 // Witnesses 2406.11811, 2103.03402, 0806.0214, 2602.15784, 2301.10544, 1410.7242 (theorem in a quote),
4742 // 1412.2039, math0603642 (TOC in a quote), 2507.09788, 2307.10959, 2308.06338, 2410.15097, 0804.3724,
4743 // math0612590 (theorem in a footnote), 1310.0491 (an ltx:text). Guards
4744 // `perfect_kernel_batch69c::{para_level_block_in_quote_opens_an_inline_logical_block,
4745 // para_level_block_in_note_and_wrapfigure_opens_an_inline_logical_block}`; OXIDIZED_DESIGN_DIVERGENCES #689.
4746 AutoOpenBridge {
4747 chain: &["ltx:inline-logical-block"],
4748 applies: |_cur, qsym| matches!(qsym, "ltx:theorem" | "ltx:proof" | "ltx:TOC"),
4749 attrs: &[],
4750 holder: outside_frontmatter_container,
4751 close_up: true,
4752 in_place: true,
4753 },
4754 ];
4755 for bridge in AUTO_OPEN_BRIDGES {
4756 let first = arena::pin(bridge.chain[0]);
4757 let last = arena::pin(bridge.chain[bridge.chain.len() - 1]);
4758 let applies = (arena::with2(cur_qname, qsym, |cur, q| (bridge.applies)(cur, q))
4759 || (in_place && bridge.in_place))
4760 && (bridge.holder)(&self.node);
4761 if applies && bridge.close_up && can_contain_qsym(last, qsym) {
4762 let mut node = self.node.clone();
4763 let mut close_to = None;
4764 while node.get_type() == Some(NodeType::ElementNode) && can_auto_close(&node) {
4765 let Some(parent) = node.get_parent() else {
4766 break;
4767 };
4768 if parent.get_type() == Some(NodeType::ElementNode)
4769 && can_contain_qsym(get_node_qname(&parent), first)
4770 {
4771 close_to = Some(node);
4772 }
4773 node = parent;
4774 }
4775 if let Some(close_to_node) = close_to {
4776 self.close_node_internal(&close_to_node)?;
4777 }
4778 }
4779 let cur_qname = get_node_qname(&self.node);
4780 if applies && can_contain_qsym(cur_qname, first) && can_contain_qsym(last, qsym) {
4781 let node_font = self.get_node_font(&self.node).clone();
4782 for (i, wrapper) in bridge.chain.iter().enumerate() {
4783 let mut attrs = string_map!("_autoopened" => "true", "_autoclose" => "true");
4784 if i == 0 {
4785 for (k, v) in bridge.attrs {
4786 attrs.insert((*k).to_string(), (*v).to_string());
4787 }
4788 }
4789 self.open_element(wrapper, Some(attrs), Some(&node_font))?;
4790 }
4791 return self.find_insertion_point_in(qsym, Some(last), in_place);
4792 }
4793 }
4794 // A theorem or proof in an abstract (Block.model: no Para.class) goes in as it is, closing the paragraph it
4795 // meets as `\@trivlist` does; at its close it is dissolved into the abstract (`dissolve_theorem_in_abstract`).
4796 if arena::with(qsym, |q| matches!(q, "ltx:theorem" | "ltx:proof"))
4797 && within_abstract(&self.node)
4798 {
4799 let mut node = self.node.clone();
4800 let mut close_to = None;
4801 while node.get_type() == Some(NodeType::ElementNode) && can_auto_close(&node) {
4802 close_to = Some(node.clone());
4803 let Some(parent) = node.get_parent() else {
4804 break;
4805 };
4806 node = parent;
4807 }
4808 if let Some(close_to_node) = close_to {
4809 self.close_node_internal(&close_to_node)?;
4810 }
4811 return Ok(self.node.clone());
4812 }
4813 // Didn't find a legit place.
4814 // Perl Document.pm:1008-1010: "<qname> isn't allowed in <cur_qname>"
4815 // (a bare qname for #PCDATA), with "Currently in <insertion
4816 // context>" as a SEPARATE Error detail — NOT a Rust backtrace
4817 // (`disabled backtrace`) merged into the user-facing message.
4818 let message = arena::with2(cur_qname, qsym, |cur_qname_str, qname| {
4819 let qname_disp = if qname == "#PCDATA" {
4820 qname.to_string()
4821 } else {
4822 s!("<{}>", qname)
4823 };
4824 s!("{} isn't allowed in <{}>", qname_disp, cur_qname_str)
4825 });
4826 let context = s!("Currently in {}", self.get_insertion_context(None)?);
4827 Error!("malformed", arena::to_string(qsym), message, context);
4828
4829 // But we'll do it anyway, unless Error => Fatal.
4830 Ok(self.node.clone())
4831 }
4832 }
4833 }
4834
4835 fn get_insertion_candidates(&self, node: &Node) -> Vec<Node> {
4836 let mut nodes: Vec<Node> = Vec::new();
4837 // Check the current element FIRST, then build list of candidates.
4838 let first = if node.get_type() == Some(NodeType::TextNode) {
4839 Cow::Owned(node.get_parent().unwrap())
4840 } else {
4841 Cow::Borrowed(node)
4842 };
4843 let is_capture = name_is(&first, "_Capture_");
4844
4845 if first.get_type() != Some(NodeType::DocumentNode) && !is_capture {
4846 nodes.push(first.clone().into_owned());
4847 }
4848
4849 // Collect previous siblings, if node is a text node.
4850 let mut element_node_opt: Option<Cow<Node>> = if node.get_type() == Some(NodeType::TextNode) {
4851 let mut current_opt = Some(Cow::Borrowed(node));
4852 while let Some(current) = current_opt {
4853 current_opt = current.get_prev_sibling().map(Cow::Owned);
4854 if name_is(¤t, "_Capture_") {
4855 nodes.extend(xml::element_nodes(¤t));
4856 } else {
4857 nodes.push(current.into_owned());
4858 }
4859 }
4860 node.get_parent().map(Cow::Owned)
4861 } else {
4862 Some(Cow::Borrowed(node))
4863 };
4864 // Now collect (element) node & ancestors
4865 while let Some(element_node) = element_node_opt {
4866 element_node_opt = element_node.get_parent().map(Cow::Owned);
4867 let node_type = element_node.get_type();
4868 if node_type.is_none() || node_type == Some(NodeType::DocumentNode) {
4869 break;
4870 }
4871 if name_is(&element_node, "_Capture_") {
4872 nodes.extend(xml::element_nodes(&element_node));
4873 } else {
4874 nodes.push(element_node.into_owned());
4875 }
4876 }
4877 if is_capture {
4878 nodes.push(first.into_owned());
4879 }
4880
4881 nodes
4882 }
4883
4884 pub fn node_set_attribute(&mut self, key: &str, value: &str) -> Result<()> {
4885 if value.is_empty() {
4886 return Ok(()); // skip if empty
4887 }
4888 if key == "xml:id" {
4889 // If it's an ID attribute
4890 let recorded = self.record_id(value); // Do id book keeping
4891
4892 // TODO: Need to improve Namespace ergonomics, also in rust-libxml
4893 // let node_ns = self
4894 // .document
4895 // .get_root_element()
4896 // .unwrap()
4897 // .get_namespace_declarations()
4898 // .into_iter()
4899 // .find(|ns| ns.get_href() == XML_NS)
4900 // .unwrap_or_else(|| {
4901 // node
4902 // .get_namespace_declarations()
4903 // .into_iter()
4904 // .find(|ns| ns.get_href() == XML_NS)
4905 // .unwrap_or_else(|| {
4906 // Namespace::new(
4907 // "xml",
4908 // &XML_NS.to_string().clone(),
4909 // &mut self.document.get_root_element().unwrap(),
4910 // ).unwrap_or_else(|_| {
4911 // panic!(
4912 // "Could not set NS for {:?}\n\n at \n\n {:?}",
4913 // self.document.node_to_string(node),
4914 // self.document.to_string(true)
4915 // )
4916 // })
4917 // })
4918 // });
4919
4920 self.node.set_attribute("xml:id", &recorded)?; // and bypass all ns stuff
4921 } else if !key.contains(':') {
4922 // No colon; no namespace (the common case!)
4923 // Ignore attributes not allowed by the model,
4924 // but accept "internal" attributes.
4925 let qname = get_node_qname(&self.node);
4926 if key.starts_with('_') || model::can_have_attribute(qname, arena::pin(key)) {
4927 self.node.set_attribute(key, value)?
4928 };
4929 } else {
4930 // Namespaced attributes: set directly for now.
4931 // TODO: proper namespace prefix resolution via model->decodeQName
4932 self.node.set_attribute(key, value)?;
4933 // else {
4934 // node.setAttributeNS($ns, "$prefix:$name" => $value); } }
4935 // else {
4936 // node.setAttribute($name => $value); } }
4937 } // redundant case...
4938 Ok(())
4939 }
4940 pub fn node_get_attribute(&mut self, name: &str) -> Option<String> {
4941 self.node.get_attribute(name)
4942 }
4943 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4944 // Document surgery (?)
4945 // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4946 // The following carry out DOM modification but NOT relative to any current
4947 // insertion point (eg self.node), but rather relative to nodes specified
4948 // in the arguments.
4949
4950 /// Set any allowed attribute on a node, decoding the prefix, if any.
4951 /// Also records, and checks, any id attributes.
4952 /// \[xml:id and namespaced attributes are always allowed\]
4953 ///
4954 /// "Allowed" is the document model's call, so this is not a plain libxml
4955 /// write: an attribute the schema does not permit on `node` is dropped rather
4956 /// than emitted, which is what keeps a binding from producing a document that
4957 /// fails validation.
4958 pub fn set_attribute(&mut self, node: &mut Node, key: &str, value: &str) -> Result<()> {
4959 self.set_attribute_internal(node, key, value, false)
4960 }
4961
4962 /// [`Document::set_attribute`] of an attribute COPIED from another tree ([`Document::append_tree`]): an empty
4963 /// value is kept on an element outside the ltx namespace, where it is data (HTML's `disabled=""`, `alt=""`;
4964 /// #1034, OXIDIZED_DESIGN_DIVERGENCES #1184). Perl's `setAttribute` drops every empty value (Document.pm:1381).
4965 fn set_copied_attribute(&mut self, node: &mut Node, key: &str, value: &str) -> Result<()> {
4966 let keep_empty = !node
4967 .as_readonly()
4968 .with_namespace_href(|href| href == Some(model::LTX_NAMESPACE));
4969 self.set_attribute_internal(node, key, value, keep_empty)
4970 }
4971
4972 fn set_attribute_internal(
4973 &mut self,
4974 node: &mut Node,
4975 key: &str,
4976 value: &str,
4977 keep_empty: bool,
4978 ) -> Result<()> {
4979 // An empty id (`id` is this port's spelling of `xml:id`) is no id, and an `_` attribute is internal.
4980 let keep_empty = keep_empty && key != "xml:id" && key != "id" && !key.starts_with('_');
4981 // Sanitize BEFORE the empty check: a value of only invalid chars (e.g. a
4982 // lone NUL) must degrade to the skip path, not reach libxml. Without this
4983 // an interior NUL panics in libxml's `CString::new(value).unwrap()`
4984 // (node.rs:639) and aborts the whole conversion — witness `$a^^@b$`-class
4985 // stray NULs (BibTeX `\"u`-mangling) reaching the `tex=` reversion
4986 // attribute now that NUL's catcode is 12/OTHER like Perl. The text sinks
4987 // (`open_text_internal`/`open_math_text_internal`) already stripped NUL;
4988 // this attribute sink did not. PR #249 review P0-1.
4989 let value_sanitized = xml_sanitize(value);
4990 // `class` is a list of NMTOKENs (LaTeXML-common.rng:94) and `xml:id` an
4991 // XML Name (:120); the ONE emitter every writer funnels through
4992 // (`add_ss_values` too) makes them so — user ruling 2026-09-18, beyond
4993 // Perl, which emits listings' `ltx_lst_language_{TeX}_LaTeX` / `C++` /
4994 // an unexpanded `\lexer@cs`, raw `\lx@add@class` `@` names, fontawesome's
4995 // `fa-*`, and csvsimple-legacy's `\par` leaking into a class and an id
4996 // (33 manuals, 3,488 jing lines; 2 manuals, 1,231). A value that is
4997 // already valid is untouched.
4998 let value_sanitized: Cow<'_, str> = match key {
4999 "class" => Cow::Owned(nmtokens_clean(&value_sanitized)),
5000 "xml:id" if !is_xml_name(&value_sanitized) => {
5001 Cow::Owned(crate::common::cleaners::clean_id(&value_sanitized))
5002 },
5003 _ => value_sanitized,
5004 };
5005 let value: &str = &value_sanitized;
5006 if value.is_empty() && !keep_empty {
5007 return Ok(()); // skip if empty
5008 }
5009 // Normalise the key first, then run Perl's plain `setAttribute`
5010 // (`Core/Document.pm:1370-1386`): schema-check, then the LITERAL `xml:id`
5011 // test. The normalisation is needed because this port spells `xml:id` as a
5012 // bare `id` throughout its property/attribute maps -- the math parser,
5013 // `base_xmath`, alignment rows and `RefStepID`'s `#id` all do it, where
5014 // Perl's constructors always write `xml:id` out in full -- so a bare `id`
5015 // arriving here normally MEANS `xml:id`. The exception is that `id` is ALSO
5016 // a real attribute in the model: `LaTeXML-bib.rnc:335,353` declare
5017 // `attribute id { text }?` on `ltx:bib-identifier` and `ltx:bib-review`,
5018 // carrying the ISSN/DOI/MR identifier itself. Letting the alias apply
5019 // unconditionally rewrote those into invalid-NCName ids
5020 // (`xml:id="0010-3640,1097-0312"`) -- witness arXiv 2508.17585.
5021 let key = if key == "id" && !model::can_have_attribute(get_node_qname(node), arena::pin("id")) {
5022 "xml:id"
5023 } else {
5024 key
5025 };
5026 // Accept internal attributes (starting with _), namespaced (containing :), and model-allowed.
5027 if !key.starts_with('_') && !key.contains(':') {
5028 let qname = get_node_qname(node);
5029 if !model::can_have_attribute(qname, arena::pin(key)) {
5030 return Ok(()); // silently skip attributes not allowed by schema
5031 }
5032 }
5033 if key == "xml:id" {
5034 // record_id_with_node detects duplicates and returns a
5035 // deduplicated id when a DIFFERENT node already claims the
5036 // same id. Previously we discarded that return value and
5037 // wrote the original `value`, which meant libxml2 saw two
5038 // nodes with the same xml:id. The post-processing scan's
5039 // libxml2 idHash lookups then ran O(n²) on any document
5040 // with enough duplicates (see 1106.1389 / KNOWN_PERL_ERRORS
5041 // #13: 14 duplicate-id sites from \addtocounter{equation}{-1}
5042 // + \subequations inside a \newtheorem[equation] theorem).
5043 let deduped = self.record_id_with_node(value, node);
5044 node.set_attribute("xml:id", &deduped)?;
5045 } else if !key.contains(':') {
5046 // No colon; no namespace (the common case!)
5047 // Note: Full model validation (can_have_attribute) is done in node_set_attribute.
5048 // Here we just set the attribute, since the caller is responsible for filtering.
5049 node.set_attribute(key, value)?;
5050 } else {
5051 // Namespaced attribute (`prefix:local`). Mirror Perl
5052 // `Core/Document.pm::setAttribute`, whose `getDocumentNamespacePrefix($ns, 1)`
5053 // *promotes* the prefix's namespace to a document namespace on first use.
5054 // That lets finalize's `apply_document_namespace_declarations` declare
5055 // `xmlns:prefix` on the root, so the prefixed attribute resolves into its
5056 // namespace on serialization and the post XSLT can copy it (e.g.
5057 // `data:sourcepos` → `data-sourcepos`). Without the promotion a code-only
5058 // namespace (like `data`, used by `--source-map`) is emitted unbound and
5059 // dropped. General over any registered prefix — implements the decodeQName
5060 // TODO. (`aria`/schema namespaces are already document namespaces, so the
5061 // re-registration is an idempotent no-op for them.)
5062 if let Ok((Some(ns_uri), _local)) = model::decode_qname(key) {
5063 let prefix = key.split(':').next().unwrap_or("");
5064 model::register_document_namespace(prefix, Some(&ns_uri));
5065 }
5066 node.set_attribute(key, value)?;
5067 }
5068 // ... TODO: continue (see Perl)
5069 Ok(())
5070 }
5071
5072 pub fn add_ss_values(&mut self, node: &mut Node, key: &str, values_str: &str) -> Result<()> {
5073 // $values = $values->toAttribute if ref $values;
5074 if !values_str.is_empty() {
5075 // Skip if `empty'; but 0 is OK!
5076 let mut values: Vec<&str> = values_str.split_whitespace().collect();
5077 if let Some(oldvalues) = node.get_attribute(key) {
5078 // previous values?
5079 let mut old: Vec<&str> = oldvalues.split_whitespace().collect();
5080 for new in values {
5081 if old.iter().all(|v| *v != new) {
5082 old.push(new);
5083 }
5084 }
5085 old.sort_unstable();
5086 self.set_attribute(node, key, &old.join(" "))?;
5087 } else {
5088 values.sort_unstable();
5089 self.set_attribute(node, key, &values.join(" "))?;
5090 }
5091 }
5092 Ok(())
5093 }
5094
5095 /// Add one or more CSS classes to a node, without disturbing the ones it
5096 /// already carries.
5097 ///
5098 /// `class` is treated as the space-separated set it is
5099 /// ([`add_ss_values`](Self::add_ss_values)), so several bindings can each
5100 /// contribute a class to the same element — which is why this exists rather
5101 /// than a plain `setAttribute("class", …)`, and what
5102 /// [`remove_ss_values`](Self::remove_ss_values) undoes.
5103 pub fn add_class(&mut self, node: &mut Node, class: &str) -> Result<()> {
5104 self.add_ss_values(node, "class", class)
5105 }
5106
5107 /// Remove space-separated values from an attribute.
5108 /// Perl: sub removeSSValues (Document.pm lines 1423-1437)
5109 pub fn remove_ss_values(&mut self, node: &mut Node, key: &str, values: &str) {
5110 let to_remove: Vec<&str> = values.split_whitespace().collect();
5111 if to_remove.is_empty() {
5112 return;
5113 }
5114 if let Some(current) = node.get_attribute(key) {
5115 let updated: Vec<&str> = current
5116 .split_whitespace()
5117 .filter(|v| !to_remove.contains(v))
5118 .collect();
5119 if updated.is_empty() {
5120 let _ = node.remove_attribute(key);
5121 } else {
5122 let mut sorted = updated;
5123 sorted.sort_unstable();
5124 node
5125 .set_attribute(key, &sorted.join(" "))
5126 .unwrap_or_default();
5127 }
5128 }
5129 }
5130
5131 /// Remove CSS class from element.
5132 /// Perl: sub removeClass (Document.pm lines 1439-1442)
5133 pub fn remove_class(&mut self, node: &mut Node, class: &str) {
5134 self.remove_ss_values(node, "class", class);
5135 }
5136
5137 /// Float to a node that can accept the given attribute.
5138 /// Returns the previous node so it can be restored after setting the attribute.
5139 /// Perl: sub floatToAttribute (Document.pm lines 1080-1092)
5140 pub fn float_to_attribute(&mut self, key: &str) -> Option<Node> {
5141 let candidates = self.get_insertion_candidates(&self.node);
5142 for candidate in candidates {
5143 let qname_sym = get_node_qname(&candidate);
5144 if sym_can_have_attribute(qname_sym, arena::pin(key)) {
5145 let savenode = self.node.clone();
5146 self.set_node(&candidate);
5147 return Some(savenode);
5148 }
5149 }
5150 Warn!(
5151 "malformed",
5152 key,
5153 s!("No open node can get attribute '{}'", key)
5154 );
5155 None
5156 }
5157
5158 /// Check if a node is currently open (i.e., is or contains the current node).
5159 /// Perl: sub isOpen (Document.pm lines 1998-2006)
5160 pub fn is_open(&self, node: &Node) -> bool {
5161 if *node == self.node {
5162 return true;
5163 }
5164 for child in node.get_child_nodes() {
5165 if self.is_open(&child) {
5166 return true;
5167 }
5168 }
5169 false
5170 }
5171
5172 //**********************************************************************
5173 // Association of nodes and ids (xml:id)
5174
5175 /// Records the association of the current Document `node` with the `id`,
5176 /// which should be the `xml:id` attribute of the `node`.
5177 /// Usually this association will be maintained by the methods
5178 /// that create nodes or set attributes.
5179 fn record_id(&mut self, id: &str) -> String {
5180 let needs_modify = if let Some(prev) = self.idstore.get(id) {
5181 // Whoops! Already assigned!!!
5182 // Can we recover?
5183 self.node != *prev
5184 } else {
5185 false
5186 };
5187 let final_id = if needs_modify {
5188 let badid = id.to_string();
5189 let new_id = self.modify_id(badid);
5190 Info!(
5191 "malformed",
5192 "id",
5193 s!("Duplicated attribute xml:id. Using id='{}'", new_id)
5194 );
5195 new_id
5196 } else {
5197 id.to_string()
5198 };
5199 self.idstore.insert(final_id.clone(), self.node.clone());
5200 final_id
5201 }
5202
5203 /// Records the association of the given `node` with the `id`,
5204 /// which should be the `xml:id` attribute of the `node`.
5205 /// Usually this association will be maintained by the methods
5206 /// that create nodes or set attributes.
5207 fn record_id_with_node(&mut self, id: &str, node: &Node) -> String {
5208 let prev_opt = if let Some(prev) = self.idstore.get(id) {
5209 // Whoops! Already assigned!!!
5210 // Can we recover? Only conflict if a DIFFERENT node already has this id.
5211 if node != prev {
5212 Some(prev.clone())
5213 } else {
5214 None
5215 }
5216 } else {
5217 None
5218 };
5219 // The spilled half: an id that left the idstore with a spilled fragment
5220 // is just as taken (its node is on disk, not in the tree).
5221 let spilled_collision = prev_opt.is_none() && self.spilled_ids.contains(id);
5222 let final_id = if spilled_collision {
5223 let new_id = self.modify_id(id.to_owned());
5224 Debug!(
5225 "malformed",
5226 "id",
5227 s!(
5228 "Duplicated attribute xml:id. Using id='{}' on <{}> id='{}' already set on a disk-staged fragment",
5229 new_id,
5230 arena::to_string(get_node_qname(node)),
5231 id
5232 )
5233 );
5234 new_id
5235 } else if let Some(prev) = prev_opt {
5236 let badid = id;
5237 let new_id = self.modify_id(id.to_owned());
5238 // Concise node descriptions, mirroring Perl `Stringify($node)`
5239 // (Common/Object.pm L40-49: `<tag attrs…>` with no child
5240 // serialization). Rust previously dumped the FULL node via
5241 // `node_to_string`, which (a) diverged from Perl's concise form and
5242 // (b) spilled child TEXT into the log — e.g. a figure caption
5243 // beginning "Error bars are the standard deviations…" then appears as
5244 // a line starting "Error" and is mis-counted as an error by
5245 // text-grep error sweeps (false positive on 2009.01426, which has
5246 // ZERO real errors). Use just the qname (+ the relevant id), which is
5247 // what an id-dedup diagnostic actually needs.
5248 let message = s!(
5249 "Duplicated attribute xml:id. Using id='{}' on <{}> id='{}' already set on <{}>",
5250 new_id,
5251 arena::to_string(get_node_qname(node)),
5252 badid,
5253 arena::to_string(get_node_qname(&prev))
5254 );
5255 // Perl-faithful (Document.pm L1454): Info-level. The id-counter
5256 // collision is the dedup-recovery path (`modify_id` appends
5257 // suffix), not silent corruption. The earlier Error-level
5258 // promotion was motivated by 1410.8171 (Sárkány PRA), but root-
5259 // cause investigation showed the empty-S3+ rendering there was
5260 // the siunitx ExplodeText! tokenization bug (fixed by
5261 // fc2aae7266), not the dedup recovery. After that fix, the
5262 // residual dedup events on the canvas are SHARED with Perl —
5263 // the in-tree test fixture tests/math/declare.xml itself bakes
5264 // in the `xml:id="S1.Ex1.m1.2a"` dedup result, confirming
5265 // Perl produces the same behavior. Downstream broken XMRefs
5266 // (post-dedup) emit Warning:expected:node "No node found with
5267 // id=…" which already surfaces the consequence at the appro-
5268 // priate severity. Math-parser hygiene fix (preventing the
5269 // collision in the first place) is tracked separately.
5270 Debug!("malformed", "id", message);
5271 new_id
5272 } else {
5273 id.to_string()
5274 };
5275 self.idstore.insert(final_id.clone(), node.clone());
5276 final_id
5277 }
5278
5279 pub fn unrecord_id(&mut self, id: &str) { self.idstore.remove(id); }
5280
5281 /// Guardian-safe unlink: walk `node`'s subtree invalidating every `xml:id`
5282 /// idstore entry, then detach it from its parent. Use this in preference
5283 /// to a raw `node.unlink()` anywhere the node *might* carry an `xml:id`
5284 /// (subtree reshuffles in math-parser, post-processing cleanup, etc.),
5285 /// to prevent the dangling-Node class of bug that produced the 1605.08055
5286 /// Finalizing-phase SIGSEGV (see SYNC_STATUS.md D3b).
5287 ///
5288 /// This is the unlink-only half of `remove_node` — it does **not** adjust
5289 /// `self.node` / the insertion point, which is correct for callers that
5290 /// intend to re-parent the unlinked subtree elsewhere (the common case).
5291 /// Callers that want the insertion-point bookkeeping should use
5292 /// `remove_node` instead.
5293 pub fn safe_unlink(&mut self, mut node: Node) {
5294 if node.get_type() == Some(NodeType::ElementNode) {
5295 if let Some(id) = node.get_attribute_ns("id", XML_NS) {
5296 self.unrecord_id(&id);
5297 }
5298 for child in node.get_child_nodes() {
5299 self.remove_node_aux(child);
5300 }
5301 }
5302 node.unlink();
5303 }
5304
5305 /// These are used to record or unrecord, in bulk, all the ids within a node (tree).
5306 ///
5307 /// When `record_id_with_node` detects a duplicate it renames the id (e.g.
5308 /// `X.1.mf` → `X.1.mfa`). Any sibling `<ltx:XMRef idref="X.1.mf"/>` in the
5309 /// same subtree would otherwise become a dangling reference for the post-
5310 /// processor. After re-recording IDs, sweep the subtree once and update any
5311 /// XMRef whose `idref` matches an entry in the rename map.
5312 ///
5313 /// Perl `Core::Document::recordNodeIDs` (Document.pm L1466-1472) has the
5314 /// same latent bug — recording renames but XMRefs aren't touched. The bug
5315 /// surfaces in our port because the math-parser path
5316 /// (`parser.rs::install_replacements`-style `unrecord+record` round-trips)
5317 /// is denser than Perl's; both end up needing this remap to keep XMRef
5318 /// chains intact. Intentional surpass-Perl divergence; tracked in
5319 /// SYNC_STATUS Task #10.
5320 pub fn record_node_ids(&mut self, node: &Node) -> Result<()> {
5321 use rustc_hash::FxHashMap;
5322 let mut rename: FxHashMap<String, String> = FxHashMap::default();
5323 // `descendant-or-self::*[@xml:id]` as a walk: finalize's rebuild runs it from the root (#802).
5324 for mut idnode in xml::descendant_or_self_elements(node, |n| n.has_attribute_ns("id", XML_NS)) {
5325 if let Some(id) = idnode.get_attribute_ns("id", XML_NS) {
5326 let newid = self.record_id_with_node(&id, &idnode);
5327 if newid != id {
5328 idnode.set_attribute("xml:id", &newid)?;
5329 rename.insert(id, newid);
5330 }
5331 }
5332 }
5333 if !rename.is_empty() {
5334 for mut xmref in xml::descendant_or_self_elements(node, |n| n.has_attribute_no_ns("idref")) {
5335 if let Some(idref) = xmref.get_attribute("idref")
5336 && let Some(new) = rename.get(&idref)
5337 {
5338 xmref.set_attribute("idref", new)?;
5339 }
5340 }
5341 }
5342 Ok(())
5343 }
5344
5345 /// Makes the SVG ids under `root` unique in the document, as the svg schema types them
5346 /// (svg-core-attrib.rng:26-28). A picture TeX copies — `\copy`, `\usebox`, expl3's `\box_use:N`
5347 /// (tex.web:20952 copies a node list with its whatsits verbatim) — writes the ids the pgf driver
5348 /// fixed at digestion (pgfsys-latexml.def.ltxml:346-352, :678-714) once per copy; PDF has no ids,
5349 /// XML must not repeat them (suanpan-l3: 9,480 jing lines; thuaslogos: copies nested in one
5350 /// picture). Walks `root` in document order: an SVG element's `id` already handed out (or held by
5351 /// an `xml:id`) is renamed with the next free suffix, and every reference — `url(#X)` in any
5352 /// attribute, `href`/`xlink:href` `#X` — binds to the latest preceding definition of X under
5353 /// `root`; a reference to a definition elsewhere is left alone.
5354 ///
5355 /// A walked element is marked (`_svgid`, a bookkeeping attribute finalize strips): the math
5356 /// parser re-creates a picture where it moves it (`append_tree`), each re-creation closing a new
5357 /// `svg:svg` — the mark travels with the copied attributes, so a moved picture keeps its ids and
5358 /// references, where an unmarked one is a new copy. `append_clone` (the alignment split's MathFork,
5359 /// the frontmatter writer's contacts and notes) instead makes a second copy beside the original: it
5360 /// copies the svg `id` as Perl does and drops the mark, so the copy's own walk renames the ids it
5361 /// repeats (guard `perfect_kernel_batchne7::tikz_badges_in_frontmatter_contacts_keep_svg_ids`). A picture keeps Perl's
5362 /// ids unless an earlier element already holds them (a relocated footnote copy can). Perl writes
5363 /// the duplicates (KNOWN_PERL_ERRORS #391); the id map follows its `appendClone`
5364 /// (Document.pm:1920-1956). Guards: `perfect_kernel_batch57::copied_pictures_keep_unique_svg_ids`,
5365 /// `perfect_kernel_batch57::rebuilt_math_pictures_keep_their_svg_ids`.
5366 pub fn record_svg_ids(&mut self, root: &Node) -> Result<()> {
5367 use rustc_hash::FxHashMap;
5368 if root.has_attribute("_svgid") {
5369 return Ok(());
5370 }
5371 let mut in_effect: FxHashMap<String, String> = FxHashMap::default();
5372 for mut node in self.findnodes("descendant-or-self::*", Some(root)) {
5373 let is_svg = with_node_qname(&node, |qname| qname.starts_with("svg:"));
5374 if !is_svg {
5375 continue;
5376 }
5377 let walked = node.has_attribute("_svgid");
5378 if !walked {
5379 node.set_attribute("_svgid", "1")?;
5380 }
5381 if let Some(id) = node.get_attribute_no_ns("id") {
5382 let taken = !walked
5383 && (self.svg_ids.contains(&id)
5384 || self.idstore.contains_key(&id)
5385 || self.spilled_ids.contains(&id));
5386 let effective = if taken {
5387 let candidate = self.next_svg_id(&id);
5388 node.set_attribute("id", &candidate)?;
5389 candidate
5390 } else {
5391 id.clone()
5392 };
5393 self.svg_ids.insert(effective.clone());
5394 in_effect.insert(id, effective);
5395 }
5396 if in_effect.is_empty() {
5397 continue;
5398 }
5399 // `xlink:href` is set as a literal prefixed name until finalize declares the namespace
5400 // (`Document::set_attribute`), so the local name is the part after the prefix.
5401 for ((name, ns), value) in node.get_properties_ns() {
5402 let rebound = if value.contains("url(#") {
5403 let mut out = String::with_capacity(value.len());
5404 let mut rest = value.as_str();
5405 while let Some(at) = rest.find("url(#") {
5406 out.push_str(&rest[..at + 5]);
5407 rest = &rest[at + 5..];
5408 let end = rest.find(')').unwrap_or(rest.len());
5409 let target = &rest[..end];
5410 out.push_str(in_effect.get(target).map_or(target, String::as_str));
5411 rest = &rest[end..];
5412 }
5413 out.push_str(rest);
5414 out
5415 } else if name.rsplit(':').next() == Some("href")
5416 && let Some(target) = value.strip_prefix('#')
5417 && let Some(new) = in_effect.get(target)
5418 {
5419 s!("#{}", new)
5420 } else {
5421 continue;
5422 };
5423 if rebound != value {
5424 match ns {
5425 Some(ns) => node.set_attribute_ns(&name, &rebound, &ns)?,
5426 None => node.set_attribute(&name, &rebound)?,
5427 }
5428 }
5429 }
5430 }
5431 Ok(())
5432 }
5433
5434 /// The next free SVG id for a repeat of `id`: `id` with a `radix_alpha` suffix, as `modify_id`
5435 /// makes them, free of every SVG id, `xml:id` and spilled id.
5436 fn next_svg_id(&mut self, id: &str) -> String {
5437 let mut n = self.svg_id_suffixes.get(id).copied().unwrap_or(1);
5438 loop {
5439 let candidate = s!("{}{}", id, radix_alpha(n));
5440 n += 1;
5441 if !self.svg_ids.contains(&candidate)
5442 && !self.idstore.contains_key(&candidate)
5443 && !self.spilled_ids.contains(&candidate)
5444 {
5445 self.svg_id_suffixes.insert(id.to_string(), n);
5446 return candidate;
5447 }
5448 }
5449 }
5450
5451 pub fn unrecord_node_ids(&mut self, node: &Node) {
5452 for idnode in xml::descendant_or_self_elements(node, |n| n.has_attribute_ns("id", XML_NS)) {
5453 if let Some(id) = idnode.get_attribute_ns("id", XML_NS) {
5454 self.unrecord_id(&id);
5455 }
5456 }
5457 }
5458
5459 //**********************************************************************
5460 // Streaming (fragmented) conversion: spill closed subtrees to disk.
5461
5462 /// Spill closed subtrees to the segment store, freeing their DOM memory
5463 /// (streaming pass 1).
5464 ///
5465 /// Walks the SPINE — root element down to the current insertion element —
5466 /// and, at every level, spills the runs of closed element children that
5467 /// precede the open (spine) child: serialize in the pre-finalize form with
5468 /// the exact `(depth, noindent)` the eager serializer would use, write to
5469 /// `store`, record every spilled `xml:id`/label in `index`, purge the
5470 /// pointer-keyed registries (`idstore` via `unrecord_id`, `node_boxes` by
5471 /// key — freed nodes' pointers can be REUSED, so a stale entry is not just
5472 /// dangling but can mis-associate a box with a future node), replace the
5473 /// run with one `<_spilled_ ref="N"/>` placeholder, and unlink+free the
5474 /// nodes. Serialization at assembly time splices the processed segment
5475 /// where the placeholder sits, so document order, nesting and
5476 /// spine-attribute finality are preserved by construction.
5477 ///
5478 /// Two deliberate exclusions:
5479 /// * ROOT-level children spill only when sectional (`ROOT_SPILLABLE`):
5480 /// the frontmatter fallback and `maybe_promote_leading_title` operate on
5481 /// the leading non-sectional root children at end-of-build.
5482 /// * An open element's heading parts (`ltx:tags`, `ltx:title`, `ltx:toctitle`) never spill: its close-time
5483 /// hooks read them (a bibliography taking the place of the unit that heads it, latexml_engine sect11.rs
5484 /// `absorb_bibliography_heading`). One title per open element, so the memory cost is negligible.
5485 ///
5486 /// Returns the number of runs spilled.
5487 pub fn spill_closed_subtrees(&mut self, index: &mut crate::sxml::FragmentIndex) -> Result<usize> {
5488 debug_assert!(
5489 self.spill_store.is_some(),
5490 "spill_closed_subtrees needs the store attached (set_spill_store)"
5491 );
5492 let Some(root) = self.document.get_root_element() else {
5493 return Ok(0);
5494 };
5495 // The spine, root-first. The insertion point may be a text node; start
5496 // from its nearest element.
5497 let mut spine: Vec<Node> = Vec::new();
5498 let mut cursor = if self.node.get_type() == Some(NodeType::ElementNode) {
5499 Some(self.node.clone())
5500 } else {
5501 self.node.get_parent()
5502 };
5503 while let Some(n) = cursor {
5504 if n.get_type() != Some(NodeType::ElementNode) {
5505 break;
5506 }
5507 cursor = n.get_parent();
5508 spine.push(n);
5509 }
5510 spine.reverse();
5511 if spine.is_empty() && self.node.get_type() == Some(NodeType::DocumentNode) {
5512 // The ROOT itself has closed (`\end{document}` absorbed): everything
5513 // under it is a closed subtree now, so the spine is just the root and
5514 // every eligible child may spill. Without this case the FINAL spill of
5515 // a streaming conversion silently no-ops — the witness kept 27,400
5516 // formulae live into the spine tail this way and died there.
5517 spine.push(root.clone());
5518 }
5519 if spine.first() != Some(&root) {
5520 // The insertion point is outside the tree under the root: nothing is
5521 // safely classifiable as closed.
5522 return Ok(0);
5523 }
5524 let namespaces: Vec<(String, String)> = root
5525 .get_namespace_declarations()
5526 .iter()
5527 .map(|ns| (ns.get_prefix(), ns.get_href()))
5528 .collect();
5529 let aligning = Self::pending_aligning_context();
5530
5531 let mut runs_spilled = 0usize;
5532 // Every spine level INCLUDING the insertion element itself: at a legal
5533 // yield seam the insertion point routinely IS the root (between
5534 // top-level constructs), where a levels-above-only walk sees an empty
5535 // spine range and spills NOTHING — the witness leaked two thirds of its
5536 // chapters into the spine tail exactly this way. The insertion element's
5537 // children are complete, closed subtrees at a seam (the constructed-node
5538 // stacks expire between absorbs); its level simply has no barrier child.
5539 for level in 0..spine.len() {
5540 let parent = spine[level].clone();
5541 let barrier = spine.get(level + 1).cloned();
5542 // The serializer's recursion contract for children of `parent`
5543 // (`serialize_into`: depth+1, parent's schema-driven noindent).
5544 let noindent = {
5545 let parent_qname = get_node_qname(&parent);
5546 model::can_contain_sym(parent_qname, pin!("#PCDATA"))
5547 };
5548 // Do NOT spill the sole `ltx:text` child of an open `ltx:text` frame: that
5549 // is exactly the `auto_collapse_children` pattern (a redundant font/frame
5550 // wrapper merged into its parent at close). Spilling the child first leaves
5551 // the still-open frame with a `<_spilled_/>` placeholder, so the close-time
5552 // collapse sees a non-`ltx:text` child and skips the merge the EAGER path
5553 // performs — the streamed output then nests where eager collapses, breaking
5554 // the byte-identity invariant (witness: a `breaklines=true` framed
5555 // `Verbatim` whose parbox layer crosses a fragment seam, issue #702). The
5556 // protected node is a small wrapper; keeping it resident until the frame
5557 // closes costs negligible memory. Conservative on purpose: it also spares a
5558 // few wrappers `auto_collapse` would NOT merge (`_force_font` /
5559 // non-mergeable attr), which stay nested in BOTH paths anyway.
5560 let parent_is_collapse_frame = get_node_qname(&parent) == pin!("ltx:text") && {
5561 let elem_kids: Vec<Node> = parent
5562 .get_child_nodes()
5563 .into_iter()
5564 .filter(|c| c.get_type() == Some(NodeType::ElementNode) && !name_is(c, SPILL_PLACEHOLDER))
5565 .collect();
5566 elem_kids.len() == 1 && get_node_qname(&elem_kids[0]) == pin!("ltx:text")
5567 };
5568 let mut run: Vec<Node> = Vec::new();
5569 let pending_from = Self::pending_alignment_from(&parent, &aligning);
5570 let mut pending = matches!(pending_from, Some(None));
5571 for child in parent.get_child_nodes() {
5572 if Some(&child) == barrier.as_ref() {
5573 break;
5574 }
5575 // `prev` itself predates the declaration and may spill; its
5576 // followers may not.
5577 let is_pending_anchor = pending_from
5578 .as_ref()
5579 .is_some_and(|prev| prev.as_ref() == Some(&child));
5580 let eligible = child.get_type() == Some(NodeType::ElementNode)
5581 && !name_is(&child, SPILL_PLACEHOLDER)
5582 && !pending
5583 && !parent_is_collapse_frame
5584 && (level > 0 || ROOT_SPILLABLE.contains(&child.get_name().as_str()))
5585 // A bibliography pins its subtree in RAM: a LATER `\bibstyle`
5586 // writes attributes onto it through a doc-wide search (sweep
5587 // witness tests/structure/bibsect.tex). Rare and small.
5588 && self
5589 .findnodes("descendant-or-self::ltx:bibliography", Some(&child))
5590 .is_empty()
5591 // (`parent` is open: its heading stays until it closes)
5592 && !matches!(
5593 get_node_qname(&child),
5594 q if q == pin!("ltx:tags") || q == pin!("ltx:title") || q == pin!("ltx:toctitle")
5595 )
5596 // The unit right before the bibliography still open (the barrier) stays too: closing, the
5597 // bibliography may take its place (latexml_engine sect11.rs `absorb_bibliography_heading`).
5598 && !barrier.as_ref().is_some_and(|open| {
5599 get_node_qname(open) == pin!("ltx:bibliography")
5600 && child.get_next_element_sibling().as_ref() == Some(open)
5601 });
5602 if eligible {
5603 run.push(child);
5604 } else {
5605 if !run.is_empty() {
5606 // A non-eligible node interrupts the run: flush what precedes it so
5607 // each placeholder replaces exactly the contiguous nodes it stands
5608 // for, and document order is preserved around the interloper.
5609 runs_spilled += self.spill_run(&mut run, level + 1, noindent, &namespaces, index)?;
5610 }
5611 // A closed NON-sectional root child stays resident for the
5612 // frontmatter heuristics, but only its prose is read: spill the
5613 // rest of it (`spill_prose_free_children`).
5614 let resident_root_child = level == 0
5615 && child.get_type() == Some(NodeType::ElementNode)
5616 && !name_is(&child, SPILL_PLACEHOLDER)
5617 && !ROOT_SPILLABLE.contains(&child.get_name().as_str())
5618 && !ROOT_FRONTMATTER.contains(&child.get_name().as_str());
5619 if resident_root_child {
5620 runs_spilled +=
5621 self.spill_prose_free_children(&child, level + 2, &namespaces, &aligning, index)?;
5622 }
5623 }
5624 if is_pending_anchor {
5625 pending = true;
5626 }
5627 }
5628 if !run.is_empty() {
5629 runs_spilled += self.spill_run(&mut run, level + 1, noindent, &namespaces, index)?;
5630 }
5631 }
5632 Ok(runs_spilled)
5633 }
5634
5635 /// `ROOT_SPILLABLE` keeps a non-sectional root-level child resident for the
5636 /// end-of-build frontmatter heuristics (`maybe_promote_leading_title`,
5637 /// `maybe_dedup_leading_title_ink` in `base_utilities.rs`), which read the
5638 /// text and font of the leading `ltx:p` paragraphs and nothing else. So its
5639 /// closed element children that hold no prose paragraph spill like any other
5640 /// closed subtree — a paragraph inside drawn content (an `svg:foreignObject`
5641 /// label under `ltx:picture`) is not document prose. A child that does hold
5642 /// prose stays resident and is walked the same way, so a wrapper
5643 /// (`ltx:quote`, `ltx:logical-block`) keeps its paragraphs and sheds its
5644 /// pictures, tables and equations; an `ltx:p` itself is kept whole.
5645 ///
5646 /// Witness: pgf-PeriodicTable's eight sectionless `\pgfPT` tables (one
5647 /// `ltx:para > ltx:picture` each) climbed ~106 MB per table under
5648 /// `--streaming` with every picture-end seam honored, because nothing under
5649 /// a root-level `ltx:para` ever spilled and the sweep of `node_boxes` found
5650 /// every table's boxes still live.
5651 fn spill_prose_free_children(
5652 &mut self,
5653 parent: &Node,
5654 depth: usize,
5655 namespaces: &[(String, String)],
5656 aligning: &Option<(Node, Option<Node>)>,
5657 index: &mut crate::sxml::FragmentIndex,
5658 ) -> Result<usize> {
5659 let noindent = model::can_contain_sym(get_node_qname(parent), pin!("#PCDATA"));
5660 let mut runs_spilled = 0usize;
5661 let mut run: Vec<Node> = Vec::new();
5662 let mut resident: Vec<Node> = Vec::new();
5663 let pending_from = Self::pending_alignment_from(parent, aligning);
5664 let mut pending = matches!(pending_from, Some(None));
5665 for child in parent.get_child_nodes() {
5666 if pending_from
5667 .as_ref()
5668 .is_some_and(|prev| prev.as_ref() == Some(&child))
5669 {
5670 // `prev` itself predates the declaration and may spill; its followers
5671 // may not.
5672 pending = true;
5673 }
5674 // Only content the schema admits directly in a paragraph block
5675 // (`ltx:para` = Block/Misc/Meta: pictures, tabulars, equations, nested
5676 // blocks) may become a segment root: pass 2 re-parses a segment under
5677 // the `_lxfragment` wrapper, whose schema decisions cannot host inline
5678 // content (a spilled `ltx:sup` from a root-level `ltx:note` failed
5679 // there: tests/cluster_regressions/frontmatter_spconf_name).
5680 let is_element = child.get_type() == Some(NodeType::ElementNode)
5681 && !name_is(&child, SPILL_PLACEHOLDER)
5682 && model::can_contain_sym(pin!("ltx:para"), get_node_qname(&child));
5683 // Prose = an `ltx:p` outside any picture that holds non-space text
5684 // outside any picture. A text-less `ltx:p` — an inline centered picture
5685 // closing under `ltx:para > ltx:p > ltx:text > ltx:picture` (no `\par`
5686 // inside the paragraph; pgf-spectra LSE emits 141 spectra that way) —
5687 // is never a leading-title candidate (`maybe_dedup_leading_title_ink`
5688 // needs alphabetic text) and spills whole like a bare picture would.
5689 // Matching the `ltx:p` itself kept every such paragraph resident and
5690 // pinned its digested boxes in `node_boxes` (163,636 entries, ~4.4 GB
5691 // of the 4.8 GB fuse on LSE); guard
5692 // `inline_pictures_in_paragraphs_stay_memory_bounded`.
5693 let holds_prose = is_element && subtree_holds_prose(&child);
5694 let eligible = is_element
5695 && !holds_prose
5696 && !pending
5697 && self
5698 .findnodes("descendant-or-self::ltx:bibliography", Some(&child))
5699 .is_empty();
5700 if eligible {
5701 if std::env::var_os("LXML_TRACE_NODE_BOXES").is_some() {
5702 eprintln!(
5703 "streaming: prose-free spill of {} under {}",
5704 child.get_name(),
5705 parent.get_name()
5706 );
5707 }
5708 run.push(child);
5709 continue;
5710 }
5711 if !run.is_empty() {
5712 runs_spilled += self.spill_run(&mut run, depth, noindent, namespaces, index)?;
5713 }
5714 if holds_prose && !pending && get_node_qname(&child) != pin!("ltx:p") {
5715 resident.push(child);
5716 }
5717 }
5718 if !run.is_empty() {
5719 runs_spilled += self.spill_run(&mut run, depth, noindent, namespaces, index)?;
5720 }
5721 for wrapper in resident {
5722 runs_spilled +=
5723 self.spill_prose_free_children(&wrapper, depth + 1, namespaces, aligning, index)?;
5724 }
5725 if runs_spilled > 0 {
5726 self.release_wrapper_boxes(parent);
5727 }
5728 Ok(runs_spilled)
5729 }
5730
5731 /// The pending aligning context, if any: `\centering`/`\raggedright`/
5732 /// `\raggedleft` record the current element and its last child
5733 /// (`setup_aligning_context`, latex_constructs/mod.rs) and stamp the class
5734 /// on that element's LATER children when the group ends
5735 /// (`apply_aligning_context`). Those children are not closed yet.
5736 fn pending_aligning_context() -> Option<(Node, Option<Node>)> {
5737 let node = state::with_value("ALIGNING_NODE", |v| match v {
5738 Some(Stored::Node(n)) => Some(n.clone()),
5739 _ => None,
5740 })?;
5741 let prev = state::with_value("ALIGNING_PREV_CHILD", |v| match v {
5742 Some(Stored::Node(p)) => Some(p.clone()),
5743 _ => None,
5744 });
5745 Some((node, prev))
5746 }
5747
5748 /// For `parent` under a pending aligning context: `Some(prev)` when the
5749 /// context's children after `prev` (all of them for `Some(None)`) are still
5750 /// to be stamped and must stay resident. Spilling them frees the anchor, and
5751 /// a later node allocated at the same address matched it instead
5752 /// (tikz-network under tufte-book: `ltx_align_left` moved from the title
5753 /// block and the first chapter to a later chapter and an appendix).
5754 fn pending_alignment_from(
5755 parent: &Node,
5756 aligning: &Option<(Node, Option<Node>)>,
5757 ) -> Option<Option<Node>> {
5758 aligning
5759 .as_ref()
5760 .filter(|(node, _)| node == parent)
5761 .map(|(_, prev)| prev.clone())
5762 }
5763
5764 /// A resident wrapper's recorded box owns what was just spilled beneath it:
5765 /// every element a constructor opens records the SAME whatsit
5766 /// (`set_node_box` on `ltx:para`, `ltx:p`, `ltx:picture`, `svg:svg` alike),
5767 /// so dropping the spilled nodes' entries frees nothing while the wrapper's
5768 /// entry still holds the picture whatsit and, through it, the whole box tree
5769 /// (the n8 witness kept every table alive this way: the sweep found the
5770 /// wrappers live, and their box was the table). Drop the entries of the
5771 /// wrapper and its ancestors below the root; the root's own box (the
5772 /// `\begin{document}` whatsit) owns no body content. A wrapper's box is
5773 /// consulted only while it is the insertion point's ancestor, which a closed
5774 /// root-level child never is again.
5775 fn release_wrapper_boxes(&mut self, wrapper: &Node) {
5776 let mut cursor = Some(wrapper.clone());
5777 while let Some(n) = cursor {
5778 if n.get_type() != Some(NodeType::ElementNode) || get_node_qname(&n) == pin!("ltx:document") {
5779 break;
5780 }
5781 self.node_boxes.remove(&n.to_hashable());
5782 cursor = n.get_parent();
5783 }
5784 }
5785
5786 /// Spill one contiguous run of closed sibling elements as a single segment.
5787 /// Consumes (drains) `run`; on success the nodes are unlinked and freed.
5788 /// Serialized-bytes ceiling per SEGMENT. A spill run is chunked so no
5789 /// segment exceeds it (approximately — a single oversized subtree still
5790 /// becomes one segment): pass 2 re-materializes a segment WHOLE, so the
5791 /// segment size bounds pass-2 peak memory the way the yield budget bounds
5792 /// pass 1. The witness's first RSS-triggered yield once spilled half the
5793 /// document as ONE 512 MB segment, and pass 2 died re-parsing it.
5794 fn segment_chunk_bytes() -> usize {
5795 // Calibration override (`LATEXML_SEGMENT_CHUNK_MIB`), deliberately env-only
5796 // and NOT a CLI flag — the same reasoning as `LATEXML_SPILL_AT_MIB`, and
5797 // for the same reason: MAX below is an ARGUED constant, not a measured one.
5798 //
5799 // Its stated basis is a TIME claim ("the point past which a single
5800 // segment's re-parse dominates pass 2"), but the pass-2 tail is linear in
5801 // fragment size — `prune_dangling_split_xmrefs`, `prune_xmduals`,
5802 // `mark_xmnode_visibility` and `cleanup_unreferenced_xmtok_ids` are each
5803 // one `findnodes` plus an O(1)-per-node loop, `finalize_subtree` is a
5804 // recursive walk, and the rewrite rule set is fixed. Larger segments
5805 // should also SUIT the allocator, which is the largest single profile
5806 // category (~16.5%): fewer, bigger alloc/free cycles.
5807 //
5808 // Note what the derivation below wants: at --max-memory 48000 it computes
5809 // watermark/72 = 166 MB and MAX then clamps it to 32 MB. This knob exists
5810 // so that ceiling can be swept rather than argued.
5811 if let Some(mib) = std::env::var("LATEXML_SEGMENT_CHUNK_MIB")
5812 .ok()
5813 .and_then(|v| v.parse::<usize>().ok())
5814 .filter(|mib| *mib > 0)
5815 {
5816 return mib.saturating_mul(1024 * 1024);
5817 }
5818 /// Validated on the 131 MB witness. The accompanying claim that a single
5819 /// segment's re-parse dominates pass 2 past this point is NOT substantiated
5820 /// by the pass-2 tail, which is linear — see the override above.
5821 const MAX: usize = 32 * 1024 * 1024;
5822 /// Below this, per-segment overhead (parse, index merge, reserialize)
5823 /// outweighs the memory saved.
5824 const MIN: usize = 4 * 1024 * 1024;
5825 /// Serialized bytes → live DOM, measured: 18.6 MB of core XML
5826 /// materialized as ~1,346 MB of libxml2 DOM on a witness slice.
5827 const DOM_EXPANSION: u64 = 72;
5828 match crate::stomach::spill_watermark_bytes() {
5829 // Pass 2 re-materializes ONE segment whole, so a chunk must fit the
5830 // same watermark pass 1 respects — otherwise the phase that exists to
5831 // bound memory becomes the phase that blows it on a small machine.
5832 Some(watermark) => ((watermark / DOM_EXPANSION) as usize).clamp(MIN, MAX),
5833 None => MAX,
5834 }
5835 }
5836
5837 fn spill_run(
5838 &mut self,
5839 run: &mut Vec<Node>,
5840 depth: usize,
5841 noindent: bool,
5842 namespaces: &[(String, String)],
5843 index: &mut crate::sxml::FragmentIndex,
5844 ) -> Result<usize> {
5845 use crate::sxml::SegmentMeta;
5846 // An element whose children are exclusively EMPTY text nodes serializes
5847 // as `<p></p>` — indistinguishable, after a parse round-trip, from a
5848 // childless `<p/>`. Mark such elements before serializing so pass 2 can
5849 // restore the empty text child and keep the round-trip exact (sweep
5850 // witness tests/fonts/abxtest.tex).
5851 fn mark_empty_text_elements(node: &Node) {
5852 if node.get_type() != Some(NodeType::ElementNode) {
5853 return;
5854 }
5855 let children = node.get_child_nodes();
5856 if !children.is_empty()
5857 && children
5858 .iter()
5859 .all(|c| c.get_type() == Some(NodeType::TextNode) && c.get_content().is_empty())
5860 {
5861 let mut n = node.clone();
5862 let _ = n.set_attribute("_lx_empty_text", "1");
5863 }
5864 for child in children {
5865 mark_empty_text_elements(&child);
5866 }
5867 }
5868 for node in run.iter() {
5869 mark_empty_text_elements(node);
5870 }
5871 if let Some(observe) = self.spill_observer {
5872 for node in run.iter() {
5873 observe(self, node);
5874 }
5875 }
5876 // Stamp the DIGESTED BOX's math-font verdict on XMArg elements before
5877 // their boxes are purged: the FLOATSUPERSCRIPT rewrite (tex_math.rs)
5878 // decides `<text font="italic">` wrapping from the box font's family,
5879 // and a fragment re-materialized in pass 2 has no boxes. An attr carries
5880 // the EXACT verdict (an ancestor-`_font` approximation mis-wrapped
5881 // text-mode superscripts — sweep witness tests/math/niceunits.tex).
5882 for node in run.iter() {
5883 for mut xmarg in self.findnodes("descendant-or-self::ltx:XMArg", Some(node)) {
5884 if let Some(tbox) = self.get_node_box(&xmarg)
5885 && let Ok(Some(font)) = tbox.get_font()
5886 && font
5887 .get_family()
5888 .map(|f| f.as_ref() == "math")
5889 .unwrap_or(false)
5890 {
5891 let _ = xmarg.set_attribute("_boxfont_math", "1");
5892 }
5893 }
5894 }
5895
5896 // What eager finalize reads above the run, for pass 2: the font it declares there, and the element it mints the
5897 // run's id-less top nodes under (2507.13358).
5898 let spill_parent = run.first().and_then(|n| n.get_parent());
5899 let context_font = spill_parent.as_ref().map(|parent| {
5900 let font = self.finalize_context_font(parent);
5901 let key = font.to_hashable();
5902 self.node_fonts.entry(key).or_insert(font);
5903 key.to_string()
5904 });
5905 let anchor = spill_parent.as_ref().and_then(Self::spill_anchor);
5906 if let Some(anchor) = &anchor {
5907 self.spill_anchors.insert(anchor.clone());
5908 }
5909 // Chunk the run so each segment stays under `segment_chunk_bytes()` of
5910 // serialized text; every chunk gets its own segment + placeholder, so
5911 // document order is preserved chunk-by-chunk.
5912 let chunk_ceiling = Self::segment_chunk_bytes();
5913 let mut runs_spilled = 0usize;
5914 let mut chunk: Vec<Node> = Vec::new();
5915 let mut xml = String::new();
5916 let all: Vec<Node> = std::mem::take(run);
5917 let total = all.len();
5918 for (i, node) in all.into_iter().enumerate() {
5919 // A spilled subtree can CONTAIN placeholders from earlier, deeper
5920 // spills (a closing section swallows its paragraphs' placeholders).
5921 // They serialize LITERALLY (`literal_placeholders` is set for all of
5922 // pass 1) and the final assembly's splice resolves them recursively —
5923 // inlining them here instead once rebuilt an 841 MB and a 1.85 GB
5924 // segment out of chapter shells on the 131 MB witness, and pass 2
5925 // died re-materializing them.
5926 debug_assert!(
5927 self.literal_placeholders,
5928 "spill_run must serialize placeholders literally (set for all of pass 1)"
5929 );
5930 self.serialize_into(&mut xml, node.as_readonly(), depth, noindent, false);
5931 chunk.push(node);
5932 let last = i + 1 == total;
5933 if xml.len() >= chunk_ceiling || last {
5934 let meta = SegmentMeta {
5935 depth,
5936 noindent,
5937 font: context_font.clone(),
5938 anchor: anchor.clone(),
5939 namespaces: namespaces.to_vec(),
5940 parent: chunk
5941 .first()
5942 .and_then(|n| n.get_parent())
5943 .map(|p| arena::to_string(get_node_qname(&p))),
5944 ancestors: {
5945 // Every ancestor xml:id: a scope rooted at one of these covers
5946 // the whole fragment (see SegmentMeta::ancestors).
5947 let mut ids = Vec::new();
5948 let mut cur = chunk.first().and_then(|n| n.get_parent());
5949 while let Some(n) = cur {
5950 // Both attribute forms — constructed ancestors carry the plain
5951 // one (see `node_xml_id_any_form`); a namespace-only read left
5952 // these lists near-empty, so label/id-scoped rules could not
5953 // cover their fragments.
5954 if let Some(id) = Self::node_xml_id_any_form(&n) {
5955 ids.push(id);
5956 }
5957 cur = n.get_parent();
5958 }
5959 ids
5960 },
5961 };
5962 let store = self
5963 .spill_store
5964 .as_mut()
5965 .expect("checked at spill_closed_subtrees entry");
5966 let seg = store.write_segment(&xml, meta)?;
5967 xml.clear();
5968 // Index + purge while the nodes are still alive, then placeholder +
5969 // free.
5970 for node in chunk.iter() {
5971 self.index_and_purge_spilled(node, seg, index);
5972 }
5973 let spill_error = |details: String| {
5974 Error::from(ErrorData {
5975 target: ErrorTarget::Document,
5976 category: ErrorCategory::Libxml,
5977 message: s!("segment staging: {}", details),
5978 })
5979 };
5980 let mut placeholder = Node::new(SPILL_PLACEHOLDER, None, &self.document)
5981 .map_err(|()| spill_error(s!("cannot create the placeholder node")))?;
5982 placeholder
5983 .set_attribute("ref", &seg.to_string())
5984 .map_err(|e| spill_error(s!("cannot mark the placeholder: {e}")))?;
5985 // Record the LAST spilled sibling's qname: build-time hooks that
5986 // consult a previous element sibling (prune_empty_para's
5987 // was-I-first test — sweep witness tests/alignment/colortbls.tex)
5988 // would otherwise see the placeholder where eager sees that node.
5989 // Never serialized — assembly splices the segment text instead.
5990 if let Some(last) = chunk.last() {
5991 placeholder
5992 .set_attribute("last", &arena::to_string(get_node_qname(last)))
5993 .map_err(|e| spill_error(s!("cannot mark the placeholder: {e}")))?;
5994 }
5995 if chunk.iter().all(prints_nothing) {
5996 placeholder
5997 .set_attribute(SPILLED_INKLESS, "1")
5998 .map_err(|e| spill_error(s!("cannot mark the placeholder: {e}")))?;
5999 }
6000 chunk
6001 .first_mut()
6002 .expect("a flushed chunk is non-empty")
6003 .add_prev_sibling(&mut placeholder)
6004 .map_err(|e| spill_error(s!("cannot insert the placeholder: {e}")))?;
6005 for node in chunk.drain(..) {
6006 // Actually FREE the spilled subtree (unlink alone leaks — see
6007 // Node::free_subtree). Its ids were unrecorded by
6008 // index_and_purge_spilled above; discard_subtree re-purges
6009 // node_boxes (cheap) and reclaims the C memory, which is the whole
6010 // point of the spill.
6011 self.discard_subtree(node);
6012 }
6013 SPILLED_SEGMENTS.set(SPILLED_SEGMENTS.get() + 1);
6014 runs_spilled += 1;
6015 }
6016 }
6017 Ok(runs_spilled)
6018 }
6019
6020 /// The nearest `xml:id` on `node` or an ancestor below the root ([`SegmentMeta::anchor`](crate::sxml::SegmentMeta)).
6021 fn spill_anchor(node: &Node) -> Option<String> {
6022 let mut cur = Some(node.clone());
6023 while let Some(n) = cur {
6024 let parent = n
6025 .get_parent()
6026 .filter(|p| p.get_type() == Some(NodeType::ElementNode));
6027 parent.as_ref()?;
6028 if let Some(id) = Self::node_xml_id_any_form(&n) {
6029 return Some(id);
6030 }
6031 cur = parent;
6032 }
6033 None
6034 }
6035
6036 /// The font `finalize_rec` declares for `parent`'s children: from the text default, each ancestor's font
6037 /// attributes its element can carry, root first ([`SegmentMeta::font`](crate::sxml::SegmentMeta)).
6038 fn finalize_context_font(&self, parent: &Node) -> Font {
6039 let mut chain = Vec::new();
6040 let mut cur = Some(parent.clone());
6041 while let Some(n) = cur.filter(|n| n.get_type() == Some(NodeType::ElementNode)) {
6042 cur = n.get_parent();
6043 chain.push(n);
6044 }
6045 let mut declared = Font::text_default();
6046 for node in chain.iter().rev() {
6047 if node.has_attribute("_standalone_font") {
6048 declared = Font::text_default();
6049 }
6050 if self.has_node_font(node) {
6051 let qname = get_node_qname(node);
6052 for (key, (_, properties)) in self.get_node_font(node).relative_to(&declared) {
6053 if model::can_have_attribute(qname, arena::pin(&key)) {
6054 declared = declared.merge_ref(&properties);
6055 }
6056 }
6057 }
6058 if let Some(anchor) = node.get_attribute("_font_anchor") {
6059 declared = declared.merge_ref(&Font {
6060 size: Some(anchor.parse::<f64>().unwrap_or(10.0)),
6061 ..Font::default()
6062 });
6063 }
6064 }
6065 declared
6066 }
6067
6068 /// Streaming, after pass 1: every spill anchor's `_ID_counter_*` attributes as construction left them — recorded
6069 /// when it spilled, else read from the spine. Pass 2 continues them; [`Self::set_id_counters`] hands them back.
6070 pub fn take_spill_anchor_counters(
6071 &mut self,
6072 ) -> rustc_hash::FxHashMap<String, Vec<(String, String)>> {
6073 let mut counters = std::mem::take(&mut self.spilled_anchor_counters);
6074 for id in std::mem::take(&mut self.spill_anchors) {
6075 if let Some(node) = self.lookup_id(&id) {
6076 counters.insert(id, id_counters(node));
6077 }
6078 }
6079 counters
6080 }
6081
6082 /// Set the `_ID_counter_*` attributes of the element `id` names, if it is in this document.
6083 pub fn set_id_counters(&mut self, id: &str, counters: &[(String, String)]) {
6084 if let Some(node) = self.idstore.get_mut(id) {
6085 for (key, value) in counters {
6086 let _ = node.set_attribute(key, value);
6087 }
6088 }
6089 }
6090
6091 /// A node's `xml:id`, namespace-aware with a defensive plain-name fallback.
6092 ///
6093 /// MECHANISM CORRECTION (2026-08-04, empirically probed against libxml
6094 /// 0.3.21): `set_attribute("xml:id", …)` DOES namespace the attribute
6095 /// (`xmlSetProp` resolves the predefined `xml` prefix), so builder-
6096 /// CONSTRUCTED nodes and PARSED nodes both store the namespaced form and
6097 /// `get_attribute_ns("id", XML_NS)` reads both; no code path in this
6098 /// workspace produces a literal-named "xml:id" attribute. The earlier
6099 /// claim here that constructed nodes carry the plain form does not
6100 /// reproduce. The 131 MB-book witness (2026-08-01: spill-time indexing
6101 /// registered 865 of 23,654 labels) was fixed by the commit that added
6102 /// this helper, but the missing-id mechanism was misattributed; the bare
6103 /// fallback is kept as belt (it is dead under the probed model, and
6104 /// harmless).
6105 pub(crate) fn node_xml_id_any_form(node: &Node) -> Option<String> {
6106 node
6107 .get_attribute_ns("id", XML_NS)
6108 .or_else(|| node.get_attribute("xml:id"))
6109 }
6110
6111 /// Record a spilled subtree's ids and labels in the fragment index, and
6112 /// purge every registry holding a handle or pointer into it.
6113 fn index_and_purge_spilled(
6114 &mut self,
6115 node: &Node,
6116 seg: crate::sxml::SegmentId,
6117 index: &mut crate::sxml::FragmentIndex,
6118 ) {
6119 // Box entries exist for TEXT nodes too (see purge_node_boxes_rec) —
6120 // purge before the element gate or a prose-heavy document leaks a
6121 // pinned `Digested` per spilled text node.
6122 self.node_boxes.remove(&node.to_hashable());
6123 if node.get_type() != Some(NodeType::ElementNode) {
6124 return;
6125 }
6126 // Namespace prefixes this subtree uses leave the resident DOM with it;
6127 // the root declaration pass consults `spilled_ns_prefixes` for them.
6128 if let Some(ns) = node.get_namespace() {
6129 let prefix = ns.get_prefix();
6130 if !prefix.is_empty() {
6131 self.spilled_ns_prefixes.insert(prefix);
6132 }
6133 }
6134 for (key, _) in node.get_attributes() {
6135 if let Some(colon) = key.find(':') {
6136 let prefix = &key[..colon];
6137 if !self.spilled_ns_prefixes.contains(prefix) {
6138 self.spilled_ns_prefixes.insert(prefix.to_string());
6139 }
6140 }
6141 }
6142 for attr in [
6143 "about", "resource", "property", "typeof", "rel", "rev", "datatype",
6144 ] {
6145 if let Some(value) = node.get_attribute(attr) {
6146 for term in value.split_whitespace() {
6147 if let Some(colon) = term.find(':') {
6148 index.record_rdfa_prefix(&term[..colon], "");
6149 }
6150 }
6151 }
6152 }
6153 let id_opt = Self::node_xml_id_any_form(node);
6154 if let Some(id) = &id_opt {
6155 index.record_id(id, seg);
6156 self.unrecord_id(id);
6157 self.spilled_ids.insert(id.clone());
6158 if self.spill_anchors.remove(id) {
6159 self
6160 .spilled_anchor_counters
6161 .insert(id.clone(), id_counters(node));
6162 }
6163 if let Some(labels) = node.get_attribute("labels") {
6164 for label in labels.split_whitespace() {
6165 index.record_label(label, id);
6166 }
6167 }
6168 }
6169 for child in node.get_child_nodes() {
6170 self.index_and_purge_spilled(&child, seg, index);
6171 }
6172 }
6173
6174 // `strip_indentation_whitespace` lived here until `spill_flat` (its only
6175 // caller was streaming pass 2): it deleted the whitespace-only text nodes
6176 // our own pretty-printer had added to spill segments, via the same
6177 // `model::can_contain_sym(#PCDATA)` query the serializer indents by. Flat
6178 // spill serialization means those nodes are never created, so the
6179 // generate-then-undo pair is gone. It also `unlink_node`d rather than
6180 // freed — the orphan-leak trap — so do not resurrect it as-is.
6181
6182 /// Remove the pointer-keyed `node_boxes` entries for `node` and its whole
6183 /// subtree. MANDATORY before freeing nodes mid-conversion: a freed node's
6184 /// address is REUSED by later allocations, and a stale entry then
6185 /// mis-associates the old box (and its font) with an unrelated new node —
6186 /// observed as spurious `<text font="italic">` wrappers the moment the
6187 /// math parser started freeing replaced trees promptly.
6188 pub fn purge_node_boxes_rec(&mut self, node: &Node) {
6189 // EVERY node type can carry an entry: absorbing text records the box
6190 // against the TEXT node (`openText_internal`), and `get_node_box` never
6191 // reads those — but an unpurged one pins its whole `Digested` forever.
6192 // Measured: the dominant pass-1 creep on a 131 MB prose-heavy book
6193 // (~11 GB of orphaned text-node boxes; every probed collection flat).
6194 self.node_boxes.remove(&node.to_hashable());
6195 if node.get_type() != Some(NodeType::ElementNode) {
6196 return; // only elements have children to descend into
6197 }
6198 for child in node.get_child_nodes() {
6199 self.purge_node_boxes_rec(&child);
6200 }
6201 }
6202
6203 /// Forget what the document keeps about a subtree about to be freed: its `node_boxes` entries and the idstore
6204 /// entries that point INTO it. Not `unrecord_node_ids`: a discard often follows a copy (`append_tree`) that
6205 /// re-recorded the SAME id strings for the copies, and those live entries stay. One walk, as `purge_node_boxes_rec`.
6206 fn forget_freed_subtree(&mut self, node: &Node) {
6207 self.node_boxes.remove(&node.to_hashable());
6208 if node.get_type() != Some(NodeType::ElementNode) {
6209 return;
6210 }
6211 // (`c"id"` reads `xml:id` without allocating; the pointer comparison keeps it exact)
6212 if let Some(Some(id)) = node.with_attribute(c"id", |id| {
6213 (self.idstore.get(id) == Some(node)).then(|| id.to_owned())
6214 }) {
6215 self.idstore.remove(&id);
6216 }
6217 for child in node.get_child_nodes() {
6218 self.forget_freed_subtree(&child);
6219 }
6220 }
6221
6222 /// Perl `Document.pm:removeNode` L1783-1792, "Don't remove insertion point!": a point at or inside `subtree`
6223 /// moves to `parent`. When the subtree is already detached it moves to the root element: our own choice (Perl's
6224 /// `removeNode` assumes a parent, :1793, and the math parser's unbound children, MathParser.pm:330, keep its point
6225 /// alive in the garbage tree); nothing is built after the post-build math parse, so no content moves (issue #790).
6226 fn keep_point_out_of(&mut self, subtree: &Node, parent: Option<&Node>) {
6227 if xml::is_descendant_or_self(&self.node, subtree)
6228 && let Some(target) = parent.cloned().or_else(|| self.document.get_root_element())
6229 {
6230 self.set_node(&target);
6231 }
6232 }
6233
6234 /// Discard a garbage subtree for good: purge the pointer-keyed
6235 /// `node_boxes` entries, then free the C memory NOW via the fork's
6236 /// `Node::free_subtree` — the missing half of every unlink-to-discard
6237 /// site (rust-libxml Linkage: a doc-created node that is unlinked but
6238 /// never re-attached is freed by NOBODY; math parsing discards thousands
6239 /// of replaced subtrees per document, measured ~1.4 MB/formula, ~1.8 GB
6240 /// retained per 32 MB streaming segment). `free_subtree` also
6241 /// neutralizes every live wrapper into the subtree, so stray clones in
6242 /// long-lived collections (`constructed_nodes`, an idstore epoch) go
6243 /// inert instead of firing a deferred `xmlFreeNode` after the document
6244 /// itself is gone.
6245 ///
6246 /// The idstore entries that point INTO the subtree are dropped with its boxes (`forget_freed_subtree`): a math
6247 /// phantom's dropped hint holding an XMDual's ids left them pointing at freed nodes, and the next record of such an
6248 /// id renamed a live token against a `<#BrokenNode>` (witnesses 2606.13225, 2605.00485, 2605.29246).
6249 ///
6250 /// PRECONDITION (the caller's contract): no live handle into the subtree is used afterwards.
6251 pub fn discard_subtree(&mut self, node: Node) {
6252 // The subtree is still alive here, so its ancestor walks are safe (#790: 0710.4421 freed the point).
6253 self.keep_point_out_of(&node, node.get_parent().as_ref());
6254 if self
6255 .text_run_font
6256 .as_ref()
6257 .is_some_and(|(run, ..)| xml::is_descendant_or_self(run, &node))
6258 {
6259 self.text_run_font = None;
6260 }
6261 self.forget_freed_subtree(&node);
6262 // The last ligated text node may be in the freed subtree, and libxml may hand its address to the next node
6263 // created: forget it (the next close then ligates from the start, as Perl's).
6264 self.ligated_text = None;
6265 node.free_subtree();
6266 }
6267
6268 /// Drop every `node_boxes` entry whose node is no longer IN this document
6269 /// tree (streaming pass 1's self-healing sweep). Entries are written for
6270 /// every constructed node and purged at the spill/discard chokepoints —
6271 /// but dozens of build-time discard paths (alignment rearrangement above
6272 /// all: 105k `align` environments on the 131 MB witness) detach nodes
6273 /// without purging, and each stale entry pins a whole `Digested` box tree.
6274 /// Measured: ~518k stale entries before the FIRST spill, growing past
6275 /// 1.75M — the dominant residual pass-1 creep after the C-side frees.
6276 /// A mark-and-retain against the live tree is immune to every such path,
6277 /// including future ones. The mark phase walks the whole live DOM, so the
6278 /// streaming driver gates it on `node_boxes` growth (core_interface.rs).
6279 pub fn sweep_stale_node_boxes(&mut self) {
6280 let t_start = std::time::Instant::now();
6281 fn mark(node: &Node, live: &mut rustc_hash::FxHashSet<usize>) {
6282 live.insert(node.to_hashable());
6283 if node.get_type() == Some(NodeType::ElementNode) {
6284 for child in node.get_child_nodes() {
6285 mark(&child, live);
6286 }
6287 }
6288 }
6289 let mut live: rustc_hash::FxHashSet<usize> = rustc_hash::FxHashSet::default();
6290 if let Some(root) = self.document.get_root_element() {
6291 mark(&root, &mut live);
6292 }
6293 let t_mark = t_start.elapsed();
6294 let before = self.node_boxes.len();
6295 let t_retain_start = std::time::Instant::now();
6296 self.node_boxes.retain(|k, _| live.contains(k));
6297 let t_retain = t_retain_start.elapsed();
6298 let after = self.node_boxes.len();
6299 self.last_swept_node_boxes_len = after;
6300 let total = t_start.elapsed();
6301 if std::env::var_os("LXML_TRACE_NODE_BOXES").is_some() {
6302 eprintln!(
6303 "streaming: node_boxes sweep {before} -> {after} (live: {}, dropped: {}) | mark: {t_mark:?}, retain: {t_retain:?}, total: {total:?}",
6304 live.len(),
6305 before - after
6306 );
6307 }
6308 }
6309
6310 /// Attach the processed-segment store for serialization: from here on,
6311 /// `serialize_into` splices each segment's output text where its
6312 /// placeholder sits (streaming assembly).
6313 pub fn set_spill_store(&mut self, store: crate::sxml::SegmentStore) {
6314 self.spill_store = Some(store);
6315 }
6316
6317 /// Streaming pass 1 switch: defer (true) or restore (false) the ROOT
6318 /// element's `after_open` hook dispatch. See the field docs.
6319 pub fn set_defer_root_after_open(&mut self, defer: bool) { self.defer_root_after_open = defer; }
6320
6321 /// Is the root's late-hook dispatch currently deferred (streaming pass 1)?
6322 /// Engine bindings consult this to defer digestion-state-dependent
6323 /// insertions (frontmatter) to end-of-digestion.
6324 pub fn root_after_open_deferred(&self) -> bool { self.defer_root_after_open }
6325
6326 /// Open a `ltx:_Capture_` wrapper at the TOP of the root — after the last
6327 /// existing `ltx:resource` child (resources lead the document in the eager
6328 /// output), else as the first child. Shared insertion context for the
6329 /// streaming-mode operations that must place content where an
6330 /// empty-just-opened root would have put it.
6331 fn open_root_top_capture(&mut self) -> Result<Option<Node>> {
6332 let Some(mut root) = self.document.get_root_element() else {
6333 return Ok(None);
6334 };
6335 let mut last_resource: Option<Node> = None;
6336 for child in root.get_child_nodes() {
6337 if child.get_type() == Some(NodeType::ElementNode) && name_is(&child, "resource") {
6338 last_resource = Some(child);
6339 }
6340 }
6341 let wrapper = match last_resource {
6342 Some(r) => match r.get_next_sibling() {
6343 Some(next) => self.insert_element_before(&next, "ltx:_Capture_", None)?,
6344 None => self.open_element_at(&mut root, "ltx:_Capture_", None, None)?,
6345 },
6346 None => match root.get_first_child() {
6347 Some(first) => self.insert_element_before(&first, "ltx:_Capture_", None)?,
6348 None => self.open_element_at(&mut root, "ltx:_Capture_", None, None)?,
6349 },
6350 };
6351 Ok(Some(wrapper))
6352 }
6353
6354 /// Streaming pass 1: fold freshly queued resources into the live document
6355 /// as they arrive, at the top of the root. Perl's own contract
6356 /// (`Package.pm:RequireResource`): with a live document, `addResource`
6357 /// inserts DIRECTLY; only a document-less preamble queues. The eager path
6358 /// keeps the queue until the root's `after_open` because its build starts
6359 /// post-digestion; under streaming that drain is deferred to
6360 /// end-of-digestion, and mid-digestion consumers — the frontmatter
6361 /// fallback's `/ltx:document/ltx:resource[last()]` anchor — need the
6362 /// resources already placed.
6363 pub fn process_pending_resources_at_top(&mut self) -> Result<()> {
6364 let resources: Vec<Resource> = state::take_pending_resources();
6365 if resources.is_empty() {
6366 state::reset_pending_resources();
6367 return Ok(());
6368 }
6369 let Some(wrapper) = self.open_root_top_capture()? else {
6370 // No root yet: re-queue for the next absorb (or the deferred drain).
6371 for resource in resources {
6372 state::push_pending_resource(resource);
6373 }
6374 return Ok(());
6375 };
6376 let savenode = self.node.clone();
6377 self.set_node(&wrapper);
6378 for resource in resources {
6379 self.add_resource(resource)?;
6380 }
6381 state::reset_pending_resources();
6382 self.unwrap_nodes(wrapper)?;
6383 self.set_node(&savenode);
6384 Ok(())
6385 }
6386
6387 /// Streaming: dispatch the ROOT's deferred after-open hooks at
6388 /// end-of-digestion — the eager timing (build starts only after digestion
6389 /// ends) — with the insertion point at the TOP of the root, as if it had
6390 /// just opened empty. `after_open` itself cannot be used here: it pins the
6391 /// current node to the dispatched element, so everything the hooks insert
6392 /// (resources, frontmatter) would APPEND after the built content instead
6393 /// of leading it. A `ltx:_Capture_` wrapper as first child recreates the
6394 /// empty-root insertion context (the frontmatter fallback's own
6395 /// technique), and is unwrapped afterwards.
6396 pub fn dispatch_deferred_root_hooks(&mut self) -> Result<()> {
6397 debug_assert!(
6398 !self.defer_root_after_open,
6399 "clear the deferral before dispatching"
6400 );
6401 let Some(mut root) = self.document.get_root_element() else {
6402 return Ok(());
6403 };
6404 let savenode = self.node.clone();
6405 let Some(wrapper) = self.open_root_top_capture()? else {
6406 return Ok(());
6407 };
6408 self.set_node(&wrapper);
6409 let qname = get_node_qname(&root);
6410 let box_opt = self.get_node_box(&root);
6411 let (_prompt, late) = self.get_tag_action_list_parts(qname, TagOptionName::AfterOpen);
6412 for action in late {
6413 action(self, &mut root, box_opt.as_ref())?;
6414 }
6415 self.unwrap_nodes(wrapper)?;
6416 self.set_node(&savenode);
6417 Ok(())
6418 }
6419
6420 /// Merge RDFa prefixes recorded from spilled content, so the root's
6421 /// `prefix=` attribute covers usages the live-DOM scan can no longer see.
6422 pub fn add_extra_rdfa_prefixes<'a>(&mut self, prefixes: impl Iterator<Item = &'a str>) {
6423 self.extra_rdfa_prefixes.extend(prefixes.map(String::from));
6424 }
6425
6426 /// Detach the spill store (the streaming driver takes it out for pass 2 —
6427 /// which mutates segments while fragment documents exist independently —
6428 /// and re-attaches it for assembly).
6429 pub fn take_spill_store(&mut self) -> Option<crate::sxml::SegmentStore> {
6430 self.spill_store.take()
6431 }
6432
6433 /// Discard the in-memory `idstore` cache and rebuild it from the
6434 /// current DOM state. Historically guarded the 1605.08055 SIGSEGV
6435 /// where `mark_xmnode_visibility` dereferenced dangling lookup_id
6436 /// entries while recursing through XMRef targets.
6437 ///
6438 /// As of cycle 72, the 5 call sites that previously dropped nodes
6439 /// without unrecord_id — math-parser `replace_tree` at
6440 /// parser.rs:456/690 (cascades via remove_node) and `unbind_node`
6441 /// loops at parser.rs:639/856 + rewrite.rs:522 (all have
6442 /// preceding unrecord_node_ids guards) — are ID-safe. This rebuild
6443 /// is retained as a belt-and-suspenders probe until the
6444 /// 1605.08055 verification per SYNC_STATUS.md D3b lands.
6445 ///
6446 /// The rebuild is a DOM walk, so live id uniqueness is restored
6447 /// alongside — duplicates already in DOM are resolved with
6448 /// `modify_id`, matching `record_node_ids` semantics.
6449 pub fn rebuild_idstore_from_dom(&mut self) -> Result<()> {
6450 self.idstore.clear();
6451 if let Some(root) = self.document.get_root_element() {
6452 self.record_node_ids(&root)?;
6453 }
6454 Ok(())
6455 }
6456
6457 /// Get a new, related, but unique id.
6458 /// Sneaky option: try "ID_SUFFIX" as a suffix for id, first.
6459 /// Perl: sub modifyID (Document.pm lines 1483-1494)
6460 pub fn modify_id(&mut self, id: String) -> String {
6461 if self.idstore.contains_key(&id) || self.spilled_ids.contains(&id) {
6462 // Whoops! Already assigned!!!
6463 // Can we recover?
6464 let badid = id;
6465 // First try ID_SUFFIX if set
6466 if let Some(Stored::String(suffix)) = state::lookup_value("ID_SUFFIX") {
6467 let suffixed = s!("{}{}", badid, arena::to_string(suffix));
6468 if !self.idstore.contains_key(&suffixed) && !self.spilled_ids.contains(&suffixed) {
6469 return suffixed;
6470 }
6471 }
6472 // Try radix_alpha(1) through radix_alpha(26^3)
6473 // Gotta give up, eventually; is 3 letters enough?
6474 for s1 in 1_i64..=(26 * 26 * 26) {
6475 let candidate = s!("{}{}", badid, radix_alpha(s1));
6476 if !self.idstore.contains_key(&candidate) && !self.spilled_ids.contains(&candidate) {
6477 return candidate;
6478 }
6479 }
6480 emit_error(
6481 "malformed",
6482 "id",
6483 &format!("Automatic incrementing of ID counters failed for '{badid}'"),
6484 );
6485 badid
6486 } else {
6487 id
6488 }
6489 }
6490
6491 pub fn lookup_id(&self, id: &str) -> Option<&Node> { self.idstore.get(id) }
6492
6493 /// Clone the idstore for use in thread-local contexts (math parsing).
6494 pub fn get_idstore_clone(&self) -> HashMap<String, Node> { self.idstore.clone() }
6495
6496 // ======================================================================
6497 // Odd bit:
6498 // In an XMDual, in each branch (content, presentation) there will be atoms
6499 // that correspond to the input (one will be real, the other an XMRef to the first).
6500 // But also there will be additional "decoration" (delimiters, punctuation, etc on the
6501 // presentation side; other symbols, bindings, whatever, on the content side).
6502 // These decorations should NOT be subject to rewrite rules,
6503 // and in cross-linked parallel markup, they should be attributed to the
6504 // upper containing object's ID, rather than left dangling.
6505 //
6506 // To determine this, we mark all math nodes as to whether they are "visible" from
6507 // presentation, content or both (the default top-level being both).
6508 // Decorations are the nodes that are visible to only one mode.
6509 // Note that nodes that are not visible at all CAN occur (& do currently when the parser
6510 // creates XMDuals), pruneXMDuals (below) gets rid of them.
6511
6512 // NOTE: This should ultimately be in a base Document class,
6513 // since it is also needed before conversion to parallel markup!
6514 pub fn mark_xmnode_visibility(&mut self) -> Result<()> {
6515 let xmath = self.findnodes("//ltx:XMath/*", None);
6516 for math in xmath.iter() {
6517 for mut node in self.findnodes("descendant-or-self::*[@_pvis or @_cvis]", Some(math)) {
6518 node.remove_attribute("_pvis")?;
6519 node.remove_attribute("_cvis")?;
6520 }
6521 }
6522 for math in xmath {
6523 self.mark_xmnode_visibility_aux(math, true, true)?;
6524 }
6525 Ok(())
6526 }
6527
6528 fn mark_xmnode_visibility_aux(&self, node: Node, cvis: bool, pvis: bool) -> Result<()> {
6529 // Recurses to math-tree depth via XMDual/XMRef-following + element-
6530 // child fan-out. Deep grammar-ambiguous papers (sandbox 0711.4787
6531 // et al, #17) hit Rust's 8 MB main-thread stack here during the
6532 // `Finalizing...` phase (via prune_xmduals → mark_xmnode_visibility).
6533 // Grow the stack on demand instead of overflowing (guard params are
6534 // configurable in `crate::stack_guard`).
6535 crate::stack_guard::maybe_grow(move || self.mark_xmnode_visibility_aux_inner(node, cvis, pvis))
6536 }
6537
6538 fn mark_xmnode_visibility_aux_inner(
6539 &self,
6540 mut node: Node,
6541 cvis: bool,
6542 mut pvis: bool,
6543 ) -> Result<()> {
6544 if (!cvis || node.has_attribute("_cvis")) && (!pvis || node.has_attribute("_pvis")) {
6545 return Ok(());
6546 }
6547 let qname = get_node_qname(&node);
6548 // Special case: for XMArg used to wrap "formal" arguments on the content side,
6549 // mark them as visible as presentation as well.
6550 if cvis && (qname == pin!("ltx:XMArg")) {
6551 pvis = true;
6552 }
6553 if cvis {
6554 node.set_attribute("_cvis", "1")?;
6555 }
6556 if pvis {
6557 node.set_attribute("_pvis", "1")?;
6558 }
6559 if qname == pin!("ltx:XMDual") {
6560 let mut children = xml::element_nodes(&node);
6561 // XMDual should have exactly 2 element children (content + presentation),
6562 // but a malformed math parse (e.g. semantic action producing empty pair
6563 // during deep ambiguity collapse) can leave an empty XMDual. Skip
6564 // visibility-marking rather than panicking on `children.remove(0)` —
6565 // see wp5 sandbox 2110.10033 and 4 sibling papers.
6566 if children.len() >= 2 {
6567 let c = children.remove(0);
6568 let p = children.remove(0);
6569 if cvis {
6570 self.mark_xmnode_visibility_aux(c, true, false)?;
6571 }
6572 if pvis {
6573 self.mark_xmnode_visibility_aux(p, false, true)?;
6574 }
6575 }
6576 } else if qname == pin!("ltx:XMRef") {
6577 match node.get_attribute("idref") {
6578 None => {
6579 let key = node.get_attribute("_xmkey");
6580 Warn!(
6581 "expected",
6582 "id",
6583 "Missing idref on ltx:XMRef",
6584 s!("_xmkey is `{}`", key.unwrap_or_default())
6585 );
6586 },
6587 Some(id) => match self.lookup_id(&id) {
6588 None => {
6589 Warn!(
6590 "expected",
6591 "node",
6592 s!("No node found with id='{id}' (referred to from ltx:XMRef)")
6593 );
6594 },
6595 Some(reffed) => {
6596 self.mark_xmnode_visibility_aux(reffed.clone(), cvis, pvis)?;
6597 },
6598 },
6599 }
6600 } else {
6601 for child in xml::element_nodes(&node) {
6602 self.mark_xmnode_visibility_aux(child, cvis, pvis)?;
6603 }
6604 }
6605 Ok(())
6606 }
6607
6608 /// Remove `ltx:XMRef[@_split_ref="1"]` whose `idref` no longer
6609 /// resolves. These are the XMRefs minted by
6610 /// `amsmath::rearrange_ams_split` to mirror the flattened cell
6611 /// sequence inside an `XMDual(XMWrap(refs), XMArray(cells))`. The
6612 /// math parser can later absorb some cells (typically inserted
6613 /// MULOP times-ops on `\mathcal{L}\rho` chains) into wrapping
6614 /// XMApps, dropping their xml:id from the live DOM and leaving
6615 /// the sibling XMRefs dangling. Left in place, each dangling
6616 /// XMRef trips three separate diagnostics later — math parser's
6617 /// read_xmref Warn, finalize's mark_xmnode_visibility Warn, and
6618 /// post-process's mark_xm_node_visibility Error.
6619 ///
6620 /// We restrict the sweep to the `_split_ref` marker so refs from
6621 /// other provenance (base_xmath `\lx@dual`, renamed-id cases like
6622 /// declare_test's `S1.Ex1.m1.1` → `.1a` rename) stay untouched.
6623 ///
6624 /// Content-preserving: XMRefs are structural cross-references,
6625 /// not author body, and the math parser has already absorbed the
6626 /// referenced cell into the visible XMArray branch — no glyph or
6627 /// formula material is lost.
6628 pub fn prune_dangling_split_xmrefs(&mut self) -> Result<()> {
6629 // `//ltx:XMRef[@_split_ref or @_mf_ref]` and `//ltx:XMRef[@idref]`, walked (#802).
6630 let is_xmref = |n: &Node| xml::is_ltx_element(n, "XMRef");
6631 let xmrefs = self.find_elements(|n| {
6632 is_xmref(n) && (n.has_attribute_no_ns("_split_ref") || n.has_attribute_no_ns("_mf_ref"))
6633 });
6634 for xmref in xmrefs {
6635 let idref = match xmref.get_attribute("idref") {
6636 Some(id) => id,
6637 None => continue,
6638 };
6639 if self.lookup_id(&idref).is_none() && xmref.get_parent().is_some() {
6640 self.remove_node(xmref);
6641 }
6642 }
6643 // Broader sweep: any XMRef pointing to a canonical math node id
6644 // `S<N>.E<M>.m1.<K>...` that no longer resolves. These are minted
6645 // by base_xmath::add_column_to_math_fork during rearrange_ams_*
6646 // (align/gather/multline), but unlike `_split_ref` they aren't
6647 // marked. The math parser absorbs cells later, leaving the refs
6648 // dangling and triggering the `Error:expected:id` cascade in
6649 // post-processing.
6650 //
6651 // We restrict the regex to the equation-numbered form (E<digit>,
6652 // not Ex<digit>) so declare_test's renamed-id case
6653 // (`S1.Ex1.m1.1` → `.1a`) stays untouched. canvas papers using
6654 // `\begin{equation}` produce `E1`/`E2`/... ids.
6655 static RE_MATH_ID: LazyLock<Regex> =
6656 LazyLock::new(|| Regex::new(r"^S\d+\.E\d+\.m\d+\.").unwrap());
6657 let xmrefs2 = self.find_elements(|n| is_xmref(n) && n.has_attribute_no_ns("idref"));
6658 for xmref in xmrefs2 {
6659 // Skip if already pruned via _split_ref sweep above.
6660 if xmref.get_parent().is_none() {
6661 continue;
6662 }
6663 let idref = match xmref.get_attribute("idref") {
6664 Some(id) => id,
6665 None => continue,
6666 };
6667 if RE_MATH_ID.is_match(&idref) && self.lookup_id(&idref).is_none() {
6668 // Safety guard: NEVER drop a ref that is an OPERAND of an XMApp.
6669 // Removing it would corrupt the application — e.g. an `\lx@dual`
6670 // content arm `XMApp(probability, XMRef)` would lose its argument,
6671 // emitting a malformed `apply(probability)` with no operand (silent
6672 // content-MathML corruption; witnessed on `aligned`+`\Pr(a,b|c)`,
6673 // docs/reproducers/class_b_aligned_pr_xmref.tex). Such content-arm
6674 // refs are essential shared links — they are NEVER the redundant
6675 // MathFork/`_split_ref` mirrors this sweep targets (those live in
6676 // XMWrap/XMArray, not as XMApp operands). Leave it dangling so the
6677 // faithful "No node found" Warn (`mark_xmnode_visibility`) fires
6678 // rather than silently corrupting the content tree.
6679 if let Some(parent) = xmref.get_parent()
6680 && get_node_qname(&parent) == pin!("ltx:XMApp")
6681 {
6682 let kids = parent.get_child_elements();
6683 let is_operand = kids
6684 .iter()
6685 .position(|k| *k == xmref)
6686 .is_some_and(|pos| pos > 0);
6687 if is_operand {
6688 continue;
6689 }
6690 }
6691 self.remove_node(xmref);
6692 }
6693 }
6694 Ok(())
6695 }
6696
6697 /// Reduce any ltx:XMDual's to just the visible branch, if the other is not visible
6698 /// (according to markXMNodeVisibility)
6699 /// If we could be 100% sure that the marking had stayed consistent (after various doc surgery)
6700 /// we could avoid re-marking, but we'd better be sure before removing nodes!
6701 pub fn prune_xmduals(&mut self) -> Result<()> {
6702 // RE-mark visibility!
6703 self.mark_xmnode_visibility()?;
6704 let pruned = self.prune_marked_xmduals();
6705 self.idref_index = None;
6706 pruned
6707 }
6708
6709 /// `prune_xmduals`' loop, over the marked visibility; `idref_index` lives only while it runs.
6710 fn prune_marked_xmduals(&mut self) -> Result<()> {
6711 // will reversing keep from problems removing nodes from trees that already have been removed?
6712 for dual in self
6713 .findnodes("descendant-or-self::ltx:XMDual", None)
6714 .into_iter()
6715 .rev()
6716 {
6717 let mut dual_children = xml::element_nodes(&dual);
6718 // Defensive: an XMDual should always have presentation +
6719 // content children, but a malformed math parse (post-ambiguity
6720 // collapse) can yield <2. Skip rather than panic.
6721 // Witness 2110.10033 (panicked at document.rs:3120, post-fix
6722 // continuation of earlier guard at document.rs:2993).
6723 let Some(presentation) = dual_children.pop() else {
6724 continue;
6725 };
6726 let Some(content) = dual_children.pop() else {
6727 continue;
6728 };
6729 if self
6730 .findnode("descendant-or-self::*[@_pvis or @_cvis]", Some(&content))
6731 .is_none()
6732 {
6733 // content never seen
6734 self.collapse_xmdual(dual, presentation)?;
6735 } else if self
6736 .findnode(
6737 "descendant-or-self::*[@_pvis or @_cvis]",
6738 Some(&presentation),
6739 )
6740 .is_none()
6741 {
6742 // pres.
6743 self.collapse_xmdual(dual, content)?;
6744 } else {
6745 // compact aligned structures, where possible
6746 self.compact_xmdual(dual, content, Some(presentation))?;
6747 }
6748 }
6749 Ok(())
6750 }
6751
6752 fn compact_xmdual(
6753 &mut self,
6754 dual: Node,
6755 content: Node,
6756 presentation: Option<Node>,
6757 ) -> Result<()> {
6758 // Perl: our $content_transfer_overrides = { decl_id, meaning, name, omcd };
6759 // Perl: our $dual_transfer_overrides = { decl_id, meaning, name, omcd, xml:id, role };
6760 static CONTENT_TRANSFER: LazyLock<HashSet<&'static str>> =
6761 LazyLock::new(|| HashSet::from_iter(["decl_id", "meaning", "name", "omcd"]));
6762 static DUAL_TRANSFER: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
6763 HashSet::from_iter(["decl_id", "meaning", "name", "omcd", "xml:id", "role"])
6764 });
6765
6766 let presentation = match presentation {
6767 Some(p) => p,
6768 None => return Ok(()),
6769 };
6770 let c_name = with_node_qname(&content, |n| n.to_string());
6771 let p_name = with_node_qname(&presentation, |n| n.to_string());
6772
6773 // Case 1: Quick fix — merge two tokens (Perl compactXMDual L1588-1593).
6774 // Perl has NO id cleanup here: mergeAttributes deliberately TRANSFERS the
6775 // content/dual xml:id onto the surviving presentation token (unRecordID +
6776 // recordID, L1308-1313), keeping refs to that id resolvable. A former
6777 // Rust-only "remove the leaked content id" block contradicted that — and
6778 // was dead anyway (its bare has/get/remove_attribute("xml:id") calls
6779 // always missed the namespaced attribute).
6780 if c_name == "ltx:XMTok" && p_name == "ltx:XMTok" {
6781 let mut pres = presentation;
6782 self.merge_attributes(&content, &mut pres, Some(&CONTENT_TRANSFER))?;
6783 self.merge_attributes(&dual, &mut pres, Some(&DUAL_TRANSFER))?;
6784 // Unlink presentation from dual before replacing, since presentation is a child of dual
6785 pres.unlink();
6786 self.replace_node(dual, vec![pres])?;
6787 return Ok(());
6788 }
6789
6790 // Case 2: Compact mirror XMApp nodes
6791 if c_name != "ltx:XMApp" || p_name != "ltx:XMApp" {
6792 return Ok(());
6793 }
6794 let content_args = xml::element_nodes(&content);
6795 let pres_args = xml::element_nodes(&presentation);
6796 if content_args.len() != pres_args.len() {
6797 return Ok(());
6798 }
6799 let n_args = content_args.len();
6800
6801 // Walk the corresponding children, double-check they are referenced in the same order
6802 enum NewArg {
6803 Single(Node),
6804 Pair(Node, Node), // (content_arg, pres_arg) — to be merged
6805 }
6806 let mut new_args: Vec<NewArg> = Vec::with_capacity(n_args);
6807 for (c_arg, p_arg) in content_args.into_iter().zip(pres_args) {
6808 if let Some(c_idref) = c_arg.get_attribute("idref")
6809 && c_idref == p_arg.get_attribute_ns("id", XML_NS).unwrap_or_default()
6810 {
6811 new_args.push(NewArg::Single(p_arg));
6812 continue;
6813 }
6814 if let Some(p_idref) = p_arg.get_attribute("idref")
6815 && p_idref == c_arg.get_attribute_ns("id", XML_NS).unwrap_or_default()
6816 {
6817 new_args.push(NewArg::Single(c_arg));
6818 continue;
6819 }
6820 // We can handle content-side XMToks to any XM* presentation subtree
6821 let c_arg_name = with_node_qname(&c_arg, |n| n.to_string());
6822 if c_arg_name != "ltx:XMTok" {
6823 return Ok(()); // Can't compact this structure
6824 }
6825 new_args.push(NewArg::Pair(c_arg, p_arg));
6826 }
6827
6828 // If we made it here, this dual has two mirrored applications — compact it.
6829 let mut parent = match dual.get_parent() {
6830 Some(p) => p,
6831 None => return Ok(()),
6832 };
6833 let mut compact_apply = self.open_element_at(&mut parent, "ltx:XMApp", None, None)?;
6834 for n_arg in new_args {
6835 let mut node = match n_arg {
6836 NewArg::Single(n) => n,
6837 NewArg::Pair(c_arg, mut p_arg) => {
6838 self.merge_attributes(&c_arg, &mut p_arg, Some(&CONTENT_TRANSFER))?;
6839 p_arg
6840 },
6841 };
6842 node.unlink();
6843 compact_apply.add_child(&mut node)?;
6844 }
6845 // Migrate dual attributes to the new XMApp
6846 self.merge_attributes(&dual, &mut compact_apply, Some(&DUAL_TRANSFER))?;
6847 // Direct DOM swap: replace dual with compact_apply without re-creating nodes.
6848 // Perl uses replaceChild which is a direct swap; replace_tree calls append_tree
6849 // which re-creates elements and fires afterOpen/afterClose hooks a second time.
6850 compact_apply.unlink();
6851 let mut dual_mut = dual;
6852 dual_mut.add_prev_sibling(&mut compact_apply).ok();
6853 self.remove_node(dual_mut);
6854 Ok(())
6855 }
6856
6857 /// Replace an XMDual with one of its branches
6858 fn collapse_xmdual(&mut self, dual: Node, mut branch: Node) -> Result<()> {
6859 // The other branch is not visible, nor referenced,
6860 // but the dual may have an id and be referenced
6861 if let Some(dualid) = dual.get_attribute_ns("id", XML_NS) {
6862 self.unrecord_id(&dualid); // We'll move or remove the ID from the dual
6863 if let Some(branchid) = branch.get_attribute_ns("id", XML_NS) {
6864 // branch has id too! Change dualid refs to branchid (Perl's `//*[@idref='$dualid']`, Document.pm:1643, #802)
6865 // No freed handle can be here: remove_node unindexes a subtree's references before discard_subtree frees it.
6866 let mut refs = self.idref_index().remove(&dualid).unwrap_or_default();
6867 for tref in &mut refs {
6868 tref.set_attribute("idref", &branchid)?;
6869 }
6870 self.idref_index().entry(branchid).or_default().extend(refs);
6871 } else {
6872 // Assign the dual's id to the branch. Record first so we
6873 // receive a deduplicated id if something else claimed it
6874 // between the `unrecord_id` above and now — write the
6875 // deduped value, not the original.
6876 let deduped = self.record_id_with_node(&dualid, &branch);
6877 branch.set_attribute("xml:id", &deduped)?;
6878 }
6879 }
6880 // Direct DOM swap: Perl uses replaceChild (no re-creation, no hooks fired twice)
6881 let mut dual_mut = dual;
6882 dual_mut.add_prev_sibling(&mut branch).ok();
6883 self.remove_node(dual_mut);
6884 Ok(())
6885 }
6886
6887 /// `idref_index`, built by one walk of the document on first use.
6888 fn idref_index(&mut self) -> &mut HashMap<String, Vec<Node>> {
6889 if self.idref_index.is_none() {
6890 let mut index: HashMap<String, Vec<Node>> = HashMap::default();
6891 for node in self.find_elements(|n| n.has_attribute_no_ns("idref")) {
6892 if let Some(idref) = node.get_attribute_no_ns("idref") {
6893 index.entry(idref).or_default().push(node);
6894 }
6895 }
6896 self.idref_index = Some(index);
6897 }
6898 self.idref_index.get_or_insert_default()
6899 }
6900
6901 /// Take `node` out of `idref_index` (when one is live), before it is freed or its `idref` changes.
6902 fn unindex_idref(&mut self, node: &Node) {
6903 if let Some(index) = self.idref_index.as_mut()
6904 && let Some(idref) = node.get_attribute_no_ns("idref")
6905 && let Some(refs) = index.get_mut(&idref)
6906 {
6907 // O(references to this idref) per removed node: a bucket is a dual's few references.
6908 refs.retain(|tref| tref != node);
6909 }
6910 }
6911
6912 /// Put `node` into `idref_index` (when one is live) under its current `idref`.
6913 fn index_idref(&mut self, node: &Node) {
6914 if let Some(index) = self.idref_index.as_mut()
6915 && let Some(idref) = node.get_attribute_no_ns("idref")
6916 {
6917 index.entry(idref).or_default().push(node.clone());
6918 }
6919 }
6920
6921 //**********************************************************************
6922 /// Record the Box that created this node.
6923 pub fn set_node_box(&mut self, node: &Node, digested: Digested) {
6924 let nodeid = node.to_hashable();
6925 self.node_boxes.insert(nodeid, digested);
6926 }
6927
6928 pub fn get_node_box(&self, node: &Node) -> Option<Digested> {
6929 if node.get_type() == Some(NodeType::ElementNode) {
6930 let nodeid = node.to_hashable();
6931 self.node_boxes.get(&nodeid).cloned()
6932 } else {
6933 None
6934 }
6935 }
6936
6937 //**********************************************************************
6938 /// Record the Font of a node
6939 pub fn set_node_font(&mut self, node: &mut Node, font: &Font) -> Result<()> {
6940 let fontid = font.to_hashable();
6941 node.set_attribute("_font", &fontid.to_string())?;
6942 // try to avoid aggressive clones, when unnecessary
6943 match self.node_fonts.get(&fontid) {
6944 None => {
6945 self.node_fonts.insert(fontid, font.clone());
6946 },
6947 Some(v) => {
6948 if v != font {
6949 self.node_fonts.insert(fontid, font.clone());
6950 }
6951 },
6952 }
6953 Ok(())
6954 }
6955
6956 pub fn copy_node_font(&mut self, from: &Node, to: &mut Node) -> Result<()> {
6957 if let Some(fontid) = from.get_attribute("_font") {
6958 to.set_attribute("_font", &fontid)?;
6959 }
6960 Ok(())
6961 }
6962
6963 /// Possibly a sign of a design flaw; Set the node's font & all children that HAD the same font.
6964 pub fn merge_node_font_rec(&mut self, node: &Node, font: &Font) -> Result<()> {
6965 let oldfont = self.get_node_font(node);
6966 let props = oldfont.purestyle_changes(font);
6967 let mut nodes = VecDeque::new();
6968 nodes.push_front(node.clone());
6969 while let Some(mut n) = nodes.pop_front() {
6970 if n.get_type() == Some(NodeType::ElementNode) {
6971 let font = &self.get_node_font(&n).merge_ref(&props);
6972 self.set_node_font(&mut n, font)?;
6973 for child in n.get_child_nodes() {
6974 nodes.push_back(child);
6975 }
6976 }
6977 }
6978 Ok(())
6979 }
6980
6981 pub fn set_box_font(&mut self, node: &mut Node) -> Result<()> {
6982 if let Some(ref thisbox) = self.box_to_absorb
6983 && let Some(font) = thisbox.get_font()?
6984 {
6985 let todo_font_clone = (*font).clone();
6986 self.set_node_font(node, &todo_font_clone)?;
6987 }
6988 Ok(())
6989 }
6990
6991 pub fn get_node_font(&self, node: &Node) -> &Font {
6992 if let Some(element) = xml::closest_element(node) {
6993 // Use the closest element (for text nodes, this is the parent element); the id is read in place, not copied
6994 // (`_font` is read on every text chunk: docs/performance/PERFORMANCE.md P11).
6995 // Tolerate non-numeric `_font` attributes — they can occur when
6996 // a corrupted property propagates across reversion (driver:
6997 // 2304.07380 panicked at parse::<u64>().unwrap()). Fall through
6998 // to the default font instead of aborting the run.
6999 if let Some(Ok(id)) = element.with_attribute(c"_font", str::parse::<u64>)
7000 && let Some(fnt) = self.node_fonts.get(&id)
7001 {
7002 return fnt;
7003 }
7004 }
7005 &FONT_TEXT_DEFAULT
7006 }
7007
7008 /// Decode a _font hash string to a Font object
7009 pub fn decode_font(&self, font_hash: &str) -> Option<&Font> {
7010 font_hash
7011 .parse::<u64>()
7012 .ok()
7013 .and_then(|id| self.node_fonts.get(&id))
7014 }
7015
7016 pub fn has_node_font(&self, node: &Node) -> bool {
7017 match xml::closest_element(node) {
7018 Some(element) => element.has_attribute("_font"),
7019 _ => false,
7020 }
7021 }
7022
7023 pub fn get_node_language(&self, node: &Node) -> String {
7024 let mut node_ref = node;
7025 let mut current;
7026 loop {
7027 if node_ref.get_type() != Some(NodeType::ElementNode) {
7028 break;
7029 }
7030 // `xml:lang` is stored namespaced (local name "lang"); the string
7031 // accessor `get_attribute("xml:lang")` always returns None — read it via
7032 // the XML namespace. (Same libxml footgun as xml:id; see
7033 // docs/archive/XMLID_ACCESSOR_AUDIT_2026-06-08.md.)
7034 if let Some(lang) = node_ref.get_attribute_ns("lang", XML_NS) {
7035 return lang;
7036 }
7037 // Perl `getNodeLanguage` reads `_font` off the SAME (walked) ancestor,
7038 // not the original node — use `node_ref`, not `node`. Be robust against a
7039 // missing/foreign _font property (Perl PR #2767): never panic on a
7040 // non-numeric font id.
7041 if let Some(Ok(id)) = node_ref.with_attribute(c"_font", str::parse::<u64>)
7042 && let Some(font) = self.node_fonts.get(&id)
7043 && let Some(lang) = font.get_language()
7044 {
7045 return lang.to_string();
7046 }
7047 match node_ref.get_parent() {
7048 Some(parent) => {
7049 current = parent;
7050 node_ref = ¤t;
7051 },
7052 _ => {
7053 break;
7054 },
7055 }
7056 }
7057 String::from("en")
7058 }
7059
7060 // sub decodeFont {
7061 // my ($self, $fontid) = @_;
7062 // return $$self{node_fonts}{$fontid} || LaTeXML::Common::Font->textDefault(); }
7063
7064 /// Remove a node from the document (from it's parent).
7065 ///
7066 /// Two pieces of bookkeeping come with it: the `xml:id` of the node and of
7067 /// every descendant is un-recorded, so the ids are free for reuse and no
7068 /// dangling reference is left behind; and if the insertion point was inside
7069 /// what is being removed, it is rescued up to the parent — otherwise the
7070 /// document would go on building into a detached subtree.
7071 ///
7072 /// The node's box leaves the boxes of its parent and of the parent's
7073 /// auto-opened ancestors (Perl `removeNode` → `removeNodeBox`,
7074 /// Document.pm:1788-1789): what the node contributed to them is gone.
7075 pub fn remove_node(&mut self, node: Node) {
7076 self.remove_node_with_box_action(node, NodeBoxAction::Unlink)
7077 }
7078
7079 /// [`remove_node`](Self::remove_node) for a node whose content lives on in
7080 /// another node, so its box stays in the boxes it is part of: a copy
7081 /// (`append_tree`; Perl's `appendChild` moves the node itself — `\sideset`'s
7082 /// nucleus, amsmath), a renamed node, a token a math ligature merged, a node
7083 /// its replacements stand for (Perl's `replaceChild` has moved it into a
7084 /// document fragment, where `removeNodeBox` finds no element to update).
7085 /// Unlinking these boxes took pieces out of the reversions that `tex=` is
7086 /// read from (KNOWN_PERL_ERRORS #272).
7087 pub fn remove_node_keeping_box(&mut self, node: Node) {
7088 self.remove_node_with_box_action(node, NodeBoxAction::Keep)
7089 }
7090
7091 /// The shared body of [`remove_node`](Self::remove_node) and
7092 /// [`remove_node_keeping_box`](Self::remove_node_keeping_box): `box_action`
7093 /// says whether the node's box is unlinked from its enclosing boxes.
7094 fn remove_node_with_box_action(&mut self, node: Node, box_action: NodeBoxAction) {
7095 let mut chopped: bool = self.node == node; // Note if we're removing insertion point
7096 if node.get_type() == Some(NodeType::ElementNode) {
7097 // If an element, do ID bookkeeping.
7098 if let Some(id) = node.get_attribute_ns("id", XML_NS) {
7099 self.unrecord_id(&id);
7100 }
7101 self.unindex_idref(&node);
7102 if box_action == NodeBoxAction::Unlink
7103 && let Some(nodebox) = self.get_node_box(&node)
7104 && let Some(parent) = node.get_parent()
7105 {
7106 self.remove_node_box(&parent, &nodebox);
7107 }
7108 for child in node.get_child_nodes() {
7109 chopped = chopped || self.remove_node_aux(child);
7110 }
7111 }
7112 if let Some(parent) = node.get_parent() {
7113 if chopped {
7114 // Don't remove insertion point!
7115 self.set_node(&parent);
7116 }
7117 // Perl's `removeChild` hands the node to XML::LibXML's proxy GC, which
7118 // frees it with the last reference. Here an unlinked node whose
7119 // `node->doc` is still set is freed by NOBODY (the fork's `Drop` frees
7120 // only doc-less nodes, and `xmlFreeDoc` never reaches an orphan), so a
7121 // bare `unlink` leaked every removed subtree for the process lifetime:
7122 // ~5-6 MB per tikz picture of pgfsys transient `svg:g` groups dropped
7123 // by `collapse_svg_group`, eager and streaming alike (pgf-PeriodicTable
7124 // n8: the glibc heap climbed 11 → 47 MB across eight spilled tables and
7125 // the manual reached 742 MB of orphans by fragment 256). The ids are
7126 // unrecorded above, so `discard_subtree`'s contract holds.
7127 self.discard_subtree(node);
7128 }
7129 }
7130
7131 fn remove_node_aux(&mut self, node: Node) -> bool {
7132 let mut chopped = self.node == node;
7133 if node.get_type() == Some(NodeType::ElementNode) {
7134 // If an element, do ID bookkeeping.
7135 if let Some(id) = node.get_attribute_ns("id", XML_NS) {
7136 self.unrecord_id(&id);
7137 }
7138 self.unindex_idref(&node);
7139 for child in node.get_child_nodes() {
7140 chopped = chopped || self.remove_node_aux(child);
7141 }
7142 }
7143 chopped
7144 }
7145
7146 //**********************************************************************
7147 // Inserting new nodes at random points into the document,
7148 // typically, later in the process or during some kind of rearrangement.
7149
7150 // This is a somewhat strange situation; There are commands and environments
7151 // that do some interesting thing to their contents. This include things like
7152 // center, flushleft, or rotate, or ...
7153 // Naively one is tempted to create a containing block with appropriate type &
7154 // attributes. However, since these things can be allowed in so many places
7155 // by LaTeX, that one has a difficult time creating a sensible document model.
7156 // The purpose of transformingBlock is to set the contents (possibly creating a
7157 // consistent <p> around them, if called for), and returning the list of newly
7158 // created nodes. These nodes can then have appropriate attributes added as
7159 // needed for each specific case.
7160
7161 // Since this situation can occur in both LaTeX and AmSTeX type documents,
7162 // we'll put it in the TeX pool so it can be reused.
7163
7164 // Tricky bit for creating nodes late in the game,
7165
7166 ////// See createElementAt
7167 /// This opens a new element at the _specified_ point, rather than the current insertion point.
7168 /// This is useful during document rearrangement or augmentation that may be needed later
7169 /// in the process.
7170 pub fn open_element_at(
7171 &mut self,
7172 point: &mut Node,
7173 qname: &str,
7174 attributes: Option<HashMap<String, String>>,
7175 font_opt: Option<Font>,
7176 ) -> Result<Node> {
7177 self.open_element_at_with_box(point, qname, attributes, font_opt, None)
7178 }
7179
7180 /// [`open_element_at`](Self::open_element_at) with Perl's `_box` attribute:
7181 /// `requested_box` is the box the new node records, ahead of the insertion
7182 /// point's box and the box being absorbed (Document.pm:1861).
7183 fn open_element_at_with_box(
7184 &mut self,
7185 point: &mut Node,
7186 qname: &str,
7187 attributes: Option<HashMap<String, String>>,
7188 mut font_opt: Option<Font>,
7189 requested_box: Option<Digested>,
7190 ) -> Result<Node> {
7191 // Font resolution priority (matching Perl's openElement/openElementAt):
7192 // 1. Explicit font_opt parameter
7193 // 2. _font attribute in attributes hash
7194 // 3. box_to_absorb.get_font() — the font of the current box being absorbed (Perl:
7195 // $attributes{_box} = $LaTeXML::BOX; $font = $attributes{_box}->getFont)
7196 // 4. Insertion point's font (final fallback, handled later)
7197 if font_opt.is_none()
7198 && let Some(ref attrs) = attributes
7199 && let Some(fontid) = attrs.get("_font")
7200 {
7201 // Tolerate non-numeric `_font` attributes — see get_node_font
7202 // for the same defensive read; same panic site, different
7203 // call. Driver: 2406.14188.
7204 if let Ok(id) = fontid.parse::<u64>() {
7205 font_opt = self.node_fonts.get(&id).cloned();
7206 }
7207 }
7208 if font_opt.is_none()
7209 && let Some(ref digested) = self.box_to_absorb
7210 && let Ok(Some(font)) = digested.get_font()
7211 {
7212 font_opt = Some((*font).clone());
7213 }
7214 let (decoded_ns, tag) = model::decode_qname(qname)?;
7215 let mut newnode;
7216 // box = self.node_boxes.get(box); // may already be the string key
7217 // If this will be the document root node, things are slightly more involved.
7218 if point.get_type() == Some(NodeType::DocumentNode) {
7219 // First node! (?)
7220 Debug!("adding schema declaration, new node will be : {}", tag);
7221 model::add_schema_declaration(self);
7222 newnode = Node::new(&tag, None, &self.document).unwrap();
7223 self.record_constructed_node(&newnode);
7224 self.document.set_root_element(&newnode);
7225 for node in &mut self.pending {
7226 newnode.add_prev_sibling(node)?; // Add saved comments, PI's
7227 }
7228
7229 if let Some(ns) = decoded_ns {
7230 // Here, we're creating the initial, document element, which will hold ALL of
7231 // the namespace declarations. If there is a default namespace (no
7232 // prefix), that will also be declared, and applied here. However, if
7233 // there is ALSO a prefix associated with that namespace, we have to declare it
7234 // FIRST due to the (apparently) buggy way that XML::LibXML works with
7235 // namespaces in setAttributeNS.
7236 let prefix_opt = model::get_document_namespace_prefix(&ns, false, false);
7237 let attprefix_opt = model::get_document_namespace_prefix(&ns, true, true);
7238 if prefix_opt.is_none()
7239 && let Some(attprefix_sym) = attprefix_opt
7240 {
7241 let attr_ns_node = arena::with(attprefix_sym, |attprefix| {
7242 Namespace::new(attprefix, &ns, &mut newnode)
7243 })
7244 .unwrap();
7245 newnode.set_namespace(&attr_ns_node)?;
7246 }
7247 // TODO: Figure out a better way to achieve the "activate" effect in
7248 // XML:LibXML::Element it seems just creating the namespace without
7249 // setting it is equivalent ??
7250 let ns_node = Namespace::new("", &ns, &mut newnode).unwrap();
7251 newnode.set_namespace(&ns_node)?;
7252 }
7253 } else {
7254 if font_opt.is_none() {
7255 font_opt = Some(self.get_node_font(point).clone());
7256 }
7257 newnode = self.open_element_internal(point, decoded_ns, &tag)?;
7258 }
7259
7260 // Source-locator stamping (`--source-map`, issues #47/#92). `open_element_at`
7261 // is the shared element-creation primitive (plain `open_element`, math, and
7262 // alignment all route here), so stamping here covers them uniformly —
7263 // including the `ltx:Math` wrapper that bypasses `open_element`. Off by
7264 // default; the cheap gate keeps the normal path free.
7265 if state::source_map_enabled() {
7266 self.stamp_source_locator(&newnode, qname);
7267 }
7268
7269 if let Some(attrs) = attributes {
7270 let mut sorted_keys = attrs.keys().map(String::as_str).collect::<Vec<_>>();
7271 sorted_keys.sort_unstable();
7272 for key in sorted_keys {
7273 if key == "font" || key == "locator" {
7274 continue;
7275 }
7276 self.set_attribute(&mut newnode, key, &attrs[key])?;
7277 }
7278 }
7279 if let Some(font) = font_opt {
7280 self.set_node_font(&mut newnode, &font)?;
7281 }
7282
7283 // Perl Document.pm:1861-1862: the new node's box is the requested `_box`
7284 // (`openElement` passes `$LaTeXML::BOX`), else the insertion point's box,
7285 // else `$LaTeXML::BOX`; and `appendNodeBox` records it on the new node AND
7286 // extends the box of every auto-opened ancestor with it, so an auto-opened
7287 // `ltx:picture` or `svg:foreignObject` measures everything opened inside it,
7288 // not just the box that opened it (batch 56iy's residual). Guard:
7289 // `node_box_append::*`. (A `Digested` clone is an `Rc` clone.)
7290 let node_box = requested_box
7291 .or_else(|| self.get_node_box(point))
7292 .or_else(|| self.box_to_absorb.clone());
7293 // A fresh node holds only this box (its pointer key may be a freed node's
7294 // stale entry, which must not combine with it); the walk then goes on
7295 // from the parent, as Perl's `appendNodeBox` finds the new node holding it.
7296 if let Some(node_box) = node_box {
7297 self
7298 .node_boxes
7299 .insert(newnode.to_hashable(), node_box.clone());
7300 if let Some(parent) = newnode.get_parent()
7301 && is_autoopened_element(&parent)
7302 {
7303 self.append_node_box(&parent, &node_box);
7304 }
7305 }
7306
7307 // Debug!(
7308 // s!("Inserting {:?} into {:?}", get_node_qname(&newnode), get_node_qname(point))
7309 // );
7310
7311 // Run afterOpen operations
7312 self.after_open(&mut newnode)?;
7313
7314 Ok(newnode)
7315 }
7316
7317 fn open_element_internal(
7318 &mut self,
7319 point: &mut Node,
7320 ns_opt: Option<String>,
7321 tag: &str,
7322 ) -> Result<Node> {
7323 // TODO:
7324 //
7325 // I am seriously irritated by the XML namespace and the confusion of the "default#"
7326 // tricks and libxml2's custom decisions about namespace interactions
7327 //
7328 // I have "hacked together" a working flow for now, but I expect to
7329 // encounter bugs related to the shortcuts taken here. I would welcome a
7330 // redesign that simplifies the namespace logic dramatically.
7331
7332 // An element added to a text node is merged away and freed by libxml, losing
7333 // it and its subtree silently; Perl dies here (no `addNewChild` on a Text, #1034).
7334 if point.get_type() == Some(NodeType::TextNode) {
7335 let message = s!("cannot insert element {tag:?} into a text node");
7336 Error!("malformed", tag, message.clone());
7337 return Err(message.into());
7338 }
7339 let new_ns = match ns_opt {
7340 Some(ns_uri) => {
7341 match point.lookup_namespace_prefix(&ns_uri) {
7342 // namespace not already declared?
7343 None => {
7344 if let Some(prefix) = model::get_document_namespace_prefix(&ns_uri, false, false) {
7345 if prefix != pin!("") {
7346 let mut root = self.document.get_root_element().unwrap();
7347 match arena::with(prefix, |prefix_str| {
7348 Namespace::new(prefix_str, &ns_uri, &mut root)
7349 }) {
7350 Ok(ns) => Some(ns),
7351 Err(_) => {
7352 // The namespace already exists on root (declared by an
7353 // earlier element of the same namespace — e.g. a prior
7354 // tikz/SVG picture) but `lookup_namespace_prefix` did not
7355 // find it from this deeply-nested insertion point. Recover
7356 // by reusing the root declaration (or creating it on the
7357 // insertion point), exactly as the already-declared branch
7358 // below — do NOT drop the namespace. Witness 1802.00756:
7359 // a `tikzpicture` inside a nested `gather*`/`minipage`/
7360 // `figure*` emitted 14× "failed to create namespace: svg"
7361 // and the `<svg:svg>`/`<svg:g>` lost their namespace.
7362 arena::with(prefix, |prefix_str| {
7363 let found = root
7364 .get_namespace_declarations()
7365 .into_iter()
7366 .find(|ns| ns.get_prefix() == prefix_str);
7367 if found.is_none() {
7368 Namespace::new(prefix_str, &ns_uri, point).ok()
7369 } else {
7370 found
7371 }
7372 })
7373 },
7374 }
7375 } else {
7376 // default namespace?
7377 None
7378 }
7379 } else {
7380 // default namespace?
7381 None
7382 }
7383 },
7384 Some(prefix) => {
7385 if !prefix.is_empty() {
7386 let mut root = self.document.get_root_element().unwrap();
7387 match Namespace::new(&prefix, &ns_uri, &mut root) {
7388 Ok(ns) => Some(ns),
7389 Err(_) => {
7390 // Namespace already exists on root — find and reuse it.
7391 // We search declarations then fall back to creating on the
7392 // insertion point (which inherits from root).
7393 let found = root
7394 .get_namespace_declarations()
7395 .into_iter()
7396 .find(|ns| ns.get_prefix() == prefix);
7397 if found.is_none() {
7398 // Try creating on the insertion point instead
7399 Namespace::new(&prefix, &ns_uri, point).ok()
7400 } else {
7401 found
7402 }
7403 },
7404 }
7405 } else {
7406 // default namespace?
7407 None
7408 }
7409 },
7410 }
7411 },
7412 None => None,
7413 };
7414
7415 let no_ns = new_ns.is_none();
7416 let mut newnode = match Node::new(tag, new_ns.clone(), &self.document) {
7417 Ok(n) => n,
7418 Err(_) => {
7419 // libxml2 rejected the tag (e.g. NUL byte, malformed name).
7420 // Bail out of element creation rather than aborting; caller
7421 // can recover. Driver: 2304.07380 panic at Node::new unwrap.
7422 let message = s!("failed to create element {:?}", tag);
7423 Error!("document", "open_element_internal", message);
7424 return Err(message.into());
7425 },
7426 };
7427 point.add_child(&mut newnode)?;
7428 if no_ns {
7429 // When no explicit namespace was determined (default namespace element),
7430 // try to find the root's default namespace first. This prevents inheriting
7431 // the parent's namespace when inside a different namespace context (e.g.,
7432 // SVG elements getting svg: prefix on LaTeXML elements like Math/XMath).
7433 let root_ns = self
7434 .document
7435 .get_root_element()
7436 .and_then(|r| r.get_namespace());
7437 let parent_ns = point.get_namespace();
7438 if let Some(ref rns) = root_ns {
7439 // Use root's namespace for default-namespace elements
7440 let _ = newnode.set_namespace(rns);
7441 } else if let Some(ns) = parent_ns {
7442 // Fallback: inherit from parent (original behavior)
7443 newnode.set_namespace(&ns)?;
7444 }
7445 } else if let Some(ref ns) = new_ns {
7446 // For explicitly namespaced elements (e.g., svg:svg), ensure the namespace
7447 // is set after add_child — Node::new may not properly bind the namespace
7448 // when the Namespace was retrieved from get_namespace_declarations().
7449 let _ = newnode.set_namespace(ns);
7450 }
7451
7452 self.record_constructed_node(&newnode);
7453 Ok(newnode)
7454 }
7455
7456 /// Whenever a node has been created using openElementAt,
7457 /// closeElementAt ought to be used to close it, when you're finished inserting into $node.
7458 /// Basically, this just runs any afterClose operations.
7459 pub fn close_element_at(&mut self, node: &mut Node) -> Result<()> { self.after_close(node) }
7460
7461 pub fn after_open(&mut self, node: &mut Node) -> Result<()> {
7462 // Streaming pass 1: the root's LATE hooks are deferred to
7463 // end-of-digestion (their eager semantics are "digestion complete") but
7464 // its early/normal hooks — structural work like the pending-resource
7465 // drain, which mid-digestion consumers depend on — still run at open.
7466 // See the `defer_root_after_open` field docs.
7467 if self.defer_root_after_open && self.document.get_root_element().as_ref() == Some(node) {
7468 let savenode = self.node.clone();
7469 self.set_node(node);
7470 let node_qname = get_node_qname(node);
7471 let box_opt = self.get_node_box(node);
7472 let (prompt, _late) = self.get_tag_action_list_parts(node_qname, TagOptionName::AfterOpen);
7473 for action in prompt {
7474 action(self, node, box_opt.as_ref())?;
7475 }
7476 self.set_node(&savenode);
7477 return Ok(());
7478 }
7479 // Set current point to this node, just in case the afterOpen's use it.
7480 let savenode = self.node.clone();
7481 self.set_node(node);
7482 let node_qname = get_node_qname(node);
7483 // Perl: my $box = getNodeBox($self, $node);
7484 let box_opt = self.get_node_box(node);
7485 for action in self.get_tag_action_list(node_qname, TagOptionName::AfterOpen) {
7486 action(self, node, box_opt.as_ref())?;
7487 }
7488 self.set_node(&savenode);
7489 Ok(())
7490 }
7491
7492 pub fn after_close(&mut self, node: &mut Node) -> Result<()> {
7493 // Should we set point to this node? (or to last child, or something ??
7494 let savenode = self.node.clone();
7495 let node_qname = get_node_qname(node);
7496 // Perl: my $box = getNodeBox($self, $node);
7497 let box_opt = self.get_node_box(node);
7498 for action in self.get_tag_action_list(node_qname, TagOptionName::AfterClose) {
7499 action(self, node, box_opt.as_ref())?;
7500 }
7501 // (unless a hook removed the node it stood on — algorithm2e's listing drops an empty line the close walk began
7502 // in — where `remove_node` already moved the point)
7503 if !savenode.is_null() {
7504 self.set_node(&savenode);
7505 }
7506 Ok(())
7507 }
7508
7509 //**********************************************************************
7510 // Appending clones of nodes
7511
7512 // Inserting clones of nodes into the document.
7513 // Nodes that exist in some other part of the document (or some other document)
7514 /// Append COPIES of `new_children` under `node`.
7515 ///
7516 /// Cloning rather than moving is what makes this usable on nodes that belong
7517 /// to another document — moving them would remove them from it. Three things
7518 /// are repaired on the way in: document fragments are expanded to their
7519 /// children, the namespace structure is rebuilt clean (libxml2 otherwise has
7520 /// a tendency to introduce annoying "default" namespace prefix
7521 /// declarations), and every `xml:id` in the copy is rewritten to a fresh id,
7522 /// with internal references remapped to match — otherwise the copy would
7523 /// duplicate the original's ids.
7524 // # Should have variants here for prepend, insert before, insert after.... ???
7525 pub fn append_clone(&mut self, node: &mut Node, new_children: Vec<Node>) -> Result<()> {
7526 // Expand any document fragments
7527 let new_children = new_children
7528 .into_iter()
7529 .flat_map(|child| {
7530 if child.get_type() == Some(NodeType::DocumentFragNode) {
7531 child.get_child_nodes()
7532 } else {
7533 vec![child]
7534 }
7535 })
7536 .collect::<Vec<Node>>();
7537 // Now find all xml:id's in the new_children and record replacement id's for them
7538 let mut id_map = HashMap::default();
7539 // Find all id's defined in the copy and change the id.
7540 // Note: XPath ".//@xml:id" can fail to find namespace-qualified attributes.
7541 // Use DOM walking as fallback to ensure all ids are found.
7542 for child in new_children.iter() {
7543 let mut xpath_ids: Vec<String> = self.findvalues(".//@xml:id", Some(child));
7544 if xpath_ids.is_empty() {
7545 // Fallback: walk DOM to find xml:id attributes
7546 Self::collect_xml_ids_from(child, &mut xpath_ids);
7547 }
7548 for id in xpath_ids {
7549 id_map.insert(id.clone(), self.modify_id(id));
7550 }
7551 }
7552 // Now do the cloning (actually copying) and insertion.
7553 self.append_clone_aux(node, new_children, &mut id_map)
7554 }
7555
7556 /// Walk DOM to collect xml:id attribute values (fallback when XPath fails).
7557 fn collect_xml_ids_from(node: &Node, ids: &mut Vec<String>) {
7558 if let Some(id) = node.get_attribute("xml:id") {
7559 ids.push(id);
7560 } else if let Some(id) = node.get_attribute_ns("id", XML_NS) {
7561 ids.push(id);
7562 }
7563 for child in node.get_child_nodes() {
7564 if child.get_type() == Some(NodeType::ElementNode) {
7565 Self::collect_xml_ids_from(&child, ids);
7566 }
7567 }
7568 }
7569
7570 fn append_clone_aux(
7571 &mut self,
7572 node: &mut Node,
7573 new_children: Vec<Node>,
7574 id_map: &mut HashMap<String, String>,
7575 ) -> Result<()> {
7576 for child in new_children.into_iter() {
7577 match child.get_type() {
7578 Some(NodeType::ElementNode) => {
7579 let mut new = self.open_element_internal(
7580 node,
7581 child.get_namespace().map(|ns| ns.get_href()),
7582 &child.get_name(),
7583 )?;
7584 // Key order: `get_attributes` is a HashMap, libxml appends on set —
7585 // sort so a cloned subtree serializes deterministically
7586 // (`open_element_at` emits sorted; Perl's native clone keeps it).
7587 let mut attrs: Vec<(String, String)> = child.get_attributes().into_iter().collect();
7588 attrs.sort();
7589 // `get_attributes` names both an `xml:id` and an SVG element's plain `id` (the svg
7590 // schema's ID attribute) "id". Perl remaps only `xml:id` and copies every other
7591 // attribute as it is (Document.pm:1943-1954), so an SVG element's own `id` is copied
7592 // verbatim: remapped into an `xml:id`, the copy was schema-invalid (tikz-shields-doc,
7593 // a TikZ badge in a frontmatter contact). Only on SVG elements: elsewhere a bare `id`
7594 // stays the `xml:id` whose namespace a cloneNode stripped (1410.8508, below).
7595 let svg_id = if with_node_qname(&child, |qname| qname.starts_with("svg:")) {
7596 child.get_attribute_no_ns("id")
7597 } else {
7598 None
7599 };
7600 for (key, val) in attrs {
7601 match key.as_str() {
7602 // The walked mark of `record_svg_ids` stays on the original: the clone is a second
7603 // copy, so its own `svg:svg` close renames the ids it repeats, with their references.
7604 "_svgid" => {},
7605 "xml:id" | "id" if svg_id.is_some() => {
7606 new.set_attribute("id", svg_id.as_deref().unwrap_or_default())?;
7607 },
7608 "xml:id" | "id" => {
7609 // Use the replacement id. The pre-walk
7610 // (findvalues/collect_xml_ids_from) normally populates
7611 // id_map with every `xml:id` it can see, but the
7612 // namespace/prefix of the attribute key returned by
7613 // libxml2's `get_attributes()` can differ from what the
7614 // XPath / DOM walk picked up (e.g. when the incoming
7615 // node's tree came through a cloneNode that stripped
7616 // the xml namespace). Fall back to minting a fresh
7617 // replacement id on-the-fly rather than panicking —
7618 // 1410.8508 hit this when the pre-walk found zero ids
7619 // but attributes on a child node did carry xml:id.
7620 let fresh;
7621 let mapped_id = match id_map.get(&val) {
7622 Some(id) => id,
7623 None => {
7624 fresh = self.modify_id(val.clone());
7625 id_map.insert(val.clone(), fresh.clone());
7626 id_map.get(&val).unwrap()
7627 },
7628 };
7629 let newid = self.record_id_with_node(mapped_id, &new);
7630 // Write the literal "xml:id" key (not the bare "id" local-
7631 // name returned by libxml's get_attributes). Otherwise the
7632 // cloned node only gets a plain `id` attribute, and the
7633 // subsequent `after_open` chain's `has_attribute_ns("id",
7634 // XML_NS)` check returns false, causing `generate_id` to
7635 // mint a fresh `.<parent>.N` xml:id that doesn't match the
7636 // sibling XMRef idrefs (which were rewritten from id_map).
7637 // Witness: arXiv:2509.07628 — MathFork mainfork emitted
7638 // 154 XMRefs with `.mf` idrefs while the cloned target
7639 // nodes received parent-scoped `.m2.N` xml:ids, leaving
7640 // every XMRef dangling and triggering 4
7641 // `Error:expected:id` per equation during post-processing
7642 // visibility marking. Same shape applies anywhere a
7643 // cloned subtree carries xml:id attributes — MathFork,
7644 // tabular-cell clone, _Capture_ flush.
7645 new.set_attribute("xml:id", &newid)?;
7646 // Update id_map so subsequent idref lookups use the ACTUAL recorded id.
7647 // record_id_with_node may change the id (e.g., if there are conflicts),
7648 // so the mapped_id and newid may differ.
7649 if *mapped_id != newid {
7650 id_map.insert(val.clone(), newid);
7651 }
7652 },
7653 "idref" => {
7654 // Refer to the replacement id if it was replaced
7655 let id = id_map.get(&val).unwrap_or(&val);
7656 new.set_attribute(&key, id)?;
7657 },
7658 other_key =>
7659 // TODO: Are namespaced attributes successfully handled here? Check.
7660 {
7661 new.set_attribute(other_key, &val)?
7662 },
7663 };
7664 }
7665 // Carry the source node's box onto the clone, matching Perl: its
7666 // `cloneNode` copies the internal `_box` attribute, so `getNodeBox`
7667 // still resolves on the clone. Our node box is a side map keyed by
7668 // node identity, so a fresh clone is box-less unless carried
7669 // explicitly — the same invariant repaired in `rename_node_internal`
7670 // for arXiv/html_feedback#6873. This completes node-box carrying
7671 // across all four node-creating ops (open / wrap / rename / clone).
7672 // Latent today — the current `append_clone` sites (MathFork, contacts)
7673 // don't re-read a clone's box for size, and box-derived outputs
7674 // (`tex=`, ids) ride across as copied attributes — but it keeps a
7675 // future size-dependent afterClose on cloned SVG content from
7676 // silently misfiring the way the foreignObject y-flip transform did.
7677 if let Some(childbox) = self.get_node_box(&child) {
7678 self.set_node_box(&new, childbox);
7679 }
7680 self.after_open(&mut new)?;
7681 self.append_clone_aux(&mut new, child.get_child_nodes(), id_map)?;
7682 self.after_close(&mut new)?;
7683 },
7684 Some(NodeType::TextNode) => node.append_text(&child.get_content())?,
7685 Some(NodeType::CommentNode) => {
7686 // Skip XML comments during cloning (Perl also skips them in most contexts)
7687 },
7688 other => {
7689 emit_warn(
7690 "internal",
7691 "document",
7692 &format!("append_clone_aux: skipping unsupported {other:?} node type"),
7693 );
7694 },
7695 };
7696 }
7697 Ok(())
7698 }
7699
7700 //**********************************************************************
7701 // Wrapping & Unwrapping nodes by another element.
7702
7703 /// Wrap `nodes` with an element named `qname`, making the new element replace
7704 /// the first `node`, and all `nodes` becomes the child of the new node.
7705 /// \[this makes most sense if `nodes` are a sequence of siblings\]
7706 ///
7707 /// Returns `None` if `qname` isn't allowed in the parent, or if `nodes`
7708 /// aren't allowed in `qname`, otherwise the newly created `qname` — so a
7709 /// caller must treat "wrapped" as a request the model may decline, not as a
7710 /// guarantee. `None` also covers a first node with no parent (already
7711 /// detached, or the root): there is nothing to wrap it in place of. Witness
7712 /// 1804.09736.
7713 ///
7714 /// The wrapper inherits the parent's font and box, so wrapping does not
7715 /// change how the enclosed material renders. [`unwrap_nodes`](Self::unwrap_nodes)
7716 /// is the inverse.
7717 pub fn wrap_nodes(&mut self, qname: &str, nodes: Vec<Node>) -> Result<Option<Node>> {
7718 self.wrap_nodes_as(qname, nodes, &[])
7719 }
7720
7721 /// [`wrap_nodes`](Self::wrap_nodes), the wrapper carrying `attributes` from its opening, so its
7722 /// `after_open`/`after_close` hooks see them: an `xml:id` given here is the one `generate_id`
7723 /// keeps.
7724 pub fn wrap_nodes_as(
7725 &mut self,
7726 qname: &str,
7727 nodes: Vec<Node>,
7728 attributes: &[(String, String)],
7729 ) -> Result<Option<Node>> {
7730 if nodes.is_empty() {
7731 return Ok(None);
7732 }
7733 let first_node = &nodes[0];
7734 // Can't wrap a node that has no parent (already detached / is the root) —
7735 // return None like the other "can't wrap here" paths. Witness: 1804.09736.
7736 let Some(mut parent) = first_node.get_parent() else {
7737 return Ok(None);
7738 };
7739 let (ns, tag) = model::decode_qname(qname)?;
7740 let mut new = self.open_element_internal(&mut parent, ns, &tag)?;
7741 for (name, value) in attributes {
7742 self.set_attribute(&mut new, name, value)?;
7743 }
7744 self.after_open(&mut new)?;
7745 parent.replace_child_node(new.clone(), first_node.clone())?;
7746
7747 self.copy_node_font(&parent, &mut new)?;
7748
7749 if let Some(tbox) = self.get_node_box(&parent) {
7750 self.set_node_box(&new, tbox);
7751 }
7752 for mut node in nodes.into_iter() {
7753 node.unlink();
7754 new.add_child(&mut node)?;
7755 }
7756 self.after_close(&mut new)?;
7757 Ok(Some(new))
7758 }
7759
7760 /// Unwrap the children of $node, by replacing $node by its children.
7761 pub fn unwrap_nodes(&mut self, node: Node) -> Result<()> {
7762 let children = node.get_child_nodes();
7763 self.replace_node(node, children)
7764 }
7765
7766 /// Replace `node` by `nodes` (presumably descendants of some kind?)
7767 // DG: Don't return the replaced `node`, as it is groudns for memory management trouble
7768 // with the low-level libxml layer. I've encountered segfaults here.
7769 ///
7770 /// No box changes hands (Perl Document.pm:2011-2025): Perl's first
7771 /// `replaceChild` moves `node` into a document fragment, so its `removeNode`
7772 /// finds no parent element whose box to update, and its closing
7773 /// `appendNodeBox` map runs over the `@nodes` its `while (shift)` loop has
7774 /// emptied. Only a `node` replaced by nothing leaves its parent's box, as
7775 /// `removeNode` does. The `\@framebox` unwrap inside an auto-opened picture
7776 /// keeps the frame's size (`x \put(0,0){A} \fbox{…} y`). Guard:
7777 /// `node_box_append::replacing_a_node_keeps_the_boxes`.
7778 pub fn replace_node(&mut self, mut node: Node, with: Vec<Node>) -> Result<()> {
7779 if node.get_parent().is_some() {
7780 let replaced = !with.is_empty();
7781 // libxml2's xmlAddNextSibling merges consecutive text nodes: when both
7782 // the reference sibling and the new node are TextNode, it appends the
7783 // new node's content to the reference node and frees the new node. The
7784 // Rust wrapper doesn't surface the merged result, so naively advancing
7785 // `c0_opt` to `with_node` would capture a pointer to freed memory,
7786 // producing silent data loss for the third+ insertion and eventually
7787 // a libxml2 SIGSEGV when the dangling pointer is re-traversed (e.g.
7788 // during a later XPath evaluation). Detect the text-text case and
7789 // coalesce in-place instead.
7790 let mut c0_opt: Option<Node> = None;
7791 for mut with_node in with.into_iter() {
7792 with_node.unlink();
7793 let is_text = with_node.get_type() == Some(NodeType::TextNode);
7794 if let Some(mut c0) = c0_opt {
7795 let c0_is_text = c0.get_type() == Some(NodeType::TextNode);
7796 if is_text && c0_is_text {
7797 let existing = c0.get_content();
7798 let added = with_node.get_content();
7799 c0.set_content(&format!("{existing}{added}"))?;
7800 // with_node is a standalone (unlinked) text node whose content
7801 // now lives in c0: free it (see `remove_node`).
7802 self.discard_subtree(with_node);
7803 c0_opt = Some(c0);
7804 continue;
7805 }
7806 c0.add_next_sibling(&mut with_node)?;
7807 } else {
7808 // first node, swap in
7809 node.add_next_sibling(&mut with_node)?;
7810 }
7811 c0_opt = Some(with_node);
7812 }
7813 if replaced {
7814 self.remove_node_keeping_box(node);
7815 } else {
7816 self.remove_node(node);
7817 }
7818 }
7819 Ok(())
7820 }
7821
7822 /// Replace `node` by `with` as Perl's `replaceTree` (Document.pm:2079-2091)
7823 /// does with their boxes: `node`'s box leaves its parent's (`removeNode`
7824 /// while `node` is still in place), then each element of `with` is recorded
7825 /// as `appendTree` → `openElementAt` records a node it re-creates — its own
7826 /// box, else the parent's, else the box being absorbed — which extends an
7827 /// auto-opened parent's box (`appendNodeBox`). `cleanup_math` unwraps a
7828 /// Math that holds only text this way (TeX_Math.pool.ltxml:219): the
7829 /// auto-opened `svg:foreignObject` around an `\hbox` in an xymatrix cell
7830 /// measures the `\hbox` in place of the Math (tests/graphics/xytest).
7831 pub fn replace_node_as_tree(&mut self, node: Node, with: Vec<Node>) -> Result<()> {
7832 let Some(parent) = node.get_parent() else {
7833 return Ok(());
7834 };
7835 if with.is_empty() {
7836 self.remove_node(node);
7837 return Ok(());
7838 }
7839 if let Some(nodebox) = self.get_node_box(&node) {
7840 self.remove_node_box(&parent, &nodebox);
7841 }
7842 let elements: Vec<Node> = with
7843 .iter()
7844 .filter(|n| n.get_type() == Some(NodeType::ElementNode))
7845 .cloned()
7846 .collect();
7847 let has_text = elements.len() < with.len();
7848 self.replace_node(node, with)?;
7849 for element in elements {
7850 let element_box = self
7851 .get_node_box(&element)
7852 .or_else(|| self.get_node_box(&parent))
7853 .or_else(|| self.box_to_absorb.clone());
7854 if let Some(element_box) = element_box {
7855 self.append_node_box(&element, &element_box);
7856 }
7857 }
7858 // Text pieces (an `XMHint`'s spaces) Perl's `appendTree` adds raw, with no
7859 // box. An auto-opened `svg:foreignObject` left with no box at all (the
7860 // `$\phantom{H}$` of a quantikz cell) Perl then turns into `svg:text`
7861 // (TeX_Box.pool.ltxml:386-389), which needs no size; the Rust
7862 // foreignObject stays and must be sized, so it records the box being
7863 // absorbed, as text arriving at an auto-opened node does
7864 // (`openText_internal`, Document.pm:1149-1150). OXIDIZED_DESIGN_DIVERGENCES
7865 // #319; guard `cluster_schema::empty_node_foreign_object_is_sized`.
7866 if has_text
7867 && is_autoopened_element(&parent)
7868 && get_node_qname(&parent) == pin!("svg:foreignObject")
7869 && self.get_node_box(&parent).is_none()
7870 && let Some(absorbed) = self.box_to_absorb.clone()
7871 {
7872 self.append_node_box(&parent, &absorbed);
7873 }
7874 Ok(())
7875 }
7876
7877 /// Rename an element to `newname`, returning the new node.
7878 ///
7879 /// Not an in-place rename: a fresh element is opened next to the original,
7880 /// the attributes and (when `reinsert`) the children are carried over, and
7881 /// the original is removed. Perl went this way "initially since
7882 /// `$node->setNodeName` was broken in XML::LibXML 1.58", and kept it because
7883 /// building the replacement through the normal open path is what runs the
7884 /// model's checks and `afterOpen` hooks for the new tag — a raw rename would
7885 /// leave an element the schema never vetted.
7886 ///
7887 /// [`rename_node_qsym`](Self::rename_node_qsym) is the same for an already
7888 /// interned name.
7889 pub fn rename_node(&mut self, node: Node, newname: &str, reinsert: bool) -> Result<Node> {
7890 let (ns, tag) = model::decode_qname(newname)?;
7891 let newsym = arena::pin(newname);
7892 self.rename_node_internal(node, newsym, ns, tag, reinsert)
7893 }
7894 pub fn rename_node_qsym(&mut self, node: Node, newsym: SymStr, reinsert: bool) -> Result<Node> {
7895 let (ns, tag) = model::decode_qname_sym(newsym)?;
7896 self.rename_node_internal(node, newsym, ns, tag, reinsert)
7897 }
7898 fn rename_node_internal(
7899 &mut self,
7900 mut node: Node,
7901 newname: SymStr,
7902 ns: Option<String>,
7903 tag: String,
7904 reinsert: bool,
7905 ) -> Result<Node> {
7906 let mut parent = node
7907 .get_parent()
7908 .expect("rename should never be called on an orphan or root node.");
7909 let mut new = self.open_element_internal(&mut parent, ns, &tag)?;
7910 // Move to the position AFTER node
7911 node.add_next_sibling(&mut new)?;
7912 // Copy ALL attributes from `node` to `newnode`, in key order (HashMap
7913 // iteration would serialize the renamed element's attributes in a
7914 // per-process random order; the original was emitted sorted).
7915 let mut id = None;
7916 let mut attrs: Vec<(String, String)> = node.get_attributes().into_iter().collect();
7917 attrs.sort();
7918 for (key, value) in attrs {
7919 // `get_attributes()` returns the `xml:id` attribute under its LOCAL name
7920 // `"id"` (it lives in the XML namespace), NOT the prefixed `"xml:id"`.
7921 // Capture it here so it can be re-registered on `new` AFTER `remove_node`
7922 // unrecords it below — and re-set it through `Document::set_attribute`
7923 // (which routes "id"/"xml:id" through `record_id_with_node` + the XML
7924 // namespace), rather than the raw `Node::set_attribute` copy used for
7925 // ordinary attributes (that would drop the namespace AND the idstore
7926 // registration). Missing this stranded the equation refnum id across
7927 // `rearrange_lone_ams_aligned`'s equation→equationgroup rename, leaving
7928 // the group with a generic paragraph id and dangling intra-math XMRefs
7929 // (witness 2311.01600; see docs/archive/EXPECTED_ID_XMREF_DESIGN_2026-06-08.md).
7930 if key == "xml:id" || key == "id" {
7931 id = Some(value);
7932 continue;
7933 }
7934 let can_have = model::can_have_attribute(newname, arena::pin(&key));
7935 if can_have {
7936 new.set_attribute(&key, &value)?;
7937 }
7938 }
7939 // AND move all content from `node` to `newnode`
7940 if !reinsert {
7941 for mut child in node.get_child_nodes() {
7942 child.unbind();
7943 new.add_child(&mut child)?;
7944 }
7945 } else {
7946 std::mem::swap(&mut self.node, &mut new);
7947 for mut child in node.get_child_nodes() {
7948 child.unbind();
7949 if child.get_type() == Some(NodeType::TextNode) {
7950 self.open_text_internal(&child.get_content())?;
7951 self.close_text_internal()?;
7952 } else {
7953 let child_qname = get_node_qname(&child);
7954 let mut point = self.find_insertion_point_qsym(child_qname, None)?;
7955 point.add_child(&mut child)?;
7956 }
7957 }
7958 std::mem::swap(&mut self.node, &mut new);
7959 }
7960 // Carry the node box across the rename. Perl's `renameNode` copies ALL of
7961 // `$node`'s attributes to `$new`, and the box is recorded as the internal
7962 // `_box` attribute, so `afterClose`'s `getNodeBox($new)` still finds it. Our
7963 // node box lives in a side map keyed by node identity — the fresh `new` node
7964 // would otherwise be box-less, so a size-dependent afterClose handler
7965 // misfires. Concretely: `insert_block` renames a `_CaptureBlock_` (which
7966 // carries the block's box) to `svg:foreignObject`; without the box, the fo's
7967 // afterClose (`tex_box.rs`, Perl `TeX_Box.pool.ltxml` L407-423) can't read a
7968 // size and skips the y-flip `transform="matrix(1 0 0 -1 0 h)"`, so a
7969 // `tabular` inside a `tcolorbox` `enhanced` skin renders upside down in the
7970 // TeX-y-up SVG group (arXiv/html_feedback#6873, paper 2601.13118 Table 2).
7971 if let Some(nodebox) = self.get_node_box(&node) {
7972 self.set_node_box(&new, nodebox);
7973 }
7974 // THEN call afterOpen... ?
7975 // It would normally be called before children added,
7976 // but how can we know if we're duplicated auto-added stuff?
7977 self.after_open(&mut new)?;
7978 self.after_close(&mut new)?;
7979 // Finally, remove the old node — its box stays where it is: `new` holds it
7980 // and lives on in its place. Perl's `removeNode` here (Document.pm:2064)
7981 // takes the box out of the parent's, so an XMText renamed to XMWrap by
7982 // `cleanup_XMText` drops a `\mbox`/`\raisebox`/`\hbox`/`\resizebox` from an
7983 // aligned cell's `tex` (KNOWN_PERL_ERRORS #272; witnesses 2605.07372,
7984 // 2605.17816, 2605.23113; guard `node_box_append::aligned_cells_keep_their_boxed_pieces`).
7985 self.remove_node_keeping_box(node);
7986
7987 // and FINALLY, we can register the new node under the id.
7988 // `Document::set_attribute("xml:id", …)` routes through
7989 // `record_id_with_node` (idstore registration + dedup) and sets the
7990 // correctly-namespaced `xml:id` attribute. Only set it when the new qname
7991 // can carry an id (mirrors the per-attribute `can_have_attribute` gate).
7992 if let Some(id) = id
7993 && model::can_have_attribute(newname, arena::pin("xml:id"))
7994 {
7995 self.set_attribute(&mut new, "xml:id", &id)?;
7996 }
7997
7998 Ok(new)
7999 }
8000
8001 /// Whitespace inside an explicit TYPEWRITER text wrapper is verbatim
8002 /// CONTENT (code indentation, measured by the sizing pass) — the p-edge
8003 /// trim recursion must not descend into it. During construction the
8004 /// public `font` attribute may not be written yet, so also decode the
8005 /// internal `_font`. `ltx:verbatim` itself is EXEMPT: Perl's edge trim
8006 /// descends into an inline `\verb` at a paragraph edge and trims its
8007 /// leading space (tokenize/verb.t), and we keep that parity.
8008 fn is_typewriter_wrapper(&self, node: &Node) -> bool {
8009 if name_is(node, "verbatim") {
8010 return false;
8011 }
8012 if node
8013 .get_attribute("font")
8014 .is_some_and(|f| f.contains("typewriter"))
8015 {
8016 return true;
8017 }
8018 node
8019 .get_attribute("_font")
8020 .and_then(|id| self.decode_font(&id))
8021 .is_some_and(|f| f.family.as_deref() == Some("typewriter"))
8022 }
8023
8024 pub fn trim_node_whitespace(&mut self, node: &Node) -> Result<()> {
8025 // A paragraph in a typewriter CONTEXT keeps its whitespace: verbatim
8026 // content is line-mapped into ltx:p's (fancyvrb et al.), where leading
8027 // spaces ARE the code indentation (2605.00468 JSON schemas flush-left)
8028 // and a space-only line is real content. Keyed on the PARENT's font
8029 // context — NOT on the node's own computed font, which is stamped from
8030 // whichever box auto-opened it (a prose paragraph STARTING with inline
8031 // \verb reads as typewriter and would wrongly keep its trailing prose
8032 // whitespace; tokenize/verb.t). Perl's own {verbatim} lands in
8033 // ltx:verbatim (no trim hook) so it never faces this; the raw-fancyvrb
8034 // constructs that do cannot be converted by Perl at all (fvextra
8035 // breaklines exceeds 7 min on a 6-line file) — surpass-Perl scope.
8036 if let Some(parent) = node.get_parent()
8037 && self.get_node_font(&parent).family.as_deref() == Some("typewriter")
8038 {
8039 return Ok(());
8040 }
8041 self.trim_node_left_whitespace(node)?;
8042 self.trim_node_right_whitespace(node)?;
8043 Ok(())
8044 }
8045
8046 fn trim_node_left_whitespace(&self, node: &Node) -> Result<()> {
8047 // An empty construction-time marker (`*_Capture_`: the frontmatter position mark, the cover-title marks) is no
8048 // content: the trim reaches past it, as it would were the marker not there.
8049 let mut candidate = node.get_first_child();
8050 while let Some(ref child) = candidate {
8051 if is_empty_capture_mark(child) {
8052 candidate = child.get_next_sibling();
8053 } else {
8054 break;
8055 }
8056 }
8057 if let Some(mut first_child) = candidate {
8058 match first_child.get_type() {
8059 Some(NodeType::TextNode) => {
8060 let content = first_child.get_content();
8061 // Perl: s/^ +// — only trim ASCII spaces, preserve unicode spaces (nbsp, em-space, etc.)
8062 let trimmed_content = content.trim_start_matches(' ');
8063 if !content.is_empty() && (trimmed_content != content) {
8064 first_child.set_content(trimmed_content)?;
8065 }
8066 },
8067 Some(NodeType::ElementNode) if !self.is_typewriter_wrapper(&first_child) => {
8068 self.trim_node_left_whitespace(&first_child)?
8069 },
8070 _ => {},
8071 };
8072 }
8073 Ok(())
8074 }
8075
8076 fn trim_node_right_whitespace(&mut self, node: &Node) -> Result<()> {
8077 // Skip trailing empty <text> font wrapper elements to find the real last content.
8078 // These are artifacts of font change tracking during alignment absorption.
8079 let mut candidate = node.get_last_child();
8080 while let Some(ref child) = candidate {
8081 if (child.get_type() == Some(NodeType::ElementNode)
8082 && name_is(child, "text")
8083 && child.get_first_child().is_none()
8084 && child.has_attribute("_noautoclose"))
8085 // …and an empty construction-time marker (`trim_node_left_whitespace`)
8086 || is_empty_capture_mark(child)
8087 {
8088 candidate = child.get_prev_sibling();
8089 } else {
8090 break;
8091 }
8092 }
8093 if let Some(mut last_child) = candidate {
8094 match last_child.get_type() {
8095 Some(NodeType::TextNode) => {
8096 let content = last_child.get_content();
8097 // Perl: s/\s+$// (TeX_Paragraph.pool.ltxml:190), all Unicode
8098 // whitespace: a U+2009 after text (babel french), the U+2002 U+200A
8099 // a classed column rule leaves at a cell's end (arydshln `:`/`;`,
8100 // repro kernel-alignment/cell_trim_unicode_space.tex). Like Perl's,
8101 // the trim reaches only the last text node, and the two engines
8102 // split text into nodes differently (SYNC_STATUS "A paragraph's
8103 // trailing whitespace").
8104 let trimmed_content = content.trim_end_matches(char::is_whitespace);
8105 if !content.is_empty() && (trimmed_content != content) {
8106 if trimmed_content.is_empty() {
8107 // Remove AND free the entirely-whitespace text node (see
8108 // `remove_node`: a bare unlink leaks it), purging its
8109 // `node_boxes` entry so a later node at the same address cannot
8110 // inherit the phantom box.
8111 self.discard_subtree(last_child);
8112 } else {
8113 last_child.set_content(trimmed_content)?;
8114 }
8115 }
8116 },
8117 Some(NodeType::ElementNode) if !self.is_typewriter_wrapper(&last_child) => {
8118 self.trim_node_right_whitespace(&last_child)?
8119 },
8120 _ => {},
8121 };
8122 }
8123 Ok(())
8124 }
8125
8126 pub fn add_resource(&mut self, resource: Resource) -> Result<()> {
8127 // let savenode_opt = self.float_to_element("ltx:resource", false);
8128 let savenode_opt = None;
8129 let mut attrib: HashMap<String, String> = HashMap::default();
8130 attrib.insert(s!("type"), resource.mimetype);
8131 attrib.insert(s!("media"), resource.media);
8132 // The origin matters only where post may keep the link without default resources: a remote source (OD #1249).
8133 if resource.origin == ResourceOrigin::Binding && is_remote(&resource.name) {
8134 attrib.insert(s!("class"), BINDING_RESOURCE_CLASS.to_string());
8135 }
8136 attrib.insert(s!("src"), resource.name);
8137 let content_box = Digested::from(Tbox {
8138 text: arena::pin(resource.content),
8139 ..Tbox::default()
8140 });
8141 self.insert_element("ltx:resource", vec![&content_box], Some(attrib))?;
8142 if let Some(savenode) = savenode_opt {
8143 self.set_node(&savenode);
8144 }
8145 Ok(())
8146 }
8147
8148 pub fn process_pending_resources(&mut self) -> Result<()> {
8149 let resources: Vec<Resource> = state::take_pending_resources();
8150 for resource in resources {
8151 self.add_resource(resource)?;
8152 }
8153 state::reset_pending_resources();
8154 Ok(())
8155 }
8156
8157 pub fn make_error(&mut self, error_class: &str, content: &str) -> Result<()> {
8158 let savenode_opt = if !self.is_openable("ltx:ERROR") {
8159 self.float_to_element("ltx:ERROR", false)?
8160 } else {
8161 None
8162 };
8163 self.open_element("ltx:ERROR", Some(string_map!("class"=>error_class)), None)?;
8164 // Perl `Document.pm:makeError` L1346: `openText_internal($self,
8165 // ToString($content))`. Drops the failing token name (`\foo`,
8166 // `\bar`, …) as visible text inside the ERROR element so the
8167 // HTML5 `<span class="ltx_ERROR ...">` is not empty. Without
8168 // this, the user sees a zero-width invisible span where the
8169 // problem source should be.
8170 if !content.is_empty() {
8171 self.open_text_internal(content)?;
8172 }
8173 self.close_element("ltx:ERROR")?;
8174 if let Some(savenode) = savenode_opt {
8175 self.set_node(&savenode);
8176 }
8177 Ok(())
8178 }
8179
8180 // The following "floatTo" operations find an appropriate point
8181 // within the document tree preceding the current insertion point.
8182 // They return undef (& issue a warning) if such a point cannot be found.
8183 // Otherwise, they move the current insertion point to the appropriate node,
8184 // and return the previous insertion point.
8185 // After you make whatever changes (insertions or whatever) to the tree,
8186 // you should do
8187 // document.set_node(savenode)
8188 // to reset the insertion point to where it had been.
8189
8190 /// Whether `node` is the insertion point's element or one of its ancestors.
8191 fn is_open_node(&self, node: &Node) -> bool {
8192 let mut current = Some(self.node.clone());
8193 while let Some(n) = current {
8194 if &n == node {
8195 return true;
8196 }
8197 current = n.get_parent();
8198 }
8199 false
8200 }
8201
8202 /// [`Self::float_to_element`] (closing form) for an element a frontmatter container (`ltx:abstract`…) refuses,
8203 /// when the insertion point is inside one: the element goes to the nearest open ancestor that admits it, as Perl's
8204 /// `floatToElement` places one (Document.pm:1052-1077), and the insertion point comes back (the saved node is
8205 /// returned for the caller to restore), so what follows stays in the container. Elsewhere `None`: the element is
8206 /// inserted where it stands, by [`Self::find_insertion_point`]'s rules. A `\tableofcontents` inside an abstract
8207 /// (1011.3976, 1602.08755, 2007.03709; OXIDIZED_DESIGN_DIVERGENCES #753).
8208 pub fn float_out_of_frontmatter(&mut self, qname: &str) -> Result<Option<Node>> {
8209 if outside_frontmatter_container(&self.node) {
8210 return Ok(None);
8211 }
8212 self.float_to_element(qname, true)
8213 }
8214
8215 /// Find a node in the document that can contain an element `qname`
8216 pub fn float_to_element(&mut self, qname: &str, closeifpossible: bool) -> Result<Option<Node>> {
8217 let mut candidates: VecDeque<Node> = VecDeque::from(self.get_insertion_candidates(&self.node));
8218 let mut closeable = true;
8219 // If the current node can contain already, we're fine right here - just return
8220 if !candidates.is_empty() && can_contain(&candidates[0], qname) {
8221 // Edge case: Don't resume at a text node, if it is current.
8222 // Don't append more to it after other insertions.
8223 if self.node.get_type() == Some(NodeType::TextNode) {
8224 self.set_node(&candidates[0]);
8225 }
8226 return Ok(candidates.pop_front());
8227 }
8228 // The closing form (`^^`) reaches a container by closing up to it, which only an OPEN node — the insertion
8229 // point's element or one of its ancestors — can be (Perl `closeToNode`, Document.pm:869, walks ancestors). The
8230 // candidates also hold a text node's previous siblings (Perl `getInsertionCandidates`, Document.pm:1020-1032,
8231 // there for the non-closing form to enter), so while the walk can still close they are passed over: neither chosen
8232 // nor counted towards `closeable`. Closing to one reported "Attempt to close … which isn't open" over an unchanged
8233 // tree (a minipage that already holds a float, then `\caption` after its `\end{minipage}` line: 2609.15558, 33998);
8234 // and a sibling that cannot auto-close (a Math, a rule) between two such minipages must not stop the closing walk
8235 // and send the float into the earlier box (OXIDIZED_DESIGN_DIVERGENCES #455).
8236 while let Some(candidate) = candidates.front() {
8237 if closeifpossible && closeable && !self.is_open_node(candidate) {
8238 candidates.pop_front();
8239 continue;
8240 }
8241 if can_contain(candidate, qname) {
8242 break;
8243 }
8244 if closeable {
8245 closeable = can_auto_close(candidate);
8246 }
8247 candidates.pop_front();
8248 }
8249 match candidates.pop_front() {
8250 Some(n) => {
8251 if closeifpossible && closeable {
8252 self.close_to_node(&n, false)?;
8253 } else {
8254 let savenode = self.node.clone();
8255 self.set_node(&n);
8256 // Debug!("Floating from " . Stringify($savenode) . " to " . Stringify($n) . " for
8257 // $qname") if ($$savenode ne $$n) && $LaTeXML::DEBUG{document};
8258 return Ok(Some(savenode));
8259 }
8260 },
8261 _ => {
8262 if can_contain_node_somehow(&self.node, qname).is_none() {
8263 Warn!(
8264 "malformed",
8265 qname,
8266 s!("No open node can contain element '{}'", qname)
8267 );
8268 // self.get_insertion_context())
8269 }
8270 },
8271 }
8272 Ok(None)
8273 }
8274
8275 // find a node that can accept a label.
8276 // A bit more than just whether the element can have the attribute, but
8277 // whether it has an id (and ideally either a refnum or title)
8278 pub fn float_to_label(&mut self) -> Option<Node> { self.float_to_label_for(None) }
8279
8280 /// [`float_to_label`](Self::float_to_label) for a label that names a counter step no element took (`raw_step`, the
8281 /// step's serial: a raw `\refstepcounter`, `binding::counter::current_raw_refstep`), which a picture may carry: a box
8282 /// drawn as a picture frame is the object such a step numbers (tcolorbox's `\refstepcounter` in its phantom code,
8283 /// tcolorbox.sty:2311 and :1154-1161, placed in the frame at :1925; a `\put` in a `picture`), as LaTeX's `\label`
8284 /// after the step names the step's anchor (latex.ltx:14963-14967 `\@currentlabel`). An object another raw step
8285 /// numbered ([`take_raw_refstep_number`](Self::take_raw_refstep_number)) is not this step's: the label climbs past it,
8286 /// as Perl's does (a second `\put` step in one `picture`; pdflatex prints each step's number, an object this port
8287 /// cannot give, OXIDIZED_DESIGN_DIVERGENCES #813). Any other label climbs past a picture, and past an object a raw
8288 /// step numbered (whose number its `\@currentlabel` is not: a `{gather*}` row's `\label` after the `\labelrel` idiom's
8289 /// immediate one, 2310.19138), to the object its step numbered, as Perl's does (Document.pm:1098-1127; the picture
8290 /// carries no `labels` there). Witnesses: 2506.01072
8291 /// (`\newtcbtheorem`), 2505.20088 (`[auto counter]`), 2402.06608 (`[blend into=figures]`), 2609.20563
8292 /// (`\newtcblisting`). An object inside `ltx:Math` (the box of a `\text{\begin{tcolorbox}…}` in a display) is not
8293 /// the step's either: its id does not survive the math's rendering, so the label climbs out of the math to where
8294 /// Perl's lands: a display, which takes the step's number when it has none
8295 /// ([`take_raw_refstep_number`](Self::take_raw_refstep_number): a `{gather*}` row, `\[…\]`) and keeps its own
8296 /// otherwise (a numbered `{equation}`), or past an inline formula the enclosing unit, whose number `\ref` prints
8297 /// (OXIDIZED_DESIGN_DIVERGENCES #813). Repro `cross-references/math_box_label_climbs_to_the_display.tex`.
8298 pub fn float_to_label_for(&mut self, raw_step: Option<i64>) -> Option<Node> {
8299 self.float_to_label_scoped(raw_step, false)
8300 }
8301
8302 /// [`float_to_label_for`](Self::float_to_label_for) for a label that follows a counter step a group has since
8303 /// undone (`after_undone_step`, `binding::counter::label_follows_an_undone_step`): it names the step still in scope,
8304 /// not the object just closed beside it (Perl's last-child start, Document.pm:1103-1104), so the climb starts at the
8305 /// current node. Where no ancestor takes it, Perl's fallback (:1113-1119, the last child, else the root) stays: a
8306 /// label at the document's own level (lastpage's `\AtEndDocument{\label{lastpage}}`) keeps its old place, where the
8307 /// root taking it gave the root an id and renumbered every generated one. Witness math0107195: a `\label` after an
8308 /// inner `equation`, still inside a theorem, names the theorem ("Theorem 5.3"; Perl and int52a the equation's 16,
8309 /// KNOWN_PERL_ERRORS #1092; OXIDIZED_DESIGN_DIVERGENCES #856). Repro
8310 /// `cross-references/label_after_an_inner_equation_names_the_theorem.tex`.
8311 pub fn float_to_label_scoped(
8312 &mut self,
8313 raw_step: Option<i64>,
8314 after_undone_step: bool,
8315 ) -> Option<Node> {
8316 let key = "labels";
8317 // The object that printed the step's number itself (an algorithm2e line, `note_raw_refstep_object`) takes the
8318 // label wherever it stands, as `\@currentlabel` is that number until the next step: in the line, or after it, at
8319 // the start of the next line or of a block (`stmt\; \label{x}`, `\While{c}{\label{x} …}`: pdflatex the line's
8320 // number). Its id is made only later (the `\lx@label` hook, sect11.rs). Witnesses 2406.05437 (`step1`, `step2`:
8321 // PDF 14, 17), 1602.05866 (`algline:mainloop`, PDF 8); OXIDIZED_DESIGN_DIVERGENCES #877.
8322 if let Some(object) = raw_step
8323 .and_then(|serial| self.raw_refstep_objects.get(&serial))
8324 .filter(|object| object.get_parent().is_some())
8325 .cloned()
8326 {
8327 let savenode = self.node.clone();
8328 self.set_node(&object);
8329 return Some(savenode);
8330 }
8331 let may_label = |node: &Node| {
8332 can_node_have_attribute(node, key)
8333 && node.has_attribute_ns("id", XML_NS)
8334 && match raw_step {
8335 Some(serial) => {
8336 node
8337 .get_attribute(RAW_REFSTEP_MARK)
8338 .is_none_or(|numbered| numbered == serial.to_string())
8339 && !within_math(node)
8340 },
8341 None => {
8342 get_node_qname(node) != pin!("ltx:picture")
8343 && node.get_attribute(RAW_REFSTEP_MARK).is_none()
8344 },
8345 }
8346 };
8347 // Perl: start from lastChild of current node if it's an element
8348 let start = if self.node.get_type() == Some(NodeType::ElementNode) && !after_undone_step {
8349 self
8350 .node
8351 .get_last_child()
8352 .unwrap_or_else(|| self.node.clone())
8353 } else {
8354 self.node.clone()
8355 };
8356 let ancestors: Vec<Node> = self
8357 .get_insertion_candidates(&start)
8358 .into_iter()
8359 .filter(|node| node.get_type() == Some(NodeType::ElementNode))
8360 .collect();
8361 let mut candidates: VecDeque<&Node> = ancestors.iter().collect();
8362 // Should we only accept a node that already has an id, or should we create an id?
8363 let mut node_opt: Option<Cow<Node>> = None;
8364 while let Some(candidate) = candidates.pop_front() {
8365 if may_label(candidate) {
8366 node_opt = Some(Cow::Borrowed(candidate));
8367 break;
8368 }
8369 }
8370
8371 if node_opt.is_none() {
8372 // No appropriate ancestor?
8373 let sib: Option<Node> = match ancestors.first() {
8374 Some(n) => n.get_last_child(),
8375 None => None,
8376 };
8377 if let Some(sibling) = sib {
8378 if may_label(&sibling) {
8379 node_opt = Some(Cow::Owned(sibling));
8380 } else if !ancestors.is_empty() {
8381 // just take root element?
8382 node_opt = Some(Cow::Borrowed(ancestors.last().as_ref().unwrap()));
8383 }
8384 } else if !ancestors.is_empty() {
8385 // just take root element?
8386 node_opt = Some(Cow::Borrowed(ancestors.last().as_ref().unwrap()));
8387 }
8388 }
8389 if let Some(node) = node_opt {
8390 let savenode = self.node.clone();
8391 self.set_node(&node);
8392 Some(savenode)
8393 } else {
8394 let message = s!("No open node with an xml:id can get attribute {:?}", key);
8395 Warn!("malformed", key, message);
8396 // $self->getInsertionContext());
8397 None
8398 }
8399 }
8400
8401 /// The object a label after a raw counter step names (the node [`float_to_label_for`](Self::float_to_label_for)
8402 /// found, current) takes the step's number: the `tags` LaTeXML makes for every step
8403 /// (`binding::counter::dialect::label_stepped_counter`), whose `refnum` is what `\ref` prints, as LaTeX's `\ref`
8404 /// prints the step's `\@currentlabel` (latex.ltx:14963-14967). Only an object with no number of its own (no
8405 /// `ltx:tags`: a box drawn as a picture, a listing's line) that may hold one and is not a unit numbered by its heading
8406 /// (an `ltx:title` holder: an unnumbered `\section*` or theorem stays unnumbered). The tag without a role, the number
8407 /// as the object prints it, is not kept: the box printed its number itself (tcolorbox's title "Theorem 1: …"). The
8408 /// object is marked with the step's `serial` (`_raw_refstep`, a bookkeeping attribute), so another step's label does
8409 /// not take it. Perl leaves the label on the enclosing section, whose number `\ref` prints (KNOWN_PERL_ERRORS
8410 /// #1038). Witnesses: 2506.01072 (`\newtcbtheorem`), 2505.20088 (`\newtcolorbox[auto counter]`), 2402.06608,
8411 /// 2609.20563 (`\newtcblisting`); guards `perfect_kernel_batch78g`.
8412 pub fn take_raw_refstep_number(&mut self, tags: &Digested, serial: i64) -> Result<()> {
8413 let mut target = self.node.clone();
8414 let qname = get_node_qname(&target);
8415 let own_tags = target
8416 .get_child_elements()
8417 .into_iter()
8418 .find(|child| get_node_qname(child) == pin!("ltx:tags"));
8419 if let Some(own_tags) = own_tags {
8420 // An object that printed the step's number itself and gives no reference form (an algorithm2e line's tag:
8421 // `\nl`'s `\refstepcounter{AlgoLine}` then `\algocf@printnl`, algorithm2e.sty:1662-1667) takes the step's
8422 // reference forms into its tags, after the printed one: `\ref` prints `\theAlgoLine` (pdflatex 14 for
8423 // 2406.05437's `step1`, which named the algorithm, 1; OXIDIZED_DESIGN_DIVERGENCES #877).
8424 let numbered_here = target.get_attribute(RAW_REFSTEP_MARK) == Some(serial.to_string());
8425 let has_forms = own_tags
8426 .get_child_elements()
8427 .iter()
8428 .any(|tag| tag.has_attribute("role"));
8429 if numbered_here && !has_forms {
8430 self.add_reference_forms(&target, own_tags, tags)?;
8431 }
8432 return Ok(());
8433 }
8434 if !can_contain_qsym(qname, pin!("ltx:tags")) || can_contain_qsym(qname, pin!("ltx:title")) {
8435 return Ok(());
8436 }
8437 let before = target.get_child_nodes();
8438 self.absorb(tags, None)?;
8439 let _ = target.set_attribute(RAW_REFSTEP_MARK, &serial.to_string());
8440 let first = before.first().cloned();
8441 for mut new in target.get_child_nodes() {
8442 if before.contains(&new) {
8443 continue;
8444 }
8445 for tag in new.get_child_elements() {
8446 if get_node_qname(&tag) == pin!("ltx:tag") && !tag.has_attribute("role") {
8447 self.remove_node(tag);
8448 }
8449 }
8450 // The number first, where an object's `ltx:tags` stands.
8451 if let Some(mut first) = first.clone() {
8452 new.unlink_node();
8453 first.add_prev_sibling(&mut new).ok();
8454 }
8455 }
8456 Ok(())
8457 }
8458
8459 /// Records `object` as the one that printed the number of the raw counter step `serial` itself (an algorithm2e line:
8460 /// `\nl`'s `\refstepcounter{AlgoLine}` then `\algocf@printnl`), marking it (`RAW_REFSTEP_MARK`): a label after the
8461 /// step names it ([`float_to_label_scoped`](Self::float_to_label_scoped)) and takes its reference forms
8462 /// ([`take_raw_refstep_number`](Self::take_raw_refstep_number)).
8463 pub fn note_raw_refstep_object(&mut self, serial: i64, object: &Node) {
8464 let mut object = object.clone();
8465 let _ = object.set_attribute(RAW_REFSTEP_MARK, &serial.to_string());
8466 self.raw_refstep_objects.insert(serial, object);
8467 }
8468
8469 /// A `\label{key}` placed on `holder` takes `key` from the elements holding it before that contain `holder` or that it
8470 /// contains: LaTeX's last `\newlabel` wins (latex.ltx `\@newl@bel`: `\global\@namedef{r@key}`, "Label multiply
8471 /// defined"), where the post scan registers in document order, the outer element first (Perl Scan.pm:196-203, ours
8472 /// `latexml_post/src/scan.rs` `register_scanned`), so an earlier label on an element inside a later one won: 2001.00288's
8473 /// `\label{algo2}` after `\KwOut` (its line) and again after `\caption` (the algorithm) printed "Algorithm 1" for
8474 /// pdflatex's "Algorithm 2" (KNOWN_PERL_ERRORS #1131, OXIDIZED_DESIGN_DIVERGENCES #877). Holders apart from each other
8475 /// keep the key: pdflatex's last `\newlabel` is the last written, the later in the document but for a float LaTeX
8476 /// defers past a later label of the key (not modelled: `[p]` figure then `\section{Two}\label{k}`, pdflatex the
8477 /// figure), and the scan already takes the later; an element
8478 /// the streaming build spilled may be one (spills are closed top-level elements, never `holder`'s ancestors or, below
8479 /// the document root, its descendants), so streaming and eager builds agree. Searched only for a key placed before.
8480 /// Guard `perfect_kernel_batch78t::the_later_label_wins`.
8481 pub fn release_earlier_label_holders(&mut self, key: &str, holder: &Node) {
8482 if self.placed_labels.insert(key.to_string()) {
8483 return;
8484 }
8485 // The document root holds what no element took; its descendants may have been spilled.
8486 let Some(parent) = holder
8487 .get_parent()
8488 .filter(|p| p.get_type() == Some(NodeType::ElementNode))
8489 else {
8490 return;
8491 };
8492 let mut nested = self.findnodes("descendant::*[@labels]", Some(holder));
8493 let mut ancestor = Some(parent);
8494 while let Some(node) = ancestor {
8495 ancestor = node
8496 .get_parent()
8497 .filter(|p| p.get_type() == Some(NodeType::ElementNode));
8498 nested.push(node);
8499 }
8500 for mut node in nested {
8501 let Some(labels) = node.get_attribute("labels") else {
8502 continue;
8503 };
8504 if !labels.split_whitespace().any(|label| label == key) {
8505 continue;
8506 }
8507 let rest: Vec<&str> = labels
8508 .split_whitespace()
8509 .filter(|label| *label != key)
8510 .collect();
8511 if rest.is_empty() {
8512 let _ = node.remove_attribute("labels");
8513 } else {
8514 let _ = node.set_attribute("labels", &rest.join(" "));
8515 }
8516 }
8517 }
8518
8519 /// The reference forms of `tags` (its tags with a role: refnum, typerefnum, …) appended to `own_tags`, an `ltx:tags`
8520 /// of `target` ([`take_raw_refstep_number`](Self::take_raw_refstep_number)).
8521 fn add_reference_forms(
8522 &mut self,
8523 target: &Node,
8524 mut own_tags: Node,
8525 tags: &Digested,
8526 ) -> Result<()> {
8527 let before = target.get_child_nodes();
8528 let savenode = self.node.clone();
8529 self.set_node(target);
8530 self.absorb(tags, None)?;
8531 self.set_node(&savenode);
8532 for new in target.get_child_nodes() {
8533 if before.contains(&new) {
8534 continue;
8535 }
8536 for mut tag in new.get_child_elements() {
8537 if get_node_qname(&tag) == pin!("ltx:tag") && tag.has_attribute("role") {
8538 tag.unlink_node();
8539 own_tags.add_child(&mut tag).ok();
8540 }
8541 }
8542 self.remove_node(new);
8543 }
8544 Ok(())
8545 }
8546
8547 /// One `ltx:tags` for an object a raw step numbered ([`take_raw_refstep_number`](Self::take_raw_refstep_number))
8548 /// that a later construct tags as well (`\eqno`'s, made after the label in `$$ \refstepcounter{foo}\label{x2} c=d
8549 /// \eqno(B) $$`): the later tags' tags join the step's `ltx:tags`, before its `refnum`, so the object shows "(B)" and
8550 /// `\ref` prints the step's number (pdflatex 42; the `\@currentlabel` `\eqno` leaves alone). The nearest open
8551 /// element holding an `ltx:tags`, from the current node. Repro
8552 /// `cross-references/unnumbered_display_label_takes_the_step_number.tex`.
8553 pub fn merge_raw_refstep_tags(&mut self) {
8554 let mut node = Some(self.node.clone());
8555 while let Some(current) = node {
8556 let tags: Vec<Node> = current
8557 .get_child_elements()
8558 .into_iter()
8559 .filter(|child| get_node_qname(child) == pin!("ltx:tags"))
8560 .collect();
8561 if !tags.is_empty() {
8562 if tags.len() > 1 && current.get_attribute(RAW_REFSTEP_MARK).is_some() {
8563 let mut first = tags[0].clone();
8564 let anchor = first.get_first_child();
8565 for mut later in tags.into_iter().skip(1) {
8566 for mut tag in later.get_child_nodes() {
8567 tag.unlink_node();
8568 match &anchor {
8569 Some(anchor) => {
8570 let mut anchor = anchor.clone();
8571 anchor.add_prev_sibling(&mut tag).ok();
8572 },
8573 None => {
8574 first.add_child(&mut tag).ok();
8575 },
8576 }
8577 }
8578 later.unlink_node();
8579 }
8580 }
8581 return;
8582 }
8583 node = current
8584 .get_parent()
8585 .filter(|p| p.get_type() == Some(NodeType::ElementNode));
8586 }
8587 }
8588
8589 pub fn set_box_to_absorb(&mut self, arg: Option<Digested>) {
8590 self
8591 .localized_boxes
8592 .push((self.box_to_absorb.take(), self.box_unended));
8593 // A whatsit the document ended inside of never ended (OXIDIZED_DESIGN #542). Any other box
8594 // shares the state of the one absorbing it: an alignment is its `\lx@begin@alignment`
8595 // whatsit's property, a cell's content opens the cell's `ltx:XMArg` (nucl-th0401019).
8596 self.box_unended = match arg {
8597 Some(ref tbox) if matches!(tbox.data(), DigestedData::Whatsit(_)) => {
8598 tbox.get_property_bool(crate::stomach::UNENDED)
8599 },
8600 Some(_) => self.box_unended,
8601 None => false,
8602 };
8603 self
8604 .localized_box_locators
8605 .push(self.current_box_locator.take());
8606 self.box_to_absorb = arg;
8607 // Capture the locator now, while the box's RefCell is unborrowed — the
8608 // source-map stamping (`open_element`) reads this Copy value instead of
8609 // re-borrowing the box mid-`be_absorbed`. Gated so the normal path is free.
8610 self.current_box_locator = if state::source_map_enabled() {
8611 self.box_to_absorb.as_ref().and_then(|b| b.get_locator())
8612 } else {
8613 None
8614 };
8615 }
8616 /// Whether the box being absorbed never ended ([`crate::stomach::UNENDED`]): the elements it
8617 /// opens auto-close ([`UNENDED_ATTRIBUTE`]).
8618 fn absorbing_unended_box(&self) -> bool { self.box_unended }
8619
8620 pub fn expire_box_to_absorb(&mut self) {
8621 (self.box_to_absorb, self.box_unended) = self.localized_boxes.pop().unwrap();
8622 self.current_box_locator = self.localized_box_locators.pop().unwrap_or(None);
8623 }
8624
8625 /// token-locators: directly set the locator used to stamp the NEXT opened
8626 /// element, without touching the `box_to_absorb` stack. The alignment absorb
8627 /// uses this to give each `tabular`/`tr`/`td` its own (table/row/cell) span,
8628 /// since those elements are opened *before* their content's `box_to_absorb`
8629 /// is set. Transient: each cell overwrites it and the enclosing
8630 /// `expire_box_to_absorb` (the Alignment absorb frame) restores the prior
8631 /// value. See docs/performance/SOURCE_PROVENANCE.md §3.1.3.
8632 #[cfg(feature = "token-locators")]
8633 pub fn set_current_box_locator(&mut self, loc: Option<Locator>) {
8634 self.current_box_locator = loc;
8635 }
8636
8637 /// Resolve a rewrite label: this document's own labels first, then the
8638 /// shared document-wide map a streaming fragment carries
8639 /// (`rewrite_labels_shared`). The two-level lookup replaces copying the
8640 /// whole label index into every fragment — see the field docs.
8641 pub fn lookup_rewrite_label(&self, key: &str) -> Option<String> {
8642 self
8643 .rewrite_labels
8644 .get(key)
8645 .or_else(|| {
8646 self
8647 .rewrite_labels_shared
8648 .as_ref()
8649 .and_then(|shared| shared.get(key))
8650 })
8651 .cloned()
8652 }
8653
8654 pub fn load_labels_for_rewrite(&mut self) -> Result<()> {
8655 // Perl Rewrite.pm:38's `//*[@labels]`, walked (#802).
8656 for mut node in self.find_elements(|n| n.has_attribute_no_ns("labels")) {
8657 if let Some(labels) = node.get_attribute("labels") {
8658 // A labelled node MUST carry an xml:id so `\ref` can resolve to it.
8659 // The `Tag('ltx:*', afterClose:late)` GenerateID hook
8660 // (latex_constructs/sect11.rs) stamps one when the node closes — the
8661 // <ltx:document> root too, which receives a label when a bare
8662 // `\label{…}` appears with no enclosing id'd sectioning (e.g.
8663 // `\input{abs}` then `\label{sec:intro}` before any \section; witness
8664 // 1703.09326; Perl's output is `<document … labels="LABEL:sec:intro"
8665 // xml:id="id1">`). This is the safety net for a labelled node still
8666 // without one: generate it here, exactly as Perl's GenerateID does (an
8667 // id-less root yields "id1" from `generate_id`'s empty-prefix→"id",
8668 // no-ancestor path), never an error.
8669 let id = match node.get_attribute("id") {
8670 Some(id) => Some(id),
8671 None => {
8672 self.generate_id(&mut node, "")?;
8673 node.get_attribute_ns("id", XML_NS)
8674 },
8675 };
8676 if let Some(id) = id {
8677 for label in labels.split_whitespace() {
8678 self.rewrite_labels.insert(label.to_string(), id.clone());
8679 }
8680 }
8681 // If generate_id still couldn't assign one (a node the model forbids
8682 // an xml:id on), the label is simply unresolvable — drop it silently
8683 // (Perl does not error here either).
8684 }
8685 }
8686 Ok(())
8687 }
8688
8689 fn set_local_font(&mut self, arg: Rc<Font>) { self.localized_fonts.push(arg); }
8690 fn get_local_font(&self) -> Option<Rc<Font>> { self.localized_fonts.last().cloned() }
8691 fn expire_local_font(&mut self) { self.localized_fonts.pop(); }
8692
8693 //**********************************************************************
8694 /// This function computes an xml:id for a node, if it hasn't already got one.
8695 /// It is suitable for use in Tag afterOpen as
8696 /// `Tag('ltx:para',afterOpen=>sub { GenerateID(@_,'p'); });`
8697 /// It generates an id of the form `<parentid>.<prefix><number>`
8698 /// The parent node (the one with `ID=<parentid>`) also maintains a counter
8699 /// stored in an attribute `_ID_counter_<prefix>` recording the last used
8700 /// `number` for `prefix` amongst its descendents.
8701 pub fn generate_id(&mut self, node: &mut Node, mut prefix: &str) -> Result<()> {
8702 // If node doesn't already have an id, and can
8703 // but isn't a _Capture_ node (which ultimately should disappear)
8704 let qname = get_node_qname(node);
8705 if !node.has_attribute_ns("id", XML_NS)
8706 && model::can_have_attribute(qname, pin!("xml:id"))
8707 && (qname != pin!("ltx:_Capture_"))
8708 {
8709 // Nearest ancestor element carrying @xml:id — a direct parent-chain
8710 // walk, equivalent to the previous `ancestor::*[@xml:id][1]` findnode
8711 // but without a per-call XPath parse+eval (generate_id runs once per
8712 // id-lacking node during finalize; 2026-08-23 audit R5).
8713 let mut found = None;
8714 let mut cur = node.get_parent();
8715 while let Some(p) = cur {
8716 if p.get_type() == Some(NodeType::ElementNode) && p.has_attribute_ns("id", XML_NS) {
8717 found = Some(p);
8718 break;
8719 }
8720 cur = p.get_parent();
8721 }
8722 // A streamed segment's top nodes are minted under the spine element it splices back under (pass 2).
8723 let anchor = found
8724 .is_none()
8725 .then(|| self.fragment_anchor_id.clone())
8726 .flatten();
8727 let mut ancestor = found.unwrap_or_else(|| self.get_document().get_root_element().unwrap());
8728 //// Old versions don't like ancestor.getAttribute('xml:id');
8729 let ancestor_id = ancestor.get_attribute_ns("id", XML_NS).or(anchor);
8730 // If we've got no ancestor_id, then we've got no ancestor (no document yet!),
8731 // or ancestor IS the root element (but without an id);
8732 // If we also have no prefix, we'll end up with an illegal id (just digits)!!!
8733 // We'll use "id" for an id prefix; this will work whether or not we have an ancestor.
8734 if prefix.is_empty() && ancestor_id.is_none() {
8735 prefix = "id";
8736 }
8737
8738 // Perl `Package.pm:939` (`'_ID_counter_' . ($prefix ? $prefix . '_' : '')`)
8739 // — empty prefix uses `_ID_counter_` with a single trailing underscore,
8740 // not `_ID_counter__`. Matters for interop with code that reads the
8741 // attribute by exact name (e.g. `Base_XMath.pool.ltxml:940` reads
8742 // `_ID_counter_` for the empty-prefix counter).
8743 let ctrkey = if prefix.is_empty() {
8744 s!("_ID_counter_")
8745 } else {
8746 s!("_ID_counter_") + prefix + "_"
8747 };
8748 let a_ctr = ancestor.get_attribute(&ctrkey).unwrap_or_else(|| s!("0"));
8749
8750 let ctr_int = 1 + a_ctr.parse::<u32>().unwrap_or(0);
8751 let ctr = ctr_int.to_string();
8752
8753 let id = match ancestor_id {
8754 Some(aid) => aid + ".",
8755 None => String::new(),
8756 } + prefix
8757 + &ctr;
8758
8759 ancestor.set_attribute(&ctrkey, &ctr)?;
8760 self.set_attribute(node, "xml:id", &id)?;
8761 }
8762 Ok(())
8763 }
8764
8765 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
8766 // Finally, another set of surgery methods
8767 // These take an array representation of the XML Tree to append
8768 // [tagname,{attributes..}, children]
8769 // THESE SHOULD BE PART OF A COMMON BASE CLASS; DUPLICATED IN Post::Document
8770 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
8771
8772 /// `replace_tree`, minus the free: the detached original stays alive and
8773 /// the CALLER owns it. The math parser needs this — parsing one formula
8774 /// rebuilds its tree while later formulae, queued up front, may sit inside
8775 /// the replaced subtree (a `\text{…$x$…}` inside math), so it defers every
8776 /// free to the end of the parse (`replace_tree_deferred` /
8777 /// `data::defer_discard`); freeing here handed those formulae to the parser
8778 /// detached and lost whole documents (sweep 102: glosmathtools, prftree,
8779 /// t-angles).
8780 pub fn replace_tree_detach(&mut self, new: Node, old: Node) -> Result<Option<Node>> {
8781 match old.get_parent() {
8782 Some(mut parent) => {
8783 let mut following = VecDeque::new(); // Collect the matching and following nodes
8784 while let Some(mut sib) = parent.get_last_child() {
8785 if sib == old {
8786 break;
8787 }
8788 // parent.remove_child(sib); // We're putting these back, in a moment!
8789 sib.unlink();
8790 following.push_front(sib);
8791 }
8792 // Unrecord old's ids BEFORE the copy, so the copy's freshly
8793 // recorded entries (append_tree → open_element_at) survive — the
8794 // copy typically re-uses the same id strings.
8795 self.unrecord_node_ids(&old);
8796 // COPY FIRST, detach `old` after: `new` may sit INSIDE `old`
8797 // (parse_single's single-node shortcut returns an original child;
8798 // tex_box's foreignObject cleanup replaces a node with its own
8799 // grandchild), so `old` must stay intact while append_tree
8800 // serializes the copy. With `following` detached, the copy lands in
8801 // old's slot either way.
8802 self.append_tree(&mut parent, vec![new])?;
8803 let inserted = parent.get_last_child();
8804 // The `chopped` half of remove_node; its id bookkeeping happened above.
8805 self.keep_point_out_of(&old, Some(&parent));
8806 // Detach `old` (the original of the copy `append_tree` just
8807 // inserted); `replace_tree` frees it, the parser defers that.
8808 {
8809 let mut old = old;
8810 old.unlink();
8811 }
8812 for mut child in following {
8813 parent.add_child(&mut child)?; // No need for clone
8814 }
8815 Ok(inserted)
8816 },
8817 _ => Ok(None),
8818 }
8819 }
8820
8821 /// Replace `old` by `new` (copied into place) and FREE the original: its
8822 /// ids were unrecorded before the copy and no handle into it is used
8823 /// afterwards (see `remove_node` for why a bare unlink leaks). Callers that
8824 /// must keep the original alive use `replace_tree_detach`.
8825 pub fn replace_tree(&mut self, new: Node, old: Node) -> Result<Option<Node>> {
8826 let inserted = self.replace_tree_detach(new, old.clone())?;
8827 if inserted.is_some() {
8828 self.discard_subtree(old);
8829 }
8830 Ok(inserted)
8831 }
8832
8833 pub fn append_tree(&mut self, node: &mut Node, data: Vec<Node>) -> Result<()> {
8834 self.append_tree_checked(node, data, false)
8835 }
8836
8837 /// [`Document::append_tree`]; `checked` (an `insertXML` chunk) warns where an `ltx:` element is opened in a node the
8838 /// model says cannot contain it, as a block `<ltx:p>` at a text point (OXIDIZED_DESIGN_DIVERGENCES #1186).
8839 fn append_tree_checked(&mut self, node: &mut Node, data: Vec<Node>, checked: bool) -> Result<()> {
8840 for child in data {
8841 match child.get_type() {
8842 Some(NodeType::ElementNode) => {
8843 // Keyed by qualified name, the namespace's code prefix (Perl `getNodeQName`, Document.pm:2108-2109;
8844 // Model.pm:306-309), so `xml:lang` and `xlink:href` survive the copy.
8845 let mut attributes: HashMap<String, String> = HashMap::default();
8846 child.for_each_property_ns(|name, ns, value| {
8847 let prefix = ns.and_then(|ns| model::get_namespace_prefix(ns, false, true));
8848 let key =
8849 prefix.map_or_else(|| name.to_owned(), |p| arena::with(p, |p| s!("{p}:{name}")));
8850 attributes.insert(key, value.to_owned());
8851 });
8852 // Perl appendTree: REMOVE xml:id from source node before re-creation.
8853 // This prevents duplicate ID registration. The ID will be re-registered
8854 // by open_element_at when the new node is created with the same ID.
8855 if let Some(xmlid) = attributes.get("xml:id") {
8856 // Unrecord before re-creation (Perl: $child->removeAttribute('xml:id') + unRecordID)
8857 self.unrecord_id(xmlid);
8858 }
8859
8860 // `get_FOREIGN_node_qname`: `data` may be a tree parsed elsewhere
8861 // (`Document::insert_xml`), whose elements can sit in a DEFAULT
8862 // namespace that is not ours — `<p xmlns="…/1999/xhtml">`. Only here is
8863 // that shape possible, and only here do we pay to resolve it.
8864 let tag_sym = model::get_foreign_node_qname(&child);
8865 let tag = arena::to_string(tag_sym);
8866 if checked && tag.starts_with("ltx:") && !node_can_contain_sym(node, tag_sym) {
8867 let parent = arena::to_string(get_node_qname(node));
8868 Warn!(
8869 "malformed",
8870 &tag,
8871 s!("<{tag}> isn't allowed in <{parent}>; inserted anyway")
8872 );
8873 }
8874 // Perl copies every attribute, `_box` included (Document.pm:2110-2116),
8875 // so the new node keeps the copied node's box rather than taking its
8876 // new parent's: a foreignObject re-created by the math parser is
8877 // sized from its own box again (tests/graphics/xytest).
8878 let child_box = self.get_node_box(&child);
8879 let mut empty_keys: Vec<String> = attributes
8880 .iter()
8881 .filter(|(key, value)| value.is_empty() && *key != "font" && *key != "locator")
8882 .map(|(key, _)| key.clone())
8883 .collect();
8884 empty_keys.sort_unstable();
8885 let mut new =
8886 self.open_element_at_with_box(node, &tag, Some(attributes), None, child_box)?;
8887 // The empty values `open_element_at` dropped, kept outside the ltx namespace (#1034; it skips
8888 // `font` and `locator` whatever their value).
8889 for key in empty_keys {
8890 self.set_copied_attribute(&mut new, &key, "")?;
8891 }
8892 self.append_tree_checked(&mut new, child.get_child_nodes(), checked)?;
8893 self.close_element_at(&mut new)?;
8894 },
8895 Some(NodeType::DocumentFragNode) => {
8896 self.append_tree_checked(node, child.get_child_nodes(), checked)?;
8897 },
8898 Some(NodeType::TextNode) => {
8899 child
8900 .as_readonly()
8901 .with_content(|text| node.append_text(text))?;
8902 },
8903 other => {
8904 log::debug!("append_tree: unhandled libxml NodeType {other:?}");
8905 },
8906 }
8907 }
8908 Ok(())
8909 }
8910
8911 /// Parse an XML / (X)HTML markup string and splice the resulting subtree into
8912 /// the document at the current insertion point.
8913 ///
8914 /// Named as the markup counterpart to [`Document::insert_element`] (Perl
8915 /// `insertElement`): both insert an already-FINISHED thing at the current point.
8916 /// Deliberately NOT an `absorb*` name — in Perl `absorb` consumes a digested
8917 /// Box and has no `XML::LibXML` branch at all (it would die on a node), so
8918 /// borrowing that verb here would imply a kinship that does not exist.
8919 ///
8920 /// This is the Rust analog of Perl BookML's `\bmlRawHTML` idiom, which composes
8921 /// two mechanisms core never chains itself: `XML::LibXML->parse_string`
8922 /// (`LaTeXML::Common::XML::Parser` `parseChunk`, `Common/XML/Parser.pm:36-39`)
8923 /// and `$document->appendTree`
8924 /// (`Document.pm:2093`, foreign-node branch `:2105-2124`). Both halves already
8925 /// exist here — libxml's parser (a direct `latexml_core` dep, used in
8926 /// `common/relaxng/scan.rs`) and [`Document::append_tree`] — so this is pure
8927 /// glue.
8928 ///
8929 /// The markup must be WELL-FORMED, but need not be a single root: several
8930 /// sibling nodes, or bare text, are accepted as a document fragment
8931 /// (OXIDIZED_DESIGN #66 — Perl's `parseChunk` is single-node only). The parsed
8932 /// nodes are re-created one by one through `append_tree`'s model-aware path, so
8933 /// namespaces declared in the snippet (e.g. xhtml) are preserved and `xml:id`s
8934 /// re-registered. Malformed markup is REJECTED, never salvaged — see
8935 /// [`crate::common::xml::parse_chunk`] for what libxml's recovery mode
8936 /// destroys — and surfaces as a clean `Error:` that inserts nothing, degrading
8937 /// the offending binding rather than aborting the conversion (the
8938 /// runtime-bindings failure-isolation contract).
8939 pub fn insert_xml(&mut self, xml: &str) -> Result<()> {
8940 // The parsed Document OWNS the nodes `append_tree` re-creates from, so it
8941 // must stay alive across the call below (bound here, dropped at fn end).
8942 let parsed = match xml::parse_fragment(xml) {
8943 Ok(doc) => doc,
8944 Err(e) => {
8945 // Quote the offending snippet: a binding may insert markup from several
8946 // places, and the reason alone would not say WHICH one to go fix. Capped
8947 // so a runaway string cannot flood the log with a single message.
8948 const SNIPPET_CAP: usize = 200;
8949 let mut snippet: String = xml.chars().take(SNIPPET_CAP).collect();
8950 if xml.chars().nth(SNIPPET_CAP).is_some() {
8951 snippet.push('…');
8952 }
8953 Error!(
8954 "malformed",
8955 "insertXML",
8956 format!("could not parse XML markup: {e}"),
8957 format!("in: {snippet}")
8958 );
8959 return Ok(());
8960 },
8961 };
8962 if parsed.is_empty() {
8963 Error!(
8964 "malformed",
8965 "insertXML",
8966 "XML markup parsed to an empty document".to_string()
8967 );
8968 return Ok(());
8969 }
8970 // `parsed` stays bound until this returns, so it keeps owning the nodes.
8971 self.insert_nodes(parsed.nodes())
8972 }
8973
8974 /// Splice ALREADY-PARSED nodes into the document at the current insertion
8975 /// point. The shared tail of [`Document::insert_xml`] and of any caller that
8976 /// obtained its nodes some other way (a script that parsed once and inserts
8977 /// repeatedly, or that edited the parsed tree before inserting).
8978 ///
8979 /// The caller must keep whatever owns `nodes` alive across this call: libxml
8980 /// nodes are pointers into their document. [`crate::common::xml::ParsedFragment`]
8981 /// exists to make that ownership explicit rather than a comment.
8982 ///
8983 /// As Perl's `appendTree` on `getElement` (Document.pm:2093, :98); the model only warns (OXIDIZED_DESIGN_DIVERGENCES
8984 /// #1186). After text the point is the open text node: it is closed first, since libxml frees an element added to a
8985 /// text node (#1034).
8986 pub fn insert_nodes(&mut self, nodes: Vec<Node>) -> Result<()> {
8987 let mut point = self.close_text_internal()?;
8988 self.append_tree_checked(&mut point, nodes, true)
8989 }
8990}
8991
8992// Auxiliary
8993
8994/// Where [`Document`]'s serializer writes: a `String`, or a file ([`Document::serialize_to_file`]).
8995trait SerializeSink {
8996 fn push_str(&mut self, s: &str);
8997 fn push(&mut self, c: char) { self.push_str(c.encode_utf8(&mut [0; 4])) }
8998 /// True once an underlying I/O error has latched, so traversal can stop early
8999 /// instead of reading/splicing the rest of a multi-GB document into a dead sink.
9000 #[inline]
9001 fn failed(&self) -> bool { false }
9002}
9003
9004impl SerializeSink for String {
9005 #[inline]
9006 fn push_str(&mut self, s: &str) { String::push_str(self, s) }
9007 #[inline]
9008 fn push(&mut self, c: char) { String::push(self, c) }
9009}
9010
9011/// A file sink buffering in a `String`, as cheap per push as the `String` sink, and writing it out in chunks of
9012/// `chunk` bytes (1 MiB). The buffer's trailing newlines stay held back, so the file ends as `serialize_to_string`'s
9013/// trimmed result does. The first write error is kept and later writes are skipped.
9014struct FileSink {
9015 file: std::fs::File,
9016 buf: String,
9017 chunk: usize,
9018 error: Option<std::io::Error>,
9019 written: u64,
9020}
9021
9022impl FileSink {
9023 fn new(file: std::fs::File, chunk: usize) -> Self {
9024 FileSink {
9025 file,
9026 buf: String::with_capacity(chunk + (chunk >> 4)),
9027 chunk,
9028 error: None,
9029 written: 0,
9030 }
9031 }
9032
9033 fn write_bytes(&mut self, bytes: &[u8]) {
9034 if self.error.is_none() {
9035 match std::io::Write::write_all(&mut self.file, bytes) {
9036 Ok(()) => self.written += bytes.len() as u64,
9037 Err(e) => self.error = Some(e),
9038 }
9039 }
9040 }
9041
9042 /// Write the buffer, and then `s`, up to their trailing newlines. A large `s` (a spliced segment's text) is
9043 /// written straight from its own string, not copied into the buffer.
9044 #[cold]
9045 fn write_out(&mut self, s: &str) {
9046 if s.len() < self.chunk {
9047 self.buf.push_str(s);
9048 let body = self.buf.trim_end_matches('\n').len();
9049 let buf = std::mem::take(&mut self.buf);
9050 self.write_bytes(&buf.as_bytes()[..body]);
9051 self.buf = buf;
9052 self.buf.drain(..body);
9053 return;
9054 }
9055 let body = s.trim_end_matches('\n').len();
9056 if body > 0 {
9057 let buf = std::mem::take(&mut self.buf);
9058 self.write_bytes(buf.as_bytes());
9059 self.write_bytes(&s.as_bytes()[..body]);
9060 self.buf = buf;
9061 self.buf.clear();
9062 }
9063 self.buf.push_str(&s[body..]);
9064 }
9065
9066 /// The last write, the buffer's trailing newlines trimmed to one; the bytes written.
9067 fn finish(mut self) -> std::io::Result<u64> {
9068 let body = self.buf.trim_end_matches('\n').len();
9069 self.buf.truncate(body);
9070 self.buf.push('\n');
9071 let buf = std::mem::take(&mut self.buf);
9072 self.write_bytes(buf.as_bytes());
9073 match self.error.take() {
9074 Some(e) => Err(e),
9075 None => Ok(self.written),
9076 }
9077 }
9078}
9079
9080impl SerializeSink for FileSink {
9081 #[inline]
9082 fn push_str(&mut self, s: &str) {
9083 if self.error.is_some() {
9084 return;
9085 }
9086 if self.buf.len() + s.len() < self.chunk {
9087 self.buf.push_str(s);
9088 } else {
9089 self.write_out(s);
9090 }
9091 }
9092
9093 #[inline]
9094 fn failed(&self) -> bool { self.error.is_some() }
9095}
9096
9097/// Strip characters that may not appear in XML 1.0 content at all: NUL and
9098/// the other C0 controls except TAB/LF/CR, plus the non-characters
9099/// U+FFFE/U+FFFF. libxml's `CString`-based APIs *panic* on interior NULs
9100/// (node.rs:639), and the rest produce non-well-formed output that downstream
9101/// XML consumers reject. Single shared policy for the document sinks
9102/// (`set_attribute`, `open_text_internal`, `open_math_text_internal`).
9103/// Borrow-free in the (overwhelmingly common) clean case.
9104fn xml_sanitize(value: &str) -> Cow<'_, str> {
9105 fn invalid(c: char) -> bool {
9106 (c < '\u{20}' && c != '\t' && c != '\n' && c != '\r') || c == '\u{FFFE}' || c == '\u{FFFF}'
9107 }
9108 if value.chars().any(invalid) {
9109 Cow::Owned(value.chars().filter(|c| !invalid(*c)).collect())
9110 } else {
9111 Cow::Borrowed(value)
9112 }
9113}
9114
9115/// Text content with its basic entities escaped (`&`, `>`, `<`), appended to `out` in one pass. No replacement
9116/// contains a character escaped, so this equals replacing `&` first and the rest after (the guard
9117/// `serializer_escape_matches_sequential_replace`).
9118fn push_escaped_text<S: SerializeSink>(out: &mut S, string: &str) {
9119 push_escaped(out, string, false)
9120}
9121
9122/// An attribute value escaped as [`push_escaped_text`], and `"`, newline and tab too.
9123fn push_escaped_attr<S: SerializeSink>(out: &mut S, string: &str) {
9124 push_escaped(out, string, true)
9125}
9126
9127fn push_escaped<S: SerializeSink>(out: &mut S, string: &str, attr: bool) {
9128 let mut rest = string;
9129 // Copy each run up to the next escaped character whole; every escaped character is ASCII.
9130 while let Some(at) =
9131 rest.find(|c| matches!(c, '&' | '<' | '>') || (attr && matches!(c, '"' | '\n' | '\t')))
9132 {
9133 out.push_str(&rest[..at]);
9134 out.push_str(match rest.as_bytes()[at] {
9135 b'&' => "&",
9136 b'<' => "<",
9137 b'>' => ">",
9138 b'"' => """,
9139 b'\n' => " ",
9140 _ => "	",
9141 });
9142 rest = &rest[at + 1..];
9143 }
9144 out.push_str(rest);
9145}
9146
9147pub trait IntoVDQS {
9148 fn into_vdqs(self) -> VecDeque<SymStr>
9149 where Self: Sized;
9150}
9151impl IntoVDQS for SymStr {
9152 fn into_vdqs(self) -> VecDeque<SymStr> {
9153 let mut vdq = VecDeque::new();
9154 vdq.push_front(self);
9155 vdq
9156 }
9157}
9158impl IntoVDQS for &str {
9159 fn into_vdqs(self) -> VecDeque<SymStr> {
9160 let mut vdq = VecDeque::new();
9161 vdq.push_front(arena::pin(self));
9162 vdq
9163 }
9164}
9165
9166impl IntoVDQS for VecDeque<SymStr> {
9167 fn into_vdqs(self) -> VecDeque<SymStr> { self }
9168}
9169
9170// containment checks are package-level (and maybe can be moved in a new submodule?)
9171
9172pub fn can_contain(node: &Node, child: &str) -> bool {
9173 let tag = model::get_node_qname(node);
9174 model::can_contain_sym(tag, arena::pin(child))
9175}
9176
9177pub fn can_contain_node(node: &Node, child: &Node) -> bool {
9178 let tag = model::get_node_qname(node);
9179 let child_tag = model::get_node_qname(child);
9180 model::can_contain_sym(tag, child_tag)
9181}
9182
9183pub fn can_contain_qname(tag: &str, child: &str) -> bool { model::can_contain(tag, child) }
9184
9185pub fn node_can_contain_sym(node: &Node, child: SymStr) -> bool {
9186 let tag = model::get_node_qname(node);
9187 model::can_contain_sym(tag, child)
9188}
9189pub fn can_contain_qsym(tag: SymStr, child: SymStr) -> bool { model::can_contain_sym(tag, child) }
9190
9191/// Can an element with (qualified name) `tag` contain a `childtag` element indirectly?
9192/// That is, by openning some number of autoOpen'able tags?
9193/// And if so, return the tag to open.
9194pub fn can_contain_indirect(tag: SymStr, child: SymStr) -> Option<SymStr> {
9195 // $tag = $model->getNodeQName($tag) if ref $tag; // In case tag is a
9196 // node. $child = $model->getNodeQName($child) if ref $child; // In case
9197 // child is a node.
9198 if !state::has_indirect_model() {
9199 let i_model = state::compute_indirect_model();
9200 state::set_indirect_model(i_model);
9201 }
9202 state::get_indirect_model_relationship(tag, child)
9203}
9204
9205pub fn can_contain_node_somehow(node: &Node, child: &str) -> Option<Option<SymStr>> {
9206 let child_sym = arena::pin(child);
9207 sym_can_contain_somehow(model::get_node_qname(node), child_sym)
9208}
9209
9210pub fn can_contain_somehow(tag: &str, child: &str) -> bool {
9211 let tag_sym = arena::pin(tag);
9212 let child_sym = arena::pin(child);
9213 sym_can_contain_somehow(tag_sym, child_sym).is_some()
9214}
9215
9216/// The return type of this method is somewhat artisinal, as we have a three-way semantics:
9217/// - `None`: There is no known structure that allows `child` as a descendant of `tag`
9218/// - `Some(None)`: `child` is directly allowed inside `tag`
9219/// - `Some(Some(inter_tag))`: `child` is allowed inside `inter_tag`, which is allowed in `tag`
9220///
9221/// This could also (maybe more naturally?) be represented with a custom 3-valued enum.
9222/// That said, I think it may be wiser to refactor the method entirely, always requiring a `bool`
9223/// check, followed by an explicit request for the `inner_tag` name, which can be `Option<SymStr>`.
9224pub fn sym_can_contain_somehow(tag: SymStr, child: SymStr) -> Option<Option<SymStr>> {
9225 match model::can_contain_sym(tag, child) {
9226 true => Some(None),
9227 false => can_contain_indirect(tag, child).map(Some),
9228 }
9229}
9230
9231pub fn can_node_have_attribute(node: &Node, attrib: &str) -> bool {
9232 let qname = model::get_node_qname(node);
9233 model::can_have_attribute(qname, arena::pin(attrib))
9234}
9235pub fn can_have_attribute(tag: &str, attrib: &str) -> bool {
9236 model::can_have_attribute(arena::pin(tag), arena::pin(attrib))
9237}
9238pub fn sym_can_have_attribute(tag: SymStr, attrib: SymStr) -> bool {
9239 model::can_have_attribute(tag, attrib)
9240}
9241
9242// Dirty little secrets:
9243// You can generically allow an element to autoClose using Tag.
9244// OR you can indicate a specific node can autoClose, or forbid it, using
9245// the _autoclose or _noautoclose attributes!
9246/// The sectioning units `\section`…`\subparagraph` open, which a frontmatter block takes without an error, as Perl's
9247/// builder does (the leniency in `find_insertion_point_qsym`).
9248fn is_lenient_sectioning_unit(qsym: SymStr) -> bool {
9249 qsym == pin!("ltx:section")
9250 || qsym == pin!("ltx:subsection")
9251 || qsym == pin!("ltx:subsubsection")
9252 || qsym == pin!("ltx:paragraph")
9253 || qsym == pin!("ltx:subparagraph")
9254}
9255
9256/// Whether a list item carries its label (`ltx:tags`: a bullet, a number, a description term); a margin list's
9257/// `\item[]` has none.
9258fn item_has_label(node: &Node) -> bool {
9259 node
9260 .get_child_elements()
9261 .iter()
9262 .any(|child| get_node_qname(child) == pin!("ltx:tags"))
9263}
9264
9265/// Whether neither `node` nor any of its ancestors is a frontmatter container (`ltx:abstract`, `ltx:acknowledgements`,
9266/// `ltx:keywords`, `ltx:classification`, `ltx:creator`), which the theorem/proof/TOC bridge leaves alone
9267/// (OXIDIZED_DESIGN_DIVERGENCES #689).
9268fn outside_frontmatter_container(node: &Node) -> bool {
9269 let mut cur = Some(node.clone());
9270 while let Some(n) = cur {
9271 if n.get_type() == Some(NodeType::ElementNode)
9272 && with_node_qname(&n, |q| {
9273 matches!(
9274 q,
9275 "ltx:abstract"
9276 | "ltx:acknowledgements"
9277 | "ltx:keywords"
9278 | "ltx:classification"
9279 | "ltx:creator"
9280 )
9281 })
9282 {
9283 return false;
9284 }
9285 cur = n.get_parent();
9286 }
9287 true
9288}
9289
9290/// Whether the nearest frontmatter container around `node` is an `ltx:abstract` its own end closed (a theorem there is
9291/// dissolved, OD #1097); one open at `\end{document}` ([`ABSTRACT_OPEN_AT_END`]: an environment never ended, cond-mat9410055) is not.
9292fn within_abstract(node: &Node) -> bool {
9293 let mut cur = Some(node.clone());
9294 while let Some(n) = cur {
9295 if n.get_type() == Some(NodeType::ElementNode) {
9296 let kind = with_node_qname(&n, |q| match q {
9297 "ltx:abstract" => Some(!n.has_attribute(ABSTRACT_OPEN_AT_END)),
9298 "ltx:acknowledgements" | "ltx:keywords" | "ltx:classification" | "ltx:creator" => {
9299 Some(false)
9300 },
9301 _ => None,
9302 });
9303 if let Some(inside) = kind {
9304 return inside;
9305 }
9306 }
9307 cur = n.get_parent();
9308 }
9309 false
9310}
9311
9312/// A closed `ltx:theorem`/`ltx:proof` whose container cannot hold it, inside an abstract (OD #1097).
9313fn is_theorem_to_dissolve(node: &Node) -> bool {
9314 with_node_qname(node, |q| matches!(q, "ltx:theorem" | "ltx:proof"))
9315 && node.get_parent().is_some_and(|parent| {
9316 parent.get_type() == Some(NodeType::ElementNode)
9317 && !can_contain_qsym(get_node_qname(&parent), get_node_qname(node))
9318 && within_abstract(&parent)
9319 })
9320}
9321
9322/// Whether `qname` is one of the sectioning units `\section`…`\subparagraph` open, by name (the auto-open bridges'
9323/// predicates see names).
9324fn is_sectioning_unit_name(qname: &str) -> bool {
9325 matches!(
9326 qname,
9327 "ltx:section" | "ltx:subsection" | "ltx:subsubsection" | "ltx:paragraph" | "ltx:subparagraph"
9328 )
9329}
9330
9331/// The sectioning units that close a quote they arrive in (`Document::close_quotes_blocking`): the display units
9332/// `\part` to `\subsubsection`, starred or not (an `\appendix`'s units are these too). The run-in `\paragraph` and
9333/// `\subparagraph` (latex.ltx `\@startsection` with a negative after-skip, article.cls:314-321) are not: pdflatex sets
9334/// the heading and the text after it inside the quote's margins, so they open an `ltx:inline-sectional-block` in the
9335/// quote (`AUTO_OPEN_BRIDGES`; main-session ruling 2026-10-17, OXIDIZED_DESIGN_DIVERGENCES #678; 2607.27159
9336/// 2505.18677 2305.11603 1809.03802 2208.14587).
9337fn is_quote_closing_unit(qsym: SymStr) -> bool {
9338 qsym == pin!("ltx:part")
9339 || qsym == pin!("ltx:chapter")
9340 || qsym == pin!("ltx:section")
9341 || qsym == pin!("ltx:subsection")
9342 || qsym == pin!("ltx:subsubsection")
9343}
9344
9345/// Whether `node` may hold a `qsym` it can contain by the model: false only for a display unit
9346/// (`is_quote_closing_unit`) at the `ltx:inline-sectional-block` a run-in `\paragraph`/`\subparagraph` opened in a
9347/// quote (`AUTO_OPEN_BRIDGES`) — a later `\section` in the same quote closes the quote, as one before the run-in heading does
9348/// (2110.03376, 1905.08876; guard `perfect_kernel_batch69a::section_after_a_paragraph_in_a_quote_closes_it`).
9349fn holds_in_quote_block(node: &Node, qsym: SymStr) -> bool {
9350 !(is_quote_closing_unit(qsym)
9351 && get_node_qname(node) == pin!("ltx:inline-sectional-block")
9352 && node
9353 .get_parent()
9354 .is_some_and(|parent| get_node_qname(&parent) == pin!("ltx:quote")))
9355}
9356
9357/// Whether `qname` is a run-in sectioning unit, `\paragraph` or `\subparagraph`, by name.
9358fn is_run_in_unit_name(qname: &str) -> bool {
9359 matches!(qname, "ltx:paragraph" | "ltx:subparagraph")
9360}
9361
9362/// A `\trivlist`'s list (`_trivlist`, latex_constructs sect06.rs): ended by its `\endtrivlist` or at its group's
9363/// end, never the target of a close by name, which closes through it (it auto-closes) to the enclosing element of that
9364/// name, as a font switch's `ltx:text` — a `\trivlist` left open in an `{itemize}` ends with it (KNOWN_PERL_ERRORS
9365/// #456).
9366fn is_trivlist(node: &Node) -> bool { node.has_attribute("_trivlist") }
9367
9368pub fn can_auto_close(node: &Node) -> bool {
9369 // text or comments auto close
9370 // otherwise must be element
9371 // without _noautoclose
9372 // and either with _autoclose
9373 // OR it has autoClose set on tag properties
9374 match node.get_type() {
9375 Some(NodeType::TextNode) | Some(NodeType::CommentNode) => true,
9376 Some(NodeType::ElementNode) if !node.has_attribute("_noautoclose") => {
9377 if node.has_attribute("_autoclose") {
9378 true
9379 } else {
9380 state::with_tag_property(get_node_qname(node), |props_opt| {
9381 if let Some(props) = props_opt {
9382 props.auto_close.unwrap_or(false)
9383 } else {
9384 false
9385 }
9386 })
9387 }
9388 },
9389 _ => false,
9390 }
9391}
9392/// Get the node's qualified name in standard form.
9393///
9394/// Ie. using the registered prefix for that namespace.
9395/// NOTE: Reconsider how _Capture_ & _WildCard_ should be integrated!?!
9396/// NOTE: Should Deprecate! (use model)
9397/// The internal attribute of an element opened by a construct the document ended inside of
9398/// ([`crate::stomach::UNENDED`]), set with `_autoclose`: closing it once it auto-closed is no
9399/// error. OXIDIZED_DESIGN #542.
9400const UNENDED_ATTRIBUTE: &str = "_unended";
9401
9402/// The transient box-capture element of `insert_block` (`ltx:_CaptureBlock_`):
9403/// a completed box, whose close force-closes its descendants.
9404pub fn is_capture_block(node: &Node) -> bool {
9405 arena::with(get_node_qname(node), |q| q == "ltx:_CaptureBlock_")
9406}
9407
9408pub fn get_node_qname(node: &Node) -> SymStr { model::get_node_qname(node) }
9409pub fn with_node_qname<R, FnR>(node: &Node, caller: FnR) -> R
9410where FnR: FnOnce(&str) -> R {
9411 model::with_node_qname(node, caller)
9412}
9413
9414/// `class` as a list of NMTOKENs: every whitespace-separated token keeps its
9415/// NameChars (letters, digits, `.`, `-`, `_`, `:`) and loses the rest
9416/// (`\\ { } @ * +` from listings language literals, raw `@` names, `fa-*`);
9417/// emptied tokens drop, and a token the cleaning made a duplicate of an
9418/// earlier one drops too (`C++`, `C+` and `C` all clean to `C`). Idempotent on
9419/// a valid list.
9420fn nmtokens_clean(value: &str) -> String {
9421 let mut out = String::with_capacity(value.len());
9422 let mut seen: Vec<String> = Vec::new();
9423 for token in value.split_whitespace() {
9424 let cleaned: String = token.chars().filter(|c| is_name_char(*c)).collect();
9425 if cleaned.is_empty() || seen.contains(&cleaned) {
9426 continue;
9427 }
9428 if !out.is_empty() {
9429 out.push(' ');
9430 }
9431 out.push_str(&cleaned);
9432 seen.push(cleaned);
9433 }
9434 out
9435}
9436
9437/// XML `NameChar` (letters, digits, `.`, `-`, `_`, `:`, and the non-ASCII
9438/// name ranges, approximated by `is_alphanumeric`).
9439fn is_name_char(c: char) -> bool { c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | ':') }
9440
9441/// XML `Name` without a colon (an `xml:id`): starts with a letter or `_`, then
9442/// NameChars only.
9443fn is_xml_name(value: &str) -> bool {
9444 let mut chars = value.chars();
9445 match chars.next() {
9446 Some(c) if c.is_alphabetic() || c == '_' => {},
9447 _ => return false,
9448 }
9449 chars.all(|c| is_name_char(c) && c != ':')
9450}
9451
9452/// Perl `eq` on two boxes: the same box object.
9453fn same_box(a: &Digested, b: &Digested) -> bool { a.as_ptr() == b.as_ptr() }
9454
9455/// A box's `mode` property (Perl `$box->getProperty('mode')`).
9456fn box_mode(bx: &Digested) -> Option<SymStr> {
9457 bx.get_property("mode").and_then(|m| match m.as_ref() {
9458 Stored::String(s) => Some(*s),
9459 _ => None,
9460 })
9461}
9462
9463fn is_autoopened_element(node: &Node) -> bool {
9464 node.get_type() == Some(NodeType::ElementNode) && node.has_attribute("_autoopened")
9465}
9466
9467/// Whether Perl's `List(…, mode => $mode)` flattens horizontal lists in this
9468/// mode: `horizontal` (List.pm:45-48). A box with no `mode` counts as
9469/// horizontal: a Rust `Tbox` carries none, where Perl's `Box()` records the
9470/// `MODE` it was made in (Package.pm, `mode => $state->lookupValue('MODE')`),
9471/// `horizontal` for paragraph text.
9472fn flattens(mode: Option<SymStr>) -> bool { mode.is_none_or(|m| m == pin!("horizontal")) }
9473
9474/// Perl `$box->unlist`: a list's boxes, else the box itself.
9475/// What [`Document::remove_node_with_box_action`] does with the removed node's
9476/// box in the boxes of its parent and of the parent's auto-opened ancestors:
9477/// [`Document::remove_node`] unlinks it, [`Document::remove_node_keeping_box`]
9478/// keeps it.
9479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9480enum NodeBoxAction {
9481 /// The box leaves them: the node's content is gone.
9482 Unlink,
9483 /// The box stays: the node's content lives on in another node.
9484 Keep,
9485}
9486
9487fn unlist(bx: &Digested) -> Vec<Digested> {
9488 match bx.data() {
9489 DigestedData::List(cell) => match cell.try_borrow() {
9490 Ok(list) => list.boxes.clone(),
9491 Err(_) => vec![bx.clone()],
9492 },
9493 _ => vec![bx.clone()],
9494 }
9495}
9496
9497/// `($box->unlist)[-1]`, without copying the list.
9498fn unlist_last(bx: &Digested) -> Option<Digested> {
9499 match bx.data() {
9500 DigestedData::List(cell) => cell
9501 .try_borrow()
9502 .ok()
9503 .and_then(|list| list.boxes.last().cloned()),
9504 _ => Some(bx.clone()),
9505 }
9506}
9507
9508/// What a horizontal `List()` puts in place of `bx` (List.pm:45-48): the boxes
9509/// of a horizontal list, else `bx`.
9510fn flatten_horizontal(bx: &Digested) -> Vec<Digested> {
9511 if matches!(bx.data(), DigestedData::List(_)) && flattens(box_mode(bx)) {
9512 unlist(bx)
9513 } else {
9514 vec![bx.clone()]
9515 }
9516}
9517
9518/// Push `thisbox` (flattened, as a horizontal `List()` would) onto `list`, the
9519/// node's own flat box list; false when `list` is not one (a list someone else
9520/// built, or one being read). Its cached size is dropped: the list grew.
9521fn push_onto_node_box(list: &Digested, thisbox: &Digested) -> bool {
9522 let own = list.as_ptr();
9523 let DigestedData::List(cell) = list.data() else {
9524 return false;
9525 };
9526 let Ok(mut list) = cell.try_borrow_mut() else {
9527 return false;
9528 };
9529 // `flatten_horizontal`, without a Vec for the one box that is not a list (MEM1 L4e).
9530 let unlisted;
9531 let pushed = if matches!(thisbox.data(), DigestedData::List(_)) && flattens(box_mode(thisbox)) {
9532 unlisted = unlist(thisbox);
9533 unlisted.as_slice()
9534 } else {
9535 std::slice::from_ref(thisbox)
9536 };
9537 // Pushing the list into itself would make it contain itself.
9538 if !list.properties.contains_key_sym(&pin!("node_box"))
9539 || pushed.iter().any(|b| b.as_ptr() == own)
9540 {
9541 return false;
9542 }
9543 list.push_boxes(pushed.iter().cloned());
9544 for cached in [
9545 pin!("cached_width"),
9546 pin!("cached_height"),
9547 pin!("cached_depth"),
9548 ] {
9549 list.properties.remove_sym(cached);
9550 }
9551 true
9552}
9553
9554/// Perl `List(@boxes, mode => $mode)` (List.pm:31-55) for a node's box, of two
9555/// or more boxes: a list of that mode, with `\\baselineskip` as its baseline
9556/// when vertical. A horizontal one is marked `node_box`, the node's own flat
9557/// list ([`push_onto_node_box`]).
9558fn node_box_list(boxes: Vec<Digested>, mode: Option<SymStr>) -> Digested {
9559 let nonempty = !boxes.is_empty();
9560 let mut list = List::new(boxes);
9561 if flattens(mode) {
9562 list
9563 .properties
9564 .insert_sym(pin!("node_box"), Stored::Bool(true));
9565 }
9566 if let Some(mode) = mode {
9567 list.properties.insert("mode", Stored::String(mode));
9568 if nonempty
9569 && arena::with(mode, |m| m.ends_with("vertical"))
9570 && let Some(baseline) = state::lookup_dimension("\\baselineskip")
9571 {
9572 list
9573 .properties
9574 .insert("baseline", Stored::Dimension(baseline));
9575 // With the rest of the interline parameters (tex.web §679), as a box's list records them — read when the node
9576 // is built, the parameters in force then.
9577 for (key, register) in [
9578 ("lineskip", "\\lineskip"),
9579 ("lineskiplimit", "\\lineskiplimit"),
9580 ] {
9581 if let Some(value) = state::lookup_register_quiet(register) {
9582 list
9583 .properties
9584 .insert(key, Stored::Dimension(crate::Dimension(value.value_of())));
9585 }
9586 }
9587 }
9588 }
9589 list.into()
9590}
9591
9592/// The `prefixes` that some node of `root`'s subtree uses: an attribute of `root` or of a
9593/// descendant element whose name is `prefix:…`, or a namespace declaration of `prefix` on a
9594/// descendant element. One preorder walk that stops once every prefix is found — it was a
9595/// recursion per prefix, each building a child `Vec` at every node (about 4–5 % of an ordinary
9596/// paper's core time, the 2026-10-16 study's 80-paper gdb sample).
9597fn namespace_prefixes_in_use<'p>(root: &Node, prefixes: &[&'p str]) -> HashSet<&'p str> {
9598 let mut found = HashSet::default();
9599 if prefixes.is_empty() {
9600 return found;
9601 }
9602 let note_attributes = |node: &Node, found: &mut HashSet<&'p str>| {
9603 node.as_readonly().for_each_property(|key, _| {
9604 for &prefix in prefixes {
9605 let plen = prefix.len();
9606 if key.len() > plen && key.starts_with(prefix) && key.as_bytes()[plen] == b':' {
9607 found.insert(prefix);
9608 }
9609 }
9610 });
9611 };
9612 note_attributes(root, &mut found);
9613 let mut cur = root.get_first_child();
9614 while let Some(node) = cur {
9615 if found.len() == prefixes.len() {
9616 break;
9617 }
9618 let mut descend = None;
9619 if node.get_type() == Some(NodeType::ElementNode) {
9620 for ns in node.get_namespace_declarations() {
9621 let ns_prefix = ns.get_prefix();
9622 if let Some(&prefix) = prefixes.iter().find(|&&p| p == ns_prefix) {
9623 found.insert(prefix);
9624 }
9625 }
9626 note_attributes(&node, &mut found);
9627 descend = node.get_first_child();
9628 }
9629 cur = descend.or_else(|| {
9630 let mut up = node;
9631 loop {
9632 if let Some(next) = up.get_next_sibling() {
9633 return Some(next);
9634 }
9635 match up.get_parent() {
9636 Some(parent) if parent != *root => up = parent,
9637 _ => return None,
9638 }
9639 }
9640 });
9641 }
9642 found
9643}
9644
9645/// An empty construction-time marker element (`*_Capture_`: `ltx:_Frontmatter_Capture_`, the cover-title marks), which
9646/// never reaches the output.
9647fn is_empty_capture_mark(node: &Node) -> bool {
9648 node.get_type() == Some(NodeType::ElementNode)
9649 && node.get_first_child().is_none()
9650 && node.get_name().ends_with("_Capture_")
9651}
9652
9653/// A processing instruction's data, `key="value"` pairs (Perl Document.pm:707-709 `insertPI`): the main "operator"
9654/// first (`class`, `package`, `options`), each only when its value is true to Perl (`$attrib{$_} ? ($_) : ()`: not
9655/// empty, not `0`), then the other keys sorted (`sort keys %attrib`), so the order is the keys' and not the hash
9656/// table's (det354 C3). An operator key with a false value is left out altogether, as Perl's second list excludes the
9657/// three names (review rev78w finding 6).
9658fn pi_data(attributes: &HashMap<String, String>) -> String {
9659 let mut other_keys: Vec<&str> = attributes
9660 .keys()
9661 .map(String::as_str)
9662 .filter(|k| !matches!(*k, "class" | "package" | "options"))
9663 .collect();
9664 other_keys.sort_unstable();
9665 let operator_keys = ["class", "package", "options"].into_iter().filter(|key| {
9666 attributes
9667 .get(*key)
9668 .is_some_and(|value| !value.is_empty() && value != "0")
9669 });
9670 operator_keys
9671 .chain(other_keys)
9672 .filter_map(|key| attributes.get(key).map(|value| s!("{}=\"{}\"", key, value)))
9673 .collect::<Vec<_>>()
9674 .join(" ")
9675}
9676
9677/// An element's `_ID_counter_*` attributes, the counters `generate_id` keeps for the ids minted under it.
9678pub fn id_counters(node: &Node) -> Vec<(String, String)> {
9679 node
9680 .get_attributes()
9681 .into_iter()
9682 .filter(|(key, _)| key.starts_with("_ID_counter"))
9683 .collect()
9684}
9685
9686#[cfg(test)]
9687mod pi_data_order {
9688 use super::{HashMap, pi_data};
9689
9690 /// Perl Document.pm:707-708: `class`/`package`/`options` first, then the rest in key order, whatever order the map
9691 /// holds them in (det354 C3).
9692 #[test]
9693 fn a_pi_lists_its_operator_then_its_keys_sorted() {
9694 for listed in [["zeta", "alpha", "mid"], ["mid", "zeta", "alpha"], [
9695 "alpha", "mid", "zeta",
9696 ]] {
9697 let mut attributes: HashMap<String, String> = HashMap::default();
9698 for key in listed {
9699 attributes.insert(key.to_string(), format!("{key}-v"));
9700 }
9701 attributes.insert("package".to_string(), "p".to_string());
9702 assert_eq!(
9703 pi_data(&attributes),
9704 r#"package="p" alpha="alpha-v" mid="mid-v" zeta="zeta-v""#
9705 );
9706 }
9707 }
9708
9709 /// Perl Document.pm:707 keeps `class`/`package`/`options` only when the value is true (`$attrib{$_} ? ($_) : ()`):
9710 /// an empty or `0` one is left out, where it printed as `options=""` (review rev78w finding 6); another key with an
9711 /// empty value stays, as Perl's `sort keys` list takes every other key.
9712 #[test]
9713 fn a_pi_drops_an_operator_key_perl_reads_as_false() {
9714 let mut attributes: HashMap<String, String> = HashMap::default();
9715 attributes.insert("class".to_string(), "article".to_string());
9716 attributes.insert("options".to_string(), String::new());
9717 attributes.insert("package".to_string(), "0".to_string());
9718 attributes.insert("dpi".to_string(), String::new());
9719 assert_eq!(pi_data(&attributes), r#"class="article" dpi="""#);
9720 attributes.insert("options".to_string(), "11pt".to_string());
9721 assert_eq!(
9722 pi_data(&attributes),
9723 r#"class="article" options="11pt" dpi="""#
9724 );
9725 }
9726}
9727
9728#[cfg(test)]
9729mod attribute_cleaners {
9730 use super::{is_xml_name, nmtokens_clean};
9731
9732 /// The emitter's `class` cleaner: listings' brace/plus/backslash language
9733 /// literals, raw `@` names and a leaked `\par` become NMTOKENs; a valid
9734 /// list is untouched.
9735 #[test]
9736 fn class_values_become_nmtokens() {
9737 assert_eq!(
9738 nmtokens_clean("ltx_lst_language_{TeX}_LaTeX"),
9739 "ltx_lst_language_TeX_LaTeX"
9740 );
9741 assert_eq!(nmtokens_clean("ltx_lst_language_C++"), "ltx_lst_language_C");
9742 assert_eq!(
9743 nmtokens_clean("ltx_lst_language_C++ ltx_lst_language_C+ ltx_lst_language_C ltx_lstlisting"),
9744 "ltx_lst_language_C ltx_lstlisting"
9745 );
9746 assert_eq!(
9747 nmtokens_clean("ltx_lstlisting \\par\\par ltx_lst_language_\\lexer@cs"),
9748 "ltx_lstlisting parpar ltx_lst_language_lexercs"
9749 );
9750 assert_eq!(nmtokens_clean("fas fa-*"), "fas fa-");
9751 assert_eq!(
9752 nmtokens_clean("ltx_font_bold ltx_align_center"),
9753 "ltx_font_bold ltx_align_center"
9754 );
9755 assert_eq!(nmtokens_clean("{}"), "");
9756 }
9757
9758 /// `xml:id` values: a valid Name is left alone; the rest go through
9759 /// `clean_id` (a leading `.` gets the `X` prefix, a `\par` leak is dropped).
9760 #[test]
9761 fn ids_are_xml_names() {
9762 assert!(is_xml_name("S2.I10.i1"));
9763 assert!(is_xml_name("_x-1"));
9764 assert!(!is_xml_name(".1"));
9765 assert!(!is_xml_name("S2.I10.i1\\par"));
9766 assert!(!is_xml_name("a:b"));
9767 assert_eq!(crate::common::cleaners::clean_id(".1"), "X.1");
9768 assert_eq!(
9769 crate::common::cleaners::clean_id("S2.I10.i1\\par"),
9770 "S2.I10.i1par"
9771 );
9772 }
9773}
9774
9775#[cfg(test)]
9776mod serializer_escape {
9777 use super::{FileSink, SerializeSink, push_escaped_attr, push_escaped_text};
9778
9779 /// The one-pass escape writes exactly what the sequential `replace` chain wrote (`&` first, then `>`, `<`, and for an
9780 /// attribute `"`, newline, tab), on strings made of every escaped character, the unescaped `\r` and `'`, entities
9781 /// already escaped, and non-ASCII text around them.
9782 #[test]
9783 fn serializer_escape_matches_sequential_replace() {
9784 fn text_by_replace(s: &str) -> String {
9785 s.replace('&', "&")
9786 .replace('>', ">")
9787 .replace('<', "<")
9788 }
9789 fn attr_by_replace(s: &str) -> String {
9790 text_by_replace(s)
9791 .replace('"', """)
9792 .replace('\n', " ")
9793 .replace('\t', "	")
9794 }
9795 let alphabet = [
9796 "&", "<", ">", "\"", "'", "\r", "\t", "\n", "a", "é", "∑", "&", "<", " ",
9797 """, ";", "#",
9798 ];
9799 let mut cases: Vec<String> = vec![
9800 String::new(),
9801 "plain".into(),
9802 "&&amp;".into(),
9803 "a<b>&c\"d'e\r\nf\tg".into(),
9804 "x\u{1F600}&\u{0300}<".into(),
9805 ];
9806 // Every string of up to three pieces of the alphabet.
9807 for a in alphabet {
9808 for b in alphabet {
9809 for c in alphabet {
9810 cases.push(format!("{a}{b}{c}"));
9811 }
9812 }
9813 }
9814 for case in &cases {
9815 let mut text = String::from("prefix");
9816 push_escaped_text(&mut text, case);
9817 assert_eq!(
9818 text,
9819 format!("prefix{}", text_by_replace(case)),
9820 "text {case:?}"
9821 );
9822 let mut attr = String::new();
9823 push_escaped_attr(&mut attr, case);
9824 assert_eq!(attr, attr_by_replace(case), "attribute {case:?}");
9825 }
9826 }
9827
9828 /// The file sink writes the `String` sink's bytes with the trailing newlines trimmed to one, whatever the pushes'
9829 /// sizes against its chunk: small runs, newline-only pushes across a chunk boundary, pushes larger than a chunk.
9830 #[test]
9831 fn file_sink_writes_the_trimmed_string() {
9832 let pushes: &[&[&str]] = &[
9833 &["<a>", "\n", " ", "text", "</a>", "\n"],
9834 &["0123456789", "\n\n\n", "\n\n", "x", "\n"],
9835 &[
9836 "abc",
9837 "a long segment\nlonger than a chunk\n\n",
9838 "\n",
9839 "tail\n\n\n",
9840 ],
9841 &["\n\n\n\n\n\n\n\n\n\n\n\n", "z"],
9842 &["", "\n"],
9843 &["no newline at all"],
9844 ];
9845 let dir = std::env::temp_dir().join(format!("lx-file-sink-{}", std::process::id()));
9846 std::fs::create_dir_all(&dir).expect("dir");
9847 for (n, case) in pushes.iter().enumerate() {
9848 for chunk in [1, 4, 8, 1 << 20] {
9849 let path = dir.join(format!("{n}.{chunk}.xml"));
9850 let mut sink = FileSink::new(std::fs::File::create(&path).expect("file"), chunk);
9851 let mut string = String::new();
9852 for push in *case {
9853 sink.push_str(push);
9854 string.push_str(push);
9855 }
9856 let written = sink.finish().expect("written");
9857 string.truncate(string.trim_end_matches('\n').len());
9858 string.push('\n');
9859 let file = std::fs::read_to_string(&path).expect("read");
9860 assert_eq!(file, string, "case {n}, chunk {chunk}");
9861 assert_eq!(written, string.len() as u64, "case {n}, chunk {chunk}");
9862 }
9863 }
9864 let _ = std::fs::remove_dir_all(&dir);
9865 }
9866
9867 /// A failed write is kept, the first one: nothing more is written or counted after it, and `finish` returns it.
9868 #[cfg(target_os = "linux")]
9869 #[test]
9870 fn file_sink_keeps_the_first_write_error() {
9871 let full = std::fs::OpenOptions::new()
9872 .write(true)
9873 .open("/dev/full")
9874 .expect("/dev/full");
9875 let mut sink = FileSink::new(full, 4);
9876 sink.push_str("<a>");
9877 assert_eq!((sink.written, sink.error.is_none()), (0, true), "buffered");
9878 assert!(!sink.failed());
9879 sink.push_str("text\n");
9880 assert!(sink.failed());
9881 let first = sink.error.as_ref().map(std::io::Error::raw_os_error);
9882 assert_eq!(first, Some(Some(28)), "ENOSPC on the first chunk");
9883 assert_eq!(sink.written, 0);
9884 sink.push_str("a segment longer than a chunk\n");
9885 sink.push_str("</a>\n");
9886 assert_eq!(sink.written, 0, "nothing counted after the error");
9887 let err = sink.finish().expect_err("the write error");
9888 assert_eq!(err.raw_os_error(), Some(28));
9889 }
9890}
9891
9892#[cfg(test)]
9893mod attribute_qnames {
9894 use libxml::tree::Node;
9895
9896 use super::Document;
9897
9898 /// An attribute is keyed by its qualified name, in the serializer and in the bookkeeping strip (Perl
9899 /// Document.pm:449-451, :491): `xml:lang` beside `lang` and `xml:id` beside `id` keep both, each with its own
9900 /// value, and only the non-namespaced `_a` is bookkeeping, so `xml:_a` stays (row XMLATTR).
9901 #[test]
9902 fn attributes_sharing_a_local_name_keep_their_own_qnames() {
9903 let mut document = Document::new();
9904 let xml = document.get_document_mut();
9905 let mut root = Node::new("document", None, xml).unwrap();
9906 xml.set_root_element(&root);
9907 for (order, pairs) in [
9908 ("lang", [("xml:lang", "en"), ("lang", "de")]),
9909 ("lang-rev", [("lang", "de"), ("xml:lang", "en")]),
9910 ("id", [("xml:id", "p1.x"), ("id", "plain")]),
9911 ("_a", [("_a", "1"), ("xml:_a", "2")]),
9912 ("_a-rev", [("xml:_a", "2"), ("_a", "1")]),
9913 ] {
9914 let mut p = Node::new("p", None, xml).unwrap();
9915 root.add_child(&mut p).unwrap();
9916 p.set_attribute("class", order).unwrap();
9917 for (name, value) in pairs {
9918 p.set_attribute(name, value).unwrap();
9919 }
9920 }
9921 document.finalize().unwrap();
9922 let serialized = document.serialize_to_string();
9923 let lines: Vec<&str> = serialized
9924 .lines()
9925 .filter(|l| l.contains("<p "))
9926 .map(str::trim)
9927 .collect();
9928 assert_eq!(lines, [
9929 r#"<p class="lang" lang="de" xml:lang="en"/>"#,
9930 r#"<p class="lang-rev" lang="de" xml:lang="en"/>"#,
9931 r#"<p class="id" id="plain" xml:id="p1.x"/>"#,
9932 r#"<p xml:_a="2" class="_a"/>"#,
9933 r#"<p xml:_a="2" class="_a-rev"/>"#,
9934 ]);
9935 }
9936}