asciimath-unicode 0.4.1

Convert asciimath to unicode
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
#![allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]

use std::{fmt, iter};
use unicode_width::UnicodeWidthStr;

use super::Conf;
use super::inline::{Mapper, MapperConf};
use super::tokens::{left_bracket_str, right_bracket_str, subscript_char, superscript_char};

use asciimath_parser::tree::{
    Expression, Frac, Func, Group, Intermediate, Matrix, Script, ScriptFunc, Simple, SimpleBinary,
    SimpleFunc, SimpleScript, SimpleUnary,
};

/// A 2D text block for multi-line rendering.
/// All lines are padded to `width` display columns with trailing spaces.
#[derive(Debug, Clone)]
pub struct Block {
    lines: Vec<String>,
    baseline: usize,
    width: usize,
}

impl Block {
    fn text(text: impl Into<String>) -> Self {
        let owned = text.into();
        let width = UnicodeWidthStr::width(&*owned);
        Block {
            lines: vec![owned],
            baseline: 0,
            width,
        }
    }

    fn empty() -> Self {
        Block {
            lines: vec![String::new()],
            baseline: 0,
            width: 0,
        }
    }

    fn space(n: usize) -> Self {
        Block {
            lines: vec![" ".repeat(n)],
            baseline: 0,
            width: n,
        }
    }

    fn height(&self) -> usize {
        self.lines.len()
    }

    fn is_multiline(&self) -> bool {
        self.lines.len() > 1
    }

    fn beside(mut self, mut other: Self) -> Self {
        let above = self.baseline.max(other.baseline);
        let self_below = self.lines.len() - self.baseline;
        let other_below = other.lines.len() - other.baseline;
        let below = self_below.max(other_below);
        let new_width = self.width + other.width;

        // Pad self above and below to align baselines
        self.lines = iter::repeat_with(|| " ".repeat(self.width))
            .take(above - self.baseline)
            .chain(self.lines)
            .chain(iter::repeat_with(|| " ".repeat(self.width)).take(below - self_below))
            .collect();

        // Pad other above and below to align baselines
        other.lines = iter::repeat_with(|| " ".repeat(other.width))
            .take(above - other.baseline)
            .chain(other.lines)
            .chain(iter::repeat_with(|| " ".repeat(other.width)).take(below - other_below))
            .collect();

        // Zip and concat
        let lines = self
            .lines
            .into_iter()
            .zip(other.lines)
            .map(|(mut left, right)| {
                left.push_str(&right);
                left
            })
            .collect();

        Block {
            lines,
            baseline: above,
            width: new_width,
        }
    }

    fn stack_frac(numer: Self, denom: Self) -> Self {
        let bar_width = numer.width.max(denom.width);
        let bar = "".repeat(bar_width);
        let baseline = numer.lines.len();

        let lines = numer
            .lines
            .into_iter()
            .map(|line| center_pad(&line, numer.width, bar_width))
            .chain(iter::once(bar))
            .chain(
                denom
                    .lines
                    .into_iter()
                    .map(|line| center_pad(&line, denom.width, bar_width)),
            )
            .collect();

        Block {
            baseline,
            width: bar_width,
            lines,
        }
    }

    fn with_brackets(self, left: &str, right: &str) -> Self {
        if left.is_empty() && right.is_empty() {
            self
        } else {
            let left_col = tall_bracket_left(left, self.height()).with_baseline(self.baseline);
            let right_col = tall_bracket_right(right, self.height()).with_baseline(self.baseline);
            let new_baseline = self.height() / 2;
            left_col
                .beside(self)
                .beside(right_col)
                .with_baseline(new_baseline)
        }
    }

    fn with_baseline(mut self, new_baseline: usize) -> Self {
        self.baseline = new_baseline;
        self
    }

    /// Pad vertically: ensure `above` lines above baseline, `below` lines below.
    fn pad_vertical(mut self, above: usize, below: usize) -> Self {
        let cur_below = self.lines.len() - 1 - self.baseline;
        if above > self.baseline {
            let extra: Vec<String> = iter::repeat_with(|| " ".repeat(self.width))
                .take(above - self.baseline)
                .collect();
            self.lines.splice(0..0, extra);
        }
        if below > cur_below {
            self.lines
                .extend(iter::repeat_with(|| " ".repeat(self.width)).take(below - cur_below));
        }
        self.baseline = above;
        self
    }

