katex-rs 0.2.4

A Rust implementation of KaTeX - Fast math typesetting for anywhere, more than just the web.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
//! Build common utilities for KaTeX DOM construction
//!
//! This module provides general functions for constructing DOM tree nodes in
//! KaTeX's math rendering process. It includes utilities for creating symbols
//! and other DOM elements with proper styling and metrics.

use crate::ParseError;
use crate::context::KatexContext;
use crate::dom_tree::{Anchor, DomSpan, HtmlDomFragment, HtmlDomNode, Span, SvgNode, SymbolNode};
use crate::font_metrics::get_character_metrics;
use crate::font_metrics_data::CharacterMetrics;
use crate::namespace::KeyMap;
use crate::options::{FontShape, FontWeight, Options};
use crate::parser::parse_node::AnyParseNode;
use crate::spacing_data::Measurement;
use crate::symbols::{Font, Mode, is_ligature};
use crate::tree::DocumentFragment;
use crate::types::ClassList;
use crate::types::{CssProperty, CssStyle, ParseErrorKind};
use crate::units::make_em;
use crate::wide_character::get_wide_character_font;
use alloc::borrow::Cow;
use bon::bon;
use phf::phf_map;

/// Font mapping for TeX font commands to font names and variants
pub const FONT_MAP: phf::Map<&str, FontMapEntry> = phf_map! {
    "mathbf" => FontMapEntry {
        variant: "bold",
        font_name: "Main-Bold",
    },
    "mathrm" => FontMapEntry {
        variant: "normal",
        font_name: "Main-Regular",
    },
    "textit" => FontMapEntry {
        variant: "italic",
        font_name: "Main-Italic",
    },
    "mathit" => FontMapEntry {
        variant: "italic",
        font_name: "Main-Italic",
    },
    "mathnormal" => FontMapEntry {
        variant: "italic",
        font_name: "Math-Italic",
    },
    "mathbb" => FontMapEntry {
        variant: "double-struck",
        font_name: "AMS-Regular",
    },
    "mathcal" => FontMapEntry {
        variant: "script",
        font_name: "Caligraphic-Regular",
    },
    "mathscr" => FontMapEntry {
        variant: "script",
        font_name: "Script-Regular",
    },
    "mathfrak" => FontMapEntry {
        variant: "fraktur",
        font_name: "Fraktur-Regular",
    },
    "mathsf" => FontMapEntry {
        variant: "sans-serif",
        font_name: "SansSerif-Regular",
    },
    "mathsfit" => FontMapEntry {
        variant: "sans-serif-italic",
        font_name: "SansSerif-Italic",
    },
    "mathtt" => FontMapEntry {
        variant: "monospace",
        font_name: "Typewriter-Regular",
    },
    "boldsymbol" => FontMapEntry {
        variant: "bold-italic",
        font_name: "Math-BoldItalic",
    },
};

/// Font map entry structure
#[derive(Debug, Clone)]
pub struct FontMapEntry {
    /// MathML mathvariant attribute value
    pub variant: &'static str,
    /// Font name for font metrics lookup
    pub font_name: &'static str,
}

/// Result of symbol lookup
#[derive(Debug, Clone)]
pub struct SymbolLookup {
    /// The symbol value (possibly replaced)
    pub value: char,
    /// Character metrics if available
    pub metrics: Option<CharacterMetrics>,
}

/// Element for vertical list
#[derive(Debug, bon::Builder)]
pub struct VListElem {
    /// The HTML DOM node element
    pub elem: HtmlDomNode,
    /// Optional shift amount
    pub shift: Option<f64>,
    /// Optional left margin
    pub margin_left: Option<String>,
    /// Optional right margin
    pub margin_right: Option<String>,
    /// Optional wrapper classes
    pub wrapper_classes: Option<ClassList>,
    /// Optional wrapper style
    pub wrapper_style: Option<CssStyle>,
}

/// Kern element for vertical list
#[derive(Debug, Clone)]
pub struct VListKern {
    /// Size of the kern
    pub size: f64,
}

impl From<f64> for VListKern {
    fn from(size: f64) -> Self {
        Self { size }
    }
}

/// Child element in vertical list (either elem or kern)
#[derive(Debug)]
pub enum VListChild {
    /// Element child
    Elem(Box<VListElem>),
    /// Kern child
    Kern(VListKern),
}

impl From<VListElem> for VListChild {
    fn from(elem: VListElem) -> Self {
        Self::Elem(Box::new(elem))
    }
}

