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
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
//! Everything that paints: the canvas layout (centering, scrolling),
//! the marker/selection boxes and the per-cell styling. The formula
//! itself is rendered by `formulaa::render`; this turns that block plus
//! the editor's zero-width annotations into styled terminal spans.
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block as UiBlock, Borders, Paragraph};
use formulaa::editor::Editor;
use formulaa::glyphs::{Mark, is_display_marker, is_lattice_glyph};
use formulaa::render::{RenderCtx, render_root};
use crate::theme;
const HELP: &str = "⌃F free move ¦ ⌃B block select ¦ \\ command ¦ // frac ¦ ^ sup ¦ _ sub ¦ ⌃Y to clipboard ¦ ⌃O save ¦ ⌃W save and quit ¦ Esc/⌃Q quit";
/// Context-sensitive last line: a mode's own manual while one is
/// active, else the generic key list (plus ⌃G when the cursor sits in
/// a grid cell).
pub fn help_line(ed: &Editor) -> String {
// The minibuffer and its completion explain themselves; only the
// boxes announce *which* box is open (their contents all look like
// a green [bracketed] run).
if let Some((kind, _)) = &ed.op_entry {
use formulaa::editor::BoxKind;
return match kind {
BoxKind::Tex => "latex box (insert or paste a LaTeX snippet)",
BoxKind::Text => "text box",
BoxKind::Rm => "rm box (upright run)",
BoxKind::Op => "op box (operator name)",
BoxKind::OpStar => "op* box (operator name, takes limits)",
}
.into();
}
if ed.free.is_some() {
return "free move".into();
}
if ed.block.is_some() {
return "block: ↑/→ wider ¦ ↓/← narrower".into();
}
if let Some(gs) = ed.grid {
return match gs {
// Only the state's name and the transitions nobody
// guesses: arrows, ⌫ and Enter explain themselves.
formulaa::editor::GridSel::Cells { .. } => {
"grid cell select: c/| column select ¦ r/- row select"
}
formulaa::editor::GridSel::Lanes { cols: true, .. } => {
"grid column select: ↑↓ back to cell select"
}
formulaa::editor::GridSel::Lanes { cols: false, .. } => {
"grid row select: ←→ back to cell select"
}
}
.into();
}
// Ordinary editing: the one base line, plus the one extra command
// this position offers.
let mut line = String::new();
if ed.in_grid() {
line.push_str("⌃G grid edit ¦ ");
}
line.push_str(HELP);
line
}
/// The help line with its key tokens bold: each `|`-separated entry
/// starts with the keys (chords, glyphs — anything that is not a
/// plain lowercase word), followed by its description. A leading
/// `label:` (the mode's name) stays plain.
fn help_spans(text: &str) -> Line<'static> {
let base = Style::default().fg(theme::BORDER_FG);
let bold = base.add_modifier(Modifier::BOLD);
let mut spans = vec![Span::styled(" ", base)];
for (e, entry) in text.split(" ¦ ").enumerate() {
if e > 0 {
spans.push(Span::styled(" ¦ ", base));
}
// A label may span several words ("grid cell select:"):
// everything through the first ':' token stays plain, and the
// key run starts after it.
let toks: Vec<&str> = entry.split(' ').collect();
let label_end = toks
.iter()
.position(|t| t.ends_with(':'))
.map_or(0, |i| i + 1);
let mut keys_done = false;
for (t, tok) in toks.iter().enumerate() {
if t > 0 {
spans.push(Span::styled(" ", base));
}
let is_key = t >= label_end && !tok.chars().all(|c| c.is_ascii_lowercase());
if is_key && !keys_done {
spans.push(Span::styled(tok.to_string(), bold));
} else {
if t >= label_end {
keys_done = true;
}
spans.push(Span::styled(tok.to_string(), base));
}
}
}
Line::from(spans)
}
pub struct View {
/// The canvas border's title: the file being edited (`*` while it
/// differs from what is on disk), or the program's name.
pub title: String,
pub scroll_x: usize,
pub scroll_y: usize,
/// While true, selection grounds draw inverted — the one-frame
/// blip that acknowledges a copy.
pub copy_blip: bool,
/// Where the completion popup was drawn last frame, in canvas
/// coordinates, for mouse hit-testing: (top row, left column,
/// width, first visible item index, rows shown).
pub popup: Option<(usize, usize, usize, usize, usize)>,
}
impl Default for View {
fn default() -> Self {
View {
title: "formulAA".into(),
scroll_x: 0,
scroll_y: 0,
copy_blip: false,
popup: None,
}
}
}
/// Draw the whole UI; returns the screen coordinates of the formula's
/// top-left cell (for mouse hit-testing).
pub fn draw(f: &mut Frame, ed: &Editor, view: &mut View) -> (u16, u16) {
let [canvas_area, help_area] =
Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).areas(f.area());
let origin = draw_canvas(f, canvas_area, ed, view);
// One bottom line: a question outranks a message, which outranks
// the usage line (the minibuffer itself shows in-place at the
// cursor).
let bottom = if let Some(ask) = &ed.ask {
let (label, answer) = match ask {
formulaa::editor::Ask::Path(buf) => ("write to: ", buf.as_str()),
formulaa::editor::Ask::SaveFirst => ("unsaved changes — save first? [Y/n] ", ""),
};
Line::from(vec![
Span::styled(
format!(" {}", label),
Style::default().fg(theme::MESSAGE_FG),
),
Span::raw(answer.to_string()),
// The block is the caret: the question is where typing goes.
Span::styled("▌", Style::default().fg(theme::MESSAGE_FG)),
])
} else if !ed.message.is_empty() {
let fg = if ed.message_error {
theme::MESSAGE_ERR_FG
} else {
theme::MESSAGE_FG
};
Line::from(Span::styled(
format!(" {}", ed.message),
Style::default().fg(fg),
))
} else {
help_spans(&help_line(ed))
};
f.render_widget(clip(bottom, help_area.width as usize), help_area);
origin
}
/// Fit a status line to the terminal, ending in `…` when it does not
/// fit — a line cut mid-word reads as a glitch, an ellipsis as "there
/// is more".
fn clip(line: Line<'static>, width: usize) -> Line<'static> {
if line
.spans
.iter()
.map(|s| s.content.chars().count())
.sum::<usize>()
<= width
{
return line;
}
let (mut out, mut left) = (Vec::new(), width.saturating_sub(1));
for span in line.spans {
let n = span.content.chars().count();
if n <= left {
left -= n;
out.push(span);
continue;
}
let head: String = span.content.chars().take(left).collect();
out.push(Span::styled(head, span.style));
out.push(Span::styled("…", span.style));
return Line::from(out);
}
Line::from(out)
}
/// Returns the screen position of the formula's top-left cell.
fn draw_canvas(f: &mut Frame, area: Rect, ed: &Editor, view: &mut View) -> (u16, u16) {
let border = UiBlock::default()
.borders(Borders::ALL)
.title(format!(" {} ", view.title))
.border_style(Style::default().fg(theme::BORDER_FG));
let inner = border.inner(area);
f.render_widget(border, area);
let ctx = RenderCtx::canonical();
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &ctx);
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
d.blip = view.copy_blip;
// ^B: the caret disappears — the blinking block IS the position,
// and the parked cursor would just sit as a stray white cell
// inside it (it never moves in this mode anyway).
if ed.block.is_some() {
d.caret = None;
}
// ^F: the free cursor itself gets the prominent caret style; the
// snap preview is the subtler colored cell.
if let Some(f) = &ed.free {
let (sy, sx) = f.snap_at;
if sy < d.height() {
d.widen(sy, sx);
let last = d.bg[sy].len().saturating_sub(1);
d.invert[sy][sx.min(last)] = true;
d.flash[sy][sx.min(last)] = true;
}
let (fy, fx) = f.at;
if fy < d.height() {
d.widen(fy, fx);
d.caret = Some((fy, fx));
}
}
// Centering and scrolling follow the *formula*, not the painted
// canvas: the floating layers (command preview, completion popup,
// name-box fenders) may reach past it, and letting them size the
// canvas would slide the formula sideways or upward as they appear
// and disappear.
//
// They are settled *before* the overlays are painted, because the
// completion popup has to know where on screen it is about to sit
// to decide which way to open. Nothing an overlay does moves them:
// the caret's row never changes, and the column it ends at is
// predictable (the minibuffer draws `\name` from the caret).
let width = block.width() as u16;
let height = (block.height() as u16).max(1);
let follow = d.caret;
// The *typed* overlays — the `\command` minibuffer and the \op name
// box — are content the user is reading as they type it, so the
// view has to reach them. The floating ones (preview, completion
// popup) deliberately do not count: letting them size the canvas is
// what used to slide the formula about while typing.
let typed_end = follow.map(|(_, cx)| match (&ed.minibuffer, &ed.op_entry) {
(Some(buf), _) => cx + 1 + buf.chars().count(),
// The box draws its content between [ ] fenders.
(_, Some((_, buf))) => cx + buf.chars().count() + 2,
_ => cx,
});
// Per axis: an oversized formula scrolls to keep the cursor (the
// free cursor included) visible with a few cells of margin; one
// that fits is centered and its offset resets. `scroll` writes the
// offset through `off` and returns the centering pad.
let scroll = |size: u16, avail: u16, cur: Option<usize>, off: &mut usize| -> u16 {
if size <= avail {
*off = 0;
return avail.saturating_sub(size) / 2;
}
let vis = avail as usize;
let margin = 4.min(vis / 4);
if let Some(c) = cur {
*off = (*off).min(c.saturating_sub(margin));
if c + margin >= *off + vis {
*off = c + margin + 1 - vis;
}
}
*off = (*off).min(size as usize - vis);
0
};
// Horizontally the two roles split: the formula alone is what gets
// centered, but the reach that has to stay on screen includes the
// typed overlay — otherwise a long \text box runs off the right
// edge with no keystroke able to bring it back. Centering it away
// is the same bug as scrolling it away: every canvas column is
// painted at `left + col`, so the pad has to leave room for the
// reach, not just for the formula.
let reach = typed_end.map_or(width, |e| width.max(e as u16 + 1));
let left = if reach <= inner.width {
view.scroll_x = 0;
(inner.width.saturating_sub(width) / 2).min(inner.width.saturating_sub(reach))
} else {
scroll(reach, inner.width, typed_end, &mut view.scroll_x)
};
let top = scroll(
height,
inner.height,
follow.map(|(cy, _)| cy),
&mut view.scroll_y,
);
view.popup = overlay_minibuffer(
ed,
&mut d,
Viewport {
left,
top,
scroll_x: view.scroll_x,
scroll_y: view.scroll_y,
width: inner.width as usize,
height: inner.height as usize,
},
);
// With a selection active the caret cell is not drawn: the colored
// range alone says what is selected (a reverse-video cell at one
// end reads as "maybe included"). The minibuffer/name-box overlays
// keep the caret they anchor on.
if ed.selection().is_some() && ed.minibuffer.is_none() && ed.op_entry.is_none() {
d.caret = None;
}
let mut text: Vec<Line> = Vec::with_capacity(top as usize + d.height());
for _ in 0..top {
text.push(Line::raw(""));
}
let pad = " ".repeat(left as usize);
let caret_style = match (ed.op_entry.is_some(), ed.free.is_some()) {
(true, _) => CaretStyle::Box,
(_, true) => CaretStyle::Free,
_ => CaretStyle::Normal,
};
for y in view.scroll_y..d.height() {
let mut spans = vec![Span::raw(pad.clone())];
spans.extend(decorate_line(&d, y, caret_style, view.scroll_x));
text.push(Line::from(spans));
}
f.render_widget(Paragraph::new(text), inner);
(inner.x + left, inner.y + top)
}
/// The painted screen: the char grid plus every parallel channel that
/// must stay the same shape as it. Growing a row, inserting a row or
/// moving the caret goes through here, so the channels cannot drift.
struct Decor {
lines: Vec<Vec<char>>,
bg: Vec<Vec<Option<Color>>>,
/// Cells drawn bold (the completion's `[^F]` chord markers).
bold: Vec<Vec<bool>>,
/// Cells whose ground blinks: the selection layer — the linear
/// Shift selection, ^B's highlighted ancestor (purple), ^F's snap
/// preview (inverted).
flash: Vec<Vec<bool>>,
/// The copy acknowledgement: selection grounds draw inverted for
/// one brief moment.
blip: bool,
/// Cells drawn in reverse video: the secondary marks (^B's
/// one-step-outward ring, ^F's snap preview). No color of their
/// own, so they read on light and dark terminals alike.
invert: Vec<Vec<bool>>,
caret: Option<(usize, usize)>,
/// The edited grid's frame rectangle (x0, x1, top, bottom).
frame: Option<(usize, usize, usize, usize)>,
/// The rectangle of a delimiter armed for unwrapping, same shape.
armed: Option<(usize, usize, usize, usize)>,
}
impl Decor {
/// Widen row `y` so column `x` exists.
fn widen(&mut self, y: usize, x: usize) {
if x >= self.lines[y].len() {
self.lines[y].resize(x + 1, ' ');
self.bg[y].resize(x + 1, None);
self.bold[y].resize(x + 1, false);
self.flash[y].resize(x + 1, false);
self.invert[y].resize(x + 1, false);
}
}
/// Make row `y` exist. Floating layers paint into rows the formula
/// does not have; growing the canvas downward is not a shift, so
/// this never moves anything already drawn.
fn ensure_row(&mut self, y: usize) {
while self.lines.len() <= y {
self.lines.push(Vec::new());
self.bg.push(Vec::new());
self.bold.push(Vec::new());
self.flash.push(Vec::new());
self.invert.push(Vec::new());
}
}
fn height(&self) -> usize {
self.lines.len()
}
}
/// How the caret cell is painted: reverse video normally, a solid
/// colored block for the free cursor (reverse video there would read
/// as "the character changed color"), green while a name box is open.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CaretStyle {
Normal,
Free,
Box,
}
/// Turn the zero-width display annotations of a rendered block into
/// colored boxes and the caret cell. Marks carry (row, col, char):
/// selection mark pairs paint a background box (theme::SELECTION_BG),
/// grid cell/lane pairs their own colors, and the ^G frame recolors
/// the edited grid's border.
fn marker_boxes(
block: &formulaa::render::Block,
extents: &[(usize, usize, usize)],
block_selected: Option<usize>,
) -> Decor {
let (lines, marks, caret) = (&block.lines, &block.marks[..], block.caret);
// Cell coordinates throughout.
let mut grid: Vec<Vec<char>> = lines.to_vec();
if grid.is_empty() {
grid.push(Vec::new());
}
let mut bg: Vec<Vec<Option<Color>>> = grid.iter().map(|row| vec![None; row.len()]).collect();
// Boxes: pair opens (selection start, ^B label) with closes within
// each row, nesting by position. Selection pairs consume extents in
// encounter order (rows top-down, columns left-right) — the same
// order the editor lists them in (one per grid cell, or one).
#[derive(Clone, Copy)]
enum BoxKind {
/// The selection ground: purple, blinking.
Sel,
/// The secondary step: reverse video, steady.
Step,
}
let mut boxes: Vec<(usize, usize, BoxKind, usize, usize)> = Vec::new();
let mut order: Vec<usize> = Vec::new(); // paint order key: depth
let mut by_row: std::collections::BTreeMap<usize, Vec<(usize, char)>> =
std::collections::BTreeMap::new();
for &(y, x, c) in marks {
by_row.entry(y).or_default().push((x, c));
}
let mut sel_seq = 0usize;
// Grid selection pairs: filled as one union rectangle (lattice
// gaps included), not per-cell patches. Cell rectangles (contents)
// and lanes (the column/row itself) collect separately — they
// paint in different colors. The frame pair (whole edited array)
// reads its extent from the end of the extents list.
let mut cell_boxes: Vec<(usize, usize, usize, usize)> = Vec::new(); // (o, close, t, b)
let mut lane_boxes: Vec<(usize, usize, usize, usize)> = Vec::new();
let mut row_lane_boxes: Vec<(usize, usize, usize, usize)> = Vec::new();
// The frame rectangle comes straight off its corner marks — the
// render puts `Mark::Frame{open:true}` on the framed block's
// top-left cell and the close mark on its bottom-right (delimiters
// included when fused).
let tl = marks
.iter()
.find(|&&(_, _, c)| Mark::decode(c) == Some(Mark::Frame { open: true }));
let br = marks
.iter()
.find(|&&(_, _, c)| Mark::decode(c) == Some(Mark::Frame { open: false }));
let frame: Option<(usize, usize, usize, usize)> = match (tl, br) {
(Some(&(t, x0, _)), Some(&(b, x1, _))) => Some((x0, x1, t, b)),
_ => None,
};
// Same corner geometry for a delimiter armed for unwrapping, read
// separately: only its two columns light up, not the lattice.
let mut armed: Option<(usize, usize, usize, usize)> = match (
marks
.iter()
.find(|&&(_, _, c)| Mark::decode(c) == Some(Mark::Delims { open: true })),
marks
.iter()
.find(|&&(_, _, c)| Mark::decode(c) == Some(Mark::Delims { open: false })),
) {
(Some(&(t, x0, _)), Some(&(b, x1, _))) => Some((x0, x1, t, b)),
_ => None,
};
// An armed │ middle lights just its own column: walk right from
// the mark to the │, then take its full vertical run.
if let Some(&(y, x, _)) = marks
.iter()
.find(|&&(_, _, c)| Mark::decode(c) == Some(Mark::MidArm))
{
let mid = formulaa::glyphs::MID;
let col = (x..grid[y].len()).find(|&cx| grid[y].get(cx) == Some(&mid));
if let Some(cx) = col {
let mut t = y;
while t > 0 && grid[t - 1].get(cx) == Some(&mid) {
t -= 1;
}
let mut b = y;
while b + 1 < grid.len() && grid[b + 1].get(cx) == Some(&mid) {
b += 1;
}
armed = Some((cx, cx, t, b));
}
}
for (y, mut row_marks) in by_row {
// Coincident ^B opens (an ancestor ring starting at the same
// cell as an inner ring) must stack outer-first so each close
// pops its own rank; everything else keeps plain (x, char)
// order.
row_marks.sort_unstable_by(|a, b| {
let open_rank = |c: char| match Mark::decode(c) {
Some(Mark::BlockOpen { rank }) => Some(rank),
_ => None,
};
(a.0.cmp(&b.0)).then_with(|| match (open_rank(a.1), open_rank(b.1)) {
(Some(ra), Some(rb)) => rb.cmp(&ra),
_ => a.1.cmp(&b.1),
})
});
let mut stack: Vec<(usize, Mark)> = Vec::new();
for (x, c) in row_marks {
let Some(mark) = Mark::decode(c) else {
continue;
};
// The vertical reach of a pair comes from the extents list,
// in the same encounter order the editor built it.
let mut extent = |seq: Option<usize>| {
let e = match seq {
Some(i) => extents.get(i),
None => {
let e = extents.get(sel_seq);
sel_seq += 1;
e
}
};
let (t, b) = match e {
Some(&(above, below, _)) => (
y.saturating_sub(above),
(y + below).min(grid.len().saturating_sub(1)),
),
None => (y, y),
};
(t, b, e.map_or(0, |&(_, _, d)| d))
};
match mark {
// The corner pairs (and the mid mark) are read by
// the scans above.
Mark::Frame { .. } | Mark::Delims { .. } | Mark::MidArm => {}
// A close pops its *matching* open — a standalone mark
// (a rank, a gap ghost) must never satisfy a pair.
Mark::Cells { open: false } | Mark::Lane { open: false, .. } => {
let opener = mark.opener();
if let Some((o, _)) = pop_matching(&mut stack, |k| Some(k) == opener) {
let (t, b, _) = extent(None);
// An empty cell's pair is zero-width: keep one
// cell so the selection stays visible.
let entry = (o, x.max(o + 1), t, b);
match mark {
Mark::Cells { .. } => cell_boxes.push(entry),
Mark::Lane { cols: true, .. } => lane_boxes.push(entry),
_ => row_lane_boxes.push(entry),
}
}
}
Mark::Sel { open: false } | Mark::BlockClose => {
// A BlockOpen's rank is not part of the pairing
// (any open ends at the next BlockClose).
let opener = mark.opener();
let matches_opener = |k: Mark| match (k, opener) {
(Mark::BlockOpen { .. }, Some(Mark::BlockOpen { .. })) => true,
(k, o) => Some(k) == o,
};
if let Some((o, oc)) = pop_matching(&mut stack, matches_opener) {
let (kind, depth, t, b) = match oc {
Mark::BlockOpen { rank } => {
// Only the highlighted ancestor and
// the one step outward are marked:
// the provisional selection blinks
// purple, the step is a steady
// reverse-video ring.
let (t, b, d) = extent(Some(rank));
if block_selected == Some(rank) {
(BoxKind::Sel, d, t, b)
} else {
(BoxKind::Step, d, t, b)
}
}
_ => {
// The linear Shift selection blinks
// like ^B's: one look for "selected".
let (t, b, _) = extent(None);
(BoxKind::Sel, 0, t, b)
}
};
boxes.push((o, x, kind, t, b));
order.push(depth);
}
}
Mark::Sel { open: true }
| Mark::Cells { open: true }
| Mark::Lane { open: true, .. }
| Mark::BlockOpen { .. } => stack.push((x, mark)),
_ => {}
}
}
}
// Outer boxes first so nested ones paint over them. The ^B rank is
// innermost-first (rank 0 = the innermost parent), so paint in
// descending rank: outermost ancestors below, inner ones on top.
let mut idx: Vec<usize> = (0..boxes.len()).collect();
idx.sort_by_key(|&i| std::cmp::Reverse(order[i]));
// Flash (the provisional selection) and the bg grounds paint in
// one outer-to-inner pass, each overwriting the other: the
// selected ancestor covers its outer neighbour's ground, and the
// inner step box then punches through the flash. A separate later
// flash pass loses the first half of that — the outer white
// ground swallows the purple whenever the selection is not the
// outermost ancestor.
let mut flash_grid: Vec<Vec<bool>> = bg.iter().map(|r| vec![false; r.len()]).collect();
let mut invert_grid: Vec<Vec<bool>> = bg.iter().map(|r| vec![false; r.len()]).collect();
for i in idx {
let (o, close, kind, t, b) = boxes[i];
for y in t..=b.min(bg.len().saturating_sub(1)) {
for x in o..close {
if x < bg[y].len() {
match kind {
BoxKind::Sel => {
bg[y][x] = Some(theme::SELECTION_BG);
flash_grid[y][x] = true;
invert_grid[y][x] = false;
}
BoxKind::Step => {
bg[y][x] = None;
flash_grid[y][x] = false;
invert_grid[y][x] = true;
}
}
}
}
}
}
// The grid selections paint one solid rectangle in the selection
// color. A cell rectangle hugs the union of its slots; a lane
// stretches along its axis to the matrix region's far edges (that
// reach is what tells "the column itself" from "every cell of the
// column").
let mut fill = |x0: usize, x1: usize, t: usize, b: usize| {
for row in bg.iter_mut().take(b + 1).skip(t) {
for x in x0..x1 {
if x < row.len() {
row[x] = Some(theme::SELECTION_BG);
}
}
}
};
let bbox = |g: &Vec<(usize, usize, usize, usize)>| {
(
g.iter().map(|&(o, ..)| o).min().unwrap(),
g.iter().map(|&(_, c, ..)| c).max().unwrap(),
g.iter().map(|&(.., t, _)| t).min().unwrap(),
g.iter().map(|&(.., b)| b).max().unwrap(),
)
};
if !cell_boxes.is_empty() {
let (x0, x1, t, b) = bbox(&cell_boxes);
fill(x0, x1, t, b);
}
if !lane_boxes.is_empty() {
let (x0, x1, t, b) = bbox(&lane_boxes);
// Columns: top-to-bottom edge of the matrix region, and one
// cell of slot padding sideways — a fused matrix has no extra
// rows above its cells, so the extra width is what keeps the
// column band tellable from a full-column cell selection.
let (t, b) = frame.map_or((t, b), |(_, _, ft, fb)| (ft, fb));
fill(x0.saturating_sub(1), x1 + 1, t, b);
}
if !row_lane_boxes.is_empty() {
let (x0, x1, t, b) = bbox(&row_lane_boxes);
// Rows: left-to-right edge of the matrix region.
let (x0, x1) = frame.map_or((x0, x1), |(fo, fc, _, _)| (fo, fc + 1));
fill(x0, x1, t, b);
}
// The grid lane-gap cursor: the ghost lane paints with exactly the
// lane-selection geometry (edge-to-edge along its axis, slot
// padding sideways for columns), just in the insert green.
for is_col in [true, false] {
let gaps: Vec<(usize, usize)> = marks
.iter()
.filter(|&&(_, _, c)| Mark::decode(c) == Some(Mark::Gap { cols: is_col }))
.map(|&(y, x, _)| (y, x))
.collect();
if gaps.is_empty() {
continue;
}
let t = gaps.iter().map(|&(y, _)| y).min().unwrap();
let b = gaps.iter().map(|&(y, _)| y).max().unwrap();
let x0 = gaps.iter().map(|&(_, x)| x).min().unwrap();
let x1 = gaps.iter().map(|&(_, x)| x).max().unwrap() + 1;
let (x0, x1, t, b) = if is_col {
let (t, b) = frame.map_or((t, b), |(_, _, ft, fb)| (ft, fb));
(x0.saturating_sub(1), x1 + 1, t, b)
} else {
let (x0, x1) = frame.map_or((x0, x1), |(fo, fc, _, _)| (fo, fc + 1));
(x0, x1, t, b)
};
for row in bg.iter_mut().take(b + 1).skip(t) {
for x in x0..x1 {
if x < row.len() {
row[x] = Some(theme::GRID_INSERT_BG);
}
}
}
}
let bold = bg.iter().map(|r| vec![false; r.len()]).collect();
let mut decor = Decor {
lines: grid,
bg,
bold,
flash: flash_grid,
invert: invert_grid,
blip: false,
caret: None,
frame,
armed,
};
// The caret cell (padded blank at the row end).
if let Some((y, x)) = caret {
decor.widen(y, x);
decor.caret = caret;
}
decor
}
/// Where the canvas sits on screen, so a floating layer can tell how
/// much room it has: canvas cell (y, x) is drawn at screen
/// (top + y - scroll_y, left + x - scroll_x), inside `width`x`height`.
#[derive(Clone, Copy)]
struct Viewport {
left: u16,
top: u16,
scroll_x: usize,
scroll_y: usize,
width: usize,
height: usize,
}
impl Viewport {
/// A viewport with room to spare, for tests that are about what an
/// overlay draws rather than where it fits.
#[cfg(test)]
fn unbounded() -> Viewport {
Viewport {
left: 0,
top: 0,
scroll_x: 0,
scroll_y: 0,
width: 200,
height: 200,
}
}
/// The screen row a canvas row lands on (None when scrolled off).
fn row_on_screen(&self, y: usize) -> Option<usize> {
y.checked_sub(self.scroll_y).map(|r| r + self.top as usize)
}
/// The screen column a canvas column lands on.
fn col_on_screen(&self, x: usize) -> usize {
x.saturating_sub(self.scroll_x) + self.left as usize
}
}
fn overlay_minibuffer(
ed: &Editor,
d: &mut Decor,
view: Viewport,
) -> Option<(usize, usize, usize, usize, usize)> {
// The in-place name box (\op \rm \text \latex) overlays exactly
// like the minibuffer: content cells at the cursor, caret at the
// box's own cursor. Drawing it as cells (not AST nodes) keeps the
// run free of the reparse-quoting rules — no stray '…' quotes.
if let Some((_, buf)) = &ed.op_entry {
let (cy, cx) = d.caret?;
if cy >= d.height() {
return None;
}
let content: Vec<char> = if buf.is_empty() {
vec!['⬚']
} else {
// No box holds meaningful spaces except \text/\latex,
// which show them as-is.
buf.chars().collect()
};
// The box shows as [content]: bracket fenders drawn as green
// glyphs (no ground — same look as the ^G grid frame), content
// on the box ground.
let end = cx + content.len() + 2;
d.widen(cy, end);
d.lines[cy][cx] = FENDER_L;
for (i, &ch) in content.iter().enumerate() {
d.lines[cy][cx + 1 + i] = ch;
d.bg[cy][cx + 1 + i] = Some(theme::MINIBUF_BG);
}
d.lines[cy][end - 1] = FENDER_R;
d.caret = Some((cy, cx + 1 + ed.op_cursor.min(content.len())));
return None;
}
let Some(buf) = &ed.minibuffer else {
return None;
};
let (cy, cx) = d.caret?;
if cy >= d.height() {
return None;
}
let text: Vec<char> = std::iter::once('\\').chain(buf.chars()).collect();
let end = cx + text.len();
d.widen(cy, end);
// Live feedback: green runs an edit, purple is a mode command,
// red runs nothing (yet) — \tau walks red -> purple (\t) ->
// green (\ta) as the name grows.
let color = if ed.command_known(buf) {
theme::MINIBUF_BG
} else if formulaa::editor::mode_command(buf).is_some() {
theme::MINIBUF_MODE_BG
} else {
theme::MINIBUF_BAD_BG
};
for (i, &ch) in text.iter().enumerate() {
d.lines[cy][cx + i] = ch;
d.bg[cy][cx + i] = Some(color);
}
// Tab opens the completion list, which replaces the preview: it
// already shows what each row inserts, next to the spellings.
if let Some(list) = &ed.completion {
let hit = overlay_completion(list, d, (cy, cx), view);
d.caret = Some((cy, end));
return hit;
}
// The command previews what committing would insert, as a small
// box right under the typed name — a symbol as its one character,
// a structure (\frac, \pmatrix …) with its empty ⬚ slots. It is a
// layer floating above the formula: it covers what is under it and
// never reflows anything, so the formula the user is aiming at
// stays put while they type (draw_canvas centers on the formula
// alone for the same reason).
if let Some(row) = ed.command_preview_row() {
use formulaa::render::{RenderCtx, render_root};
let block = render_root(&row, None, &RenderCtx::canonical());
// The preview is the completion popup with one row, so it is
// drawn as one: the same ground, the same blank column each
// side, on the same side of the caret. A box that jumped as
// Tab was pressed read as two features.
let below = place_below(&view, cy);
let box_w = block.lines.iter().map(Vec::len).max().unwrap_or(0) + 2;
for (dy, bline) in block.lines.iter().enumerate() {
let y = if below {
cy + 1 + dy
} else {
// Upward: bottom-anchored just above the caret row;
// rows that do not fit are dropped rather than
// spilling over the typed \name.
match (cy + dy).checked_sub(block.height()) {
Some(y) => y,
None => continue,
}
};
d.ensure_row(y);
d.widen(y, cx + box_w - 1);
for dx in 0..box_w {
let ch = dx
.checked_sub(1)
.and_then(|i| bline.get(i).copied())
.unwrap_or(' ');
d.lines[y][cx + dx] = ch;
d.bg[y][cx + dx] = Some(theme::POPUP_BG);
}
}
}
d.caret = Some((cy, end));
None
}
fn place_below(view: &Viewport, cy: usize) -> bool {
let caret_row = view.row_on_screen(cy).unwrap_or(0);
let below = view.height.saturating_sub(caret_row + 1);
let above = caret_row.min(cy);
below >= above || above == 0
}
fn overlay_completion(
list: &formulaa::complete::Completion,
d: &mut Decor,
caret: (usize, usize),
view: Viewport,
) -> Option<(usize, usize, usize, usize, usize)> {
let (cy, cx) = caret;
if list.items.is_empty() {
return None;
}
// One column for the symbols, one for the spellings, so the rows
// line up into two readable columns.
let sym_w = list
.items
.iter()
.map(|i| i.symbol.chars().count())
.max()
.unwrap_or(0);
let rows: Vec<Vec<char>> = list
.items
.iter()
.map(|item| {
let pad = sym_w - item.symbol.chars().count();
format!(" {}{} {} ", item.symbol, " ".repeat(pad), item.names)
.chars()
.collect()
})
.collect();
let box_w = rows.iter().map(|r| r.len()).max().unwrap_or(0);
// Vertical: how many rows are free on each side of the caret's own
// screen row. A caret scrolled out of view leaves the popup where
// it would have been.
let caret_row = view.row_on_screen(cy).unwrap_or(0);
let below = view.height.saturating_sub(caret_row + 1);
let above = caret_row.min(cy);
let downward = place_below(&view, cy);
let room = if downward { below } else { above }.max(1);
let shown = rows.len().min(room);
// Scroll the window so the selection is inside it.
let start = list
.sel
.saturating_sub(shown - 1)
.min(rows.len() - shown)
.min(list.sel);
let top = if downward {
cy + 1
} else {
// Opening upward: the last drawn row sits just above the caret.
cy.saturating_sub(shown)
};
// Horizontal: shift left so the box fits. It can only travel as far
// as the canvas's own left edge — the centering pad left of that is
// screen space the Decor cannot address — so whatever still hangs
// over the right edge is trimmed, ending in an ellipsis. A row cut
// by the border reads as a rendering fault; one that ends in `…`
// reads as "there is more".
let overflow = (view.col_on_screen(cx) + box_w).saturating_sub(view.width);
let x0 = cx.saturating_sub(overflow).max(view.scroll_x);
let box_w = box_w.min(view.width.saturating_sub(view.col_on_screen(x0)));
if box_w == 0 {
return None;
}
for (i, row) in rows[start..start + shown].iter().enumerate() {
let y = top + i;
d.ensure_row(y);
d.widen(y, x0 + box_w.saturating_sub(1));
// A mode command's symbol is its chord, `[^F]`: drawn bold, so
// the marker reads apart from the glyphs without a row tint
// (a tinted row under the selection highlight reads as
// neither).
let item = &list.items[start + i];
let mode = item
.commit()
.is_some_and(|c| formulaa::editor::mode_command(c).is_some());
let bg = if start + i == list.sel {
theme::POPUP_SEL_BG
} else {
theme::POPUP_BG
};
for dx in 0..box_w {
let trimmed = dx + 1 == box_w && row.len() > box_w;
d.lines[y][x0 + dx] = if trimmed {
'…'
} else {
row.get(dx).copied().unwrap_or(' ')
};
d.bg[y][x0 + dx] = Some(bg);
// The chord sits in the symbol column: " [^F]" is
// columns 1..=sym_w of the row.
d.bold[y][x0 + dx] = mode && (1..=sym_w).contains(&dx);
}
}
// The drawn rectangle, for mouse hit-testing (a click on a row
// accepts it).
Some((top, x0, box_w, start, shown))
}
/// A close mark pops its *matching* open; standalone marks in between
/// (ranks, gap ghosts) stay on the stack.
fn pop_matching(
stack: &mut Vec<(usize, Mark)>,
ok: impl Fn(Mark) -> bool,
) -> Option<(usize, Mark)> {
let at = stack.iter().rposition(|&(_, m)| ok(m))?;
Some(stack.remove(at))
}
/// Display sentinels for the open name box's [ ] fenders: drawn as
/// green glyphs (the ^G frame color), never as ordinary text.
const FENDER_L: char = '\u{F8F0}';
const FENDER_R: char = '\u{F8F1}';
/// Delimiter pieces: recolored only on the rectangle's edge columns —
/// a fused matrix's own parens sit exactly there, while a delimiter
/// nested inside a cell does not. The pair pieces come from the
/// symbols table; the extras are the shapes drawn outside it (angle
/// arms, mid/norm columns, over/underbrace corners).
fn is_delim_piece(c: char) -> bool {
use formulaa::glyphs::{ARM_FALL, ARM_RISE, MID, NORM, is_brace_corner};
formulaa::symbols::Delim::all_pieces().contains(&c)
|| matches!(c, ARM_RISE | ARM_FALL | MID | NORM)
|| is_brace_corner(c)
}
/// The pieces a radical shows on its left column: the root glyph and
/// the overline's corner above it (its stem is the shared │, already a
/// delim piece). An armed radical lights these the way an armed pair
/// lights its delimiters.
fn is_radical_piece(c: char) -> bool {
matches!(c, '√' | '∛' | '∜' | formulaa::glyphs::OVERLINE_CORNER)
}
/// A wide accent's visible pieces: the `┈` band and the mark material
/// riding in it. An armed accent lights its bands (which live on the
/// rect's top/bottom rows), since it has no delimiter columns to
/// light.
fn is_accent_band_piece(c: char) -> bool {
c == formulaa::glyphs::OP_BAND
|| formulaa::symbols::Accent::ALL
.iter()
.any(|a| a.cells().contains(&c))
}
/// Turn a rendered cell row into spans: private-use marker chars become
/// their glyphs, the cursor glyph blinks, and box
/// backgrounds from `marker_boxes` are applied to plain glyphs.
fn decorate_line(d: &Decor, y: usize, caret: CaretStyle, scroll_x: usize) -> Vec<Span<'static>> {
let (line, bg) = (&d.lines[y], &d.bg[y]);
let cursor = d.caret.and_then(|(cy, cx)| (cy == y).then_some(cx));
let cursor_style = match caret {
// Inside a name box: the caret turns green so the modal layer
// is visible at the cursor itself.
CaretStyle::Box => Style::default()
.fg(theme::BOX_CURSOR_FG)
.bg(theme::BOX_CURSOR_BG)
.add_modifier(Modifier::BOLD | Modifier::SLOW_BLINK),
// The free cursor keeps the selection purple (fixed white
// glyph, so it reads on light terminals too); the blink is
// what says "provisional".
CaretStyle::Free => Style::default()
.fg(theme::GROUND_FG)
.bg(theme::SELECTION_BG)
.add_modifier(Modifier::BOLD | Modifier::SLOW_BLINK),
CaretStyle::Normal => Style::default()
.add_modifier(Modifier::REVERSED | Modifier::BOLD | Modifier::SLOW_BLINK),
};
let mut spans = Vec::new();
let mut buf = String::new();
let mut buf_bg: Option<Color> = None;
let blip = d.blip;
let flush = move |buf: &mut String, buf_bg: Option<Color>, spans: &mut Vec<Span<'static>>| {
if !buf.is_empty() {
let s = std::mem::take(buf);
spans.push(match buf_bg {
// A themed ground fixes its glyph color too: the
// terminal's own foreground (black, on a light theme)
// has no contrast guarantee against it.
Some(color) => {
let mut style = Style::default().bg(color).fg(theme::GROUND_FG);
// Grid-mode selections have no flash cells, so the
// copy blip inverts their ground here instead.
if blip && color == theme::SELECTION_BG {
style = style.add_modifier(Modifier::REVERSED);
}
Span::styled(s, style)
}
None => Span::raw(s),
});
}
};
for (i, &c) in line.iter().enumerate().skip(scroll_x) {
let cell_bg = bg.get(i).copied().flatten();
// Display chars resolve to their glyph before ANY branch draws
// the cell: a private-use codepoint reaching the terminal shows
// as whatever the font maps that page to (fonts keep logos
// there), so no branch — the caret included — may emit `c` raw.
let shown = match (c, Mark::decode(c)) {
(FENDER_L, _) => '[',
(FENDER_R, _) => ']',
// Backstop for every decoration: blank, never raw.
_ if is_display_marker(c) => ' ',
_ => c,
};
let cell = shown.to_string();
if cursor == Some(i) {
flush(&mut buf, buf_bg, &mut spans);
let style = match cell_bg {
Some(color) if caret != CaretStyle::Free => cursor_style.bg(color),
_ => cursor_style,
};
spans.push(Span::styled(cell, style));
} else if d.invert.get(y).and_then(|r| r.get(i)).copied() == Some(true) {
// A secondary mark: reverse video (blinking when it is
// also provisional — the ^F snap preview). No fixed color,
// so it reads under any terminal theme.
flush(&mut buf, buf_bg, &mut spans);
let mut m = Modifier::REVERSED;
if d.flash.get(y).and_then(|r| r.get(i)).copied() == Some(true) {
m |= Modifier::SLOW_BLINK;
}
spans.push(Span::styled(cell, Style::default().add_modifier(m)));
} else if d.flash.get(y).and_then(|r| r.get(i)).copied() == Some(true) {
// A provisional ground blinks: ^B's highlighted ancestor
// (purple) and ^F's snap preview (white) keep their own
// color, and the blink is what says "not committed yet".
// A copy acknowledges itself by inverting these grounds
// for one brief blip.
flush(&mut buf, buf_bg, &mut spans);
let mut style = Style::default().add_modifier(Modifier::SLOW_BLINK);
if d.blip {
style = style.add_modifier(Modifier::REVERSED);
}
if let Some(color) = cell_bg {
style = style.bg(color).fg(theme::GROUND_FG);
}
spans.push(Span::styled(cell, style));
} else if c == FENDER_L || c == FENDER_R {
// The open box's fenders: green glyphs, no ground.
flush(&mut buf, buf_bg, &mut spans);
let mut style = Style::default()
.fg(theme::GRID_FRAME_FG)
.add_modifier(Modifier::BOLD);
if let Some(color) = cell_bg {
style = style.bg(color);
}
spans.push(Span::styled(cell, style));
} else if c == '␣' {
flush(&mut buf, buf_bg, &mut spans);
// The ␣ glyph dims on the open canvas; on a themed
// ground it turns white like any other glyph there (dim
// gray on dark purple reads as a hole).
let mut style = Style::default().fg(theme::SPACE_FG);
if let Some(color) = cell_bg {
style = style.bg(color).fg(theme::GROUND_FG);
}
spans.push(Span::styled(cell, style));
} else if d.bold.get(y).and_then(|r| r.get(i)).copied() == Some(true) {
// A bold cell (the completion's [^F] chord markers): its
// own span, keeping whatever background it carries.
flush(&mut buf, buf_bg, &mut spans);
let mut style = Style::default().add_modifier(Modifier::BOLD);
if let Some(color) = cell_bg {
style = style.bg(color).fg(theme::GROUND_FG);
}
spans.push(Span::styled(cell, style));
} else if d.armed.is_some_and(|(o, close, t, b)| {
// A delimiter armed for unwrapping: its two columns take the
// selection ground, because they are exactly what the next
// Backspace/^D removes.
(t..=b).contains(&y)
&& (((is_delim_piece(c) || is_radical_piece(c)) && (i == o || i == close))
// A wide accent has no side columns; its bands run
// along the rect's top/bottom rows.
|| (is_accent_band_piece(c) && (y == t || y == b) && (o..=close).contains(&i)))
}) {
flush(&mut buf, buf_bg, &mut spans);
spans.push(Span::styled(
cell,
Style::default()
.bg(theme::SELECTION_BG)
.fg(theme::GROUND_FG)
.add_modifier(Modifier::BOLD),
));
} else if d.frame.is_some_and(|(o, close, t, b)| {
// The edited grid's frame recolors while grid mode is on.
// The rectangle is exact (render-placed corners): lattice
// glyphs recolor anywhere inside it, delimiter pieces only
// on its edge columns — so a delimiter nested in a cell
// stays untinted, and a one-line pmatrix's parens tint.
(t..=b).contains(&y)
&& ((is_lattice_glyph(c) && (o..=close).contains(&i))
|| (is_delim_piece(c) && (i == o || i == close)))
}) {
flush(&mut buf, buf_bg, &mut spans);
let mut style = Style::default().fg(theme::GRID_FRAME_FG);
if let Some(color) = cell_bg {
style = style.bg(color);
}
spans.push(Span::styled(cell, style));
} else {
if cell_bg != buf_bg {
flush(&mut buf, buf_bg, &mut spans);
buf_bg = cell_bg;
}
buf.push_str(&cell);
}
}
flush(&mut buf, buf_bg, &mut spans);
spans
}
#[cfg(test)]
mod tests {
/// A formula larger than the canvas scrolls on both axes so the
/// cursor stays visible; one that fits is centered (offsets 0).
#[test]
fn canvas_scrolls_to_follow_the_cursor() {
use ratatui::{Terminal, backend::TestBackend};
let render = |ed: &Editor, w: u16, h: u16| -> View {
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| {
draw(f, ed, &mut view);
})
.unwrap();
view
};
// Fits: centered, no scrolling.
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+1");
let v = render(&ed, 40, 12);
assert_eq!((v.scroll_x, v.scroll_y), (0, 0));
// Wide: the cursor sits at the right end, so the view scrolled.
let mut ed = Editor::new();
type_script_keys(&mut ed, &"a+".repeat(40));
let v = render(&ed, 24, 12);
assert!(v.scroll_x > 0, "no horizontal scroll: {}", v.scroll_x);
assert_eq!(v.scroll_y, 0);
// Tall: many display lines, cursor on the last one.
let mut ed = Editor::new();
for _ in 0..12 {
ed.input(Key::Char('x'), false, false);
ed.input(Key::Enter, false, false);
}
let v = render(&ed, 40, 8);
assert!(v.scroll_y > 0, "no vertical scroll: {}", v.scroll_y);
// …and moving back to the top scrolls back.
ed.input(Key::Char('a'), false, true); // ^A: document start
let v = render(&ed, 40, 8);
assert_eq!(v.scroll_y, 0, "did not scroll back to the top");
}
use super::*;
use formulaa::input::Key;
/// Full display pipeline: decorated AST -> render -> marker_boxes.
fn display(ed: &Editor) -> Vec<String> {
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let ctx = RenderCtx { italic: true };
let block = render_root(&root, cursor_ref, &ctx);
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
d.lines.into_iter().map(String::from_iter).collect()
}
/// The full grid-mode display pipeline: selected cells paint the
/// selection color at their own height, and a lane gap shows the
/// green ghost column.
#[test]
fn grid_mode_paints_cells_and_gaps() {
let bg_of = |ed: &Editor| {
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
)
};
let mut ed = Editor::new();
for c in "\\bmatrix22 a".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('g'), false, true); // ^G grid
// Cell cursor: the current (top-left) cell is painted.
let d = bg_of(&ed);
let painted =
d.bg.iter()
.flatten()
.filter(|c| **c == Some(theme::SELECTION_BG))
.count();
assert!(painted > 0, "cell cursor paints its cell");
// Column mode on a gap: the green ghost lane appears.
ed.input(Key::Char('|'), false, false);
ed.input(Key::Left, false, false); // gap 0
let d = bg_of(&ed);
let green =
d.bg.iter()
.flatten()
.filter(|c| **c == Some(theme::GRID_INSERT_BG))
.count();
assert!(green > 0, "gap cursor paints the ghost lane");
// Back on a column: the lane band stretches to the matrix
// region's top and bottom edges — the reach (not a second
// color) is what tells "the column itself" apart from a
// cell selection.
ed.input(Key::Right, false, false);
let d = bg_of(&ed);
let sel_rows: Vec<usize> =
d.bg.iter()
.enumerate()
.filter(|(_, row)| row.contains(&Some(theme::SELECTION_BG)))
.map(|(y, _)| y)
.collect();
assert!(
sel_rows.len() >= 3,
"column lane spans every display row: {:?}",
sel_rows
);
// The frame rect is reported while grid mode is on (the draw
// path recolors the lattice glyphs inside it).
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
assert!(d.frame.is_some(), "grid mode reports its frame rect");
// The gap's green bar runs unbroken through the lattice rows:
// every display row between the first and last green cell has
// green in it (a 2-row matrix has a separator row between).
ed.input(Key::Left, false, false); // back to gap 0
let d = bg_of(&ed);
let green_rows: Vec<usize> =
d.bg.iter()
.enumerate()
.filter(|(_, row)| row.contains(&Some(theme::GRID_INSERT_BG)))
.map(|(y, _)| y)
.collect();
assert!(green_rows.len() >= 3, "green spans rows: {:?}", green_rows);
let (lo, hi) = (green_rows[0], *green_rows.last().unwrap());
assert_eq!(
green_rows.len(),
hi - lo + 1,
"no holes in the gap bar: {:?}",
green_rows
);
// The column band is strictly wider than the same column's
// cell selection: it claims the slot padding, which is what
// keeps "the column itself" visible as such in a fused matrix.
let width_at = |d: &Decor, y: usize| {
d.bg[y]
.iter()
.filter(|c| **c == Some(theme::SELECTION_BG))
.count()
};
ed.input(Key::Right, false, false); // gap 0 -> column 0
let d = bg_of(&ed);
let lane_row =
d.bg.iter()
.position(|row| row.contains(&Some(theme::SELECTION_BG)))
.unwrap();
let lane_w = width_at(&d, lane_row);
ed.input(Key::Up, false, false); // demote: full-column cells
let d = bg_of(&ed);
let cells_row =
d.bg.iter()
.position(|row| row.contains(&Some(theme::SELECTION_BG)))
.unwrap();
let cells_w = width_at(&d, cells_row);
assert!(
lane_w > cells_w,
"lane band wider than cell band: {} vs {}",
lane_w,
cells_w
);
}
/// The frame survives a gap cursor on the matrix's baseline row:
/// the gap's ghost marks share that row with the frame pair, and
/// pairing must not let a ghost mark satisfy the frame close.
#[test]
fn frame_survives_a_middle_row_gap() {
let mut ed = Editor::new();
for c in r"\bmatrix22 a".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('g'), false, true);
ed.input(Key::Char('r'), false, false);
ed.input(Key::Down, false, false); // the gap between the rows
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
let (o, close, t, b) = d.frame.expect("frame rect survives the gap row");
assert!(close - o >= 6, "full-width frame: {:?}", (o, close));
assert!(b - t >= 2, "full-height frame: {:?}", (t, b));
}
/// A fused matrix (pmatrix/bmatrix) recolors BOTH delimiter
/// columns as its frame — the markers sit just inside them.
#[test]
fn fused_frame_recolors_both_delimiters() {
let mut ed = Editor::new();
for c in r"\pmatrix22 a".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('g'), false, true); // ^G grid
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
let (o, close, t, b) = d.frame.expect("frame rect");
// Walk every framed row and collect which columns the draw
// pass would tint; the leftmost and rightmost delimiter pieces
// must both be inside the scan range.
let mut tinted = std::collections::HashSet::new();
for line in d.lines.iter().take(b + 1).skip(t) {
for (i, &c) in line.iter().enumerate() {
if (is_lattice_glyph(c) && (o..=close).contains(&i))
|| (is_delim_piece(c) && (i == o || i == close))
{
tinted.insert(c);
}
}
}
assert!(
tinted.iter().any(|c| "⎛⎜⎝(".contains(*c)),
"left paren column tinted: {:?}",
tinted
);
assert!(
tinted.iter().any(|c| "⎞⎟⎠)".contains(*c)),
"right paren column tinted: {:?}",
tinted
);
}
/// A bare array that merely sits INSIDE a delimiter (not fused —
/// it has siblings) keeps the frame recolor to its own lattice:
/// the enclosing parens stay untinted.
#[test]
fn unfused_frame_leaves_the_outer_delimiter_alone() {
use formulaa::ast::{Field, Node};
use formulaa::symbols::ColDelim as C;
use formulaa::symbols::Delim as D;
let mut ed = Editor::new();
ed.root = vec![Node::Delim {
left: D::Col(C::Paren),
right: D::Col(C::Paren),
mids: 0,
segs: vec![vec![
Node::Array {
rows: 2,
cols: 2,
cells: vec![vec![Node::Sym('x')], vec![], vec![], vec![]],
},
Node::Sym('f'),
]],
}];
ed.path = vec![(0, Field::Seg(0)), (0, Field::Cell(0))];
ed.col = 0;
ed.input(Key::Char('g'), false, true); // ^G grid
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
let (o, close, t, b) = d.frame.expect("frame rect");
let mut tinted = std::collections::HashSet::new();
for line in d.lines.iter().take(b + 1).skip(t) {
for (i, &c) in line.iter().enumerate() {
if (is_lattice_glyph(c) && (o..=close).contains(&i))
|| (is_delim_piece(c) && (i == o || i == close))
{
tinted.insert(c);
}
}
}
assert!(
tinted.iter().any(|c| "┌┼┬├".contains(*c)),
"array lattice tinted: {:?}",
tinted
);
assert!(
!tinted.iter().any(|c| "⎛⎜⎝⎞⎟⎠()".contains(*c)),
"outer parens must stay untinted: {:?}",
tinted
);
}
/// The exact corner-based frame: a matrix nested inside a cell
/// keeps its own delimiters untinted while the outer frame colors.
#[test]
fn frame_rect_is_exact() {
let mut ed = Editor::new();
for c in r"\bmatrix22 ".chars() {
ed.input(Key::Char(c), false, false);
}
for c in r"\pmatrix22 x".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('g'), false, true); // grid mode on the INNER grid
ed.input(Key::Esc, false, false);
ed.input(Key::Tab, false, false); // out of inner seg…
ed.input(Key::Tab, false, false); // …back into the outer cell
ed.input(Key::Char('g'), false, true); // grid mode on the OUTER grid
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
let (o, close, t, b) = d.frame.expect("outer frame rect");
let mut tinted = std::collections::HashSet::new();
for line in d.lines.iter().take(b + 1).skip(t) {
for (i, &c) in line.iter().enumerate() {
if (is_lattice_glyph(c) && (o..=close).contains(&i))
|| (is_delim_piece(c) && (i == o || i == close))
{
tinted.insert(c);
}
}
}
assert!(
!tinted.iter().any(|c| "⎛⎜⎝⎞⎟⎠()".contains(*c)),
"nested parens stay untinted: {:?}",
tinted
);
}
/// Mouse clicks stay true while the gap ghost (a width-bearing
/// decoration) is up: the probe render includes the ghost lane.
#[test]
fn click_lands_true_while_the_gap_ghost_is_up() {
let mut ed = Editor::new();
for c in r"\bmatrix22 x".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('g'), false, true);
ed.input(Key::Char('|'), false, false);
ed.input(Key::Left, false, false); // gap 0: ghost left of column 0
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut xy = None;
for (y, line) in block.lines.iter().enumerate() {
if let Some(x) = line.iter().position(|&c| c == '𝑥') {
xy = Some((y, x));
}
}
let (y, x) = xy.expect("x visible in the ghosted display");
ed.click(x, y);
assert!(
matches!(ed.path.last(), Some((_, formulaa::ast::Field::Cell(0)))),
"click lands in x's own cell: {:?}",
ed.path
);
}
/// Typing \alpha shows α as a ghost at the caret; typing \frac
/// floats the empty template under it — before committing.
#[test]
fn minibuffer_preview_shows_the_shape() {
let mut ed = Editor::new();
for c in "x\\alpha".chars() {
ed.input(Key::Char(c), false, false);
}
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
overlay_minibuffer(&ed, &mut d, Viewport::unbounded());
let (cy, _) = d.caret.unwrap();
let below: String = d.lines[cy + 1..].iter().flatten().collect();
assert!(below.contains('α'), "symbol previews below: {:?}", below);
let painted = d.bg[cy + 1..]
.iter()
.flatten()
.filter(|c| **c == Some(theme::POPUP_BG))
.count();
assert!(painted > 0, "preview cell painted");
// Structural command: the template floats below the caret.
let mut ed = Editor::new();
for c in "x\\frac".chars() {
ed.input(Key::Char(c), false, false);
}
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
overlay_minibuffer(&ed, &mut d, Viewport::unbounded());
let below: String = d.lines[1..].iter().flatten().collect();
assert!(
below.contains('─'),
"fraction bar in the preview: {:?}",
below
);
assert!(
below.contains('⬚'),
"empty slots in the preview: {:?}",
below
);
let previewed = d.bg[1..]
.iter()
.flatten()
.filter(|c| **c == Some(theme::POPUP_BG))
.count();
assert!(previewed > 0, "preview box painted");
}
/// The preview floats above the formula: opening one inside a
/// structure must not move a single formula row, because the user
/// is aiming at the layout underneath while they type.
#[test]
fn preview_floats_without_moving_the_formula() {
// 1/2 as a real fraction, cursor back up in the numerator: the
// preview lands on the bar row, with the denominator below it.
let mut ed = Editor::new();
type_script_keys(&mut ed, "//1");
ed.input(Key::Down, false, false);
ed.input(Key::Char('2'), false, false);
ed.input(Key::Up, false, false);
for c in "\\alpha".chars() {
ed.input(Key::Char(c), false, false);
}
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let rows = block.lines.len();
assert_eq!(rows, 3, "expected numerator/bar/denominator: {:?}", block);
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
overlay_minibuffer(&ed, &mut d, Viewport::unbounded());
let all: String = d.lines.iter().flatten().collect();
assert!(all.contains('α'), "the preview is drawn: {}", all);
// No row was opened, and the denominator is where it was.
assert_eq!(d.lines.len(), rows, "rows were opened: {:?}", d.lines);
assert!(
d.lines[rows - 1].contains(&'2'),
"the denominator moved: {:?}",
d.lines
);
}
/// …and the same at canvas level: the formula keeps its screen
/// position when a preview appears, rather than being re-centered
/// around the overlay.
#[test]
fn preview_does_not_move_the_formula_on_screen() {
use ratatui::{Terminal, backend::TestBackend};
let shot = |ed: &Editor| -> Vec<String> {
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(40, 14)).unwrap();
term.draw(|f| {
draw(f, ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect()
};
// \frac is the demanding case: the typed name runs past the
// right edge of a one-row formula and its template is three
// rows tall, so a canvas sized from the painted cells would
// re-center on both axes.
let at = |shot: &[String], ch: char| -> Option<(usize, usize)> {
shot.iter()
.enumerate()
.find_map(|(y, l)| l.find(ch).map(|x| (y, x)))
};
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y");
let before = shot(&ed);
let anchor = at(&before, '𝑥').expect("the formula is on screen");
for c in "\\frac".chars() {
ed.input(Key::Char(c), false, false);
}
let after = shot(&ed);
assert!(
after.iter().any(|l| l.contains('⬚')),
"the preview is drawn:\n{}",
after.join("\n")
);
assert_eq!(
at(&after, '𝑥'),
Some(anchor),
"the formula moved when the preview opened:\n{}\n---\n{}",
before.join("\n"),
after.join("\n")
);
}
/// The completion list draws under the typed name: a symbol
/// column, the spellings next to it, and the highlighted row
/// picked out — and, like every overlay, the formula stays put.
#[test]
fn the_completion_list_draws_under_the_name() {
use ratatui::{Terminal, backend::TestBackend};
let shot = |ed: &Editor| -> Vec<String> {
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(48, 16)).unwrap();
term.draw(|f| {
draw(f, ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect()
};
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y");
let before = shot(&ed);
let anchor = before
.iter()
.enumerate()
.find_map(|(y, l)| l.find('𝑥').map(|x| (y, x)))
.expect("the formula is on screen");
for c in "\\al".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Down, false, false);
let after = shot(&ed);
let screen = after.join("\n");
assert!(
screen.contains("al[p[ha]]"),
"the α row is listed:\n{}",
screen
);
assert!(screen.contains('α'), "the symbol column:\n{}", screen);
assert_eq!(
after
.iter()
.enumerate()
.find_map(|(y, l)| l.find('𝑥').map(|x| (y, x))),
Some(anchor),
"the formula moved under the popup:\n{}",
screen
);
// The highlighted row is painted apart from the rest.
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(48, 16)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let selected = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.filter(|&(x, y)| buf[(x, y)].bg == theme::POPUP_SEL_BG)
.count();
assert!(selected > 0, "no highlighted row:\n{}", screen);
}
/// The popup places itself to stay on screen: it scrolls its own
/// window so the highlighted row is drawn (arrows must never go
/// silent), opens upward when there is more room there, and shifts
/// left rather than running off the right edge.
#[test]
fn completion_popup_stays_on_screen() {
// An arrow always opens the list; Tab would commit these
// queries, since they are already commands.
let open = |ed: &mut Editor, q: &str| {
for c in format!("\\{}", q).chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Down, false, false);
};
// A short terminal cannot show all 12 rows: stepping to the
// last one must still show it highlighted somewhere.
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y");
open(&mut ed, "a");
let n = ed.completion.as_ref().unwrap().items.len();
assert!(n > 5, "need a list taller than the terminal: {}", n);
for _ in 0..n - 1 {
ed.input(Key::Down, false, false);
}
let last = ed.completion.as_ref().unwrap().items[n - 1].names.clone();
// Its opening letters, not the whole row: a row wider than the
// box is drawn trimmed, which is not what this is about.
let head: String = last.chars().take(5).collect();
let screen = shot_at(&ed, 40, 14).join("\n");
assert!(
screen.contains(&head),
"the selected row is off screen:\n{}",
screen
);
// Opening upward must not land on the formula: a multi-row
// formula with the caret low in it has more screen rows above
// the caret than below, but only as many *canvas* rows as the
// formula is tall — counting the centering pad as room is what
// used to clamp the box down onto the formula itself.
let mut ed = Editor::new();
type_script_keys(&mut ed, "//1");
ed.input(Key::Down, false, false);
ed.input(Key::Char('2'), false, false);
open(&mut ed, "al");
let screen = shot_at(&ed, 60, 20).join("\n");
assert!(
screen.contains('─') && screen.contains('2'),
"the popup covered the formula:\n{}",
screen
);
assert!(
screen.contains("\\al"),
"the popup covered the name being typed:\n{}",
screen
);
// Anchored near the right edge, the box shifts left instead of
// being cut off: a full row must survive intact.
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y+z+w+q+r+s+t");
open(&mut ed, "al");
let first = ed.completion.as_ref().unwrap().items[0].names.clone();
let screen = shot_at(&ed, 30, 20).join("\n");
assert!(
screen.contains(&first),
"row {:?} was clipped at the right edge:\n{}",
first,
screen
);
}
/// The preview and the completion list are one box at two sizes:
/// same neutral ground, same blank column each side, same side of
/// the caret and same starting column — pressing Tab must not make
/// the box jump. (The list's highlighted row is the one thing
/// colored, because it is the one thing that is a choice.)
#[test]
fn the_preview_and_the_popup_are_the_same_box() {
let where_is = |ed: &Editor, w: u16, h: u16, ch: char| -> Option<(usize, usize)> {
let mut view = View::default();
let mut term =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
term.draw(|f| {
draw(f, ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
(0..buf.area.height).find_map(|y| {
(0..buf.area.width).find_map(|x| {
let cell = &buf[(x, y)];
(cell.symbol() == ch.to_string()
&& (cell.bg == theme::POPUP_BG || cell.bg == theme::POPUP_SEL_BG))
.then_some((y as usize, x as usize))
})
})
};
// Same place, same ground, opening downward…
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y");
for c in "\\alpha".chars() {
ed.input(Key::Char(c), false, false);
}
let preview = where_is(&ed, 34, 12, 'α').expect("the preview is drawn on its own ground");
ed.input(Key::Down, false, false);
let popup = where_is(&ed, 34, 12, 'α').expect("the popup row is drawn");
assert_eq!(preview, popup, "the box moved");
// …and the same when there is no room below, so both flip up.
let mut ed = Editor::new();
for _ in 0..8 {
ed.input(Key::Char('x'), false, false);
ed.input(Key::Enter, false, false);
}
for c in "\\alpha".chars() {
ed.input(Key::Char(c), false, false);
}
let preview = where_is(&ed, 34, 8, 'α').expect("the preview lands on screen");
ed.input(Key::Down, false, false);
let popup = where_is(&ed, 34, 8, 'α').expect("the popup lands on screen");
assert_eq!(preview, popup, "the box flipped to the other side");
}
/// A typed overlay is content, not decoration: centering it off the
/// right edge is the same failure as scrolling it off. The
/// centering pad has to leave room for it.
#[test]
fn a_typed_overlay_is_never_centered_off_screen() {
let mut ed = Editor::new();
type_script_keys(&mut ed, "x+y");
ed.input(Key::Char('\\'), false, false);
for c in "text".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Enter, false, false);
for c in "the quick brown fox jumps".chars() {
ed.input(Key::Char(c), false, false);
}
let screen = shot_at(&ed, 50, 10).join("\n");
assert!(
screen.contains("jumps"),
"the box was clipped off the right edge:\n{}",
screen
);
}
/// The preview is a floating box like the popup, so it has to make
/// the same choice: a caret with no screen rows under it puts the
/// box above rather than off the bottom.
#[test]
fn the_preview_lands_on_screen_when_there_is_no_room_below() {
let mut ed = Editor::new();
// A formula taller than the canvas pins the caret to the last
// visible row once it is scrolled to the bottom.
for _ in 0..8 {
ed.input(Key::Char('x'), false, false);
ed.input(Key::Enter, false, false);
}
for c in "\\alpha".chars() {
ed.input(Key::Char(c), false, false);
}
let screen = shot_at(&ed, 40, 8).join("\n");
assert!(
screen.contains('α'),
"the preview fell off the bottom:\n{}",
screen
);
}
/// A label cell under the caret prints its letter: private-use
/// codepoints must never reach the terminal (fonts map that page
/// to logos, so a leak shows as a random glyph).
/// Private-use codepoints must never reach the terminal (fonts map
/// that page to logos, so a leak shows as a random glyph): every
/// decoration cell resolves to a real glyph or a blank, under the
/// caret included.
#[test]
fn display_markers_never_reach_the_terminal() {
let ghost = Mark::SlotGhost.ch();
for cursor in [None, Some(0)] {
let d = Decor {
lines: vec![vec![ghost, Mark::Gap { cols: true }.ch()]],
bg: vec![vec![None, None]],
bold: vec![vec![false, false]],
flash: vec![vec![false, false]],
invert: vec![vec![false, false]],
blip: false,
caret: cursor.map(|x| (0, x)),
frame: None,
armed: None,
};
let spans = decorate_line(&d, 0, CaretStyle::Normal, 0);
let painted: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert!(
painted
.chars()
.all(|c| !formulaa::glyphs::is_display_marker(c)),
"cursor={:?}: {:?}",
cursor,
painted
);
}
}
/// The name box never shows the reparse-quoting quotes: typing a
/// single letter into \rm displays that letter, bare, with the
/// caret at the box cursor.
#[test]
fn op_box_overlay_is_quote_free() {
let mut ed = Editor::new();
for c in "\\rm a".chars() {
ed.input(Key::Char(c), false, false);
}
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
overlay_minibuffer(&ed, &mut d, Viewport::unbounded());
let all: String = d.lines.iter().flatten().collect();
assert!(
all.contains(&format!("{}a{}", FENDER_L, FENDER_R)),
"bracket fenders around content: {}",
all
);
assert!(!all.contains('\''), "no quote artifacts: {}", all);
// With the caret at the end of the content it sits on the right
// fender's cell — the painted line must still show the bracket
// (the caret draws the mapped glyph, not the raw sentinel).
{
let (cy, _) = d.caret.unwrap();
let spans = decorate_line(&d, cy, CaretStyle::Box, 0);
let painted: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert!(
painted.contains("[a]"),
"fenders survive the caret: {}",
painted
);
}
// ← moves the display caret inside the box.
let (cy, cx) = d.caret.unwrap();
ed.input(Key::Left, false, false);
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut d2 = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
overlay_minibuffer(&ed, &mut d2, Viewport::unbounded());
let (cy2, cx2) = d2.caret.unwrap();
assert_eq!(cy2, cy);
assert_eq!(cx2 + 1, cx, "caret stepped left inside the box");
}
#[test]
fn minibuffer_overlays_at_the_cursor_without_layout_shift() {
let mut ed = Editor::new();
type_script_keys(&mut ed, "a+b");
ed.input(Key::Left, false, false);
ed.input(Key::Left, false, false);
let before = display(&ed);
ed.input(Key::Char('\\'), false, false);
type_script_keys(&mut ed, "fr");
let (root, cursor) = ed.decorated();
let cursor_ref = cursor.as_ref().map(|(p, c)| (p.as_slice(), *c));
let block = render_root(&root, cursor_ref, &RenderCtx { italic: true });
let mut d = marker_boxes(
&block,
&ed.marker_extents(),
ed.block.is_some().then_some(ed.block_sel),
);
let (cy, cx) = d.caret.unwrap();
overlay_minibuffer(&ed, &mut d, Viewport::unbounded());
// The overlay covers the glyphs to the right of the cursor in
// place: same height, and the cells left of the cursor are
// untouched.
assert_eq!(d.lines.len(), before.len(), "no vertical shift");
let text: String = d.lines[cy][cx..cx + 3].iter().collect();
assert_eq!(text, "\\fr", "typed command shown at the cursor");
let kept: String = d.lines[cy][..cx].iter().collect();
assert_eq!(kept, before[cy].chars().take(cx).collect::<String>());
assert_eq!(d.caret, Some((cy, cx + 3)), "caret after the text");
assert!(d.bg[cy][cx].is_some(), "overlay cells are tinted");
}
fn type_script_keys(ed: &mut Editor, s: &str) {
for c in s.chars() {
ed.input(Key::Char(c), false, false);
}
}
#[test]
fn selection_box_paints_without_touching_the_text() {
let lines: Vec<Vec<char>> = vec![" ab ".chars().collect()];
let marks = [
(0, 1, Mark::Sel { open: true }.ch()),
(0, 3, Mark::Sel { open: false }.ch()),
];
let block = formulaa::render::Block {
lines: lines.clone(),
baseline: 0,
caret: None,
marks: marks.to_vec(),
};
let d = marker_boxes(&block, &[(0, 0, 0)], None);
assert_eq!(d.lines, lines, "text must be untouched");
assert_eq!(
d.bg[0],
vec![
None,
Some(theme::SELECTION_BG),
Some(theme::SELECTION_BG),
None
]
);
}
#[test]
fn selection_box_covers_the_block_extent_only() {
// A selected fraction: rows from the extent, not from content
// scanning — the denominator row below the box stays unpainted
// when the extent says so.
let lines: Vec<Vec<char>> = vec![
" 1 ".chars().collect(),
"───".chars().collect(),
" 2 ".chars().collect(),
];
let marks = [
(1, 0, Mark::Sel { open: true }.ch()),
(1, 3, Mark::Sel { open: false }.ch()),
];
let block = |marks: &[(usize, usize, char)]| formulaa::render::Block {
lines: lines.clone(),
baseline: 1,
caret: None,
marks: marks.to_vec(),
};
let d = marker_boxes(&block(&marks), &[(1, 1, 0)], None);
assert!(d.bg.iter().all(|row| row.iter().all(|c| c.is_some())));
let d = marker_boxes(&block(&marks), &[(0, 0, 0)], None);
assert!(
d.bg[2].iter().all(|c| c.is_none()),
"extent must bound the box"
);
}
#[test]
fn caret_pads_the_row_end() {
let lines: Vec<Vec<char>> = vec!["xy".chars().collect()];
let block = formulaa::render::Block {
lines: lines.clone(),
baseline: 0,
caret: Some((0, 2)),
marks: vec![],
};
let d = marker_boxes(&block, &[], None);
assert_eq!(d.caret, Some((0, 2)));
assert_eq!(d.lines[0].len(), 3, "caret cell padded at the row end");
}
#[test]
fn caret_display_never_shifts_the_layout() {
// (x^a, not x^2: an inlinable script like ² must re-expand to 2D
// while the caret is inside it — that shift is inherent.)
let mut ed = Editor::new();
for k in "x^a".chars() {
ed.input(Key::Char(k), false, false);
}
ed.input(Key::Tab, false, false);
ed.input(Key::Char('+'), false, false);
ed.input(Key::Char('/'), false, false);
ed.input(Key::Char('/'), false, false);
ed.input(Key::Char('1'), false, false);
ed.input(Key::Down, false, false);
ed.input(Key::Char('2'), false, false);
let ctx = RenderCtx { italic: true };
let plain: Vec<String> = render_root(&ed.root, None, &ctx)
.to_strings()
.iter()
.map(|l| l.trim_end().to_string())
.collect();
// Every cursor position must display with the same geometry as
// the cursor-less render (the caret is an overlay, not a column).
for cand in ed.jump_candidates() {
if cand.is_cursor {
continue;
}
let (p, c) = cand.pos;
ed.path = p;
ed.col = c;
let got: Vec<String> = display(&ed)
.iter()
.map(|l| l.trim_end().to_string())
.collect();
assert_eq!(
got, plain,
"layout shifted at path {:?} col {}",
ed.path, ed.col
);
}
}
#[test]
fn mode_displays_keep_the_editing_geometry() {
// Formulas whose editing view differs from the plain one: an
// empty-limit ∑ band, a fused matrix, an inline superscript.
// Entering ^G / ^B must keep the geometry — cells may only
// change where a label got overlaid.
for keys in [
vec!["\\", "s", "u", "m", "\n", "x"],
vec!["\\", "p", "m", "a", "t", "r", "i", "x", "\n", "a", ">", "b"],
vec!["x", "^", "2"],
] {
let mut ed = Editor::new();
for k in keys {
match k {
"\n" => ed.input(Key::Enter, false, false),
">" => ed.input(Key::Right, false, false),
k => ed.input(Key::Char(k.chars().next().unwrap()), false, false),
};
}
let editing = display(&ed);
for key in ['g', 'b'] {
ed.input(Key::Char(key), false, true);
let mode = display(&ed);
assert_eq!(mode.len(), editing.len(), "height changed in ^{}", key);
for (y, (m, e)) in mode.iter().zip(&editing).enumerate() {
let (m, e): (Vec<char>, Vec<char>) = (m.chars().collect(), e.chars().collect());
for x in 0..m.len().max(e.len()) {
let (mc, ec) = (
m.get(x).copied().unwrap_or(' '),
e.get(x).copied().unwrap_or(' '),
);
let label = (0xE000..0xE100).contains(&(mc as u32));
assert!(
mc == ec || label,
"^{} shifted cell ({}, {}): {:?} vs {:?}",
key,
y,
x,
mc,
ec
);
}
}
ed.input(Key::Esc, false, false);
}
}
}
/// A mode command's row wears its chord in the symbol column,
/// bold: [^F] is what tells \free apart from the edits without a
/// row tint of its own.
#[test]
fn mode_rows_show_their_chord_bold() {
use ratatui::{Terminal, backend::TestBackend};
let mut ed = Editor::new();
ed.input(Key::Char('\\'), false, false);
ed.input(Key::Char('f'), false, false);
ed.input(Key::Down, false, false);
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(40, 14)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let screen: Vec<String> = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect();
let at = screen
.iter()
.enumerate()
.find_map(|(y, l)| l.find("[^F]").map(|x| (x, y)))
.unwrap_or_else(|| panic!("no [^F] marker:\n{}", screen.join("\n")));
let cell = &buf[(at.0 as u16, at.1 as u16)];
assert!(
cell.style()
.add_modifier
.contains(ratatui::style::Modifier::BOLD),
"the chord marker is not bold"
);
}
/// ^B's provisional selection is the selection purple with a
/// blink (the caret is bold reverse video; flash cells are
/// non-bold, which is what the filter below keys on).
#[test]
fn block_select_flashes_in_reverse_video() {
use ratatui::style::Modifier;
use ratatui::{Terminal, backend::TestBackend};
// Nested pairs: the innermost ancestor is selected, and the
// one step OUTWARD shows as a white ring around it — the
// configuration where a wrong paint order once let the outer
// ground swallow the purple.
let mut ed = Editor::new();
for c in "((x".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Char('b'), false, true); // ^B (inside the pairs)
assert!(ed.block.is_some());
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(30, 8)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let flashing = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.filter(|&(x, y)| {
let c = &buf[(x, y)];
c.bg == theme::SELECTION_BG
&& c.style().add_modifier.contains(Modifier::SLOW_BLINK)
&& !c.style().add_modifier.contains(Modifier::BOLD)
})
.count();
assert!(flashing > 0, "no flashing purple cells in ^B");
// …and the outward step shows as a steady reverse-video ring
// (the inner step is deliberately not drawn — selection starts
// at the innermost ancestor, so it needs no announcing). The
// parked caret is hidden in this mode, so every reversed cell
// is the ring: steady (no blink) and never bold.
let ring = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.filter(|&(x, y)| {
let m = buf[(x, y)].style().add_modifier;
m.contains(Modifier::REVERSED)
})
.collect::<Vec<_>>();
assert!(!ring.is_empty(), "no outward step ring");
for &(x, y) in &ring {
let m = buf[(x, y)].style().add_modifier;
assert!(
!m.contains(Modifier::BOLD) && !m.contains(Modifier::SLOW_BLINK),
"a reversed cell that is not the steady ring at {:?}",
(x, y)
);
}
}
/// The draw records where the completion popup landed (canvas
/// coordinates) so the mouse can pick rows.
#[test]
fn the_popup_rect_is_recorded_for_the_mouse() {
use ratatui::{Terminal, backend::TestBackend};
let mut ed = Editor::new();
ed.input(Key::Char('\\'), false, false);
ed.input(Key::Char('a'), false, false);
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(40, 14)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
assert!(view.popup.is_none(), "no list, no rect");
ed.input(Key::Down, false, false); // open the list
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let (top, _left, w, start, shown) = view.popup.expect("no popup rect");
assert!(shown > 0 && w > 0 && start == 0, "{:?}", view.popup);
// The rect starts where the rows were drawn: below the caret.
assert!(top > 0);
}
/// Arming a wide accent lights its bands (it has no delimiter
/// columns): some cells must take the armed ground, or the first
/// Backspace looks like a dead key.
#[test]
fn an_armed_wide_accent_lights_up() {
use ratatui::{Terminal, backend::TestBackend};
let mut ed = Editor::new();
for c in "ab".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Left, true, false);
ed.input(Key::Left, true, false);
for c in "\\hat".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Enter, false, false);
ed.input(Key::Left, false, false); // into the base
ed.input(Key::Home, false, false);
ed.input(Key::Backspace, false, false); // arm
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(30, 8)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let armed = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.filter(|&(x, y)| {
let c = &buf[(x, y)];
c.bg == theme::SELECTION_BG && c.style().add_modifier.contains(Modifier::BOLD)
})
.count();
assert!(armed > 0, "the armed accent shows nothing");
}
/// The help line bolds its key tokens (⌃F, \\, //) and leaves the
/// descriptions and mode labels plain.
#[test]
fn help_line_bolds_the_keys() {
use ratatui::{Terminal, backend::TestBackend};
let ed = Editor::new();
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(60, 8)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let y = buf.area.height - 1;
let line: String = (0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect();
let at = line.find("⌃F").expect("no ⌃F in the help line") as u16;
// The string index counts bytes; find the cell by scanning.
let mut cx = 0;
let mut seen = String::new();
for x in 0..buf.area.width {
if seen.len() >= at as usize {
cx = x;
break;
}
seen.push_str(buf[(x, y)].symbol());
}
assert!(
buf[(cx, y)].style().add_modifier.contains(Modifier::BOLD),
"⌃ is not bold"
);
// A description word stays plain.
let mut fx = None;
let mut seen = String::new();
let dat = line.find(" free ").unwrap() + 1;
for x in 0..buf.area.width {
if seen.len() >= dat {
fx = Some(x);
break;
}
seen.push_str(buf[(x, y)].symbol());
}
let fx = fx.unwrap();
assert!(
!buf[(fx, y)].style().add_modifier.contains(Modifier::BOLD),
"'free' is bold"
);
// …and it says so when the terminal cuts it short.
assert!(
line.ends_with('…'),
"no ellipsis on a clipped line: {}",
line
);
let wide: String = shot_at(&Editor::new(), 200, 8).pop().unwrap();
assert!(
!wide.trim_end().ends_with('…'),
"ellipsis on a line that fits: {}",
wide
);
}
fn shot_at(ed: &Editor, w: u16, h: u16) -> Vec<String> {
use ratatui::{Terminal, backend::TestBackend};
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| {
draw(f, ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect()
}
/// Coincident ^B opens (the ancestor ring and the whole-row ring
/// both starting at column 0) pair each close with its own rank:
/// the frac is the flashing selection, the row around it is the
/// steady ring — not the whole row painted purple.
#[test]
fn coincident_block_opens_pair_with_their_own_close() {
use ratatui::style::Modifier;
use ratatui::{Terminal, backend::TestBackend};
let mut ed = Editor::new();
type_script_keys(&mut ed, "\\frac");
ed.input(Key::Enter, false, false); // frac at index 0, cursor in numerator
type_script_keys(&mut ed, "1");
ed.input(Key::Down, false, false);
type_script_keys(&mut ed, "2");
ed.input(Key::Tab, false, false);
type_script_keys(&mut ed, "+y");
for _ in 0..3 {
ed.input(Key::Left, false, false); // back inside the frac
}
assert!(!ed.path.is_empty(), "the cursor did not re-enter the frac");
ed.input(Key::Char('b'), false, true); // ^B
// One step out: the fraction and the whole row, whose boxes
// open on the same cell — which is what this test is about.
ed.input(Key::Up, false, false);
assert!(ed.block.is_some());
let mut view = View::default();
let mut term = Terminal::new(TestBackend::new(30, 8)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let mut y_cell = None;
let mut purple = 0;
for y in 0..buf.area.height {
for x in 0..buf.area.width {
let c = &buf[(x, y)];
if c.symbol() == "\u{1d466}" {
y_cell = Some(c.clone());
}
if c.bg == theme::SELECTION_BG {
purple += 1;
}
}
}
assert!(purple > 0, "no purple selection at all");
let y_cell = y_cell.unwrap_or_else(|| {
let screen: Vec<String> = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect();
panic!("no y on screen:\n{}", screen.join("\n"))
});
assert_ne!(
y_cell.bg,
theme::SELECTION_BG,
"the whole row is painted as the selection (ranks swapped)"
);
assert!(
y_cell.style().add_modifier.contains(Modifier::REVERSED),
"y is not inside the step ring"
);
}
/// A multi-word mode label ("grid cell select:") stays plain and
/// the keys after it still bold.
#[test]
fn multi_word_mode_labels_keep_key_bolding() {
use ratatui::style::Modifier;
let line = help_spans("grid cell select: c/| column select ¦ r/- row select");
let bold_of = |tok: &str| {
line.spans
.iter()
.find(|s| s.content == tok)
.unwrap_or_else(|| panic!("no span {tok:?}"))
.style
.add_modifier
.contains(Modifier::BOLD)
};
assert!(bold_of("c/|"), "key after a multi-word label lost its bold");
assert!(bold_of("r/-"));
assert!(!bold_of("grid"));
assert!(!bold_of("select:"));
}
/// The command preview opening upward is clamped above the caret
/// row: on a tiny terminal it must not paint over the typed \name.
#[test]
fn preview_never_covers_the_typed_command() {
let mut ed = Editor::new();
type_script_keys(&mut ed, "\\frac");
ed.input(Key::Enter, false, false);
ed.input(Key::Down, false, false); // caret in the denominator: bottom row
type_script_keys(&mut ed, "\\frac");
let screen = shot_at(&ed, 30, 6);
assert!(
screen.iter().any(|l| l.contains("frac")),
"the preview covered the typed \\frac:\n{}",
screen.join("\n")
);
}
/// The copy blip reaches grid-mode selections too: their ground is
/// painted straight as bg (no flash cells), so the blip inverts it
/// at the paint layer.
#[test]
fn grid_selection_inverts_during_the_copy_blip() {
use ratatui::style::Modifier;
use ratatui::{Terminal, backend::TestBackend};
let mut ed = Editor::new();
for c in "\\bmatrix22".chars() {
ed.input(Key::Char(c), false, false);
}
ed.input(Key::Enter, false, false);
ed.input(Key::Char('x'), false, false);
ed.input(Key::Char('g'), false, true); // ^G
ed.input(Key::Right, true, false); // widen the rectangle
let mut view = View {
copy_blip: true,
..Default::default()
};
let mut term = Terminal::new(TestBackend::new(30, 8)).unwrap();
term.draw(|f| {
draw(f, &ed, &mut view);
})
.unwrap();
let buf = term.backend().buffer().clone();
let inverted = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.filter(|&(x, y)| {
let c = &buf[(x, y)];
// Not the caret (bold): only the plain ground runs.
c.bg == theme::SELECTION_BG
&& c.style().add_modifier.contains(Modifier::REVERSED)
&& !c.style().add_modifier.contains(Modifier::BOLD)
})
.count();
assert!(inverted > 0, "the blip never reached the grid selection");
}
}