    /// Center horizontally to `width` display columns.
    fn pad_center(mut self, width: usize) -> Self {
        if width > self.width {
            for line in &mut self.lines {
                *line = center_pad(line, self.width, width);
            }
            self.width = width;
        }
        self
    }
}

impl fmt::Display for Block {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (idx, line) in self.lines.iter().enumerate() {
            if idx > 0 {
                f.write_str("\n")?;
            }
            f.write_str(line.trim_end())?;
        }
        Ok(())
    }
}

fn center_pad(s: &str, current_width: usize, target_width: usize) -> String {
    if current_width >= target_width {
        s.to_string()
    } else {
        let left = (target_width - current_width).div_ceil(2);
        let right = target_width - current_width - left;
        format!("{}{}{}", " ".repeat(left), s, " ".repeat(right))
    }
}

fn tall_bracket_left(bracket: &str, height: usize) -> Block {
    if bracket.is_empty() {
        Block {
            lines: vec![String::new(); height],
            baseline: height / 2,
            width: 0,
        }
    } else if height <= 1 {
        Block::text(bracket)
    } else {
        let (top, mid_top, mid_bot, bot, fill) = match bracket {
            "(" | "left(" => ('', '', '', '', ''),
            "[" | "left[" => ('', '', '', '', ''),
            "" | "(:" | "langle" | "<<" => ('', '', '', '', ''),
            "" | "|__" | "lfloor" => ('', '', '', '', ''),
            "" | "|~" | "lceiling" => ('', '', '', '', ''),
            "{" if height == 2 => ('', ' ', ' ', '', ' '),
            "{" if height.is_multiple_of(2) => ('', '', '', '', ''),
            "{" => ('', '', '', '', ''),
            // "|", "|:", and anything else
            _ => ('', '', '', '', ''),
        };
        let mut lines = Vec::with_capacity(height);
        lines.push(top.to_string());
        for idx in 1..height - 1 {
            lines.push(
                if idx == height / 2 {
                    mid_bot
                } else if idx == height / 2 - 1 {
                    mid_top
                } else {
                    fill
                }
                .to_string(),
            );
        }
        lines.push(bot.to_string());
        Block {
            lines,
            baseline: height / 2,
            width: 1,
        }
    }
}

fn tall_bracket_right(bracket: &str, height: usize) -> Block {
    if bracket.is_empty() {
        Block {
            lines: vec![String::new(); height],
            baseline: height / 2,
            width: 0,
        }
    } else if height <= 1 {
        Block::text(bracket)
    } else {
        let (top, mid_top, mid_bot, bot, fill) = match bracket {
            ")" | "right)" => ('', '', '', '', ''),
            "]" | "right]" => ('', '', '', '', ''),
            "" | ":)" | "rangle" | ">>" => ('', '', '', '', ''),
            "" | "__|" | "rfloor" => ('', '', '', '', ''),
            "" | "~|" | "rceiling" => ('', '', '', '', ''),
            "}" if height == 2 => ('', ' ', ' ', '', ' '),
            "}" if height.is_multiple_of(2) => ('', '', '', '', ''),
            "}" => ('', '', '', '', ''),
            // "|", ":|", and anything else
            _ => ('', '', '', '', ''),
        };
        let mut lines = Vec::with_capacity(height);
        lines.push(top.to_string());
        for idx in 1..height - 1 {
            lines.push(
                if idx == height / 2 {
                    mid_bot
                } else if idx == height / 2 - 1 {
                    mid_top
                } else {
                    fill
                }
                .to_string(),
            );
        }
        lines.push(bot.to_string());
        Block {
            lines,
            baseline: height / 2,
            width: 1,
        }
    }
}