/// Element with shift for individual shift positioning
#[derive(Debug)]
pub struct VListElemAndShift {
    /// The HTML DOM node element
    pub elem: HtmlDomNode,
    /// Shift amount
    pub shift: f64,
    /// Optional left margin
    pub margin_left: Option<String>,
    /// Optional right margin
    pub margin_right: Option<String>,
    /// Optional wrapper classes
    pub wrapper_classes: Option<ClassList>,
    /// Optional wrapper style
    pub wrapper_style: Option<CssStyle>,
}

#[bon]
impl VListElemAndShift {
    /// Creates a new VListElemAndShift
    #[builder]
    pub const fn new(
        /// Element for vertical list
        elem: HtmlDomNode,
        /// Shift amount
        shift: f64,
        /// Optional left margin
        margin_left: Option<String>,
        /// Optional right margin
        margin_right: Option<String>,
        /// Optional wrapper classes
        wrapper_classes: Option<ClassList>,
        /// Optional wrapper style
        wrapper_style: Option<CssStyle>,
    ) -> Self {
        Self {
            elem,
            shift,
            margin_left,
            margin_right,
            wrapper_classes,
            wrapper_style,
        }
    }
}

/// Parameters for make_v_list function
#[derive(Debug)]
pub enum VListParam {
    /// Individual shift positioning
    IndividualShift {
        /// The children elements with individual shifts
        children: Vec<VListElemAndShift>,
    },
    /// Top positioning
    Top {
        /// The position data for top alignment
        position_data: f64,
        /// The child elements
        children: Vec<VListChild>,
    },
    /// Bottom positioning
    Bottom {
        /// The position data for bottom alignment
        position_data: f64,
        /// The child elements
        children: Vec<VListChild>,
    },
    /// Shift positioning
    Shift {
        /// The position data for shift alignment
        position_data: f64,
        /// The child elements
        children: Vec<VListChild>,
    },
    /// First baseline positioning
    FirstBaseline {
        /// The child elements
        children: Vec<VListChild>,
    },
}

/// Result of get_v_list_children_and_depth function
#[derive(Debug)]
pub struct VListChildrenAndDepth {
    /// The processed children
    pub children: Vec<VListChild>,
    /// The calculated depth
    pub depth: f64,
}

/// Compute height, depth, and max_font_size of an element based on its children
fn size_element_from_children_dom(node: &mut DomSpan) {
    let (height, depth, max_font_size) = size_properties(&node.children);

    node.height = height;
    node.depth = depth;
    node.max_font_size = max_font_size;
}

/// Create a span with given classes and options
#[must_use]
pub fn make_span<T: Into<ClassList>>(
    classes: T,
    children: Vec<HtmlDomNode>,
    options: Option<&Options>,
    style: Option<CssStyle>,
) -> DomSpan {
    let classes = classes.into();
    // `Span::builder` offers a flexible construction API but it also ends up
    // allocating intermediate buffers on every invocation. The vast majority of
    // `make_span` calls populate just a handful of fields, so we build the span
    // directly instead of going through the builder. This trims a noticeable
    // amount of per-node work in tight rendering loops.

    let mut node = Span::from_parts(children, classes, style, options);

    // Compute height, depth, and max_font_size from children
    size_element_from_children_dom(&mut node);

    node
}

