math-core 0.8.1

Convert LaTeX equations to MathML Core
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
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
use insta::assert_snapshot;
use math_core::{LatexToMathML, MathCoreConfig, MathDisplay, MaxExpansions, PrettyPrint};

#[test]
fn test_zero_arg() {
    let macros = vec![
        ("half".to_string(), r"\frac{1}{2}".to_string()),
        ("mycmd".to_string(), r"\sqrt{3}".to_string()),
        ("withText".to_string(), r"\text{a b}\sum".to_string()),
    ];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"x = \half, \withText 3";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("custom_cmd_zero_arg", mathml.mathml, latex);
}

#[test]
fn test_one_arg() {
    let macros = vec![
        ("half".to_string(), r"\frac{1}{2}\mspace{3mu}".to_string()),
        (
            "mycmd".to_string(),
            r"\begin{array}{c|c}#1 & 0\end{array}".to_string(),
        ),
    ];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"x = \mycmd{3} + \half";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("custom_cmd_one_arg", mathml.mathml, latex);
}

#[test]
fn test_error() {
    let macros = vec![
        ("x".to_string(), "x".to_string()),
        ("mycmd".to_string(), r"\sqrt{#}".to_string()),
    ];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let error = LatexToMathML::new(config).unwrap_err();

    assert_eq!(error.1, 1);
    assert_eq!(error.2, r"\sqrt{#}");
}

#[test]
fn test_spacing() {
    let macros = vec![("eq".to_string(), r"=".to_string())];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"x + \eq 3";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("custom_cmd_spacing", mathml.mathml, latex);
}

#[test]
fn test_empty_args() {
    let macros = vec![
        (
            "odv".to_string(),
            r"\frac{\mathrm d #1}{\mathrm d #2}".to_string(),
        ),
        ("bb".to_string(), r"\mathbb{#1}".to_string()),
        ("two".to_string(), r"#1+#2".to_string()),
    ];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        ("empty_first_arg", r"\odv{}{x}"),
        ("empty_second_arg", r"\odv{y}{}"),
        ("empty_only_arg", r"\bb{}"),
        ("empty_arg_at_stream_end", r"\two{a}{}"),
        ("empty_arg_at_stream_start", r"\two{}{b}"),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap();

        assert_snapshot!(name, mathml.mathml, latex);
    }
}

#[test]
fn test_literal_args() {
    let macros = vec![("hs".to_string(), r"\hspace{#1}".to_string())];

    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };

    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"x \hs{3em} y";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("custom_cmd_literal_args", mathml.mathml, latex);
}

#[test]
fn test_newcommand() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        (
            "newcommand_one_arg",
            r"\newcommand{\bb}[1]{\mathbb{#1}}\bb{C}",
        ),
        (
            "newcommand_zero_args",
            r"\newcommand{\zz}{\mathbb{Z}}x \in \zz",
        ),
        (
            "newcommand_two_args",
            r"\newcommand{\pair}[2]{(#1, #2)}\pair{x}{y}",
        ),
        // Without braces around the name, as `\newcommand` also allows.
        (
            "newcommand_unbraced_name",
            r"\newcommand\half{\frac{1}{2}}\half",
        ),
        // A predefined command which is itself a token stream.
        (
            "newcommand_predefined_cmd_in_body",
            r"\newcommand{\imp}{\implies}a \imp b",
        ),
        // A command defined by an earlier `\newcommand`, with an argument, which is the
        // case where the arguments of the two commands could clobber each other.
        (
            "newcommand_nested_cmd_in_body",
            r"\newcommand{\br}[1]{[#1]}\newcommand{\dbr}[1]{\br{\br{#1}}}\dbr{z}",
        ),
        // A command which takes an argument, followed by a reference to the argument of the
        // command being expanded. The inner command must not consume the outer argument.
        (
            "newcommand_arg_after_nested_cmd",
            r"\newcommand{\zoo}[1]{\ket{a}#1}\zoo{b}",
        ),
        // The same, but with the argument reference inside the nested command as well, and
        // with the two arguments in the opposite order.
        (
            "newcommand_arg_in_and_after_nested_cmd",
            r"\newcommand{\zoo}[2]{\ket{#2}#1}\zoo{b}{c}",
        ),
        // A predefined command which takes an argument, in the same position.
        (
            "newcommand_arg_after_predefined_cmd",
            r"\newcommand{\zoo}[1]{\pod{a}#1}\zoo{b}",
        ),
        // `\text` rejects anything that isn't a text-mode token, so an argument reference
        // inside it only works because the argument is substituted before `\text` sees it.
        (
            "newcommand_arg_in_text",
            r"\newcommand{\txt}[1]{\text{a#1b}}\txt{xy}",
        ),
        // A body which is empty expands to `\relax`, and must not swallow what comes after
        // it. The `\relax` still shows up as an empty row here, because the first token of
        // an expansion goes through `parse_token` rather than through the sequence handling
        // which drops a `\relax`.
        ("newcommand_empty_body", r"\newcommand{\nop}{}a\nop b"),
        // The same command as an argument, where it has to produce an empty group.
        ("newcommand_empty_body_as_arg", r"\newcommand{\nop}{}x^\nop"),
        // An empty argument is equivalent to `{}`, so it still counts as an argument for the
        // construct it is substituted into.
        (
            "newcommand_empty_arg_as_group",
            r"\newcommand{\p}[1]{x^#1}\p{}",
        ),
        // The class of the body determines the spacing, as it does for config macros.
        ("newcommand_spacing", r"\newcommand{\eq}{=}x + \eq 3"),
        (
            "newcommand_empty_arg",
            r"\newcommand{\bb}[1]{\mathbb{#1}}\bb{}",
        ),
        // `\mathchoice` must not clobber the arguments of the command it appears in, neither
        // when it comes before the argument reference nor when it contains one itself.
        (
            "newcommand_mathchoice_in_body",
            r"\newcommand{\mc}[1]{\mathchoice{D}{T}{S}{SS}#1\mathchoice{#1}{[#1]}{#1}{#1}}\mc{z}",
        ),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

