cindermark 0.2.0

High-performance incremental Markdown parser with UTF-16 offsets, built for native text editors on Apple platforms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
#![allow(clippy::manual_strip)]
//! Block-level parser producing a `Document` from source text.
//!
//! Matches the exact semantics of `MarkdownParser.swift`:
//! - Same block detection priority order
//! - Same line grouping rules for lists, blockquotes, paragraphs
//! - Two parse modes: Grouped (for rendering) and Editable (for block editor)
//!
//! Operates on raw source bytes with line-oriented scanning. The inline parser
//! (`inline.rs`) runs on each block's text content after block parsing.

use crate::ast::*;
use crate::inline;
use crate::utf16::Utf16Map;

/// Maximum columns in a table before it's treated as a paragraph.
/// Even on a 27" display, tables beyond ~20 columns are unusable.
const MAX_TABLE_COLUMNS: usize = 20;

/// Maximum data rows in a table.
const MAX_TABLE_ROWS: usize = 500;

/// Maximum tab-expanded indentation columns for a nested list / checkbox
/// marker. Marker lines indented deeper than this keep their historical
/// behavior (indented code block / paragraph continuation), which also
/// bounds nesting depth for hosts that render one level per 4 columns.
const MAX_LIST_INDENT_COLUMNS: usize = 32;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParsedListKind {
    Bullet,
    Ordered,
    Checkbox(bool),
}

#[derive(Debug, Clone)]
struct ParsedListMarker<'a> {
    kind: ParsedListKind,
    indent: usize,
    marker_start: usize,
    marker_end: usize,
    content_start: usize,
    marker_source: &'a str,
    unordered_marker: Option<char>,
    ordered_delimiter: Option<char>,
    ordered_raw_number: &'a str,
    ordered_number: u32,
}

/// Options controlling opt-in parser extensions.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParseOptions {
    /// URI-scheme prefix for block-level image / attachment markers:
    /// `![](<scheme><UUID>)` on a line by itself. The scheme string is the
    /// literal text between `![](` and the UUID, including any trailing
    /// colon — e.g. Ember Notes passes `"ember:"`.
    ///
    /// `None` (the default) disables the extension entirely: marker-shaped
    /// lines fall through to the regular paragraph path, which is the
    /// CommonMark-clean behavior.
    pub image_marker_scheme: Option<String>,
}

/// Parse source text into a `Document` with the given mode and default
/// options (all extensions that require configuration are off).
pub fn parse(source: &str, mode: ParseMode) -> Document {
    parse_with_options(source, mode, &ParseOptions::default())
}

/// Parse source text into a `Document` with the given mode and options.
pub fn parse_with_options(source: &str, mode: ParseMode, options: &ParseOptions) -> Document {
    let bytes = source.as_bytes();
    let utf16_map = Utf16Map::build(bytes);
    let lines = split_lines(source);
    let mut blocks = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        let line = &lines[i];
        let trimmed = line.text.trim();

        // Empty line
        if trimmed.is_empty() {
            if mode == ParseMode::Grouped {
                // Collapse multiple empty lines
                if let Some(last) = blocks.last() {
                    if matches!(block_kind_tag(last), BlockKindTag::Empty) {
                        i += 1;
                        continue;
                    }
                }
            }
            blocks.push(make_block(
                BlockKind::Empty,
                &lines,
                i,
                i + 1,
                bytes,
                &utf16_map,
            ));
            i += 1;
            continue;
        }

        // Image / sketch marker: `![](<scheme><UUID>)` on a line by itself
        // (opt-in via `ParseOptions::image_marker_scheme`). Host editors
        // inject these as text attachments (U+FFFC) so the user sees an
        // inline image, not raw markdown. Must run before paragraph
        // collection — once a marker rolls up into a paragraph block the
        // injector can't get at it.
        if let Some(scheme) = options.image_marker_scheme.as_deref() {
            if let Some(uuid) = parse_image_marker_line(trimmed, scheme) {
                blocks.push(make_block(
                    BlockKind::ImageMarker { uuid },
                    &lines,
                    i,
                    i + 1,
                    bytes,
                    &utf16_map,
                ));
                i += 1;
                continue;
            }
        }

        // Indented code block (CommonMark §4.4): 4+ leading spaces (or tab).
        // Must come before fenced code so `    ```` is treated as code, not a fence.
        // Cannot interrupt a paragraph — that constraint is naturally enforced
        // because paragraph collection runs entirely within a single outer-loop
        // iteration and emits its block before we return here.
        // Nested-list exception: indented lines that carry a list/checkbox
        // marker (or an injected U+FFFC marker attachment) are list items,
        // not code — see `starts_indented_code`.
        if starts_indented_code(line.text) {
            let start_line = i;
            let mut code_lines: Vec<String> = Vec::new();
            let mut last_content_offset = 0; // index in code_lines past the last non-blank line
            while i < lines.len() {
                let cl = lines[i].text;
                if starts_indented_code(cl) {
                    code_lines.push(strip_indented_code_indent(cl).to_string());
                    i += 1;
                    last_content_offset = code_lines.len();
                } else if cl.trim().is_empty() {
                    code_lines.push(String::new());
                    i += 1;
                } else {
                    break;
                }
            }
            // Drop trailing blank lines per CommonMark §4.4.
            code_lines.truncate(last_content_offset);
            // Rewind `i` past any consumed-but-discarded trailing blank lines so
            // they get re-emitted as Empty blocks on the next outer iteration.
            i = start_line + last_content_offset;
            blocks.push(make_block(
                BlockKind::CodeBlock {
                    language: None,
                    code: code_lines.join("\n"),
                },
                &lines,
                start_line,
                i,
                bytes,
                &utf16_map,
            ));
            continue;
        }

        // Fenced code block
        if trimmed.starts_with("```") {
            let start_line = i;
            let language = {
                let after_fence = trimmed[3..].trim();
                if after_fence.is_empty() {
                    None
                } else {
                    // Take first word only (CommonMark: info string's first word is the language)
                    Some(
                        after_fence
                            .split_whitespace()
                            .next()
                            .unwrap_or(after_fence)
                            .to_string(),
                    )
                }
            };
            let mut code_lines: Vec<&str> = Vec::new();
            i += 1;
            while i < lines.len() {
                let cl = lines[i].text.trim();
                if cl.starts_with("```") {
                    i += 1;
                    break;
                }
                code_lines.push(lines[i].text);
                i += 1;
            }
            let code = code_lines.join("\n");
            // Route ```mermaid fences into a dedicated block kind so Swift
            // can render the diagram instead of a code tile. Detection is
            // case-insensitive to tolerate `Mermaid` / `MERMAID`.
            let kind = if language.as_deref().is_some_and(is_mermaid_info_string) {
                BlockKind::MermaidDiagram {
                    diagram_type: MermaidDiagramType::from_source(&code),
                    source: code,
                }
            } else {
                BlockKind::CodeBlock { language, code }
            };
            blocks.push(make_block(kind, &lines, start_line, i, bytes, &utf16_map));
            continue;
        }

        // Table: current line has pipes AND next line is a separator
        if is_table_row(trimmed)
            && i + 1 < lines.len()
            && is_table_separator(lines[i + 1].text.trim())
        {
            let headers = parse_table_row(trimmed);
            // Column limit: tables beyond MAX_TABLE_COLUMNS fall through to paragraph
            if headers.len() <= MAX_TABLE_COLUMNS {
                let start_line = i;
                let separator_line = lines[i + 1].text.trim();
                let alignments = parse_alignments(separator_line);
                i += 2; // skip header + separator
                let mut rows: Vec<Vec<String>> = Vec::new();
                while i < lines.len() && rows.len() < MAX_TABLE_ROWS {
                    let rt = lines[i].text.trim();
                    if !is_table_row(rt) {
                        break;
                    }
                    rows.push(parse_table_row(rt));
                    i += 1;
                }
                // Skip remaining rows beyond the limit
                while i < lines.len() && is_table_row(lines[i].text.trim()) {
                    i += 1;
                }
                blocks.push(make_block(
                    BlockKind::Table {
                        headers,
                        rows,
                        alignments,
                    },
                    &lines,
                    start_line,
                    i,
                    bytes,
                    &utf16_map,
                ));
                continue;
            }
            // else: too many columns, fall through to paragraph
        }

        // Horizontal rule
        if is_horizontal_rule(trimmed) {
            blocks.push(make_block(
                BlockKind::HorizontalRule,
                &lines,
                i,
                i + 1,
                bytes,
                &utf16_map,
            ));
            i += 1;
            continue;
        }

        // Heading
        if let Some(kind) = parse_heading(trimmed) {
            blocks.push(make_block(kind, &lines, i, i + 1, bytes, &utf16_map));
            i += 1;
            continue;
        }

        // Blockquote (with callout detection on first line)
        if trimmed.starts_with("> ") || trimmed == ">" {
            let start_line = i;
            let mut quote_lines: Vec<&str> = Vec::new();
            while i < lines.len() {
                let ql = lines[i].text.trim();
                if ql.starts_with("> ") {
                    quote_lines.push(&ql[2..]);
                } else if ql == ">" {
                    quote_lines.push("");
                } else {
                    break;
                }
                i += 1;
            }
            // Callout: first line begins with `[!<kind>]` (optionally followed by a title).
            // Remaining lines form the body. Unknown kind names degrade to a plain blockquote.
            if let Some(first) = quote_lines.first() {
                if let Some((kind, title)) = parse_callout_header(first) {
                    let body = if quote_lines.len() > 1 {
                        quote_lines[1..].join("\n")
                    } else {
                        String::new()
                    };
                    blocks.push(make_block(
                        BlockKind::Callout {
                            kind,
                            title,
                            text: body,
                        },
                        &lines,
                        start_line,
                        i,
                        bytes,
                        &utf16_map,
                    ));
                    continue;
                }
            }
            blocks.push(make_block(
                BlockKind::Blockquote {
                    text: quote_lines.join("\n"),
                },
                &lines,
                start_line,
                i,
                bytes,
                &utf16_map,
            ));
            continue;
        }

        let list_marker = parse_list_marker(line.text);

        // Checkbox (GFM-style extension layered on valid bullet markers).
        if let Some(marker) = list_marker
            .as_ref()
            .filter(|m| matches!(m.kind, ParsedListKind::Checkbox(_)))
        {
            let checked = matches!(marker.kind, ParsedListKind::Checkbox(true));
            let text = line.text[marker.content_start..].to_string();
            blocks.push(make_block_with_marker(
                BlockKind::Checkbox { checked, text },
                marker_to_meta(marker, line, bytes, &utf16_map),
                &lines,
                i,
                i + 1,
                bytes,
                &utf16_map,
            ));
            i += 1;
            continue;
        }

        // Unordered list
        if let Some(marker) = list_marker
            .as_ref()
            .filter(|m| m.kind == ParsedListKind::Bullet)
        {
            match mode {
                ParseMode::Grouped => {
                    let start_line = i;
                    let first_marker = marker.clone();
                    let mut items: Vec<String> = Vec::new();
                    while i < lines.len() {
                        let Some(ul_marker) = parse_list_marker(lines[i].text) else {
                            let ul = lines[i].text.trim();
                            if ul.is_empty() {
                                break;
                            }
                            if let Some(last) = items.last_mut() {
                                last.push(' ');
                                last.push_str(ul);
                            }
                            i += 1;
                            continue;
                        };

                        if matches!(ul_marker.kind, ParsedListKind::Checkbox(_)) {
                            break; // hand off to checkbox parser
                        } else if ul_marker.kind == ParsedListKind::Bullet
                            && ul_marker.unordered_marker == first_marker.unordered_marker
                        {
                            items.push(lines[i].text[ul_marker.content_start..].to_string());
                        } else {
                            break;
                        }
                        i += 1;
                    }
                    let list_items = items
                        .into_iter()
                        .map(|text| ListItem {
                            text,
                            inline_spans: Vec::new(),
                        })
                        .collect();
                    blocks.push(make_block_with_marker(
                        BlockKind::BulletList { items: list_items },
                        marker_to_meta(&first_marker, &lines[start_line], bytes, &utf16_map),
                        &lines,
                        start_line,
                        i,
                        bytes,
                        &utf16_map,
                    ));
                }
                ParseMode::Editable => {
                    let text = line.text[marker.content_start..].to_string();
                    blocks.push(make_block_with_marker(
                        BlockKind::BulletItem { text },
                        marker_to_meta(marker, line, bytes, &utf16_map),
                        &lines,
                        i,
                        i + 1,
                        bytes,
                        &utf16_map,
                    ));
                    i += 1;
                }
            }
            continue;
        }

        // Ordered list
        if let Some(marker) = list_marker
            .as_ref()
            .filter(|m| m.kind == ParsedListKind::Ordered)
        {
            match mode {
                ParseMode::Grouped => {
                    let start_line = i;
                    let first_marker = marker.clone();
                    let mut items: Vec<String> = Vec::new();
                    while i < lines.len() {
                        let ol = lines[i].text.trim();
                        if let Some(ol_marker) = parse_list_marker(lines[i].text) {
                            if ol_marker.kind == ParsedListKind::Ordered
                                && ol_marker.ordered_delimiter == first_marker.ordered_delimiter
                            {
                                items.push(lines[i].text[ol_marker.content_start..].to_string());
                            } else {
                                break;
                            }
                        } else if ol.is_empty() {
                            break;
                        } else {
                            // Continuation of previous item
                            if let Some(last) = items.last_mut() {
                                last.push(' ');
                                last.push_str(ol);
                            }
                        }
                        i += 1;
                    }
                    let list_items = items
                        .into_iter()
                        .map(|text| ListItem {
                            text,
                            inline_spans: Vec::new(),
                        })
                        .collect();
                    blocks.push(make_block_with_marker(
                        BlockKind::OrderedList {
                            start: first_marker.ordered_number,
                            items: list_items,
                        },
                        marker_to_meta(&first_marker, &lines[start_line], bytes, &utf16_map),
                        &lines,
                        start_line,
                        i,
                        bytes,
                        &utf16_map,
                    ));
                }
                ParseMode::Editable => {
                    let text = line.text[marker.content_start..].to_string();
                    let number = marker.ordered_number;
                    blocks.push(make_block_with_marker(
                        BlockKind::NumberedItem { number, text },
                        marker_to_meta(marker, line, bytes, &utf16_map),
                        &lines,
                        i,
                        i + 1,
                        bytes,
                        &utf16_map,
                    ));
                    i += 1;
                }
            }
            continue;
        }

        // Footnote definition
        if let Some(kind) = parse_footnote_def(trimmed) {
            blocks.push(make_block(kind, &lines, i, i + 1, bytes, &utf16_map));
            i += 1;
            continue;
        }

        // Paragraph — collect consecutive non-special lines
        let start_line = i;
        let mut para_lines: Vec<&str> = Vec::new();
        while i < lines.len() {
            let pl = lines[i].text;
            let pt = pl.trim();
            if pt.is_empty()
                || pt.starts_with("```")
                || is_heading_line(pt)
                || pt.starts_with("> ")
                || is_horizontal_rule(pt)
                || parse_list_marker(pl).is_some()
                || parse_footnote_def(pt).is_some()
                || (is_table_row(pt)
                    && i + 1 < lines.len()
                    && is_table_separator(lines[i + 1].text.trim()))
                || (!para_lines.is_empty() && parse_setext_underline(pl).is_some())
            {
                break;
            }
            para_lines.push(pl);
            i += 1;
        }

        // Setext heading: paragraph followed by =/- underline line.
        // CommonMark resolves the ambiguity in favor of setext over thematic break.
        if !para_lines.is_empty() && i < lines.len() {
            if let Some(level) = parse_setext_underline(lines[i].text) {
                let heading_text = para_lines.join("\n").trim().to_string();
                blocks.push(make_block(
                    BlockKind::Heading {
                        level,
                        text: heading_text,
                    },
                    &lines,
                    start_line,
                    i + 1,
                    bytes,
                    &utf16_map,
                ));
                i += 1;
                continue;
            }
        }

        if !para_lines.is_empty() {
            blocks.push(make_block(
                BlockKind::Paragraph {
                    text: para_lines.join("\n"),
                },
                &lines,
                start_line,
                i,
                bytes,
                &utf16_map,
            ));
        }
    }

    // Run inline parsing on all blocks
    inline::parse_inline_spans(&mut blocks, bytes, &utf16_map);

    Document {
        line_count: lines.len() as u32,
        blocks,
    }
}