/// Makes a vertical list by stacking elements and kerns on top of each other
/// with complete KaTeX logic including pstrut creation, table layout, and
/// styling
pub fn make_v_list(params: VListParam, _options: &Options) -> Result<DomSpan, ParseError> {
    let VListChildrenAndDepth { children, depth } = get_v_list_children_and_depth(params)?;

    // Create pstrut: a phantom strut taller than any list item
    // This ensures precise baseline positioning without font ascent/line-height
    // interference
    let mut pstrut_size = 0.0f64;
    for child in &children {
        if let VListChild::Elem(elem) = child {
            pstrut_size = pstrut_size
                .max(elem.elem.max_font_size())
                .max(elem.elem.height());
        }
    }
    pstrut_size += 2.0; // Add buffer for safety
    let mut pstrut = make_span("pstrut", vec![], None, None);
    pstrut
        .style
        .insert(CssProperty::Height, make_em(pstrut_size));

    // Process children and calculate positioning
    let mut real_children: Vec<HtmlDomNode> = Vec::new();
    let mut min_pos = depth;
    let mut max_pos = depth;
    let mut curr_pos = depth;

    for child in children {
        match child {
            VListChild::Kern(kern) => {
                curr_pos += kern.size;
            }
            VListChild::Elem(child) => {
                let elem = child.elem;
                let classes = child.wrapper_classes.unwrap_or_default();
                let style = child.wrapper_style.unwrap_or_default();

                let elem_height = elem.height();
                let elem_depth = elem.depth();

                // Create wrapper span with pstrut and element
                let mut child_wrap = make_span(
                    classes,
                    vec![pstrut.clone().into(), elem],
                    None,
                    Some(style),
                );

                // Set top positioning for vertical alignment
                child_wrap.style.insert(
                    CssProperty::Top,
                    make_em(-pstrut_size - curr_pos - elem_depth),
                );

                // Apply margins if specified
                if let Some(margin_left) = &child.margin_left {
                    child_wrap
                        .style
                        .insert(CssProperty::MarginLeft, margin_left.clone());
                }
                if let Some(margin_right) = &child.margin_right {
                    child_wrap
                        .style
                        .insert(CssProperty::MarginRight, margin_right.clone());
                }

                real_children.push(child_wrap.into());
                curr_pos += elem_height + elem_depth;
            }
        }
        min_pos = min_pos.min(curr_pos);
        max_pos = max_pos.max(curr_pos);
    }

    // Create the main vlist cell with vertical-align: bottom
    let mut vlist = make_span("vlist", real_children, None, None);
    vlist.style.insert(CssProperty::Height, make_em(max_pos));

    // Handle depth with multiple rows when needed
    let rows: Vec<HtmlDomNode> = if min_pos < 0.0 {
        // Create depth row with proper height
        let empty_span = make_span(ClassList::Empty, vec![], None, None);
        let mut depth_strut = make_span("vlist", vec![empty_span.into()], None, None);
        depth_strut
            .style
            .insert(CssProperty::Height, make_em(-min_pos));

        // Create top row with zero-width space for Safari compatibility
        let top_strut = make_span(
            "vlist-s",
            vec![HtmlDomNode::Symbol(
                SymbolNode::builder().text("\u{200b}").build(),
            )],
            None,
            None,
        );

        vec![
            make_span("vlist-r", vec![vlist.into(), top_strut.into()], None, None).into(),
            make_span("vlist-r", vec![depth_strut.into()], None, None).into(),
        ]
    } else {
        vec![make_span("vlist-r", vec![vlist.into()], None, None).into()]
    };

    // Add vlist-t2 class if depth row is present
    let vtable_classes = if rows.len() == 2 {
        ClassList::Const(&["vlist-t", "vlist-t2"])
    } else {
        ClassList::Const(&["vlist-t"])
    };

    // Create the table structure with vlist-t class
    let mut vtable = make_span(vtable_classes, rows, None, None);

    // Set final height and depth on the table
    vtable.height = max_pos;
    vtable.depth = -min_pos;

    Ok(vtable)
}

/// Computes the updated children list and the overall depth for vertical lists.
///
/// This helper function for make_v_list makes it easier to enforce type safety
/// by allowing early exits (returns) in the logic.
pub fn get_v_list_children_and_depth(
    params: VListParam,
) -> Result<VListChildrenAndDepth, ParseError> {
    match params {
        VListParam::IndividualShift {
            children: old_children,
        } => {
            let mut iter = old_children.into_iter();
            let Some(first_child) = iter.next() else {
                return Ok(VListChildrenAndDepth {
                    children: Vec::new(),
                    depth: 0.0,
                });
            };

            let VListElemAndShift {
                elem,
                shift,
                margin_left,
                margin_right,
                wrapper_classes,
                wrapper_style,
            } = first_child;

            let elem_height = elem.height();
            let elem_depth = elem.depth();
            let depth = -shift - elem_depth;
            let mut curr_pos = depth;
            let mut prev_height = elem_height;
            let mut prev_depth = elem_depth;

            let mut children: Vec<VListChild> = Vec::new();
            children.push(
                VListElem {
                    elem,
                    shift: Some(shift),
                    margin_left,
                    margin_right,
                    wrapper_classes,
                    wrapper_style,
                }
                .into(),
            );

            // Add in kerns to the list of children to get each element to be
            // shifted to the correct specified shift
            for child in iter {
                let VListElemAndShift {
                    elem,
                    shift,
                    margin_left,
                    margin_right,
                    wrapper_classes,
                    wrapper_style,
                } = child;

                let elem_height = elem.height();
                let elem_depth = elem.depth();
                let diff = -shift - curr_pos - elem_depth;
                let size = diff - (prev_height + prev_depth);

                curr_pos += diff;

                children.push(VListChild::Kern(VListKern { size }));
                children.push(
                    VListElem {
                        elem,
                        shift: Some(shift),
                        margin_left,
                        margin_right,
                        wrapper_classes,
                        wrapper_style,
                    }
                    .into(),
                );

                prev_height = elem_height;
                prev_depth = elem_depth;
            }

            Ok(VListChildrenAndDepth { children, depth })
        }
        VListParam::Top {
            position_data,
            children: vlist_children,
        } => {
            // We always start at the bottom, so calculate the bottom by adding up
            // all the sizes
            let mut bottom = position_data;
            for child in &vlist_children {
                bottom -= match child {
                    VListChild::Kern(kern) => kern.size,
                    VListChild::Elem(elem) => elem.elem.height() + elem.elem.depth(),
                };
            }
            let depth = bottom;
            Ok(VListChildrenAndDepth {
                children: vlist_children,
                depth,
            })
        }
        VListParam::Bottom {
            position_data,
            children: vlist_children,
        } => {
            let depth = -position_data;
            Ok(VListChildrenAndDepth {
                children: vlist_children,
                depth,
            })
        }
        VListParam::Shift {
            position_data,
            children: vlist_children,
        } => {
            // Find the first Elem child to calculate depth
            let first_elem = vlist_children.iter().find_map(|child| {
                if let VListChild::Elem(elem) = child {
                    Some(elem)
                } else {
                    None
                }
            });

            let depth = first_elem
                .map_or_else(|| -position_data, |elem| -elem.elem.depth() - position_data);

            Ok(VListChildrenAndDepth {
                children: vlist_children,
                depth,
            })
        }
        VListParam::FirstBaseline {
            children: vlist_children,
        } => {
            // Find the first Elem child to calculate depth
            let first_elem = vlist_children.iter().find_map(|child| {
                if let VListChild::Elem(elem) = child {
                    Some(elem)
                } else {
                    None
                }
            });

            let depth = first_elem.map_or(0.0, |elem| -elem.elem.depth());

            Ok(VListChildrenAndDepth {
                children: vlist_children,
                depth,
            })
        }
    }
}

