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
use std::iter::Peekable;
use std::ops::Range;
use crate::{CommonMarkCache, CommonMarkOptions};
use egui::{self, Id, Pos2, TextStyle, Ui};
use crate::List;
use egui_commonmark_backend_extended::elements::{
blockquote, footnote, footnote_start, heading_end_spacing, heading_start_spacing, newline,
paragraph_end_spacing, rule, soft_break, ImmutableCheckbox,
};
use egui_commonmark_backend_extended::misc::*;
use egui_commonmark_backend_extended::pulldown::*;
use pulldown_cmark::{CowStr, HeadingLevel};
/// Search-match highlight kind for a single rendered text segment.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum HighlightKind {
None,
Match,
Active,
}
impl HighlightKind {
fn background_color(self, ui: &Ui) -> Option<egui::Color32> {
let dark = ui.style().visuals.dark_mode;
match self {
HighlightKind::None => None,
HighlightKind::Match => Some(if dark {
egui::Color32::from_rgb(102, 92, 46)
} else {
egui::Color32::from_rgb(255, 229, 127)
}),
HighlightKind::Active => Some(if dark {
egui::Color32::from_rgb(156, 107, 26)
} else {
egui::Color32::from_rgb(255, 167, 38)
}),
}
}
}
/// One borrowed visible segment plus its exact identity in raw Markdown source.
#[derive(Clone, Debug, PartialEq, Eq)]
struct EmojiTextSegment<'a> {
rendered: &'a str,
source_range: Range<usize>,
raw: &'a str,
replaced: bool,
}
/// Visit recognized `:shortcode:` replacements without allocating unchanged text.
fn visit_emoji_text_segments<'a>(
text: &'a str,
span: &Range<usize>,
mut visit: impl FnMut(EmojiTextSegment<'a>),
) {
// Transformed pulldown text cannot be mapped safely back to original source bytes.
if text.len() != span.len() {
visit(EmojiTextSegment {
rendered: text,
source_range: span.clone(),
raw: text,
replaced: false,
});
return;
}
let mut plain_start = 0usize;
let mut search_from = 0usize;
let mut replaced_any = false;
while let Some(open_rel) = text[search_from..].find(':') {
let open = search_from + open_rel;
let name_start = open + 1;
let Some(close_rel) = text[name_start..].find(':') else {
break;
};
let close = name_start + close_rel;
let name = &text[name_start..close];
if !name.is_empty() {
if let Some(emoji) = emojis::get_by_shortcode(name) {
if plain_start < open {
visit(EmojiTextSegment {
rendered: &text[plain_start..open],
source_range: span.start + plain_start..span.start + open,
raw: &text[plain_start..open],
replaced: false,
});
}
let raw_end = close + 1;
visit(EmojiTextSegment {
rendered: emoji.as_str(),
source_range: span.start + open..span.start + raw_end,
raw: &text[open..raw_end],
replaced: true,
});
replaced_any = true;
plain_start = raw_end;
search_from = raw_end;
continue;
}
}
// Keep unknown syntax literal while searching later openers in this event.
search_from = name_start;
}
if !replaced_any {
visit(EmojiTextSegment {
rendered: text,
source_range: span.clone(),
raw: text,
replaced: false,
});
} else if plain_start < text.len() {
visit(EmojiTextSegment {
rendered: &text[plain_start..],
source_range: span.start + plain_start..span.end,
raw: &text[plain_start..],
replaced: false,
});
}
}
/// Only ordinary visible text may expand; image alt text and code blocks stay literal.
fn emoji_expansion_is_eligible(in_image: bool, in_code_block: bool) -> bool {
!in_image && !in_code_block
}
/// Resolve one indivisible replacement against source-authoritative search ranges.
fn highlight_for_source_span(
source_span: &Range<usize>,
ranges: &[Range<usize>],
active: Option<&Range<usize>>,
) -> HighlightKind {
let overlaps =
|range: &Range<usize>| range.start < source_span.end && source_span.start < range.end;
if active.is_some_and(overlaps) {
HighlightKind::Active
} else if ranges.iter().any(overlaps) {
HighlightKind::Match
} else {
HighlightKind::None
}
}
/// Visit borrowed text slices tagged with exact source-range highlighting.
/// Assumes non-overlapping source ranges, matching app search production.
fn visit_highlight_segments<'a>(
text: &'a str,
span: &Range<usize>,
ranges: &[Range<usize>],
active: Option<&Range<usize>>,
mut visit: impl FnMut(&'a str, HighlightKind),
) {
let mut cursor = 0usize;
let mut found = false;
for range in ranges {
let start = range.start.max(span.start);
let end = range.end.min(span.end);
if start >= end {
continue;
}
let local_start = start - span.start;
let local_end = end - span.start;
if !text.is_char_boundary(local_start) || !text.is_char_boundary(local_end) {
continue;
}
found = true;
if local_start > cursor && text.is_char_boundary(cursor) {
visit(&text[cursor..local_start], HighlightKind::None);
}
let kind = if active == Some(range) {
HighlightKind::Active
} else {
HighlightKind::Match
};
visit(&text[local_start..local_end], kind);
cursor = local_end;
}
if !found {
visit(text, HighlightKind::None);
} else if cursor < text.len() && text.is_char_boundary(cursor) {
visit(&text[cursor..], HighlightKind::None);
}
}
/// Split a long inline-code token into fixed-size chunks so the row-wrap layout
/// can put each chunk on its own row instead of overflowing the content width.
/// Short tokens (<= MAX) pass through unchanged.
///
/// Blind char-count cut (not break-friendly on `/`, `-`, etc.): variable-length
/// segments can still exceed the column at narrow widths and re-introduce the
/// original clipping bug. Fixed-size chunks always fit.
fn inline_code_wrap_segments(text: &str) -> Vec<String> {
const MAX_SEGMENT_CHARS: usize = 56;
if text.chars().count() <= MAX_SEGMENT_CHARS {
return vec![text.to_owned()];
}
let mut segments = Vec::new();
let mut current = String::with_capacity(MAX_SEGMENT_CHARS * 4);
let mut current_len = 0;
for ch in text.chars() {
current.push(ch);
current_len += 1;
if current_len >= MAX_SEGMENT_CHARS {
segments.push(std::mem::take(&mut current));
current_len = 0;
}
}
if !current.is_empty() {
segments.push(current);
}
segments
}
/// Count the visual lines a markdown table cell will occupy when rendered.
/// Used by the `fn table` renderer to compute heterogeneous row heights so
/// long inline-code paths (chunked by `inline_code_wrap_segments`) don't get
/// clipped by a fixed row height. Only `Event::Code` chunking adds visual
/// lines today; other inline events flow on a single line within a cell.
fn cell_visual_lines(cell: &[(pulldown_cmark::Event, Range<usize>)]) -> usize {
let mut max_lines = 1usize;
for (event, _) in cell {
if let pulldown_cmark::Event::Code(text) = event {
let chunks = inline_code_wrap_segments(text).len();
if chunks > max_lines {
max_lines = chunks;
}
}
}
max_lines
}
/// Heuristic visual-line count for an HTML-table cell (rendered as a plain
/// `RichText` string, not as a markdown event stream). Counts explicit
/// newlines and adds a crude wrap estimate of ~60 chars per visual line.
/// Over-estimates slightly by design — extra row height is preferable to
/// clipping. Exact estimation would require knowing the rendered column
/// width up front, which TableBuilder doesn't expose before render.
fn html_cell_visual_lines(cell: &str) -> usize {
let explicit_lines = cell.lines().count().max(1);
let wrap_est = cell.len().saturating_sub(1) / 60;
explicit_lines.saturating_add(wrap_est).max(1)
}
/// Redirect Shift+vertical-wheel over a hovered wide-table into its inner
/// horizontal scroll offset. Plain vertical wheel is left untouched so the
/// outer document scroller keeps scrolling the page (this is the behavior
/// users expect; the unconditional redirect from #4 caused #22).
///
/// The Shift modifier acts as an explicit opt-in for sideways table scrolling
/// without dragging the bottom scrollbar. Native horizontal trackpad input is
/// already consumed by `ScrollArea::horizontal()` inside its `.show()` call,
/// so this helper only ever touches the Y delta.
///
/// Edge pass-through: when the table is at either side and the wheel direction
/// would push past the edge, the delta is left for the outer scroller.
fn forward_shift_wheel_to_horizontal_scroll<R>(
ui: &Ui,
out: &mut egui::containers::scroll_area::ScrollAreaOutput<R>,
) {
if !ui.rect_contains_pointer(out.inner_rect) {
return;
}
if !ui.ctx().input(|i| i.modifiers.shift) {
return;
}
let dy = ui.ctx().input(|i| i.smooth_scroll_delta.y);
if dy.abs() < 0.1 {
return;
}
let max_x = (out.content_size.x - out.inner_rect.width()).max(0.0);
if max_x <= 0.0 {
return;
}
let at_left = out.state.offset.x <= 0.0 && dy > 0.0;
let at_right = out.state.offset.x >= max_x && dy < 0.0;
if at_left || at_right {
return;
}
let new_x = (out.state.offset.x - dy).clamp(0.0, max_x);
if (new_x - out.state.offset.x).abs() > f32::EPSILON {
out.state.offset.x = new_x;
out.state.store(ui.ctx(), out.id);
ui.ctx().input_mut(|i| i.smooth_scroll_delta.y = 0.0);
ui.ctx().request_repaint();
}
}
/// Newline logic is constructed by the following:
/// All elements try to insert a newline before them (if they are allowed)
/// and end their own line.
struct Newline {
/// Whether a newline should not be inserted before a widget. This is only for
/// the first widget.
should_not_start_newline_forced: bool,
/// Whether an element should insert a newline before it
should_start_newline: bool,
/// Whether an element should end it's own line using a newline
/// This will have to be set to false in cases such as when blocks are within
/// a list.
should_end_newline: bool,
/// only false when the widget is the last one.
should_end_newline_forced: bool,
}
impl Default for Newline {
fn default() -> Self {
Self {
should_not_start_newline_forced: true,
should_start_newline: true,
should_end_newline: true,
should_end_newline_forced: true,
}
}
}
impl Newline {
pub fn can_insert_end(&self) -> bool {
self.should_end_newline && self.should_end_newline_forced
}
pub fn can_insert_start(&self) -> bool {
self.should_start_newline && !self.should_not_start_newline_forced
}
pub fn try_insert_start(&self, ui: &mut Ui) {
if self.can_insert_start() {
newline(ui);
}
}
pub fn try_insert_end(&self, ui: &mut Ui) {
if self.can_insert_end() {
newline(ui);
}
}
}
#[derive(Default)]
struct DefinitionList {
is_first_item: bool,
is_def_list_def: bool,
}
pub struct CommonMarkViewerInternal {
curr_table: usize,
curr_code_block: usize,
text_style: Style,
list: List,
link: Option<Link>,
image: Option<Image>,
line: Newline,
code_block: Option<CodeBlock>,
/// Only populated if the html_fn option has been set
html_block: String,
is_list_item: bool,
def_list: DefinitionList,
is_table: bool,
is_blockquote: bool,
checkbox_events: Vec<CheckboxClickEvent>,
/// Track current heading for position recording
current_heading_y: Option<f32>,
current_heading_text: String,
/// Accumulate heading RichText fragments for single render at end
current_heading_rich_texts: Vec<egui::RichText>,
/// Per-render-pass counter: number of headings seen so far with each
/// normalized title. Used to build composite cache keys that
/// disambiguate duplicate-titled headers (e.g. multiple `## Installation`).
/// Reset at the start of each `show*` call so the count restarts at 0.
heading_occurrence_counts: std::collections::HashMap<String, usize>,
}
pub(crate) struct CheckboxClickEvent {
pub(crate) checked: bool,
pub(crate) span: Range<usize>,
}
impl CommonMarkViewerInternal {
pub fn new() -> Self {
Self {
curr_table: 0,
curr_code_block: 0,
text_style: Style::default(),
list: List::default(),
link: None,
image: None,
line: Newline::default(),
is_list_item: false,
def_list: Default::default(),
code_block: None,
html_block: String::new(),
is_table: false,
is_blockquote: false,
checkbox_events: Vec::new(),
current_heading_y: None,
current_heading_text: String::new(),
current_heading_rich_texts: Vec::new(),
heading_occurrence_counts: std::collections::HashMap::new(),
}
}
}
fn parser_options_math(is_math_enabled: bool) -> pulldown_cmark::Options {
if is_math_enabled {
parser_options() | pulldown_cmark::Options::ENABLE_MATH
} else {
parser_options()
}
}
/// Hash the layout-affecting render context.
///
/// `split_points` cache y-positions, which become invalid when anything that
/// affects layout changes. The previous code (parsers/pulldown.rs invalidation
/// block) only watched `available_size`, so zooming (Ctrl++/-) or toggling
/// dark mode would leave stale split_points in place and the viewport-skip
/// math would render the wrong content range.
fn compute_layout_signature(ui: &egui::Ui, options: &CommonMarkOptions) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
// Width drives wrap and is the dominant layout input. Quantize to the
// nearest pixel so sub-pixel float jitter from per-frame egui rounding
// (very common during image/font async loading) doesn't invalidate the
// cache. Real width changes (resize, zoom) flip the int bucket; tiny
// float fluctuations don't.
(ui.available_width().round() as i32).hash(&mut h);
// Body / monospace text heights — quantize to 0.1 px for the same
// reason. A real font/zoom change shifts heights by multiple px; sub-
// pixel rounding from per-frame ppp resolution stays in one bucket.
((ui.text_style_height(&egui::TextStyle::Body) * 10.0).round() as i32).hash(&mut h);
((ui.text_style_height(&egui::TextStyle::Monospace) * 10.0).round() as i32).hash(&mut h);
// Theme doesn't change widget heights, but it does change the resolved
// syntect theme — invalidating here keeps split_points and the syntect
// cache (added later) coherent.
ui.style().visuals.dark_mode.hash(&mut h);
// Caller-configured constraints that affect block widths.
options.default_width.hash(&mut h);
options.indentation_spaces.hash(&mut h);
h.finish()
}
/// Threshold for content-height drift from the last bootstrap that triggers a
/// re-bootstrap to refresh split_points. Larger than the known ~44px egui
/// oscillation between show()/show_viewport() content-size reporting, but
/// small enough to catch real image-load growth.
const CONTENT_H_DRIFT_THRESHOLD: f32 = 1024.0;
/// Whether a TagEnd marks a safe block-level boundary for viewport-skip.
///
/// At a block end the renderer's transient inline state (heading rich-text
/// accumulator, list nesting, emphasis flags) is neutral, so a future frame
/// can start rendering from the next event without losing context.
///
/// Inline ends (Emphasis, Strong, Link, Image, Superscript, Subscript) are
/// rejected — splitting mid-paragraph would orphan inline formatting state.
/// Table-internal ends (TableHead, TableRow, TableCell) are rejected because
/// tables are pre-parsed and rendered as a single atomic unit.
fn is_block_end_tag(tag: &pulldown_cmark::TagEnd) -> bool {
use pulldown_cmark::TagEnd;
matches!(
tag,
TagEnd::Paragraph
| TagEnd::Heading(_)
| TagEnd::BlockQuote(_)
| TagEnd::CodeBlock
| TagEnd::List(_)
| TagEnd::Item
| TagEnd::FootnoteDefinition
| TagEnd::Table
| TagEnd::HtmlBlock
| TagEnd::MetadataBlock(_)
| TagEnd::DefinitionList
| TagEnd::DefinitionListTitle
| TagEnd::DefinitionListDefinition
)
}
/// Detect if text parsed as inline math (`$...$`) is actually NOT a real LaTeX
/// formula. Returns true for currency amounts and other false positives like:
/// - `$17.57` → parsed as InlineMath("17.57")
/// - `$3,000–$4,000` → parsed as InlineMath("3,000–")
/// - `$/t is worse because...total_usd...` → long English sentence with `_` in identifiers
///
/// The approach: real LaTeX math contains structural syntax (backslash
/// commands, braces, sub/superscripts) OR math operators/grouping (`= < >`,
/// parens, brackets) OR is a signed number / short variable. Anything with
/// none of those markers is almost certainly a misparse. Additionally, very
/// long "math" containing multiple English words is almost certainly a false
/// positive from `$` being used as currency.
fn is_likely_currency(tex: &str) -> bool {
let trimmed = tex.trim();
if trimmed.is_empty() {
return false;
}
// Real LaTeX commands (\frac, \sum, etc.) are the strongest signal
let has_backslash_cmd = trimmed.contains('\\');
if has_backslash_cmd {
return false;
}
// Braces are strong LaTeX indicators (grouping: {x+1}, subscript: _{n})
let has_braces = trimmed.contains('{') || trimmed.contains('}');
if has_braces {
return false;
}
// Relational / grouping operators that a closed `$...$` currency amount
// never contains: `w(z)`, `f(R)`, `D>0`, `p=P`, `[-1.1,-1.0]`, `=0`.
// Their presence means real math, not a `$5`-style misparse.
if trimmed.contains(|c: char| matches!(c, '=' | '<' | '>' | '(' | ')' | '[' | ']')) {
return false;
}
// A signed number is math (`-1.38`, `+2.6`); closed currency is unsigned
// (`$5`, never `$-5$`). Leading `+`/`-` followed by a digit.
let mut leading = trimmed.chars();
if matches!(leading.next(), Some('+' | '-'))
&& leading.next().is_some_and(|c| c.is_ascii_digit())
{
return false;
}
// A short all-letters token is a variable name (`G`, `w`, `D`).
if trimmed.len() <= 3 && trimmed.chars().all(|c| c.is_ascii_alphabetic()) {
return false;
}
// A clean numeric literal with no internal whitespace is an intentional
// `$number$` (e.g. a χ² value `$8.5$`), not currency. Currency only reaches
// InlineMath by spanning two `$` across prose, so its mis-parsed content
// carries spaces or dashes (`"8.5 to "`, `"3,000–"`) — which fail this test
// and fall through to the currency branch below.
if trimmed.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ',')
&& trimmed.chars().any(|c| c.is_ascii_digit())
{
return false;
}
// For ^ and _, only trust them as math if the content is short and
// doesn't look like English prose. Long text with underscores from
// identifiers (total_usd, miss_cost) is a false positive.
let has_sub_super = trimmed.contains('^') || trimmed.contains('_');
if has_sub_super {
// Count whitespace-separated words — real inline math rarely has >5 words
let word_count = trimmed.split_whitespace().count();
if word_count > 5 {
return true; // Too many words — this is prose, not math
}
// Short content with ^ or _ is likely real math (e.g., x_i, a^2)
return false;
}
// No math syntax found — this is almost certainly a currency/misparse
true
}
impl CommonMarkViewerInternal {
/// Compute a hash of the text content for event cache lookup.
fn hash_content(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
/// Be aware that this acquires egui::Context internally.
/// If split Id is provided then split points will be populated
pub(crate) fn show(
&mut self,
ui: &mut egui::Ui,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
text: &str,
split_points_id: Option<Id>,
) -> (egui::InnerResponse<()>, Vec<CheckboxClickEvent>) {
let max_width = options.max_width(ui);
let layout = egui::Layout::left_to_right(egui::Align::BOTTOM).with_main_wrap(true);
// Compute content hash and ensure events are cached
let content_hash = Self::hash_content(text);
if cache.get_cached_events(content_hash).is_none() {
let math_enabled = options.math_fn.is_some() || cfg!(feature = "math");
let owned_events: Vec<(pulldown_cmark::Event<'static>, Range<usize>)> =
pulldown_cmark::Parser::new_ext(text, parser_options_math(math_enabled))
.into_offset_iter()
.map(|(event, range)| (event.into_static(), range))
.collect();
cache.set_cached_events(content_hash, owned_events);
}
let re = ui.allocate_ui_with_layout(egui::vec2(max_width, 0.0), layout, |ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let height = ui.text_style_height(&TextStyle::Body);
ui.set_row_height(height);
// Use cached events — clone the Vec reference data for iteration
// (events are 'static so this is cheap pointer copies, not re-parsing)
let events_data = cache.get_cached_events(content_hash)
.expect("events just cached")
.to_vec();
let mut events = events_data
.into_iter()
.enumerate()
.peekable();
while let Some((index, (e, src_span))) = events.next() {
let start_position = ui.next_widget_position();
// Add a viewport-skip waypoint at every block-level end (not
// just list-internal ends as the original code did). Without
// this, docs whose content is mostly headings + paragraphs
// produce empty split_points, the viewport-skip math falls
// back to Pos2::ZERO, and rendered content overlaps. This is
// the root cause of the "buggy in scenarios more complex
// than the example application" warning on show_scrollable.
let is_block_end = matches!(
&e,
pulldown_cmark::Event::End(end) if is_block_end_tag(end)
);
if events.peek().is_none() {
self.line.should_end_newline_forced = false;
}
self.process_event(ui, &mut events, e, src_span, cache, options, max_width);
// Defense in depth: only add a split point when we're at a
// block end AND outside any stateful container (list, table,
// blockquote). The viewport-skip path in `show_scrollable`
// recreates the renderer with `CommonMarkViewerInternal::new`
// each frame, so the transient state of `self.list`,
// `self.is_table`, and `self.is_blockquote` is *not* replayed
// when iteration jumps in via `skip(first_event_index)`. A
// split point inside one of those containers would land
// iteration mid-state — for lists this fires
// `List::start_item` on an empty stack and panics
// (`lib.rs:566 unreachable!()`); for tables / blockquotes it
// would visually corrupt rendering. The container-state
// check below must run after `process_event` (above) since
// that's where the start/end of these containers updates
// `self.list` / `self.is_table` / `self.is_blockquote`.
let safe_for_split = is_block_end
&& !self.list.is_inside_a_list()
&& !self.is_table
&& !self.is_blockquote;
if let Some(source_id) = split_points_id {
if safe_for_split {
let scroll_cache = scroll_cache(cache, &source_id);
let end_position = ui.next_widget_position();
let split_point_exists = scroll_cache
.split_points
.iter()
.any(|(i, _, _)| *i == index);
if !split_point_exists {
scroll_cache
.split_points
.push((index, start_position, end_position));
}
}
}
if index == 0 {
self.line.should_not_start_newline_forced = false;
}
}
if let Some(source_id) = split_points_id {
scroll_cache(cache, &source_id).page_size =
Some(ui.next_widget_position().to_vec2());
}
});
(re, std::mem::take(&mut self.checkbox_events))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn show_scrollable(
&mut self,
source_id: Id,
ui: &mut egui::Ui,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
text: &str,
content_version: Option<u64>,
pending_scroll_offset: Option<f32>,
scroll_source: Option<egui::scroll_area::ScrollSource>,
) -> egui::scroll_area::ScrollAreaOutput<()> {
let available_size = ui.available_size();
let scroll_id = source_id.with("_scroll_area");
let layout_sig = compute_layout_signature(ui, options);
// Ensure parsed events are cached on the ScrollableCache, keyed by a
// content version. The caller can provide a monotonic version (bumped
// on every reload) — when omitted we fall back to hashing the content,
// which still beats reparsing but is O(N) per frame for the hash.
// The big win either way is avoiding pulldown_cmark::Parser::new_ext +
// collect on every frame (~52 ms at 100k lines).
let version = content_version.unwrap_or_else(|| Self::hash_content(text));
let mut content_changed = false;
{
let sc = scroll_cache(cache, &source_id);
if sc.events.is_empty() || sc.content_version != version {
content_changed = true;
// Must mirror `show()`'s `math_enabled` derivation
// (parsers/pulldown.rs in this file: `options.math_fn.is_some()
// || cfg!(feature = "math")`). The bootstrap branch below
// calls `self.show()` which parses again with `cfg!(feature =
// "math")` included; if our parse here omits it, the two
// event streams diverge for any document containing `$…$`
// (currency, regex, env vars). split_points are then indexed
// off `cache.cached_events` (with-math) but consumed against
// `sc.events` (without-math), so the viewport-skip path lands
// iteration at an unrelated event — often `Tag::Item` with no
// matching `Tag::List` start → `List::start_item` panics
// (`lib.rs:566 unreachable!()`). See docs/devlog/027.
let math_enabled =
options.math_fn.is_some() || cfg!(feature = "math");
sc.events = pulldown_cmark::Parser::new_ext(
text,
parser_options_math(math_enabled),
)
.into_offset_iter()
.map(|(e, r)| (e.into_static(), r))
.collect();
sc.content_version = version;
// Content changed — cached split_points y-coords are no
// longer valid for this content. Drop them so the first
// post-change frame falls into the bootstrap branch below.
sc.page_size = None;
sc.split_points.clear();
}
// Width/zoom/theme change: y-coordinates are invalid for the
// new layout, even though parsed events are still good.
if sc.layout_signature != layout_sig {
sc.layout_signature = layout_sig;
sc.page_size = None;
sc.split_points.clear();
sc.available_size = available_size;
}
// When the caller wants to jump to a specific scroll position
// (outline click, search-jump), we must paint *every* event
// this frame — not just the viewport-clipped subset. Otherwise
// a far target's block doesn't paint, the cache.active_search_y
// / header_position never gets recorded, and the two-stage
// corrective scroll (src/main.rs:scroll_to_active_match) can't
// snap to the precise y. Forcing the bootstrap branch costs one
// full-paint frame (~100 ms at 100k lines) per jump, which is
// acceptable for a one-off action.
//
// Critically, we DO NOT clear split_points here even though
// `page_size = None` forces a bootstrap. Reason: split_points
// store screen-y coordinates which are only meaningful at the
// scroll position they were captured at. The original scroll=0
// bootstrap stored values where screen-y ≈ content-y + panel
// chrome (~44 px). Clearing here lets the forced bootstrap at
// non-zero scroll re-populate them with screen-y values that
// diverge from content-y by the scroll amount, breaking every
// subsequent skip-paint's partition_point / allocate_space math
// by hundreds of pixels (visible as outline-click landing at
// the wrong heading and blank space at viewport top after
// scrolling). The push-site dedup-by-event-index keeps the
// original (good) values intact even though bootstrap re-runs.
if pending_scroll_offset.is_some() {
sc.page_size = None;
}
// Content-height drift check: if the previous frame's content
// height has drifted from when split_points were captured by
// more than CONTENT_H_DRIFT_THRESHOLD, the y-positions are stale
// (typically because async image/font loading shifted the doc
// after the initial bootstrap). Invalidate to trigger ONE
// re-bootstrap with refreshed positions. Uses absolute-drift
// hysteresis instead of bucketing because egui's `show()` vs
// `show_viewport()` content_size.y reporting differs by ~44 px
// (panel chrome) for the same content — any bucket-boundary
// approach would oscillate; only |drift| > threshold breaks
// out of that cycle.
if sc.bootstrap_content_h > 0.0
&& (sc.last_content_h - sc.bootstrap_content_h).abs() > CONTENT_H_DRIFT_THRESHOLD
{
sc.page_size = None;
sc.split_points.clear();
}
}
// Header positions are content-keyed; new content means the cached
// y values point at the wrong headings. Done outside the `sc` borrow
// scope above so `cache` is reborrowable.
if content_changed {
cache.clear_header_positions();
}
// Helper: build the renderer-owned ScrollArea with caller config.
let make_scroll_area = || {
let mut sa = egui::ScrollArea::vertical()
.id_salt(scroll_id)
.auto_shrink([false, true]);
if let Some(offset) = pending_scroll_offset {
sa = sa.vertical_scroll_offset(offset);
}
if let Some(src) = scroll_source {
sa = sa.scroll_source(src);
}
sa
};
// FORCE BOOTSTRAP EVERY FRAME: disable viewport-virtualization until
// the skip-paint slicing bugs are fully resolved (see
// docs/devlog/030-skip-paint-investigation.md for the design plan).
// The slice path renders events without their preceding container
// context (Start tags before the slice are missing), producing
// layout differences vs bootstrap — visible as flicker, wrong
// spacing, and shifted indents during scroll. Bootstrap renders
// the full document each frame; measured on T470 (i5-7200U, 2c):
// 1.2 ms / 348 events, 5.7 ms / 2514 events, 39 ms / 20k events,
// 229 ms / 100k events. Acceptable up to ~10k events; degraded
// above. The skip-paint code below is kept as `unreachable!`
// so future restoration can drop the early return.
{
let out = make_scroll_area().show(ui, |ui| {
cache.set_scroll_offset(pending_scroll_offset.unwrap_or(0.0));
self.show(ui, cache, options, text, Some(source_id));
});
let sc = scroll_cache(cache, &source_id);
sc.available_size = available_size;
sc.last_content_h = out.content_size.y;
sc.bootstrap_content_h = out.content_size.y;
return out;
}
// Kept for future restoration once skip-paint is bug-free.
#[allow(unreachable_code)]
let page_size_opt = scroll_cache(cache, &source_id).page_size;
#[allow(unreachable_code)]
let Some(page_size) = page_size_opt else {
unreachable!()
};
let num_rows = scroll_cache(cache, &source_id).events.len();
let out = make_scroll_area()
.show_viewport(ui, |ui, viewport| {
ui.set_height(page_size.y);
// ui.cursor().top() inside show_viewport is viewport-relative;
// record_header_position and record_active_search_y_viewport
// add this offset to recover content-relative y.
cache.set_scroll_offset(viewport.min.y);
let layout = egui::Layout::left_to_right(egui::Align::BOTTOM).with_main_wrap(true);
let max_width = options.max_width(ui);
ui.allocate_ui_with_layout(egui::vec2(max_width, 0.0), layout, |ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let scroll_cache = scroll_cache(cache, &source_id);
// split_points are populated in event order, which matches
// top-to-bottom layout order, so y-coords are monotonic
// non-decreasing. Binary-search instead of linear filter:
// O(log N) vs the old O(N) at 15k+ split points (100k-line doc).
// First waypoint: the second-to-last split point whose
// end.y is still above the viewport. Picking "second-to-last"
// gives us a safety frame above the viewport top to avoid
// clipping inline-flow content that started just above.
let above = scroll_cache
.split_points
.partition_point(|(_, _, end)| end.y < viewport.min.y);
let (first_event_index, _, first_end_position) = if above >= 2 {
scroll_cache.split_points[above - 2]
} else {
(0, Pos2::ZERO, Pos2::ZERO)
};
// Last waypoint: the second split point whose start.y is
// strictly below the viewport bottom. Same safety idea on
// the bottom edge.
let below = scroll_cache
.split_points
.partition_point(|(_, start, _)| start.y <= viewport.max.y);
let last_event_index = scroll_cache
.split_points
.get(below + 1)
.map(|(index, _, _)| *index)
.unwrap_or(num_rows);
// Clone only the events we'll actually iterate this frame
// — the visible viewport plus safety margins above/below.
// The previous implementation cloned the full Vec (~1.5 ms
// at 30k events on Recent-Changes.md), then `skip`ed all
// but ~150 events. This trims the clone to the actual
// range used, dropping per-frame allocation churn from
// ~1.5 ms to ~10 µs on the same doc. The slice clone is
// released before `process_event` mutably re-borrows the
// cache for syntect/header state — NLL covers this.
let range_end = last_event_index.min(scroll_cache.events.len());
let events_range: Vec<(pulldown_cmark::Event<'static>, Range<usize>)> =
if first_event_index < range_end {
scroll_cache.events[first_event_index..range_end].to_vec()
} else {
Vec::new()
};
let last_sp_y_used = scroll_cache
.split_points
.get(below + 1)
.map(|p| p.2.y)
.unwrap_or(0.0);
eprintln!(
"[SKIP] vp=[{:.0},{:.0}] evt=[{},{}]/{} sp_y=[{:.0},{:.0}] a={} b={}",
viewport.min.y, viewport.max.y,
first_event_index, last_event_index, num_rows,
first_end_position.y, last_sp_y_used,
above, below
);
// Advance cursor VERTICALLY by first_end_position.y to
// position events at the right viewport y. `to_vec2()`
// would also pass first_end_position.x as allocation
// width — that's the X-cursor where the previous block
// ended (often a non-zero left margin or a list-indent
// depth). In `left_to_right(BOTTOM).with_main_wrap`,
// allocate_space consumes that as width-advance,
// shifting subsequent events right and breaking
// indentation of code blocks, tables, and text.
ui.allocate_space(egui::vec2(0.0, first_end_position.y));
// Re-attach original indices via map so peekable iteration
// and downstream consumers still see the absolute event
// index (used by `if i == 0 { ... }` below for the
// bootstrap-newline gate).
let mut events = events_range
.into_iter()
.enumerate()
.map(|(offset, ev)| (offset + first_event_index, ev))
.peekable();
while let Some((i, (e, src_span))) = events.next() {
if events.peek().is_none() {
self.line.should_end_newline_forced = false;
}
self.process_event(ui, &mut events, e, src_span, cache, options, max_width);
if i == 0 {
self.line.should_not_start_newline_forced = false;
}
}
});
});
// NOTE: deliberately NOT updating last_content_h from skip-paint's
// `out.content_size.y`. That value is unreliable: skip-paint does
// `set_height(page_size.y)` (min height) then `allocate_space(Vec2(0,
// first_end_position.y))` which can advance the cursor by tens of
// thousands of px when scrolled deep — content_size.y inflates to
// 2× the real document height. Feeding that into the drift check
// triggers an invalidation, re-bootstrap fires at the current
// (non-zero) scroll, split_points get repopulated with screen-y
// coords that are catastrophically off, the next skip-paint picks
// wrong events, content_h spikes the other way, drift fires again
// — death spiral. Empirically: 619 bootstraps in 30 s of scroll on
// T470, panel flickered blank with garbled styling. Restricting
// drift signal to bootstrap-only content_h prevents the false
// positive. Async-image-load growth is still caught — that fires
// during the SECOND bootstrap (which is allowed to happen for
// other reasons, e.g. font/scrollbar layout settling at startup),
// where the new content_h IS written to last_content_h.
// Scroll-overshoot clamp.
let real_max_scroll = (page_size.y - out.inner_rect.height()).max(0.0);
let clamped = out.state.offset.y > real_max_scroll;
if clamped {
let mut state = out.state;
state.offset.y = real_max_scroll;
state.store(ui.ctx(), out.id);
ui.ctx().request_repaint();
}
let _ = clamped;
out
// No trailing invalidation needed — layout_signature is checked at
// the top of show_scrollable, so a width/zoom/theme change in the
// same frame falls into the bootstrap branch above immediately
// instead of one frame later.
}
#[allow(clippy::too_many_arguments)]
fn process_event<'e>(
&mut self,
ui: &mut Ui,
events: &mut Peekable<impl Iterator<Item = EventIteratorItem<'e>>>,
event: pulldown_cmark::Event,
src_span: Range<usize>,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
max_width: f32,
) {
self.event(ui, event, src_span, cache, options, max_width);
self.def_list_def_wrapping(events, max_width, cache, options, ui);
self.item_list_wrapping(events, max_width, cache, options, ui);
self.table(events, cache, options, ui, max_width);
self.blockquote(events, max_width, cache, options, ui);
}
fn def_list_def_wrapping<'e>(
&mut self,
events: &mut Peekable<impl Iterator<Item = EventIteratorItem<'e>>>,
max_width: f32,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
ui: &mut Ui,
) {
if self.def_list.is_def_list_def {
self.def_list.is_def_list_def = false;
let item_events = delayed_events(events, |tag| {
matches!(tag, pulldown_cmark::TagEnd::DefinitionListDefinition)
});
let mut events_iter = item_events.into_iter().enumerate().peekable();
self.line.try_insert_start(ui);
// Proccess a single event separately so that we do not insert spaces where we do not
// want them
self.line.should_start_newline = false;
if let Some((_, (e, src_span))) = events_iter.next() {
self.process_event(ui, &mut events_iter, e, src_span, cache, options, max_width);
}
ui.label(" ".repeat(options.indentation_spaces));
self.line.should_start_newline = true;
self.line.should_end_newline = false;
// Required to ensure that the content is aligned with the identation
ui.horizontal_wrapped(|ui| {
while let Some((_, (e, src_span))) = events_iter.next() {
self.process_event(
ui,
&mut events_iter,
e,
src_span,
cache,
options,
max_width,
);
}
});
self.line.should_end_newline = true;
// Only end the definition items line if it is not the last element in the list
if !matches!(
events.peek(),
Some((
_,
(
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::DefinitionList),
_
)
))
) {
self.line.try_insert_end(ui);
}
}
}
fn item_list_wrapping<'e>(
&mut self,
events: &mut impl Iterator<Item = EventIteratorItem<'e>>,
max_width: f32,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
ui: &mut Ui,
) {
if self.is_list_item {
self.is_list_item = false;
let item_events = delayed_events_list_item(events);
let mut events_iter = item_events.into_iter().enumerate().peekable();
// Required to ensure that the content of the list item is aligned with
// the * or - when wrapping
ui.horizontal_wrapped(|ui| {
while let Some((_, (e, src_span))) = events_iter.next() {
self.process_event(
ui,
&mut events_iter,
e,
src_span,
cache,
options,
max_width,
);
}
});
}
}
fn blockquote<'e>(
&mut self,
events: &mut Peekable<impl Iterator<Item = EventIteratorItem<'e>>>,
max_width: f32,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
ui: &mut Ui,
) {
if self.is_blockquote {
let mut collected_events = delayed_events(events, |tag| {
matches!(tag, pulldown_cmark::TagEnd::BlockQuote(_))
});
self.line.try_insert_start(ui);
// Currently the blockquotes are made in such a way that they need a newline at the end
// and the start so when this is the first element in the markdown the newline must be
// manually enabled
self.line.should_not_start_newline_forced = false;
if let Some(alert) = parse_alerts(&options.alerts, &mut collected_events) {
egui_commonmark_backend_extended::alert_ui(alert, ui, |ui| {
for (event, src_span) in collected_events {
self.event(ui, event, src_span, cache, options, max_width);
}
})
} else {
blockquote(ui, ui.visuals().weak_text_color(), |ui| {
self.text_style.quote = true;
for (event, src_span) in collected_events {
self.event(ui, event, src_span, cache, options, max_width);
}
self.text_style.quote = false;
});
}
if events.peek().is_none() {
self.line.should_end_newline_forced = false;
}
self.line.try_insert_end(ui);
self.is_blockquote = false;
}
}
fn table<'e>(
&mut self,
events: &mut Peekable<impl Iterator<Item = EventIteratorItem<'e>>>,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
ui: &mut Ui,
max_width: f32,
) {
if self.is_table {
self.line.try_insert_start(ui);
let id = ui.id().with("_table").with(self.curr_table);
self.curr_table += 1;
// Consume events into header/rows up front so we know the column count
// (TableBuilder requires the column count declared before rendering).
// `header` is a Vec<Cell> for a single header row, so `header.len()` is
// the column count. Each row in `rows` is itself a Vec<Cell>.
let Table { header, rows } = parse_table(events);
// Drop trailing empty rows that pulldown_cmark sometimes appends.
let rows: Vec<_> = rows.into_iter().filter(|r| !r.is_empty()).collect();
let num_cols = if !header.is_empty() {
header.len()
} else {
rows.first().map(|r| r.len()).unwrap_or(0)
};
let line_h = ui.text_style_height(&egui::TextStyle::Body);
if num_cols == 0 {
self.is_table = false;
if events.peek().is_none() {
self.line.should_end_newline_forced = false;
}
self.line.try_insert_end(ui);
return;
}
// Per-line cell height; rows grow taller when cells contain multi-chunk
// inline-code wraps (computed below via `cell_visual_lines`).
let cell_h = line_h * 1.5;
// Header is one row; its height grows if any header cell has wrapped code.
let header_lines = header
.iter()
.map(|c| cell_visual_lines(c))
.max()
.unwrap_or(1);
let header_h = cell_h * header_lines as f32;
// Pre-compute per-body-row height so multi-chunk cells aren't clipped.
let body_heights: Vec<f32> = rows
.iter()
.map(|row| {
let max_lines = row
.iter()
.map(|c| cell_visual_lines(c))
.max()
.unwrap_or(1);
cell_h * max_lines as f32
})
.collect();
// Outer ScrollArea::horizontal handles the case where columns
// (auto-sized to content) total wider than the parent ui; without it,
// narrow windows clip the rightmost columns. Plain vertical wheel
// remains with the outer document scroller (#22); Shift+wheel opts in
// to horizontal table scrolling via `forward_shift_wheel_to_horizontal_scroll`.
// ui.vertical(...) is essential: TableBuilder's body() positions itself
// relative to the parent's cursor, but the parent here is a horizontal-
// flow Ui from the markdown renderer. Without the vertical scope the
// body's first row overlaps the header row.
let mut scroll_out = egui::ScrollArea::horizontal()
.id_salt(id.with("_scroll"))
.max_width(max_width)
.auto_shrink([false, true])
.show(ui, |ui| {
ui.vertical(|ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
let table = egui_extras::TableBuilder::new(ui)
.id_salt(id)
.striped(true)
.resizable(true)
.vscroll(false)
// Shrink horizontally to the columns' content so a
// table narrower than the panel hugs its columns
// instead of stretching the bordered frame full width
// with an empty gap after the last column (#47). The
// outer ScrollArea still bounds wide tables at
// max_width and provides horizontal scroll.
.auto_shrink([true, true])
.min_scrolled_height(0.0)
.cell_layout(egui::Layout::left_to_right(egui::Align::Center))
.columns(
egui_extras::Column::auto().resizable(true).at_least(40.0),
num_cols,
)
.header(header_h, |mut row| {
for col in header {
row.col(|ui| {
let col_w = ui.available_width();
for (e, src_span) in col {
let tmp_start = std::mem::replace(
&mut self.line.should_start_newline,
false,
);
let tmp_end = std::mem::replace(
&mut self.line.should_end_newline,
false,
);
self.event(
ui, e, src_span, cache, options, col_w,
);
self.line.should_start_newline = tmp_start;
self.line.should_end_newline = tmp_end;
}
});
}
});
table.body(|mut body| {
for (row_idx, row) in rows.into_iter().enumerate() {
let h = body_heights
.get(row_idx)
.copied()
.unwrap_or(cell_h);
body.row(h, |mut row_ui| {
for col in row {
row_ui.col(|ui| {
let col_w = ui.available_width();
for (e, src_span) in col {
let tmp_start = std::mem::replace(
&mut self.line.should_start_newline,
false,
);
let tmp_end = std::mem::replace(
&mut self.line.should_end_newline,
false,
);
self.event(
ui, e, src_span, cache, options, col_w,
);
self.line.should_start_newline = tmp_start;
self.line.should_end_newline = tmp_end;
}
});
}
});
}
});
});
});
});
forward_shift_wheel_to_horizontal_scroll(ui, &mut scroll_out);
self.is_table = false;
if events.peek().is_none() {
self.line.should_end_newline_forced = false;
}
self.line.try_insert_end(ui);
}
}
fn event(
&mut self,
ui: &mut Ui,
event: pulldown_cmark::Event,
src_span: Range<usize>,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
max_width: f32,
) {
match event {
pulldown_cmark::Event::Start(tag) => self.start_tag(ui, tag, options),
pulldown_cmark::Event::End(tag) => self.end_tag(ui, tag, cache, options, max_width),
pulldown_cmark::Event::Text(text) => {
self.event_text_with_highlights(text, &src_span, cache, ui, options);
}
pulldown_cmark::Event::Code(text) => {
self.text_style.code = true;
let segments = inline_code_wrap_segments(&text);
let wrap = segments.len() > 1;
// For non-wrapped inline code, derive an interior span (strip equal
// backticks on each side) so search highlights line up with the visible
// code text. Wrapped (>56 char) code skips highlighting in v1.
let interior_span = if !wrap && src_span.len() >= text.len() {
let delim_total = src_span.len() - text.len();
if delim_total > 0 && delim_total % 2 == 0 {
let bt = delim_total / 2;
Some((src_span.start + bt)..(src_span.end - bt))
} else {
None
}
} else {
None
};
for segment in segments {
if let Some(ref span) = interior_span {
// Inline code stays source-literal while retaining byte-range highlights.
self.event_literal_text_with_highlights(
segment.into(),
span,
cache,
ui,
options,
);
} else {
self.event_text(segment.into(), ui, options);
}
if wrap {
ui.end_row();
}
}
self.text_style.code = false;
}
pulldown_cmark::Event::InlineHtml(text) => {
self.event_text(text, ui, options);
}
pulldown_cmark::Event::Html(text) => {
// Always accumulate HTML blocks for table detection
self.html_block.push_str(&text);
}
pulldown_cmark::Event::FootnoteReference(footnote) => {
footnote_start(ui, &footnote);
}
pulldown_cmark::Event::SoftBreak => {
soft_break(ui);
}
pulldown_cmark::Event::HardBreak => newline(ui),
pulldown_cmark::Event::Rule => {
self.line.try_insert_start(ui);
rule(ui, self.line.can_insert_end());
}
pulldown_cmark::Event::TaskListMarker(mut checkbox) => {
if options.mutable {
if ui
.add(egui::Checkbox::without_text(&mut checkbox))
.clicked()
{
self.checkbox_events.push(CheckboxClickEvent {
checked: checkbox,
span: src_span,
});
}
} else {
ui.add(ImmutableCheckbox::without_text(&mut checkbox));
}
}
pulldown_cmark::Event::InlineMath(tex) => {
if is_likely_currency(&tex) {
// Render as plain text with $ prefix instead of math
let text: CowStr = format!("${tex}").into();
self.event_text(text, ui, options);
} else {
#[cfg(feature = "math")]
{
crate::render_math(ui, cache, &tex, true);
}
#[cfg(not(feature = "math"))]
if let Some(math_fn) = options.math_fn {
math_fn(ui, &tex, true);
}
}
}
pulldown_cmark::Event::DisplayMath(tex) => {
// Display math (`$$…$$`) is a block: force it onto its own line
// even when the source keeps it in the same paragraph as the
// preceding text (`obeys\n$$…$$`). Without the breaks it flows to
// the right of that text and, being taller than a line, gets
// pushed down by the row's bottom-alignment.
newline(ui);
#[cfg(feature = "math")]
{
crate::render_math(ui, cache, &tex, false);
}
#[cfg(not(feature = "math"))]
if let Some(math_fn) = options.math_fn {
math_fn(ui, &tex, false);
}
newline(ui);
}
}
}
fn event_text(&mut self, text: CowStr, ui: &mut Ui, options: &CommonMarkOptions) {
self.emit_text(text, None, HighlightKind::None, ui, options);
}
/// Render text while optionally retaining a different raw spelling for heading identity.
fn emit_text(
&mut self,
text: CowStr,
raw_heading_text: Option<&str>,
hl: HighlightKind,
ui: &mut Ui,
options: &CommonMarkOptions,
) {
let bg = hl.background_color(ui);
let mut rich_text = if bg.is_some() && self.text_style.code {
// egui's RichText renderer overrides `background_color` with the theme's
// `code_bg_color` whenever `.code()` is set (widget_text.rs:421). To make
// our search highlight visible inside inline code, build the RichText
// manually with a monospace font instead of calling `.code()` — that gives
// the visual effect of code (monospace + slightly larger weight) while
// letting our background_color survive.
let mut t = egui::RichText::new(text.as_ref())
.text_style(egui::TextStyle::Monospace);
if self.text_style.strong {
t = t.strong();
}
if self.text_style.emphasis {
t = t.italics();
}
if self.text_style.strikethrough {
t = t.strikethrough();
}
if self.text_style.quote {
t = t.weak();
}
t
} else {
self.text_style.to_richtext_with_options(ui, &text, options)
};
if let Some(bg) = bg {
rich_text = rich_text.background_color(bg);
}
if let Some(image) = &mut self.image {
image.alt_text.push(rich_text);
} else if let Some(block) = &mut self.code_block {
// Code blocks render via syntect after end_tag; highlight inside code
// blocks is a v2 feature (would need syntect integration). Just collect text.
block.content.push_str(&text);
} else if let Some(link) = &mut self.link {
link.text.push(rich_text);
} else if self.text_style.heading.is_some() {
// Accumulate heading text for position tracking
self.current_heading_text
.push_str(raw_heading_text.unwrap_or(&text));
// Accumulate RichText - will render all at once in end_tag(Heading)
self.current_heading_rich_texts.push(rich_text);
} else {
ui.label(rich_text);
}
}
/// Render source-literal text while preserving fine-grained search highlighting.
fn event_literal_text_with_highlights(
&mut self,
text: CowStr,
span: &Range<usize>,
cache: &mut CommonMarkCache,
ui: &mut Ui,
options: &CommonMarkOptions,
) {
// Emit borrowed slices directly; record captured active Y after cache borrows end.
let mut active_y = None;
visit_highlight_segments(
&text,
span,
cache.search_ranges(),
cache.active_search_range(),
|segment_text, hl| {
if hl == HighlightKind::Active {
active_y = Some(ui.cursor().top());
}
self.emit_text(segment_text.into(), None, hl, ui, options);
},
);
if let Some(y) = active_y {
cache.record_active_search_y_viewport(y);
}
}
/// Expand eligible emoji shortcodes, then preserve source-based search semantics.
fn event_text_with_highlights(
&mut self,
text: CowStr,
span: &Range<usize>,
cache: &mut CommonMarkCache,
ui: &mut Ui,
options: &CommonMarkOptions,
) {
if !emoji_expansion_is_eligible(self.image.is_some(), self.code_block.is_some()) {
self.event_text(text, ui, options);
return;
}
// Emit borrowed source slices and static emoji strings directly.
let mut active_y = None;
visit_emoji_text_segments(&text, span, |segment| {
if segment.replaced {
// Replacement glyphs are indivisible, but overlap uses raw source range.
let hl = highlight_for_source_span(
&segment.source_range,
cache.search_ranges(),
cache.active_search_range(),
);
if hl == HighlightKind::Active {
active_y = Some(ui.cursor().top());
}
self.emit_text(segment.rendered.into(), Some(segment.raw), hl, ui, options);
return;
}
// Plain source-preserving segments retain exact highlight splitting.
visit_highlight_segments(
segment.rendered,
&segment.source_range,
cache.search_ranges(),
cache.active_search_range(),
|segment_text, hl| {
if hl == HighlightKind::Active {
active_y = Some(ui.cursor().top());
}
self.emit_text(segment_text.into(), None, hl, ui, options);
},
);
});
if let Some(y) = active_y {
cache.record_active_search_y_viewport(y);
}
}
fn start_tag(&mut self, ui: &mut Ui, tag: pulldown_cmark::Tag, options: &CommonMarkOptions) {
match tag {
pulldown_cmark::Tag::Paragraph => {
self.line.try_insert_start(ui);
}
pulldown_cmark::Tag::Heading { level, .. } => {
// End current row to ensure heading starts at left edge
ui.end_row();
// Record position BEFORE spacing for scroll navigation
self.current_heading_y = Some(ui.cursor().top());
self.current_heading_text.clear();
// Add extra spacing above headings if configured
heading_start_spacing(ui, &options.typography);
self.text_style.heading = Some(match level {
HeadingLevel::H1 => 0,
HeadingLevel::H2 => 1,
HeadingLevel::H3 => 2,
HeadingLevel::H4 => 3,
HeadingLevel::H5 => 4,
HeadingLevel::H6 => 5,
});
}
// deliberately not using the built in alerts from pulldown-cmark as
// the markdown itself cannot be localized :( e.g: [!TIP]
pulldown_cmark::Tag::BlockQuote(_) => {
self.is_blockquote = true;
}
pulldown_cmark::Tag::CodeBlock(c) => {
// List items render in one horizontal_wrapped row; end it before a block widget.
if self.list.is_inside_a_list() {
ui.end_row();
}
match c {
pulldown_cmark::CodeBlockKind::Fenced(lang) => {
self.code_block = Some(crate::CodeBlock {
lang: Some(lang.to_string()),
content: "".to_string(),
});
}
pulldown_cmark::CodeBlockKind::Indented => {
self.code_block = Some(crate::CodeBlock {
lang: None,
content: "".to_string(),
});
}
}
self.line.try_insert_start(ui);
}
pulldown_cmark::Tag::List(point) => {
if !self.list.is_inside_a_list() && self.line.can_insert_start() {
newline(ui);
}
if let Some(number) = point {
self.list.start_level_with_number(number);
} else {
self.list.start_level_without_number();
}
self.line.should_start_newline = false;
self.line.should_end_newline = false;
}
pulldown_cmark::Tag::Item => {
self.is_list_item = true;
self.list.start_item(ui, options);
}
pulldown_cmark::Tag::FootnoteDefinition(note) => {
self.line.try_insert_start(ui);
self.line.should_start_newline = false;
self.line.should_end_newline = false;
footnote(ui, ¬e);
}
pulldown_cmark::Tag::Table(_) => {
self.is_table = true;
}
pulldown_cmark::Tag::TableHead => {}
pulldown_cmark::Tag::TableRow => {}
pulldown_cmark::Tag::TableCell => {}
pulldown_cmark::Tag::Emphasis => {
self.text_style.emphasis = true;
}
pulldown_cmark::Tag::Strong => {
self.text_style.strong = true;
}
pulldown_cmark::Tag::Strikethrough => {
self.text_style.strikethrough = true;
}
pulldown_cmark::Tag::Link { dest_url, .. } => {
self.link = Some(crate::Link {
destination: dest_url.to_string(),
text: Vec::new(),
});
}
pulldown_cmark::Tag::Image { dest_url, .. } => {
self.image = Some(crate::Image::new(&dest_url, options));
}
pulldown_cmark::Tag::HtmlBlock => {
self.line.try_insert_start(ui);
}
pulldown_cmark::Tag::MetadataBlock(_) => {}
pulldown_cmark::Tag::DefinitionList => {
self.line.try_insert_start(ui);
self.def_list.is_first_item = true;
}
pulldown_cmark::Tag::DefinitionListTitle => {
// we disable newline as the first title should not insert a newline
// as we have already done that upon the DefinitionList Tag
if !self.def_list.is_first_item {
self.line.try_insert_start(ui)
} else {
self.def_list.is_first_item = false;
}
}
pulldown_cmark::Tag::DefinitionListDefinition => {
self.def_list.is_def_list_def = true;
}
// Not yet supported
pulldown_cmark::Tag::Superscript | pulldown_cmark::Tag::Subscript => {}
}
}
fn end_tag(
&mut self,
ui: &mut Ui,
tag: pulldown_cmark::TagEnd,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
max_width: f32,
) {
match tag {
pulldown_cmark::TagEnd::Paragraph => {
self.line.try_insert_end(ui);
// Add extra paragraph spacing if configured
paragraph_end_spacing(ui, &options.typography);
}
pulldown_cmark::TagEnd::Heading { .. } => {
// Render all accumulated heading fragments at once, positioned at left edge
if !self.current_heading_rich_texts.is_empty() {
let available = ui.available_rect_before_wrap();
let left_edge = ui.min_rect().left();
let heading_rect = egui::Rect::from_min_size(
egui::pos2(left_edge, available.top()),
egui::vec2(available.width() + (available.left() - left_edge), available.height()),
);
let rich_texts = std::mem::take(&mut self.current_heading_rich_texts);
ui.allocate_ui_at_rect(heading_rect, |ui| {
for rt in rich_texts {
ui.label(rt);
}
});
}
// Record header position for scroll navigation. Composite key
// is `normalized_title` for the 0th occurrence and
// `normalized_title#N` for the Nth duplicate (matches the key
// built by the app's `header_position_key` helper), so multiple
// headings with the same title get distinct cache entries.
if let Some(y) = self.current_heading_y.take() {
if !self.current_heading_text.is_empty() {
let normalized = self.current_heading_text.trim().to_lowercase();
let nth = self
.heading_occurrence_counts
.entry(normalized.clone())
.or_insert(0);
let key = if *nth == 0 {
normalized.clone()
} else {
format!("{normalized}#{nth}")
};
*nth += 1;
// `y` (== `ui.cursor().top()` at heading start) is a
// SCREEN-y coordinate. The click handler uses the
// cached value with `ScrollArea::vertical_scroll_offset(N)`,
// which interprets N as a CONTENT-y (where 0 is the
// top of the ScrollArea's content layout). Subtract
// `ui.min_rect().top()` — that's the screen y of the
// closure's ui top-left, which tracks the current
// scroll offset (it shifts up as the user scrolls).
// The subtraction cancels out both the panel chrome
// AND any active scroll offset, leaving a pure
// content-y that's invariant across scroll positions.
//
// Empirical verification on Recent-Changes.md:
// - At scroll=0: title cursor=323, min_rect.top()=44
// → content_y = 279
// - After click to scroll=273: cursor=50,
// min_rect.top()=-229 → content_y = 279
// - Same heading, same content_y, regardless of scroll
//
// Previously stored `cur_offset + cursor.y` which gave
// 323 (off by 44 = panel chrome height), so scrolling
// to (323-50)=273 landed 44 px past the heading.
let content_y = y - ui.min_rect().top();
// Always refresh with current layout, not first-paint
// value. First-paint pinning produced increasing
// overshoot for deeper headers — the first frame
// renders before async font fallbacks (Noto) finish
// loading; once fonts settle, line widths shrink/grow
// by a few px per line, and the cumulative drift
// moves every heading's true y by an amount that
// scales linearly with its depth in the doc. The
// pinned cache then sends outline-clicks to the
// stale (under-shot) position. Updating each paint
// keeps the click target in sync with the current
// rendered layout.
cache.record_header_content_y(&key, content_y);
}
}
self.current_heading_text.clear();
// Add extra spacing below headings if configured
heading_end_spacing(ui, &options.typography);
self.line.try_insert_end(ui);
self.text_style.heading = None;
}
pulldown_cmark::TagEnd::BlockQuote(_) => {}
pulldown_cmark::TagEnd::CodeBlock => {
self.end_code_block(ui, cache, options, max_width);
// Keep any following list-item text below the completed block widget.
if self.list.is_inside_a_list() {
ui.end_row();
}
}
pulldown_cmark::TagEnd::List(_) => {
if self.list.is_last_level() {
self.line.should_start_newline = true;
self.line.should_end_newline = true;
}
self.list.end_level(ui, self.line.can_insert_end());
if !self.list.is_inside_a_list() {
// Reset all the state and make it ready for the next list that occurs
self.list = List::default();
}
}
pulldown_cmark::TagEnd::Item => {}
pulldown_cmark::TagEnd::FootnoteDefinition => {
self.line.should_start_newline = true;
self.line.should_end_newline = true;
self.line.try_insert_end(ui);
}
pulldown_cmark::TagEnd::Table => {}
pulldown_cmark::TagEnd::TableHead => {}
pulldown_cmark::TagEnd::TableRow => {}
pulldown_cmark::TagEnd::TableCell => {
// Ensure space between cells
ui.label(" ");
}
pulldown_cmark::TagEnd::Emphasis => {
self.text_style.emphasis = false;
}
pulldown_cmark::TagEnd::Strong => {
self.text_style.strong = false;
}
pulldown_cmark::TagEnd::Strikethrough => {
self.text_style.strikethrough = false;
}
pulldown_cmark::TagEnd::Link => {
if let Some(link) = self.link.take() {
link.end(ui, cache);
}
}
pulldown_cmark::TagEnd::Image => {
if let Some(image) = self.image.take() {
image.end(ui, cache, options);
}
}
pulldown_cmark::TagEnd::HtmlBlock => {
if !self.html_block.is_empty() {
if let Some(table) = egui_commonmark_backend_extended::html_table::parse_html_table(&self.html_block) {
self.render_html_table(ui, &table, options, max_width);
} else if let Some(html_fn) = options.html_fn {
html_fn(ui, &self.html_block);
} else {
// Render non-table HTML as plain text (existing fallback)
let text: pulldown_cmark::CowStr = std::mem::take(&mut self.html_block).into();
self.event_text(text, ui, options);
}
self.html_block.clear();
}
}
pulldown_cmark::TagEnd::MetadataBlock(_) => {}
pulldown_cmark::TagEnd::DefinitionList => self.line.try_insert_end(ui),
pulldown_cmark::TagEnd::DefinitionListTitle
| pulldown_cmark::TagEnd::DefinitionListDefinition => {}
pulldown_cmark::TagEnd::Superscript | pulldown_cmark::TagEnd::Subscript => {}
}
}
fn end_code_block(
&mut self,
ui: &mut Ui,
cache: &mut CommonMarkCache,
options: &CommonMarkOptions,
max_width: f32,
) {
if let Some(block) = self.code_block.take() {
let id = ui.id().with("_code_block").with(self.curr_code_block);
self.curr_code_block += 1;
block.end(ui, cache, options, max_width, id);
self.line.try_insert_end(ui);
}
}
fn render_html_table(
&mut self,
ui: &mut Ui,
table: &egui_commonmark_backend_extended::html_table::HtmlTable,
options: &CommonMarkOptions,
max_width: f32,
) {
let id = ui.id().with("_html_table").with(self.curr_table);
self.curr_table += 1;
let num_cols = table
.header
.first()
.or(table.rows.first())
.map(|r| r.len())
.unwrap_or(0);
let line_h = ui.text_style_height(&egui::TextStyle::Body);
let cell_h = line_h * 1.5;
if num_cols == 0 {
self.line.try_insert_end(ui);
return;
}
// Heuristic per-row heights: count explicit newlines + crude wrap est at
// ~60 chars/visual-line. Over-estimates slightly (extra row height is
// preferable to clipping). Header rows use the same heuristic.
let row_height_for = |cells: &[String]| -> f32 {
let max_lines = cells
.iter()
.map(|c| html_cell_visual_lines(c))
.max()
.unwrap_or(1);
cell_h * max_lines as f32
};
let header_h = table
.header
.first()
.map(|row| row_height_for(row))
.unwrap_or(cell_h);
let extra_header_heights: Vec<f32> = table
.header
.iter()
.skip(1)
.map(|row| row_height_for(row))
.collect();
let body_heights: Vec<f32> = table.rows.iter().map(|row| row_height_for(row)).collect();
// Outer ScrollArea::horizontal handles wide tables that exceed parent width;
// ui.vertical() prevents the header/body Y-overlap quirk. Plain vertical wheel
// stays with the outer document scroller (#22); Shift+wheel opts in to
// horizontal table scrolling via `forward_shift_wheel_to_horizontal_scroll`.
let mut scroll_out = egui::ScrollArea::horizontal()
.id_salt(id.with("_scroll"))
.max_width(max_width)
.auto_shrink([false, true])
.show(ui, |ui| {
ui.vertical(|ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
let builder = egui_extras::TableBuilder::new(ui)
.id_salt(id)
.striped(true)
.resizable(true)
.vscroll(false)
// Hug columns when narrower than the panel (#47); the
// outer ScrollArea still handles wide-table overflow.
.auto_shrink([true, true])
.min_scrolled_height(0.0)
.cell_layout(egui::Layout::left_to_right(egui::Align::Center))
.columns(
egui_extras::Column::auto().resizable(true).at_least(40.0),
num_cols,
);
let render_cell_strong = |ui: &mut Ui, cell: &str| {
egui::Frame::NONE
.inner_margin(egui::Margin::symmetric(8, 4))
.show(ui, |ui| {
ui.strong(cell);
});
};
if let Some(first_header) = table.header.first() {
builder
.header(header_h, |mut row| {
for cell in first_header {
row.col(|ui| render_cell_strong(ui, cell));
}
})
.body(|mut body| {
// Extra header rows after the first render as bold
// body rows (TableBuilder has only one native header row).
for (idx, extra) in table.header.iter().skip(1).enumerate() {
let h = extra_header_heights
.get(idx)
.copied()
.unwrap_or(cell_h);
body.row(h, |mut row_ui| {
for cell in extra {
row_ui.col(|ui| render_cell_strong(ui, cell));
}
});
}
for (row_idx, row) in table.rows.iter().enumerate() {
let h = body_heights
.get(row_idx)
.copied()
.unwrap_or(cell_h);
body.row(h, |mut row_ui| {
for cell in row {
row_ui.col(|ui| {
egui::Frame::NONE
.inner_margin(egui::Margin::symmetric(
8, 4,
))
.show(ui, |ui| {
let rich_text = self
.text_style
.to_richtext_with_options(
ui,
cell,
options,
);
ui.label(rich_text);
});
});
}
});
}
});
} else {
builder.body(|mut body| {
for (row_idx, row) in table.rows.iter().enumerate() {
let h = body_heights
.get(row_idx)
.copied()
.unwrap_or(cell_h);
body.row(h, |mut row_ui| {
for cell in row {
row_ui.col(|ui| {
egui::Frame::NONE
.inner_margin(egui::Margin::symmetric(8, 4))
.show(ui, |ui| {
let rich_text = self
.text_style
.to_richtext_with_options(
ui,
cell,
options,
);
ui.label(rich_text);
});
});
}
});
}
});
}
});
});
});
forward_shift_wheel_to_horizontal_scroll(ui, &mut scroll_out);
self.line.try_insert_end(ui);
}
}
#[cfg(test)]
mod tests {
use super::*;
use pulldown_cmark::{Event, Options, Parser, Tag};
// Snapshot scanner output so ranges and raw/rendered identities stay explicit.
fn segment_snapshot(text: &str, start: usize) -> Vec<(String, Range<usize>, String, bool)> {
let mut snapshots = Vec::new();
visit_emoji_text_segments(text, &(start..start + text.len()), |segment| {
snapshots.push((
segment.rendered.to_owned(),
segment.source_range,
segment.raw.to_owned(),
segment.replaced,
));
});
snapshots
}
// Collect highlight output only in tests; production emission stays borrowed.
fn highlight_snapshot(
text: &str,
span: &Range<usize>,
ranges: &[Range<usize>],
active: Option<&Range<usize>>,
) -> Vec<(String, HighlightKind)> {
let mut snapshots = Vec::new();
visit_highlight_segments(text, span, ranges, active, |segment, kind| {
snapshots.push((segment.to_owned(), kind));
});
snapshots
}
// Exercise expansion at pulldown event boundaries without invoking egui painting.
fn expanded_visible_text(markdown: &str) -> String {
let mut visible = String::new();
let mut image_depth = 0usize;
let mut code_block_depth = 0usize;
for (event, span) in Parser::new_ext(markdown, Options::all()).into_offset_iter() {
match event {
Event::Start(Tag::Image { .. }) => image_depth += 1,
Event::End(pulldown_cmark::TagEnd::Image) => image_depth -= 1,
Event::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
Event::End(pulldown_cmark::TagEnd::CodeBlock) => code_block_depth -= 1,
Event::Text(text)
if emoji_expansion_is_eligible(image_depth > 0, code_block_depth > 0) =>
{
visit_emoji_text_segments(&text, &span, |segment| {
visible.push_str(segment.rendered);
});
}
Event::Text(text) | Event::Code(text) => visible.push_str(&text),
_ => {}
}
}
visible
}
#[test]
fn no_colon_fast_path_borrows_original_text() {
let text = "plain text only";
let mut seen = 0;
visit_emoji_text_segments(text, &(7..7 + text.len()), |segment| {
seen += 1;
assert_eq!(segment.rendered.as_ptr(), text.as_ptr());
assert_eq!(segment.raw.as_ptr(), text.as_ptr());
assert_eq!(segment.source_range, 7..7 + text.len());
assert!(!segment.replaced);
});
assert_eq!(seen, 1);
}
#[test]
fn unknown_only_fast_path_borrows_original_text() {
let text = ":unknown: and :still_unknown:";
let mut seen = 0;
visit_emoji_text_segments(text, &(3..3 + text.len()), |segment| {
seen += 1;
assert_eq!(segment.rendered.as_ptr(), text.as_ptr());
assert_eq!(segment.raw.as_ptr(), text.as_ptr());
assert_eq!(segment.source_range, 3..3 + text.len());
assert!(!segment.replaced);
});
assert_eq!(seen, 1);
}
#[test]
fn plain_query_boundary_does_not_highlight_following_emoji() {
let text = "hello world :rocket:";
let span = 30..30 + text.len();
let world = 36..41;
let mut snapshots = Vec::new();
visit_emoji_text_segments(text, &span, |segment| {
if segment.replaced {
snapshots.push((
segment.rendered.to_owned(),
highlight_for_source_span(
&segment.source_range,
std::slice::from_ref(&world),
None,
),
));
} else {
snapshots.extend(highlight_snapshot(
segment.rendered,
&segment.source_range,
std::slice::from_ref(&world),
None,
));
}
});
assert_eq!(
snapshots,
vec![
("hello ".into(), HighlightKind::None),
("world".into(), HighlightKind::Match),
(" ".into(), HighlightKind::None),
("🚀".into(), HighlightKind::None),
]
);
}
#[test]
fn emoji_segments_keep_absolute_raw_source_ranges() {
assert_eq!(
segment_snapshot("A :pushpin: B", 20),
vec![
("A ".into(), 20..22, "A ".into(), false),
("📌".into(), 22..31, ":pushpin:".into(), true),
(" B".into(), 31..33, " B".into(), false),
]
);
}
#[test]
fn emoji_segments_support_multiple_and_adjacent_shortcodes() {
assert_eq!(
segment_snapshot(":rocket::pushpin:", 0),
vec![
("🚀".into(), 0..8, ":rocket:".into(), true),
("📌".into(), 8..17, ":pushpin:".into(), true),
]
);
}
#[test]
fn emoji_segments_preserve_unknown_empty_and_unterminated_candidates() {
for text in [
":not_a_gemoji:",
"::",
"prefix :pushpin",
"12:30",
"https://x:y",
] {
assert_eq!(
segment_snapshot(text, 7),
vec![(text.into(), 7..7 + text.len(), text.into(), false)]
);
}
}
#[test]
fn emoji_segments_continue_after_unknown_candidates() {
assert_eq!(
segment_snapshot(":unknown: then :rocket:", 4),
vec![
(
":unknown: then ".into(),
4..19,
":unknown: then ".into(),
false
),
("🚀".into(), 19..27, ":rocket:".into(), true),
]
);
}
#[test]
fn emoji_segments_are_utf8_safe_before_and_after_shortcode() {
assert_eq!(
segment_snapshot("é:pushpin:界", 10),
vec![
("é".into(), 10..12, "é".into(), false),
("📌".into(), 12..21, ":pushpin:".into(), true),
("界".into(), 21..24, "界".into(), false),
]
);
}
#[test]
fn emoji_segments_refuse_non_identity_source_mapping() {
let mut snapshots = Vec::new();
visit_emoji_text_segments("📌", &(10..19), |segment| {
snapshots.push((
segment.rendered.to_owned(),
segment.source_range,
segment.raw.to_owned(),
segment.replaced,
));
});
assert_eq!(snapshots, vec![("📌".into(), 10..19, "📌".into(), false)]);
}
#[test]
fn replacement_highlight_is_indivisible_for_any_source_overlap() {
let source = 22..31;
assert_eq!(
highlight_for_source_span(&source, &[25..26], None),
HighlightKind::Match
);
assert_eq!(
highlight_for_source_span(&source, &[0..100], None),
HighlightKind::Match
);
}
#[test]
fn active_overlap_wins_over_regular_match() {
assert_eq!(
highlight_for_source_span(&(22..31), &[22..31], Some(&(24..25))),
HighlightKind::Active
);
}
#[test]
fn disjoint_source_ranges_do_not_highlight_replacement() {
assert_eq!(
highlight_for_source_span(&(22..31), &[0..22, 31..40], None),
HighlightKind::None
);
}
#[test]
fn emoji_expansion_eligibility_excludes_images_and_code_blocks() {
assert!(emoji_expansion_is_eligible(false, false));
assert!(!emoji_expansion_is_eligible(true, false));
assert!(!emoji_expansion_is_eligible(false, true));
assert!(!emoji_expansion_is_eligible(true, true));
}
#[test]
fn eligible_markdown_text_and_link_labels_expand() {
let markdown = "Paragraph :pushpin: *:rocket:* [:pushpin:](https://e/:rocket:)";
assert_eq!(expanded_visible_text(markdown), "Paragraph 📌 🚀 📌");
}
#[test]
fn production_inline_code_stays_literal_and_keeps_source_highlighting() {
// Drive the production Event::Code branch and inspect its heading accumulator output.
egui::__run_test_ui(|ui| {
let markdown = "`:pushpin:`";
let mut renderer = CommonMarkViewerInternal::new();
let mut cache = CommonMarkCache::default();
cache.set_search_ranges(std::iter::once(1..10).collect());
cache.set_active_search_range(Some(1..10));
renderer.text_style.heading = Some(1);
renderer.event(
ui,
Event::Code(":pushpin:".into()),
0..markdown.len(),
&mut cache,
&CommonMarkOptions::default(),
540.0,
);
assert_eq!(renderer.current_heading_rich_texts.len(), 1);
assert_eq!(renderer.current_heading_rich_texts[0].text(), ":pushpin:");
assert_eq!(renderer.current_heading_text, ":pushpin:");
assert!(
cache.active_search_y().is_some(),
"inline-code active search range was not recorded"
);
});
}
#[test]
fn production_heading_accumulates_emoji_display_and_raw_shortcode_identity() {
// Drive production Event::Text while heading mode is active.
egui::__run_test_ui(|ui| {
let mut renderer = CommonMarkViewerInternal::new();
let mut cache = CommonMarkCache::default();
renderer.text_style.heading = Some(1);
renderer.event(
ui,
Event::Text("Pin :pushpin:".into()),
3..16,
&mut cache,
&CommonMarkOptions::default(),
540.0,
);
let display: String = renderer
.current_heading_rich_texts
.iter()
.map(|text| text.text())
.collect();
assert_eq!(display, "Pin 📌");
assert_eq!(renderer.current_heading_text, "Pin :pushpin:");
});
}
#[test]
fn production_duplicate_shortcode_headings_use_raw_occurrence_keys() {
// Run complete heading start/text/end production events twice against one cache.
egui::__run_test_ui(|ui| {
let mut renderer = CommonMarkViewerInternal::new();
let mut cache = CommonMarkCache::default();
let options = CommonMarkOptions::default();
for _ in 0..2 {
renderer.start_tag(
ui,
Tag::Heading {
level: HeadingLevel::H2,
id: None,
classes: Vec::new(),
attrs: Vec::new(),
},
&options,
);
renderer.event(
ui,
Event::Text("Pin :pushpin:".into()),
3..16,
&mut cache,
&options,
540.0,
);
renderer.end_tag(
ui,
pulldown_cmark::TagEnd::Heading(HeadingLevel::H2),
&mut cache,
&options,
540.0,
);
}
assert!(cache.get_header_position("pin :pushpin:").is_some());
assert!(cache.get_header_position("pin :pushpin:#1").is_some());
assert!(cache.get_header_position("pin 📌").is_none());
assert!(cache.get_header_position("pin 📌#1").is_none());
});
}
#[test]
fn inline_fenced_and_indented_code_remain_literal() {
let markdown = "`:pushpin:`\n\n```text\n:rocket:\n```\n\n :pushpin:\n";
assert_eq!(
expanded_visible_text(markdown),
":pushpin::rocket:\n:pushpin:\n"
);
}
#[test]
fn image_alt_text_and_url_remain_literal() {
let markdown = "";
assert_eq!(expanded_visible_text(markdown), ":pushpin:");
}
}