#[allow(clippy::too_many_lines)]
fn is_spaced_operator(sym: &str) -> bool {
    matches!(
        sym,
        "+" | "-"
            | "="
            | "!="
            | "ne"
            | "<"
            | "lt"
            | "<="
            | "le"
            | "lt="
            | "leq"
            | ">"
            | "gt"
            | ">="
            | "ge"
            | "gt="
            | "geq"
            | "mlt"
            | "ll"
            | "mgt"
            | "gg"
            | "-<"
            | "prec"
            | "-lt"
            | ">-"
            | "succ"
            | "-<="
            | "preceq"
            | ">-="
            | "succeq"
            | "in"
            | "!in"
            | "notin"
            | "sub"
            | "subset"
            | "sup"
            | "supset"
            | "sube"
            | "subseteq"
            | "supe"
            | "supseteq"
            | "-="
            | "equiv"
            | "~="
            | "cong"
            | "~~"
            | "approx"
            | "~"
            | "sim"
            | "prop"
            | "propto"
            | "=>"
            | "implies"
            | "<=>"
            | "iff"
            | "AA"
            | "forall"
            | "EE"
            | "exists"
            | "|--"
            | "vdash"
            | "|=="
            | "models"
            | "and"
            | "or"
            | "if"
            | "+-"
            | "pm"
            | "-+"
            | "mp"
            | "xx"
            | "times"
            | "-:"
            | "div"
            | "divide"
            | "*"
            | "cdot"
            | "**"
            | "ast"
            | "o+"
            | "oplus"
            | "ox"
            | "otimes"
            | "o."
            | "odot"
            | "^^"
            | "wedge"
            | "land"
            | "vv"
            | "vee"
            | "lor"
            | "nn"
            | "cap"
            | "uu"
            | "cup"
            | "rarr"
            | "rightarrow"
            | "->"
            | "to"
            | "larr"
            | "leftarrow"
            | "<-"
            | "harr"
            | "leftrightarrow"
            | "<->"
            | "rArr"
            | "Rightarrow"
            | "==>"
            | "lArr"
            | "Leftarrow"
            | "<=="
            | "hArr"
            | "Leftrightarrow"
            | "<==>"
            | "|->"
            | "mapsto"
    )
}

fn is_spaced_ident(id: &str) -> bool {
    matches!(id, "+" | "-" | "=" | ">" | "<" | "" | "" | "")
}

fn inter_is_spaced_op(inter: &Intermediate<'_>) -> bool {
    match inter {
        Intermediate::ScriptFunc(ScriptFunc::Simple(SimpleScript {
            simple: Simple::Symbol(sym),
            script: Script::None,
        })) => is_spaced_operator(sym),
        Intermediate::ScriptFunc(ScriptFunc::Simple(SimpleScript {
            simple: Simple::Ident(id),
            script: Script::None,
        })) => is_spaced_ident(id),
        _ => false,
    }
}

impl Conf {
    fn block_inline_simple(self, simple: &Simple<'_>) -> Block {
        let mut s = String::new();
        self.inline_simple(simple, &mut Mapper::new(&mut s))
            .unwrap_or_else(|_| unreachable!("write to String is infallible"));
        Block::text(s)
    }

    pub(crate) fn block_expression(self, expr: &Expression<'_>) -> Block {
        let mut items = expr.iter();
        let Some(first) = items.next() else {
            return Block::empty();
        };
        let mut result = self.block_intermediate(first);
        for inter in items {
            let block = self.block_intermediate(inter);
            if inter_is_spaced_op(inter) {
                result = result.beside(Block::space(1));
                result = result.beside(block);
                result = result.beside(Block::space(1));
            } else {
                result = result.beside(block);
            }
        }
        result
    }

    fn block_intermediate(self, inter: &Intermediate<'_>) -> Block {
        match inter {
            Intermediate::ScriptFunc(sf) => self.block_scriptfunc(sf),
            Intermediate::Frac(frac) => self.block_frac(frac),
        }
    }

    fn block_scriptfunc(self, sf: &ScriptFunc<'_>) -> Block {
        match sf {
            ScriptFunc::Simple(ss) => self.block_simplescript(ss),
            ScriptFunc::Func(func) => self.block_func(func),
        }
    }

    fn block_simplescript(self, ss: &SimpleScript<'_>) -> Block {
        let base_block = self.block_simple(&ss.simple);
        self.block_apply_script(base_block, &ss.script)
    }