/// Looks up the given symbol in font metrics, after applying any symbol
/// replacements
pub fn lookup_symbol(
    ctx: &KatexContext,
    value: &str,
    font_name: &str,
    mode: Mode,
) -> Result<Option<SymbolLookup>, ParseError> {
    let query = if let Some(char_info) = ctx.symbols.get(mode, value)
        && let Some(replaced) = char_info.replace
    {
        replaced
    } else {
        value
            .chars()
            .next()
            .ok_or_else(|| ParseError::new(ParseErrorKind::EmptyLookupSymbolInput))?
    };

    let metrics = get_character_metrics(ctx, query, font_name, mode)?;
    Ok(Some(SymbolLookup {
        value: query,
        metrics: metrics.copied(),
    }))
}

/// Makes a symbol node after translation via the list of symbols
pub fn make_symbol(
    ctx: &KatexContext,
    value: &str,
    font_name: &str,
    mode: Mode,
    options: Option<&Options>,
    classes: ClassList,
) -> Result<SymbolNode, ParseError> {
    let (metrics, value) = lookup_symbol(ctx, value, font_name, mode)?.map_or_else(
        || (None, value.to_owned()),
        |lookup| (lookup.metrics, lookup.value.to_string()),
    );

    let (height, depth, italic, skew, width) = metrics.map_or((0.0, 0.0, 0.0, 0.0, 0.0), |m| {
        let italic = if mode == Mode::Text || options.as_ref().is_some_and(|o| o.font == "mathit") {
            0.0
        } else {
            m.italic
        };

        (m.height, m.depth, italic, m.skew, m.width)
    });

    let mut classes_vec = classes;
    let mut style = CssStyle::with_capacity(2);

    if let Some(options) = options {
        if options.style.is_tight() {
            classes_vec.push("mtight");
        }
        if let Some(color) = options.get_color() {
            style.insert(CssProperty::Color, color);
        }
    }

    let mut symbol = SymbolNode::builder()
        .text(&value)
        .height(height)
        .depth(depth)
        .italic(italic)
        .skew(skew)
        .width(width)
        .classes(classes_vec)
        .style(style)
        .build();

    if let Some(options) = options {
        symbol.max_font_size = options.size_multiplier;
    }
    Ok(symbol)
}

/// Makes a symbol in Main-Regular or AMS-Regular for operators
pub fn mathsym(
    ctx: &KatexContext,
    value: &str,
    mode: Mode,
    options: &Options,
    classes: ClassList,
) -> Result<SymbolNode, ParseError> {
    if options.font == "boldsymbol"
        && lookup_symbol(ctx, value, "Main-Bold", mode)?
            .is_some_and(|lookup| lookup.metrics.is_some())
    {
        let mut combined_classes = classes;
        combined_classes.push("mathbf");
        make_symbol(
            ctx,
            value,
            "Main-Bold",
            mode,
            Some(options),
            combined_classes,
        )
    } else if value == "\\"
        || ctx
            .symbols
            .get(mode, value)
            .is_some_and(|info| matches!(info.font, Font::Main))
    {
        make_symbol(ctx, value, "Main-Regular", mode, Some(options), classes)
    } else {
        let mut combined_classes = classes;
        combined_classes.push("amsrm");
        make_symbol(
            ctx,
            value,
            "AMS-Regular",
            mode,
            Some(options),
            combined_classes,
        )
    }
}