// MARK: - Line splitting

/// A line with its byte range in the source.
struct Line<'a> {
    text: &'a str,
    byte_start: usize,
    byte_end: usize, // exclusive, includes the newline if present
}

fn split_lines(source: &str) -> Vec<Line<'_>> {
    let mut lines = Vec::new();
    let mut start = 0;
    let bytes = source.as_bytes();

    for (i, &b) in bytes.iter().enumerate() {
        if b == b'\n' {
            // Strip trailing \r for Windows line endings
            let text_end = if i > start && bytes[i - 1] == b'\r' {
                i - 1
            } else {
                i
            };
            lines.push(Line {
                text: &source[start..text_end],
                byte_start: start,
                byte_end: i + 1,
            });
            start = i + 1;
        }
    }
    // Trailing content after last newline
    if start < source.len() {
        let end = if source.as_bytes().last() == Some(&b'\r') {
            source.len() - 1
        } else {
            source.len()
        };
        lines.push(Line {
            text: &source[start..end],
            byte_start: start,
            byte_end: source.len(),
        });
    }

    lines
}

// MARK: - Block construction

fn make_block(
    kind: BlockKind,
    lines: &[Line],
    line_start: usize,
    line_end: usize,
    source: &[u8],
    utf16_map: &Utf16Map,
) -> BlockNode {
    make_block_with_optional_marker(kind, None, lines, line_start, line_end, source, utf16_map)
}

fn make_block_with_marker(
    kind: BlockKind,
    list_marker: ListMarkerMeta,
    lines: &[Line],
    line_start: usize,
    line_end: usize,
    source: &[u8],
    utf16_map: &Utf16Map,
) -> BlockNode {
    make_block_with_optional_marker(
        kind,
        Some(list_marker),
        lines,
        line_start,
        line_end,
        source,
        utf16_map,
    )
}

fn make_block_with_optional_marker(
    kind: BlockKind,
    list_marker: Option<ListMarkerMeta>,
    lines: &[Line],
    line_start: usize,
    line_end: usize,
    source: &[u8],
    utf16_map: &Utf16Map,
) -> BlockNode {
    let byte_start = lines[line_start].byte_start as u32;
    let byte_end = if line_end > 0 && line_end <= lines.len() {
        lines[line_end - 1].byte_end as u32
    } else {
        byte_start
    };
    let utf16_start = utf16_map.byte_to_utf16(byte_start, source);
    let utf16_end = utf16_map.byte_to_utf16(byte_end, source);

    BlockNode {
        kind,
        line_start: line_start as u32,
        line_end: line_end as u32,
        utf16_start,
        utf16_end,
        byte_start,
        byte_end,
        list_marker,
        inline_spans: Vec::new(),
    }
}

