Skip to main content

latex_rust/parser/
ast.rs

1//! Typed math AST produced by the parser.
2
3use crate::color::Color;
4use crate::dim::Dim;
5use crate::parser::group_rules;
6use crate::parser::parse::lexicon::is_superscript_char;
7use crate::parser::parse::{option_ends_early, paren_script_match, ParseOptions, Stop};
8use crate::parser::token::{tokenize, Token};
9
10/// TeX math atom class (Appendix G).
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum AtomKind {
13    /// Ordinary (`x`, `1`, `\alpha` as a letter-like glyph).
14    Ord,
15    /// Large operator class.
16    Op,
17    /// Binary operator (`+`, `\times`).
18    Bin,
19    /// Relation (`=`, `\leq`).
20    Rel,
21    /// Opening delimiter.
22    Open,
23    /// Closing delimiter.
24    Close,
25    /// Punctuation (`,`).
26    Punct,
27    /// Inner (fraction-like).
28    Inner,
29}
30
31impl AtomKind {
32    fn gold(self) -> &'static str {
33        match self {
34            Self::Ord => "Ord",
35            Self::Op => "Op",
36            Self::Bin => "Bin",
37            Self::Rel => "Rel",
38            Self::Open => "Open",
39            Self::Close => "Close",
40            Self::Punct => "Punct",
41            Self::Inner => "Inner",
42        }
43    }
44}
45
46/// Accent or decoration applied to a nucleus.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum AccentKind {
49    /// `\hat`
50    Hat,
51    /// `\check`
52    Check,
53    /// `\breve`
54    Breve,
55    /// `\acute`
56    Acute,
57    /// `\grave`
58    Grave,
59    /// `\tilde`
60    Tilde,
61    /// `\bar`
62    Bar,
63    /// `\vec`
64    Vec,
65    /// `\dot`
66    Dot,
67    /// `\ddot`
68    Ddot,
69    /// `\dddot`
70    Dddot,
71    /// `\ddddot`
72    Ddddot,
73    /// `\widehat`
74    WideHat,
75    /// `\widetilde`
76    WideTilde,
77    /// `\overline`
78    Overline,
79    /// `\underline`
80    Underline,
81    /// `\overbrace`
82    Overbrace,
83    /// `\underbrace`
84    Underbrace,
85    /// `\overleftarrow`
86    Overleftarrow,
87    /// `\overrightarrow`
88    Overrightarrow,
89    /// `\overleftrightarrow`
90    Overleftrightarrow,
91    /// `\underleftarrow`
92    Underleftarrow,
93    /// `\underrightarrow`
94    Underrightarrow,
95    /// `\underleftrightarrow`
96    Underleftrightarrow,
97    /// `\cancel`
98    Cancel,
99    /// `\bcancel`
100    BCancel,
101    /// `\xcancel`
102    XCancel,
103    /// `\boxed`
104    Boxed,
105    /// `\mathring`
106    Ring,
107    /// `\not`
108    Not,
109}
110
111impl AccentKind {
112    pub(crate) fn gold(self) -> &'static str {
113        match self {
114            Self::Hat => "hat",
115            Self::Check => "check",
116            Self::Breve => "breve",
117            Self::Acute => "acute",
118            Self::Grave => "grave",
119            Self::Tilde => "tilde",
120            Self::Bar => "bar",
121            Self::Vec => "vec",
122            Self::Dot => "dot",
123            Self::Ddot => "ddot",
124            Self::Dddot => "dddot",
125            Self::Ddddot => "ddddot",
126            Self::WideHat => "widehat",
127            Self::WideTilde => "widetilde",
128            Self::Overline => "overline",
129            Self::Underline => "underline",
130            Self::Overbrace => "overbrace",
131            Self::Underbrace => "underbrace",
132            Self::Overleftarrow => "overleftarrow",
133            Self::Overrightarrow => "overrightarrow",
134            Self::Overleftrightarrow => "overleftrightarrow",
135            Self::Underleftarrow => "underleftarrow",
136            Self::Underrightarrow => "underrightarrow",
137            Self::Underleftrightarrow => "underleftrightarrow",
138            Self::Cancel => "cancel",
139            Self::BCancel => "bcancel",
140            Self::XCancel => "xcancel",
141            Self::Boxed => "boxed",
142            Self::Ring => "mathring",
143            Self::Not => "not",
144        }
145    }
146}
147
148/// Font / text style for a run of characters.
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum TextStyle {
151    /// `\mathrm`
152    Rm,
153    /// `\mathbf`
154    Bf,
155    /// `\mathit`
156    It,
157    /// `\mathsf`
158    Sf,
159    /// `\mathtt`
160    Tt,
161    /// `\mathbb`
162    Bb,
163    /// `\mathcal`
164    Cal,
165    /// `\mathfrak`
166    Frak,
167    /// `\mathscr`
168    Scr,
169    /// `\boldsymbol`
170    Boldsymbol,
171    /// `\pmb`
172    Pmb,
173    /// `\text`
174    Text,
175}
176
177impl TextStyle {
178    fn gold(self) -> &'static str {
179        match self {
180            Self::Rm => "rm",
181            Self::Bf => "bf",
182            Self::It => "it",
183            Self::Sf => "sf",
184            Self::Tt => "tt",
185            Self::Bb => "bb",
186            Self::Cal => "cal",
187            Self::Frak => "frak",
188            Self::Scr => "scr",
189            Self::Boldsymbol => "boldsymbol",
190            Self::Pmb => "pmb",
191            Self::Text => "text",
192        }
193    }
194}
195
196/// One item of a text-mode run (`\text{…}` body).
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub enum TextItem {
199    /// A maximal run of plain characters (no whitespace).
200    Str(String),
201    /// Collapsed inter-word space.
202    Space,
203    /// A `\ ` control space.
204    ControlSpace,
205    /// A `~` no-break space.
206    NoBreakSpace,
207    /// A text symbol such as `\ldots`, `\quad`, `\qquad`.
208    Symbol(&'static str),
209    /// A nested text command with its own style.
210    Nested(TextStyle, TextRun),
211    /// Math embedded in text with `\(…\)` or `$…$`.
212    Math(Box<MathNode>),
213}
214
215/// Body of a text-mode command. Adjacent `Str` items are merged, no `Str` is
216/// empty, and no `Space` follows a `Space`.
217#[derive(Clone, Debug, Default, PartialEq, Eq)]
218pub struct TextRun(Vec<TextItem>);
219
220impl TextRun {
221    /// Creates a new `TextRun` from a vector of items, enforcing invariants.
222    #[must_use]
223    pub fn new(items: Vec<TextItem>) -> Self {
224        let mut run = Self::default();
225        for item in items {
226            run.push(item);
227        }
228        run
229    }
230
231    /// Creates a `TextRun` from a plain string, converting spaces to `Space` items.
232    #[must_use]
233    pub fn plain(s: &str) -> Self {
234        let mut run = Self::default();
235        for c in s.chars() {
236            if c == ' ' {
237                run.push(TextItem::Space);
238            } else {
239                run.push_char(c);
240            }
241        }
242        run
243    }
244
245    /// Appends an item to the run, maintaining invariants.
246    pub fn push(&mut self, item: TextItem) {
247        match (self.0.last_mut(), item) {
248            (_, TextItem::Str(s)) if s.is_empty() => {}
249            (Some(TextItem::Str(prev)), TextItem::Str(s)) => prev.push_str(&s),
250            (Some(TextItem::Space), TextItem::Space) => {}
251            (_, item) => self.0.push(item),
252        }
253    }
254
255    /// Appends a character to the last `Str` item or creates a new one.
256    pub fn push_char(&mut self, c: char) {
257        if let Some(TextItem::Str(s)) = self.0.last_mut() {
258            s.push(c);
259        } else {
260            self.0.push(TextItem::Str(c.to_string()));
261        }
262    }
263
264    /// Appends all items from another `TextRun`.
265    pub fn append(&mut self, other: TextRun) {
266        for item in other.0 {
267            self.push(item);
268        }
269    }
270
271    /// Returns a slice of the items in this run.
272    #[must_use]
273    pub fn items(&self) -> &[TextItem] {
274        &self.0
275    }
276
277    /// Checks if the run is empty.
278    #[must_use]
279    pub fn is_empty(&self) -> bool {
280        self.0.is_empty()
281    }
282
283    /// Returns `Some` only when the run contains exactly one `Str` item.
284    #[must_use]
285    pub fn as_str(&self) -> Option<&str> {
286        match self.0.as_slice() {
287            [TextItem::Str(s)] => Some(s),
288            _ => None,
289        }
290    }
291
292    /// Converts the run to a plain string representation.
293    #[must_use]
294    pub fn to_plain_string(&self) -> String {
295        let mut result = String::new();
296        for item in &self.0 {
297            match item {
298                TextItem::Str(s) => result.push_str(s),
299                TextItem::Space | TextItem::ControlSpace | TextItem::NoBreakSpace => {
300                    result.push(' ');
301                }
302                TextItem::Symbol(name) => {
303                    if *name == "ldots" {
304                        result.push('\u{2026}');
305                    } else {
306                        result.push(' ');
307                    }
308                }
309                TextItem::Nested(_, run) => result.push_str(&run.to_plain_string()),
310                TextItem::Math(_) => {}
311            }
312        }
313        result
314    }
315}
316
317/// Horizontal skip.
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub enum SpaceKind {
320    /// `\,`
321    Thin,
322    /// `\:` or `\>`
323    Medium,
324    /// `\;`
325    Thick,
326    /// `\!`
327    NegThin,
328    /// `\quad`
329    Quad,
330    /// `\qquad`
331    Qquad,
332    /// `\ ` (control space)
333    ControlSpace,
334    /// `\hspace{...}` in em.
335    Hspace(Dim),
336}
337
338/// Matrix / alignment environment.
339#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340pub enum MatrixStyle {
341    /// `{matrix}`
342    Matrix,
343    /// `{pmatrix}`
344    Pmatrix,
345    /// `{bmatrix}`
346    Bmatrix,
347    /// `{vmatrix}`
348    Vmatrix,
349    /// `{Vmatrix}`
350    VVmatrix,
351    /// `{Bmatrix}`
352    BBmatrix,
353    /// `{cases}`
354    Cases,
355    /// `{array}`
356    Array,
357    /// `{aligned}`
358    Aligned,
359    /// `{align}`
360    Align,
361    /// `{gather}`
362    Gather,
363    /// `{gathered}`: unnumbered centered display rows in an inline stack.
364    Gathered,
365    /// `{multline}`
366    Multline,
367    /// `{equation}`
368    Equation,
369    /// `{split}`
370    Split,
371}
372
373impl MatrixStyle {
374    fn gold(self) -> &'static str {
375        match self {
376            Self::Matrix => "matrix",
377            Self::Pmatrix => "pmatrix",
378            Self::Bmatrix => "bmatrix",
379            Self::Vmatrix => "vmatrix",
380            Self::VVmatrix => "Vmatrix",
381            Self::BBmatrix => "Bmatrix",
382            Self::Cases => "cases",
383            Self::Array => "array",
384            Self::Aligned => "aligned",
385            Self::Align => "align",
386            Self::Gather => "gather",
387            Self::Gathered => "gathered",
388            Self::Multline => "multline",
389            Self::Equation => "equation",
390            Self::Split => "split",
391        }
392    }
393
394    /// `align` / `gather` / `multline` / `equation` take display style and numbers.
395    #[must_use]
396    pub fn is_display_env(self) -> bool {
397        matches!(
398            self,
399            Self::Align | Self::Gather | Self::Multline | Self::Equation
400        )
401    }
402
403    /// Rows are numbered unless `\nonumber` / `\notag` / `\tag` says otherwise.
404    #[must_use]
405    pub fn numbers_rows(self) -> bool {
406        matches!(self, Self::Align | Self::Gather)
407    }
408
409    /// One equation number for the whole environment (last line for `multline`).
410    #[must_use]
411    pub fn numbers_once(self) -> bool {
412        matches!(self, Self::Equation | Self::Multline)
413    }
414}
415
416/// One column of an `{array}` preamble (`l`, `c`, `r`, `|`).
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub enum ColSpec {
419    /// `l`
420    Left,
421    /// `c`
422    Center,
423    /// `r`
424    Right,
425    /// `|`
426    VRule,
427}
428
429impl ColSpec {
430    fn gold(self) -> char {
431        match self {
432            Self::Left => 'l',
433            Self::Center => 'c',
434            Self::Right => 'r',
435            Self::VRule => '|',
436        }
437    }
438
439    /// True for `|`.
440    #[must_use]
441    pub fn is_rule(self) -> bool {
442        matches!(self, Self::VRule)
443    }
444}
445
446/// Per-row equation number in numbered environments.
447#[derive(Clone, Debug, PartialEq, Eq)]
448pub enum EqNumber {
449    /// Auto number when the environment numbers rows; none otherwise.
450    Default,
451    /// `\nonumber` / `\notag`
452    Suppress,
453    /// `\tag{...}` or `\tag*{...}`
454    Tag {
455        /// `\tag*` — no parentheses around the tag.
456        star: bool,
457        /// Tag body (text style at layout).
458        body: Box<MathNode>,
459    },
460}
461
462/// One row of a matrix / alignment environment.
463#[derive(Clone, Debug, PartialEq, Eq)]
464pub enum EnvRow {
465    /// Alignment cells (`&`-separated).
466    Cells {
467        /// Column entries.
468        cells: Vec<MathNode>,
469        /// Number / tag for this row.
470        number: EqNumber,
471        /// `\label{...}` keys bound to this row's number.
472        labels: Vec<String>,
473    },
474    /// `\hline`
475    Hline,
476    /// `\intertext{...}`
477    Intertext(Box<MathNode>),
478}
479
480impl EnvRow {
481    /// A data row with default numbering and no labels.
482    #[must_use]
483    pub fn cells(cells: Vec<MathNode>) -> Self {
484        Self::Cells {
485            cells,
486            number: EqNumber::Default,
487            labels: Vec::new(),
488        }
489    }
490}
491
492/// Which integral glyph.
493#[derive(Clone, Copy, Debug, PartialEq, Eq)]
494pub enum IntegralKind {
495    /// `\int`
496    Int,
497    /// `\iint`
498    Iint,
499    /// `\iiint`
500    Iiint,
501    /// `\oint`
502    Oint,
503    /// `\oiint`
504    Oiint,
505}
506
507impl IntegralKind {
508    fn gold(self) -> &'static str {
509        match self {
510            Self::Int => "int",
511            Self::Iint => "iint",
512            Self::Iiint => "iiint",
513            Self::Oint => "oint",
514            Self::Oiint => "oiint",
515        }
516    }
517}
518
519/// `\phantom` / `\vphantom` / `\hphantom`.
520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
521pub enum PhantomKind {
522    /// `\phantom`
523    Full,
524    /// `\vphantom`
525    Vertical,
526    /// `\hphantom`
527    Horizontal,
528}
529
530impl PhantomKind {
531    fn gold(self) -> &'static str {
532        match self {
533            Self::Full => "phantom",
534            Self::Vertical => "vphantom",
535            Self::Horizontal => "hphantom",
536        }
537    }
538}
539
540/// A `\left` / `\right` delimiter (or `.` for empty).
541#[derive(Clone, Debug, PartialEq, Eq)]
542pub enum Delimiter {
543    /// `\left.` / `\right.`
544    Empty,
545    /// Literal character (`(`, `[`, `|`).
546    Char(char),
547    /// Named delimiter (`langle`, `{` from `\{`).
548    Named(String),
549}
550
551impl Delimiter {
552    fn gold(&self) -> String {
553        match self {
554            Self::Empty => ".".into(),
555            Self::Char(c) => c.to_string(),
556            Self::Named(n) => {
557                if n == "{" || n == "}" || n == "|" {
558                    format!("\\{n}")
559                } else {
560                    n.clone()
561                }
562            }
563        }
564    }
565}
566
567/// `\big` / `\Big` / `\bigg` / `\Bigg` (and `l`/`r`/`m` siblings).
568#[derive(Clone, Copy, Debug, PartialEq, Eq)]
569pub enum DelimSize {
570    /// `\big` — about 1.2 em.
571    Big,
572    /// `\Big` — about 1.8 em.
573    Big2,
574    /// `\bigg` — about 2.4 em.
575    Bigg,
576    /// `\Bigg` — about 3.0 em.
577    Bigg2,
578}
579
580impl DelimSize {
581    fn gold(self) -> &'static str {
582        match self {
583            Self::Big => "big",
584            Self::Big2 => "Big",
585            Self::Bigg => "bigg",
586            Self::Bigg2 => "Bigg",
587        }
588    }
589
590    /// Map a control sequence to a size. `None` if it is not a `\big` family command.
591    #[must_use]
592    pub fn from_command(name: &str) -> Option<Self> {
593        match name {
594            "big" | "bigl" | "bigr" | "bigm" => Some(Self::Big),
595            "Big" | "Bigl" | "Bigr" | "Bigm" => Some(Self::Big2),
596            "bigg" | "biggl" | "biggr" | "biggm" => Some(Self::Bigg),
597            "Bigg" | "Biggl" | "Biggr" | "Biggm" => Some(Self::Bigg2),
598            _ => None,
599        }
600    }
601
602    /// Open / Close / Rel from the `l` / `r` / `m` suffix; `None` for unsuffixed `\big`.
603    #[must_use]
604    pub fn class_from_command(name: &str) -> Option<AtomKind> {
605        if name.ends_with('l') {
606            Some(AtomKind::Open)
607        } else if name.ends_with('r') {
608            Some(AtomKind::Close)
609        } else if name.ends_with('m') {
610            Some(AtomKind::Rel)
611        } else {
612            None
613        }
614    }
615}
616
617/// Which command built a [`MathNode::Fraction`].
618///
619/// `\frac` and `{a \over b}` are [`FracStyle::Frac`]. `\dfrac`, `\tfrac`, and
620/// `\cfrac` keep their own style, which layout uses and which [`MathNode::gold`]
621/// and [`MathNode::to_latex`] print back.
622#[derive(Clone, Copy, Debug, PartialEq, Eq)]
623#[non_exhaustive]
624pub enum FracStyle {
625    /// `\frac` and infix `\over`.
626    Frac,
627    /// `\dfrac`. Layout uses display style.
628    Dfrac,
629    /// `\tfrac`. Layout uses text style.
630    Tfrac,
631    /// `\cfrac`. Layout uses display style.
632    Cfrac,
633}
634
635impl FracStyle {
636    pub(crate) fn gold(self) -> &'static str {
637        match self {
638            Self::Frac => "frac",
639            Self::Dfrac => "dfrac",
640            Self::Tfrac => "tfrac",
641            Self::Cfrac => "cfrac",
642        }
643    }
644}
645
646/// Typed math-mode syntax tree.
647///
648/// Produced by [`crate::parse()`]. [`MathNode::gold`] is the gold-stable debug form.
649/// The enum is non-exhaustive so a later release can add a variant. A
650/// downstream match needs a wildcard.
651///
652/// # Examples
653///
654/// ```
655/// use latex_rust::parse;
656///
657/// let n = parse("x^2").unwrap();
658/// assert!(n.gold().contains("sup"));
659/// ```
660#[derive(Debug, PartialEq, Eq)]
661#[non_exhaustive]
662pub enum MathNode {
663    /// Single character with a TeX atom class.
664    Atom(char, AtomKind),
665    /// `\frac` / `\dfrac` / `\tfrac` / `\cfrac` / `{a \over b}`.
666    ///
667    /// The style is the command. `\over` is [`FracStyle::Frac`].
668    Fraction(FracStyle, Box<MathNode>, Box<MathNode>),
669    /// `\sqrt` / `\sqrt[n]`. Index `None` is a square root.
670    Radical(Option<Box<MathNode>>, Box<MathNode>),
671    /// `x^{}`
672    Superscript(Box<MathNode>, Box<MathNode>),
673    /// `x_{}`
674    Subscript(Box<MathNode>, Box<MathNode>),
675    /// `x_{}^{}`
676    SubSup(Box<MathNode>, Box<MathNode>, Box<MathNode>),
677    /// `\left ... \right`
678    Delimited(Delimiter, Box<MathNode>, Delimiter),
679    /// `\big` / `\Big` / `\bigg` / `\Bigg` (and `l`/`r`/`m` forms).
680    SizedDelim(Delimiter, DelimSize, AtomKind),
681    /// Horizontal list of nodes.
682    Row(Vec<MathNode>),
683    /// Matrix or multiline environment. `colspec` is the `{array}` preamble (empty otherwise).
684    Matrix(MatrixStyle, Vec<ColSpec>, Vec<EnvRow>),
685    /// `\substack{...}` — stacked script-style lines.
686    Substack(Vec<MathNode>),
687    /// `\ref{key}`
688    Ref(String),
689    /// `\tag{...}` / `\tag*{...}` (peeled into [`EnvRow`] when inside an environment).
690    Tag {
691        /// `\tag*`
692        star: bool,
693        /// Tag body.
694        body: Box<MathNode>,
695    },
696    /// `\label{key}`
697    Label(String),
698    /// `\nonumber` / `\notag`
699    NoNumber,
700    /// `\hline` (peeled into [`EnvRow::Hline`] in environments).
701    Hline,
702    /// `\intertext{...}`
703    Intertext(Box<MathNode>),
704    /// `\sum` with optional lower / upper limits.
705    Sum(Option<Box<MathNode>>, Option<Box<MathNode>>),
706    /// `\int` family with optional limits.
707    Integral(IntegralKind, Option<Box<MathNode>>, Option<Box<MathNode>>),
708    /// `\prod` with optional limits.
709    Product(Option<Box<MathNode>>, Option<Box<MathNode>>),
710    /// `\lim` with optional subscript.
711    Limit(Option<Box<MathNode>>),
712    /// `\overset` / `\underset` / `\stackrel` (base, over, under).
713    OverUnder(Box<MathNode>, Option<Box<MathNode>>, Option<Box<MathNode>>),
714    /// Accent or decoration on a nucleus.
715    Accent(Box<MathNode>, AccentKind),
716    /// `\cancelto{value}{expr}`
717    CancelTo(Box<MathNode>, Box<MathNode>),
718    /// Styled character run (`\mathrm`, `\text`, …).
719    Text(TextRun, TextStyle),
720    /// Explicit math skip.
721    Space(SpaceKind),
722    /// Named operator (`\sin`). The flag is `\limits` vs `\nolimits`.
723    Operator(String, bool),
724    /// Named glyph (`\alpha`, `\times`). The string is the control-sequence name.
725    Symbol(String),
726    /// `\color` applied to a following math list.
727    Color(Color, Box<MathNode>),
728    /// `\textcolor{...}{...}`
729    TextColor(Color, Box<MathNode>),
730    /// `\colorbox{...}{...}`
731    ColorBox(Color, Box<MathNode>),
732    /// `\fcolorbox{border}{fill}{body}`
733    FColorBox(Color, Color, Box<MathNode>),
734    /// Vertical strut (height, depth) in em.
735    Strut(Dim, Dim),
736    /// `\phantom` family.
737    Phantom(PhantomKind, Box<MathNode>),
738}
739
740impl Clone for MathNode {
741    fn clone(&self) -> Self {
742        clone_node(self)
743    }
744}
745
746impl Drop for MathNode {
747    fn drop(&mut self) {
748        // Box drop walks children on the native stack. A 10,000-deep `\left`
749        // or `\frac` is a valid tree under a raised `max_depth` and must drop
750        // on a 256 KiB thread, so the children move to a heap stack first.
751        let mut stack = Vec::new();
752        self.drain_children(&mut stack);
753        while let Some(mut child) = stack.pop() {
754            child.drain_children(&mut stack);
755        }
756    }
757}
758
759fn push_box(out: &mut Vec<MathNode>, slot: &mut Box<MathNode>) {
760    out.push(std::mem::replace(slot.as_mut(), MathNode::Hline));
761}
762
763fn push_opt(out: &mut Vec<MathNode>, slot: &mut Option<Box<MathNode>>) {
764    if let Some(child) = slot.take() {
765        out.push(*child);
766    }
767}
768
769impl MathNode {
770    fn drain_children(&mut self, out: &mut Vec<MathNode>) {
771        match self {
772            Self::Fraction(_, a, b) | Self::Superscript(a, b) | Self::Subscript(a, b) => {
773                push_box(out, a);
774                push_box(out, b);
775            }
776            Self::CancelTo(a, b) => {
777                push_box(out, a);
778                push_box(out, b);
779            }
780            Self::SubSup(a, b, c) => {
781                push_box(out, a);
782                push_box(out, b);
783                push_box(out, c);
784            }
785            Self::Radical(index, body) => {
786                push_opt(out, index);
787                push_box(out, body);
788            }
789            Self::Delimited(_, body, _) | Self::Intertext(body) => push_box(out, body),
790            Self::Row(items) | Self::Substack(items) => out.append(items),
791            Self::Matrix(_, _, rows) => {
792                for row in rows {
793                    row.drain_nodes(out);
794                }
795            }
796            Self::Tag { body, .. } => push_box(out, body),
797            Self::Sum(lower, upper) | Self::Product(lower, upper) => {
798                push_opt(out, lower);
799                push_opt(out, upper);
800            }
801            Self::Integral(_, lower, upper) => {
802                push_opt(out, lower);
803                push_opt(out, upper);
804            }
805            Self::Limit(lower) => push_opt(out, lower),
806            Self::OverUnder(base, over, under) => {
807                push_box(out, base);
808                push_opt(out, over);
809                push_opt(out, under);
810            }
811            Self::Accent(body, _)
812            | Self::Color(_, body)
813            | Self::TextColor(_, body)
814            | Self::ColorBox(_, body)
815            | Self::Phantom(_, body) => push_box(out, body),
816            Self::FColorBox(_, _, body) => push_box(out, body),
817            Self::Atom(_, _)
818            | Self::SizedDelim(_, _, _)
819            | Self::Ref(_)
820            | Self::Label(_)
821            | Self::NoNumber
822            | Self::Hline
823            | Self::Text(_, _)
824            | Self::Space(_)
825            | Self::Operator(_, _)
826            | Self::Symbol(_)
827            | Self::Strut(_, _) => {}
828        }
829    }
830}
831
832impl EnvRow {
833    fn drain_nodes(&mut self, out: &mut Vec<MathNode>) {
834        match self {
835            Self::Cells { cells, number, .. } => {
836                out.append(cells);
837                number.drain_node(out);
838            }
839            Self::Hline => {}
840            Self::Intertext(body) => push_box(out, body),
841        }
842    }
843}
844
845impl EqNumber {
846    fn drain_node(&mut self, out: &mut Vec<MathNode>) {
847        if let Self::Tag { body, .. } = self {
848            push_box(out, body);
849        }
850    }
851}
852
853enum CloneTask<'a> {
854    Node(&'a MathNode),
855    Finish(Finish),
856}
857
858enum Finish {
859    Pair(PairKind),
860    Radical {
861        has_index: bool,
862    },
863    SubSup,
864    Delimited(Delimiter, Delimiter),
865    List(ListKind, usize),
866    Matrix {
867        style: MatrixStyle,
868        cols: Vec<ColSpec>,
869        rows: Vec<RowPlan>,
870    },
871    Tag {
872        star: bool,
873    },
874    Limits {
875        kind: LimitKind,
876        has_lo: bool,
877        has_hi: bool,
878    },
879    Limit {
880        has_lo: bool,
881    },
882    OverUnder {
883        has_over: bool,
884        has_under: bool,
885    },
886    Accent(AccentKind),
887    Wrap(WrapKind),
888    Intertext,
889}
890
891enum PairKind {
892    Fraction(FracStyle),
893    Superscript,
894    Subscript,
895    CancelTo,
896}
897
898enum ListKind {
899    Row,
900    Substack,
901}
902
903enum LimitKind {
904    Sum,
905    Product,
906    Integral(IntegralKind),
907}
908
909enum WrapKind {
910    Color(Color),
911    TextColor(Color),
912    ColorBox(Color),
913    FColorBox(Color, Color),
914    Phantom(PhantomKind),
915}
916
917enum RowPlan {
918    Hline,
919    Intertext,
920    Cells {
921        n: usize,
922        number: NumPlan,
923        labels: Vec<String>,
924    },
925}
926
927enum NumPlan {
928    Default,
929    Suppress,
930    Tag { star: bool },
931}
932
933fn clone_node(root: &MathNode) -> MathNode {
934    let mut tasks = vec![CloneTask::Node(root)];
935    let mut done = Vec::new();
936    while let Some(task) = tasks.pop() {
937        match task {
938            CloneTask::Node(node) => schedule_clone(node, &mut tasks, &mut done),
939            CloneTask::Finish(finish) => finish_clone(finish, &mut done),
940        }
941    }
942    done.pop().unwrap_or(MathNode::Hline)
943}
944
945fn pop_node(done: &mut Vec<MathNode>) -> MathNode {
946    done.pop().unwrap_or(MathNode::Hline)
947}
948
949fn schedule_clone<'a>(
950    node: &'a MathNode,
951    tasks: &mut Vec<CloneTask<'a>>,
952    done: &mut Vec<MathNode>,
953) {
954    match node {
955        MathNode::Atom(ch, kind) => done.push(MathNode::Atom(*ch, *kind)),
956        MathNode::SizedDelim(delim, size, kind) => {
957            done.push(MathNode::SizedDelim(delim.clone(), *size, *kind));
958        }
959        MathNode::Ref(key) => done.push(MathNode::Ref(key.clone())),
960        MathNode::Label(key) => done.push(MathNode::Label(key.clone())),
961        MathNode::NoNumber => done.push(MathNode::NoNumber),
962        MathNode::Hline => done.push(MathNode::Hline),
963        MathNode::Text(text, style) => done.push(MathNode::Text(text.clone(), *style)),
964        MathNode::Space(kind) => done.push(MathNode::Space(kind.clone())),
965        MathNode::Operator(name, limits) => {
966            done.push(MathNode::Operator(name.clone(), *limits));
967        }
968        MathNode::Symbol(name) => done.push(MathNode::Symbol(name.clone())),
969        MathNode::Strut(height, depth) => {
970            done.push(MathNode::Strut(height.clone(), depth.clone()));
971        }
972        MathNode::Fraction(style, a, b) => {
973            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Fraction(*style))));
974            tasks.push(CloneTask::Node(b));
975            tasks.push(CloneTask::Node(a));
976        }
977        MathNode::Superscript(a, b) => {
978            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Superscript)));
979            tasks.push(CloneTask::Node(b));
980            tasks.push(CloneTask::Node(a));
981        }
982        MathNode::Subscript(a, b) => {
983            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Subscript)));
984            tasks.push(CloneTask::Node(b));
985            tasks.push(CloneTask::Node(a));
986        }
987        MathNode::CancelTo(a, b) => {
988            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::CancelTo)));
989            tasks.push(CloneTask::Node(b));
990            tasks.push(CloneTask::Node(a));
991        }
992        MathNode::SubSup(a, b, c) => {
993            tasks.push(CloneTask::Finish(Finish::SubSup));
994            tasks.push(CloneTask::Node(c));
995            tasks.push(CloneTask::Node(b));
996            tasks.push(CloneTask::Node(a));
997        }
998        MathNode::Radical(index, body) => {
999            tasks.push(CloneTask::Finish(Finish::Radical {
1000                has_index: index.is_some(),
1001            }));
1002            tasks.push(CloneTask::Node(body));
1003            if let Some(index) = index {
1004                tasks.push(CloneTask::Node(index));
1005            }
1006        }
1007        MathNode::Delimited(left, body, right) => {
1008            tasks.push(CloneTask::Finish(Finish::Delimited(
1009                left.clone(),
1010                right.clone(),
1011            )));
1012            tasks.push(CloneTask::Node(body));
1013        }
1014        MathNode::Row(items) => {
1015            tasks.push(CloneTask::Finish(Finish::List(ListKind::Row, items.len())));
1016            for item in items.iter().rev() {
1017                tasks.push(CloneTask::Node(item));
1018            }
1019        }
1020        MathNode::Substack(items) => {
1021            tasks.push(CloneTask::Finish(Finish::List(
1022                ListKind::Substack,
1023                items.len(),
1024            )));
1025            for item in items.iter().rev() {
1026                tasks.push(CloneTask::Node(item));
1027            }
1028        }
1029        MathNode::Matrix(style, cols, rows) => schedule_matrix(*style, cols, rows, tasks),
1030        MathNode::Tag { star, body } => {
1031            tasks.push(CloneTask::Finish(Finish::Tag { star: *star }));
1032            tasks.push(CloneTask::Node(body));
1033        }
1034        MathNode::Sum(lower, upper) => {
1035            schedule_limits(LimitKind::Sum, lower, upper, tasks);
1036        }
1037        MathNode::Product(lower, upper) => {
1038            schedule_limits(LimitKind::Product, lower, upper, tasks);
1039        }
1040        MathNode::Integral(kind, lower, upper) => {
1041            schedule_limits(LimitKind::Integral(*kind), lower, upper, tasks);
1042        }
1043        MathNode::Limit(lower) => {
1044            tasks.push(CloneTask::Finish(Finish::Limit {
1045                has_lo: lower.is_some(),
1046            }));
1047            if let Some(lower) = lower {
1048                tasks.push(CloneTask::Node(lower));
1049            }
1050        }
1051        MathNode::OverUnder(base, over, under) => {
1052            tasks.push(CloneTask::Finish(Finish::OverUnder {
1053                has_over: over.is_some(),
1054                has_under: under.is_some(),
1055            }));
1056            if let Some(under) = under {
1057                tasks.push(CloneTask::Node(under));
1058            }
1059            if let Some(over) = over {
1060                tasks.push(CloneTask::Node(over));
1061            }
1062            tasks.push(CloneTask::Node(base));
1063        }
1064        MathNode::Accent(body, kind) => {
1065            tasks.push(CloneTask::Finish(Finish::Accent(*kind)));
1066            tasks.push(CloneTask::Node(body));
1067        }
1068        MathNode::Color(color, body) => {
1069            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::Color(*color))));
1070            tasks.push(CloneTask::Node(body));
1071        }
1072        MathNode::TextColor(color, body) => {
1073            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::TextColor(*color))));
1074            tasks.push(CloneTask::Node(body));
1075        }
1076        MathNode::ColorBox(color, body) => {
1077            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::ColorBox(*color))));
1078            tasks.push(CloneTask::Node(body));
1079        }
1080        MathNode::FColorBox(border, fill, body) => {
1081            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::FColorBox(
1082                *border, *fill,
1083            ))));
1084            tasks.push(CloneTask::Node(body));
1085        }
1086        MathNode::Phantom(kind, body) => {
1087            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::Phantom(*kind))));
1088            tasks.push(CloneTask::Node(body));
1089        }
1090        MathNode::Intertext(body) => {
1091            tasks.push(CloneTask::Finish(Finish::Intertext));
1092            tasks.push(CloneTask::Node(body));
1093        }
1094    }
1095}
1096
1097fn schedule_limits<'a>(
1098    kind: LimitKind,
1099    lower: &'a Option<Box<MathNode>>,
1100    upper: &'a Option<Box<MathNode>>,
1101    tasks: &mut Vec<CloneTask<'a>>,
1102) {
1103    tasks.push(CloneTask::Finish(Finish::Limits {
1104        kind,
1105        has_lo: lower.is_some(),
1106        has_hi: upper.is_some(),
1107    }));
1108    if let Some(upper) = upper {
1109        tasks.push(CloneTask::Node(upper));
1110    }
1111    if let Some(lower) = lower {
1112        tasks.push(CloneTask::Node(lower));
1113    }
1114}
1115
1116fn schedule_matrix<'a>(
1117    style: MatrixStyle,
1118    cols: &[ColSpec],
1119    rows: &'a [EnvRow],
1120    tasks: &mut Vec<CloneTask<'a>>,
1121) {
1122    let mut plan = Vec::with_capacity(rows.len());
1123    let mut kids = Vec::new();
1124    for row in rows {
1125        match row {
1126            EnvRow::Hline => plan.push(RowPlan::Hline),
1127            EnvRow::Intertext(body) => {
1128                plan.push(RowPlan::Intertext);
1129                kids.push(body.as_ref());
1130            }
1131            EnvRow::Cells {
1132                cells,
1133                number,
1134                labels,
1135            } => {
1136                let num = match number {
1137                    EqNumber::Default => NumPlan::Default,
1138                    EqNumber::Suppress => NumPlan::Suppress,
1139                    EqNumber::Tag { star, .. } => NumPlan::Tag { star: *star },
1140                };
1141                plan.push(RowPlan::Cells {
1142                    n: cells.len(),
1143                    number: num,
1144                    labels: labels.clone(),
1145                });
1146                for cell in cells {
1147                    kids.push(cell);
1148                }
1149                if let EqNumber::Tag { body, .. } = number {
1150                    kids.push(body);
1151                }
1152            }
1153        }
1154    }
1155    tasks.push(CloneTask::Finish(Finish::Matrix {
1156        style,
1157        cols: cols.to_vec(),
1158        rows: plan,
1159    }));
1160    for kid in kids.into_iter().rev() {
1161        tasks.push(CloneTask::Node(kid));
1162    }
1163}
1164
1165fn finish_clone(finish: Finish, done: &mut Vec<MathNode>) {
1166    match finish {
1167        Finish::Pair(kind) => {
1168            let b = Box::new(pop_node(done));
1169            let a = Box::new(pop_node(done));
1170            done.push(match kind {
1171                PairKind::Fraction(style) => MathNode::Fraction(style, a, b),
1172                PairKind::Superscript => MathNode::Superscript(a, b),
1173                PairKind::Subscript => MathNode::Subscript(a, b),
1174                PairKind::CancelTo => MathNode::CancelTo(a, b),
1175            });
1176        }
1177        Finish::SubSup => {
1178            let c = Box::new(pop_node(done));
1179            let b = Box::new(pop_node(done));
1180            let a = Box::new(pop_node(done));
1181            done.push(MathNode::SubSup(a, b, c));
1182        }
1183        Finish::Radical { has_index } => {
1184            let body = Box::new(pop_node(done));
1185            let index = if has_index {
1186                Some(Box::new(pop_node(done)))
1187            } else {
1188                None
1189            };
1190            done.push(MathNode::Radical(index, body));
1191        }
1192        Finish::Delimited(left, right) => {
1193            let body = Box::new(pop_node(done));
1194            done.push(MathNode::Delimited(left, body, right));
1195        }
1196        Finish::List(kind, n) => {
1197            let start = done.len().saturating_sub(n);
1198            let items = done.split_off(start);
1199            done.push(match kind {
1200                ListKind::Row => MathNode::Row(items),
1201                ListKind::Substack => MathNode::Substack(items),
1202            });
1203        }
1204        Finish::Tag { star } => {
1205            let body = Box::new(pop_node(done));
1206            done.push(MathNode::Tag { star, body });
1207        }
1208        Finish::Limits {
1209            kind,
1210            has_lo,
1211            has_hi,
1212        } => {
1213            let upper = if has_hi {
1214                Some(Box::new(pop_node(done)))
1215            } else {
1216                None
1217            };
1218            let lower = if has_lo {
1219                Some(Box::new(pop_node(done)))
1220            } else {
1221                None
1222            };
1223            done.push(match kind {
1224                LimitKind::Sum => MathNode::Sum(lower, upper),
1225                LimitKind::Product => MathNode::Product(lower, upper),
1226                LimitKind::Integral(integral) => MathNode::Integral(integral, lower, upper),
1227            });
1228        }
1229        Finish::Limit { has_lo } => {
1230            let lower = if has_lo {
1231                Some(Box::new(pop_node(done)))
1232            } else {
1233                None
1234            };
1235            done.push(MathNode::Limit(lower));
1236        }
1237        Finish::OverUnder {
1238            has_over,
1239            has_under,
1240        } => {
1241            let under = if has_under {
1242                Some(Box::new(pop_node(done)))
1243            } else {
1244                None
1245            };
1246            let over = if has_over {
1247                Some(Box::new(pop_node(done)))
1248            } else {
1249                None
1250            };
1251            let base = Box::new(pop_node(done));
1252            done.push(MathNode::OverUnder(base, over, under));
1253        }
1254        Finish::Accent(kind) => {
1255            let body = Box::new(pop_node(done));
1256            done.push(MathNode::Accent(body, kind));
1257        }
1258        Finish::Wrap(kind) => {
1259            let body = Box::new(pop_node(done));
1260            done.push(match kind {
1261                WrapKind::Color(color) => MathNode::Color(color, body),
1262                WrapKind::TextColor(color) => MathNode::TextColor(color, body),
1263                WrapKind::ColorBox(color) => MathNode::ColorBox(color, body),
1264                WrapKind::FColorBox(border, fill) => MathNode::FColorBox(border, fill, body),
1265                WrapKind::Phantom(phantom) => MathNode::Phantom(phantom, body),
1266            });
1267        }
1268        Finish::Intertext => {
1269            let body = Box::new(pop_node(done));
1270            done.push(MathNode::Intertext(body));
1271        }
1272        Finish::Matrix { style, cols, rows } => {
1273            let n = matrix_child_count(&rows);
1274            let start = done.len().saturating_sub(n);
1275            let kids = done.split_off(start);
1276            let mut kids = kids.into_iter();
1277            let mut built = Vec::with_capacity(rows.len());
1278            for row in rows {
1279                built.push(match row {
1280                    RowPlan::Hline => EnvRow::Hline,
1281                    RowPlan::Intertext => {
1282                        EnvRow::Intertext(Box::new(kids.next().unwrap_or(MathNode::Hline)))
1283                    }
1284                    RowPlan::Cells { n, number, labels } => {
1285                        let mut cells = Vec::with_capacity(n);
1286                        for _ in 0..n {
1287                            cells.push(kids.next().unwrap_or(MathNode::Hline));
1288                        }
1289                        let number = match number {
1290                            NumPlan::Default => EqNumber::Default,
1291                            NumPlan::Suppress => EqNumber::Suppress,
1292                            NumPlan::Tag { star } => EqNumber::Tag {
1293                                star,
1294                                body: Box::new(kids.next().unwrap_or(MathNode::Hline)),
1295                            },
1296                        };
1297                        EnvRow::Cells {
1298                            cells,
1299                            number,
1300                            labels,
1301                        }
1302                    }
1303                });
1304            }
1305            done.push(MathNode::Matrix(style, cols, built));
1306        }
1307    }
1308}
1309
1310fn matrix_child_count(rows: &[RowPlan]) -> usize {
1311    let mut n = 0usize;
1312    for row in rows {
1313        match row {
1314            RowPlan::Hline => {}
1315            RowPlan::Intertext => n = n.saturating_add(1),
1316            RowPlan::Cells {
1317                n: cells, number, ..
1318            } => {
1319                n = n.saturating_add(*cells);
1320                if matches!(number, NumPlan::Tag { .. }) {
1321                    n = n.saturating_add(1);
1322                }
1323            }
1324        }
1325    }
1326    n
1327}
1328
1329impl MathNode {
1330    /// Gold-stable S-expression. One space between items; no trailing space.
1331    ///
1332    /// The walk is an explicit heap stack, so a tree `parse` accepted cannot
1333    /// overflow the caller's stack here.
1334    #[must_use]
1335    pub fn gold(&self) -> String {
1336        let mut stack = vec![GoldOp::Node(self)];
1337        let mut out = String::new();
1338        while let Some(op) = stack.pop() {
1339            match op {
1340                GoldOp::Text(text) => out.push_str(&text),
1341                GoldOp::Node(node) => {
1342                    let mut forward = Vec::new();
1343                    gold_expand(node, &mut forward);
1344                    for op in forward.into_iter().rev() {
1345                        stack.push(op);
1346                    }
1347                }
1348            }
1349        }
1350        out
1351    }
1352
1353    /// LaTeX reprint of this tree.
1354    ///
1355    /// The method is total: every node prints, and it does not return
1356    /// [`Err`](crate::Error) or panic. Braces and spaces may differ from the
1357    /// source that built the tree, so compare trees, then compare a reprint
1358    /// to a reprint. It is not a byte-preserving formatter.
1359    ///
1360    /// Braces follow one rule based on the parser's grouping rules
1361    /// (documents/TEXT_MODE_SPEC.md section 5), and a reprint never nests
1362    /// deeper than any source of the same tree. Command arguments always
1363    /// print braced (`\frac {1}{2}`). A script argument that is a single
1364    /// nucleus prints bare (`x_a`), a row is one group, and an empty
1365    /// argument is `{}`. Row items print bare unless one would change
1366    /// meaning: a nested row, a superscript character, or a `)` that the
1367    /// parser's paren lookahead would pair with an earlier `(`. Superscript
1368    /// primes print as `'` marks. An alphabetic control word is followed by
1369    /// a space, so `\sin x` does not become `\sinx`, and two bare letters
1370    /// are split by a space. `\overline` is that full command.
1371    ///
1372    /// A [`MathNode::Fraction`] prints as the command in its [`FracStyle`].
1373    /// `\over` is stored as [`FracStyle::Frac`], so it prints as `\frac`;
1374    /// `\choose` and `\binom` print as `\binom`.
1375    ///
1376    /// A [`MathNode::Color`] is its own group. A color nested in a row
1377    /// therefore does not swallow the nodes that follow it.
1378    #[must_use]
1379    pub fn to_latex(&self) -> String {
1380        self.to_latex_with(&ParseOptions::new())
1381    }
1382
1383    /// [`to_latex`](Self::to_latex) for a tree that will be read back with
1384    /// `options`. Only [`ParseOptions::prime_symbol`] changes the output:
1385    /// with it on, `'` reads back as `\prime`, so a `′` superscript prints
1386    /// as `^{′}` instead of a `'` mark.
1387    #[must_use]
1388    pub fn to_latex_with(&self, options: &ParseOptions) -> String {
1389        let mut out = self.print_raw(options.prime_symbol);
1390        // The parser strips `\(…\)` and `\[…\]` fences around the whole
1391        // input and rejects an unclosed one, so a print that only starts
1392        // with `\(` or `\[` is one group. A print that starts or ends with a
1393        // whitespace atom the tokenizer does not skip (U+00A0, U+2007, `\x0b`;
1394        // a comment hid it from the `preprocess` trim) is one group too, so
1395        // the braces are its ends. A space, tab or newline is not an atom:
1396        // `<`, `>` and `!` print with a trailing space the tokenizer skips.
1397        let fenced = ["\\(", "\\["]
1398            .iter()
1399            .any(|open| out.starts_with(open) && out.len() > open.len());
1400        let trimmed = |c: Option<char>| {
1401            c.is_some_and(|c| c.is_whitespace() && !matches!(c, ' ' | '\t' | '\n' | '\r'))
1402        };
1403        if fenced || trimmed(out.chars().next()) || trimmed(out.chars().next_back()) {
1404            out.insert(0, '{');
1405            out.push('}');
1406        }
1407        out
1408    }
1409
1410    /// The print of `self` as it is written inside a larger print: no group
1411    /// is added around a leading `\(` or `\[`.
1412    fn print_raw(&self, literal_primes: bool) -> String {
1413        let mut buf = LatexBuf::new(literal_primes);
1414        let mut stack = vec![LatexOp::Node(self)];
1415        while let Some(op) = stack.pop() {
1416            match op {
1417                LatexOp::Text(text) => buf.out.push_str(&text),
1418                LatexOp::Node(node) => {
1419                    let mut forward = LatexBuf::new(buf.literal_primes);
1420                    write_node(&mut forward, node);
1421                    for op in forward.ops.into_iter().rev() {
1422                        stack.push(op);
1423                    }
1424                }
1425            }
1426        }
1427        buf.out
1428    }
1429}
1430
1431enum LatexOp<'a> {
1432    Node(&'a MathNode),
1433    Text(String),
1434}
1435
1436struct LatexBuf<'a> {
1437    ops: Vec<LatexOp<'a>>,
1438    out: String,
1439    /// A `′` superscript prints as `^{′}`, not as `'` marks.
1440    literal_primes: bool,
1441}
1442
1443impl<'a> LatexBuf<'a> {
1444    fn new(literal_primes: bool) -> Self {
1445        Self {
1446            ops: Vec::new(),
1447            out: String::new(),
1448            literal_primes,
1449        }
1450    }
1451
1452    fn push_str(&mut self, text: &str) {
1453        if let Some(LatexOp::Text(prev)) = self.ops.last_mut() {
1454            prev.push_str(text);
1455            return;
1456        }
1457        self.ops.push(LatexOp::Text(text.to_string()));
1458    }
1459
1460    fn push(&mut self, c: char) {
1461        if let Some(LatexOp::Text(prev)) = self.ops.last_mut() {
1462            prev.push(c);
1463            return;
1464        }
1465        self.ops.push(LatexOp::Text(c.to_string()));
1466    }
1467
1468    fn node(&mut self, node: &'a MathNode) {
1469        self.ops.push(LatexOp::Node(node));
1470    }
1471}
1472
1473enum GoldOp<'a> {
1474    Node(&'a MathNode),
1475    Text(String),
1476}
1477
1478fn gold_text(buf: &mut Vec<GoldOp<'_>>, text: impl Into<String>) {
1479    buf.push(GoldOp::Text(text.into()));
1480}
1481
1482fn gold_node<'a>(buf: &mut Vec<GoldOp<'a>>, node: &'a MathNode) {
1483    buf.push(GoldOp::Node(node));
1484}
1485
1486fn gold_opt<'a>(buf: &mut Vec<GoldOp<'a>>, node: &'a Option<Box<MathNode>>) {
1487    match node {
1488        None => gold_text(buf, "_"),
1489        Some(node) => gold_node(buf, node),
1490    }
1491}
1492
1493fn gold_expand<'a>(node: &'a MathNode, buf: &mut Vec<GoldOp<'a>>) {
1494    match node {
1495        MathNode::Atom(c, k) => gold_text(buf, format!("(atom {} {})", k.gold(), quote_atom(*c))),
1496        MathNode::Fraction(style, n, d) => {
1497            gold_text(buf, format!("({} ", style.gold()));
1498            gold_node(buf, n);
1499            gold_text(buf, " ");
1500            gold_node(buf, d);
1501            gold_text(buf, ")");
1502        }
1503        MathNode::Radical(None, r) => {
1504            gold_text(buf, "(sqrt ");
1505            gold_node(buf, r);
1506            gold_text(buf, ")");
1507        }
1508        MathNode::Radical(Some(i), r) => {
1509            gold_text(buf, "(sqrtn ");
1510            gold_node(buf, i);
1511            gold_text(buf, " ");
1512            gold_node(buf, r);
1513            gold_text(buf, ")");
1514        }
1515        MathNode::Superscript(b, e) => {
1516            gold_text(buf, "(sup ");
1517            gold_node(buf, b);
1518            gold_text(buf, " ");
1519            gold_node(buf, e);
1520            gold_text(buf, ")");
1521        }
1522        MathNode::Subscript(b, s) => {
1523            gold_text(buf, "(sub ");
1524            gold_node(buf, b);
1525            gold_text(buf, " ");
1526            gold_node(buf, s);
1527            gold_text(buf, ")");
1528        }
1529        MathNode::SubSup(b, s, e) => {
1530            gold_text(buf, "(subsup ");
1531            gold_node(buf, b);
1532            gold_text(buf, " ");
1533            gold_node(buf, s);
1534            gold_text(buf, " ");
1535            gold_node(buf, e);
1536            gold_text(buf, ")");
1537        }
1538        MathNode::Delimited(l, b, r) => {
1539            gold_text(buf, format!("(delim {} ", l.gold()));
1540            gold_node(buf, b);
1541            gold_text(buf, format!(" {})", r.gold()));
1542        }
1543        MathNode::SizedDelim(d, sz, k) => {
1544            gold_text(
1545                buf,
1546                format!("(big {} {} {})", sz.gold(), k.gold(), quote_delim(d)),
1547            );
1548        }
1549        MathNode::Row(items) => {
1550            if items.is_empty() {
1551                gold_text(buf, "(row)");
1552            } else {
1553                gold_text(buf, "(row");
1554                for it in items {
1555                    gold_text(buf, " ");
1556                    gold_node(buf, it);
1557                }
1558                gold_text(buf, ")");
1559            }
1560        }
1561        MathNode::Matrix(style, spec, rows) => {
1562            let mut head = format!("(matrix {}", style.gold());
1563            if !spec.is_empty() {
1564                head.push(' ');
1565                for c in spec {
1566                    head.push(c.gold());
1567                }
1568            }
1569            gold_text(buf, head);
1570            for row in rows {
1571                gold_text(buf, " ");
1572                gold_row(buf, row);
1573            }
1574            gold_text(buf, ")");
1575        }
1576        MathNode::Substack(lines) => {
1577            gold_text(buf, "(substack");
1578            for ln in lines {
1579                gold_text(buf, " ");
1580                gold_node(buf, ln);
1581            }
1582            gold_text(buf, ")");
1583        }
1584        MathNode::Ref(k) => gold_text(buf, format!("(ref {k})")),
1585        MathNode::Tag { star: false, body } => {
1586            gold_text(buf, "(tag ");
1587            gold_node(buf, body);
1588            gold_text(buf, ")");
1589        }
1590        MathNode::Tag { star: true, body } => {
1591            gold_text(buf, "(tagstar ");
1592            gold_node(buf, body);
1593            gold_text(buf, ")");
1594        }
1595        MathNode::Label(k) => gold_text(buf, format!("(label {k})")),
1596        MathNode::NoNumber => gold_text(buf, "(nonumber)"),
1597        MathNode::Hline => gold_text(buf, "(hline)"),
1598        MathNode::Intertext(n) => {
1599            gold_text(buf, "(intertext ");
1600            gold_node(buf, n);
1601            gold_text(buf, ")");
1602        }
1603        MathNode::Sum(lo, hi) => {
1604            gold_text(buf, "(sum ");
1605            gold_opt(buf, lo);
1606            gold_text(buf, " ");
1607            gold_opt(buf, hi);
1608            gold_text(buf, ")");
1609        }
1610        MathNode::Integral(k, lo, hi) => {
1611            gold_text(buf, format!("({} ", k.gold()));
1612            gold_opt(buf, lo);
1613            gold_text(buf, " ");
1614            gold_opt(buf, hi);
1615            gold_text(buf, ")");
1616        }
1617        MathNode::Product(lo, hi) => {
1618            gold_text(buf, "(prod ");
1619            gold_opt(buf, lo);
1620            gold_text(buf, " ");
1621            gold_opt(buf, hi);
1622            gold_text(buf, ")");
1623        }
1624        MathNode::Limit(lo) => {
1625            gold_text(buf, "(lim ");
1626            gold_opt(buf, lo);
1627            gold_text(buf, ")");
1628        }
1629        MathNode::OverUnder(b, over, under) => {
1630            gold_text(buf, "(overunder ");
1631            gold_node(buf, b);
1632            gold_text(buf, " ");
1633            gold_opt(buf, over);
1634            gold_text(buf, " ");
1635            gold_opt(buf, under);
1636            gold_text(buf, ")");
1637        }
1638        MathNode::Accent(b, a) => {
1639            gold_text(buf, format!("(accent {} ", a.gold()));
1640            gold_node(buf, b);
1641            gold_text(buf, ")");
1642        }
1643        MathNode::CancelTo(v, e) => {
1644            gold_text(buf, "(cancelto ");
1645            gold_node(buf, v);
1646            gold_text(buf, " ");
1647            gold_node(buf, e);
1648            gold_text(buf, ")");
1649        }
1650        MathNode::Text(t, st) => {
1651            let plain = t
1652                .items()
1653                .iter()
1654                .all(|item| matches!(item, TextItem::Str(_) | TextItem::Space));
1655            if plain {
1656                gold_text(
1657                    buf,
1658                    format!("(text {} {})", st.gold(), quote_text(&t.to_plain_string())),
1659                );
1660            } else {
1661                gold_text(buf, format!("(text {} ", st.gold()));
1662                gold_run(buf, t);
1663                gold_text(buf, ")");
1664            }
1665        }
1666        MathNode::Space(SpaceKind::Thin) => gold_text(buf, "(space thin)"),
1667        MathNode::Space(SpaceKind::Medium) => gold_text(buf, "(space medium)"),
1668        MathNode::Space(SpaceKind::Thick) => gold_text(buf, "(space thick)"),
1669        MathNode::Space(SpaceKind::NegThin) => gold_text(buf, "(space negthin)"),
1670        MathNode::Space(SpaceKind::Quad) => gold_text(buf, "(space quad)"),
1671        MathNode::Space(SpaceKind::Qquad) => gold_text(buf, "(space qquad)"),
1672        MathNode::Space(SpaceKind::ControlSpace) => gold_text(buf, "(space control)"),
1673        MathNode::Space(SpaceKind::Hspace(d)) => {
1674            gold_text(buf, format!("(space hspace {})", dim_gold(d)));
1675        }
1676        MathNode::Operator(name, false) => gold_text(buf, format!("(op {name})")),
1677        MathNode::Operator(name, true) => gold_text(buf, format!("(op {name} limits)")),
1678        MathNode::Symbol(name) => gold_text(buf, format!("(symbol {name})")),
1679        MathNode::Color(c, b) => {
1680            gold_text(buf, format!("(color {} ", c.css_hex()));
1681            gold_node(buf, b);
1682            gold_text(buf, ")");
1683        }
1684        MathNode::TextColor(c, b) => {
1685            gold_text(buf, format!("(textcolor {} ", c.css_hex()));
1686            gold_node(buf, b);
1687            gold_text(buf, ")");
1688        }
1689        MathNode::ColorBox(c, b) => {
1690            gold_text(buf, format!("(colorbox {} ", c.css_hex()));
1691            gold_node(buf, b);
1692            gold_text(buf, ")");
1693        }
1694        MathNode::FColorBox(border, fill, b) => {
1695            gold_text(
1696                buf,
1697                format!("(fcolorbox {} {} ", border.css_hex(), fill.css_hex()),
1698            );
1699            gold_node(buf, b);
1700            gold_text(buf, ")");
1701        }
1702        MathNode::Strut(h, d) => {
1703            gold_text(buf, format!("(strut {} {})", dim_gold(h), dim_gold(d)));
1704        }
1705        MathNode::Phantom(k, b) => {
1706            gold_text(buf, format!("({} ", k.gold()));
1707            gold_node(buf, b);
1708            gold_text(buf, ")");
1709        }
1710    }
1711}
1712
1713fn gold_row<'a>(buf: &mut Vec<GoldOp<'a>>, row: &'a EnvRow) {
1714    match row {
1715        EnvRow::Hline => gold_text(buf, "(hline)"),
1716        EnvRow::Intertext(n) => {
1717            gold_text(buf, "(intertext ");
1718            gold_node(buf, n);
1719            gold_text(buf, ")");
1720        }
1721        EnvRow::Cells {
1722            cells,
1723            number,
1724            labels,
1725        } => {
1726            gold_text(buf, "(");
1727            for (i, cell) in cells.iter().enumerate() {
1728                if i > 0 {
1729                    gold_text(buf, " ");
1730                }
1731                gold_node(buf, cell);
1732            }
1733            match number {
1734                EqNumber::Default => {}
1735                EqNumber::Suppress => gold_text(buf, " (nonumber)"),
1736                EqNumber::Tag { star: false, body } => {
1737                    gold_text(buf, " (tag ");
1738                    gold_node(buf, body);
1739                    gold_text(buf, ")");
1740                }
1741                EqNumber::Tag { star: true, body } => {
1742                    gold_text(buf, " (tagstar ");
1743                    gold_node(buf, body);
1744                    gold_text(buf, ")");
1745                }
1746            }
1747            for lab in labels {
1748                gold_text(buf, format!(" (label {lab})"));
1749            }
1750            gold_text(buf, ")");
1751        }
1752    }
1753}
1754
1755fn quote_delim(d: &Delimiter) -> String {
1756    match d {
1757        Delimiter::Empty => ".".into(),
1758        Delimiter::Char(c) => quote_atom(*c),
1759        Delimiter::Named(n) => n.clone(),
1760    }
1761}
1762
1763fn quote_atom(c: char) -> String {
1764    match c {
1765        '"' => "'\"'".into(),
1766        '\'' => "\"'\"".into(),
1767        _ => format!("\"{c}\""),
1768    }
1769}
1770
1771/// `(run item…)` for a text run that is not plain characters and spaces.
1772fn gold_run<'a>(buf: &mut Vec<GoldOp<'a>>, run: &'a TextRun) {
1773    gold_text(buf, "(run");
1774    for item in run.items() {
1775        match item {
1776            TextItem::Str(s) => gold_text(buf, format!(" {}", quote_text(s))),
1777            TextItem::Space => gold_text(buf, " space"),
1778            TextItem::ControlSpace => gold_text(buf, " ctrlspace"),
1779            TextItem::NoBreakSpace => gold_text(buf, " nbsp"),
1780            TextItem::Symbol(n) => gold_text(buf, format!(" (symbol {n})")),
1781            TextItem::Nested(st, r) => {
1782                gold_text(buf, format!(" (nested {} ", st.gold()));
1783                gold_run(buf, r);
1784                gold_text(buf, ")");
1785            }
1786            TextItem::Math(m) => {
1787                gold_text(buf, " (math ");
1788                gold_node(buf, m);
1789                gold_text(buf, ")");
1790            }
1791        }
1792    }
1793    gold_text(buf, ")");
1794}
1795
1796fn quote_text(t: &str) -> String {
1797    format!("\"{}\"", t.replace('\\', "\\\\").replace('"', "\\\""))
1798}
1799
1800fn dim_gold(d: &Dim) -> String {
1801    const RATIOS: [(i64, i64); 10] = [
1802        (0, 1),
1803        (1, 1),
1804        (2, 1),
1805        (1, 2),
1806        (1, 18),
1807        (2, 18),
1808        (3, 18),
1809        (7, 10),
1810        (3, 10),
1811        (1, 10),
1812    ];
1813    for (n, den) in RATIOS {
1814        if d.eq_dim(&Dim::ratio(n, den)) {
1815            if den == 1 {
1816                return n.to_string();
1817            }
1818            return format!("{n}/{den}");
1819        }
1820    }
1821    for i in -64i64..65 {
1822        if d.eq_dim(&Dim::from_i64(i)) {
1823            return i.to_string();
1824        }
1825    }
1826    d.to_dec_string()
1827}
1828
1829fn write_node<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
1830    match node {
1831        MathNode::Atom(c, _) => write_atom(out, *c),
1832        MathNode::Fraction(style, num, den) => {
1833            write_cmd(out, style.gold());
1834            write_arg(out, num);
1835            write_arg(out, den);
1836        }
1837        MathNode::Radical(index, body) => {
1838            write_cmd(out, "sqrt");
1839            if let Some(index) = index {
1840                write_option(out, index);
1841            }
1842            write_arg_after_option(out, body);
1843        }
1844        MathNode::Superscript(base, sup) => write_scripts(out, base, None, Some(sup)),
1845        MathNode::Subscript(base, sub) => write_scripts(out, base, Some(sub), None),
1846        MathNode::SubSup(base, sub, sup) => write_scripts(out, base, Some(sub), Some(sup)),
1847        MathNode::Delimited(open, body, close) => {
1848            // `\binom` parses to this tree and costs one level less.
1849            if let (
1850                Delimiter::Char('('),
1851                Delimiter::Char(')'),
1852                MathNode::Fraction(FracStyle::Frac, n, d),
1853            ) = (open, close, body.as_ref())
1854            {
1855                write_cmd(out, "binom");
1856                write_arg(out, n);
1857                write_arg(out, d);
1858            } else {
1859                write_cmd(out, "left");
1860                write_delim(out, open);
1861                out.node(body);
1862                write_cmd(out, "right");
1863                write_delim(out, close);
1864            }
1865        }
1866        MathNode::SizedDelim(delim, size, kind) => {
1867            out.push('\\');
1868            out.push_str(size.gold());
1869            out.push_str(sized_suffix(*kind, delim));
1870            out.push(' ');
1871            write_delim(out, delim);
1872        }
1873        MathNode::Row(items) => write_row(out, items),
1874        MathNode::Matrix(style, spec, rows) => write_matrix(out, *style, spec, rows),
1875        MathNode::Substack(lines) => {
1876            write_cmd(out, "substack");
1877            out.push('{');
1878            match lines.as_slice() {
1879                // The `{` is required, and `{]}` unwraps to a bare `]` (G3),
1880                // so a lone bracket keeps two groups.
1881                [line @ MathNode::Atom('[' | ']', _)] => write_group(out, line),
1882                _ => {
1883                    for (i, line) in lines.iter().enumerate() {
1884                        if i > 0 {
1885                            out.push_str("\\\\");
1886                        }
1887                        out.node(line);
1888                    }
1889                }
1890            }
1891            out.push('}');
1892        }
1893        MathNode::Ref(key) => write_braced_text(out, "ref", key),
1894        MathNode::Tag { star, body } => {
1895            write_cmd(out, "tag");
1896            if *star {
1897                out.push('*');
1898            }
1899            write_group(out, body);
1900        }
1901        MathNode::Label(key) => write_braced_text(out, "label", key),
1902        MathNode::NoNumber => write_cmd(out, "nonumber"),
1903        MathNode::Hline => write_cmd(out, "hline"),
1904        MathNode::Intertext(body) => write_intertext(out, body),
1905        MathNode::Sum(lower, upper) => {
1906            write_op_scripts(out, "sum", lower.as_deref(), upper.as_deref())
1907        }
1908        MathNode::Product(lower, upper) => {
1909            write_op_scripts(out, "prod", lower.as_deref(), upper.as_deref())
1910        }
1911        MathNode::Integral(kind, lower, upper) => {
1912            write_op_scripts(out, kind.gold(), lower.as_deref(), upper.as_deref())
1913        }
1914        MathNode::Limit(lower) => write_op_scripts(out, "lim", lower.as_deref(), None),
1915        MathNode::OverUnder(base, over, under) => {
1916            write_over_under(out, base, over.as_deref(), under.as_deref())
1917        }
1918        MathNode::Accent(body, kind) => {
1919            write_cmd(out, kind.gold());
1920            write_arg(out, body);
1921        }
1922        MathNode::CancelTo(value, expr) => {
1923            write_cmd(out, "cancelto");
1924            write_arg(out, value);
1925            write_arg(out, expr);
1926        }
1927        MathNode::Text(text, style) => {
1928            if *style == TextStyle::Text
1929                || text
1930                    .as_str()
1931                    .is_some_and(|t| t.chars().all(|c| c.is_ascii_alphabetic()))
1932            {
1933                write_cmd(out, style_cmd(*style));
1934                out.push('{');
1935                print_run(out, text);
1936                out.push('}');
1937            } else {
1938                write_cmd(out, style_cmd(*style));
1939                out.push('{');
1940                write_cmd(out, "text");
1941                out.push('{');
1942                print_run(out, text);
1943                out.push('}');
1944                out.push('}');
1945            }
1946        }
1947        MathNode::Space(kind) => write_space(out, kind),
1948        MathNode::Operator(name, limits) => write_operator(out, name, *limits),
1949        MathNode::Symbol(name) => write_cmd(out, name),
1950        MathNode::Color(color, body) => {
1951            out.push('{');
1952            write_cmd(out, "color");
1953            push_html(out, *color);
1954            out.node(body);
1955            out.push('}');
1956        }
1957        MathNode::TextColor(color, body) => write_paint(out, "textcolor", *color, None, body),
1958        MathNode::ColorBox(color, body) => write_paint(out, "colorbox", *color, None, body),
1959        MathNode::FColorBox(border, fill, body) => {
1960            write_paint(out, "fcolorbox", *border, Some(*fill), body)
1961        }
1962        MathNode::Strut(height, depth) => write_strut(out, height, depth),
1963        MathNode::Phantom(kind, body) => {
1964            write_cmd(out, kind.gold());
1965            write_arg(out, body);
1966        }
1967    }
1968}
1969
1970/// The items of a row of two or more primes of one spelling (all U+2032
1971/// atoms, or all `\prime` symbols). Such a run prints unbraced inside one
1972/// `^{…}` group, so its reprint costs one brace level for any run length.
1973fn prime_run(node: &MathNode) -> Option<&[MathNode]> {
1974    match node {
1975        MathNode::Row(items)
1976            if items.len() >= 2
1977                && (items
1978                    .iter()
1979                    .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord)))
1980                    || items
1981                        .iter()
1982                        .all(|item| matches!(item, MathNode::Symbol(name) if name == "prime"))) =>
1983        {
1984            Some(items)
1985        }
1986        _ => None,
1987    }
1988}
1989
1990/// True for a superscript that prints as `'` marks: one `′` atom or a run.
1991fn is_primes(sup: &MathNode) -> bool {
1992    matches!(sup, MathNode::Atom('′', AtomKind::Ord))
1993        || prime_run(sup).is_some_and(|items| {
1994            items
1995                .iter()
1996                .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord)))
1997        })
1998}
1999
2000fn write_scripts<'a>(
2001    out: &mut LatexBuf<'a>,
2002    base: &'a MathNode,
2003    sub: Option<&'a MathNode>,
2004    sup: Option<&'a MathNode>,
2005) {
2006    match base {
2007        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
2008        // `x'^a` parses as `(x')^a` and `x_b'^a` as `(x_b')^a`, so a primed
2009        // base needs no braces when a `^` superscript follows. More marks
2010        // would join the base's primes instead.
2011        MathNode::Superscript(_, prime) | MathNode::SubSup(_, _, prime)
2012            if sub.is_none()
2013                && !out.literal_primes
2014                && is_primes(prime)
2015                && !sup.is_some_and(is_primes) =>
2016        {
2017            out.node(base)
2018        }
2019        // A lone bracket is a nucleus here, though not as an argument.
2020        MathNode::Atom('(' | ')' | '[', _) => out.node(base),
2021        _ if bare_arg(base) => out.node(base),
2022        _ => write_group(out, base),
2023    }
2024    if let Some(sub) = sub {
2025        out.push('_');
2026        write_script_arg(out, sub);
2027    }
2028    let Some(sup) = sup else {
2029        return;
2030    };
2031    if !out.literal_primes && matches!(sup, MathNode::Atom('′', AtomKind::Ord)) {
2032        out.push('\'');
2033        return;
2034    }
2035    match prime_run(sup) {
2036        Some(items)
2037            if !out.literal_primes
2038                && items
2039                    .iter()
2040                    .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord))) =>
2041        {
2042            for _ in items {
2043                out.push('\'');
2044            }
2045        }
2046        Some(items) => {
2047            out.push_str("^{");
2048            for item in items {
2049                out.node(item);
2050            }
2051            out.push('}');
2052        }
2053        None => {
2054            // Primes after a superscript join it: `x^a''` is the row of the
2055            // old superscript and the primes. Print them as marks after the
2056            // argument.
2057            let (core, marks) = match sup {
2058                MathNode::Row(items) if !out.literal_primes => match items.split_first() {
2059                    Some((rest, tail))
2060                        if !tail.is_empty()
2061                            && tail
2062                                .iter()
2063                                .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord))) =>
2064                    {
2065                        (rest, tail.len())
2066                    }
2067                    _ => (sup, 0),
2068                },
2069                _ => (sup, 0),
2070            };
2071            out.push('^');
2072            write_script_arg(out, core);
2073            for _ in 0..marks {
2074                out.push('\'');
2075            }
2076        }
2077    }
2078}
2079
2080fn write_op_scripts<'a>(
2081    out: &mut LatexBuf<'a>,
2082    name: &str,
2083    sub: Option<&'a MathNode>,
2084    sup: Option<&'a MathNode>,
2085) {
2086    write_cmd(out, name);
2087    if let Some(sub) = sub {
2088        out.push('_');
2089        write_script_arg(out, sub);
2090    }
2091    if let Some(sup) = sup {
2092        out.push('^');
2093        write_script_arg(out, sup);
2094    }
2095}
2096
2097fn write_group<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
2098    out.push('{');
2099    out.node(node);
2100    out.push('}');
2101}
2102
2103fn write_row<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode]) {
2104    if items.is_empty() {
2105        out.push_str("{}");
2106        return;
2107    }
2108    write_row_items(out, items);
2109}
2110
2111/// Row items print bare unless the parser would read them back differently
2112/// (spec 5.3, row item): a nested row stays a group, and a prime or
2113/// superscript character would attach to its neighbour. Two bare letters are
2114/// split by a space so they do not form an operator word. Then the row paren
2115/// pass (spec 5.4) groups any item that would close a scripted paren group.
2116fn write_row_items_at<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode], row_start: bool) {
2117    let mut braced: Vec<bool> = items
2118        .iter()
2119        .enumerate()
2120        .map(|(i, item)| {
2121            if row_start && i == 0 && matches!(item, MathNode::Hline | MathNode::Intertext(_)) {
2122                true
2123            } else {
2124                match item {
2125                    MathNode::Row(_) => true,
2126                    MathNode::Atom(c, _) => *c == '\'' || is_superscript_char(*c),
2127                    _ => false,
2128                }
2129            }
2130        })
2131        .collect();
2132    // The pass prints every item once; those strings are reused below, so a
2133    // nested row is printed once per level, not twice (that was 2^k).
2134    let prints = paren_groups(items, &mut braced, out.literal_primes);
2135    let mut prev_letter = false;
2136    for (i, (item, braced)) in items.iter().zip(braced).enumerate() {
2137        let letter = !braced && matches!(item, MathNode::Atom(c, _) if c.is_ascii_alphabetic());
2138        if letter && prev_letter {
2139            out.push(' ');
2140        }
2141        prev_letter = letter;
2142        match (item, prints.as_ref().and_then(|p| p.get(i))) {
2143            (MathNode::Row(inner), _) if braced && inner.is_empty() => out.push_str("{}"),
2144            (_, Some(print)) if braced => {
2145                out.push('{');
2146                out.push_str(print);
2147                out.push('}');
2148            }
2149            (_, Some(print)) => out.push_str(print),
2150            _ if braced => write_group(out, item),
2151            _ => out.node(item),
2152        }
2153    }
2154}
2155
2156fn write_row_items<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode]) {
2157    write_row_items_at(out, items, false);
2158}
2159
2160/// The first cell of an environment row: the parser reads a leading `\hline` or
2161/// `\intertext` as a row rule or a text row, so such an item prints braced.
2162fn write_cell<'a>(out: &mut LatexBuf<'a>, cell: &'a MathNode) {
2163    match cell {
2164        MathNode::Hline | MathNode::Intertext(_) => write_group(out, cell),
2165        MathNode::Row(items) if !items.is_empty() => write_row_items_at(out, items, true),
2166        _ => out.node(cell),
2167    }
2168}
2169
2170/// True when the print of `node` starts with a bare `(` that begins an atom:
2171/// the `(` itself, or a scripted node whose innermost base is `(`.
2172fn starts_with_open_paren(node: &MathNode) -> bool {
2173    let mut current = node;
2174    loop {
2175        match current {
2176            MathNode::Superscript(base, _)
2177            | MathNode::Subscript(base, _)
2178            | MathNode::SubSup(base, _, _) => current = base,
2179            MathNode::Atom(c, _) => return *c == '(',
2180            _ => return false,
2181        }
2182    }
2183}
2184
2185/// The parser's tokens for a print: tokenized and passed through the group
2186/// rules, as `parse_with_options` does.
2187fn item_tokens(printed: &str) -> Option<Vec<Token>> {
2188    tokenize(printed).ok().map(group_rules::apply)
2189}
2190
2191/// The row paren pass (spec 5.4). The row is tokenized as printed, and the
2192/// parser's own lookahead ([`paren_script_match`]) runs from every bare `(`
2193/// that starts an item. Paren-script groups always print braced, so any match
2194/// it finds is a hazard: the item holding the matching `)` is grouped, which
2195/// hides it, and the scan repeats until no `(` matches. Returns the print of
2196/// each item when the pass ran, so the caller does not print them again.
2197fn paren_groups(
2198    items: &[MathNode],
2199    braced: &mut [bool],
2200    literal_primes: bool,
2201) -> Option<Vec<String>> {
2202    let starts = |braced: &[bool]| {
2203        items
2204            .iter()
2205            .zip(braced)
2206            .any(|(item, braced)| !braced && starts_with_open_paren(item))
2207    };
2208    if !starts(braced) {
2209        return None;
2210    }
2211    let prints: Vec<String> = items
2212        .iter()
2213        .map(|item| item.print_raw(literal_primes))
2214        .collect();
2215    let mut item_toks = Vec::with_capacity(items.len());
2216    for (print, flag) in prints.iter().zip(braced.iter_mut()) {
2217        match item_tokens(print) {
2218            Some(toks) => item_toks.push(toks),
2219            None => {
2220                // Not expected for printer output; grouping is always safe.
2221                *flag = true;
2222                item_toks.push(Vec::new());
2223            }
2224        }
2225    }
2226    loop {
2227        let mut tokens = Vec::new();
2228        let mut owner = Vec::new();
2229        let mut first = Vec::with_capacity(items.len());
2230        let mut prev_letter = false;
2231        let mut spans: Vec<(usize, usize)> = Vec::with_capacity(items.len());
2232        for (i, ((item, toks), flag)) in items
2233            .iter()
2234            .zip(item_toks.iter_mut())
2235            .zip(braced.iter())
2236            .enumerate()
2237        {
2238            let letter = !flag && matches!(item, MathNode::Atom(c, _) if c.is_ascii_alphabetic());
2239            if letter && prev_letter {
2240                tokens.push(Token::Space);
2241                owner.push(i);
2242            }
2243            prev_letter = letter;
2244            if *flag {
2245                tokens.push(Token::BeginGroup);
2246                owner.push(i);
2247            }
2248            let skip = toks
2249                .iter()
2250                .take_while(|t| matches!(t, Token::Space))
2251                .count();
2252            first.push(tokens.len() + skip);
2253            spans.push((tokens.len(), toks.len()));
2254            tokens.append(toks);
2255            owner.resize(tokens.len(), i);
2256            if *flag {
2257                tokens.push(Token::EndGroup);
2258                owner.push(i);
2259            }
2260        }
2261        let hit = items
2262            .iter()
2263            .zip(braced.iter())
2264            .zip(&first)
2265            .filter(|((item, flag), _)| !**flag && starts_with_open_paren(item))
2266            .find_map(|(_, pos)| paren_script_match(&tokens, *pos, Stop::eof()))
2267            .and_then(|m| owner.get(m).copied());
2268        let grouped = match hit.and_then(|j| braced.get_mut(j)) {
2269            Some(flag) if !*flag => {
2270                *flag = true;
2271                true
2272            }
2273            _ => false,
2274        };
2275        if !grouped {
2276            return Some(prints);
2277        }
2278        for ((start, len), toks) in spans.into_iter().rev().zip(item_toks.iter_mut().rev()) {
2279            let mut piece = tokens.split_off(start);
2280            piece.truncate(len);
2281            *toks = piece;
2282        }
2283    }
2284}
2285
2286/// True when `node` prints as exactly one nucleus, so an argument needs no
2287/// braces around it.
2288fn bare_arg(node: &MathNode) -> bool {
2289    let mut node = node;
2290    loop {
2291        return match node {
2292            MathNode::Atom(c, _) => {
2293                !c.is_whitespace()
2294                    && !is_superscript_char(*c)
2295                    && !matches!(
2296                        *c,
2297                        '(' | ')' | '[' | '\'' | '^' | '_' | '&' | '#' | '~' | '$'
2298                    )
2299            }
2300            MathNode::Row(_)
2301            | MathNode::Superscript(..)
2302            | MathNode::Subscript(..)
2303            | MathNode::SubSup(..)
2304            | MathNode::Color(..)
2305            | MathNode::Ref(_)
2306            | MathNode::Tag { .. }
2307            | MathNode::Label(_)
2308            | MathNode::NoNumber
2309            | MathNode::Hline
2310            | MathNode::Intertext(_) => false,
2311            MathNode::Operator(name, limits) => match operator_limits(name) {
2312                Some(default) => default == *limits,
2313                None => !*limits,
2314            },
2315            MathNode::Sum(lo, hi) | MathNode::Product(lo, hi) | MathNode::Integral(_, lo, hi) => {
2316                lo.is_none() && hi.is_none()
2317            }
2318            MathNode::Limit(lo) => lo.is_none(),
2319            MathNode::OverUnder(base, None, None) => {
2320                node = base;
2321                continue;
2322            }
2323            MathNode::OverUnder(base, ..) => !matches!(
2324                base.as_ref(),
2325                MathNode::Accent(_, AccentKind::Overbrace | AccentKind::Underbrace)
2326            ),
2327            _ => true,
2328        };
2329    }
2330}
2331
2332/// True when `printed` contains `pattern` outside every brace group, not
2333/// as the second character of a control symbol.
2334fn has_top_level(printed: &str, pattern: &[char]) -> bool {
2335    let chars: Vec<char> = printed.chars().collect();
2336    let mut braces = 0usize;
2337    let mut i = 0;
2338    while let Some(&c) = chars.get(i) {
2339        if braces == 0 && chars.get(i..i + pattern.len()) == Some(pattern) {
2340            return true;
2341        }
2342        match c {
2343            '\\' => i += 1,
2344            '{' => braces += 1,
2345            '}' => braces = braces.saturating_sub(1),
2346            _ => {}
2347        }
2348        i += 1;
2349    }
2350    false
2351}
2352
2353/// `[…]` around an optional argument (spec 5.3). A `]` at brace level zero
2354/// would end the option early, so such content is grouped; a lone `]` keeps
2355/// two groups, since `{]}` is read as a bare `]` (G3). Parens need nothing:
2356/// the paren lookahead skips options (Q1).
2357fn write_option<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
2358    out.push('[');
2359    match node {
2360        // `[]` reads as an empty row; `[{}]` would cost one more level.
2361        MathNode::Row(items) if items.is_empty() => {}
2362        MathNode::Atom(']', _) => {
2363            out.push('{');
2364            write_group(out, node);
2365            out.push('}');
2366        }
2367        _ => {
2368            // Print the body once and reuse it: printing it again through
2369            // `out.node` made nested options cost 2^k.
2370            let body = node.print_raw(out.literal_primes);
2371            if item_tokens(&body).is_none_or(option_ends_early) {
2372                out.push('{');
2373                out.push_str(&body);
2374                out.push('}');
2375            } else {
2376                out.push_str(&body);
2377            }
2378        }
2379    }
2380    out.push(']');
2381}
2382
2383/// An argument right after a command that takes `[…]`: a lone `[` keeps two
2384/// groups, since `{[}` is read as a bare `[` and would open the option (G3).
2385fn write_arg_after_option<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
2386    if matches!(node, MathNode::Atom('[', _)) {
2387        out.push('{');
2388        write_group(out, node);
2389        out.push('}');
2390    } else {
2391        write_arg(out, node);
2392    }
2393}
2394
2395/// A command argument: always braced (spec 5, Q2). An empty row is `{}`, a
2396/// row is one group, and a color is already its own group. A braced argument
2397/// costs no more depth than a bare one, so this never nests deeper than the
2398/// source.
2399fn write_arg<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
2400    match node {
2401        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
2402        MathNode::Row(items) => {
2403            out.push('{');
2404            write_row_items(out, items);
2405            out.push('}');
2406        }
2407        MathNode::Color(..) => out.node(node),
2408        _ => write_group(out, node),
2409    }
2410}
2411
2412/// A sub- or superscript argument, bare first (spec 5.3, script): bare when it
2413/// prints as exactly one nucleus (G1), otherwise one group.
2414fn write_script_arg<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
2415    match node {
2416        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
2417        MathNode::Row(items) => {
2418            out.push('{');
2419            write_row_items(out, items);
2420            out.push('}');
2421        }
2422        MathNode::Color(..) => out.node(node),
2423        _ if bare_arg(node) => out.node(node),
2424        _ => write_group(out, node),
2425    }
2426}
2427
2428fn write_matrix<'a>(
2429    out: &mut LatexBuf<'a>,
2430    style: MatrixStyle,
2431    spec: &[ColSpec],
2432    rows: &'a [EnvRow],
2433) {
2434    write_cmd(out, "begin");
2435    out.push('{');
2436    out.push_str(style.gold());
2437    out.push('}');
2438    if matches!(style, MatrixStyle::Array) || !spec.is_empty() {
2439        out.push('{');
2440        for col in spec {
2441            out.push(col.gold());
2442        }
2443        out.push('}');
2444    }
2445    let mut prev_cells = false;
2446    for row in rows {
2447        let cells = matches!(row, EnvRow::Cells { .. });
2448        if prev_cells {
2449            out.push_str("\\\\");
2450        }
2451        prev_cells = cells;
2452        match row {
2453            EnvRow::Hline => write_cmd(out, "hline"),
2454            EnvRow::Intertext(body) => write_intertext(out, body),
2455            EnvRow::Cells {
2456                cells,
2457                number,
2458                labels,
2459            } => {
2460                for (i, cell) in cells.iter().enumerate() {
2461                    if i > 0 {
2462                        out.push('&');
2463                    }
2464                    if i == 0 {
2465                        write_cell(out, cell);
2466                    } else {
2467                        out.node(cell);
2468                    }
2469                    if i + 1 == cells.len() {
2470                        write_eq_meta(out, number, labels);
2471                    }
2472                }
2473                if cells.is_empty() {
2474                    write_eq_meta(out, number, labels);
2475                }
2476            }
2477        }
2478    }
2479    write_cmd(out, "end");
2480    out.push('{');
2481    out.push_str(style.gold());
2482    out.push('}');
2483}
2484
2485fn write_eq_meta<'a>(out: &mut LatexBuf<'a>, number: &'a EqNumber, labels: &[String]) {
2486    for key in labels {
2487        write_braced_text(out, "label", key);
2488    }
2489    match number {
2490        EqNumber::Default => {}
2491        EqNumber::Suppress => write_cmd(out, "nonumber"),
2492        EqNumber::Tag { star, body } => {
2493            write_cmd(out, "tag");
2494            if *star {
2495                out.push('*');
2496            }
2497            write_group(out, body);
2498        }
2499    }
2500}
2501
2502fn write_over_under<'a>(
2503    out: &mut LatexBuf<'a>,
2504    base: &'a MathNode,
2505    over: Option<&'a MathNode>,
2506    under: Option<&'a MathNode>,
2507) {
2508    if let MathNode::Accent(body, kind @ (AccentKind::Overbrace | AccentKind::Underbrace)) = base {
2509        write_cmd(out, kind.gold());
2510        write_arg(out, body);
2511        if let Some(under) = under {
2512            out.push('_');
2513            write_arg(out, under);
2514        }
2515        if let Some(over) = over {
2516            out.push('^');
2517            write_arg(out, over);
2518        }
2519        return;
2520    }
2521    if let MathNode::Symbol(name) = base {
2522        let cmd = match (name.as_str(), over) {
2523            ("longrightarrow", Some(_)) => Some("xrightarrow"),
2524            ("longleftarrow", Some(_)) => Some("xleftarrow"),
2525            _ => None,
2526        };
2527        if let Some(cmd) = cmd {
2528            write_cmd(out, cmd);
2529            if let Some(under) = under {
2530                write_option(out, under);
2531            }
2532            if let Some(over) = over {
2533                write_arg_after_option(out, over);
2534            }
2535            return;
2536        }
2537    }
2538    match (over, under) {
2539        (Some(over), Some(under)) => {
2540            write_cmd(out, "overset");
2541            write_arg(out, over);
2542            write_cmd(out, "underset");
2543            write_arg(out, under);
2544            write_arg(out, base);
2545        }
2546        (Some(over), None) => {
2547            write_cmd(out, "overset");
2548            write_arg(out, over);
2549            write_arg(out, base);
2550        }
2551        (None, Some(under)) => {
2552            write_cmd(out, "underset");
2553            write_arg(out, under);
2554            write_arg(out, base);
2555        }
2556        (None, None) => out.node(base),
2557    }
2558}
2559
2560fn write_intertext<'a>(out: &mut LatexBuf<'a>, body: &'a MathNode) {
2561    write_cmd(out, "intertext");
2562    out.push('{');
2563    if let MathNode::Text(text, _) = body {
2564        print_run(out, text);
2565    } else {
2566        out.node(body);
2567    }
2568    out.push('}');
2569}
2570
2571fn write_paint<'a>(
2572    out: &mut LatexBuf<'a>,
2573    cmd: &str,
2574    first: Color,
2575    second: Option<Color>,
2576    body: &'a MathNode,
2577) {
2578    write_cmd(out, cmd);
2579    push_html(out, first);
2580    if let Some(second) = second {
2581        push_html(out, second);
2582    }
2583    write_arg(out, body);
2584}
2585
2586fn write_operator(out: &mut LatexBuf<'_>, name: &str, limits: bool) {
2587    match operator_limits(name) {
2588        Some(default) => {
2589            write_cmd(out, name);
2590            if limits != default {
2591                write_cmd(out, if limits { "limits" } else { "nolimits" });
2592            }
2593        }
2594        None => {
2595            write_cmd(out, "operatorname");
2596            out.push('{');
2597            push_escaped(out, name);
2598            out.push('}');
2599            if limits {
2600                write_cmd(out, "limits");
2601            }
2602        }
2603    }
2604}
2605
2606fn operator_limits(name: &str) -> Option<bool> {
2607    Some(match name {
2608        "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "arcsin" | "arccos" | "arctan" | "sinh"
2609        | "cosh" | "tanh" | "coth" | "log" | "ln" | "lg" | "exp" | "limsup" | "liminf" | "sup"
2610        | "inf" | "max" | "min" | "det" | "dim" | "ker" | "deg" | "gcd" | "lcm" | "Pr" | "arg" => {
2611            false
2612        }
2613        "coprod" | "bigcup" | "bigcap" | "bigsqcup" | "bigvee" | "bigwedge" | "bigoplus"
2614        | "bigotimes" | "biguplus" => true,
2615        _ => return None,
2616    })
2617}
2618
2619fn write_space(out: &mut LatexBuf<'_>, kind: &SpaceKind) {
2620    match kind {
2621        SpaceKind::Thin => out.push_str("\\,"),
2622        SpaceKind::Medium => out.push_str("\\:"),
2623        SpaceKind::Thick => out.push_str("\\;"),
2624        SpaceKind::NegThin => out.push_str("\\!"),
2625        SpaceKind::Quad => write_cmd(out, "quad"),
2626        SpaceKind::Qquad => write_cmd(out, "qquad"),
2627        // The space is the control symbol, not disposable padding. `preprocess`
2628        // keeps one trailing ASCII space after an odd run of backslashes, so
2629        // this reprint parses again. Do not drop the space or replace it with
2630        // a token that trimming would delete.
2631        SpaceKind::ControlSpace => out.push_str("\\ "),
2632        SpaceKind::Hspace(dim) => {
2633            write_cmd(out, "hspace");
2634            out.push('{');
2635            out.push_str(&dim.to_tex_string());
2636            out.push('}');
2637        }
2638    }
2639}
2640
2641fn write_strut(out: &mut LatexBuf<'_>, height: &Dim, depth: &Dim) {
2642    if height.eq_dim(&Dim::ratio(7, 10)) && depth.eq_dim(&Dim::ratio(3, 10)) {
2643        write_cmd(out, "strut");
2644        return;
2645    }
2646    write_cmd(out, "rule");
2647    out.push_str("{0em}{");
2648    out.push_str(&height.to_tex_string());
2649    out.push('}');
2650}
2651
2652fn write_atom(out: &mut LatexBuf<'_>, c: char) {
2653    match c {
2654        '{' | '}' | '%' | '\\' => {
2655            out.push('\\');
2656            out.push(c);
2657        }
2658        '<' | '>' | '!' => {
2659            out.push(c);
2660            out.push(' ');
2661        }
2662        _ => out.push(c),
2663    }
2664}
2665
2666fn write_delim(out: &mut LatexBuf<'_>, delim: &Delimiter) {
2667    match delim {
2668        Delimiter::Empty => out.push('.'),
2669        Delimiter::Char(c) => write_atom(out, *c),
2670        Delimiter::Named(name) if name == "{" || name == "}" || name == "|" => {
2671            out.push('\\');
2672            out.push_str(name);
2673        }
2674        Delimiter::Named(name) => write_cmd(out, name),
2675    }
2676}
2677
2678fn sized_suffix(kind: AtomKind, delim: &Delimiter) -> &'static str {
2679    if kind == delim_class(delim) {
2680        return "";
2681    }
2682    match kind {
2683        AtomKind::Open => "l",
2684        AtomKind::Close => "r",
2685        AtomKind::Rel => "m",
2686        AtomKind::Ord | AtomKind::Op | AtomKind::Bin | AtomKind::Punct | AtomKind::Inner => "",
2687    }
2688}
2689
2690fn delim_class(delim: &Delimiter) -> AtomKind {
2691    match delim {
2692        Delimiter::Char(c) => atom_class(*c),
2693        Delimiter::Named(name) if name == "{" => AtomKind::Open,
2694        Delimiter::Named(name) if name == "}" => AtomKind::Close,
2695        Delimiter::Empty | Delimiter::Named(_) => AtomKind::Open,
2696    }
2697}
2698
2699fn atom_class(c: char) -> AtomKind {
2700    match c {
2701        '+' | '-' | '*' | '±' | '∓' | '·' | '×' | '÷' => AtomKind::Bin,
2702        '=' | '<' | '>' | '≠' | '≤' | '≥' | '≈' | '≡' => AtomKind::Rel,
2703        '(' | '[' | '{' => AtomKind::Open,
2704        ')' | ']' | '}' => AtomKind::Close,
2705        ',' | ';' | '!' | '?' | ':' => AtomKind::Punct,
2706        _ => AtomKind::Ord,
2707    }
2708}
2709
2710fn style_cmd(style: TextStyle) -> &'static str {
2711    match style {
2712        TextStyle::Rm => "mathrm",
2713        TextStyle::Bf => "mathbf",
2714        TextStyle::It => "mathit",
2715        TextStyle::Sf => "mathsf",
2716        TextStyle::Tt => "mathtt",
2717        TextStyle::Bb => "mathbb",
2718        TextStyle::Cal => "mathcal",
2719        TextStyle::Frak => "mathfrak",
2720        TextStyle::Scr => "mathscr",
2721        TextStyle::Boldsymbol => "boldsymbol",
2722        TextStyle::Pmb => "pmb",
2723        TextStyle::Text => "text",
2724    }
2725}
2726
2727fn write_cmd(out: &mut LatexBuf<'_>, name: &str) {
2728    out.push('\\');
2729    out.push_str(name);
2730    if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic()) {
2731        out.push(' ');
2732    }
2733}
2734
2735fn write_braced_text(out: &mut LatexBuf<'_>, cmd: &str, text: &str) {
2736    write_cmd(out, cmd);
2737    out.push('{');
2738    push_escaped(out, text);
2739    out.push('}');
2740}
2741
2742/// Escapes special LaTeX characters in text.
2743///
2744/// The first character is escaped if it is a space, '[', or ']'.
2745/// All characters are escaped if they are '\', '{', '}', '%', '$', '&', '_', or '^'.
2746/// Command for a nested text run of `style` inside text.
2747fn text_cmd(style: TextStyle) -> &'static str {
2748    match style {
2749        TextStyle::Text => "text",
2750        TextStyle::Rm => "textrm",
2751        TextStyle::Bf => "textbf",
2752        TextStyle::It => "textit",
2753        TextStyle::Sf => "textsf",
2754        TextStyle::Tt => "texttt",
2755        _ => "text",
2756    }
2757}
2758
2759/// Canonical text-mode print of a run (spec 2.5). `parse` reads it back to
2760/// the same run, and math-level code never looks inside it.
2761fn print_run<'a>(out: &mut LatexBuf<'a>, run: &'a TextRun) {
2762    let mut stack = vec![run.items().iter()];
2763
2764    while let Some(mut iter) = stack.pop() {
2765        if let Some(item) = iter.next() {
2766            stack.push(iter);
2767
2768            match item {
2769                TextItem::Str(s) => {
2770                    for c in s.chars() {
2771                        match c {
2772                            '\\' => out.push_str(r"\textbackslash{}"),
2773                            '^' => out.push_str(r"\textasciicircum{}"),
2774                            '~' => out.push_str(r"\textasciitilde{}"),
2775                            '{' | '}' | '$' | '%' | '&' | '#' | '_' => {
2776                                out.push('\\');
2777                                out.push(c);
2778                            }
2779                            _ => out.push(c),
2780                        }
2781                    }
2782                }
2783                TextItem::Space => out.push(' '),
2784                TextItem::ControlSpace => out.push_str(r"\ "),
2785                TextItem::NoBreakSpace => out.push('~'),
2786                TextItem::Symbol(name) => {
2787                    out.push('\\');
2788                    out.push_str(name);
2789                    out.push_str("{}");
2790                }
2791                TextItem::Nested(style, nested_run) => {
2792                    write_cmd(out, text_cmd(*style));
2793                    out.push('{');
2794                    stack.push(nested_run.items().iter());
2795                }
2796                TextItem::Math(node) => {
2797                    // A `\)` in the body would close `\(` early. Such a body
2798                    // uses `$…$`, or one group when it also has a `$`.
2799                    let body = node.print_raw(out.literal_primes);
2800                    let close = has_top_level(&body, &['\\', ')']);
2801                    // The body is printed once (`out.node` again would cost
2802                    // 2^k for text nested in math nested in text).
2803                    if close && !has_top_level(&body, &['$']) {
2804                        out.push('$');
2805                        out.push_str(&body);
2806                        out.push('$');
2807                    } else if close {
2808                        out.push_str(r"\({");
2809                        out.push_str(&body);
2810                        out.push_str(r"}\)");
2811                    } else {
2812                        out.push_str(r"\(");
2813                        out.push_str(&body);
2814                        out.push_str(r"\)");
2815                    }
2816                }
2817            }
2818        } else if !stack.is_empty() {
2819            out.push('}');
2820        }
2821    }
2822}
2823
2824fn push_escaped(out: &mut LatexBuf<'_>, text: &str) {
2825    for (i, c) in text.chars().enumerate() {
2826        match c {
2827            ' ' | '[' | ']' if i == 0 => {
2828                out.push('\\');
2829                out.push(c);
2830            }
2831            '\\' | '{' | '}' | '%' | '$' | '&' | '_' | '^' => {
2832                out.push('\\');
2833                out.push(c);
2834            }
2835            _ => out.push(c),
2836        }
2837    }
2838}
2839
2840fn push_html(out: &mut LatexBuf<'_>, color: Color) {
2841    out.push_str("[HTML]{");
2842    let hex = color.css_hex();
2843    match hex.strip_prefix('#') {
2844        Some(body) => out.push_str(body),
2845        None => out.push_str(&hex),
2846    }
2847    out.push('}');
2848}