/// Takes font options, and returns the appropriate font lookup name
#[must_use]
pub fn retrieve_text_font_name(
    font_family: &str,
    font_weight: &FontWeight,
    font_shape: &FontShape,
) -> String {
    let base_font_name = match font_family {
        "amsrm" => "AMS",
        "textrm" => "Main",
        "textsf" => "SansSerif",
        "texttt" => "Typewriter",
        _ => font_family,
    };

    let font_styles_name = match (font_weight, font_shape) {
        (FontWeight::TextBf, FontShape::TextIt) => "BoldItalic",
        (FontWeight::TextBf, _) => "Bold",
        (_, FontShape::TextIt) => "Italic",
        _ => "Regular",
    };

    format!("{base_font_name}-{font_styles_name}")
}

#[inline]
fn both_single_same_mbin_or_mord(a: &ClassList, b: &ClassList) -> bool {
    let mut a_iter = a.into_iter();
    let mut b_iter = b.into_iter();
    matches!((a_iter.next(), b_iter.next()), (Some("mbin"), Some("mbin")) | (Some("mord"), Some("mord")) if a_iter.next().is_none() && b_iter.next().is_none())
}

#[inline]
fn can_combine_symbols(prev: &SymbolNode, next: &SymbolNode) -> bool {
    if both_single_same_mbin_or_mord(&prev.classes, &next.classes) {
        return false;
    }
    if prev.skew != next.skew || prev.max_font_size != next.max_font_size {
        return false;
    }

    if prev.classes != next.classes {
        return false;
    }

    prev.style == next.style
}

/// Push a node into the vector, merging it into the previous symbol when
/// possible.
#[inline]
pub fn push_combine_chars(chars: &mut Vec<HtmlDomNode>, node: HtmlDomNode) {
    match node {
        HtmlDomNode::Symbol(next_sym) => {
            if let Some(HtmlDomNode::Symbol(prev_sym)) = chars.last_mut()
                && can_combine_symbols(prev_sym, &next_sym)
            {
                prev_sym.height = prev_sym.height.max(next_sym.height);
                prev_sym.depth = prev_sym.depth.max(next_sym.depth);
                prev_sym.italic = next_sym.italic;
                prev_sym.text.push_str(&next_sym.text);
            } else {
                chars.push(HtmlDomNode::Symbol(next_sym));
            }
        }
        other => chars.push(other),
    }
}

impl KatexContext {
    /// Create a glue (spacing) node with proper unit conversion
    ///
    /// This method creates a spacing element that matches KaTeX's behavior,
    /// properly converting measurements to CSS ems using the context's
    /// calculate_size method.
    pub fn make_glue<T>(
        &self,
        measurement: &Measurement<T>,
        options: &Options,
    ) -> Result<DomSpan, ParseError>
    where
        T: AsRef<str>,
    {
        // Calculate the size using proper unit conversion
        let mut rule = make_span("mspace", vec![], Some(options), None);
        let size = self.calculate_size(measurement, options)?;
        rule.style.insert(CssProperty::MarginRight, make_em(size));
        Ok(rule)
    }
}