    fn block_apply_script(self, base: Block, script: &Script<'_>) -> Block {
        match script {
            Script::None => base,
            Script::Sub(sub) => {
                let conf = MapperConf {
                    sub_sup: Some(subscript_char),
                    ..MapperConf::default()
                };
                let mut out = String::new();
                if self.inline_simple(sub, &mut conf.wrap(&mut out)).is_ok() {
                    base.beside(Block::text(out))
                } else {
                    // Vertical: sub below-right
                    let sub_blk = self.block_simple(sub);
                    let original = base.baseline;
                    let base_h = base.height();
                    base.with_baseline(base_h)
                        .beside(sub_blk.with_baseline(0))
                        .with_baseline(original)
                }
            }
            Script::Super(sup) => {
                let conf = MapperConf {
                    sub_sup: Some(superscript_char),
                    ..MapperConf::default()
                };
                let mut out = String::new();
                if self.inline_simple(sup, &mut conf.wrap(&mut out)).is_ok() {
                    base.beside(Block::text(out))
                } else {
                    // Vertical: sup above-right
                    let sup_blk = self.block_simple(sup);
                    let new_baseline = sup_blk.height() + base.baseline;
                    let sup_h = sup_blk.height();
                    base.with_baseline(0)
                        .beside(sup_blk.with_baseline(sup_h))
                        .with_baseline(new_baseline)
                }
            }
            Script::Subsuper(sub, sup) => {
                let lower_conf = MapperConf {
                    sub_sup: Some(subscript_char),
                    ..MapperConf::default()
                };
                let upper_conf = MapperConf {
                    sub_sup: Some(superscript_char),
                    ..MapperConf::default()
                };
                let mut subscript = String::new();
                let mut superscript = String::new();
                if self
                    .inline_simple(sub, &mut lower_conf.wrap(&mut subscript))
                    .is_ok()
                    && self
                        .inline_simple(sup, &mut upper_conf.wrap(&mut superscript))
                        .is_ok()
                {
                    base.beside(Block::text(format!("{subscript}{superscript}")))
                } else {
                    // Vertical: sup above-right, then sub below-right
                    let upper = self.block_simple(sup);
                    let new_baseline = upper.height() + base.baseline;
                    let upper_h = upper.height();
                    let with_sup = base
                        .with_baseline(0)
                        .beside(upper.with_baseline(upper_h))
                        .with_baseline(new_baseline);

                    let lower = self.block_simple(sub);
                    let original = with_sup.baseline;
                    let with_sup_h = with_sup.height();
                    with_sup
                        .with_baseline(with_sup_h)
                        .beside(lower.with_baseline(0))
                        .with_baseline(original)
                }
            }
        }
    }

    fn block_simple(self, simple: &Simple<'_>) -> Block {
        match simple {
            Simple::Missing => Block::empty(),
            Simple::Group(group) => self.block_group(group),
            Simple::Matrix(matrix) => self.block_matrix(matrix),
            Simple::Unary(unary) => self.block_unary(unary),
            Simple::Binary(binary) => self.block_binary(binary),
            Simple::Func(func) => self.block_simplefunc(func),
            _ => self.block_inline_simple(simple),
        }
    }

    fn block_simplefunc(self, func: &SimpleFunc<'_>) -> Block {
        let name = Block::text(func.func);
        // a bare function name has a missing argument and takes no separator
        if matches!(func.arg(), Simple::Missing) {
            name
        } else {
            let arg = self.block_simple(func.arg());
            name.beside(Block::space(1)).beside(arg)
        }
    }

    fn block_unary(self, unary: &SimpleUnary<'_>) -> Block {
        if unary.op == "sqrt" {
            let arg = self.block_simple(unary.arg());
            if arg.is_multiline() {
                return Block::text("").beside(arg);
            }
            let mut s = String::from("");
            self.inline_simple(unary.arg(), &mut Mapper::new(&mut s))
                .unwrap_or_else(|_| unreachable!("write to String is infallible"));
            Block::text(s)
        } else {
            let mut s = String::new();
            let mut mapper = Mapper::new(&mut s);
            self.inline_simpleunary(unary, &mut mapper)
                .unwrap_or_else(|_| unreachable!("write to String is infallible"));
            Block::text(s)
        }
    }

    fn block_binary(self, binary: &SimpleBinary<'_>) -> Block {
        if binary.op == "frac" {
            self.block_simplefrac(binary.first(), binary.second())
        } else {
            let mut s = String::new();
            let mut mapper = Mapper::new(&mut s);
            self.inline_simplebinary(binary, &mut mapper)
                .unwrap_or_else(|_| unreachable!("write to String is infallible"));
            Block::text(s)
        }
    }

    fn try_script_simplefrac(self, numer: &Simple<'_>, denom: &Simple<'_>) -> Option<String> {
        if self.script_fracs {
            let mut text = String::new();
            self.inline_simplefrac(numer, denom, &mut Mapper::new(&mut text))
                .ok()?;
            Some(text)
        } else {
            None
        }
    }

    fn try_script_frac(self, frac: &Frac<'_>) -> Option<String> {
        if self.script_fracs {
            let mut text = String::new();
            self.inline_frac(frac, &mut Mapper::new(&mut text)).ok()?;
            Some(text)
        } else {
            None
        }
    }

