Skip to main content

latexml_post/mathml/
mod.rs

1//! MathML conversion processor.
2//!
3//! Port of `LaTeXML::Post::MathML` (2162 lines) + submodules:
4//! - `Presentation.pm` (146 lines) — Presentation MathML rendering rules
5//! - `Content.pm` (31 lines) — Content MathML rendering rules
6//! - `Linebreaker.pm` (1053 lines) — MathML line-breaking algorithm
7//! - `OperatorDictionary.pm` (252 lines) — Operator symbol table
8//!
9//! This is the primary math conversion format for web output.
10//! Converts XMath parsed math into Presentation MathML and/or Content MathML.
11
12pub mod content;
13pub mod linebreaker;
14pub mod operator_dictionary;
15pub mod presentation;
16
17use latexml_core::common::xml::name_is;
18use libxml::tree::Node;
19use rustc_hash::FxHashMap as HashMap;
20
21use crate::{
22  document::{NodeData, PostDocument},
23  math_processor::{MathConversion, MathProcessor, math_is_parsed, process_math},
24  processor::{ProcessResult, Processor},
25};
26
27const MML_URI: &str = "http://www.w3.org/1998/Math/MathML";
28const MML_MIMETYPE: &str = "application/mathml-presentation+xml";
29const CMML_MIMETYPE: &str = "application/mathml-content+xml";
30
31/// MathML post-processor.
32///
33/// Port of `LaTeXML::Post::MathML`.
34/// Handles both Presentation and Content MathML conversion.
35pub struct MathML {
36  name:            String,
37  is_secondary:    bool,
38  /// Whether to produce Content MathML (vs Presentation).
39  content_mathml:  bool,
40  /// Whether to remap styled alphanumerics to Unicode's Plane-1 Mathematical
41  /// Alphanumeric Symbols. Perl `$$MATHPROCESSOR{plane1}`, default on
42  /// (`preprocess` L70); `--noplane1` keeps ASCII + a `mathvariant` attribute.
43  plane1:          bool,
44  /// Perl `$$MATHPROCESSOR{hackplane1}` (`--hackplane1`): remap only the
45  /// variants in `plane1_hackable`, and to the simpler variant named there.
46  /// Implies `plane1` (Perl L71).
47  hack_plane1:     bool,
48  /// Whether to enable line-breaking.
49  linebreaking:    bool,
50  /// Line width for line-breaking.
51  line_width:      u32,
52  /// Whether to keep the XMath nodes alongside the generated MathML.
53  keep_xmath:      bool,
54  /// Whether to emit invisible times (U+2062). When false, replaces with zero-width space.
55  /// Perl: $$MATHPROCESSOR{invisibletimes} — defaults to true.
56  invisible_times: bool,
57  /// Whether to include TeX source annotation in parallel MathML.
58  /// Perl: --mathtex adds <m:annotation encoding='application/x-tex'>
59  mathtex:         bool,
60  /// Whether to add intent=":literal" on all `<math>` elements.
61  /// ar5iv.sty.ltxml monkey-patches outerWrapper to add this.
62  intent_literal:  bool,
63  /// Parallel-markup secondaries (e.g. a Content-MathML processor under a
64  /// Presentation-MathML primary). Held by the primary rather than registered
65  /// as independent chain passes: during the primary's `process_math_node`,
66  /// each secondary's `convert_node` runs against the still-live XMath and the
67  /// results are folded into one `<m:semantics>` via [`combine_parallel`].
68  /// Port of Perl `MathProcessor`'s primary→secondary parallel model
69  /// (`$$self{parallel}` / `combineParallel`). Empty for a standalone format.
70  secondaries:     Vec<Box<dyn MathProcessor>>,
71}
72
73impl MathML {
74  /// Create a Presentation MathML processor.
75  pub fn new_presentation() -> Self {
76    MathML {
77      name:            "MathML[Presentation]".to_string(),
78      is_secondary:    false,
79      content_mathml:  false,
80      plane1:          true,
81      hack_plane1:     false,
82      linebreaking:    false,
83      line_width:      80,
84      keep_xmath:      false,
85      invisible_times: true,
86      mathtex:         false,
87      intent_literal:  false,
88      secondaries:     Vec::new(),
89    }
90  }
91
92  /// Create a Content MathML processor.
93  pub fn new_content() -> Self {
94    MathML {
95      name:            "MathML[Content]".to_string(),
96      is_secondary:    false,
97      content_mathml:  true,
98      plane1:          true,
99      hack_plane1:     false,
100      linebreaking:    false,
101      line_width:      80,
102      keep_xmath:      false,
103      invisible_times: true,
104      mathtex:         false,
105      intent_literal:  false,
106      secondaries:     Vec::new(),
107    }
108  }
109
110  /// Enable intent=":literal" on all `<math>` elements.
111  /// Perl: ar5iv.sty.ltxml monkey-patches outerWrapper for this.
112  pub fn with_intent_literal(mut self, enable: bool) -> Self {
113    self.intent_literal = enable;
114    self
115  }
116
117  /// Enable line-breaking with the given width.
118  pub fn with_linebreaking(mut self, width: u32) -> Self {
119    self.linebreaking = true;
120    self.line_width = width;
121    self
122  }
123
124  /// Keep XMath nodes in the output alongside MathML.
125  pub fn with_keep_xmath(mut self, keep: bool) -> Self {
126    self.keep_xmath = keep;
127    self
128  }
129
130  /// Set whether to emit invisible times (U+2062) in MathML output.
131  /// When false, invisible times is replaced with zero-width space (U+200B).
132  /// Perl: --noinvisibletimes
133  pub fn with_invisible_times(mut self, emit: bool) -> Self {
134    self.invisible_times = emit;
135    self
136  }
137
138  /// Set the Plane-1 remapping mode. `plane1` off keeps ASCII text plus a
139  /// `mathvariant` attribute; `hack_plane1` remaps only the poorly-supported
140  /// variants and implies `plane1`. Perl `--plane1` / `--hackplane1`.
141  pub fn with_plane1(mut self, plane1: bool, hack_plane1: bool) -> Self {
142    self.plane1 = plane1;
143    self.hack_plane1 = hack_plane1;
144    self
145  }
146
147  /// Enable TeX source annotation in MathML output (--mathtex).
148  pub fn with_mathtex(mut self, enable: bool) -> Self {
149    self.mathtex = enable;
150    self
151  }
152
153  /// Mark this processor as a parallel-markup secondary (e.g. the Content-MathML
154  /// format under a Presentation primary). Secondaries get their format-specific
155  /// `id_suffix` and are folded into the primary's `<m:semantics>` rather than
156  /// emitted as a standalone `<m:math>`. Port of `MathProcessor`'s secondary role.
157  pub fn secondary(mut self) -> Self {
158    self.is_secondary = true;
159    self
160  }
161
162  /// Attach parallel-markup secondaries to this (primary) processor. Their
163  /// conversions are merged into one `<m:semantics>` by
164  /// [`combine_parallel`](MathProcessor::combine_parallel)
165  /// during the primary's pass. Mirrors Perl `MathProcessor`'s primary holding
166  /// its parallel secondaries.
167  pub fn with_secondaries(mut self, secondaries: Vec<Box<dyn MathProcessor>>) -> Self {
168    self.secondaries = secondaries;
169    self
170  }
171}
172
173impl Processor for MathML {
174  fn get_name(&self) -> &str { &self.name }
175
176  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
177    doc.findnodes("//ltx:Math[not(ancestor::ltx:Math)]")
178  }
179
180  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
181    // Register the MathML namespace so add_nodes can create m: elements
182    doc.add_namespace("m", MML_URI);
183    content::reset_document_share_counter();
184
185    // Process all math nodes
186    process_math(self, &mut doc, nodes, self.keep_xmath)?;
187    Ok(vec![doc])
188  }
189}
190
191impl MathProcessor for MathML {
192  fn convert_node(&self, doc: &PostDocument, xmath: &Node) -> Option<MathConversion> {
193    // Set invisible_times flag for rendering
194    presentation::set_invisible_times(self.invisible_times);
195    presentation::set_plane1(self.plane1, self.hack_plane1);
196
197    let xml = if self.content_mathml {
198      content::convert_to_cmml(doc, xmath)
199    } else {
200      presentation::convert_to_pmml(doc, xmath)
201    };
202
203    let mimetype = if self.content_mathml {
204      CMML_MIMETYPE
205    } else {
206      MML_MIMETYPE
207    };
208
209    // If mathtex is enabled, wrap in <m:semantics> with TeX annotation.
210    // Skip when this primary carries parallel secondaries: `combine_parallel`
211    // then builds the single `<m:semantics>` (primary + content annotation-xml
212    // + the x-tex annotation), so wrapping here would double-nest semantics.
213    let final_xml = if self.mathtex && self.secondaries.is_empty() {
214      let tex_str = xmath
215        .get_parent()
216        .and_then(|p| p.get_attribute("tex"))
217        .unwrap_or_default();
218      if tex_str.is_empty() {
219        xml
220      } else {
221        NodeData::Element {
222          tag:        "m:semantics".to_string(),
223          attributes: None,
224          children:   vec![xml, NodeData::Element {
225            tag:        "m:annotation".to_string(),
226            attributes: Some(HashMap::from_iter([(
227              "encoding".to_string(),
228              "application/x-tex".to_string(),
229            )])),
230            children:   vec![NodeData::Text(tex_str)],
231          }],
232        }
233      }
234    } else {
235      xml
236    };
237
238    Some(MathConversion {
239      processor_name: self.name.clone(),
240      mimetype:       Some(mimetype.to_string()),
241      xml:            Some(final_xml),
242      string:         None,
243      src:            None,
244      width:          None,
245      height:         None,
246      depth:          None,
247    })
248  }
249
250  fn combine_parallel(
251    &self,
252    _doc: &PostDocument,
253    xmath: &Node,
254    primary: MathConversion,
255    secondaries: Vec<MathConversion>,
256  ) -> MathConversion {
257    if secondaries.is_empty() {
258      return primary;
259    }
260
261    // Build m:semantics element with primary + annotation-xml for secondaries
262    let mut children = Vec::new();
263    if let Some(ref xml) = primary.xml {
264      children.push(xml.clone());
265    }
266    let primary_only = children.len();
267
268    for secondary in &secondaries {
269      let mimetype = secondary.mimetype.as_deref().unwrap_or("unknown");
270      // Parallel markup names the format via the canonical encoding label
271      // (e.g. `MathML-Content`), not the raw internal mimetype. Port of
272      // `%ENCODINGS` / `encoding_for_mimetype`.
273      let encoding = encoding_for_mimetype(mimetype).to_string();
274      if let Some(ref xml) = secondary.xml {
275        children.push(NodeData::Element {
276          tag:        "m:annotation-xml".to_string(),
277          attributes: Some(HashMap::from_iter([("encoding".to_string(), encoding)])),
278          children:   vec![xml.clone()],
279        });
280      } else if let Some(string) = secondary.string.as_ref().filter(|s| !s.is_empty()) {
281        // Perl `MathML.pm` L128 `elsif (my $string = ...)` skips a false string. Only
282        // the empty one is meant: Perl's truthiness also drops "0", losing the
283        // UnicodeMath annotation of `$0$` (KNOWN_PERL_ERRORS #1289), which we keep.
284        children.push(NodeData::Element {
285          tag:        "m:annotation".to_string(),
286          attributes: Some(HashMap::from_iter([("encoding".to_string(), encoding)])),
287          children:   vec![NodeData::Text(string.clone())],
288        });
289      }
290    }
291
292    // TeX source annotation. In the standalone (no-secondary) path this is added
293    // by `convert_node`; in the parallel path that wrap is skipped, so the
294    // single combined `<m:semantics>` carries the x-tex annotation here.
295    if self.mathtex {
296      let tex_str = xmath
297        .get_parent()
298        .and_then(|p| p.get_attribute("tex"))
299        .unwrap_or_default();
300      if !tex_str.is_empty() {
301        children.push(NodeData::Element {
302          tag:        "m:annotation".to_string(),
303          attributes: Some(HashMap::from_iter([(
304            "encoding".to_string(),
305            "application/x-tex".to_string(),
306          )])),
307          children:   vec![NodeData::Text(tex_str)],
308        });
309      }
310    }
311
312    // Perl L132-133: `m:semantics` only when some annotation was made, else the
313    // primary as it is (an empty UnicodeMath string adds none).
314    if children.len() == primary_only {
315      return primary;
316    }
317    MathConversion {
318      processor_name: self.name.clone(),
319      mimetype:       primary
320        .mimetype
321        .clone()
322        .or_else(|| Some(MML_MIMETYPE.to_string())),
323      xml:            Some(NodeData::Element {
324        tag: "m:semantics".to_string(),
325        attributes: None,
326        children,
327      }),
328      string:         None,
329      src:            None,
330      width:          None,
331      height:         None,
332      depth:          None,
333    }
334  }
335
336  fn outer_wrapper(&self, _doc: &PostDocument, xmath: &Node, conversion: NodeData) -> NodeData {
337    let mut attrs = HashMap::default();
338    // Determine display mode and alttext from parent Math element
339    // Port of MathML::outerWrapper (L77-100)
340    if let Some(math) = xmath.get_parent() {
341      let mode = math
342        .get_attribute("mode")
343        .unwrap_or_else(|| "inline".to_string());
344      attrs.insert(
345        "display".to_string(),
346        if mode == "display" {
347          "block".to_string()
348        } else {
349          "inline".to_string()
350        },
351      );
352      if let Some(tex) = math.get_attribute("tex") {
353        attrs.insert("alttext".to_string(), tex);
354      }
355      if let Some(class) = math.get_attribute("class") {
356        attrs.insert("class".to_string(), class);
357      }
358
359      // Image fallback (Perl L81-87): when the `--mathimages` post-processor has
360      // rendered this formula, advertise the bitmap so a renderer without MathML
361      // support can show it. `altimg-valign` carries the baseline offset and Perl
362      // NEGATES the depth ("Note the sign!"): `imagedepth="5"` → `-5px`.
363      if let Some(src) = math.get_attribute("imagesrc").filter(|s| !s.is_empty()) {
364        attrs.insert("altimg".to_string(), src);
365        // Perl appends 'px' unconditionally once `imagesrc` is present, so a
366        // missing `imagewidth` yields the literal `"px"` rather than omitting the
367        // attribute. Mirrored: `--mathimages` always sets both dimensions, so the
368        // quirk is unreachable in practice, and diverging here would cost
369        // byte-parity for no gain.
370        attrs.insert(
371          "altimg-width".to_string(),
372          format!("{}px", math.get_attribute("imagewidth").unwrap_or_default()),
373        );
374        attrs.insert(
375          "altimg-height".to_string(),
376          format!(
377            "{}px",
378            math.get_attribute("imageheight").unwrap_or_default()
379          ),
380        );
381        // Perl-falsy depth (absent, empty, or "0") omits the attribute entirely
382        // rather than emitting a bare "-px" or "-0px".
383        if let Some(depth) = math
384          .get_attribute("imagedepth")
385          .filter(|d| !d.is_empty() && d != "0")
386        {
387          attrs.insert("altimg-valign".to_string(), format!("-{depth}px"));
388        }
389      }
390
391      // RDFa (Perl L88-90): the Math element's own value, else the XMath's.
392      // Perl's `$math->getAttribute($_) || $xmath->getAttribute($_)` is a TRUTH
393      // test, so an EMPTY value on the Math falls through to the XMath rather
394      // than shadowing it; the trailing `$val ? … : ()` then drops the pair if
395      // neither had one.
396      for key in [
397        "about", "resource", "property", "rel", "rev", "typeof", "datatype", "content",
398      ] {
399        let non_empty = |n: &Node| n.get_attribute(key).filter(|v| !v.is_empty());
400        if let Some(val) = non_empty(&math).or_else(|| non_empty(xmath)) {
401          attrs.insert(key.to_string(), val);
402        }
403      }
404    }
405
406    // ar5iv.sty.ltxml: intent=":literal" for all math elements
407    if self.intent_literal {
408      attrs.insert("intent".to_string(), ":literal".to_string());
409    }
410
411    NodeData::Element {
412      tag:        "m:math".to_string(),
413      attributes: Some(attrs),
414      children:   vec![conversion],
415    }
416  }
417
418  fn raw_id_suffix(&self) -> &str {
419    if self.content_mathml {
420      ".cmml"
421    } else {
422      ".pmml"
423    }
424  }
425
426  fn is_secondary(&self) -> bool { self.is_secondary }
427
428  fn can_convert(&self, _doc: &PostDocument, math: &Node) -> bool {
429    // Content MathML requires parsed math
430    if self.content_mathml {
431      math_is_parsed(math)
432    } else {
433      true
434    }
435  }
436
437  fn parallel_secondaries(&self) -> &[Box<dyn MathProcessor>] { &self.secondaries }
438
439  fn preprocess(&self, _doc: &PostDocument, _nodes: &[Node]) {
440    // Register MathML namespace
441    log::trace!("MathML: would register m namespace for {}", MML_URI);
442  }
443}
444
445/// MathML encoding names for parallel markup annotation-xml.
446///
447/// Port of `%ENCODINGS`.
448pub fn encoding_for_mimetype(mimetype: &str) -> &str {
449  match mimetype {
450    "application/mathml-presentation+xml" => "MathML-Presentation",
451    "application/mathml-content+xml" => "MathML-Content",
452    "image/svg+xml" => "SVG1.1",
453    _ => mimetype,
454  }
455}
456
457/// Math style step-down table.
458///
459/// Port of `%stylestep`.
460pub fn style_step(style: &str) -> &str {
461  match style {
462    "display" => "text",
463    "text" => "script",
464    "script" => "scriptscript",
465    _ => "scriptscript",
466  }
467}
468
469/// Size percentage for math styles.
470///
471/// Port of `%stylesize`.
472pub fn style_size(style: &str) -> &str {
473  match style {
474    "display" | "text" => "100%",
475    "script" => "70%",
476    _ => "50%",
477  }
478}
479
480/// Perl's `%attr` for `pmml_text_aux` — the presentation attributes an
481/// enclosing `ltx:*` element contributes to the `m:mtext` elements below it.
482///
483/// Perl threads an open hash (`MathML.pm` L1029, L1041-1045), but only these
484/// five keys are ever written on this path, so they are named fields. The other
485/// keys `stylizeContent` consults (`role`, `class`, `cssstyle`, `href`, `title`,
486/// `stretchy`) are never set by this caller — they come off the node itself.
487#[derive(Clone, Default, Debug)]
488pub struct TextAttrs {
489  font:            Option<String>,
490  fontsize:        Option<String>,
491  color:           Option<String>,
492  backgroundcolor: Option<String>,
493  opacity:         Option<String>,
494}
495
496impl TextAttrs {
497  /// Overlay `node`'s own presentation attributes, as Perl `pmml_text_aux`
498  /// L1041-1045 does: an attribute PRESENT on the element wins over what was
499  /// inherited; an absent one leaves the inherited value in place.
500  fn overlay(&self, node: &Node) -> Self {
501    let pick = |cur: &Option<String>, name: &str| -> Option<String> {
502      node
503        .get_attribute(name)
504        .filter(|v| !v.is_empty())
505        .or_else(|| cur.clone())
506    };
507    Self {
508      font:            pick(&self.font, "font"),
509      fontsize:        pick(&self.fontsize, "fontsize"),
510      color:           pick(&self.color, "color"),
511      backgroundcolor: pick(&self.backgroundcolor, "backgroundcolor"),
512      opacity:         pick(&self.opacity, "opacity"),
513    }
514  }
515}
516
517/// The first direct element child of `node` with the given namespace URI and
518/// local name — Perl's `findnode('<prefix>:<name>', $node)` without depending on
519/// the prefix being registered in the document's XPath context.
520fn element_child_named(node: &Node, ns_uri: &str, local: &str) -> Option<Node> {
521  let mut current = node.get_first_child();
522  while let Some(c) = current {
523    if c.get_type() == Some(libxml::tree::NodeType::ElementNode)
524      && name_is(&c, local)
525      && c.get_namespace().map(|ns| ns.get_href()).as_deref() == Some(ns_uri)
526    {
527      return Some(c);
528    }
529    current = c.get_next_sibling();
530  }
531  None
532}
533
534/// Perl's `\p{Format}` over the codepoints that occur in math content — the
535/// same approximation `pmml_token_inner` uses, so the two arms agree.
536fn is_format_char(c: char) -> bool {
537  matches!(c,
538    '\u{00AD}' | '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}')
539}
540
541/// `stylizeContent` (`MathML.pm` L672-828) for the `$tag eq 'm:mtext'` case —
542/// the styling half of the `pmml_text_aux` path.
543///
544/// **The token half of the same Perl function lives in
545/// `presentation::pmml_token_inner`**, the golden-guarded faithful copy of the
546/// `m:mi`/`m:mo`/`m:mn` branches (operator dictionary, plane-1 remapping,
547/// stretch/size interplay). Perl is one function; the Rust split is by target
548/// tag, and neither half should grow the other's branches. (This function used
549/// to be a whole second copy of `stylizeContent`, tag-generic and dead — nothing
550/// called it, so its `m:mo` arm had drifted out of parity unnoticed.)
551///
552/// What `m:mtext` reaches, and hence emits:
553/// - **no `mathvariant`** — Perl clears it unconditionally for `m:mtext`
554///   (L756-757); a font survives only as an `ltx_font_*` / `ltx_mathvariant_*`
555///   CSS class.
556/// - **no plane-1 remapping** — guarded off by `($tag ne 'm:mtext')` (L737).
557/// - **no `href`/`title`** — gated on `$istoken` (L691-692).
558/// - **no operator-dictionary attributes** — `%props` is filled only for `m:mo`
559///   (L764), and `$stretchy` is cleared for every other tag (L767). So Perl's
560///   `delete $mmlattr{stretchy}` in `pmml_text_aux` (L1069) is belt-and-braces
561///   over something already absent, and has nothing to port.
562///
563/// `node` is `None` for a text node — Perl's non-`XML_ELEMENT_NODE` `$item`,
564/// which contributes no attributes of its own (`$iselement` is false).
565///
566/// Returns Perl's `($text, %mmlattr)` pair. The text can differ from the input
567/// only via the empty-item failsafe below; the caller that discards it (the
568/// raw-markup arm, Perl's `my ($ignore, %mmlattr)`) is doing what Perl does.
569fn stylize_text_content(
570  node: Option<&Node>,
571  attrs: &TextAttrs,
572  text: &str,
573) -> (String, HashMap<String, String>) {
574  let attr_of = |name: &str| -> Option<String> {
575    node
576      .and_then(|n| n.get_attribute(name))
577      .filter(|v| !v.is_empty())
578  };
579  // Perl L677-686: the passed-in %attr wins, then the item's own attribute,
580  // then the inherited context — the text around the formula, which an
581  // `XMText`'s content is written against (OXIDIZED_DESIGN_DIVERGENCES #780).
582  let font = attrs
583    .font
584    .clone()
585    .or_else(|| attr_of("font"))
586    .or_else(presentation::ctx_text_font);
587  let size = attrs.fontsize.clone().or_else(|| attr_of("fontsize"));
588  let color = attrs
589    .color
590    .clone()
591    .or_else(|| attr_of("color"))
592    .or_else(presentation::ctx_color);
593  // NB Perl L683-684 reads `$attr{backgroundcolor} && ($iselement &&
594  // $item->getAttribute('backgroundcolor')) || $BGCOLOR`, so the item's own
595  // attribute counts only when an inherited one is ALSO set, and the result is
596  // then the item's. Mirrored, quirk included; `pmml_token_inner` carries the
597  // same note for the token arm.
598  let bgcolor = attrs
599    .backgroundcolor
600    .as_ref()
601    .and_then(|_| attr_of("backgroundcolor"))
602    .or_else(presentation::ctx_bgcolor);
603  let opacity = attrs
604    .opacity
605    .clone()
606    .or_else(|| attr_of("opacity"))
607    .or_else(presentation::ctx_opacity);
608  let mut class = attr_of("class");
609  // NB Perl reads `$attr{ccsstyle}` here (L686) — three c's, a typo for
610  // `cssstyle`, so the passed-in half never contributes and only the item's own
611  // attribute is ever seen. `%attr` carries no cssstyle on this path either way.
612  let mut cssstyle = attr_of("cssstyle");
613
614  // Perl L707-713: the failsafe for an item with nothing to show. An invisible
615  // operator supplies its own character; anything else falls back to the item's
616  // name, meaning or role — or a literal `?` for a bare text node — and is
617  // painted red, since arriving here means something upstream emitted an empty
618  // token. The red usually does NOT survive: an all-empty fallback is caught by
619  // the Format test below, which clears the color again.
620  let role = attr_of("role");
621  let mut color = color;
622  let text = if text.is_empty() {
623    match role
624      .as_deref()
625      .and_then(presentation::default_token_content)
626    {
627      Some(default) => default.to_string(),
628      None => {
629        color = Some("red".to_string());
630        if node.is_some() {
631          attr_of("name")
632            .or_else(|| attr_of("meaning"))
633            .or(role)
634            .unwrap_or_default()
635        } else {
636          "?".to_string()
637        }
638      },
639    }
640  } else {
641    text.to_string()
642  };
643
644  // Perl L744-745: purely-Format content (invisible times/apply/separator, …)
645  // needs no visual styling attributes at all.
646  let (font, color, bgcolor, opacity) = if text.chars().all(is_format_char) {
647    (None, None, None, None)
648  } else {
649    (font, color, bgcolor, opacity)
650  };
651
652  // Perl L746-756: patch up weak font translations with a CSS class. For
653  // `m:mtext` this is the ONLY channel a font has, since the mathvariant is
654  // dropped below.
655  if let Some(ref f) = font {
656    let extra = if f.contains("caligraphic") {
657      Some("ltx_font_mathcaligraphic".to_string())
658    } else if f.contains("script") {
659      Some("ltx_font_mathscript".to_string())
660    } else if f.contains("fraktur") && text.chars().all(|c| "+-0123456789.".contains(c)) {
661      Some("ltx_font_oldstyle".to_string())
662    } else if f.contains("smallcaps") {
663      Some("ltx_font_smallcaps".to_string())
664    } else {
665      Some(crate::unicode::unicode_mathvariant(f))
666        .filter(|v| *v != "normal")
667        .map(|v| format!("ltx_mathvariant_{v}"))
668    };
669    if let Some(extra) = extra {
670      class = Some(match class {
671        Some(c) if !c.is_empty() => format!("{c} {extra}"),
672        _ => extra,
673      });
674    }
675  }
676
677  // Perl L758-759: opacity folds into the css style.
678  if let Some(op) = opacity {
679    cssstyle = Some(match cssstyle {
680      Some(c) if !c.is_empty() => format!("{c};opacity:{op}"),
681      _ => format!("opacity:{op}"),
682    });
683  }
684
685  let mut out: HashMap<String, String> = HashMap::default();
686  // Perl L770-771: text that is empty or purely invisible operators gets no
687  // size (nor stretchiness, which an `m:mtext` could not carry anyway). Note
688  // this is a NARROWER class than the `\p{Format}` test above — only the three
689  // invisible operators — so the two cannot be folded together.
690  let size = size.filter(|_| !text.chars().all(|c| matches!(c, '\u{2061}'..='\u{2063}')));
691
692  // Perl L779-797: emit a size only when it differs from the style's nominal
693  // size, re-expressed relative to a script context and converted to em. The
694  // `stretchyhack` minsize/maxsize arm needs `$issymm`, which for a non-`m:mo`
695  // tag reduces to `$text eq '/'` (L703) — `$islargeop` needs a SUMOP/INTOP
696  // role and `$props{symmetric}` is `m:mo`-only.
697  if let Some(s) = size.filter(|s| s != presentation::context_size()) {
698    let s = presentation::resolve_size(s);
699    if text == "/" {
700      out.insert("minsize".to_string(), s.clone());
701      out.insert("maxsize".to_string(), s);
702    } else {
703      out.insert("mathsize".to_string(), s);
704    }
705  }
706  if let Some(c) = color {
707    out.insert("mathcolor".to_string(), c);
708  }
709  if let Some(bg) = bgcolor {
710    out.insert("mathbackground".to_string(), bg);
711  }
712  if let Some(style) = cssstyle.filter(|s| !s.is_empty()) {
713    out.insert("style".to_string(), style);
714  }
715  if let Some(c) = class.filter(|c| !c.is_empty()) {
716    out.insert("class".to_string(), c);
717  }
718  (text, out)
719}
720
721/// Convert an XMHint spacing attribute to em value.
722///
723/// Port of `getXMHintSpacing`.
724pub fn get_xm_hint_spacing(width: &str) -> f64 {
725  // Perl (MathML.pm L380-385): /^([\d\.\+\-]+)(pt|mu|em)(\s+plus\s+…)?(\s+minus\s+…)?$/
726  // — a GLUE width ("3.0pt plus 2.0pt minus 1.0pt") contributes its natural
727  // part; the stretch/shrink tails are ignored.
728  let trimmed = width.trim();
729  let base = trimmed
730    .split(" plus ")
731    .next()
732    .unwrap_or(trimmed)
733    .split(" minus ")
734    .next()
735    .unwrap_or(trimmed)
736    .trim();
737  if let Some((num_str, unit)) = base
738    .rfind(|c: char| c.is_ascii_digit() || c == '.')
739    .map(|i| (&base[..=i], base[i + 1..].trim()))
740  {
741    let num: f64 = num_str.parse().unwrap_or(0.0);
742    match unit {
743      "em" => num,
744      "mu" => num / 18.0,
745      "pt" => num / 10.0, // Assuming 10pt font
746      _ => 0.0,
747    }
748  } else {
749    0.0
750  }
751}
752
753/// Find an inherited attribute by walking up the LaTeXML ancestor chain.
754///
755/// Port of `find_inherited_attribute`.
756pub fn find_inherited_attribute(
757  _doc: &PostDocument,
758  node: &Node,
759  attribute: &str,
760) -> Option<String> {
761  let mut current = Some(node.clone());
762  while let Some(ref n) = current {
763    // Perl getQName returns undef for non-elements → stop. Also guards the
764    // FFI: reading the ns field of a Document node is a misaligned deref.
765    if n.get_type() != Some(libxml::tree::NodeType::ElementNode) {
766      break;
767    }
768    if let Some(ns) = n.get_namespace() {
769      if ns.get_href() != crate::document::LTX_NSURI {
770        break; // Stop at non-LaTeXML elements
771      }
772    }
773    if let Some(val) = n.get_attribute(attribute) {
774      return Some(val);
775    }
776    current = n.get_parent();
777  }
778  None
779}
780
781/// The font a formula's tokens are read against: a `font` inside the formula (between the `XMath` and its
782/// `ltx:Math`), never the text around it. Perl's pmml_top/cmml_top take [`find_inherited_attribute`]
783/// (MathML.pm:278, :1293), the enclosing text element's font, which is right only while the tokens are written
784/// relative to that element; ours are written relative to the text default (document.rs `finalize_rec`), so a token
785/// without a `font` is upright serif whatever text surrounds the formula, and a sans or italic text font must not
786/// reach it (`<mi>` of `\mathrm{c}` in a theorem body, of `+` in `\emph` of a sans document).
787/// OXIDIZED_DESIGN_DIVERGENCES #780; witness 2608.14133.
788pub fn math_context_font(xmath: &Node) -> Option<String> {
789  let mut current = Some(xmath.clone());
790  while let Some(ref n) = current {
791    if n.get_type() != Some(libxml::tree::NodeType::ElementNode) {
792      break;
793    }
794    if n
795      .get_namespace()
796      .is_some_and(|ns| ns.get_href() != crate::document::LTX_NSURI)
797    {
798      break;
799    }
800    if let Some(val) = n.get_attribute("font") {
801      return Some(val);
802    }
803    if name_is(n, "Math") {
804      return None;
805    }
806    current = n.get_parent();
807  }
808  None
809}
810
811// ======================================================================
812// DefMathML converter dispatch table
813//
814// Port of the `%MMLTable_P` / `%MMLTable_C` lookup tables and the
815// 800+ lines of DefMathML declarations in MathML.pm.
816//
817// The Perl pattern is:
818//   DefMathML("Mode:Role:Meaning", \&pmml_handler, \&cmml_handler);
819// Lookup tries: "Mode:Role:Meaning", "Mode:?:Meaning", "Mode:Role:?", "Mode:?:?"
820//
821// In Rust, we encode this as a static table of known role→tag mappings
822// and meaning→element mappings, and the actual dispatch happens in
823// presentation.rs::pmml_apply() and content.rs::cmml().
824
825/// Presentation MathML tag for a token role.
826///
827/// Port of Token:ROLE:? DefMathML declarations.
828/// These map roles to their default MathML element type.
829pub fn pmml_tag_for_role(role: &str) -> &'static str {
830  match role {
831    // Operators → m:mo
832    "PUNCT" | "PERIOD" | "OPEN" | "CLOSE" | "MIDDLE" | "VERTBAR" | "ARROW" | "OVERACCENT"
833    | "UNDERACCENT" | "ADDOP" | "MULOP" | "BINOP" | "RELOP" | "METARELOP" | "MODIFIEROP"
834    | "COMPOSEOP" | "APPLYOP" | "OPERATOR" | "SUPOP" | "POSTFIX" | "DIFFOP" => "m:mo",
835    // Big operators → m:mo (with largeop)
836    "BIGOP" | "SUMOP" | "INTOP" | "LIMITOP" => "m:mo",
837    // Functions → m:mi (but rendered as operator names)
838    "FUNCTION" | "OPFUNCTION" | "TRIGFUNCTION" => "m:mi",
839    // Numbers → m:mn
840    "NUMBER" => "m:mn",
841    // Identifiers → m:mi (default)
842    _ => "m:mi",
843  }
844}
845
846/// Whether a role should use the "big operator" presentation style.
847///
848/// Port of `Token:INTOP:?` → `\&pmml_bigop`, `Token:SUMOP:?` → `\&pmml_bigop`, etc.
849pub fn is_bigop_role(role: &str) -> bool { matches!(role, "INTOP" | "SUMOP" | "BIGOP" | "LIMITOP") }
850
851/// Presentation handler type for XMApp nodes.
852///
853/// Port of the `Apply:ROLE:?` entries in DefMathML.
854/// Returns the handler category that presentation.rs should use.
855#[derive(Debug, Clone, Copy, PartialEq)]
856pub enum ApplyHandler {
857  /// Infix: op between args (ADDOP, MULOP, RELOP, etc.)
858  Infix,
859  /// Script: sub/superscript (SUPERSCRIPTOP, SUBSCRIPTOP)
860  Script,
861  /// Big operator with possible limits (SUMOP, INTOP, BIGOP, LIMITOP)
862  Summation,
863  /// Prefix: op before args (DIFFOP, default)
864  Prefix,
865  /// Postfix: args then op (POSTFIX)
866  Postfix,
867  /// Fraction (FRACOP)
868  Fraction,
869  /// Over accent (OVERACCENT)
870  OverAccent,
871  /// Under accent (UNDERACCENT)
872  UnderAccent,
873  /// Enclose (ENCLOSE)
874  Enclose,
875  /// Generic application (default)
876  Generic,
877}
878
879/// Determine the presentation handler for an XMApp based on operator role.
880///
881/// Port of the `Apply:ROLE:?` DefMathML declarations.
882pub fn apply_handler_for_role(role: &str) -> ApplyHandler {
883  match role {
884    "ADDOP" | "MULOP" | "BINOP" | "RELOP" | "METARELOP" | "ARROW" | "COMPOSEOP" | "MODIFIEROP"
885    | "MIDDLE" => ApplyHandler::Infix,
886    "SUPERSCRIPTOP" | "SUBSCRIPTOP" => ApplyHandler::Script,
887    "SUMOP" | "INTOP" | "BIGOP" | "LIMITOP" => ApplyHandler::Summation,
888    "DIFFOP" => ApplyHandler::Prefix,
889    "POSTFIX" => ApplyHandler::Postfix,
890    "FRACOP" => ApplyHandler::Fraction,
891    "OVERACCENT" => ApplyHandler::OverAccent,
892    "UNDERACCENT" => ApplyHandler::UnderAccent,
893    "ENCLOSE" => ApplyHandler::Enclose,
894    _ => ApplyHandler::Generic,
895  }
896}
897
898/// Determine the presentation handler for a specific meaning.
899///
900/// Port of the `Apply:?:meaning` DefMathML declarations.
901/// Returns Some(handler) if a meaning-specific handler exists, None for role-based fallback.
902pub fn apply_handler_for_meaning(meaning: &str) -> Option<ApplyHandler> {
903  match meaning {
904    "square-root" | "nth-root" => None, // Handled specially in pmml_apply
905    "formulae" | "multirelation" => Some(ApplyHandler::Infix),
906    "limit-from" | "annotated" => Some(ApplyHandler::Prefix),
907    "continued-fraction" => Some(ApplyHandler::Fraction),
908    _ => None,
909  }
910}
911
912/// Known Content MathML elements for specific meanings.
913///
914/// Port of the `Token:?:meaning` content DefMathML declarations.
915/// See also content.rs::meaning_to_cmml_element() for the full list.
916pub fn cmml_element_for_meaning(meaning: &str) -> Option<&'static str> {
917  content::meaning_to_cmml_element_pub(meaning)
918}
919
920/// Whether an XMApp with this meaning has a dedicated Content MathML structure.
921///
922/// Port of the `Apply:?:meaning` content DefMathML declarations.
923pub fn has_dedicated_cmml_structure(meaning: &str) -> bool {
924  matches!(
925    meaning,
926    "square-root"
927      | "nth-root"
928      | "set"
929      | "list"
930      | "open-interval"
931      | "closed-interval"
932      | "closed-open-interval"
933      | "open-closed-interval"
934      | "formulae"
935      | "multirelation"
936      | "cases"
937  )
938}
939
940// ======================================================================
941// Presentation MathML helpers
942//
943// Port of `pmml_maybe_resize`, `pmml_row`, `pmml_parenthesize`,
944// `pmml_text_aux`, `filter_row` from MathML.pm.
945
946/// Wrap items in an mrow, filtering out ignorable items.
947///
948/// Port of `pmml_row` + `filter_row`.
949pub fn pmml_row(items: Vec<NodeData>) -> NodeData {
950  // Filter out ignorable items (those with _ignorable attribute)
951  let filtered: Vec<NodeData> = items
952    .into_iter()
953    .filter(|item| match item {
954      NodeData::Element { attributes, .. } => {
955        if let Some(attrs) = attributes {
956          !attrs.contains_key("_ignorable")
957        } else {
958          true
959        }
960      },
961      _ => true,
962    })
963    .collect();
964
965  if filtered.len() == 1 {
966    filtered.into_iter().next().unwrap()
967  } else {
968    NodeData::Element {
969      tag:        "m:mrow".to_string(),
970      attributes: None,
971      children:   filtered,
972    }
973  }
974}
975
976/// Parenthesize an expression with open/close delimiters.
977///
978/// Port of `pmml_parenthesize`.
979pub fn pmml_parenthesize(item: NodeData, open: Option<&str>, close: Option<&str>) -> NodeData {
980  if open.is_none() && close.is_none() {
981    return item;
982  }
983
984  let mut children = Vec::new();
985  if let Some(o) = open {
986    children.push(NodeData::Element {
987      tag:        "m:mo".to_string(),
988      attributes: Some(HashMap::from_iter([
989        ("fence".to_string(), "true".to_string()),
990        ("stretchy".to_string(), "true".to_string()),
991      ])),
992      children:   vec![NodeData::Text(o.to_string())],
993    });
994  }
995  children.push(item);
996  if let Some(c) = close {
997    children.push(NodeData::Element {
998      tag:        "m:mo".to_string(),
999      attributes: Some(HashMap::from_iter([
1000        ("fence".to_string(), "true".to_string()),
1001        ("stretchy".to_string(), "true".to_string()),
1002      ])),
1003      children:   vec![NodeData::Text(c.to_string())],
1004    });
1005  }
1006
1007  NodeData::Element {
1008    tag: "m:mrow".to_string(),
1009    attributes: None,
1010    children,
1011  }
1012}
1013
1014/// Punctuate a list of items with separators.
1015///
1016/// Port of `pmml_punctuate`.
1017pub fn pmml_punctuate(separators: &str, items: Vec<NodeData>) -> NodeData {
1018  if items.is_empty() {
1019    return NodeData::Element {
1020      tag:        "m:mrow".to_string(),
1021      attributes: None,
1022      children:   vec![],
1023    };
1024  }
1025
1026  let mut result = Vec::new();
1027  let mut sep_chars: Vec<char> = separators.chars().collect();
1028  let last_sep = if sep_chars.is_empty() {
1029    ','
1030  } else {
1031    *sep_chars.last().unwrap()
1032  };
1033
1034  let mut iter = items.into_iter();
1035  result.push(iter.next().unwrap());
1036
1037  for item in iter {
1038    let sep = if sep_chars.is_empty() {
1039      last_sep
1040    } else {
1041      sep_chars.remove(0)
1042    };
1043    result.push(NodeData::Element {
1044      tag:        "m:mo".to_string(),
1045      attributes: Some(HashMap::from_iter([(
1046        "separator".to_string(),
1047        "true".to_string(),
1048      )])),
1049      children:   vec![NodeData::Text(sep.to_string())],
1050    });
1051    result.push(item);
1052  }
1053
1054  pmml_row(result)
1055}
1056
1057/// Convert a text node within XMText to Presentation MathML.
1058///
1059/// Port of `pmml_text_aux` (`MathML.pm` L1029-1077). `attrs` is Perl's `%attr`:
1060/// the presentation attributes accumulated from the enclosing `ltx:*` elements,
1061/// which `stylize_text_content` then puts on the `m:mtext`. The top-level caller
1062/// (the `ltx:XMText` arm of `pmml_internal`, Perl L494-498) passes an empty set,
1063/// exactly as Perl's bare `pmml_text_aux($_)` does.
1064pub fn pmml_text_aux(doc: &PostDocument, node: &Node, attrs: &TextAttrs) -> Vec<NodeData> {
1065  use libxml::tree::NodeType;
1066
1067  match node.get_type() {
1068    Some(NodeType::TextNode) => {
1069      // Perl stylizes the RAW content first (L1034) and only then rewrites the
1070      // whitespace (L1035), so an empty text node reaches the failsafe as empty.
1071      let (text, attributes) = stylize_text_content(None, attrs, &node.get_content());
1072      // Perl L1035: `s/^\s+/NBSP/` then `s/\s+$/NBSP/` — a leading or trailing
1073      // whitespace RUN is REPLACED by a single NBSP, not trimmed away. (This arm
1074      // used to `trim_start()` unconditionally and only then test the
1075      // already-trimmed string with `starts_with(is_whitespace)`, which can never
1076      // be true — so leading space was silently dropped instead of becoming the
1077      // NBSP that keeps `$a \text{ and } b$` from closing up.)
1078      let head_trimmed = text.trim_start();
1079      let mut text = if head_trimmed.len() == text.len() {
1080        text.clone()
1081      } else {
1082        format!("\u{00A0}{head_trimmed}")
1083      };
1084      let tail_trimmed = text.trim_end();
1085      if tail_trimmed.len() != text.len() {
1086        text = format!("{tail_trimmed}\u{00A0}");
1087      }
1088      vec![NodeData::Element {
1089        tag:        "m:mtext".to_string(),
1090        attributes: (!attributes.is_empty()).then_some(attributes),
1091        children:   vec![NodeData::Text(text)],
1092      }]
1093    },
1094    Some(NodeType::ElementNode) => {
1095      // Perl L1041-1045: the element's own font/fontsize/color/backgroundcolor/
1096      // opacity join the inherited set for everything below it.
1097      let attrs = attrs.overlay(node);
1098      let tag = doc.get_qname(node).unwrap_or_default();
1099      match tag.as_str() {
1100        "ltx:Math" => {
1101          // Nested math: convert XMath if present
1102          match doc.findnode_at("ltx:XMath", node) {
1103            Some(xmath) => {
1104              vec![presentation::convert_to_pmml(doc, &xmath)]
1105            },
1106            // Perl L1051-1052: no XMath left means this Math was already
1107            // converted on an earlier pass — hand back the existing
1108            // `m:math`'s children rather than dropping the formula. Perl finds
1109            // it with `findnode('m:math', …)`, a DIRECT child; we scan the
1110            // children by namespace URI because the `m` prefix is not in the
1111            // document's XPath context at this point — this very processor is
1112            // what introduces MathML, so `m:` would fail to resolve and the
1113            // formula would go on being dropped silently.
1114            _ => match element_child_named(node, MML_URI, "math") {
1115              Some(mml) => {
1116                let mut out = Vec::new();
1117                let mut current = mml.get_first_child();
1118                while let Some(ref c) = current {
1119                  if let Some(nd) = rebuild_text_subtree_with_doc(c, true, Some(doc)) {
1120                    out.push(nd);
1121                  }
1122                  current = c.get_next_sibling();
1123                }
1124                out
1125              },
1126              _ => vec![],
1127            },
1128          }
1129        },
1130        // Perl L1057-1059: an `ltx:text` is transparent — recurse and let the
1131        // attributes ride down — but ONLY when it is not framed. `m:mtext`
1132        // cannot express a frame, so a framed one falls through to the
1133        // raw-markup arm below, where the XSLT can still render the box.
1134        "ltx:text" if !node.has_attribute("framed") && !node.has_attribute("framecolor") => {
1135          // Recurse on children
1136          let mut results = Vec::new();
1137          if let Some(child) = node.get_first_child() {
1138            let mut current = Some(child);
1139            while let Some(ref c) = current {
1140              results.extend(pmml_text_aux(doc, c, &attrs));
1141              current = c.get_next_sibling();
1142            }
1143          }
1144          vec![presentation::maybe_resize(doc, node, pmml_row(results))]
1145        },
1146        "ltx:picture" => {
1147          // Picture in text: wrap in mtext. Eagerly materialize the picture
1148          // subtree into owned NodeData so the result is not tied to the
1149          // source node's libxml2 lifetime. Perl: MathProcessor.pm
1150          // convertXMTextContent (Post.pm L456-489). A lazy
1151          // `NodeData::XmlNode(node.clone())` here SIGSEGVs in
1152          // `add_xml_node` once the parent XMath is unlinked (its children
1153          // are stripped into a detached document fragment and later
1154          // accesses via the stale rust-libxml wrapper dereference freed
1155          // memory — reproducible on 0710.1208 / 1110.2158 / 1605.07431).
1156          // Perl L1061-1063 passes no %attr through this arm — the picture is
1157          // its own rendering, so the surrounding math font/color does not
1158          // restyle it.
1159          vec![NodeData::Element {
1160            tag:        "m:mtext".to_string(),
1161            attributes: None,
1162            children:   convert_xm_text_content(doc, node, true),
1163          }]
1164        },
1165        _ => {
1166          // Unknown element (e.g. ltx:ref, ltx:bibref, ltx:inline-block,
1167          // …): preserve the raw subtree inside the mtext so the XSLT
1168          // can transform it (ltx:ref → HTML <a>, etc.). Perl
1169          // `pmml_text_aux` (MathML.pm L1063-1073) clones the whole
1170          // node into the returned mtext; we eagerly materialize an
1171          // owned subtree, threading `doc` through so URI→prefix
1172          // resolution recovers the canonical `ltx:` prefix on
1173          // default-namespace elements.
1174          //
1175          // Perl L1067-1072 stylizes this `m:mtext` from the accumulated %attr
1176          // and — when the raw subtree still holds an `ltx:Math` — warns
1177          // `unexpected:nested-math` and leaves the content-MathML unconverted,
1178          // which renders operator-first (garbled) in the browser. We instead
1179          // convert any nested `ltx:Math` in `rebuild_text_subtree_with_doc`
1180          // below (to a self-contained inline `<m:math>` — see
1181          // `nested_ltx_math_to_inline_mathml`), so a `\parbox`/`\mbox`-with-math
1182          // in math renders correctly (arXiv html_feedback #6847). Surpass-Perl;
1183          // see OXIDIZED_DESIGN #101.
1184          // Perl `my ($ignore, %mmlattr) = …` — the raw subtree is carried over
1185          // verbatim below, so only the attributes are wanted here.
1186          let (_, attributes) = stylize_text_content(Some(node), &attrs, &node.get_content());
1187          let cloned = rebuild_text_subtree_with_doc(node, true, Some(doc))
1188            .unwrap_or_else(|| NodeData::Text("\u{00A0}".to_string()));
1189          vec![NodeData::Element {
1190            tag:        "m:mtext".to_string(),
1191            attributes: (!attributes.is_empty()).then_some(attributes),
1192            children:   vec![cloned],
1193          }]
1194        },
1195      }
1196    },
1197    _ => vec![],
1198  }
1199}
1200
1201/// Convert a nested `ltx:Math` — a `$...$` inside a text box (`\parbox`/`\mbox`/
1202/// `\text`) that itself sits in math — into a self-contained INLINE `<m:math>`
1203/// element, or `None` if the Math is empty.
1204///
1205/// Why a full `<m:math>` rather than the bare presentation `convert_to_pmml`
1206/// returns: this node lands inside the text box's HTML (`ltx:inline-block` /
1207/// `ltx:text` → `<span>`), and per HTML5's MathML text-integration-point rules a
1208/// bare `<mrow>` inside that HTML is parsed as HTML and renders as flat text —
1209/// not math (subscripts/superscripts/calligraphic lost). The `<math>` re-enters
1210/// MathML context. Nested math is always inline (a `$...$`), so `display=inline`;
1211/// `alttext`/`class` ride from the `ltx:Math`. The top-level pass gets the same
1212/// wrapper from `MathProcessor::outer_wrapper`; this is its nested analogue
1213/// (arXiv html_feedback #6847 / OXIDIZED_DESIGN #101).
1214fn nested_ltx_math_to_inline_mathml(doc: &PostDocument, math_node: &Node) -> Option<NodeData> {
1215  let inner = match doc.findnode_at("ltx:XMath", math_node) {
1216    Some(xmath) => presentation::convert_to_pmml(doc, &xmath),
1217    // No XMath left => already converted on an earlier pass; its `<m:math>` is
1218    // already a full element, so reuse it as-is.
1219    None => {
1220      return element_child_named(math_node, MML_URI, "math")
1221        .and_then(|mml| rebuild_text_subtree_with_doc(&mml, true, Some(doc)));
1222    },
1223  };
1224  let mut attrs: HashMap<String, String> = HashMap::default();
1225  attrs.insert("display".to_string(), "inline".to_string());
1226  if let Some(tex) = math_node.get_attribute("tex") {
1227    attrs.insert("alttext".to_string(), tex);
1228  }
1229  if let Some(class) = math_node.get_attribute("class") {
1230    attrs.insert("class".to_string(), class);
1231  }
1232  Some(NodeData::Element {
1233    tag:        "m:math".to_string(),
1234    attributes: Some(attrs),
1235    children:   vec![inner],
1236  })
1237}
1238
1239/// Eagerly materialize an XMText-or-picture subtree into owned NodeData.
1240///
1241/// Port of `LaTeXML::Post::MathProcessor::convertXMTextContent`
1242/// (Post.pm L456-489). Walks `node` recursively and rebuilds the subtree
1243/// as owned NodeData, so downstream consumers do not depend on the
1244/// source node's libxml2 lifetime. Internal `_*` attributes and stray
1245/// `xml:id` are dropped (Perl mirrors this); `fragid` would be remapped
1246/// to a fresh id in Perl but MathML::Presentation does not carry a
1247/// processor-level id suffix through this path, so we drop it too and
1248/// let the surrounding MathML ids govern.
1249///
1250/// When `convert_spaces` is true, leading/trailing whitespace on text
1251/// nodes is replaced with NBSP so the rendered MathML does not collapse
1252/// the space. A nested `ltx:Math` (a `$...$` inside a text box that itself
1253/// sits in math) is CONVERTED to presentation MathML by
1254/// `rebuild_text_subtree_with_doc` rather than cloned raw — see the
1255/// reentrancy note there (arXiv html_feedback #6847); Perl leaves it raw and
1256/// warns `unexpected:nested-math`, which renders operator-first (garbled).
1257pub fn convert_xm_text_content(
1258  doc: &PostDocument,
1259  node: &Node,
1260  convert_spaces: bool,
1261) -> Vec<NodeData> {
1262  node
1263    .get_child_nodes()
1264    .iter()
1265    .filter_map(|c| rebuild_text_subtree_with_doc(c, convert_spaces, Some(doc)))
1266    .collect()
1267}
1268
1269/// Rebuild a libxml2 subtree into owned `NodeData`, dropping internal
1270/// `_*`, `xml:id`, and `fragid` attributes. Shared between
1271/// `convert_xm_text_content` (Perl `convertXMTextContent`,
1272/// Post.pm L456-489) and `pmml_text_aux` for cases where Perl
1273/// calls `cloneNode($node, 'nest')` (MathML.pm L1073) — i.e. when an
1274/// unhandled element like `ltx:ref` appears inside a text-mode
1275/// fragment and must survive into the output so the XSLT can
1276/// transform it (e.g. `ltx:ref` → `<a>`).
1277pub fn rebuild_text_subtree(node: &Node, convert_spaces: bool) -> Option<NodeData> {
1278  rebuild_text_subtree_with_doc(node, convert_spaces, None)
1279}
1280
1281/// Same as `rebuild_text_subtree`, but consults the post-document's
1282/// namespace map to resolve elements whose source `xmlns="…"` carries
1283/// an empty prefix. `add_nodes` only emits elements whose tag is
1284/// `prefix:local`; without a prefix the element is dropped with a
1285/// `malformed:namespace` warning. libxml2 reports an empty
1286/// `Namespace::get_prefix()` for the default-namespace branch even
1287/// when the doc has a `ltx:` prefix declared elsewhere, so we
1288/// reverse-lookup the URI in `PostDocument::namespaces` to recover
1289/// the canonical prefix.
1290pub fn rebuild_text_subtree_with_doc(
1291  node: &Node,
1292  convert_spaces: bool,
1293  doc: Option<&PostDocument>,
1294) -> Option<NodeData> {
1295  use libxml::tree::NodeType;
1296  match node.get_type() {
1297    Some(NodeType::TextNode) => {
1298      let mut text = node.get_content();
1299      if convert_spaces {
1300        if text.starts_with(char::is_whitespace) {
1301          text = format!("\u{00A0}{}", text.trim_start());
1302        }
1303        if text.ends_with(char::is_whitespace) {
1304          text = format!("{}\u{00A0}", text.trim_end());
1305        }
1306      }
1307      Some(NodeData::Text(text))
1308    },
1309    Some(NodeType::ElementNode) => {
1310      // A nested `ltx:Math` — a `$...$` inside a \parbox/\mbox/inline-block that
1311      // itself sits in math. The top-level pass skipped it
1312      // (`//ltx:Math[not(ancestor::ltx:Math)]`), so cloning it verbatim leaks
1313      // unconverted `<ltx:XMath>` content-MathML into the HTML, which the browser
1314      // renders in operator-first document order (garbled, arXiv html_feedback
1315      // #6847 / arXiv:2608.05024). Convert it here instead. Needs `doc` for
1316      // URI→prefix + the ancestor style/font context; the doc-less
1317      // `rebuild_text_subtree` callers keep the verbatim clone (they never carry
1318      // nested math). See OXIDIZED_DESIGN #101.
1319      if let Some(d) = doc
1320        && d.get_qname(node).as_deref() == Some("ltx:Math")
1321        && let Some(mml) = nested_ltx_math_to_inline_mathml(d, node)
1322      {
1323        return Some(mml);
1324      }
1325      let tag = {
1326        let local = node.get_name();
1327        match node.get_namespace() {
1328          Some(ns) => {
1329            let prefix = ns.get_prefix();
1330            if !prefix.is_empty() {
1331              format!("{prefix}:{local}")
1332            } else {
1333              // Default-namespace element. add_nodes won't accept a
1334              // tag without prefix — reverse-resolve URI → prefix
1335              // via the post-document's namespace map.
1336              let uri = ns.get_href();
1337              match doc.and_then(|d| {
1338                d.namespaces
1339                  .iter()
1340                  .find(|(p, u)| !p.is_empty() && **u == uri)
1341                  .map(|(p, _)| p.clone())
1342              }) {
1343                Some(p) => format!("{p}:{local}"),
1344                None => local,
1345              }
1346            }
1347          },
1348          None => local,
1349        }
1350      };
1351      // Copy attributes, skipping internal `_*`, `xml:id`, and `fragid`.
1352      // Matches Perl convertXMTextContent (Post.pm L479-483); the
1353      // `fragid → xml:id` remap requires the MathProcessor's IDSuffix
1354      // which this helper does not receive — drop both here rather
1355      // than forge a wrong id. NOTE: get_attributes() reports xml:id
1356      // under its LOCAL name "id", so that spelling must be skipped
1357      // too — it used to leak through as a plain id= duplicate. The
1358      // namespace probe keeps a GENUINE plain `id` (the model grants
1359      // one to `ltx:bib-identifier`/`ltx:bib-review`, carrying a
1360      // DOI/ISSN) from being dropped along with it.
1361      let has_xml_id = node
1362        .get_attribute_ns("id", latexml_core::common::xml::XML_NS)
1363        .is_some();
1364      let mut attrs: HashMap<String, String> = HashMap::default();
1365      for (k, v) in node.get_attributes() {
1366        if k.starts_with('_') || k == "xml:id" || k == "fragid" || (k == "id" && has_xml_id) {
1367          continue;
1368        }
1369        attrs.insert(k, v);
1370      }
1371      let children: Vec<NodeData> = node
1372        .get_child_nodes()
1373        .iter()
1374        .filter_map(|c| rebuild_text_subtree_with_doc(c, convert_spaces, doc))
1375        .collect();
1376      Some(NodeData::Element {
1377        tag,
1378        attributes: if attrs.is_empty() { None } else { Some(attrs) },
1379        children,
1380      })
1381    },
1382    _ => None,
1383  }
1384}
1385
1386/// Unwrap an mrow if it has no attributes.
1387///
1388/// Port of `pmml_unrow`.
1389pub fn pmml_unrow(mml: NodeData) -> Vec<NodeData> {
1390  match mml {
1391    NodeData::Element {
1392      ref tag,
1393      ref attributes,
1394      ref children,
1395    } if tag == "m:mrow" && attributes.as_ref().map(|a| a.is_empty()).unwrap_or(true) => {
1396      children.clone()
1397    },
1398    _ => vec![mml],
1399  }
1400}
1401
1402#[cfg(test)]
1403mod tests {
1404  use super::*;
1405
1406  #[test]
1407  fn test_style_step() {
1408    assert_eq!(style_step("display"), "text");
1409    assert_eq!(style_step("text"), "script");
1410    assert_eq!(style_step("script"), "scriptscript");
1411    assert_eq!(style_step("scriptscript"), "scriptscript");
1412  }
1413
1414  #[test]
1415  fn test_pmml_tag_for_role() {
1416    assert_eq!(pmml_tag_for_role("NUMBER"), "m:mn");
1417    assert_eq!(pmml_tag_for_role("ID"), "m:mi");
1418    assert_eq!(pmml_tag_for_role("ADDOP"), "m:mo");
1419    assert_eq!(pmml_tag_for_role("FUNCTION"), "m:mi");
1420    assert_eq!(pmml_tag_for_role("SUMOP"), "m:mo");
1421  }
1422
1423  #[test]
1424  fn test_apply_handler_for_role() {
1425    assert_eq!(apply_handler_for_role("ADDOP"), ApplyHandler::Infix);
1426    assert_eq!(
1427      apply_handler_for_role("SUPERSCRIPTOP"),
1428      ApplyHandler::Script
1429    );
1430    assert_eq!(apply_handler_for_role("FRACOP"), ApplyHandler::Fraction);
1431    assert_eq!(
1432      apply_handler_for_role("OVERACCENT"),
1433      ApplyHandler::OverAccent
1434    );
1435    assert_eq!(apply_handler_for_role("SUMOP"), ApplyHandler::Summation);
1436    assert_eq!(apply_handler_for_role("FUNCTION"), ApplyHandler::Generic);
1437  }
1438
1439  #[test]
1440  fn test_is_bigop_role() {
1441    assert!(is_bigop_role("SUMOP"));
1442    assert!(is_bigop_role("INTOP"));
1443    assert!(!is_bigop_role("ADDOP"));
1444    assert!(!is_bigop_role("ID"));
1445  }
1446
1447  #[test]
1448  fn test_encoding_for_mimetype() {
1449    assert_eq!(
1450      encoding_for_mimetype("application/mathml-presentation+xml"),
1451      "MathML-Presentation"
1452    );
1453    assert_eq!(
1454      encoding_for_mimetype("application/mathml-content+xml"),
1455      "MathML-Content"
1456    );
1457    assert_eq!(encoding_for_mimetype("image/svg+xml"), "SVG1.1");
1458    assert_eq!(encoding_for_mimetype("text/plain"), "text/plain");
1459  }
1460
1461  #[test]
1462  fn test_pmml_row_single() {
1463    let items = vec![NodeData::Text("x".to_string())];
1464    let result = pmml_row(items);
1465    match result {
1466      NodeData::Text(s) => assert_eq!(s, "x"),
1467      _ => panic!("Expected Text, got Element"),
1468    }
1469  }
1470
1471  #[test]
1472  fn test_pmml_row_multiple() {
1473    let items = vec![
1474      NodeData::Text("x".to_string()),
1475      NodeData::Text("+".to_string()),
1476      NodeData::Text("y".to_string()),
1477    ];
1478    let result = pmml_row(items);
1479    match result {
1480      NodeData::Element { tag, children, .. } => {
1481        assert_eq!(tag, "m:mrow");
1482        assert_eq!(children.len(), 3);
1483      },
1484      _ => panic!("Expected Element"),
1485    }
1486  }
1487
1488  #[test]
1489  fn test_pmml_parenthesize() {
1490    let item = NodeData::Text("x".to_string());
1491    let result = pmml_parenthesize(item.clone(), Some("("), Some(")"));
1492    match result {
1493      NodeData::Element { tag, children, .. } => {
1494        assert_eq!(tag, "m:mrow");
1495        assert_eq!(children.len(), 3); // open, item, close
1496      },
1497      _ => panic!("Expected mrow"),
1498    }
1499
1500    // No parens → pass through
1501    let result2 = pmml_parenthesize(item, None, None);
1502    match result2 {
1503      NodeData::Text(s) => assert_eq!(s, "x"),
1504      _ => panic!("Expected passthrough"),
1505    }
1506  }
1507}