/// Makes either a mathord or textord in the correct font and color.
/// Corresponds to the JavaScript `makeOrd` function.
pub fn make_ord(
    ctx: &KatexContext,
    node: &AnyParseNode,
    options: &Options,
) -> Result<HtmlDomNode, ParseError> {
    // Extract mode and text from the node
    let (mode, text, ord_type) = match node {
        AnyParseNode::MathOrd(math_ord) => (math_ord.mode, &math_ord.text, Mode::Math),
        AnyParseNode::TextOrd(text_ord) => (text_ord.mode, &text_ord.text, Mode::Text),
        // Spacing use TextOrd type by default
        AnyParseNode::Spacing(spacing) => (spacing.mode, &spacing.text, Mode::Text),
        _ => {
            return Err(ParseError::new(ParseErrorKind::MakeOrdExpectedNode));
        }
    };

    let classes = ClassList::Static("mord");

    // Math mode or Old font (i.e. \rm)
    let is_font = mode == Mode::Math || (mode == Mode::Text && !options.font.is_empty());
    let font_or_family = if is_font {
        if options.font.is_empty() {
            None
        } else {
            Some(&options.font)
        }
    } else if options.font_family.is_empty() {
        None
    } else {
        Some(&options.font_family)
    };

    // Handle wide characters
    let mut utf16_iter = text.encode_utf16();
    if let Some(code_unit) = utf16_iter.next()
        && code_unit == 0xD835
        && let Ok((font_name, font_class)) = get_wide_character_font(text, mode)
        && !font_name.is_empty()
    {
        let mut combined_classes = classes;
        if !font_class.is_empty() {
            combined_classes.push(font_class);
        }
        return Ok(
            make_symbol(ctx, text, font_name, mode, Some(options), combined_classes)?.into(),
        );
    }

    // Handle font selection
    if let Some(font_or_family) = font_or_family {
        let (font_name, font_classes) = if font_or_family == "boldsymbol" {
            // Special handling for boldsymbol
            let font_data = bold_symbol(ctx, text, mode, ord_type)?;
            (font_data.font_name, vec![Cow::Owned(font_data.font_class)])
        } else if is_font {
            // Font command like \mathbf
            let font_name: &str = FONT_MAP
                .get(font_or_family)
                .map_or(font_or_family, |entry| entry.font_name);
            (
                font_name.to_owned(),
                vec![Cow::Owned(font_or_family.clone())],
            )
        } else {
            // Font family like \textrm
            let font_name =
                retrieve_text_font_name(font_or_family, &options.font_weight, &options.font_shape);
            (
                font_name,
                vec![
                    Cow::Owned(font_or_family.clone()),
                    Cow::Borrowed(options.font_weight.as_str()),
                    Cow::Borrowed(options.font_shape.as_str()),
                ],
            )
        };

        if lookup_symbol(ctx, text, &font_name, mode)?
            .is_some_and(|lookup| lookup.metrics.is_some())
        {
            let mut combined_classes = classes;
            combined_classes.extend(font_classes);
            return Ok(
                make_symbol(ctx, text, &font_name, mode, Some(options), combined_classes)?.into(),
            );
        }

        // Handle ligature decomposition for monospace fonts
        if font_name.starts_with("Typewriter") && is_ligature(text) {
            let mut base_classes = classes;
            base_classes.extend(font_classes);

            let mut parts = Vec::new();
            for ch in text.chars() {
                let char_str = ch.to_string();
                let symbol = make_symbol(
                    ctx,
                    &char_str,
                    &font_name,
                    mode,
                    Some(options),
                    base_classes.clone(),
                )?;
                parts.push(symbol.into());
            }
            return Ok(make_fragment(parts).into());
        }
    }

    // Default font handling
    match ord_type {
        Mode::Math => {
            let mut combined_classes = classes;
            combined_classes.push("mathnormal");
            Ok(make_symbol(
                ctx,
                text,
                "Math-Italic",
                mode,
                Some(options),
                combined_classes,
            )?
            .into())
        }
        Mode::Text => {
            // Check symbol table for font information
            let symbol_info = ctx.symbols.get(mode, text);
            if let Some(info) = symbol_info {
                match &info.font {
                    Font::Ams => {
                        let font_name = retrieve_text_font_name(
                            "amsrm",
                            &options.font_weight,
                            &options.font_shape,
                        );
                        let mut combined_classes = classes;
                        combined_classes.push("amsrm");
                        combined_classes.push(options.font_weight.as_str());
                        combined_classes.push(options.font_shape.as_str());
                        Ok(make_symbol(
                            ctx,
                            text,
                            &font_name,
                            mode,
                            Some(options),
                            combined_classes,
                        )?
                        .into())
                    }
                    Font::Main => {
                        let font_name = retrieve_text_font_name(
                            "textrm",
                            &options.font_weight,
                            &options.font_shape,
                        );
                        let mut combined_classes = classes;
                        combined_classes.push(options.font_weight.as_str());
                        combined_classes.push(options.font_shape.as_str());
                        Ok(make_symbol(
                            ctx,
                            text,
                            &font_name,
                            mode,
                            Some(options),
                            combined_classes,
                        )?
                        .into())
                    }
                    Font::Custom(font) => {
                        let font_name = retrieve_text_font_name(
                            font,
                            &options.font_weight,
                            &options.font_shape,
                        );
                        let mut combined_classes = classes;
                        combined_classes.push(options.font_weight.as_str());
                        combined_classes.push(options.font_shape.as_str());
                        Ok(make_symbol(
                            ctx,
                            text,
                            &font_name,
                            mode,
                            Some(options),
                            combined_classes,
                        )?
                        .into())
                    }
                }
            } else {
                // Default to main font
                let font_name =
                    retrieve_text_font_name("textrm", &options.font_weight, &options.font_shape);
                let mut combined_classes = classes;
                combined_classes.push(options.font_weight.as_str());
                combined_classes.push(options.font_shape.as_str());
                Ok(
                    make_symbol(ctx, text, &font_name, mode, Some(options), combined_classes)?
                        .into(),
                )
            }
        }
    }
}