#[test]
fn test_providecommand() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        // For a name which isn't taken, `\providecommand` behaves like `\newcommand`.
        (
            "providecommand_zero_args",
            r"\providecommand{\zz}{\mathbb{Z}}x \in \zz",
        ),
        (
            "providecommand_one_arg",
            r"\providecommand{\bb}[1]{\mathbb{#1}}\bb{C}",
        ),
        (
            "providecommand_unbraced_name",
            r"\providecommand\half{\frac{1}{2}}\half",
        ),
        // If the name is taken, the existing definition wins and the new one is discarded.
        (
            "providecommand_existing_custom_cmd",
            r"\newcommand{\zz}{\mathbb{Z}}\providecommand{\zz}{\mathbb{Q}}\zz",
        ),
        (
            "providecommand_existing_builtin",
            r"\providecommand{\frac}[2]{#1/#2}\frac{1}{2}",
        ),
        // A discarded definition doesn't stop a later `\newcommand` of the same name.
        (
            "providecommand_then_newcommand",
            r"\providecommand{\alpha}{a}\newcommand{\zz}{\mathbb{Z}}\zz",
        ),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

#[test]
fn test_renewcommand() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        (
            "renewcommand_replaces_newcommand",
            r"\newcommand{\zz}{\mathbb{Z}}\renewcommand{\zz}{\mathbb{Q}}\zz",
        ),
        // The command is used directly after the redefinition, so the token for it has
        // already been read with the old definition in place.
        (
            "renewcommand_used_immediately",
            r"\newcommand{\zz}{\mathbb{Z}}\renewcommand{\zz}{\mathbb{Q}}\zz\zz",
        ),
        // The number of arguments may change, too.
        (
            "renewcommand_changes_num_args",
            r"\newcommand{\bb}{\mathbb{Z}}\renewcommand{\bb}[1]{\mathbb{#1}}\bb{C}",
        ),
        (
            "renewcommand_unbraced_name",
            r"\newcommand\half{\frac{1}{2}}\renewcommand\half{\frac{1}{3}}\half",
        ),
        // A builtin command can be redefined as well.
        (
            "renewcommand_replaces_builtin",
            r"\renewcommand{\epsilon}{\varepsilon}\epsilon",
        ),
        (
            "renewcommand_replaces_builtin_with_args",
            r"\renewcommand{\frac}[2]{#1/#2}\frac{1}{2}",
        ),
        // A body refers to the names it mentions, not to what they meant when it was
        // recorded, so redefining a command does change the commands which use it, as it
        // does in LaTeX.
        (
            "renewcommand_affects_earlier_body",
            r"\newcommand{\xx}{1}\newcommand{\yy}{\xx}\renewcommand{\xx}{2}\yy",
        ),
        // After a `\renewcommand`, `\providecommand` still finds the name taken.
        (
            "renewcommand_then_providecommand",
            r"\renewcommand{\epsilon}{a}\providecommand{\epsilon}{b}\epsilon",
        ),
        // Redefining a command in terms of a command which is *not* the one being redefined
        // is not recursion, even when the two look alike.
        (
            "renewcommand_body_uses_other_command",
            r"\newcommand{\zz}{\mathbb{Z}}\renewcommand{\zz}{(\mathbb{Z})}\zz",
        ),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