fn marker_to_meta(
    marker: &ParsedListMarker,
    line: &Line,
    source: &[u8],
    utf16_map: &Utf16Map,
) -> ListMarkerMeta {
    let marker_byte_start = (line.byte_start + marker.marker_start) as u32;
    let marker_byte_end = (line.byte_start + marker.marker_end) as u32;
    let content_byte_start = (line.byte_start + marker.content_start) as u32;

    ListMarkerMeta {
        indent: marker.indent as u32,
        marker_utf16_start: utf16_map.byte_to_utf16(marker_byte_start, source),
        marker_utf16_end: utf16_map.byte_to_utf16(marker_byte_end, source),
        marker_byte_start,
        marker_byte_end,
        content_byte_start,
        marker_source: marker.marker_source.to_string(),
        unordered_marker: marker
            .unordered_marker
            .map(|c| c.to_string())
            .unwrap_or_default(),
        ordered_delimiter: marker
            .ordered_delimiter
            .map(|c| c.to_string())
            .unwrap_or_default(),
        ordered_raw_number: marker.ordered_raw_number.to_string(),
    }
}

#[derive(PartialEq)]
enum BlockKindTag {
    Empty,
    Other,
}

fn block_kind_tag(block: &BlockNode) -> BlockKindTag {
    match block.kind {
        BlockKind::Empty => BlockKindTag::Empty,
        _ => BlockKindTag::Other,
    }
}

// MARK: - Block detection helpers

fn parse_heading(line: &str) -> Option<BlockKind> {
    for level in (1..=6u8).rev() {
        let prefix = "#".repeat(level as usize);
        let marker = format!("{} ", prefix);
        if line.starts_with(&marker) {
            return Some(BlockKind::Heading {
                level,
                text: line[marker.len()..].to_string(),
            });
        }
    }
    None
}

fn is_heading_line(line: &str) -> bool {
    if !line.starts_with('#') {
        return false;
    }
    for level in 1..=6 {
        let marker = format!("{} ", "#".repeat(level));
        if line.starts_with(&marker) {
            return true;
        }
    }
    false
}

/// CommonMark §4.4: a line begins an indented code block when it is indented
/// by ≥4 spaces (or a leading tab), and is not blank, and isn't already part
/// of another block. Tabs count as advancing to the next 4-column stop, but
/// for our byte scanner a leading tab is treated as ≥4 columns.
fn is_indented_code_line(line: &str) -> bool {
    let bytes = line.as_bytes();
    if bytes.is_empty() {
        return false;
    }
    if bytes[0] == b'\t' {
        return !line[1..].trim().is_empty();
    }
    if bytes.len() >= 4 && &bytes[..4] == b"    " {
        return !line[4..].trim().is_empty() || bytes.len() > 4;
    }
    false
}

/// True when the line's first non-whitespace character is U+FFFC — the
/// object replacement character host editors substitute for injected list
/// marker attachments. Such lines are attachment carriers, not code: a
/// deeply indented list item whose marker was replaced by an attachment
/// must keep parsing as paragraph content so the editor's marker layout
/// (not code styling) applies on re-parse.
fn is_attachment_carrier_line(line: &str) -> bool {
    line.trim_start_matches([' ', '\t']).starts_with('\u{FFFC}')
}

/// Whether the line opens (or continues) an indented code block.
///
/// List and checkbox markers win over indented code up to
/// `MAX_LIST_INDENT_COLUMNS`, so nested list items indented ≥4 columns
/// parse as list items instead of code. Attachment-carrier lines (U+FFFC)
/// always stay paragraph content. Both are deliberate deviations from
/// CommonMark §4.4 in favor of editor-friendly nested lists.
fn starts_indented_code(line: &str) -> bool {
    is_indented_code_line(line)
        && parse_list_marker(line).is_none()
        && !is_attachment_carrier_line(line)
}

/// Strip the 4-space (or 1-tab) indentation from an indented-code line.
fn strip_indented_code_indent(line: &str) -> &str {
    let bytes = line.as_bytes();
    if !bytes.is_empty() && bytes[0] == b'\t' {
        &line[1..]
    } else if bytes.len() >= 4 && &bytes[..4] == b"    " {
        &line[4..]
    } else {
        line
    }
}

/// Detect a callout header `[!<kind>]` with optional trailing title.
/// Returns the kind and (if present) the trimmed custom title.
///
/// Format (all parts after `>` stripping done by caller):
///   `[!note]`            → (Note, None)
///   `[!tip] Friendly`    → (Tip, Some("Friendly"))
///   `[!Warning]`         → case-insensitive kind
///   `[!unknown]`         → None  (caller falls back to plain blockquote)
///
/// Foldable markers (`[!note]-` / `[!note]+`) are currently ignored — the `-`
/// or `+` is stripped so unknown-kind fallback doesn't fire. We skip the fold
/// state for launch and can surface it later without an ABI change.
pub(crate) fn parse_callout_header(
    line: &str,
) -> Option<(crate::ast::CalloutKind, Option<String>)> {
    let trimmed = line.trim_start();
    let after_open = trimmed.strip_prefix("[!")?;
    let close_idx = after_open.find(']')?;
    let kind_name = &after_open[..close_idx];
    let kind = crate::ast::CalloutKind::from_name(kind_name)?;
    let mut rest = &after_open[close_idx + 1..];
    // Strip optional fold marker (+ open-by-default, - closed-by-default)
    if rest.starts_with('+') || rest.starts_with('-') {
        rest = &rest[1..];
    }
    let title = rest.trim();
    let title = if title.is_empty() {
        None
    } else {
        Some(title.to_string())
    };
    Some((kind, title))
}

/// Detect a CommonMark setext heading underline: `=+` (level 1) or `-+` (level 2),
/// with optional 0-3 leading spaces and trailing whitespace, nothing else.
/// Returns the heading level if matched.
pub(crate) fn parse_setext_underline(line: &str) -> Option<u8> {
    let bytes = line.as_bytes();
    let mut i = 0;
    // 0-3 leading spaces (4+ would be an indented code line, not setext).
    let mut leading_spaces = 0;
    while i < bytes.len() && bytes[i] == b' ' {
        leading_spaces += 1;
        i += 1;
    }
    if leading_spaces > 3 {
        return None;
    }
    if i >= bytes.len() {
        return None;
    }
    let underline_char = bytes[i];
    if underline_char != b'=' && underline_char != b'-' {
        return None;
    }
    while i < bytes.len() && bytes[i] == underline_char {
        i += 1;
    }
    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
        i += 1;
    }
    if i != bytes.len() {
        return None;
    }
    Some(if underline_char == b'=' { 1 } else { 2 })
}

fn is_horizontal_rule(line: &str) -> bool {
    let stripped: String = line.chars().filter(|c| *c != ' ').collect();
    if stripped.len() < 3 {
        return false;
    }
    (stripped.chars().all(|c| c == '-') && stripped.len() >= 3)
        || (stripped.chars().all(|c| c == '*') && stripped.len() == 3)
        || (stripped.chars().all(|c| c == '_') && stripped.len() >= 3)
}

fn parse_list_marker(line: &str) -> Option<ParsedListMarker<'_>> {
    let bytes = line.as_bytes();
    // Leading whitespace scan with CommonMark tab expansion: a tab advances
    // to the next multiple-of-4 column. `indent` stays the count of leading
    // whitespace CHARACTERS (== bytes; indentation is ASCII), matching what
    // hosts already receive for 0-3 space indents — the FFI consumer treats
    // it as a UTF-16 length covering the indentation run. The tab-expanded
    // `columns` value is only used to cap the nesting depth.
    let mut indent = 0;
    let mut columns = 0usize;
    while indent < bytes.len() {
        match bytes[indent] {
            b' ' => columns += 1,
            b'\t' => columns = (columns / 4 + 1) * 4,
            _ => break,
        }
        indent += 1;
    }
    if columns > MAX_LIST_INDENT_COLUMNS || indent >= bytes.len() {
        return None;
    }

    let marker_start = indent;
    let marker_byte = bytes[marker_start];

    if matches!(marker_byte, b'-' | b'+' | b'*') {
        let after_marker = marker_start + 1;
        if after_marker >= bytes.len() || !is_marker_space(bytes[after_marker]) {
            return None;
        }

        let mut bullet_marker_end = after_marker + 1;
        while bullet_marker_end < bytes.len() && is_marker_space(bytes[bullet_marker_end]) {
            bullet_marker_end += 1;
        }

        if let Some((checked, checkbox_end)) = parse_checkbox_tail(bytes, bullet_marker_end) {
            let marker_source = &line[marker_start..checkbox_end];
            return Some(ParsedListMarker {
                kind: ParsedListKind::Checkbox(checked),
                indent,
                marker_start,
                marker_end: checkbox_end,
                content_start: checkbox_end,
                marker_source,
                unordered_marker: Some(marker_byte as char),
                ordered_delimiter: None,
                ordered_raw_number: "",
                ordered_number: 0,
            });
        }

        let marker_source = &line[marker_start..bullet_marker_end];
        return Some(ParsedListMarker {
            kind: ParsedListKind::Bullet,
            indent,
            marker_start,
            marker_end: bullet_marker_end,
            content_start: bullet_marker_end,
            marker_source,
            unordered_marker: Some(marker_byte as char),
            ordered_delimiter: None,
            ordered_raw_number: "",
            ordered_number: 0,
        });
    }

    if marker_byte.is_ascii_digit() {
        let number_start = marker_start;
        let mut number_end = number_start;
        while number_end < bytes.len() && bytes[number_end].is_ascii_digit() {
            number_end += 1;
        }
        let digit_count = number_end - number_start;
        if digit_count == 0 || digit_count > 9 || number_end >= bytes.len() {
            return None;
        }

        let delimiter = bytes[number_end];
        if delimiter != b'.' && delimiter != b')' {
            return None;
        }

        let after_delimiter = number_end + 1;
        if after_delimiter >= bytes.len() || !is_marker_space(bytes[after_delimiter]) {
            return None;
        }

        let mut marker_end = after_delimiter + 1;
        while marker_end < bytes.len() && is_marker_space(bytes[marker_end]) {
            marker_end += 1;
        }

        let raw_number = &line[number_start..number_end];
        let ordered_number = raw_number.parse::<u32>().unwrap_or(1);
        let marker_source = &line[marker_start..marker_end];

        return Some(ParsedListMarker {
            kind: ParsedListKind::Ordered,
            indent,
            marker_start,
            marker_end,
            content_start: marker_end,
            marker_source,
            unordered_marker: None,
            ordered_delimiter: Some(delimiter as char),
            ordered_raw_number: raw_number,
            ordered_number,
        });
    }

    None
}