/// Create an SVG span with given classes and SvgNode
pub fn make_svg_span<T: Into<ClassList>>(
    classes: T,
    svg_node: Vec<SvgNode>,
    options: &Options,
) -> DomSpan {
    Span::builder()
        .children(svg_node.into_iter().map(HtmlDomNode::SvgNode).collect())
        .classes(classes.into())
        .build(Some(options))
}

/// W/H of vec
pub const VEC_SVG_DATA: (f64, f64) = (0.471, 0.714);
/// W/H of oiint1
pub const OIINT_SIZE1: (f64, f64) = (0.957, 0.499);
/// W/H of oiint2
pub const OIINT_SIZE2: (f64, f64) = (1.472, 0.659);
/// W/H of oiiint1
pub const OIIINT_SIZE1: (f64, f64) = (1.304, 0.499);
/// W/H of oiiint2
pub const OIIINT_SIZE2: (f64, f64) = (1.98, 0.659);

/// SVG data for static SVG elements
///
/// Equivalent to KaTeX buildCommon.js svgData
/// However, the values slightly differ because they are based on phf_map!
/// Values are `path` => (width, height)
const SVG_DATA: phf::Map<&'static str, (f64, f64)> = phf_map! {
    // values from the font glyph
    "vec" => VEC_SVG_DATA,
    // oval to overlay the integrand
    "oiintSize1" => OIINT_SIZE1,
    "oiintSize2" => OIINT_SIZE2,
    "oiiintSize1" => OIIINT_SIZE1,
    "oiiintSize2" => OIIINT_SIZE2,
};

/// Creates a static SVG span for elements like vec
pub fn static_svg(path_name: &str, options: &Options) -> Result<DomSpan, ParseError> {
    if let Some((width, height)) = SVG_DATA.get(path_name) {
        use crate::build_common::make_svg_span;
        use crate::dom_tree::{PathNode, SvgChildNode};

        let path = PathNode {
            path_name: path_name.to_owned(),
            alternate: None,
        };
        let svg_attributes = [
            ("width".to_owned(), make_em(*width)),
            ("height".to_owned(), make_em(*height)),
            // Override CSS rule `.katex svg { width: 100% }`
            ("style".to_owned(), format!("width:{}", make_em(*width))),
            (
                "viewBox".to_owned(),
                format!("0 0 {} {}", 1000.0 * width, 1000.0 * height),
            ),
            ("preserveAspectRatio".to_owned(), "xMinYMin".to_owned()),
        ]
        .iter()
        .cloned()
        .collect();

        let svg_node = SvgNode::builder()
            .children(vec![SvgChildNode::Path(path)])
            .attributes(svg_attributes)
            .build();
        let mut span = make_svg_span("overlay", vec![svg_node], options);
        span.height = *height;
        span.style.insert(CssProperty::Height, make_em(*height));
        span.style.insert(CssProperty::Width, make_em(*width));
        Ok(span)
    } else {
        // Fallback
        use crate::build_common::make_span;
        Ok(make_span(ClassList::Empty, vec![], Some(options), None))
    }
}

/// Result of boldsymbol font selection
#[derive(Debug)]
struct FontData {
    font_name: String,
    font_class: String,
}

/// Determines which font to use for boldsymbol
fn bold_symbol(
    ctx: &KatexContext,
    text: &str,
    mode: Mode,
    ord_type: Mode,
) -> Result<FontData, ParseError> {
    if ord_type != Mode::Text
        && lookup_symbol(ctx, text, "Math-BoldItalic", mode)?
            .is_some_and(|lookup| lookup.metrics.is_some())
    {
        Ok(FontData {
            font_name: "Math-BoldItalic".to_owned(),
            font_class: "boldsymbol".to_owned(),
        })
    } else {
        // Some glyphs do not exist in Math-BoldItalic so we need to use
        // Main-Bold instead.
        Ok(FontData {
            font_name: "Main-Bold".to_owned(),
            font_class: "mathbf".to_owned(),
        })
    }
}

