Skip to main content

d2_rs_math/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5// Source-derived fraction, class-spacing, numeric and script-style portions:
6// Copyright 2017–2022 The MathJax Consortium, Apache-2.0.
7// Translated and modified from pinned mathjax-go v0.1.0; see
8// THIRD_PARTY_NOTICES.md for source mapping and retained third-party terms.
9
10//! LaTeX math labels: a Rust port of upstream D2's `d2latex` package and the
11//! `mathjax-go` TeX renderer it uses, producing the same measurements and SVG
12//! as Go D2 without a JavaScript runtime or browser.
13//!
14//! The `oracle-fixtures` feature compiles tests that read regenerated Go-oracle
15//! artifacts.
16
17use d2_rs_core::Size;
18use thiserror::Error;
19
20mod input_limits;
21mod internal_text;
22pub use input_limits::{MAX_GROUP_NESTING_DEPTH, MAX_INPUT_BYTES, validate_input};
23
24mod ams;
25mod array_body;
26mod array_rules;
27mod buildrel;
28mod cases;
29mod cd;
30mod compound_glyphs;
31mod glyphs;
32mod large_glyphs;
33mod length;
34mod limits;
35mod named_colors;
36mod radical_glyphs;
37mod root_index;
38mod rule;
39mod scene;
40mod size3_glyphs;
41mod size4_glyphs;
42mod source_symbols;
43mod stack_annotations;
44mod stretch_glyphs;
45mod table;
46mod vertical_delimiters;
47// Native mhchem expansion, inserted into the owning TeX parser.
48#[cfg(all(test, feature = "oracle-fixtures"))]
49mod aboxed_contract_tests;
50mod accents;
51mod adjust_limits;
52#[cfg(all(test, feature = "oracle-fixtures"))]
53mod adjust_limits_contract_tests;
54mod alias_font_glyphs;
55mod alias_fonts;
56mod alignment;
57#[cfg(all(test, feature = "oracle-fixtures"))]
58mod alignment_marks_contract_tests;
59mod bold_glyphs;
60mod brackets;
61#[cfg(all(test, feature = "oracle-fixtures"))]
62mod brackets_contract_tests;
63mod braket;
64#[cfg(all(test, feature = "oracle-fixtures"))]
65mod braket_contract_tests;
66mod classes;
67mod command_registry;
68#[cfg(all(test, feature = "oracle-fixtures"))]
69mod continued_fraction_contract_tests;
70mod declaration_font_glyphs;
71mod declaration_fonts;
72mod double_struck;
73mod enclose;
74#[cfg(all(test, feature = "oracle-fixtures"))]
75mod enclose_contract_tests;
76#[cfg(all(test, feature = "oracle-fixtures"))]
77mod fixed_accents_contract_tests;
78mod font_bindings;
79#[cfg(all(test, feature = "oracle-fixtures"))]
80mod font_declarations_contract_tests;
81#[cfg(all(test, feature = "oracle-fixtures"))]
82mod font_wrappers_contract_tests;
83mod framebox;
84mod general_fraction;
85#[cfg(all(test, feature = "oracle-fixtures"))]
86mod general_fraction_contract_tests;
87mod genfrac_palette;
88mod hfill;
89#[cfg(all(test, feature = "oracle-fixtures"))]
90mod line_accents_contract_tests;
91mod math_minwidth;
92mod mhchem;
93mod mml_spacing;
94mod mml_token;
95#[cfg(all(test, feature = "oracle-fixtures"))]
96mod multiscript_contract_tests;
97mod multiscripts;
98mod nonscript;
99mod operator_dictionary;
100mod padded;
101mod paired_delimiters;
102#[cfg(all(test, feature = "oracle-fixtures"))]
103mod paired_delimiters_contract_tests;
104mod pending_dots;
105mod pending_not;
106mod physics;
107#[cfg(all(test, feature = "oracle-fixtures"))]
108mod physics_contract_tests;
109mod physics_matrix_quantity;
110mod position;
111#[cfg(all(test, feature = "oracle-fixtures"))]
112mod set_macros_contract_tests;
113#[cfg(all(test, feature = "oracle-fixtures"))]
114mod size_contract_tests;
115mod smallop_glyphs;
116mod source_macros;
117mod split_fraction;
118#[cfg(all(test, feature = "oracle-fixtures"))]
119mod split_fraction_contract_tests;
120#[cfg(all(test, feature = "oracle-fixtures"))]
121mod stacks_contract_tests;
122mod style_classes;
123mod styles;
124mod tex_variant_glyphs;
125#[cfg(all(test, feature = "oracle-fixtures"))]
126mod under_over_contract_tests;
127#[cfg(all(test, feature = "oracle-fixtures"))]
128mod under_over_marks_contract_tests;
129mod wrapper_font_glyphs;
130mod xarrow;
131use length::{Dimension, Minimums};
132mod calligraphic_glyphs;
133mod italic_glyphs;
134mod letter_unicode;
135mod mathit_glyphs;
136mod number_unicode;
137pub use scene::import_scene_svg;
138/// Pinned Go `math` functions shared by the renderers and color parsing.
139pub mod gomath;
140#[doc(hidden)]
141pub mod svg_bounds;
142#[doc(hidden)]
143pub mod svg_budget;
144#[doc(hidden)]
145pub mod svg_clip;
146#[doc(hidden)]
147pub mod svg_color;
148#[doc(hidden)]
149pub mod svg_compile;
150#[doc(hidden)]
151pub mod svg_declarations;
152#[doc(hidden)]
153pub mod svg_element;
154#[doc(hidden)]
155pub mod svg_frozen_text;
156#[doc(hidden)]
157pub mod svg_geometry;
158#[doc(hidden)]
159pub mod svg_gradient;
160#[doc(hidden)]
161pub mod svg_gradient_stop;
162#[doc(hidden)]
163pub mod svg_gradient_tree;
164#[doc(hidden)]
165pub mod svg_image;
166#[doc(hidden)]
167pub mod svg_import;
168#[doc(hidden)]
169pub mod svg_length;
170#[doc(hidden)]
171pub mod svg_path;
172#[doc(hidden)]
173pub mod svg_primitive;
174#[doc(hidden)]
175pub mod svg_resources;
176#[doc(hidden)]
177pub mod svg_scene;
178#[doc(hidden)]
179pub mod svg_style;
180#[doc(hidden)]
181pub mod svg_stylesheet;
182#[doc(hidden)]
183pub mod svg_transform;
184mod svg_trig;
185#[doc(hidden)]
186pub mod svg_use;
187#[doc(hidden)]
188pub mod svg_viewport;
189#[doc(hidden)]
190pub mod svg_xml_admission;
191#[doc(hidden)]
192pub mod svg_xml_budget;
193#[doc(hidden)]
194pub mod svg_xml_document;
195
196/// Math parsing or rendering failure.
197#[derive(Clone, Debug, Eq, Error, PartialEq)]
198pub enum MathError {
199    /// Input rejected before the recursive MathJax parser.
200    #[error("{0}")]
201    InputLimit(String),
202    /// An original MathJax parser leaves a nil child which SVG wrapping
203    /// dereferences. Native context is not a fabricated Go runtime stack.
204    #[error(
205        "panic recovered: runtime error: invalid memory address or nil pointer dereference\nnative source context: mathjax-go/internal/svg/renderer.wrap:61"
206    )]
207    SourceNilChild,
208    /// The pinned parser failed before constructing a renderable TeX error.
209    #[error("{0}")]
210    SourceConversion(String),
211    /// No expression was supplied.
212    #[error("math expression is empty")]
213    Empty,
214    /// The emitted SVG did not expose finite positive intrinsic dimensions.
215    #[error("mathjax-go: SVG dimensions not found")]
216    InvalidDimensions,
217    /// The expression is outside the translated MathJax surface; no exact
218    /// SVG can be produced.
219    #[error("unsupported: TeX outside the translated mathjax-go surface")]
220    Unsupported,
221    /// A brace group was not balanced.
222    #[error("math expression has an unbalanced {delimiter} at byte {byte}")]
223    Unbalanced { delimiter: char, byte: usize },
224}
225
226/// Measures the actual emitted SVG using original D2's serialized intrinsic units.
227pub fn measure(expression: &str) -> Result<Size, MathError> {
228    let svg = render(expression)?;
229    let doc = roxmltree::Document::parse(&svg).map_err(|_| MathError::InvalidDimensions)?;
230    let root = doc.root_element();
231    let dimension = |name| {
232        let value = root.attribute(name).ok_or(MathError::InvalidDimensions)?;
233        let (numeric, unit) = value.strip_suffix("ex").map_or((value, 1.0), |v| (v, 8.0));
234        let number = numeric
235            .parse::<f64>()
236            .map_err(|_| MathError::InvalidDimensions)?
237            * unit;
238        if !number.is_finite() || number <= 0.0 {
239            return Err(MathError::InvalidDimensions);
240        }
241        Ok(number.ceil())
242    };
243    Ok(Size {
244        width: dimension("width")?,
245        height: dimension("height")?,
246    })
247}
248
249// Unsupported parser paths remain a visible text fallback, without recursion
250// through the public render-then-measure boundary.
251fn fallback_measure(expression: &str) -> Result<Size, MathError> {
252    validate(expression)?;
253    let mut width: f64 = 0.0;
254    let mut height: f64 = 18.0;
255    let mut escaped = false;
256    let mut script_depth = 0_u32;
257    let mut command = false;
258    for (byte, rune) in expression.char_indices() {
259        if escaped {
260            escaped = false;
261            if rune.is_ascii_alphabetic() {
262                command = true;
263                continue;
264            }
265            width += 8.0;
266            continue;
267        }
268        match rune {
269            '\\' => {
270                escaped = true;
271                command = false;
272            }
273            '^' | '_' => {
274                script_depth = script_depth.saturating_add(1);
275                height = height.max(18.0 + f64::from(script_depth) * 8.0);
276            }
277            '{' | '}' => {}
278            c if c.is_whitespace() => width += 3.0,
279            _ => width += if script_depth > 0 { 6.0 } else { 9.0 },
280        }
281        if command && !rune.is_ascii_alphabetic() {
282            command = false;
283        }
284        let _ = byte;
285    }
286    if escaped {
287        width += 8.0;
288    }
289    Ok(Size {
290        width: width.max(1.0).ceil(),
291        height: height.ceil(),
292    })
293}
294
295/// Renders TeX exactly as D2 v0.9.0's `d2latex.Render` (mathjax-go v0.1.0
296/// `mathjax.Render`) does, or refuses.
297///
298/// Unlike [`render`], this never returns the visible-text fallback: inputs
299/// outside the translated MathJax parser/layout surface are reported as
300/// [`MathError::Unsupported`] so callers never embed approximate output.
301pub fn render_exact(expression: &str) -> Result<String, MathError> {
302    validate_input(expression)?;
303    if let Some(ast) = parse(expression) {
304        if let Some(error) = cd::first_error_node(&ast) {
305            return match error {
306                Atom::SourceError(message) => Err(MathError::SourceConversion(message.clone())),
307                Atom::ErrorDisplay(message) => Ok(cd::render_error(message)),
308                _ => unreachable!(),
309            };
310        }
311        if cd::first_nil_child(&ast).is_some() {
312            return Err(MathError::SourceNilChild);
313        }
314        if let Some(layout) = layout(&ast) {
315            return Ok(render_layout(&layout));
316        }
317    }
318    Err(MathError::Unsupported)
319}
320
321/// Renders a deterministic semantic SVG for a TeX label.
322///
323/// The fallback keeps the original expression in a text node so unsupported
324/// MathJax commands remain visible. Exact MathJax paths, glyph metrics, and
325/// accessibility markup are a separate parity task.
326pub fn render(expression: &str) -> Result<String, MathError> {
327    validate_input(expression)?;
328    // Recoverable parser errors precede structural fallback validation, as in
329    // original MathJax. This also preserves the earliest padded-argument error.
330    if let Some(ast) = parse(expression) {
331        if let Some(error) = cd::first_error_node(&ast) {
332            return match error {
333                Atom::SourceError(message) => Err(MathError::SourceConversion(message.clone())),
334                Atom::ErrorDisplay(message) => Ok(cd::render_error(message)),
335                _ => unreachable!(),
336            };
337        }
338        if cd::first_nil_child(&ast).is_some() {
339            return Err(MathError::SourceNilChild);
340        }
341        if let Some(layout) = layout(&ast) {
342            return Ok(render_layout(&layout));
343        }
344    }
345    validate(expression)?;
346    let size = fallback_measure(expression)?;
347    let escaped = escape_text(expression);
348    Ok(format!(
349        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\"><text x=\"0\" y=\"{}\" font-family=\"serif\">{}</text></svg>",
350        number(size.width),
351        number(size.height),
352        number(size.width),
353        number(size.height),
354        number((size.height * 0.78).max(1.0)),
355        escaped
356    ))
357}
358
359#[derive(Clone, Debug)]
360enum Atom {
361    ErrorDisplay(String),
362    SourceError(String),
363    // Source structural leaves carry no glyph or advance.
364    EmptyNode(&'static str),
365    RuleSpace {
366        dimensions: [Dimension; 3],
367        background: Option<String>,
368        mathsize: f64,
369    },
370    // Height/depth-only source node (CD mpadded strut, xarrow mspace); it
371    // still emits its own empty SVG node.
372    Strut(f64, f64, &'static str),
373    CdArrow {
374        code: u32,
375        texclass: Option<usize>,
376        over: Option<Box<Atom>>,
377        under: Option<Box<Atom>>,
378        minimums: Minimums,
379    },
380    Glyph(u32),
381    FontGlyph {
382        original: u32,
383        paint: u32,
384        bold: bool,
385        font_variant: &'static str,
386    },
387    VariantGlyph(u32),
388    CalligraphicGlyph(u32),
389    ItalicGlyph(u32),
390    // Physical Unicode math characters retain their identity under font commands.
391    LiteralGlyph(u32),
392    Unit(u32),
393    Reference {
394        body: Box<Atom>,
395        href: String,
396    },
397    TaggedTable {
398        spacing: Option<f64>,
399        rows: Vec<Vec<Atom>>,
400        tags: Vec<Option<ams::Tag>>,
401        environment: String,
402        container_align: &'static str,
403    },
404    Boxed(Box<Atom>),
405    NotToken {
406        first: Box<Atom>,
407        kind: &'static str,
408        class: usize,
409    },
410    Space(f64),
411    // A source filter candidate; inherited level is recorded before removal.
412    NonscriptSpace {
413        body: Box<Atom>,
414        remove: bool,
415    },
416    Kern(Dimension),
417    Sequence(Vec<Atom>),
418    InferredRow(Vec<Atom>),
419    ExplicitRow(Vec<Atom>),
420    Mrow(Box<Atom>),
421    NamedFunction(Box<Atom>),
422    // A literal normal mi with svg/texclass.go autoOP, distinct from
423    // native Identifier rows that may represent separate font tokens.
424    AutoOperator(Box<Atom>),
425    // Explicit mo spacing is owned by the outermost embellished wrapper.
426    MathMLSpace {
427        body: Box<Atom>,
428        left: Option<Dimension>,
429        right: Option<Dimension>,
430    },
431    ApplyFunction,
432    Identifier(Vec<Atom>),
433    OperatorToken(Vec<Atom>),
434    RawOperator {
435        attributes: &'static [(&'static str, &'static str)],
436        cleanup: bool,
437        code: u32,
438        body: Box<Atom>,
439        definition: operator_dictionary::Definition,
440        // An explicit source texClass property, which
441        // applyOperatorInheritance does not replace.
442        texclass: Option<i8>,
443    },
444    Number(Vec<Atom>),
445    Fraction(Box<Atom>, Box<Atom>),
446    GeneralFraction(Box<Atom>, Box<Atom>, general_fraction::Spec),
447    FractionStrut(f64),
448    HorizontalMark {
449        body: Box<Atom>,
450        code: u32,
451        stretchy: bool,
452        mathaccent: bool,
453    },
454    BracketMark {
455        body: Box<Atom>,
456        thickness: f64,
457        height: String,
458        under: bool,
459        mathsize: f64,
460    },
461    SplitFraction(Box<Atom>, Box<Atom>, f64),
462    Sqrt(Box<Atom>),
463    // \textbf/\textit: an mtext token whose characters take the math font
464    // variant mapping (only alphanumeric content is admitted).
465    StyledText(Vec<Atom>),
466    // Original tex/commands.go sqrt with an optional index: mroot(base, index).
467    // mathsize is resolved by styles::resolve_sizes; only 1 is laid out.
468    Root {
469        body: Box<Atom>,
470        index: Box<Atom>,
471        mathsize: f64,
472    },
473    SizedSqrt {
474        body: Box<Atom>,
475        mathsize: f64,
476    },
477    Operator(Box<Atom>),
478    MovesScripts(Box<Atom>),
479    ScriptPolicy {
480        body: Box<Atom>,
481        moves: bool,
482        movable: Option<bool>,
483        movable_property: bool,
484    },
485    Ord(Box<Atom>),
486    Class {
487        body: Box<Atom>,
488        class: usize,
489    },
490    Phantom(Box<Atom>),
491    Padded {
492        body: Box<Atom>,
493        padding: padded::Padding,
494    },
495    // mathtools \math*lap / \cramped*lap: an mstyle carrying an explicit
496    // data-cramped attribute, which svg handleAttributes copies.
497    CrampedStyle(Box<Atom>, bool),
498    DeclaredStyle {
499        body: Box<Atom>,
500        display: bool,
501        level: usize,
502    },
503    DeclaredSize {
504        body: Box<Atom>,
505        factor: f64,
506    },
507    Choice([Box<Atom>; 4]),
508    XArrow {
509        code: u32,
510        over: Box<Atom>,
511        under: Option<Box<Atom>>,
512    },
513    Text(String),
514    ColorBox {
515        body: Box<Atom>,
516        background: String,
517        mathsize: f64,
518    },
519    Color {
520        body: Box<Atom>,
521        color: String,
522    },
523    Cancel {
524        body: Box<Atom>,
525        up: bool,
526        down: bool,
527        arrow: bool,
528        options: enclose::Options,
529    },
530    FenceDelimiter {
531        code: u32,
532        class: usize,
533        color: Option<String>,
534    },
535    FixedDelimiter {
536        code: u32,
537        size: f64,
538    },
539    Fenced {
540        open: u32,
541        body: Vec<Atom>,
542        close: u32,
543        close_color: Option<String>,
544        stretchy: bool,
545        inner: bool,
546    },
547    Matrix {
548        spacing: Option<f64>,
549        options: Option<table::MultlineOptions>,
550        rows: Vec<Vec<Atom>>,
551        environment: String,
552        column_spec: String,
553    },
554    Multiscripts {
555        base: Box<Atom>,
556        sub: Box<Atom>,
557        sup: Box<Atom>,
558        post: Option<[Box<Atom>; 2]>,
559        prescript: bool,
560        mathsize: f64,
561    },
562    Scripts {
563        // Original parser distinguishes msub/msup from moving under/over nodes.
564        limits: bool,
565        // tex/script_attachment.go: parser-built compact families can be reused.
566        eager: bool,
567        accent: Option<accents::Spec>,
568        leading_space: f64,
569        base: Box<Atom>,
570        sub: Option<Box<Atom>>,
571        sup: Option<Box<Atom>>,
572    },
573}
574
575#[derive(Clone, Copy)]
576struct PositionedGlyph {
577    font_original: Option<u32>,
578    font_variant: &'static str,
579    bold: bool,
580    small_operator: bool,
581    variant: bool,
582    codepoint: u32,
583    unit: bool,
584    calligraphic: bool,
585    italic: bool,
586    x: f64,
587    baseline: f64,
588    scale: f64,
589    large: bool,
590    stretch: bool,
591    radical_variant: Option<usize>,
592    assembly_height: Option<(f64, f64)>,
593}
594
595#[derive(Clone, Copy)]
596struct TableLine {
597    x: f64,
598    x2: Option<f64>,
599    frame: bool,
600    y1: f64,
601    y2: f64,
602    dashed: bool,
603}
604struct LayoutGroup {
605    // Local SVG x and its paint-frame scale, before any scale round trip.
606    x_frame: Option<(f64, f64)>,
607    data_cramped: Option<bool>,
608    // moToSVG's own "translate(0 u)" (u in the node's units, already x1000)
609    // for symmetric/largeop centering; it replaces standardSVG's scale.
610    own_translate: Option<f64>,
611    accent_offset: Option<f64>,
612    box_border: Option<f64>,
613    reference: Option<String>,
614    tagged: Option<ams::TaggedLayout>,
615    percentage: Option<table::Percentage>,
616    table_line: Option<TableLine>,
617    mathsize: Option<f64>,
618    tex_class: usize,
619    before_glyph: usize,
620    scale: f64,
621    x: f64,
622    baseline: f64,
623    color: Option<String>,
624    background: Option<(String, f64, f64, f64)>,
625    kind: &'static str,
626    delimiter: Option<cd::Delimiter>,
627    arrow: Option<enclose::Arrow>,
628    body: Box<Layout>,
629    lines: Vec<(f64, f64, f64, f64, f64)>,
630}
631
632struct Layout {
633    bounds_em: Option<(f64, f64)>,
634    // Source BBox width in ems, separate from SVG paint-plan coordinates.
635    width_em: Option<f64>,
636    // BBox.W in the unscaled wrapper frame. Retain this before multiplying
637    // by the absolute paint scale; tables apply their row RScale separately.
638    intrinsic_width_em: Option<f64>,
639    width: f64,
640    ascent: f64,
641    depth: f64,
642    glyphs: Vec<PositionedGlyph>,
643    rules: Vec<(f64, f64, f64, f64)>,
644    groups: Vec<LayoutGroup>,
645}
646
647#[derive(Clone, Copy)]
648struct GlyphData {
649    height: f64,
650    depth: f64,
651    width: f64,
652    path: &'static str,
653}
654
655thread_local! {
656    // The mathcolor inherited at the current layout position.
657    static INHERITED_COLOR: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
658}
659
660fn is_large_operator(code: u32) -> bool {
661    matches!(code, 0x220F | 0x2211 | 0x222B)
662        || compound(code).is_some_and(|g| g.large.is_some())
663        // Other operator-dictionary largeop characters with -largeop and
664        // -smallop glyphs (tex/operator_dictionary_generated.go, font data).
665        || (operator_dictionary::lookup(code, operator_dictionary::Form::Prefix).flag("largeop")
666            && large_glyphs::LARGE_GLYPHS
667                .binary_search_by_key(&code, |g| g.codepoint)
668                .is_ok()
669            && smallop_glyphs::SMALL_OP_GLYPHS
670                .binary_search_by_key(&code, |g| g.codepoint)
671                .is_ok())
672}
673
674fn compound(code: u32) -> Option<&'static compound_glyphs::Compound> {
675    compound_glyphs::COMPOUNDS
676        .binary_search_by_key(&code, |g| g.codepoint)
677        .ok()
678        .map(|i| &compound_glyphs::COMPOUNDS[i])
679}
680
681fn uses_normal_text_fallback(codepoint: u32) -> bool {
682    matches!(codepoint, 0xB5 | 0x2103 | 0x2030)
683        || (compound(codepoint).is_none()
684            && glyphs::GLYPHS
685                .binary_search_by_key(&codepoint, |g| g.codepoint)
686                .is_err())
687}
688
689// Original svg/wrapper.go isCJK: unknown wide glyphs use one em;
690// other unknown glyphs use .6em, with common .75/.2 height/depth.
691fn unknown_glyph_width(codepoint: u32) -> f64 {
692    if matches!(codepoint, 0x1100..=0x115F | 0x2329 | 0x232A | 0x2E80..=0x303E
693        | 0x3040..=0x3247 | 0x3250..=0x4DBF | 0x4E00..=0xA4C6 | 0xA960..=0xA97C
694        | 0xAC00..=0xD7A3 | 0xF900..=0xFAFF | 0xFE10..=0xFE19 | 0xFE30..=0xFE6B
695        | 0xFF01..=0xFF60 | 0xFFE0..=0xFFE6 | 0x1B000..=0x1B001 | 0x1F200..=0x1F251
696        | 0x20000..=0x3FFFD)
697    {
698        1.0
699    } else {
700        0.6
701    }
702}
703
704fn glyph(codepoint: u32) -> Option<GlyphData> {
705    if let Some(g) = compound(codepoint) {
706        return Some(GlyphData {
707            height: g.height,
708            depth: g.depth,
709            width: g.width,
710            path: "",
711        });
712    }
713    // Original gensymb identities missing from the normal font use the
714    // SVG wrapper's non-CJK unknownText metrics, not mathematical mu or C.
715    if uses_normal_text_fallback(codepoint) {
716        return Some(GlyphData {
717            height: 0.75,
718            depth: 0.2,
719            width: unknown_glyph_width(codepoint),
720            path: "",
721        });
722    }
723    glyphs::GLYPHS
724        .binary_search_by_key(&codepoint, |glyph| glyph.codepoint)
725        .ok()
726        .map(|index| {
727            let glyph = glyphs::GLYPHS[index];
728            GlyphData {
729                height: glyph.height,
730                depth: glyph.depth,
731                width: glyph.width,
732                path: glyph.path,
733            }
734        })
735}
736
737fn smallop_glyph(codepoint: u32) -> Option<GlyphData> {
738    if compound(codepoint).is_some_and(|g| g.large.is_some()) {
739        return glyph(codepoint);
740    }
741
742    smallop_glyphs::SMALL_OP_GLYPHS
743        .binary_search_by_key(&codepoint, |g| g.codepoint)
744        .ok()
745        .map(|i| {
746            let g = smallop_glyphs::SMALL_OP_GLYPHS[i];
747            GlyphData {
748                height: g.height,
749                depth: g.depth,
750                width: g.width,
751                path: g.path,
752            }
753        })
754}
755fn variant_glyph(codepoint: u32) -> Option<GlyphData> {
756    tex_variant_glyphs::TEX_VARIANT_GLYPHS
757        .binary_search_by_key(&codepoint, |g| g.codepoint)
758        .ok()
759        .map(|i| {
760            let g = tex_variant_glyphs::TEX_VARIANT_GLYPHS[i];
761            GlyphData {
762                height: g.height,
763                depth: g.depth,
764                width: g.width,
765                path: g.path,
766            }
767        })
768        .or_else(|| glyph(codepoint))
769}
770fn glyph_for(item: PositionedGlyph) -> Option<GlyphData> {
771    if declaration_fonts::extended(item.font_variant) && !item.large && !item.small_operator {
772        return declaration_fonts::lookup(item.codepoint, item.font_variant);
773    }
774    if item.bold {
775        return double_struck::bold(item.codepoint).map(|r| r.0);
776    }
777    if item.large {
778        if let Some((h, d, w)) = compound(item.codepoint).and_then(|g| g.large) {
779            return Some(GlyphData {
780                height: h,
781                depth: d,
782                width: w,
783                path: "",
784            });
785        }
786    }
787
788    if item.small_operator {
789        return smallop_glyph(item.codepoint);
790    }
791    if item.variant {
792        return variant_glyph(item.codepoint);
793    }
794    if item.calligraphic {
795        return calligraphic_glyph(item.codepoint);
796    }
797    if item.italic {
798        return italic_glyph(item.codepoint);
799    }
800    if let Some((total, depth)) = item.assembly_height {
801        return Some(GlyphData {
802            height: total - depth,
803            depth,
804            width: 1.056,
805            path: "",
806        });
807    }
808    if let Some(index) = item.radical_variant {
809        return radical_glyphs::RADICAL_GLYPHS.get(index).copied();
810    }
811    if item.stretch {
812        return stretch_glyphs::STRETCH_GLYPHS.iter().find_map(|glyph| {
813            (glyph.codepoint == item.codepoint).then_some(GlyphData {
814                height: glyph.height,
815                depth: glyph.depth,
816                width: glyph.width,
817                path: glyph.path,
818            })
819        });
820    }
821    if item.large {
822        // Font.Lookup keeps the requested variant for Content descendants,
823        // even when the parent character falls back to normal-font data.
824        if let Some((height, depth, width)) = compound(item.codepoint).and_then(|g| g.large) {
825            return Some(GlyphData {
826                height,
827                depth,
828                width,
829                path: "",
830            });
831        }
832        return large_glyphs::LARGE_GLYPHS
833            .binary_search_by_key(&item.codepoint, |glyph| glyph.codepoint)
834            .ok()
835            .map(|index| {
836                let glyph = large_glyphs::LARGE_GLYPHS[index];
837                GlyphData {
838                    height: glyph.height,
839                    depth: glyph.depth,
840                    width: glyph.width,
841                    path: glyph.path,
842                }
843            })
844            .or_else(|| glyph(item.codepoint));
845    }
846    glyph(item.codepoint)
847}
848
849// Source parser.go parseCharacter and wrapper.go getVariant select italic for
850// one-rune mi. Exact own entries precede SMP remaps and normal inheritance.
851fn automatic_italic_atom(character: char) -> Atom {
852    let code = character as u32;
853    if italic_glyphs::ITALIC_GLYPHS
854        .binary_search_by_key(&code, |g| g.codepoint)
855        .is_ok()
856    {
857        return Atom::ItalicGlyph(code);
858    }
859    let code = italic_font_code(code);
860    if uses_normal_text_fallback(code) {
861        Atom::ItalicGlyph(character as u32)
862    } else {
863        Atom::Glyph(code)
864    }
865}
866
867// Original base/AMS mathchar0mi maps; default one-rune mi is italic unless
868// the source entry declares normal. hbar's variantForm is dispatched separately.
869fn source_identifier(name: &str) -> Option<(u32, bool)> {
870    Some((
871        match name {
872            "alpha" => 0x3B1,
873            "beta" => 0x3B2,
874            "gamma" => 0x3B3,
875            "delta" => 0x3B4,
876            "epsilon" => 0x3F5,
877            "zeta" => 0x3B6,
878            "eta" => 0x3B7,
879            "theta" => 0x3B8,
880            "iota" => 0x3B9,
881            "kappa" => 0x3BA,
882            "lambda" => 0x3BB,
883            "mu" => 0x3BC,
884            "nu" => 0x3BD,
885            "xi" => 0x3BE,
886            "omicron" => 0x3BF,
887            "pi" => 0x3C0,
888            "rho" => 0x3C1,
889            "varsigma" => 0x3C2,
890            "sigma" => 0x3C3,
891            "tau" => 0x3C4,
892            "upsilon" => 0x3C5,
893            "phi" => 0x3D5,
894            "chi" => 0x3C7,
895            "psi" => 0x3C8,
896            "omega" => 0x3C9,
897            "varepsilon" => 0x3B5,
898            "vartheta" => 0x3D1,
899            "varpi" => 0x3D6,
900            "varrho" => 0x3F1,
901            "varphi" => 0x3C6,
902            "varkappa" => 0x3F0,
903            "digamma" => 0x3DD,
904            "imath" => 0x131,
905            "jmath" => 0x237,
906            "hslash" => 0x210F,
907            "partial" => 0x2202,
908            "nabla" => 0x2207,
909            "backslash" => 0x2216,
910            "varGamma" => 0x393,
911            "varDelta" => 0x394,
912            "varTheta" => 0x398,
913            "varLambda" => 0x39B,
914            "varXi" => 0x39E,
915            "varPi" => 0x3A0,
916            "varSigma" => 0x3A3,
917            "varUpsilon" => 0x3A5,
918            "varPhi" => 0x3A6,
919            "varPsi" => 0x3A8,
920            "varOmega" => 0x3A9,
921            _ => return None,
922        },
923        matches!(name, "nabla" | "backslash"),
924    ))
925}
926
927fn command_codepoint(name: &str) -> Option<u32> {
928    let greek = [
929        ("alpha", 0x1D6FC),
930        ("beta", 0x1D6FD),
931        ("gamma", 0x1D6FE),
932        ("delta", 0x1D6FF),
933        ("epsilon", 0x1D700),
934        ("zeta", 0x1D701),
935        ("eta", 0x1D702),
936        ("theta", 0x1D703),
937        ("iota", 0x1D704),
938        ("kappa", 0x1D705),
939        ("lambda", 0x1D706),
940        ("mu", 0x1D707),
941        ("nu", 0x1D708),
942        ("xi", 0x1D709),
943        ("omicron", 0x1D70A),
944        ("pi", 0x1D70B),
945        ("rho", 0x1D70C),
946        ("varsigma", 0x1D70D),
947        ("sigma", 0x1D70E),
948        ("tau", 0x1D70F),
949        ("upsilon", 0x1D710),
950        ("phi", 0x1D711),
951        ("chi", 0x1D712),
952        ("psi", 0x1D713),
953        ("omega", 0x1D714),
954        ("Gamma", 0x393),
955        ("Delta", 0x394),
956        ("Theta", 0x398),
957        ("Lambda", 0x39B),
958        ("Xi", 0x39E),
959        ("Pi", 0x3A0),
960        ("Sigma", 0x3A3),
961        ("Upsilon", 0x3A5),
962        ("Phi", 0x3A6),
963        ("Psi", 0x3A8),
964        ("Omega", 0x3A9),
965    ];
966    greek
967        .iter()
968        .find(|(candidate, _)| *candidate == name)
969        .map(|(_, cp)| *cp)
970        .or_else(|| {
971            Some(match name {
972                "infty" => 0x221E,
973                "sum" => 0x2211,
974                "prod" => 0x220F,
975                "int" => 0x222B,
976                "pm" => 0x00B1,
977                "times" => 0x00D7,
978                "otimes" => 0x2297,
979                "cdot" => 0x22C5,
980                "le" | "leq" => 0x2264,
981                "ge" | "geq" => 0x2265,
982                "neq" => 0x2260,
983                "equiv" => 0x2261,
984                "circ" => 0x2218,
985                "approx" => 0x2248,
986                "sim" => 0x223C,
987                "in" => 0x2208,
988                "notin" => 0x2209,
989                "rightarrow" | "to" => 0x2192,
990                "leftarrow" => 0x2190,
991                "uparrow" => 0x2191,
992                "downarrow" => 0x2193,
993                "updownarrow" => 0x2195,
994                "Uparrow" => 0x21d1,
995                "Downarrow" => 0x21d3,
996                "Updownarrow" => 0x21d5,
997                "leftrightarrow" => 0x2194,
998                "Leftarrow" => 0x21D0,
999                "Rightarrow" => 0x21D2,
1000                "Leftrightarrow" => 0x21D4,
1001                "longleftarrow" => 0x27F5,
1002                "longrightarrow" => 0x27F6,
1003                "longleftrightarrow" => 0x27F7,
1004                "Longleftarrow" => 0x27F8,
1005                "Longrightarrow" => 0x27F9,
1006                "Longleftrightarrow" => 0x27FA,
1007                "longmapsto" => 0x27FC,
1008                "rightleftharpoons" => 0x21CC,
1009                "hookrightarrow" => 0x21AA,
1010                "hookleftarrow" => 0x21A9,
1011                "langle" => 0x27E8,
1012                "rangle" => 0x27E9,
1013                "vert" | "mid" => 0x2223,
1014                "partial" => 0x2202,
1015                "degree" => 0xB0,
1016                "ldots" => 0x2026,
1017                "cdots" => 0x22EF,
1018                "micro" => 0xB5,
1019                "ohm" => 0x2126,
1020                _ => return None,
1021            })
1022        })
1023}
1024
1025// tex/source_runtime.go lookupMJSourceEntry ignores maps without a parser
1026// (remap/not_remap) and only admits backslash-prefixed DelimiterMap keys.
1027// The retained source table also contains raw delimiter keys; those entries
1028// belong to readDelimiter's namespace and do not register commands.
1029fn command_symbol(name: &str) -> Option<&'static source_symbols::Symbol> {
1030    let symbol = source_symbols::lookup(name)?;
1031    if matches!(symbol.map, "remap" | "not_remap")
1032        || (symbol.parser == source_symbols::Parser::Delimiter
1033            && matches!(name, "(" | ")" | "[" | "]" | "<" | ">" | "/" | "."))
1034    {
1035        return None;
1036    }
1037    Some(symbol)
1038}
1039
1040fn resolve_named_color(color: String) -> String {
1041    named_colors::NAMED_COLORS
1042        .binary_search_by_key(&color.as_str(), |entry| entry.0)
1043        .ok()
1044        .map_or(color.clone(), |index| {
1045            named_colors::NAMED_COLORS[index].1.to_owned()
1046        })
1047}
1048
1049fn parse(expression: &str) -> Option<Atom> {
1050    let mut result = parse_unresolved(expression)?;
1051    if cd::first_error(&result).is_none() && cd::first_nil_child(&result).is_none() {
1052        table::inherit_columns(&mut result, 'c');
1053        ams::containers(&mut result, "center");
1054        styles::resolve_sizes(&mut result, 1.0);
1055        styles::resolve(&mut result, true, 0, false);
1056        if let Err(message) = nonscript::filter(&mut result, None) {
1057            return Some(Atom::SourceError(message));
1058        }
1059        operator_dictionary::inherit(&mut result, operator_dictionary::Form::Infix);
1060    }
1061    Some(result)
1062}
1063
1064// Inheritance selects mathchoice after the complete tree has been parsed.
1065// Nested cells and arrow labels must retain all four branches until then.
1066fn parse_unresolved(expression: &str) -> Option<Atom> {
1067    let shared = ams::Shared::default();
1068    let result = parse_unresolved_shared(expression, shared.clone())?;
1069    if cd::first_error(&result).is_none() && shared.borrow().current.tag.is_some() {
1070        let tag = ams::make_tag(&shared)?;
1071        return Some(Atom::TaggedTable {
1072            spacing: None,
1073            rows: vec![vec![result]],
1074            tags: vec![Some(tag)],
1075            environment: "equation-tag".into(),
1076            container_align: "center",
1077        });
1078    }
1079    Some(result)
1080}
1081fn parse_unresolved_shared(expression: &str, ams: ams::Shared) -> Option<Atom> {
1082    parse_with_stack(expression, ams, Default::default())
1083}
1084fn parse_with_stack(
1085    expression: &str,
1086    ams: ams::Shared,
1087    equation_seen: EquationStack,
1088) -> Option<Atom> {
1089    parse_with_root_stack(expression, ams, equation_seen, false, Default::default())
1090}
1091fn parse_with_root_stack(
1092    expression: &str,
1093    ams: ams::Shared,
1094    equation_seen: EquationStack,
1095    in_root: bool,
1096    root_moves: root_index::Shared,
1097) -> Option<Atom> {
1098    let mut parser = Parser {
1099        in_root,
1100        root_moves,
1101        physics_after: None,
1102        physics_auto: None,
1103        command_position: None,
1104        pending_cell: None,
1105        pending_infix: None,
1106        row_delimiter: None,
1107        active_color: None,
1108        equation_seen,
1109        array_cell: None,
1110        vector_alias: false,
1111        vector_font: None,
1112        ams,
1113        splice_inferred: false,
1114        chars: expression.chars().collect(),
1115        index: 0,
1116        active_font: None,
1117        normal_font: false,
1118        calligraphic_font: false,
1119        multi_letter_font: false,
1120        operator_letters: false,
1121        operator_pattern: false,
1122        no_auto_operator: false,
1123    };
1124    let result = parser.sequence(None)?;
1125    (parser.index == parser.chars.len()).then_some(result)
1126}
1127
1128type EquationStack = std::rc::Rc<std::cell::Cell<bool>>;
1129
1130struct Parser {
1131    in_root: bool,
1132    root_moves: root_index::Shared,
1133    physics_after: Option<physics::After>,
1134    physics_auto: Option<physics::AutoOpen>,
1135    command_position: Option<position::Position>,
1136    pending_cell: Option<array_body::PendingCell>,
1137    pending_infix: Option<general_fraction::PendingInfix>,
1138    row_delimiter: Option<braket::RowDelimiter>,
1139    active_color: Option<String>,
1140    equation_seen: EquationStack,
1141    array_cell: Option<array_body::CellState>,
1142    vector_alias: bool,
1143    vector_font: Option<bool>,
1144    ams: ams::Shared,
1145    splice_inferred: bool,
1146    chars: Vec<char>,
1147    index: usize,
1148    active_font: Option<&'static str>,
1149    normal_font: bool,
1150    calligraphic_font: bool,
1151    multi_letter_font: bool,
1152    operator_letters: bool,
1153    operator_pattern: bool,
1154    no_auto_operator: bool,
1155}
1156
1157impl Parser {
1158    // parser.go ambientFontToken/applyFontScope: only the creating parser's
1159    // eligible tokens inherit a MathFont/SetFont environment. Named mathchar0mi
1160    // symbols and already resolved inner scopes retain their own variants.
1161    fn ambient_font(&self, mut atom: Atom) -> Atom {
1162        if let Some(font) = self.active_font {
1163            declaration_fonts::apply_wrapper(&mut atom, font);
1164        }
1165        self.vector_font_token(atom)
1166    }
1167
1168    // parser.go applyFontScope's Go-only boldsymbol extension also selects
1169    // tokens without ambientFontSource. Resolve them in their creating parser
1170    // so an enclosing scope cannot overwrite an inner lexical font choice.
1171    fn nonambient_font(&self, atom: Atom) -> Atom {
1172        if self.active_font == Some("boldsymbol") {
1173            self.ambient_font(atom)
1174        } else {
1175            self.vector_font_token(atom)
1176        }
1177    }
1178
1179    fn sequence(&mut self, closing: Option<char>) -> Option<Atom> {
1180        self.sequence_with_infix(closing, false)
1181    }
1182
1183    fn sequence_with_infix(&mut self, closing: Option<char>, infix_pending: bool) -> Option<Atom> {
1184        self.sequence_with_prefix(closing, infix_pending, Vec::new())
1185    }
1186
1187    fn sequence_with_prefix(
1188        &mut self,
1189        closing: Option<char>,
1190        infix_pending: bool,
1191        prefix: Vec<Atom>,
1192    ) -> Option<Atom> {
1193        let initial_font = self.active_font;
1194        let initial_color = self.active_color.clone();
1195        let result = self.sequence_with_dots(closing, infix_pending, false, prefix);
1196        self.active_font = initial_font;
1197        self.active_color = initial_color;
1198        result
1199    }
1200
1201    fn style_sequence(&mut self, closing: Option<char>, infix_pending: bool) -> Option<Atom> {
1202        let initial_font = self.active_font;
1203        let result = self.sequence_with_dots(closing, infix_pending, true, Vec::new());
1204        self.active_font = initial_font;
1205        result
1206    }
1207
1208    fn sequence_with_dots(
1209        &mut self,
1210        closing: Option<char>,
1211        infix_pending: bool,
1212        style_pending: bool,
1213        mut children: Vec<Atom>,
1214    ) -> Option<Atom> {
1215        let mut dots = pending_dots::Pending::default();
1216        let mut positions: Vec<position::Position> = Vec::new();
1217        let mut closed = false;
1218        while self.index < self.chars.len()
1219            || self.physics_after.is_some()
1220            || self.pending_cell.is_some()
1221            || self.pending_infix.is_some()
1222            || self.row_delimiter.is_some()
1223        {
1224            // Over's arguments are read once before StyleItems close; the
1225            // enclosing logical row then owns the complete numerator.
1226            if self.pending_infix.is_some() {
1227                if style_pending {
1228                    break;
1229                }
1230                dots.finish(&mut positions, &mut children);
1231                if let Some(position) = positions.last() {
1232                    return Some(position.missing_box());
1233                }
1234                let item = self.pending_infix.take()?;
1235                if infix_pending {
1236                    self.index = self.chars.len();
1237                    return Some(Atom::ErrorDisplay(format!(
1238                        "Ambiguous use of \\{}",
1239                        item.name
1240                    )));
1241                }
1242                self.active_font = item.font;
1243                self.active_color = item.color;
1244                let right = self.sequence_with_infix(closing, true)?;
1245                if cd::first_error(&right).is_some() {
1246                    return Some(right);
1247                }
1248                let content = self.finish_infix(Atom::Sequence(children), right, item.spec)?;
1249                if cd::first_error(&content).is_some() {
1250                    self.index = self.chars.len();
1251                }
1252                if self.pending_cell.is_some() {
1253                    children = vec![content];
1254                    continue;
1255                }
1256                return Some(Atom::Sequence(vec![content]));
1257            }
1258            // parser.go replays the same closing CellItem after Style/Over
1259            // have delivered their final MML. A real group owns the event;
1260            // it must not consume its close brace while styles unwind.
1261            if self.pending_cell.is_some() {
1262                if style_pending || infix_pending {
1263                    break;
1264                }
1265                dots.finish(&mut positions, &mut children);
1266                if let Some(position) = positions.last() {
1267                    return Some(position.missing_box());
1268                }
1269                let item = self.pending_cell.take()?;
1270                if !item.linebreak {
1271                    self.index = self.chars.len();
1272                    return Some(Atom::ErrorDisplay("Misplaced \\cr".into()));
1273                }
1274                self.active_font = item.font;
1275                self.active_color = item.color;
1276                children.push(Atom::Sequence(item.cell.spaces()));
1277                continue;
1278            }
1279            if let Some(after) = self.physics_after.take() {
1280                let tail = self.physics_complete_after(after)?;
1281                if cd::first_error(&tail).is_some() {
1282                    self.index = self.chars.len();
1283                    return Some(tail);
1284                }
1285                let Atom::Sequence(nodes) = tail else {
1286                    unreachable!()
1287                };
1288                for node in nodes {
1289                    let mut delivered = dots.deliver(&mut positions, node);
1290                    if let Some(last) = delivered.pop() {
1291                        children.extend(delivered);
1292                        let node = self.attach_scripts(last)?;
1293                        if children.last().is_some_and(physics::named_function)
1294                            && physics::accepts_application(&node)
1295                        {
1296                            children.push(Atom::ApplyFunction);
1297                        }
1298                        children.push(node);
1299                    }
1300                }
1301                continue;
1302            }
1303            if self.physics_auto.as_ref().is_some_and(|a| a.closed) {
1304                break;
1305            }
1306            // Right/Middle close every continuation before Left receives
1307            // the saved delimiter and its original lexical color.
1308            if self.row_delimiter.is_some() {
1309                break;
1310            }
1311            if closing.is_some_and(|value| self.chars[self.index] == value) {
1312                self.index += 1;
1313                closed = true;
1314                break;
1315            }
1316            if self.chars[self.index] == '}' && self.physics_auto.is_some() {
1317                return Some(physics::AutoOpen::stop_error());
1318            }
1319            if self.chars[self.index] == '}' {
1320                self.index = self.chars.len();
1321                return Some(Atom::ErrorDisplay(
1322                    "Extra close brace or missing open brace".to_owned(),
1323                ));
1324            }
1325            // Original parseRow handles syntax before raw character tokens.
1326            if matches!(self.chars[self.index], '&' | '#') {
1327                if self.chars[self.index] == '&' {
1328                    if let Some(position) = positions.last() {
1329                        self.index = self.chars.len();
1330                        return Some(position.missing_box());
1331                    }
1332                }
1333                if self.chars[self.index] == '&' && closing.is_none() {
1334                    if let Some(cell) = &mut self.array_cell {
1335                        cell.stop = Some(array_body::CellItem::entry());
1336                        self.index += 1;
1337                        break;
1338                    }
1339                }
1340                let message = if self.chars[self.index] == '&' {
1341                    "Misplaced &"
1342                } else {
1343                    "You can't use 'macro parameter character #' in math mode"
1344                };
1345                self.index = self.chars.len();
1346                return Some(Atom::ErrorDisplay(message.to_owned()));
1347            }
1348            if self.chars[self.index] == '%' {
1349                while self.index < self.chars.len() {
1350                    let c = self.chars[self.index];
1351                    self.index += 1;
1352                    if matches!(c, '\n' | '\r') {
1353                        break;
1354                    }
1355                }
1356                continue;
1357            }
1358            // Base's special map consumes ASCII space/tab/CR/LF and NBSP.
1359            // Other Unicode spaces are ordinary tokens and keep font metrics.
1360            if matches!(self.chars[self.index], ' ' | '\t' | '\r' | '\n' | '\u{a0}') {
1361                self.index += 1;
1362                continue;
1363            }
1364            if self.chars[self.index] == '\\' {
1365                let name: String = self.chars[self.index + 1..]
1366                    .iter()
1367                    .take_while(|c| c.is_ascii_alphabetic())
1368                    .collect();
1369                if self.paired_definition(&name).is_none() {
1370                    if !self.ams.borrow().macros.contains_key(&name) {
1371                        if name == "nonscript" {
1372                            self.index += name.len() + 1;
1373                            dots.finish(&mut positions, &mut children);
1374                            if let Some(last) = children.last_mut() {
1375                                pending_dots::finish_function(last);
1376                            }
1377                            dots = pending_dots::Pending::start_nonscript();
1378                            continue;
1379                        }
1380                        if name == "not" {
1381                            self.index += name.len() + 1;
1382                            dots.finish(&mut positions, &mut children);
1383                            if let Some(last) = children.last_mut() {
1384                                pending_dots::finish_function(last);
1385                            }
1386                            dots = pending_dots::Pending::start_not();
1387                            continue;
1388                        }
1389                        if name == "dots" {
1390                            self.index += name.len() + 1;
1391                            dots.finish(&mut positions, &mut children);
1392                            if let Some(last) = children.last_mut() {
1393                                pending_dots::finish_function(last);
1394                            }
1395                            dots = pending_dots::Pending::start(self);
1396                            continue;
1397                        }
1398                        // These stack items are non-MML successors. Left/Open
1399                        // retain Dots until their completed fenced/group node.
1400                        if matches!(
1401                            name.as_str(),
1402                            "not" | "nonscript" | "raise" | "lower" | "moveleft" | "moveright"
1403                        ) {
1404                            dots.finish(&mut positions, &mut children);
1405                        }
1406                    }
1407                    if matches!(name.as_str(), "hline" | "hdashline")
1408                        && !self.ams.borrow().macros.contains_key(&name)
1409                    {
1410                        let rules = self
1411                            .array_cell
1412                            .as_ref()
1413                            .filter(|cell| {
1414                                closing.is_none()
1415                                    && !dots.active()
1416                                    && cell.rule_allowed
1417                                    && cell.at_start
1418                                    && children.is_empty()
1419                            })
1420                            .and_then(|cell| cell.rules.clone());
1421                        let Some(rules) = rules else {
1422                            self.index = self.chars.len();
1423                            return Some(Atom::ErrorDisplay(format!("Misplaced \\{name}")));
1424                        };
1425                        if let Some(e) = self.array_cell.as_ref().and_then(|c| c.equation.as_ref())
1426                        {
1427                            rules.borrow_mut().rows = e.borrow().rows.len();
1428                        }
1429                        rules.borrow_mut().add(&name);
1430                        self.index += name.len() + 1;
1431                        continue;
1432                    }
1433                    if hfill::is_fill(&name) && !self.ams.borrow().macros.contains_key(&name) {
1434                        self.index += name.len() + 1;
1435                        let allowed = closing.is_none()
1436                            && !infix_pending
1437                            && self.physics_auto.is_none()
1438                            && positions.is_empty()
1439                            && !dots.active()
1440                            && !children.last().is_some_and(physics::named_function)
1441                            && self
1442                                .array_cell
1443                                .as_ref()
1444                                .is_some_and(|cell| !cell.fills.blocked);
1445                        if !allowed {
1446                            self.index = self.chars.len();
1447                            return Some(hfill::unsupported(&name));
1448                        }
1449                        self.array_cell.as_mut()?.fills.push(children.len());
1450                        continue;
1451                    }
1452                    if alignment::is_command(&name) {
1453                        self.index += name.len() + 1;
1454                        match self.equation_command(
1455                            &name,
1456                            &mut children,
1457                            closing.is_none() && !dots.active(),
1458                        ) {
1459                            Ok(true) => {}
1460                            Ok(false) => return None,
1461                            Err(error) => {
1462                                self.index = self.chars.len();
1463                                return Some(Atom::ErrorDisplay(error));
1464                            }
1465                        }
1466                        continue;
1467                    }
1468                    if matches!(name.as_str(), "shoveleft" | "shoveright") {
1469                        if dots.active() {
1470                            return Some(Atom::ErrorDisplay(format!(
1471                                "\\{name} only allowed in multline environment"
1472                            )));
1473                        }
1474                        if let Some(cell) = &mut self.array_cell {
1475                            if matches!(cell.environment.as_str(), "multline" | "multline*")
1476                                && cell.shove_allowed
1477                            {
1478                                if !cell.at_start || !children.is_empty() {
1479                                    return Some(Atom::ErrorDisplay(format!(
1480                                        "\\{name} must come at the beginning of the line"
1481                                    )));
1482                                }
1483                                cell.shove =
1484                                    Some(if name == "shoveleft" { "left" } else { "right" });
1485                                self.index += name.len() + 1;
1486                                continue;
1487                            }
1488                        }
1489                    }
1490                    if matches!(name.as_str(), "right" | "middle")
1491                        && !self.ams.borrow().macros.contains_key(&name)
1492                    {
1493                        self.index += name.len() + 1;
1494                        let delimiter = match self.native_delimiter(&name, false) {
1495                            Ok(code) => code,
1496                            Err(error) => return Some(Atom::ErrorDisplay(error)),
1497                        };
1498                        if closing != Some('\0') || self.physics_auto.is_some() {
1499                            return Some(Atom::ErrorDisplay(if name == "middle" {
1500                                "Extra \\middle".into()
1501                            } else {
1502                                "Missing \\left or extra \\right".into()
1503                            }));
1504                        }
1505                        self.row_delimiter = Some(braket::RowDelimiter {
1506                            middle: name == "middle",
1507                            delimiter,
1508                            color: self.active_color.clone(),
1509                        });
1510                        break;
1511                    }
1512                    if general_fraction::is_infix(&name)
1513                        && !self.ams.borrow().macros.contains_key(&name)
1514                    {
1515                        self.index += name.len() + 1;
1516                        // BaseMethods.Over reads both delimiters and the dimension
1517                        // before the pending OverItem checks ambiguity.
1518                        let spec = match self.read_infix_spec(&name) {
1519                            Ok(spec) => spec,
1520                            Err(error) => {
1521                                self.index = self.chars.len();
1522                                return Some(Atom::ErrorDisplay(error));
1523                            }
1524                        };
1525                        self.pending_infix = Some(general_fraction::PendingInfix {
1526                            name,
1527                            spec,
1528                            font: self.active_font,
1529                            color: self.active_color.clone(),
1530                        });
1531                        continue;
1532                    }
1533                    if matches!(name.as_str(), "uproot" | "leftroot")
1534                        && !self.ams.borrow().macros.contains_key(&name)
1535                    {
1536                        self.index += name.len() + 1;
1537                        if let Err(message) = self.move_root(&name) {
1538                            self.index = self.chars.len();
1539                            return Some(Atom::ErrorDisplay(message));
1540                        }
1541                        continue;
1542                    }
1543                    if declaration_fonts::declaration(&name)
1544                        && !self.ams.borrow().macros.contains_key(&name)
1545                    {
1546                        self.index += name.len() + 1;
1547                        if let Some(cell) = &mut self.array_cell {
1548                            cell.at_start &= children.is_empty();
1549                        }
1550                        let previous = self.active_font;
1551                        self.active_font = Some(declaration_fonts::font_name(&name)?);
1552                        if dots.active() {
1553                            continue;
1554                        }
1555                        if let Some(cell) = &mut self.array_cell {
1556                            cell.fills.offset += children.len();
1557                        }
1558                        // SetFont adds no stack item: its continuation keeps
1559                        // the enclosing StyleItem as the closing recipient.
1560                        let body = self.sequence_with_dots(
1561                            closing,
1562                            infix_pending,
1563                            style_pending,
1564                            Vec::new(),
1565                        );
1566                        if let Some(cell) = &mut self.array_cell {
1567                            cell.fills.offset -= children.len();
1568                        }
1569                        self.active_font = previous;
1570                        let body = body?;
1571                        if let Atom::Sequence(v) = body {
1572                            // SetFont continues the same row. A pending FnItem
1573                            // observes its first final child across this boundary.
1574                            if children.last().is_some_and(physics::named_function)
1575                                && v.first().is_some_and(physics::accepts_application)
1576                            {
1577                                children.push(Atom::ApplyFunction);
1578                            }
1579                            for atom in v {
1580                                children.extend(dots.deliver(&mut positions, atom));
1581                            }
1582                        } else {
1583                            children.extend(dots.deliver(&mut positions, body));
1584                        }
1585                        if let Some(position) = positions.last() {
1586                            return Some(position.missing_box());
1587                        }
1588                        if self.pending_cell.is_some() || self.pending_infix.is_some() {
1589                            continue;
1590                        }
1591                        return Some(Atom::Sequence(children));
1592                    }
1593                    if matches!(name.as_str(), "limits" | "nolimits") {
1594                        self.index += name.len() + 1;
1595                        if dots.active() {
1596                            self.index = self.chars.len();
1597                            return Some(Atom::ErrorDisplay(format!(
1598                                "\\{name} is allowed only on operators"
1599                            )));
1600                        }
1601                        match limits::set_limits(children.pop(), &name) {
1602                            Ok(base) => children.push(base),
1603                            Err(message) => {
1604                                self.index = self.chars.len();
1605                                return Some(Atom::ErrorDisplay(message));
1606                            }
1607                        }
1608                        continue;
1609                    }
1610                    if let Some(factor) = styles::size_declaration(&name) {
1611                        dots.finish(&mut positions, &mut children);
1612                        if let Some(cell) = &mut self.array_cell {
1613                            cell.shove_allowed = false;
1614                            cell.fills.blocked = true;
1615                            cell.rule_allowed = false;
1616                            if cell.cd_end.is_some() {
1617                                cell.cd_end = Some(true);
1618                            }
1619                        }
1620                        self.index += name.len() + 1;
1621                        let body = self.style_sequence(closing, infix_pending)?;
1622                        children.extend(dots.deliver(
1623                            &mut positions,
1624                            Atom::DeclaredSize {
1625                                body: Box::new(body),
1626                                factor,
1627                            },
1628                        ));
1629                        if self.pending_cell.is_some() || self.pending_infix.is_some() {
1630                            continue;
1631                        }
1632                        return Some(Atom::Sequence(children));
1633                    }
1634                    if let Some((display, level)) = styles::declaration(&name) {
1635                        dots.finish(&mut positions, &mut children);
1636                        if let Some(cell) = &mut self.array_cell {
1637                            cell.shove_allowed = false;
1638                            cell.fills.blocked = true;
1639                            cell.rule_allowed = false;
1640                            if cell.cd_end.is_some() {
1641                                cell.cd_end = Some(true);
1642                            }
1643                        }
1644                        self.index += name.len() + 1;
1645                        let body = self.style_sequence(closing, infix_pending)?;
1646                        children.extend(dots.deliver(
1647                            &mut positions,
1648                            Atom::DeclaredStyle {
1649                                body: Box::new(body),
1650                                display,
1651                                level,
1652                            },
1653                        ));
1654                        if self.pending_cell.is_some() || self.pending_infix.is_some() {
1655                            continue;
1656                        }
1657                        return Some(Atom::Sequence(children));
1658                    }
1659                }
1660            }
1661            let command: String = self.chars[self.index..].iter().take(7).collect();
1662            if command.starts_with(r"\color")
1663                && self.paired_definition("color").is_none()
1664                && self
1665                    .chars
1666                    .get(self.index + 6)
1667                    .is_none_or(|c| !c.is_ascii_alphabetic())
1668            {
1669                self.index += 6;
1670                let color = resolve_named_color(self.braced_text()?);
1671                if let Some(cell) = &mut self.array_cell {
1672                    cell.rule_allowed = false;
1673                    cell.fills.blocked = true;
1674                }
1675                dots.finish(&mut positions, &mut children);
1676                let previous_color = self.active_color.replace(color.clone());
1677                let body = self.style_sequence(closing, infix_pending);
1678                self.active_color = previous_color;
1679                let body = body?;
1680                children.extend(dots.deliver(
1681                    &mut positions,
1682                    Atom::Color {
1683                        body: Box::new(body),
1684                        color,
1685                    },
1686                ));
1687                if self.pending_cell.is_some() || self.pending_infix.is_some() {
1688                    continue;
1689                }
1690                return Some(Atom::Sequence(children));
1691            }
1692            if self.chars[self.index] == '\\' {
1693                let name: String = self.chars[self.index + 1..]
1694                    .iter()
1695                    .take_while(|c| c.is_ascii_alphabetic())
1696                    .collect();
1697                if matches!(name.as_str(), "ce" | "pu") && self.paired_definition(&name).is_none() {
1698                    self.index += name.len() + 1;
1699                    if let Err(message) = self.insert_chemistry(&name) {
1700                        self.index = self.chars.len();
1701                        return Some(Atom::ErrorDisplay(message));
1702                    }
1703                    continue;
1704                }
1705            }
1706            if matches!(self.chars[self.index], '\'' | '\u{2019}') {
1707                if dots.active() {
1708                    dots.finish(&mut positions, &mut children);
1709                    children.push(Atom::Identifier(Vec::new()));
1710                }
1711                let base = children
1712                    .pop()
1713                    .unwrap_or_else(|| Atom::Identifier(Vec::new()));
1714                let atom = self.attach_primes(base)?;
1715                if cd::first_error(&atom).is_some() {
1716                    self.index = self.chars.len();
1717                    return Some(atom);
1718                }
1719                children.push(atom);
1720                continue;
1721            }
1722            if matches!(self.chars[self.index], '_' | '^') {
1723                if dots.active() {
1724                    dots.finish(&mut positions, &mut children);
1725                    // Stack.Prev on DotsItem sees no stored MML. Scripts and
1726                    // primes receive a fresh empty mi, not the emitted dots.
1727                    children.push(Atom::Identifier(Vec::new()));
1728                }
1729                let base = children
1730                    .pop()
1731                    .unwrap_or_else(|| Atom::Identifier(Vec::new()));
1732                let atom = self.attach_scripts(base)?;
1733                if cd::first_error(&atom).is_some() {
1734                    self.index = self.chars.len();
1735                    return Some(atom);
1736                }
1737                children.push(atom);
1738                continue;
1739            }
1740            let autoclose = self
1741                .chars
1742                .get(self.index)
1743                .copied()
1744                .filter(|c| matches!(c, ')' | ']' | '|'));
1745            let position_close = !positions.is_empty() && self.position_linebreak();
1746            let atom = self.atom()?;
1747            if self
1748                .array_cell
1749                .as_ref()
1750                .is_some_and(|cell| cell.stop.is_some())
1751            {
1752                break;
1753            }
1754            // A source parser error aborts parsing before missing group closes
1755            // or later commands can replace the earliest diagnostic.
1756            if cd::first_error(&atom).is_some() {
1757                self.index = self.chars.len();
1758                return Some(atom);
1759            }
1760            if position_close {
1761                self.index = self.chars.len();
1762                return Some(positions.last()?.missing_box());
1763            }
1764            if self.pending_cell.is_some() {
1765                continue;
1766            }
1767            if let Some(position) = self.command_position.take() {
1768                positions.push(position);
1769                continue;
1770            }
1771            if std::mem::take(&mut self.splice_inferred) {
1772                if let Atom::Sequence(v) = atom {
1773                    for item in v {
1774                        for delivered in dots.deliver(&mut positions, item) {
1775                            if children.last().is_some_and(physics::named_function)
1776                                && physics::accepts_application(&delivered)
1777                            {
1778                                children.push(Atom::ApplyFunction);
1779                            }
1780                            children.push(delivered);
1781                        }
1782                    }
1783                    continue;
1784                }
1785            }
1786            let atom = if !positions.is_empty() && physics::named_function(&atom) {
1787                self.attach_scripts(atom)?
1788            } else {
1789                atom
1790            };
1791            let mut delivered = dots.deliver(&mut positions, atom);
1792            if let Some(auto) = &mut self.physics_auto {
1793                delivered.retain_mut(|item| {
1794                    if auto.closed {
1795                        auto.trailing.push(item.clone());
1796                        false
1797                    } else {
1798                        !auto.accept(item, autoclose)
1799                    }
1800                });
1801                if auto.closed {
1802                    children.extend(delivered);
1803                    break;
1804                }
1805            }
1806            let atom = self.attach_scripts(delivered.pop()?)?;
1807            children.extend(delivered);
1808            if cd::first_error(&atom).is_some() {
1809                self.index = self.chars.len();
1810                return Some(atom);
1811            }
1812            if children.last().is_some_and(physics::named_function)
1813                && physics::accepts_application(&atom)
1814            {
1815                children.push(Atom::ApplyFunction);
1816            }
1817            children.push(atom);
1818        }
1819        dots.finish(&mut positions, &mut children);
1820        // parseRow reports a missing terminator when the input ends first; a
1821        // nested group's consumed close brace does not close this row.
1822        if let Some(position) = positions.last() {
1823            return Some(position.missing_box());
1824        }
1825        if closing.is_some()
1826            && closing != Some('\0')
1827            && !closed
1828            && self.pending_cell.is_none()
1829            && self.pending_infix.is_none()
1830            && !self.physics_auto.as_ref().is_some_and(|a| a.closed)
1831        {
1832            return Some(Atom::ErrorDisplay(
1833                "Extra open brace or missing close brace".to_owned(),
1834            ));
1835        }
1836        if closing.is_none() {
1837            if let Some(cell) = &mut self.array_cell {
1838                if cell.stop.is_none() && cell.cd_end.take() == Some(true) {
1839                    children.push(Atom::Strut(850., 200., "mpadded"));
1840                }
1841            }
1842        }
1843        Some(Atom::Sequence(children))
1844    }
1845
1846    fn insert_chemistry(&mut self, name: &str) -> Result<(), String> {
1847        let raw = self.padded_raw_argument(name)?;
1848        let expansion = mhchem::to_tex(&raw, name).map_err(|error| error.message)?;
1849        self.chars.splice(self.index..self.index, expansion.chars());
1850        Ok(())
1851    }
1852
1853    // TexParser.GetNext uses ECMAScript whitespace, not Unicode White_Space.
1854    fn prime_space(c: &char) -> bool {
1855        matches!(*c, '\t'..='\r' | ' ' | '\u{a0}' | '\u{1680}' |
1856            '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
1857            '\u{205f}' | '\u{3000}' | '\u{feff}')
1858    }
1859
1860    // tex/pending_prime.go retains the original base until the next item.
1861    // An immediately following script consumes the pending prime token.
1862    fn attach_primes(&mut self, atom: Atom) -> Option<Atom> {
1863        self.index += 1;
1864        let mut count = 1;
1865        loop {
1866            while self.chars.get(self.index).is_some_and(Self::prime_space) {
1867                self.index += 1;
1868            }
1869            if !self
1870                .chars
1871                .get(self.index)
1872                .is_some_and(|c| matches!(c, '\'' | '\u{2019}'))
1873            {
1874                break;
1875            }
1876            self.index += 1;
1877            count += 1;
1878        }
1879        // HFill observes the pending PrimeItem before it is reduced to MML.
1880        if self.chars.get(self.index) == Some(&'\\') {
1881            let name: String = self.chars[self.index + 1..]
1882                .iter()
1883                .take_while(|c| c.is_ascii_alphabetic())
1884                .collect();
1885            if hfill::is_fill(&name)
1886                && self.paired_definition(&name).is_none()
1887                && !self.ams.borrow().macros.contains_key(&name)
1888            {
1889                self.index = self.chars.len();
1890                return Some(hfill::unsupported(&name));
1891            }
1892        }
1893        // attachPrimes creates an ORD operator token. The named \prime
1894        // command is an identifier; preserve that distinct origin.
1895        let prime = Atom::OperatorToken(match count {
1896            1 => vec![Atom::Glyph(0x2032)],
1897            2 => vec![Atom::Glyph(0x2033)],
1898            3 => vec![Atom::Glyph(0x2034)],
1899            4 => vec![Atom::Glyph(0x2057)],
1900            _ => (0..count).map(|_| Atom::Glyph(0x2032)).collect(),
1901        });
1902        // Node properties do not hide the original script kind.
1903        let atom = match atom {
1904            Atom::ScriptPolicy { body, .. }
1905                if matches!(body.as_ref(), Atom::Scripts { limits: false, .. }) =>
1906            {
1907                *body
1908            }
1909            atom => atom,
1910        };
1911        if matches!(
1912            &atom,
1913            Atom::Scripts {
1914                limits: false,
1915                sup: Some(_),
1916                eager,
1917                sub,
1918                ..
1919            } if *eager || sub.is_some()
1920        ) {
1921            return Some(Atom::ErrorDisplay(
1922                "Prime causes double exponent: use braces to clarify".into(),
1923            ));
1924        }
1925        if self
1926            .chars
1927            .get(self.index)
1928            .is_some_and(|c| matches!(c, '^' | '_'))
1929        {
1930            let marker = self.chars[self.index];
1931            let mut result = self.attach_script_items(atom, true)?;
1932            if let Atom::Scripts { sup, .. } = &mut result {
1933                if marker == '^' {
1934                    if let Some(script) = sup.take() {
1935                        *sup = Some(Box::new(Atom::InferredRow(vec![prime, *script])));
1936                    }
1937                } else {
1938                    *sup = Some(Box::new(prime));
1939                }
1940            }
1941            return Some(result);
1942        }
1943        Some(match atom {
1944            Atom::Scripts {
1945                limits: false,
1946                base,
1947                sub,
1948                sup: None,
1949                leading_space,
1950                ..
1951            } => Atom::Scripts {
1952                limits: false,
1953                accent: None,
1954                base,
1955                sub,
1956                sup: Some(Box::new(prime)),
1957                leading_space,
1958                eager: true,
1959            },
1960            base => Atom::Scripts {
1961                limits: false,
1962                accent: None,
1963                eager: true,
1964                leading_space: 0.,
1965                base: Box::new(base),
1966                sub: None,
1967                sup: Some(Box::new(prime)),
1968            },
1969        })
1970    }
1971
1972    fn attach_scripts(&mut self, atom: Atom) -> Option<Atom> {
1973        self.attach_script_items(atom, false)
1974    }
1975
1976    fn attach_script_items(&mut self, atom: Atom, first_only: bool) -> Option<Atom> {
1977        if !self
1978            .chars
1979            .get(self.index)
1980            .is_some_and(|c| matches!(c, '_' | '^'))
1981        {
1982            return Some(atom);
1983        }
1984        let atom = match atom {
1985            Atom::ScriptPolicy {
1986                body,
1987                moves,
1988                movable,
1989                movable_property,
1990            } => {
1991                match *body {
1992                    Atom::Scripts {
1993                        base,
1994                        sub,
1995                        sup,
1996                        limits,
1997                        accent,
1998                        eager,
1999                        leading_space,
2000                    } if !limits || moves && (eager || sub.is_some()) => {
2001                        // setLimits has already selected the node family. Keep
2002                        // authored under accents when the existing owner is reused.
2003                        Atom::Scripts {
2004                            base,
2005                            eager: eager || sub.is_some(),
2006                            sub,
2007                            sup,
2008                            limits,
2009                            accent,
2010                            leading_space,
2011                        }
2012                    }
2013                    body @ Atom::Multiscripts {
2014                        prescript: true, ..
2015                    } if !moves => body,
2016                    body @ Atom::XArrow { .. } => body,
2017                    body => Atom::ScriptPolicy {
2018                        body: Box::new(body),
2019                        moves,
2020                        movable,
2021                        movable_property,
2022                    },
2023                }
2024            }
2025            atom => atom,
2026        };
2027        // script_attachment.go checks occupied authored under/over slots even
2028        // when movesupsub is absent and the next script needs a new owner.
2029        if let Atom::Scripts {
2030            sub: Some(_),
2031            sup,
2032            limits: true,
2033            eager: false,
2034            accent,
2035            ..
2036        } = &atom
2037            && !accent.is_some_and(|spec| spec.enabled)
2038        {
2039            let marker = self.chars[self.index];
2040            if marker == '_' || sup.is_some() {
2041                return Some(Atom::ErrorDisplay(
2042                    if marker == '_' {
2043                        "Double subscripts: use braces to clarify"
2044                    } else {
2045                        "Double exponent: use braces to clarify"
2046                    }
2047                    .into(),
2048                ));
2049            }
2050        }
2051        let (mut atom, mut sub, mut sup, limits, accent) = match atom {
2052            Atom::Multiscripts {
2053                base,
2054                sub,
2055                sup,
2056                post,
2057                prescript: true,
2058                mathsize,
2059            } => {
2060                let [post_sub, post_sup] = post.unwrap_or_else(multiscripts::empty_pair);
2061                let present =
2062                    |a: Box<Atom>| (!matches!(a.as_ref(), Atom::EmptyNode("none"))).then_some(a);
2063                (
2064                    Atom::Multiscripts {
2065                        base,
2066                        sub,
2067                        sup,
2068                        post: None,
2069                        prescript: true,
2070                        mathsize,
2071                    },
2072                    present(post_sub),
2073                    present(post_sup),
2074                    false,
2075                    None,
2076                )
2077            }
2078            Atom::Scripts {
2079                base,
2080                sub,
2081                sup,
2082                limits,
2083                accent,
2084                eager,
2085                ..
2086            } if eager || !limits && sub.is_some() && accent.is_none() => {
2087                (*base, sub, sup, limits, accent)
2088            }
2089            atom => {
2090                let limits = script_moves(&atom);
2091                (atom, None, None, limits, None)
2092            }
2093        };
2094        while self.index < self.chars.len() && matches!(self.chars[self.index], '_' | '^') {
2095            let marker = self.chars[self.index];
2096            self.index += 1;
2097            while self.chars.get(self.index).is_some_and(Self::prime_space) {
2098                self.index += 1;
2099            }
2100            // script_argument.go inserts a boundary after an immediate digit;
2101            // subsequent font/macro continuation retains the full number scanner.
2102            if self.chars.get(self.index).is_some_and(char::is_ascii_digit) {
2103                self.chars.insert(self.index + 1, ' ');
2104            }
2105            let duplicate = if marker == '_' {
2106                sub.is_some()
2107            } else {
2108                sup.is_some()
2109            };
2110            if duplicate {
2111                self.index = self.chars.len();
2112                return Some(Atom::ErrorDisplay(
2113                    if marker == '_' {
2114                        "Double subscripts: use braces to clarify"
2115                    } else {
2116                        "Double exponent: use braces to clarify"
2117                    }
2118                    .into(),
2119                ));
2120            }
2121            let script = loop {
2122                while self.chars.get(self.index).is_some_and(Self::prime_space) {
2123                    self.index += 1;
2124                }
2125                if self.index == self.chars.len() {
2126                    return Some(Atom::ErrorDisplay(
2127                        "Missing superscript or subscript argument".to_owned(),
2128                    ));
2129                }
2130                let braced = self.chars.get(self.index) == Some(&'{');
2131                if self.chars.get(self.index) == Some(&'\\') {
2132                    let start = self.index;
2133                    self.index += 1;
2134                    let name = self.capture_control_sequence();
2135                    self.index = start;
2136                    // script_argument.go: SetSize and SetStyle push stack items
2137                    // that a pending SubsupItem cannot accept without a group.
2138                    if self.paired_definition(&name).is_none()
2139                        && (matches!(name.as_str(), "dots" | "not" | "nonscript")
2140                            && !self.ams.borrow().macros.contains_key(&name)
2141                            || styles::size_declaration(&name).is_some()
2142                            || matches!(
2143                                name.as_str(),
2144                                "displaystyle" | "textstyle" | "scriptstyle" | "scriptscriptstyle"
2145                            ))
2146                    {
2147                        return Some(Atom::ErrorDisplay(format!(
2148                            "Missing open brace for {}script",
2149                            if marker == '_' { "sub" } else { "super" }
2150                        )));
2151                    }
2152                }
2153                let script = if self.chars.get(self.index) == Some(&'}') {
2154                    return Some(Atom::ErrorDisplay(
2155                        "Extra close brace or missing open brace".into(),
2156                    ));
2157                } else if self
2158                    .chars
2159                    .get(self.index)
2160                    .is_some_and(|c| matches!(c, '^' | '_' | '&' | '\'' | '\u{2019}'))
2161                {
2162                    // script_argument.go: another pending stack item cannot fill
2163                    // SubsupItem. Check occupied slots before its missing-open error.
2164                    let next = self.chars[self.index];
2165                    let duplicate =
2166                        (next == '_' && sub.is_some()) || (next == '^' && sup.is_some());
2167                    return Some(Atom::ErrorDisplay(if duplicate {
2168                        if next == '_' {
2169                            "Double subscripts: use braces to clarify"
2170                        } else {
2171                            "Double exponent: use braces to clarify"
2172                        }
2173                        .into()
2174                    } else {
2175                        format!(
2176                            "Missing open brace for {}script",
2177                            if marker == '_' { "sub" } else { "super" }
2178                        )
2179                    }));
2180                } else {
2181                    self.atom_or_group()?
2182                };
2183                if self.command_position.take().is_some() {
2184                    return Some(Atom::ErrorDisplay(format!(
2185                        "Missing open brace for {}script",
2186                        if marker == '_' { "sub" } else { "super" }
2187                    )));
2188                }
2189                // Source parseScriptArgument retains a braced ORD TeXAtom,
2190                // unlike the ordinary parsed arguments of stackrel.
2191                let script = if braced {
2192                    Atom::Ord(Box::new(script))
2193                } else {
2194                    script
2195                };
2196                // Empty PushAll leaves SubsupItem pending, including the
2197                // no-node limits commands dispatched through commandEvent.
2198                if !matches!(&script, Atom::Sequence(items) if items.is_empty()) {
2199                    break script;
2200                }
2201            };
2202            if cd::first_error(&script).is_some() {
2203                self.index = self.chars.len();
2204                return Some(script);
2205            }
2206            if marker == '_' {
2207                sub = Some(Box::new(script));
2208            } else {
2209                sup = Some(Box::new(script));
2210            }
2211            if first_only {
2212                break;
2213            }
2214        }
2215        if sub.is_some() || sup.is_some() {
2216            if let Atom::Multiscripts {
2217                post,
2218                prescript: true,
2219                ..
2220            } = &mut atom
2221            {
2222                let [empty_sub, empty_sup] = multiscripts::empty_pair();
2223                *post = Some([sub.unwrap_or(empty_sub), sup.unwrap_or(empty_sup)]);
2224                return Some(atom);
2225            }
2226            atom = Atom::Scripts {
2227                eager: true,
2228                leading_space: 0.,
2229                accent,
2230                limits,
2231                base: Box::new(atom),
2232                sub,
2233                sup,
2234            };
2235        }
2236        Some(atom)
2237    }
2238
2239    // Pinned base_ams_handlers.go amsOperatorName owns a genuine child
2240    // parser with normal font and the operator-letter identifier pattern.
2241    fn operator_name(&mut self) -> Option<Atom> {
2242        while self.chars.get(self.index).is_some_and(Self::prime_space) {
2243            self.index += 1;
2244        }
2245        let star = self.chars.get(self.index) == Some(&'*');
2246        if star {
2247            self.index += 1;
2248        }
2249        let raw = match self.padded_raw_argument("operatorname") {
2250            Ok(s) => s,
2251            Err(e) => return Some(Atom::ErrorDisplay(e)),
2252        };
2253        // amsOperatorName reparses once in a copied normal-font environment.
2254        // Preserve the complete row so kerns, scripts and pending items keep
2255        // their actual recipient, instead of parsing each character separately.
2256        let terminal_space = raw.ends_with(' ');
2257        let mut raw = raw.trim_matches(|c| Self::prime_space(&c)).to_owned();
2258        if raw.ends_with('\\') && terminal_space {
2259            raw.push(' ');
2260        }
2261        let mut parser = self.padded_child(&raw);
2262        parser.active_font = Some("mathrm");
2263        parser.normal_font = false;
2264        parser.calligraphic_font = false;
2265        parser.multi_letter_font = false;
2266        parser.operator_letters = true;
2267        parser.operator_pattern = true;
2268        parser.vector_alias = false;
2269        let macro_count = std::mem::take(&mut self.ams.borrow_mut().paired_macro_count);
2270        let result = parser.sequence(None);
2271        self.ams.borrow_mut().paired_macro_count = macro_count;
2272        let result = result?;
2273        if cd::first_error(&result).is_some() {
2274            return Some(result);
2275        }
2276        let mut children = match result {
2277            Atom::Sequence(items) => items,
2278            atom => vec![atom],
2279        };
2280        // AMS writes movablelimits as a property, not an attribute. The
2281        // SVG script core reads attributes, so a newly owned core has no
2282        // movable-limits attribute; a wrapped child keeps its own attribute.
2283        let own_core =
2284            children.len() != 1 || children.first().is_some_and(operator_name_identifier);
2285        // amsOperatorName retains mi identity; every other result gets an OP TeXAtom.
2286        let body = if children.len() == 1 && children.first().is_some_and(operator_name_identifier)
2287        {
2288            children.pop().unwrap()
2289        } else {
2290            Atom::Class {
2291                class: 1,
2292                body: Box::new(Atom::Sequence(children)),
2293            }
2294        };
2295        let body = Atom::Operator(Box::new(body));
2296        if !star {
2297            while self.chars.get(self.index).is_some_and(Self::prime_space) {
2298                self.index += 1;
2299            }
2300            let rest: String = self.chars[self.index..].iter().take(7).collect();
2301            if rest == r"\limits"
2302                && self
2303                    .chars
2304                    .get(self.index + 7)
2305                    .is_none_or(|c| !c.is_ascii_alphabetic())
2306            {
2307                self.index += 7;
2308            }
2309        }
2310        Some(Atom::ScriptPolicy {
2311            body: Box::new(body),
2312            moves: star,
2313            movable: own_core.then_some(false),
2314            movable_property: true,
2315        })
2316    }
2317
2318    fn atom_or_group(&mut self) -> Option<Atom> {
2319        let auto = self.physics_auto.take();
2320        let result = self.script_atom_or_group();
2321        self.physics_auto = auto;
2322        result
2323    }
2324
2325    fn script_atom_or_group(&mut self) -> Option<Atom> {
2326        while self
2327            .chars
2328            .get(self.index)
2329            .is_some_and(|c| c.is_whitespace())
2330        {
2331            self.index += 1;
2332        }
2333        if self.chars.get(self.index) == Some(&'{') {
2334            self.index += 1;
2335            self.sequence(Some('}'))
2336        } else {
2337            let previous = self.multi_letter_font;
2338            self.multi_letter_font = false;
2339            let result = self.atom();
2340            self.multi_letter_font = previous;
2341            result
2342        }
2343    }
2344
2345    // Original tex/source_runtime.go lookupMJSourceSymbol for the
2346    // CharacterMap/DelimiterMap entries the native command handlers above do
2347    // not own. Entries whose attributes select an untranslated path return
2348    // None (explicit refusal) rather than an approximated token.
2349    fn source_symbol(&self, name: &str) -> Option<Atom> {
2350        use source_symbols::Parser as P;
2351        let symbol = command_symbol(name)?;
2352        let text = symbol.text?;
2353        let mut chars = text.chars();
2354        let character = chars.next()?;
2355        if chars.next().is_some() {
2356            return None;
2357        }
2358        let code = character as u32;
2359        let attributes: Vec<(&str, &str)> = symbol.attributes.to_vec();
2360        match symbol.parser {
2361            P::Mathchar0mi | P::Mathchar7 => {
2362                if attributes.as_slice() == [("variantForm", "true")] {
2363                    if self.normal_font || self.calligraphic_font {
2364                        return None;
2365                    }
2366                    return Some(Atom::Identifier(vec![Atom::VariantGlyph(code)]));
2367                }
2368                let normal = match attributes.as_slice() {
2369                    [] => symbol.parser == P::Mathchar7,
2370                    [("mathvariant", "normal")] => true,
2371                    [("mathvariant", "italic")] => false,
2372                    _ => return None,
2373                };
2374                let glyph = if self.normal_font {
2375                    Atom::Glyph(code)
2376                } else if self.calligraphic_font {
2377                    Atom::CalligraphicGlyph(code)
2378                } else if normal {
2379                    Atom::Glyph(code)
2380                } else {
2381                    automatic_italic_atom(character)
2382                };
2383                let token = Atom::Identifier(vec![glyph]);
2384                Some(if symbol.parser == P::Mathchar7 {
2385                    self.ambient_font(token)
2386                } else {
2387                    self.nonambient_font(token)
2388                })
2389            }
2390            // Other registered CharacterMap parsers also create mo tokens;
2391            // command_symbol has already excluded the parserless remap maps.
2392            P::Mathchar0mo | P::Delimiter | P::Other => {
2393                let (mut big, mut texclass, mut variant) = (false, None::<i8>, false);
2394                match attributes.as_slice() {
2395                    [] | [("largeop", "false")] | [("accent", "false")] => {}
2396                    [("texClass", "1"), ("movesupsub", "true")]
2397                    | [
2398                        ("texClass", "1"),
2399                        ("movesupsub", "true"),
2400                        ("movablelimits", "true"),
2401                    ] => big = true,
2402                    // Integral-like OP entries do not move their scripts.
2403                    [("texClass", "1")] => {
2404                        return (is_large_operator(code)
2405                            && !self.normal_font
2406                            && !self.calligraphic_font)
2407                            .then(|| self.nonambient_font(Atom::Glyph(code)));
2408                    }
2409                    [("texClass", "6")] => texclass = Some(6),
2410                    [("variantForm", "true")] => variant = true,
2411                    [("mathvariant", "bold")] if symbol.parser == P::Mathchar0mo => {
2412                        // Physics vector mo: the bold variant of the character.
2413                        let mut body = Atom::Glyph(code);
2414                        declaration_fonts::apply_wrapper(&mut body, "mathbf");
2415                        if !matches!(body, Atom::Glyph(_) | Atom::FontGlyph { .. })
2416                            || self.normal_font
2417                            || self.calligraphic_font
2418                        {
2419                            return None;
2420                        }
2421                        let definition =
2422                            operator_dictionary::lookup(code, operator_dictionary::Form::Infix);
2423                        if definition.flag("largeop") {
2424                            return None;
2425                        }
2426                        return Some(Atom::RawOperator {
2427                            attributes: &[],
2428                            cleanup: false,
2429                            texclass: None,
2430                            code,
2431                            body: Box::new(body),
2432                            definition,
2433                        });
2434                    }
2435                    _ => return None,
2436                }
2437                if self.normal_font || self.calligraphic_font {
2438                    return None;
2439                }
2440                if big {
2441                    // Native large-operator path (sum/prod/int); other glyphs
2442                    // are not yet sized there.
2443                    return is_large_operator(code).then(|| {
2444                        Atom::MovesScripts(Box::new(self.nonambient_font(Atom::Glyph(code))))
2445                    });
2446                }
2447                let mut definition =
2448                    operator_dictionary::lookup(code, operator_dictionary::Form::Infix);
2449                if definition.flag("largeop") {
2450                    return None;
2451                }
2452                if let Some(class) = texclass {
2453                    definition.class = class;
2454                }
2455                let operator = Atom::RawOperator {
2456                    attributes: symbol.attributes,
2457                    cleanup: symbol.parser == P::Mathchar0mo,
2458                    texclass,
2459                    code,
2460                    body: Box::new(self.nonambient_font(if variant {
2461                        Atom::VariantGlyph(code)
2462                    } else {
2463                        Atom::Glyph(code)
2464                    })),
2465                    definition,
2466                };
2467                // tex/clean_stretchy.go also visits registered command mo
2468                // tokens. An ORD dictionary entry keeps its TeXAtom owner.
2469                Some(
2470                    if symbol.parser == P::Mathchar0mo && definition.class == 0 {
2471                        Atom::Ord(Box::new(operator))
2472                    } else {
2473                        operator
2474                    },
2475                )
2476            }
2477        }
2478    }
2479
2480    fn atom(&mut self) -> Option<Atom> {
2481        let character = *self.chars.get(self.index)?;
2482        self.index += 1;
2483        if character == '{' {
2484            let previous = self.multi_letter_font;
2485            self.multi_letter_font = false;
2486            let array = self.array_cell.take();
2487            let auto = self.physics_auto.take();
2488            let group = self.sequence(Some('}'));
2489            self.physics_auto = auto;
2490            self.array_cell = array;
2491            self.multi_letter_font = previous;
2492            return group.map(|body| Atom::Ord(Box::new(body)));
2493        }
2494        if character == '\\' {
2495            let start = self.index;
2496            while self.index < self.chars.len() && self.chars[self.index].is_ascii_alphabetic() {
2497                self.index += 1;
2498            }
2499            if self.index == start {
2500                let paired_name = self
2501                    .chars
2502                    .get(self.index)
2503                    .copied()
2504                    .unwrap_or(' ')
2505                    .to_string();
2506                if let Some(definition) = self.paired_definition(&paired_name) {
2507                    if self.index < self.chars.len() {
2508                        self.index += 1;
2509                    }
2510                    return self.paired_delimiter(&paired_name, definition);
2511                }
2512                let Some(&delimiter) = self.chars.get(self.index) else {
2513                    return Some(self.internal_text(" ".to_owned()));
2514                };
2515                self.index += 1;
2516                // parser.go readControlSequence's non-dotall fallback.
2517                let delimiter = match delimiter {
2518                    '\n' | '\r' | '\u{2028}' | '\u{2029}' => ' ',
2519                    c => c,
2520                };
2521                return Some(Atom::DeclaredStyle {
2522                    display: false,
2523                    level: 0,
2524                    body: Box::new(Atom::Space(match delimiter {
2525                        '!' => -0.167,
2526                        ',' => 0.167,
2527                        ':' => 0.222,
2528                        ';' => 0.278,
2529                        // Original notchar map shadows the Spacer entry for this name.
2530                        '{' | '}' => {
2531                            return Some(Atom::RawOperator {
2532                                attributes: &[],
2533                                cleanup: false,
2534                                texclass: None,
2535                                code: delimiter as u32,
2536                                body: Box::new(Atom::Glyph(delimiter as u32)),
2537                                definition: operator_dictionary::lookup(
2538                                    delimiter as u32,
2539                                    operator_dictionary::Form::Infix,
2540                                ),
2541                            });
2542                        }
2543                        // tex/braket.go braketBar takes priority over the
2544                        // Base delimiter map and creates an ORD U+2225 mo.
2545                        '|' => {
2546                            return Some(Atom::RawOperator {
2547                                attributes: &[],
2548                                cleanup: false,
2549                                texclass: Some(0),
2550                                code: 0x2225,
2551                                body: Box::new(self.nonambient_font(Atom::Glyph(0x2225))),
2552                                definition: operator_dictionary::lookup(
2553                                    0x2225,
2554                                    operator_dictionary::Form::Infix,
2555                                ),
2556                            });
2557                        }
2558                        '>' => 0.222,
2559                        '\\' => return self.cell_command("\\"),
2560                        ' ' => return Some(self.internal_text(" ".to_owned())),
2561                        _ => {
2562                            let name = delimiter.to_string();
2563                            if let Some(atom) = self.source_symbol(&name) {
2564                                return Some(atom);
2565                            }
2566                            if command_registry::recognized(&name)
2567                                || command_symbol(&name).is_some()
2568                            {
2569                                return None;
2570                            }
2571                            return Some(Atom::ErrorDisplay(format!(
2572                                "Undefined control sequence \\{name}"
2573                            )));
2574                        }
2575                    })),
2576                });
2577            }
2578            let name: String = self.chars[start..self.index].iter().collect();
2579            if let Some(definition) = self.paired_definition(&name) {
2580                return self.paired_delimiter(&name, definition);
2581            }
2582            // Original tex/commands.go declareMathOperator: \cs expands to
2583            // \operatorname{body} (or \operatorname*) via the parse-state macros.
2584            if name == "DeclareMathOperator" {
2585                while self
2586                    .chars
2587                    .get(self.index)
2588                    .is_some_and(|c| c.is_whitespace())
2589                {
2590                    self.index += 1;
2591                }
2592                let star = self.chars.get(self.index) == Some(&'*');
2593                if star {
2594                    self.index += 1;
2595                }
2596                let cs = self.padded_raw_argument(&name).ok()?;
2597                let cs = cs.trim();
2598                let cs_name = cs.strip_prefix('\\')?;
2599                let single = cs_name.chars().all(|c| c.is_ascii_alphabetic())
2600                    || cs_name.chars().count() == 1;
2601                if cs_name.is_empty() || !single {
2602                    return None;
2603                }
2604                let body = self.padded_raw_argument(&name).ok()?;
2605                let command = if star {
2606                    "\\operatorname*"
2607                } else {
2608                    "\\operatorname"
2609                };
2610                self.ams
2611                    .borrow_mut()
2612                    .macros
2613                    .insert(cs_name.to_owned(), format!("{command}{{{body}}}"));
2614                self.splice_inferred = true;
2615                return Some(Atom::Sequence(Vec::new()));
2616            }
2617            let user_macro = self.ams.borrow().macros.get(&name).cloned();
2618            if let Some(expansion) = user_macro {
2619                if self.chars.get(self.index) == Some(&' ') {
2620                    self.index += 1;
2621                }
2622                self.chars.splice(self.index..self.index, expansion.chars());
2623                self.splice_inferred = true;
2624                return Some(Atom::Sequence(Vec::new()));
2625            }
2626            if name == "not" {
2627                return Some(pending_not::fallback());
2628            }
2629            if hfill::is_fill(&name) {
2630                return Some(hfill::unsupported(&name));
2631            }
2632            if matches!(name.as_str(), "uproot" | "leftroot") {
2633                return Some(match self.move_root(&name) {
2634                    Ok(()) => {
2635                        self.splice_inferred = true;
2636                        Atom::Sequence(Vec::new())
2637                    }
2638                    Err(error) => Atom::ErrorDisplay(error),
2639                });
2640            }
2641            // Original tex/symbols.go simpleMacros (installed as parse-state
2642            // macros, so command() expands them before any other handler):
2643            // the expansion is spliced in front of the unparsed input.
2644            if let Some(body) = source_macros::body(&name) {
2645                let expand = (|| -> Result<String, String> {
2646                    let count = body
2647                        .as_bytes()
2648                        .windows(2)
2649                        .filter(|pair| pair[0] == b'#' && (b'1'..=b'9').contains(&pair[1]))
2650                        .map(|pair| (pair[1] - b'0') as usize)
2651                        .max()
2652                        .unwrap_or(0);
2653                    let mut args = Vec::new();
2654                    if let Some(default) = source_macros::optional_default(&name) {
2655                        while self.chars.get(self.index).is_some_and(Self::prime_space) {
2656                            self.index += 1;
2657                        }
2658                        args.push(if self.chars.get(self.index) == Some(&'[') {
2659                            self.padded_brackets()?
2660                        } else {
2661                            default.into()
2662                        });
2663                    }
2664                    for _ in args.len()..count {
2665                        args.push(self.padded_raw_argument(&name)?);
2666                    }
2667                    let mut expansion = if count == 0 {
2668                        body.to_owned()
2669                    } else {
2670                        paired_delimiters::substitute(body, &args)?
2671                    };
2672                    paired_delimiters::add_args(
2673                        &mut expansion,
2674                        &self.chars[self.index..].iter().collect::<String>(),
2675                    )?;
2676                    Ok(expansion)
2677                })();
2678                let expansion = match expand {
2679                    Ok(expansion) => expansion,
2680                    Err(message) => return Some(Atom::ErrorDisplay(message)),
2681                };
2682                self.chars = expansion.chars().collect();
2683                self.index = 0;
2684                self.ams.borrow_mut().paired_macro_count += 1;
2685                if self.ams.borrow().paired_macro_count > 1000 {
2686                    return Some(Atom::ErrorDisplay("MathJax maximum macro substitution count exceeded; is here a recursive macro call?".into()));
2687                }
2688                self.splice_inferred = true;
2689                return Some(Atom::Sequence(Vec::new()));
2690            }
2691            if matches!(
2692                name.as_str(),
2693                "DeclarePairedDelimiter"
2694                    | "DeclarePairedDelimiters"
2695                    | "DeclarePairedDelimiterX"
2696                    | "DeclarePairedDelimitersX"
2697                    | "DeclarePairedDelimiterXPP"
2698                    | "DeclarePairedDelimitersXPP"
2699            ) {
2700                return self.declare_paired_delimiter(&name);
2701            }
2702            if matches!(
2703                name.as_str(),
2704                "newenvironment"
2705                    | "renewenvironment"
2706                    | "newcommand"
2707                    | "renewcommand"
2708                    | "providecommand"
2709                    | "def"
2710                    | "gdef"
2711                    | "edef"
2712                    | "xdef"
2713                    | "let"
2714            ) {
2715                return Some(Atom::ErrorDisplay(format!(
2716                    "Undefined control sequence \\{name}"
2717                )));
2718            }
2719            if matches!(name.as_str(), "cr" | "newline") {
2720                return self.cell_command(&name);
2721            }
2722            if matches!(name.as_str(), "shoveleft" | "shoveright") {
2723                return Some(Atom::ErrorDisplay(format!(
2724                    "\\{name} only allowed in multline environment"
2725                )));
2726            }
2727            if name == "dots" {
2728                let mut nodes = Vec::new();
2729                pending_dots::Pending::start(self).finish(&mut Vec::new(), &mut nodes);
2730                self.splice_inferred = true;
2731                return Some(Atom::Sequence(nodes));
2732            }
2733            if name == "sideset" {
2734                let pre = self.padded_argument(&name)?;
2735                if cd::first_error(&pre).is_some() {
2736                    return Some(pre);
2737                }
2738                let post = self.padded_argument(&name)?;
2739                if cd::first_error(&post).is_some() {
2740                    return Some(post);
2741                }
2742                let base = self.padded_argument(&name)?;
2743                if cd::first_error(&base).is_some() {
2744                    return Some(base);
2745                }
2746                let body = multiscripts::side_set(pre, post, base);
2747                // Source properties on the OP TeXAtom do not supply the
2748                // script core's movablelimits attribute (msubsup.go).
2749                return Some(Atom::ScriptPolicy {
2750                    body: Box::new(Atom::Class {
2751                        body: Box::new(body),
2752                        class: 1,
2753                    }),
2754                    moves: true,
2755                    movable: None,
2756                    movable_property: false,
2757                });
2758            }
2759            if name == "prescript" {
2760                let sup = self.prescript_argument("sup")?;
2761                if cd::first_error(&sup).is_some() {
2762                    return Some(sup);
2763                }
2764                let sub = self.prescript_argument("sub")?;
2765                if cd::first_error(&sub).is_some() {
2766                    return Some(sub);
2767                }
2768                let base = self.prescript_argument("arg")?;
2769                if cd::first_error(&base).is_some() {
2770                    return Some(base);
2771                }
2772                if matches!(sub, Atom::EmptyNode("none")) && matches!(sup, Atom::EmptyNode("none"))
2773                {
2774                    self.splice_inferred = true;
2775                    return Some(base);
2776                }
2777                return Some(Atom::Multiscripts {
2778                    base: Box::new(base),
2779                    sub: Box::new(sub),
2780                    sup: Box::new(sup),
2781                    post: None,
2782                    prescript: true,
2783                    mathsize: 1.0,
2784                });
2785            }
2786            if name == "mathtoolsset" {
2787                let raw = match self.padded_raw_argument(&name) {
2788                    Ok(v) => v,
2789                    Err(e) => return Some(Atom::ErrorDisplay(e)),
2790                };
2791                let result = self.ams.borrow_mut().set_options(&raw);
2792                if result.is_ok() {
2793                    self.splice_inferred = true;
2794                }
2795                return Some(match result {
2796                    Ok(()) => Atom::Sequence(Vec::new()),
2797                    Err(e) => Atom::ErrorDisplay(e),
2798                });
2799            }
2800            if matches!(
2801                name.as_str(),
2802                "centercolon" | "ordinarycolon" | "MTThinColon"
2803            ) {
2804                return Some(self.mathtools_colon(name != "ordinarycolon", name == "MTThinColon"));
2805            }
2806            let relation = match name.as_str() {
2807                "coloneqq" => Some((":=", "≔")),
2808                "Coloneqq" => Some(("::=", "⩴")),
2809                "coloneq" => Some((":-", "")),
2810                "Coloneq" => Some(("::-", "")),
2811                "eqqcolon" => Some(("=:", "≕")),
2812                "Eqqcolon" => Some(("=::", "")),
2813                "eqcolon" => Some(("-:", "∹")),
2814                "Eqcolon" => Some(("-::", "")),
2815                "colonapprox" => Some((r":\approx", "")),
2816                "Colonapprox" => Some((r"::\approx", "")),
2817                "colonsim" => Some((r":\sim", "")),
2818                "Colonsim" => Some((r"::\sim", "")),
2819                "dblcolon" => Some((r"::", "∷")),
2820                _ => None,
2821            };
2822            if let Some((expansion, unicode)) = relation {
2823                if !unicode.is_empty() && self.ams.borrow().option("use-unicode") == "true" {
2824                    return Some(Atom::Class {
2825                        class: 3,
2826                        body: Box::new(Atom::Glyph(unicode.chars().next().unwrap() as u32)),
2827                    });
2828                }
2829                let expansion = expansion
2830                    .replace(':', "\\MTThinColon")
2831                    .replace('-', "\\mathrel{-}");
2832                return parse_unresolved_shared(
2833                    &format!("\\mathrel{{{expansion}}}"),
2834                    self.ams.clone(),
2835                );
2836            }
2837            if !command_registry::recognized(&name) {
2838                return Some(Atom::ErrorDisplay(format!(
2839                    "Undefined control sequence \\{name}"
2840                )));
2841            }
2842            // Original tex/commands.go spacer fixes scriptlevel at zero.
2843            let explicit_space = match name.as_str() {
2844                "quad" => Some(1.0),
2845                "qquad" => Some(2.0),
2846                "enspace" | "enskip" => Some(0.5),
2847                "thinspace" => Some(0.167),
2848                "negthinspace" => Some(-0.167),
2849                "negmedspace" => Some(-0.222),
2850                "negthickspace" => Some(-0.278),
2851                _ => None,
2852            };
2853            if let Some(width) = explicit_space {
2854                return Some(Atom::DeclaredStyle {
2855                    display: false,
2856                    level: 0,
2857                    body: Box::new(Atom::Space(width)),
2858                });
2859            }
2860            if let Some((display, level)) = styles::declaration(&name) {
2861                return Some(Atom::DeclaredStyle {
2862                    body: Box::new(self.sequence(None)?),
2863                    display,
2864                    level,
2865                });
2866            }
2867            if let Some(parameters) = xarrow::parameters(&name) {
2868                return self.xarrow_argument(&name, parameters);
2869            }
2870            if name == "mathchoice" {
2871                let mut branches = Vec::new();
2872                for _ in 0..4 {
2873                    let a = self.padded_argument(&name)?;
2874                    if cd::first_error(&a).is_some() {
2875                        return Some(a);
2876                    }
2877                    // parseArgumentString returns an inferred mrow for a
2878                    // multi-item branch. It survives MathChoice replacement.
2879                    let a = match a {
2880                        Atom::Sequence(items) if items.len() != 1 => Atom::ExplicitRow(items),
2881                        a => a,
2882                    };
2883                    branches.push(Box::new(a));
2884                }
2885                return Some(Atom::Choice(branches.try_into().ok()?));
2886            }
2887            if name == "mmlToken" {
2888                return self.mml_token(&name);
2889            }
2890            if matches!(name.as_str(), "splitfrac" | "splitdfrac") {
2891                let numerator = self.padded_argument(&name)?;
2892                if cd::first_error(&numerator).is_some() {
2893                    return Some(numerator);
2894                }
2895                let denominator = self.padded_argument(&name)?;
2896                if cd::first_error(&denominator).is_some() {
2897                    return Some(denominator);
2898                }
2899                let unwrap = |a| {
2900                    if let Atom::Sequence(v) = a {
2901                        v
2902                    } else {
2903                        vec![a]
2904                    }
2905                };
2906                let mut num = unwrap(numerator);
2907                num.extend([Atom::Identifier(Vec::new()), Atom::Space(1.)]);
2908                let mut den = vec![Atom::Space(1.), Atom::Identifier(Vec::new())];
2909                den.extend(unwrap(denominator));
2910                let style = |v| {
2911                    Box::new(Atom::DeclaredStyle {
2912                        body: Box::new(Atom::Sequence(v)),
2913                        display: false,
2914                        level: 0,
2915                    })
2916                };
2917                return Some(Atom::DeclaredStyle {
2918                    body: Box::new(Atom::SplitFraction(style(num), style(den), 1.)),
2919                    display: name == "splitdfrac",
2920                    level: 0,
2921                });
2922            }
2923            if matches!(name.as_str(), "binom" | "dbinom" | "tbinom") {
2924                return self.binomial_command(&name);
2925            }
2926            if matches!(name.as_str(), "dfrac" | "tfrac") {
2927                return self.styled_fraction(&name);
2928            }
2929            if matches!(
2930                name.as_str(),
2931                "bar"
2932                    | "hat"
2933                    | "widehat"
2934                    | "tilde"
2935                    | "widetilde"
2936                    | "vec"
2937                    | "dot"
2938                    | "ddot"
2939                    | "dddot"
2940                    | "ddddot"
2941                    | "acute"
2942                    | "grave"
2943                    | "breve"
2944                    | "check"
2945                    | "mathring"
2946            ) {
2947                let previous_alias = self.vector_alias;
2948                self.vector_alias |= matches!(name.as_str(), "hat" | "vec");
2949                let base = self.padded_argument(&name);
2950                self.vector_alias = previous_alias;
2951                let base = base?;
2952                if cd::first_error(&base).is_some() {
2953                    return Some(base);
2954                }
2955                let code = match name.as_str() {
2956                    "bar" => 0xaf,
2957                    "hat" | "widehat" => 0x5e,
2958                    "tilde" | "widetilde" => 0x7e,
2959                    "vec" => 0x20d7,
2960                    "dot" => 0x2d9,
2961                    "ddot" => 0xa8,
2962                    "dddot" => 0x20db,
2963                    "ddddot" => 0x20dc,
2964                    "acute" => 0xb4,
2965                    "grave" => 0x60,
2966                    "breve" => 0x2d8,
2967                    "check" => 0x2c7,
2968                    _ => 0x2da,
2969                };
2970                let body = if matches!(code, 0x20db | 0x20dc) {
2971                    Atom::OperatorToken(
2972                        (0..if code == 0x20db { 3 } else { 4 })
2973                            .map(|_| Atom::Glyph(0x2e))
2974                            .collect(),
2975                    )
2976                } else {
2977                    // inheritance.go checkOperatorPrimes precedes the accent
2978                    // character remap, including command-created grave mo.
2979                    Atom::Glyph(if code == 0x60 { 0x2035 } else { code })
2980                };
2981                let mark = Atom::HorizontalMark {
2982                    body: Box::new(self.ambient_font(body)),
2983                    code,
2984                    stretchy: name.starts_with("wide"),
2985                    mathaccent: true,
2986                };
2987                return Some(Atom::Ord(Box::new(Atom::Scripts {
2988                    base: Box::new(base),
2989                    sub: None,
2990                    sup: Some(Box::new(mark)),
2991                    limits: true,
2992                    eager: false,
2993                    leading_space: 0.,
2994                    accent: Some(accents::Spec {
2995                        enabled: true,
2996                        under: false,
2997                        mathsize: 1.,
2998                    }),
2999                })));
3000            }
3001            if matches!(
3002                name.as_str(),
3003                "overline"
3004                    | "underline"
3005                    | "overbrace"
3006                    | "underbrace"
3007                    | "overparen"
3008                    | "underparen"
3009                    | "overrightarrow"
3010                    | "overleftarrow"
3011                    | "underrightarrow"
3012                    | "underleftarrow"
3013                    | "overleftrightarrow"
3014                    | "underleftrightarrow"
3015            ) {
3016                let mut base = self.padded_argument(&name)?;
3017                if cd::first_error(&base).is_some() {
3018                    return Some(base);
3019                }
3020                check_movable_limits(&mut base);
3021                let under = name.starts_with("under");
3022                let code = match name.as_str() {
3023                    "overline" | "underline" => 0x2015,
3024                    "overbrace" => 0x23de,
3025                    "underbrace" => 0x23df,
3026                    "overparen" => 0x23dc,
3027                    "underparen" => 0x23dd,
3028                    "overleftrightarrow" | "underleftrightarrow" => 0x2194,
3029                    "overrightarrow" | "underrightarrow" => 0x2192,
3030                    "overleftarrow" | "underleftarrow" => 0x2190,
3031                    _ => 0xaf,
3032                };
3033                let mark = Box::new(Atom::HorizontalMark {
3034                    body: Box::new(Atom::Glyph(code)),
3035                    code,
3036                    stretchy: name != "bar",
3037                    mathaccent: code == 0x2192,
3038                });
3039                let stack = Atom::Scripts {
3040                    base: Box::new(base),
3041                    sub: if under { Some(mark.clone()) } else { None },
3042                    sup: if under { None } else { Some(mark) },
3043                    limits: true,
3044                    eager: false,
3045                    leading_space: 0.,
3046                    accent: Some(accents::Spec {
3047                        enabled: true,
3048                        under,
3049                        mathsize: 1.,
3050                    }),
3051                };
3052                return Some(if matches!(name.as_str(), "overbrace" | "underbrace") {
3053                    // UnderOver(stack=true) writes movesupsub on the OP
3054                    // TeXAtom, but no movablelimits attribute on its core.
3055                    Atom::ScriptPolicy {
3056                        body: Box::new(Atom::Class {
3057                            class: 1,
3058                            body: Box::new(stack),
3059                        }),
3060                        moves: true,
3061                        movable: None,
3062                        movable_property: false,
3063                    }
3064                } else {
3065                    stack
3066                });
3067            }
3068            if name == "stackrel" || name == "stackbin" {
3069                // Pinned tex/symbols.go expands these before direct handlers.
3070                let expansion = (|| -> Result<String, String> {
3071                    let script = self.padded_raw_argument(&name)?;
3072                    let base = self.padded_raw_argument(&name)?;
3073                    let class = if name == "stackrel" {
3074                        "mathrel"
3075                    } else {
3076                        "mathbin"
3077                    };
3078                    Ok([
3079                        "\\",
3080                        class,
3081                        "{\\mathop{",
3082                        &base,
3083                        "}\\limits^{",
3084                        &script,
3085                        "}}",
3086                    ]
3087                    .concat())
3088                })();
3089                return match expansion {
3090                    Ok(expansion) => {
3091                        self.chars.splice(self.index..self.index, expansion.chars());
3092                        self.atom()
3093                    }
3094                    Err(error) => Some(Atom::ErrorDisplay(error)),
3095                };
3096            }
3097            if matches!(name.as_str(), "overset" | "underset" | "overunderset") {
3098                return self.stack_annotation(&name);
3099            }
3100            if name == "buildrel" {
3101                return self.build_relation();
3102            }
3103            if name == "adjustlimits" {
3104                return self.adjust_limits(&name);
3105            }
3106            if matches!(name.as_str(), "shoveleft" | "shoveright") {
3107                return Some(Atom::ErrorDisplay(format!(
3108                    "\\{name} only allowed in multline environment"
3109                )));
3110            }
3111            if matches!(
3112                name.as_str(),
3113                "Aboxed"
3114                    | "ArrowBetweenLines"
3115                    | "MTFlushSpaceAbove"
3116                    | "MTFlushSpaceBelow"
3117                    | "vdotswithin"
3118                    | "shortvdotswithin"
3119            ) {
3120                return Some(Atom::ErrorDisplay(format!(
3121                    "\\{name} can only be used in aligment environments"
3122                )));
3123            }
3124            if matches!(name.as_str(), "overbracket" | "underbracket") {
3125                return self.bracket_command(&name);
3126            }
3127            if name == "cfrac" {
3128                return self.continued_fraction();
3129            }
3130            if name == "genfrac" {
3131                return self.general_fraction_command(&name);
3132            }
3133            if name == "frac" {
3134                let numerator = self.padded_argument(&name)?;
3135                if cd::first_error(&numerator).is_some() {
3136                    return Some(numerator);
3137                }
3138                let denominator = self.padded_argument(&name)?;
3139                if cd::first_error(&denominator).is_some() {
3140                    return Some(denominator);
3141                }
3142                return Some(Atom::Fraction(Box::new(numerator), Box::new(denominator)));
3143            }
3144            if matches!(name.as_str(), "sqrt" | "root") {
3145                return self.root_command(&name);
3146            }
3147            if matches!(name.as_str(), "minCDarrowwidth" | "minCDarrowheight") {
3148                let raw = match self.read_dimension(&name) {
3149                    Ok(raw) => raw,
3150                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3151                };
3152                let value = length::dimension(&raw);
3153                let mut state = self.ams.borrow_mut();
3154                let minimums = state
3155                    .cd_minimums
3156                    .get_or_insert((Dimension::relative(2.75), Dimension::relative(1.75)));
3157                if name == "minCDarrowwidth" {
3158                    minimums.0 = value;
3159                } else {
3160                    minimums.1 = value;
3161                }
3162                // Original amscdCommand returns no nodes.
3163                self.splice_inferred = true;
3164                return Some(Atom::Sequence(Vec::new()));
3165            }
3166            if matches!(
3167                name.as_str(),
3168                "kern" | "mkern" | "hskip" | "mskip" | "hspace" | "mspace"
3169            ) {
3170                let raw = match self.read_dimension(&name) {
3171                    Ok(raw) => raw,
3172                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3173                };
3174                return Some(Atom::Kern(length::dimension(&raw)));
3175            }
3176            if name == "strut" {
3177                // commands.go Strut and base_ams_handlers.go CFrac use the
3178                // same explicit empty mrow and fixed 8.6pt/3pt mpadded box.
3179                return Some(Atom::FractionStrut(1.));
3180            }
3181            if matches!(
3182                name.as_str(),
3183                "matrix" | "array" | "pmatrix" | "cases" | "eqalign" | "eqalignno" | "leqalignno"
3184            ) {
3185                // matrix_command.go startMatrixBody checks the opening
3186                // argument before installing its ArrayItem. Preserve that
3187                // diagnostic even while command-form table layout is outside
3188                // the translated surface (environment tables are separate).
3189                while self
3190                    .chars
3191                    .get(self.index)
3192                    .is_some_and(|c| *c == '\u{feff}' || (*c != '\u{85}' && c.is_whitespace()))
3193                {
3194                    self.index += 1;
3195                }
3196                if self.index == self.chars.len() {
3197                    return Some(Atom::ErrorDisplay(format!("Missing argument for \\{name}")));
3198                }
3199                return None;
3200            }
3201            if name == "rule" {
3202                return self.rule();
3203            }
3204            if matches!(name.as_str(), "Rule" | "Space") {
3205                return self.rule_space(&name);
3206            }
3207            if matches!(name.as_str(), "raise" | "lower" | "moveleft" | "moveright") {
3208                return self.position_command(&name);
3209            }
3210            if matches!(
3211                name.as_str(),
3212                "evaluated"
3213                    | "eval"
3214                    | "outerproduct"
3215                    | "dyad"
3216                    | "ketbra"
3217                    | "op"
3218                    | "matrixelement"
3219                    | "matrixel"
3220                    | "mel"
3221                    | "expectationvalue"
3222                    | "expval"
3223                    | "ev"
3224                    | "commutator"
3225                    | "comm"
3226                    | "anticommutator"
3227                    | "acomm"
3228                    | "poissonbracket"
3229                    | "pb"
3230                    | "mqty"
3231                    | "matrixquantity"
3232                    | "pmqty"
3233                    | "Pmqty"
3234                    | "bmqty"
3235                    | "vmqty"
3236                    | "smqty"
3237                    | "smallmatrixquantity"
3238                    | "spmqty"
3239                    | "sPmqty"
3240                    | "sbmqty"
3241                    | "svmqty"
3242            ) {
3243                return self.physics_macro(&name);
3244            }
3245            if matches!(
3246                name.as_str(),
3247                "gradient"
3248                    | "grad"
3249                    | "div"
3250                    | "divergence"
3251                    | "curl"
3252                    | "Res"
3253                    | "pv"
3254                    | "principalvalue"
3255                    | "PV"
3256                    | "Re"
3257                    | "Im"
3258            ) {
3259                return self.physics_operator_application(&name);
3260            }
3261            if name == "vnabla" {
3262                return self.physics_nabla();
3263            }
3264            // Physics ordinary-symbol map wraps the bold mo in one ORD atom;
3265            // vnabla above is a separate macro with two ORD owners.
3266            if name == "gradientnabla" {
3267                return Some(Atom::Ord(Box::new(self.source_symbol(&name)?)));
3268            }
3269            // commands.go vectorAccent is a continuing StarMacro. Let the
3270            // registered hat/vec handler own its accent and caller suffix.
3271            if matches!(name.as_str(), "vectorunit" | "vu") {
3272                while self.chars.get(self.index).is_some_and(Self::prime_space) {
3273                    self.index += 1;
3274                }
3275                let star = self.chars.get(self.index) == Some(&'*');
3276                if star {
3277                    self.index += 1;
3278                }
3279                let raw = match self.padded_raw_argument(&name) {
3280                    Ok(raw) => raw,
3281                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3282                };
3283                let recipe = if star {
3284                    r"\hat{\vb*{#1}}"
3285                } else {
3286                    r"\hat{\vb{#1}}"
3287                };
3288                let expansion = paired_delimiters::substitute(recipe, &[raw]);
3289                let mut expansion = match expansion {
3290                    Ok(value) => value,
3291                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3292                };
3293                if let Err(message) = paired_delimiters::add_args(
3294                    &mut expansion,
3295                    &self.chars[self.index..].iter().collect::<String>(),
3296                ) {
3297                    return Some(Atom::ErrorDisplay(message));
3298                }
3299                self.chars = expansion.chars().collect();
3300                self.index = 0;
3301                self.ams.borrow_mut().paired_macro_count += 1;
3302                if self.ams.borrow().paired_macro_count > 1000 {
3303                    return Some(Atom::ErrorDisplay("MathJax maximum macro substitution count exceeded; is here a recursive macro call?".into()));
3304                }
3305                return self.atom();
3306            }
3307            if name == "diffd" {
3308                // tex/commands.go physicsDifferential("d"): TeXAtom(ORD, mi d normal).
3309                return Some(Atom::Ord(Box::new(Atom::Identifier(vec![Atom::Glyph(
3310                    0x64,
3311                )]))));
3312            }
3313            if let Some(text) = match name.as_str() {
3314                "qcc" => Some("c.c."),
3315                "qif" => Some("if"),
3316                "qthen" => Some("then"),
3317                "qelse" => Some("else"),
3318                "qotherwise" => Some("otherwise"),
3319                "qunless" => Some("unless"),
3320                "qgiven" => Some("given"),
3321                "qusing" => Some("using"),
3322                "qassume" => Some("assume"),
3323                "qsince" => Some("since"),
3324                "qlet" => Some("let"),
3325                "qfor" => Some("for"),
3326                "qall" => Some("all"),
3327                "qeven" => Some("even"),
3328                "qodd" => Some("odd"),
3329                "qinteger" => Some("integer"),
3330                "qand" => Some("and"),
3331                "qor" => Some("or"),
3332                "qas" => Some("as"),
3333                "qin" => Some("in"),
3334                "qqtext" | "qq" => Some(""),
3335                _ => None,
3336            } {
3337                // commands.go quickQuadText inserts an uncharged program in
3338                // this parser, retaining late-bound text/quad and pending items.
3339                while self
3340                    .chars
3341                    .get(self.index)
3342                    .is_some_and(|c| internal_text::space(*c))
3343                {
3344                    self.index += 1;
3345                }
3346                let star = self.chars.get(self.index) == Some(&'*');
3347                if star {
3348                    self.index += 1;
3349                }
3350                let mut overrun = false;
3351                let text = if text.is_empty() {
3352                    while self
3353                        .chars
3354                        .get(self.index)
3355                        .is_some_and(|c| internal_text::space(*c))
3356                    {
3357                        self.index += 1;
3358                    }
3359                    overrun = self.index + 1 == self.chars.len()
3360                        && self.chars.get(self.index) == Some(&'\\');
3361                    match self.padded_raw_argument(&name) {
3362                        Ok(raw) => raw,
3363                        Err(message) => return Some(Atom::ErrorDisplay(message)),
3364                    }
3365                } else {
3366                    text.to_owned()
3367                };
3368                let expansion = format!(
3369                    "{}\\text{{{text}}}\\quad ",
3370                    if star { "" } else { "\\quad" }
3371                );
3372                self.chars.splice(self.index..self.index, expansion.chars());
3373                if overrun {
3374                    self.index += 1;
3375                }
3376                self.splice_inferred = true;
3377                return Some(Atom::Sequence(Vec::new()));
3378            }
3379            if matches!(name.as_str(), "vb" | "vectorbold") {
3380                return self.physics_vector_bold(&name);
3381            }
3382            if declaration_fonts::wrapper(&name) {
3383                let body = self.bounded_font_argument(&name)?;
3384                return Some(Atom::Ord(Box::new(body)));
3385            }
3386            if name == "displaylines" || name == "substack" {
3387                let raw = match self.padded_raw_argument(&name) {
3388                    Ok(v) => v,
3389                    Err(e) => return Some(Atom::ErrorDisplay(e)),
3390                };
3391                let (body, environment, column_spec) = if name == "displaylines" {
3392                    (raw, "displaylines", String::new())
3393                } else {
3394                    (raw, "subarray", "c".to_owned())
3395                };
3396                let mut options = None;
3397                let rows = table::parse_rows_count_options(
3398                    &body,
3399                    environment,
3400                    self.ams.clone(),
3401                    self.equation_seen.clone(),
3402                    None,
3403                    &mut options,
3404                )?;
3405                return Some(Atom::Matrix {
3406                    spacing: None,
3407                    options,
3408                    rows,
3409                    environment: environment.to_owned(),
3410                    column_spec,
3411                });
3412            }
3413            if name == "label" {
3414                let raw = match self.padded_raw_argument(&name) {
3415                    Ok(v) => v,
3416                    Err(e) => return Some(Atom::ErrorDisplay(e)),
3417                };
3418                let result = self.ams.borrow_mut().label(raw);
3419                if let Err(e) = result {
3420                    return Some(Atom::ErrorDisplay(e));
3421                }
3422                self.splice_inferred = true;
3423                return Some(Atom::Sequence(vec![]));
3424            }
3425            if matches!(name.as_str(), "ref" | "refeq" | "eqref") {
3426                let raw = match self.padded_raw_argument(&name) {
3427                    Ok(v) => v,
3428                    Err(e) => return Some(Atom::ErrorDisplay(e)),
3429                };
3430                let label = self
3431                    .ams
3432                    .borrow()
3433                    .labels
3434                    .get(&raw)
3435                    .cloned()
3436                    .unwrap_or_else(|| ams::Label {
3437                        text: "???".into(),
3438                        id: String::new(),
3439                    });
3440                return Some(Atom::Reference {
3441                    body: Box::new(self.internal_math(
3442                        &if name == "eqref" {
3443                            format!("({})", label.text)
3444                        } else {
3445                            label.text
3446                        },
3447                        None,
3448                        false,
3449                    )?),
3450                    href: format!("#{}", ams::uri(&label.id)),
3451                });
3452            }
3453            if name == "tag" {
3454                if matches!(
3455                    self.ams.borrow().current.environment.as_str(),
3456                    "split" | "aligned"
3457                ) {
3458                    return Some(Atom::ErrorDisplay(format!(
3459                        "\\tag not allowed in {} environment",
3460                        self.ams.borrow().current.environment
3461                    )));
3462                }
3463                if self
3464                    .ams
3465                    .borrow()
3466                    .current
3467                    .tag
3468                    .as_ref()
3469                    .is_some_and(|t| !t.raw.is_empty())
3470                {
3471                    return Some(Atom::ErrorDisplay("Multiple \\tag".into()));
3472                }
3473                while self
3474                    .chars
3475                    .get(self.index)
3476                    .is_some_and(|c| c.is_whitespace())
3477                {
3478                    self.index += 1;
3479                }
3480                let star = self.chars.get(self.index) == Some(&'*');
3481                if star {
3482                    self.index += 1;
3483                }
3484                let raw = match self.padded_raw_argument(&name) {
3485                    Ok(v) => v,
3486                    Err(e) => return Some(Atom::ErrorDisplay(e)),
3487                };
3488                self.ams.borrow_mut().set_tag(raw, star);
3489                self.splice_inferred = true;
3490                return Some(Atom::Sequence(vec![]));
3491            }
3492            if matches!(name.as_str(), "notag" | "nonumber") {
3493                self.ams.borrow_mut().notag();
3494                self.splice_inferred = true;
3495                return Some(Atom::Sequence(vec![]));
3496            }
3497            if name == "fbox" {
3498                let raw = match self.padded_raw_argument(&name) {
3499                    Ok(raw) => raw,
3500                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3501                };
3502                return Some(Atom::Boxed(Box::new(
3503                    self.internal_math(&raw, None, false)?,
3504                )));
3505            }
3506            if name == "framebox" {
3507                return self.frame_box();
3508            }
3509            if matches!(name.as_str(), "begin" | "end") {
3510                // tex/environment_count.go reads the argument before dispatch
3511                // for both BeginEnd commands, including malformed/orphan ends.
3512                let environment = match self.read_argument(&name) {
3513                    Ok(environment) => environment,
3514                    Err(message) => return Some(Atom::ErrorDisplay(message)),
3515                };
3516                if name == "end" {
3517                    let message = if environment.contains('\\') {
3518                        format!("Invalid environment name '{environment}'")
3519                    } else if !known_environment(&environment) {
3520                        format!("Unknown environment '{environment}'")
3521                    } else if environment == "spreadlines" {
3522                        format!("Extra \\end{{{environment}}}")
3523                    } else {
3524                        format!("Missing \\begin{{{environment}}} or extra \\end{{{environment}}}")
3525                    };
3526                    return Some(Atom::ErrorDisplay(message));
3527                }
3528                return self.environment(&environment);
3529            }
3530            if styles::size_declaration(&name).is_some() {
3531                return Some(Atom::ErrorDisplay(format!(
3532                    "Undefined control sequence \\{name}"
3533                )));
3534            }
3535            if matches!(
3536                name.as_str(),
3537                "phantom"
3538                    | "hphantom"
3539                    | "vphantom"
3540                    | "smash"
3541                    | "llap"
3542                    | "rlap"
3543                    | "clap"
3544                    | "mathllap"
3545                    | "mathrlap"
3546                    | "mathclap"
3547                    | "crampedllap"
3548                    | "crampedrlap"
3549                    | "crampedclap"
3550            ) {
3551                return self.padded_command(&name);
3552            }
3553            if let Some(class) = [
3554                "mathord",
3555                "mathop",
3556                "mathbin",
3557                "mathrel",
3558                "mathopen",
3559                "mathclose",
3560                "mathpunct",
3561                "mathinner",
3562                "vcenter",
3563            ]
3564            .iter()
3565            .position(|command| *command == name)
3566            {
3567                let atom = Atom::Class {
3568                    body: Box::new(self.padded_argument(&name)?),
3569                    class,
3570                };
3571                // commands.go mathClass returns a pending FnItem only for
3572                // this command, not for all generated OP TeXAtoms.
3573                return Some(if class == 1 {
3574                    Atom::NamedFunction(Box::new(atom))
3575                } else {
3576                    atom
3577                });
3578            }
3579            if name == "ce" || name == "pu" {
3580                // parseOneToken calls the command in the owning parser. The
3581                // inserted text belongs to its subsequent row, while this
3582                // one-token argument receives an empty inferred row.
3583                return Some(match self.insert_chemistry(&name) {
3584                    Ok(()) => Atom::Sequence(Vec::new()),
3585                    Err(message) => Atom::ErrorDisplay(message),
3586                });
3587            }
3588            if name == "celsius" || name == "perthousand" {
3589                return Some(Atom::Unit(if name == "celsius" { 0x2103 } else { 0x2030 }));
3590            }
3591            if matches!(
3592                name.as_str(),
3593                "text"
3594                    | "textnormal"
3595                    | "textrm"
3596                    | "textup"
3597                    | "textbf"
3598                    | "textit"
3599                    | "texttt"
3600                    | "textsf"
3601                    | "mbox"
3602                    | "hbox"
3603            ) {
3604                return self.hbox_command(&name);
3605            }
3606            if matches!(
3607                name.as_str(),
3608                "bra"
3609                    | "ket"
3610                    | "braket"
3611                    | "innerproduct"
3612                    | "ip"
3613                    | "Bra"
3614                    | "Ket"
3615                    | "Braket"
3616                    | "Set"
3617                    | "set"
3618            ) {
3619                return self.native_braket(&name);
3620            }
3621            if matches!(
3622                name.as_str(),
3623                "mathbb" | "mathbf" | "mathfrak" | "mathit" | "mathclap" | "substack"
3624            ) {
3625                return self.atom_or_group();
3626            }
3627            if name == "operatorname" {
3628                return self.operator_name();
3629            }
3630            if name == "colon" {
3631                // Base mathchar0mo: mo ":" with an explicit texClass PUNCT.
3632                let mut definition =
3633                    operator_dictionary::lookup(0x3A, operator_dictionary::Form::Infix);
3634                definition.class = 6;
3635                return Some(Atom::RawOperator {
3636                    attributes: &[],
3637                    cleanup: false,
3638                    texclass: Some(6),
3639                    code: 0x3A,
3640                    body: Box::new(Atom::Glyph(0x3A)),
3641                    definition,
3642                });
3643            }
3644            if matches!(name.as_str(), "limits" | "nolimits") {
3645                return Some(Atom::Sequence(Vec::new()));
3646            }
3647            if name == "textcolor" {
3648                let color = resolve_named_color(self.braced_text()?);
3649                if let Some(cell) = &mut self.array_cell {
3650                    cell.rule_allowed = false;
3651                }
3652                let previous_color = self.active_color.replace(color.clone());
3653                let body = self.atom_or_group();
3654                self.active_color = previous_color;
3655                return Some(Atom::Color {
3656                    body: Box::new(body?),
3657                    color,
3658                });
3659            }
3660            if name == "color" {
3661                let color = resolve_named_color(self.braced_text()?);
3662                if let Some(cell) = &mut self.array_cell {
3663                    cell.rule_allowed = false;
3664                }
3665                return Some(Atom::Color {
3666                    body: Box::new(Atom::Sequence(Vec::new())),
3667                    color,
3668                });
3669            }
3670            if name == "colorbox" {
3671                let background = match self.padded_raw_argument(&name) {
3672                    Ok(raw) => resolve_named_color(raw),
3673                    Err(error) => return Some(Atom::ErrorDisplay(error)),
3674                };
3675                let text = match self.padded_raw_argument(&name) {
3676                    Ok(raw) => raw,
3677                    Err(error) => return Some(Atom::ErrorDisplay(error)),
3678                };
3679                return Some(Atom::ColorBox {
3680                    // commands.go colorBox uses internalMath, whose literal
3681                    // text retains tildes and inherits the creating font.
3682                    body: Box::new(self.internal_math(&text, None, false)?),
3683                    background,
3684                    mathsize: 1.,
3685                });
3686            }
3687            if matches!(name.as_str(), "cancel" | "bcancel" | "xcancel" | "cancelto") {
3688                return self.enclose_command(&name);
3689            }
3690            if matches!(
3691                name.as_str(),
3692                "qty"
3693                    | "quantity"
3694                    | "pqty"
3695                    | "bqty"
3696                    | "Bqty"
3697                    | "vqty"
3698                    | "abs"
3699                    | "absolutevalue"
3700                    | "norm"
3701                    | "order"
3702            ) {
3703                return self.physics_quantity(&name);
3704            }
3705            if matches!(
3706                name.as_str(),
3707                "dv" | "derivative"
3708                    | "pdv"
3709                    | "partialderivative"
3710                    | "pderivative"
3711                    | "fdv"
3712                    | "fderivative"
3713                    | "functionalderivative"
3714                    | "dd"
3715                    | "differential"
3716                    | "var"
3717                    | "variation"
3718            ) {
3719                return self.physics_derivative(&name);
3720            }
3721            if matches!(
3722                name.as_str(),
3723                "vert" | "lvert" | "rvert" | "Vert" | "lVert" | "rVert"
3724            ) {
3725                let code = if name.contains("Vert") { 0x2016 } else { 0x7c };
3726                // The source DelimiterMap entry's explicit texClass (e.g. \vert
3727                // ORD, \lvert OPEN) survives operator inheritance.
3728                let texclass = source_symbols::lookup(&name).and_then(|symbol| {
3729                    symbol
3730                        .attributes
3731                        .iter()
3732                        .find(|(key, _)| *key == "texClass")
3733                        .and_then(|(_, value)| value.parse::<i8>().ok())
3734                });
3735                let mut definition =
3736                    operator_dictionary::lookup(code, operator_dictionary::Form::Infix);
3737                if let Some(class) = texclass {
3738                    definition.class = class;
3739                }
3740                return Some(Atom::RawOperator {
3741                    attributes: &[],
3742                    cleanup: false,
3743                    texclass,
3744                    code,
3745                    body: Box::new(Atom::Glyph(code)),
3746                    definition,
3747                });
3748            }
3749            if physics::is_function(&name) {
3750                return self.physics_expression(&name);
3751            }
3752            if name == "left" {
3753                return self.left_right();
3754            }
3755            if name == "right" {
3756                return Some(Atom::ErrorDisplay(
3757                    self.native_delimiter("right", false)
3758                        .err()
3759                        .unwrap_or_else(|| "Missing \\left or extra \\right".into()),
3760                ));
3761            }
3762            if name == "middle" {
3763                return self.middle();
3764            }
3765            if let Some(size) = braket::fixed_size(&name) {
3766                let code = match self.native_delimiter(&name, true) {
3767                    Ok(c) => c,
3768                    Err(e) => return Some(Atom::ErrorDisplay(e)),
3769                };
3770                let class = if name.ends_with('l') {
3771                    4
3772                } else if name.ends_with('r') {
3773                    5
3774                } else if name.ends_with('m') {
3775                    3
3776                } else {
3777                    0
3778                };
3779                return Some(Atom::Class {
3780                    body: Box::new(Atom::FixedDelimiter { code, size }),
3781                    class,
3782                });
3783            }
3784            if matches!(name.as_str(), "degree" | "micro" | "ohm") {
3785                return command_codepoint(&name).map(Atom::Unit);
3786            }
3787            if matches!(name.as_str(), "sum" | "prod") {
3788                return Some(Atom::MovesScripts(Box::new(
3789                    self.nonambient_font(Atom::Glyph(command_codepoint(&name)?)),
3790                )));
3791            }
3792            if matches!(name.as_str(), "space" | "nobreakspace") {
3793                return Some(Atom::Text("\u{00a0}".to_owned()));
3794            }
3795            if name == "rightleftharpoons" {
3796                return Some(Atom::VariantGlyph(0x21CC));
3797            }
3798            if name == "hbar" {
3799                return Some(Atom::VariantGlyph(0x210F));
3800            }
3801            if name == "prime" {
3802                return Some(Atom::VariantGlyph(0x2032));
3803            }
3804            if name == "backprime" {
3805                return Some(Atom::VariantGlyph(0x2035));
3806            }
3807            if let Some((code, normal)) = source_identifier(&name) {
3808                let glyph = if self.normal_font {
3809                    Atom::Glyph(code)
3810                } else if self.calligraphic_font {
3811                    Atom::CalligraphicGlyph(code)
3812                } else if normal {
3813                    Atom::Glyph(code)
3814                } else {
3815                    automatic_italic_atom(char::from_u32(code).unwrap())
3816                };
3817                // These original map entries create mi tokens, including
3818                // non-letter identifiers such as partial and nabla.
3819                let token = Atom::Identifier(vec![glyph]);
3820                return Some(
3821                    if source_symbols::lookup(&name)
3822                        .is_some_and(|s| s.parser == source_symbols::Parser::Mathchar7)
3823                    {
3824                        self.ambient_font(token)
3825                    } else {
3826                        self.nonambient_font(token)
3827                    },
3828                );
3829            }
3830            if let Some(codepoint) = command_codepoint(&name) {
3831                if command_symbol(&name)
3832                    .is_some_and(|s| s.attributes.contains(&("accent", "false")))
3833                {
3834                    return self.source_symbol(&name);
3835                }
3836                if source_symbols::lookup(&name)
3837                    .is_some_and(|s| s.parser == source_symbols::Parser::Mathchar7)
3838                {
3839                    return self.source_symbol(&name);
3840                }
3841                let token = self.nonambient_font(Atom::Glyph(
3842                    if self.normal_font && (0x1D6FC..=0x1D714).contains(&codepoint) {
3843                        match name.as_str() {
3844                            // Base character map retains these variant Greek identities.
3845                            "epsilon" => 0x3F5,
3846                            "phi" => 0x3D5,
3847                            _ => 0x3B1 + codepoint - 0x1D6FC,
3848                        }
3849                    } else {
3850                        codepoint
3851                    },
3852                ));
3853                return Some(
3854                    if source_symbols::lookup(&name).is_some_and(|s| {
3855                        s.parser == source_symbols::Parser::Mathchar0mo
3856                            && operator_dictionary::lookup(
3857                                codepoint,
3858                                operator_dictionary::Form::Infix,
3859                            )
3860                            .class
3861                                == 0
3862                    }) {
3863                        Atom::Ord(Box::new(Atom::RawOperator {
3864                            attributes: source_symbols::lookup(&name)?.attributes,
3865                            cleanup: true,
3866                            code: codepoint,
3867                            body: Box::new(token),
3868                            definition: operator_dictionary::lookup(
3869                                codepoint,
3870                                operator_dictionary::Form::Infix,
3871                            ),
3872                            texclass: None,
3873                        }))
3874                    } else {
3875                        token
3876                    },
3877                );
3878            }
3879            if let Some(text) = physics::function_name(&name) {
3880                let moving = matches!(
3881                    name.as_str(),
3882                    "lim" | "min" | "max" | "sup" | "inf" | "gcd" | "liminf" | "limsup"
3883                );
3884                let token = text.chars().map(|c| Atom::Glyph(c as u32)).collect();
3885                let body = if moving {
3886                    Atom::OperatorToken(token)
3887                } else {
3888                    Atom::Identifier(token)
3889                };
3890                let operator = Atom::Operator(Box::new(self.nonambient_font(body)));
3891                // Original commands.go: non-limit function names set
3892                // commandNamedFunction, so parseRow's pending FnItem may add
3893                // an ApplyFunction before the next item.
3894                return Some(if moving {
3895                    Atom::MovesScripts(Box::new(operator))
3896                } else {
3897                    Atom::NamedFunction(Box::new(operator))
3898                });
3899            }
3900            if let Some(atom) = self.source_symbol(&name) {
3901                return Some(atom);
3902            }
3903            // A valid source command with an untranslated native handler stays
3904            // on the visible implementation fallback, never an undefined error.
3905            return None;
3906        }
3907        if character == '}' {
3908            return None;
3909        }
3910        if character == '~' {
3911            return Some(Atom::Text("\u{a0}".to_owned()));
3912        }
3913        // parser.go otherNode consults the option only for math tokens;
3914        // InternalText retains literal colons and subsequent option changes.
3915        if character == ':' {
3916            return Some(
3917                self.mathtools_colon(self.ams.borrow().option("centercolon") == "true", false),
3918            );
3919        }
3920        if self.operator_letters
3921            && (character.is_ascii_alphabetic() || matches!(character, '-' | '*'))
3922        {
3923            let mut letters = vec![character];
3924            if self.operator_pattern {
3925                while self
3926                    .chars
3927                    .get(self.index)
3928                    .is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '-' | '*'))
3929                {
3930                    letters.push(self.chars[self.index]);
3931                    self.index += 1;
3932                }
3933            } else if matches!(character, '-' | '*') && self.multi_letter_font {
3934                return Some(Atom::SourceError(format!(
3935                    "identifier pattern does not match {:?}",
3936                    character.to_string()
3937                )));
3938            } else if self.multi_letter_font {
3939                while self
3940                    .chars
3941                    .get(self.index)
3942                    .is_some_and(|c| c.is_ascii_alphabetic())
3943                {
3944                    letters.push(self.chars[self.index]);
3945                    self.index += 1;
3946                }
3947            }
3948            let token = self.ambient_font(Atom::Identifier(
3949                letters
3950                    .into_iter()
3951                    .map(|c| {
3952                        if self.active_font == Some("") {
3953                            automatic_italic_atom(c)
3954                        } else {
3955                            Atom::Glyph(c as u32)
3956                        }
3957                    })
3958                    .collect(),
3959            ));
3960            return Some(
3961                if self.operator_pattern
3962                    && !self.no_auto_operator
3963                    && matches!(&token, Atom::Identifier(v) if automatic_operator(v))
3964                {
3965                    Atom::AutoOperator(Box::new(token))
3966                } else {
3967                    token
3968                },
3969            );
3970        }
3971        // parser.go ordinaryNumberPattern: literal commas are separate mo
3972        // tokens; only braced thousands separators belong to one number.
3973        if character.is_ascii_digit() || matches!(character, '.' | ',') {
3974            static NUMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
3975            let pattern = NUMBER.get_or_init(|| {
3976                regex::Regex::new(r"^(?:[0-9]+(?:\{,\}[0-9]{3})*(?:\.[0-9]*)?|\.[0-9]+)").unwrap()
3977            });
3978            let rest: String = self.chars[self.index - 1..].iter().collect();
3979            if let Some(number) = pattern.find(&rest) {
3980                self.index += number.as_str().chars().count() - 1;
3981                return Some(
3982                    self.ambient_font(Atom::Number(
3983                        number
3984                            .as_str()
3985                            .chars()
3986                            .filter(|c| !matches!(c, '{' | '}'))
3987                            .map(|c| Atom::Glyph(c as u32))
3988                            .collect(),
3989                    )),
3990                );
3991            }
3992            // The digit scanner does not register fixStretchy on unmatched
3993            // dots/commas, unlike BaseConfiguration.Other.
3994            return Some(self.ambient_font(Atom::RawOperator {
3995                attributes: &[],
3996                cleanup: false,
3997                texclass: None,
3998                code: character as u32,
3999                body: Box::new(Atom::Glyph(character as u32)),
4000                definition: operator_dictionary::lookup(
4001                    character as u32,
4002                    operator_dictionary::Form::Infix,
4003                ),
4004            }));
4005        }
4006        if self.multi_letter_font && character.is_ascii_alphabetic() {
4007            let mut letters = vec![character];
4008            while self
4009                .chars
4010                .get(self.index)
4011                .is_some_and(|c| c.is_ascii_alphabetic())
4012            {
4013                letters.push(self.chars[self.index]);
4014                self.index += 1;
4015            }
4016            return Some(
4017                self.ambient_font(Atom::Identifier(
4018                    letters
4019                        .into_iter()
4020                        .map(|c| {
4021                            if self.calligraphic_font {
4022                                Atom::CalligraphicGlyph(c as u32)
4023                            } else {
4024                                Atom::Glyph(c as u32)
4025                            }
4026                        })
4027                        .collect(),
4028                )),
4029            );
4030        }
4031        // Source applyMathVariant changes the variant on the original token,
4032        // never rewrites a physical SMP/Planck character into an ASCII letter.
4033        if matches!(character as u32, 0x1D400..=0x1D7FF | 0x210E) {
4034            let code = character as u32;
4035            // Font SMP remapping owns known physical glyphs. A hole in that
4036            // table remains a one-character mi with the default italic variant.
4037            let glyph = if uses_normal_text_fallback(code) {
4038                self.ambient_font(Atom::ItalicGlyph(code))
4039            } else {
4040                self.nonambient_font(Atom::LiteralGlyph(code))
4041            };
4042            return Some(Atom::Identifier(vec![glyph]));
4043        }
4044        let range = operator_dictionary::range(character as u32);
4045        // parser.go parseCharacterChecked: Other without a pinned Unicode
4046        // range is a conversion error, rather than a rendered TeX diagnostic.
4047        if range.is_none() && !number_unicode::is_digit(character) {
4048            return Some(Atom::SourceError(format!(
4049                "no Unicode range for character U+{:04X}",
4050                character as u32
4051            )));
4052        }
4053        let identifier = character.is_ascii_alphabetic() || range.is_some_and(|r| r.kind == "mi");
4054        if identifier && range.is_some_and(|r| r.variant == Some("normal")) {
4055            // Other's authored range variant overrides the ambient font.
4056            return Some(
4057                self.nonambient_font(Atom::Identifier(vec![Atom::Glyph(character as u32)])),
4058            );
4059        }
4060        if !identifier {
4061            let code = match character {
4062                '-' => 0x2212,
4063                '*' => 0x2217,
4064                '`' => 0x2018,
4065                _ => character as u32,
4066            };
4067            // tex/inheritance.go moPrimeRemap changes the rendered text,
4068            // retaining the authored operator for dictionary classification.
4069            let paint = match code {
4070                0x22 | 0x201D | 0x201E => 0x2033,
4071                0x27 | 0x2019 | 0x201A => 0x2032,
4072                0x60 | 0x2018 | 0x201B => 0x2035,
4073                0x201C | 0x201F => 0x2036,
4074                _ => code,
4075            };
4076            let body = if matches!(character, ')' | ']' | '|') {
4077                // parser.go Physics AutoClose creates its own non-stretchy
4078                // mo, without Other's ambient-font eligibility.
4079                self.nonambient_font(Atom::Glyph(paint))
4080            } else if self.calligraphic_font {
4081                Atom::CalligraphicGlyph(paint)
4082            } else {
4083                self.ambient_font(Atom::Glyph(paint))
4084            };
4085            let definition = operator_dictionary::lookup(code, operator_dictionary::Form::Infix);
4086            let operator = Atom::RawOperator {
4087                attributes: &[],
4088                cleanup: !matches!(character, ')' | ']' | '|'),
4089                texclass: None,
4090                code,
4091                body: Box::new(body),
4092                definition,
4093            };
4094            // tex/clean_stretchy.go wraps registered raw ORD operators in a
4095            // TeXAtom after inheritance; command-produced tokens stay distinct.
4096            return Some(
4097                if definition.class == 0 && !matches!(character, ')' | ']' | '|') {
4098                    Atom::Ord(Box::new(operator))
4099                } else {
4100                    operator
4101                },
4102            );
4103        }
4104        if self.calligraphic_font {
4105            return Some(Atom::CalligraphicGlyph(character as u32));
4106        }
4107        // Original base remap table converts a math hyphen to U+2212 even
4108        // under a normal-font TeXAtom; literal text remains a hyphen.
4109        if !self.normal_font && identifier {
4110            return Some(
4111                self.ambient_font(Atom::Identifier(vec![automatic_italic_atom(character)])),
4112            );
4113        }
4114        Some(Atom::Glyph(if character == '-' {
4115            0x2212
4116        } else {
4117            character as u32
4118        }))
4119    }
4120
4121    fn braced_text(&mut self) -> Option<String> {
4122        while self
4123            .chars
4124            .get(self.index)
4125            .is_some_and(|c| c.is_whitespace())
4126        {
4127            self.index += 1;
4128        }
4129        if self.chars.get(self.index) != Some(&'{') {
4130            return None;
4131        }
4132        self.index += 1;
4133        let start = self.index;
4134        let mut depth = 1;
4135        while self.index < self.chars.len() {
4136            match self.chars[self.index] {
4137                '\\' => {
4138                    self.index += 1;
4139                }
4140                '{' => depth += 1,
4141                '}' => {
4142                    depth -= 1;
4143                    if depth == 0 {
4144                        let text = self.chars[start..self.index].iter().collect();
4145                        self.index += 1;
4146                        return Some(text);
4147                    }
4148                }
4149                _ => {}
4150            }
4151            self.index += 1;
4152        }
4153        None
4154    }
4155
4156    // tex/dimension.go GetDimen owns its own whitespace and argument scan.
4157    fn read_dimension(&mut self, name: &str) -> Result<String, String> {
4158        let missing = || format!("Missing dimension or its units for \\{name}");
4159        static GRAMMAR: std::sync::OnceLock<(regex::Regex, regex::Regex)> =
4160            std::sync::OnceLock::new();
4161        let (full, prefix) = GRAMMAR.get_or_init(|| {
4162            let space = r"[\t-\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}\x{feff}]";
4163            let value = format!(r"{space}*([-+]?(?:[.,][0-9]+|[0-9]+(?:[.,][0-9]*)?)){space}*(pt|em|ex|mu|px|mm|cm|in|pc)");
4164            (regex::Regex::new(&format!(r"^{value}{space}*$")).unwrap(),
4165             regex::Regex::new(&format!(r"^{value} ?")).unwrap())
4166        });
4167        while self.chars.get(self.index).is_some_and(|c| {
4168            matches!(
4169                c, '\t'..='\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' |
4170                '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}'
4171            )
4172        }) {
4173            self.index += 1;
4174        }
4175        let braced = self.chars.get(self.index) == Some(&'{');
4176        let raw = if braced {
4177            self.braced_text()
4178                .ok_or_else(|| "Missing close brace".to_owned())?
4179        } else {
4180            self.chars[self.index..].iter().collect()
4181        };
4182        let captures = if braced { full } else { prefix }
4183            .captures(&raw)
4184            .ok_or_else(missing)?;
4185        if !braced {
4186            self.index += captures[0].chars().count();
4187        }
4188        let numeric = captures[1].replace(',', ".");
4189        if &captures[2] == "mu" {
4190            let em = numeric.parse::<f64>().unwrap_or(0.0) / 18.0;
4191            if em.abs() < 0.0006 {
4192                return Ok("0em".into());
4193            }
4194            return Ok(format!(
4195                "{}em",
4196                number(em.signum() * alignment::round_thousandth(em.abs()))
4197            ));
4198        }
4199        Ok(format!("{numeric}{}", &captures[2]))
4200    }
4201
4202    fn mathtools_colon(&self, center: bool, thin: bool) -> Atom {
4203        let colon = Atom::RawOperator {
4204            attributes: &[],
4205            cleanup: false,
4206            texclass: None,
4207            code: 0x3a,
4208            body: Box::new(Atom::Glyph(0x3a)),
4209            definition: operator_dictionary::lookup(0x3a, operator_dictionary::Form::Infix),
4210        };
4211        if !center {
4212            return colon;
4213        }
4214        let dy = length::dimension(&self.ams.borrow().option("centercolon-offset")).em(0.0, 1.0);
4215        let mut padding = padded::Padding {
4216            height_add: dy,
4217            depth_add: -dy,
4218            voffset_em: dy,
4219            ..Default::default()
4220        };
4221        if thin {
4222            let width = self.ams.borrow().option("thincolon-dw");
4223            let value = length::dimension(&width).em(0.0, 1.0);
4224            if width.starts_with(['+', '-']) {
4225                padding.width_add = value;
4226            } else {
4227                padding.width_absolute = Some(value);
4228            }
4229            padding.lspace_em =
4230                length::dimension(&self.ams.borrow().option("thincolon-dx")).em(0.0, 1.0);
4231        }
4232        Atom::Padded {
4233            body: Box::new(colon),
4234            padding,
4235        }
4236    }
4237
4238    fn environment(&mut self, environment: &str) -> Option<Atom> {
4239        let in_root = self.in_root;
4240        if root_index::array_environment(environment) {
4241            self.in_root = false;
4242        }
4243        let result = self.environment_inner(environment);
4244        self.in_root = in_root;
4245        result
4246    }
4247    fn environment_inner(&mut self, environment: &str) -> Option<Atom> {
4248        // BeginEnd dispatches the literal name and rejects it before reading
4249        // a body (pinned tex/environment_count.go and environments.go).
4250        if environment.contains('\\') {
4251            return Some(Atom::ErrorDisplay(format!(
4252                "Invalid environment name '{environment}'"
4253            )));
4254        }
4255        if !known_environment(environment) {
4256            return Some(Atom::ErrorDisplay(format!(
4257                "Unknown environment '{environment}'"
4258            )));
4259        }
4260        if environment == "spreadlines" {
4261            let spread = match self.read_dimension("begin") {
4262                Ok(v) => v,
4263                Err(message) => return Some(Atom::ErrorDisplay(message)),
4264            };
4265            let body = match self.capture_environment(environment) {
4266                Ok(v) => v,
4267                Err(e) => return Some(Atom::ErrorDisplay(e)),
4268            };
4269            let mut atom = parse_with_root_stack(
4270                &body,
4271                self.ams.clone(),
4272                self.equation_seen.clone(),
4273                self.in_root,
4274                self.root_moves.clone(),
4275            )?;
4276            table::spread(&mut atom, length::dimension(&spread).em(0.0, 1.0));
4277            self.splice_inferred = true;
4278            return Some(atom);
4279        }
4280        if matches!(environment, "numcases" | "subnumcases") {
4281            if let Err(error) = self.padded_raw_argument(&format!("begin{{{environment}}}")) {
4282                return Some(Atom::ErrorDisplay(error));
4283            }
4284            let body = match self.capture_environment(environment) {
4285                Ok(v) => v,
4286                Err(e) => return Some(Atom::ErrorDisplay(e)),
4287            };
4288            for cells in table::raw_rows(&body) {
4289                let atom = parse_unresolved_shared(cells[0].trim(), self.ams.clone())?;
4290                if cd::first_error(&atom).is_some() {
4291                    return Some(atom);
4292                }
4293                if cells.len() > 2 {
4294                    return Some(Atom::ErrorDisplay(
4295                        "Extra alignment tab in text for numcase environment".into(),
4296                    ));
4297                }
4298            }
4299            // Cases emits this dependency after row parsing, but D2 does not
4300            // activate EmpheqConfiguration in its default compiler.
4301            return Some(Atom::ErrorDisplay(
4302                "Undefined control sequence \\empheqlbrace".into(),
4303            ));
4304        }
4305        let mut multline = matches!(environment, "multline" | "multline*" | "multlined")
4306            .then(table::MultlineOptions::default);
4307        if environment == "multlined" {
4308            let present =
4309                self.chars[self.index..].iter().find(|c| !c.is_whitespace()) == Some(&'[');
4310            let first = match self.padded_brackets() {
4311                Ok(v) => {
4312                    if !present {
4313                        self.ams.borrow().option("multlined-pos")
4314                    } else {
4315                        v
4316                    }
4317                }
4318                Err(e) => return Some(Atom::ErrorDisplay(e)),
4319            };
4320            let second = if !first.is_empty() {
4321                match self.padded_brackets() {
4322                    Ok(v) => v,
4323                    Err(e) => return Some(Atom::ErrorDisplay(e)),
4324                }
4325            } else {
4326                String::new()
4327            };
4328            let (position, width) = if present && !"cbt".contains(first.as_str()) {
4329                (second, first)
4330            } else {
4331                (first, second)
4332            };
4333            let options = multline.as_mut().unwrap();
4334            options.position = position;
4335            options.width = width;
4336        }
4337        let column_spec = if matches!(environment, "array" | "subarray" | "crampedsubarray") {
4338            match self.padded_raw_argument(&format!("begin{{{environment}}}")) {
4339                Ok(v) => v,
4340                Err(e) => return Some(Atom::ErrorDisplay(e)),
4341            }
4342        } else if matches!(environment, "aligned" | "alignedat") {
4343            match self.padded_brackets() {
4344                Ok(value) => match value.trim() {
4345                    "t" => "baseline 1".into(),
4346                    "b" => "baseline -1".into(),
4347                    "c" => "axis".into(),
4348                    value => value.into(),
4349                },
4350                Err(message) => {
4351                    let message = if message == "Could not find closing ']' for argument" {
4352                        format!("{message} to \\begin")
4353                    } else {
4354                        message
4355                    };
4356                    return Some(Atom::ErrorDisplay(message));
4357                }
4358            }
4359        } else if environment.ends_with('*') && environment.contains("matrix") {
4360            let present =
4361                self.chars[self.index..].iter().find(|c| !c.is_whitespace()) == Some(&'[');
4362            match self.padded_brackets() {
4363                Ok(value) => {
4364                    if !present && environment.contains("smallmatrix") {
4365                        self.ams.borrow().option("smallmatrix-align")
4366                    } else {
4367                        value
4368                    }
4369                }
4370                Err(message) => return Some(Atom::ErrorDisplay(message)),
4371            }
4372        } else {
4373            String::new()
4374        };
4375        // Source beginEnvironment consumes the pair-count argument before
4376        // captureEnvironment. Its contents are not part of the table cells.
4377        let mut pair_count = None;
4378        if environment.contains("alignat") || environment == "alignedat" {
4379            let count = match self.padded_raw_argument("begin") {
4380                Ok(count) => count,
4381                Err(message) => return Some(Atom::ErrorDisplay(message)),
4382            };
4383            if !count.chars().all(|c| c.is_ascii_digit()) {
4384                return Some(Atom::ErrorDisplay(format!(
4385                    "Argument to \\begin{{{environment}}} must me a positive integer"
4386                )));
4387            }
4388            pair_count = Some(count);
4389        }
4390        // parser.go checkEquationEnvironment: Stack.global survives End and
4391        // row/cell continuations; a real child parser starts a fresh stack.
4392        if matches!(
4393            environment,
4394            "equation"
4395                | "equation*"
4396                | "align"
4397                | "align*"
4398                | "alignat"
4399                | "alignat*"
4400                | "flalign"
4401                | "flalign*"
4402                | "xalignat"
4403                | "xalignat*"
4404                | "xxalignat"
4405                | "gather"
4406                | "gather*"
4407                | "eqnarray"
4408                | "eqnarray*"
4409                | "multline"
4410                | "multline*"
4411        ) && self.equation_seen.replace(true)
4412        {
4413            return Some(Atom::ErrorDisplay(
4414                "Erroneous nesting of equation structures".into(),
4415            ));
4416        }
4417        let content = match self.capture_environment(environment) {
4418            Ok(content) => content,
4419            Err(message) => return Some(Atom::ErrorDisplay(message)),
4420        };
4421        if !known_environment(environment) {
4422            return Some(Atom::ErrorDisplay(format!(
4423                "Unknown environment '{environment}'"
4424            )));
4425        }
4426        // The starred mathtools cases forms typeset their second column as
4427        // text (mathtools_handlers_environments.go); that path is not
4428        // translated, so refuse instead of laying the column out as math.
4429        if environment.ends_with("cases*") {
4430            return None;
4431        }
4432        if let Some(mut options) = multline {
4433            let rows = table::parse_multline(
4434                &content,
4435                environment,
4436                self.ams.clone(),
4437                self.equation_seen.clone(),
4438                &mut options,
4439            )?;
4440            return Some(Atom::Matrix {
4441                spacing: None,
4442                options: Some(options),
4443                rows,
4444                environment: environment.into(),
4445                column_spec,
4446            });
4447        }
4448        if environment == "CD" {
4449            let body = cd::parse_rows(&content, self.ams.clone(), self.equation_seen.clone())?;
4450            let options = Some(table::MultlineOptions {
4451                row_spacing: body.spacing,
4452                align: body.align,
4453                rules: body.rules,
4454                ..Default::default()
4455            });
4456            return Some(Atom::Matrix {
4457                spacing: None,
4458                options,
4459                rows: body.rows,
4460                environment: environment.to_owned(),
4461                column_spec,
4462            });
4463        }
4464        // Only equation/equation* own this AMS tag scope. The legacy
4465        // math/displaymath handlers are unreachable: neither name is in
4466        // the pinned default environment maps.
4467        if matches!(environment, "equation" | "equation*") {
4468            self.ams.borrow_mut().start("equation");
4469            let result = parse_with_root_stack(
4470                &content,
4471                self.ams.clone(),
4472                self.equation_seen.clone(),
4473                self.in_root,
4474                self.root_moves.clone(),
4475            );
4476            let tag = ams::get_tag(&self.ams)?;
4477            self.ams.borrow_mut().end();
4478            if let Some(tag) = tag {
4479                return Some(Atom::TaggedTable {
4480                    spacing: None,
4481                    rows: vec![vec![result?]],
4482                    tags: vec![Some(tag)],
4483                    environment: "equation-tag".into(),
4484                    container_align: "center",
4485                });
4486            }
4487            self.splice_inferred = true;
4488            return result;
4489        }
4490        let scoped = matches!(environment, "split" | "align" | "align*" | "aligned");
4491        if scoped {
4492            self.ams.borrow_mut().start(environment);
4493        }
4494        let mut options = None;
4495        let rows = table::parse_rows_count_options(
4496            &content,
4497            environment,
4498            self.ams.clone(),
4499            self.equation_seen.clone(),
4500            pair_count.as_deref(),
4501            &mut options,
4502        );
4503        let tags = self.ams.borrow().current.row_tags.clone();
4504        if scoped {
4505            self.ams.borrow_mut().end();
4506        }
4507        if scoped && tags.iter().any(Option::is_some) {
4508            return Some(Atom::TaggedTable {
4509                spacing: None,
4510                rows: rows?,
4511                tags,
4512                environment: environment.into(),
4513                container_align: "center",
4514            });
4515        }
4516        if environment == "alignedat" {
4517            let options = options.get_or_insert_with(Default::default);
4518            options.position = column_spec.clone();
4519            if pair_count
4520                .as_ref()
4521                .is_some_and(|count| count.trim_start_matches('0').is_empty())
4522            {
4523                options.align = rows
4524                    .as_ref()?
4525                    .iter()
4526                    .map(|r| vec!["center"; r.len()])
4527                    .collect();
4528                options.column_gap = Some(1.0);
4529            }
4530        }
4531        Some(Atom::Matrix {
4532            spacing: None,
4533            options,
4534            rows: rows?,
4535            environment: environment.to_owned(),
4536            column_spec,
4537        })
4538    }
4539
4540    // Original tex/parser.go readControlSequence/readArgument and
4541    // environments.go captureEnvironment. Escaped control characters do not
4542    // start environments; only matching trimmed names affect nesting.
4543    fn capture_environment(&mut self, environment: &str) -> Result<String, String> {
4544        let start = self.index;
4545        let mut depth = 1usize;
4546        let mut braces = 0usize;
4547        while self.index < self.chars.len() {
4548            if matches!(environment, "numcases" | "subnumcases") {
4549                match self.chars[self.index] {
4550                    '{' => braces += 1,
4551                    '}' => braces = braces.saturating_sub(1),
4552                    '&' if braces == 0 => {
4553                        // Do not raise a text error while capturing ahead
4554                        // of a formula that still needs to execute.
4555                        if let Ok(end) = cases::text_end(&self.chars, self.index + 1) {
4556                            self.index = end;
4557                            continue;
4558                        }
4559                    }
4560                    _ => {}
4561                }
4562            }
4563            if self.chars[self.index] != '\\' {
4564                self.index += 1;
4565                continue;
4566            }
4567            let command_start = self.index;
4568            self.index += 1;
4569            let name = self.capture_control_sequence();
4570            if name != "begin" && name != "end" {
4571                continue;
4572            }
4573            while self
4574                .chars
4575                .get(self.index)
4576                .is_some_and(|c| c.is_whitespace())
4577            {
4578                self.index += 1;
4579            }
4580            let raw = match self.chars.get(self.index) {
4581                None => return Err(format!("Missing argument for \\{name}")),
4582                Some('}') => return Err("Extra close brace or missing open brace".to_owned()),
4583                Some('{') => self
4584                    .braced_text()
4585                    .ok_or_else(|| "Missing close brace".to_owned())?,
4586                Some('\\') => {
4587                    let argument_start = self.index;
4588                    self.index += 1;
4589                    self.capture_control_sequence();
4590                    self.chars[argument_start..self.index].iter().collect()
4591                }
4592                Some(_) => {
4593                    let value = self.chars[self.index].to_string();
4594                    self.index += 1;
4595                    value
4596                }
4597            };
4598            if raw.trim() != environment {
4599                continue;
4600            }
4601            if name == "begin" {
4602                depth += 1;
4603            } else {
4604                depth -= 1;
4605                if depth == 0 {
4606                    return Ok(self.chars[start..command_start].iter().collect());
4607                }
4608            }
4609        }
4610        Err(format!("Missing \\end{{{environment}}}"))
4611    }
4612
4613    fn capture_control_sequence(&mut self) -> String {
4614        let start = self.index;
4615        if self
4616            .chars
4617            .get(self.index)
4618            .is_some_and(|c| c.is_ascii_alphabetic())
4619        {
4620            while self
4621                .chars
4622                .get(self.index)
4623                .is_some_and(|c| c.is_ascii_alphabetic())
4624            {
4625                self.index += 1;
4626            }
4627            let name = self.chars[start..self.index].iter().collect();
4628            if self.chars.get(self.index) == Some(&' ') {
4629                self.index += 1;
4630            }
4631            name
4632        } else if let Some(c) = self.chars.get(self.index).copied() {
4633            self.index += 1;
4634            c.to_string()
4635        } else {
4636            " ".to_owned()
4637        }
4638    }
4639}
4640
4641// D2's default compiler has no augmented empheq/newcommand environment map.
4642// Registered names from source_tables_{base,ams,mathtools,amscd_braket_cases,
4643// physics}_maps.go. Legacy handler switch cases in environments.go do not
4644// register names (notably math and displaymath).
4645fn known_environment(name: &str) -> bool {
4646    matches!(
4647        name,
4648        "equation"
4649            | "equation*"
4650            | "split"
4651            | "matrix"
4652            | "matrix*"
4653            | "smallmatrix"
4654            | "smallmatrix*"
4655            | "array"
4656            | "subarray"
4657            | "crampedsubarray"
4658            | "pmatrix"
4659            | "pmatrix*"
4660            | "bmatrix"
4661            | "bmatrix*"
4662            | "Bmatrix"
4663            | "Bmatrix*"
4664            | "vmatrix"
4665            | "vmatrix*"
4666            | "Vmatrix"
4667            | "Vmatrix*"
4668            | "psmallmatrix"
4669            | "psmallmatrix*"
4670            | "bsmallmatrix"
4671            | "bsmallmatrix*"
4672            | "Bsmallmatrix"
4673            | "Bsmallmatrix*"
4674            | "vsmallmatrix"
4675            | "vsmallmatrix*"
4676            | "Vsmallmatrix"
4677            | "Vsmallmatrix*"
4678            | "cases"
4679            | "dcases"
4680            | "rcases"
4681            | "drcases"
4682            | "cases*"
4683            | "dcases*"
4684            | "rcases*"
4685            | "drcases*"
4686            | "numcases"
4687            | "subnumcases"
4688            | "align"
4689            | "align*"
4690            | "eqnarray"
4691            | "eqnarray*"
4692            | "alignat"
4693            | "alignat*"
4694            | "xalignat"
4695            | "xalignat*"
4696            | "xxalignat"
4697            | "aligned"
4698            | "alignedat"
4699            | "gather"
4700            | "gather*"
4701            | "gathered"
4702            | "multline"
4703            | "multline*"
4704            | "multlined"
4705            | "lgathered"
4706            | "rgathered"
4707            | "spreadlines"
4708            | "flalign"
4709            | "flalign*"
4710            | "CD"
4711    )
4712}
4713
4714fn layout(atom: &Atom) -> Option<Layout> {
4715    let mut result = Layout {
4716        bounds_em: None,
4717        width_em: None,
4718        intrinsic_width_em: None,
4719        width: 0.0,
4720        ascent: 0.0,
4721        depth: 0.0,
4722        glyphs: Vec::new(),
4723        rules: Vec::new(),
4724        groups: Vec::new(),
4725    };
4726    result.width = layout_at(atom, 0.0, 0.0, 1.0, &mut result)?;
4727    if let Some(width) = result.width_em {
4728        result.width = width * 1000.0;
4729    }
4730    retain_negative_glyph_depth(&mut result);
4731    ams::mark(&mut result, true);
4732    table::resolve(&mut result);
4733    Some(result)
4734}
4735
4736fn retain_negative_glyph_depth(bounds: &mut Layout) {
4737    if bounds.rules.is_empty()
4738        && bounds.groups.iter().all(|g| {
4739            matches!(
4740                g.kind,
4741                "TeXAtom"
4742                    | "mi"
4743                    | "mo"
4744                    | "msup"
4745                    | "msub"
4746                    | "msubsup"
4747                    | "mpadded"
4748                    | "mphantom"
4749                    | "mstyle"
4750                    | "mtext"
4751                    | "mover"
4752                    | "munder"
4753                    | "munderover"
4754                    | "mtable"
4755                    | "mspace"
4756            )
4757        })
4758        && (!bounds.glyphs.is_empty() || !bounds.groups.is_empty())
4759    {
4760        // Source BBox.Empty starts H/D at -infinity. Preserve signed natural
4761        // glyph bounds on both sides of the baseline before viewport clamping.
4762        if bounds.depth == 0.0 {
4763            bounds.depth = bounds
4764                .glyphs
4765                .iter()
4766                .filter_map(|g| {
4767                    glyph_for(*g).map(|data| data.depth * 1000.0 * g.scale - g.baseline)
4768                })
4769                .chain(
4770                    bounds
4771                        .groups
4772                        .iter()
4773                        .map(|g| styles::group_natural_bounds(g).1 - g.baseline),
4774                )
4775                .fold(f64::NEG_INFINITY, f64::max);
4776        }
4777        if bounds.ascent == 0.0 {
4778            bounds.ascent = bounds
4779                .glyphs
4780                .iter()
4781                .filter_map(|g| {
4782                    glyph_for(*g).map(|data| data.height * 1000.0 * g.scale + g.baseline)
4783                })
4784                .chain(
4785                    bounds
4786                        .groups
4787                        .iter()
4788                        .map(|g| styles::group_natural_bounds(g).0 + g.baseline),
4789                )
4790                .fold(f64::NEG_INFINITY, f64::max);
4791        }
4792    }
4793}
4794
4795fn layout_at(atom: &Atom, x: f64, baseline: f64, scale: f64, out: &mut Layout) -> Option<f64> {
4796    layout_at_with_style(atom, x, baseline, scale, out, true, false)
4797}
4798
4799fn layout_at_with_style(
4800    atom: &Atom,
4801    x: f64,
4802    baseline: f64,
4803    scale: f64,
4804    out: &mut Layout,
4805    display_style: bool,
4806    prime_style: bool,
4807) -> Option<f64> {
4808    out.intrinsic_width_em = None;
4809    let width =
4810        layout_at_with_style_inner(atom, x, baseline, scale, out, display_style, prime_style);
4811    if matches!(atom, Atom::Sequence(_)) && style_classes::has_declaration(atom)
4812        || !matches!(
4813            atom,
4814            Atom::Glyph(_)
4815                | Atom::Sequence(_)
4816                | Atom::Identifier(_)
4817                | Atom::Number(_)
4818                | Atom::OperatorToken(_)
4819                | Atom::StyledText(_)
4820                | Atom::Scripts { .. }
4821        )
4822    {
4823        out.intrinsic_width_em = None;
4824    }
4825    width
4826}
4827
4828fn layout_at_with_style_inner(
4829    atom: &Atom,
4830    x: f64,
4831    baseline: f64,
4832    scale: f64,
4833    out: &mut Layout,
4834    display_style: bool,
4835    prime_style: bool,
4836) -> Option<f64> {
4837    match atom {
4838        Atom::NonscriptSpace { .. } => None, // consumed by filterNonscript
4839        Atom::FontGlyph {
4840            original,
4841            paint,
4842            bold,
4843            font_variant,
4844        } => double_struck::layout(
4845            *original,
4846            *paint,
4847            *bold,
4848            font_variant,
4849            x,
4850            baseline,
4851            scale,
4852            out,
4853            display_style,
4854        ),
4855        Atom::FixedDelimiter { code, size } => {
4856            braket::layout_fixed(*code, *size, x, baseline, scale, out)
4857        }
4858        Atom::FenceDelimiter { code, class, color } => {
4859            let width =
4860                braket::layout_token(*code, *class, x, baseline, scale, out, display_style)?;
4861            if let Some(color) = braket::explicit_color(color.as_deref()) {
4862                out.groups.last_mut()?.color = Some(color);
4863            }
4864            Some(width)
4865        }
4866        Atom::Fenced {
4867            open,
4868            body,
4869            close,
4870            close_color,
4871            stretchy,
4872            ..
4873        } => braket::layout(
4874            *open,
4875            body,
4876            *close,
4877            close_color.as_deref(),
4878            *stretchy,
4879            x,
4880            baseline,
4881            scale,
4882            out,
4883            display_style,
4884            prime_style,
4885        ),
4886        Atom::NamedFunction(body) => {
4887            layout_at_with_style(body, x, baseline, scale, out, display_style, prime_style)
4888        }
4889        Atom::ApplyFunction => layout_at_with_style(
4890            &Atom::OperatorToken(vec![Atom::Glyph(0x2061)]),
4891            x,
4892            baseline,
4893            scale,
4894            out,
4895            display_style,
4896            prime_style,
4897        ),
4898        Atom::ExplicitRow(children) => {
4899            let mut local = general_fraction::blank();
4900            local.width = layout_at_with_style(
4901                &Atom::Sequence(children.clone()),
4902                0.,
4903                0.,
4904                scale,
4905                &mut local,
4906                display_style,
4907                prime_style,
4908            )?;
4909            retain_negative_glyph_depth(&mut local);
4910            let width = local.width;
4911            out.ascent = out.ascent.max(baseline + local.ascent);
4912            out.depth = out.depth.max(local.depth - baseline);
4913            out.width_em = local.width_em;
4914            out.groups.push(LayoutGroup {
4915                x_frame: None,
4916                data_cramped: None,
4917                own_translate: None,
4918                accent_offset: None,
4919                box_border: None,
4920                reference: None,
4921                tagged: None,
4922                percentage: None,
4923                table_line: None,
4924                mathsize: None,
4925                tex_class: 0,
4926                before_glyph: out.glyphs.len(),
4927                scale,
4928                x,
4929                baseline,
4930                color: None,
4931                background: None,
4932                kind: "mrow",
4933                delimiter: None,
4934                arrow: None,
4935                body: Box::new(local),
4936                lines: Vec::new(),
4937            });
4938            Some(width)
4939        }
4940        Atom::InferredRow(children) => physics::layout_inferred(
4941            children,
4942            x,
4943            baseline,
4944            scale,
4945            out,
4946            display_style,
4947            prime_style,
4948        ),
4949        Atom::SourceError(_) | Atom::ErrorDisplay(_) | Atom::Choice(_) => None,
4950        Atom::RawOperator {
4951            body, definition, ..
4952        } => operator_dictionary::layout(body, *definition, x, baseline, scale, out, display_style),
4953        Atom::DeclaredStyle {
4954            body,
4955            display,
4956            level,
4957        } => styles::layout_decl(body, *display, *level, x, baseline, out),
4958        Atom::DeclaredSize { body, factor } => styles::layout_size(
4959            body,
4960            *factor,
4961            x,
4962            baseline,
4963            scale,
4964            out,
4965            display_style,
4966            prime_style,
4967        ),
4968        Atom::XArrow { code, over, under } => xarrow::layout(
4969            *code,
4970            over,
4971            under.as_deref(),
4972            x,
4973            baseline,
4974            scale,
4975            out,
4976            prime_style,
4977        ),
4978        Atom::Strut(height, depth, kind) => {
4979            out.ascent = out.ascent.max(baseline + height * scale);
4980            out.depth = out.depth.max(depth * scale - baseline);
4981            out.groups.push(LayoutGroup {
4982                x_frame: None,
4983                data_cramped: None,
4984                own_translate: None,
4985                accent_offset: None,
4986                box_border: None,
4987                reference: None,
4988                tagged: None,
4989                percentage: None,
4990                table_line: None,
4991                mathsize: None,
4992                tex_class: 0,
4993                before_glyph: out.glyphs.len(),
4994                scale,
4995                x,
4996                baseline,
4997                color: None,
4998                background: None,
4999                kind,
5000                body: Box::new(Layout {
5001                    bounds_em: None,
5002                    width_em: None,
5003                    intrinsic_width_em: None,
5004                    width: 0.0,
5005                    ascent: 0.0,
5006                    depth: 0.0,
5007                    glyphs: Vec::new(),
5008                    rules: Vec::new(),
5009                    groups: Vec::new(),
5010                }),
5011                delimiter: None,
5012                arrow: None,
5013                lines: Vec::new(),
5014            });
5015            Some(0.0)
5016        }
5017        Atom::CdArrow {
5018            code,
5019            over,
5020            under,
5021            minimums,
5022            ..
5023        } => cd::layout_arrow(
5024            *code,
5025            over.as_deref(),
5026            under.as_deref(),
5027            *minimums,
5028            x,
5029            baseline,
5030            scale,
5031            out,
5032        ),
5033        Atom::Unit(codepoint) => {
5034            let width = layout_at_with_style(
5035                &Atom::Glyph(*codepoint),
5036                x,
5037                baseline,
5038                scale,
5039                out,
5040                display_style,
5041                prime_style,
5042            )?;
5043            out.glyphs.last_mut()?.unit = true;
5044            Some(width)
5045        }
5046        Atom::Glyph(codepoint)
5047        | Atom::LiteralGlyph(codepoint)
5048        | Atom::VariantGlyph(codepoint)
5049        | Atom::CalligraphicGlyph(codepoint)
5050        | Atom::ItalicGlyph(codepoint) => {
5051            let calligraphic =
5052                matches!(atom, Atom::CalligraphicGlyph(_)) && !is_large_operator(*codepoint);
5053            let italic = matches!(atom, Atom::ItalicGlyph(_)) && !is_large_operator(*codepoint);
5054            let variant = matches!(atom, Atom::VariantGlyph(_));
5055            let literal = matches!(atom, Atom::LiteralGlyph(_));
5056            let small_operator = !literal && !display_style && is_large_operator(*codepoint);
5057            let large = !literal && display_style && is_large_operator(*codepoint);
5058            let glyph = if large {
5059                glyph_for(PositionedGlyph {
5060                    codepoint: *codepoint,
5061                    x: 0.0,
5062                    baseline: 0.0,
5063                    scale: 1.0,
5064                    font_original: None,
5065                    font_variant: "normal",
5066                    bold: false,
5067                    small_operator: false,
5068                    variant: false,
5069                    unit: false,
5070                    calligraphic: false,
5071                    italic: false,
5072                    large: true,
5073                    stretch: false,
5074                    radical_variant: None,
5075                    assembly_height: None,
5076                })?
5077            } else if small_operator {
5078                smallop_glyph(*codepoint)?
5079            } else if variant {
5080                variant_glyph(*codepoint)?
5081            } else if calligraphic {
5082                calligraphic_glyph(*codepoint)?
5083            } else if italic {
5084                italic_glyph(*codepoint)?
5085            } else {
5086                glyph(*codepoint)?
5087            };
5088            let axis_shift = if !literal && is_large_operator(*codepoint) {
5089                ((glyph.height + glyph.depth) / 2.0 + 0.25 - glyph.height) * 1000.0 * scale
5090            } else {
5091                0.0
5092            };
5093            out.glyphs.push(PositionedGlyph {
5094                font_original: None,
5095                font_variant: "normal",
5096                bold: false,
5097                small_operator,
5098                variant,
5099                unit: false,
5100                calligraphic,
5101                italic,
5102                codepoint: *codepoint,
5103                x,
5104                baseline: baseline + axis_shift,
5105                scale,
5106                large,
5107                stretch: false,
5108                radical_variant: None,
5109                assembly_height: None,
5110            });
5111            out.ascent = out
5112                .ascent
5113                .max(baseline + axis_shift + glyph.height * 1000.0 * scale);
5114            out.depth = out
5115                .depth
5116                .max(-(baseline + axis_shift - glyph.depth * 1000.0 * scale));
5117            let corrections = if small_operator {
5118                smallop_glyphs::ITALIC_CORRECTIONS
5119            } else if variant {
5120                tex_variant_glyphs::ITALIC_CORRECTIONS
5121            } else if !literal && is_large_operator(*codepoint) {
5122                large_glyphs::ITALIC_CORRECTIONS
5123            } else if calligraphic {
5124                calligraphic_glyphs::ITALIC_CORRECTIONS
5125            } else if italic {
5126                italic_glyphs::ITALIC_CORRECTIONS
5127            } else {
5128                glyphs::ITALIC_CORRECTIONS
5129            };
5130            let correction = if calligraphic {
5131                calligraphic_correction(*codepoint)
5132            } else if italic {
5133                italic_correction(*codepoint)
5134            } else {
5135                corrections
5136                    .binary_search_by_key(codepoint, |entry| entry.0)
5137                    .ok()
5138                    .map_or_else(
5139                        || {
5140                            if compound(*codepoint).is_some() {
5141                                glyphs::ITALIC_CORRECTIONS
5142                                    .binary_search_by_key(codepoint, |e| e.0)
5143                                    .ok()
5144                                    .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1)
5145                            } else {
5146                                0.0
5147                            }
5148                        },
5149                        |index| corrections[index].1,
5150                    )
5151            };
5152            out.width_em = Some((glyph.width + correction) * scale);
5153            out.intrinsic_width_em = Some(glyph.width + correction);
5154            Some((glyph.width + correction) * 1000.0 * scale)
5155        }
5156        Atom::Space(_) | Atom::Kern(_) | Atom::EmptyNode(_) | Atom::RuleSpace { .. } => {
5157            let (height, depth, background) = if let Atom::RuleSpace {
5158                dimensions,
5159                background,
5160                mathsize,
5161            } = atom
5162            {
5163                (
5164                    dimensions[1].em(0., scale * mathsize) * 1000. * scale,
5165                    dimensions[2].em(0., scale * mathsize) * 1000. * scale,
5166                    background.clone(),
5167                )
5168            } else {
5169                (0., 0., None)
5170            };
5171            let width = match atom {
5172                Atom::Space(width) => width * 1000.0 * scale,
5173                Atom::Kern(dimension) => dimension.em(0.0, scale) * 1000.0 * scale,
5174                Atom::EmptyNode(_) => 0.0,
5175                Atom::RuleSpace {
5176                    dimensions,
5177                    mathsize,
5178                    ..
5179                } => dimensions[0].em(0., scale * mathsize) * 1000. * scale,
5180                _ => unreachable!(),
5181            };
5182            // Explicit TeX glue is an mspace node even though it paints no
5183            // primitive. Preserve that node independently of its advance.
5184            let local = Layout {
5185                bounds_em: None,
5186                width_em: None,
5187                intrinsic_width_em: None,
5188                width,
5189                ascent: height,
5190                depth,
5191                glyphs: Vec::new(),
5192                rules: Vec::new(),
5193                groups: Vec::new(),
5194            };
5195            out.groups.push(LayoutGroup {
5196                x_frame: None,
5197                data_cramped: None,
5198                own_translate: None,
5199                accent_offset: None,
5200                box_border: None,
5201                reference: None,
5202                tagged: None,
5203                percentage: None,
5204                table_line: None,
5205                mathsize: None,
5206                tex_class: 0,
5207                before_glyph: out.glyphs.len(),
5208                scale,
5209                x,
5210                baseline,
5211                color: None,
5212                background: background
5213                    .filter(|c| c != "transparent")
5214                    .map(|c| (c, width, height, depth)),
5215                kind: if let Atom::EmptyNode(kind) = atom {
5216                    kind
5217                } else {
5218                    "mspace"
5219                },
5220                body: Box::new(local),
5221                delimiter: None,
5222                arrow: None,
5223                lines: Vec::new(),
5224            });
5225            out.ascent = out.ascent.max(baseline + height);
5226            out.depth = out.depth.max(depth - baseline);
5227            Some(width)
5228        }
5229        Atom::Sequence(children) => {
5230            if style_classes::has_declaration(atom) {
5231                return style_classes::layout(
5232                    atom,
5233                    x,
5234                    baseline,
5235                    scale,
5236                    out,
5237                    display_style,
5238                    prime_style,
5239                );
5240            }
5241            let classes = sequence_tex_classes(children);
5242            let stretch = braket::row_dimensions(children, scale, display_style, prime_style)?;
5243            // Source wrapper.computeChildrenBBox/BBox.Append composes em widths
5244            // before scaling the row at its parent boundary.
5245            let mut cursor_em = 0.0;
5246            let mut intrinsic_cursor_em = 0.0;
5247            let mut previous = None;
5248            for (index, child) in children.iter().enumerate() {
5249                let mut boundary_space = 0.0;
5250                if !operator_dictionary::spacelike(child) {
5251                    if let Some(previous_index) = previous {
5252                        let script = scale < 1.0
5253                            || !style_classes::adjusts_current_level(child)
5254                                && style_classes::returned_script_level(
5255                                    &children[previous_index],
5256                                    false,
5257                                );
5258                        boundary_space = tex_class_spacing(
5259                            return_tex_class(&children[previous_index], classes[previous_index]),
5260                            classes::adjustment_class(child, classes[index]).or(Some(0)),
5261                            script,
5262                        ) * scale;
5263                    }
5264                    previous = Some(index);
5265                }
5266                if table::replaces_leading_space(child) || matches!(child, Atom::InferredRow(_)) {
5267                    boundary_space = 0.0;
5268                }
5269                let (left_space, right_space) = mml_spacing::row_spaces(children, index, scale);
5270                if mml_spacing::core(child).is_some() {
5271                    boundary_space = left_space * 1000.0 * scale;
5272                }
5273                cursor_em += boundary_space / (1000.0 * scale);
5274                intrinsic_cursor_em += boundary_space / (1000.0 * scale);
5275                let cursor = x + (cursor_em * scale) * 1000.0;
5276                let group_start = out.groups.len();
5277                out.width_em = None;
5278                out.intrinsic_width_em = None;
5279                let advance =
5280                    if let (Some((height, depth)), Atom::FenceDelimiter { code, class, color }) =
5281                        (stretch, child)
5282                        && table::can_stretch(*code)
5283                    {
5284                        braket::layout_stretched_token(
5285                            *code,
5286                            *class,
5287                            color.as_deref(),
5288                            height,
5289                            depth,
5290                            cursor,
5291                            baseline,
5292                            scale,
5293                            out,
5294                        )?
5295                    } else {
5296                        layout_at_with_style(
5297                            child,
5298                            cursor,
5299                            baseline,
5300                            scale,
5301                            out,
5302                            display_style,
5303                            prime_style,
5304                        )?
5305                    };
5306                // Preserve the source glyph/space's intrinsic em metrics instead
5307                // of recovering them from an already scaled/rounded unit value.
5308                let em = match child {
5309                    Atom::Glyph(code) if !is_large_operator(*code) => glyph(*code).map(|g| {
5310                        g.width
5311                            + glyphs::ITALIC_CORRECTIONS
5312                                .binary_search_by_key(code, |v| v.0)
5313                                .ok()
5314                                .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1)
5315                    }),
5316                    Atom::Identifier(items) | Atom::Number(items) | Atom::OperatorToken(items) => {
5317                        let mut width = 0.0;
5318                        let mut last_ic = 0.0;
5319                        let mut complete = true;
5320                        for item in items {
5321                            if let Atom::Glyph(code) = item {
5322                                if let Some(g) = glyph(*code).filter(|_| !is_large_operator(*code))
5323                                {
5324                                    width += g.width;
5325                                    last_ic = glyphs::ITALIC_CORRECTIONS
5326                                        .binary_search_by_key(code, |v| v.0)
5327                                        .ok()
5328                                        .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1);
5329                                } else {
5330                                    complete = false;
5331                                    break;
5332                                }
5333                            } else {
5334                                complete = false;
5335                                break;
5336                            }
5337                        }
5338                        complete.then_some(
5339                            width
5340                                + if matches!(child, Atom::Number(_)) {
5341                                    0.0
5342                                } else {
5343                                    last_ic
5344                                },
5345                        )
5346                    }
5347                    Atom::Space(width) => Some(*width),
5348                    Atom::Kern(dimension) => Some(dimension.em(0.0, scale)),
5349                    _ => None,
5350                };
5351                intrinsic_cursor_em += em
5352                    .or(out.intrinsic_width_em)
5353                    .or(out.width_em.map(|w| w / scale))
5354                    .unwrap_or(advance / (1000.0 * scale));
5355                cursor_em += em
5356                    .or(out.width_em.map(|w| w / scale))
5357                    .unwrap_or(advance / (1000.0 * scale));
5358                cursor_em += right_space;
5359                intrinsic_cursor_em += right_space;
5360                if atom_tex_class(child) == Some(2) && classes[index] == Some(0) {
5361                    classes::demote_group(&mut out.groups[group_start..]);
5362                }
5363            }
5364            out.intrinsic_width_em = Some(intrinsic_cursor_em);
5365            out.width_em = Some(cursor_em * scale);
5366            Some(cursor_em * 1000.0 * scale)
5367        }
5368        Atom::Identifier(children)
5369        | Atom::Number(children)
5370        | Atom::OperatorToken(children)
5371        | Atom::StyledText(children) => {
5372            let mut local = Layout {
5373                bounds_em: None,
5374                width_em: None,
5375                intrinsic_width_em: None,
5376                width: 0.0,
5377                ascent: 0.0,
5378                depth: 0.0,
5379                glyphs: Vec::new(),
5380                rules: Vec::new(),
5381                groups: Vec::new(),
5382            };
5383            let mut cursor = 0.0;
5384            let mut width_em = 0.0;
5385            let mut intrinsic_width_em = 0.0;
5386            for (i, child) in children.iter().enumerate() {
5387                local.width_em = None;
5388                local.intrinsic_width_em = None;
5389                let advance = layout_at_with_style(
5390                    child,
5391                    cursor,
5392                    0.0,
5393                    scale,
5394                    &mut local,
5395                    display_style,
5396                    prime_style,
5397                )?;
5398                cursor += advance;
5399                width_em += local.width_em.unwrap_or(advance / 1000.0);
5400                intrinsic_width_em += local
5401                    .intrinsic_width_em
5402                    .unwrap_or_else(|| local.width_em.unwrap_or(advance / 1000.0) / scale);
5403                // mtext advances by glyph widths alone (no italic correction).
5404                if matches!(atom, Atom::Number(_) | Atom::StyledText(_)) || i + 1 < children.len() {
5405                    let correction = classes::italic_correction(child, display_style);
5406                    cursor -= correction * 1000.0 * scale;
5407                    width_em -= correction * scale;
5408                    intrinsic_width_em -= correction;
5409                }
5410            }
5411            local.width = cursor;
5412            retain_negative_glyph_depth(&mut local);
5413            out.ascent = out.ascent.max(baseline + local.ascent);
5414            out.depth = out.depth.max(local.depth - baseline);
5415            out.groups.push(LayoutGroup {
5416                x_frame: None,
5417                data_cramped: None,
5418                own_translate: None,
5419                accent_offset: None,
5420                box_border: None,
5421                reference: None,
5422                tagged: None,
5423                percentage: None,
5424                table_line: None,
5425                mathsize: None,
5426                tex_class: 0,
5427                before_glyph: out.glyphs.len(),
5428                scale,
5429                x,
5430                baseline,
5431                color: None,
5432                background: None,
5433                kind: if matches!(atom, Atom::Number(_)) {
5434                    "mn"
5435                } else if matches!(atom, Atom::StyledText(_)) {
5436                    "mtext"
5437                } else if matches!(atom, Atom::OperatorToken(_)) {
5438                    "mo"
5439                } else {
5440                    "mi"
5441                },
5442                delimiter: None,
5443                arrow: None,
5444                body: Box::new(local),
5445                lines: Vec::new(),
5446            });
5447            out.width_em = Some(width_em);
5448            out.intrinsic_width_em = Some(intrinsic_width_em);
5449            Some(cursor)
5450        }
5451        Atom::MathMLSpace { body, .. }
5452        | Atom::AutoOperator(body)
5453        | Atom::Operator(body)
5454        | Atom::MovesScripts(body)
5455        | Atom::ScriptPolicy { body, .. } => {
5456            layout_at_with_style(body, x, baseline, scale, out, display_style, prime_style)
5457        }
5458        Atom::Phantom(body) => padded::layout_node(
5459            body,
5460            None,
5461            true,
5462            x,
5463            baseline,
5464            scale,
5465            out,
5466            display_style,
5467            prime_style,
5468        ),
5469        Atom::Padded { body, padding } => padded::layout_node(
5470            body,
5471            Some(padding),
5472            false,
5473            x,
5474            baseline,
5475            scale,
5476            out,
5477            display_style,
5478            prime_style,
5479        ),
5480        Atom::CrampedStyle(body, _) => {
5481            let data_cramped = match atom {
5482                Atom::CrampedStyle(_, cramped) => Some(*cramped),
5483                _ => None,
5484            };
5485            let mut local = Layout {
5486                bounds_em: None,
5487                width_em: None,
5488                intrinsic_width_em: None,
5489                width: 0.0,
5490                ascent: 0.0,
5491                depth: 0.0,
5492                glyphs: Vec::new(),
5493                rules: Vec::new(),
5494                groups: Vec::new(),
5495            };
5496            local.width = layout_at_with_style(
5497                body,
5498                0.0,
5499                0.0,
5500                scale,
5501                &mut local,
5502                display_style,
5503                prime_style,
5504            )?;
5505            retain_negative_glyph_depth(&mut local);
5506            let width = local.width;
5507            out.width_em = local.width_em;
5508            out.ascent = out.ascent.max(baseline + local.ascent);
5509            out.depth = out.depth.max(local.depth - baseline);
5510            out.groups.push(LayoutGroup {
5511                x_frame: None,
5512                data_cramped,
5513                own_translate: None,
5514                accent_offset: None,
5515                box_border: None,
5516                reference: None,
5517                tagged: None,
5518                percentage: None,
5519                table_line: None,
5520                mathsize: None,
5521                tex_class: 0,
5522                before_glyph: out.glyphs.len(),
5523                scale,
5524                x,
5525                baseline,
5526                color: None,
5527                background: None,
5528                kind: "mstyle",
5529                body: Box::new(local),
5530                delimiter: None,
5531                arrow: None,
5532                lines: Vec::new(),
5533            });
5534            Some(width)
5535        }
5536        Atom::Ord(body) | Atom::Class { body, .. } => {
5537            // Original texatom.go/standardSVG: a TeXAtom owns a local frame.
5538            // Keep child placements local until SVG serialization so parent and
5539            // child translations receive the original independent rounding.
5540            let mut local = Layout {
5541                bounds_em: None,
5542                width_em: None,
5543                intrinsic_width_em: None,
5544                width: 0.0,
5545                ascent: 0.0,
5546                depth: 0.0,
5547                glyphs: Vec::new(),
5548                rules: Vec::new(),
5549                groups: Vec::new(),
5550            };
5551            local.width = layout_at_with_style(
5552                body,
5553                0.0,
5554                0.0,
5555                scale,
5556                &mut local,
5557                display_style,
5558                prime_style,
5559            )?;
5560            retain_negative_glyph_depth(&mut local);
5561            let width = local.width;
5562            out.width_em = local.width_em;
5563            let (h, d) = if matches!(atom, Atom::Class { class: 8, .. }) {
5564                let (h, d) = styles::em_bounds(&local);
5565                let delta = (h + d) / 2. + 0.25 * scale - h;
5566                ((h + delta) * 1000., (d - delta) * 1000.)
5567            } else {
5568                (local.ascent, local.depth)
5569            };
5570            out.ascent = out.ascent.max(baseline + h);
5571            out.depth = out.depth.max(d - baseline);
5572            out.groups.push(LayoutGroup {
5573                x_frame: None,
5574                data_cramped: None,
5575                own_translate: None,
5576                accent_offset: None,
5577                box_border: None,
5578                reference: None,
5579                tagged: None,
5580                percentage: None,
5581                table_line: None,
5582                mathsize: None,
5583                tex_class: if let Atom::Class { class, .. } = atom {
5584                    *class
5585                } else {
5586                    0
5587                },
5588                before_glyph: out.glyphs.len(),
5589                scale,
5590                x,
5591                baseline,
5592                color: None,
5593                background: None,
5594                kind: "TeXAtom",
5595                body: Box::new(local),
5596                delimiter: None,
5597                arrow: None,
5598                lines: Vec::new(),
5599            });
5600            Some(width)
5601        }
5602        Atom::Mrow(body) | Atom::Reference { body, .. } => {
5603            let mut local = Layout {
5604                bounds_em: None,
5605                width_em: None,
5606                intrinsic_width_em: None,
5607                width: 0.0,
5608                ascent: 0.0,
5609                depth: 0.0,
5610                glyphs: vec![],
5611                rules: vec![],
5612                groups: vec![],
5613            };
5614            local.width = layout_at_with_style(
5615                body,
5616                0.0,
5617                0.0,
5618                scale,
5619                &mut local,
5620                display_style,
5621                prime_style,
5622            )?;
5623            let width = local.width;
5624            out.ascent = out.ascent.max(baseline + local.ascent);
5625            out.depth = out.depth.max(local.depth - baseline);
5626            out.groups.push(LayoutGroup {
5627                x_frame: None,
5628                data_cramped: None,
5629                own_translate: None,
5630                accent_offset: None,
5631                box_border: None,
5632                reference: match atom {
5633                    Atom::Reference { href, .. } => Some(href.clone()),
5634                    _ => None,
5635                },
5636                tagged: None,
5637                percentage: None,
5638                table_line: None,
5639                mathsize: None,
5640                tex_class: 0,
5641                before_glyph: out.glyphs.len(),
5642                scale,
5643                x,
5644                baseline,
5645                color: None,
5646                background: None,
5647                kind: "mrow",
5648                body: Box::new(local),
5649                delimiter: None,
5650                arrow: None,
5651                lines: vec![],
5652            });
5653            Some(width)
5654        }
5655        Atom::TaggedTable {
5656            rows,
5657            tags,
5658            environment,
5659            container_align,
5660            spacing,
5661        } => ams::layout_tagged(
5662            rows,
5663            tags,
5664            environment,
5665            container_align,
5666            *spacing,
5667            x,
5668            baseline,
5669            scale,
5670            out,
5671        ),
5672        Atom::Boxed(body) => {
5673            enclose::layout_box(body, x, baseline, scale, out, display_style, prime_style)
5674        }
5675        Atom::NotToken { first, kind, .. } => pending_not::layout_token(
5676            first,
5677            kind,
5678            x,
5679            baseline,
5680            scale,
5681            out,
5682            display_style,
5683            prime_style,
5684        ),
5685        Atom::Text(text) => {
5686            // Original mtext appends glyph widths without mi italic correction.
5687            // Retain its local frame so zero-width laps use the actual text width.
5688            let mut local = Layout {
5689                bounds_em: None,
5690                width_em: None,
5691                intrinsic_width_em: None,
5692                width: 0.0,
5693                ascent: 0.0,
5694                depth: 0.0,
5695                glyphs: Vec::new(),
5696                rules: Vec::new(),
5697                groups: Vec::new(),
5698            };
5699            let mut cursor = 0.0;
5700            for character in text.chars() {
5701                let code = character as u32;
5702                cursor += layout_at_with_style(
5703                    &Atom::LiteralGlyph(code),
5704                    cursor,
5705                    0.0,
5706                    scale,
5707                    &mut local,
5708                    display_style,
5709                    prime_style,
5710                )?;
5711                cursor -= glyphs::ITALIC_CORRECTIONS
5712                    .binary_search_by_key(&code, |e| e.0)
5713                    .ok()
5714                    .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1)
5715                    * 1000.0
5716                    * scale;
5717            }
5718            local.width = cursor;
5719            retain_negative_glyph_depth(&mut local);
5720            out.ascent = out.ascent.max(baseline + local.ascent);
5721            out.depth = out.depth.max(local.depth - baseline);
5722            out.groups.push(LayoutGroup {
5723                x_frame: None,
5724                data_cramped: None,
5725                own_translate: None,
5726                accent_offset: None,
5727                box_border: None,
5728                reference: None,
5729                tagged: None,
5730                percentage: None,
5731                table_line: None,
5732                mathsize: None,
5733                tex_class: 0,
5734                before_glyph: out.glyphs.len(),
5735                scale,
5736                x,
5737                baseline,
5738                color: None,
5739                background: None,
5740                kind: "mtext",
5741                body: Box::new(local),
5742                delimiter: None,
5743                arrow: None,
5744                lines: Vec::new(),
5745            });
5746            Some(cursor)
5747        }
5748        Atom::Cancel {
5749            body,
5750            up,
5751            down,
5752            arrow,
5753            options,
5754        } => enclose::layout_node(
5755            body,
5756            *up,
5757            *down,
5758            *arrow,
5759            options,
5760            x,
5761            baseline,
5762            scale,
5763            out,
5764            display_style,
5765            prime_style,
5766        ),
5767        Atom::Color { body, .. } | Atom::ColorBox { body, .. } => {
5768            // Original menclose.go/menclose_notation.go/.shapes.go and mstyle:
5769            // retain scope, dynamic child bounds, padding, and diagonal strokes.
5770            let pad = if let Atom::ColorBox { mathsize, .. } = atom {
5771                // Original colorBox uses PaddingProperties(5px), Ex8/XHeight.442.
5772                length::dimension("5px").em(0., scale * mathsize) * 1000. * scale
5773            } else {
5774                0.0
5775            };
5776            let mut local = Layout {
5777                bounds_em: None,
5778                width_em: None,
5779                intrinsic_width_em: None,
5780                width: 0.0,
5781                ascent: 0.0,
5782                depth: 0.0,
5783                glyphs: Vec::new(),
5784                rules: Vec::new(),
5785                groups: Vec::new(),
5786            };
5787            // tex/inheritance.go cleanMathMLAttributes drops an explicit
5788            // mathcolor equal to the inherited one, so a nested mstyle of the
5789            // same color emits no fill/stroke.
5790            let explicit_color = if let Atom::Color { color, .. } = atom {
5791                let inherited = INHERITED_COLOR.with(|c| c.borrow().last().cloned());
5792                INHERITED_COLOR.with(|c| c.borrow_mut().push(color.clone()));
5793                (inherited.as_deref() != Some(color.as_str())).then(|| color.clone())
5794            } else {
5795                None
5796            };
5797            let laid_out = layout_at_with_style(
5798                body,
5799                0.0,
5800                0.0,
5801                scale,
5802                &mut local,
5803                display_style,
5804                prime_style,
5805            );
5806            if matches!(atom, Atom::Color { .. }) {
5807                INHERITED_COLOR.with(|c| c.borrow_mut().pop());
5808            }
5809            local.width = laid_out? + 2.0 * pad;
5810            if pad != 0.0 {
5811                // Original svg/mpadded.go paddedToSVG: the lspace offset is a
5812                // separate content g placed inside the mpadded node.
5813                let content = std::mem::replace(
5814                    &mut local,
5815                    Layout {
5816                        bounds_em: None,
5817                        width_em: None,
5818                        intrinsic_width_em: None,
5819                        width: 0.0,
5820                        ascent: 0.0,
5821                        depth: 0.0,
5822                        glyphs: Vec::new(),
5823                        rules: Vec::new(),
5824                        groups: Vec::new(),
5825                    },
5826                );
5827                local.width = content.width;
5828                local.ascent = content.ascent;
5829                local.depth = content.depth;
5830                local.width_em = content.width_em;
5831                local.groups.push(LayoutGroup {
5832                    x_frame: None,
5833                    data_cramped: None,
5834                    own_translate: None,
5835                    accent_offset: None,
5836                    box_border: None,
5837                    reference: None,
5838                    tagged: None,
5839                    percentage: None,
5840                    table_line: None,
5841                    mathsize: None,
5842                    tex_class: 0,
5843                    before_glyph: 0,
5844                    scale,
5845                    x: pad,
5846                    baseline: 0.0,
5847                    color: None,
5848                    background: None,
5849                    kind: "",
5850                    delimiter: None,
5851                    arrow: None,
5852                    body: Box::new(content),
5853                    lines: Vec::new(),
5854                });
5855            }
5856            let (ascent, depth) = if matches!(atom, Atom::ColorBox { .. }) {
5857                // Original mpadded adds dimensions in em before SVG *1000;
5858                // adding converted pixel values changes exact binary ties.
5859                (
5860                    (local.ascent / 1000.0 + pad / 1000.0) * 1000.0,
5861                    (local.depth / 1000.0 + pad / 1000.0) * 1000.0,
5862                )
5863            } else {
5864                (local.ascent + pad, local.depth + pad)
5865            };
5866            let width = local.width;
5867            let lines = Vec::new();
5868            let color = explicit_color;
5869            let background = if let Atom::ColorBox { background, .. } = atom {
5870                Some((background.clone(), width, ascent, depth))
5871            } else {
5872                None
5873            };
5874            out.groups.push(LayoutGroup {
5875                x_frame: None,
5876                data_cramped: None,
5877                own_translate: None,
5878                accent_offset: None,
5879                box_border: None,
5880                reference: None,
5881                tagged: None,
5882                percentage: None,
5883                table_line: None,
5884                mathsize: None,
5885                tex_class: 0,
5886                before_glyph: out.glyphs.len(),
5887                scale,
5888                x,
5889                baseline,
5890                color,
5891                background,
5892                kind: if matches!(atom, Atom::ColorBox { .. }) {
5893                    "mpadded"
5894                } else {
5895                    "mstyle"
5896                },
5897                body: Box::new(local),
5898                delimiter: None,
5899                arrow: None,
5900                lines,
5901            });
5902            out.ascent = out.ascent.max(baseline + ascent);
5903            out.depth = out.depth.max(depth - baseline);
5904            Some(width)
5905        }
5906        Atom::SplitFraction(numerator, denominator, mathsize) => split_fraction::layout(
5907            numerator,
5908            denominator,
5909            *mathsize,
5910            x,
5911            baseline,
5912            scale,
5913            out,
5914            display_style,
5915            prime_style,
5916        ),
5917        Atom::BracketMark {
5918            body,
5919            thickness,
5920            height,
5921            under,
5922            mathsize,
5923        } => brackets::layout(
5924            body,
5925            *thickness,
5926            height,
5927            *under,
5928            *mathsize,
5929            x,
5930            baseline,
5931            scale,
5932            out,
5933            prime_style,
5934        ),
5935        Atom::HorizontalMark { body, .. } => {
5936            // Under/over marks are mo text tokens, including fixed line marks.
5937            // Their role is distinct from the same character used as a name.
5938            if matches!(body.as_ref(), Atom::OperatorToken(_)) {
5939                layout_at_with_style(body, x, baseline, scale, out, display_style, prime_style)
5940            } else {
5941                layout_at_with_style(
5942                    &Atom::OperatorToken(vec![(**body).clone()]),
5943                    x,
5944                    baseline,
5945                    scale,
5946                    out,
5947                    display_style,
5948                    prime_style,
5949                )
5950            }
5951        }
5952        Atom::FractionStrut(mathsize) => general_fraction::strut(
5953            *mathsize,
5954            x,
5955            baseline,
5956            scale,
5957            out,
5958            display_style,
5959            prime_style,
5960        ),
5961        Atom::GeneralFraction(numerator, denominator, spec) => general_fraction::layout(
5962            numerator,
5963            denominator,
5964            *spec,
5965            x,
5966            baseline,
5967            scale,
5968            out,
5969            display_style,
5970            prime_style,
5971        ),
5972        Atom::Fraction(numerator, denominator) => general_fraction::layout(
5973            numerator,
5974            denominator,
5975            general_fraction::Spec::new("medium", false),
5976            x,
5977            baseline,
5978            scale,
5979            out,
5980            display_style,
5981            prime_style,
5982        ),
5983        Atom::Sqrt(body) | Atom::SizedSqrt { body, .. } | Atom::Root { body, .. } => {
5984            let mathsize = if let Atom::SizedSqrt { mathsize, .. } = atom {
5985                *mathsize
5986            } else {
5987                1.0
5988            };
5989            let root_index = match atom {
5990                // Sized mroot layout is not translated.
5991                Atom::Root { mathsize, .. } if *mathsize != 1.0 => return None,
5992                Atom::Root { index, .. } => Some(index.as_ref()),
5993                _ => None,
5994            };
5995            let parent_x = x;
5996            let parent_baseline = baseline;
5997            let parent = out;
5998            let mut root = Layout {
5999                bounds_em: None,
6000                width_em: None,
6001                intrinsic_width_em: None,
6002                width: 0.0,
6003                ascent: 0.0,
6004                depth: 0.0,
6005                glyphs: Vec::new(),
6006                rules: Vec::new(),
6007                groups: Vec::new(),
6008            };
6009            let out = &mut root;
6010            let x = 0.0;
6011            let baseline = 0.0;
6012            // Original internal/svg/msqrt.go and mo.go: exact delimiter selection,
6013            // rootPQ clearance, child prime style and quantized assembled surds.
6014            let mut body_box = Layout {
6015                bounds_em: None,
6016                width_em: None,
6017                intrinsic_width_em: None,
6018                width: 0.0,
6019                ascent: 0.0,
6020                depth: 0.0,
6021                glyphs: Vec::new(),
6022                rules: Vec::new(),
6023                groups: Vec::new(),
6024            };
6025            body_box.width =
6026                layout_at_with_style(body, 0.0, 0.0, scale, &mut body_box, display_style, true)?;
6027            retain_negative_glyph_depth(&mut body_box);
6028            let rule = 60.0 * scale;
6029            let clearance = if display_style { 442.0 * scale } else { rule };
6030            let requested = body_box.ascent + body_box.depth + 2.0 * rule + clearance / 4.0;
6031            let variant = [1.0, 1.2, 1.8, 2.4, 3.0]
6032                .iter()
6033                .position(|size| size * 1000.0 * scale >= requested);
6034            let assembly_height = if variant.is_none() {
6035                let total =
6036                    2.3 + ((requested / (1000.0 * scale) - 2.3).max(0.0) / 0.65).ceil() * 0.65;
6037                // Original mo.go stretchBaseline: preserve exact requested H/D,
6038                // otherwise distribute quantized size using delimiter HDW .85/.35.
6039                let depth = if requested / (1000.0 * scale) == total {
6040                    body_box.depth / (1000.0 * scale)
6041                } else {
6042                    0.35 * total / (0.85 + 0.35)
6043                };
6044                Some((total, depth))
6045            } else {
6046                None
6047            };
6048            let surd = if let Some(index) = variant {
6049                radical_glyphs::RADICAL_GLYPHS[index]
6050            } else {
6051                let (total, depth) = assembly_height?;
6052                GlyphData {
6053                    height: total - depth,
6054                    depth,
6055                    width: 1.056,
6056                    path: "",
6057                }
6058            };
6059            // Original computes root bounds in em before the outer SVG scale.
6060            // Retain that operation order when padded nodes expose H/D alone.
6061            let body_h_em = body_box.ascent / (1000.0 * scale);
6062            let body_d_em = body_box.depth / (1000.0 * scale);
6063            let clearance_em = if display_style { 0.442 } else { 0.06 };
6064            let requested_em = body_h_em + body_d_em + 2.0 * 0.06 + clearance_em / 4.0;
6065            let q_em = if surd.height + surd.depth > requested_em {
6066                ((surd.height + surd.depth) - (requested_em - 2.0 * 0.06 - clearance_em / 2.0))
6067                    / 2.0
6068            } else {
6069                0.06 + clearance_em / 4.0
6070            };
6071            let height_em = body_h_em + q_em + 0.06;
6072            // All five pinned radical font variants have italic correction .02.
6073            let surd_width =
6074                (surd.width + if variant.is_some() { 0.02 } else { 0.0 }) * 1000.0 * scale;
6075            // Source rootToSVG scales the paint rule before adding it to H+q.
6076            // Bounds use unscaled Rule independently in computeRootBBox.
6077            let paint_height_em = body_h_em + q_em + 0.06 * scale * mathsize;
6078            let surd_baseline = baseline + (paint_height_em - surd.height) * 1000.0 * scale;
6079            // rootToSVG retains a translated baseContainer independently of
6080            // each child placement. Flattening those translations changes
6081            // downstream affine arithmetic even when serialized sums agree.
6082            let body_width = body_box.width;
6083            let body_width_em = body_box.width_em.unwrap_or(body_width / 1000.0) / scale;
6084            let width_em = ((surd.width + if variant.is_some() { 0.02 } else { 0.0 })
6085                + body_width_em)
6086                .max(surd.width + if variant.is_some() { 0.02 } else { 0.0 })
6087                * scale;
6088            parent.width_em = Some(width_em);
6089            // Original svg/msqrt.go rootDimensions: the index is laid out at
6090            // scriptlevel+2 and shifts the surd and base right by x when it
6091            // is wider than the surd's offset. wrapper.go:getScale retains
6092            // the squared multiplier (0.4999999999999999): the default 8px
6093            // minimum is only 0.442em at pxPerEm = Ex / XHeight.
6094            let mut root_shift = 0.0;
6095            let mut root_group = None;
6096            let mut root_glyph: Option<PositionedGlyph> = None;
6097            if let Some(index) = root_index {
6098                let index_scale = styles::SCRIPT_MULTIPLIER * styles::SCRIPT_MULTIPLIER;
6099                let mut index_box = Layout {
6100                    bounds_em: None,
6101                    width_em: None,
6102                    intrinsic_width_em: None,
6103                    width: 0.0,
6104                    ascent: 0.0,
6105                    depth: 0.0,
6106                    glyphs: Vec::new(),
6107                    rules: Vec::new(),
6108                    groups: Vec::new(),
6109                };
6110                index_box.width = layout_at_with_style(
6111                    index,
6112                    0.0,
6113                    0.0,
6114                    index_scale,
6115                    &mut index_box,
6116                    false,
6117                    prime_style,
6118                )?;
6119                retain_negative_glyph_depth(&mut index_box);
6120                let rscale = index_scale / scale;
6121                let root_w = index_box.width_em.unwrap_or(index_box.width / 1000.0) / index_scale;
6122                let root_h = index_box.ascent / (1000.0 * index_scale);
6123                let root_d = index_box.depth / (1000.0 * index_scale);
6124                let surd_w = surd.width + if variant.is_some() { 0.02 } else { 0.0 };
6125                let offset = if variant.is_some() { 0.6 } else { 0.5 } * surd_w;
6126                let width = root_w.max(offset / rscale);
6127                let dx = (width - root_w).max(0.0);
6128                let total = surd.height + surd.depth;
6129                let b = if variant.is_some() { 0.55 * total } else { 1.9 };
6130                let h = b - (total - paint_height_em) + (root_d * rscale).max(0.0);
6131                // computeRootBBox calls rootDimensions with unscaled Rule;
6132                // rootToSVG independently uses Rule * bbox.Scale for paint.
6133                let bbox_h = b - (total - height_em) + (root_d * rscale).max(0.0);
6134                let x_root = width * rscale - offset;
6135                root_shift = x_root * 1000.0 * scale;
6136                // computeRootBBox: Combine(root, 0, h), then the base at
6137                // x + surd.W, in em before the parent scale.
6138                parent.width_em = Some(
6139                    ((x_root + surd_w) + body_width_em)
6140                        .max(surd_w)
6141                        .max(root_w * rscale)
6142                        * scale,
6143                );
6144                out.ascent = out
6145                    .ascent
6146                    .max(baseline + (bbox_h + root_h * rscale) * 1000.0 * scale);
6147                out.depth = out
6148                    .depth
6149                    .max((root_d * rscale - bbox_h) * 1000.0 * scale - baseline);
6150                let mut group = LayoutGroup {
6151                    x_frame: None,
6152                    data_cramped: None,
6153                    own_translate: None,
6154                    accent_offset: None,
6155                    box_border: None,
6156                    reference: None,
6157                    tagged: None,
6158                    percentage: None,
6159                    table_line: None,
6160                    mathsize: None,
6161                    tex_class: 0,
6162                    before_glyph: out.glyphs.len(),
6163                    scale: index_scale,
6164                    x: dx * rscale * 1000.0 * scale,
6165                    baseline: baseline + h * 1000.0 * scale,
6166                    color: None,
6167                    background: None,
6168                    kind: "",
6169                    body: Box::new(index_box),
6170                    delimiter: None,
6171                    arrow: None,
6172                    lines: Vec::new(),
6173                };
6174                // The index is the mroot's own child node (no extra frame).
6175                if group.body.glyphs.is_empty()
6176                    && group.body.rules.is_empty()
6177                    && group.body.groups.len() == 1
6178                {
6179                    let mut child = group.body.groups.pop()?;
6180                    child.x += group.x;
6181                    child.x_frame = None;
6182                    child.baseline += group.baseline;
6183                    child.before_glyph = out.glyphs.len();
6184                    group = child;
6185                } else if group.body.groups.is_empty()
6186                    && group.body.rules.is_empty()
6187                    && group.body.glyphs.len() == 1
6188                {
6189                    let mut glyph = group.body.glyphs.pop()?;
6190                    glyph.x += group.x;
6191                    glyph.baseline += group.baseline;
6192                    root_glyph = Some(glyph);
6193                } else {
6194                    group.kind = "mrow";
6195                }
6196                root_group = Some((group, root_w * rscale * 1000.0 * scale));
6197            }
6198            out.ascent = out.ascent.max(baseline + body_box.ascent);
6199            out.depth = out.depth.max(body_box.depth - baseline);
6200            let body_box = if root_index.is_some() {
6201                // mroot's base is its own (non-inferred) child: wrap it in an
6202                // untransformed container and place the base node itself.
6203                let shift = root_shift + surd_width;
6204                let mut container = Layout {
6205                    bounds_em: None,
6206                    width_em: body_box.width_em,
6207                    intrinsic_width_em: None,
6208                    width: body_box.width,
6209                    ascent: body_box.ascent,
6210                    depth: body_box.depth,
6211                    glyphs: Vec::new(),
6212                    rules: Vec::new(),
6213                    groups: Vec::new(),
6214                };
6215                let mut base = body_box;
6216                if base.glyphs.is_empty() && base.rules.is_empty() && base.groups.len() == 1 {
6217                    let mut child = base.groups.pop()?;
6218                    child.x += shift;
6219                    child.x_frame = None;
6220                    child.before_glyph = 0;
6221                    container.groups.push(child);
6222                } else if base.groups.is_empty() && base.rules.is_empty() && base.glyphs.len() == 1
6223                {
6224                    let mut glyph = base.glyphs.pop()?;
6225                    glyph.x += shift;
6226                    container.glyphs.push(glyph);
6227                } else {
6228                    container.groups.push(LayoutGroup {
6229                        x_frame: None,
6230                        data_cramped: None,
6231                        own_translate: None,
6232                        accent_offset: None,
6233                        box_border: None,
6234                        reference: None,
6235                        tagged: None,
6236                        percentage: None,
6237                        table_line: None,
6238                        mathsize: None,
6239                        tex_class: 0,
6240                        before_glyph: 0,
6241                        scale,
6242                        x: shift,
6243                        baseline: 0.0,
6244                        color: None,
6245                        background: None,
6246                        kind: "mrow",
6247                        body: Box::new(base),
6248                        delimiter: None,
6249                        arrow: None,
6250                        lines: Vec::new(),
6251                    });
6252                }
6253                container
6254            } else {
6255                body_box
6256            };
6257            out.groups.push(LayoutGroup {
6258                x_frame: None,
6259                data_cramped: None,
6260                own_translate: None,
6261                accent_offset: None,
6262                box_border: None,
6263                reference: None,
6264                tagged: None,
6265                percentage: None,
6266                table_line: None,
6267                mathsize: None,
6268                tex_class: 0,
6269                before_glyph: out.glyphs.len(),
6270                scale,
6271                x: if root_index.is_some() {
6272                    x
6273                } else {
6274                    x + surd_width
6275                },
6276                baseline,
6277                color: None,
6278                background: None,
6279                kind: "",
6280                body: Box::new(body_box),
6281                delimiter: None,
6282                arrow: None,
6283                lines: Vec::new(),
6284            });
6285            let mut root_width = 0.0;
6286            if let Some((group, width)) = root_group {
6287                root_width = width;
6288                if let Some(glyph) = root_glyph {
6289                    out.glyphs.push(glyph);
6290                } else {
6291                    out.groups.push(group);
6292                }
6293            }
6294            out.glyphs.push(PositionedGlyph {
6295                font_original: None,
6296                font_variant: "normal",
6297                bold: false,
6298                small_operator: false,
6299                variant: false,
6300                unit: false,
6301                calligraphic: false,
6302                italic: false,
6303                codepoint: 0x221A,
6304                x: x + root_shift,
6305                baseline: surd_baseline,
6306                scale,
6307                large: false,
6308                stretch: false,
6309                radical_variant: variant,
6310                assembly_height,
6311            });
6312            // Source rootToSVG applies bbox.Scale before the script parent scale.
6313            let painted_rule = rule * scale * mathsize;
6314            out.rules.push((
6315                x + root_shift + surd_width,
6316                baseline + (paint_height_em - 0.06 * scale * mathsize) * 1000.0 * scale,
6317                body_width,
6318                painted_rule,
6319            ));
6320            // BBox.Combine adds the scaled surd height to its already computed
6321            // placement offset; retain that subtraction before addition.
6322            out.ascent = out.ascent.max(
6323                baseline
6324                    + (height_em + 0.06).max(surd.height + (height_em - surd.height))
6325                        * 1000.0
6326                        * scale,
6327            );
6328            out.depth = out
6329                .depth
6330                .max((surd.depth - (height_em - surd.height)) * 1000.0 * scale - baseline);
6331            let width = (root_shift + surd_width + body_width)
6332                .max(surd_width)
6333                .max(root_width);
6334            out.width = width;
6335            parent.ascent = parent.ascent.max(parent_baseline + out.ascent);
6336            parent.depth = parent.depth.max(out.depth - parent_baseline);
6337            parent.groups.push(LayoutGroup {
6338                x_frame: None,
6339                data_cramped: None,
6340                own_translate: None,
6341                accent_offset: None,
6342                box_border: None,
6343                reference: None,
6344                tagged: None,
6345                percentage: None,
6346                table_line: None,
6347                mathsize: None,
6348                tex_class: 0,
6349                before_glyph: parent.glyphs.len(),
6350                // wrapper.place adds the mroot's own dx (rootToSVG sets it to
6351                // the index shift) to the parent's placement.
6352                x: parent_x + root_shift,
6353                baseline: parent_baseline,
6354                scale,
6355                color: None,
6356                background: None,
6357                kind: if root_index.is_some() {
6358                    "mroot"
6359                } else {
6360                    "msqrt"
6361                },
6362                delimiter: None,
6363                arrow: None,
6364                body: Box::new(root),
6365                lines: Vec::new(),
6366            });
6367            Some(width)
6368        }
6369        Atom::Matrix {
6370            rows,
6371            environment,
6372            column_spec,
6373            options,
6374            spacing,
6375        } => table::layout(
6376            rows,
6377            environment,
6378            column_spec,
6379            options.as_ref(),
6380            *spacing,
6381            x,
6382            baseline,
6383            scale,
6384            out,
6385            prime_style,
6386        ),
6387        Atom::Multiscripts {
6388            base,
6389            sub,
6390            sup,
6391            post,
6392            prescript,
6393            mathsize,
6394        } => multiscripts::layout(
6395            base,
6396            sub,
6397            sup,
6398            post.as_ref(),
6399            *prescript,
6400            *mathsize,
6401            x,
6402            baseline,
6403            scale,
6404            out,
6405            display_style,
6406            prime_style,
6407        ),
6408        Atom::Scripts {
6409            base,
6410            sub,
6411            sup,
6412            limits,
6413            leading_space,
6414            accent,
6415            ..
6416        } => {
6417            // Pinned tex/move_limits_filter.go converts an inline stack when
6418            // its direct base owns the movablelimits property. A mathop
6419            // TeXAtom owns that property independently of its deeper core.
6420            let operator_limits = *limits && (display_style || !mathop_movable_property(base));
6421            if operator_limits && !classes::movable_limits(base, display_style) {
6422                return classes::layout_limits(
6423                    base,
6424                    sub.as_deref(),
6425                    sup.as_deref(),
6426                    *leading_space,
6427                    *accent,
6428                    x,
6429                    baseline,
6430                    scale,
6431                    out,
6432                    display_style,
6433                    prime_style,
6434                );
6435            }
6436            // Original internal/svg/msubsup.go: actual child bounds, base italic
6437            // correction, and TeX sub/sup shift constraints determine the box.
6438            let ordinary_probe = |atom: &Atom, child_scale, display, prime| {
6439                let mut bounds = Layout {
6440                    bounds_em: None,
6441                    width_em: None,
6442                    intrinsic_width_em: None,
6443                    width: 0.0,
6444                    ascent: 0.0,
6445                    depth: 0.0,
6446                    glyphs: Vec::new(),
6447                    rules: Vec::new(),
6448                    groups: Vec::new(),
6449                };
6450                bounds.width =
6451                    layout_at_with_style(atom, 0.0, 0.0, child_scale, &mut bounds, display, prime)?;
6452                retain_negative_glyph_depth(&mut bounds);
6453                Some(bounds)
6454            };
6455            let base_box = ordinary_probe(base, scale, display_style, prime_style)?;
6456            // wrapper.go caps scriptlevel at two before getScale. The
6457            // level-two product stays below 0.5 at the default 8px minimum.
6458            let script_scale = (scale * styles::SCRIPT_MULTIPLIER)
6459                .max(styles::SCRIPT_MULTIPLIER * styles::SCRIPT_MULTIPLIER);
6460            // Source constructs/stretches under-over children before selecting
6461            // movable-limit side placement. The core mark keeps that sizing.
6462            let mut requested_em = base_box.width_em.unwrap_or(base_box.width / 1000.);
6463            if operator_limits {
6464                for a in [sub, sup].into_iter().flatten() {
6465                    if !matches!(a.as_ref(), Atom::HorizontalMark { stretchy: true, .. }) {
6466                        let bounds = ordinary_probe(a, script_scale, false, prime_style)?;
6467                        requested_em =
6468                            requested_em.max(bounds.width_em.unwrap_or(bounds.width / 1000.));
6469                    }
6470                }
6471            }
6472            let probe = |atom: &Atom, child_scale, display, prime| {
6473                if operator_limits && matches!(atom, Atom::HorizontalMark { .. }) {
6474                    accents::probe_mark(atom, requested_em, child_scale, prime, display)
6475                } else {
6476                    ordinary_probe(atom, child_scale, display, prime)
6477                }
6478            };
6479            let sub_box = if let Some(a) = sub {
6480                Some(probe(a, script_scale, false, true)?)
6481            } else {
6482                None
6483            };
6484            let sup_box = if let Some(a) = sup {
6485                Some(probe(a, script_scale, false, prime_style)?)
6486            } else {
6487                None
6488            };
6489            let (core, core_scale, core_display, core_prime) =
6490                styles::script_core(base, scale, display_style, prime_style);
6491            let core_box = probe(core, core_scale, core_display, core_prime)?;
6492            let (character, ic) = if let Atom::RawOperator {
6493                body, definition, ..
6494            } = core
6495            {
6496                (
6497                    !definition.flag("largeop"),
6498                    operator_dictionary::body_correction(body, *definition, core_display)
6499                        * 1000.0
6500                        * core_scale,
6501                )
6502            } else if let Atom::Glyph(codepoint)
6503            | Atom::LiteralGlyph(codepoint)
6504            | Atom::VariantGlyph(codepoint)
6505            | Atom::Unit(codepoint)
6506            | Atom::CalligraphicGlyph(codepoint)
6507            | Atom::ItalicGlyph(codepoint) = core
6508            {
6509                let corrections = if !core_display && is_large_operator(*codepoint) {
6510                    smallop_glyphs::ITALIC_CORRECTIONS
6511                } else if matches!(core, Atom::VariantGlyph(_)) {
6512                    tex_variant_glyphs::ITALIC_CORRECTIONS
6513                } else if is_large_operator(*codepoint) {
6514                    large_glyphs::ITALIC_CORRECTIONS
6515                } else if matches!(core, Atom::CalligraphicGlyph(_)) {
6516                    calligraphic_glyphs::ITALIC_CORRECTIONS
6517                } else {
6518                    glyphs::ITALIC_CORRECTIONS
6519                };
6520                let ic = (if matches!(core, Atom::CalligraphicGlyph(_))
6521                    && !is_large_operator(*codepoint)
6522                {
6523                    calligraphic_correction(*codepoint)
6524                } else if matches!(core, Atom::ItalicGlyph(_)) && !is_large_operator(*codepoint) {
6525                    italic_correction(*codepoint)
6526                } else {
6527                    corrections
6528                        .binary_search_by_key(codepoint, |e| e.0)
6529                        .ok()
6530                        .map_or(0.0, |i| corrections[i].1)
6531                }) * 1000.0
6532                    * core_scale;
6533                (!is_large_operator(*codepoint), ic)
6534            } else if let Atom::FontGlyph { paint, .. } = core {
6535                (
6536                    !is_large_operator(*paint),
6537                    classes::italic_correction(core, core_display) * 1000.0 * core_scale,
6538                )
6539            } else if let Atom::Identifier(children) = core {
6540                let ic = children
6541                    .last()
6542                    .map_or(0., |a| classes::italic_correction(a, core_display))
6543                    * 1000.0
6544                    * core_scale;
6545                (children.len() == 1, ic)
6546            } else if let Atom::Number(children) = core {
6547                (children.len() == 1, 0.0)
6548            } else {
6549                (false, 0.0)
6550            };
6551            // Source baseWidth/adjustedIC remain in em until place() scales
6552            // the combined offset. Scaling their terms first changes ties.
6553            let unit = 1000.0 * scale;
6554            let base_em = base_box
6555                .width_em
6556                .map(|v| v / scale)
6557                .unwrap_or(base_box.width / unit);
6558            let ic_em = ic / unit;
6559            let base_width_em = base_em - if sub.is_some() { ic_em } else { 0.0 } + 0.033;
6560            let adjusted_em = if ic == 0.0 {
6561                0.0
6562            } else {
6563                (1.05 * (ic / (1000.0 * core_scale)) + 0.05) * (core_scale / scale)
6564            };
6565            let base_width = base_width_em * unit;
6566            // CommonMsubsup.scriptChild remains child 1 (the subscript).
6567            // supShift therefore starts from that child's depth when both
6568            // scripts exist, before enforcing their mutual clearance.
6569            // svg/msubsup.go uses the script wrapper's RScale in drop
6570            // terms; a mathsize or scriptlevel declaration belongs to that
6571            // wrapper, independently of the inherited script scale.
6572            let sub_scale = sub
6573                .as_deref()
6574                .map_or(script_scale, |a| accents::own_scale(a, script_scale));
6575            let first_script_scale = sub
6576                .as_deref()
6577                .or(sup.as_deref())
6578                .map_or(script_scale, |a| accents::own_scale(a, script_scale));
6579            let mut u = sub_box.as_ref().or(sup_box.as_ref()).map_or(0.0, |bounds| {
6580                let minimum = (if prime_style {
6581                    289.0
6582                } else if display_style {
6583                    413.0
6584                } else {
6585                    363.0
6586                }) * scale;
6587                let drop = if character {
6588                    0.0
6589                } else {
6590                    core_box.ascent - 386.0 * first_script_scale
6591                };
6592                drop.max(minimum).max(bounds.depth + 110.5 * scale)
6593            });
6594            let mut v = sub_box.as_ref().map_or(0.0, |bounds| {
6595                let drop = if character {
6596                    0.0
6597                } else {
6598                    core_box.depth + 50.0 * sub_scale
6599                };
6600                if sup.is_some() {
6601                    drop.max(247.0 * scale)
6602                } else {
6603                    drop.max(150.0 * scale).max(
6604                        (bounds.ascent / (1000.0 * script_scale) * (script_scale / scale)
6605                            - 0.8 * 0.442)
6606                            * 1000.0
6607                            * scale,
6608                    )
6609                }
6610            });
6611            if let (Some(sub_bounds), Some(sup_bounds)) = (&sub_box, &sup_box) {
6612                let space = (u - sup_bounds.depth) - (sub_bounds.ascent - v);
6613                if space < 180.0 * scale {
6614                    v += 180.0 * scale - space;
6615                    let p = 353.6 * scale - (u - sup_bounds.depth);
6616                    if p > 0.0 {
6617                        u += p;
6618                        v -= p;
6619                    }
6620                }
6621            }
6622            let mut local = Layout {
6623                bounds_em: None,
6624                width_em: None,
6625                intrinsic_width_em: None,
6626                width: 0.0,
6627                ascent: 0.0,
6628                depth: 0.0,
6629                glyphs: Vec::new(),
6630                rules: Vec::new(),
6631                groups: Vec::new(),
6632            };
6633            // Source msubsup places child wrappers in its own frame. Keep
6634            // composite child frames (and independent RScale rounding).
6635            let mut place = |atom: &Atom,
6636                             dx: f64,
6637                             dy: f64,
6638                             child_scale: f64,
6639                             display: bool,
6640                             prime: bool|
6641             -> Option<()> {
6642                let mut child = probe(atom, child_scale, display, prime)?;
6643                if child.glyphs.is_empty()
6644                    && child.rules.is_empty()
6645                    && child.groups.len() == 1
6646                    && child.groups[0].x == 0.0
6647                    && child.groups[0].baseline == 0.0
6648                    && (child.groups[0].scale == child_scale || child.groups[0].kind == "mstyle")
6649                {
6650                    let mut group = child.groups.pop()?;
6651                    group.x = dx;
6652                    group.x_frame = None;
6653                    group.baseline = dy;
6654                    group.before_glyph = local.glyphs.len();
6655                    local.groups.push(group);
6656                } else if matches!(
6657                    atom,
6658                    Atom::Glyph(_)
6659                        | Atom::FontGlyph { .. }
6660                        | Atom::LiteralGlyph(_)
6661                        | Atom::VariantGlyph(_)
6662                        | Atom::CalligraphicGlyph(_)
6663                        | Atom::ItalicGlyph(_)
6664                        | Atom::Unit(_)
6665                ) {
6666                    layout_at_with_style(atom, dx, dy, child_scale, &mut local, display, prime)?;
6667                } else if child.groups.is_empty()
6668                    && child.rules.is_empty()
6669                    && child.glyphs.len() == 1
6670                {
6671                    // Transparent parser policies (for example MovesScripts)
6672                    // do not introduce MathML rows. Source msubsup places the
6673                    // existing child wrapper; retain its intrinsic glyph offset.
6674                    classes::place(child, dx, dy, child_scale, &mut local);
6675                } else {
6676                    local.groups.push(LayoutGroup {
6677                        x_frame: None,
6678                        data_cramped: None,
6679                        own_translate: None,
6680                        accent_offset: None,
6681                        box_border: None,
6682                        reference: None,
6683                        tagged: None,
6684                        percentage: None,
6685                        table_line: None,
6686                        mathsize: None,
6687                        tex_class: 0,
6688                        before_glyph: local.glyphs.len(),
6689                        x: dx,
6690                        baseline: dy,
6691                        scale: child_scale,
6692                        kind: "mrow",
6693                        color: None,
6694                        background: None,
6695                        delimiter: None,
6696                        arrow: None,
6697                        lines: Vec::new(),
6698                        body: Box::new(child),
6699                    });
6700                }
6701                Some(())
6702            };
6703            place(base, 0.0, 0.0, scale, display_style, prime_style)?;
6704            let mut ascent = base_box.ascent;
6705            let mut depth = base_box.depth;
6706            if let (Some(atom), Some(bounds)) = (sup, &sup_box) {
6707                let offset = (base_width_em
6708                    + if sub.is_some() {
6709                        adjusted_em
6710                    } else {
6711                        adjusted_em - ic_em
6712                    })
6713                    * unit;
6714                place(atom, offset, u, script_scale, false, prime_style)?;
6715                ascent = ascent.max(u + bounds.ascent);
6716                depth = depth.max(bounds.depth - u);
6717            }
6718            if let (Some(atom), Some(bounds)) = (sub, &sub_box) {
6719                place(atom, base_width, -v, script_scale, false, true)?;
6720                ascent = ascent.max(bounds.ascent - v);
6721                depth = depth.max(bounds.depth + v);
6722            }
6723            // Source computes script BBox.Combine widths in em, then applies
6724            // parent scaling. Adding scaled font-unit values first moves ties.
6725
6726            let mut width_em = base_em + leading_space / unit;
6727            if let Some(bounds) = &sup_box {
6728                let offset = base_width_em
6729                    + if sub.is_some() {
6730                        adjusted_em
6731                    } else {
6732                        adjusted_em - ic_em
6733                    };
6734                width_em =
6735                    width_em.max(offset + bounds.width_em.unwrap_or(bounds.width / 1000.0) / scale);
6736            }
6737            if let Some(bounds) = &sub_box {
6738                width_em = width_em
6739                    .max(base_width_em + bounds.width_em.unwrap_or(bounds.width / 1000.0) / scale);
6740            }
6741            let width = (width_em
6742                + if sub.is_some() || sup.is_some() {
6743                    0.05
6744                } else {
6745                    0.0
6746                })
6747                * unit;
6748            local.width = width;
6749            local.ascent = ascent;
6750            local.depth = depth;
6751            let script_width_em = (width_em
6752                + if sub.is_some() || sup.is_some() {
6753                    0.05
6754                } else {
6755                    0.0
6756                })
6757                * scale;
6758            local.width_em = Some(script_width_em);
6759            out.width_em = Some(script_width_em);
6760            out.intrinsic_width_em = Some(
6761                width_em
6762                    + if sub.is_some() || sup.is_some() {
6763                        0.05
6764                    } else {
6765                        0.0
6766                    },
6767            );
6768            out.groups.push(LayoutGroup {
6769                x_frame: None,
6770                data_cramped: None,
6771                own_translate: None,
6772                accent_offset: None,
6773                box_border: None,
6774                reference: None,
6775                tagged: None,
6776                percentage: None,
6777                table_line: None,
6778                mathsize: None,
6779                tex_class: 0,
6780                before_glyph: out.glyphs.len(),
6781                x,
6782                baseline,
6783                scale,
6784                kind: if operator_limits {
6785                    if sub.is_some() {
6786                        if sup.is_some() {
6787                            "munderover"
6788                        } else {
6789                            "munder"
6790                        }
6791                    } else {
6792                        "mover"
6793                    }
6794                } else if sub.is_some() {
6795                    if sup.is_some() { "msubsup" } else { "msub" }
6796                } else {
6797                    "msup"
6798                },
6799                color: None,
6800                background: None,
6801                delimiter: None,
6802                arrow: None,
6803                lines: Vec::new(),
6804                body: Box::new(local),
6805            });
6806            out.ascent = out.ascent.max(baseline + ascent);
6807            out.depth = out.depth.max(depth - baseline);
6808            Some(width)
6809        }
6810    }
6811}
6812
6813// AMS operatorname keeps a single mi result; other tokens acquire a
6814// TeXAtom owner. This distinguishes core attributes from owner attributes.
6815fn operator_name_identifier(atom: &Atom) -> bool {
6816    match atom {
6817        Atom::Identifier(_) | Atom::AutoOperator(_) => true,
6818        Atom::Operator(a) | Atom::ScriptPolicy { body: a, .. } => operator_name_identifier(a),
6819        Atom::Glyph(c)
6820        | Atom::LiteralGlyph(c)
6821        | Atom::ItalicGlyph(c)
6822        | Atom::VariantGlyph(c)
6823        | Atom::CalligraphicGlyph(c) => char::from_u32(*c).is_some_and(letter_unicode::is_letter),
6824        _ => false,
6825    }
6826}
6827
6828fn mathop_movable_property(base: &Atom) -> bool {
6829    match base {
6830        Atom::ScriptPolicy {
6831            movable_property: true,
6832            ..
6833        } => true,
6834        Atom::Class { class: 1, .. } => true,
6835        Atom::NamedFunction(body) => mathop_movable_property(body),
6836        _ => false,
6837    }
6838}
6839
6840// commands.go checkMovableLimits inspects only the direct parsed argument,
6841// preserving policies below authored grouped and scripted bases.
6842fn check_movable_limits(base: &mut Atom) {
6843    if let Atom::Sequence(children) = base
6844        && children.len() == 1
6845    {
6846        check_movable_limits(&mut children[0]);
6847        return;
6848    }
6849    if matches!(base, Atom::MovesScripts(_))
6850        || mathop_movable_property(base)
6851        || matches!(base, Atom::RawOperator { definition, .. }
6852            if definition.flag("movablelimits"))
6853    {
6854        let moves = script_moves(base);
6855        // checkMovableLimits writes on the direct node. A mathop TeXAtom
6856        // keeps the independent attribute of its deeper operator core.
6857        let own_core = !mathop_movable_property(base);
6858        let body = std::mem::replace(base, Atom::Sequence(Vec::new()));
6859        *base = Atom::ScriptPolicy {
6860            body: Box::new(body),
6861            moves,
6862            movable: own_core.then_some(false),
6863            movable_property: false,
6864        };
6865    }
6866}
6867
6868// Source movesupsub is independent of the retained script node kind.
6869fn script_moves(atom: &Atom) -> bool {
6870    match atom {
6871        Atom::ScriptPolicy { moves, .. } => *moves,
6872        Atom::NamedFunction(body) => script_moves(body),
6873        Atom::Class { class: 1, .. } | Atom::MovesScripts(_) => true,
6874        _ => false,
6875    }
6876}
6877
6878// Original internal/svg/texclass.go and internal/mml/node.go. Fraction/root
6879// fractions retain null classes; nodeFactory initializes radical wrappers to ORD.
6880fn atom_tex_class(atom: &Atom) -> Option<usize> {
6881    match atom {
6882        Atom::NonscriptSpace { body, .. } => atom_tex_class(body),
6883        // svg/texclass.go MmlMi.operatorName: normal multi-character ASCII
6884        // identifiers acquire OP spacing without becoming function items.
6885        Atom::NotToken { class, .. } => Some(*class),
6886        Atom::AutoOperator(_) => Some(1),
6887        Atom::CdArrow { texclass, .. } => *texclass,
6888        Atom::MathMLSpace { .. } => Some(0),
6889        Atom::FontGlyph { original, .. } => atom_tex_class(&Atom::Glyph(*original)),
6890        Atom::RawOperator { definition, .. } => {
6891            (definition.class >= 0).then_some(definition.class as usize)
6892        }
6893        Atom::Glyph(code)
6894        | Atom::LiteralGlyph(code)
6895        | Atom::VariantGlyph(code)
6896        | Atom::CalligraphicGlyph(code)
6897        | Atom::ItalicGlyph(code) => Some(compound(*code).map_or_else(
6898            || {
6899                match *code {
6900                    0x220F | 0x2211 | 0x222B => 1,
6901                    c if is_large_operator(c) => 1,
6902                    0x2B | 0x2D | 0x2212 | 0xB1 | 0xD7 | 0x22C5 | 0x2297 | 0x2218 => 2,
6903                    0x3D
6904                    | 0x2248
6905                    | 0x223C
6906                    | 0x2260
6907                    | 0x2261
6908                    | 0x2264
6909                    | 0x2265
6910                    | 0x3C
6911                    | 0x3E
6912                    | 0x2190..=0x2195
6913                    | 0x21A9
6914                    | 0x21AA
6915                    | 0x21CC
6916                    | 0x21D0..=0x21D5
6917                    | 0x27F5..=0x27FA
6918                    | 0x27FC => 3,
6919                    0x28 | 0x5B | 0x7B => 4,
6920                    0x29 | 0x5D | 0x7D => 5,
6921                    0x2C | 0x3B => 6,
6922                    // Other mo tokens take their class from the original
6923                    // operator dictionary (tex/operator_dictionary_generated.go).
6924                    c if mathml_node_kind(c) == "mo" => {
6925                        operator_dictionary::lookup(c, operator_dictionary::Form::Infix)
6926                            .class
6927                            .max(0) as usize
6928                    }
6929                    _ => 0,
6930                }
6931            },
6932            |g| g.class,
6933        )),
6934        Atom::NamedFunction(body) => {
6935            if let Atom::Sequence(items) = body.as_ref() {
6936                items
6937                    .iter()
6938                    .rev()
6939                    .find(|item| !operator_dictionary::spacelike(item))
6940                    .and_then(atom_tex_class)
6941            } else {
6942                atom_tex_class(body)
6943            }
6944        }
6945        Atom::ApplyFunction => None,
6946        Atom::InferredRow(children) | Atom::ExplicitRow(children) => {
6947            children.first().and_then(atom_tex_class)
6948        }
6949        Atom::FenceDelimiter { code, class: 0, .. } => Some(
6950            operator_dictionary::lookup(*code, operator_dictionary::Form::Infix)
6951                .class
6952                .max(0) as usize,
6953        ),
6954        Atom::FenceDelimiter { class, .. } => Some(*class),
6955        Atom::Fenced { inner, .. } => Some(if *inner { 7 } else { 4 }),
6956        Atom::XArrow { .. } => Some(3),
6957        Atom::Operator(..) => Some(1),
6958        Atom::MovesScripts(body) | Atom::ScriptPolicy { body, .. } => atom_tex_class(body),
6959        Atom::Class { class, .. } => Some(*class),
6960        Atom::Boxed(..)
6961        | Atom::Sqrt(..)
6962        | Atom::Root { .. }
6963        | Atom::SizedSqrt { .. }
6964        | Atom::TaggedTable { .. }
6965        | Atom::Mrow(..)
6966        | Atom::Reference { .. }
6967        | Atom::Text(..)
6968        | Atom::Identifier(..)
6969        | Atom::StyledText(..)
6970        | Atom::Number(..)
6971        | Atom::OperatorToken(..)
6972        | Atom::Unit(..)
6973        | Atom::Ord(..)
6974        | Atom::ColorBox { .. } => Some(0),
6975        Atom::Color { body, .. }
6976        | Atom::Phantom(body)
6977        | Atom::CrampedStyle(body, _)
6978        | Atom::DeclaredStyle { body, .. }
6979        | Atom::DeclaredSize { body, .. }
6980        | Atom::Padded { body, .. } => atom_tex_class(body),
6981        Atom::Cancel { .. } => Some(0),
6982        Atom::Scripts { base, .. } => physics::script_class(base),
6983        Atom::Multiscripts { base, .. } => Some(physics::script_class(base).unwrap_or(0)),
6984        Atom::Matrix { environment, .. } => Some(if table::fences(environment).is_some() {
6985            7
6986        } else {
6987            0
6988        }),
6989        Atom::Sequence(children) => children.last().and_then(atom_tex_class),
6990        Atom::HorizontalMark { .. } => Some(0),
6991        Atom::BracketMark { .. } => None,
6992        Atom::FractionStrut(_)
6993        | Atom::FixedDelimiter { .. }
6994        | Atom::Choice(..)
6995        | Atom::Fraction(..)
6996        | Atom::SplitFraction(..)
6997        | Atom::GeneralFraction(..)
6998        | Atom::Space(_)
6999        | Atom::RuleSpace { .. }
7000        | Atom::Kern(_)
7001        | Atom::EmptyNode(_)
7002        | Atom::Strut(..)
7003        | Atom::ErrorDisplay(..)
7004        | Atom::SourceError(..) => None,
7005    }
7006}
7007
7008fn automatic_operator(children: &[Atom]) -> bool {
7009    children.len() >= 2
7010        && children.iter().enumerate().all(|(index, child)| {
7011            matches!(child, Atom::Glyph(code) if char::from_u32(*code).is_some_and(|c|
7012            c.is_ascii_alphabetic() || index > 0 && c.is_ascii_digit()))
7013        })
7014}
7015// setRowTeXClass returns a left/right row's closing delimiter while the
7016// row wrapper retains INNER for its own leading space.
7017fn return_tex_class(atom: &Atom, prepared: Option<usize>) -> Option<usize> {
7018    if mml_spacing::resets_tex_class(atom) {
7019        return None;
7020    }
7021    match atom {
7022        // svg/texclass.go effectiveTeXClass: an unset fraction class is
7023        // ORD when it becomes a predecessor, unlike an explicit NONE.
7024        Atom::Fraction(..) | Atom::GeneralFraction(..) | Atom::SplitFraction(..) => Some(0),
7025        Atom::InferredRow(children) | Atom::ExplicitRow(children) => {
7026            children.last().and_then(atom_tex_class)
7027        }
7028        Atom::Scripts { base, .. } if classes::wrapped_core_class(base).is_some() => {
7029            classes::adjustment_class(atom, prepared)
7030        }
7031        Atom::NamedFunction(body) => {
7032            if let Atom::Sequence(items) = body.as_ref() {
7033                items
7034                    .iter()
7035                    .rev()
7036                    .find(|item| !operator_dictionary::spacelike(item))
7037                    .and_then(|item| return_tex_class(item, atom_tex_class(item)))
7038            } else {
7039                return_tex_class(body, prepared)
7040            }
7041        }
7042        Atom::Fenced { .. } => Some(5),
7043        Atom::Matrix { environment, .. } if table::fences(environment).is_some() => Some(5),
7044        Atom::Color { body, .. }
7045        | Atom::Phantom(body)
7046        | Atom::CrampedStyle(body, _)
7047        | Atom::DeclaredStyle { body, .. }
7048        | Atom::DeclaredSize { body, .. }
7049        | Atom::Padded { body, .. }
7050        | Atom::ScriptPolicy { body, .. } => return_tex_class(body, prepared),
7051        Atom::Sequence(children) => {
7052            // setRowTeXClass returns the final child's prepared class. In
7053            // particular, isLastTeXAtom can demote a trailing BIN inside a
7054            // declaration before the following sibling reads PrevClass.
7055            let classes = sequence_tex_classes(children);
7056            children
7057                .iter()
7058                .enumerate()
7059                .rev()
7060                .find(|(_, child)| !operator_dictionary::spacelike(child))
7061                .and_then(|(index, child)| return_tex_class(child, classes[index]))
7062        }
7063        _ => prepared,
7064    }
7065}
7066fn sequence_tex_classes(children: &[Atom]) -> Vec<Option<usize>> {
7067    let mut classes: Vec<_> = children.iter().map(atom_tex_class).collect();
7068    let mut previous = None;
7069    for (index, child) in children.iter().enumerate() {
7070        if operator_dictionary::spacelike(child) {
7071            continue;
7072        }
7073        // adjustTeXClass demotes an automatically classified mi before a
7074        // binary or relation item, before deciding that item's own class.
7075        if matches!(
7076            classes::adjustment_class(child, classes[index]),
7077            Some(2 | 3)
7078        ) {
7079            if let Some(i) = previous {
7080                if matches!(&children[i], Atom::AutoOperator(_)) {
7081                    classes[i] = Some(0);
7082                }
7083            }
7084        }
7085        let previous_class =
7086            previous.and_then(|i: usize| return_tex_class(&children[i], classes[i]));
7087        if classes::adjustment_class(child, classes[index]) == Some(2)
7088            && (matches!(previous_class, None | Some(1 | 2 | 3 | 4 | 6))
7089                // texclass.go isLastTeXAtom tests the physical final child.
7090                // Empty styles and spaces still keep a preceding BIN internal.
7091                || index + 1 == children.len())
7092        {
7093            classes[index] = Some(0);
7094        } else if matches!(
7095            classes::adjustment_class(child, classes[index]),
7096            Some(3 | 5 | 6)
7097        ) && previous_class == Some(2)
7098        {
7099            classes[previous.unwrap()] = Some(0);
7100        }
7101        previous = Some(index);
7102    }
7103    classes
7104}
7105fn tex_class_spacing(left: Option<usize>, right: Option<usize>, script: bool) -> f64 {
7106    const TABLE: [[i8; 8]; 8] = [
7107        [0, -1, 2, 3, 0, 0, 0, 1],
7108        [-1, -1, 0, 3, 0, 0, 0, 1],
7109        [2, 2, 0, 0, 2, 0, 0, 2],
7110        [3, 3, 0, 0, 3, 0, 0, 3],
7111        [0, 0, 0, 0, 0, 0, 0, 0],
7112        [0, -1, 2, 3, 0, 0, 0, 1],
7113        [1, 1, 0, 1, 1, 1, 1, 1],
7114        [1, -1, 2, 3, 1, 0, 1, 1],
7115    ];
7116    let (Some(left), Some(right)) = (left, right) else {
7117        return 0.0;
7118    };
7119    if left > 7 || right > 7 {
7120        return 0.0;
7121    }
7122    let space = TABLE[left][right];
7123    if script && space >= 0 {
7124        return 0.0;
7125    }
7126    match space.abs() {
7127        1 => 1000.0 / 6.0,
7128        2 => 2000.0 / 9.0,
7129        3 => 5000.0 / 18.0,
7130        _ => 0.0,
7131    }
7132}
7133
7134// Original internal/svg/stretch.go: top/bottom parts and clipped extender.
7135fn render_radical_assembly(svg: &mut String, item: PositionedGlyph, total: f64, depth: f64) {
7136    let height = total - depth;
7137    let [top, extender, bottom] = radical_glyphs::ASSEMBLY_PARTS;
7138    let width = 1.056;
7139    // Original svg/stretch.go stretchVertical: wrapper.place on the mo,
7140    // standardSVG's scale only for RScale != 1, then placeChar paths whose
7141    // own place() transform follows their d attribute.
7142    let (placed_x, placed_y) = (root_number(item.x), root_number(item.baseline));
7143    let mut transform = if placed_x == "0" && placed_y == "0" {
7144        String::new()
7145    } else {
7146        format!("translate({placed_x},{placed_y})")
7147    };
7148    if item.scale != 1.0 && number(item.scale) != "1" {
7149        transform = format!("{transform} scale({})", number(item.scale))
7150            .trim()
7151            .to_owned();
7152    }
7153    if transform.is_empty() {
7154        svg.push_str("<g data-mml-node=\"mo\">");
7155    } else {
7156        svg.push_str(&format!(
7157            "<g data-mml-node=\"mo\" transform=\"{transform}\">"
7158        ));
7159    }
7160    for (code, glyph, y) in [
7161        (0xE001, top, height - top.height),
7162        (0x23B7, bottom, bottom.depth - depth),
7163    ] {
7164        let (x, y) = (
7165            root_number((width - glyph.width) * 500.0),
7166            root_number(y * 1000.0),
7167        );
7168        let place = if x == "0" && y == "0" {
7169            String::new()
7170        } else {
7171            format!(" transform=\"translate({x},{y})\"")
7172        };
7173        svg.push_str(&format!(
7174            "<path data-c=\"{:X}\" d=\"M{}Z\"{place}></path>",
7175            code, glyph.path
7176        ));
7177    }
7178    let top_extent = (top.height + top.depth - 0.1).max(0.0);
7179    let bottom_extent = (bottom.height + bottom.depth - 0.1).max(0.0);
7180    let extent = total - top_extent - bottom_extent;
7181    if extent > 0.0 && extender.height + extender.depth != 0.0 {
7182        let stretch = 1.5 * extent / (extender.height + extender.depth);
7183        let y = (stretch * (extender.height - extender.depth) - extent) / 2.0;
7184        svg.push_str(&format!("<svg width=\"{}\" height=\"{}\" y=\"{}\" x=\"{}\" viewBox=\"0 {} {} {}\"><path data-c=\"E000\" d=\"M{}Z\" transform=\"scale(1,{})\"></path></svg>",
7185            root_number(extender.width*1000.0), root_number(extent*1000.0),
7186            root_number((bottom_extent-depth)*1000.0), root_number((width-extender.width)*500.0),
7187            root_number(y*1000.0), root_number(extender.width*1000.0), root_number(extent*1000.0),
7188            extender.path, number(stretch)));
7189    }
7190    svg.push_str("</g>");
7191}
7192
7193// Original wrapper.place/standardSVG retain local coordinates and RScale.
7194// Returning to the parent's frame before fixed() preserves Source rounding;
7195// multiplying rounded world coordinates is observably different for scripts.
7196fn layout_in_parent_frame(layout: &Layout, scale: f64) -> Layout {
7197    Layout {
7198        bounds_em: layout.bounds_em.map(|(h, d)| (h / scale, d / scale)),
7199        width_em: layout.width_em.map(|w| w / scale),
7200        intrinsic_width_em: None,
7201        width: layout.width / scale,
7202        ascent: layout.ascent / scale,
7203        depth: layout.depth / scale,
7204        glyphs: layout
7205            .glyphs
7206            .iter()
7207            .map(|glyph| PositionedGlyph {
7208                x: glyph.x / scale,
7209                baseline: glyph.baseline / scale,
7210                scale: glyph.scale / scale,
7211                ..*glyph
7212            })
7213            .collect(),
7214        rules: layout
7215            .rules
7216            .iter()
7217            .map(|(x, y, w, h)| (x / scale, y / scale, w / scale, h / scale))
7218            .collect(),
7219        groups: layout
7220            .groups
7221            .iter()
7222            .map(|group| LayoutGroup {
7223                x_frame: group.x_frame.map(|(x, frame)| (x, frame / scale)),
7224                data_cramped: group.data_cramped,
7225                own_translate: group.own_translate,
7226                accent_offset: group.accent_offset,
7227                box_border: group.box_border.map(|v| v / scale),
7228                reference: group.reference.clone(),
7229                tagged: group.tagged.as_ref().map(|t| ams::copy_tagged(t, scale)),
7230                percentage: group.percentage.clone(),
7231                table_line: group.table_line,
7232                mathsize: group.mathsize,
7233                tex_class: group.tex_class,
7234                before_glyph: group.before_glyph,
7235                scale: group.scale / scale,
7236                x: group
7237                    .x_frame
7238                    .map_or(group.x / scale, |(x, frame)| x * (frame / scale)),
7239                baseline: group.baseline / scale,
7240                color: group.color.clone(),
7241                kind: group.kind,
7242                delimiter: group.delimiter,
7243                arrow: group.arrow,
7244                background: group
7245                    .background
7246                    .as_ref()
7247                    .map(|(c, w, h, d)| (c.clone(), w / scale, h / scale, d / scale)),
7248                body: Box::new(layout_in_parent_frame(&group.body, scale)),
7249                lines: group
7250                    .lines
7251                    .iter()
7252                    .map(|(x1, y1, x2, y2, w)| {
7253                        (x1 / scale, y1 / scale, x2 / scale, y2 / scale, w / scale)
7254                    })
7255                    .collect(),
7256            })
7257            .collect(),
7258    }
7259}
7260
7261// Original svg/wrapper.go placeChar: preserve a compound group, use the same
7262// variant for children, and advance by their returned widths; parent width is
7263// the source compound entry, not the measured painted run.
7264fn render_compound_character(mut item: PositionedGlyph, code: u32, x: f64, y: f64) -> String {
7265    if compound(item.codepoint).is_some_and(|g| g.large.is_some()) {
7266        item.calligraphic = false;
7267        item.italic = false;
7268        item.variant = false;
7269    }
7270
7271    let (placed_x, placed_y) = (root_number(x * 1000.0), root_number(y * 1000.0));
7272    let place = if placed_x == "0" && placed_y == "0" {
7273        String::new()
7274    } else {
7275        format!(" transform=\"translate({placed_x},{placed_y})\"")
7276    };
7277    let content = if let Some(content) = declaration_fonts::content(code, item.font_variant) {
7278        Some(content)
7279    } else if item.bold {
7280        double_struck::bold(code)
7281            .map(|r| r.2)
7282            .filter(|s| !s.is_empty())
7283    } else {
7284        compound(code).map(|g| g.content)
7285    };
7286    if let Some(content) = content {
7287        let mut svg = format!("<g data-c=\"{code:X}\"{place}>");
7288        let mut offset = 0.0;
7289        for ch in content.chars() {
7290            let (paint, bold) = if item.bold {
7291                double_struck::bold_child(ch as u32)
7292            } else {
7293                (ch as u32, false)
7294            };
7295            let child = PositionedGlyph {
7296                codepoint: paint,
7297                bold,
7298                ..item
7299            };
7300            svg.push_str(&render_compound_character(child, paint, offset, y));
7301            offset += glyph_for(child).expect("source compound child").width;
7302        }
7303        svg.push_str("</g>");
7304        return svg;
7305    }
7306    let child = PositionedGlyph {
7307        codepoint: code,
7308        ..item
7309    };
7310    let g = glyph_for(child).expect("source character");
7311    let path = if g.path.is_empty() {
7312        String::new()
7313    } else {
7314        format!("M{}Z", g.path)
7315    };
7316    format!("<path data-c=\"{code:X}\" d=\"{path}\"{place}></path>")
7317}
7318
7319fn painted_code(item: PositionedGlyph) -> u32 {
7320    if (item.italic || item.calligraphic)
7321        && (!item.calligraphic
7322            || calligraphic_glyphs::CALLIGRAPHIC_GLYPHS
7323                .binary_search_by_key(&item.codepoint, |g| g.codepoint)
7324                .is_err())
7325        && italic_glyphs::ITALIC_GLYPHS
7326            .binary_search_by_key(&item.codepoint, |g| g.codepoint)
7327            .is_err()
7328    {
7329        italic_font_code(item.codepoint)
7330    } else {
7331        item.codepoint
7332    }
7333}
7334
7335fn render_layout_group(svg: &mut String, group: &LayoutGroup, parent_kind: &str) {
7336    if group.tagged.is_some() {
7337        ams::render_tagged(svg, group);
7338        return;
7339    }
7340    if group.kind == "#array-frame-lines" {
7341        for (x1, y1, x2, y2, width) in &group.lines {
7342            svg.push_str(&format!(
7343                "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke-width=\"{}\"></line>",
7344                root_number(*x1 / group.scale),
7345                root_number(*y1 / group.scale),
7346                root_number(*x2 / group.scale),
7347                root_number(*y2 / group.scale),
7348                root_number(*width / group.scale)
7349            ));
7350        }
7351        return;
7352    }
7353    if let Some(line) = group.table_line {
7354        let style = if line.dashed { "dashed" } else { "solid" };
7355        if line.frame {
7356            svg.push_str(&format!("<rect data-frame=\"true\" class=\"mjx-{style}\" width=\"{}\" height=\"{}\" x=\"{}\" y=\"{}\"></rect>", root_number(line.x2.unwrap() - line.x), root_number(line.y2 - line.y1), root_number(line.x), root_number(line.y1)));
7357        } else {
7358            svg.push_str(&format!("<line data-line=\"{}\" class=\"mjx-{style}\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"></line>", if line.x2.is_some() { "h" } else { "v" }, root_number(line.x), root_number(line.y1), root_number(line.x2.unwrap_or(line.x)), root_number(line.y2)));
7359        }
7360        return;
7361    }
7362    if group.kind == "#inferred-place" {
7363        return;
7364    }
7365    // Accent/stretch character plans can retain an identity frame solely
7366    // for their selected delimiter glyph. It is not another SVG element.
7367    if group.kind.is_empty()
7368        && parent_kind == "mo"
7369        && group.x == 0.0
7370        && group.baseline == 0.0
7371        && group.scale == 1.0
7372    {
7373        if let Some(delimiter) = group.delimiter {
7374            cd::render_delimiter(svg, delimiter);
7375            return;
7376        }
7377    }
7378    let mut local =
7379        layout_in_parent_frame(&group.body, group.scale / group.mathsize.unwrap_or(1.0));
7380    let offsets: Vec<_> = local
7381        .groups
7382        .iter()
7383        .filter(|g| g.kind == "#inferred-place")
7384        .map(|g| (g.x, g.baseline))
7385        .collect();
7386    local.groups.retain(|g| g.kind != "#inferred-place");
7387    let inherited = offsets
7388        .iter()
7389        .rev()
7390        .map(|(x, y)| format!(" translate({},{})", root_number(*x), root_number(*y)))
7391        .collect::<String>();
7392    let color = group
7393        .color
7394        .as_ref()
7395        .map(|c| format!(" fill=\"{}\" stroke=\"{}\"", escape(c), escape(c)))
7396        .unwrap_or_default();
7397    // moToSVG SetAttr replaces standardSVG's scale when mathaccent installs
7398    // its own centering translation; place() then prepends its translation.
7399    let vcenter = group.kind == "TeXAtom" && group.tex_class == 8;
7400    // moToSVG installs the fixed variant's centering transform on its own
7401    // token element, replacing standardSVG's scale when the offset is nonzero.
7402    let fixed_fence_offset = group
7403        .delimiter
7404        .filter(|d| d.fixed && d.font_variant.is_some())
7405        .map(|d| d.height);
7406    // standardSVG emits scale only for RScale != 1 (see glyph placement).
7407    let scaling = if group.scale == 1.0
7408        || number(group.scale) == "1"
7409        || group.own_translate.is_some()
7410        || group.accent_offset.is_some()
7411        || vcenter
7412        || fixed_fence_offset.is_some_and(|v| v != 0.0)
7413    {
7414        String::new()
7415    } else {
7416        format!(" scale({})", number(group.scale))
7417    };
7418    let tex_class = if group.kind == "TeXAtom" {
7419        format!(
7420            " data-mjx-texclass=\"{}\"",
7421            [
7422                "ORD", "OP", "BIN", "REL", "OPEN", "CLOSE", "PUNCT", "INNER", "VCENTER"
7423            ][group.tex_class]
7424        )
7425    } else {
7426        String::new()
7427    };
7428    let bracket = matches!(group.kind, "#bracket-over" | "#bracket-under");
7429    let placed_x = group.x
7430        + if bracket {
7431            (group.box_border.unwrap() / group.scale).max(0.)
7432        } else {
7433            0.
7434        };
7435    // mtable explicitly calls wrapper.place on rows and cells. The source
7436    // tests numeric truthiness before fixed(), retaining tiny translations.
7437    let (placed_x, placed_y) = (root_number(placed_x), root_number(group.baseline));
7438    let enclose_block =
7439        group.kind.is_empty() && matches!(parent_kind, "menclose" | "#array-menclose-zero");
7440    let position = if enclose_block {
7441        // menclose creates its anonymous block directly, with this exact
7442        // separator and a positive-left test rather than wrapper.place.
7443        if group.x > 0.0 {
7444            format!("translate({placed_x}, {placed_y})")
7445        } else {
7446            String::new()
7447        }
7448    } else if placed_x == "0"
7449        && placed_y == "0"
7450        && !(matches!(group.kind, "mtr" | "mtd") && (group.x != 0.0 || group.baseline != 0.0))
7451    {
7452        String::new()
7453    } else {
7454        format!("translate({placed_x},{placed_y})")
7455    };
7456    let mut placement = format!("{position}{inherited}{scaling}").trim().to_owned();
7457    if let Some(offset) = fixed_fence_offset.filter(|v| *v != 0.0) {
7458        let own = format!("translate(0 {})", root_number(offset));
7459        placement = if placement.is_empty() {
7460            own
7461        } else {
7462            format!("{placement} {own}")
7463        };
7464    }
7465    if let Some(offset) = group.own_translate {
7466        let own = format!("translate(0 {})", root_number(offset));
7467        placement = if placement.is_empty() {
7468            own
7469        } else {
7470            format!("{placement} {own}")
7471        };
7472    }
7473    if let Some(offset) = group.accent_offset {
7474        let own = format!("translate({} 0)", root_number(offset));
7475        placement = if placement.is_empty() {
7476            own
7477        } else {
7478            format!("{placement} {own}")
7479        };
7480    }
7481    if vcenter {
7482        let delta = (local.ascent + local.depth) / 2. + 250. - local.ascent;
7483        let own = format!("translate(0 {})", root_number(delta));
7484        placement = if placement.is_empty() {
7485            own
7486        } else {
7487            format!("{placement} {own}")
7488        };
7489    }
7490    let transform = if placement.is_empty() {
7491        String::new()
7492    } else {
7493        format!(" transform=\"{}\"", placement)
7494    };
7495    if let Some(href) = &group.reference {
7496        svg.push_str(&format!("<a href=\"{}\">", escape(href)));
7497    }
7498    // amsHandleReference attaches MathJax_ref; SVG addElementClass retains
7499    // the initial space when installing the first class on the wrapper.
7500    let reference_class = if group.reference.is_some() {
7501        " class=\" MathJax_ref\""
7502    } else {
7503        ""
7504    };
7505    if group.kind.is_empty() {
7506        svg.push_str(&format!("<g{}{}>", color, transform));
7507    } else {
7508        let border_style = if bracket {
7509            brackets::border_style(
7510                group.box_border.unwrap() / group.scale,
7511                group.kind == "#bracket-under",
7512            )
7513        } else {
7514            String::new()
7515        };
7516        // standardSVG installs relative scale before color and attributes;
7517        // parent place updates that transform in its original attribute slot.
7518        let table_attr = if group.kind == "#array-menclose-zero" {
7519            " data-padding=\"0\""
7520        } else if group.kind == "#padded-left" {
7521            " data-align=\"left\""
7522        } else if group.kind == "#padded-right" {
7523            " data-align=\"right\""
7524        } else if group.kind == "#padded-center" {
7525            " data-align=\"center\""
7526        } else if group
7527            .percentage
7528            .as_ref()
7529            .is_some_and(|t| t.width_includes_label)
7530        {
7531            " data-width-includes-label=\"true\""
7532        } else {
7533            ""
7534        };
7535        let attrs = if !table_attr.is_empty() && group.scale != 1.0 {
7536            format!("{transform}{color}{table_attr}")
7537        } else if !table_attr.is_empty() {
7538            format!("{color}{table_attr}{transform}")
7539        } else if let Some(cramped) = group.data_cramped {
7540            // standardSVG installs scale before handleAttributes copies the
7541            // explicit data-cramped; a later place() transform follows it.
7542            let cramped = format!(" data-cramped=\"{cramped}\"");
7543            if scaling.is_empty() {
7544                format!("{color}{cramped}{transform}")
7545            } else {
7546                format!("{transform}{color}{cramped}")
7547            }
7548        } else if !scaling.is_empty() {
7549            format!("{border_style}{transform}{color}{reference_class}{tex_class}")
7550        } else {
7551            format!("{reference_class}{color}{border_style}{tex_class}{transform}")
7552        };
7553        svg.push_str(&format!(
7554            "<g data-mml-node=\"{}\"{attrs}>",
7555            if bracket || group.kind.starts_with("#padded-") {
7556                "mpadded"
7557            } else if group.kind == "#array-menclose-zero" {
7558                "menclose"
7559            } else {
7560                group.kind
7561            }
7562        ));
7563    }
7564    if group.reference.is_some() {
7565        svg.push_str(&format!("<rect data-hitbox=\"true\" fill=\"none\" stroke=\"none\" pointer-events=\"all\" width=\"{}\" height=\"{}\" y=\"{}\"></rect>",root_number(local.width),root_number(local.ascent+local.depth),root_number(-local.depth)));
7566    }
7567    if let Some((color, width, ascent, depth)) = &group.background {
7568        svg.push_str(&format!("<rect fill=\"{}\" x=\"0\" y=\"{}\" width=\"{}\" height=\"{}\" data-bgcolor=\"true\"></rect>",
7569            escape(color), root_number(-depth/group.scale), root_number(*width/group.scale), root_number((ascent+depth)/group.scale)));
7570    }
7571    // Render the retained child scope using the same native primitive renderer;
7572    // its outer viewport is omitted because mstyle/menclose are not SVG viewports.
7573    if let Some(delimiter) = group.delimiter {
7574        cd::render_delimiter(svg, delimiter);
7575    }
7576    if bracket {
7577        brackets::render(
7578            svg,
7579            &local,
7580            group.box_border.unwrap() / group.scale,
7581            group.kind == "#bracket-under",
7582        );
7583    }
7584    // Token wrappers own the MathML node. Their children are character
7585    // primitives, as wrapper.textToSVG/placeChar emit directly into that node.
7586    let child_kind =
7587        if group.kind.is_empty() && matches!(parent_kind, "mi" | "mn" | "mo" | "mtext" | "text") {
7588            parent_kind
7589        } else {
7590            group.kind
7591        };
7592    let child = render_layout_in_parent(&local, child_kind);
7593    let marker = "<g data-mml-node=\"math\">";
7594    let start = child.find(marker).expect("native math root") + marker.len();
7595    let end = child.len() - "</g></g></svg>".len();
7596    svg.push_str(&child[start..end]);
7597    for (x1, y1, x2, y2, width) in &group.lines {
7598        svg.push_str(&format!(
7599            "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke-width=\"{}\"></line>",
7600            root_number(*x1 / group.scale),
7601            root_number(*y1 / group.scale),
7602            root_number(*x2 / group.scale),
7603            root_number(*y2 / group.scale),
7604            root_number(*width / group.scale)
7605        ));
7606    }
7607    if let Some(t) = group.box_border.filter(|_| !bracket) {
7608        let t = t / group.scale;
7609        svg.push_str(&format!("<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke-width=\"{}\"></rect>",root_number(t/2.0),root_number(t/2.0-local.depth),root_number(local.width-t),root_number(local.ascent+local.depth-t),root_number(t)));
7610    }
7611    if let Some(arrow) = group.arrow {
7612        enclose::render_arrow(svg, arrow);
7613    }
7614    svg.push_str("</g>");
7615    if group.reference.is_some() {
7616        svg.push_str("</a>");
7617    }
7618}
7619
7620fn render_layout(layout: &Layout) -> String {
7621    render_layout_in_parent(layout, "math")
7622}
7623
7624fn render_layout_in_parent(layout: &Layout, parent_kind: &str) -> String {
7625    let character_parent = matches!(parent_kind, "mi" | "mn" | "mo" | "mtext" | "text");
7626    // Original wrapper.computeChildrenBBox uses BBox.Append: signed logical
7627    // advances determine width, including negative kerns and deferred paint.
7628    let width = layout.width;
7629    let ascent = layout.ascent;
7630    let depth = layout.depth;
7631    // Preserve the emitted intrinsic coordinate system independently of measurement.
7632    // Original Typesetter.Typeset clamps only the final viewport to
7633    // options.Em/1000 em (default Em=16), preserving the logical baseline.
7634    let (ascent_em, depth_em) = if styles::has_em_bounds(layout) {
7635        styles::viewport_bounds(layout)
7636    } else {
7637        (ascent / 1000., depth / 1000.)
7638    };
7639    let (view_width, view_height, x_scale, y_scale) = (
7640        width.max(16.0),
7641        ((ascent_em + depth_em).max(0.016)) * 1000.0,
7642        1.0,
7643        1.0,
7644    );
7645    // MathJax serializes its TeX em units using a 442-unit ex conversion.
7646    let width_ex = view_width / 442.0;
7647    let height_ex = (ascent_em + depth_em).max(0.016) / 0.442;
7648    // svg/typesetter.go serializes the retained em BBox in SVG units once.
7649    // Reusing paint-frame bounds can round declaration scales a second time.
7650    let scaled_depth = depth_em * 1000.;
7651    let scaled_ascent = ascent_em * 1000.;
7652    let mut svg = format!(
7653        "<svg style=\"vertical-align: {};\" xmlns=\"http://www.w3.org/2000/svg\" width=\"{}ex\" height=\"{}ex\" role=\"img\" focusable=\"false\" viewBox=\"0 {} {} {}\"><g stroke=\"currentColor\" fill=\"currentColor\" stroke-width=\"0\" transform=\"scale(1,-1)\"><g data-mml-node=\"math\">",
7654        if scaled_depth == 0.0 {
7655            "0".to_owned()
7656        } else {
7657            format!("{}ex", number(-scaled_depth / 442.0))
7658        },
7659        number(width_ex),
7660        number(height_ex),
7661        root_number(-scaled_ascent),
7662        root_number(view_width),
7663        root_number(view_height)
7664    );
7665    if ams::responsive(layout) {
7666        svg = format!(
7667            "<svg style=\"vertical-align: {}; min-width: {}ex;\" xmlns=\"http://www.w3.org/2000/svg\" width=\"100%\" height=\"{}ex\" role=\"img\" focusable=\"false\"><g stroke=\"currentColor\" fill=\"currentColor\" stroke-width=\"0\" transform=\"scale(0.0181,-0.0181) translate(0, {})\"><g data-mml-node=\"math\">",
7668            if depth == 0.0 {
7669                "0".into()
7670            } else {
7671                format!("{}ex", number(-depth / 442.0))
7672            },
7673            number(math_minwidth::minimum(layout).unwrap_or(view_width) / 442.0),
7674            number(height_ex),
7675            root_number(-ascent)
7676        );
7677    }
7678    if x_scale != 1.0 || y_scale != 1.0 {
7679        svg.push_str(&format!(
7680            "<g transform=\"scale({} {})\">",
7681            number(x_scale),
7682            number(y_scale)
7683        ));
7684    }
7685    let inferred: Vec<_> = layout
7686        .groups
7687        .iter()
7688        .filter(|g| g.kind == "#inferred-place")
7689        .collect();
7690    for group in inferred.iter().rev() {
7691        svg.push_str(&format!(
7692            "<g transform=\"translate({},{})\">",
7693            root_number(group.x),
7694            root_number(group.baseline)
7695        ));
7696    }
7697    {
7698        let mut glyph_index = 0;
7699        while glyph_index < layout.glyphs.len() {
7700            for group in layout
7701                .groups
7702                .iter()
7703                .filter(|g| g.before_glyph == glyph_index)
7704            {
7705                render_layout_group(&mut svg, group, parent_kind);
7706            }
7707            let item = layout.glyphs[glyph_index];
7708            if let Some((total, depth)) = item.assembly_height {
7709                render_radical_assembly(&mut svg, item, total, depth);
7710                glyph_index += 1;
7711                continue;
7712            }
7713            // Script elements are emitted by their owning LayoutGroup. Glyph
7714            // coordinates alone do not introduce a second MathML script node.
7715            let item = layout.glyphs[glyph_index];
7716            let Some(glyph) = glyph_for(item) else {
7717                glyph_index += 1;
7718                continue;
7719            };
7720            let path = if glyph.path.is_empty() {
7721                String::new()
7722            } else {
7723                format!("M{}Z", glyph.path)
7724            };
7725            let node = mathml_node_kind(item.codepoint);
7726            // Original svg/mo.go moToSVG: a symmetric/largeop mo installs its
7727            // own "translate(0 u)" (u = centerOffset of its children bbox,
7728            // replacing standardSVG's scale), and wrapper.place prepends the
7729            // parent placement, which excludes u.
7730            let axis_u = if (item.large || item.small_operator) && !character_parent {
7731                Some((glyph.height + glyph.depth) / 2.0 + 0.25 - glyph.height).filter(|u| *u != 0.0)
7732            } else {
7733                None
7734            };
7735            let placed_baseline = item.baseline - axis_u.map_or(0.0, |u| u * 1000.0 * item.scale);
7736            let (placed_x, placed_y) = (root_number(item.x), root_number(placed_baseline));
7737            let position = if placed_x == "0" && placed_y == "0" {
7738                String::new()
7739            } else {
7740                format!("translate({placed_x},{placed_y})")
7741            };
7742            // standardSVG emits scale only for RScale != 1; source script
7743            // scales are exact powers clamped to 8px, so a ratio that
7744            // serializes as 1 is the source's exact 1.
7745            let own_scale = if let Some(u) = axis_u {
7746                format!("translate(0 {})", root_number(u * 1000.0))
7747            } else if item.scale == 1.0 || number(item.scale) == "1" {
7748                String::new()
7749            } else {
7750                format!("scale({})", number(item.scale))
7751            };
7752            let transform = format!("{position} {own_scale}").trim().to_owned();
7753            let transform_attribute = if transform.is_empty() {
7754                String::new()
7755            } else {
7756                format!(" transform=\"{transform}\"")
7757            };
7758            // Known spacing glyphs also have no path. They remain blank;
7759            // only failed font lookup uses the unknown-text fallback.
7760            let text_fallback = if item.calligraphic {
7761                calligraphic_glyphs::CALLIGRAPHIC_GLYPHS
7762                    .binary_search_by_key(&item.codepoint, |g| g.codepoint)
7763                    .is_err()
7764                    && italic_glyphs::ITALIC_GLYPHS
7765                        .binary_search_by_key(&item.codepoint, |g| g.codepoint)
7766                        .is_err()
7767                    && uses_normal_text_fallback(italic_font_code(item.codepoint))
7768            } else if item.italic {
7769                italic_glyphs::ITALIC_GLYPHS
7770                    .binary_search_by_key(&item.codepoint, |g| g.codepoint)
7771                    .is_err()
7772                    && uses_normal_text_fallback(italic_font_code(item.codepoint))
7773            } else {
7774                uses_normal_text_fallback(item.codepoint)
7775            };
7776            // A Unit is an explicit node, not a character child of a token.
7777            let character_child = character_parent && !item.unit;
7778            let content = if declaration_fonts::content(item.codepoint, item.font_variant).is_some()
7779                || compound(item.codepoint).is_some()
7780                || item.bold && double_struck::bold(item.codepoint).is_some_and(|r| !r.2.is_empty())
7781            {
7782                render_compound_character(
7783                    item,
7784                    item.codepoint,
7785                    if character_child {
7786                        item.x / 1000.0
7787                    } else {
7788                        0.0
7789                    },
7790                    if character_child {
7791                        item.baseline / 1000.0
7792                    } else {
7793                        0.0
7794                    },
7795                )
7796            } else if glyph.path.is_empty() && text_fallback {
7797                let text_transform = if character_child && !transform_attribute.is_empty() {
7798                    format!("{transform} scale(1,-1)")
7799                } else {
7800                    "scale(1,-1)".into()
7801                };
7802                let code = painted_code(item);
7803                let encoded_style = (0x1D400..=0x1D7FF).contains(&code);
7804                format!(
7805                    "<text data-variant=\"{}\" transform=\"{text_transform}\" font-size=\"884px\"{}{}>{}</text>",
7806                    if item.large {
7807                        "-largeop"
7808                    } else if item.small_operator {
7809                        "-smallop"
7810                    } else if item.calligraphic {
7811                        "-tex-calligraphic"
7812                    } else if item.italic {
7813                        "italic"
7814                    } else if item.font_original.is_some() {
7815                        item.font_variant
7816                    } else {
7817                        "normal"
7818                    },
7819                    if encoded_style {
7820                        String::new()
7821                    } else {
7822                        format!(
7823                            " font-family=\"{}\"",
7824                            if matches!(item.font_variant, "monospace" | "sans-serif") {
7825                                item.font_variant
7826                            } else if matches!(
7827                                item.font_variant,
7828                                "bold-sans-serif" | "sans-serif-italic" | "sans-serif-bold-italic"
7829                            ) {
7830                                "sans-serif"
7831                            } else if item.calligraphic
7832                                || matches!(
7833                                    item.font_variant,
7834                                    "script" | "bold-script" | "-tex-bold-calligraphic"
7835                                )
7836                            {
7837                                "cursive"
7838                            } else {
7839                                "serif"
7840                            }
7841                        )
7842                    },
7843                    if encoded_style {
7844                        ""
7845                    } else {
7846                        match (
7847                            item.italic
7848                                || item.calligraphic
7849                                || matches!(
7850                                    item.font_variant,
7851                                    "bold-italic"
7852                                        | "-tex-mathit"
7853                                        | "sans-serif-italic"
7854                                        | "sans-serif-bold-italic"
7855                                        | "-tex-bold-calligraphic"
7856                                ),
7857                            item.font_original.is_some()
7858                                && matches!(
7859                                    item.font_variant,
7860                                    "bold"
7861                                        | "bold-italic"
7862                                        | "double-struck"
7863                                        | "bold-fraktur"
7864                                        | "bold-script"
7865                                        | "bold-sans-serif"
7866                                        | "sans-serif-bold-italic"
7867                                        | "-tex-bold-calligraphic"
7868                                ),
7869                        ) {
7870                            (true, true) => " font-style=\"italic\" font-weight=\"bold\"",
7871                            (true, false) => " font-style=\"italic\"",
7872                            (false, true) => " font-weight=\"bold\"",
7873                            _ => "",
7874                        }
7875                    },
7876                    escape_text(&char::from_u32(code).unwrap().to_string())
7877                )
7878            } else {
7879                let code = painted_code(item);
7880                format!(
7881                    "<path data-c=\"{:X}\" d=\"{}\"{}></path>",
7882                    code,
7883                    path,
7884                    if character_child {
7885                        transform_attribute.as_str()
7886                    } else {
7887                        ""
7888                    }
7889                )
7890            };
7891            if character_child {
7892                svg.push_str(&content);
7893            } else {
7894                svg.push_str(&format!(
7895                    "<g data-mml-node=\"{}\"{}{}>{}</g>",
7896                    node,
7897                    if item.unit {
7898                        " class=\" MathML-Unit\""
7899                    } else {
7900                        ""
7901                    },
7902                    transform_attribute,
7903                    content
7904                ));
7905            }
7906            glyph_index += 1;
7907        }
7908    }
7909    for group in layout
7910        .groups
7911        .iter()
7912        .filter(|g| g.before_glyph == layout.glyphs.len())
7913    {
7914        render_layout_group(&mut svg, group, parent_kind);
7915    }
7916    for (x, y, rule_width, rule_height) in &layout.rules {
7917        svg.push_str(&format!(
7918            "<rect width=\"{}\" height=\"{}\" x=\"{}\" y=\"{}\"></rect>",
7919            root_number(*rule_width),
7920            root_number(*rule_height),
7921            root_number(*x),
7922            root_number(*y)
7923        ));
7924    }
7925    for _ in &inferred {
7926        svg.push_str("</g>");
7927    }
7928    if x_scale != 1.0 || y_scale != 1.0 {
7929        svg.push_str("</g>");
7930    }
7931    svg.push_str("</g></g></svg>");
7932    svg
7933}
7934
7935fn mathml_node_kind(codepoint: u32) -> &'static str {
7936    if (b'0' as u32..=b'9' as u32).contains(&codepoint) {
7937        "mn"
7938    } else if matches!(codepoint,0x2190..=0x2195|0x21A9|0x21AA|0x21CC|0x21D0..=0x21D5|0x27F5..=0x27FA|0x27FC)
7939        || [
7940            '+' as u32, '-' as u32, '=' as u32, '<' as u32, '>' as u32, '|' as u32, '(' as u32,
7941            ')' as u32, 0x27E8, 0x27E9, 0x2223, 0x2212, 0x221A, 0x220F, 0x2211, 0x222B,
7942            // Remaining command_codepoint targets registered by the original
7943            // base mathchar0mo map (tex/source_tables_base_maps.go), whose
7944            // ParseMethods.mathchar0mo creates an mo token.
7945            0xB1, 0xD7, 0x2297, 0x22C5, 0x2264, 0x2265, 0x2260, 0x2261, 0x2218, 0x2248, 0x223C,
7946            0x2208, 0x2209, 0x2026, 0x22EF,
7947        ]
7948        .contains(&codepoint)
7949        || is_large_operator(codepoint)
7950    {
7951        "mo"
7952    } else {
7953        "mi"
7954    }
7955}
7956
7957fn validate(expression: &str) -> Result<(), MathError> {
7958    if expression.trim().is_empty() {
7959        return Err(MathError::Empty);
7960    }
7961    let mut stack = Vec::new();
7962    let mut escaped = false;
7963    for (byte, rune) in expression.char_indices() {
7964        if escaped {
7965            escaped = false;
7966            continue;
7967        }
7968        match rune {
7969            '\\' => escaped = true,
7970            '{' => stack.push(byte),
7971            '}' if stack.pop().is_none() => {
7972                return Err(MathError::Unbalanced {
7973                    delimiter: '}',
7974                    byte,
7975                });
7976            }
7977            _ => {}
7978        }
7979    }
7980    if let Some(byte) = stack.pop() {
7981        return Err(MathError::Unbalanced {
7982            delimiter: '{',
7983            byte,
7984        });
7985    }
7986    Ok(())
7987}
7988
7989// Original svg/dom.go uses distinct character-data and attribute escaping.
7990fn escape_text(value: &str) -> String {
7991    value
7992        .replace('&', "&amp;")
7993        .replace('<', "&lt;")
7994        .replace('>', "&gt;")
7995}
7996
7997fn escape(value: &str) -> String {
7998    escape_text(value).replace('"', "&quot;")
7999}
8000
8001// Original root viewBox uses CommonOutputJax.fixed with one decimal.
8002fn root_number(value: f64) -> String {
8003    // jscompat.ToFixed rounds the exact binary number, resolving ties upward.
8004    if value.abs() < 0.0006 {
8005        return "0".to_owned();
8006    }
8007    let magnitude = value.abs();
8008    let bits = magnitude.to_bits();
8009    let exponent = ((bits >> 52) & 0x7ff) as i32 - 1023 - 52;
8010    let mantissa = ((bits & ((1_u64 << 52) - 1)) | (1_u64 << 52)) as u128;
8011    let numerator = mantissa * 10;
8012    let rounded = if exponent >= 0 {
8013        numerator.checked_shl(exponent as u32)
8014    } else {
8015        let shift = (-exponent) as u32;
8016        if shift >= 128 {
8017            Some(0)
8018        } else {
8019            let quotient = numerator >> shift;
8020            let remainder = numerator & ((1_u128 << shift) - 1);
8021            Some(quotient + u128::from(remainder >= 1_u128 << (shift - 1)))
8022        }
8023    };
8024    let Some(rounded) = rounded else {
8025        return format!("{value:.1}");
8026    };
8027    let sign = if value < 0.0 { "-" } else { "" };
8028    if rounded % 10 == 0 {
8029        format!("{sign}{}", rounded / 10)
8030    } else {
8031        format!("{sign}{}.{}", rounded / 10, rounded % 10)
8032    }
8033}
8034
8035fn number(value: f64) -> String {
8036    let mut output = format!("{value:.3}");
8037    while output.ends_with('0') {
8038        output.pop();
8039    }
8040    if output.ends_with('.') {
8041        output.pop();
8042    }
8043    output
8044}
8045
8046#[cfg(test)]
8047mod tests {
8048    use super::{measure, render};
8049    use d2_rs_core::Size;
8050
8051    #[test]
8052    fn environment_argument_errors_render_before_structural_fallback() {
8053        // Pinned mathjax-go tex/environment_count.go readEnvironmentName and
8054        // environment_end.go endEnvironment: argument errors are MathJax
8055        // error nodes, as are orphan ends on this parser's input.
8056        for (expression, message) in [
8057            (r"\end{", "Missing close brace"),
8058            (r"\begin{", "Missing close brace"),
8059            (r"\end", r"Missing argument for \end"),
8060            (r"\begin", r"Missing argument for \begin"),
8061            (r"\end}", "Extra close brace or missing open brace"),
8062            (r"\end{\foo}", r"Invalid environment name '\foo'"),
8063            (r"\end\foo ", r"Invalid environment name '\foo'"),
8064            ("\\end\\\n", r"Invalid environment name '\ '"),
8065            ("\\end\u{feff}{", "Missing close brace"),
8066            ("\\end\u{85}{", "Unknown environment '\u{85}'"),
8067            (r"\end{missing}", "Unknown environment 'missing'"),
8068            (
8069                r"\end{matrix}",
8070                r"Missing \begin{matrix} or extra \end{matrix}",
8071            ),
8072            (r"\end{spreadlines}", r"Extra \end{spreadlines}"),
8073        ] {
8074            assert_eq!(
8075                super::render_exact(expression).unwrap(),
8076                super::cd::render_error(message),
8077                "{expression}"
8078            );
8079            assert_eq!(
8080                render(expression).unwrap(),
8081                super::cd::render_error(message),
8082                "{expression}"
8083            );
8084            assert!(super::measure(expression).is_ok(), "{expression}");
8085        }
8086    }
8087
8088    #[test]
8089    fn linebreak_mspace_keeps_operator_spacing_on_the_following_token() {
8090        // Pinned mathjax-go 94d80186bfd7 svg/texclass.go setTeXClass returns
8091        // the previous node for mspace; wrapper.go addChildren places the
8092        // zero-width break before the following token's leading space.
8093        // These transforms are captured from the pinned Go D2 SVG renderer.
8094        for (expression, spaces, last_identifier) in [
8095            (r"= \\ b", vec!["translate(778,0)"], "translate(1055.8,0)"),
8096            (
8097                r"a = \\ b",
8098                vec!["translate(1584.8,0)"],
8099                "translate(1862.6,0)",
8100            ),
8101            (
8102                r"a + \\ b",
8103                vec!["translate(1529.2,0)"],
8104                "translate(1751.4,0)",
8105            ),
8106            (
8107                r"a < \\ b",
8108                vec!["translate(1584.8,0)"],
8109                "translate(1862.6,0)",
8110            ),
8111            (
8112                r"a = \\b",
8113                vec!["translate(1584.8,0)"],
8114                "translate(1862.6,0)",
8115            ),
8116            (r"a, \\ b", vec!["translate(807,0)"], "translate(973.7,0)"),
8117            (r"a; \\ b", vec!["translate(807,0)"], "translate(973.7,0)"),
8118            (
8119                r"a = \newline b",
8120                vec!["translate(1584.8,0)"],
8121                "translate(1862.6,0)",
8122            ),
8123            (
8124                r"a = \\[2pt] b",
8125                vec!["translate(1584.8,0)", "translate(1584.8,0)"],
8126                "translate(1862.6,0)",
8127            ),
8128            (r"a \\ b", vec!["translate(529,0)"], "translate(529,0)"),
8129        ] {
8130            let svg = super::render_exact(expression).unwrap();
8131            let document = roxmltree::Document::parse(&svg).unwrap();
8132            let actual = document
8133                .descendants()
8134                .filter(|node| node.attribute("data-mml-node") == Some("mspace"))
8135                .map(|node| node.attribute("transform").unwrap_or(""))
8136                .collect::<Vec<_>>();
8137            assert_eq!(actual, spaces, "break placement for {expression:?}");
8138            let identifier = document
8139                .descendants()
8140                .rfind(|node| node.attribute("data-mml-node") == Some("mi"))
8141                .unwrap();
8142            assert_eq!(
8143                identifier.attribute("transform"),
8144                Some(last_identifier),
8145                "following token placement for {expression:?}"
8146            );
8147        }
8148        let svg = super::render_exact(r"a + \\").unwrap();
8149        let document = roxmltree::Document::parse(&svg).unwrap();
8150        let spacer = document
8151            .descendants()
8152            .find(|node| node.attribute("data-mml-node") == Some("mspace"))
8153            .unwrap();
8154        assert_eq!(spacer.attribute("transform"), Some("translate(1529.2,0)"));
8155
8156        // Pinned svg/wrapper.go addChildren accumulates em advances before
8157        // place converts to SVG units. A size declaration closed by a break
8158        // must preserve that order in fenced rows.
8159        for (expression, kind, placement) in [
8160            (r"\left(\small a \\ b \right)", "mo", "translate(1267.6,0)"),
8161            (
8162                r"\left(\small a \newline b \right)",
8163                "mo",
8164                "translate(1267.6,0)",
8165            ),
8166            // texclass.go setRowTeXClass returns the prepared trailing BIN
8167            // (demoted by isLastTeXAtom) through the closed declaration.
8168            (r"\left(\small a + \\ b\right)", "mi", "translate(1499.9,0)"),
8169            (
8170                r"\left(\scriptstyle a + \\ b\right)",
8171                "mi",
8172                "translate(1313.2,0)",
8173            ),
8174            (
8175                r"\left(\scriptscriptstyle a + \\ b\right)",
8176                "mi",
8177                "translate(1042.5,0)",
8178            ),
8179            (
8180                r"\left(\displaystyle a + \\ b\right)",
8181                "mi",
8182                "translate(1696,0)",
8183            ),
8184        ] {
8185            let svg = super::render_exact(expression).unwrap();
8186            let document = roxmltree::Document::parse(&svg).unwrap();
8187            let last = document
8188                .descendants()
8189                .rfind(|node| node.attribute("data-mml-node") == Some(kind))
8190                .unwrap();
8191            assert_eq!(last.attribute("transform"), Some(placement), "{expression}");
8192        }
8193
8194        // parser.go pendingCell closes StyleItems before an open owner emits
8195        // spaces. The lexical environment survives, but mstyle does not.
8196        // wrapper.go addChildren retains local em positions inside scripts;
8197        // scaling and then dividing 449.65 changes fixed()'s rounding tie.
8198        for expression in [r"x^{\small a \\ b}", r"x^{\small a \newline b}"] {
8199            let svg = super::render_exact(expression).unwrap();
8200            let document = roxmltree::Document::parse(&svg).unwrap();
8201            let spacer = document
8202                .descendants()
8203                .find(|node| node.attribute("data-mml-node") == Some("mspace"))
8204                .unwrap();
8205            assert_eq!(
8206                spacer.attribute("transform"),
8207                Some("translate(449.6,0)"),
8208                "{expression}"
8209            );
8210            let identifier = document
8211                .descendants()
8212                .rfind(|node| node.attribute("data-mml-node") == Some("mi"))
8213                .unwrap();
8214            assert_eq!(
8215                identifier.attribute("transform"),
8216                Some("translate(449.6,0)"),
8217                "{expression}"
8218            );
8219        }
8220        for (expression, spacer_x, token_x) in [
8221            (r"\displaystyle a = \\ b", "1584.8", "1862.6"),
8222            (r"\scriptstyle a = \\ b", "924.2", "924.2"),
8223            (r"\displaystyle a \\ b", "529", "529"),
8224            (r"\scriptstyle a \\ b", "374.1", "374.1"),
8225        ] {
8226            let svg = super::render_exact(expression).unwrap();
8227            let document = roxmltree::Document::parse(&svg).unwrap();
8228            let math = document
8229                .descendants()
8230                .find(|node| node.attribute("data-mml-node") == Some("math"))
8231                .unwrap();
8232            let children: Vec<_> = math.children().filter(|node| node.is_element()).collect();
8233            assert_eq!(
8234                children
8235                    .iter()
8236                    .map(|node| node.attribute("data-mml-node").unwrap())
8237                    .collect::<Vec<_>>(),
8238                ["mstyle", "mspace", "mi"],
8239                "style closure for {expression:?}"
8240            );
8241            assert_eq!(
8242                children[1].attribute("transform").unwrap(),
8243                format!("translate({spacer_x},0)")
8244            );
8245            assert_eq!(
8246                children[2].attribute("transform").unwrap(),
8247                format!("translate({token_x},0)")
8248            );
8249        }
8250        // wrapper.go getScale and BBox.Append scale the intrinsic em width.
8251        // Reconstructing it from paint units changes mfrac.go alignX's tie.
8252        for expression in [
8253            r"\frac{\scriptscriptstyle a + \\ b}{c}",
8254            r"\frac{\scriptscriptstyle a + \newline b}{c}",
8255        ] {
8256            let svg = super::render_exact(expression).unwrap();
8257            let document = roxmltree::Document::parse(&svg).unwrap();
8258            let denominator = document
8259                .descendants()
8260                .find(|node| node.attribute("data-mml-node") == Some("mfrac"))
8261                .unwrap()
8262                .children()
8263                .filter(|node| node.is_element())
8264                .nth(1)
8265                .unwrap();
8266            assert_eq!(
8267                denominator.attribute("transform"),
8268                Some("translate(544.7,-686)"),
8269                "{expression}"
8270            );
8271        }
8272        let svg = super::render_exact(r"a + \color{red}").unwrap();
8273        let document = roxmltree::Document::parse(&svg).unwrap();
8274        let operator = document
8275            .descendants()
8276            .find(|node| node.attribute("data-mml-node") == Some("mo"))
8277            .unwrap();
8278        assert_eq!(operator.attribute("transform"), Some("translate(751.2,0)"));
8279
8280        // svg/texclass.go setPreviousClass reads the node returned from a
8281        // transparent wrapper. A raised style returns its final script-level
8282        // token, so the following identifier retains that level for spacing.
8283        // adjustTeXClass on a following mo instead uses its own inherited
8284        // level. Keep the operator controls at their Go positions as well.
8285        for position in [r"\raise1em", r"\lower1em"] {
8286            for (style, identifier_x, plus_x, after_operator_x) in [
8287                (r"\scriptstyle", "924.2", "1202", "1980"),
8288                (r"\scriptscriptstyle", "653.5", "931.3", "1709.3"),
8289                (r"\displaystyle", "1862.6", "1862.6", "2640.6"),
8290            ] {
8291                for (tail, token_x) in [
8292                    ("b", identifier_x),
8293                    ("+ b", after_operator_x),
8294                    ("= b", after_operator_x),
8295                ] {
8296                    let expression = format!(r"{position}{style} a = \\ {tail}");
8297                    let svg = super::render_exact(&expression).unwrap();
8298                    let document = roxmltree::Document::parse(&svg).unwrap();
8299                    let identifier = document
8300                        .descendants()
8301                        .rfind(|node| node.attribute("data-mml-node") == Some("mi"))
8302                        .unwrap();
8303                    assert_eq!(
8304                        identifier.attribute("transform").unwrap(),
8305                        format!("translate({token_x},0)"),
8306                        "{expression}"
8307                    );
8308                    if tail == "+ b" {
8309                        let operator = document
8310                            .descendants()
8311                            .rfind(|node| node.attribute("data-mml-node") == Some("mo"))
8312                            .unwrap();
8313                        assert_eq!(
8314                            operator.attribute("transform").unwrap(),
8315                            format!("translate({plus_x},0)"),
8316                            "{expression}"
8317                        );
8318                    }
8319                }
8320            }
8321        }
8322
8323        // tex/parser.go captures the RightItem's lexical color before
8324        // Style/Over/Cell continuations restore the enclosing environment.
8325        for expression in [
8326            r"\left(\color{red}x\right)",
8327            r"\left(\color{red}x\right.",
8328            r"\left(\color{red}x\over y\right)",
8329            r"\left(\color{red} a \over b \\ c\right)",
8330        ] {
8331            let svg = super::render_exact(expression).unwrap();
8332            let document = roxmltree::Document::parse(&svg).unwrap();
8333            let close = document
8334                .descendants()
8335                .rfind(|node| node.attribute("data-mml-node") == Some("mo"))
8336                .unwrap();
8337            assert_eq!(close.attribute("fill"), Some("red"), "{expression}");
8338            assert_eq!(close.attribute("stroke"), Some("red"), "{expression}");
8339        }
8340        // LeftItem retains the middle's prefix, empty CLOSE/OPEN atoms and
8341        // lexical color. cleanMathMLAttributes removes inherited duplicates.
8342        for (expression, colors, middles) in [
8343            (
8344                r"\left(\color{red}x\middle|y\right)",
8345                vec![None, Some("red"), None],
8346                1,
8347            ),
8348            (
8349                r"\left(\color{red}\bf x\middle|y\over z\right)",
8350                vec![None, Some("red"), None],
8351                1,
8352            ),
8353            (
8354                r"\color{green}\left(\color{red}x\middle|y\right)+z",
8355                vec![None, Some("red"), None, None],
8356                1,
8357            ),
8358            (
8359                r"\left(\color{red}\left[x\right]\right)",
8360                vec![None, None, None, Some("red")],
8361                0,
8362            ),
8363        ] {
8364            let svg = super::render_exact(expression).unwrap();
8365            let document = roxmltree::Document::parse(&svg).unwrap();
8366            assert_eq!(
8367                document
8368                    .descendants()
8369                    .filter(|node| node.attribute("data-mml-node") == Some("mo"))
8370                    .map(|node| node.attribute("fill"))
8371                    .collect::<Vec<_>>(),
8372                colors,
8373                "{expression}",
8374            );
8375            for class in ["OPEN", "CLOSE"] {
8376                assert_eq!(
8377                    document
8378                        .descendants()
8379                        .filter(|node| node.attribute("data-mjx-texclass") == Some(class))
8380                        .count(),
8381                    middles,
8382                    "{class} in {expression}",
8383                );
8384            }
8385        }
8386
8387        // svg/wrapper.go:112 and mo.go:351 stretch delimiters in every row,
8388        // including rows captured by OverItems. These pinned Go viewBoxes
8389        // cover local fraction siblings, styles, colors and an empty middle.
8390        for (expression, view_box) in [
8391            (
8392                r"\left(\color{red}x\over y\middle|z\over w\right)",
8393                "0 -1939.9 3832.5 3379.8",
8394            ),
8395            (
8396                r"\left(x\over y\middle|\frac{z}{w}\right)",
8397                "0 -1449.5 3973 2399",
8398            ),
8399            (
8400                r"\left(\frac{x}{y}\middle|z\over w\right)",
8401                "0 -1939.9 3832.5 3379.8",
8402            ),
8403            (
8404                r"\scriptstyle\left(x\over y\middle|z\over w\right)",
8405                "0 -1040.4 2257 1711.8",
8406            ),
8407            (
8408                r"\left(x\over \frac{y}{z}\middle\Vert w\right)",
8409                "0 -1749.5 4082.5 2999",
8410            ),
8411            (
8412                r"\left(x\over y\middle[\frac{z}{w}\right)",
8413                "0 -1449.5 4168 2399",
8414            ),
8415            (
8416                r"\left(x\over y\middle.\frac{z}{w}\right)",
8417                "0 -1449.5 3640 2399",
8418            ),
8419            (r"\left(x\middle|y\right)", "0 -750 2118 1000"),
8420            (r"\left(x\middle\Vert y\right)", "0 -750 2618 1000"),
8421            (
8422                r"\scriptstyle\left(x\middle\Vert y\right)",
8423                "0 -530.3 1851.2 707.1",
8424            ),
8425            (
8426                r"\color{red}\left(x\middle\Vert y\right)",
8427                "0 -750 2618 1000",
8428            ),
8429        ] {
8430            let svg = super::render_exact(expression).unwrap();
8431            let document = roxmltree::Document::parse(&svg).unwrap();
8432            assert_eq!(
8433                document.root_element().attribute("viewBox"),
8434                Some(view_box),
8435                "middle stretching for {expression}",
8436            );
8437        }
8438        // tex/left_right.go leaves the middle's class and symmetry to the
8439        // dictionary. mo.go stretchBaseline retains the requested H/D for
8440        // asymmetric assembly instead of centering it on the math axis.
8441        for (expression, placement, extent) in [
8442            (
8443                r"\left(x\middle\Vert\frac{y}{z}\over w\right)",
8444                "translate(572,0)",
8445                Some("1150.3"),
8446            ),
8447            (
8448                r"\scriptstyle \left(x\middle\Vert\frac{y}{z}\over w\right)",
8449                "translate(572,0)",
8450                Some("1343"),
8451            ),
8452            (
8453                r"\left(x\over y\middle\Vert\frac{z}{w}\right)",
8454                "translate(1748,0)",
8455                Some("2009"),
8456            ),
8457            (r"\left(\middle\Vert\right)", "translate(389,0)", None),
8458            (
8459                r"\left(x\middle\uparrow\frac{y}{z}\over w\right)",
8460                "translate(849.8,0)",
8461                Some("363.3"),
8462            ),
8463            (r"\left(\middle\uparrow\right)", "translate(666.8,0)", None),
8464        ] {
8465            let svg = super::render_exact(expression).unwrap();
8466            let document = roxmltree::Document::parse(&svg).unwrap();
8467            let middle = document
8468                .descendants()
8469                .filter(|node| node.attribute("data-mml-node") == Some("mo"))
8470                .nth(1)
8471                .unwrap();
8472            assert_eq!(
8473                middle.attribute("transform"),
8474                Some(placement),
8475                "{expression}"
8476            );
8477            assert_eq!(
8478                middle
8479                    .children()
8480                    .find(|node| node.has_tag_name("svg"))
8481                    .and_then(|node| node.attribute("height")),
8482                extent,
8483                "{expression}",
8484            );
8485        }
8486    }
8487
8488    #[test]
8489    fn measures_scripts_deterministically() {
8490        let base = measure("a+b").unwrap();
8491        let scripted = measure("a^2+b_1").unwrap();
8492        assert!(scripted.height > base.height);
8493        assert_eq!(measure("a^2+b_1"), Ok(scripted));
8494    }
8495
8496    #[test]
8497    fn source_metacharacter_errors_and_fraction_validation() {
8498        assert!(measure(r#"\frac{1}{2}"#).unwrap().width > 0.0);
8499        let svg = render(r#"x < y & z"#).unwrap();
8500        assert!(svg.contains("data-mjx-error=\"Misplaced &amp;\""));
8501        assert_eq!(
8502            measure(r#"\frac{1}{"#),
8503            Ok(Size {
8504                width: 207.0,
8505                height: 18.0
8506            })
8507        );
8508    }
8509
8510    #[test]
8511    fn original_empty_expressions_keep_the_clamped_em_viewport() {
8512        // Actual original Go Render/Measure controls: empty and whitespace
8513        // have the same positive 16-unit viewport and one-pixel measure.
8514        for expression in ["", "  ", "\t", "\n"] {
8515            assert_eq!(
8516                measure(expression),
8517                Ok(Size {
8518                    width: 1.0,
8519                    height: 1.0
8520                })
8521            );
8522        }
8523    }
8524
8525    #[test]
8526    fn renders_original_recoverable_fraction_argument_error() {
8527        // Actual Go v0.9.0 renders this parser diagnostic as merror.
8528        assert!(
8529            render(r"\frac{")
8530                .unwrap()
8531                .contains("data-mjx-error=\"Missing close brace\"")
8532        );
8533        let size = measure(r"\frac{").unwrap();
8534        assert_eq!((size.width, size.height), (207.0, 18.0));
8535    }
8536
8537    #[test]
8538    fn renders_source_derived_glyphs_for_common_tex_constructs() {
8539        let fraction = render(r#"\frac{1}{2}"#).unwrap();
8540        assert!(fraction.contains("data-c=\"31\""));
8541        assert!(fraction.contains("data-c=\"32\""));
8542        assert!(fraction.contains("<rect "));
8543
8544        let radical = render(r#"\sqrt{x+1}"#).unwrap();
8545        assert!(radical.contains("data-c=\"221A\""));
8546        assert!(radical.contains("data-c=\"1D465\""));
8547
8548        let greek = render(r#"\alpha+\Omega"#).unwrap();
8549        assert!(greek.contains("data-c=\"1D6FC\""));
8550        assert!(greek.contains("data-c=\"3A9\""));
8551
8552        let matrix = render(r#"\begin{pmatrix}a&b\\c&d\end{pmatrix}"#).unwrap();
8553        assert!(matrix.contains("data-c=\"28\""));
8554        assert!(matrix.contains("data-c=\"29\""));
8555        assert!(matrix.contains("data-c=\"1D44E\""));
8556
8557        let aligned = render(r#"\begin{aligned}a&=b+c\\d&=e\end{aligned}"#).unwrap();
8558        assert!(aligned.contains("data-c=\"3D\""));
8559        assert!(aligned.contains("data-c=\"1D44E\""));
8560    }
8561
8562    #[test]
8563    fn matches_frozen_v090_mathjax_dimensions() {
8564        let cases = [
8565            (r#"a + b = c"#, (72.0, 15.0)),
8566            (r#"\frac{1}{2}"#, (18.0, 37.0)),
8567            (r#"x_i^2+\sum_{n=0}^{\infty}n^{-2}"#, (99.0, 51.0)),
8568            (
8569                r#"\left\langle \frac{x}{y}\middle|z\right\rangle"#,
8570                (60.0, 44.0),
8571            ),
8572            (r#"\begin{pmatrix}a&b\\c&d\end{pmatrix}"#, (64.0, 44.0)),
8573            (r#"\begin{aligned}a&=b+c\\d&=e\end{aligned}"#, (72.0, 42.0)),
8574            (
8575                r#"\min_{\mathclap{\substack{x\in\mathbb{R}^n\\x\geq0\\Ax\leq b}}}c^Tx"#,
8576                (62.0, 55.0),
8577            ),
8578            (
8579                r#"\begin{CD}A@>f>>B\\@VgVV@VVhV\\C@>>k>D\end{CD}"#,
8580                (106.0, 112.0),
8581            ),
8582            (r#"\bra{\psi}A\ket{\phi}+\braket{x|y}"#, (154.0, 19.0)),
8583            (
8584                r#"\cancel{x}+\bcancel{y}+\xcancel{z}+\cancelto{0}{w}"#,
8585                (155.0, 26.0),
8586            ),
8587            (
8588                r#"f(x)=\begin{cases}x^2&x\geq0\\-x&x<0\end{cases}"#,
8589                (159.0, 44.0),
8590            ),
8591            (r#"\color{red}{x}+\colorbox{yellow}{y}"#, (53.0, 22.0)),
8592            (r#"90\degree+20\celsius+5\micro\ohm"#, (134.0, 18.0)),
8593            (r#"\ce{2H2 + O2 -> 2H2O}"#, (165.0, 16.0)),
8594            (r#"\dv{x}f(x)+\qty(\frac{a}{b})"#, (125.0, 38.0)),
8595            (
8596                r#"\Huge{\frac{\alpha g^2}{\omega^5} e^{[ -0.74\bigl\{\frac{\omega U_\omega 19.5}{g}\bigr\}^{\!-4}\,]}}"#,
8597                (382.0, 101.0),
8598            ),
8599            (r#"gibberish\; math:\sum_{i=0}^\infty i^2"#, (179.0, 51.0)),
8600            (
8601                r#"\min_{ \mathclap{\substack{ x \in \mathbb{R}^n \ x \geq 0 \ Ax \leq b }}} c^T x"#,
8602                (62.0, 32.0),
8603            ),
8604            (
8605                r#"\begin{equation} \label{eq1}
8606\begin{split}
8607A & = \frac{\\pi r^2}{2} \\
8608 & = \frac{1}{2} \pi r^2
8609\end{split}
8610\end{equation}"#,
8611                (82.0, 82.0),
8612            ),
8613            (
8614                r#"\lim_{h \rightarrow 0 } \frac{f(x+h)-f(x)}{h}"#,
8615                (162.0, 41.0),
8616            ),
8617            (r#"f(x) = x^2 + 2x + 1"#, (150.0, 21.0)),
8618            (
8619                r#"\var{F[g(x)]}
8620\dd(\cos\theta)"#,
8621                (128.0, 19.0),
8622            ),
8623            (
8624                r#"\displaylines{x = a + b \\ y = b + c}
8625\sum_{k=1}^{n} h_{k} \int_{0}^{1} \bigl(\partial_{k} f(x_{k-1}+t h_{k} e_{k}) -\partial_{k} f(a)\bigr) \,dt"#,
8626                (404.0, 52.0),
8627            ),
8628            (r#"1 + 1"#, (41.0, 14.0)),
8629        ];
8630        for (expression, (width, height)) in cases {
8631            assert_eq!(
8632                measure(expression).unwrap(),
8633                Size { width, height },
8634                "MathJax fixture dimensions for {expression:?}"
8635            );
8636        }
8637    }
8638}
8639
8640#[cfg(test)]
8641mod original_general_fraction_contract {
8642    use super::*;
8643    #[cfg(feature = "oracle-fixtures")]
8644    #[test]
8645    fn original_fraction_boxes_and_serialized_dimensions() {
8646        let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
8647            "tests/fixtures/fractions-source-v090.json"
8648        ))
8649        .unwrap();
8650        let rows = rows.as_array().unwrap();
8651        assert_eq!(rows.len(), 13);
8652        for row in rows {
8653            let expression = row["expression"].as_str().unwrap();
8654            assert_eq!(
8655                measure(expression).unwrap(),
8656                Size {
8657                    width: row["width"].as_f64().unwrap(),
8658                    height: row["height"].as_f64().unwrap()
8659                },
8660                "{expression}"
8661            );
8662            let native = render(expression).unwrap();
8663            let native = roxmltree::Document::parse(&native).unwrap();
8664            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
8665            for key in ["width", "height", "viewBox", "style"] {
8666                assert_eq!(
8667                    native.root_element().attribute(key),
8668                    source.root_element().attribute(key),
8669                    "{expression} {key}"
8670                );
8671            }
8672        }
8673    }
8674    #[test]
8675    fn source_binary_ties_use_ecmascript_root_serialization() {
8676        for (value, expected) in [
8677            (2.25, "2.3"),
8678            (2.55, "2.5"),
8679            (-2.25, "-2.3"),
8680            (0.0005, "0"),
8681            (1233.5533905932737, "1233.6"),
8682        ] {
8683            assert_eq!(root_number(value), expected);
8684        }
8685    }
8686}
8687
8688#[cfg(all(test, feature = "oracle-fixtures"))]
8689mod original_radical_contract {
8690    use super::{measure, render};
8691    use d2_rs_core::Size;
8692    #[cfg(feature = "oracle-fixtures")]
8693    #[test]
8694    fn original_varied_radical_boxes_and_serialized_dimensions() {
8695        let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
8696            "tests/fixtures/radicals-source-v090.json"
8697        ))
8698        .unwrap();
8699        let rows = rows.as_array().unwrap();
8700        assert_eq!(rows.len(), 16);
8701        for row in rows {
8702            let expression = row["expression"].as_str().unwrap();
8703            assert_eq!(
8704                measure(expression).unwrap(),
8705                Size {
8706                    width: row["width"].as_f64().unwrap(),
8707                    height: row["height"].as_f64().unwrap(),
8708                },
8709                "{expression}"
8710            );
8711            let native = render(expression).unwrap();
8712            let native = roxmltree::Document::parse(&native).unwrap();
8713            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
8714            for key in ["width", "height", "viewBox", "style"] {
8715                assert_eq!(
8716                    native.root_element().attribute(key),
8717                    source.root_element().attribute(key),
8718                    "{expression} {key}"
8719                );
8720            }
8721        }
8722    }
8723}
8724
8725#[cfg(all(test, feature = "oracle-fixtures"))]
8726mod original_cancel_color_contract {
8727    use super::{measure, render};
8728    use d2_rs_core::Size;
8729    #[cfg(feature = "oracle-fixtures")]
8730    #[test]
8731    fn original_cancel_color_boxes_and_serialized_dimensions() {
8732        let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
8733            "tests/fixtures/cancel-color-source-v090.json"
8734        ))
8735        .unwrap();
8736        let rows = rows.as_array().unwrap();
8737        assert_eq!(rows.len(), 25);
8738        for row in rows {
8739            let expression = row["expression"].as_str().unwrap();
8740            assert_eq!(
8741                measure(expression).unwrap(),
8742                Size {
8743                    width: row["width"].as_f64().unwrap(),
8744                    height: row["height"].as_f64().unwrap()
8745                },
8746                "{expression}"
8747            );
8748            let native = render(expression).unwrap();
8749            let native = roxmltree::Document::parse(&native).unwrap();
8750            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
8751            for key in ["width", "height", "viewBox", "style"] {
8752                assert_eq!(
8753                    native.root_element().attribute(key),
8754                    source.root_element().attribute(key),
8755                    "{expression} {key}"
8756                );
8757            }
8758        }
8759    }
8760}
8761
8762#[cfg(all(test, feature = "oracle-fixtures"))]
8763mod original_gensymb_contract {
8764    use super::{measure, render};
8765    use d2_rs_core::Size;
8766    #[cfg(feature = "oracle-fixtures")]
8767    #[test]
8768    fn original_gensymb_boxes_and_serialized_dimensions() {
8769        let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
8770            "tests/fixtures/gensymb-source-v090.json"
8771        ))
8772        .unwrap();
8773        let rows = rows.as_array().unwrap();
8774        assert_eq!(rows.len(), 22);
8775        for row in rows {
8776            let expression = row["expression"].as_str().unwrap();
8777            assert_eq!(
8778                measure(expression).unwrap(),
8779                Size {
8780                    width: row["width"].as_f64().unwrap(),
8781                    height: row["height"].as_f64().unwrap()
8782                },
8783                "{expression}"
8784            );
8785            let native = render(expression).unwrap();
8786            let native = roxmltree::Document::parse(&native).unwrap();
8787            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
8788            for key in ["width", "height", "viewBox", "style"] {
8789                assert_eq!(
8790                    native.root_element().attribute(key),
8791                    source.root_element().attribute(key),
8792                    "{expression} {key}"
8793                );
8794            }
8795        }
8796    }
8797}
8798
8799#[cfg(all(test, feature = "oracle-fixtures"))]
8800mod original_texatom_scope_contract {
8801    use super::*;
8802    #[cfg(feature = "oracle-fixtures")]
8803    #[test]
8804    fn upright_scopes_preserve_source_boxes_negative_depth_and_local_placements() {
8805        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
8806            "tests/fixtures/texatom-scope-source-v090.json"
8807        ))
8808        .unwrap();
8809        assert_eq!(rows.len(), 28);
8810        for row in rows {
8811            let expression = row["expression"].as_str().unwrap();
8812            let expected = row["svg"].as_str().unwrap();
8813            let actual = render(expression).unwrap();
8814            let source = roxmltree::Document::parse(expected).unwrap();
8815            let native = roxmltree::Document::parse(&actual).unwrap();
8816            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
8817                assert_eq!(
8818                    native.root_element().attribute(key),
8819                    source.root_element().attribute(key),
8820                    "{expression}: {key}"
8821                );
8822            }
8823            let size = measure(expression).unwrap();
8824            assert_eq!(
8825                (size.width, size.height),
8826                (
8827                    row["width"].as_f64().unwrap(),
8828                    row["height"].as_f64().unwrap()
8829                ),
8830                "{expression}"
8831            );
8832            if expression == r"a+\mathrm{x+y}+b" {
8833                let source_scope = source
8834                    .descendants()
8835                    .find(|n| n.attribute("data-mml-node") == Some("TeXAtom"))
8836                    .unwrap();
8837                let native_scope = native
8838                    .descendants()
8839                    .find(|n| n.attribute("data-mml-node") == Some("TeXAtom"))
8840                    .unwrap();
8841                for key in ["transform", "data-mjx-texclass"] {
8842                    assert_eq!(native_scope.attribute(key), source_scope.attribute(key));
8843                }
8844                let placements = |n: roxmltree::Node<'_, '_>| {
8845                    n.descendants()
8846                        .filter(|n| n.has_tag_name("g"))
8847                        .filter_map(|n| n.attribute("transform").map(str::to_owned))
8848                        .collect::<Vec<_>>()
8849                };
8850                assert_eq!(placements(native_scope), placements(source_scope));
8851            }
8852        }
8853        // Math remapping is independent of normal-font selection; literal
8854        // text keeps the ASCII hyphen from the original text path.
8855        assert!(render(r"\mathrm{u-v}").unwrap().contains("data-c=\"2212\""));
8856        assert!(
8857            render(r"\colorbox{red}{u-v}")
8858                .unwrap()
8859                .contains("data-c=\"2D\"")
8860        );
8861    }
8862}
8863
8864fn italic_glyph(code: u32) -> Option<GlyphData> {
8865    if let Ok(i) = italic_glyphs::ITALIC_GLYPHS.binary_search_by_key(&code, |g| g.codepoint) {
8866        let g = italic_glyphs::ITALIC_GLYPHS[i];
8867        return Some(GlyphData {
8868            height: g.height,
8869            depth: g.depth,
8870            width: g.width,
8871            path: g.path,
8872        });
8873    }
8874    glyph(italic_font_code(code))
8875}
8876fn italic_correction(code: u32) -> f64 {
8877    if italic_glyphs::ITALIC_GLYPHS
8878        .binary_search_by_key(&code, |g| g.codepoint)
8879        .is_ok()
8880    {
8881        return italic_glyphs::ITALIC_CORRECTIONS
8882            .binary_search_by_key(&code, |g| g.0)
8883            .ok()
8884            .map_or(0.0, |i| italic_glyphs::ITALIC_CORRECTIONS[i].1);
8885    }
8886    let code = italic_font_code(code);
8887    glyphs::ITALIC_CORRECTIONS
8888        .binary_search_by_key(&code, |g| g.0)
8889        .ok()
8890        .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1)
8891}
8892
8893fn calligraphic_glyph(codepoint: u32) -> Option<GlyphData> {
8894    if let Ok(index) =
8895        calligraphic_glyphs::CALLIGRAPHIC_GLYPHS.binary_search_by_key(&codepoint, |g| g.codepoint)
8896    {
8897        let data = calligraphic_glyphs::CALLIGRAPHIC_GLYPHS[index];
8898        return Some(GlyphData {
8899            height: data.height,
8900            depth: data.depth,
8901            width: data.width,
8902            path: data.path,
8903        });
8904    }
8905    if let Ok(index) =
8906        italic_glyphs::ITALIC_GLYPHS.binary_search_by_key(&codepoint, |g| g.codepoint)
8907    {
8908        let data = italic_glyphs::ITALIC_GLYPHS[index];
8909        return Some(GlyphData {
8910            height: data.height,
8911            depth: data.depth,
8912            width: data.width,
8913            path: data.path,
8914        });
8915    }
8916    glyph(italic_font_code(codepoint))
8917}
8918
8919fn italic_font_code(code: u32) -> u32 {
8920    match code {
8921        0x41..=0x5A => 0x1D434 + code - 0x41,
8922        0x61..=0x7A => {
8923            if code == 0x68 {
8924                0x210E
8925            } else {
8926                0x1D44E + code - 0x61
8927            }
8928        }
8929        0x391..=0x3A9 if code != 0x3A2 => 0x1D6E2 + code - 0x391,
8930        0x3F4 => 0x1D6F3,
8931        0x3B1..=0x3C9 => 0x1D6FC + code - 0x3B1,
8932        0x2207 => 0x1D6FB,
8933        0x2202 => 0x1D715,
8934        0x3F5 => 0x1D716,
8935        0x3D1 => 0x1D717,
8936        0x3F0 => 0x1D718,
8937        0x3D5 => 0x1D719,
8938        0x3F1 => 0x1D71A,
8939        0x3D6 => 0x1D71B,
8940        _ => code,
8941    }
8942}
8943
8944fn calligraphic_correction(codepoint: u32) -> f64 {
8945    if calligraphic_glyphs::CALLIGRAPHIC_GLYPHS
8946        .binary_search_by_key(&codepoint, |g| g.codepoint)
8947        .is_ok()
8948    {
8949        return calligraphic_glyphs::ITALIC_CORRECTIONS
8950            .binary_search_by_key(&codepoint, |e| e.0)
8951            .ok()
8952            .map_or(0.0, |i| calligraphic_glyphs::ITALIC_CORRECTIONS[i].1);
8953    }
8954    if italic_glyphs::ITALIC_GLYPHS
8955        .binary_search_by_key(&codepoint, |g| g.codepoint)
8956        .is_ok()
8957    {
8958        return italic_glyphs::ITALIC_CORRECTIONS
8959            .binary_search_by_key(&codepoint, |e| e.0)
8960            .ok()
8961            .map_or(0.0, |i| italic_glyphs::ITALIC_CORRECTIONS[i].1);
8962    }
8963    let smp = italic_font_code(codepoint);
8964    glyphs::ITALIC_CORRECTIONS
8965        .binary_search_by_key(&smp, |e| e.0)
8966        .ok()
8967        .map_or(0.0, |i| glyphs::ITALIC_CORRECTIONS[i].1)
8968}
8969
8970fn original_font_code(code: u32) -> u32 {
8971    match code {
8972        0x1D434..=0x1D44D => code - 0x1D434 + 'A' as u32,
8973        0x1D44E..=0x1D467 => code - 0x1D44E + 'a' as u32,
8974        0x210E => 'h' as u32,
8975        0x1D6E2..=0x1D6FA => code - 0x1D6E2 + 0x391,
8976        0x1D6FC..=0x1D714 => code - 0x1D6FC + 0x3B1,
8977        0x1D6FB => 0x2207,
8978        0x1D715 => 0x2202,
8979        0x1D716 => 0x3F5,
8980        0x1D717 => 0x3D1,
8981        0x1D718 => 0x3F0,
8982        0x1D719 => 0x3D5,
8983        0x1D71A => 0x3F1,
8984        0x1D71B => 0x3D6,
8985        _ => code,
8986    }
8987}
8988
8989fn apply_math_font(atom: &mut Atom, calligraphic: bool) {
8990    match atom {
8991        Atom::FontGlyph { original, .. } => {
8992            let code = *original;
8993            *atom = if calligraphic {
8994                Atom::CalligraphicGlyph(code)
8995            } else {
8996                Atom::Glyph(code)
8997            };
8998        }
8999        Atom::Glyph(code) | Atom::CalligraphicGlyph(code) | Atom::ItalicGlyph(code) => {
9000            let original = original_font_code(*code);
9001            *atom = if calligraphic {
9002                Atom::CalligraphicGlyph(original)
9003            } else {
9004                Atom::Glyph(original)
9005            };
9006        }
9007        Atom::Choice(v) => {
9008            for a in v {
9009                apply_math_font(a, calligraphic);
9010            }
9011        }
9012        Atom::Fenced { body: v, .. }
9013        | Atom::InferredRow(v)
9014        | Atom::ExplicitRow(v)
9015        | Atom::Sequence(v)
9016        | Atom::Identifier(v)
9017        | Atom::Number(v)
9018        | Atom::OperatorToken(v) => {
9019            for a in v {
9020                apply_math_font(a, calligraphic);
9021            }
9022        }
9023        Atom::Fraction(a, b)
9024        | Atom::SplitFraction(a, b, _)
9025        | Atom::GeneralFraction(a, b, _)
9026        | Atom::Root {
9027            body: a, index: b, ..
9028        } => {
9029            apply_math_font(a, calligraphic);
9030            apply_math_font(b, calligraphic);
9031        }
9032        Atom::BracketMark { body: a, .. }
9033        | Atom::HorizontalMark { body: a, .. }
9034        | Atom::NamedFunction(a)
9035        | Atom::Sqrt(a)
9036        | Atom::SizedSqrt { body: a, .. }
9037        | Atom::Operator(a)
9038        | Atom::AutoOperator(a)
9039        | Atom::MathMLSpace { body: a, .. }
9040        | Atom::MovesScripts(a)
9041        | Atom::ScriptPolicy { body: a, .. }
9042        | Atom::RawOperator { body: a, .. }
9043        | Atom::Reference { body: a, .. }
9044        | Atom::Boxed(a)
9045        | Atom::Ord(a)
9046        | Atom::Class { body: a, .. }
9047        | Atom::Phantom(a)
9048        | Atom::CrampedStyle(a, _)
9049        | Atom::DeclaredStyle { body: a, .. }
9050        | Atom::DeclaredSize { body: a, .. }
9051        | Atom::Padded { body: a, .. }
9052        | Atom::ColorBox { body: a, .. }
9053        | Atom::Color { body: a, .. }
9054        | Atom::Cancel { body: a, .. } => apply_math_font(a, calligraphic),
9055        Atom::Matrix { rows, .. } | Atom::TaggedTable { rows, .. } => {
9056            for row in rows {
9057                for a in row {
9058                    apply_math_font(a, calligraphic);
9059                }
9060            }
9061        }
9062        Atom::Multiscripts {
9063            base,
9064            sub,
9065            sup,
9066            post,
9067            ..
9068        } => {
9069            for a in [base, sub, sup] {
9070                apply_math_font(a, calligraphic);
9071            }
9072            if let Some(v) = post {
9073                for a in v {
9074                    apply_math_font(a, calligraphic);
9075                }
9076            }
9077        }
9078        Atom::Scripts { base, sub, sup, .. } => {
9079            apply_math_font(base, calligraphic);
9080            for a in [sub, sup].into_iter().flatten() {
9081                apply_math_font(a, calligraphic);
9082            }
9083        }
9084        Atom::XArrow { over, under, .. } => {
9085            apply_math_font(over, calligraphic);
9086            if let Some(a) = under {
9087                apply_math_font(a, calligraphic);
9088            }
9089        }
9090        Atom::CdArrow { over, under, .. } => {
9091            for a in [over, under].into_iter().flatten() {
9092                apply_math_font(a, calligraphic);
9093            }
9094        }
9095        _ => {}
9096    }
9097}
9098
9099#[cfg(all(test, feature = "oracle-fixtures"))]
9100mod original_amscd_contract {
9101    use super::*;
9102    #[cfg(feature = "oracle-fixtures")]
9103    #[test]
9104    fn complete_source_cd_font_text_dimension_and_error_boxes() {
9105        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9106            "tests/fixtures/amscd-source-v090.json"
9107        ))
9108        .unwrap();
9109        assert_eq!(rows.len(), 32);
9110        for row in rows {
9111            let expression = row["expression"].as_str().unwrap();
9112            let actual = render(expression).unwrap();
9113            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9114            let native = roxmltree::Document::parse(&actual).unwrap();
9115            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9116                assert_eq!(
9117                    native.root_element().attribute(key),
9118                    source.root_element().attribute(key),
9119                    "{expression}: {key}"
9120                );
9121            }
9122            let size = measure(expression).unwrap();
9123            assert_eq!(
9124                (size.width, size.height),
9125                (
9126                    row["width"].as_f64().unwrap(),
9127                    row["height"].as_f64().unwrap()
9128                ),
9129                "{expression}"
9130            );
9131            if source
9132                .descendants()
9133                .any(|node| node.attribute("data-mml-node") == Some("merror"))
9134            {
9135                // v0.10.0 admits font-family (d2svgimport/style.go:21), so the
9136                // merror box now stops at the frozen text fallback, as the
9137                // release CLI reports for `x: |latex \begin{CD}A@>f>B\end{CD}|`
9138                // in PNG and PDF exports.
9139                assert_eq!(
9140                    import_scene_svg(&actual).unwrap_err(),
9141                    "frozen MathJax <text> fallback supports only one U+00B5 micro sign"
9142                );
9143            }
9144        }
9145        // A whitespace variant exercises the same algorithm as the former
9146        // literal witness; no complete formula geometry is dispatched.
9147        let canonical = render(r"\begin{CD}A@>f>>B\\@VgVV@VVhV\\C@>>k>D\end{CD}").unwrap();
9148        let spaced = render(r"\begin{CD} A@>f>>B\\@VgVV@VVhV\\C@>>k>D\end{CD}").unwrap();
9149        assert_eq!(canonical, spaced);
9150    }
9151}
9152
9153#[cfg(all(test, feature = "oracle-fixtures"))]
9154mod original_cd_paint_contract {
9155    use super::*;
9156    #[cfg(feature = "oracle-fixtures")]
9157    #[test]
9158    fn source_cached_equality_bounds_and_local_script_label_frames() {
9159        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9160            "tests/fixtures/cd-paint-source-v090.json"
9161        ))
9162        .unwrap();
9163        assert_eq!(rows.len(), 12);
9164        for (index, row) in rows.iter().enumerate() {
9165            let expression = row["expression"].as_str().unwrap();
9166            let actual = render(expression).unwrap();
9167            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9168            let native = roxmltree::Document::parse(&actual).unwrap();
9169            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9170                assert_eq!(
9171                    native.root_element().attribute(key),
9172                    source.root_element().attribute(key),
9173                    "{expression}: {key}"
9174                );
9175            }
9176            let measured = measure(expression).unwrap();
9177            assert_eq!(
9178                (measured.width, measured.height),
9179                (
9180                    row["width"].as_f64().unwrap(),
9181                    row["height"].as_f64().unwrap()
9182                ),
9183                "{expression}"
9184            );
9185            if index == 0 {
9186                let nested = |doc: &roxmltree::Document<'_>| {
9187                    doc.descendants()
9188                        .find(|n| n.has_tag_name("svg") && n.parent_element().is_some())
9189                        .unwrap()
9190                        .attribute("width")
9191                        .unwrap()
9192                        .to_owned()
9193                };
9194                assert_eq!(nested(&source), "2750");
9195                assert_eq!(nested(&native), nested(&source));
9196            }
9197            if index == 8 {
9198                let placement = |doc: &roxmltree::Document<'_>| {
9199                    doc.descendants()
9200                        .find(|n| n.attribute("data-c") == Some("32"))
9201                        .unwrap()
9202                        .ancestors()
9203                        .find_map(|n| n.attribute("transform"))
9204                        .unwrap()
9205                        .to_owned()
9206                };
9207                assert_eq!(placement(&source), "translate(609,363) scale(0.707)");
9208                assert_eq!(placement(&native), placement(&source));
9209            }
9210        }
9211    }
9212}
9213
9214#[cfg(all(test, feature = "oracle-fixtures"))]
9215mod original_cd_capture_contract {
9216    use super::*;
9217    #[cfg(feature = "oracle-fixtures")]
9218    #[test]
9219    fn source_row_annotations_environment_nesting_and_earliest_errors() {
9220        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9221            "tests/fixtures/cd-capture-source-v090.json"
9222        ))
9223        .unwrap();
9224        assert_eq!(rows.len(), 11);
9225        for row in rows {
9226            let expression = row["expression"].as_str().unwrap();
9227            let actual = render(expression).unwrap();
9228            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9229            let native = roxmltree::Document::parse(&actual).unwrap();
9230            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9231                assert_eq!(
9232                    native.root_element().attribute(key),
9233                    source.root_element().attribute(key),
9234                    "{expression}: {key}"
9235                );
9236            }
9237            let measured = measure(expression).unwrap();
9238            assert_eq!(
9239                (measured.width, measured.height),
9240                (
9241                    row["width"].as_f64().unwrap(),
9242                    row["height"].as_f64().unwrap()
9243                ),
9244                "{expression}"
9245            );
9246            let error = |doc: &roxmltree::Document<'_>| {
9247                doc.descendants()
9248                    .find_map(|node| node.attribute("data-mjx-error"))
9249                    .map(str::to_owned)
9250            };
9251            assert_eq!(error(&native), error(&source), "{expression}");
9252        }
9253    }
9254}
9255
9256#[cfg(all(test, feature = "oracle-fixtures"))]
9257mod original_numeric_contract {
9258    use super::*;
9259    #[cfg(feature = "oracle-fixtures")]
9260    #[test]
9261    fn source_numeric_runs_script_core_font_scopes_and_unknown_metrics() {
9262        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9263            "tests/fixtures/numeric-source-v090.json"
9264        ))
9265        .unwrap();
9266        assert_eq!(rows.len(), 32);
9267        for row in rows {
9268            let expression = row["expression"].as_str().unwrap();
9269            let actual = render(expression).unwrap();
9270            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9271            let native = roxmltree::Document::parse(&actual).unwrap();
9272            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9273                assert_eq!(
9274                    native.root_element().attribute(key),
9275                    source.root_element().attribute(key),
9276                    "{expression}: {key}"
9277                );
9278            }
9279            let measured = measure(expression).unwrap();
9280            assert_eq!(
9281                (measured.width, measured.height),
9282                (
9283                    row["width"].as_f64().unwrap(),
9284                    row["height"].as_f64().unwrap()
9285                ),
9286                "{expression}"
9287            );
9288        }
9289        // Root dimensions alone do not distinguish a known blank glyph from
9290        // missing-font text. Preserve the original scene acceptance contract.
9291        let prior: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9292            "tests/fixtures/amscd-source-v090.json"
9293        ))
9294        .unwrap();
9295        let spacing = prior
9296            .iter()
9297            .find(|row| row["expression"] == r"\text{two words}")
9298            .unwrap();
9299        let source_svg = spacing["svg"].as_str().unwrap();
9300        let native_svg = render(spacing["expression"].as_str().unwrap()).unwrap();
9301        assert!(import_scene_svg(source_svg).is_ok());
9302        assert!(import_scene_svg(&native_svg).is_ok());
9303        let source = roxmltree::Document::parse(source_svg).unwrap();
9304        let native = roxmltree::Document::parse(&native_svg).unwrap();
9305        let blanks = |doc: &roxmltree::Document<'_>| {
9306            doc.descendants()
9307                .filter(|n| n.has_tag_name("path") && n.attribute("d") == Some(""))
9308                .count()
9309        };
9310        assert!(blanks(&source) > 0);
9311        assert_eq!(blanks(&native), blanks(&source));
9312    }
9313}
9314
9315#[cfg(all(test, feature = "oracle-fixtures"))]
9316mod original_length_contract {
9317    use super::*;
9318    #[cfg(feature = "oracle-fixtures")]
9319    #[test]
9320    fn source_relative_absolute_signed_spacing_and_root_viewports() {
9321        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9322            "tests/fixtures/length-source-v090.json"
9323        ))
9324        .unwrap();
9325        assert_eq!(rows.len(), 36);
9326        for row in rows {
9327            let expression = row["expression"].as_str().unwrap();
9328            let actual = render(expression).unwrap();
9329            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9330            let native = roxmltree::Document::parse(&actual).unwrap();
9331            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9332                assert_eq!(
9333                    native.root_element().attribute(key),
9334                    source.root_element().attribute(key),
9335                    "{expression}: {key}"
9336                );
9337            }
9338            let measured = measure(expression).unwrap();
9339            assert_eq!(
9340                (measured.width, measured.height),
9341                (
9342                    row["width"].as_f64().unwrap(),
9343                    row["height"].as_f64().unwrap()
9344                ),
9345                "{expression}"
9346            );
9347            let error = |doc: &roxmltree::Document<'_>| {
9348                doc.descendants()
9349                    .find_map(|n| n.attribute("data-mjx-error"))
9350                    .map(str::to_owned)
9351            };
9352            assert_eq!(error(&native), error(&source), "{expression}");
9353        }
9354    }
9355}
9356
9357#[cfg(all(test, feature = "oracle-fixtures"))]
9358mod original_class_contract {
9359    use super::*;
9360    #[test]
9361    fn source_classes_arrows_limits_variants_and_inherited_script_scales() {
9362        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9363            "tests/fixtures/classes-source-v090.json"
9364        ))
9365        .unwrap();
9366        assert_eq!(rows.len(), 275);
9367        for (index, row) in rows.into_iter().enumerate() {
9368            let expression = row["expression"].as_str().unwrap();
9369            let actual = render(expression).unwrap();
9370            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9371            let native = roxmltree::Document::parse(&actual).unwrap();
9372            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9373                assert_eq!(
9374                    native.root_element().attribute(key),
9375                    source.root_element().attribute(key),
9376                    "{expression}: {key}"
9377                );
9378            }
9379            let size = measure(expression).unwrap();
9380            assert_eq!(
9381                (size.width, size.height),
9382                (
9383                    row["width"].as_f64().unwrap(),
9384                    row["height"].as_f64().unwrap()
9385                ),
9386                "{expression}"
9387            );
9388            let paths = |doc: &roxmltree::Document<'_>| {
9389                doc.descendants()
9390                    .filter(|n| n.has_tag_name("path"))
9391                    .map(|n| {
9392                        (
9393                            n.attribute("data-c").unwrap_or("").to_owned(),
9394                            n.attribute("d").unwrap_or("").to_owned(),
9395                        )
9396                    })
9397                    .collect::<Vec<_>>()
9398            };
9399            assert_eq!(
9400                paths(&native),
9401                paths(&source),
9402                "{expression}: complete glyph inventory"
9403            );
9404            let error = |doc: &roxmltree::Document<'_>| {
9405                doc.descendants()
9406                    .find_map(|n| n.attribute("data-mjx-error"))
9407                    .map(str::to_owned)
9408            };
9409            assert_eq!(error(&native), error(&source), "{expression}");
9410            if index < 128 && index % 4 == 0 {
9411                let classes = |doc: &roxmltree::Document<'_>| {
9412                    doc.descendants()
9413                        .filter_map(|n| n.attribute("data-mjx-texclass"))
9414                        .map(str::to_owned)
9415                        .collect::<Vec<_>>()
9416                };
9417                assert_eq!(
9418                    classes(&native),
9419                    classes(&source),
9420                    "{expression}: effective class"
9421                );
9422            }
9423        }
9424    }
9425}
9426
9427#[cfg(all(test, feature = "oracle-fixtures"))]
9428mod original_style_contract {
9429    use super::*;
9430    #[test]
9431    fn source_style_declarations_choices_boundaries_and_inherited_levels() {
9432        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9433            "tests/fixtures/styles-source-v090.json"
9434        ))
9435        .unwrap();
9436        assert_eq!(rows.len(), 259);
9437        for row in rows.into_iter() {
9438            let expression = row["expression"].as_str().unwrap();
9439            let actual = render(expression).unwrap();
9440            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9441            let native = roxmltree::Document::parse(&actual).unwrap();
9442            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9443                assert_eq!(
9444                    native.root_element().attribute(key),
9445                    source.root_element().attribute(key),
9446                    "{expression}: {key}"
9447                );
9448            }
9449            let size = measure(expression).unwrap();
9450            assert_eq!(
9451                (size.width, size.height),
9452                (
9453                    row["width"].as_f64().unwrap(),
9454                    row["height"].as_f64().unwrap()
9455                ),
9456                "{expression}"
9457            );
9458            let paths = |doc: &roxmltree::Document<'_>| {
9459                doc.descendants()
9460                    .filter(|n| n.has_tag_name("path"))
9461                    .map(|n| {
9462                        (
9463                            n.attribute("data-c").unwrap_or("").to_owned(),
9464                            n.attribute("d").unwrap_or("").to_owned(),
9465                        )
9466                    })
9467                    .collect::<Vec<_>>()
9468            };
9469            assert_eq!(
9470                paths(&native),
9471                paths(&source),
9472                "{expression}: complete glyph inventory"
9473            );
9474            let error = |doc: &roxmltree::Document<'_>| {
9475                doc.descendants()
9476                    .find_map(|n| n.attribute("data-mjx-error"))
9477                    .map(str::to_owned)
9478            };
9479            assert_eq!(error(&native), error(&source), "{expression}");
9480            // Preserve the source's independently rounded parent/style frames
9481            // and radical paint Rule scaling, which equal roots cannot check.
9482            if [
9483                r"x_{\displaystyle x+y}",
9484                r"x^{\displaystyle x+y}",
9485                r"x^{\displaystyle \sqrt{x}}",
9486                r"x_{\displaystyle \sqrt{x}}",
9487                r"x_{\textstyle x+y}",
9488                r"\scriptstyle \sqrt{x}",
9489                r"\scriptscriptstyle \sqrt{x}",
9490                r"x_{\scriptscriptstyle \sqrt{x}}",
9491                r"x^{\scriptscriptstyle \sqrt{x}}",
9492            ]
9493            .contains(&expression)
9494            {
9495                let transforms = |doc: &roxmltree::Document<'_>| {
9496                    doc.descendants()
9497                        .filter_map(|n| n.attribute("transform"))
9498                        .map(str::to_owned)
9499                        .collect::<Vec<_>>()
9500                };
9501                assert_eq!(
9502                    transforms(&native),
9503                    transforms(&source),
9504                    "{expression}: retained paint frames"
9505                );
9506                let rectangles = |doc: &roxmltree::Document<'_>| {
9507                    doc.descendants()
9508                        .filter(|n| n.has_tag_name("rect"))
9509                        .map(|n| {
9510                            ["x", "y", "width", "height"]
9511                                .map(|key| n.attribute(key).unwrap_or("").to_owned())
9512                        })
9513                        .collect::<Vec<_>>()
9514                };
9515                assert_eq!(
9516                    rectangles(&native),
9517                    rectangles(&source),
9518                    "{expression}: scaled paint rule"
9519                );
9520            }
9521        }
9522    }
9523}
9524
9525#[cfg(all(test, feature = "oracle-fixtures"))]
9526mod original_xarrow_contract {
9527    use super::*;
9528    #[test]
9529    fn source_labeled_arrow_families_padding_styles_and_script_errors() {
9530        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9531            "tests/fixtures/xarrows-source-v090.json"
9532        ))
9533        .unwrap();
9534        assert_eq!(rows.len(), 286);
9535        for row in rows.into_iter() {
9536            let expression = row["expression"].as_str().unwrap();
9537            let actual = render(expression).unwrap();
9538            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9539            let native = roxmltree::Document::parse(&actual).unwrap();
9540            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9541                assert_eq!(
9542                    native.root_element().attribute(key),
9543                    source.root_element().attribute(key),
9544                    "{expression}: {key}"
9545                );
9546            }
9547            let size = measure(expression).unwrap();
9548            assert_eq!(
9549                (size.width, size.height),
9550                (
9551                    row["width"].as_f64().unwrap(),
9552                    row["height"].as_f64().unwrap()
9553                ),
9554                "{expression}"
9555            );
9556            let paths = |doc: &roxmltree::Document<'_>| {
9557                doc.descendants()
9558                    .filter(|n| n.has_tag_name("path"))
9559                    .map(|n| {
9560                        (
9561                            n.attribute("data-c").unwrap_or("").to_owned(),
9562                            n.attribute("d").unwrap_or("").to_owned(),
9563                        )
9564                    })
9565                    .collect::<Vec<_>>()
9566            };
9567            assert_eq!(
9568                paths(&native),
9569                paths(&source),
9570                "{expression}: complete glyph inventory"
9571            );
9572            let error = |doc: &roxmltree::Document<'_>| {
9573                doc.descendants()
9574                    .find_map(|n| n.attribute("data-mjx-error"))
9575                    .map(str::to_owned)
9576            };
9577            assert_eq!(error(&native), error(&source), "{expression}");
9578        }
9579    }
9580}
9581
9582#[cfg(all(test, feature = "oracle-fixtures"))]
9583mod original_host_primitive_contract {
9584    use super::*;
9585    #[cfg(feature = "oracle-fixtures")]
9586    fn compare(source: &str, count: usize) {
9587        let rows: Vec<serde_json::Value> = serde_json::from_str(source).unwrap();
9588        assert_eq!(rows.len(), count);
9589        for row in rows {
9590            let expression = row["expression"].as_str().unwrap();
9591            let svg = render(expression).unwrap();
9592            let native = roxmltree::Document::parse(&svg).unwrap();
9593            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9594            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9595                assert_eq!(
9596                    native.root_element().attribute(key),
9597                    source.root_element().attribute(key),
9598                    "{expression}: {key}"
9599                );
9600            }
9601            let size = measure(expression).unwrap();
9602            assert_eq!(
9603                (size.width, size.height),
9604                (
9605                    row["width"].as_f64().unwrap(),
9606                    row["height"].as_f64().unwrap()
9607                ),
9608                "{expression}"
9609            );
9610            let paths = |doc: &roxmltree::Document<'_>| {
9611                doc.descendants()
9612                    .filter(|n| n.has_tag_name("path"))
9613                    .map(|n| {
9614                        (
9615                            n.attribute("data-c").unwrap_or("").to_owned(),
9616                            n.attribute("d").unwrap_or("").to_owned(),
9617                        )
9618                    })
9619                    .collect::<Vec<_>>()
9620            };
9621            assert_eq!(
9622                paths(&native),
9623                paths(&source),
9624                "{expression}: glyph inventory"
9625            );
9626            let errors = |doc: &roxmltree::Document<'_>| {
9627                doc.descendants()
9628                    .filter_map(|n| n.attribute("data-mjx-error"))
9629                    .map(str::to_owned)
9630                    .collect::<Vec<_>>()
9631            };
9632            assert_eq!(
9633                errors(&native),
9634                errors(&source),
9635                "{expression}: diagnostics"
9636            );
9637        }
9638    }
9639    #[cfg(feature = "oracle-fixtures")]
9640    #[test]
9641    fn source_equivalence_circle_and_nbsp_commands_in_context() {
9642        compare(
9643            d2_rs_testdata::oracle_fixture!("tests/fixtures/host-primitives-source-v090.json"),
9644            161,
9645        );
9646    }
9647    #[cfg(feature = "oracle-fixtures")]
9648    #[test]
9649    fn source_undefined_command_namespace_and_error_precedence() {
9650        compare(
9651            d2_rs_testdata::oracle_fixture!("tests/fixtures/undefined-commands-source-v090.json"),
9652            758,
9653        );
9654    }
9655    #[cfg(feature = "oracle-fixtures")]
9656    #[test]
9657    fn source_default_command_recognition_preserves_unimplemented_names() {
9658        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9659            "tests/fixtures/commands-source-v090.json"
9660        ))
9661        .unwrap();
9662        assert!(
9663            !rows.is_empty(),
9664            "the source command inventory must be complete"
9665        );
9666        let mut recognized_names = Vec::new();
9667        for row in &rows {
9668            let name = row["command"].as_str().unwrap();
9669            // Go recognizes a name unless the only diagnostic of its render is
9670            // "Undefined control sequence \<name>" (scripts/generate-math-command-registry.py).
9671            let svg = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9672            let errors: Vec<&str> = svg
9673                .descendants()
9674                .filter_map(|n| n.attribute("data-mjx-error"))
9675                .collect();
9676            let recognized = errors != [format!("Undefined control sequence \\{name}")];
9677            if recognized {
9678                recognized_names.push(name);
9679            }
9680            assert_eq!(command_registry::recognized(name), recognized, "{name}");
9681        }
9682        assert_eq!(command_registry::COMMANDS, recognized_names);
9683    }
9684}
9685
9686#[cfg(all(test, feature = "oracle-fixtures"))]
9687mod original_mhchem_host_contract {
9688    use super::*;
9689    #[test]
9690    fn source_raw_chemistry_units_nested_arguments_and_error_precedence() {
9691        // Full1039-case differential reports retain123 outstanding host cases.
9692        // This permanent fixture contains the 916 completely qualified controls.
9693        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9694            "tests/fixtures/mhchem-host-source-v090.json"
9695        ))
9696        .unwrap();
9697        assert_eq!(rows.len(), 916);
9698        for row in rows {
9699            let expression = row["expression"].as_str().unwrap();
9700            if let Some(expected) = row["render_error"].as_str() {
9701                assert_eq!(
9702                    render(expression).unwrap_err().to_string(),
9703                    expected,
9704                    "{expression}"
9705                );
9706                assert_eq!(
9707                    measure(expression).unwrap_err().to_string(),
9708                    row["measure_error"].as_str().unwrap(),
9709                    "{expression}"
9710                );
9711                assert!(
9712                    row["svg"].is_null(),
9713                    "{expression}: source conversion failed"
9714                );
9715                continue;
9716            }
9717            let actual = render(expression).unwrap();
9718            let native = roxmltree::Document::parse(&actual).unwrap();
9719            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9720            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9721                assert_eq!(
9722                    native.root_element().attribute(key),
9723                    source.root_element().attribute(key),
9724                    "{expression}: {key}"
9725                );
9726            }
9727            let size = measure(expression).unwrap();
9728            assert_eq!(
9729                (size.width, size.height),
9730                (
9731                    row["width"].as_f64().unwrap(),
9732                    row["height"].as_f64().unwrap()
9733                ),
9734                "{expression}"
9735            );
9736            let paths = |doc: &roxmltree::Document<'_>| {
9737                doc.descendants()
9738                    .filter(|n| n.has_tag_name("path"))
9739                    .map(|n| {
9740                        (
9741                            n.attribute("data-c").unwrap_or("").to_owned(),
9742                            n.attribute("d").unwrap_or("").to_owned(),
9743                        )
9744                    })
9745                    .collect::<Vec<_>>()
9746            };
9747            assert_eq!(
9748                paths(&native),
9749                paths(&source),
9750                "{expression}: full glyph inventory"
9751            );
9752            let errors = |doc: &roxmltree::Document<'_>| {
9753                doc.descendants()
9754                    .filter_map(|n| n.attribute("data-mjx-error"))
9755                    .map(str::to_owned)
9756                    .collect::<Vec<_>>()
9757            };
9758            assert_eq!(
9759                errors(&native),
9760                errors(&source),
9761                "{expression}: diagnostics"
9762            );
9763        }
9764    }
9765}
9766
9767#[cfg(all(test, feature = "oracle-fixtures"))]
9768mod original_literal_font_contract {
9769    use super::*;
9770    #[test]
9771    fn source_automatic_letter_variants_and_explicit_font_contexts() {
9772        // Complete1062-case source inventory includes literals, named variants and nested fonts.
9773        // Root/glyph/text/error checks are separate from the complete raster gate.
9774        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9775            "tests/fixtures/literal-font-source-v090.json"
9776        ))
9777        .unwrap();
9778        assert_eq!(rows.len(), 1062);
9779        for row in rows {
9780            let expression = row["expression"].as_str().unwrap();
9781            let actual = render(expression).unwrap();
9782            let native = roxmltree::Document::parse(&actual).unwrap();
9783            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9784            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9785                assert_eq!(
9786                    native.root_element().attribute(key),
9787                    source.root_element().attribute(key),
9788                    "{expression}: {key}"
9789                );
9790            }
9791            let size = measure(expression).unwrap();
9792            assert_eq!(
9793                (size.width, size.height),
9794                (
9795                    row["width"].as_f64().unwrap(),
9796                    row["height"].as_f64().unwrap()
9797                ),
9798                "{expression}"
9799            );
9800            let content = |doc: &roxmltree::Document<'_>| {
9801                doc.descendants()
9802                    .filter(|n| {
9803                        n.has_tag_name("path")
9804                            || n.has_tag_name("text")
9805                            || n.attribute("data-mjx-error").is_some()
9806                    })
9807                    .map(|n| {
9808                        if n.has_tag_name("path") {
9809                            vec![
9810                                "path".to_owned(),
9811                                n.attribute("data-c").unwrap_or("").to_owned(),
9812                                n.attribute("d").unwrap_or("").to_owned(),
9813                            ]
9814                        } else if n.has_tag_name("text") {
9815                            let mut a = n
9816                                .attributes()
9817                                .map(|a| (a.name(), a.value()))
9818                                .collect::<Vec<_>>();
9819                            a.sort_unstable();
9820                            vec![
9821                                "text".to_owned(),
9822                                format!("{a:?}"),
9823                                n.text().unwrap_or("").to_owned(),
9824                            ]
9825                        } else {
9826                            vec![
9827                                "error".to_owned(),
9828                                n.attribute("data-mjx-error").unwrap().to_owned(),
9829                            ]
9830                        }
9831                    })
9832                    .collect::<Vec<_>>()
9833            };
9834            assert_eq!(
9835                content(&native),
9836                content(&source),
9837                "{expression}: glyph/text/diagnostic inventory"
9838            );
9839        }
9840    }
9841}
9842
9843#[cfg(all(test, feature = "oracle-fixtures"))]
9844mod original_compound_font_contract {
9845    use super::*;
9846    #[test]
9847    fn source_compound_metrics_children_groups_and_font_contexts() {
9848        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9849            "tests/fixtures/compound-font-source-v090.json"
9850        ))
9851        .unwrap();
9852        assert_eq!(rows.len(), 160);
9853        assert_eq!(compound_glyphs::COMPOUNDS.len(), 20);
9854        for row in rows {
9855            let expression = row["expression"].as_str().unwrap();
9856            let actual = render(expression).unwrap();
9857            let native = roxmltree::Document::parse(&actual).unwrap();
9858            let source = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9859            for key in ["style", "width", "height", "viewBox"] {
9860                assert_eq!(
9861                    native.root_element().attribute(key),
9862                    source.root_element().attribute(key),
9863                    "{expression}: {key}"
9864                );
9865            }
9866            let size = measure(expression).unwrap();
9867            assert_eq!(
9868                (size.width, size.height),
9869                (
9870                    row["width"].as_f64().unwrap(),
9871                    row["height"].as_f64().unwrap()
9872                ),
9873                "{expression}"
9874            );
9875            let paths = |doc: &roxmltree::Document<'_>| {
9876                doc.descendants()
9877                    .filter(|n| n.has_tag_name("path"))
9878                    .map(|n| {
9879                        (
9880                            n.attribute("data-c").map(str::to_owned),
9881                            n.attribute("d").map(str::to_owned),
9882                        )
9883                    })
9884                    .collect::<Vec<_>>()
9885            };
9886            assert_eq!(
9887                paths(&native),
9888                paths(&source),
9889                "{expression}: glyph inventory"
9890            );
9891            let groups = |doc: &roxmltree::Document<'_>| {
9892                doc.descendants()
9893                    .filter(|n| n.has_tag_name("g") && n.attribute("data-c").is_some())
9894                    .map(|n| {
9895                        (
9896                            n.attribute("data-c").map(str::to_owned),
9897                            n.children()
9898                                .filter(|c| c.is_element())
9899                                .map(|c| {
9900                                    (
9901                                        c.attribute("data-c").map(str::to_owned),
9902                                        c.attribute("transform").map(str::to_owned),
9903                                    )
9904                                })
9905                                .collect::<Vec<_>>(),
9906                        )
9907                    })
9908                    .collect::<Vec<_>>()
9909            };
9910            assert_eq!(
9911                groups(&native),
9912                groups(&source),
9913                "{expression}: compound child identity/placement"
9914            );
9915        }
9916    }
9917}
9918
9919#[cfg(all(test, feature = "oracle-fixtures"))]
9920mod original_matrix_table_contract {
9921    use super::*;
9922    #[test]
9923    fn original_generic_matrix_geometry_glyphs_row_cell_frames_and_errors() {
9924        let rows: Vec<serde_json::Value> = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
9925            "tests/fixtures/matrix-table-source-v090.json"
9926        ))
9927        .unwrap();
9928        assert_eq!(rows.len(), 293);
9929        for row in rows {
9930            let expression = row["expression"].as_str().unwrap();
9931            let svg = render(expression).unwrap();
9932            let a = roxmltree::Document::parse(row["svg"].as_str().unwrap()).unwrap();
9933            let n = roxmltree::Document::parse(&svg).unwrap();
9934            for key in ["style", "width", "height", "viewBox", "role", "focusable"] {
9935                assert_eq!(
9936                    n.root_element().attribute(key),
9937                    a.root_element().attribute(key),
9938                    "{expression}: {key}"
9939                );
9940            }
9941            let size = measure(expression).unwrap();
9942            assert_eq!(
9943                (size.width, size.height),
9944                (
9945                    row["width"].as_f64().unwrap(),
9946                    row["height"].as_f64().unwrap()
9947                ),
9948                "{expression}"
9949            );
9950            let paths = |doc: &roxmltree::Document<'_>| {
9951                doc.descendants()
9952                    .filter(|e| e.has_tag_name("path"))
9953                    .map(|e| {
9954                        (
9955                            e.attribute("data-c").unwrap_or("").to_owned(),
9956                            e.attribute("d").unwrap_or("").to_owned(),
9957                        )
9958                    })
9959                    .collect::<Vec<_>>()
9960            };
9961            assert_eq!(paths(&n), paths(&a), "{expression}: paths");
9962            let frames = |doc: &roxmltree::Document<'_>| {
9963                doc.descendants()
9964                    .filter(|e| matches!(e.attribute("data-mml-node"), Some("mtr" | "mtd")))
9965                    .map(|e| {
9966                        (
9967                            e.attribute("data-mml-node").unwrap().to_owned(),
9968                            local_matrix(e.attribute("transform").unwrap_or("")),
9969                        )
9970                    })
9971                    .collect::<Vec<_>>()
9972            };
9973            assert_eq!(
9974                frames(&n),
9975                frames(&a),
9976                "{expression}: actual row/cell frames"
9977            );
9978            // Script/style scopes may place the table on an ancestor or on
9979            // mtable itself. Compare its full affine placement, preserving
9980            // every serialized coordinate rather than demanding wrapper bytes.
9981            fn multiply(a: [f64; 6], b: [f64; 6]) -> [f64; 6] {
9982                [
9983                    a[0] * b[0] + a[2] * b[1],
9984                    a[1] * b[0] + a[3] * b[1],
9985                    a[0] * b[2] + a[2] * b[3],
9986                    a[1] * b[2] + a[3] * b[3],
9987                    a[0] * b[4] + a[2] * b[5] + a[4],
9988                    a[1] * b[4] + a[3] * b[5] + a[5],
9989                ]
9990            }
9991            fn local_matrix(transform: &str) -> [f64; 6] {
9992                let mut matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
9993                for operation in transform.split(')') {
9994                    let Some((name, values)) = operation.trim().split_once('(') else {
9995                        continue;
9996                    };
9997                    let v = values
9998                        .split(|c: char| c == ',' || c.is_whitespace())
9999                        .filter(|x| !x.is_empty())
10000                        .map(|x| x.parse::<f64>().unwrap())
10001                        .collect::<Vec<_>>();
10002                    let own = match name.trim() {
10003                        "translate" => [1.0, 0.0, 0.0, 1.0, v[0], v.get(1).copied().unwrap_or(0.0)],
10004                        "scale" => [v[0], 0.0, 0.0, v.get(1).copied().unwrap_or(v[0]), 0.0, 0.0],
10005                        "matrix" => v.try_into().unwrap(),
10006                        _ => panic!("unsupported source transform: {name}"),
10007                    };
10008                    matrix = multiply(matrix, own);
10009                }
10010                matrix
10011            }
10012            fn world(node: roxmltree::Node<'_, '_>) -> [f64; 6] {
10013                node.ancestors().collect::<Vec<_>>().into_iter().rev().fold(
10014                    [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
10015                    |matrix, ancestor| {
10016                        multiply(
10017                            matrix,
10018                            local_matrix(ancestor.attribute("transform").unwrap_or("")),
10019                        )
10020                    },
10021                )
10022            }
10023            let tables = |doc: &roxmltree::Document<'_>| {
10024                doc.descendants()
10025                    .filter(|e| e.attribute("data-mml-node") == Some("mtable"))
10026                    .map(world)
10027                    .collect::<Vec<_>>()
10028            };
10029            assert_eq!(
10030                tables(&n),
10031                tables(&a),
10032                "{expression}: complete table affine placement"
10033            );
10034            let errors = |doc: &roxmltree::Document<'_>| {
10035                doc.descendants()
10036                    .filter_map(|e| e.attribute("data-mjx-error"))
10037                    .map(str::to_owned)
10038                    .collect::<Vec<_>>()
10039            };
10040            assert_eq!(errors(&n), errors(&a), "{expression}: errors");
10041        }
10042    }
10043}
10044
10045#[cfg(all(test, feature = "oracle-fixtures"))]
10046mod prime_contract_tests;
10047
10048#[cfg(all(test, feature = "oracle-fixtures"))]
10049mod ams_contract_tests;
10050
10051#[doc(hidden)]
10052pub mod svg_image_static;
10053
10054pub mod png_first_frame;
10055#[doc(hidden)]
10056pub mod svg_image_config;
10057pub mod webp_first_frame;
10058
10059#[doc(hidden)]
10060pub mod svg_document_import;
10061
10062#[doc(hidden)]
10063pub mod svg_asset_cache;
10064
10065#[cfg(test)]
10066mod mathjax_exact_tests;
10067#[cfg(all(test, feature = "oracle-fixtures"))]
10068mod source_nil_child_tests;
10069
10070/// Shared imageasset SVG acquisition helpers.
10071pub mod image_svg;
10072
10073pub mod svg_effects;
10074
10075pub mod svg_text;