/// A command in the body of a `\newcommand` is recorded by name, so it means whatever that
/// name means when the command is expanded, the way it does in LaTeX. This is what config
/// macros have always done; these are the cases where a document definition used to differ.
#[test]
fn test_late_resolution() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        // A builtin which is redefined after the body was recorded.
        (
            "late_resolution_of_builtin",
            r"\newcommand{\foo}{\epsilon}\renewcommand{\epsilon}{e}\foo",
        ),
        // The same, with neither name in braces.
        (
            "late_resolution_unbraced_name",
            r"\newcommand\foo{\epsilon}\renewcommand\epsilon{e}\foo",
        ),
        // A body which isn't a group consists of a single token, which is recorded by name
        // just like the tokens of a group are.
        (
            "late_resolution_unbraced_body",
            r"\newcommand\foo\epsilon\renewcommand\epsilon{e}\foo",
        ),
        // The definition is assembled out of the argument of another command, so its body
        // reaches the queue by substitution rather than straight from the lexer.
        (
            "late_resolution_through_argument",
            r"\newcommand{\m}[1]{x#1}\newcommand{\a}{1}\newcommand{\z}{0}\m{\renewcommand{\z}{\a}}\renewcommand{\a}{2}\z",
        ),
        // `\begin` and `\end` get their meaning in the lexer, which consumes the environment
        // name along with them, so they have no name to be recorded under. `\\` does.
        (
            "late_resolution_env_in_body",
            r"\newcommand{\m}{\begin{matrix}a\\b\end{matrix}}\m",
        ),
        // Two commands with an empty body mean the same thing without being the same command.
        (
            "late_resolution_empty_bodies",
            r"\newcommand{\p}{}\newcommand{\q}{}\newcommand{\pq}{a\p b\q c}\renewcommand{\q}{!}\pq",
        ),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

/// The same, across snippets: the name a body refers to has to outlive the snippet which
/// recorded it, and the redefinition which it picks up comes from a later snippet.
#[test]
fn test_late_resolution_across_snippets() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\newcommand{\foo}{\epsilon}", MathDisplay::Inline)
        .unwrap();
    converter
        .convert_with_global_state(r"\renewcommand{\epsilon}{e}", MathDisplay::Inline)
        .unwrap();
    let mathml = converter
        .convert_with_global_state(r"\foo", MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("late_resolution_across_snippets", mathml.mathml, r"\foo");
}

