Skip to main content

Document

Struct Document 

Source
pub struct Document {
Show 20 fields pub document: Document, pub pending: Vec<Node>, pub node: Node, pub node_boxes: FxHashMap<usize, Digested>, pub node_fonts: FxHashMap<u64, Font>, pub idstore: FxHashMap<String, Node>, pub spilled_ids: FxHashSet<String>, pub fragment_anchor_id: Option<String>, pub svg_ids: FxHashSet<String>, pub svg_id_suffixes: FxHashMap<String, i64>, pub spilled_ns_prefixes: FxHashSet<String>, pub rewrite_labels: FxHashMap<String, String>, pub rewrite_labels_shared: Option<Rc<FxHashMap<String, String>>>, pub literal_placeholders: bool, pub spill_observer: Option<fn(&Document, &Node)>, pub spill_flat: bool, pub fragment_ancestor_ids: FxHashSet<String>, pub fragment_parent_qname: Option<SymStr>, pub last_swept_node_boxes_len: usize, pub field_ink_settled: bool, /* private fields */
}

Fields§

§document: Document§pending: Vec<Node>§node: Node§node_boxes: FxHashMap<usize, Digested>§node_fonts: FxHashMap<u64, Font>§idstore: FxHashMap<String, Node>§spilled_ids: FxHashSet<String>

Streaming pass 1: every xml:id moved out of idstore by a spill. The GLOBAL half of id-collision dedup — a later build-time minting of the same id must rename exactly as eager would have (witness: the 131 MB book restarts chapter numbering per part, and the second Ch1 collided only with a SPILLED chapter).

§fragment_anchor_id: Option<String>

Streaming pass 2: the segment’s SegmentMeta::anchor. generate_id mints under it what eager mints under that element, the parse wrapper holding its counters.

§svg_ids: FxHashSet<String>

Every SVG id (the svg schema’s ID attribute, not xml:id) handed out (record_svg_ids). Ids only, no nodes or addresses: whether an element was already walked travels on the element itself (its _svgid mark), so a removed picture leaves nothing dangling, and an id stays taken once given.

§svg_id_suffixes: FxHashMap<String, i64>

The next suffix to try per SVG id base (record_svg_ids), so the n-th copy of a picture does not re-probe the n-1 suffixes before it.

§spilled_ns_prefixes: FxHashSet<String>

Streaming pass 1: every namespace PREFIX (xlink, svg, …) an element or attribute of a spilled subtree used. apply_document_namespace_ declarations declares a prefix on the root only when it is used (Perl behaviour) and scans the RESIDENT DOM; a prefix used solely inside spilled segments (xlink:href on svg:pattern/svg:use) was serialized unbound — six TikZ manuals flipped schema-invalid at the transition watermark (atableau, circuitikzmanual, tikzlings-doc, tkz-grapheur-doc-en/ -fr, tzplot-doc; batch 56fr). Guard streaming_declares_namespaces_used_only_in_spilled_segments.

§rewrite_labels: FxHashMap<String, String>§rewrite_labels_shared: Option<Rc<FxHashMap<String, String>>>

Document-wide labels SHARED by every streaming pass-2 fragment and the spine, consulted only when rewrite_labels misses: the spilled content’s and the spine’s id-bearing ones, built once before pass 2. Copying the spilled index into each fragment’s own map was quadratic in document size: 28,068 labels × 459,579 segments on the 131 MB witness = 12.9 billion String allocations. Frag-local labels still win.

§literal_placeholders: bool

Streaming: serialize spill placeholders LITERALLY (<_spilled_ ref=…/>) instead of splicing the segment text. True during pass 1 (a spilling ancestor must keep its children’s placeholders — inlining them rebuilt multi-GB segments: an 841 MB and a 1.85 GB one on the 131 MB witness, and pass 2 died re-parsing them) and on pass-2 fragment docs (which re-emit the placeholders they contain). False only at final assembly, where the splice resolves placeholders RECURSIVELY.

§spill_observer: Option<fn(&Document, &Node)>

Streaming: called on each subtree as it spills, while it is still in the live DOM, so a document-wide fact that pass 2 needs before processing any segment can be gathered from content pass 1 no longer holds (the math parser’s d-token evidence, latexml_math_parser::read_differential_evidence).

§spill_flat: bool

Serialize spill segments FLAT — no indentation, no decorative newlines.

A spilled segment’s text is an intermediate: pass 2 re-parses it, processes it, and re-serializes with serialize_aux at the recorded depth, and only THAT text reaches the output. The indentation pass 1 used to emit was therefore generated, written to disk, read back, materialized as libxml2 text nodes, deleted again by strip_indentation_whitespace, and finally regenerated — pure round-trip tax.

Measured on the 131 MB witness: 51.2% of serialized bytes are leading whitespace + newlines (189.4 MB of 381.5 MB sampled, 6,092,937 lines). Over ~2.45 GB of segment text that is ~1.2 GB generated and written, read back, and ~40M text nodes allocated in pass 2’s parse — which strip_indentation_whitespace then unlink_nodes, and unlink does not free, so they are orphaned for the fragment’s lifetime.

Set for pass 1 only. Fragment documents in pass 2 are separate Documents and default to false, so the OUTPUT keeps its formatting exactly.

§fragment_ancestor_ids: FxHashSet<String>

Streaming pass 2 only: the fragment’s ancestor xml:ids at spill time (SegmentMeta::ancestors). A label:/id:-scoped rewrite whose scope resolves to one of these covers the WHOLE fragment.

§fragment_parent_qname: Option<SymStr>

Streaming pass 2 only: the recorded qname of the fragment’s REAL parent (SegmentMeta::parent). finalize_rec substitutes it for the ltx:_lxfragment parse wrapper in schema decisions, so top-level fragment content is judged against the element it will splice back under (e.g. the empty-ltx:text collapse needs can_contain(parent, grandchild)).

§last_swept_node_boxes_len: usize

Size of node_boxes after the last sweep (lowered when a spill purges below it); the streaming sweep gate measures growth from it.

§field_ink_settled: bool

Set once the frontmatter placement settled the field ink (latexml_engine lift_marked_field_ink): no more field marks after it.

Implementations§

Source§

impl Document

Source

pub fn new() -> Self

Source

pub fn from_xml_document( doc: XmlDoc, node_fonts: HashMap<u64, Font>, ) -> Result<Self>

Wrap an existing XML document (a streamed fragment from crate::sxml::FragmentReader) as a Document, so the pass-2 phases — rewrites, math parsing, per-fragment finalize — run on it with the same machinery the eager path uses. The insertion point starts at the root; the idstore is rebuilt from the fragment’s own xml:ids; node_fonts is seeded by the caller (the hash→Font table is conversion-global and pointer-free, so sharing its contents is safe).

Source

pub fn get_element(&self) -> Option<Node>

Get the element at (or containing) the current insertion point.

Source

pub fn findnodes(&mut self, xpath: &str, node_opt: Option<&Node>) -> Vec<Node>

Find the nodes according to the given xpath expression, the xpath is relative to $node (if given), otherwise to the document node.