fn is_marker_space(byte: u8) -> bool {
    byte == b' ' || byte == b'\t'
}

fn parse_checkbox_tail(bytes: &[u8], marker_content_start: usize) -> Option<(bool, usize)> {
    if marker_content_start + 3 > bytes.len() || bytes[marker_content_start] != b'[' {
        return None;
    }

    let state = bytes[marker_content_start + 1];
    let checked = match state {
        b' ' => false,
        b'x' | b'X' => true,
        _ => return None,
    };

    if bytes[marker_content_start + 2] != b']' {
        return None;
    }

    let after_checkbox = marker_content_start + 3;
    if after_checkbox == bytes.len() {
        return Some((checked, after_checkbox));
    }
    if !is_marker_space(bytes[after_checkbox]) {
        return None;
    }

    let mut end = after_checkbox + 1;
    while end < bytes.len() && is_marker_space(bytes[end]) {
        end += 1;
    }
    Some((checked, end))
}

fn parse_checkbox_any_indent(trimmed_line: &str) -> Option<(&str, &str, bool)> {
    let bytes = trimmed_line.as_bytes();
    let bullet = *bytes.first()?;
    if !matches!(bullet, b'-' | b'+' | b'*') || bytes.get(1) != Some(&b' ') {
        return None;
    }

    let (checked, end) = parse_checkbox_tail(bytes, 2)?;
    Some((&trimmed_line[..end], &trimmed_line[end..], checked))
}

/// Parses `![](<scheme><UUID>)` block markers (image / sketch attachments),
/// where `scheme` is the host-configured prefix (e.g. `"ember:"`).
///
/// Returns the UUID string (preserving original case) when `line` is *exactly*
/// the marker — leading / trailing whitespace is the caller's job to strip
/// (we receive the already-trimmed line from the parser loop). Anything that
/// isn't a single marker — extra text on the same line, surrounding inline
/// markdown, or a malformed UUID — falls through to the regular paragraph
/// path so the user sees raw markdown instead of a silently-injected blank.
///
/// UUID validation is deliberately permissive: any 36-char `8-4-4-4-12`
/// hex sequence (case-insensitive) qualifies. Stricter version-bit checks
/// would reject UUIDs the app itself produced via `UUID()` (which returns
/// v4) without round-trip-safe value across SwiftData migrations.
pub(crate) fn parse_image_marker_line(line: &str, scheme: &str) -> Option<String> {
    let stripped = line
        .strip_prefix("![](")?
        .strip_prefix(scheme)?
        .strip_suffix(')')?;
    if !is_uuid_format(stripped) {
        return None;
    }
    Some(stripped.to_string())
}

fn is_uuid_format(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.len() != 36 {
        return false;
    }
    for (i, b) in bytes.iter().enumerate() {
        let expect_hyphen = matches!(i, 8 | 13 | 18 | 23);
        if expect_hyphen {
            if *b != b'-' {
                return false;
            }
        } else if !b.is_ascii_hexdigit() {
            return false;
        }
    }
    true
}

fn parse_footnote_def(line: &str) -> Option<BlockKind> {
    if !line.starts_with("[^") {
        return None;
    }
    let close_bracket = line.find(']')?;
    if close_bracket <= 2 {
        return None;
    }
    let after_close = close_bracket + 1;
    if after_close >= line.len() || line.as_bytes()[after_close] != b':' {
        return None;
    }
    let label = line[2..close_bracket].to_string();
    let text_start = after_close + 1;
    let text = if text_start < line.len() {
        line[text_start..].trim().to_string()
    } else {
        String::new()
    };
    Some(BlockKind::FootnoteDefinition { label, text })
}

// MARK: - Table helpers

fn is_table_row(line: &str) -> bool {
    line.contains('|') && !line.trim_start().starts_with("|--")
}

fn is_table_separator(line: &str) -> bool {
    let stripped = line.replace([' ', '|', '-', ':'], "");
    stripped.is_empty() && line.contains('-') && line.contains('|')
}

fn parse_table_row(line: &str) -> Vec<String> {
    let mut cells: Vec<String> = line.split('|').map(|s| s.trim().to_string()).collect();
    if cells.first().is_some_and(|s| s.is_empty()) {
        cells.remove(0);
    }
    if cells.last().is_some_and(|s| s.is_empty()) {
        cells.pop();
    }
    cells
}

fn parse_alignments(separator: &str) -> Vec<ColumnAlignment> {
    let mut cells: Vec<&str> = separator.split('|').map(|s| s.trim()).collect();
    if cells.first().is_some_and(|s| s.is_empty()) {
        cells.remove(0);
    }
    if cells.last().is_some_and(|s| s.is_empty()) {
        cells.pop();
    }

    cells
        .iter()
        .map(|cell| {
            let has_leading = cell.starts_with(':');
            let has_trailing = cell.ends_with(':');
            if has_leading && has_trailing {
                ColumnAlignment::Center
            } else if has_trailing {
                ColumnAlignment::Right
            } else if has_leading {
                ColumnAlignment::Left
            } else {
                ColumnAlignment::Default
            }
        })
        .collect()
}

// MARK: - Public utilities (matching Swift API)

/// Extract wiki link titles from content (skipping code blocks).
pub fn extract_wiki_links(content: &str) -> Vec<String> {
    let without_code = strip_code_blocks(content);
    parse_inline_segments(&without_code)
        .into_iter()
        .filter_map(|seg| match seg {
            InlineSegment::WikiLink(title) => Some(title),
            _ => None,
        })
        .collect()
}

/// Toggle checkbox at a line index, returning the new content.
pub fn toggle_checkbox(content: &str, line_index: u32) -> String {
    let lines: Vec<&str> = content.split('\n').collect();
    let idx = line_index as usize;
    if idx >= lines.len() {
        return content.to_string();
    }
    let line = lines[idx];
    let trimmed = line.trim_start();
    let indent: &str = &line[..line.len() - trimmed.len()];

    let (marker_source, item_text, checked) = if let Some(marker) = parse_list_marker(line) {
        let ParsedListKind::Checkbox(checked) = marker.kind else {
            return content.to_string();
        };
        (
            marker.marker_source.to_string(),
            line[marker.content_start..].to_string(),
            checked,
        )
    } else if let Some((marker_source, item_text, checked)) = parse_checkbox_any_indent(trimmed) {
        (marker_source.to_string(), item_text.to_string(), checked)
    } else {
        return content.to_string();
    };

    let old_state = if checked {
        if marker_source.contains("[X]") {
            "[X]"
        } else {
            "[x]"
        }
    } else {
        "[ ]"
    };
    let new_state = if checked { "[ ]" } else { "[x]" };
    let new_marker_source = marker_source.replacen(old_state, new_state, 1);
    let new_line = format!("{indent}{new_marker_source}{item_text}");

    let mut result: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
    result[idx] = new_line;
    result.join("\n")
}

// MARK: - Inline segments (for wiki link extraction)

enum InlineSegment {
    #[allow(dead_code)]
    Text(String),
    WikiLink(String),
}

fn parse_inline_segments(text: &str) -> Vec<InlineSegment> {
    let mut segments = Vec::new();
    let mut remaining = text;

    while let Some(open_pos) = remaining.find("[[") {
        let before = &remaining[..open_pos];
        if !before.is_empty() {
            segments.push(InlineSegment::Text(before.to_string()));
        }
        let after_open = &remaining[open_pos + 2..];
        if let Some(close_pos) = after_open.find("]]") {
            let body = &after_open[..close_pos];
            // Aliased form `[[target|Display]]` — the target for backlinks is
            // the pre-pipe portion; the display text is rendered inline only.
            let target = body.split('|').next().unwrap_or(body).trim().to_string();
            if !target.is_empty() {
                segments.push(InlineSegment::WikiLink(target));
            } else {
                segments.push(InlineSegment::Text("[[]]".to_string()));
            }
            remaining = &after_open[close_pos + 2..];
        } else {
            segments.push(InlineSegment::Text(remaining[open_pos..].to_string()));
            remaining = "";
        }
    }

    if !remaining.is_empty() {
        segments.push(InlineSegment::Text(remaining.to_string()));
    }

    segments
}