    fn block_simplefrac(self, numer: &Simple<'_>, denom: &Simple<'_>) -> Block {
        if self.vulgar_fracs
            && let Some(frac) = super::ast::extract_vulgar_frac(numer, denom, self.strip_brackets)
        {
            Block::text(frac)
        } else if let Some(text) = self.try_script_simplefrac(numer, denom) {
            Block::text(text)
        } else {
            Block::stack_frac(
                self.block_simple_or_expr_stripped(numer),
                self.block_simple_or_expr_stripped(denom),
            )
        }
    }

    /// If `strip_brackets` is on and simple is a group, render the inner expression.
    fn block_simple_or_expr_stripped(self, simple: &Simple<'_>) -> Block {
        if self.strip_brackets
            && let Simple::Group(Group { expr, .. }) = simple
        {
            self.block_expression(expr)
        } else {
            self.block_simple(simple)
        }
    }

    fn block_frac(self, frac: &Frac<'_>) -> Block {
        if let (
            ScriptFunc::Simple(SimpleScript {
                simple: num,
                script: Script::None,
            }),
            ScriptFunc::Simple(SimpleScript {
                simple: den,
                script: Script::None,
            }),
        ) = (&frac.numer, &frac.denom)
        {
            self.block_simplefrac(num, den)
        } else if let Some(text) = self.try_script_frac(frac) {
            Block::text(text)
        } else {
            Block::stack_frac(
                self.block_scriptfunc_for_frac(&frac.numer),
                self.block_scriptfunc_for_frac(&frac.denom),
            )
        }
    }

    fn block_scriptfunc_for_frac(self, sf: &ScriptFunc<'_>) -> Block {
        match sf {
            ScriptFunc::Simple(SimpleScript {
                simple,
                script: Script::None,
            }) => self.block_simple_or_expr_stripped(simple),
            _ => self.block_scriptfunc(sf),
        }
    }

    fn block_group(self, group: &Group<'_>) -> Block {
        let inner = self.block_expression(&group.expr);
        let left = left_bracket_str(group.left_bracket);
        let right = right_bracket_str(group.right_bracket);
        inner.with_brackets(left, right)
    }

    fn block_matrix(self, matrix: &Matrix<'_>) -> Block {
        let num_rows = matrix.num_rows();
        let num_cols = matrix.num_cols();
        let sep_width = 2;

        let mut cells = Vec::with_capacity(num_rows * num_cols);
        for row in matrix.rows() {
            for expr in row {
                cells.push(self.block_expression(expr));
            }
        }

        // one width, one above, one below for all cells
        let col_width = cells.iter().map(|c| c.width).max().unwrap_or_default();
        let above = cells.iter().map(|c| c.baseline).max().unwrap_or_default();
        let below = cells
            .iter()
            .map(|c| c.height() - 1 - c.baseline)
            .max()
            .unwrap_or_default();

        // build rows
        let total_width = col_width * num_cols + (num_cols - 1) * sep_width;
        let mut grid_lines: Vec<String> = Vec::new();
        let mut cells = cells.into_iter();
        for _ in 0..num_rows {
            if !grid_lines.is_empty() {
                grid_lines.push(" ".repeat(total_width));
            }
            let mut cell_row = cells
                .by_ref()
                .take(num_cols)
                .map(|cell| cell.pad_vertical(above, below).pad_center(col_width));
            let mut row_block: Block = cell_row
                .next()
                .unwrap_or_else(|| unreachable!("must have at least one col"));
            for cell in cell_row {
                row_block = row_block.beside(Block::space(sep_width)).beside(cell);
            }
            grid_lines.extend(row_block.lines);
        }

        let grid = Block {
            baseline: grid_lines.len() / 2,
            width: total_width,
            lines: grid_lines,
        };
        let left = left_bracket_str(matrix.left_bracket);
        let right = right_bracket_str(matrix.right_bracket);
        grid.with_brackets(left, right)
    }