Source

pub fn get_xpath(&mut self) -> &mut XPath

Get an XPath context that knows about our namespace mappings.

Source

pub fn find_elements(&self, keep: impl FnMut(&Node) -> bool) -> Vec<Node>

The document’s elements that keep accepts, in document order: //*[pred] as a walk, which cannot fail on a large document as libxml2’s node set does (xml::descendant_or_self_elements, #802).

Source

pub fn findnode(&mut self, xpath: &str, node: Option<&Node>) -> Option<Node>

Like findnodes, but only returns the first matched node

Source

pub fn findvalues( &mut self, xpath: &str, node_opt: Option<&Node>, ) -> Vec<String>

Like findnodes, but expects an xpath that evaluates to a literal value (e.g. for attributes)

Source

pub fn get_node(&self) -> &Node

The current insertion point: the node that absorbed content is appended to, and the one open_element opens beneath. Perl’s $document->getNode.

Source

pub fn get_node_mut(&mut self) -> &mut Node

Source

pub fn get_document(&self) -> &XmlDoc

Source

pub fn get_document_mut(&mut self) -> &mut XmlDoc

Source

pub fn finalize(&mut self) -> Result<()>

Source

pub fn finalize_subtree(&mut self, node: &mut Node) -> Result<()>

finalize restricted to one subtree: resolve fonts against ancestors and strip the _font/_autoopened/… bookkeeping attributes, without the document-level passes (idstore rebuild, XMDual pruning, RDFa/namespace declarations) that only make sense for a complete document.

Used by latexml_post::make_bibliography to render a .bib field value into an XML fragment through the real engine: it absorbs into a scratch ltx:text wrapper and serializes that wrapper’s children.

Whole-document finalize cannot serve that caller — not because it errors (it returns Ok), but because running finalize_rec from the ROOT legitimately UNWRAPS a redundant font-only ltx:text: measured on such a scratch document, the content survives at the root while the caller’s wrapper handle is left detached and childless (wrapper_children 1 -> 0, parent = None), so it serializes to nothing. Starting the recursion AT the wrapper keeps it addressable.

Source

pub fn finalize_subtree_in( &mut self, node: &mut Node, context: Font, ) -> Result<()>

finalize_subtree under context, the font declared around the subtree (a streamed segment’s SegmentMeta::font).

Source

pub fn cleanup_unreferenced_xmtok_ids(&mut self)

Remove xml:ids from XMTok elements that aren’t referenced by any idref. The Rust math parser generates xml:ids on XMTok nodes for internal XMRef linkage during parsing. After finalization (which includes prune_xmduals), some ids are no longer referenced. Perl’s parser doesn’t generate these ids.

Source

pub fn absorb( &mut self, object: &Digested, props_opt: Option<SymHashMap<Stored>>, ) -> Result<()>

Document construction at the Current Insertion Point.

absorb the given $box into the DOM (called from constructors). This will return a list of whatever nodes were created. Note that this may include nodes that are children of other nodes in the list or nodes that are no longer in the document. Also, note that when a text nodes is appended to, the complete text node is in the list, not just the portion that was added. [Note that recording the nodes being constructed isn’t all that costly, but filtering them for parent/child relations IS, particularly since it usually isn’t needed]

A box that is a TBox, or List, or Whatsit, is responsible for carrying out its own insertion, but it should ultimately call methods of Document that will record the nodes that were created. $box can also be a plain string (Digested::Postponed) which will be inserted according to whatever font, mode, etc, are in %props.

Source

pub fn mark_field_box(&mut self, element: &mut Node)

Mark element, opened by a TeX box’s constructor for its material (an \hbox’s ltx:text, a \vbox/\parbox/minipage capture, an alignment’s container), with FIELD_BOX_ATTRIBUTE: the text a box sets is no body text of the page for a field’s print outside it (latexml_engine field_runs_after_body_text, OXIDIZED_DESIGN #715). Only the element the box’s own constructor opened, at the point it opens it: material a box absorbs straight into its context (a \vbox in a \vbox, a capture unwrapped) marks nothing (review r5 finding 1).

Source

pub fn arm_field_box(&mut self)

Arm Self::mark_field_box for the next element opened (Self::open_element), when it is the caller’s own (an alignment’s open_container); Self::disarm_field_box after it.

Source

pub fn disarm_field_box(&mut self)

Source

pub fn settle_field_ink(&mut self) -> Result<()>

Close the open run of field ink, if any, and mark no more (FieldRun): the frontmatter placement settled it. The field ledger records no more either (field_ledger_settle).

Source

pub fn get_constructed_nodes(&self) -> &[Node]

Source

pub fn absorb_string( &mut self, object: &str, props: &SymHashMap<Stored>, ) -> Result<Option<Node>>

This is a refactored else cases from the main absorb routine, to allow for better type hygiene

Source

pub fn insert_element_before( &self, point: &Node, qname: &str, attrib: Option<HashMap<String, String>>, ) -> Result<Node>

Perl: insertElementBefore — insert a new element before a given point node. Creates a new element with the given qname and attributes, inserts it before point in the DOM tree, and returns the new node.

Source

pub fn insert_mark( &mut self, qname: &str, attrib: Option<HashMap<String, String>>, ) -> Result<Node>

Insert a construction-time position mark: an empty internal element (*_Capture_-suffixed, admitted anywhere by the model, never in the output) at the current point, as Document::insert_element does, its name recorded first. A mark of a name a pass gates on with Document::made_mark (_Frontmatter_Capture_, _CoverTitleBegin_Capture_, _CoverTitleEnd_Capture_) must be made only here (or copied from one made here), so a pass looking for marks of a name none was made of has none to find and skips its scan of the document; other marks (insert_element) are not recorded.

Source

pub fn made_mark(&self, qname: &str) -> bool

Was a position mark named qname ever made in this document (Document::insert_mark)? False: none is in it.

Source

pub fn made_field_marks(&self) -> bool

Was a field mark (FIELD_MARK_TARGET) ever made in this document? False: none is in it — a field mark is made 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 from one).

Source

pub fn insert_element( &mut self, qname: &str, content: Vec<&Digested>, attrib: Option<HashMap<String, String>>, ) -> Result<Node>

Shorthand for open,absorb,close, but returns the new node.

Source

pub fn insert_pi( &mut self, op: &str, attributes_opt: Option<HashMap<String, String>>, ) -> Result<()>

Insert a ProcessingInstruction of the form Does NOT move the current insertion point to the PI, but may move up past a text node.

Source

pub fn open_element( &mut self, qname: &str, attributes: Option<HashMap<String, String>>, font_opt: Option<&Font>, ) -> Result<Node>

Open a new qname element and make it the current insertion point.

Where it opens is the model’s decision, not the caller’s: the insertion point is first moved by find_insertion_point, which auto-opens any element the schema requires in between and auto-closes any that cannot contain qname. So a binding may open a ltx:para without first checking what is currently open.

See open_element_at to open at an explicit node instead, and close_element for the counterpart.

Source

pub fn close_element_if_open(&mut self, qname: &str) -> Result<Option<Node>>