fn strip_code_blocks(text: &str) -> String {
    let mut result = String::new();
    let mut in_code_block = false;

    for line in text.lines() {
        if line.trim().starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }
        if !in_code_block {
            // Strip inline code spans
            let mut cleaned = String::new();
            let mut in_inline_code = false;
            for ch in line.chars() {
                if ch == '`' {
                    in_inline_code = !in_inline_code;
                } else if !in_inline_code {
                    cleaned.push(ch);
                }
            }
            result.push_str(&cleaned);
            result.push('\n');
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper to parse in grouped mode
    fn parse_grouped(input: &str) -> Vec<BlockNode> {
        parse(input, ParseMode::Grouped).blocks
    }

    fn parse_editable(input: &str) -> Vec<BlockNode> {
        parse(input, ParseMode::Editable).blocks
    }

    // MARK: - Headings

    #[test]
    fn h1_heading() {
        let blocks = parse_grouped("# Hello World");
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0].kind, BlockKind::Heading { level: 1, text } if text == "Hello World")
        );
    }

    #[test]
    fn h2_heading() {
        let blocks = parse_grouped("## Sub Heading");
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0].kind, BlockKind::Heading { level: 2, text } if text == "Sub Heading")
        );
    }

    #[test]
    fn h3_heading() {
        let blocks = parse_grouped("### Small Heading");
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0].kind, BlockKind::Heading { level: 3, text } if text == "Small Heading")
        );
    }

    #[test]
    fn heading_requires_space() {
        let blocks = parse_grouped("#NoSpace");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn all_heading_levels() {
        for level in 1..=6u8 {
            let input = format!("{} Heading {}", "#".repeat(level as usize), level);
            let blocks = parse_grouped(&input);
            assert_eq!(blocks.len(), 1);
            if let BlockKind::Heading { level: l, text: _ } = &blocks[0].kind {
                assert_eq!(*l, level);
            } else {
                panic!("Expected heading for level {}", level);
            }
        }
    }

    // MARK: - Code blocks

    #[test]
    fn code_block_with_language() {
        let blocks = parse_grouped("```swift\nlet x = 1\n```");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { language, code } = &blocks[0].kind {
            assert_eq!(language.as_deref(), Some("swift"));
            assert_eq!(code, "let x = 1");
        } else {
            panic!("Expected code block");
        }
    }

    #[test]
    fn code_block_no_language() {
        let blocks = parse_grouped("```\nsome code\n```");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { language, code } = &blocks[0].kind {
            assert!(language.is_none());
            assert_eq!(code, "some code");
        } else {
            panic!("Expected code block");
        }
    }

    #[test]
    fn code_block_language_first_word_only() {
        let blocks = parse_grouped("```python3 interactive\nprint('hi')\n```");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { language, .. } = &blocks[0].kind {
            assert_eq!(language.as_deref(), Some("python3"));
        } else {
            panic!("Expected code block");
        }
    }

    #[test]
    fn unclosed_code_block() {
        let blocks = parse_grouped("```\nno closing fence");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { code, .. } = &blocks[0].kind {
            assert_eq!(code, "no closing fence");
        } else {
            panic!("Expected code block");
        }
    }

    // MARK: - Tables

    #[test]
    fn simple_table() {
        let input = "| A | B |\n| --- | --- |\n| 1 | 2 |";
        let blocks = parse_grouped(input);
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Table { headers, rows, .. } = &blocks[0].kind {
            assert_eq!(headers, &["A", "B"]);
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0], &["1", "2"]);
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn table_with_alignments() {
        let input = "| Left | Center | Right |\n| :--- | :---: | ---: |\n| a | b | c |";
        let blocks = parse_grouped(input);
        if let BlockKind::Table { alignments, .. } = &blocks[0].kind {
            assert_eq!(
                alignments,
                &[
                    ColumnAlignment::Left,
                    ColumnAlignment::Center,
                    ColumnAlignment::Right
                ]
            );
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn table_column_limit_enforced() {
        // A 3-column table should parse normally
        let small = "| A | B | C |\n| --- | --- | --- |\n| 1 | 2 | 3 |";
        let blocks = parse_grouped(small);
        assert!(matches!(&blocks[0].kind, BlockKind::Table { .. }));

        // Verify the constant is 20
        assert_eq!(super::MAX_TABLE_COLUMNS, 20);
    }

    // MARK: - Horizontal rule

    #[test]
    fn hr_dashes() {
        let blocks = parse_grouped("---");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(blocks[0].kind, BlockKind::HorizontalRule));
    }

    #[test]
    fn hr_stars() {
        let blocks = parse_grouped("***");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(blocks[0].kind, BlockKind::HorizontalRule));
    }

    #[test]
    fn hr_underscores() {
        let blocks = parse_grouped("___");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(blocks[0].kind, BlockKind::HorizontalRule));
    }

    // MARK: - Blockquote

    #[test]
    fn blockquote_single_line() {
        let blocks = parse_grouped("> Hello");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Blockquote { text } = &blocks[0].kind {
            assert_eq!(text, "Hello");
        } else {
            panic!("Expected blockquote");
        }
    }

    #[test]
    fn blockquote_multiline() {
        let blocks = parse_grouped("> line 1\n> line 2");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Blockquote { text } = &blocks[0].kind {
            assert_eq!(text, "line 1\nline 2");
        } else {
            panic!("Expected blockquote");
        }
    }

    // MARK: - Checkbox

    #[test]
    fn checkbox_unchecked() {
        let blocks = parse_grouped("- [ ] task");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Checkbox { checked, text } = &blocks[0].kind {
            assert!(!checked);
            assert_eq!(text, "task");
        } else {
            panic!("Expected checkbox");
        }
    }

    #[test]
    fn checkbox_checked() {
        let blocks = parse_grouped("- [x] done");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Checkbox { checked, text } = &blocks[0].kind {
            assert!(checked);
            assert_eq!(text, "done");
        } else {
            panic!("Expected checkbox");
        }
    }

    // MARK: - Lists

    #[test]
    fn unordered_list() {
        let blocks = parse_grouped("- first\n- second\n- third");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::BulletList { items } = &blocks[0].kind {
            assert_eq!(items.len(), 3);
            assert_eq!(items[0].text, "first");
            assert_eq!(items[1].text, "second");
            assert_eq!(items[2].text, "third");
        } else {
            panic!("Expected bullet list");
        }
    }

    #[test]
    fn ordered_list() {
        let blocks = parse_grouped("1. first\n2. second");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::OrderedList { items, .. } = &blocks[0].kind {
            assert_eq!(items.len(), 2);
            assert_eq!(items[0].text, "first");
            assert_eq!(items[1].text, "second");
        } else {
            panic!("Expected ordered list");
        }
    }

    // MARK: - Editable mode

    #[test]
    fn editable_bullet_items() {
        let blocks = parse_editable("- first\n- second");
        assert_eq!(blocks.len(), 2);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { text } if text == "first"));
        assert!(matches!(&blocks[1].kind, BlockKind::BulletItem { text } if text == "second"));
    }

    #[test]
    fn editable_numbered_items() {
        let blocks = parse_editable("1. first\n2. second");
        assert_eq!(blocks.len(), 2);
        assert!(
            matches!(&blocks[0].kind, BlockKind::NumberedItem { number: 1, text } if text == "first")
        );
        assert!(
            matches!(&blocks[1].kind, BlockKind::NumberedItem { number: 2, text } if text == "second")
        );
    }

    // MARK: - Nested lists (deep indentation)

    /// Returns the block's list-marker indent, panicking if the block has
    /// no marker metadata (i.e. it isn't a list/checkbox item).
    fn marker_indent(block: &BlockNode) -> u32 {
        block
            .list_marker
            .as_ref()
            .expect("expected list marker meta")
            .indent
    }

    #[test]
    fn nested_bullets_two_space_steps() {
        let blocks = parse_editable("- a\n  - b\n    - c");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { text } if text == "a"));
        assert!(matches!(&blocks[1].kind, BlockKind::BulletItem { text } if text == "b"));
        assert!(matches!(&blocks[2].kind, BlockKind::BulletItem { text } if text == "c"));
        assert_eq!(marker_indent(&blocks[0]), 0);
        assert_eq!(marker_indent(&blocks[1]), 2);
        assert_eq!(marker_indent(&blocks[2]), 4);
    }

    #[test]
    fn nested_bullet_four_space_is_list_item_not_code() {
        // Previously degenerate: `    - b` parsed as an indented code block.
        let blocks = parse_editable("- a\n    - b");
        assert_eq!(blocks.len(), 2);
        assert!(matches!(&blocks[1].kind, BlockKind::BulletItem { text } if text == "b"));
        assert_eq!(marker_indent(&blocks[1]), 4);
    }

    #[test]
    fn nested_bullet_six_space() {
        let blocks = parse_editable("- a\n    - b\n      - c");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[2].kind, BlockKind::BulletItem { text } if text == "c"));
        assert_eq!(marker_indent(&blocks[2]), 6);
    }

    #[test]
    fn standalone_deep_bullet_is_list_item() {
        // Deliberate deviation from CommonMark §4.4: a 4-space-indented
        // marker line is a list item even without a parent list.
        let blocks = parse_editable("    - item");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { text } if text == "item"));
        assert_eq!(marker_indent(&blocks[0]), 4);
    }

    #[test]
    fn nested_ordered_under_ordered_three_space() {
        // 3-space nesting always worked; regression guard.
        let blocks = parse_editable("1. a\n   1. b");
        assert_eq!(blocks.len(), 2);
        assert!(
            matches!(&blocks[1].kind, BlockKind::NumberedItem { number: 1, text } if text == "b")
        );
        assert_eq!(marker_indent(&blocks[1]), 3);
    }

    #[test]
    fn nested_ordered_under_ordered_four_space() {
        let blocks = parse_editable("1. a\n    1. b\n    2. c\n2. d");
        assert_eq!(blocks.len(), 4);
        assert!(
            matches!(&blocks[1].kind, BlockKind::NumberedItem { number: 1, text } if text == "b")
        );
        assert!(
            matches!(&blocks[2].kind, BlockKind::NumberedItem { number: 2, text } if text == "c")
        );
        assert!(
            matches!(&blocks[3].kind, BlockKind::NumberedItem { number: 2, text } if text == "d")
        );
        assert_eq!(marker_indent(&blocks[1]), 4);
        assert_eq!(marker_indent(&blocks[3]), 0);
    }

    #[test]
    fn nested_checkbox_under_bullet() {
        // Previously degenerate: the indented checkbox line became code.
        let blocks = parse_editable("- a\n    - [ ] task\n    - [x] done");
        assert_eq!(blocks.len(), 3);
        assert!(
            matches!(&blocks[1].kind, BlockKind::Checkbox { checked: false, text } if text == "task")
        );
        assert!(
            matches!(&blocks[2].kind, BlockKind::Checkbox { checked: true, text } if text == "done")
        );
        assert_eq!(marker_indent(&blocks[1]), 4);
        assert_eq!(marker_indent(&blocks[2]), 4);
    }

    #[test]
    fn nested_mixed_marker_kinds() {
        let blocks = parse_editable("- a\n    1. b\n        - [ ] c");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { .. }));
        assert!(matches!(&blocks[1].kind, BlockKind::NumberedItem { .. }));
        assert!(matches!(&blocks[2].kind, BlockKind::Checkbox { .. }));
        assert_eq!(marker_indent(&blocks[1]), 4);
        assert_eq!(marker_indent(&blocks[2]), 8);
    }

    #[test]
    fn tab_indented_bullet_is_list_item() {
        // A tab expands to the next multiple-of-4 column for the depth cap,
        // but the reported indent stays the CHARACTER count (1 tab = 1 char)
        // because hosts consume it as a text range length.
        let blocks = parse_editable("- a\n\t- b\n\t\t- c");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[1].kind, BlockKind::BulletItem { text } if text == "b"));
        assert!(matches!(&blocks[2].kind, BlockKind::BulletItem { text } if text == "c"));
        assert_eq!(marker_indent(&blocks[1]), 1);
        assert_eq!(marker_indent(&blocks[2]), 2);
    }

    #[test]
    fn mixed_space_tab_indent() {
        // "  \t" = column 2, then tab advances to column 4 → 3 chars.
        let blocks = parse_editable("  \t- x");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { text } if text == "x"));
        assert_eq!(marker_indent(&blocks[0]), 3);
        let meta = blocks[0].list_marker.as_ref().unwrap();
        assert_eq!(meta.marker_utf16_start, 3);
        assert_eq!(meta.marker_utf16_end, 5);
        assert_eq!(meta.marker_source, "- ");
    }

    #[test]
    fn deep_marker_range_excludes_indentation() {
        let blocks = parse_editable("    - b");
        let meta = blocks[0].list_marker.as_ref().unwrap();
        assert_eq!(meta.indent, 4);
        assert_eq!(meta.marker_utf16_start, 4);
        assert_eq!(meta.marker_utf16_end, 6);
        assert_eq!(meta.marker_source, "- ");
    }

    #[test]
    fn six_plus_nesting_levels() {
        let mut src = String::new();
        for level in 0..7 {
            src.push_str(&" ".repeat(level * 4));
            src.push_str(&format!("- level {}\n", level));
        }
        let blocks = parse_editable(&src);
        assert_eq!(blocks.len(), 7);
        for (level, block) in blocks.iter().enumerate() {
            assert!(
                matches!(&block.kind, BlockKind::BulletItem { text } if *text == format!("level {}", level)),
                "level {} misparsed: {:?}",
                level,
                block.kind
            );
            assert_eq!(marker_indent(block), (level * 4) as u32);
        }
    }

    #[test]
    fn indent_cap_at_32_columns() {
        // 32 columns: still a list item.
        let at_cap = format!("{}- ok", " ".repeat(32));
        let blocks = parse_editable(&at_cap);
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletItem { text } if text == "ok"));
        assert_eq!(marker_indent(&blocks[0]), 32);

        // 33 columns: past the cap → historical indented-code behavior.
        let past_cap = format!("{}- too deep", " ".repeat(33));
        let blocks = parse_editable(&past_cap);
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::CodeBlock { .. }));

        // 9 tabs = 36 columns: past the cap too.
        let tabs = format!("{}- too deep", "\t".repeat(9));
        let blocks = parse_editable(&tabs);
        assert!(matches!(&blocks[0].kind, BlockKind::CodeBlock { .. }));
    }

    #[test]
    fn attachment_carrier_line_is_paragraph_not_code() {
        // After the host editor injects a marker attachment, a nested list
        // line becomes `    \u{FFFC}text`. It must re-parse as a paragraph
        // (the editor styles marker layout from the attachment), never as
        // an indented code block.
        let blocks = parse_editable("    \u{FFFC}text");
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0].kind, BlockKind::Paragraph { .. }),
            "expected paragraph, got {:?}",
            blocks[0].kind
        );

        // Tab-prefixed carrier line too.
        let blocks = parse_editable("\t\u{FFFC}text");
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn deep_indent_plain_text_still_code() {
        // Non-marker indented lines keep CommonMark indented-code behavior.
        let blocks = parse_editable("    let x = 1");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::CodeBlock { .. }));
    }

    #[test]
    fn indented_code_run_broken_by_nested_list_line() {
        // A marker line inside an indented run splits the code block.
        let blocks = parse_editable("    code one\n    - item\n    code two");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0].kind, BlockKind::CodeBlock { code, .. } if code == "code one"));
        assert!(matches!(&blocks[1].kind, BlockKind::BulletItem { text } if text == "item"));
        assert!(matches!(&blocks[2].kind, BlockKind::CodeBlock { code, .. } if code == "code two"));
    }

    #[test]
    fn grouped_nested_bullets_not_flattened() {
        // Previously the nested line was glued onto the previous item's
        // text ("a - b"). Now each marker line is its own item.
        let blocks = parse_grouped("- a\n    - b\n- c");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::BulletList { items } = &blocks[0].kind {
            let texts: Vec<&str> = items.iter().map(|i| i.text.as_str()).collect();
            assert_eq!(texts, vec!["a", "b", "c"]);
        } else {
            panic!("Expected bullet list, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn grouped_nested_checkbox_splits_bullet_run() {
        let blocks = parse_grouped("- a\n    - [ ] t\n- b");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletList { .. }));
        assert!(
            matches!(&blocks[1].kind, BlockKind::Checkbox { checked: false, text } if text == "t")
        );
        assert!(matches!(&blocks[2].kind, BlockKind::BulletList { .. }));
        assert_eq!(marker_indent(&blocks[1]), 4);
    }

    #[test]
    fn grouped_nested_ordered_separate_run() {
        let blocks = parse_grouped("- a\n    1. b");
        assert_eq!(blocks.len(), 2);
        assert!(matches!(&blocks[0].kind, BlockKind::BulletList { .. }));
        if let BlockKind::OrderedList { items, .. } = &blocks[1].kind {
            assert_eq!(items.len(), 1);
            assert_eq!(items[0].text, "b");
        } else {
            panic!("Expected ordered list, got {:?}", blocks[1].kind);
        }
    }

    #[test]
    fn toggle_nested_checkbox() {
        let toggled = toggle_checkbox("- a\n    - [ ] task", 1);
        assert_eq!(toggled, "- a\n    - [x] task");
        let toggled_back = toggle_checkbox(&toggled, 1);
        assert_eq!(toggled_back, "- a\n    - [ ] task");
    }

    #[test]
    fn toggle_tab_indented_checkbox() {
        let toggled = toggle_checkbox("- a\n\t- [ ] task", 1);
        assert_eq!(toggled, "- a\n\t- [x] task");
    }

    // MARK: - Paragraph

    #[test]
    fn simple_paragraph() {
        let blocks = parse_grouped("Hello world");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { text } if text == "Hello world"));
    }

    #[test]
    fn multiline_paragraph() {
        let blocks = parse_grouped("Line one\nLine two");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Paragraph { text } = &blocks[0].kind {
            assert_eq!(text, "Line one\nLine two");
        } else {
            panic!("Expected paragraph");
        }
    }

    // MARK: - Empty

    #[test]
    fn empty_line() {
        let blocks = parse_grouped("before\n\nafter");
        assert_eq!(blocks.len(), 3);
        assert!(matches!(blocks[1].kind, BlockKind::Empty));
    }

    // MARK: - Footnote definition

    #[test]
    fn footnote_def() {
        let blocks = parse_grouped("[^1]: Some footnote text");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::FootnoteDefinition { label, text } = &blocks[0].kind {
            assert_eq!(label, "1");
            assert_eq!(text, "Some footnote text");
        } else {
            panic!("Expected footnote definition");
        }
    }

    // MARK: - UTF-16 offsets

    #[test]
    fn utf16_offsets_ascii() {
        let blocks = parse_grouped("# Hello\nworld");
        assert_eq!(blocks[0].utf16_start, 0);
        assert_eq!(blocks[0].utf16_end, 8); // "# Hello\n" = 8 UTF-16 units
        assert_eq!(blocks[1].utf16_start, 8);
    }

    // MARK: - Mixed content

    #[test]
    fn mixed_document() {
        let input = "# Title\n\nSome text\n\n- item 1\n- item 2\n\n> quote\n\n---";
        let blocks = parse_grouped(input);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 1, .. }
        ));
        assert!(matches!(blocks[1].kind, BlockKind::Empty));
        assert!(matches!(&blocks[2].kind, BlockKind::Paragraph { .. }));
        assert!(matches!(blocks[3].kind, BlockKind::Empty));
        assert!(matches!(&blocks[4].kind, BlockKind::BulletList { .. }));
        assert!(matches!(blocks[5].kind, BlockKind::Empty));
        assert!(matches!(&blocks[6].kind, BlockKind::Blockquote { .. }));
        assert!(matches!(blocks[7].kind, BlockKind::Empty));
        assert!(matches!(blocks[8].kind, BlockKind::HorizontalRule));
    }

    // MARK: - Wiki links

    #[test]
    fn extract_wiki_links_basic() {
        let links = extract_wiki_links("see [[Note One]] and [[Note Two]]");
        assert_eq!(links, vec!["Note One", "Note Two"]);
    }

    #[test]
    fn extract_wiki_links_skips_code() {
        let links = extract_wiki_links("text `[[not a link]]` and [[real link]]");
        assert_eq!(links, vec!["real link"]);
    }

    #[test]
    fn extract_wiki_links_skips_code_block() {
        let links = extract_wiki_links("text\n```\n[[not a link]]\n```\n[[real]]");
        assert_eq!(links, vec!["real"]);
    }

    #[test]
    fn extract_wiki_link_alias_uses_target() {
        // `[[Project Apollo|the moon shot]]` — the target (pre-pipe) is the
        // backlink anchor; the post-pipe text is just display.
        let links = extract_wiki_links("see [[Project Apollo|the moon shot]] today");
        assert_eq!(links, vec!["Project Apollo"]);
    }

    #[test]
    fn extract_wiki_link_alias_mixed_with_bare() {
        let links = extract_wiki_links("[[Foo|first alias]] and [[Bar]] and [[Foo|second alias]]");
        // Each `[[...]]` yields its target; dedup happens at the document level
        // (see `extract_wiki_links_from_doc`), not in this per-segment helper.
        assert_eq!(links, vec!["Foo", "Bar", "Foo"]);
    }

    #[test]
    fn extract_wiki_link_empty_target_with_alias_ignored() {
        // `[[|alias]]` has empty target and must not produce a backlink.
        let links = extract_wiki_links("garbage [[|only alias]] end");
        assert!(
            links.is_empty(),
            "Empty target should produce no backlink, got {:?}",
            links
        );
    }

    // MARK: - Toggle checkbox

    #[test]
    fn toggle_checkbox_check() {
        let result = toggle_checkbox("- [ ] task", 0);
        assert_eq!(result, "- [x] task");
    }

    #[test]
    fn toggle_checkbox_uncheck() {
        let result = toggle_checkbox("- [x] task", 0);
        assert_eq!(result, "- [ ] task");
    }

    // MARK: - Setext headings (CommonMark §4.3)

    #[test]
    fn setext_h1_equals() {
        let blocks = parse_grouped("Title\n=====");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Heading { level, text } = &blocks[0].kind {
            assert_eq!(*level, 1);
            assert_eq!(text, "Title");
        } else {
            panic!("Expected setext H1, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn setext_h2_dashes() {
        let blocks = parse_grouped("Subtitle\n---");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Heading { level, text } = &blocks[0].kind {
            assert_eq!(*level, 2);
            assert_eq!(text, "Subtitle");
        } else {
            panic!("Expected setext H2, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn setext_single_equals_is_h1() {
        // CommonMark: any number of = (≥1) makes a level-1 setext heading.
        let blocks = parse_grouped("Hi\n=");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 1, .. }
        ));
    }

    #[test]
    fn setext_with_leading_spaces_in_underline() {
        // 0-3 leading spaces on the underline are allowed.
        let blocks = parse_grouped("Title\n   ====");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 1, .. }
        ));
    }

    #[test]
    fn setext_underline_with_trailing_whitespace() {
        let blocks = parse_grouped("Title\n===   ");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 1, .. }
        ));
    }

    #[test]
    fn setext_h2_wins_over_thematic_break() {
        // `Foo\n---` — the `---` looks like a thematic break, but a preceding
        // paragraph means it's a setext H2 (CommonMark spec resolution).
        let blocks = parse_grouped("Foo\n---");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 2, .. }
        ));
    }

    #[test]
    fn setext_heading_followed_by_paragraph() {
        let blocks = parse_grouped("Foo\n---\nbar");
        assert_eq!(blocks.len(), 2);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Heading { level: 2, .. }
        ));
        assert!(matches!(&blocks[1].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn setext_after_blank_line_is_thematic_break() {
        // Blank line breaks the paragraph; `---` then becomes a thematic break.
        let blocks = parse_grouped("Foo\n\n---");
        // [Paragraph "Foo", Empty, HorizontalRule]
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
        assert!(matches!(blocks[2].kind, BlockKind::HorizontalRule));
    }

    #[test]
    fn setext_no_match_when_no_paragraph_above() {
        // Just `===` alone has no preceding paragraph; treated as paragraph.
        let blocks = parse_grouped("===");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn setext_multiline_paragraph_heading() {
        let blocks = parse_grouped("Foo\nBar\n===");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Heading { level, text } = &blocks[0].kind {
            assert_eq!(*level, 1);
            assert_eq!(text, "Foo\nBar");
        } else {
            panic!(
                "Expected multi-line setext heading, got {:?}",
                blocks[0].kind
            );
        }
    }

    // MARK: - Indented code blocks (CommonMark §4.4)

    #[test]
    fn indented_code_block_basic() {
        let blocks = parse_grouped("    let x = 1");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { language, code } = &blocks[0].kind {
            assert!(language.is_none());
            assert_eq!(code, "let x = 1");
        } else {
            panic!("Expected indented code block, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn indented_code_with_tab() {
        let blocks = parse_grouped("\tlet x = 1");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::CodeBlock { .. }));
    }

    #[test]
    fn indented_code_multi_line() {
        let blocks = parse_grouped("    line one\n    line two\n    line three");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { code, .. } = &blocks[0].kind {
            assert_eq!(code, "line one\nline two\nline three");
        } else {
            panic!("Expected indented code block");
        }
    }

    #[test]
    fn indented_code_includes_internal_blank_line() {
        let blocks = parse_grouped("    line one\n\n    line three");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { code, .. } = &blocks[0].kind {
            assert_eq!(code, "line one\n\nline three");
        } else {
            panic!("Expected single indented code block, got {:?}", blocks);
        }
    }

    #[test]
    fn indented_code_strips_trailing_blanks() {
        let blocks = parse_grouped("    code\n\n\nparagraph");
        // [CodeBlock "code", Empty, Empty, Paragraph]
        assert!(blocks.len() >= 2);
        if let BlockKind::CodeBlock { code, .. } = &blocks[0].kind {
            assert_eq!(code, "code");
        } else {
            panic!("Expected indented code block, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn three_space_indent_is_paragraph_not_code() {
        // Only 4+ spaces qualify; 3 spaces is paragraph text.
        let blocks = parse_grouped("   not code");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn indented_code_cannot_interrupt_paragraph() {
        // The indented line is a continuation of the paragraph, not a new code block.
        let blocks = parse_grouped("paragraph\n    not code");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Paragraph { text } = &blocks[0].kind {
            assert!(text.contains("not code"));
        } else {
            panic!("Expected paragraph, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn indented_code_preserves_extra_indent() {
        // Spaces beyond the first 4 belong to the code content.
        let blocks = parse_grouped("        deep indent");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::CodeBlock { code, .. } = &blocks[0].kind {
            assert_eq!(code, "    deep indent");
        } else {
            panic!("Expected indented code block");
        }
    }

    // MARK: - Source preservation regressions
    //
    // The editor renders source text verbatim; the SwiftUI preview defers to
    // `AttributedString(markdown:)` (Apple's CommonMark parser). For both
    // paths to render correctly, the parser must preserve the raw bytes that
    // CommonMark assigns special meaning to — trailing-space hard breaks,
    // backslash hard breaks, and HTML entity references.

    #[test]
    fn paragraph_preserves_two_space_hard_break() {
        // Two trailing spaces + newline — `AttributedString(markdown:)` treats
        // this as a hard line break. We must keep both spaces in the joined text.
        let input = "line one  \nline two";
        let blocks = parse_grouped(input);
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Paragraph { text } = &blocks[0].kind {
            assert_eq!(
                text, "line one  \nline two",
                "Trailing spaces must survive line join"
            );
        } else {
            panic!("Expected paragraph, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn paragraph_preserves_backslash_hard_break() {
        // Trailing backslash + newline — also a CommonMark hard line break.
        let input = "line one\\\nline two";
        let blocks = parse_grouped(input);
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Paragraph { text } = &blocks[0].kind {
            assert_eq!(text, "line one\\\nline two");
        } else {
            panic!("Expected paragraph, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn paragraph_preserves_html_entities() {
        // Entities pass through unchanged so the preview path can decode them.
        let input = "5 &amp; 6 &lt; 10 &#x2603;";
        let blocks = parse_grouped(input);
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Paragraph { text } = &blocks[0].kind {
            assert_eq!(text, "5 &amp; 6 &lt; 10 &#x2603;");
        } else {
            panic!("Expected paragraph, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn setext_underline_strips_inline_scan() {
        // The underline must not be inline-scanned (otherwise `==` triggers highlight).
        let doc = parse("Title\n===", ParseMode::Grouped);
        assert_eq!(doc.blocks.len(), 1);
        // No inline spans should be created from the `===` underline.
        let highlights: Vec<_> = doc.blocks[0]
            .inline_spans
            .iter()
            .filter(|s| matches!(s.kind, InlineKind::Highlight))
            .collect();
        assert!(
            highlights.is_empty(),
            "Setext underline must be excluded from inline scan"
        );
    }

    // MARK: - Callouts

    #[test]
    fn callout_note_no_title_no_body() {
        let blocks = parse_grouped("> [!note]");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Callout { kind, title, text } = &blocks[0].kind {
            assert_eq!(*kind, CalloutKind::Note);
            assert!(title.is_none());
            assert_eq!(text, "");
        } else {
            panic!("Expected Callout, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn callout_tip_with_title() {
        let blocks = parse_grouped("> [!tip] Pro tip for you");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Callout { kind, title, .. } = &blocks[0].kind {
            assert_eq!(*kind, CalloutKind::Tip);
            assert_eq!(title.as_deref(), Some("Pro tip for you"));
        } else {
            panic!("Expected Callout");
        }
    }

    #[test]
    fn callout_warning_with_body() {
        let blocks = parse_grouped("> [!warning]\n> Watch out\n> for storms");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Callout { kind, title, text } = &blocks[0].kind {
            assert_eq!(*kind, CalloutKind::Warning);
            assert!(title.is_none());
            assert_eq!(text, "Watch out\nfor storms");
        } else {
            panic!("Expected Callout");
        }
    }

    #[test]
    fn callout_important_with_title_and_body() {
        let blocks = parse_grouped("> [!important] Read carefully\n> This matters");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Callout { kind, title, text } = &blocks[0].kind {
            assert_eq!(*kind, CalloutKind::Important);
            assert_eq!(title.as_deref(), Some("Read carefully"));
            assert_eq!(text, "This matters");
        } else {
            panic!("Expected Callout");
        }
    }

    #[test]
    fn callout_caution_case_insensitive_kind() {
        let blocks = parse_grouped("> [!CAUTION] Big deal");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(
            &blocks[0].kind,
            BlockKind::Callout {
                kind: CalloutKind::Caution,
                ..
            }
        ));
    }

    #[test]
    fn callout_all_five_kinds() {
        for (name, expected) in [
            ("note", CalloutKind::Note),
            ("tip", CalloutKind::Tip),
            ("warning", CalloutKind::Warning),
            ("important", CalloutKind::Important),
            ("caution", CalloutKind::Caution),
        ] {
            let input = format!("> [!{}]", name);
            let blocks = parse_grouped(&input);
            assert_eq!(blocks.len(), 1, "kind={}", name);
            if let BlockKind::Callout { kind, .. } = &blocks[0].kind {
                assert_eq!(*kind, expected, "kind={}", name);
            } else {
                panic!("Expected Callout for {}", name);
            }
        }
    }

    #[test]
    fn unknown_callout_kind_degrades_to_blockquote() {
        let blocks = parse_grouped("> [!nonsense] Not a callout\n> just a quote");
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0].kind, BlockKind::Blockquote { .. }));
    }

    #[test]
    fn regular_blockquote_still_works() {
        let blocks = parse_grouped("> Just a quote\n> with two lines");
        assert_eq!(blocks.len(), 1);
        if let BlockKind::Blockquote { text } = &blocks[0].kind {
            assert_eq!(text, "Just a quote\nwith two lines");
        } else {
            panic!("Expected Blockquote, got {:?}", blocks[0].kind);
        }
    }

    #[test]
    fn three_dashes_at_bof_is_thematic_break() {
        // Previously the parser carved a YAML frontmatter block out of `---`
        // fences at BOF. That support has been removed; a leading `---` now
        // behaves as a normal thematic break, and a second `---` on a later
        // line is either a thematic break or a setext underline per spec.
        let blocks = parse_grouped("---\ntitle: example\n---\nbody");
        assert!(matches!(&blocks[0].kind, BlockKind::HorizontalRule));
        // `title: example` on line 2 followed by `---` on line 3 still forms
        // a setext H2 (the ambiguity resolved in setext's favor).
        assert!(blocks
            .iter()
            .any(|b| matches!(&b.kind, BlockKind::Heading { level: 2, .. })));
    }

    #[test]
    fn callout_fold_markers_stripped() {
        // `[!note]+` and `[!note]-` both parse as Note; the +/- is consumed.
        let open = parse_grouped("> [!note]+ Expanded");
        assert!(matches!(
            &open[0].kind,
            BlockKind::Callout {
                kind: CalloutKind::Note,
                ..
            }
        ));
        if let BlockKind::Callout { title, .. } = &open[0].kind {
            assert_eq!(title.as_deref(), Some("Expanded"));
        }
        let closed = parse_grouped("> [!note]- Collapsed");
        assert!(matches!(
            &closed[0].kind,
            BlockKind::Callout {
                kind: CalloutKind::Note,
                ..
            }
        ));
    }

    // MARK: - Regression checks across the five delight features

    #[test]
    fn callout_works_in_editable_mode() {
        let blocks = parse_editable("> [!tip] Hey\n> body line");
        assert!(blocks
            .iter()
            .any(|b| matches!(&b.kind, BlockKind::Callout { .. })));
    }

    #[test]
    fn double_percent_in_text_without_closer_is_not_comment() {
        // `50%%` alone is a single unmatched `%%` — no comment should form.
        let blocks = parse_grouped("reached 50%% utilization today");
        assert!(
            blocks[0]
                .inline_spans
                .iter()
                .all(|s| !matches!(s.kind, crate::ast::InlineKind::Comment)),
            "Unmatched %% must not create a Comment span"
        );
    }

    #[test]
    fn hex_color_does_not_eat_trailing_markdown() {
        // `#ff0000 **bold**` — hex span claims only the hex token; bold still parses.
        let blocks = parse_grouped("#ff0000 **bold**");
        let spans = &blocks[0].inline_spans;
        assert!(spans
            .iter()
            .any(|s| matches!(&s.kind, crate::ast::InlineKind::HexColor { .. })));
        assert!(spans
            .iter()
            .any(|s| matches!(&s.kind, crate::ast::InlineKind::Bold)));
    }

    #[test]
    fn wiki_alias_inside_blockquote_works() {
        let blocks = parse_grouped("> see [[Target|Display]] today");
        if let BlockKind::Blockquote { .. } = &blocks[0].kind {
            assert!(blocks[0]
                .inline_spans
                .iter()
                .any(|s| matches!(s.kind, crate::ast::InlineKind::WikiLink)));
        } else {
            panic!("Expected Blockquote");
        }
    }

    // MARK: - Image marker

    fn ember_options() -> ParseOptions {
        ParseOptions {
            image_marker_scheme: Some("ember:".to_string()),
        }
    }

    fn parse_editable_ember(input: &str) -> Vec<BlockNode> {
        parse_with_options(input, ParseMode::Editable, &ember_options()).blocks
    }

    fn parse_grouped_ember(input: &str) -> Vec<BlockNode> {
        parse_with_options(input, ParseMode::Grouped, &ember_options()).blocks
    }

    #[test]
    fn image_marker_uppercase_uuid_recognised() {
        let blocks = parse_editable_ember("![](ember:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)\n");
        assert_eq!(
            blocks.len(),
            1,
            "marker should not be merged with empty trailing"
        );
        match &blocks[0].kind {
            BlockKind::ImageMarker { uuid } => {
                assert_eq!(uuid, "DEBD1746-CBBB-4A33-9CB0-4B1A5D956200");
            }
            other => panic!("expected ImageMarker, got {:?}", other),
        }
    }

    #[test]
    fn image_marker_lowercase_uuid_recognised() {
        let blocks = parse_editable_ember("![](ember:debd1746-cbbb-4a33-9cb0-4b1a5d956200)\n");
        assert!(matches!(&blocks[0].kind, BlockKind::ImageMarker { .. }));
    }

    #[test]
    fn image_marker_grouped_mode_recognised() {
        // Grouped mode is what preview surfaces consume; same dispatch rule.
        let blocks = parse_grouped_ember("![](ember:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)");
        assert!(matches!(&blocks[0].kind, BlockKind::ImageMarker { .. }));
    }

    #[test]
    fn image_marker_inside_paragraph_falls_through() {
        // Inline form (text on same line) is not a block marker — must
        // remain a Paragraph so editor surfaces don't accidentally tear
        // out a chunk of the user's prose.
        let blocks = parse_editable_ember(
            "look at this ![](ember:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200) inline\n",
        );
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn image_marker_malformed_uuid_falls_through() {
        let blocks = parse_editable_ember("![](ember:not-a-uuid)\n");
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn image_marker_wrong_scheme_falls_through() {
        let blocks = parse_editable_ember("![](other:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)\n");
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn image_marker_disabled_without_scheme() {
        // Default options: the extension is off and marker-shaped lines are
        // plain paragraphs — CommonMark-clean behavior for new adopters.
        let blocks = parse_editable("![](ember:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)\n");
        assert!(matches!(&blocks[0].kind, BlockKind::Paragraph { .. }));
    }

    #[test]
    fn image_marker_custom_scheme_recognised() {
        let options = ParseOptions {
            image_marker_scheme: Some("cinder:".to_string()),
        };
        let blocks = parse_with_options(
            "![](cinder:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)\n",
            ParseMode::Editable,
            &options,
        )
        .blocks;
        assert!(matches!(&blocks[0].kind, BlockKind::ImageMarker { .. }));
    }

    #[test]
    fn image_marker_in_document_alongside_other_blocks() {
        let src = "# Title\n\n![](ember:DEBD1746-CBBB-4A33-9CB0-4B1A5D956200)\n\nNext paragraph\n";
        let blocks = parse_editable_ember(src);
        let kinds: Vec<&BlockKind> = blocks.iter().map(|b| &b.kind).collect();
        assert!(matches!(kinds[0], BlockKind::Heading { .. }));
        // Empty line, then marker, then empty line, then paragraph — exact
        // count varies by mode but the marker must be present.
        assert!(blocks
            .iter()
            .any(|b| matches!(b.kind, BlockKind::ImageMarker { .. })));
        assert!(blocks
            .iter()
            .any(|b| matches!(b.kind, BlockKind::Paragraph { .. })));
    }
}