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
//! Markdown rendering for gpuikit
//!
//! This crate provides markdown parsing and rendering using GPUI elements.
//! It supports CommonMark and GitHub Flavored Markdown.
//!
//! # Example
//!
//! ```ignore
//! use gpuikit_markdown::{markdown, MarkdownStyle};
//!
//! // Simple usage - create markdown element inline
//! div().child(markdown("# Hello\n\nThis is **bold** text.", cx))
//!
//! // With custom style
//! div().child(
//! markdown("# Hello", cx)
//! .style(MarkdownStyle::new().code_font("Monaco"))
//! )
//! ```
mod code_highlight;
mod elements;
mod inline_style;
mod parser;
mod selectable_text;
mod selection;
mod stitch;
mod style;
pub use code_highlight::normalize_language;
#[cfg(feature = "editor")]
pub use code_highlight::{
code_highlight_themes, init_code_highlighting, set_code_highlight_theme, CodeHighlightTheme,
DEFAULT_DARK_THEME, DEFAULT_LIGHT_THEME,
};
pub use elements::*;
pub use inline_style::*;
pub use parser::*;
pub use selectable_text::{RunRole, SelectableText};
pub use selection::{MarkdownSelection, SelectionPosition};
pub use stitch::preprocessing_available;
pub use style::*;
use crate::a11y::{A11y, Announce};
use crate::theme::{ActiveTheme, Themeable};
use gpui::{
div, prelude::*, rems, App, Context, ElementId, Entity, EntityId, IntoElement, ParentElement,
Role, SharedString, Styled, Task, Window,
};
use pulldown_cmark::{Alignment, Event, Tag, TagEnd};
/// The id of the element every run of one document hangs under.
///
/// gpui hashes an element's *whole* id path into an accessibility node id and
/// refuses duplicates, so run ids only need to be unique within a document if
/// the document itself is uniquely identified. Keyed on the entity so it is
/// also stable across frames: assistive technology reads a changed node id as
/// a different element.
fn document_element_id(entity_id: EntityId) -> ElementId {
ElementId::NamedInteger("md-doc".into(), entity_id.as_u64())
}
/// The id of one text run, in document order. Only unique underneath a
/// [`document_element_id`].
fn run_element_id(index: usize) -> ElementId {
ElementId::NamedInteger("md-run".into(), index as u64)
}
/// A markdown document that can be rendered as a GPUI element.
///
/// This entity parses and holds markdown content, ready for rendering.
///
/// # Streaming
///
/// Content arriving a piece at a time — an LLM reply, a log tail — goes in
/// through [`append`](Self::append), which extends the source and re-parses on
/// a background thread. The previously parsed events keep rendering until the
/// new parse lands, so the document never blanks, and deltas arriving during a
/// parse coalesce into a single follow-up parse rather than one each.
///
/// ```ignore
/// markdown.update(cx, |markdown, cx| markdown.append(&delta, cx));
/// ```
pub struct Markdown {
source: SharedString,
/// The source the current [`events`](Self::events) were parsed from. Lags
/// [`source`](Self::source) while a parse is in flight.
parsed_source: SharedString,
events: Vec<MarkdownEvent>,
/// Which code block, if any, the parsed source leaves unclosed, as an
/// ordinal among the document's code blocks.
///
/// Published together with [`events`](Self::events) so it can never
/// describe a different parse than the one being rendered.
unclosed_code_block: Option<usize>,
/// Document-wide text selection, shared with every rendered run.
selection: MarkdownSelection,
parse_state: ParseState,
/// Handle to the running parse loop. Held here so that dropping the
/// document cancels a parse in flight.
parse_task: Option<Task<()>>,
preprocess_partial: bool,
}
/// Whether a background parse is running, and whether the source changed again
/// while it ran.
///
/// This pair is the whole coalescing rule: a request that arrives mid-parse
/// sets `dirty` instead of spawning a second parse, and the running loop
/// re-runs once against the newest source when it lands.
enum ParseState {
Idle,
Parsing { dirty: bool },
}
/// One finished parse: the events, and what the source said about the last
/// code block.
///
/// The two travel together on purpose. A flag published separately from the
/// events it describes would, for one frame, describe the previous parse.
struct ParsedDocument {
events: Vec<MarkdownEvent>,
/// The ordinal — among this document's code blocks, in document order —
/// of the block whose fence never closed, if there is one.
///
/// That block is rendered as plain monospace: a fence that is still
/// arriving is a different cache key on every delta, so highlighting it
/// costs a full syntect pass per frame and evicts every settled block's
/// entry. It highlights once, and for good, when its closer lands.
unclosed_code_block: Option<usize>,
}
/// Parsed markdown event with source range information.
#[derive(Clone, Debug)]
pub struct MarkdownEvent {
/// The pulldown-cmark event.
pub event: Event<'static>,
/// Where the event came from in the text handed to the parser.
///
/// With [partial-syntax preprocessing](Markdown::preprocess_partial) on
/// and something to close, that text is the *preprocessed* source, so
/// offsets past the first insertion do not line up with
/// [`Markdown::source`]. Rendering does not read this field.
pub source_range: std::ops::Range<usize>,
}
impl Markdown {
/// Create a new Markdown instance from source text.
///
/// This first parse is synchronous, so a document is never empty on its
/// first frame; later ones go to a background thread.
pub fn new(source: impl Into<SharedString>, _cx: &mut Context<Self>) -> Self {
let source: SharedString = source.into();
let preprocess_partial = true;
let parsed = Self::parse(&source, preprocess_partial);
Self {
parsed_source: source.clone(),
source,
events: parsed.events,
unclosed_code_block: parsed.unclosed_code_block,
selection: MarkdownSelection::new(),
parse_state: ParseState::Idle,
parse_task: None,
preprocess_partial,
}
}
/// Get the source text.
///
/// While a parse is in flight this is ahead of what is rendered — see
/// [`parsed_source`](Self::parsed_source).
pub fn source(&self) -> &str {
&self.source
}
/// The source the currently rendered events came from.
///
/// Equal to [`source`](Self::source) once the latest parse has landed.
pub fn parsed_source(&self) -> &str {
&self.parsed_source
}
/// Update the markdown content. Drops any selection — its positions
/// belong to the old text.
///
/// The re-parse happens on a background thread: the previous events keep
/// rendering until it lands, so [`events`](Self::events) still reports the
/// old parse when read in the same turn. Setting the source it already has
/// does nothing at all.
pub fn set_source(&mut self, source: impl Into<SharedString>, cx: &mut Context<Self>) {
let source = source.into();
if source == self.source {
return;
}
self.source = source;
self.selection.clear();
self.request_parse(cx);
}
/// Append to the markdown content — one delta of a streaming document.
///
/// Unlike [`set_source`](Self::set_source) this keeps the selection: a
/// selection is a pair of `(run, byte offset)` positions, so text arriving
/// at the end of the document cannot disturb one made earlier in it.
///
/// Appending nothing does nothing.
pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {
if text.is_empty() {
return;
}
let mut source = String::with_capacity(self.source.len() + text.len());
source.push_str(&self.source);
source.push_str(text);
self.source = source.into();
self.request_parse(cx);
}
/// Whether a background parse is in flight — i.e. whether what is rendered
/// is still one source behind.
pub fn is_parsing(&self) -> bool {
matches!(self.parse_state, ParseState::Parsing { .. })
}
/// Whether syntax a partial document leaves open is closed before parsing.
/// On by default, and inert unless the crate was built with the `stitch`
/// feature — see [`preprocessing_available`].
pub fn preprocess_partial(&self) -> bool {
self.preprocess_partial
}
/// Turn [partial-syntax preprocessing](Self::preprocess_partial) on or
/// off. Re-parses the current source unless nothing changed.
pub fn set_preprocess_partial(&mut self, preprocess_partial: bool, cx: &mut Context<Self>) {
if self.preprocess_partial == preprocess_partial {
return;
}
self.preprocess_partial = preprocess_partial;
self.request_parse(cx);
}
/// The document's selection handle — for clearing it from outside (e.g.
/// when another document in the same view starts a selection).
pub fn selection(&self) -> MarkdownSelection {
self.selection.clone()
}
/// The currently selected text, if any — what ⌘C should copy. Routing
/// the copy binding is the embedding app's job; this is the value.
pub fn selected_text(&self) -> Option<String> {
self.selection.selected_text()
}
/// Re-parse the current source in the background.
///
/// While a parse is running this only marks the document dirty — the
/// running loop picks the newest source up when it lands. Ten deltas
/// during one parse therefore cost one extra parse, not ten.
fn request_parse(&mut self, cx: &mut Context<Self>) {
if let ParseState::Parsing { dirty } = &mut self.parse_state {
*dirty = true;
return;
}
self.parse_state = ParseState::Parsing { dirty: false };
let mut pending = (self.source.clone(), self.preprocess_partial);
// One task looping, rather than a task that re-spawns itself: the
// handle lives on the entity, so a task assigning `parse_task` from
// inside itself would drop the very task doing the assigning.
self.parse_task = Some(cx.spawn(async move |this, cx| {
loop {
let (source, preprocess_partial) = pending;
let parse = {
let source = source.clone();
cx.background_executor()
.spawn(async move { Self::parse(&source, preprocess_partial) })
};
let parsed = parse.await;
match this.update(cx, |this, cx| this.parse_landed(source, parsed, cx)) {
Ok(Some(next)) => pending = next,
// Nothing more to parse, or the document is gone.
Ok(None) | Err(_) => break,
}
}
}));
}
/// Publish a finished parse and decide whether to run another.
///
/// Publishing and deciding happen in this one update, so a delta arriving
/// around it cannot be lost: it either set `dirty` before this ran and is
/// picked up here, or it lands afterwards, finds [`ParseState::Idle`], and
/// starts a parse of its own.
fn parse_landed(
&mut self,
parsed_source: SharedString,
parsed: ParsedDocument,
cx: &mut Context<Self>,
) -> Option<(SharedString, bool)> {
self.events = parsed.events;
self.unclosed_code_block = parsed.unclosed_code_block;
self.parsed_source = parsed_source;
cx.notify();
match self.parse_state {
ParseState::Parsing { dirty: true } => {
self.parse_state = ParseState::Parsing { dirty: false };
Some((self.source.clone(), self.preprocess_partial))
}
_ => {
self.parse_state = ParseState::Idle;
None
}
}
}
fn parse(source: &str, preprocess_partial: bool) -> ParsedDocument {
// Asked of the *raw* source, before preprocessing: `close_open_syntax`
// rewrites inline markers and its output is what the events describe,
// but a fence is a property of the text the caller actually appended
// to. (mdstitch closes no fences, so the two agree here regardless —
// asking the raw source is what keeps that true if it ever starts to.)
let fence_open = parser::has_open_code_fence(source);
let source = if preprocess_partial {
stitch::close_open_syntax(source)
} else {
std::borrow::Cow::Borrowed(source)
};
let parser = Parser::new_ext(&source, parser::default_options());
let events: Vec<MarkdownEvent> = parser
.into_offset_iter()
.map(|(event, range)| MarkdownEvent {
event: event.into_static(),
source_range: range,
})
.collect();
// The ordinal comes from the events rather than from the scan, so the
// two can never point at a block the renderer will not reach. A scan
// saying "open" with no code block in the events yields `None`.
let unclosed_code_block = if fence_open {
events
.iter()
.filter(|event| matches!(event.event, Event::Start(Tag::CodeBlock(_))))
.count()
.checked_sub(1)
} else {
None
};
ParsedDocument {
events,
unclosed_code_block,
}
}
/// Get the parsed events.
///
/// These are the events of [`parsed_source`](Self::parsed_source), which
/// is one source behind while a parse is in flight.
pub fn events(&self) -> &[MarkdownEvent] {
&self.events
}
}
/// Element for rendering markdown content.
#[derive(IntoElement)]
pub struct MarkdownElement {
markdown: Entity<Markdown>,
style: MarkdownStyle,
element_id: Option<ElementId>,
}
/// Create a markdown element from source text.
///
/// This is a convenience function that creates the entity and element in one step.
/// For more control, use `Markdown::new()` and `MarkdownElement::new()` separately.
///
/// Note that this mints a *new* entity on every call. Called from a `render`,
/// the document gets a new element id every frame, which a screen reader reads
/// as the whole document being replaced. Hold an `Entity<Markdown>` — which
/// text selection needs anyway — for anything longer-lived than a one-shot.
pub fn markdown(source: impl Into<SharedString>, cx: &mut App) -> MarkdownElement {
let entity = cx.new(|cx| Markdown::new(source, cx));
MarkdownElement::new(entity)
}
impl MarkdownElement {
/// Create a new markdown element with default styling.
pub fn new(markdown: Entity<Markdown>) -> Self {
Self {
markdown,
style: MarkdownStyle::default(),
element_id: None,
}
}
/// Set a custom style for the markdown.
pub fn style(mut self, style: MarkdownStyle) -> Self {
self.style = style;
self
}
/// Override the element id the document — and therefore all of its text
/// runs — is scoped under.
///
/// The default is derived from the `Markdown` entity, which is unique and
/// stable already. Set this only when the same entity is rendered more
/// than once in a frame; each copy then needs its own id. (Note that two
/// live copies of one entity still share a single selection.)
pub fn id(mut self, id: impl Into<ElementId>) -> Self {
self.element_id = Some(id.into());
self
}
/// The id this element renders under — the explicit [`Self::id`] if one
/// was given, otherwise the entity-derived default.
pub fn element_id(&self) -> ElementId {
self.element_id
.clone()
.unwrap_or_else(|| document_element_id(self.markdown.entity_id()))
}
}
impl RenderOnce for MarkdownElement {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let document_id = self.element_id();
let markdown = self.markdown.read(cx);
let events = markdown.events.clone();
let unclosed_code_block = markdown.unclosed_code_block;
let selection = markdown.selection.clone();
let style = self.style.clone();
// New frame: the previous frame's run layouts are about to be
// dropped and must not be hit-tested.
selection.begin_frame();
let renderer = MarkdownRenderer::new(style, selection, unclosed_code_block);
renderer.render_events(&events, document_id, cx)
}
}
/// Internal renderer that builds the element tree from markdown events.
struct MarkdownRenderer {
style: MarkdownStyle,
elements: Vec<gpui::AnyElement>,
// State tracking
in_heading: Option<HeadingLevel>,
in_code_block: bool,
/// The language token of the fence currently open, normalized from its
/// info string. `None` for an indented block or a bare fence.
code_block_language: Option<String>,
/// The ordinal of the code block the source leaves unclosed, if any —
/// see [`ParsedDocument::unclosed_code_block`].
unclosed_code_block: Option<usize>,
/// How many code blocks this renderer has opened. Counted here rather than
/// taken from the parse so that the ordinal is compared against the blocks
/// actually being drawn.
code_blocks_seen: usize,
/// Whether the block currently open is that unclosed one, i.e. whether it
/// draws plain.
code_block_is_unclosed: bool,
in_block_quote: bool,
in_image: Option<ImageContext>,
list_stack: Vec<ListContext>,
/// Document-order index for selectable text runs. A run's index is its
/// element id, its selection identity and its slot in the per-frame
/// registry all at once, so there is only ever one counter to keep in
/// step.
run_counter: usize,
/// Shared selection state, handed to every run.
selection: MarkdownSelection,
// Table state
in_table: bool,
table_alignments: Vec<Alignment>,
table_rows: Vec<Vec<RichText>>,
current_row: Vec<RichText>,
in_table_head: bool,
// Rich text tracking
current_text: RichText,
active_style: InlineStyle,
/// Every list row this renderer emitted, in document order.
///
/// A rendered element only reports its height, which cannot say which
/// marker a row got, what it was indented by, or which row a piece of text
/// landed in — exactly what nesting scrambles.
#[cfg(test)]
emitted_list_items: Vec<ListRow>,
/// The language every code block was flushed with, in document order.
///
/// A drawn element reports its height, not its colors, so this is how the
/// tests read the plain-versus-highlighted decision. Mirrors
/// [`Self::emitted_list_items`].
#[cfg(test)]
emitted_code_blocks: Vec<Option<String>>,
}
/// One row `flush_list_item` emitted, as the tests read it.
#[cfg(test)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct ListRow {
marker: elements::ItemMarker,
indent_level: usize,
text: String,
}
#[derive(Clone, Debug)]
struct ImageContext {
url: String,
alt: String,
}
#[derive(Clone, Debug)]
struct ListContext {
ordered: bool,
current_index: u64,
/// The item of *this* list that is currently open, if any. Only the
/// innermost list may be asked: a nested list opens while its parent's
/// item is still open, so a child's blocks would otherwise be attributed
/// to the parent's item.
item: Option<ItemContext>,
}
/// One open list item.
#[derive(Clone, Debug, Default)]
struct ItemContext {
/// The marker this item's first block drew, once it has drawn one. Every
/// later block of the same item reserves the width of this same marker
/// without painting it, so their text lines up under the first block's.
marker: Option<String>,
}
impl MarkdownRenderer {
fn new(
style: MarkdownStyle,
selection: MarkdownSelection,
unclosed_code_block: Option<usize>,
) -> Self {
Self {
style,
selection,
elements: Vec::new(),
in_heading: None,
in_code_block: false,
code_block_language: None,
unclosed_code_block,
code_blocks_seen: 0,
code_block_is_unclosed: false,
in_block_quote: false,
in_image: None,
list_stack: Vec::new(),
run_counter: 0,
in_table: false,
table_alignments: Vec::new(),
table_rows: Vec::new(),
current_row: Vec::new(),
in_table_head: false,
current_text: RichText::new(),
active_style: InlineStyle::default(),
#[cfg(test)]
emitted_list_items: Vec::new(),
#[cfg(test)]
emitted_code_blocks: Vec::new(),
}
}
fn render_events(
mut self,
events: &[MarkdownEvent],
document_id: ElementId,
cx: &App,
) -> impl IntoElement {
for event in events {
self.handle_event(&event.event, cx);
}
// The id is what scopes the run ids below it; the role is what puts
// the document into the accessibility tree. `.announce()` is only
// reachable on a div that already has an `.id()`, so the two cannot
// drift apart. A bare `.id()` adds no hitbox, so selection
// hit-testing and link clicks are untouched. A document is named by
// its contents, so it takes no accessible name — see
// `crate::a11y::role_requires_a_name`.
div()
.id(document_id)
.announce(A11y::new(Role::Document))
.w_full()
.flex()
.flex_col()
.gap(rems(self.style.block_spacing))
.children(self.elements)
}
fn handle_event(&mut self, event: &Event<'static>, cx: &App) {
match event {
Event::Start(tag) => self.handle_start_tag(tag, cx),
Event::End(tag) => self.handle_end_tag(tag, cx),
Event::Text(text) => self.handle_text(text),
Event::Code(code) => self.handle_inline_code(code),
// Agent/LLM output often uses single newlines as real breaks;
// `soft_break_as_hard_break` opts into honoring them.
Event::SoftBreak => {
if self.style.soft_break_as_hard_break {
self.current_text.push("\n", self.active_style)
} else {
self.current_text.push(" ", self.active_style)
}
}
Event::HardBreak => self.current_text.push("\n", self.active_style),
Event::Rule => self.push_divider(cx),
Event::TaskListMarker(checked) => self.handle_task_marker(*checked),
Event::Html(_) | Event::InlineHtml(_) => {}
Event::FootnoteReference(_) | Event::InlineMath(_) | Event::DisplayMath(_) => {}
}
}
/// Takes `cx` because a nested list flushes its parent's item, and
/// flushing builds an element.
fn handle_start_tag(&mut self, tag: &Tag<'static>, cx: &App) {
match tag {
Tag::Paragraph => {}
Tag::Heading { level, .. } => {
self.in_heading = Some((*level).into());
}
Tag::BlockQuote(_) => {
self.in_block_quote = true;
}
Tag::CodeBlock(kind) => {
self.in_code_block = true;
// Compared before the increment, so the flag is set on the
// block whose ordinal this is rather than on the next one.
self.code_block_is_unclosed =
self.unclosed_code_block == Some(self.code_blocks_seen);
self.code_blocks_seen += 1;
self.code_block_language =
parser::code_block_language(kind).and_then(code_highlight::normalize_language);
}
Tag::List(start) => {
// A list nested under an item opens *before* that item ends,
// so the parent's text is still buffered here. Left there, the
// first child item's flush would pick it up and emit both as
// one row, and the parent's own `End(Item)` would then find an
// empty buffer and emit nothing.
//
// Flushed before the push, so the parent's row gets its own
// indent, its own marker and — for an ordered list — its own
// ordinal rather than the child's first one. Guarded on a
// non-empty stack because a top-level list has no parent item
// to attribute a row to.
if !self.list_stack.is_empty() {
self.flush_list_item(cx);
}
self.list_stack.push(ListContext {
ordered: start.is_some(),
current_index: start.unwrap_or(1),
item: None,
});
}
Tag::Item => {
// Opened on the innermost list, which is the one this item
// belongs to. A loose item's blocks each end with
// `End(Paragraph)`, and this is what tells that ending it is
// inside an item rather than in body text.
if let Some(list_ctx) = self.list_stack.last_mut() {
list_ctx.item = Some(ItemContext::default());
}
}
Tag::Emphasis => {
self.active_style.italic = true;
}
Tag::Strong => {
self.active_style.bold = true;
}
Tag::Strikethrough => {
self.active_style.strikethrough = true;
}
Tag::Link { dest_url, .. } => {
// Inline: the link is a styled, clickable range of the
// surrounding text run, not its own block element.
self.active_style.link = Some(self.current_text.add_link(dest_url.to_string()));
}
Tag::Image {
dest_url, title, ..
} => {
self.in_image = Some(ImageContext {
url: dest_url.to_string(),
alt: title.to_string(),
});
}
Tag::Table(alignments) => {
self.in_table = true;
self.table_alignments = alignments.clone();
self.table_rows.clear();
}
Tag::TableHead => {
self.in_table_head = true;
self.current_row.clear();
}
Tag::TableRow => {
self.current_row.clear();
}
Tag::TableCell => {
self.current_text.clear();
}
// Listed rather than folded into a `_ => {}` wildcard on purpose:
// an exhaustive match is what turns a pulldown-cmark upgrade into a
// compile error instead of silently dropped styling.
//
// Superscript and Subscript are inert because the options that
// produce them are off (see `parser::default_options`) *and*
// because `InlineStyle` has nowhere to put them.
Tag::FootnoteDefinition(_)
| Tag::MetadataBlock(_)
| Tag::DefinitionList
| Tag::DefinitionListTitle
| Tag::DefinitionListDefinition
| Tag::Superscript
| Tag::Subscript
| Tag::HtmlBlock => {}
}
}
fn handle_end_tag(&mut self, tag: &TagEnd, cx: &App) {
match tag {
TagEnd::Paragraph => {
if self.in_block_quote {
self.flush_block_quote(cx);
} else if self.in_list_item() {
// A loose list wraps each item's content in a paragraph.
// Flushed as body text it would lose its marker, its
// indent and its number, and the item's `End(Item)` would
// then find an empty buffer and emit nothing at all.
self.flush_list_item(cx);
} else {
self.flush_paragraph(cx);
}
}
TagEnd::Heading(level) => {
let heading_level: elements::HeadingLevel = (*level).into();
self.in_heading = None;
self.flush_heading(heading_level, cx);
}
TagEnd::BlockQuote(_) => {
self.in_block_quote = false;
}
TagEnd::CodeBlock => {
self.in_code_block = false;
self.flush_code_block(cx);
}
TagEnd::List(_) => {
self.list_stack.pop();
}
TagEnd::Item => {
// Flushed *before* the item closes: a tight item's text is
// still buffered here, and closing first would leave it with
// no item to take its marker from.
self.flush_list_item(cx);
if let Some(list_ctx) = self.list_stack.last_mut() {
list_ctx.item = None;
}
}
TagEnd::Emphasis => {
self.active_style.italic = false;
}
TagEnd::Strong => {
self.active_style.bold = false;
}
TagEnd::Strikethrough => {
self.active_style.strikethrough = false;
}
TagEnd::Link => {
self.active_style.link = None;
}
TagEnd::Image => {
self.flush_image(cx);
}
TagEnd::Table => {
self.flush_table(cx);
self.in_table = false;
}
TagEnd::TableHead => {
self.in_table_head = false;
if !self.current_row.is_empty() {
self.table_rows.push(std::mem::take(&mut self.current_row));
}
}
TagEnd::TableRow => {
if !self.current_row.is_empty() {
self.table_rows.push(std::mem::take(&mut self.current_row));
}
}
TagEnd::TableCell => {
self.current_row
.push(std::mem::take(&mut self.current_text));
}
TagEnd::FootnoteDefinition
| TagEnd::MetadataBlock(_)
| TagEnd::DefinitionList
| TagEnd::DefinitionListTitle
| TagEnd::DefinitionListDefinition
| TagEnd::Superscript
| TagEnd::Subscript
| TagEnd::HtmlBlock => {}
}
}
fn handle_text(&mut self, text: &str) {
if let Some(ref mut img_ctx) = self.in_image {
img_ctx.alt = text.to_string();
} else {
self.current_text.push(text, self.active_style);
}
}
fn handle_inline_code(&mut self, code: &str) {
// A styled span (background wash via the palette), not literal
// backticks in the text.
let mut style = self.active_style;
style.code = true;
self.current_text.push(code, style);
}
fn handle_task_marker(&mut self, checked: bool) {
let marker = if checked { "☑ " } else { "☐ " };
self.current_text.push(marker, self.active_style);
}
/// Theme-resolved colors for inline code and link spans.
fn palette(&self, cx: &App) -> InlinePalette {
let theme = cx.theme();
InlinePalette {
code_background: Some(self.style.inline_code_bg.unwrap_or(theme.surface())),
link_color: Some(self.style.link_color.unwrap_or(theme.accent())),
}
}
/// Id and selection context for the next text run, in document order.
/// The counter must tick once per selectable run and nowhere else — it
/// is the identity the element id, the per-frame registry and the
/// highlights all agree on.
fn next_run(&mut self, cx: &App) -> (ElementId, elements::RunContext) {
let run = self.run_counter;
self.run_counter += 1;
let theme = cx.theme();
let run_cx = elements::RunContext {
selection: self.selection.clone(),
run,
selection_background: self
.style
.selection_background
.unwrap_or_else(|| theme.accent().opacity(0.25)),
};
(run_element_id(run), run_cx)
}
fn flush_paragraph(&mut self, cx: &App) {
if self.current_text.is_empty() {
return;
}
let rich_text = std::mem::take(&mut self.current_text);
let palette = self.palette(cx);
let (id, run_cx) = self.next_run(cx);
let element =
elements::rich_paragraph(id, &rich_text, &self.style.body, &palette, run_cx, cx);
self.elements.push(element.into_any_element());
}
fn flush_heading(&mut self, level: HeadingLevel, cx: &App) {
if self.current_text.is_empty() {
return;
}
let rich_text = std::mem::take(&mut self.current_text);
let heading_style = match level {
elements::HeadingLevel::H1 => &self.style.h1,
elements::HeadingLevel::H2 => &self.style.h2,
elements::HeadingLevel::H3 => &self.style.h3,
elements::HeadingLevel::H4 => &self.style.h4,
elements::HeadingLevel::H5 => &self.style.h5,
elements::HeadingLevel::H6 => &self.style.h6,
}
.clone();
let palette = self.palette(cx);
let (id, run_cx) = self.next_run(cx);
let element =
elements::rich_heading(id, &rich_text, level, &heading_style, &palette, run_cx, cx);
self.elements.push(element.into_any_element());
}
fn flush_block_quote(&mut self, cx: &App) {
if self.current_text.is_empty() {
return;
}
let rich_text = std::mem::take(&mut self.current_text);
let palette = self.palette(cx);
let (id, run_cx) = self.next_run(cx);
let element = elements::rich_block_quote(
id,
&rich_text,
&self.style.body,
self.style.block_quote_border,
self.style.block_quote_text,
&palette,
run_cx,
cx,
);
self.elements.push(element.into_any_element());
}
fn flush_code_block(&mut self, cx: &App) {
// Both taken before the early return: an empty fence still closes, and
// neither its language nor its unclosed-ness must leak into the next
// block.
//
// A block whose fence has not closed yet is drawn with no language,
// which is the path a bare fence already takes: no syntect pass, and
// no cache entry for text that is about to change. It highlights once
// its closer arrives.
let is_unclosed = std::mem::take(&mut self.code_block_is_unclosed);
let language = self.code_block_language.take().filter(|_| !is_unclosed);
#[cfg(test)]
self.emitted_code_blocks.push(language.clone());
if self.current_text.is_empty() {
return;
}
let text = self.current_text.to_plain_text();
self.current_text.clear();
let (id, run_cx) = self.next_run(cx);
let element = elements::code_block(
id,
text,
language.as_deref(),
&self.style.code,
&self.style.code_font_family,
self.style.code_block_bg,
self.style.code_block_border,
run_cx,
cx,
);
self.elements.push(element.into_any_element());
}
/// Whether the innermost list has an item open — i.e. whether a block
/// ending right now is one of that item's blocks.
///
/// Only the innermost is asked. A nested list opens while its parent's
/// item is still open, so "any item on the stack" would route a child's
/// blocks against the parent's context.
fn in_list_item(&self) -> bool {
self.list_stack
.last()
.is_some_and(|list_ctx| list_ctx.item.is_some())
}
/// The marker the row about to be emitted draws.
///
/// An item's first block takes the list's next ordinal and remembers what
/// it drew; every later block of the same item redraws that marker
/// hidden, advancing nothing — an ordinal belongs to an item, not to a
/// flush, so `1. a` with a second paragraph must not leave the next item
/// at `3.`.
fn take_item_marker(&mut self) -> elements::ItemMarker {
let Some(list_ctx) = self.list_stack.last_mut() else {
return elements::ItemMarker::Shown(elements::unordered_marker());
};
if let Some(marker) = list_ctx.item.as_ref().and_then(|item| item.marker.clone()) {
return elements::ItemMarker::Hidden(marker);
}
let marker = if list_ctx.ordered {
let marker = elements::ordered_marker(list_ctx.current_index);
list_ctx.current_index += 1;
marker
} else {
elements::unordered_marker()
};
if let Some(item) = list_ctx.item.as_mut() {
item.marker = Some(marker.clone());
}
elements::ItemMarker::Shown(marker)
}
fn flush_list_item(&mut self, cx: &App) {
if self.current_text.is_empty() {
return;
}
let rich_text = std::mem::take(&mut self.current_text);
let marker = self.take_item_marker();
let indent_level = self.list_stack.len().saturating_sub(1);
#[cfg(test)]
self.emitted_list_items.push(ListRow {
marker: marker.clone(),
indent_level,
text: rich_text.to_plain_text(),
});
let palette = self.palette(cx);
let (id, run_cx) = self.next_run(cx);
let element = elements::rich_list_item(
id,
&rich_text,
marker,
indent_level,
&self.style.body,
&palette,
run_cx,
cx,
);
self.elements.push(element.into_any_element());
}
fn flush_image(&mut self, cx: &App) {
let img_ctx = match self.in_image.take() {
Some(ctx) => ctx,
None => return,
};
self.current_text.clear();
let alt = if img_ctx.alt.is_empty() {
None
} else {
Some(img_ctx.alt.as_str())
};
let element = elements::image(img_ctx.url, alt, cx);
self.elements.push(element.into_any_element());
}
fn flush_table(&mut self, cx: &App) {
if self.table_rows.is_empty() {
return;
}
let rows = std::mem::take(&mut self.table_rows);
let alignments = std::mem::take(&mut self.table_alignments);
let element = self.render_table(rows, alignments, cx);
self.elements.push(element.into_any_element());
}
fn render_table(
&self,
rows: Vec<Vec<RichText>>,
alignments: Vec<Alignment>,
cx: &App,
) -> impl IntoElement {
let theme = cx.theme();
let border_color = theme.border();
div()
.flex()
.flex_col()
.border_1()
.border_color(border_color)
.rounded_sm()
.overflow_hidden()
.children(rows.into_iter().enumerate().map(|(row_idx, row)| {
let is_header = row_idx == 0;
let bg = if is_header {
theme.surface()
} else if row_idx % 2 == 0 {
theme.bg()
} else {
theme.surface().opacity(0.5)
};
div()
.flex()
.flex_row()
.bg(bg)
.when(row_idx > 0, |el| el.border_t_1().border_color(border_color))
.children(row.into_iter().enumerate().map(|(col_idx, cell)| {
let alignment = alignments.get(col_idx).copied().unwrap_or(Alignment::None);
// Styled (code wash, link color) but not clickable —
// cells sit in a custom layout without element ids.
let (text, highlights) = cell.to_highlights_with(&self.palette(cx));
let styled_text: SharedString = text.into();
div()
.flex_1()
// Same shape as a list item: without `min_w_0` the
// cell can't shrink below one unbroken line.
.min_w_0()
.px_2()
.py_1()
.text_size(rems(self.style.body.size))
.when(col_idx > 0, |el| el.border_l_1().border_color(border_color))
.when(is_header, |el| el.font_weight(gpui::FontWeight::SEMIBOLD))
.map(|el| match alignment {
Alignment::Left | Alignment::None => el,
Alignment::Center => el.text_center(),
Alignment::Right => el.text_right(),
})
.child(gpui::StyledText::new(styled_text).with_highlights(highlights))
}))
}))
}
fn push_divider(&mut self, cx: &App) {
let element = elements::divider(self.style.rule_color, cx);
self.elements.push(element.into_any_element());
}
}
#[cfg(test)]
mod tests {
use super::selectable_text::recorder::{self, RecordedRun};
use super::*;
use gpui::{point, px, size, AnyElement, Pixels, Render, TestAppContext, VisualTestContext};
use std::cell::Cell;
use std::collections::HashSet;
use std::rc::Rc;
/// Narrow enough that every sample text below has to wrap.
const WIDTH: Pixels = px(240.);
/// Long enough to take several lines at that width — and exactly one line
/// if whatever contains it refuses to wrap.
const LONG: &str = "This one is deliberately long enough that it has to wrap onto several lines inside a narrow container.";
struct TestView {
source: SharedString,
}
impl Render for TestView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// The root element is stretched to the window, so the div we
// measure has to be a child of it — inside a column it keeps its
// content height, which is the signal these tests read.
div().flex().flex_col().child(
div()
.w(WIDTH)
.debug_selector(|| "measured".into())
.child(markdown(self.source.clone(), cx)),
)
}
}
/// Render `source` into a [`WIDTH`]-wide container and report how tall it
/// got. Text that will not wrap stays one line tall however long it is.
fn height(cx: &mut TestAppContext, source: &str) -> Pixels {
cx.update(crate::theme::init);
let source = SharedString::from(source.to_string());
let (_view, cx) = cx.add_window_view(move |_window, _cx| TestView { source });
cx.debug_bounds("measured")
.expect("the measured container was never drawn")
.size
.height
}
/// The height of a single line of body text.
fn line(cx: &mut TestAppContext) -> Pixels {
height(cx, "x")
}
/// A list item's text column is narrower than a paragraph's by the marker
/// and the gap (and, when nested, the indent), so it is allowed to take a
/// couple of lines more than the same text set as a paragraph.
#[track_caller]
fn assert_wrapped_like_a_paragraph(item: Pixels, paragraph: Pixels, line: Pixels) {
assert!(
paragraph > line,
"the baseline paragraph did not wrap ({paragraph:?}), so this measures nothing"
);
assert!(
item > line,
"the text stayed on one line ({item:?}) instead of wrapping"
);
assert!(
item <= paragraph + line * 2.,
"{item:?} is much taller than the same text as a paragraph ({paragraph:?})"
);
}
/// One of every kind of run this renderer emits, in this order: heading,
/// paragraph, quote, list item, code.
const EVERY_RUN_KIND: &str = concat!(
"# Title\n",
"\n",
"A paragraph.\n",
"\n",
"> A quote.\n",
"\n",
"- An item\n",
"\n",
"```\n",
"let x = 1;\n",
"```\n",
);
/// Draw one frame of whatever `build` produces, and report every run the
/// way gpui's accessibility walk would have seen it.
fn draw(
cx: &mut VisualTestContext,
build: impl FnOnce() -> Vec<MarkdownElement>,
) -> Vec<RecordedRun> {
recorder::clear();
cx.draw(
point(px(0.), px(0.)),
size(px(800.), px(600.)),
|_window, _cx| -> AnyElement { div().children(build()).into_any_element() },
);
recorder::take()
}
/// The last two segments of a run's id path: the document it belongs to,
/// and the run itself.
fn doc_and_run(run: &RecordedRun) -> (&str, &str) {
match run.id_segments.as_slice() {
[.., doc, this] => (doc.as_str(), this.as_str()),
other => panic!("a run's id path should have at least two segments: {other:?}"),
}
}
fn id_paths(runs: &[RecordedRun]) -> Vec<String> {
runs.iter().map(|run| run.id_path.clone()).collect()
}
/// The fence's info string used to be dropped at `Tag::CodeBlock` and a
/// literal `None` passed on to the element, so fixing the code block
/// element alone would have changed nothing.
#[gpui::test]
fn a_fence_carries_its_language_without_leaking_it(cx: &mut TestAppContext) {
use pulldown_cmark::CodeBlockKind;
cx.update(crate::theme::init);
cx.update(|cx| {
let mut renderer =
MarkdownRenderer::new(MarkdownStyle::default(), MarkdownSelection::new(), None);
let fence = |info: &'static str| Tag::CodeBlock(CodeBlockKind::Fenced(info.into()));
renderer.handle_start_tag(&fence("rust,ignore"), cx);
assert_eq!(
renderer.code_block_language.as_deref(),
Some("rust"),
"the info string should reach the renderer, normalized"
);
// An empty fence still closes, and must not hand its language to
// whatever block comes next.
renderer.flush_code_block(cx);
assert_eq!(renderer.code_block_language, None);
for no_language in [
fence(""),
fence("text"),
Tag::CodeBlock(CodeBlockKind::Indented),
] {
renderer.handle_start_tag(&no_language, cx);
assert_eq!(
renderer.code_block_language, None,
"{no_language:?} names no language"
);
}
});
}
#[gpui::test]
fn two_documents_in_one_frame_get_disjoint_run_ids(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let (first, second) = (document(cx, EVERY_RUN_KIND), document(cx, EVERY_RUN_KIND));
let cx = cx.add_empty_window();
let runs = draw(cx, || {
vec![
MarkdownElement::new(first.clone()),
MarkdownElement::new(second.clone()),
]
});
assert_eq!(runs.len(), 10, "five runs per document, twice over");
// The whole point: gpui hashes the *whole* path into a node id, and
// two documents used to mint the same `md-run-N` under the same
// ancestors.
let paths = id_paths(&runs);
let distinct: HashSet<&String> = paths.iter().collect();
assert_eq!(distinct.len(), 10, "colliding id paths: {paths:?}");
let mut documents = HashSet::new();
for run in &runs {
let (doc, this) = doc_and_run(run);
assert!(doc.starts_with("md-doc-"), "unscoped run: {}", run.id_path);
assert!(this.starts_with("md-run-"), "odd run id: {}", run.id_path);
documents.insert(doc.to_string());
}
assert_eq!(
documents.len(),
2,
"two documents, two scopes: {documents:?}"
);
}
#[gpui::test]
fn a_long_unordered_list_item_wraps(cx: &mut TestAppContext) {
let line = line(cx);
let paragraph = height(cx, LONG);
let item = height(cx, &format!("- {LONG}"));
assert_wrapped_like_a_paragraph(item, paragraph, line);
}
#[gpui::test]
fn a_long_ordered_list_item_wraps(cx: &mut TestAppContext) {
let line = line(cx);
let paragraph = height(cx, LONG);
let item = height(cx, &format!("1. {LONG}"));
assert_wrapped_like_a_paragraph(item, paragraph, line);
}
#[gpui::test]
fn a_long_list_item_with_inline_styles_wraps(cx: &mut TestAppContext) {
// Bold, code and a link put a different element in the same flex
// container — the `rich_list_item` path rather than `list_item`.
let styled = format!("**Bold** and `code` and a [link](#) — {LONG}");
let line = line(cx);
let paragraph = height(cx, &styled);
let item = height(cx, &format!("- {styled}"));
assert_wrapped_like_a_paragraph(item, paragraph, line);
}
#[gpui::test]
fn a_long_nested_list_item_wraps(cx: &mut TestAppContext) {
// An indented item, so the row is rendered at `indent_level > 0`. The
// parent now emits a row of its own, so subtract it to measure the
// nested one — what is left is the nested row plus the block gap.
let line = line(cx);
let paragraph = height(cx, LONG);
let parent = height(cx, "- parent");
let item = height(cx, &format!("- parent\n - {LONG}")) - parent;
assert_wrapped_like_a_paragraph(item, paragraph, line);
}
// --- nested lists ---
/// Drive the renderer over `source` and report the list rows it emitted,
/// as `(marker, indent level, text)` in document order. No window is
/// needed: this reads what `flush_list_item` built, not what it laid out.
fn emitted_rows(cx: &mut TestAppContext, source: &str) -> Vec<(ItemMarker, usize, String)> {
cx.update(crate::theme::init);
let events = Markdown::parse(source, false).events;
cx.update(|cx: &mut App| {
let mut renderer =
MarkdownRenderer::new(MarkdownStyle::default(), MarkdownSelection::new(), None);
for event in &events {
renderer.handle_event(&event.event, cx);
}
renderer
.emitted_list_items
.iter()
.map(|row| (row.marker.clone(), row.indent_level, row.text.clone()))
.collect()
})
}
/// The same rows, carrying only the marker a reader actually sees: a
/// continuation block of a multi-block item draws none, so it reads as
/// empty here.
fn list_rows(cx: &mut TestAppContext, source: &str) -> Vec<(String, usize, String)> {
emitted_rows(cx, source)
.into_iter()
.map(|(marker, indent_level, text)| {
let marker = match marker {
ItemMarker::Shown(marker) => marker,
ItemMarker::Hidden(_) => String::new(),
};
(marker, indent_level, text)
})
.collect()
}
/// Draw `source` and report the role each of its runs announced, in
/// document order — what a screen reader would be told the document is.
fn run_roles(cx: &mut TestAppContext, source: &str) -> Vec<Option<Role>> {
cx.update(crate::theme::init);
let doc = document(cx, source);
let cx = cx.add_empty_window();
draw(cx, || vec![MarkdownElement::new(doc.clone())])
.iter()
.map(|run| run.role)
.collect()
}
/// A nested document and the same items un-indented must lay out to the
/// same height: nesting changes a row's indent, never whether it exists.
/// Comparing against the flat form hardcodes neither the line height nor
/// the block spacing.
#[track_caller]
fn assert_same_row_count(cx: &mut TestAppContext, nested: &str, flat: &str) {
let nested_height = height(cx, nested);
let flat_height = height(cx, flat);
assert_eq!(
nested_height, flat_height,
"{nested:?} laid out to {nested_height:?}, but the same items flat \
({flat:?}) came to {flat_height:?}"
);
}
#[gpui::test]
fn a_nested_list_does_not_swallow_its_parents_text(cx: &mut TestAppContext) {
// The whole bug: `- x` with an indented `- y` under it used to render
// as one row reading "xy", because the child's flush picked up the
// parent's still-buffered text.
assert_eq!(
list_rows(cx, "- x\n - y"),
vec![
("•".to_string(), 0, "x".to_string()),
("•".to_string(), 1, "y".to_string()),
]
);
}
#[gpui::test]
fn an_ordered_list_nested_in_an_unordered_one(cx: &mut TestAppContext) {
assert_eq!(
list_rows(cx, "- x\n 1. y\n 2. z"),
vec![
("•".to_string(), 0, "x".to_string()),
("1.".to_string(), 1, "y".to_string()),
("2.".to_string(), 1, "z".to_string()),
]
);
}
#[gpui::test]
fn an_unordered_list_nested_in_an_ordered_one(cx: &mut TestAppContext) {
assert_eq!(
list_rows(cx, "1. x\n - y"),
vec![
("1.".to_string(), 0, "x".to_string()),
("•".to_string(), 1, "y".to_string()),
]
);
}
#[gpui::test]
fn three_levels_of_nesting_each_keep_their_own_row(cx: &mut TestAppContext) {
assert_eq!(
list_rows(cx, "- a\n - b\n - c"),
vec![
("•".to_string(), 0, "a".to_string()),
("•".to_string(), 1, "b".to_string()),
("•".to_string(), 2, "c".to_string()),
]
);
}
#[gpui::test]
fn a_parent_with_inline_styles_keeps_its_own_row(cx: &mut TestAppContext) {
// The `rich_list_item` path: bold, code and a link put spans in the
// parent's buffer, which is what the child used to inherit.
assert_eq!(
list_rows(cx, "- **bold** and `code` and a [link](#)\n - child"),
vec![
("•".to_string(), 0, "bold and code and a link".to_string()),
("•".to_string(), 1, "child".to_string()),
]
);
}
#[gpui::test]
fn a_nested_list_does_not_renumber_its_parents_siblings(cx: &mut TestAppContext) {
// The parent's row is emitted from inside the *child's* `Start(List)`,
// which is where the parent's ordinal is taken. Flush after pushing
// the child's context and `x` burns the child's `1.` while `z`
// silently becomes `1.` too.
assert_eq!(
list_rows(cx, "1. x\n - y\n2. z"),
vec![
("1.".to_string(), 0, "x".to_string()),
("•".to_string(), 1, "y".to_string()),
("2.".to_string(), 0, "z".to_string()),
]
);
}
#[gpui::test]
fn nested_task_items_keep_their_own_checkboxes(cx: &mut TestAppContext) {
// Checkboxes are pushed into `current_text`, so they travelled with
// whatever the flush picked up: both used to land on one row.
assert_eq!(
list_rows(cx, "- [ ] parent\n - [x] child"),
vec![
("•".to_string(), 0, "☐ parent".to_string()),
("•".to_string(), 1, "☑ child".to_string()),
]
);
}
#[gpui::test]
fn a_parent_with_no_text_of_its_own_emits_no_row(cx: &mut TestAppContext) {
// Nothing buffered to flush, so the guard in `flush_list_item` has to
// keep the extra flush from inventing a blank row.
assert_eq!(
list_rows(cx, "-\n - child"),
vec![("•".to_string(), 1, "child".to_string())]
);
}
#[gpui::test]
fn a_list_that_follows_a_paragraph_does_not_absorb_it(cx: &mut TestAppContext) {
// A top-level `Tag::List` has no parent item to attribute a row to,
// and the paragraph already flushed at `End(Paragraph)`. An unguarded
// flush here could only ever invent a row.
assert_eq!(
list_rows(cx, "A paragraph.\n\n- item"),
vec![("•".to_string(), 0, "item".to_string())]
);
}
#[gpui::test]
fn a_nested_list_lays_out_as_many_rows_as_a_flat_one(cx: &mut TestAppContext) {
assert_same_row_count(cx, "- x\n - y", "- x\n- y");
}
#[gpui::test]
fn a_deeply_nested_list_lays_out_as_many_rows_as_a_flat_one(cx: &mut TestAppContext) {
assert_same_row_count(
cx,
"1. a\n - b\n - c\n2. d",
"1. a\n- b\n- c\n2. d",
);
}
// --- loose lists ---
/// A list whose items are separated by a blank line, and the same list
/// without them. CommonMark calls the first *loose* and wraps each item's
/// content in a paragraph; both must render as the same list.
#[track_caller]
fn assert_loose_matches_tight(cx: &mut TestAppContext, loose: &str, tight: &str) {
let loose_rows = list_rows(cx, loose);
let tight_rows = list_rows(cx, tight);
assert!(
!tight_rows.is_empty(),
"{tight:?} emitted no rows at all, so this measures nothing"
);
assert_eq!(
loose_rows, tight_rows,
"{loose:?} emitted {loose_rows:?}, but the same items tight ({tight:?}) \
emitted {tight_rows:?}"
);
}
#[gpui::test]
fn a_loose_list_keeps_its_markers(cx: &mut TestAppContext) {
// The whole bug: the blank line makes each item's content a paragraph,
// which was flushed as body text — no marker, no indent, no number —
// and the item's `End(Item)` then found an empty buffer.
assert_eq!(
list_rows(cx, "- one\n\n- two\n"),
vec![
("•".to_string(), 0, "one".to_string()),
("•".to_string(), 0, "two".to_string()),
]
);
}
#[gpui::test]
fn a_loose_ordered_list_keeps_its_numbers(cx: &mut TestAppContext) {
assert_eq!(
list_rows(cx, "1. one\n\n2. two\n\n3. three\n"),
vec![
("1.".to_string(), 0, "one".to_string()),
("2.".to_string(), 0, "two".to_string()),
("3.".to_string(), 0, "three".to_string()),
]
);
}
#[gpui::test]
fn loose_and_tight_lists_emit_the_same_rows(cx: &mut TestAppContext) {
for (loose, tight) in [
("- one\n\n- two\n", "- one\n- two\n"),
("1. one\n\n2. two\n", "1. one\n2. two\n"),
(
"- **bold** and `code` and a [link](#)\n\n- plain\n",
"- **bold** and `code` and a [link](#)\n- plain\n",
),
("- [ ] todo\n\n- [x] done\n", "- [ ] todo\n- [x] done\n"),
// Looseness is per list: the outer list here is loose and the
// inner one tight, and both routes have to agree.
("- parent\n\n - child\n", "- parent\n - child\n"),
] {
assert_loose_matches_tight(cx, loose, tight);
}
}
#[gpui::test]
fn a_nested_loose_list_still_indents(cx: &mut TestAppContext) {
assert_eq!(
list_rows(cx, "- parent\n\n - child\n"),
vec![
("•".to_string(), 0, "parent".to_string()),
("•".to_string(), 1, "child".to_string()),
]
);
}
#[gpui::test]
fn a_loose_item_is_announced_as_a_list_item(cx: &mut TestAppContext) {
assert_eq!(
run_roles(cx, "- one\n\n- two\n"),
vec![Some(Role::ListItem), Some(Role::ListItem)],
"a loose list used to be announced as a sequence of paragraphs"
);
}
#[gpui::test]
fn an_item_with_two_blocks_draws_one_marker(cx: &mut TestAppContext) {
assert_eq!(
emitted_rows(cx, "- first block\n\n second block\n"),
vec![
(
ItemMarker::Shown("•".to_string()),
0,
"first block".to_string()
),
(
ItemMarker::Hidden("•".to_string()),
0,
"second block".to_string()
),
]
);
}
#[gpui::test]
fn an_items_second_paragraph_does_not_burn_a_number(cx: &mut TestAppContext) {
// The ordinal belongs to the item, not to the flush: taken per flush,
// `still one` would have eaten `2.` and left the next item at `3.`.
assert_eq!(
list_rows(cx, "1. one\n\n still one\n\n2. two\n"),
vec![
("1.".to_string(), 0, "one".to_string()),
(String::new(), 0, "still one".to_string()),
("2.".to_string(), 0, "two".to_string()),
]
);
}
#[gpui::test]
fn a_continuation_block_is_announced_as_a_paragraph(cx: &mut TestAppContext) {
// The runs are a flat list, so a second `ListItem` here would tell a
// screen reader this one-item list has two items.
assert_eq!(
run_roles(cx, "- first block\n\n second block\n"),
vec![Some(Role::ListItem), Some(Role::Paragraph)]
);
}
#[gpui::test]
fn a_paragraph_after_a_list_is_still_a_paragraph(cx: &mut TestAppContext) {
assert_eq!(
run_roles(cx, "- one\n\n- two\n\nAfter the list.\n"),
vec![
Some(Role::ListItem),
Some(Role::ListItem),
Some(Role::Paragraph)
]
);
}
#[gpui::test]
fn a_block_after_a_nested_list_belongs_to_the_item_that_held_it(cx: &mut TestAppContext) {
// The inner `End(List)` arrives first, so this block lands back at the
// parent's indent under a hidden marker — which is what alignment with
// the parent's own text demands.
assert_eq!(
emitted_rows(cx, "- parent\n\n - child\n\n after the child\n"),
vec![
(ItemMarker::Shown("•".to_string()), 0, "parent".to_string()),
(ItemMarker::Shown("•".to_string()), 1, "child".to_string()),
(
ItemMarker::Hidden("•".to_string()),
0,
"after the child".to_string()
),
]
);
}
#[gpui::test]
fn a_loose_list_lays_out_like_a_tight_one(cx: &mut TestAppContext) {
assert_eq!(height(cx, "- one\n\n- two\n"), height(cx, "- one\n- two\n"));
}
#[gpui::test]
fn a_continuation_block_starts_in_the_items_text_column(cx: &mut TestAppContext) {
// A hidden marker still takes up its width, so an item's second block
// wraps exactly like a second item would. Drop that width and the
// block gets a wider column and comes out shorter.
let two_blocks = height(cx, &format!("- {LONG}\n\n {LONG}"));
let two_items = height(cx, &format!("- {LONG}\n- {LONG}"));
assert_eq!(
two_blocks, two_items,
"an item's second block ({two_blocks:?}) did not wrap like a second \
item ({two_items:?})"
);
}
#[gpui::test]
fn a_long_table_cell_wraps(cx: &mut TestAppContext) {
let line = line(cx);
let short = height(cx, "| A | B |\n| --- | --- |\n| one | two |");
let long = height(cx, &format!("| A | B |\n| --- | --- |\n| {LONG} | two |"));
assert!(
long >= short + line,
"the cell stayed one line tall ({long:?} against {short:?}) instead of wrapping"
);
}
#[gpui::test]
fn a_document_keeps_its_run_ids_across_frames(cx: &mut TestAppContext) {
// Assistive technology reads a changed node id as a different
// element, so redrawing an unchanged document must not renumber it.
cx.update(crate::theme::init);
let doc = document(cx, EVERY_RUN_KIND);
let cx = cx.add_empty_window();
let first = draw(cx, || vec![MarkdownElement::new(doc.clone())]);
let second = draw(cx, || vec![MarkdownElement::new(doc.clone())]);
assert_eq!(id_paths(&first), id_paths(&second));
assert!(!first.is_empty());
}
#[gpui::test]
fn an_explicit_id_separates_two_elements_over_one_entity(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let doc = document(cx, EVERY_RUN_KIND);
let cx = cx.add_empty_window();
let runs = draw(cx, || {
vec![
MarkdownElement::new(doc.clone()).id("left"),
MarkdownElement::new(doc.clone()).id("right"),
]
});
let paths = id_paths(&runs);
let distinct: HashSet<&String> = paths.iter().collect();
assert_eq!(distinct.len(), 10, "colliding id paths: {paths:?}");
let documents: HashSet<&str> = runs.iter().map(|run| doc_and_run(run).0).collect();
assert_eq!(
documents,
HashSet::from(["left", "right"]),
"the override should replace the entity-derived scope"
);
}
// --- streaming ---
/// Everything the parse produced as text, so a test can say what the
/// document currently reads as without spelling out an event list.
fn rendered_text(markdown: &Markdown) -> String {
markdown
.events()
.iter()
.filter_map(|event| match &event.event {
Event::Text(text) | Event::Code(text) => Some(text.to_string()),
_ => None,
})
.collect()
}
fn document(cx: &mut TestAppContext, source: &str) -> Entity<Markdown> {
let source = source.to_string();
cx.new(|cx| Markdown::new(source, cx))
}
/// Count parses by counting notifications: a landed parse is the only
/// thing this entity notifies for.
fn count_parses(cx: &mut TestAppContext, markdown: &Entity<Markdown>) -> Rc<Cell<usize>> {
let parses = Rc::new(Cell::new(0));
let counter = parses.clone();
cx.update(|cx| {
cx.observe(markdown, move |_, _| counter.set(counter.get() + 1))
.detach()
});
parses
}
#[gpui::test]
fn the_first_parse_is_synchronous(cx: &mut TestAppContext) {
// A document must not be empty on its first frame, so `new` parses
// before it returns rather than scheduling like every later parse.
let markdown = document(cx, "# Hello");
markdown.read_with(cx, |markdown, _| {
assert_eq!(rendered_text(markdown), "Hello");
assert_eq!(markdown.parsed_source(), "# Hello");
assert!(!markdown.is_parsing());
});
}
#[gpui::test]
fn append_extends_the_document(cx: &mut TestAppContext) {
let markdown = document(cx, "Hello");
markdown.update(cx, |markdown, cx| markdown.append(", world", cx));
cx.run_until_parked();
markdown.read_with(cx, |markdown, _| {
assert_eq!(markdown.source(), "Hello, world");
assert_eq!(markdown.parsed_source(), "Hello, world");
assert_eq!(rendered_text(markdown), "Hello, world");
});
}
#[gpui::test]
fn appending_nothing_is_inert(cx: &mut TestAppContext) {
let markdown = document(cx, "Hello");
let parses = count_parses(cx, &markdown);
markdown.update(cx, |markdown, cx| markdown.append("", cx));
cx.run_until_parked();
assert_eq!(parses.get(), 0, "an empty delta scheduled a parse");
markdown.read_with(cx, |markdown, _| assert_eq!(markdown.source(), "Hello"));
}
#[gpui::test]
fn the_old_parse_keeps_rendering_until_the_new_one_lands(cx: &mut TestAppContext) {
// The point of parsing off the UI thread is that the view never goes
// blank: the previous events stay up while the new parse runs.
let markdown = document(cx, "before");
markdown.update(cx, |markdown, cx| markdown.append(" and after", cx));
markdown.read_with(cx, |markdown, _| {
assert!(markdown.is_parsing());
assert_eq!(markdown.source(), "before and after");
assert_eq!(markdown.parsed_source(), "before");
assert_eq!(rendered_text(markdown), "before");
});
cx.run_until_parked();
markdown.read_with(cx, |markdown, _| {
assert!(!markdown.is_parsing());
assert_eq!(rendered_text(markdown), "before and after");
});
}
#[gpui::test]
fn deltas_arriving_during_a_parse_coalesce(cx: &mut TestAppContext) {
let markdown = document(cx, "one");
let parses = count_parses(cx, &markdown);
// Five deltas with no chance for the executor to run in between: the
// first schedules a parse, the other four only mark it dirty.
markdown.update(cx, |markdown, cx| {
for delta in [" two", " three", " four", " five", " six"] {
markdown.append(delta, cx);
}
});
cx.run_until_parked();
assert_eq!(
parses.get(),
2,
"five deltas during one parse should cost one extra parse, not four"
);
markdown.read_with(cx, |markdown, _| {
assert_eq!(rendered_text(markdown), "one two three four five six")
});
}
#[gpui::test]
fn a_long_stream_lands_on_the_final_source(cx: &mut TestAppContext) {
let markdown = document(cx, "");
let mut expected = String::new();
for i in 0..200 {
let delta = format!("{i} ");
expected.push_str(&delta);
markdown.update(cx, |markdown, cx| markdown.append(&delta, cx));
// Let some deltas land mid-parse and others find the document idle.
if i % 7 == 0 {
cx.run_until_parked();
}
}
cx.run_until_parked();
markdown.read_with(cx, |markdown, _| {
assert_eq!(markdown.source(), expected);
assert_eq!(markdown.parsed_source(), expected);
assert!(!markdown.is_parsing());
assert_eq!(rendered_text(markdown), expected.trim_end());
});
}
#[gpui::test]
fn setting_the_same_source_does_not_reparse(cx: &mut TestAppContext) {
let markdown = document(cx, "# Same");
let parses = count_parses(cx, &markdown);
markdown.update(cx, |markdown, cx| markdown.set_source("# Same", cx));
cx.run_until_parked();
assert_eq!(parses.get(), 0, "an unchanged source scheduled a parse");
markdown.update(cx, |markdown, cx| markdown.set_source("# Different", cx));
cx.run_until_parked();
assert_eq!(parses.get(), 1);
}
#[gpui::test]
fn append_keeps_the_selection(cx: &mut TestAppContext) {
// Selection positions are `(run, byte offset within the run)`, so text
// arriving at the end of the document cannot disturb one made earlier.
let markdown = document(cx, "First block\n\nSecond block");
let selection = markdown.read_with(cx, |markdown, _| markdown.selection());
selection.select_in_run(0, 0..5);
markdown.update(cx, |markdown, cx| markdown.append("\n\nThird block", cx));
cx.run_until_parked();
assert!(!selection.is_empty(), "append dropped the selection");
let (start, end) = selection.range().expect("the selection went away");
assert_eq!((start.run, start.offset), (0, 0));
assert_eq!((end.run, end.offset), (0, 5));
}
#[gpui::test]
fn set_source_drops_the_selection(cx: &mut TestAppContext) {
let markdown = document(cx, "First block\n\nSecond block");
let selection = markdown.read_with(cx, |markdown, _| markdown.selection());
selection.select_in_run(0, 0..5);
markdown.update(cx, |markdown, cx| markdown.set_source("Something else", cx));
assert!(
selection.is_empty(),
"the selection survived a source it no longer indexes"
);
}
#[gpui::test]
fn the_default_document_id_follows_the_entity(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let doc = document(cx, "Hello.");
let expected = document_element_id(doc.entity_id());
assert_eq!(MarkdownElement::new(doc.clone()).element_id(), expected);
assert_eq!(
MarkdownElement::new(doc).id("mine").element_id(),
ElementId::Name("mine".into())
);
}
#[gpui::test]
fn every_run_kind_reports_a_role_and_its_text(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let doc = document(cx, EVERY_RUN_KIND);
let cx = cx.add_empty_window();
let runs = draw(cx, || vec![MarkdownElement::new(doc.clone())]);
let reported: Vec<(Option<Role>, Option<&str>, Option<usize>)> = runs
.iter()
.map(|run| (run.role, run.label.as_deref(), run.level))
.collect();
assert_eq!(
reported,
vec![
(Some(Role::Heading), Some("Title"), Some(1)),
(Some(Role::Paragraph), Some("A paragraph."), None),
(Some(Role::Blockquote), Some("A quote."), None),
(Some(Role::ListItem), Some("An item"), None),
(Some(Role::Code), Some("let x = 1;\n"), None),
]
);
}
#[gpui::test]
fn headings_report_their_level(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let doc = document(cx, "# One\n\n### Three\n");
let cx = cx.add_empty_window();
let runs = draw(cx, || vec![MarkdownElement::new(doc.clone())]);
let levels: Vec<_> = runs.iter().map(|run| run.level).collect();
assert_eq!(levels, vec![Some(1), Some(3)]);
}
#[test]
fn heading_levels_are_numbered_one_through_six() {
let levels: Vec<u8> = [
HeadingLevel::H1,
HeadingLevel::H2,
HeadingLevel::H3,
HeadingLevel::H4,
HeadingLevel::H5,
HeadingLevel::H6,
]
.into_iter()
.map(HeadingLevel::level)
.collect();
assert_eq!(levels, vec![1, 2, 3, 4, 5, 6]);
}
#[gpui::test]
fn dropping_the_document_mid_parse_is_harmless(cx: &mut TestAppContext) {
let markdown = document(cx, "start");
markdown.update(cx, |markdown, cx| markdown.append(" more", cx));
drop(markdown);
// The parse task is owned by the entity, so this drives an in-flight
// parse whose document is already gone.
cx.run_until_parked();
}
#[cfg(feature = "stitch")]
#[gpui::test]
fn partial_emphasis_renders_as_emphasis(cx: &mut TestAppContext) {
// Mid-stream `**bold` has no closer yet. Parsed as-is it draws literal
// asterisks that turn into bold one delta later — the flicker.
let markdown = document(cx, "A **partially written");
markdown.read_with(cx, |markdown, _| {
assert_eq!(rendered_text(markdown), "A partially written");
assert!(markdown
.events()
.iter()
.any(|event| matches!(event.event, Event::Start(Tag::Strong))));
});
}
#[gpui::test]
#[cfg(feature = "stitch")]
fn a_partial_link_is_not_a_link_yet(cx: &mut TestAppContext) {
// The label reads as plain text until the URL completes — a live link
// to a placeholder URL would be worse than no link.
let markdown = document(cx, "See [the docs](htt");
markdown.read_with(cx, |markdown, _| {
assert_eq!(rendered_text(markdown), "See the docs");
assert!(
!markdown
.events()
.iter()
.any(|event| matches!(event.event, Event::Start(Tag::Link { .. }))),
"an incomplete URL became a clickable link"
);
});
}
#[cfg(feature = "stitch")]
#[gpui::test]
fn a_complete_document_parses_the_same_either_way(cx: &mut TestAppContext) {
let source = "# Title\n\nA **bold** word, `code`, and a [link](https://example.com).\n";
let markdown = document(cx, source);
let with_preprocessing = markdown.read_with(cx, |markdown, _| rendered_text(markdown));
markdown.update(cx, |markdown, cx| {
markdown.set_preprocess_partial(false, cx)
});
cx.run_until_parked();
markdown.read_with(cx, |markdown, _| {
assert_eq!(rendered_text(markdown), with_preprocessing)
});
}
#[cfg(feature = "stitch")]
#[gpui::test]
fn preprocessing_can_be_turned_off(cx: &mut TestAppContext) {
let markdown = document(cx, "A **partially written");
markdown.update(cx, |markdown, cx| {
assert!(markdown.preprocess_partial());
markdown.set_preprocess_partial(false, cx);
});
cx.run_until_parked();
markdown.read_with(cx, |markdown, _| {
assert!(!markdown.preprocess_partial());
assert_eq!(rendered_text(markdown), "A **partially written");
});
}
// --- a code fence that has not closed yet ---
//
// A streaming fence is a different cache key on every delta, so
// highlighting it costs a full syntect pass per frame and fills the cache
// with prefixes that evict every settled block. The fix is to draw it
// plain until its closer arrives, which these read as `language == None`
// on the block — the same thing a bare fence gets, and the path that skips
// syntect entirely.
/// The language each code block was flushed with, in document order.
fn emitted_code_block_languages(cx: &mut TestAppContext, source: &str) -> Vec<Option<String>> {
cx.update(crate::theme::init);
let parsed = Markdown::parse(source, false);
cx.update(|cx: &mut App| {
let mut renderer = MarkdownRenderer::new(
MarkdownStyle::default(),
MarkdownSelection::new(),
parsed.unclosed_code_block,
);
for event in &parsed.events {
renderer.handle_event(&event.event, cx);
}
renderer.emitted_code_blocks.clone()
})
}
#[gpui::test]
fn an_unclosed_fence_is_drawn_plain(cx: &mut TestAppContext) {
assert_eq!(
emitted_code_block_languages(cx, "```rust\nfn main() {\n"),
vec![None],
"a fence still arriving must not be highlighted"
);
}
#[gpui::test]
fn a_closed_fence_keeps_its_language(cx: &mut TestAppContext) {
assert_eq!(
emitted_code_block_languages(cx, "```rust\nfn main() {}\n```\n"),
vec![Some("rust".to_string())],
"a settled block highlights, once, forever"
);
}
/// Only the block that is actually open loses its language. Earlier blocks
/// in the same document are settled and keep theirs.
#[gpui::test]
fn only_the_open_block_loses_its_language(cx: &mut TestAppContext) {
let source = "```rust\nfn a() {}\n```\n\nThen:\n\n```python\ndef b():\n";
assert_eq!(
emitted_code_block_languages(cx, source),
vec![Some("rust".to_string()), None],
);
}
/// The issue proposed keying this on `stitch::close_open_syntax` returning
/// `Cow::Owned`. It cannot be: an open `**bold` after a *settled* fence
/// makes that signal fire and would strip a finished block's colors.
#[gpui::test]
fn an_open_inline_marker_does_not_disturb_a_settled_fence(cx: &mut TestAppContext) {
let source = "```rust\nfn a() {}\n```\n\n**bold";
assert_eq!(
emitted_code_block_languages(cx, source),
vec![Some("rust".to_string())],
"the block closed; what happens after it is not its business"
);
}
/// The entity end to end: a fence streamed in through `append` is plain
/// for every delta until the closer lands, and highlighted from then on.
#[gpui::test]
fn a_streamed_fence_highlights_when_it_finishes(cx: &mut TestAppContext) {
let deltas = [
"Here you go:\n\n",
"```ru",
"st\n",
"fn main() {\n",
" println!(\"hi\");\n",
"}\n",
"``",
"`\n",
"\nDone.",
];
let markdown = document(cx, "");
for (index, delta) in deltas.iter().enumerate() {
markdown.update(cx, |markdown, cx| markdown.append(delta, cx));
cx.run_until_parked();
let source = markdown.read_with(cx, |markdown, _| markdown.source().to_string());
let languages = emitted_code_block_languages(cx, &source);
let closed = index >= 7;
if index < 1 {
assert!(languages.is_empty(), "no code block yet: {source:?}");
} else if closed {
assert_eq!(
languages,
vec![Some("rust".to_string())],
"after delta {index} the fence has closed: {source:?}"
);
} else {
assert_eq!(
languages,
vec![None],
"after delta {index} the fence is still open: {source:?}"
);
}
}
}
}