Skip to main content

latexml_post/mathml/
presentation.rs

1//! Presentation MathML rendering rules.
2//!
3//! Port of `LaTeXML::Post::MathML::Presentation` (146 lines) +
4//! the presentation portion of `LaTeXML::Post::MathML` (main module, ~1000 lines).
5//! Converts XMath nodes to Presentation MathML elements (mi, mo, mn, mrow, etc.).
6//!
7//! Key concepts:
8//! - `pmml(node)` dispatches conversion by tag (XMTok, XMApp, XMDual, etc.)
9//! - `stylizeContent(item, tag)` determines text, mathvariant, size, spacing
10//! - Scripts (sub/sup/under/over) handle pre/mid/post positioning
11//! - Style context tracks display/text/script/scriptscript levels
12
13use std::cell::Cell;
14
15use latexml_core::common::xml::name_is;
16use libxml::tree::Node;
17use rustc_hash::FxHashMap as HashMap;
18
19use super::operator_dictionary;
20use crate::document::{NodeData, PostDocument, XMBranch, element_children, element_children_iter};
21
22// Thread-local flag for invisible times emission.
23// When false, U+2062 is replaced with U+200B (zero-width space).
24thread_local! {
25  static INVISIBLE_TIMES: Cell<bool> = const { Cell::new(true) };
26  /// Whether to remap styled alphanumerics into Unicode's Plane-1 Mathematical
27  /// Alphanumeric Symbols. Perl `$$MATHPROCESSOR{plane1}`, defaulted to 1 in
28  /// `preprocess` (L70) and negatable with `latexmlpost --noplane1`. When off, the
29  /// text stays ASCII and the style is carried by a `mathvariant` attribute
30  /// instead β€” which some renderers and screen readers handle far better than the
31  /// Plane-1 codepoints, whose font coverage is patchy.
32  static PLANE1: Cell<bool> = const { Cell::new(true) };
33  /// Perl `$$MATHPROCESSOR{hackplane1}` (`--hackplane1`): remap only the variants
34  /// in `plane1_hackable`, and to the SIMPLER variant it names. This exists
35  /// because the doubly-styled blocks (bold-script, bold-fraktur) are the worst
36  /// supported of all, so `\mathbf{\mathcal{E}}` is better served by the plain
37  /// script codepoint than by a bold-script one no font will have. Implies
38  /// `plane1` (Perl L71).
39  static HACK_PLANE1: Cell<bool> = const { Cell::new(false) };
40  /// Inherited style context (Perl `pmml_top` L278-285 binds
41  /// $LaTeXML::MathML::FONT/COLOR/BGCOLOR/OPACITY from the XMath node's
42  /// ancestor chain; `pmml` L332-335 locally rebinds them from each node on
43  /// the way down). A token missing its own attribute styles from context β€”
44  /// e.g. `{\color{red}$a+b$}` colors every token. (audit F8b; the SIZE/
45  /// DESIRED_SIZE half is deliberately NOT ported: our engine stamps
46  /// absolute fontsize on tokens, which the mathsize context gate already
47  /// compensates.)
48  static CTX_FONT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
49  /// The font of the text around the formula (Perl's `$LaTeXML::MathML::FONT`, MathML.pm:278), which an `XMText`'s
50  /// content is written against and its `m:mtext` falls back to; the tokens' own context is `CTX_FONT`, read inside
51  /// the formula only (`math_context_font`, OXIDIZED_DESIGN_DIVERGENCES #780).
52  static CTX_TEXTFONT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
53  static CTX_COLOR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
54  static CTX_BGCOLOR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
55  static CTX_OPACITY: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
56  /// Current math style context, tracking Perl's `$LaTeXML::MathML::STYLE` /
57  /// `$LaTeXML::MathML::SIZE`. Stepped down inside sub/superscripts (`pmml_scriptsize`)
58  /// and fraction parts (`pmml_smaller`); its `size_percent()` is the contextual size a
59  /// token's `fontsize` is compared against, so a token only emits an explicit
60  /// `mathsize` when it *differs* from what the surrounding script/fraction structure
61  /// already implies (Perl `stylizeContent` L777). Reset to `Display` at each
62  /// `convert_to_pmml` entry.
63  static CURRENT_STYLE: Cell<MathStyle> = const { Cell::new(MathStyle::Display) };
64}
65
66/// Set whether to emit invisible times (called by MathML processor before rendering).
67pub fn set_invisible_times(emit: bool) { INVISIBLE_TIMES.with(|f| f.set(emit)); }
68
69fn get_invisible_times() -> bool { INVISIBLE_TIMES.with(|f| f.get()) }
70
71/// Set the Plane-1 remapping mode (called by the MathML processor before
72/// rendering). Mirrors Perl `preprocess` L69-71: `hackplane1` implies `plane1`.
73pub fn set_plane1(plane1: bool, hack_plane1: bool) {
74  PLANE1.with(|f| f.set(plane1 || hack_plane1));
75  HACK_PLANE1.with(|f| f.set(hack_plane1));
76}
77
78/// Perl `%plane1hackable` (L659-664) β€” the mathvariants worth remapping under
79/// `--hackplane1`, each mapped to the simpler variant to remap it AS. A variant
80/// absent from this table is left un-remapped in hack mode, which is the whole
81/// point: `bold` stays `mathvariant="bold"` on ASCII rather than becoming 𝐃.
82fn plane1_hackable(variant: &str) -> Option<&'static str> {
83  match variant {
84    "script" | "bold-script" => Some("script"),
85    "fraktur" | "bold-fraktur" => Some("fraktur"),
86    "double-struck" => Some("double-struck"),
87    _ => None,
88  }
89}
90
91/// The variant to actually remap with, or `None` to skip remapping entirely.
92///
93/// Port of Perl `stylizeContent` L734-736:
94/// ```text
95/// my $u_variant = $variant
96///   && ($plane1hack ? $plane1hackable{$variant}
97///   : ($plane1 ? $variant : undef));
98/// ```
99fn plane1_target_variant(variant: &str) -> Option<&str> {
100  if HACK_PLANE1.with(|f| f.get()) {
101    plane1_hackable(variant)
102  } else if PLANE1.with(|f| f.get()) {
103    Some(variant)
104  } else {
105    None
106  }
107}
108
109/// The contextual font size (e.g. "100%", "70%", "50%") implied by the current math style.
110/// A token whose own `fontsize` equals this needs no explicit `mathsize` attribute.
111fn current_context_size() -> &'static str { CURRENT_STYLE.with(|s| s.get().size_percent()) }
112
113/// Math style levels.
114#[derive(Debug, Clone, Copy, PartialEq)]
115pub enum MathStyle {
116  Display,
117  Text,
118  Script,
119  ScriptScript,
120}
121
122impl MathStyle {
123  /// Step down one level (for fractions, etc.).
124  pub fn step_down(self) -> Self {
125    match self {
126      MathStyle::Display => MathStyle::Text,
127      MathStyle::Text => MathStyle::Script,
128      MathStyle::Script => MathStyle::ScriptScript,
129      MathStyle::ScriptScript => MathStyle::ScriptScript,
130    }
131  }
132
133  /// Step to script size (for sub/superscripts).
134  pub fn script_step(self) -> Self {
135    match self {
136      MathStyle::Display | MathStyle::Text => MathStyle::Script,
137      MathStyle::Script => MathStyle::ScriptScript,
138      MathStyle::ScriptScript => MathStyle::ScriptScript,
139    }
140  }
141
142  /// CSS-style size percentage.
143  pub fn size_percent(self) -> &'static str {
144    match self {
145      MathStyle::Display | MathStyle::Text => "100%",
146      MathStyle::Script => "70%",
147      MathStyle::ScriptScript => "50%",
148    }
149  }
150
151  /// Parse a source `mathstyle` attribute (Perl gates on `$stylestep{$style}`,
152  /// so only the four canonical names count).
153  pub fn from_attr(s: &str) -> Option<Self> {
154    match s {
155      "display" => Some(MathStyle::Display),
156      "text" => Some(MathStyle::Text),
157      "script" => Some(MathStyle::Script),
158      "scriptscript" => Some(MathStyle::ScriptScript),
159      _ => None,
160    }
161  }
162}
163
164/// m:mstyle attributes for a mathstyle transition.
165///
166/// Port of Perl `%stylemap` (`needs`=true: something below cares about
167/// displaystyle) and `%stylemap2` (`needs`=false: only a fontsize context is
168/// required), MathML.pm L240-268. Same-style transitions yield nothing.
169fn stylemap_attrs(
170  ostyle: MathStyle,
171  nstyle: MathStyle,
172  needs: bool,
173) -> &'static [(&'static str, &'static str)] {
174  use MathStyle::*;
175  match (ostyle, nstyle, needs) {
176    (Display, Text, true) => &[("displaystyle", "false")],
177    (Display, Script, true) => &[("displaystyle", "false"), ("scriptlevel", "+1")],
178    (Display, ScriptScript, true) => &[("displaystyle", "false"), ("scriptlevel", "+2")],
179    (Text, Display, true) => &[("displaystyle", "true")],
180    (Display, Script, false) | (Text, Script, _) => &[("scriptlevel", "+1")],
181    (Display, ScriptScript, false) | (Text, ScriptScript, _) => &[("scriptlevel", "+2")],
182    (Script, Display, _) => &[("displaystyle", "true"), ("scriptlevel", "-1")],
183    (Script, Text, _) => &[("scriptlevel", "-1")],
184    (Script, ScriptScript, _) => &[("scriptlevel", "+1")],
185    (ScriptScript, Display, _) => &[("displaystyle", "true"), ("scriptlevel", "-2")],
186    (ScriptScript, Text, _) => &[("scriptlevel", "-2")],
187    (ScriptScript, Script, _) => &[("scriptlevel", "-1")],
188    _ => &[],
189  }
190}
191
192/// Does this subtree contain something whose rendering depends on
193/// displaystyle? Port of Perl `needsMathstyle` (MathML.pm L512-523):
194/// m:mfrac β†’ yes; `_largeop` β†’ yes; an m:mstyle that already pins
195/// displaystyle shields its subtree.
196fn needs_mathstyle(node: &NodeData) -> bool {
197  if let NodeData::Element { tag, attributes, children } = node {
198    if tag == "m:mfrac" {
199      return true;
200    }
201    if let Some(attrs) = attributes {
202      if attrs.contains_key("_largeop") {
203        return true;
204      }
205      if tag == "m:mstyle" && attrs.contains_key("displaystyle") {
206        return false;
207      }
208    }
209    return children.iter().any(needs_mathstyle);
210  }
211  false
212}
213
214/// Wrap `result` in m:mstyle for an ostyle→nstyle transition, when the
215/// transition table says the wrap carries information (Perl MathML.pm
216/// L421-427 / L487-491).
217fn maybe_style_wrap(result: NodeData, ostyle: MathStyle, nstyle: Option<MathStyle>) -> NodeData {
218  let Some(nstyle) = nstyle else { return result };
219  let style_attrs = stylemap_attrs(ostyle, nstyle, needs_mathstyle(&result));
220  if style_attrs.is_empty() {
221    return result;
222  }
223  NodeData::Element {
224    tag:        "m:mstyle".to_string(),
225    attributes: Some(HashMap::from_iter(
226      style_attrs
227        .iter()
228        .map(|(k, v)| (k.to_string(), v.to_string())),
229    )),
230    children:   vec![result],
231  }
232}
233
234/// Wrap `result` in m:mpadded / frame it, when the source node (or its
235/// containing XMDual) carries sizing attributes.
236///
237/// Port of Perl `pmml_maybe_resize` (MathML.pm L525-575): stretchy-ARROW
238/// width β†’ m:mover + m:mspace; width/height/depth/xoffset/yoffset β†’
239/// m:mpadded (reusing an existing mpadded/mrow); framed/framecolor β†’
240/// ltx_framed_* class + border-color style.
241fn pmml_maybe_resize(doc: &PostDocument, node: &Node, result: NodeData) -> NodeData {
242  // Relevant attributes MAY sit on a containing XMDual (Perl L529-531).
243  let parent = node.get_parent().filter(|p| doc.is_qname(p, "ltx:XMDual"));
244  let getattr = |name: &str| {
245    node
246      .get_attribute(name)
247      .or_else(|| parent.as_ref().and_then(|p| p.get_attribute(name)))
248  };
249  let width = getattr("width");
250  let height = getattr("height");
251  let depth = getattr("depth");
252  let xoff = getattr("xoffset");
253  let yoff = getattr("yoffset");
254  let role = getattr("role");
255  let class = getattr("class");
256
257  let mut result = result;
258  if let Some(ref w) = width
259    && role.as_deref() == Some("ARROW")
260    && class.as_deref().is_some_and(|c| {
261      c.split_ascii_whitespace()
262        .any(|w| w == "ltx_horizontally_stretchy")
263    })
264  {
265    // Special-case hack for stretchy arrows with a specified width;
266    // stretchiness (currently) only has effect within munder/mover (Perl L543-545).
267    result = NodeData::Element {
268      tag:        "m:mover".to_string(),
269      attributes: None,
270      children:   vec![result, NodeData::Element {
271        tag:        "m:mspace".to_string(),
272        attributes: Some(HashMap::from_iter([("width".to_string(), w.clone())])),
273        children:   vec![],
274      }],
275    };
276  } else if width.is_some()
277    || height.is_some()
278    || depth.is_some()
279    || xoff.is_some()
280    || yoff.is_some()
281  {
282    // Reuse an m:mpadded, convert an m:mrow, else wrap (Perl L547-552).
283    let needs_wrap = !matches!(&result,
284      NodeData::Element { tag, .. } if tag == "m:mpadded" || tag == "m:mrow");
285    if needs_wrap {
286      result = NodeData::Element {
287        tag:        "m:mpadded".to_string(),
288        attributes: None,
289        children:   vec![result],
290      };
291    }
292    if let NodeData::Element { tag, attributes, .. } = &mut result {
293      if tag == "m:mrow" {
294        *tag = "m:mpadded".to_string();
295      }
296      let attrs = attributes.get_or_insert_with(Default::default);
297      for (key, val) in [
298        ("width", width),
299        ("height", height),
300        ("depth", depth),
301        ("lspace", xoff),
302        ("voffset", yoff),
303      ] {
304        if let Some(v) = val {
305          attrs.insert(key.to_string(), v);
306        }
307      }
308    }
309  }
310
311  // framed/framecolor come from the node itself only (Perl L566-574).
312  if let Some(frame) = node.get_attribute("framed")
313    && let NodeData::Element { attributes, .. } = &mut result
314  {
315    let attrs = attributes.get_or_insert_with(Default::default);
316    let frame_class = format!("ltx_framed_{frame}");
317    let merged = match attrs.get("class") {
318      Some(c) if !c.is_empty() => format!("{c} {frame_class}"),
319      _ => frame_class,
320    };
321    attrs.insert("class".to_string(), merged);
322    if let Some(color) = node.get_attribute("framecolor") {
323      let style = format!("border-color: {color}");
324      let merged = match attrs.get("style") {
325        Some(s) if !s.is_empty() => format!("{s}; {style}"),
326        _ => style,
327      };
328      attrs.insert("style".to_string(), merged);
329    }
330  }
331  result
332}
333
334fn ctx_get(
335  cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
336) -> Option<String> {
337  cell.with(|c| c.borrow().clone())
338}
339
340/// Rebind a context cell to the node's attribute (if present) for a scope;
341/// returns the saved value for restore. Perl's `local $CTX = attr || $CTX`.
342fn ctx_rebind(
343  cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
344  attr: Option<String>,
345) -> Option<String> {
346  // Perl-falsy: an empty attribute value keeps the inherited context.
347  let attr = attr.filter(|v| !v.is_empty());
348  cell.with(|c| {
349    let old = c.borrow().clone();
350    if attr.is_some() {
351      *c.borrow_mut() = attr;
352    }
353    old
354  })
355}
356
357fn ctx_set(
358  cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
359  val: Option<String>,
360) {
361  cell.with(|c| *c.borrow_mut() = val);
362}
363
364/// Embellishing roles (scripts/accents applied to operators).
365fn is_embellishing_role(role: &str) -> bool {
366  matches!(
367    role,
368    "SUPERSCRIPTOP" | "SUBSCRIPTOP" | "OVERACCENT" | "UNDERACCENT" | "MODIFIER" | "MODIFIEROP"
369  )
370}
371
372/// Default token content for invisible operators β€” Perl's
373/// `%default_token_content`, consulted by `stylizeContent`'s empty-item
374/// failsafe. Shared with the `m:mtext` half of that function in the parent
375/// module, so the two arms cannot drift.
376pub(super) fn default_token_content(role: &str) -> Option<&'static str> {
377  match role {
378    "MULOP" => Some("\u{2062}"), // INVISIBLE TIMES
379    "ADDOP" => Some("\u{2064}"), // INVISIBLE PLUS
380    "PUNCT" => Some("\u{2063}"), // INVISIBLE SEPARATOR
381    _ => None,
382  }
383}
384
385/// Get the operator role, following embellished operators.
386fn get_operator_role(doc: &PostDocument, node: &Node) -> Option<String> {
387  if let Some(role) = node.get_attribute("role") {
388    return Some(role);
389  }
390  if doc.is_qname(node, "ltx:XMApp") {
391    let children = element_children(node);
392    if children.len() >= 2 {
393      let op_role = children[0].get_attribute("role").unwrap_or_default();
394      if is_embellishing_role(&op_role) {
395        return get_operator_role(doc, &children[1]);
396      }
397    }
398  }
399  None
400}
401
402/// Convert an XMath tree to Presentation MathML.
403///
404/// Entry point for Presentation MathML conversion.
405/// Port of `MathML::Presentation::convertNode` + `pmml_top`.
406pub fn convert_to_pmml(doc: &PostDocument, xmath: &Node) -> NodeData {
407  // Reentrancy-safe: `convert_to_pmml` can run WHILE an outer conversion is in
408  // progress β€” a nested `ltx:Math` inside a \parbox/\mbox/inline-block that
409  // itself sits in math (arXiv html_feedback #6847). This function overwrites
410  // the inherited style/context thread-locals below, so snapshot them on entry
411  // and restore on exit; otherwise the outer conversion resumes with the
412  // nested math's style/font and mangles its remaining tokens.
413  let saved_style = CURRENT_STYLE.with(|s| s.get());
414  let saved_font = CTX_FONT.with(|c| c.borrow().clone());
415  let saved_text_font = CTX_TEXTFONT.with(|c| c.borrow().clone());
416  let saved_color = CTX_COLOR.with(|c| c.borrow().clone());
417  let saved_bgcolor = CTX_BGCOLOR.with(|c| c.borrow().clone());
418  let saved_opacity = CTX_OPACITY.with(|c| c.borrow().clone());
419
420  // Perl Presentation.pm `convertNode` L20-21 + `pmml_top`: display-mode math
421  // starts in displaystyle, everything else in textstyle. Both are 100% size,
422  // but the mathstyle transitions (m:mstyle wraps for \tfrac/\dfrac/
423  // \displaystyle, audit F7) key off this baseline.
424  let mode_is_display = xmath
425    .get_parent()
426    .and_then(|p| p.get_attribute("mode"))
427    .is_some_and(|m| m == "display");
428  CURRENT_STYLE.with(|s| {
429    s.set(if mode_is_display {
430      MathStyle::Display
431    } else {
432      MathStyle::Text
433    })
434  });
435  // Perl pmml_top L278-285: bind the inherited style context from the XMath
436  // node's ancestor chain, so tokens without their own attributes pick up
437  // the surrounding color ({\color{red}$a+b$}); the font from inside the
438  // formula only (`math_context_font`, OXIDIZED_DESIGN_DIVERGENCES #780).
439  ctx_set(&CTX_FONT, super::math_context_font(xmath));
440  ctx_set(
441    &CTX_TEXTFONT,
442    super::find_inherited_attribute(doc, xmath, "font"),
443  );
444  ctx_set(
445    &CTX_COLOR,
446    super::find_inherited_attribute(doc, xmath, "color"),
447  );
448  ctx_set(
449    &CTX_BGCOLOR,
450    super::find_inherited_attribute(doc, xmath, "backgroundcolor"),
451  );
452  ctx_set(
453    &CTX_OPACITY,
454    super::find_inherited_attribute(doc, xmath, "opacity"),
455  );
456  let children = element_children(xmath);
457  let results: Vec<NodeData> = children.iter().map(|c| pmml(doc, c)).collect();
458  let mut result = if results.len() == 1 {
459    results.into_iter().next().unwrap()
460  } else {
461    pmml_row(results)
462  };
463  fill_empty_operands(&mut result);
464  // Adjust spacing to match TeX rules (Perl's adjust_spacing)
465  adjust_spacing(&mut result);
466  // Clean up internal _role/_lspace/_rspace before serialization
467  clean_internal_attrs(&mut result);
468
469  // Restore the caller's inherited context (see the reentrancy note above).
470  CURRENT_STYLE.with(|s| s.set(saved_style));
471  ctx_set(&CTX_FONT, saved_font);
472  ctx_set(&CTX_TEXTFONT, saved_text_font);
473  ctx_set(&CTX_COLOR, saved_color);
474  ctx_set(&CTX_BGCOLOR, saved_bgcolor);
475  ctx_set(&CTX_OPACITY, saved_opacity);
476  result
477}
478
479/// Presentation conversion of a node for use as ci CONTENT by the content
480/// side (Perl `cmml_decoratedSymbol` L1403 calls pmml($item)).
481pub(super) fn pmml_for_ci(doc: &PostDocument, node: &Node) -> NodeData { pmml(doc, node) }
482
483/// Bind the top-level conversion context for the CONTENT pipeline.
484///
485/// Port of Perl `cmml_top` (MathML.pm L1290-1300): content conversion runs
486/// under STYLE='text' with the same inherited FONT/COLOR/BGCOLOR/OPACITY
487/// bindings as `pmml_top` β€” the pmml subtrees embedded in content (ci
488/// interiors via `cmml_decoratedSymbol`) and `stylize_ci_content`'s font
489/// fallback depend on them. Without this the content path ran at whatever
490/// the previous conversion left (audit should-fix 11).
491pub(super) fn bind_cmml_top_context(doc: &PostDocument, xmath: &Node) {
492  CURRENT_STYLE.with(|s| s.set(MathStyle::Text));
493  ctx_set(&CTX_FONT, super::math_context_font(xmath));
494  ctx_set(
495    &CTX_TEXTFONT,
496    super::find_inherited_attribute(doc, xmath, "font"),
497  );
498  ctx_set(
499    &CTX_COLOR,
500    super::find_inherited_attribute(doc, xmath, "color"),
501  );
502  ctx_set(
503    &CTX_BGCOLOR,
504    super::find_inherited_attribute(doc, xmath, "backgroundcolor"),
505  );
506  ctx_set(
507    &CTX_OPACITY,
508    super::find_inherited_attribute(doc, xmath, "opacity"),
509  );
510}
511
512/// The inherited font context, for the content side's ci stylization
513/// (Perl stylizeContent's `|| $LaTeXML::MathML::FONT` fallback).
514pub(super) fn ctx_font() -> Option<String> { ctx_get(&CTX_FONT) }
515
516/// The text font around the formula, for an `XMText`'s `m:mtext` (Perl stylizeContent's `|| $LaTeXML::MathML::FONT`).
517pub(super) fn ctx_text_font() -> Option<String> { ctx_get(&CTX_TEXTFONT) }
518
519/// The inherited color context (Perl `|| $LaTeXML::MathML::COLOR`).
520pub(super) fn ctx_color() -> Option<String> { ctx_get(&CTX_COLOR) }
521
522/// The inherited background-color context (Perl `|| $LaTeXML::MathML::BGCOLOR`).
523pub(super) fn ctx_bgcolor() -> Option<String> { ctx_get(&CTX_BGCOLOR) }
524
525/// The inherited opacity context (Perl `|| $LaTeXML::MathML::OPACITY`).
526pub(super) fn ctx_opacity() -> Option<String> { ctx_get(&CTX_OPACITY) }
527
528/// The current style's nominal size, as a percentage string β€” Perl's
529/// `$LaTeXML::MathML::SIZE || 'text'` comparand in `stylizeContent` L779-781.
530pub(super) fn context_size() -> &'static str { current_context_size() }
531
532/// `resolve_token_size`, for the `m:mtext` arm of `stylizeContent`.
533pub(super) fn resolve_size(s: String) -> String { resolve_token_size(s) }
534
535/// `pmml_maybe_resize`, for the `ltx:text` arm of `pmml_text_aux` (Perl L1059).
536pub(super) fn maybe_resize(doc: &PostDocument, node: &Node, result: NodeData) -> NodeData {
537  pmml_maybe_resize(doc, node, result)
538}
539
540/// Core dispatch: convert a single XMath node to Presentation MathML.
541///
542/// Port of `pmml` + `pmml_internal`.
543fn pmml(doc: &PostDocument, node: &Node) -> NodeData {
544  // Perl L332-335: rebind the color/background/opacity context from this
545  // node for the subtree, so styles inherit downward.
546  let saved_color = ctx_rebind(&CTX_COLOR, node.get_attribute("color"));
547  let saved_bg = ctx_rebind(&CTX_BGCOLOR, node.get_attribute("backgroundcolor"));
548  let saved_op = ctx_rebind(&CTX_OPACITY, node.get_attribute("opacity"));
549  let mut result = pmml_inner(doc, node);
550  ctx_set(&CTX_COLOR, saved_color);
551  ctx_set(&CTX_BGCOLOR, saved_bg);
552  ctx_set(&CTX_OPACITY, saved_op);
553  // Perl MathML.pm L339-341: wrap in m:menclose if the source node carries an
554  // `enclose` attribute (e.g. \boxed puts enclose="box" on the whole XMApp).
555  if let Some(enclose) = node.get_attribute("enclose").filter(|e| !e.is_empty()) {
556    let mut attrs = HashMap::default();
557    attrs.insert("notation".to_string(), enclose);
558    result = NodeData::Element {
559      tag:        "m:menclose".to_string(),
560      attributes: Some(attrs),
561      children:   vec![result],
562    };
563  }
564  // Port of Perl MathML.pm L344-348: attach author spacing (lpadding/rpadding,
565  // e.g. from `~` ties or collapsed XMHints β€” `{\rm number~of~…}`) as the
566  // internal `_lpadding`/`_rpadding` attributes the space_walk consumes.
567  // Perl's `_getspace($refr, $node, …)` SUMS the referring XMRef's padding
568  // with the target's; here the XMRef branch of `pmml_inner` recurses through
569  // this wrapper for the target, and the XMRef's own padding is then added on
570  // top β€” same sum. Without this attachment the spacewalk sees zero author
571  // padding and `~`-separated words render jammed together (witness
572  // astro-ph0001001 S9.Ex4.m1). Same recursion argument covers enclose /
573  // class / _role below, with refr-preference falling out of the outer level
574  // overwriting (_role) or appending (class) the inner one; sole corner
575  // divergence: an XMRef AND its target both carrying `enclose` would nest
576  // two m:menclose where Perl picks the XMRef's one.
577  if doc.is_qname(node, "ltx:XMRef") {
578    // XMRef level: SUM the referring node's padding onto the target's
579    // (Perl `_getspace` refr+node).
580    add_source_padding(node, &mut result);
581  } else {
582    // Ordinary level: the node's padding ASSIGNS (an XMDual over a padded
583    // presentation child must not double-count β€” Perl overwrites).
584    attach_source_padding(node, &mut result);
585  }
586  // Perl L350-352: merge the source node's class onto the result. A stand-in's (OD #1249) goes on the token that
587  // holds its twin instead, never on a wrapper (`\boxed`'s menclose, `\mathrlap`'s mpadded), which keeps its own.
588  if let Some(cl) = node.get_attribute("class").filter(|cl| !cl.is_empty()) {
589    let standin = cl.split_whitespace().any(|c| c == "ltx_standin");
590    match standin.then(|| standin_token(&mut result)).flatten() {
591      Some(token) => merge_class(token, cl),
592      None => merge_class(&mut result, cl),
593    }
594  }
595  if let NodeData::Element { ref mut attributes, .. } = result {
596    // Perl L354-355: record the source role so the spacewalk can atom-type
597    // composite results (XMApp/XMDual with role=RELOP etc., not just tokens).
598    if let Some(role) = node.get_attribute("role") {
599      let attrs = attributes.get_or_insert_with(Default::default);
600      attrs.insert("_role".to_string(), role);
601    }
602  }
603  result
604}
605
606/// Perl MathML.pm L350-352: `class` joined onto an element result's own.
607fn merge_class(result: &mut NodeData, cl: String) {
608  if let NodeData::Element { attributes, .. } = result {
609    let attrs = attributes.get_or_insert_with(Default::default);
610    match attrs.get("class") {
611      Some(ocl) if !ocl.is_empty() && *ocl != cl => {
612        let merged = format!("{ocl} {cl}");
613        attrs.insert("class".to_string(), merged);
614      },
615      _ => {
616        attrs.insert("class".to_string(), cl);
617      },
618    }
619  }
620}
621
622const TOKEN_TAGS: [&str; 4] = ["m:mtext", "m:mi", "m:mn", "m:mo"];
623
624fn is_token(data: &NodeData) -> bool {
625  matches!(data, NodeData::Element { tag, .. } if TOKEN_TAGS.contains(&tag.as_str()))
626}
627
628/// The one token inside a wrapper result, which holds a stand-in's twin; `None` when the result is itself a token
629/// or holds other than exactly one.
630fn standin_token(result: &mut NodeData) -> Option<&mut NodeData> {
631  fn count(data: &NodeData) -> usize {
632    match data {
633      NodeData::Element { children, .. } => children
634        .iter()
635        .map(|child| usize::from(is_token(child)) + count(child))
636        .sum(),
637      _ => 0,
638    }
639  }
640  fn first(data: &mut NodeData) -> Option<&mut NodeData> {
641    let NodeData::Element { children, .. } = data else {
642      return None;
643    };
644    for child in children {
645      if is_token(child) {
646        return Some(child);
647      }
648      if let Some(token) = first(child) {
649        return Some(token);
650      }
651    }
652    None
653  }
654  if is_token(result) || count(result) != 1 {
655    return None;
656  }
657  first(result)
658}
659
660/// Add `node`'s lpadding/rpadding (converted to em) onto `result`'s internal
661/// `_lpadding`/`_rpadding`, summing with any value already present.
662fn attach_source_padding(node: &Node, result: &mut NodeData) {
663  // Perl ASSIGNS (`$$result[1]{_lpadding} = $l if $l`) β€” the outer node's
664  // padding wins over whatever the inner conversion set (an XMDual whose
665  // presentation child also carries padding must not double-count). The
666  // XMRef branch separately ADDS the referring node's padding on top,
667  // reproducing Perl's `_getspace` refr+node SUM (see `pmml_inner`).
668  for (src, dst) in [("lpadding", "_lpadding"), ("rpadding", "_rpadding")] {
669    if let Some(v) = node.get_attribute(src) {
670      let em = super::get_xm_hint_spacing(&v);
671      if em != 0.0
672        && let NodeData::Element { ref mut attributes, .. } = *result
673      {
674        let attrs = attributes.get_or_insert_with(Default::default);
675        attrs.insert(dst.to_string(), fmt_em(em));
676      }
677    }
678  }
679}
680
681/// ADD `node`'s padding onto the result (XMRef-over-target: Perl `_getspace`
682/// SUMS the referring node's padding with the target's).
683fn add_source_padding(node: &Node, result: &mut NodeData) {
684  for (src, dst) in [("lpadding", "_lpadding"), ("rpadding", "_rpadding")] {
685    if let Some(v) = node.get_attribute(src) {
686      let em = super::get_xm_hint_spacing(&v);
687      if em != 0.0
688        && let NodeData::Element { ref mut attributes, .. } = *result
689      {
690        let attrs = attributes.get_or_insert_with(Default::default);
691        let prior = attrs
692          .get(dst)
693          .and_then(|s| s.trim_end_matches("em").parse::<f64>().ok())
694          .unwrap_or(0.0);
695        attrs.insert(dst.to_string(), fmt_em(prior + em));
696      }
697    }
698  }
699}
700
701fn pmml_inner(doc: &PostDocument, node: &Node) -> NodeData {
702  // Fast-path dispatch: all tags we recognize live in the ltx namespace.
703  // Compare localname directly and check namespace prefix separately to
704  // avoid the `format!("{}:{}", prefix, localname)` allocation inside
705  // `get_qname`. On non-ltx nodes, fall through to the generic m:mtext
706  // wrapping (same as the original catchall).
707  let is_ltx = doc.qname_prefix(node).as_deref() == Some("ltx");
708  let localname = if is_ltx {
709    node.get_name()
710  } else {
711    String::new()
712  };
713
714  // Follow XMRef
715  if is_ltx && localname == "XMRef" {
716    if let Some(idref) = node.get_attribute("idref") {
717      if let Some(target) = doc.find_node_by_id(&idref) {
718        return pmml(doc, target);
719      }
720    }
721    return pmml_error("Unresolved XMRef");
722  }
723
724  if is_ltx {
725    match localname.as_str() {
726      "XMath" => {
727        let results: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
728        return pmml_row(results);
729      },
730      "XMDual" => {
731        let children = element_children(node);
732        return if children.len() >= 2 {
733          pmml(doc, &children[1]) // Presentation branch
734        } else {
735          pmml_error("Empty XMDual")
736        };
737      },
738      "XMWrap" | "XMArg" => {
739        // Perl L400-401: only present when parsing failed; resizable.
740        let results: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
741        return pmml_maybe_resize(doc, node, pmml_row(results));
742      },
743      "XMApp" => return pmml_apply(doc, node),
744      "XMTok" => return pmml_token(doc, node),
745      "XMHint" => return pmml_hint(doc, node),
746      "XMArray" => return pmml_array(doc, node),
747      "XMText" => {
748        // Perl L494-501: iterate over child nodes, not just text content.
749        // This preserves ltx:picture (SVG) elements inside XMText.
750        let mut children = Vec::new();
751        if let Some(child) = node.get_first_child() {
752          let mut current = Some(child);
753          while let Some(ref c) = current {
754            children.extend(super::pmml_text_aux(doc, c, &super::TextAttrs::default()));
755            current = c.get_next_sibling();
756          }
757        }
758        return pmml_maybe_resize(doc, node, pmml_row(children));
759      },
760      "ERROR" => {
761        // Perl L503-506: an `m:merror` of class `ltx_ERROR` around the source text (issue 1132). The node's own class
762        // (`undefined`) is merged on once by `pmml`, where Perl's L350-352 merges it a second time ("undefined
763        // undefined", KNOWN_PERL_ERRORS #1369).
764        let mut merror = pmml_error(&node.get_content());
765        if let NodeData::Element { ref mut attributes, .. } = merror {
766          *attributes = Some(HashMap::from_iter([(
767            "class".to_string(),
768            "ltx_ERROR".to_string(),
769          )]));
770        }
771        return merror;
772      },
773      _ => {},
774    }
775  }
776
777  // Catchall: wrap content in m:mtext.
778  NodeData::Element {
779    tag:        "m:mtext".to_string(),
780    attributes: None,
781    children:   vec![NodeData::Text(node.get_content())],
782  }
783}
784
785/// Convert an XMApp to Presentation MathML.
786///
787/// Port of `pmml_internal` XMApp branch.
788fn pmml_apply(doc: &PostDocument, node: &Node) -> NodeData {
789  let children = element_children(node);
790  if children.is_empty() {
791    return pmml_error("Missing Operator");
792  }
793
794  let role = node.get_attribute("role").unwrap_or_default();
795
796  // Handle floating/post scripts.
797  //
798  // `<msub>` / `<msup>` require a base; for "floating" scripts (e.g.
799  // `{}^c`, `_d`) the base is structurally absent. We materialize
800  // the missing base as `<m:mrow></m:mrow>`: an empty `<mi>` claims an
801  // identifier with no text (task #264). Unlike an absent operand's slot
802  // (`invisible_operand`, issue 991), a script base is no row child, so no
803  // operator is spaced against it.
804  if role.contains("SUBSCRIPT") || role.contains("SUPERSCRIPT") {
805    let is_sub = role.contains("SUB");
806    let tag = if is_sub { "m:msub" } else { "m:msup" };
807    return NodeData::Element {
808      tag:        tag.to_string(),
809      attributes: None,
810      children:   vec![
811        NodeData::Element {
812          tag:        "m:mrow".to_string(),
813          attributes: None,
814          children:   vec![],
815        },
816        pmml_scriptsize(doc, &children[0]),
817      ],
818    };
819  }
820
821  let op = &children[0];
822  let args = &children[1..];
823
824  // Realize the operator
825  let rop = if doc.is_qname(op, "ltx:XMRef") {
826    op.get_attribute("idref")
827      .and_then(|id| doc.find_node_by_id(&id).cloned())
828      .unwrap_or_else(|| op.clone())
829  } else {
830    op.clone()
831  };
832
833  let op_role = get_operator_role(doc, &rop).unwrap_or_default();
834  let meaning = rop.get_attribute("meaning").unwrap_or_default();
835
836  // Perl MathML.pm L413-427: the operator's `mathstyle` switches the current
837  // style for the conversion of this application, and the result is wrapped
838  // in m:mstyle per the transition tables (\tfrac in display math β†’
839  // <mstyle displaystyle="false">, \dfrac in text β†’ displaystyle="true").
840  let style_attr = rop
841    .get_attribute("mathstyle")
842    .or_else(|| op.get_attribute("mathstyle"));
843  let ostyle = CURRENT_STYLE.with(|s| s.get());
844  let nstyle = style_attr.as_deref().and_then(MathStyle::from_attr);
845  if let Some(n) = nstyle {
846    CURRENT_STYLE.with(|s| s.set(n));
847  }
848  let result = pmml_apply_dispatch(doc, op, &rop, args, &op_role, &meaning);
849  CURRENT_STYLE.with(|s| s.set(ostyle));
850  // Perl L421: resize BEFORE the mstyle wrap.
851  let result = pmml_maybe_resize(doc, node, result);
852  maybe_style_wrap(result, ostyle, nstyle)
853}
854
855/// Role/meaning dispatch for an XMApp (the body of Perl's
856/// `lookupPresenter('Apply',…)` call in `pmml_internal`).
857fn pmml_apply_dispatch(
858  doc: &PostDocument,
859  op: &Node,
860  rop: &Node,
861  args: &[Node],
862  op_role: &str,
863  meaning: &str,
864) -> NodeData {
865  // Dispatch by role
866  match op_role {
867    "SUPERSCRIPTOP" | "SUBSCRIPTOP" if args.len() >= 2 => {
868      pmml_script_full(doc, op, &args[0], &args[1])
869    },
870    "FRACOP" if args.len() >= 2 => {
871      // Perl MathML.pm L1597-1605 `Apply:FRACOP:?`: linethickness passes
872      // through VERBATIM whenever defined (\binom β†’ "0pt", \genfrac 2pt β†’
873      // "2.0pt"); mathcolor from the op's color OR the inherited context
874      // ({\color{red}$\frac{a}{b}$} colors the fraction bar, Perl L1600);
875      // bevelled fractions carry class="ltx_bevelled" β†’ bevelled="true".
876      let mut attrs = HashMap::default();
877      if let Some(t) = rop.get_attribute("thickness") {
878        attrs.insert("linethickness".to_string(), t);
879      }
880      if let Some(c) = rop
881        .get_attribute("color")
882        .filter(|c| !c.is_empty())
883        .or_else(|| ctx_get(&CTX_COLOR))
884      {
885        attrs.insert("mathcolor".to_string(), c);
886      }
887      if let Some(cl) = rop.get_attribute("class")
888        && cl.split_ascii_whitespace().any(|c| c == "ltx_bevelled")
889      {
890        attrs.insert("bevelled".to_string(), "true".to_string());
891      }
892      NodeData::Element {
893        tag:        "m:mfrac".to_string(),
894        attributes: if attrs.is_empty() { None } else { Some(attrs) },
895        children:   vec![pmml_smaller(doc, &args[0]), pmml_smaller(doc, &args[1])],
896      }
897    },
898    "OVERACCENT" if !args.is_empty() => {
899      // Perl MathML.pm L1492-1504: check if base is XMApp with UNDERACCENT β†’ m:munderover
900      let base = &args[0];
901      let base_children = element_children(base);
902      if doc.is_qname(base, "ltx:XMApp") && base_children.len() == 2 {
903        let inner_role = base_children[0].get_attribute("role").unwrap_or_default();
904        if inner_role == "UNDERACCENT" {
905          // Combine into m:munderover: base_of_inner, under_accent, over_accent
906          return NodeData::Element {
907            tag:        "m:munderover".to_string(),
908            attributes: Some(HashMap::from_iter([
909              ("accent".to_string(), "true".to_string()),
910              ("accentunder".to_string(), "true".to_string()),
911            ])),
912            children:   vec![
913              pmml(doc, &base_children[1]), // the actual base
914              pmml(doc, &base_children[0]), // the under-accent
915              pmml(doc, op),                // the over-accent
916            ],
917          };
918        }
919      }
920      NodeData::Element {
921        tag:        "m:mover".to_string(),
922        attributes: Some(HashMap::from_iter([(
923          "accent".to_string(),
924          "true".to_string(),
925        )])),
926        children:   vec![pmml(doc, base), pmml(doc, op)],
927      }
928    },
929    "UNDERACCENT" if !args.is_empty() => {
930      // Perl MathML.pm L1507-1519: check if base is XMApp with OVERACCENT β†’ m:munderover
931      let base = &args[0];
932      let base_children = element_children(base);
933      if doc.is_qname(base, "ltx:XMApp") && base_children.len() == 2 {
934        let inner_role = base_children[0].get_attribute("role").unwrap_or_default();
935        if inner_role == "OVERACCENT" {
936          return NodeData::Element {
937            tag:        "m:munderover".to_string(),
938            attributes: Some(HashMap::from_iter([
939              ("accent".to_string(), "true".to_string()),
940              ("accentunder".to_string(), "true".to_string()),
941            ])),
942            children:   vec![
943              pmml(doc, &base_children[1]), // the actual base
944              pmml(doc, op),                // the under-accent
945              pmml(doc, &base_children[0]), // the over-accent
946            ],
947          };
948        }
949      }
950      NodeData::Element {
951        tag:        "m:munder".to_string(),
952        attributes: Some(HashMap::from_iter([(
953          "accentunder".to_string(),
954          "true".to_string(),
955        )])),
956        children:   vec![pmml(doc, base), pmml(doc, op)],
957      }
958    },
959    "POSTFIX" if !args.is_empty() => {
960      let mut items: Vec<NodeData> = args.iter().map(|a| pmml(doc, a)).collect();
961      items.push(pmml(doc, op));
962      pmml_row(items)
963    },
964    "ADDOP" | "RELOP" | "MULOP" | "BINOP" | "ARROW" | "METARELOP" | "COMPOSEOP" | "MODIFIEROP"
965    | "MIDDLE" => {
966      // Infix: arg1 op arg2 op arg3 ...
967      pmml_infix(doc, op, args)
968    },
969    "SUMOP" | "INTOP" | "BIGOP" | "LIMITOP" => {
970      // Big operator: Σ/∫ applied to args (gets FUNCTION APPLICATION ⁑).
971      // DIFFOP (βˆ‚, d, βˆ‡-as-diff) is deliberately EXCLUDED β€” Perl MathML.pm:702
972      // `$ismoveop = … (SUMOP|INTOP|BIGOP|LIMITOP)$/  # Not DIFFOP`; a DIFFOP
973      // falls to the generic apply below, which juxtaposes (no ⁑) because its
974      // base renders as <m:mo>. (Witness: `\partial f` β†’ βˆ‚f, not βˆ‚β‘f.)
975      pmml_summation(doc, op, args)
976    },
977    "OPEN" | "CLOSE" if !args.is_empty() => {
978      // Fenced: (args)
979      pmml_parenthesize(doc, op, args)
980    },
981    "ENCLOSE" if !args.is_empty() => {
982      // Perl MathML.pm L1507-1513 `Apply:ENCLOSE:?`: m:menclose with the
983      // operator's `enclose` attribute as notation (e.g. \cancel β†’
984      // updiagonalstrike); if the op (or the inherited context) carries a
985      // color, the enclosure gets it as mathcolor and the base is reset via
986      // m:mstyle to the context color (default black).
987      let mut attrs = HashMap::default();
988      if let Some(notation) = rop.get_attribute("enclose").filter(|n| !n.is_empty()) {
989        attrs.insert("notation".to_string(), notation);
990      }
991      let color = rop
992        .get_attribute("color")
993        .filter(|c| !c.is_empty())
994        .or_else(|| ctx_get(&CTX_COLOR));
995      let base = pmml(doc, &args[0]);
996      let inner = if let Some(ref c) = color {
997        attrs.insert("mathcolor".to_string(), c.clone());
998        // Perl: ['m:mstyle', { mathcolor => $COLOR || 'black' }, …] β€” reset
999        // the base to the CONTEXT color so only the enclosure is tinted.
1000        NodeData::Element {
1001          tag:        "m:mstyle".to_string(),
1002          attributes: Some(HashMap::from_iter([(
1003            "mathcolor".to_string(),
1004            ctx_get(&CTX_COLOR).unwrap_or_else(|| "black".to_string()),
1005          )])),
1006          children:   vec![base],
1007        }
1008      } else {
1009        base
1010      };
1011      NodeData::Element {
1012        tag:        "m:menclose".to_string(),
1013        attributes: if attrs.is_empty() { None } else { Some(attrs) },
1014        children:   vec![inner],
1015      }
1016    },
1017    _ if meaning == "multirelation" => {
1018      // Multirelation: a = b = c (interleaved args and operators)
1019      // Port of `Apply:?:multirelation` handler.
1020      let mut items = Vec::new();
1021      for (i, arg) in args.iter().enumerate() {
1022        if i > 0 && i % 2 == 1 {
1023          // Odd positions are operators in multirelation
1024          items.push(pmml(doc, arg));
1025        } else {
1026          items.push(pmml(doc, arg));
1027        }
1028      }
1029      pmml_row(items)
1030    },
1031    _ => {
1032      // Default: function application
1033      if meaning == "limit-from" && !args.is_empty() {
1034        // limit-from: base followed by direction
1035        let items: Vec<NodeData> = args.iter().map(|a| pmml(doc, a)).collect();
1036        pmml_row(items)
1037      } else if meaning == "annotated" && args.len() >= 2 {
1038        // annotated: variable with annotation (e.g. "x modulo p")
1039        pmml_row(vec![
1040          pmml(doc, &args[0]),
1041          NodeData::Element {
1042            tag:        "m:mspace".to_string(),
1043            attributes: Some(HashMap::from_iter([(
1044              "width".to_string(),
1045              "0.389em".to_string(),
1046            )])),
1047            children:   vec![],
1048          },
1049          pmml(doc, &args[1]),
1050        ])
1051      } else if meaning == "square-root" && !args.is_empty() {
1052        // Perl L1639-1642: mathcolor from the op's color or the context.
1053        NodeData::Element {
1054          tag:        "m:msqrt".to_string(),
1055          attributes: rop
1056            .get_attribute("color")
1057            .or_else(|| ctx_get(&CTX_COLOR))
1058            .map(|c| HashMap::from_iter([("mathcolor".to_string(), c)])),
1059          children:   vec![pmml(doc, &args[0])],
1060        }
1061      } else if meaning == "continued-fraction" && args.len() >= 2 {
1062        pmml_cfrac(doc, op, &args[0], &args[1])
1063      } else if meaning == "nth-root" && args.len() >= 2 {
1064        // Perl L1644-1647: `['m:mroot', …, pmml($_[2]), pmml_scriptsize($_[1])]`
1065        // β€” args are (degree, radicand) in BOTH engines' XMath; m:mroot takes
1066        // the base first, then the scriptsized degree. (Previously swapped:
1067        // degree rendered as the base, radicand shrunk.)
1068        NodeData::Element {
1069          tag:        "m:mroot".to_string(),
1070          attributes: rop
1071            .get_attribute("color")
1072            .or_else(|| ctx_get(&CTX_COLOR))
1073            .map(|c| HashMap::from_iter([("mathcolor".to_string(), c)])),
1074          children:   vec![pmml(doc, &args[1]), pmml_scriptsize(doc, &args[0])],
1075        }
1076      } else {
1077        // Generic application: op(arg1, arg2, ...). Insert FUNCTION APPLICATION
1078        // (⁑, U+2061) ONLY when the operator's base is NOT an <m:mo> β€” Perl
1079        // MathML.pm `Apply:?:?` (`$is_mo ? () : pmml_mo("\x{2061}")`). So an
1080        // OPERATOR/DIFFOP like βˆ‡ juxtaposes (βˆ‡Ο•, spacing via the mo's rspace),
1081        // while a function identifier f gets f⁑(x).
1082        let pop = pmml(doc, op);
1083        let needs_apply = !op_base_is_mo(&pop);
1084        let mut items = vec![pop];
1085        if needs_apply {
1086          items.push(pmml_mo_str("\u{2061}")); // FUNCTION APPLICATION
1087        }
1088        for arg in args {
1089          items.push(pmml(doc, arg));
1090        }
1091        pmml_row(items)
1092      }
1093    },
1094  }
1095}
1096
1097/// Convert an XMTok to the appropriate Presentation MathML token.
1098///
1099/// Port of `stylizeContent` + token converter.
1100fn pmml_token(doc: &PostDocument, node: &Node) -> NodeData {
1101  // Perl `pmml_bigop` (MathML.pm L847-856): a SUMOP/INTOP/BIGOP token whose
1102  // recorded `mathstyle` differs from the current style converts under the
1103  // switched style and wraps in m:mstyle via %stylemap (the displaystyle-
1104  // carrying table, unconditionally) β€” e.g. `\displaystyle\sum` in inline
1105  // math keeps its large rendering. Token:LIMITOP is plain pmml_mo in Perl.
1106  let nstyle = match node.get_attribute("role").as_deref() {
1107    Some("SUMOP" | "INTOP" | "BIGOP") => node
1108      .get_attribute("mathstyle")
1109      .as_deref()
1110      .and_then(MathStyle::from_attr),
1111    _ => None,
1112  };
1113  let ostyle = CURRENT_STYLE.with(|s| s.get());
1114  if let Some(n) = nstyle {
1115    CURRENT_STYLE.with(|s| s.set(n));
1116  }
1117  let result = pmml_token_inner(doc, node, None);
1118  CURRENT_STYLE.with(|s| s.set(ostyle));
1119  match nstyle {
1120    Some(n) if n != ostyle => {
1121      let style_attrs = stylemap_attrs(ostyle, n, true);
1122      if style_attrs.is_empty() {
1123        result
1124      } else {
1125        NodeData::Element {
1126          tag:        "m:mstyle".to_string(),
1127          attributes: Some(HashMap::from_iter(
1128            style_attrs
1129              .iter()
1130              .map(|(k, v)| (k.to_string(), v.to_string())),
1131          )),
1132          children:   vec![result],
1133        }
1134      }
1135    },
1136    _ => result,
1137  }
1138}
1139
1140/// Resolve a token's explicit fontsize for emission (Perl `stylizeContent`
1141/// L782-792): a %-size in script context is re-expressed relative to the
1142/// script style's nominal size, then any %-size is converted to em ("safari
1143/// apparently ignores %").
1144fn resolve_token_size(mut s: String) -> String {
1145  if let Some(req) = s.strip_suffix('%') {
1146    let ctx = current_context_size().trim_end_matches('%');
1147    if matches!(
1148      CURRENT_STYLE.with(|c| c.get()),
1149      MathStyle::Script | MathStyle::ScriptScript
1150    ) && let (Ok(req), Ok(ex)) = (req.parse::<f64>(), ctx.parse::<f64>())
1151      && ex != 0.0
1152    {
1153      s = format!("{}%", (100.0 * req / ex) as i32);
1154    }
1155    if let Some(pct) = s.strip_suffix('%')
1156      && let Ok(pct) = pct.parse::<f64>()
1157    {
1158      s = fmt_em(pct / 100.0);
1159    }
1160  }
1161  s
1162}
1163
1164/// A Format character (Unicode Cf) of those that occur in math: invisible operators, ZWSP, …
1165fn is_format_char(c: char) -> bool {
1166  matches!(c,
1167    '\u{00AD}' | '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}')
1168}
1169
1170/// A visible operator of MathML Core category K (infix `/`, `\`, `_`, U+2206): no operator space,
1171/// as TeX's Ord `/` (mathcode "013D) and `\backslash` ("26E30F); issue 789. The invisible K
1172/// operators (U+2061-2064) stay bare, as Format text gets no presentation attributes (Perl L747).
1173fn is_core_k_glyph(text: &str, role: &str) -> bool {
1174  !text.chars().all(is_format_char) && operator_dictionary::opdict_category(text, role) == "K"
1175}
1176
1177/// The text of the invisible operand: U+2060 WORD JOINER β€” zero-width, default-ignorable, not
1178/// White_Space anywhere (Unicode, JS `\s`/`trim()`, Python, Rust), no line break (UAX #14 WJ),
1179/// and no math meaning (unlike the invisible operators U+2061-2064). Issue 991.
1180const INVISIBLE_OPERAND_TEXT: &str = "\u{2060}";
1181
1182/// The placeholder for an operand that is not there (an `absent` token, an empty-symbol unit):
1183/// `<m:mphantom><m:mi>&#x2060;</m:mi></m:mphantom>`, where Perl writes an empty `<m:mi/>`
1184/// (`MathML.pm:1475`). The `mi` is an Ord atom, as amsmath's `{}` before an align cell is
1185/// (`\displaystyle{{}##}`): MathJax spaces an operator by the class of the atom before it, and an
1186/// EMPTY `mphantom` has none, so the `=` after it got no space (issue 991). The `mphantom` keeps
1187/// it invisible; the `mi` is never empty (the `debug_assert!` in `document.rs`). OXIDIZED_DESIGN #1150.
1188fn invisible_operand() -> NodeData {
1189  NodeData::Element {
1190    tag:        "m:mphantom".to_string(),
1191    attributes: None,
1192    children:   vec![NodeData::Element {
1193      tag:        "m:mi".to_string(),
1194      attributes: None,
1195      children:   vec![NodeData::Text(INVISIBLE_OPERAND_TEXT.to_string())],
1196    }],
1197  }
1198}
1199
1200/// An empty box beside an operator (`\mbox{}=b`, `a=\strut`, `\makebox[0pt]{}=b`, `\mbox{}-b`: an empty `XMText`, an
1201/// empty `<m:mrow>` as in Perl, MathML.pm:499) is TeX's zero-width Ord atom, so it gets the absent operand's
1202/// placeholder: empty, it has no class in MathJax, which sets the operator with no space on its side (issue 991), and
1203/// the spacing walk reads `βˆ’` as unary. Rows only: in a script or fraction slot the empty `<m:mrow>` stays. A box sized anywhere
1204/// inside (`\makebox[0pt]{}`, `\mbox{\makebox[1cm]{}\makebox[1cm]{}}`) keeps it all, the placeholder added as its
1205/// last child. OXIDIZED_DESIGN #1150.
1206fn fill_empty_operands(node: &mut NodeData) {
1207  let NodeData::Element { tag, children, .. } = node else {
1208    return;
1209  };
1210  if is_mrow_like(tag) {
1211    let beside_operator = |i: usize| {
1212      let left = children[..i].iter().rev().find(|c| !is_space_like(c));
1213      let right = children[i + 1..].iter().find(|c| !is_space_like(c));
1214      left.is_some_and(is_embellished_operator) || right.is_some_and(is_embellished_operator)
1215    };
1216    let empty: Vec<usize> = (0..children.len())
1217      .filter(|&i| is_empty_box(&children[i]) && beside_operator(i))
1218      .collect();
1219    for i in empty {
1220      let slot = &mut children[i];
1221      if has_output_attributes(slot) {
1222        if let NodeData::Element { children: inner, .. } = slot {
1223          inner.push(invisible_operand());
1224        }
1225      } else {
1226        // Only internal attributes (`\mbox{}\,`'s `_rpadding`): kept on the placeholder for the spacing walk.
1227        let internal = match slot {
1228          NodeData::Element { attributes, .. } => attributes.take(),
1229          _ => None,
1230        };
1231        *slot = invisible_operand();
1232        if let NodeData::Element { attributes, .. } = slot {
1233          *attributes = internal;
1234        }
1235      }
1236    }
1237  }
1238  for child in children.iter_mut() {
1239    fill_empty_operands(child);
1240  }
1241}
1242
1243/// A grouping element whose children all are such, an empty one vacuously: what an empty `XMText` becomes.
1244fn is_empty_box(node: &NodeData) -> bool {
1245  matches!(node, NodeData::Element { tag, children, .. }
1246    if matches!(tag.as_str(), "m:mrow" | "m:mpadded" | "m:mstyle") && children.iter().all(is_empty_box))
1247}
1248
1249/// An attribute that reaches the output (not an internal `_role`, `_rpadding`, …) on `node` or any descendant.
1250fn has_output_attributes(node: &NodeData) -> bool {
1251  matches!(node, NodeData::Element { attributes, children, .. }
1252    if attributes.as_ref().is_some_and(|a| a.keys().any(|k| !k.starts_with('_')))
1253      || children.iter().any(has_output_attributes))
1254}
1255
1256/// MathML Core Β§3.2.5.1: an `mtext`, an `mspace`, or a grouping element whose in-flow children all are space-like.
1257fn is_space_like(node: &NodeData) -> bool {
1258  match node {
1259    NodeData::Element { tag, children, .. } => match tag.as_str() {
1260      "m:mtext" | "m:mspace" => true,
1261      "m:mrow" | "m:mpadded" | "m:mstyle" | "m:mphantom" => children.iter().all(is_space_like),
1262      _ => false,
1263    },
1264    _ => false,
1265  }
1266}
1267
1268/// A visible `mo`, or a script element whose base is one (MathML Core's embellished operator, in the cases we emit).
1269/// An invisible operator (`\text{}A`'s U+200B, an invisible times) is spaced the same in every form.
1270fn is_embellished_operator(node: &NodeData) -> bool {
1271  match node {
1272    NodeData::Element { tag, .. } if tag == "m:mo" => !is_node_text_invisible_op(node),
1273    NodeData::Element { tag, children, .. } if is_embellisher_tag(tag) => {
1274      children.first().is_some_and(is_embellished_operator)
1275    },
1276    _ => false,
1277  }
1278}
1279
1280/// `role_override` mirrors Perl's `pmml_mo($op, role => 'OPERATOR')` call
1281/// (MathML.pm L634): the caller forces the operator dictionary to a specific
1282/// role (`OPERATOR` β†’ PREFIX form) rather than the node's stored role. When set,
1283/// this is a DIRECT `pmml_mo` invocation, so β€” like Perl's `pmml_mo`, which
1284/// records no `_role` (only the `pmml` wrapper does, MathML.pm L354) β€” we leave
1285/// `_role` unset so the operator atom-types as `Ord` rather than by its infix
1286/// role. See `pmml_infix`'s single-argument (prefix) branch and issue #535.
1287fn pmml_token_inner(doc: &PostDocument, node: &Node, role_override: Option<&str>) -> NodeData {
1288  let role = role_override
1289    .map(String::from)
1290    .or_else(|| node.get_attribute("role"))
1291    .unwrap_or_else(|| "UNKNOWN".to_string());
1292  // Perl stylizeContent L678: token attribute, else the inherited context.
1293  let font = node.get_attribute("font").or_else(|| ctx_get(&CTX_FONT));
1294  let mut text = node.get_content();
1295  let meaning = node.get_attribute("meaning");
1296
1297  // Handle special meanings
1298  if meaning.as_deref() == Some("absent") {
1299    // "absent" is XMath's placeholder for a structurally missing operand: the LHS of an
1300    // `align` continuation cell `& = …`, a prefix relation, `\frac{a}{}`, `\sqrt{}`.
1301    return invisible_operand();
1302  }
1303
1304  // Determine tag based on role
1305  let tag = match role.as_str() {
1306    "NUMBER" => "m:mn",
1307    "ID" | "UNKNOWN" => "m:mi",
1308    "FUNCTION" | "OPFUNCTION" | "TRIGFUNCTION" => "m:mi",
1309    _ => "m:mo",
1310  };
1311
1312  // Handle empty tokens
1313  if text.is_empty() {
1314    // arXiv/html_feedback#970 (paper 2312.06275): a siunitx unit declared with an
1315    // empty symbol β€” `\DeclareSIUnit{\nothing}{\relax}` β€” reaches here with empty
1316    // content but `meaning`=<unit name>. The general fallback below turns that
1317    // into a visible `<m:mi>nothing</m:mi>` (Perl renders the same, in red β€”
1318    // SHARED-FAILURE). A unit whose symbol produces nothing must render
1319    // INVISIBLY: the same invisible placeholder used for `absent` above, never the
1320    // unit name. OXIDIZED_DESIGN #114.
1321    if node
1322      .get_attribute("class")
1323      .is_some_and(|c| c.split_whitespace().any(|w| w == "ltx_unit"))
1324    {
1325      return invisible_operand();
1326    }
1327    if let Some(default) = default_token_content(&role) {
1328      text = default.to_string();
1329    } else {
1330      text = meaning
1331        .or_else(|| node.get_attribute("name"))
1332        .unwrap_or_else(|| role.clone());
1333    }
1334  }
1335
1336  // Minus sign normalization
1337  if text == "-" && matches!(role.as_str(), "ADDOP" | "OPERATOR") {
1338    text = "\u{2212}".to_string(); // MINUS SIGN
1339  }
1340
1341  // Perl L772-775: when invisibletimes is false, replace U+2062 with U+200B
1342  let is_replaced_invisible_times = text == "\u{2062}" && !get_invisible_times();
1343  if is_replaced_invisible_times {
1344    text = "\u{200B}".to_string(); // ZERO WIDTH SPACE
1345  }
1346
1347  let mut attrs = HashMap::default();
1348
1349  // Perl L747-748: text consisting only of Format characters (invisible
1350  // times/apply/separator, ZWSP, …) gets NO visual styling attributes β€”
1351  // without this, context color would paint invisible operators.
1352  // (Approximates \p{Format} with the Cf codepoints that occur in math.)
1353  let is_format_only = text.chars().all(is_format_char);
1354
1355  // Perl: zero-width space <mo> needs lspace/rspace="0em" to prevent browser
1356  // default operator spacing that creates visible gaps between letters.
1357  // Issue 789: likewise a visible Core-K operator, as Chrome 155 spaces a bare
1358  // `<mo>/</mo>` 0.222em each side.
1359  if tag == "m:mo" && (is_replaced_invisible_times || is_core_k_glyph(&text, &role)) {
1360    attrs.insert("lspace".to_string(), "0em".to_string());
1361    attrs.insert("rspace".to_string(), "0em".to_string());
1362  }
1363
1364  // Math variant from font β€” with Plane 1 Unicode conversion.
1365  // Port of Perl stylizeContent lines 689-756.
1366  if !is_format_only {
1367    use crate::unicode;
1368    let mut variant: Option<&str> = font.as_deref().map(unicode::unicode_mathvariant);
1369
1370    // Perl MathML.pm:717-719: a single char in `mi` is italic by default (MathML Core
1371    // `text-transform: math-auto`), so an italic variant says nothing and anything else β€” no
1372    // font, an upright `\mathrm{d}`, `\operatorname{e}` β€” must say `normal` explicitly.
1373    // Repro math-parse/upright_single_letter_is_normal; guards
1374    // `perfect_kernel_batch56::{upright_single_letter_is_normal,
1375    // letters_in_an_italic_context_stay_plain_mi, declaremathoperator_keeps_the_following_letters_italic}`.
1376    if tag == "m:mi" && text.chars().count() == 1 {
1377      if variant == Some("italic") {
1378        variant = None;
1379      } else if variant.is_none_or(str::is_empty) {
1380        variant = Some("normal");
1381      }
1382    } else if font.is_some() && variant == Some("normal") {
1383      variant = None; // normal is default for non-single-char-mi tokens
1384    } else if tag == "m:mi" && text.chars().count() > 1 && font.is_none() {
1385      variant = Some("normal"); // multi-char mi without font β†’ normal
1386    }
1387
1388    // Plane 1 Unicode conversion. Perl L734-737 picks the variant to remap WITH:
1389    // under `--hackplane1` only the `plane1_hackable` variants remap (and to the
1390    // simpler variant named there), under the default `plane1` the variant itself,
1391    // and under `--noplane1` nothing remaps β€” the text stays ASCII and the
1392    // `mathvariant` attribute emitted below carries the style instead. `m:mtext`
1393    // never remaps at all.
1394    if let Some(v) = variant
1395      && tag != "m:mtext"
1396      && let Some(u_variant) = plane1_target_variant(v)
1397      && let Some(u_text) = unicode::unicode_convert(&text, u_variant)
1398      && (!u_text.is_empty() || text.is_empty())
1399    {
1400      text = u_text;
1401      // Perl L739-740 keeps a BOLD variant when the hack downgraded it (e.g.
1402      // `bold-script` remapped as `script` still deserves `mathvariant="bold"`,
1403      // since the codepoint carries only the script-ness); otherwise the
1404      // character carries the whole style and the attribute is dropped.
1405      variant = if u_variant != v && v.starts_with("bold") {
1406        Some("bold")
1407      } else {
1408        None
1409      };
1410    }
1411
1412    // Emit remaining variant attribute
1413    if let Some(v) = variant {
1414      if tag == "m:mi" && text.chars().count() == 1 {
1415        if v != "italic" {
1416          attrs.insert("mathvariant".to_string(), v.to_string());
1417        }
1418      } else if v != "normal" {
1419        attrs.insert("mathvariant".to_string(), v.to_string());
1420      }
1421    }
1422
1423    // Font-based CSS class fallbacks.
1424    // Port of Perl L746-756: added regardless of plane1 conversion.
1425    let is_format_only = text.chars().all(|c| {
1426      matches!(c,
1427        '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202F}'
1428        | '\u{2060}'..='\u{2064}' | '\u{FEFF}' | '\u{00AD}')
1429    }) && !text.is_empty();
1430    if let Some(ref f) = font {
1431      if !is_format_only {
1432        if f.contains("caligraphic") {
1433          let prev = attrs.get("class").cloned().unwrap_or_default();
1434          let new = if prev.is_empty() {
1435            "ltx_font_mathcaligraphic".to_string()
1436          } else {
1437            format!("{} ltx_font_mathcaligraphic", prev)
1438          };
1439          attrs.insert("class".to_string(), new);
1440        } else if f.contains("script") {
1441          let prev = attrs.get("class").cloned().unwrap_or_default();
1442          let new = if prev.is_empty() {
1443            "ltx_font_mathscript".to_string()
1444          } else {
1445            format!("{} ltx_font_mathscript", prev)
1446          };
1447          attrs.insert("class".to_string(), new);
1448        } else if f.contains("fraktur") && text.chars().all(|c| "+-0123456789.".contains(c)) {
1449          let prev = attrs.get("class").cloned().unwrap_or_default();
1450          let new = if prev.is_empty() {
1451            "ltx_font_oldstyle".to_string()
1452          } else {
1453            format!("{} ltx_font_oldstyle", prev)
1454          };
1455          attrs.insert("class".to_string(), new);
1456        } else if f.contains("smallcaps") {
1457          let prev = attrs.get("class").cloned().unwrap_or_default();
1458          let new = if prev.is_empty() {
1459            "ltx_font_smallcaps".to_string()
1460          } else {
1461            format!("{} ltx_font_smallcaps", prev)
1462          };
1463          attrs.insert("class".to_string(), new);
1464        } else if let Some(v) = variant {
1465          if v != "normal" {
1466            let prev = attrs.get("class").cloned().unwrap_or_default();
1467            let new = if prev.is_empty() {
1468              format!("ltx_mathvariant_{}", v)
1469            } else {
1470              format!("{} ltx_mathvariant_{}", prev, v)
1471            };
1472            attrs.insert("class".to_string(), new);
1473          }
1474        }
1475      }
1476    }
1477  }
1478
1479  // Perl emits mathsize for ALL token types, not just m:mo (witness:
1480  // smallmatrix cells get mathsize="0.700em"). The context gate compensates
1481  // for our engine stamping absolute fontsize="70%" on script tokens where
1482  // Perl's leaves them bare β€” a matching size must NOT be re-emitted.
1483  if tag != "m:mo"
1484    && let Some(size) = node.get_attribute("fontsize")
1485    && size != current_context_size()
1486  {
1487    attrs.insert("mathsize".to_string(), resolve_token_size(size));
1488  }
1489
1490  // Operator-specific attributes: the mo half of Perl `stylizeContent`
1491  // (L697-827) β€” operator-dictionary xor-emission, size/stretchy interplay,
1492  // largeop/movablelimits/symmetric. (audit F8)
1493  if tag == "m:mo" {
1494    let props = operator_dictionary::opdict_lookup(&text, &role);
1495    // Perl L697-704: implied attributes.
1496    let mut stretchy = node.with_attribute(c"stretchy", |v| v == "true") == Some(true);
1497    let is_fence = matches!(role.as_str(), "OPEN" | "CLOSE" | "MIDDLE");
1498    let is_sep = role == "PUNCT";
1499    let is_largeop = matches!(role.as_str(), "SUMOP" | "INTOP");
1500    let is_moveop = matches!(role.as_str(), "SUMOP" | "INTOP" | "BIGOP" | "LIMITOP"); // Not DIFFOP
1501    let is_symm = is_largeop || text == "/"; // WANTS to be symmetric
1502    let pos = node
1503      .get_attribute("scriptpos")
1504      .unwrap_or_else(|| "post".to_string());
1505
1506    // Perl L774-778: ignore size when stretching; invisible operators get
1507    // neither size nor stretchiness.
1508    let mut size = node.get_attribute("fontsize");
1509    if stretchy {
1510      size = None;
1511    }
1512    // Include U+200B: under --noinvisibletimes the ⁒ was already replaced by
1513    // ZWSP above, and its size/stretchiness must still be cleared (Perl runs
1514    // this check on the ORIGINAL text before replacing).
1515    let is_invisible = !text.is_empty()
1516      && text
1517        .chars()
1518        .all(|c| matches!(c, '\u{2061}'..='\u{2063}' | '\u{200B}'));
1519    if is_invisible {
1520      stretchy = false;
1521      size = None;
1522    }
1523
1524    // Perl L779-798: size resolution. Emit only when the token's size
1525    // differs from the current contextual size (inside a script the msup/
1526    // msub structure already shrinks it β€” a matching "70%" must NOT be
1527    // re-emitted); a differing %-size in script context is re-expressed
1528    // relative to the script's nominal size, then converted to em ("safari
1529    // apparently ignores %"). Symmetric-wanting delimiters at explicit
1530    // sizes use the minsize/maxsize stretchyhack ("Thanks Peter
1531    // Krautzberger") instead of mathsize.
1532    let mut props_stretchy = props.stretchy;
1533    let mut stretchyhack = false;
1534    let resolved_size = size
1535      .filter(|s| s != current_context_size())
1536      .map(resolve_token_size);
1537    if let Some(size) = resolved_size {
1538      if is_symm || props.symmetric {
1539        stretchyhack = true;
1540        // Force the attribute to avoid browser bugs (esp "|").
1541        if !matches!(text.as_str(), "(" | ")" | "[" | "]" | "{" | "}") {
1542          props_stretchy = false;
1543        }
1544        stretchy = true; // pretend we asked for stretchy
1545        attrs.insert("minsize".to_string(), size.clone());
1546        attrs.insert("maxsize".to_string(), size);
1547      } else {
1548        stretchy = false; // size specifically set β†’ don't stretch it
1549        attrs.insert("mathsize".to_string(), size);
1550      }
1551    }
1552    let _ = stretchyhack;
1553
1554    // Perl L811-826: emit operator-dictionary attributes only where the
1555    // wanted value differs from what the dictionary already implies (xor).
1556    if stretchy != props_stretchy {
1557      attrs.insert(
1558        "stretchy".to_string(),
1559        (if stretchy { "true" } else { "false" }).to_string(),
1560      );
1561    }
1562    if is_fence != props.fence {
1563      attrs.insert(
1564        "fence".to_string(),
1565        (if is_fence { "true" } else { "false" }).to_string(),
1566      );
1567    }
1568    if is_sep != props.separator {
1569      attrs.insert(
1570        "separator".to_string(),
1571        (if is_sep { "true" } else { "false" }).to_string(),
1572      );
1573    }
1574    if is_largeop != props.largeop {
1575      attrs.insert(
1576        "largeop".to_string(),
1577        (if is_largeop { "true" } else { "false" }).to_string(),
1578      );
1579    }
1580    if is_largeop {
1581      attrs.insert("_largeop".to_string(), "1".to_string()); // For needsMathstyle
1582    }
1583    if is_symm && !props.symmetric && (stretchy || props_stretchy) {
1584      attrs.insert("symmetric".to_string(), "true".to_string());
1585    }
1586    // If an operator has specifically located its scripts, don't let MathML
1587    // move them. (Perl also honors $NOMOVABLELIMITS from script layout β€”
1588    // unported, audit F17.)
1589    if is_moveop && pos.contains("mid") {
1590      attrs.insert("movablelimits".to_string(), "false".to_string());
1591    }
1592
1593    // Store internal spacing attributes for adjust_spacing (Perl L821-824).
1594    // Perl's `pmml_mo` records no `_role` β€” only the `pmml()` wrapper does
1595    // (MathML.pm L354). A direct `pmml_mo` call (role_override set) therefore
1596    // leaves `_role` absent so the spacewalk atom-types the operator as `Ord`,
1597    // not by an infix role it does not actually carry here (issue #535). On the
1598    // ordinary path the `pmml()` wrapper re-stamps `_role` anyway.
1599    if role_override.is_none() {
1600      attrs.insert("_role".to_string(), role);
1601    }
1602    if props.lspace > 0.0 {
1603      attrs.insert("_lspace".to_string(), fmt_em(props.lspace));
1604    }
1605    if props.rspace > 0.0 {
1606      attrs.insert("_rspace".to_string(), fmt_em(props.rspace));
1607    }
1608  }
1609
1610  // Color / background / opacity (Perl L680-687 fallback to the inherited
1611  // context; L761-762 opacity β†’ css style; the Format suppression above).
1612  if !is_format_only {
1613    if let Some(color) = node.get_attribute("color").or_else(|| ctx_get(&CTX_COLOR)) {
1614      attrs.insert("mathcolor".to_string(), color);
1615    }
1616    // NB Perl's `$attr{backgroundcolor} && $item->getAttribute(…) || $BGCOLOR`
1617    // (L683-684) means a token's OWN backgroundcolor attribute is never
1618    // consulted on this path β€” only the context. Mirrored faithfully.
1619    if let Some(bg) = ctx_get(&CTX_BGCOLOR) {
1620      attrs.insert("mathbackground".to_string(), bg);
1621    }
1622    let cssstyle = node.get_attribute("cssstyle").unwrap_or_default();
1623    let opacity = node
1624      .get_attribute("opacity")
1625      .or_else(|| ctx_get(&CTX_OPACITY));
1626    let style = match (cssstyle.is_empty(), opacity) {
1627      (true, None) => String::new(),
1628      (true, Some(op)) => format!("opacity:{op}"),
1629      (false, None) => cssstyle,
1630      (false, Some(op)) => format!("{cssstyle};opacity:{op}"),
1631    };
1632    if !style.is_empty() {
1633      attrs.insert("style".to_string(), style);
1634    }
1635  }
1636
1637  // Href
1638  if let Some(href) = node.get_attribute("href") {
1639    attrs.insert("href".to_string(), href);
1640  }
1641
1642  // Class
1643  if let Some(class) = node.get_attribute("class") {
1644    attrs.insert("class".to_string(), class);
1645  }
1646
1647  // Source locator (token-locators): carry the XMTok's source position onto the
1648  // MathML token element so the editor can map a rendered symbol back to its
1649  // source (per-token in-equation provenance, Β§7 A.3). The math XSLT copies the
1650  // generated MathML verbatim, so emit the final HTML5 `data-sourcepos` name.
1651  // `data:sourcepos` is namespaced (the LaTeXML `data:` namespace), so read it
1652  // by local name + namespace URI (like `xml:id` is read elsewhere).
1653  if let Some(sp) = node.get_attribute_ns("sourcepos", "http://dlmf.nist.gov/LaTeXML/data") {
1654    attrs.insert("data-sourcepos".to_string(), sp);
1655  }
1656
1657  // Perl pmml_mi/pmml_mn/pmml_mo (L830-845) all pass the token through
1658  // pmml_maybe_resize (raised/framed/phantom-sized tokens).
1659  pmml_maybe_resize(doc, node, NodeData::Element {
1660    tag:        tag.to_string(),
1661    attributes: if attrs.is_empty() { None } else { Some(attrs) },
1662    children:   vec![NodeData::Text(text)],
1663  })
1664}
1665
1666/// Convert an XMHint to MathML.
1667///
1668/// Port of Hint handler.
1669fn pmml_hint(doc: &PostDocument, node: &Node) -> NodeData {
1670  if latexml_core::document::is_phantom_box(node) {
1671    return pmml_phantom(doc, node);
1672  }
1673  // Perl `Hint:?:?` (MathML.pm L1479-1483): the width is normalized through
1674  // getXMHintSpacing to em (so `\qquad` β†’ width="2em", not the raw "20pt");
1675  // zero-width hints still MUST return a node, marked `_ignorable` so
1676  // filter_row drops them from rows.
1677  let w = node
1678    .get_attribute("width")
1679    .map(|w| super::get_xm_hint_spacing(&w))
1680    .unwrap_or(0.0);
1681  let attrs = if w != 0.0 {
1682    // Perl appends 'em' to the raw number ($w . 'em'), NOT fmt_em β€” emulate
1683    // Perl's default %.15g stringification.
1684    HashMap::from_iter([("width".to_string(), format!("{}em", perl_num(w)))])
1685  } else {
1686    HashMap::from_iter([("_ignorable".to_string(), "1".to_string())])
1687  };
1688  NodeData::Element {
1689    tag:        "m:mspace".to_string(),
1690    attributes: Some(attrs),
1691    children:   vec![],
1692  }
1693}
1694
1695/// A phantom's hint holding its argument (math_common.rs; OXIDIZED_DESIGN_DIVERGENCES #1141): TeX's invisible box of
1696/// it (latex.ltx `\finph@nt`), `<mphantom>` (MathML Core Β§3.3.7) sized by the browser's font; `\hphantom` drops the
1697/// height and depth, `\vphantom` the width, through `<mpadded>` (Β§3.3.6). A phantom whose items carry spacing, which
1698/// its row has no operator to set (`\phantom{b\,c}`), takes TeX's width of its box (`phantom_spacing_as_width`).
1699fn pmml_phantom(doc: &PostDocument, node: &Node) -> NodeData {
1700  let content: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
1701  let mut content = pmml_row(content);
1702  if is_phantom_operator(&content) {
1703    quiet_phantom_operator(&mut content);
1704  }
1705  let name = node.get_attribute("name");
1706  let width = if name.as_deref() == Some("vphantom") {
1707    None
1708  } else {
1709    phantom_spacing_as_width(node, &mut content)
1710  };
1711  let phantom = NodeData::Element {
1712    tag:        "m:mphantom".to_string(),
1713    attributes: None,
1714    children:   vec![content],
1715  };
1716  // With a unit: the XSLT's styling of a size reads its unit (LaTeXML-common.xsl `f:adddim` knows pt and px; a bare `0` gave NaN).
1717  let zero = || "0pt".to_string();
1718  let mut padded = match name.as_deref() {
1719    Some("hphantom") => HashMap::from_iter([
1720      ("height".to_string(), zero()),
1721      ("depth".to_string(), zero()),
1722    ]),
1723    Some("vphantom") => HashMap::from_iter([("width".to_string(), zero())]),
1724    _ => HashMap::default(),
1725  };
1726  if let Some(width) = width {
1727    padded.insert("width".to_string(), width);
1728  }
1729  if padded.is_empty() {
1730    return phantom;
1731  }
1732  NodeData::Element {
1733    tag:        "m:mpadded".to_string(),
1734    attributes: Some(padded),
1735    children:   vec![phantom],
1736  }
1737}
1738
1739/// The width of a phantom's box when its items carry spacing (an `lpadding`/`rpadding`: `\phantom{b\,c}`,
1740/// `\phantom{x\!}`, a phantom inside folded into its neighbour's, `\phantom{b\phantom{c}d}`): the hint's `width`, TeX's
1741/// (math_common.rs), as `<mpadded>`'s; a row of the phantom's items has no operator to set it on, so it was lost.
1742/// The items' padding leaves them, the width holding it.
1743fn phantom_spacing_as_width(node: &Node, content: &mut NodeData) -> Option<String> {
1744  let items: Vec<Node> = element_children_iter(node)
1745    .flat_map(|child| {
1746      if child.get_name() == "XMArg" {
1747        element_children_iter(&child).collect()
1748      } else {
1749        vec![child]
1750      }
1751    })
1752    .collect();
1753  if !items
1754    .iter()
1755    .any(|item| item.has_attribute("lpadding") || item.has_attribute("rpadding"))
1756  {
1757    return None;
1758  }
1759  let width = super::get_xm_hint_spacing(&node.get_attribute("width")?);
1760  let mut unpad = |item: &mut NodeData| {
1761    if let NodeData::Element { attributes: Some(attrs), .. } = item {
1762      attrs.remove("_lpadding");
1763      attrs.remove("_rpadding");
1764    }
1765  };
1766  match content {
1767    NodeData::Element { tag, children, .. } if tag == "m:mrow" => {
1768      children.iter_mut().for_each(&mut unpad)
1769    },
1770    item => unpad(item),
1771  }
1772  Some(fmt_em(width.max(0.0)))
1773}
1774
1775/// Is a phantom's content a lone operator, which makes the phantom an embellished operator (MathML Core Β§3.2.4): an
1776/// `mo`, a script of one (`is_embellished_operator`), or a grouping element of one, as `\displaystyle` gives every
1777/// alignment cell's (`<mstyle>`).
1778fn is_phantom_operator(node: &NodeData) -> bool {
1779  match node {
1780    NodeData::Element { tag, children, .. }
1781      if matches!(tag.as_str(), "m:mstyle" | "m:mrow" | "m:mpadded") =>
1782    {
1783      matches!(&children[..], [only] if is_phantom_operator(only))
1784    },
1785    _ => is_embellished_operator(node),
1786  }
1787}
1788
1789/// The core `mo` of a phantom's lone operator (`is_phantom_operator`): a phantom of it is an embellished operator, which
1790/// the row around it spaces by the `mo`'s `lspace`/`rspace` and, a fence, stretches; TeX's box of it is an Ord, unspaced
1791/// and of its own size (`a\vphantom{=}b`, `\sqrt{\vphantom{\int}x}`, `\left(\mathstrut\frac12\right)`). A sized
1792/// delimiter (`minsize`/`maxsize`: `\vphantom{\Bigl(}`) keeps its stretch, which they fix, so it follows U+2060 in an
1793/// `<mrow>`, no longer an embellished operator the row's fences would leave out of their stretch.
1794fn quiet_phantom_operator(node: &mut NodeData) {
1795  let text = get_node_text(node);
1796  let NodeData::Element { tag, attributes, children } = node else {
1797    return;
1798  };
1799  if is_embellisher_tag(tag) || matches!(tag.as_str(), "m:mstyle" | "m:mrow" | "m:mpadded") {
1800    if let Some(base) = children.first_mut() {
1801      quiet_phantom_operator(base);
1802    }
1803    return;
1804  }
1805  if tag != "m:mo" {
1806    return;
1807  }
1808  let attrs = attributes.get_or_insert_with(HashMap::default);
1809  attrs.insert("lspace".to_string(), "0em".to_string());
1810  attrs.insert("rspace".to_string(), "0em".to_string());
1811  let role = attrs.get("_role").map_or("ATOM", String::as_str);
1812  let stretchy = match attrs.get("stretchy").map(String::as_str) {
1813    Some(stretchy) => stretchy == "true",
1814    None => operator_dictionary::opdict_lookup(&text, role).stretchy,
1815  };
1816  if !stretchy {
1817    return;
1818  }
1819  if !attrs.contains_key("maxsize") {
1820    attrs.insert("stretchy".to_string(), "false".to_string());
1821    return;
1822  }
1823  let operator = std::mem::replace(node, NodeData::Text(String::new()));
1824  *node = NodeData::Element {
1825    tag:        "m:mrow".to_string(),
1826    attributes: None,
1827    children:   vec![
1828      NodeData::Element {
1829        tag:        "m:mi".to_string(),
1830        attributes: None,
1831        children:   vec![NodeData::Text(INVISIBLE_OPERAND_TEXT.to_string())],
1832      },
1833      operator,
1834    ],
1835  };
1836}
1837
1838/// Format a float the way Perl stringifies numbers (%.15g): 15 SIGNIFICANT
1839/// digits, no trailing zeros. (The previous {v:.15} was 15 DECIMALS β€” wrong
1840/// for |v| < 0.1 or >= 10; PR_READINESS batch-14 fix.)
1841fn perl_num(v: f64) -> String {
1842  if v == 0.0 {
1843    return "0".to_string();
1844  }
1845  let magnitude = v.abs().log10().floor() as i32;
1846  let decimals = (14 - magnitude).clamp(0, 17) as usize;
1847  let s = format!("{v:.decimals$}");
1848  if s.contains('.') {
1849    s.trim_end_matches('0').trim_end_matches('.').to_string()
1850  } else {
1851    s
1852  }
1853}
1854
1855/// Convert an XMArray to an mtable.
1856///
1857/// Port of `pmml_internal` XMArray branch (`MathML.pm` L432-486).
1858fn pmml_array(doc: &PostDocument, node: &Node) -> NodeData {
1859  // Perl `pmml_internal` XMArray branch (L432-506): the array's `mathstyle`
1860  // switches the current style for the cell conversions; the mtable gets
1861  // displaystyle="true" when that style is display ("Mozilla seems to need
1862  // some encouragement?"), and the whole result wraps in m:mstyle per the
1863  // transition tables.
1864  let ostyle = CURRENT_STYLE.with(|s| s.get());
1865  let nstyle = node
1866    .get_attribute("mathstyle")
1867    .as_deref()
1868    .and_then(MathStyle::from_attr);
1869  if let Some(n) = nstyle {
1870    CURRENT_STYLE.with(|s| s.set(n));
1871  }
1872  let result = pmml_array_inner(doc, node);
1873  CURRENT_STYLE.with(|s| s.set(ostyle));
1874  // Perl L492-506: XMArray resizes AFTER the mstyle wrap (XMApp: before).
1875  let result = maybe_style_wrap(result, ostyle, nstyle);
1876  pmml_maybe_resize(doc, node, result)
1877}
1878
1879/// A length attribute that is zero (`0pt`, `0`, `0.0pt`, `-0em`); an unreadable one is not.
1880fn is_zero_length(length: &str) -> bool {
1881  length
1882    .trim()
1883    .trim_end_matches(|c: char| c.is_ascii_alphabetic())
1884    .trim()
1885    .parse::<f64>()
1886    .is_ok_and(|v| v == 0.0)
1887}
1888
1889fn pmml_array_inner(doc: &PostDocument, node: &Node) -> NodeData {
1890  let mut rows = Vec::new();
1891  let width = node.get_attribute("width");
1892  let vattach = node
1893    .get_attribute("vattach")
1894    .unwrap_or_else(|| "middle".to_string());
1895  // Perl MathML.pm:438-440 (#2875): a top-attached array sits on its first row's baseline, a bottom one on its last's.
1896  let align = match vattach.as_str() {
1897    "top" => "baseline1",
1898    "bottom" => "baseline-1",
1899    "middle" | "" => "axis",
1900    _ => vattach.as_str(),
1901  };
1902  // Perl L478-481 defaults `rowsep` to `0pt`; only an author's non-zero one is written (below).
1903  let rowsep = node
1904    .get_attribute("rowsep")
1905    .filter(|sep| !is_zero_length(sep));
1906  let colsep = node
1907    .get_attribute("colsep")
1908    .unwrap_or_else(|| "5pt".to_string());
1909
1910  let mut nrows = 0;
1911  let mut ncols = 0;
1912  for row_node in element_children(node) {
1913    let mut cols = Vec::new();
1914    let mut nc = 0;
1915    for cell_node in element_children(&row_node) {
1916      nc += 1;
1917      let cell_align = cell_node.get_attribute("align");
1918      let colspan = cell_node.get_attribute("colspan");
1919      let rowspan = cell_node.get_attribute("rowspan");
1920      let mut td_attrs = HashMap::default();
1921      if let Some(a) = &cell_align {
1922        if a != "center" {
1923          td_attrs.insert("columnalign".to_string(), a.clone());
1924          td_attrs.insert("class".to_string(), format!("ltx_align_{}", a));
1925        }
1926      }
1927      // Perl MathML.pm L456-473: fold `border` β†’ `ltx_border_*` and `thead` β†’
1928      // `ltx_th_*` (each attribute is space-separated values) together with any
1929      // explicit `class` into the `m:mtd` `class`. This is how a column rule
1930      // (`|` / `\hline` / array `!{|}`, dginev#740) and colortbl rules reach the
1931      // rendered table β€” the CSS paints `ltx_border_*`. Perl assembles the cell
1932      // from a hash literal whose LATER `class` key wins, so when a cell has BOTH
1933      // a non-center align AND a border/thead/class the border/thead/class value
1934      // REPLACES the `ltx_align_*` class set just above (the `columnalign`
1935      // attribute stays). We mirror that by overwriting the `class` key here.
1936      let bc = cell_node.get_attribute("border").and_then(|b| {
1937        let s = b
1938          .split_whitespace()
1939          .map(|p| format!("ltx_border_{p}"))
1940          .collect::<Vec<_>>()
1941          .join(" ");
1942        (!s.is_empty()).then_some(s)
1943      });
1944      let hc = cell_node.get_attribute("thead").and_then(|t| {
1945        let s = t
1946          .split_whitespace()
1947          .map(|p| format!("ltx_th_{p}"))
1948          .collect::<Vec<_>>()
1949          .join(" ");
1950        (!s.is_empty()).then_some(s)
1951      });
1952      // Perl `$c = ($bc ? ($hc ? "$bc $hc" : $bc) : $hc)`.
1953      let border_thead = match (bc, hc) {
1954        (Some(bc), Some(hc)) => Some(format!("{bc} {hc}")),
1955        (Some(bc), None) => Some(bc),
1956        (None, Some(hc)) => Some(hc),
1957        (None, None) => None,
1958      };
1959      let cl = cell_node.get_attribute("class").filter(|s| !s.is_empty());
1960      // Perl `($c || $cl ? (class => ($c && $cl ? "$c $cl" : $c || $cl)) : ())`.
1961      if let Some(class) = match (border_thead, cl) {
1962        (Some(c), Some(cl)) => Some(format!("{c} {cl}")),
1963        (Some(c), None) => Some(c),
1964        (None, Some(cl)) => Some(cl),
1965        (None, None) => None,
1966      } {
1967        td_attrs.insert("class".to_string(), class);
1968      }
1969      if let Some(cs) = colspan {
1970        td_attrs.insert("columnspan".to_string(), cs);
1971      }
1972      if let Some(rs) = rowspan {
1973        td_attrs.insert("rowspan".to_string(), rs);
1974      }
1975      // A cell's `backgroundcolor` (e.g. nicematrix `\CodeBefore` fills, #6569)
1976      // rides onto the `m:mtd` as `mathbackground`, matching how token-level
1977      // backgrounds are emitted (`mod.rs` `pmml_token`).
1978      if let Some(bg) = cell_node.get_attribute("backgroundcolor") {
1979        td_attrs.insert("mathbackground".to_string(), bg);
1980      }
1981
1982      let cell_children = element_children(&cell_node);
1983      let cell_content = if cell_children.is_empty() {
1984        vec![]
1985      } else {
1986        // Perl L468: cells filter _ignorable items too.
1987        filter_row(cell_children.iter().map(|c| pmml(doc, c)).collect())
1988      };
1989
1990      cols.push(NodeData::Element {
1991        tag:        "m:mtd".to_string(),
1992        attributes: if td_attrs.is_empty() {
1993          None
1994        } else {
1995          Some(td_attrs)
1996        },
1997        children:   cell_content,
1998      });
1999    }
2000    if nc > ncols {
2001      ncols = nc;
2002    }
2003    nrows += 1;
2004    rows.push(NodeData::Element {
2005      tag:        "m:mtr".to_string(),
2006      attributes: None,
2007      children:   cols,
2008    });
2009  }
2010
2011  // Perl L478-482: no separators for one row/column. The default `rowspacing="0pt"` is not written: Core has
2012  // none, and Firefox and MathJax set its rows touching (issue 695, OXIDIZED_DESIGN #1041).
2013  let emit_colsep = ncols >= 2;
2014
2015  let mut table_attrs = HashMap::default();
2016  if align != "axis" {
2017    table_attrs.insert("align".to_string(), align.to_string());
2018  }
2019  if let Some(rowsep) = rowsep.filter(|_| nrows >= 2) {
2020    table_attrs.insert("rowspacing".to_string(), rowsep);
2021  }
2022  if emit_colsep {
2023    table_attrs.insert("columnspacing".to_string(), colsep);
2024  }
2025  if let Some(w) = width {
2026    table_attrs.insert("width".to_string(), w);
2027  }
2028  // Perl L484-485: "Mozilla seems to need some encouragement?"
2029  if CURRENT_STYLE.with(|s| s.get()) == MathStyle::Display {
2030    table_attrs.insert("displaystyle".to_string(), "true".to_string());
2031  }
2032
2033  NodeData::Element {
2034    tag:        "m:mtable".to_string(),
2035    attributes: if table_attrs.is_empty() {
2036      None
2037    } else {
2038      Some(table_attrs)
2039    },
2040    children:   rows,
2041  }
2042}
2043
2044// ======================================================================
2045// Layout helpers
2046
2047/// Simple sub/superscript.
2048fn pmml_script_simple(doc: &PostDocument, tag: &str, base: &Node, script: &Node) -> NodeData {
2049  NodeData::Element {
2050    tag:        tag.to_string(),
2051    attributes: None,
2052    children:   vec![pmml(doc, base), pmml_scriptsize(doc, script)],
2053  }
2054}
2055
2056/// Convert node at script size (sub/superscripts). Port of Perl `pmml_scriptsize`:
2057/// steps the style to scriptstyle (β†’ scriptscript when already in a script) for the
2058/// duration of the recursion, so contained tokens compare against the smaller size.
2059fn pmml_scriptsize(doc: &PostDocument, node: &Node) -> NodeData {
2060  let old = CURRENT_STYLE.with(|s| {
2061    let o = s.get();
2062    s.set(o.script_step());
2063    o
2064  });
2065  let r = pmml(doc, node);
2066  CURRENT_STYLE.with(|s| s.set(old));
2067  r
2068}
2069
2070/// Convert node at smaller size (fraction numerator/denominator). Port of Perl
2071/// `pmml_smaller`: steps the style down one level for the duration of the recursion.
2072fn pmml_smaller(doc: &PostDocument, node: &Node) -> NodeData {
2073  let old = CURRENT_STYLE.with(|s| {
2074    let o = s.get();
2075    s.set(o.step_down());
2076    o
2077  });
2078  let r = pmml(doc, node);
2079  CURRENT_STYLE.with(|s| s.set(old));
2080  r
2081}
2082
2083/// Infix operator: arg1 op arg2 op arg3 ...
2084///
2085/// Port of `pmml_infix`.
2086fn pmml_infix(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2087  // `args` is matched UNFILTERED β€” XMath's `absent` placeholders keep their
2088  // slot. They exist to satisfy the content-arm contract (every binary
2089  // application has 2 operands), and it is tempting to drop them so no empty box
2090  // reaches the output β€” but the slot is the atom the operator is spaced against.
2091  //
2092  // Dropping the absent LHS of a continuation row (`& = RHS` in an `align`, whose
2093  // LHS is inherited from the row above) makes `<mo>=</mo>` the first child of its
2094  // `<mrow>`: MathJax spaces an operator by the TeX class of the atom before it, so
2095  // the `=` got no left space and the `=` column stopped lining up. That is issue
2096  // #312 β€” reported against 0.7.5-rc1 as "the alignment is all off around `=`".
2097  //
2098  // The slot must be an atom, too: `pmml_token` renders `absent` through `invisible_operand`
2099  // (an `<m:mphantom>` holding a U+2060 `<m:mi>`, an Ord), where an empty `mphantom`, which
2100  // has no TeX class in MathJax, left the `=` without its space (issue 991).
2101  // Perl's slot is an empty `<m:mi/>` (`MathML.pm:1475`). Task #264 proposed suppressing
2102  // the placeholder; that is what regressed #312, so it is closed in the other direction.
2103  match args {
2104    [] => pmml(doc, op),
2105    // One operand is rendered PREFIX. Port of Perl `pmml_infix` L632-635:
2106    // "Infix with 1 arg is presumably Prefix! (aka Operator)" β€” genuine unary
2107    // operators (`-21`, `+x`). Perl renders the operator via
2108    // `pmml_mo($op, role => 'OPERATOR')` when `$op` is an `ltx:XMTok`, which
2109    // selects the operator dictionary's PREFIX entry (e.g. `βˆ’` gets lspace 0,
2110    // not the infix ADDOP's 0.278em). WITHOUT this, a unary minus after a
2111    // relation (`a = -b`) reaches the spacewalk with infix ADDOP spacing on the
2112    // `βˆ’` and role ADDOP; the walk then wants no TeX space (Relβ†’Bin = 0) yet
2113    // sees 0.556em of dictionary spacing and zeroes BOTH `=`.rspace and
2114    // `βˆ’`.lspace, collapsing the gap (issue #535). A non-token (embellished)
2115    // operator renders normally, exactly as Perl's ternary does.
2116    [arg] => {
2117      let op_prefix = if name_is(op, "XMTok") {
2118        pmml_token_inner(doc, op, Some("OPERATOR"))
2119      } else {
2120        pmml(doc, op)
2121      };
2122      pmml_row(vec![op_prefix, pmml(doc, arg)])
2123    },
2124    // arg1 op arg2 op arg3 …
2125    [first, rest @ ..] => {
2126      let op_mml = pmml(doc, op);
2127      let mut items = vec![pmml(doc, first)];
2128      for arg in rest {
2129        items.push(op_mml.clone());
2130        items.push(pmml(doc, arg));
2131      }
2132      pmml_row(items)
2133    },
2134  }
2135}
2136
2137/// True iff `node` is the XMath placeholder for a structurally-absent
2138/// operand β€” an `<ltx:XMTok>` with `meaning="absent"`. The math
2139/// parser inserts these as the left operand for prefix-relop rules
2140/// (`Apply(=, absent, RHS)` for `& = ...` continuation rows) and as
2141/// the right operand for postfix-relop rules. Used by `pmml_infix`
2142/// to suppress materialization in Presentation MathML. Task #264.
2143fn is_absent_operand(node: &Node) -> bool {
2144  if !name_is(node, "XMTok") {
2145    return false;
2146  }
2147  node.with_attribute(c"meaning", |v| v == "absent") == Some(true)
2148}
2149
2150/// Big operator with possible limits.
2151///
2152/// Port of `pmml_summation`.
2153fn pmml_summation(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2154  let op_mml = pmml(doc, op);
2155  // FUNCTION APPLICATION (⁑) only if the operator base is NOT an <m:mo> β€” Perl's
2156  // universal is_mo rule (MathML.pm Apply:?:?). Big operators βˆ‘/∫/⋃/∏/lim all
2157  // render as <m:mo> (incl. scripted forms like βˆ‘_i via munder), so they
2158  // juxtapose their body (βˆ‘a_i, ∫f) rather than emit βˆ‘β‘a_i β€” matching Perl.
2159  let needs_apply = !op_base_is_mo(&op_mml);
2160  let mut items = vec![op_mml];
2161  if needs_apply {
2162    items.push(pmml_mo_str("\u{2061}")); // FUNCTION APPLICATION
2163  }
2164  for arg in args {
2165    items.push(pmml(doc, arg));
2166  }
2167  pmml_row(items)
2168}
2169
2170/// Parenthesized/fenced expression.
2171///
2172/// Port of `pmml_parenthesize`.
2173fn pmml_parenthesize(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2174  let mut items = vec![pmml(doc, op)];
2175  for arg in args {
2176    items.push(pmml(doc, arg));
2177  }
2178  pmml_row(items)
2179}
2180
2181// ======================================================================
2182// Script handling
2183//
2184// Port of `pmml_script` + `pmml_script_decipher` + `pmml_script_multi_layout`.
2185// Handles complex sub/superscript positioning with pre/mid/post scripts.
2186
2187/// Script pair: (sub, sup) where either can be None.
2188type ScriptPair = (Option<Node>, Option<Node>);
2189
2190/// Full script handler: disentangles pre/mid/post scripts.
2191///
2192/// Port of `pmml_script`.
2193fn pmml_script_full(doc: &PostDocument, op: &Node, base: &Node, script: &Node) -> NodeData {
2194  let (inner_base, pre_scripts, mid_scripts, post_scripts, emb_right) =
2195    pmml_script_decipher(doc, op, base, script);
2196
2197  // Perl `pmml_script` (L876-891) + `pmml_script_mid_layout` (L899-906):
2198  // the inner base converts under ITS recorded mathstyle (blocking a nested
2199  // m:mstyle from the token/apply paths), and when that style differs from
2200  // the context the whole script layout gets one m:mstyle displaystyle wrap
2201  // β€” mstyle doesn't nest well inside scripts.
2202  let ostyle = CURRENT_STYLE.with(|s| s.get());
2203  let bstyle = inner_base
2204    .get_attribute("mathstyle")
2205    .as_deref()
2206    .and_then(MathStyle::from_attr);
2207  if let Some(b) = bstyle {
2208    CURRENT_STYLE.with(|s| s.set(b));
2209  }
2210  let base_mml = pmml(doc, &inner_base);
2211  CURRENT_STYLE.with(|s| s.set(ostyle));
2212
2213  // Apply mid scripts (under/over)
2214  let base_mml = apply_mid_scripts(doc, base_mml, &mid_scripts, emb_right.as_ref());
2215
2216  // Apply pre/post scripts
2217  let layout = apply_multi_scripts(doc, base_mml, &pre_scripts, &post_scripts);
2218  match bstyle {
2219    Some(b) if b != ostyle => NodeData::Element {
2220      tag:        "m:mstyle".to_string(),
2221      attributes: Some(HashMap::from_iter([(
2222        "displaystyle".to_string(),
2223        (if b == MathStyle::Display {
2224          "true"
2225        } else {
2226          "false"
2227        })
2228        .to_string(),
2229      )])),
2230      children:   vec![layout],
2231    },
2232    _ => layout,
2233  }
2234}
2235
2236/// Decipher nested script applications into pre/mid/post groups.
2237///
2238/// Port of `pmml_script_decipher`.
2239fn pmml_script_decipher(
2240  doc: &PostDocument,
2241  op: &Node,
2242  base: &Node,
2243  script: &Node,
2244) -> (
2245  Node,
2246  Vec<ScriptPair>,
2247  Vec<ScriptPair>,
2248  Vec<ScriptPair>,
2249  Option<Node>,
2250) {
2251  let mut pre_scripts: Vec<ScriptPair> = Vec::new();
2252  let mut mid_scripts: Vec<ScriptPair> = Vec::new();
2253  let mut post_scripts: Vec<ScriptPair> = Vec::new();
2254  // Perl's `$emb_right` β€” the base's RIGHT embellishment, used to phantom-pad
2255  // the under/over scripts (L968, L1015-1017). Perl also declares `$emb_left`
2256  // but NEVER assigns it, so that half of `pmml_scriptsize_padded` is dead code
2257  // upstream and is deliberately not represented here.
2258  let mut emb_right: Option<Node> = None;
2259  let mut saw_mid = false;
2260
2261  // Perl tracks the last level seen in each of the three groups, so that a
2262  // script at a DIFFERENT nesting level starts a new pair instead of filling the
2263  // free slot of the current one. Perl compares with `ne`, and the initials are
2264  // the number 0 β€” which stringifies to "0" and so matches a literal `post0`.
2265  let (mut pre_level, mut mid_level, mut post_level) =
2266    ("0".to_string(), "0".to_string(), "0".to_string());
2267
2268  let (pos, level) = parse_scriptpos(op);
2269  let is_sub = op.get_attribute("role").unwrap_or_default().contains("SUB");
2270
2271  // Place the first script.
2272  let pair = if is_sub {
2273    (Some(script.clone()), None)
2274  } else {
2275    (None, Some(script.clone()))
2276  };
2277  match pos {
2278    ScriptPos::Pre => {
2279      pre_scripts.push(pair);
2280      pre_level = level;
2281    },
2282    ScriptPos::Mid => {
2283      saw_mid = true;
2284      mid_scripts.push(pair);
2285      mid_level = level;
2286    },
2287    ScriptPos::Post => {
2288      post_scripts.push(pair);
2289      post_level = level;
2290    },
2291  }
2292
2293  // Walk down through nested scripts on the base.
2294  let mut current_base = base.clone();
2295  loop {
2296    // Perl `$base = realize($base, 'presentation')` β€” note it ASSIGNS, so the
2297    // base ultimately returned is the realized one, and the realization follows
2298    // XMDual as well as XMRef.
2299    let Some(realized) = doc.realize_xm_node_branch(&current_base, XMBranch::Presentation) else {
2300      break;
2301    };
2302    current_base = realized;
2303
2304    if !doc.is_qname(&current_base, "ltx:XMApp") {
2305      break;
2306    }
2307
2308    let children = element_children(&current_base);
2309    if children.len() < 3 {
2310      break;
2311    }
2312
2313    let xop = &children[0];
2314    if !doc.is_qname(xop, "ltx:XMTok") {
2315      break;
2316    }
2317
2318    let xrole = xop.get_attribute("role").unwrap_or_default();
2319    let is_script_op = xrole.contains("SUPERSCRIPTOP") || xrole.contains("SUBSCRIPTOP");
2320    if !is_script_op {
2321      break;
2322    }
2323
2324    let xbase = children[1].clone();
2325    let xscript = &children[2];
2326    let (xpos, xlevel) = parse_scriptpos(xop);
2327    let x_is_sub = xrole.contains("SUB");
2328
2329    match xpos {
2330      // Prescripts accumulate outward-in, so Perl appends (`push`) and inspects
2331      // the LAST pair; mid and post scripts accumulate inward-out, so it
2332      // prepends (`unshift`) and inspects the FIRST.
2333      ScriptPos::Pre => place_script(
2334        &mut pre_scripts,
2335        &mut pre_level,
2336        xlevel,
2337        x_is_sub,
2338        xscript.clone(),
2339        false,
2340      ),
2341      ScriptPos::Mid => {
2342        saw_mid = true;
2343        place_script(
2344          &mut mid_scripts,
2345          &mut mid_level,
2346          xlevel,
2347          x_is_sub,
2348          xscript.clone(),
2349          true,
2350        );
2351      },
2352      ScriptPos::Post => {
2353        // Perl L1015-1017: a POST script found BELOW a mid (under/over) script is
2354        // not a script of the outer construct at all β€” it is an embellishment of
2355        // the base, e.g. the prime in `\mathop{X'}\limits_{p}^{q}`. Record it for
2356        // phantom padding and STOP the walk WITHOUT descending, so `current_base`
2357        // stays the embellished `Apply(post-sup, X, ')` and renders whole. Without
2358        // this the prime is treated as an outer postscript, which inverts the
2359        // nesting (`msup` outside `munderover` instead of in) and leaves the limits
2360        // uncentred over the primed base.
2361        if saw_mid {
2362          emb_right = Some(xscript.clone());
2363          break;
2364        }
2365        place_script(
2366          &mut post_scripts,
2367          &mut post_level,
2368          xlevel,
2369          x_is_sub,
2370          xscript.clone(),
2371          true,
2372        );
2373      },
2374    }
2375
2376    current_base = xbase;
2377  }
2378
2379  (
2380    current_base,
2381    pre_scripts,
2382    mid_scripts,
2383    post_scripts,
2384    emb_right,
2385  )
2386}
2387
2388/// Where a script sits relative to its base β€” the keyword half of the
2389/// `scriptpos` attribute.
2390#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2391enum ScriptPos {
2392  /// Before the base, as an `m:mmultiscripts` prescript.
2393  Pre,
2394  /// Under/over the base, as `m:munder`/`m:mover`/`m:munderover`.
2395  Mid,
2396  /// After the base β€” the default, and the only one `m:msub`/`m:msup` express.
2397  Post,
2398}
2399
2400/// Split a `scriptpos` attribute into its position keyword and nesting level.
2401///
2402/// Port of Perl's
2403/// `($op->getAttribute('scriptpos') || 'post0') =~ /^(pre|mid|post)?(\d+)?$/`.
2404/// Both capture groups are optional, so a value with neither part (or one that
2405/// does not match at all, leaving both undef) yields no keyword β€” which Perl's
2406/// `$pos eq 'pre'` / `eq 'mid'` chain then falls through to post. The level is
2407/// compared with `ne` against the running level, never arithmetically, so it
2408/// stays a string here; a missing one is Perl's undef, i.e. `""`.
2409fn parse_scriptpos(op: &Node) -> (ScriptPos, String) {
2410  let raw = op
2411    .get_attribute("scriptpos")
2412    .unwrap_or_else(|| "post0".to_string());
2413  let (pos, rest) = if let Some(rest) = raw.strip_prefix("pre") {
2414    (ScriptPos::Pre, rest)
2415  } else if let Some(rest) = raw.strip_prefix("mid") {
2416    (ScriptPos::Mid, rest)
2417  } else if let Some(rest) = raw.strip_prefix("post") {
2418    (ScriptPos::Post, rest)
2419  } else {
2420    (ScriptPos::Post, raw.as_str())
2421  };
2422  // The regex is anchored, so a trailing remainder that is not all digits means
2423  // the whole match failed: no keyword and no level.
2424  if rest.is_empty() || rest.bytes().all(|b| b.is_ascii_digit()) {
2425    (pos, rest.to_string())
2426  } else {
2427    (ScriptPos::Post, String::new())
2428  }
2429}
2430
2431/// Add one script to a pre/mid/post group, at the given nesting level.
2432///
2433/// Port of the shared shape of Perl `pmml_script_decipher` L1005-1020:
2434/// ```text
2435/// push/unshift(@list, [undef, undef]) if ($level ne $nl) || $list[END][$spos];
2436/// $list[END][$spos] = $xscript; $level = $nl;
2437/// ```
2438/// A script starts a NEW pair when it would collide with the current pair's
2439/// occupied slot **or** when it sits at a different nesting level β€” the latter
2440/// being what keeps `{x_a}^b` a two-pair `m:mmultiscripts` (the `b` rides to the
2441/// right of the whole `x_a` box) rather than collapsing to an `m:msubsup` that
2442/// stacks the two.
2443///
2444/// `at_front` selects Perl's `unshift`/`$list[0]` (mid and post, which
2445/// accumulate inward-out) over `push`/`$list[-1]` (pre).
2446///
2447/// One deliberate divergence: on an empty list Perl's pre arm evaluates
2448/// `$pres[-1][$spos]` as undef and, if the levels happen to match, then dies
2449/// assigning to `$pres[-1]`. Creating the pair is the obvious reading of the
2450/// intent, and cannot differ from Perl anywhere Perl does not simply crash.
2451fn place_script(
2452  list: &mut Vec<ScriptPair>,
2453  level: &mut String,
2454  new_level: String,
2455  is_sub: bool,
2456  script: Node,
2457  at_front: bool,
2458) {
2459  let slot_taken = |p: &ScriptPair| if is_sub { p.0.is_some() } else { p.1.is_some() };
2460  let current = if at_front { list.first() } else { list.last() };
2461  if current.is_none_or(slot_taken) || *level != new_level {
2462    if at_front {
2463      list.insert(0, (None, None));
2464    } else {
2465      list.push((None, None));
2466    }
2467  }
2468  let pair = if at_front {
2469    list.first_mut()
2470  } else {
2471    list.last_mut()
2472  }
2473  .expect("a pair was just ensured to exist");
2474  if is_sub {
2475    pair.0 = Some(script);
2476  } else {
2477    pair.1 = Some(script);
2478  }
2479  *level = new_level;
2480}
2481
2482/// Apply mid scripts (under/over) to a base.
2483fn apply_mid_scripts(
2484  doc: &PostDocument,
2485  mut base: NodeData,
2486  mid_scripts: &[ScriptPair],
2487  emb_right: Option<&Node>,
2488) -> NodeData {
2489  for (sub_opt, sup_opt) in mid_scripts {
2490    let under = sub_opt
2491      .as_ref()
2492      .map(|s| pmml_scriptsize_padded(doc, s, emb_right));
2493    let over = sup_opt
2494      .as_ref()
2495      .map(|s| pmml_scriptsize_padded(doc, s, emb_right));
2496
2497    base = match (under, over) {
2498      (Some(u), None) => NodeData::Element {
2499        tag:        "m:munder".to_string(),
2500        attributes: None,
2501        children:   vec![base, u],
2502      },
2503      (None, Some(o)) => NodeData::Element {
2504        tag:        "m:mover".to_string(),
2505        attributes: None,
2506        children:   vec![base, o],
2507      },
2508      (Some(u), Some(o)) => NodeData::Element {
2509        tag:        "m:munderover".to_string(),
2510        attributes: None,
2511        children:   vec![base, u, o],
2512      },
2513      (None, None) => base,
2514    };
2515  }
2516  base
2517}
2518
2519/// An under/over script at scriptsize, padded by a phantom of the base's right
2520/// embellishment when there is one.
2521///
2522/// Port of `pmml_scriptsize_padded` (`MathML.pm` L925-934) β€” "This is to handle
2523/// primed sums, etc." An `\mathop{X'}\limits_{p}^{q}` centres its limits on the
2524/// whole `Xβ€²` box unless each limit is widened by an invisible copy of the `β€²`,
2525/// which shifts them back over the `X` itself.
2526///
2527/// Perl's `$emb_left` arm is NOT ported: `pmml_script_decipher` declares
2528/// `$emb_left` and never assigns it (L968 β†’ L1022), so the left phantom is
2529/// unreachable upstream. Only the right embellishment can occur, so this takes a
2530/// single `emb_right`.
2531fn pmml_scriptsize_padded(doc: &PostDocument, script: &Node, emb_right: Option<&Node>) -> NodeData {
2532  let script_mml = pmml_scriptsize(doc, script);
2533  match emb_right {
2534    None => script_mml,
2535    Some(emb) => NodeData::Element {
2536      tag:        "m:mrow".to_string(),
2537      attributes: None,
2538      children:   vec![script_mml, NodeData::Element {
2539        tag:        "m:mphantom".to_string(),
2540        attributes: None,
2541        children:   vec![pmml_scriptsize(doc, emb)],
2542      }],
2543    },
2544  }
2545}
2546
2547/// Apply pre/post scripts to a base.
2548///
2549/// Port of `pmml_script_multi_layout`.
2550fn apply_multi_scripts(
2551  doc: &PostDocument,
2552  base: NodeData,
2553  pre_scripts: &[ScriptPair],
2554  post_scripts: &[ScriptPair],
2555) -> NodeData {
2556  // An absent script slot is an empty `<m:mrow/>`, as Perl emits (`pmml_scriptsize`
2557  // of an undefined slot). MathML Core **removed** `<m:none/>`; an empty `m:mrow`
2558  // is the accepted placeholder for an omitted subtree, so this is both the
2559  // faithful and the standards-current choice.
2560  let none_mml = || NodeData::Element {
2561    tag:        "m:mrow".to_string(),
2562    attributes: None,
2563    children:   vec![],
2564  };
2565
2566  if !pre_scripts.is_empty() {
2567    // mmultiscripts with prescripts
2568    let mut children = vec![base];
2569    for (sub_opt, sup_opt) in post_scripts {
2570      children.push(
2571        sub_opt
2572          .as_ref()
2573          .map(|s| pmml_scriptsize(doc, s))
2574          .unwrap_or_else(none_mml),
2575      );
2576      children.push(
2577        sup_opt
2578          .as_ref()
2579          .map(|s| pmml_scriptsize(doc, s))
2580          .unwrap_or_else(none_mml),
2581      );
2582    }
2583    children.push(NodeData::Element {
2584      tag:        "m:mprescripts".to_string(),
2585      attributes: None,
2586      children:   vec![],
2587    });
2588    for (sub_opt, sup_opt) in pre_scripts {
2589      children.push(
2590        sub_opt
2591          .as_ref()
2592          .map(|s| pmml_scriptsize(doc, s))
2593          .unwrap_or_else(none_mml),
2594      );
2595      children.push(
2596        sup_opt
2597          .as_ref()
2598          .map(|s| pmml_scriptsize(doc, s))
2599          .unwrap_or_else(none_mml),
2600      );
2601    }
2602    NodeData::Element {
2603      tag: "m:mmultiscripts".to_string(),
2604      attributes: None,
2605      children,
2606    }
2607  } else if post_scripts.len() > 1 {
2608    // mmultiscripts with multiple postscripts
2609    let mut children = vec![base];
2610    for (sub_opt, sup_opt) in post_scripts {
2611      children.push(
2612        sub_opt
2613          .as_ref()
2614          .map(|s| pmml_scriptsize(doc, s))
2615          .unwrap_or_else(none_mml),
2616      );
2617      children.push(
2618        sup_opt
2619          .as_ref()
2620          .map(|s| pmml_scriptsize(doc, s))
2621          .unwrap_or_else(none_mml),
2622      );
2623    }
2624    NodeData::Element {
2625      tag: "m:mmultiscripts".to_string(),
2626      attributes: None,
2627      children,
2628    }
2629  } else if post_scripts.is_empty() {
2630    base
2631  } else {
2632    // Single post script pair
2633    let (sub_opt, sup_opt) = &post_scripts[0];
2634    match (sub_opt, sup_opt) {
2635      (Some(sub_node), None) => NodeData::Element {
2636        tag:        "m:msub".to_string(),
2637        attributes: None,
2638        children:   vec![base, pmml_scriptsize(doc, sub_node)],
2639      },
2640      (None, Some(sup_node)) => NodeData::Element {
2641        tag:        "m:msup".to_string(),
2642        attributes: None,
2643        children:   vec![base, pmml_scriptsize(doc, sup_node)],
2644      },
2645      (Some(sub_node), Some(sup_node)) => NodeData::Element {
2646        tag:        "m:msubsup".to_string(),
2647        attributes: None,
2648        children:   vec![
2649          base,
2650          pmml_scriptsize(doc, sub_node),
2651          pmml_scriptsize(doc, sup_node),
2652        ],
2653      },
2654      (None, None) => base,
2655    }
2656  }
2657}
2658
2659// ======================================================================
2660// Continued fractions
2661//
2662// Port of `do_cfrac`.
2663
2664/// Handle continued fraction rendering.
2665///
2666/// Port of `Apply:?:continued-fraction` + `do_cfrac`.
2667fn pmml_cfrac(doc: &PostDocument, op: &Node, numer: &Node, denom: &Node) -> NodeData {
2668  // Perl registration (L1954-1960): only the `cfrac-inline` variant unrolls
2669  // via do_cfrac; display cfrac is a plain (recursively converted) mfrac.
2670  if op.with_attribute(c"name", |v| v == "cfrac-inline") == Some(true) {
2671    return pmml_row(do_cfrac(doc, numer, denom));
2672  }
2673  NodeData::Element {
2674    tag:        "m:mfrac".to_string(),
2675    attributes: None,
2676    children:   vec![pmml_smaller(doc, numer), pmml_smaller(doc, denom)],
2677  }
2678}
2679
2680/// Port of Perl `do_cfrac` (L1930-1951): unroll an inline continued fraction β€”
2681/// when the denominator is a sum (or \cdots) its LAST summand is pulled up to
2682/// the top level (a trailing \cdots, a nested cfrac unrolled recursively, or
2683/// an invisible-times of \cdots and a factor), leaving the current fraction
2684/// with the trailing operator inside its denominator row.
2685fn do_cfrac(doc: &PostDocument, numer: &Node, denom: &Node) -> Vec<NodeData> {
2686  if doc.is_qname(denom, "ltx:XMApp") {
2687    let dchildren = element_children(denom);
2688    if dchildren.len() >= 2 {
2689      let denomop = &dchildren[0];
2690      let denomargs = &dchildren[1..];
2691      if denomop.with_attribute(c"role", |v| v == "ADDOP") == Some(true)
2692        || denomop.get_content() == "\u{22EF}"
2693      {
2694        let (rest, last) = denomargs.split_at(denomargs.len() - 1);
2695        let last = &last[0];
2696        if !rest.is_empty() {
2697          let curr = NodeData::Element {
2698            tag:        "m:mfrac".to_string(),
2699            attributes: None,
2700            children:   vec![pmml_smaller(doc, numer), NodeData::Element {
2701              tag:        "m:mrow".to_string(),
2702              attributes: None,
2703              children:   vec![
2704                if rest.len() > 1 {
2705                  pmml_infix(doc, denomop, rest)
2706                } else {
2707                  pmml_smaller(doc, &rest[0])
2708                },
2709                pmml_smaller(doc, denomop),
2710              ],
2711            }],
2712          };
2713          if last.get_content() == "\u{22EF}" {
2714            // Denominator ends with \cdots: bring the dots up to toplevel.
2715            return vec![curr, pmml_smaller(doc, last)];
2716          } else if doc.is_qname(last, "ltx:XMApp") {
2717            let lchildren = element_children(last);
2718            if lchildren.len() >= 2 {
2719              let lastop = &lchildren[0];
2720              let lastargs = &lchildren[1..];
2721              if lastop.with_attribute(c"meaning", |v| v == "continued-fraction") == Some(true)
2722                && lastargs.len() >= 2
2723              {
2724                // Denominator ends with a cfrac: unroll it to toplevel.
2725                let mut out = vec![curr];
2726                out.extend(do_cfrac(doc, &lastargs[0], &lastargs[1]));
2727                return out;
2728              } else if lastop.get_content() == "\u{2062}"
2729                && lastargs.len() == 2
2730                && lastargs[0].get_content() == "\u{22EF}"
2731              {
2732                // Denominator ends with (invisible-times of) \cdots Β· factor.
2733                return vec![
2734                  curr,
2735                  pmml_smaller(doc, &lastargs[0]),
2736                  pmml_smaller(doc, &lastargs[1]),
2737                ];
2738              }
2739            }
2740          }
2741        }
2742      }
2743    }
2744  }
2745  vec![NodeData::Element {
2746    tag:        "m:mfrac".to_string(),
2747    attributes: None,
2748    children:   vec![pmml_smaller(doc, numer), pmml_smaller(doc, denom)],
2749  }]
2750}
2751
2752// ======================================================================
2753// Utility functions
2754
2755/// Wrap nodes in an mrow (or return single node unwrapped).
2756/// Perl MathML.pm `Apply:?:?`: descend through script wrappers (msub/msup/…) to
2757/// the operator's base and report whether it renders as `<m:mo>`. A generic
2758/// application inserts FUNCTION APPLICATION (⁑) only when the base is NOT an
2759/// `<m:mo>`, so an OPERATOR/DIFFOP (βˆ‡, βˆ‚) juxtaposes its argument while a
2760/// function identifier (`f`, `\sin`) gets the invisible apply char.
2761fn op_base_is_mo(node: &NodeData) -> bool {
2762  let mut cur = node;
2763  loop {
2764    let NodeData::Element { tag, children, .. } = cur else {
2765      return false;
2766    };
2767    if tag == "m:mo" {
2768      return true;
2769    }
2770    // Perl regex `^m:(?:msub|msup|munder|mover|mprescripts)` β€” a prefix match,
2771    // so it also covers msubsup/munderover; descend to the base (first child).
2772    // m:mstyle: the F7 mathstyle wrap (e.g. `\displaystyle\sum`) is transparent
2773    // embellishment too β€” Perl's summation never re-examines it (it never
2774    // emits ⁑ at all, L1796-1798).
2775    if matches!(
2776      tag.as_str(),
2777      "m:msub"
2778        | "m:msup"
2779        | "m:msubsup"
2780        | "m:munder"
2781        | "m:mover"
2782        | "m:munderover"
2783        | "m:mprescripts"
2784        | "m:mstyle"
2785    ) {
2786      match children.first() {
2787        Some(child) => cur = child,
2788        None => return false,
2789      }
2790    } else if tag == "m:mrow"
2791      && let [child] = children
2792        .iter()
2793        .filter(|c| !is_drawn_phantom(c))
2794        .collect::<Vec<_>>()[..]
2795    {
2796      // An operator beside an edge phantom (`\mathop{\vphantom{X}\sum}`, the parser's XMWrap dual) is still that
2797      // operator; before the phantom was drawn it was the bare `<mo>`.
2798      cur = child;
2799    } else {
2800      return false;
2801    }
2802  }
2803}
2804
2805/// A phantom as presentation draws it: `<mphantom>`, or the `<mpadded>` of `\hphantom`/`\vphantom` around one.
2806fn is_drawn_phantom(node: &NodeData) -> bool {
2807  match node {
2808    NodeData::Element { tag, children, .. } => {
2809      tag == "m:mphantom"
2810        || (tag == "m:mpadded" && matches!(&children[..], [only] if is_drawn_phantom(only)))
2811    },
2812    _ => false,
2813  }
2814}
2815
2816/// Port of Perl `filter_row` (L577-579): drop `_ignorable` items.
2817fn filter_row(items: Vec<NodeData>) -> Vec<NodeData> {
2818  items
2819    .into_iter()
2820    .filter(|i| {
2821      !matches!(i, NodeData::Element { attributes: Some(a), .. } if a.contains_key("_ignorable"))
2822    })
2823    .collect()
2824}
2825
2826fn pmml_row(children: Vec<NodeData>) -> NodeData {
2827  // Perl `pmml_row` (L581-584) filters `_ignorable` items (zero-width hints).
2828  let children = filter_row(children);
2829  if children.len() == 1 {
2830    children.into_iter().next().unwrap()
2831  } else {
2832    NodeData::Element {
2833      tag: "m:mrow".to_string(),
2834      attributes: None,
2835      children,
2836    }
2837  }
2838}
2839
2840/// Create an mo element from a string.
2841fn pmml_mo_str(text: &str) -> NodeData {
2842  NodeData::Element {
2843    tag:        "m:mo".to_string(),
2844    attributes: None,
2845    children:   vec![NodeData::Text(text.to_string())],
2846  }
2847}
2848
2849/// Create a MathML error element.
2850fn pmml_error(msg: &str) -> NodeData {
2851  NodeData::Element {
2852    tag:        "m:merror".to_string(),
2853    attributes: None,
2854    children:   vec![NodeData::Element {
2855      tag:        "m:mtext".to_string(),
2856      attributes: None,
2857      children:   vec![NodeData::Text(msg.to_string())],
2858    }],
2859  }
2860}
2861
2862/// Map a LaTeXML font name to a MathML mathvariant value.
2863///
2864/// Wrapper around `unicode::unicode_mathvariant` (full Perl parity).
2865/// Returns `Some(variant)` for recognized fonts, `None` only for empty input.
2866pub fn font_to_mathvariant(font: &str) -> Option<&'static str> {
2867  if font.is_empty() {
2868    return None;
2869  }
2870  Some(crate::unicode::unicode_mathvariant(font))
2871}
2872
2873// ======================================================================
2874// TeX spacing adjustment
2875//
2876// Port of Perl's `adjust_spacing` / `space_walk` / `adjust_pair`.
2877// Walks adjacent pairs in mrow and adjusts lspace/rspace to match TeX spacing.
2878
2879/// TeX spacing values: thin=3mu, med=4mu, thick=5mu (in em = mu/18)
2880const TEX_SPACING: [f64; 4] = [0.0, 0.167, 0.222, 0.2778];
2881
2882/// Spacing epsilon β€” ignore differences below this (em)
2883const SPACING_EPSILON: f64 = 0.01;
2884
2885/// Don't complain if we can't adjust less than this (em) β€” Perl `$fudge`.
2886const SPACING_FUDGE: f64 = 0.3;
2887
2888/// Map LaTeXML role to TeX atom type.
2889fn role_to_atom_type(role: &str) -> &'static str {
2890  match role {
2891    "ATOM" | "UNKNOWN" | "ID" | "NUMBER" | "POSTFIX" | "FUNCTION" | "DIFFOP" | "SUPOP"
2892    | "ELIDEOP" => "Ord",
2893    "OPFUNCTION" | "TRIGFUNCTION" | "BIGOP" | "SUMOP" | "INTOP" | "LIMITOP" | "OPERATOR" => "Op",
2894    "ADDOP" | "MULOP" | "BINOP" | "APPLYOP" | "COMPOSEOP" => "Bin",
2895    "RELOP" | "METARELOP" | "MODIFIEROP" | "MODIFIER" | "ARROW" => "Rel",
2896    "OPEN" => "Open",
2897    "CLOSE" => "Close",
2898    "PUNCT" | "VERTBAR" | "PERIOD" => "Punct",
2899    "ARRAY" | "POSTSUBSCRIPT" | "POSTSUPERSCRIPT" | "FLOATSUPERSCRIPT" | "FLOATSUBSCRIPT" => {
2900      "Inner"
2901    },
2902    "MIDDLE" => "Ord",
2903    _ => "Ord",
2904  }
2905}
2906
2907/// Get TeX spacing code for a pair of atom types.
2908fn atompair_spacing(left: &str, right: &str) -> i32 {
2909  match (left, right) {
2910    ("Ord", "Op") | ("Op", "Ord") | ("Op", "Op") | ("Close", "Op") => 1,
2911    ("Ord", "Bin")
2912    | ("Bin", "Ord")
2913    | ("Bin", "Open")
2914    | ("Bin", "Inner")
2915    | ("Close", "Bin")
2916    | ("Inner", "Bin")
2917    | ("Bin", "Op") => -2,
2918    ("Ord", "Rel")
2919    | ("Rel", "Ord")
2920    | ("Op", "Rel")
2921    | ("Rel", "Open")
2922    | ("Rel", "Inner")
2923    | ("Close", "Rel")
2924    | ("Inner", "Rel")
2925    | ("Rel", "Op") => -3,
2926    ("Ord", "Inner")
2927    | ("Op", "Inner")
2928    | ("Close", "Inner")
2929    | ("Inner", "Inner")
2930    | ("Inner", "Open")
2931    | ("Punct", "Ord")
2932    | ("Punct", "Op")
2933    | ("Punct", "Rel")
2934    | ("Punct", "Open")
2935    | ("Punct", "Close")
2936    | ("Punct", "Punct")
2937    | ("Punct", "Inner")
2938    | ("Inner", "Ord")
2939    | ("Inner", "Punct") => -1,
2940    ("Inner", "Op") => 1,
2941    _ => 0,
2942  }
2943}
2944
2945/// Map MathML tag to TeX atom type.
2946fn m_atom_type(tag: &str) -> Option<&'static str> {
2947  match tag {
2948    "m:mfrac" => Some("Ord"),
2949    "m:marray" => Some("Inner"),
2950    "m:mspace" => Some("Ord"),
2951    _ => None,
2952  }
2953}
2954
2955/// Check if a MathML tag is an embellished operator container.
2956fn is_embellisher_tag(tag: &str) -> bool {
2957  matches!(
2958    tag,
2959    "m:msub" | "m:msup" | "m:msubsup" | "m:munder" | "m:mover" | "m:munderover"
2960  )
2961}
2962
2963/// Check if a MathML tag is mrow-like.
2964fn is_mrow_like(tag: &str) -> bool {
2965  matches!(
2966    tag,
2967    "m:mrow" | "m:mpadded" | "m:msqrt" | "m:mstyle" | "m:merror" | "m:mphantom" | "m:mtd"
2968  )
2969}
2970
2971/// Check if text is an invisible operator.
2972fn is_invisible_op(text: &str) -> bool {
2973  !text.is_empty()
2974    && text
2975      .chars()
2976      .all(|c| matches!(c, '\u{200B}' | '\u{2061}' | '\u{2062}' | '\u{2063}'))
2977}
2978
2979/// Format em value. Port of Perl `fmt_em` (MathML.pm L1285):
2980/// `sprintf("%.3fem")` β€” trailing zeros are KEPT ("0.330em", "1.200em"),
2981/// matching Perl byte-for-byte; zero (Perl false-y) β†’ "0em". (audit F4)
2982fn fmt_em(val: f64) -> String {
2983  if val == 0.0 {
2984    "0em".to_string()
2985  } else {
2986    format!("{val:.3}em")
2987  }
2988}
2989
2990/// Get role from a NodeData, following embellished operators.
2991fn get_node_role(node: &NodeData) -> String {
2992  match node {
2993    NodeData::Element { tag, attributes, children } => {
2994      if is_embellisher_tag(tag) {
2995        if let Some(base) = children.first() {
2996          return get_node_role(base);
2997        }
2998      }
2999      attributes
3000        .as_ref()
3001        .and_then(|a| a.get("_role"))
3002        .cloned()
3003        .unwrap_or_default()
3004    },
3005    _ => String::new(),
3006  }
3007}
3008
3009fn get_node_tag(node: &NodeData) -> &str {
3010  match node {
3011    NodeData::Element { tag, .. } => tag,
3012    _ => "",
3013  }
3014}
3015
3016fn get_node_text(node: &NodeData) -> String {
3017  match node {
3018    NodeData::Text(t) => t.clone(),
3019    NodeData::Element { children, .. } => children.iter().map(get_node_text).collect(),
3020    _ => String::new(),
3021  }
3022}
3023
3024/// Check if all text in `node` consists only of invisible-op characters,
3025/// without allocating a concatenated String like `get_node_text` does.
3026/// Used by `adjust_spacing` where we only need the boolean answer.
3027fn is_node_text_invisible_op(node: &NodeData) -> bool {
3028  fn check(node: &NodeData, seen_any: &mut bool) -> bool {
3029    match node {
3030      NodeData::Text(t) => {
3031        if !t.is_empty() {
3032          *seen_any = true;
3033        }
3034        t.chars()
3035          .all(|c| matches!(c, '\u{200B}' | '\u{2061}' | '\u{2062}' | '\u{2063}'))
3036      },
3037      NodeData::Element { children, .. } => children.iter().all(|c| check(c, seen_any)),
3038      _ => true,
3039    }
3040  }
3041  let mut seen_any = false;
3042  let ok = check(node, &mut seen_any);
3043  ok && seen_any
3044}
3045
3046fn set_node_attr(node: &mut NodeData, key: &str, value: &str) {
3047  if let NodeData::Element { attributes, .. } = node {
3048    let attrs = attributes.get_or_insert_with(HashMap::default);
3049    attrs.insert(key.to_string(), value.to_string());
3050  }
3051}
3052
3053fn get_node_attr(node: &NodeData, key: &str) -> Option<String> {
3054  match node {
3055    NodeData::Element { attributes, .. } => attributes.as_ref().and_then(|a| a.get(key)).cloned(),
3056    _ => None,
3057  }
3058}
3059
3060fn get_node_attr_f64(node: &NodeData, key: &str) -> f64 {
3061  match node {
3062    NodeData::Element { attributes, .. } => attributes
3063      .as_ref()
3064      .and_then(|a| a.get(key))
3065      .and_then(|v| v.strip_suffix("em"))
3066      .and_then(|v| v.parse::<f64>().ok())
3067      .unwrap_or(0.0),
3068    _ => 0.0,
3069  }
3070}
3071
3072/// Perl `%tag_arg_pattern` (MathML.pm L1084-1088): how a tag participates in
3073/// the spacing walk.
3074#[derive(PartialEq, Clone, Copy)]
3075enum WalkType {
3076  Atom,
3077  Mrow,
3078  Other,
3079}
3080fn walk_type(tag: &str) -> WalkType {
3081  match tag {
3082    "m:mi" | "m:mo" | "m:mn" | "m:ms" | "m:mtext" => WalkType::Atom,
3083    "m:mrow" | "m:mpadded" | "m:msqrt" | "m:mstyle" | "m:merror" | "m:mphantom" | "m:mtd" => {
3084      WalkType::Mrow
3085    },
3086    _ => WalkType::Other,
3087  }
3088}
3089
3090/// Resolve a child-index path from the walk root. The walk mutates only
3091/// attributes and rewraps nodes in place (sibling indices stay stable), so
3092/// queued paths never dangle.
3093fn node_at<'a>(root: &'a NodeData, path: &[usize]) -> &'a NodeData {
3094  let mut cur = root;
3095  for &i in path {
3096    match cur {
3097      NodeData::Element { children, .. } => cur = &children[i],
3098      _ => unreachable!("spacewalk path into non-element"),
3099    }
3100  }
3101  cur
3102}
3103
3104fn node_at_mut<'a>(root: &'a mut NodeData, path: &[usize]) -> &'a mut NodeData {
3105  let mut cur = root;
3106  for &i in path {
3107    match cur {
3108      NodeData::Element { children, .. } => cur = &mut children[i],
3109      _ => unreachable!("spacewalk path into non-element"),
3110    }
3111  }
3112  cur
3113}
3114
3115fn child_path(path: &[usize], i: usize) -> Vec<usize> {
3116  let mut p = path.to_vec();
3117  p.push(i);
3118  p
3119}
3120
3121/// Descend through embellished operators (scripts) to the inner operator,
3122/// for role/opdict-spacing reads (Perl adjust_pair L1225-1227).
3123fn descend_embellishers(root: &NodeData, mut path: Vec<usize>) -> Vec<usize> {
3124  loop {
3125    match node_at(root, &path) {
3126      NodeData::Element { tag, children, .. }
3127        if is_embellisher_tag(tag) && !children.is_empty() =>
3128      {
3129        path.push(0);
3130      },
3131      _ => return path,
3132    }
3133  }
3134}
3135
3136/// Walk the MathML tree and adjust spacing. Port of Perl `adjust_spacing` /
3137/// `space_walk` (MathML.pm L1079-1133): resolves the difference between
3138/// TeX's inter-atom spacing and MathML's operator-dictionary spacing.
3139pub fn adjust_spacing(node: &mut NodeData) { space_walk(node, Vec::new()); }
3140
3141/// Port of Perl `space_walk`: pairs VISUALLY adjacent items by unwinding
3142/// nested mrows into the pair stream, streaming script bases (TeX attaches
3143/// scripts without affecting inter-atom spacing) while recursing on the
3144/// scripts themselves, and carrying invisible operators between a pair as
3145/// the preferred place to materialize an adjustment.
3146fn space_walk(root: &mut NodeData, path: Vec<usize>) {
3147  use std::collections::VecDeque;
3148  let (wt, nch) = match node_at(root, &path) {
3149    NodeData::Element { tag, children, .. } => (walk_type(tag), children.len()),
3150    _ => return,
3151  };
3152  match wt {
3153    WalkType::Atom => {},
3154    WalkType::Other => {
3155      for i in 0..nch {
3156        space_walk(root, child_path(&path, i));
3157      }
3158    },
3159    WalkType::Mrow => {
3160      let mut queue: VecDeque<Vec<usize>> = (0..nch).map(|i| child_path(&path, i)).collect();
3161      // First prev: unwrap leading nested mrows (Perl L1105-1108).
3162      let mut first = None;
3163      while let Some(p) = queue.pop_front() {
3164        let unwrap = match node_at(root, &p) {
3165          NodeData::Element { tag, children, .. } if tag == "m:mrow" => Some(children.len()),
3166          _ => None,
3167        };
3168        match unwrap {
3169          Some(n) => {
3170            for i in (0..n).rev() {
3171              queue.push_front(child_path(&p, i));
3172            }
3173          },
3174          None => {
3175            first = Some(p);
3176            break;
3177          },
3178        }
3179      }
3180      let Some(first) = first else { return };
3181      space_walk(root, first.clone());
3182      // The visually adjacent atoms, each with the invisible operator before it.
3183      let mut items: Vec<(Option<Vec<usize>>, Vec<usize>)> = vec![(None, first)];
3184      while let Some(popped) = queue.pop_front() {
3185        let mut next = popped;
3186        // Save an invisible operator as the potential target for lspace
3187        // (Perl L1111-1114).
3188        let mut invisop: Option<Vec<usize>> = None;
3189        {
3190          let n = node_at(root, &next);
3191          if get_node_tag(n) == "m:mo" && is_node_text_invisible_op(n) {
3192            invisop = Some(next);
3193            match queue.pop_front() {
3194              Some(p) => next = p,
3195              None => break,
3196            }
3197          }
3198        }
3199        enum Kind {
3200          Mrow(usize),
3201          Script(usize),
3202          Plain,
3203        }
3204        let kind = match node_at(root, &next) {
3205          NodeData::Element { tag, children, .. } => {
3206            if tag == "m:mrow" {
3207              Kind::Mrow(children.len())
3208            } else if !children.is_empty()
3209              && (tag.starts_with("m:msup")
3210                || tag.starts_with("m:msub")
3211                || tag.starts_with("m:munder")
3212                || tag.starts_with("m:mover")
3213                || tag.starts_with("m:mmultiscripts"))
3214            {
3215              // Prefix match like Perl's regex β€” covers msubsup/munderover.
3216              // A CHILDLESS script element (malformed input) is treated as
3217              // Plain β€” streaming its base would index children[0] (Perl's
3218              // undef-shift exits silently).
3219              Kind::Script(children.len())
3220            } else {
3221              Kind::Plain
3222            }
3223          },
3224          _ => Kind::Plain,
3225        };
3226        match kind {
3227          Kind::Mrow(n) => {
3228            // Unwrap into the stream; the invisible op goes back in front.
3229            for i in (0..n).rev() {
3230              queue.push_front(child_path(&next, i));
3231            }
3232            if let Some(iv) = invisop {
3233              queue.push_front(iv);
3234            }
3235            continue;
3236          },
3237          Kind::Script(n) => {
3238            // Stream the base; recurse on the scripts (Perl L1121-1128).
3239            for i in 1..n {
3240              space_walk(root, child_path(&next, i));
3241            }
3242            queue.push_front(child_path(&next, 0));
3243            if let Some(iv) = invisop {
3244              queue.push_front(iv);
3245            }
3246            continue;
3247          },
3248          Kind::Plain => {},
3249        }
3250        space_walk(root, next.clone());
3251        items.push((invisop, next));
3252      }
3253      let (roles, classes) = tex_atom_types(root, &items);
3254      let converted = |i: usize| roles[i] == "Bin" && classes[i] == "Ord";
3255      // A Bin TeX made an Ord (`a+-b`'s `βˆ’`, `a+b+`) is tight where Core spaces it: a later child by its infix
3256      // entry, as postfix `+`/`βˆ’` have none (Β§3.2.4.2); a first child is prefix, 0 already (issue 824).
3257      for (i, (_, path)) in items.iter().enumerate().skip(1) {
3258        let inner = descend_embellishers(root, path.clone());
3259        let node = node_at(root, &inner);
3260        if converted(i)
3261          && get_node_tag(node) == "m:mo"
3262          && get_node_attr_f64(node, "_lspace") + get_node_attr_f64(node, "_rspace")
3263            > SPACING_EPSILON
3264        {
3265          let sign = node_at_mut(root, &inner);
3266          for key in ["lspace", "rspace", "_lspace", "_rspace"] {
3267            set_node_attr(sign, key, "0em");
3268          }
3269        }
3270      }
3271      // A converted atom's pairs read TeX's classes (`|βŠ₯⟩`, 2405.12855: `|` is an Ord); the others the role table.
3272      for (i, (invisop, next)) in items.iter().enumerate().skip(1) {
3273        let prev = &items[i - 1].1;
3274        let types = if converted(i - 1) || converted(i) {
3275          &classes
3276        } else {
3277          &roles
3278        };
3279        adjust_pair(root, prev, next, invisop.as_deref(), types[i - 1], types[i]);
3280      }
3281    },
3282  }
3283}
3284
3285/// The TeX atom type of a walk item, by its tag or its (embellished) operator's role (Perl adjust_pair L1229-1230).
3286/// A Core-K operator in a Bin role (`/` MULOP) is TeX's Ord (issue 789); a kept Rel or Punct (`\mathrel{/}`,
3287/// `\mathpunct{/}`) spaces by its class over the forced zero (revMML2).
3288fn item_atom_type(root: &NodeData, path: &[usize]) -> &'static str {
3289  let inner = descend_embellishers(root, path.to_vec());
3290  let node = node_at(root, &inner);
3291  let tag = get_node_tag(node);
3292  let role = get_node_attr(node, "_role").unwrap_or_else(|| "ATOM".to_string());
3293  m_atom_type(tag).unwrap_or_else(|| match role_to_atom_type(&role) {
3294    "Bin" if tag == "m:mo" && is_core_k_glyph(&get_node_text(node), &role) => "Ord",
3295    class => class,
3296  })
3297}
3298
3299/// The items' atom types after TeX's pass over the list (tex.web Β§728-729): a Bin first, after a Bin, Op, Rel,
3300/// Open or Punct, before a Rel, Close or Punct, or last is an Ord. An `mspace` is glue there, not an atom. The pass
3301/// reads `βˆ‡`, `|`, `β€–` and `.` as TeX does, Ords (class 0), not as the role table's Op and Punct. Returns the role
3302/// table's types and the classes after the pass.
3303fn tex_atom_types(
3304  root: &NodeData,
3305  items: &[(Option<Vec<usize>>, Vec<usize>)],
3306) -> (Vec<&'static str>, Vec<&'static str>) {
3307  let roles: Vec<&'static str> = items.iter().map(|(_, p)| item_atom_type(root, p)).collect();
3308  let mut types: Vec<&'static str> = items
3309    .iter()
3310    .zip(&roles)
3311    .map(|((_, p), &ty)| {
3312      let inner = descend_embellishers(root, p.clone());
3313      match get_node_attr(node_at(root, &inner), "_role").as_deref() {
3314        Some("OPERATOR" | "VERTBAR" | "PERIOD") => "Ord",
3315        _ => ty,
3316      }
3317    })
3318    .collect();
3319  let mut r: Option<usize> = None; // the previous noad; none acts as TeX's initial `op_noad`
3320  for (i, (_, path)) in items.iter().enumerate() {
3321    if get_node_tag(node_at(root, path)) == "m:mspace" {
3322      continue;
3323    }
3324    let r_type = r.map_or("Op", |j| types[j]);
3325    match (types[i], r) {
3326      ("Bin", _) if matches!(r_type, "Bin" | "Op" | "Rel" | "Open" | "Punct") => types[i] = "Ord",
3327      ("Rel" | "Close" | "Punct", Some(j)) if r_type == "Bin" => types[j] = "Ord",
3328      _ => {},
3329    }
3330    r = Some(i);
3331  }
3332  if let Some(j) = r.filter(|&j| types[j] == "Bin") {
3333    types[j] = "Ord";
3334  }
3335  (roles, types)
3336}
3337
3338/// Adjust the spacing between a visually adjacent pair. Port of Perl
3339/// `adjust_pair` (MathML.pm L1220-1284), all branches.
3340fn adjust_pair(
3341  root: &mut NodeData,
3342  prev: &[usize],
3343  next: &[usize],
3344  invisop: Option<&[usize]>,
3345  prev_type: &str,
3346  next_type: &str,
3347) {
3348  let iprev = descend_embellishers(root, prev.to_vec());
3349  let inext = descend_embellishers(root, next.to_vec());
3350
3351  // Author spacing (in em) reads from the OUTER pair; role/opdict spacing
3352  // from the inner (possibly embellished) operator.
3353  let prev_req_right = get_node_attr_f64(node_at(root, prev), "_rpadding");
3354  let next_req_left = get_node_attr_f64(node_at(root, next), "_lpadding");
3355  let prev_dict_right = get_node_attr_f64(node_at(root, &iprev), "_rspace");
3356  let next_dict_left = get_node_attr_f64(node_at(root, &inext), "_lspace");
3357  let tex_code = atompair_spacing(prev_type, next_type);
3358  let tex_space = TEX_SPACING[tex_code.unsigned_abs() as usize];
3359  let target = prev_req_right + next_req_left + tex_space;
3360  let default = prev_dict_right + next_dict_left;
3361  if (target - default).abs() <= SPACING_EPSILON {
3362    return;
3363  }
3364
3365  let prev_tag = get_node_tag(node_at(root, prev)).to_string();
3366  let next_tag = get_node_tag(node_at(root, next)).to_string();
3367  // In MathML Core neither mspace nor mpadded may have negative width, and
3368  // relative +/- widths are unsupported β€” so a NEGATIVE target rewraps prev
3369  // in an m:mpadded with an ADJUSTED absolute width (Perl L1252-1260,
3370  // compute_size L1135-1145: atoms only, string metrics of the default math
3371  // font, with the ridiculous-but-Perl minimum-10pt hack for mathscript).
3372  if target < 0.0 {
3373    let sizeable = match node_at(root, prev) {
3374      NodeData::Element { tag, attributes, .. } if walk_type(tag) == WalkType::Atom => Some(
3375        attributes
3376          .as_ref()
3377          .and_then(|a| a.get("class"))
3378          .cloned()
3379          .unwrap_or_default(),
3380      ),
3381      _ => None,
3382    };
3383    if let Some(class) = sizeable {
3384      let text = get_node_text(node_at(root, prev));
3385      let font = latexml_core::common::font::Font::math_default();
3386      let (w, _h, _d) = font.compute_string_size(&text, Default::default());
3387      let mut w_sp = w.0;
3388      // Perl L1140-1141: minimum of 10pt for mathscript β€” Dimension(10*65535)
3389      // (Perl's constant, one sp shy of 10pt), applied regardless of width
3390      // (Perl's $w is an always-truthy Dimension object).
3391      if class.contains("mathscript") {
3392        w_sp = w_sp.max(10 * 65535);
3393      }
3394      let mut reqw = (w_sp as f64 / 65536.0) / 10.0 + target;
3395      if reqw < 0.0 {
3396        reqw = 0.0;
3397      }
3398      let slot = node_at_mut(root, prev);
3399      let old = std::mem::replace(slot, NodeData::Text(String::new()));
3400      *slot = NodeData::Element {
3401        tag:        "m:mpadded".to_string(),
3402        attributes: Some(HashMap::from_iter([("width".to_string(), fmt_em(reqw))])),
3403        children:   vec![old],
3404      };
3405    }
3406  } else if prev_tag == "m:mspace" || next_tag == "m:mspace" {
3407    // Merge into the mspace's existing width (Perl L1261-1262).
3408    let target_path = if prev_tag == "m:mspace" { prev } else { next };
3409    let n = node_at_mut(root, target_path);
3410    let old_w = match n {
3411      NodeData::Element { attributes, .. } => attributes
3412        .as_ref()
3413        .and_then(|a| a.get("width"))
3414        .map(|w| super::get_xm_hint_spacing(w))
3415        .unwrap_or(0.0),
3416      _ => 0.0,
3417    };
3418    set_node_attr(n, "width", &fmt_em(target + old_w));
3419  } else if let Some(iv) = invisop {
3420    set_node_attr(node_at_mut(root, iv), "lspace", &fmt_em(target));
3421  } else if prev_tag == "m:mo" && next_tag == "m:mo" {
3422    // BOTH are mo: account for each one's dictionary spacing (Perl L1264-1275).
3423    let p = prev_dict_right;
3424    let n = next_dict_left;
3425    let rem = target - n;
3426    if rem >= 0.0 {
3427      let v = if rem > SPACING_EPSILON { rem } else { 0.0 };
3428      set_node_attr(node_at_mut(root, prev), "rspace", &fmt_em(v));
3429    } else {
3430      let rem = target - p;
3431      if rem >= 0.0 {
3432        let v = if rem > SPACING_EPSILON { rem } else { 0.0 };
3433        set_node_attr(node_at_mut(root, next), "lspace", &fmt_em(v));
3434      } else {
3435        // Split the difference; Perl concatenates the raw number here
3436        // (`$rem . 'em'`), NOT fmt_em.
3437        let rem = target / 2.0;
3438        if rem != p {
3439          set_node_attr(
3440            node_at_mut(root, prev),
3441            "rspace",
3442            &format!("{}em", perl_num(rem)),
3443          );
3444        }
3445        if rem != n {
3446          set_node_attr(
3447            node_at_mut(root, next),
3448            "lspace",
3449            &format!("{}em", perl_num(rem)),
3450          );
3451        }
3452      }
3453    }
3454  } else if prev_tag == "m:mo" {
3455    set_node_attr(node_at_mut(root, prev), "rspace", &fmt_em(target));
3456  } else if next_tag == "m:mo" {
3457    set_node_attr(node_at_mut(root, next), "lspace", &fmt_em(target));
3458  } else if (target - default).abs() > SPACING_FUDGE {
3459    Info!(
3460      "ignored",
3461      "spacing",
3462      &format!("No place to set spacing to {target} (default {default})")
3463    );
3464  }
3465}
3466
3467/// Clean up internal _role/_lspace/_rspace attributes before serialization.
3468pub fn clean_internal_attrs(node: &mut NodeData) {
3469  if let NodeData::Element { attributes, children, .. } = node {
3470    if let Some(attrs) = attributes {
3471      attrs.remove("_role");
3472      attrs.remove("_lspace");
3473      attrs.remove("_rspace");
3474      attrs.remove("_largeop");
3475      attrs.remove("_lpadding");
3476      attrs.remove("_rpadding");
3477      attrs.remove("_ignorable");
3478      if attrs.is_empty() {
3479        *attributes = None;
3480      }
3481    }
3482    for child in children {
3483      clean_internal_attrs(child);
3484    }
3485  }
3486}
3487
3488#[cfg(test)]
3489mod tests {
3490  use rustc_hash::FxHashMap as HashMap;
3491
3492  use super::*;
3493
3494  #[test]
3495  fn math_style_step_down_monotone_saturates_at_scriptscript() {
3496    assert_eq!(MathStyle::Display.step_down(), MathStyle::Text);
3497    assert_eq!(MathStyle::Text.step_down(), MathStyle::Script);
3498    assert_eq!(MathStyle::Script.step_down(), MathStyle::ScriptScript);
3499    assert_eq!(MathStyle::ScriptScript.step_down(), MathStyle::ScriptScript);
3500  }
3501
3502  #[test]
3503  fn math_style_script_step_collapses_display_and_text() {
3504    assert_eq!(MathStyle::Display.script_step(), MathStyle::Script);
3505    assert_eq!(MathStyle::Text.script_step(), MathStyle::Script);
3506    assert_eq!(MathStyle::Script.script_step(), MathStyle::ScriptScript);
3507    assert_eq!(
3508      MathStyle::ScriptScript.script_step(),
3509      MathStyle::ScriptScript
3510    );
3511  }
3512
3513  #[test]
3514  fn math_style_size_percent_matches_tex_tradition() {
3515    assert_eq!(MathStyle::Display.size_percent(), "100%");
3516    assert_eq!(MathStyle::Text.size_percent(), "100%");
3517    assert_eq!(MathStyle::Script.size_percent(), "70%");
3518    assert_eq!(MathStyle::ScriptScript.size_percent(), "50%");
3519  }
3520
3521  #[test]
3522  fn invisible_times_roundtrip() {
3523    set_invisible_times(false);
3524    assert!(!get_invisible_times());
3525    set_invisible_times(true);
3526    assert!(get_invisible_times());
3527  }
3528
3529  #[test]
3530  fn embellishing_role_matches_canonical_set() {
3531    for r in [
3532      "SUPERSCRIPTOP",
3533      "SUBSCRIPTOP",
3534      "OVERACCENT",
3535      "UNDERACCENT",
3536      "MODIFIER",
3537      "MODIFIEROP",
3538    ] {
3539      assert!(is_embellishing_role(r), "{} should embellish", r);
3540    }
3541  }
3542
3543  #[test]
3544  fn embellishing_role_rejects_others() {
3545    for r in ["ADDOP", "MULOP", "ATOM", "UNKNOWN", ""] {
3546      assert!(!is_embellishing_role(r), "{} should not embellish", r);
3547    }
3548  }
3549
3550  #[test]
3551  fn default_token_content_maps_invisible_chars() {
3552    assert_eq!(default_token_content("MULOP"), Some("\u{2062}"));
3553    assert_eq!(default_token_content("ADDOP"), Some("\u{2064}"));
3554    assert_eq!(default_token_content("PUNCT"), Some("\u{2063}"));
3555  }
3556
3557  #[test]
3558  fn default_token_content_none_for_other_roles() {
3559    assert_eq!(default_token_content("ATOM"), None);
3560    assert_eq!(default_token_content(""), None);
3561    assert_eq!(default_token_content("RELOP"), None);
3562  }
3563
3564  #[test]
3565  fn clean_internal_attrs_removes_underscore_attrs() {
3566    let mut node = NodeData::Element {
3567      tag:        "mrow".to_string(),
3568      attributes: Some(HashMap::from_iter([
3569        ("_role".to_string(), "MULOP".to_string()),
3570        ("_lspace".to_string(), "4".to_string()),
3571        ("keep".to_string(), "yes".to_string()),
3572      ])),
3573      children:   vec![],
3574    };
3575    clean_internal_attrs(&mut node);
3576    if let NodeData::Element { attributes, .. } = &node {
3577      let attrs = attributes
3578        .as_ref()
3579        .expect("still has the non-internal attr");
3580      assert_eq!(attrs.len(), 1);
3581      assert_eq!(attrs.get("keep").map(String::as_str), Some("yes"));
3582    } else {
3583      panic!("expected element");
3584    }
3585  }
3586
3587  #[test]
3588  fn clean_internal_attrs_unsets_attributes_when_empty() {
3589    let mut node = NodeData::Element {
3590      tag:        "mrow".to_string(),
3591      attributes: Some(HashMap::from_iter([
3592        ("_role".to_string(), "MULOP".to_string()),
3593        ("_largeop".to_string(), "true".to_string()),
3594      ])),
3595      children:   vec![],
3596    };
3597    clean_internal_attrs(&mut node);
3598    if let NodeData::Element { attributes, .. } = &node {
3599      // All attrs were internal β†’ attributes becomes None.
3600      assert!(attributes.is_none());
3601    } else {
3602      panic!("expected element");
3603    }
3604  }
3605
3606  #[test]
3607  fn clean_internal_attrs_recurses_into_children() {
3608    let mut node = NodeData::Element {
3609      tag:        "mrow".to_string(),
3610      attributes: None,
3611      children:   vec![NodeData::Element {
3612        tag:        "mi".to_string(),
3613        attributes: Some(HashMap::from_iter([(
3614          "_rspace".to_string(),
3615          "1".to_string(),
3616        )])),
3617        children:   vec![],
3618      }],
3619    };
3620    clean_internal_attrs(&mut node);
3621    if let NodeData::Element { children, .. } = &node {
3622      if let NodeData::Element { attributes, .. } = &children[0] {
3623        assert!(attributes.is_none(), "recursion cleared child's only attr");
3624      } else {
3625        panic!("expected element child");
3626      }
3627    } else {
3628      panic!("expected element root");
3629    }
3630  }
3631
3632  #[test]
3633  fn clean_internal_attrs_ignores_text_nodes() {
3634    let mut node = NodeData::Text("x".to_string());
3635    clean_internal_attrs(&mut node);
3636    match &node {
3637      NodeData::Text(s) => assert_eq!(s, "x"),
3638      _ => panic!("expected text untouched"),
3639    }
3640  }
3641  #[test]
3642  fn test_role_to_atom_type() {
3643    // Perl MathML.pm $role_atomtype (L1150)
3644    assert_eq!(role_to_atom_type("ID"), "Ord");
3645    assert_eq!(role_to_atom_type("NUMBER"), "Ord");
3646    assert_eq!(role_to_atom_type("ADDOP"), "Bin");
3647    assert_eq!(role_to_atom_type("RELOP"), "Rel");
3648    assert_eq!(role_to_atom_type("OPEN"), "Open");
3649    assert_eq!(role_to_atom_type("CLOSE"), "Close");
3650    assert_eq!(role_to_atom_type("SUMOP"), "Op");
3651    assert_eq!(role_to_atom_type("PUNCT"), "Punct");
3652    assert_eq!(role_to_atom_type("ARRAY"), "Inner");
3653    assert_eq!(role_to_atom_type("no-such-role"), "Ord");
3654  }
3655
3656  #[test]
3657  fn test_atompair_spacing() {
3658    // Perl MathML.pm $atompair_spacing (L1196): negative = display/text-style only
3659    assert_eq!(atompair_spacing("Ord", "Op"), 1);
3660    assert_eq!(atompair_spacing("Ord", "Bin"), -2);
3661    assert_eq!(atompair_spacing("Rel", "Ord"), -3);
3662    assert_eq!(atompair_spacing("Open", "Ord"), 0);
3663    assert_eq!(atompair_spacing("Open", "Open"), 0);
3664    assert_eq!(atompair_spacing("Punct", "Bin"), 0);
3665    // The full Inner row (Perl L1207) β€” the (Inner, Punct) cell was MISSING
3666    // until 2026-07-02 (PR_READINESS review): matrix-then-comma lost its
3667    // thin space.
3668    assert_eq!(atompair_spacing("Inner", "Ord"), -1);
3669    assert_eq!(atompair_spacing("Inner", "Op"), 1);
3670    assert_eq!(atompair_spacing("Inner", "Bin"), -2);
3671    assert_eq!(atompair_spacing("Inner", "Rel"), -3);
3672    assert_eq!(atompair_spacing("Inner", "Open"), -1);
3673    assert_eq!(atompair_spacing("Inner", "Close"), 0);
3674    assert_eq!(atompair_spacing("Inner", "Punct"), -1);
3675    assert_eq!(atompair_spacing("Inner", "Inner"), -1);
3676  }
3677
3678  #[test]
3679  fn test_fmt_em() {
3680    // Perl fmt_em (L1285) byte-parity: %.3f keeps trailing zeros (audit F4).
3681    assert_eq!(fmt_em(0.0), "0em");
3682    assert_eq!(fmt_em(1.0), "1.000em");
3683    assert_eq!(fmt_em(0.167), "0.167em");
3684    assert_eq!(fmt_em(0.33), "0.330em");
3685    assert_eq!(fmt_em(1.2), "1.200em");
3686  }
3687}