/// Makes a line span with the given className, options, and thickness
///
/// Creates a span element designed to represent a horizontal line (rule) in
/// mathematical expressions. The line's height is determined by the thickness
/// parameter or falls back to the font's default rule thickness, with a minimum
/// of the minimum rule thickness.
///
/// This function corresponds to the JavaScript `makeLineSpan` function in
/// buildCommon.js.
///
/// # Arguments
/// * `class_name` - CSS class name to apply to the line span
/// * `options` - KaTeX options containing font metrics and styling information
/// * `thickness` - Optional thickness of the line in em units. If None, uses
///   default rule thickness
///
/// # Returns
/// A DomSpan configured as a horizontal line element
#[must_use]
pub fn make_line_span(
    class_name: &'static str,
    options: &Options,
    thickness: Option<f64>,
) -> DomSpan {
    let mut line = make_span(class_name, vec![], Some(options), None);

    // Calculate line height: use thickness, or default rule thickness, with minimum
    // threshold
    let default_thickness = options.font_metrics().default_rule_thickness;
    let line_thickness = thickness.unwrap_or(default_thickness);
    line.height = line_thickness.max(options.min_rule_thickness);

    // Set border-bottom-width style to create the visual line
    line.style
        .insert(CssProperty::BorderBottomWidth, make_em(line.height));

    // Set maximum font size to 1.0 for consistent sizing
    line.max_font_size = 1.0;

    line
}

/// Makes an anchor element with the given href, classes, children, and options
///
/// Creates an HTML anchor (`<a>`) element that can contain other DOM nodes as
/// children. The anchor's size properties (height, depth, maxFontSize) are
/// automatically calculated based on its children.
///
/// This function corresponds to the JavaScript `makeAnchor` function in
/// buildCommon.js.
///
/// # Arguments
/// * `href` - URL or reference for the anchor's href attribute
/// * `classes` - CSS classes to apply to the anchor
/// * `children` - Child DOM nodes to be contained within the anchor
/// * `options` - KaTeX options for styling and configuration
///
/// # Returns
/// An Anchor element properly sized based on its children
#[must_use]
pub fn make_anchor<T: Into<ClassList>>(
    href: &str,
    classes: T,
    children: Vec<HtmlDomNode>,
    options: &Options,
) -> Anchor {
    // Create attributes map with href
    let mut attributes = KeyMap::default();
    attributes.insert("href".to_owned(), href.to_owned());

    let mut anchor = Anchor::builder()
        .children(children)
        .attributes(attributes)
        .classes(classes.into())
        .height(0.0)
        .depth(0.0)
        .max_font_size(options.size_multiplier)
        .build(Some(options));

    // Calculate size properties based on children
    let (height, depth, max_font_size) = size_properties(&anchor.children);
    anchor.height = height;
    anchor.depth = depth;
    anchor.max_font_size = max_font_size;

    anchor
}

/// Makes a document fragment with the given list of children
///
/// Creates an HTML document fragment that can contain multiple DOM nodes
/// without creating a wrapper element. The fragment's size properties are
/// automatically calculated based on its children.
///
/// This function corresponds to the JavaScript `makeFragment` function in
/// buildCommon.js.
///
/// # Arguments
/// * `children` - Child DOM nodes to be contained within the fragment
///
/// # Returns
/// An HtmlDocumentFragment properly sized based on its children
#[must_use]
pub fn make_fragment(children: Vec<HtmlDomNode>) -> HtmlDomFragment {
    let mut fragment = DocumentFragment::new(children);

    // Calculate size properties based on children
    let (height, depth, max_font_size) = size_properties(&fragment.children);
    fragment.height = height;
    fragment.depth = depth;
    fragment.max_font_size = max_font_size;

    fragment
}

/// Wraps a group in a span if it's a document fragment
///
/// If the input node is a DocumentFragment, wraps it in a span to allow classes
/// and styles to be applied. Otherwise, returns the node unchanged.
///
/// This function corresponds to the JavaScript `wrapFragment` function in
/// buildCommon.js.
///
/// # Arguments
/// * `group` - The DOM node that might need wrapping
/// * `options` - KaTeX options for styling the wrapper span if needed
///
/// # Returns
/// Either the original node (if not a fragment) or a span containing the
/// fragment
#[must_use]
pub fn wrap_fragment(group: HtmlDomNode, options: &Options) -> HtmlDomNode {
    match group {
        HtmlDomNode::Fragment(fragment) => {
            // Wrap the fragment in a span
            let span = make_span(
                ClassList::Empty,
                vec![HtmlDomNode::Fragment(fragment)],
                Some(options),
                None,
            );
            HtmlDomNode::DomSpan(span)
        }
        _ => group, // Return the node unchanged if it's not a fragment
    }
}

fn size_properties(children: &[HtmlDomNode]) -> (f64, f64, f64) {
    let mut height = 0.0;
    let mut depth = 0.0;
    let mut max_font_size = 0.0;

    for child in children {
        if child.height() > height {
            height = child.height();
        }
        if child.depth() > depth {
            depth = child.depth();
        }
        if child.max_font_size() > max_font_size {
            max_font_size = child.max_font_size();
        }
    }

    (height, depth, max_font_size)
}