    fn block_func(self, func: &Func<'_>) -> Block {
        let name = Block::text(func.func);
        let name_with_script = self.block_apply_script(name, &func.script);
        // a bare function name (e.g. `f`, `g`) has a missing argument and takes no separator
        if let ScriptFunc::Simple(SimpleScript {
            simple: Simple::Missing,
            ..
        }) = func.arg()
        {
            name_with_script
        } else {
            let arg = self.block_scriptfunc(func.arg());
            name_with_script.beside(Block::space(1)).beside(arg)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Block, Conf};
    use crate::tokens;
    use std::fmt::Write;

    fn render_block(input: &str) -> String {
        render_block_conf(input, Conf::default())
    }

    fn render_block_conf(input: &str, conf: Conf) -> String {
        let mut out = String::new();
        let expr = tokens::parse(input);
        write!(out, "{}", conf.block_expression(&expr)).unwrap();
        out
    }

    #[test]
    fn block_text() {
        let block = Block::text("hello");
        assert_eq!(block.width, 5);
        assert_eq!(block.baseline, 0);
        assert_eq!(block.height(), 1);
        assert_eq!(format!("{block}"), "hello");
    }

    #[test]
    fn block_empty() {
        let block = Block::empty();
        assert_eq!(block.width, 0);
        assert_eq!(block.height(), 1);
        assert_eq!(format!("{block}"), "");
    }

    #[test]
    fn block_beside() {
        let left = Block::text("ab");
        let right = Block::text("cd");
        let result = left.beside(right);
        assert_eq!(result.width, 4);
        assert_eq!(format!("{result}"), "abcd");
    }

    #[test]
    fn block_beside_different_heights() {
        let left = Block {
            lines: vec!["a".to_string(), "b".to_string()],
            baseline: 0,
            width: 1,
        };
        let right = Block::text("x");
        let result = left.beside(right);
        assert_eq!(result.height(), 2);
        assert_eq!(result.width, 2);
        assert_eq!(format!("{result}"), "ax\nb");
    }

    #[test]
    fn block_stack_frac() {
        let numer = Block::text("x");
        let denom = Block::text("y");
        let frac = Block::stack_frac(numer, denom);
        assert_eq!(frac.height(), 3);
        assert_eq!(frac.baseline, 1);
        assert_eq!(format!("{frac}"), "x\n\ny");
    }

    #[test]
    fn block_stack_frac_different_widths() {
        let numer = Block::text("abc");
        let denom = Block::text("d");
        let frac = Block::stack_frac(numer, denom);
        assert_eq!(frac.width, 3);
        assert_eq!(format!("{frac}"), "abc\n───\n d");
    }

    #[test]
    fn block_display_strips_trailing_spaces() {
        let block = Block {
            lines: vec!["ab  ".to_string(), "c   ".to_string()],
            baseline: 0,
            width: 4,
        };
        assert_eq!(format!("{block}"), "ab\nc");
    }

    #[test]
    fn simple_passthrough() {
        assert_eq!(render_block("x"), "x");
        assert_eq!(render_block("42"), "42");
        assert_eq!(render_block("alpha"), "α");
    }

    #[test]
    fn inline_superscript() {
        assert_eq!(render_block("x^2"), "");
    }

    #[test]
    fn inline_subscript() {
        assert_eq!(render_block("x_x"), "xₓ");
    }

    #[test]
    fn vulgar_frac_passthrough() {
        assert_eq!(render_block("1/2"), "½");
    }

    #[test]
    fn script_frac_passthrough() {
        assert_eq!(render_block("x/n"), "ˣ⁄ₙ");
    }

    #[test]
    fn stacked_frac_xy() {
        let result = render_block("x/y");
        assert_eq!(result, "x\n\ny");
    }

    #[test]
    fn stacked_frac_with_expressions() {
        let conf = Conf {
            vulgar_fracs: false,
            script_fracs: false,
            ..Default::default()
        };
        let result = render_block_conf("(x+1)/y", conf);
        assert_eq!(result, "x + 1\n─────\n  y");
    }

    #[test]
    fn stacked_frac_denom_expr() {
        let conf = Conf {
            vulgar_fracs: false,
            script_fracs: false,
            ..Default::default()
        };
        let result = render_block_conf("x/(y+1)", conf);
        assert_eq!(result, "  x\n─────\ny + 1");
    }

    #[test]
    fn vertical_subscript() {
        let result = render_block("x_y");
        assert_eq!(result, "x\n y");
    }

    #[test]
    fn vertical_superscript() {
        let result = render_block("x^rho");
        assert_eq!(result, " ρ\nx");
    }

    #[test]
    fn group_single_line() {
        assert_eq!(render_block("(x)"), "(x)");
    }

    #[test]
    fn group_multiline_brackets() {
        let result = render_block("(x/y)");
        assert_eq!(result, "⎛x⎞\n⎜─⎟\n⎝y⎠");
    }

    #[test]
    fn matrix_simple() {
        let result = render_block("[[a,b],[c,d]]");
        assert!(result.contains('a'));
        assert!(result.contains('b'));
        assert!(result.contains('c'));
        assert!(result.contains('d'));
        assert!(result.contains('') || result.contains('['));
    }

    #[test]
    fn frac_plus_term() {
        let result = render_block("x/y + z");
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 3);
        assert!(lines[1].contains('+'));
        assert!(lines[1].contains('z'));
    }