#[test]
fn test_forward_reference() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        // The body of a command may name a command which doesn't exist yet; the name is
        // resolved when the command is used.
        (
            "forward_reference",
            r"\newcommand{\foo}{x+\baz}\newcommand{\baz}{y}\foo",
        ),
        // The same, with the forward reference inside a nested group and with arguments.
        (
            "forward_reference_with_args",
            r"\newcommand{\foo}[1]{\baz{#1}}\newcommand{\baz}[1]{[#1]}\foo{z}",
        ),
        // A forward reference is resolved every time the command is expanded, so the two uses
        // here get different definitions.
        (
            "forward_reference_resolved_at_use",
            r"\newcommand{\foo}{\baz}\newcommand{\baz}{1}\foo\renewcommand{\baz}{2}\foo",
        ),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }

    // A command which is never defined is an error, but only once it is used.
    converter
        .convert_with_local_state(r"\newcommand{\foo}{x+\baz}", MathDisplay::Inline)
        .unwrap();
    assert!(
        converter
            .convert_with_local_state(r"\newcommand{\foo}{x+\baz}\foo", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_forward_reference_across_snippets() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    // The name which the definition refers to is defined in a later snippet, so the name has
    // to survive the snippet which mentions it.
    converter
        .convert_with_global_state(r"\newcommand{\foo}{x+\baz}", MathDisplay::Inline)
        .unwrap();
    converter
        .convert_with_global_state(r"\newcommand{\baz}{y}", MathDisplay::Inline)
        .unwrap();
    let mathml = converter
        .convert_with_global_state(r"\foo", MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("forward_reference_across_snippets", mathml.mathml, r"\foo");

    // ... but not after the global state has been reset.
    converter.reset_global_state();
    assert!(
        converter
            .convert_with_global_state(r"\foo", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_expansion_limit() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for latex in [
        // Two commands which expand to each other.
        r"\newcommand{\a}{\b}\newcommand{\b}{\a}\a",
        // A command which expands to itself.
        r"\newcommand{\a}{x\a}\a",
        // A `\renewcommand` whose body mentions the command being redefined. The body refers
        // to the new definition, not to the old one, so this recurses, as it does in LaTeX.
        r"\newcommand{\zz}{\mathbb{Z}}\renewcommand{\zz}{(\zz)}\zz",
    ] {
        let Err(err) = converter.convert_with_local_state(latex, MathDisplay::Inline) else {
            panic!("`{latex}` should not have converted");
        };
        assert!(
            err.to_string().contains("Too many expansions"),
            "unexpected error for `{latex}`: {err}"
        );
    }
}

#[test]
fn test_configurable_expansion_limit() {
    // This terminates, but it needs three expansions: `\a`, and then `\b` twice.
    let latex = r"\newcommand{\a}{\b\b}\newcommand{\b}{x}\a";

    let strict = LatexToMathML::new(MathCoreConfig {
        max_expansions: MaxExpansions(2),
        ..Default::default()
    })
    .unwrap();
    let Err(err) = strict.convert_with_local_state(latex, MathDisplay::Inline) else {
        panic!("`{latex}` should not have converted with a limit of 2 expansions");
    };
    assert!(
        err.to_string().contains("Too many expansions"),
        "unexpected error: {err}"
    );

    // With a higher limit, the same input converts fine.
    let lenient = LatexToMathML::new(MathCoreConfig {
        max_expansions: MaxExpansions(100),
        ..Default::default()
    })
    .unwrap();
    assert!(
        lenient
            .convert_with_local_state(latex, MathDisplay::Inline)
            .is_ok()
    );
}

#[test]
fn test_config_macros_referring_to_each_other() {
    let macros = vec![
        // The macro which is defined first refers to the one which is defined later.
        ("half".to_string(), r"\frac{1}{\two}".to_string()),
        ("two".to_string(), r"2".to_string()),
    ];
    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"\half";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!(
        "config_macros_referring_to_each_other",
        mathml.mathml,
        latex
    );
}

#[test]
fn test_config_macro_with_undefined_command() {
    let macros = vec![
        ("half".to_string(), r"\frac{1}{2}".to_string()),
        ("bad".to_string(), r"\frac{1}{\nosuchcommand}".to_string()),
    ];
    let config = MathCoreConfig {
        macros,
        ..Default::default()
    };

    // A name which none of the macros defines is still reported right away.
    let error = LatexToMathML::new(config).unwrap_err();
    assert_eq!(error.1, 1);
    assert_eq!(error.2, r"\frac{1}{\nosuchcommand}");
}

#[test]
fn test_renewcommand_config_macro() {
    let macros = vec![("half".to_string(), r"\frac{1}{2}".to_string())];
    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    // A macro from the configuration can be redefined, ...
    let latex = r"\renewcommand{\half}{\frac{1}{3}}\half";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("renewcommand_replaces_config_macro", mathml.mathml, latex);

    // ... but only for the snippet which does it, because the configuration is immutable.
    let latex = r"\half";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("renewcommand_config_macro_after", mathml.mathml, latex);
}

#[test]
fn test_renewcommand_unreliable_rendering() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        allow_unreliable_rendering: true,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    // Overwrite a command that is only available when `allow_unreliable_rendering` is set.
    let latex = r"\renewcommand{\widecheck}{x}\widecheck";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!(
        "renewcommand_replaces_builtin_unreliable",
        mathml.mathml,
        latex
    );
}

#[test]
fn test_renewcommand_across_snippets() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\newcommand{\zz}{\mathbb{Z}}\zz", MathDisplay::Inline)
        .unwrap();
    // A definition from an earlier snippet can be replaced, ...
    converter
        .convert_with_global_state(r"\renewcommand{\zz}{\mathbb{Q}}", MathDisplay::Inline)
        .unwrap();
    let mathml = converter
        .convert_with_global_state(r"\zz", MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("renewcommand_across_snippets", mathml.mathml, r"\zz");

    // ... but not after the global state has been reset.
    converter.reset_global_state();
    assert!(
        converter
            .convert_with_global_state(r"\renewcommand{\zz}{\mathbb{R}}", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_providecommand_with_config_macro() {
    let macros = vec![("half".to_string(), r"\frac{1}{2}".to_string())];
    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    // A macro from the configuration also counts as already defined.
    let latex = r"\providecommand{\half}{\frac{1}{3}}\half";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("providecommand_existing_config_macro", mathml.mathml, latex);
}

#[test]
fn test_newcommand_uses_config_macro() {
    let macros = vec![("half".to_string(), r"\frac{1}{2}".to_string())];
    let config = MathCoreConfig {
        macros,
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    let latex = r"\newcommand{\halves}[1]{#1\half}\halves{3}";
    let mathml = converter
        .convert_with_local_state(latex, MathDisplay::Inline)
        .unwrap();

    assert_snapshot!("newcommand_uses_config_macro", mathml.mathml, latex);
}

#[test]
fn test_newcommand_across_snippets() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    // The definition in the first snippet is available in the second one.
    converter
        .convert_with_global_state(
            r"\newcommand{\bb}[1]{\mathbb{#1}}\bb{R}",
            MathDisplay::Inline,
        )
        .unwrap();
    let mathml = converter
        .convert_with_global_state(r"\bb{C}", MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("newcommand_across_snippets", mathml.mathml, r"\bb{C}");

    // ... but not after the global state has been reset.
    converter.reset_global_state();
    assert!(
        converter
            .convert_with_global_state(r"\bb{C}", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_newcommand_in_convert_all() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    let results = converter.convert_all(&[
        (r"\newcommand{\zz}{\mathbb{Z}}", MathDisplay::Inline),
        (r"n \in \zz", MathDisplay::Inline),
    ]);
    let mathml = &results[1].as_ref().unwrap().mathml;
    assert_snapshot!("newcommand_in_convert_all", mathml, r"n \in \zz");
}

#[test]
fn test_newcommand_without_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    // Outside of the global group, which is the default, a definition is only good for the
    // snippet which contains it, ...
    let latex = r"\newcommand{\bb}[1]{\mathbb{#1}}\bb{R}";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("newcommand_without_global_group", mathml.mathml, latex);

    // ... so the next snippet doesn't know it, ...
    assert!(
        converter
            .convert_with_global_state(r"\bb{C}", MathDisplay::Inline)
            .is_err()
    );
    // ... and can define it again itself.
    converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
}

#[test]
fn test_renewcommand_without_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\newcommand{\zz}{\mathbb{Z}}\zz", MathDisplay::Inline)
        .unwrap();
    // The definition from the earlier snippet is gone, so there is nothing to replace.
    assert!(
        converter
            .convert_with_global_state(r"\renewcommand{\zz}{\mathbb{Q}}", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_newcommand_in_convert_all_without_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    let results = converter.convert_all(&[
        (r"\newcommand{\zz}{\mathbb{Z}}", MathDisplay::Inline),
        (r"n \in \zz", MathDisplay::Inline),
    ]);
    assert!(results[0].is_ok());
    assert!(results[1].is_err());
}

#[test]
fn test_newcommand_does_not_leak_into_local_state() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_local_state(r"\newcommand{\zz}{\mathbb{Z}}\zz", MathDisplay::Inline)
        .unwrap();
    assert!(
        converter
            .convert_with_local_state(r"\zz", MathDisplay::Inline)
            .is_err()
    );
}

/// `\let` binds the meaning a name has right now, which is what a `\newcommand` body,
/// recorded by name, deliberately doesn't do.
#[test]
fn test_let() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        // The reason `\let` exists: hold on to a definition one is about to replace. Without
        // it, the redefinition would refer to itself and run into the expansion limit.
        (
            "let_keep_old_meaning",
            r"\let\originalepsilon\epsilon\renewcommand{\epsilon}{1+\originalepsilon}\epsilon",
        ),
        // The `=` between the two names is optional, and so is the space around it.
        ("let_plain", r"\let\a\alpha\a"),
        ("let_equals", r"\let\a=\alpha\a"),
        ("let_equals_spaced", r"\let\a = \alpha \a"),
        // Only one `=` is skipped, so this binds `\eq` to `=` itself.
        ("let_to_equals", r"\let\eq==x\eq y"),
        // Early binding: `\a` keeps the meaning `\alpha` had at the `\let`, unlike
        // `\newcommand{\a}{\alpha}`, whose body would follow the redefinition.
        (
            "let_does_not_follow_redefinition",
            r"\let\a\alpha\renewcommand{\alpha}{\beta}\a",
        ),
        // A command which takes arguments keeps its arity.
        ("let_command_with_args", r"\let\f\frac\f{1}{2}"),
        // The source may be a custom command, in which case the reference to its body is
        // what gets copied.
        (
            "let_to_custom_cmd",
            r"\newcommand{\m}[1]{\sqrt{#1}}\let\n\m\n{2}",
        ),
        // `\let` and `\newcommand` write into the same place, so a name never means two
        // things at once, no matter which of them comes last.
        (
            "let_overwrites_newcommand",
            r"\newcommand{\a}{x}\let\a\alpha\a",
        ),
        (
            "renewcommand_overwrites_let",
            r"\let\a\alpha\renewcommand{\a}{x}\a",
        ),
        // A `\let` to a name which is itself `\let` copies the meaning, not the name, so
        // redefining the middle name afterwards leaves both of the others alone.
        ("let_chain", r"\let\a\alpha\let\b\a\renewcommand{\a}{x}\a\b"),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

/// In the global group, a `\let` outlives the snippet which contains it, just like a
/// `\newcommand` does.
#[test]
fn test_let_across_snippets() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\newcommand{\zz}{\mathbb{Z}}", MathDisplay::Inline)
        .unwrap();
    // The source is a command from an earlier snippet, so its body lives in the store which
    // outlives the snippets, and the reference to it stays good.
    converter
        .convert_with_global_state(r"\let\oldzz\zz", MathDisplay::Inline)
        .unwrap();
    converter
        .convert_with_global_state(r"\renewcommand{\zz}{\mathbb{Q}}", MathDisplay::Inline)
        .unwrap();
    let latex = r"\zz \oldzz";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("let_across_snippets", mathml.mathml, latex);
}

#[test]
fn test_let_without_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\let\a\alpha\a", MathDisplay::Inline)
        .unwrap();
    // Outside of the global group, the binding is forgotten with the snippet.
    assert!(
        converter
            .convert_with_global_state(r"\a", MathDisplay::Inline)
            .is_err()
    );
}

/// `\global\let` writes into the store which outlives the snippet, even though the conversion
/// doesn't run in the global group.
#[test]
fn test_global_let() {
    // Each case defines something in the first snippet and uses it in the second one.
    for (name, definition, usage) in [
        // The source is a command defined in this very snippet, so its body has to be copied
        // into the store which outlives the snippet.
        (
            "global_let_to_local_cmd",
            r"\newcommand{\zzz}{z}\global\let\zzzz\zzz",
            r"\zzzz",
        ),
        // The copy has to follow a chain of `\let`s, and the arity has to survive it.
        (
            "global_let_chain",
            r"\newcommand{\m}[1]{\sqrt{#1}}\let\n\m\global\let\o\n",
            r"\o{2}",
        ),
        // Sources which live somewhere that outlives the snippet already, so nothing is copied.
        ("global_let_to_builtin", r"\global\let\a\alpha", r"\a"),
        (
            "global_let_to_builtin_with_args",
            r"\global\let\f\frac",
            r"\f{1}{2}",
        ),
        ("global_let_to_config_cmd", r"\global\let\c\cfgcmd", r"\c"),
        // `\global\global\let` is allowed, as it is in LaTeX.
        ("global_let_doubled", r"\global\global\let\a\alpha", r"\a"),
    ] {
        let config = MathCoreConfig {
            macros: vec![("cfgcmd".to_string(), r"\mathbb{C}".to_string())],
            pretty_print: PrettyPrint::Always,
            ..Default::default()
        };
        let mut converter = LatexToMathML::new(config).unwrap();
        converter
            .convert_with_global_state(definition, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{definition}` with error '{e}'"));
        let mathml = converter
            .convert_with_global_state(usage, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{usage}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, &format!("{definition}\n{usage}"));
    }
}

/// A `\global\let` copies the meaning of its source, but the *names* that meaning refers to are
/// still looked up when the command is expanded, as they are in LaTeX.
#[test]
fn test_global_let_keeps_late_binding() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(
            r"\newcommand{\inner}{x}\newcommand{\outer}{\inner+1}\global\let\g\outer",
            MathDisplay::Inline,
        )
        .unwrap();
    // `\g` outlived the snippet, but the `\inner` its body mentions did not, so expanding it
    // in the next snippet fails just like `\outer` itself would in LaTeX.
    assert!(
        converter
            .convert_with_global_state(r"\g", MathDisplay::Inline)
            .is_err()
    );
    // With `\inner` defined again, `\g` works.
    let latex = r"\newcommand{\inner}{y}\g";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("global_let_late_binding", mathml.mathml, latex);
}

/// A global definition takes effect right away, as it does in TeX: it is not shadowed by a
/// local definition of the same name for the rest of the snippet.
#[test]
fn test_global_let_beats_local() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    let latex = r"\newcommand{\a}{1}\a\global\let\a\alpha\a";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("global_let_beats_local", mathml.mathml, latex);
    // And it is still α in the next snippet.
    let latex = r"\a";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("global_let_beats_local_next_snippet", mathml.mathml, latex);
}

/// In the global group, every definition outlives the snippet anyway, so `\global` changes
/// nothing.
#[test]
fn test_global_let_in_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(
            r"\newcommand{\zzz}{z}\global\let\zzzz\zzz",
            MathDisplay::Inline,
        )
        .unwrap();
    let latex = r"\zzz\zzzz";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("global_let_in_global_group", mathml.mathml, latex);
}

/// `\def` defines a command the way `\newcommand` does, but with TeX's syntax.
#[test]
fn test_def() {
    let config = MathCoreConfig {
        macros: vec![("cfgcmd".to_string(), r"\mathbb{C}".to_string())],
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    for (name, latex) in [
        ("def_zero_args", r"\def\zz{\mathbb{Z}}x \in \zz"),
        ("def_one_arg", r"\def\bb#1{\mathbb{#1}}\bb{C}"),
        // The arguments don't have to be braced, so `\add 2 3` gives `2+3`.
        ("def_two_args", r"\def\add#1#2{#1+#2}\add 2 3"),
        (
            "def_nine_args",
            r"\def\n#1#2#3#4#5#6#7#8#9{#9#8#7#6#5#4#3#2#1}\n123456789",
        ),
        // A body which is empty expands to `\relax`, and must not swallow what comes after it.
        ("def_empty_body", r"\def\nop{}a\nop b"),
        // Unlike `\newcommand`, `\def` replaces whatever the name meant before without
        // complaining, whether that was a builtin, a macro from the configuration, or another
        // definition made in this very snippet.
        ("def_redefines_builtin", r"\def\frac#1#2{#1/#2}\frac{1}{2}"),
        ("def_redefines_config_macro", r"\def\cfgcmd{y}\cfgcmd"),
        ("def_redefines_def", r"\def\zz{1}\def\zz{2}\zz"),
        (
            "def_redefines_newcommand",
            r"\newcommand{\zz}{1}\def\zz{2}\zz",
        ),
        (
            "newcommand_redefines_def",
            r"\def\zz{1}\renewcommand{\zz}{2}\zz",
        ),
        // The body is recorded by name, so it follows a later redefinition of that name and
        // may refer to a command which doesn't exist yet.
        ("def_late_binding", r"\def\a{\b}\def\b{x}\a"),
        (
            "def_follows_redefinition",
            r"\def\a{\b}\def\b{x}\a\def\b{y}\a",
        ),
        // An argument may be used more than once, or not at all.
        ("def_repeated_arg", r"\def\sq#1{#1^2}\sq{y}+\sq{y}"),
        ("def_unused_arg", r"\def\drop#1{z}\drop{y}"),
        // `\let` can hold on to a definition which a `\def` is about to replace.
        (
            "def_after_let",
            r"\let\oldalpha\alpha\def\alpha{1+\oldalpha}\alpha",
        ),
        // Whitespace between `\def` and the name, and between the name and the parameter
        // text, is skipped, the way TeX skips it when it reads the name. Whitespace *within*
        // the parameter text is a delimiter, and is rejected; see the error tests.
        ("def_spaced", r"\def \a #1{[#1]}\a{x}"),
        ("def_spaced_without_params", r"\def \a {x}\a"),
    ] {
        let mathml = converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{latex}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, latex);
    }
}

/// `\gdef` and `\global\def` write into the store which outlives the snippet, even though the
/// conversion doesn't run in the global group.
#[test]
fn test_gdef() {
    // Each case defines something in the first snippet and uses it in the second one.
    for (name, definition, usage) in [
        ("gdef", r"\gdef\zz{z}", r"\zz"),
        ("gdef_with_args", r"\gdef\bb#1{\mathbb{#1}}", r"\bb{C}"),
        ("global_def", r"\global\def\add#1#2{#1+#2}", r"\add 2 3"),
        // `\global` in front of something which is global already changes nothing, and it may
        // be repeated, as it may in LaTeX.
        ("global_gdef", r"\global\gdef\a{\alpha}", r"\a"),
        ("global_global_def", r"\global\global\def\a{\alpha}", r"\a"),
        // The body refers to a command defined in this very snippet, whose body therefore has
        // to be copied into the store which outlives the snippet along with it.
        (
            "gdef_body_refers_to_local_cmd",
            r"\newcommand{\zzz}{z}\gdef\g{\zzz}",
            r"\newcommand{\zzz}{q}\g",
        ),
        // A `\global\let` to a `\gdef` picks up the arity.
        (
            "gdef_then_global_let",
            r"\gdef\m#1{\sqrt{#1}}\global\let\n\m",
            r"\n{2}",
        ),
    ] {
        let config = MathCoreConfig {
            pretty_print: PrettyPrint::Always,
            ..Default::default()
        };
        let mut converter = LatexToMathML::new(config).unwrap();
        converter
            .convert_with_global_state(definition, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{definition}` with error '{e}'"));
        let mathml = converter
            .convert_with_global_state(usage, MathDisplay::Inline)
            .unwrap_or_else(|e| panic!("failed to convert `{usage}` with error '{e}'"));
        assert_snapshot!(name, mathml.mathml, &format!("{definition}\n{usage}"));
    }
}

#[test]
fn test_def_without_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\def\a{\alpha}\a", MathDisplay::Inline)
        .unwrap();
    // Outside of the global group, a plain `\def` is forgotten with the snippet.
    assert!(
        converter
            .convert_with_global_state(r"\a", MathDisplay::Inline)
            .is_err()
    );
}

/// A `\gdef` outlives the snippet, but the names its body mentions are still looked up when the
/// command is expanded, as they are in LaTeX.
#[test]
fn test_gdef_keeps_late_binding() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\def\inner{x}\gdef\g{\inner+1}", MathDisplay::Inline)
        .unwrap();
    // `\g` outlived the snippet, but the `\inner` its body mentions did not.
    assert!(
        converter
            .convert_with_global_state(r"\g", MathDisplay::Inline)
            .is_err()
    );
    // With `\inner` defined again, `\g` works.
    let latex = r"\def\inner{y}\g";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("gdef_late_binding", mathml.mathml, latex);
}

/// A global definition takes effect right away, as it does in TeX: it is not shadowed by a
/// local definition of the same name for the rest of the snippet.
#[test]
fn test_gdef_beats_local() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    let latex = r"\def\a{1}\a\gdef\a{\alpha}\a";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("gdef_beats_local", mathml.mathml, latex);
    // And it is still α in the next snippet.
    let latex = r"\a";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("gdef_beats_local_next_snippet", mathml.mathml, latex);
}

/// In the global group, every definition outlives the snippet anyway, so a plain `\def` reaches
/// just as far as a `\gdef`.
#[test]
fn test_def_in_global_group() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        global_group: true,
        ..Default::default()
    };
    let mut converter = LatexToMathML::new(config).unwrap();

    converter
        .convert_with_global_state(r"\def\zzz{z}\gdef\zzzz{q}", MathDisplay::Inline)
        .unwrap();
    let latex = r"\zzz\zzzz";
    let mathml = converter
        .convert_with_global_state(latex, MathDisplay::Inline)
        .unwrap();
    assert_snapshot!("def_in_global_group", mathml.mathml, latex);
}

/// A `\def` may expand to itself, which the expansion limit stops.
#[test]
fn test_def_recursion() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    assert!(
        converter
            .convert_with_local_state(r"\def\a{\a}\a", MathDisplay::Inline)
            .is_err()
    );
}

#[test]
fn test_let_with_ignore_unknown_commands() {
    let config = MathCoreConfig {
        pretty_print: PrettyPrint::Always,
        ignore_unknown_commands: true,
        ..Default::default()
    };
    let converter = LatexToMathML::new(config).unwrap();

    // A `\let` to a name which is unknown at the time of the `\let` is not an error, and
    // the name can be defined later.
    let latex = r"\let\a\zzzz\newcommand{\zzzz}{x}\a";
    assert!(
        converter
            .convert_with_local_state(latex, MathDisplay::Inline)
            .is_err()
    );
}