Note: This closes the deepest open node of a given type. This can cause problems with auto-opened nodes, esp. ones for fontswitches! Since this is an “explicit request”, we’re currently skipping over those nodes, ie. we’re automatically closing them, even if they’re the same type as we’re asking to close!!! This is kinda risky! Maybe we should try to request closing of specific nodes. close_element, but a no-op when no qname element is open on the current ancestor chain: the strict close (auto-closing or force-closing the intervening descendants) whenever the element is still open, and silence only when content that the element could not hold auto-closed it already. Used for a replacement’s closing tag of an element the same replacement opened (OXIDIZED_DESIGN_DIVERGENCES #202).

Source

pub fn close_quotes_blocking(&mut self, qsyms: &[SymStr]) -> Result<bool>

Close the {quote}, {quotation} or {verse} (ltx:quote, which does not auto-close) standing between the current point and a place that can hold one of qsyms — a display sectioning unit \part..\subsubsection (find_insertion_point_qsym; a run-in \paragraph/\subparagraph stays in the quote, is_quote_closing_unit) or a bibliography and the unit it stands as (latex_constructs adjust_backmatter_element). Each of these environments is LaTeX’s unlabelled list \list{}{…}\item\relax (article.cls:389-408), a margin, no structure: the heading and what follows it are the document’s own unit, typeset within the margin (latex.ltx \@startsection; thebibliography = \section* + \list, article.cls:565-584). The quotes in the way, from the innermost, are closed only when that alone (with the auto-closing elements between) makes the place reachable — a quote in a list 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 is dropped. The environment’s end then finds its quote closed (latex_constructs sect06 quote_environment). Returns whether it closed any. User rulings 2026-10-16 (D1, bibliography) and 2026-10-17 (D5, sectioning units: as the item bridge’s margin-list exemption), OXIDIZED_DESIGN_DIVERGENCES #677, #678; witnesses 2203.09193 1904.12066 1610.09996 2109.09861 2403.09260 1609.06434 astro-ph0410583 1504.06728 (bibliography), 0712.1985 (a title page in {quotation}). Guards perfect_kernel_batch69a::{bibliography_in_a_quote_closes_the_quote, section_in_a_quotation_closes_it}.

Source

pub fn float_backmatter_out_of_container(&mut self, qname: &str) -> Result<bool>

A bibliography begun in a float or a heading (the nearest container that does not auto-close) is built after it, in the nearest open ancestor that can hold it (cond-mat0108156, hep-ph0004227; OXIDIZED_DESIGN_DIVERGENCES #1099).

Source

pub fn restore_floated_backmatter(&mut self)

The close of back matter Document::float_backmatter_out_of_container floated: back to the point it left.

Source

pub fn close_abandoned_element(&mut self, qname: &str) -> Result<Option<Node>>

Closes a still-open qname element whose source groups were ABANDONED (tex.web §1335: the groups open at \end are reported once, then dropped): every descendant still open closes with it — running each one’s close-time hooks: the bare-\bibitem bibliography’s heading absorption (repros boxes-groups/abandoned_document_close_runs_bibliography_hooks, …_invents_no_bibliography_title), the empty-para prune (jpnedumathsymbols-doc), the ltx:p whitespace trim (tikz-optics). The descendants that do not auto-close are listed in an Info line (biblatex-ms: itemize), not a Warning: the abandonment was reported already. A no-op when no qname element is open.

Source

pub fn close_element(&mut self, qname: &str) -> Result<Option<Node>>

Source

pub fn is_openable(&self, test_qname: &str) -> bool

Source

pub fn is_closeable<T: IntoVDQS>(&self, tags: T) -> Option<Node>

Check whether it is possible to close each element in @tags, any intervening nodes must be autocloseable. returning the last Some(node) that would be closed if it is possible, otherwise None

Source

pub fn maybe_close_element(&mut self, qname: &str) -> Result<Option<Node>>

Close qname, if it is closeable — the forgiving counterpart to close_element.

Returns the closed node, or None when no such element is open (or it cannot be auto-closed from here). That “or nothing happens” is the point: it lets a binding close an element it may have opened without having to track whether it did, where close_element would report an error.

Source

pub fn close_to_node(&mut self, node: &Node, ifopen: bool) -> Result<()>

Closes all nodes until $node becomes the current point.

Source

pub fn close_node(&mut self, node: &Node) -> Result<()>

Closes all nodes until $node is closed.

Source

pub fn maybe_close_node(&mut self, node: &Node) -> Result<()>

Only if needed/possible: closes all nodes until $node is closed

Source

pub fn close_node_with_strictness( &mut self, strict: bool, node: &Node, ) -> Result<()>

Source

pub fn get_tag_action_list_parts( &self, tag: SymStr, when: TagOptionName, ) -> (Vec<TagConstructionClosure>, Vec<TagConstructionClosure>)

Like Self::get_tag_action_list, but keeps the _Late bucket separate. Streaming needs the split: a root’s early/normal hooks (structural — the pending-resource drain) run at open as usual, while its _late hooks (semantically “with digestion complete” — frontmatter placement, root classes) are deferred to end-of-digestion.

Source

pub fn get_tag_action_list( &self, tag: SymStr, when: TagOptionName, ) -> Vec<TagConstructionClosure> ⓘ

get the actions that should be performed on afterOpen or afterClose

Source

pub fn serialize_to_string(&self) -> String

Source

pub fn serialize_to_file(&self, path: &Path) -> Result<u64>

Document::serialize_to_string’s bytes, written to a new file at path instead: a split run’s core result goes to post through a file, and a document-sized String (2 GiB for Nasser’s whole book, issue 777) would exist only to be written there. On a write error the partial file is removed. Returns the bytes written.

Source

pub fn serialize_aux( &self, node: &Node, depth: usize, noindent: bool, heuristic: bool, ) -> String

We ought to try for something close to C14N (http://www.w3.org/TR/xml-c14n), but keep XML declaration, comments and don’t convert empty elements.

Source

pub fn set_node(&mut self, node: &Node)

Move the current insertion point to node — Perl Document.pm:setNode L74-87.

A document fragment is not itself an insertion point: as in Perl, a single-child fragment is descended into, and a fragment with several children is an error (reported, not fatal — see the body comment on why this returns ()).

Source

pub fn insert_math_token( &mut self, text: &str, attributes: HashMap<String, String>, font_opt: Option<&Font>, ) -> Result<Node>

Source

pub fn insert_comment(&mut self, text: &str) -> Result<Node>

Insert a new comment, or append to previous comment. Does NOT move the current insertion point to the Comment, but may move up past a text node. Perl: Document.pm lines 678-698

Source

pub fn drops_whitespace_here(&self) -> bool

Perl openText’s whitespace rule (Document.pm:747-749): whitespace is dropped at the document start and in an element that cannot hold text.

Source

pub fn open_text(&mut self, text: &str, font: &Font) -> Result<Option<Node>>

Source

pub fn close_text_internal(&mut self) -> Result<Node>

Source

pub fn close_node_internal(&mut self, node: &Node) -> Result<()>

Close node, and any current nodes below it. No checking! Use this when you’ve already verified that node can be closed. and, of course, node must be current or some ancestor of it!!!

Source

pub fn merge_attributes( &mut self, from: &Node, to: &mut Node, force: Option<&HashSet<&'static str>>, ) -> Result<()>

Source

pub fn record_constructed_node(&mut self, node: &Node)

Note that a box has been absorbed creating node; This does book keeping so that we can return the sequence of nodes that were added by absorbing material.

Source

pub fn filter_deletions(&self, nodes: Vec<Node>) -> Vec<Node>

Source

pub fn filter_children(&self, nodes: Vec<Node>) -> Vec<Node>

Given a list of nodes such as from ->absorb, filter out all the nodes that are children of other nodes in the list.

Source

pub fn get_insertion_context(&self, levels_opt: Option<usize>) -> Result<String>

Return a string indicating the path to the current insertion point in the document. if $levels is defined, show only that many levels

Source

pub fn find_insertion_point( &mut self, qname: &str, has_opened_opt: Option<SymStr>, ) -> Result<Node>

Find the node where an element with qualified name qname can be inserted. This will move up the tree (closing auto-closable elements), or down (inserting auto-openable elements), as needed.

Source

pub fn find_insertion_point_qsym( &mut self, qsym: SymStr, has_opened_opt: Option<SymStr>, ) -> Result<Node>

Source

pub fn set_in_place(&mut self, qname: &str) -> Result<()>

Sets the insertion point where TeX sets qname in place, inside its container: a wrap float in a box (a footnote, a \parbox, a cell; wrapfig.sty:104-107 \ifinner). These are Self::find_insertion_point’s routes, with the ltx:inline-logical-block bridge of a theorem (OXIDIZED_DESIGN_DIVERGENCES #689) open to it in a container that holds no Para.class (a note), so that a closing float marker (^^) then finds it held where it stands. Not in a frontmatter container (#689’s exclusion): there the point stays and the marker floats it out (OXIDIZED_DESIGN_DIVERGENCES #1254).

Source

pub fn node_set_attribute(&mut self, key: &str, value: &str) -> Result<()>

Source

pub fn node_get_attribute(&mut self, name: &str) -> Option<String>

Source

pub fn set_attribute( &mut self, node: &mut Node, key: &str, value: &str, ) -> Result<()>

Set any allowed attribute on a node, decoding the prefix, if any. Also records, and checks, any id attributes. [xml:id and namespaced attributes are always allowed]

“Allowed” is the document model’s call, so this is not a plain libxml write: an attribute the schema does not permit on node is dropped rather than emitted, which is what keeps a binding from producing a document that fails validation.

Source

pub fn add_ss_values( &mut self, node: &mut Node, key: &str, values_str: &str, ) -> Result<()>

Source

pub fn add_class(&mut self, node: &mut Node, class: &str) -> Result<()>

Add one or more CSS classes to a node, without disturbing the ones it already carries.

class is treated as the space-separated set it is (add_ss_values), so several bindings can each contribute a class to the same element — which is why this exists rather than a plain setAttribute("class", …), and what remove_ss_values undoes.

Source

pub fn remove_ss_values(&mut self, node: &mut Node, key: &str, values: &str)

Remove space-separated values from an attribute. Perl: sub removeSSValues (Document.pm lines 1423-1437)

Source

pub fn remove_class(&mut self, node: &mut Node, class: &str)

Remove CSS class from element. Perl: sub removeClass (Document.pm lines 1439-1442)

Source

pub fn float_to_attribute(&mut self, key: &str) -> Option<Node>

Float to a node that can accept the given attribute. Returns the previous node so it can be restored after setting the attribute. Perl: sub floatToAttribute (Document.pm lines 1080-1092)

Source

pub fn is_open(&self, node: &Node) -> bool

Check if a node is currently open (i.e., is or contains the current node). Perl: sub isOpen (Document.pm lines 1998-2006)

Source

pub fn unrecord_id(&mut self, id: &str)

Guardian-safe unlink: walk node’s subtree invalidating every xml:id idstore entry, then detach it from its parent. Use this in preference to a raw node.unlink() anywhere the node might carry an xml:id (subtree reshuffles in math-parser, post-processing cleanup, etc.), to prevent the dangling-Node class of bug that produced the 1605.08055 Finalizing-phase SIGSEGV (see SYNC_STATUS.md D3b).

This is the unlink-only half of remove_node — it does not adjust self.node / the insertion point, which is correct for callers that intend to re-parent the unlinked subtree elsewhere (the common case). Callers that want the insertion-point bookkeeping should use remove_node instead.

Source

pub fn record_node_ids(&mut self, node: &Node) -> Result<()>

These are used to record or unrecord, in bulk, all the ids within a node (tree).

When record_id_with_node detects a duplicate it renames the id (e.g. X.1.mf → X.1.mfa). Any sibling <ltx:XMRef idref="X.1.mf"/> in the same subtree would otherwise become a dangling reference for the post- processor. After re-recording IDs, sweep the subtree once and update any XMRef whose idref matches an entry in the rename map.

Perl Core::Document::recordNodeIDs (Document.pm L1466-1472) has the same latent bug — recording renames but XMRefs aren’t touched. The bug surfaces in our port because the math-parser path (parser.rs::install_replacements-style unrecord+record round-trips) is denser than Perl’s; both end up needing this remap to keep XMRef chains intact. Intentional surpass-Perl divergence; tracked in SYNC_STATUS Task #10.

Source

pub fn record_svg_ids(&mut self, root: &Node) -> Result<()>

Makes the SVG ids under root unique in the document, as the svg schema types them (svg-core-attrib.rng:26-28). A picture TeX copies — \copy, \usebox, expl3’s \box_use:N (tex.web:20952 copies a node list with its whatsits verbatim) — writes the ids the pgf driver fixed at digestion (pgfsys-latexml.def.ltxml:346-352, :678-714) once per copy; PDF has no ids, XML must not repeat them (suanpan-l3: 9,480 jing lines; thuaslogos: copies nested in one picture). Walks root in document order: an SVG element’s id already handed out (or held by an xml:id) is renamed with the next free suffix, and every reference — url(#X) in any attribute, href/xlink:href #X — binds to the latest preceding definition of X under root; a reference to a definition elsewhere is left alone.

A walked element is marked (_svgid, a bookkeeping attribute finalize strips): the math parser re-creates a picture where it moves it (append_tree), each re-creation closing a new svg:svg — the mark travels with the copied attributes, so a moved picture keeps its ids and references, where an unmarked one is a new copy. append_clone (the alignment split’s MathFork, the frontmatter writer’s contacts and notes) instead makes a second copy beside the original: it copies the svg id as Perl does and drops the mark, so the copy’s own walk renames the ids it repeats (guard perfect_kernel_batchne7::tikz_badges_in_frontmatter_contacts_keep_svg_ids). A picture keeps Perl’s ids unless an earlier element already holds them (a relocated footnote copy can). Perl writes the duplicates (KNOWN_PERL_ERRORS #391); the id map follows its appendClone (Document.pm:1920-1956). Guards: perfect_kernel_batch57::copied_pictures_keep_unique_svg_ids, perfect_kernel_batch57::rebuilt_math_pictures_keep_their_svg_ids.

Source

pub fn unrecord_node_ids(&mut self, node: &Node)

Source

pub fn spill_closed_subtrees( &mut self, index: &mut FragmentIndex, ) -> Result<usize>

Spill closed subtrees to the segment store, freeing their DOM memory (streaming pass 1).

Walks the SPINE — root element down to the current insertion element — and, at every level, spills the runs of closed element children that precede the open (spine) child: serialize in the pre-finalize form with the exact (depth, noindent) the eager serializer would use, write to store, record every spilled xml:id/label in index, purge the pointer-keyed registries (idstore via unrecord_id, node_boxes by key — freed nodes’ pointers can be REUSED, so a stale entry is not just dangling but can mis-associate a box with a future node), replace the run with one <_spilled_ ref="N"/> placeholder, and unlink+free the nodes. Serialization at assembly time splices the processed segment where the placeholder sits, so document order, nesting and spine-attribute finality are preserved by construction.

Two deliberate exclusions:

  • ROOT-level children spill only when sectional (ROOT_SPILLABLE): the frontmatter fallback and maybe_promote_leading_title operate on the leading non-sectional root children at end-of-build.
  • An open element’s heading parts (ltx:tags, ltx:title, ltx:toctitle) never spill: its close-time hooks read them (a bibliography taking the place of the unit that heads it, latexml_engine sect11.rs absorb_bibliography_heading). One title per open element, so the memory cost is negligible.

Returns the number of runs spilled.

Source

pub fn take_spill_anchor_counters( &mut self, ) -> FxHashMap<String, Vec<(String, String)>>

Streaming, after pass 1: every spill anchor’s _ID_counter_* attributes as construction left them — recorded when it spilled, else read from the spine. Pass 2 continues them; Self::set_id_counters hands them back.

Source

pub fn set_id_counters(&mut self, id: &str, counters: &[(String, String)])

Set the _ID_counter_* attributes of the element id names, if it is in this document.

Source

pub fn purge_node_boxes_rec(&mut self, node: &Node)

Remove the pointer-keyed node_boxes entries for node and its whole subtree. MANDATORY before freeing nodes mid-conversion: a freed node’s address is REUSED by later allocations, and a stale entry then mis-associates the old box (and its font) with an unrelated new node — observed as spurious <text font="italic"> wrappers the moment the math parser started freeing replaced trees promptly.

Source

pub fn discard_subtree(&mut self, node: Node)

Discard a garbage subtree for good: purge the pointer-keyed node_boxes entries, then free the C memory NOW via the fork’s Node::free_subtree — the missing half of every unlink-to-discard site (rust-libxml Linkage: a doc-created node that is unlinked but never re-attached is freed by NOBODY; math parsing discards thousands of replaced subtrees per document, measured ~1.4 MB/formula, ~1.8 GB retained per 32 MB streaming segment). free_subtree also neutralizes every live wrapper into the subtree, so stray clones in long-lived collections (constructed_nodes, an idstore epoch) go inert instead of firing a deferred xmlFreeNode after the document itself is gone.

The idstore entries that point INTO the subtree are dropped with its boxes (forget_freed_subtree): a math phantom’s dropped hint holding an XMDual’s ids left them pointing at freed nodes, and the next record of such an id renamed a live token against a <#BrokenNode> (witnesses 2606.13225, 2605.00485, 2605.29246).

PRECONDITION (the caller’s contract): no live handle into the subtree is used afterwards.

Source

pub fn sweep_stale_node_boxes(&mut self)

Drop every node_boxes entry whose node is no longer IN this document tree (streaming pass 1’s self-healing sweep). Entries are written for every constructed node and purged at the spill/discard chokepoints — but dozens of build-time discard paths (alignment rearrangement above all: 105k align environments on the 131 MB witness) detach nodes without purging, and each stale entry pins a whole Digested box tree. Measured: ~518k stale entries before the FIRST spill, growing past 1.75M — the dominant residual pass-1 creep after the C-side frees. A mark-and-retain against the live tree is immune to every such path, including future ones. The mark phase walks the whole live DOM, so the streaming driver gates it on node_boxes growth (core_interface.rs).

Source

pub fn set_spill_store(&mut self, store: SegmentStore)

Attach the processed-segment store for serialization: from here on, serialize_into splices each segment’s output text where its placeholder sits (streaming assembly).

Source

pub fn set_defer_root_after_open(&mut self, defer: bool)

Streaming pass 1 switch: defer (true) or restore (false) the ROOT element’s after_open hook dispatch. See the field docs.

Source

pub fn root_after_open_deferred(&self) -> bool

Is the root’s late-hook dispatch currently deferred (streaming pass 1)? Engine bindings consult this to defer digestion-state-dependent insertions (frontmatter) to end-of-digestion.

Source

pub fn process_pending_resources_at_top(&mut self) -> Result<()>

Streaming pass 1: fold freshly queued resources into the live document as they arrive, at the top of the root. Perl’s own contract (Package.pm:RequireResource): with a live document, addResource inserts DIRECTLY; only a document-less preamble queues. The eager path keeps the queue until the root’s after_open because its build starts post-digestion; under streaming that drain is deferred to end-of-digestion, and mid-digestion consumers — the frontmatter fallback’s /ltx:document/ltx:resource[last()] anchor — need the resources already placed.

Source

pub fn dispatch_deferred_root_hooks(&mut self) -> Result<()>

Streaming: dispatch the ROOT’s deferred after-open hooks at end-of-digestion — the eager timing (build starts only after digestion ends) — with the insertion point at the TOP of the root, as if it had just opened empty. after_open itself cannot be used here: it pins the current node to the dispatched element, so everything the hooks insert (resources, frontmatter) would APPEND after the built content instead of leading it. A ltx:_Capture_ wrapper as first child recreates the empty-root insertion context (the frontmatter fallback’s own technique), and is unwrapped afterwards.

Source

pub fn add_extra_rdfa_prefixes<'a>( &mut self, prefixes: impl Iterator<Item = &'a str>, )

Merge RDFa prefixes recorded from spilled content, so the root’s prefix= attribute covers usages the live-DOM scan can no longer see.

Source

pub fn take_spill_store(&mut self) -> Option<SegmentStore>

Detach the spill store (the streaming driver takes it out for pass 2 — which mutates segments while fragment documents exist independently — and re-attaches it for assembly).

Source

pub fn rebuild_idstore_from_dom(&mut self) -> Result<()>

Discard the in-memory idstore cache and rebuild it from the current DOM state. Historically guarded the 1605.08055 SIGSEGV where mark_xmnode_visibility dereferenced dangling lookup_id entries while recursing through XMRef targets.

As of cycle 72, the 5 call sites that previously dropped nodes without unrecord_id — math-parser replace_tree at parser.rs:456/690 (cascades via remove_node) and unbind_node loops at parser.rs:639/856 + rewrite.rs:522 (all have preceding unrecord_node_ids guards) — are ID-safe. This rebuild is retained as a belt-and-suspenders probe until the 1605.08055 verification per SYNC_STATUS.md D3b lands.

The rebuild is a DOM walk, so live id uniqueness is restored alongside — duplicates already in DOM are resolved with modify_id, matching record_node_ids semantics.

Source

pub fn modify_id(&mut self, id: String) -> String

Get a new, related, but unique id. Sneaky option: try “ID_SUFFIX” as a suffix for id, first. Perl: sub modifyID (Document.pm lines 1483-1494)

Source

pub fn lookup_id(&self, id: &str) -> Option<&Node>

Source

pub fn get_idstore_clone(&self) -> HashMap<String, Node>

Clone the idstore for use in thread-local contexts (math parsing).

Source

pub fn mark_xmnode_visibility(&mut self) -> Result<()>

Source

pub fn prune_dangling_split_xmrefs(&mut self) -> Result<()>

Remove ltx:XMRef[@_split_ref="1"] whose idref no longer resolves. These are the XMRefs minted by amsmath::rearrange_ams_split to mirror the flattened cell sequence inside an XMDual(XMWrap(refs), XMArray(cells)). The math parser can later absorb some cells (typically inserted MULOP times-ops on \mathcal{L}\rho chains) into wrapping XMApps, dropping their xml:id from the live DOM and leaving the sibling XMRefs dangling. Left in place, each dangling XMRef trips three separate diagnostics later — math parser’s read_xmref Warn, finalize’s mark_xmnode_visibility Warn, and post-process’s mark_xm_node_visibility Error.

We restrict the sweep to the _split_ref marker so refs from other provenance (base_xmath \lx@dual, renamed-id cases like declare_test’s S1.Ex1.m1.1 → .1a rename) stay untouched.

Content-preserving: XMRefs are structural cross-references, not author body, and the math parser has already absorbed the referenced cell into the visible XMArray branch — no glyph or formula material is lost.

Source

pub fn prune_xmduals(&mut self) -> Result<()>

Reduce any ltx:XMDual’s to just the visible branch, if the other is not visible (according to markXMNodeVisibility) If we could be 100% sure that the marking had stayed consistent (after various doc surgery) we could avoid re-marking, but we’d better be sure before removing nodes!

Source

pub fn set_node_box(&mut self, node: &Node, digested: Digested)

Record the Box that created this node.

Source

pub fn get_node_box(&self, node: &Node) -> Option<Digested>

Source

pub fn set_node_font(&mut self, node: &mut Node, font: &Font) -> Result<()>

Record the Font of a node

Source

pub fn copy_node_font(&mut self, from: &Node, to: &mut Node) -> Result<()>

Source

pub fn merge_node_font_rec(&mut self, node: &Node, font: &Font) -> Result<()>

Possibly a sign of a design flaw; Set the node’s font & all children that HAD the same font.

Source

pub fn set_box_font(&mut self, node: &mut Node) -> Result<()>

Source

pub fn get_node_font(&self, node: &Node) -> &Font

Source

pub fn decode_font(&self, font_hash: &str) -> Option<&Font>

Decode a _font hash string to a Font object

Source

pub fn has_node_font(&self, node: &Node) -> bool

Source

pub fn get_node_language(&self, node: &Node) -> String

Source

pub fn remove_node(&mut self, node: Node)

Remove a node from the document (from it’s parent).

Two pieces of bookkeeping come with it: the xml:id of the node and of every descendant is un-recorded, so the ids are free for reuse and no dangling reference is left behind; and if the insertion point was inside what is being removed, it is rescued up to the parent — otherwise the document would go on building into a detached subtree.

The node’s box leaves the boxes of its parent and of the parent’s auto-opened ancestors (Perl removeNode → removeNodeBox, Document.pm:1788-1789): what the node contributed to them is gone.

Source

pub fn remove_node_keeping_box(&mut self, node: Node)

remove_node for a node whose content lives on in another node, so its box stays in the boxes it is part of: a copy (append_tree; Perl’s appendChild moves the node itself — \sideset’s nucleus, amsmath), a renamed node, a token a math ligature merged, a node its replacements stand for (Perl’s replaceChild has moved it into a document fragment, where removeNodeBox finds no element to update). Unlinking these boxes took pieces out of the reversions that tex= is read from (KNOWN_PERL_ERRORS #272).

Source

pub fn open_element_at( &mut self, point: &mut Node, qname: &str, attributes: Option<HashMap<String, String>>, font_opt: Option<Font>, ) -> Result<Node>

This opens a new element at the specified point, rather than the current insertion point. This is useful during document rearrangement or augmentation that may be needed later in the process.

Source

pub fn close_element_at(&mut self, node: &mut Node) -> Result<()>

Whenever a node has been created using openElementAt, closeElementAt ought to be used to close it, when you’re finished inserting into $node. Basically, this just runs any afterClose operations.

Source

pub fn after_open(&mut self, node: &mut Node) -> Result<()>

Source

pub fn after_close(&mut self, node: &mut Node) -> Result<()>

Source

pub fn append_clone( &mut self, node: &mut Node, new_children: Vec<Node>, ) -> Result<()>

Append COPIES of new_children under node.

Cloning rather than moving is what makes this usable on nodes that belong to another document — moving them would remove them from it. Three things are repaired on the way in: document fragments are expanded to their children, the namespace structure is rebuilt clean (libxml2 otherwise has a tendency to introduce annoying “default” namespace prefix declarations), and every xml:id in the copy is rewritten to a fresh id, with internal references remapped to match — otherwise the copy would duplicate the original’s ids.

Source

pub fn wrap_nodes( &mut self, qname: &str, nodes: Vec<Node>, ) -> Result<Option<Node>>

Wrap nodes with an element named qname, making the new element replace the first node, and all nodes becomes the child of the new node. [this makes most sense if nodes are a sequence of siblings]

Returns None if qname isn’t allowed in the parent, or if nodes aren’t allowed in qname, otherwise the newly created qname — so a caller must treat “wrapped” as a request the model may decline, not as a guarantee. None also covers a first node with no parent (already detached, or the root): there is nothing to wrap it in place of. Witness 1804.09736.

The wrapper inherits the parent’s font and box, so wrapping does not change how the enclosed material renders. unwrap_nodes is the inverse.

Source

pub fn wrap_nodes_as( &mut self, qname: &str, nodes: Vec<Node>, attributes: &[(String, String)], ) -> Result<Option<Node>>

wrap_nodes, the wrapper carrying attributes from its opening, so its after_open/after_close hooks see them: an xml:id given here is the one generate_id keeps.

Source

pub fn unwrap_nodes(&mut self, node: Node) -> Result<()>

Unwrap the children of $node, by replacing $node by its children.

Source

pub fn replace_node(&mut self, node: Node, with: Vec<Node>) -> Result<()>

Replace node by nodes (presumably descendants of some kind?)

No box changes hands (Perl Document.pm:2011-2025): Perl’s first replaceChild moves node into a document fragment, so its removeNode finds no parent element whose box to update, and its closing appendNodeBox map runs over the @nodes its while (shift) loop has emptied. Only a node replaced by nothing leaves its parent’s box, as removeNode does. The \@framebox unwrap inside an auto-opened picture keeps the frame’s size (x \put(0,0){A} \fbox{…} y). Guard: node_box_append::replacing_a_node_keeps_the_boxes.

Source

pub fn replace_node_as_tree( &mut self, node: Node, with: Vec<Node>, ) -> Result<()>

Replace node by with as Perl’s replaceTree (Document.pm:2079-2091) does with their boxes: node’s box leaves its parent’s (removeNode while node is still in place), then each element of with is recorded as appendTree → openElementAt records a node it re-creates — its own box, else the parent’s, else the box being absorbed — which extends an auto-opened parent’s box (appendNodeBox). cleanup_math unwraps a Math that holds only text this way (TeX_Math.pool.ltxml:219): the auto-opened svg:foreignObject around an \hbox in an xymatrix cell measures the \hbox in place of the Math (tests/graphics/xytest).

Source

pub fn rename_node( &mut self, node: Node, newname: &str, reinsert: bool, ) -> Result<Node>

Rename an element to newname, returning the new node.

Not an in-place rename: a fresh element is opened next to the original, the attributes and (when reinsert) the children are carried over, and the original is removed. Perl went this way “initially since $node->setNodeName was broken in XML::LibXML 1.58”, and kept it because building the replacement through the normal open path is what runs the model’s checks and afterOpen hooks for the new tag — a raw rename would leave an element the schema never vetted.

rename_node_qsym is the same for an already interned name.

Source

pub fn rename_node_qsym( &mut self, node: Node, newsym: SymStr, reinsert: bool, ) -> Result<Node>

Source

pub fn trim_node_whitespace(&mut self, node: &Node) -> Result<()>

Source

pub fn add_resource(&mut self, resource: Resource) -> Result<()>

Source

pub fn process_pending_resources(&mut self) -> Result<()>

Source

pub fn make_error(&mut self, error_class: &str, content: &str) -> Result<()>

Source

pub fn float_out_of_frontmatter(&mut self, qname: &str) -> Result<Option<Node>>

Self::float_to_element (closing form) for an element a frontmatter container (ltx:abstract…) refuses, when the insertion point is inside one: the element goes to the nearest open ancestor that admits it, as Perl’s floatToElement places one (Document.pm:1052-1077), and the insertion point comes back (the saved node is returned for the caller to restore), so what follows stays in the container. Elsewhere None: the element is inserted where it stands, by Self::find_insertion_point’s rules. A \tableofcontents inside an abstract (1011.3976, 1602.08755, 2007.03709; OXIDIZED_DESIGN_DIVERGENCES #753).

Source

pub fn float_to_element( &mut self, qname: &str, closeifpossible: bool, ) -> Result<Option<Node>>

Find a node in the document that can contain an element qname

Source

pub fn float_to_label(&mut self) -> Option<Node>

Source

pub fn float_to_label_for(&mut self, raw_step: Option<i64>) -> Option<Node>

float_to_label for a label that names a counter step no element took (raw_step, the step’s serial: a raw \refstepcounter, binding::counter::current_raw_refstep), which a picture may carry: a box drawn as a picture frame is the object such a step numbers (tcolorbox’s \refstepcounter in its phantom code, tcolorbox.sty:2311 and :1154-1161, placed in the frame at :1925; a \put in a picture), as LaTeX’s \label after the step names the step’s anchor (latex.ltx:14963-14967 \@currentlabel). An object another raw step numbered (take_raw_refstep_number) is not this step’s: the label climbs past it, as Perl’s does (a second \put step in one picture; pdflatex prints each step’s number, an object this port cannot give, OXIDIZED_DESIGN_DIVERGENCES #813). Any other label climbs past a picture, and past an object a raw step numbered (whose number its \@currentlabel is not: a {gather*} row’s \label after the \labelrel idiom’s immediate one, 2310.19138), to the object its step numbered, as Perl’s does (Document.pm:1098-1127; the picture carries no labels there). Witnesses: 2506.01072 (\newtcbtheorem), 2505.20088 ([auto counter]), 2402.06608 ([blend into=figures]), 2609.20563 (\newtcblisting). An object inside ltx:Math (the box of a \text{\begin{tcolorbox}…} in a display) is not the step’s either: its id does not survive the math’s rendering, so the label climbs out of the math to where Perl’s lands: a display, which takes the step’s number when it has none (take_raw_refstep_number: a {gather*} row, \[…\]) and keeps its own otherwise (a numbered {equation}), or past an inline formula the enclosing unit, whose number \ref prints (OXIDIZED_DESIGN_DIVERGENCES #813). Repro cross-references/math_box_label_climbs_to_the_display.tex.

Source

pub fn float_to_label_scoped( &mut self, raw_step: Option<i64>, after_undone_step: bool, ) -> Option<Node>

float_to_label_for for a label that follows a counter step a group has since undone (after_undone_step, binding::counter::label_follows_an_undone_step): it names the step still in scope, not the object just closed beside it (Perl’s last-child start, Document.pm:1103-1104), so the climb starts at the current node. Where no ancestor takes it, Perl’s fallback (:1113-1119, the last child, else the root) stays: a label at the document’s own level (lastpage’s \AtEndDocument{\label{lastpage}}) keeps its old place, where the root taking it gave the root an id and renumbered every generated one. Witness math0107195: a \label after an inner equation, still inside a theorem, names the theorem (“Theorem 5.3”; Perl and int52a the equation’s 16, KNOWN_PERL_ERRORS #1092; OXIDIZED_DESIGN_DIVERGENCES #856). Repro cross-references/label_after_an_inner_equation_names_the_theorem.tex.

Source

pub fn take_raw_refstep_number( &mut self, tags: &Digested, serial: i64, ) -> Result<()>

The object a label after a raw counter step names (the node float_to_label_for found, current) takes the step’s number: the tags LaTeXML makes for every step (binding::counter::dialect::label_stepped_counter), whose refnum is what \ref prints, as LaTeX’s \ref prints the step’s \@currentlabel (latex.ltx:14963-14967). Only an object with no number of its own (no 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 (an ltx:title holder: an unnumbered \section* or theorem stays unnumbered). The tag without a role, the number as the object prints it, is not kept: the box printed its number itself (tcolorbox’s title “Theorem 1: …”). The object is marked with the step’s serial (_raw_refstep, a bookkeeping attribute), so another step’s label does not take it. Perl leaves the label on the enclosing section, whose number \ref prints (KNOWN_PERL_ERRORS #1038). Witnesses: 2506.01072 (\newtcbtheorem), 2505.20088 (\newtcolorbox[auto counter]), 2402.06608, 2609.20563 (\newtcblisting); guards perfect_kernel_batch78g.

Source

pub fn note_raw_refstep_object(&mut self, serial: i64, object: &Node)

Records object as the one that printed the number of the raw counter step serial itself (an algorithm2e line: \nl’s \refstepcounter{AlgoLine} then \algocf@printnl), marking it (RAW_REFSTEP_MARK): a label after the step names it (float_to_label_scoped) and takes its reference forms (take_raw_refstep_number).

Source

pub fn release_earlier_label_holders(&mut self, key: &str, holder: &Node)

A \label{key} placed on holder takes key from the elements holding it before that contain holder or that it contains: LaTeX’s last \newlabel wins (latex.ltx \@newl@bel: \global\@namedef{r@key}, “Label multiply defined”), where the post scan registers in document order, the outer element first (Perl Scan.pm:196-203, ours latexml_post/src/scan.rs register_scanned), so an earlier label on an element inside a later one won: 2001.00288’s \label{algo2} after \KwOut (its line) and again after \caption (the algorithm) printed “Algorithm 1” for pdflatex’s “Algorithm 2” (KNOWN_PERL_ERRORS #1131, OXIDIZED_DESIGN_DIVERGENCES #877). Holders apart from each other keep the key: pdflatex’s last \newlabel is the last written, the later in the document but for a float LaTeX defers past a later label of the key (not modelled: [p] figure then \section{Two}\label{k}, pdflatex the figure), and the scan already takes the later; an element the streaming build spilled may be one (spills are closed top-level elements, never holder’s ancestors or, below the document root, its descendants), so streaming and eager builds agree. Searched only for a key placed before. Guard perfect_kernel_batch78t::the_later_label_wins.

Source

pub fn merge_raw_refstep_tags(&mut self)

One ltx:tags for an object a raw step numbered (take_raw_refstep_number) that a later construct tags as well (\eqno‘s, made after the label in $$ \refstepcounter{foo}\label{x2} c=d \eqno(B) $$): the later tags’ tags join the step’s ltx:tags, before its refnum, so the object shows “(B)” and \ref prints the step’s number (pdflatex 42; the \@currentlabel \eqno leaves alone). The nearest open element holding an ltx:tags, from the current node. Repro cross-references/unnumbered_display_label_takes_the_step_number.tex.

Source

pub fn set_box_to_absorb(&mut self, arg: Option<Digested>)

Source

pub fn expire_box_to_absorb(&mut self)

Source

pub fn lookup_rewrite_label(&self, key: &str) -> Option<String>

Resolve a rewrite label: this document’s own labels first, then the shared document-wide map a streaming fragment carries (rewrite_labels_shared). The two-level lookup replaces copying the whole label index into every fragment — see the field docs.

Source

pub fn load_labels_for_rewrite(&mut self) -> Result<()>

Source

pub fn generate_id(&mut self, node: &mut Node, prefix: &str) -> Result<()>

This function computes an xml:id for a node, if it hasn’t already got one. It is suitable for use in Tag afterOpen as Tag('ltx:para',afterOpen=>sub { GenerateID(@_,'p'); }); It generates an id of the form <parentid>.<prefix><number> The parent node (the one with ID=<parentid>) also maintains a counter stored in an attribute _ID_counter_<prefix> recording the last used number for prefix amongst its descendents.

Source

pub fn replace_tree_detach( &mut self, new: Node, old: Node, ) -> Result<Option<Node>>

replace_tree, minus the free: the detached original stays alive and the CALLER owns it. The math parser needs this — parsing one formula rebuilds its tree while later formulae, queued up front, may sit inside the replaced subtree (a \text{…$x$…} inside math), so it defers every free to the end of the parse (replace_tree_deferred / data::defer_discard); freeing here handed those formulae to the parser detached and lost whole documents (sweep 102: glosmathtools, prftree, t-angles).

Source

pub fn replace_tree(&mut self, new: Node, old: Node) -> Result<Option<Node>>

Replace old by new (copied into place) and FREE the original: its ids were unrecorded before the copy and no handle into it is used afterwards (see remove_node for why a bare unlink leaks). Callers that must keep the original alive use replace_tree_detach.

Source

pub fn append_tree(&mut self, node: &mut Node, data: Vec<Node>) -> Result<()>

Source

pub fn insert_xml(&mut self, xml: &str) -> Result<()>

Parse an XML / (X)HTML markup string and splice the resulting subtree into the document at the current insertion point.

Named as the markup counterpart to Document::insert_element (Perl insertElement): both insert an already-FINISHED thing at the current point. Deliberately NOT an absorb* name — in Perl absorb consumes a digested Box and has no XML::LibXML branch at all (it would die on a node), so borrowing that verb here would imply a kinship that does not exist.

This is the Rust analog of Perl BookML’s \bmlRawHTML idiom, which composes two mechanisms core never chains itself: XML::LibXML->parse_string (LaTeXML::Common::XML::Parser parseChunk, Common/XML/Parser.pm:36-39) and $document->appendTree (Document.pm:2093, foreign-node branch :2105-2124). Both halves already exist here — libxml’s parser (a direct latexml_core dep, used in common/relaxng/scan.rs) and Document::append_tree — so this is pure glue.

The markup must be WELL-FORMED, but need not be a single root: several sibling nodes, or bare text, are accepted as a document fragment (OXIDIZED_DESIGN #66 — Perl’s parseChunk is single-node only). The parsed nodes are re-created one by one through append_tree’s model-aware path, so namespaces declared in the snippet (e.g. xhtml) are preserved and xml:ids re-registered. Malformed markup is REJECTED, never salvaged — see crate::common::xml::parse_chunk for what libxml’s recovery mode destroys — and surfaces as a clean Error: that inserts nothing, degrading the offending binding rather than aborting the conversion (the runtime-bindings failure-isolation contract).

Source

pub fn insert_nodes(&mut self, nodes: Vec<Node>) -> Result<()>

Splice ALREADY-PARSED nodes into the document at the current insertion point. The shared tail of Document::insert_xml and of any caller that obtained its nodes some other way (a script that parsed once and inserts repeatedly, or that edited the parsed tree before inserting).

The caller must keep whatever owns nodes alive across this call: libxml nodes are pointers into their document. crate::common::xml::ParsedFragment exists to make that ownership explicit rather than a comment.

As Perl’s appendTree on getElement (Document.pm:2093, :98); the model only warns (OXIDIZED_DESIGN_DIVERGENCES #1186). After text the point is the open text node: it is closed first, since libxml frees an element added to a text node (#1034).

Trait Implementations§

Source§

impl Default for Document

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Object for Document

Source§

fn get_locator(&self) -> Option<Locator>

The object’s stored source locator, if it has one. None is the honest “no recorded source position” (replacing the old Locator::default() file!()/line!() sentinel). For “where the parser is now” (error reporting, box creation), use the free fn gullet::get_locator().
Source§

fn stringify(&self) -> String

Source§

fn isa_box(&self) -> bool

Source§

fn is_expandable(&self) -> bool

Source§

fn is_definition(&self) -> bool

Source§

fn is_comment(&self) -> bool

Source§

fn get_origin(&self) -> DefinitionOrigin

Who made this definition (K1 provenance, definition::origin). The default is Unknown, which counts as LaTeXML’s own.
Source§

fn revert(&self) -> Result<Tokens>

each concrete object needs to provide its own path back to tokens

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.