    #[test]
    fn operator_spacing() {
        let conf = Conf {
            vulgar_fracs: false,
            script_fracs: false,
            ..Default::default()
        };
        let result = render_block_conf("x + y", conf);
        assert_eq!(result, "x + y");
    }

    #[test]
    fn existing_tests_still_pass_inline() {
        let conf = Conf::default();
        let res = conf.parse("sum_(i=1)^n i^3=((n(n+1))/2)^2").to_string();
        assert_eq!(res, "∑ᵢ₌₁ⁿi³=(ⁿ⁽ⁿ⁺¹⁾⁄₂)²");
    }

    #[test]
    fn angle_bracket_height() {
        let result = render_block("<< (x + 1) / x_y >>");
        eprintln!("angle bracket result:\n{result}");
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 4, "expected 4 lines:\n{result}");
    }

    #[test]
    fn conf_block_true_uses_block_rendering() {
        let conf = Conf {
            block: true,
            ..Default::default()
        };
        let result = conf.parse("x/y").to_string();
        assert_eq!(result, "x\n\ny");
    }

    /// Block config that forces stacked fractions (so wrapped content is multiline).
    fn stacked() -> Conf {
        Conf {
            vulgar_fracs: false,
            script_fracs: false,
            ..Default::default()
        }
    }

    #[test]
    fn tall_square_brackets() {
        assert_eq!(render_block_conf("[x/y]", stacked()), "⎡x⎤\n⎢─⎥\n⎣y⎦");
    }

    #[test]
    fn tall_curly_brackets() {
        assert_eq!(render_block_conf("{x/y}", stacked()), "⎧x⎫\n⎨─⎬\n⎩y⎭");
    }

    #[test]
    fn tall_vertical_bars() {
        assert_eq!(render_block_conf("|x/y|", stacked()), "│x│\n│─│\n│y│");
    }

    #[test]
    fn tall_angle_brackets() {
        assert_eq!(render_block_conf("(:x/y:)", stacked()), "╱x╲\n⎜─⎟\n╲y╱");
    }

    #[test]
    fn tall_brackets_use_uniform_glyphs() {
        // every interior row of a tall paren uses the paren extension ⎜, never the
        // box-drawing │ filler
        assert_eq!(
            render_block_conf("((a/b)/(c/d))", stacked()),
            "⎛a⎞\n⎜─⎟\n⎜b⎟\n⎜─⎟\n⎜c⎟\n⎜─⎟\n⎝d⎠"
        );
        // ceiling columns stay in the square-bracket family (no stray paren ⎜/⎟)
        assert_eq!(
            render_block_conf("|~ (a/b)/(c/d) ~|", stacked()),
            "⌈a⌉\n⎢─⎥\n⎢b⎥\n⎢─⎥\n⎢c⎥\n⎢─⎥\n⎢d⎥"
        );
    }

    #[test]
    fn spaced_symbol_operator() {
        // `xx` renders as a spaced `×`, exercising `is_spaced_operator`.
        let result = render_block_conf("a/b xx c/d", stacked());
        assert_eq!(result, "a   c\n─ × ─\nb   d");
    }

    #[test]
    fn vertical_superscript_fraction() {
        let result = render_block_conf("x^(a/b)", stacked());
        assert_eq!(result, " ⎛a⎞\n ⎜─⎟\n ⎝b⎠\nx");
    }

    #[test]
    fn vertical_subscript_fraction() {
        let result = render_block_conf("x_(a/b)", stacked());
        assert_eq!(result, "x\n ⎛a⎞\n ⎜─⎟\n ⎝b⎠");
    }

    #[test]
    fn vertical_subsuper_fraction() {
        let result = render_block_conf("x_(a/b)^(c/d)", stacked());
        let lines: Vec<&str> = result.lines().collect();
        // superscript stacked above, base, subscript stacked below
        assert_eq!(lines.len(), 7);
        assert!(result.contains('c') && result.contains('d'));
        assert!(result.contains('a') && result.contains('b'));
    }

    #[test]
    fn matrix_tall_content() {
        let result = render_block_conf("[[a/b,c],[d,e/f]]", stacked());
        assert!(result.contains('') && result.contains(''));
        for needle in ['a', 'b', 'c', 'd', 'e', 'f'] {
            assert!(result.contains(needle), "missing {needle} in:\n{result}");
        }
    }

    #[test]
    fn floor_stays_inline_in_block() {
        // floor/ceil/abs fall back to inline rendering even in block mode.
        assert_eq!(render_block_conf("floor(x/y)", stacked()), "⌊x/y⌋");
        assert_eq!(render_block_conf("abs(x/y)", stacked()), "|x/y|");
    }

    #[test]
    fn simple_func_in_block() {
        // a function applied to a multiline argument renders beside it.
        let result = render_block_conf("sin(x/y)", stacked());
        assert!(result.contains("sin"));
        assert_eq!(result.lines().count(), 3);
    }

    #[test]
    fn spaced_operator_full_list() {
        // `|->` (mapsto) is the last arm of `is_spaced_operator`, so matching it
        // forces evaluation of every preceding operator pattern.
        let conf = Conf {
            block: true,
            ..Default::default()
        };
        assert_eq!(conf.parse("a |-> b").to_string(), "a ↦ b");
        assert_eq!(conf.parse("a mapsto b").to_string(), "a ↦ b");
        assert_eq!(conf.parse("a cdot b").to_string(), "a ⋅ b");
    }

    #[test]
    fn block_sqrt_multiline() {
        // sqrt of a stacked fraction renders the radical beside the block
        let result = render_block_conf("sqrt(x/y)", stacked());
        assert_eq!(result, " ⎛x⎞\n√⎜─⎟\n ⎝y⎠");
    }

    #[test]
    fn block_sqrt_inline() {
        // sqrt of a single-line argument stays inline
        assert_eq!(render_block_conf("sqrt(x)", stacked()), "√(x)");
    }

    #[test]
    fn block_binary_root() {
        // a non-frac binary falls back to inline rendering
        assert_eq!(render_block_conf("root(3)(x)", stacked()), "∛(x)");
    }

    #[test]
    fn block_inline_subsuper() {
        // sub/superscriptable scripts render inline even in block mode
        assert_eq!(render_block_conf("x_a^b", stacked()), "xₐᵇ");
    }

    #[test]
    fn block_empty_input() {
        assert_eq!(render_block_conf("", stacked()), "");
    }

    #[test]
    fn block_frac_scriptfunc_numerator() {
        // numerator carries a script, so the frac is rendered via the `Frac` path
        assert_eq!(render_block_conf("x^2/y", stacked()), "\n──\n y");
        assert_eq!(render_block_conf("x_i/y", stacked()), "xᵢ\n──\n y");
    }

    #[test]
    fn block_nested_frac() {
        let result = render_block_conf("(a/b)/(c/d)", stacked());
        let lines: Vec<&str> = result.lines().collect();
        assert!(lines.len() >= 5);
        for needle in ['a', 'b', 'c', 'd'] {
            assert!(result.contains(needle), "missing {needle} in:\n{result}");
        }
    }

    #[test]
    fn invisible_brackets() {
        // `{:` and `:}` are invisible grouping brackets
        assert_eq!(render_block_conf("{:x/y:}", stacked()), "x\n\ny");
        // one invisible side exercises the empty-bracket column on the other
        assert_eq!(render_block_conf("(:x/y:}", stacked()), "╱x\n⎜─\n╲y");
        assert_eq!(render_block_conf("{:x/y:)", stacked()), "x╲\n─⎟\ny╱");
    }

    #[test]
    fn applied_identifier_in_stacked_frac() {
        // numerator and denominator are identifiers applied to bracketed arguments
        let result = render_block_conf("f(x)/g(y)", stacked());
        assert_eq!(result, "f (x)\n─────\ng (y)");
    }

    #[test]
    fn explicit_frac_binary_in_block() {
        // the `frac(a)(b)` binary form stacks just like infix `a/b`
        assert_eq!(render_block_conf("frac(a)(b)", stacked()), "a\n\nb");
    }

    #[test]
    fn bare_function_no_trailing_space() {
        // a bare function name with no argument renders without a separator
        assert_eq!(render_block("g"), "g");
        assert_eq!(render_block("g h"), "g h");
    }

    #[test]
    fn block_script_fraction() {
        // with script fractions enabled, a subscriptable frac renders inline in block mode
        let conf = Conf {
            block: true,
            ..Default::default()
        };
        assert_eq!(conf.parse("x/n").to_string(), "ˣ⁄ₙ");
    }
}