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
use crate::options::ParserOptions;
use crate::syntax::{SyntaxKind, SyntaxNode};
use rowan::GreenNodeBuilder;
use super::block_dispatcher::{
BlockContext, BlockDetectionResult, BlockEffect, BlockParserRegistry, BlockQuotePrepared,
PreparedBlockMatch,
};
use super::blocks::blockquotes;
use super::blocks::code_blocks;
use super::blocks::definition_lists;
use super::blocks::fenced_divs;
use super::blocks::headings::{emit_atx_heading, try_parse_atx_heading};
use super::blocks::line_blocks;
use super::blocks::lists;
use super::blocks::paragraphs;
use super::blocks::raw_blocks::{extract_environment_name, is_inline_math_environment};
use super::utils::container_stack;
use super::utils::helpers::{split_lines_inclusive, strip_newline};
use super::utils::inline_emission;
use super::utils::marker_utils;
use super::utils::text_buffer;
use super::blocks::blockquotes::strip_n_blockquote_markers;
use super::utils::continuation::ContinuationPolicy;
use container_stack::{Container, ContainerStack, byte_index_at_column, leading_indent};
use definition_lists::{emit_definition_marker, emit_term};
use line_blocks::{parse_line_block, try_parse_line_block_start};
use lists::{
ListItemEmissionInput, ListMarker, is_content_nested_bullet_marker, start_nested_list,
try_parse_list_marker,
};
use marker_utils::{count_blockquote_markers, parse_blockquote_marker_info};
use text_buffer::TextBuffer;
const GITHUB_ALERT_MARKERS: [&str; 5] = [
"[!TIP]",
"[!WARNING]",
"[!IMPORTANT]",
"[!CAUTION]",
"[!NOTE]",
];
pub struct Parser<'a> {
lines: Vec<&'a str>,
pos: usize,
builder: GreenNodeBuilder<'static>,
containers: ContainerStack,
config: &'a ParserOptions,
block_registry: BlockParserRegistry,
/// True when the previous block was a metadata block (YAML, Pandoc title, or MMD title).
/// The first line after a metadata block is treated as if it has a blank line before it,
/// matching Pandoc's behavior of allowing headings etc. directly after frontmatter.
after_metadata_block: bool,
}
impl<'a> Parser<'a> {
pub fn new(input: &'a str, config: &'a ParserOptions) -> Self {
// Use split_lines_inclusive to preserve line endings (both LF and CRLF)
let lines = split_lines_inclusive(input);
Self {
lines,
pos: 0,
builder: GreenNodeBuilder::new(),
containers: ContainerStack::new(),
config,
block_registry: BlockParserRegistry::new(),
after_metadata_block: false,
}
}
pub fn parse(mut self) -> SyntaxNode {
self.parse_document_stack();
SyntaxNode::new_root(self.builder.finish())
}
/// Emit buffered PLAIN content if Definition container has open PLAIN.
/// Close containers down to `keep`, emitting buffered content first.
fn close_containers_to(&mut self, keep: usize) {
// Emit buffered PARAGRAPH/PLAIN content before closing
while self.containers.depth() > keep {
match self.containers.stack.last() {
// Handle ListItem with buffering
Some(Container::ListItem { buffer, .. }) if !buffer.is_empty() => {
// Clone buffer to avoid borrow issues
let buffer_clone = buffer.clone();
log::debug!(
"Closing ListItem with buffer (is_empty={}, segment_count={})",
buffer_clone.is_empty(),
buffer_clone.segment_count()
);
// Determine if this should be Plain or PARAGRAPH:
// 1. Check if parent LIST has blank lines between items (list-level loose)
// 2. OR check if this item has blank lines within its content (item-level loose)
let parent_list_is_loose = self
.containers
.stack
.iter()
.rev()
.find_map(|c| match c {
Container::List {
has_blank_between_items,
..
} => Some(*has_blank_between_items),
_ => None,
})
.unwrap_or(false);
let use_paragraph =
parent_list_is_loose || buffer_clone.has_blank_lines_between_content();
log::debug!(
"Emitting ListItem buffer: use_paragraph={} (parent_list_is_loose={}, item_has_blanks={})",
use_paragraph,
parent_list_is_loose,
buffer_clone.has_blank_lines_between_content()
);
// Pop container first
self.containers.stack.pop();
// Emit buffered content as Plain or PARAGRAPH
buffer_clone.emit_as_block(&mut self.builder, use_paragraph, self.config);
self.builder.finish_node(); // Close LIST_ITEM
}
// Handle ListItem without content
Some(Container::ListItem { .. }) => {
log::debug!("Closing empty ListItem (no buffer content)");
// Just close normally (empty list item)
self.containers.stack.pop();
self.builder.finish_node();
}
// Handle Paragraph with buffering
Some(Container::Paragraph { buffer, .. }) if !buffer.is_empty() => {
// Clone buffer to avoid borrow issues
let buffer_clone = buffer.clone();
// Pop container first
self.containers.stack.pop();
// Emit buffered content with inline parsing (handles markers)
buffer_clone.emit_with_inlines(&mut self.builder, self.config);
self.builder.finish_node();
}
// Handle Paragraph without content
Some(Container::Paragraph { .. }) => {
// Just close normally
self.containers.stack.pop();
self.builder.finish_node();
}
// Handle Definition with buffered PLAIN
Some(Container::Definition {
plain_open: true,
plain_buffer,
..
}) if !plain_buffer.is_empty() => {
let text = plain_buffer.get_accumulated_text();
let line_without_newline = text
.strip_suffix("\r\n")
.or_else(|| text.strip_suffix('\n'));
if let Some(line) = line_without_newline
&& !line.contains('\n')
&& !line.contains('\r')
&& let Some(level) = try_parse_atx_heading(line)
{
emit_atx_heading(&mut self.builder, &text, level, self.config);
} else {
// Emit PLAIN node with buffered inline-parsed content
self.builder.start_node(SyntaxKind::PLAIN.into());
inline_emission::emit_inlines(&mut self.builder, &text, self.config);
self.builder.finish_node();
}
// Mark PLAIN as closed and clear buffer
if let Some(Container::Definition {
plain_open,
plain_buffer,
..
}) = self.containers.stack.last_mut()
{
plain_buffer.clear();
*plain_open = false;
}
// Pop container and finish node
self.containers.stack.pop();
self.builder.finish_node();
}
// Handle Definition with PLAIN open but empty buffer
Some(Container::Definition {
plain_open: true, ..
}) => {
// Mark PLAIN as closed
if let Some(Container::Definition {
plain_open,
plain_buffer,
..
}) = self.containers.stack.last_mut()
{
plain_buffer.clear();
*plain_open = false;
}
// Pop container and finish node
self.containers.stack.pop();
self.builder.finish_node();
}
// All other containers
_ => {
self.containers.stack.pop();
self.builder.finish_node();
}
}
}
}
/// Emit buffered PLAIN content if there's an open PLAIN in a Definition.
/// This is used when we need to close PLAIN but keep the Definition container open.
fn emit_buffered_plain_if_needed(&mut self) {
// Check if we have an open PLAIN with buffered content
if let Some(Container::Definition {
plain_open: true,
plain_buffer,
..
}) = self.containers.stack.last()
&& !plain_buffer.is_empty()
{
let text = plain_buffer.get_accumulated_text();
let line_without_newline = text
.strip_suffix("\r\n")
.or_else(|| text.strip_suffix('\n'));
if let Some(line) = line_without_newline
&& !line.contains('\n')
&& !line.contains('\r')
&& let Some(level) = try_parse_atx_heading(line)
{
emit_atx_heading(&mut self.builder, &text, level, self.config);
} else {
// Emit PLAIN node with buffered inline-parsed content
self.builder.start_node(SyntaxKind::PLAIN.into());
inline_emission::emit_inlines(&mut self.builder, &text, self.config);
self.builder.finish_node();
}
}
// Mark PLAIN as closed and clear buffer
if let Some(Container::Definition {
plain_open,
plain_buffer,
..
}) = self.containers.stack.last_mut()
&& *plain_open
{
plain_buffer.clear();
*plain_open = false;
}
}
/// Close blockquotes down to a target depth.
///
/// Must use `Parser::close_containers_to` (not `ContainerStack::close_to`) so list/paragraph
/// buffers are emitted for losslessness.
fn close_blockquotes_to_depth(&mut self, target_depth: usize) {
let mut current = self.current_blockquote_depth();
while current > target_depth {
while !matches!(self.containers.last(), Some(Container::BlockQuote { .. })) {
if self.containers.depth() == 0 {
break;
}
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::BlockQuote { .. })) {
self.close_containers_to(self.containers.depth() - 1);
current -= 1;
} else {
break;
}
}
}
fn active_alert_blockquote_depth(&self) -> Option<usize> {
self.containers.stack.iter().rev().find_map(|c| match c {
Container::Alert { blockquote_depth } => Some(*blockquote_depth),
_ => None,
})
}
fn in_active_alert(&self) -> bool {
self.active_alert_blockquote_depth().is_some()
}
fn previous_block_requires_blank_before_heading(&self) -> bool {
matches!(
self.containers.last(),
Some(Container::Paragraph { .. })
| Some(Container::ListItem { .. })
| Some(Container::Definition { .. })
| Some(Container::DefinitionItem { .. })
| Some(Container::FootnoteDefinition { .. })
)
}
fn alert_marker_from_content(content: &str) -> Option<&'static str> {
let (without_newline, _) = strip_newline(content);
let trimmed = without_newline.trim();
GITHUB_ALERT_MARKERS
.into_iter()
.find(|marker| *marker == trimmed)
}
/// Emit buffered list item content if we're in a ListItem and it has content.
/// This is used before starting block-level elements inside list items.
fn emit_list_item_buffer_if_needed(&mut self) {
if let Some(Container::ListItem { buffer, .. }) = self.containers.stack.last_mut()
&& !buffer.is_empty()
{
let buffer_clone = buffer.clone();
buffer.clear();
let use_paragraph = buffer_clone.has_blank_lines_between_content();
buffer_clone.emit_as_block(&mut self.builder, use_paragraph, self.config);
}
}
/// Check if a paragraph is currently open.
fn is_paragraph_open(&self) -> bool {
matches!(self.containers.last(), Some(Container::Paragraph { .. }))
}
/// Close paragraph if one is currently open.
fn close_paragraph_if_open(&mut self) {
if self.is_paragraph_open() {
self.close_containers_to(self.containers.depth() - 1);
}
}
/// Prepare for a block-level element by flushing buffers and closing paragraphs.
/// This is a common pattern before starting tables, code blocks, divs, etc.
fn prepare_for_block_element(&mut self) {
self.emit_list_item_buffer_if_needed();
self.close_paragraph_if_open();
}
fn handle_footnote_open_effect(
&mut self,
block_match: &super::block_dispatcher::PreparedBlockMatch,
content: &str,
) {
let content_start = block_match
.payload
.as_ref()
.and_then(|p| p.downcast_ref::<super::block_dispatcher::FootnoteDefinitionPrepared>())
.map(|p| p.content_start)
.unwrap_or(0);
while matches!(
self.containers.last(),
Some(Container::FootnoteDefinition { .. })
) {
self.close_containers_to(self.containers.depth() - 1);
}
let content_col = 4;
self.containers
.push(Container::FootnoteDefinition { content_col });
if content_start > 0 {
let first_line_content = &content[content_start..];
if !first_line_content.trim().is_empty() {
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
first_line_content,
self.config,
);
} else {
let (_, newline_str) = strip_newline(content);
if !newline_str.is_empty() {
self.builder.token(SyntaxKind::NEWLINE.into(), newline_str);
}
}
}
}
fn handle_list_open_effect(
&mut self,
block_match: &super::block_dispatcher::PreparedBlockMatch,
content: &str,
indent_to_emit: Option<&str>,
) {
use super::block_dispatcher::ListPrepared;
let prepared = block_match
.payload
.as_ref()
.and_then(|p| p.downcast_ref::<ListPrepared>());
let Some(prepared) = prepared else {
return;
};
if prepared.indent_cols >= 4 && !lists::in_list(&self.containers) {
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
content,
self.config,
);
return;
}
if self.is_paragraph_open() {
if !block_match.detection.eq(&BlockDetectionResult::Yes) {
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
content,
self.config,
);
return;
}
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(
self.containers.last(),
Some(Container::Definition {
plain_open: true,
..
})
) {
self.emit_buffered_plain_if_needed();
}
let matched_level = lists::find_matching_list_level(
&self.containers,
&prepared.marker,
prepared.indent_cols,
);
let list_item = ListItemEmissionInput {
content,
marker_len: prepared.marker_len,
spaces_after_cols: prepared.spaces_after_cols,
spaces_after_bytes: prepared.spaces_after,
indent_cols: prepared.indent_cols,
indent_bytes: prepared.indent_bytes,
};
let current_content_col = paragraphs::current_content_col(&self.containers);
let deep_ordered_matched_level = matched_level
.and_then(|level| self.containers.stack.get(level).map(|c| (level, c)))
.and_then(|(level, container)| match container {
Container::List {
marker: list_marker,
base_indent_cols,
..
} if matches!(
(&prepared.marker, list_marker),
(ListMarker::Ordered(_), ListMarker::Ordered(_))
) && prepared.indent_cols >= 4
&& *base_indent_cols >= 4
&& prepared.indent_cols.abs_diff(*base_indent_cols) <= 3 =>
{
Some(level)
}
_ => None,
});
if deep_ordered_matched_level.is_none()
&& current_content_col > 0
&& prepared.indent_cols >= current_content_col
{
if let Some(level) = matched_level
&& let Some(Container::List {
base_indent_cols, ..
}) = self.containers.stack.get(level)
&& prepared.indent_cols == *base_indent_cols
{
let num_parent_lists = self.containers.stack[..level]
.iter()
.filter(|c| matches!(c, Container::List { .. }))
.count();
if num_parent_lists > 0 {
self.close_containers_to(level + 1);
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if let Some(indent_str) = indent_to_emit {
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
if let Some(nested_marker) = prepared.nested_marker {
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
lists::add_list_item(&mut self.containers, &mut self.builder, &list_item);
}
return;
}
}
self.emit_list_item_buffer_if_needed();
start_nested_list(
&mut self.containers,
&mut self.builder,
&prepared.marker,
&list_item,
indent_to_emit,
);
return;
}
if let Some(level) = matched_level {
self.close_containers_to(level + 1);
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if let Some(indent_str) = indent_to_emit {
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
if let Some(nested_marker) = prepared.nested_marker {
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
lists::add_list_item(&mut self.containers, &mut self.builder, &list_item);
}
return;
}
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
while matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
while matches!(self.containers.last(), Some(Container::List { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
self.builder.start_node(SyntaxKind::LIST.into());
if let Some(indent_str) = indent_to_emit {
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
self.containers.push(Container::List {
marker: prepared.marker.clone(),
base_indent_cols: prepared.indent_cols,
has_blank_between_items: false,
});
if let Some(nested_marker) = prepared.nested_marker {
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
lists::add_list_item(&mut self.containers, &mut self.builder, &list_item);
}
}
fn handle_definition_list_effect(
&mut self,
block_match: &super::block_dispatcher::PreparedBlockMatch,
content: &str,
indent_to_emit: Option<&str>,
) {
use super::block_dispatcher::DefinitionPrepared;
let prepared = block_match
.payload
.as_ref()
.and_then(|p| p.downcast_ref::<DefinitionPrepared>());
let Some(prepared) = prepared else {
return;
};
match prepared {
DefinitionPrepared::Definition {
marker_char,
indent,
spaces_after,
spaces_after_cols,
has_content,
} => {
self.emit_buffered_plain_if_needed();
while matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
while matches!(self.containers.last(), Some(Container::List { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::Definition { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
// A definition marker cannot start a new definition item without a term.
// If the preceding term/item was closed by a blank line but we are still
// inside the same definition list, reopen a definition item for continuation.
if definition_lists::in_definition_list(&self.containers)
&& !matches!(
self.containers.last(),
Some(Container::DefinitionItem { .. })
)
{
self.builder.start_node(SyntaxKind::DEFINITION_ITEM.into());
self.containers.push(Container::DefinitionItem {});
}
if !definition_lists::in_definition_list(&self.containers) {
self.builder.start_node(SyntaxKind::DEFINITION_LIST.into());
self.containers.push(Container::DefinitionList {});
}
if !matches!(
self.containers.last(),
Some(Container::DefinitionItem { .. })
) {
self.builder.start_node(SyntaxKind::DEFINITION_ITEM.into());
self.containers.push(Container::DefinitionItem {});
}
self.builder.start_node(SyntaxKind::DEFINITION.into());
if let Some(indent_str) = indent_to_emit {
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
emit_definition_marker(&mut self.builder, *marker_char, *indent);
let indent_bytes = byte_index_at_column(content, *indent);
if *spaces_after > 0 {
let space_start = indent_bytes + 1;
let space_end = space_start + *spaces_after;
if space_end <= content.len() {
self.builder.token(
SyntaxKind::WHITESPACE.into(),
&content[space_start..space_end],
);
}
}
if !*has_content {
let current_line = self.lines[self.pos];
let (_, newline_str) = strip_newline(current_line);
if !newline_str.is_empty() {
self.builder.token(SyntaxKind::NEWLINE.into(), newline_str);
}
}
let content_col = *indent + 1 + *spaces_after_cols;
let content_start_bytes = indent_bytes + 1 + *spaces_after;
let after_marker_and_spaces = content.get(content_start_bytes..).unwrap_or("");
let mut plain_buffer = TextBuffer::new();
let mut definition_pushed = false;
if *has_content {
let current_line = self.lines[self.pos];
let (trimmed_line, _) = strip_newline(current_line);
let content_start = content_start_bytes.min(trimmed_line.len());
let content_slice = &trimmed_line[content_start..];
let content_line = ¤t_line[content_start_bytes.min(current_line.len())..];
let (blockquote_depth, inner_blockquote_content) =
count_blockquote_markers(content_line);
let should_start_list_from_first_line = self
.lines
.get(self.pos + 1)
.map(|next_line| {
let (next_without_newline, _) = strip_newline(next_line);
if next_without_newline.trim().is_empty() {
return false;
}
let (next_indent_cols, _) = leading_indent(next_without_newline);
next_indent_cols >= content_col
})
.unwrap_or(false);
if blockquote_depth > 0 {
self.containers.push(Container::Definition {
content_col,
plain_open: false,
plain_buffer: TextBuffer::new(),
});
definition_pushed = true;
let marker_info = parse_blockquote_marker_info(content_line);
for level in 0..blockquote_depth {
self.builder.start_node(SyntaxKind::BLOCK_QUOTE.into());
if let Some(info) = marker_info.get(level) {
blockquotes::emit_one_blockquote_marker(
&mut self.builder,
info.leading_spaces,
info.has_trailing_space,
);
}
self.containers.push(Container::BlockQuote {});
}
if !inner_blockquote_content.trim().is_empty() {
paragraphs::start_paragraph_if_needed(
&mut self.containers,
&mut self.builder,
);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
inner_blockquote_content,
self.config,
);
}
} else if let Some(marker_match) =
try_parse_list_marker(content_slice, self.config)
&& should_start_list_from_first_line
{
self.containers.push(Container::Definition {
content_col,
plain_open: false,
plain_buffer: TextBuffer::new(),
});
definition_pushed = true;
let (indent_cols, indent_bytes) = leading_indent(content_line);
self.builder.start_node(SyntaxKind::LIST.into());
self.containers.push(Container::List {
marker: marker_match.marker.clone(),
base_indent_cols: indent_cols,
has_blank_between_items: false,
});
let list_item = ListItemEmissionInput {
content: content_line,
marker_len: marker_match.marker_len,
spaces_after_cols: marker_match.spaces_after_cols,
spaces_after_bytes: marker_match.spaces_after_bytes,
indent_cols,
indent_bytes,
};
if let Some(nested_marker) = is_content_nested_bullet_marker(
content_line,
marker_match.marker_len,
marker_match.spaces_after_bytes,
) {
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
lists::add_list_item(
&mut self.containers,
&mut self.builder,
&list_item,
);
}
} else if let Some(fence) = code_blocks::try_parse_fence_open(content_slice) {
self.containers.push(Container::Definition {
content_col,
plain_open: false,
plain_buffer: TextBuffer::new(),
});
definition_pushed = true;
let bq_depth = self.current_blockquote_depth();
if let Some(indent_str) = indent_to_emit {
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
let fence_line = current_line[content_start..].to_string();
let new_pos = if self.config.extensions.tex_math_gfm
&& code_blocks::is_gfm_math_fence(&fence)
{
code_blocks::parse_fenced_math_block(
&mut self.builder,
&self.lines,
self.pos,
fence,
bq_depth,
content_col,
Some(&fence_line),
)
} else {
code_blocks::parse_fenced_code_block(
&mut self.builder,
&self.lines,
self.pos,
fence,
bq_depth,
content_col,
Some(&fence_line),
)
};
self.pos = new_pos - 1;
} else {
let (_, newline_str) = strip_newline(current_line);
let (content_without_newline, _) = strip_newline(after_marker_and_spaces);
if content_without_newline.is_empty() {
plain_buffer.push_line(newline_str);
} else {
let line_with_newline = if !newline_str.is_empty() {
format!("{}{}", content_without_newline, newline_str)
} else {
content_without_newline.to_string()
};
plain_buffer.push_line(line_with_newline);
}
}
}
if !definition_pushed {
self.containers.push(Container::Definition {
content_col,
plain_open: *has_content,
plain_buffer,
});
}
}
DefinitionPrepared::Term { blank_count } => {
self.emit_buffered_plain_if_needed();
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if !definition_lists::in_definition_list(&self.containers) {
self.builder.start_node(SyntaxKind::DEFINITION_LIST.into());
self.containers.push(Container::DefinitionList {});
}
while matches!(
self.containers.last(),
Some(Container::Definition { .. }) | Some(Container::DefinitionItem { .. })
) {
self.close_containers_to(self.containers.depth() - 1);
}
self.builder.start_node(SyntaxKind::DEFINITION_ITEM.into());
self.containers.push(Container::DefinitionItem {});
emit_term(&mut self.builder, content, self.config);
for i in 0..*blank_count {
let blank_pos = self.pos + 1 + i;
if blank_pos < self.lines.len() {
let blank_line = self.lines[blank_pos];
self.builder.start_node(SyntaxKind::BLANK_LINE.into());
self.builder
.token(SyntaxKind::BLANK_LINE.into(), blank_line);
self.builder.finish_node();
}
}
self.pos += *blank_count;
}
}
}
/// Get current blockquote depth from container stack.
fn blockquote_marker_info(
&self,
payload: Option<&BlockQuotePrepared>,
line: &str,
) -> Vec<marker_utils::BlockQuoteMarkerInfo> {
payload
.map(|payload| payload.marker_info.clone())
.unwrap_or_else(|| parse_blockquote_marker_info(line))
}
/// Build blockquote marker metadata for the current source line.
///
/// When a blockquote marker is detected at a shifted list content column
/// (e.g. ` > ...` inside a list item), the prefix indentation must be
/// folded into the first marker's leading spaces for lossless emission.
fn marker_info_for_line(
&self,
payload: Option<&BlockQuotePrepared>,
raw_line: &str,
marker_line: &str,
shifted_prefix: &str,
used_shifted: bool,
) -> Vec<marker_utils::BlockQuoteMarkerInfo> {
let mut marker_info = if used_shifted {
parse_blockquote_marker_info(marker_line)
} else {
self.blockquote_marker_info(payload, raw_line)
};
if used_shifted && !shifted_prefix.is_empty() {
let (prefix_cols, _) = leading_indent(shifted_prefix);
if let Some(first) = marker_info.first_mut() {
first.leading_spaces += prefix_cols;
}
}
marker_info
}
/// Detect blockquote markers that begin at list-content indentation instead
/// of column 0 on the physical line.
fn shifted_blockquote_from_list<'b>(
&self,
line: &'b str,
) -> Option<(usize, &'b str, &'b str, &'b str)> {
if !lists::in_list(&self.containers) {
return None;
}
let list_content_col = paragraphs::current_content_col(&self.containers);
if list_content_col == 0 {
return None;
}
let (indent_cols, _) = leading_indent(line);
if indent_cols < list_content_col {
return None;
}
let idx = byte_index_at_column(line, list_content_col);
if idx > line.len() {
return None;
}
let candidate = &line[idx..];
let (candidate_depth, candidate_inner) = count_blockquote_markers(candidate);
if candidate_depth == 0 {
return None;
}
Some((candidate_depth, candidate_inner, candidate, &line[..idx]))
}
fn emit_blockquote_markers(
&mut self,
marker_info: &[marker_utils::BlockQuoteMarkerInfo],
depth: usize,
) {
for i in 0..depth {
if let Some(info) = marker_info.get(i) {
blockquotes::emit_one_blockquote_marker(
&mut self.builder,
info.leading_spaces,
info.has_trailing_space,
);
}
}
}
fn current_blockquote_depth(&self) -> usize {
blockquotes::current_blockquote_depth(&self.containers)
}
/// Emit or buffer a blockquote marker depending on parser state.
///
/// If a paragraph is open and we're using integrated parsing, buffer the marker.
/// Otherwise emit it directly to the builder.
fn emit_or_buffer_blockquote_marker(
&mut self,
leading_spaces: usize,
has_trailing_space: bool,
) {
if let Some(Container::ListItem { buffer, .. }) = self.containers.stack.last_mut() {
buffer.push_blockquote_marker(leading_spaces, has_trailing_space);
return;
}
// If paragraph is open, buffer the marker (it will be emitted at correct position)
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
// Buffer the marker in the paragraph
paragraphs::append_paragraph_marker(
&mut self.containers,
leading_spaces,
has_trailing_space,
);
} else {
// Emit directly
blockquotes::emit_one_blockquote_marker(
&mut self.builder,
leading_spaces,
has_trailing_space,
);
}
}
fn parse_document_stack(&mut self) {
self.builder.start_node(SyntaxKind::DOCUMENT.into());
log::debug!("Starting document parse");
// Pandoc title block is handled via the block dispatcher.
while self.pos < self.lines.len() {
let line = self.lines[self.pos];
log::debug!("Parsing line {}: {}", self.pos + 1, line);
if self.parse_line(line) {
continue;
}
self.pos += 1;
}
self.close_containers_to(0);
self.builder.finish_node(); // DOCUMENT
}
/// Returns true if the line was consumed.
fn parse_line(&mut self, line: &str) -> bool {
// Count blockquote markers on this line. Inside list items, blockquotes can begin
// at the list content column (e.g. ` > ...` after `1. `), not at column 0.
let (mut bq_depth, mut inner_content) = count_blockquote_markers(line);
let mut bq_marker_line = line;
let mut shifted_bq_prefix = "";
let mut used_shifted_bq = false;
if bq_depth == 0
&& let Some((candidate_depth, candidate_inner, candidate_line, candidate_prefix)) =
self.shifted_blockquote_from_list(line)
{
bq_depth = candidate_depth;
inner_content = candidate_inner;
bq_marker_line = candidate_line;
shifted_bq_prefix = candidate_prefix;
used_shifted_bq = true;
}
let current_bq_depth = self.current_blockquote_depth();
let has_blank_before = self.pos == 0 || self.lines[self.pos - 1].trim().is_empty();
let mut blockquote_match: Option<PreparedBlockMatch> = None;
let dispatcher_ctx = if current_bq_depth == 0 {
Some(BlockContext {
content: line,
has_blank_before,
has_blank_before_strict: has_blank_before,
at_document_start: self.pos == 0,
in_fenced_div: self.in_fenced_div(),
blockquote_depth: current_bq_depth,
config: self.config,
content_indent: 0,
indent_to_emit: None,
list_indent_info: None,
in_list: lists::in_list(&self.containers),
next_line: if self.pos + 1 < self.lines.len() {
Some(self.lines[self.pos + 1])
} else {
None
},
})
} else {
None
};
let blockquote_payload = if let Some(dispatcher_ctx) = dispatcher_ctx.as_ref() {
self.block_registry
.detect_prepared(dispatcher_ctx, &self.lines, self.pos)
.and_then(|prepared| {
if matches!(prepared.effect, BlockEffect::OpenBlockQuote) {
blockquote_match = Some(prepared);
blockquote_match.as_ref().and_then(|prepared| {
prepared
.payload
.as_ref()
.and_then(|payload| payload.downcast_ref::<BlockQuotePrepared>())
.cloned()
})
} else {
None
}
})
} else {
None
};
log::debug!(
"parse_line [{}]: bq_depth={}, current_bq={}, depth={}, line={:?}",
self.pos,
bq_depth,
current_bq_depth,
self.containers.depth(),
line.trim_end()
);
// Handle blank lines specially (including blank lines inside blockquotes)
// A line like ">" with nothing after is a blank line inside a blockquote
let is_blank = line.trim_end_matches('\n').trim().is_empty()
|| (bq_depth > 0 && inner_content.trim_end_matches('\n').trim().is_empty());
if is_blank {
if self.is_paragraph_open()
&& paragraphs::has_open_inline_math_environment(&self.containers)
{
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line,
self.config,
);
self.pos += 1;
return true;
}
// Close paragraph if open
self.close_paragraph_if_open();
// Close Plain node in Definition if open
// Blank lines should close Plain, allowing subsequent content to be siblings
// Emit buffered PLAIN content before continuing
self.emit_buffered_plain_if_needed();
// Note: Blank lines between terms and definitions are now preserved
// and emitted as part of the term parsing logic
// For blank lines inside blockquotes, we need to handle them at the right depth.
// If a shifted blockquote marker was detected in list-item content, preserve the
// leading shifted indentation before the first marker for losslessness.
// First, adjust blockquote depth if needed
if bq_depth > current_bq_depth {
// Open blockquotes
for _ in current_bq_depth..bq_depth {
self.builder.start_node(SyntaxKind::BLOCK_QUOTE.into());
self.containers.push(Container::BlockQuote {});
}
} else if bq_depth < current_bq_depth {
// Close blockquotes down to bq_depth (must use Parser close to emit buffers)
self.close_blockquotes_to_depth(bq_depth);
}
// Peek ahead to determine what containers to keep open
let mut peek = self.pos + 1;
while peek < self.lines.len() && self.lines[peek].trim().is_empty() {
peek += 1;
}
// Determine what containers to keep open based on next line
let levels_to_keep = if peek < self.lines.len() {
ContinuationPolicy::new(self.config, &self.block_registry).compute_levels_to_keep(
self.current_blockquote_depth(),
&self.containers,
&self.lines,
peek,
self.lines[peek],
)
} else {
0
};
log::trace!(
"Blank line: depth={}, levels_to_keep={}, next='{}'",
self.containers.depth(),
levels_to_keep,
if peek < self.lines.len() {
self.lines[peek]
} else {
"<EOF>"
}
);
// Check if blank line should be buffered in a ListItem BEFORE closing containers
// Close containers down to the level we want to keep
while self.containers.depth() > levels_to_keep {
match self.containers.last() {
Some(Container::ListItem { .. }) => {
// levels_to_keep wants to close the ListItem - blank line is between items
log::debug!(
"Closing ListItem at blank line (levels_to_keep={} < depth={})",
levels_to_keep,
self.containers.depth()
);
self.close_containers_to(self.containers.depth() - 1);
}
Some(Container::List { .. })
| Some(Container::FootnoteDefinition { .. })
| Some(Container::Alert { .. })
| Some(Container::Paragraph { .. })
| Some(Container::Definition { .. })
| Some(Container::DefinitionItem { .. })
| Some(Container::DefinitionList { .. }) => {
log::debug!(
"Closing {:?} at blank line (depth {} > levels_to_keep {})",
self.containers.last(),
self.containers.depth(),
levels_to_keep
);
self.close_containers_to(self.containers.depth() - 1);
}
_ => break,
}
}
// If we kept a list item open, its first-line text may still be buffered.
// Flush it *before* emitting the blank line node (and its blockquote markers)
// so byte order matches the source.
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.emit_list_item_buffer_if_needed();
}
// Emit blockquote markers for this blank line if inside blockquotes
if bq_depth > 0 {
let marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
self.emit_blockquote_markers(&marker_info, bq_depth);
}
self.builder.start_node(SyntaxKind::BLANK_LINE.into());
self.builder
.token(SyntaxKind::BLANK_LINE.into(), inner_content);
self.builder.finish_node();
self.pos += 1;
return true;
}
// Handle blockquote depth changes
if bq_depth > current_bq_depth {
// Need to open new blockquote(s)
// But first check blank_before_blockquote requirement
if self.config.extensions.blank_before_blockquote
&& current_bq_depth == 0
&& !blockquote_payload
.as_ref()
.map(|payload| payload.can_start)
.unwrap_or_else(|| blockquotes::can_start_blockquote(self.pos, &self.lines))
{
// Can't start blockquote without blank line - treat as paragraph
// Flush any pending list-item inline buffer first so this line
// stays in source order relative to buffered list text.
self.emit_list_item_buffer_if_needed();
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line,
self.config,
);
self.pos += 1;
return true;
}
// For nested blockquotes, also need blank line before (blank_before_blockquote)
// Check if previous line inside the blockquote was blank
let can_nest = if current_bq_depth > 0 {
if self.config.extensions.blank_before_blockquote {
// Check if we're right after a blank line or at start of blockquote
matches!(self.containers.last(), Some(Container::BlockQuote { .. }))
|| (self.pos > 0 && {
let prev_line = self.lines[self.pos - 1];
let (prev_bq_depth, prev_inner) = count_blockquote_markers(prev_line);
prev_bq_depth >= current_bq_depth && prev_inner.trim().is_empty()
})
} else {
true
}
} else {
blockquote_payload
.as_ref()
.map(|payload| payload.can_nest)
.unwrap_or(true)
};
if !can_nest {
// Can't nest deeper - treat extra > as content
// Only strip markers up to current depth
let content_at_current_depth =
blockquotes::strip_n_blockquote_markers(line, current_bq_depth);
// Emit blockquote markers for current depth (for losslessness)
let marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
for i in 0..current_bq_depth {
if let Some(info) = marker_info.get(i) {
self.emit_or_buffer_blockquote_marker(
info.leading_spaces,
info.has_trailing_space,
);
}
}
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
// Lazy continuation with the extra > as content
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
content_at_current_depth,
self.config,
);
self.pos += 1;
return true;
} else {
// Start new paragraph with the extra > as content
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
content_at_current_depth,
self.config,
);
self.pos += 1;
return true;
}
}
// Preserve source order when a deeper blockquote line arrives while
// list-item text is still buffered (e.g. issue #174).
self.emit_list_item_buffer_if_needed();
// Close paragraph before opening blockquote
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
// Parse marker information for all levels
let marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
if let (Some(dispatcher_ctx), Some(prepared)) =
(dispatcher_ctx.as_ref(), blockquote_match.as_ref())
{
let _ = self.block_registry.parse_prepared(
prepared,
dispatcher_ctx,
&mut self.builder,
&self.lines,
self.pos,
);
for _ in 0..bq_depth {
self.containers.push(Container::BlockQuote {});
}
} else {
// First, emit markers for existing blockquote levels (before opening new ones)
for level in 0..current_bq_depth {
if let Some(info) = marker_info.get(level) {
self.emit_or_buffer_blockquote_marker(
info.leading_spaces,
info.has_trailing_space,
);
}
}
// Then open new blockquotes and emit their markers
for level in current_bq_depth..bq_depth {
self.builder.start_node(SyntaxKind::BLOCK_QUOTE.into());
// Emit the marker for this new level
if let Some(info) = marker_info.get(level) {
blockquotes::emit_one_blockquote_marker(
&mut self.builder,
info.leading_spaces,
info.has_trailing_space,
);
}
self.containers.push(Container::BlockQuote {});
}
}
// Now parse the inner content
// Pass inner_content as line_to_append since markers are already stripped
return self.parse_inner_content(inner_content, Some(inner_content));
} else if bq_depth < current_bq_depth {
// Need to close some blockquotes, but first check for lazy continuation
// Lazy continuation: line without > continues content in a blockquote
if bq_depth == 0 {
// Check for lazy paragraph continuation
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line,
self.config,
);
self.pos += 1;
return true;
}
// Check for lazy list continuation - if we're in a list item and
// this line looks like a list item with matching marker
if lists::in_blockquote_list(&self.containers)
&& let Some(marker_match) = try_parse_list_marker(line, self.config)
{
let (indent_cols, indent_bytes) = leading_indent(line);
if let Some(level) = lists::find_matching_list_level(
&self.containers,
&marker_match.marker,
indent_cols,
) {
// Continue the list inside the blockquote
// Close containers to the target level, emitting buffers properly
self.close_containers_to(level + 1);
// Close any open paragraph or list item at this level
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
// Check if content is a nested bullet marker
if let Some(nested_marker) = is_content_nested_bullet_marker(
line,
marker_match.marker_len,
marker_match.spaces_after_bytes,
) {
let list_item = ListItemEmissionInput {
content: line,
marker_len: marker_match.marker_len,
spaces_after_cols: marker_match.spaces_after_cols,
spaces_after_bytes: marker_match.spaces_after_bytes,
indent_cols,
indent_bytes,
};
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
let list_item = ListItemEmissionInput {
content: line,
marker_len: marker_match.marker_len,
spaces_after_cols: marker_match.spaces_after_cols,
spaces_after_bytes: marker_match.spaces_after_bytes,
indent_cols,
indent_bytes,
};
lists::add_list_item(
&mut self.containers,
&mut self.builder,
&list_item,
);
}
self.pos += 1;
return true;
}
}
}
// Not lazy continuation - close paragraph if open
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
// Close blockquotes down to the new depth (must use Parser close to emit buffers)
self.close_blockquotes_to_depth(bq_depth);
// Parse the inner content at the new depth
if bq_depth > 0 {
// Emit markers at current depth before parsing content
let marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
for i in 0..bq_depth {
if let Some(info) = marker_info.get(i) {
self.emit_or_buffer_blockquote_marker(
info.leading_spaces,
info.has_trailing_space,
);
}
}
// Content with markers stripped - use inner_content for paragraph appending
return self.parse_inner_content(inner_content, Some(inner_content));
} else {
// Not inside blockquotes - use original line
return self.parse_inner_content(line, None);
}
} else if bq_depth > 0 {
// Same blockquote depth - emit markers and continue parsing inner content
let mut list_item_continuation = false;
let same_depth_marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
let has_explicit_same_depth_marker = same_depth_marker_info.len() >= bq_depth;
// Check if we should close the ListItem
// ListItem should continue if the line is properly indented for continuation
if matches!(
self.containers.last(),
Some(Container::ListItem { content_col: _, .. })
) {
let (indent_cols, _) = leading_indent(inner_content);
let content_indent = self.content_container_indent_to_strip();
let effective_indent = indent_cols.saturating_sub(content_indent);
let content_col = match self.containers.last() {
Some(Container::ListItem { content_col, .. }) => *content_col,
_ => 0,
};
// Check if this line starts a new list item at outer level
let is_new_item_at_outer_level =
if try_parse_list_marker(inner_content, self.config).is_some() {
effective_indent < content_col
} else {
false
};
// Close ListItem if:
// 1. It's a new list item at an outer (or same) level, OR
// 2. The line is not indented enough to continue the current item
if is_new_item_at_outer_level
|| (effective_indent < content_col && !has_explicit_same_depth_marker)
{
log::debug!(
"Closing ListItem: is_new_item={}, effective_indent={} < content_col={}",
is_new_item_at_outer_level,
effective_indent,
content_col
);
self.close_containers_to(self.containers.depth() - 1);
} else {
log::debug!(
"Keeping ListItem: effective_indent={} >= content_col={}",
effective_indent,
content_col
);
list_item_continuation = true;
}
}
// Fenced code blocks inside list items need marker emission in this branch.
// If we keep continuation buffering for these lines, opening fence markers in
// blockquote contexts can be dropped from CST text.
if list_item_continuation && code_blocks::try_parse_fence_open(inner_content).is_some()
{
list_item_continuation = false;
}
let continuation_has_explicit_marker = list_item_continuation && {
if has_explicit_same_depth_marker {
for i in 0..bq_depth {
if let Some(info) = same_depth_marker_info.get(i) {
self.emit_or_buffer_blockquote_marker(
info.leading_spaces,
info.has_trailing_space,
);
}
}
true
} else {
false
}
};
if !list_item_continuation {
let marker_info = self.marker_info_for_line(
blockquote_payload.as_ref(),
line,
bq_marker_line,
shifted_bq_prefix,
used_shifted_bq,
);
for i in 0..bq_depth {
if let Some(info) = marker_info.get(i) {
self.emit_or_buffer_blockquote_marker(
info.leading_spaces,
info.has_trailing_space,
);
}
}
}
let line_to_append = if list_item_continuation {
if continuation_has_explicit_marker {
Some(inner_content)
} else {
Some(line)
}
} else {
Some(inner_content)
};
return self.parse_inner_content(inner_content, line_to_append);
}
// No blockquote markers - parse as regular content
// But check for lazy continuation first
if current_bq_depth > 0 {
// Check for lazy paragraph continuation
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line,
self.config,
);
self.pos += 1;
return true;
}
// Check for lazy list continuation
if lists::in_blockquote_list(&self.containers)
&& let Some(marker_match) = try_parse_list_marker(line, self.config)
{
let (indent_cols, indent_bytes) = leading_indent(line);
if let Some(level) = lists::find_matching_list_level(
&self.containers,
&marker_match.marker,
indent_cols,
) {
// Close containers to the target level, emitting buffers properly
self.close_containers_to(level + 1);
// Close any open paragraph or list item at this level
if matches!(self.containers.last(), Some(Container::Paragraph { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
// Check if content is a nested bullet marker
if let Some(nested_marker) = is_content_nested_bullet_marker(
line,
marker_match.marker_len,
marker_match.spaces_after_bytes,
) {
let list_item = ListItemEmissionInput {
content: line,
marker_len: marker_match.marker_len,
spaces_after_cols: marker_match.spaces_after_cols,
spaces_after_bytes: marker_match.spaces_after_bytes,
indent_cols,
indent_bytes,
};
lists::add_list_item_with_nested_empty_list(
&mut self.containers,
&mut self.builder,
&list_item,
nested_marker,
);
} else {
let list_item = ListItemEmissionInput {
content: line,
marker_len: marker_match.marker_len,
spaces_after_cols: marker_match.spaces_after_cols,
spaces_after_bytes: marker_match.spaces_after_bytes,
indent_cols,
indent_bytes,
};
lists::add_list_item(&mut self.containers, &mut self.builder, &list_item);
}
self.pos += 1;
return true;
}
}
}
// No blockquote markers - use original line
self.parse_inner_content(line, None)
}
/// Get the total indentation to strip from content containers (footnotes + definitions).
fn content_container_indent_to_strip(&self) -> usize {
self.containers
.stack
.iter()
.filter_map(|c| match c {
Container::FootnoteDefinition { content_col, .. } => Some(*content_col),
Container::Definition { content_col, .. } => Some(*content_col),
_ => None,
})
.sum()
}
/// Parse content inside blockquotes (or at top level).
///
/// `content` - The content to parse (may have indent/markers stripped)
/// `line_to_append` - Optional line to use when appending to paragraphs.
/// If None, uses self.lines[self.pos]
fn parse_inner_content(&mut self, content: &str, line_to_append: Option<&str>) -> bool {
log::debug!(
"parse_inner_content [{}]: depth={}, last={:?}, content={:?}",
self.pos,
self.containers.depth(),
self.containers.last(),
content.trim_end()
);
// Calculate how much indentation should be stripped for content containers
// (definitions, footnotes) FIRST, so we can check for block markers correctly
let content_indent = self.content_container_indent_to_strip();
let (stripped_content, indent_to_emit) = if content_indent > 0 {
let (indent_cols, _) = leading_indent(content);
if indent_cols >= content_indent {
let idx = byte_index_at_column(content, content_indent);
(&content[idx..], Some(&content[..idx]))
} else {
// Line has less indent than required - preserve leading whitespace
let trimmed_start = content.trim_start();
let ws_len = content.len() - trimmed_start.len();
if ws_len > 0 {
(trimmed_start, Some(&content[..ws_len]))
} else {
(content, None)
}
}
} else {
(content, None)
};
if self.config.extensions.alerts
&& self.current_blockquote_depth() > 0
&& !self.in_active_alert()
&& !self.is_paragraph_open()
&& let Some(marker) = Self::alert_marker_from_content(stripped_content)
{
let (_, newline_str) = strip_newline(stripped_content);
self.builder.start_node(SyntaxKind::ALERT.into());
self.builder.token(SyntaxKind::ALERT_MARKER.into(), marker);
if !newline_str.is_empty() {
self.builder.token(SyntaxKind::NEWLINE.into(), newline_str);
}
self.containers.push(Container::Alert {
blockquote_depth: self.current_blockquote_depth(),
});
self.pos += 1;
return true;
}
// Check if we're in a Definition container (with or without an open PLAIN)
// Continuation lines should be added to PLAIN, not treated as new blocks
// BUT: Don't treat lines with block element markers as continuations
if matches!(self.containers.last(), Some(Container::Definition { .. })) {
let is_definition_marker =
definition_lists::try_parse_definition_marker(stripped_content).is_some()
&& !stripped_content.starts_with(':');
if content_indent == 0 && is_definition_marker {
// Definition markers at top-level should start a new definition.
} else {
let policy = ContinuationPolicy::new(self.config, &self.block_registry);
if policy.definition_plain_can_continue(
stripped_content,
content,
content_indent,
&BlockContext {
content: stripped_content,
has_blank_before: self.pos == 0
|| self.lines[self.pos - 1].trim().is_empty(),
has_blank_before_strict: self.pos == 0
|| self.lines[self.pos - 1].trim().is_empty(),
at_document_start: self.pos == 0 && self.current_blockquote_depth() == 0,
in_fenced_div: self.in_fenced_div(),
blockquote_depth: self.current_blockquote_depth(),
config: self.config,
content_indent,
indent_to_emit: None,
list_indent_info: None,
in_list: lists::in_list(&self.containers),
next_line: if self.pos + 1 < self.lines.len() {
Some(self.lines[self.pos + 1])
} else {
None
},
},
&self.lines,
self.pos,
) {
let content_line = stripped_content;
let (text_without_newline, newline_str) = strip_newline(content_line);
let indent_prefix = if !text_without_newline.trim().is_empty() {
indent_to_emit.unwrap_or("")
} else {
""
};
let content_line = format!("{}{}", indent_prefix, text_without_newline);
if let Some(Container::Definition {
plain_open,
plain_buffer,
..
}) = self.containers.stack.last_mut()
{
let line_with_newline = if !newline_str.is_empty() {
format!("{}{}", content_line, newline_str)
} else {
content_line
};
plain_buffer.push_line(line_with_newline);
*plain_open = true;
}
self.pos += 1;
return true;
}
}
}
// Handle blockquotes that appear after stripping content-container indentation
// (e.g. ` > quote` inside a definition list item).
if content_indent > 0 {
let (bq_depth, inner_content) = count_blockquote_markers(stripped_content);
let current_bq_depth = self.current_blockquote_depth();
if bq_depth > 0 {
// If definition/list plain text is buffered, flush it before opening nested
// blockquotes so block order remains lossless and stable across reparse.
self.emit_buffered_plain_if_needed();
self.emit_list_item_buffer_if_needed();
// Blockquotes can nest inside content containers; preserve the stripped indentation
// as WHITESPACE before the first marker for losslessness.
self.close_paragraph_if_open();
if bq_depth > current_bq_depth {
let marker_info = parse_blockquote_marker_info(stripped_content);
// Open new blockquotes and emit their markers.
for level in current_bq_depth..bq_depth {
self.builder.start_node(SyntaxKind::BLOCK_QUOTE.into());
if level == current_bq_depth
&& let Some(indent_str) = indent_to_emit
{
self.builder
.token(SyntaxKind::WHITESPACE.into(), indent_str);
}
if let Some(info) = marker_info.get(level) {
blockquotes::emit_one_blockquote_marker(
&mut self.builder,
info.leading_spaces,
info.has_trailing_space,
);
}
self.containers.push(Container::BlockQuote {});
}
} else if bq_depth < current_bq_depth {
self.close_blockquotes_to_depth(bq_depth);
} else {
// Same depth: emit markers for losslessness.
let marker_info = parse_blockquote_marker_info(stripped_content);
self.emit_blockquote_markers(&marker_info, bq_depth);
}
return self.parse_inner_content(inner_content, Some(inner_content));
}
}
// Store the stripped content for later use
let content = stripped_content;
if self.is_paragraph_open()
&& (paragraphs::has_open_inline_math_environment(&self.containers)
|| paragraphs::has_open_display_math_dollars(&self.containers))
{
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line_to_append.unwrap_or(self.lines[self.pos]),
self.config,
);
self.pos += 1;
return true;
}
// Precompute dispatcher match once per line (reused by multiple branches below).
// This covers: blocks requiring blank lines, blocks that can interrupt paragraphs,
// and blocks that can appear without blank lines (e.g. reference definitions).
use super::blocks::lists;
use super::blocks::paragraphs;
let list_indent_info = if lists::in_list(&self.containers) {
let content_col = paragraphs::current_content_col(&self.containers);
if content_col > 0 {
Some(super::block_dispatcher::ListIndentInfo { content_col })
} else {
None
}
} else {
None
};
let next_line = if self.pos + 1 < self.lines.len() {
// For lookahead-based blocks (e.g. setext headings), the dispatcher expects
// `ctx.next_line` to be in the same “inner content” form as `ctx.content`.
Some(count_blockquote_markers(self.lines[self.pos + 1]).1)
} else {
None
};
let current_bq_depth = self.current_blockquote_depth();
if let Some(alert_bq_depth) = self.active_alert_blockquote_depth()
&& current_bq_depth < alert_bq_depth
{
while matches!(self.containers.last(), Some(Container::Alert { .. })) {
self.close_containers_to(self.containers.depth() - 1);
}
}
let dispatcher_ctx = BlockContext {
content,
has_blank_before: false, // filled in later
has_blank_before_strict: false, // filled in later
at_document_start: false, // filled in later
in_fenced_div: self.in_fenced_div(),
blockquote_depth: current_bq_depth,
config: self.config,
content_indent,
indent_to_emit,
list_indent_info,
in_list: lists::in_list(&self.containers),
next_line,
};
// We'll update these two fields shortly (after they are computed), but we can still
// use this ctx shape to avoid rebuilding repeated context objects.
let mut dispatcher_ctx = dispatcher_ctx;
// Initial detection (before blank/doc-start are computed). Note: this can
// match reference definitions, but footnotes are handled explicitly later.
let dispatcher_match =
self.block_registry
.detect_prepared(&dispatcher_ctx, &self.lines, self.pos);
// Check for heading (needs blank line before, or at start of container)
// Note: for fenced div nesting, the line immediately after a div opening fence
// should be treated like the start of a container (Pandoc allows nested fences
// without an intervening blank line). Similarly, the first line after a metadata
// block (YAML/Pandoc title/MMD title) is treated as having a blank before it.
let after_metadata_block = std::mem::replace(&mut self.after_metadata_block, false);
let has_blank_before = if self.pos == 0 || after_metadata_block {
true
} else {
let prev_line = self.lines[self.pos - 1];
let (prev_bq_depth, prev_inner) = count_blockquote_markers(prev_line);
let (prev_inner_no_nl, _) = strip_newline(prev_inner);
let prev_is_fenced_div_open = self.config.extensions.fenced_divs
&& fenced_divs::try_parse_div_fence_open(
strip_n_blockquote_markers(prev_inner_no_nl, prev_bq_depth).trim_start(),
)
.is_some();
let prev_line_blank = prev_line.trim().is_empty();
prev_line_blank
|| prev_is_fenced_div_open
|| matches!(self.containers.last(), Some(Container::BlockQuote { .. }))
|| !self.previous_block_requires_blank_before_heading()
};
// For indented code blocks, we need a stricter condition - only actual blank lines count
// Being at document start (pos == 0) is OK only if we're not inside a blockquote
let at_document_start = self.pos == 0 && current_bq_depth == 0;
let prev_line_blank = if self.pos > 0 {
let prev_line = self.lines[self.pos - 1];
let (prev_bq_depth, prev_inner) = count_blockquote_markers(prev_line);
prev_line.trim().is_empty() || (prev_bq_depth > 0 && prev_inner.trim().is_empty())
} else {
false
};
let has_blank_before_strict = at_document_start || prev_line_blank;
dispatcher_ctx.has_blank_before = has_blank_before;
dispatcher_ctx.has_blank_before_strict = has_blank_before_strict;
dispatcher_ctx.at_document_start = at_document_start;
let dispatcher_match =
if dispatcher_ctx.has_blank_before || dispatcher_ctx.at_document_start {
// Recompute now that blank/doc-start conditions are known.
self.block_registry
.detect_prepared(&dispatcher_ctx, &self.lines, self.pos)
} else {
dispatcher_match
};
if has_blank_before {
if let Some(env_name) = extract_environment_name(content)
&& is_inline_math_environment(&env_name)
{
if !self.is_paragraph_open() {
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
}
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line_to_append.unwrap_or(self.lines[self.pos]),
self.config,
);
self.pos += 1;
return true;
}
if let Some(block_match) = dispatcher_match.as_ref() {
let detection = block_match.detection;
match detection {
BlockDetectionResult::YesCanInterrupt => {
self.emit_list_item_buffer_if_needed();
if self.is_paragraph_open() {
self.close_containers_to(self.containers.depth() - 1);
}
}
BlockDetectionResult::Yes => {
self.prepare_for_block_element();
}
BlockDetectionResult::No => unreachable!(),
}
if matches!(block_match.effect, BlockEffect::CloseFencedDiv) {
self.close_containers_to_fenced_div();
}
let lines_consumed = self.block_registry.parse_prepared(
block_match,
&dispatcher_ctx,
&mut self.builder,
&self.lines,
self.pos,
);
if matches!(
self.block_registry.parser_name(block_match),
"yaml_metadata" | "pandoc_title_block" | "mmd_title_block"
) {
self.after_metadata_block = true;
}
match block_match.effect {
BlockEffect::None => {}
BlockEffect::OpenFencedDiv => {
self.containers.push(Container::FencedDiv {});
}
BlockEffect::CloseFencedDiv => {
self.close_fenced_div();
}
BlockEffect::OpenFootnoteDefinition => {
self.handle_footnote_open_effect(block_match, content);
}
BlockEffect::OpenList => {
self.handle_list_open_effect(block_match, content, indent_to_emit);
}
BlockEffect::OpenDefinitionList => {
self.handle_definition_list_effect(block_match, content, indent_to_emit);
}
BlockEffect::OpenBlockQuote => {
// Detection only for now; keep core blockquote handling intact.
}
}
if lines_consumed == 0 {
log::warn!(
"block parser made no progress at line {} (parser={})",
self.pos + 1,
self.block_registry.parser_name(block_match)
);
return false;
}
self.pos += lines_consumed;
return true;
}
} else if let Some(block_match) = dispatcher_match.as_ref() {
// Without blank-before, only allow interrupting blocks OR blocks that are
// explicitly allowed without blank lines (e.g. reference definitions).
let parser_name = self.block_registry.parser_name(block_match);
match block_match.detection {
BlockDetectionResult::YesCanInterrupt => {
if matches!(block_match.effect, BlockEffect::OpenFencedDiv)
&& self.is_paragraph_open()
{
// Fenced divs must not interrupt paragraphs without a blank line.
if !self.is_paragraph_open() {
paragraphs::start_paragraph_if_needed(
&mut self.containers,
&mut self.builder,
);
}
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line_to_append.unwrap_or(self.lines[self.pos]),
self.config,
);
self.pos += 1;
return true;
}
if matches!(block_match.effect, BlockEffect::OpenList)
&& self.is_paragraph_open()
&& !lists::in_list(&self.containers)
&& self.content_container_indent_to_strip() == 0
{
// Do not let lists interrupt a paragraph without a blank line.
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line_to_append.unwrap_or(self.lines[self.pos]),
self.config,
);
self.pos += 1;
return true;
}
self.emit_list_item_buffer_if_needed();
if self.is_paragraph_open() {
self.close_containers_to(self.containers.depth() - 1);
}
}
BlockDetectionResult::Yes => {
// Keep ambiguous fenced-div openers from interrupting an
// active paragraph without a blank line.
if parser_name == "fenced_div_open" && self.is_paragraph_open() {
if !self.is_paragraph_open() {
paragraphs::start_paragraph_if_needed(
&mut self.containers,
&mut self.builder,
);
}
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line_to_append.unwrap_or(self.lines[self.pos]),
self.config,
);
self.pos += 1;
return true;
}
}
BlockDetectionResult::No => unreachable!(),
}
if !matches!(block_match.detection, BlockDetectionResult::No) {
if matches!(block_match.effect, BlockEffect::CloseFencedDiv) {
self.close_containers_to_fenced_div();
}
let lines_consumed = self.block_registry.parse_prepared(
block_match,
&dispatcher_ctx,
&mut self.builder,
&self.lines,
self.pos,
);
match block_match.effect {
BlockEffect::None => {}
BlockEffect::OpenFencedDiv => {
self.containers.push(Container::FencedDiv {});
}
BlockEffect::CloseFencedDiv => {
self.close_fenced_div();
}
BlockEffect::OpenFootnoteDefinition => {
self.handle_footnote_open_effect(block_match, content);
}
BlockEffect::OpenList => {
self.handle_list_open_effect(block_match, content, indent_to_emit);
}
BlockEffect::OpenDefinitionList => {
self.handle_definition_list_effect(block_match, content, indent_to_emit);
}
BlockEffect::OpenBlockQuote => {
// Detection only for now; keep core blockquote handling intact.
}
}
if lines_consumed == 0 {
log::warn!(
"block parser made no progress at line {} (parser={})",
self.pos + 1,
self.block_registry.parser_name(block_match)
);
return false;
}
self.pos += lines_consumed;
return true;
}
}
// Check for line block (if line_blocks extension is enabled)
if self.config.extensions.line_blocks
&& (has_blank_before || self.pos == 0)
&& try_parse_line_block_start(content).is_some()
// Guard against context-stripped content (e.g. inside blockquotes) that
// looks like a line block while the raw source line does not. Calling
// parse_line_block on raw lines in that state would consume 0 lines.
&& try_parse_line_block_start(self.lines[self.pos]).is_some()
{
log::debug!("Parsed line block at line {}", self.pos);
// Close paragraph before opening line block
self.close_paragraph_if_open();
let new_pos = parse_line_block(&self.lines, self.pos, &mut self.builder, self.config);
if new_pos > self.pos {
self.pos = new_pos;
return true;
}
}
// Paragraph or list item continuation
// Check if we're inside a ListItem - if so, buffer the content instead of emitting
if matches!(self.containers.last(), Some(Container::ListItem { .. })) {
log::debug!(
"Inside ListItem - buffering content: {:?}",
line_to_append.unwrap_or(self.lines[self.pos]).trim_end()
);
// Inside list item - buffer content for later parsing
let line = line_to_append.unwrap_or(self.lines[self.pos]);
// Add line to buffer in the ListItem container
if let Some(Container::ListItem { buffer, .. }) = self.containers.stack.last_mut() {
buffer.push_text(line);
}
self.pos += 1;
return true;
}
log::debug!(
"Not in ListItem - creating paragraph for: {:?}",
line_to_append.unwrap_or(self.lines[self.pos]).trim_end()
);
// Not in list item - create paragraph as usual
paragraphs::start_paragraph_if_needed(&mut self.containers, &mut self.builder);
// For lossless parsing: use line_to_append if provided (e.g., for blockquotes
// where markers have been stripped), otherwise use the original line
let line = line_to_append.unwrap_or(self.lines[self.pos]);
paragraphs::append_paragraph_line(
&mut self.containers,
&mut self.builder,
line,
self.config,
);
self.pos += 1;
true
}
fn fenced_div_container_index(&self) -> Option<usize> {
self.containers
.stack
.iter()
.rposition(|c| matches!(c, Container::FencedDiv { .. }))
}
fn close_containers_to_fenced_div(&mut self) {
if let Some(index) = self.fenced_div_container_index() {
self.close_containers_to(index + 1);
}
}
fn close_fenced_div(&mut self) {
if let Some(index) = self.fenced_div_container_index() {
self.close_containers_to(index);
}
}
fn in_fenced_div(&self) -> bool {
self.containers
.stack
.iter()
.any(|c| matches!(c, Container::FencedDiv { .. }))
}
}