panache 2.34.0

An LSP, formatter, and linter for Pandoc markdown, Quarto, and RMarkdown
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
use crate::config::{Config, WrapMode};
use crate::directives::{DirectiveTracker, extract_directive_from_node};
use crate::parser::blocks::headings::{try_parse_atx_heading, try_parse_setext_heading};
use crate::parser::utils::attributes::parse_attribute_content;
use crate::syntax::{BlockQuote, DefinitionItem, DisplayMath, FencedDiv, SyntaxKind, SyntaxNode};
use rowan::NodeOrToken;
use rowan::ast::AstNode;

use super::code_blocks;
use super::code_blocks::FormattedCodeMap;
use super::headings;
use super::inline;
use super::inline_layout;
use super::paragraphs;
use super::tables;
use super::utils::{is_block_element, is_structural_block};

pub struct Formatter {
    pub(super) output: String,
    pub(super) config: Config,
    pub(super) consecutive_blank_lines: usize,
    pub(super) fenced_div_depth: usize,
    pub(super) formatted_code: FormattedCodeMap,
    /// Stack of max marker widths for nested lists (for right-aligning markers)
    pub(super) max_marker_widths: Vec<usize>,
    /// Optional byte range to format (start, end). If None, format entire document.
    range: Option<(usize, usize)>,
    /// Track ignore directives for formatting
    pub(super) directive_tracker: DirectiveTracker,
    /// Depth of ignore region (for preserving content exactly)
    ignore_region_start: Option<usize>,
}

impl Formatter {
    pub fn new(
        config: Config,
        formatted_code: FormattedCodeMap,
        range: Option<(usize, usize)>,
    ) -> Self {
        Self {
            output: String::with_capacity(8192),
            config,
            consecutive_blank_lines: 0,
            fenced_div_depth: 0,
            formatted_code,
            max_marker_widths: Vec::new(),
            range,
            directive_tracker: DirectiveTracker::new(),
            ignore_region_start: None,
        }
    }
    pub fn format(mut self, node: &SyntaxNode) -> String {
        self.format_node_sync(node, 0);
        self.output
    }

    /// Check if a node overlaps with the formatting range
    fn is_in_range(&self, node: &SyntaxNode) -> bool {
        if let Some((range_start, range_end)) = self.range {
            let node_start: usize = node.text_range().start().into();
            let node_end: usize = node.text_range().end().into();

            // Node overlaps with range if it starts before range ends and ends after range starts
            node_start < range_end && node_end > range_start
        } else {
            // No range specified, format everything
            true
        }
    }

    /// Check if we should process a direct child of DOCUMENT
    /// When range filtering is active, only process nodes that overlap with the range
    fn should_process_top_level_node(&self, node: &SyntaxNode) -> bool {
        // If no range specified, process everything
        if self.range.is_none() {
            return true;
        }

        // Always process DOCUMENT node (container)
        if node.kind() == SyntaxKind::DOCUMENT {
            return true;
        }

        // For structural block elements, check if they overlap with the range
        if is_structural_block(node.kind()) {
            return self.is_in_range(node);
        }

        // For non-block elements (tokens), don't include them
        false
    }

    // Delegate to extracted wrapping module
    pub(super) fn format_inline_node(&self, node: &SyntaxNode) -> String {
        inline::format_inline_node(node, &self.config)
    }

    // Delegate to wrapping module
    pub(super) fn wrapped_lines_for_paragraph(
        &self,
        node: &SyntaxNode,
        width: usize,
    ) -> Vec<String> {
        let text = node.text().to_string();
        if text.contains("[@") && text.contains("]:") {
            return text.lines().map(ToString::to_string).collect();
        }
        inline_layout::wrapped_lines_for_paragraph(&self.config, node, width, &|n| {
            self.format_inline_node(n)
        })
    }

    pub(super) fn wrapped_lines_for_paragraph_with_widths(
        &self,
        node: &SyntaxNode,
        widths: &[usize],
    ) -> Vec<String> {
        inline_layout::wrapped_lines_for_paragraph_with_widths(&self.config, node, widths, &|n| {
            self.format_inline_node(n)
        })
    }

    pub(super) fn sentence_lines_for_paragraph(&self, node: &SyntaxNode) -> Vec<String> {
        inline_layout::sentence_lines_for_paragraph(&self.config, node, &|n| {
            self.format_inline_node(n)
        })
    }

    // Delegate to headings module
    pub(super) fn format_heading(&self, node: &SyntaxNode) -> String {
        headings::format_heading(node)
    }

    fn contains_latex_command(&self, node: &SyntaxNode) -> bool {
        paragraphs::contains_latex_command(node)
    }

    fn is_grid_table_continuation_paragraph(&self, node: &SyntaxNode) -> bool {
        if node.kind() != SyntaxKind::PARAGRAPH {
            return false;
        }
        let text = node.text().to_string();
        let lines: Vec<&str> = text
            .lines()
            .map(str::trim_end)
            .filter(|l| !l.trim().is_empty())
            .collect();
        if lines.len() < 2 {
            return false;
        }
        lines.iter().all(|line| {
            let trimmed = line.trim_start();
            trimmed.starts_with('|') || trimmed.starts_with('+')
        }) && lines.iter().any(|line| line.contains("+-"))
            && lines.iter().any(|line| line.trim_start().starts_with('|'))
    }

    fn is_grid_table_caption_definition_list(&self, node: &SyntaxNode) -> bool {
        if node.kind() != SyntaxKind::DEFINITION_LIST {
            return false;
        }
        if !node
            .text()
            .to_string()
            .lines()
            .any(|line| line.trim_start().starts_with(':'))
        {
            return false;
        }
        if let Some(prev) = node.prev_sibling() {
            return prev.kind() == SyntaxKind::GRID_TABLE
                || self.is_grid_table_continuation_paragraph(&prev);
        }
        false
    }

    fn horizontal_rule_text(&self, available_width: usize) -> String {
        "-".repeat(available_width.max(3))
    }

    fn paragraph_starts_with_atx_heading_candidate(&self, node: &SyntaxNode) -> bool {
        if node.kind() != SyntaxKind::PARAGRAPH {
            return false;
        }
        let text = node.text().to_string();
        let first_line = text.lines().next().unwrap_or_default();
        let trimmed = first_line.trim_start_matches([' ', '\t']);
        let leading_hashes = trimmed.chars().take_while(|&c| c == '#').count();
        (1..=6).contains(&leading_hashes)
            && trimmed[leading_hashes..]
                .chars()
                .next()
                .is_some_and(char::is_whitespace)
    }

    pub(super) fn leading_atx_heading_with_remainder(
        &self,
        node: &SyntaxNode,
    ) -> Option<(String, String)> {
        if !matches!(node.kind(), SyntaxKind::PLAIN | SyntaxKind::PARAGRAPH) {
            return None;
        }

        let text = node.text().to_string();
        let mut lines = text.lines();
        let first_line = lines.next()?.trim_start_matches([' ', '\t']);
        try_parse_atx_heading(first_line)?;

        let remainder = lines
            .flat_map(str::split_whitespace)
            .collect::<Vec<_>>()
            .join(" ");

        if remainder.is_empty() {
            return None;
        }

        Some((first_line.trim_end().to_string(), remainder))
    }

    pub(super) fn wrap_text_for_indent(&self, text: &str, indent: usize) -> Vec<String> {
        let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);
        let width = self.config.line_width.saturating_sub(indent);
        match wrap_mode {
            WrapMode::Preserve => vec![text.to_string()],
            WrapMode::Reflow | WrapMode::Sentence => {
                inline_layout::wrap_text_first_fit(text, width)
            }
        }
    }

    fn paragraph_starts_with_setext_heading_candidate(&self, node: &SyntaxNode) -> bool {
        if node.kind() != SyntaxKind::PARAGRAPH {
            return false;
        }
        let text = node.text().to_string();
        let mut lines = text.lines();
        let first = lines.next().unwrap_or_default();
        let second = lines.next().unwrap_or_default();
        if second.is_empty() {
            return false;
        }
        try_parse_setext_heading(&[first, second], 0).is_some()
    }

    // Delegate to code_blocks module
    fn format_code_block(&mut self, node: &SyntaxNode) {
        code_blocks::format_code_block(node, &self.config, &self.formatted_code, &mut self.output);
    }

    fn format_code_block_to_string(&mut self, node: &SyntaxNode) -> String {
        let saved_output = self.output.clone();
        self.output.clear();
        self.format_code_block(node);
        let formatted = self.output.clone();
        self.output = saved_output;
        formatted
    }

    fn strip_leading_columns(line: &str, columns: usize) -> String {
        let mut cols = 0usize;
        let mut idx = 0usize;

        for (byte_idx, ch) in line.char_indices() {
            if cols >= columns {
                idx = byte_idx;
                break;
            }

            match ch {
                ' ' => {
                    cols += 1;
                    idx = byte_idx + ch.len_utf8();
                }
                '\t' => {
                    cols += 4 - (cols % 4);
                    idx = byte_idx + ch.len_utf8();
                }
                _ => {
                    idx = byte_idx;
                    break;
                }
            }
        }

        if cols >= columns {
            line[idx..].to_string()
        } else if line.chars().all(|c| matches!(c, ' ' | '\t')) {
            String::new()
        } else {
            line[idx..].to_string()
        }
    }

    fn format_container_code_block(
        &mut self,
        node: &SyntaxNode,
        first_line_prefix: &str,
        continuation_indent: usize,
        trim_first_line_start: bool,
        normalize_content_indent: bool,
        indent_blank_content_lines: bool,
    ) {
        let formatted = self.format_code_block_to_string(node);

        let mut lines = formatted.lines();
        if let Some(first_line) = lines.next() {
            self.output.push_str(first_line_prefix);
            if trim_first_line_start {
                self.output.push_str(first_line.trim_start());
            } else {
                self.output.push_str(first_line);
            }
            self.output.push('\n');
        }

        let mut remaining: Vec<&str> = lines.collect();
        if remaining.is_empty() {
            return;
        }

        let closing = remaining.pop().unwrap();
        let content_indent_cols = if normalize_content_indent {
            continuation_indent
        } else {
            0
        };

        let continuation_prefix = " ".repeat(continuation_indent);
        for line in remaining {
            if line.trim().is_empty() && !indent_blank_content_lines {
                self.output.push('\n');
                continue;
            }

            self.output.push_str(&continuation_prefix);
            if normalize_content_indent {
                self.output
                    .push_str(&Self::strip_leading_columns(line, content_indent_cols));
            } else {
                self.output.push_str(line);
            }
            self.output.push('\n');
        }

        self.output.push_str(&continuation_prefix);
        if normalize_content_indent {
            self.output
                .push_str(&Self::strip_leading_columns(closing, content_indent_cols));
        } else {
            self.output.push_str(closing);
        }
        self.output.push('\n');
    }

    /// Format a code block that is a continuation of a definition or list item.
    /// Adds indentation prefix to each line of the fenced code block.
    pub(super) fn format_indented_code_block(&mut self, node: &SyntaxNode, indent: usize) {
        let is_fenced = node
            .children()
            .any(|child| child.kind() == SyntaxKind::CODE_FENCE_OPEN);
        let in_list_item = node
            .ancestors()
            .any(|ancestor| ancestor.kind() == SyntaxKind::LIST_ITEM);
        let code_text = node.text().to_string();
        let should_preserve_raw_indented = !is_fenced
            && in_list_item
            && (code_text.contains("```")
                || code_text.contains("<details")
                || code_text.contains("</details>"));
        if should_preserve_raw_indented {
            self.output.push_str(&code_text);
            if !self.output.ends_with('\n') {
                self.output.push('\n');
            }
            return;
        }

        let indent_str = " ".repeat(indent);

        self.format_container_code_block(node, &indent_str, indent, false, false, true);

        // Ensure we end with exactly one newline
        if !self.output.ends_with('\n') {
            self.output.push('\n');
        }
    }

    // The large format_node_sync method - keeping it here for now, can extract later
    pub(super) fn format_node_sync(&mut self, node: &SyntaxNode, indent: usize) {
        // Check if formatting is ignored - if so, preserve content exactly
        // Exception: Always process DOCUMENT, COMMENT, and HTML_BLOCK nodes (may contain directives)
        if self.directive_tracker.is_formatting_ignored()
            && node.kind() != SyntaxKind::DOCUMENT
            && node.kind() != SyntaxKind::COMMENT
            && node.kind() != SyntaxKind::HTML_BLOCK
        {
            let text = node.text().to_string();
            self.output.push_str(&text);
            return;
        }

        // Reset blank line counter when we hit a non-blank node
        if node.kind() != SyntaxKind::BLANK_LINE {
            self.consecutive_blank_lines = 0;
        }

        let line_width = self.config.line_width;

        match node.kind() {
            SyntaxKind::DOCUMENT => {
                for el in node.children_with_tokens() {
                    match el {
                        rowan::NodeOrToken::Node(n) => {
                            // When range filtering is active, only process nodes that overlap
                            if self.should_process_top_level_node(&n) {
                                self.format_node_sync(&n, indent);
                            }
                        }
                        rowan::NodeOrToken::Token(t) => match t.kind() {
                            SyntaxKind::WHITESPACE => {}
                            SyntaxKind::NEWLINE => {}
                            SyntaxKind::BLANK_LINE => {
                                if !self.output.is_empty() {
                                    self.output.push('\n');
                                }
                            }
                            SyntaxKind::ESCAPED_CHAR => {
                                // Token already includes backslash (e.g., "\*")
                                self.output.push_str(t.text());
                            }
                            SyntaxKind::NONBREAKING_SPACE => {
                                // Keep Pandoc escaped-space form for idempotency and losslessness.
                                self.output.push_str(r"\ ");
                            }
                            SyntaxKind::IMAGE_LINK_START
                            | SyntaxKind::LINK_START
                            | SyntaxKind::LATEX_COMMAND => {
                                self.output.push_str(t.text());
                            }
                            _ => self.output.push_str(t.text()),
                        },
                    }
                }
            }

            SyntaxKind::HEADING => {
                log::trace!("Formatting heading");
                // Determine level
                let mut level = 1;
                let mut attributes = String::new();

                // First pass: get level and attributes
                for child in node.children() {
                    match child.kind() {
                        SyntaxKind::ATX_HEADING_MARKER => {
                            let t = child.text().to_string();
                            level = t.chars().take_while(|&c| c == '#').count().clamp(1, 6);
                        }
                        SyntaxKind::SETEXT_HEADING_UNDERLINE => {
                            let t = child.text().to_string();
                            if t.chars().all(|c| c == '=') {
                                level = 1;
                            } else {
                                level = 2;
                            }
                        }
                        SyntaxKind::ATTRIBUTE => {
                            attributes = normalize_attribute_text(&child.text().to_string());
                        }
                        _ => {}
                    }
                }

                // Output heading marker
                self.output.push_str(&"#".repeat(level));
                self.output.push(' ');

                // Second pass: format content by traversing tokens/nodes directly
                // This preserves formatting without adding spaces between inline elements
                let content_start = self.output.len();
                for child in node.children() {
                    if child.kind() == SyntaxKind::HEADING_CONTENT {
                        for element in child.children_with_tokens() {
                            match element {
                                NodeOrToken::Token(t) => {
                                    self.output.push_str(t.text());
                                }
                                NodeOrToken::Node(n) => {
                                    // Format inline nodes (emphasis, code, spans, etc.)
                                    let formatted = self.format_inline_node(&n);
                                    self.output.push_str(&formatted);
                                }
                            }
                        }
                    }
                }

                // Trim trailing whitespace and hashes from content
                let content_end = self.output.len();
                let content = self.output[content_start..content_end].to_string();
                let trimmed = content.trim_end_matches(|c: char| c == '#' || c.is_whitespace());
                self.output.truncate(content_start);
                self.output.push_str(trimmed);

                // Trim trailing whitespace from content
                self.output = self.output.trim_end().to_string();

                // Add attributes if present
                if !attributes.is_empty() {
                    self.output.push(' ');
                    self.output.push_str(&attributes);
                }

                self.output.push('\n');

                if let Some(next) = node.next_sibling()
                    && (is_block_element(next.kind()) || next.kind() == SyntaxKind::HEADING)
                    && !(self.config.extensions.blank_before_header
                        && self.paragraph_starts_with_atx_heading_candidate(&next))
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                }
            }

            SyntaxKind::HORIZONTAL_RULE => {
                // Output normalized horizontal rule using full available width.
                self.output
                    .push_str(&self.horizontal_rule_text(self.config.line_width));
                self.output.push('\n');

                // Ensure blank line after if followed by block element
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && !self.paragraph_starts_with_setext_heading_candidate(&next)
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                    self.consecutive_blank_lines = 1;
                }
            }

            SyntaxKind::REFERENCE_DEFINITION => {
                // Output reference definition as-is: [label]: url "title"
                let text = node.text().to_string();
                self.output.push_str(text.trim_end());
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }

                // Ensure blank line after if followed by non-reference block element
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && next.kind() != SyntaxKind::REFERENCE_DEFINITION
                    && next.kind() != SyntaxKind::FOOTNOTE_DEFINITION
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                }
            }

            SyntaxKind::FOOTNOTE_DEFINITION => {
                // Format footnote definition with proper indentation
                // Extract marker and children first
                let mut marker = String::new();
                let mut child_blocks = Vec::new();

                for element in node.children_with_tokens() {
                    match element {
                        NodeOrToken::Token(token)
                            if matches!(
                                token.kind(),
                                SyntaxKind::FOOTNOTE_REFERENCE
                                    | SyntaxKind::FOOTNOTE_LABEL_START
                                    | SyntaxKind::FOOTNOTE_LABEL_ID
                                    | SyntaxKind::FOOTNOTE_LABEL_END
                                    | SyntaxKind::FOOTNOTE_LABEL_COLON
                            ) =>
                        {
                            marker.push_str(token.text());
                        }
                        NodeOrToken::Node(child) => {
                            child_blocks.push(child);
                        }
                        _ => {}
                    }
                }

                // Output indent and marker
                self.output.push_str(&" ".repeat(indent));
                self.output.push_str(marker.trim_end());

                // Format child blocks with 4-space indentation
                let child_indent = indent + 4;
                let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);
                let mut first = true;
                let mut pending_blank_lines = 0usize;

                for child in &child_blocks {
                    if child.kind() == SyntaxKind::BLANK_LINE {
                        pending_blank_lines = pending_blank_lines.saturating_add(1);
                        continue;
                    }

                    // Emit exactly one normalized blank line between child blocks.
                    if !first && !self.output.ends_with("\n\n") {
                        self.output.push('\n');
                    }
                    pending_blank_lines = 0;

                    if first {
                        first = false;
                        // First paragraph - check if it can go on same line
                        if child.kind() == SyntaxKind::PARAGRAPH {
                            // Calculate how much space is available on first line
                            let marker_len = marker.len();
                            let first_line_space = self
                                .config
                                .line_width
                                .saturating_sub(indent + marker_len + 1);

                            let available_width =
                                self.config.line_width.saturating_sub(child_indent);
                            let widths = [first_line_space, available_width];
                            let lines = match wrap_mode {
                                WrapMode::Preserve => {
                                    let text = child.text().to_string();
                                    text.lines().map(|line| line.to_string()).collect()
                                }
                                WrapMode::Reflow => {
                                    self.wrapped_lines_for_paragraph_with_widths(child, &widths)
                                }
                                WrapMode::Sentence => self.sentence_lines_for_paragraph(child),
                            };

                            if !lines.is_empty() {
                                self.output.push(' ');
                                self.output
                                    .push_str(lines[0].trim_start_matches([' ', '\t']));
                                self.output.push('\n');
                                for line in lines.iter().skip(1) {
                                    self.output.push_str(&" ".repeat(child_indent));
                                    self.output.push_str(line.trim_start_matches([' ', '\t']));
                                    self.output.push('\n');
                                }
                                continue;
                            }
                        }
                    }

                    // Format blocks with indentation
                    match child.kind() {
                        SyntaxKind::PARAGRAPH => {
                            // Handle paragraph with wrapping and indentation
                            let available_width =
                                self.config.line_width.saturating_sub(child_indent);

                            match wrap_mode {
                                WrapMode::Preserve => {
                                    let text = child.text().to_string();
                                    for line in text.lines() {
                                        self.output.push_str(&" ".repeat(child_indent));
                                        self.output.push_str(line.trim_start_matches([' ', '\t']));
                                        self.output.push('\n');
                                    }
                                }
                                WrapMode::Reflow => {
                                    let lines =
                                        self.wrapped_lines_for_paragraph(child, available_width);
                                    for line in lines {
                                        self.output.push_str(&" ".repeat(child_indent));
                                        self.output.push_str(line.trim_start_matches([' ', '\t']));
                                        self.output.push('\n');
                                    }
                                }
                                WrapMode::Sentence => {
                                    let lines = self.sentence_lines_for_paragraph(child);
                                    for line in lines {
                                        self.output.push_str(&" ".repeat(child_indent));
                                        self.output.push_str(line.trim_start_matches([' ', '\t']));
                                        self.output.push('\n');
                                    }
                                }
                            }
                        }
                        SyntaxKind::BLANK_LINE => {
                            // Normalize blank lines to just newlines
                            self.output.push('\n');
                        }
                        SyntaxKind::CODE_BLOCK => {
                            // Format code blocks as fenced blocks with indentation
                            // Extract code content, stripping WHITESPACE tokens (indentation)
                            let mut code_lines = Vec::new();
                            for code_child in child.children() {
                                if code_child.kind() == SyntaxKind::CODE_CONTENT {
                                    // Build content line by line, skipping WHITESPACE tokens
                                    let mut line_content = String::new();
                                    for token in code_child.children_with_tokens() {
                                        if let NodeOrToken::Token(t) = token {
                                            match t.kind() {
                                                SyntaxKind::WHITESPACE => {
                                                    // Skip WHITESPACE (indentation preserved for losslessness)
                                                }
                                                SyntaxKind::TEXT => {
                                                    line_content.push_str(t.text());
                                                }
                                                SyntaxKind::NEWLINE => {
                                                    // End of line - save it and start new line
                                                    code_lines.push(line_content.clone());
                                                    line_content.clear();
                                                }
                                                _ => {}
                                            }
                                        }
                                    }
                                    // Don't forget last line if it doesn't end with newline
                                    if !line_content.is_empty() {
                                        code_lines.push(line_content);
                                    }
                                }
                            }

                            // Strip trailing blank lines from code content
                            while code_lines.last().is_some_and(|l| l.is_empty()) {
                                code_lines.pop();
                            }

                            // Output fenced code block with footnote indentation
                            self.output.push_str(&" ".repeat(child_indent));
                            self.output.push_str("```\n");
                            for line in code_lines {
                                if !line.is_empty() {
                                    self.output.push_str(&" ".repeat(child_indent));
                                    self.output.push_str(&line);
                                }
                                self.output.push('\n');
                            }
                            self.output.push_str(&" ".repeat(child_indent));
                            self.output.push_str("```\n");
                        }
                        _ => {
                            // Other blocks (lists, etc.) - format with indentation
                            // format_node_sync(child, child_indent) already accounts for indent,
                            // so we can append its output directly.
                            let saved_output = self.output.clone();
                            self.output.clear();
                            self.format_node_sync(child, child_indent);
                            let formatted = self.output.clone();
                            self.output = saved_output;
                            self.output.push_str(&formatted);
                        }
                    }
                }

                // If no child blocks, just end with newline
                if child_blocks.is_empty() {
                    self.output.push('\n');
                }

                // Add blank line after footnote definition (matching Pandoc's behavior)
                if let Some(next) = node.next_sibling() {
                    let next_kind = next.kind();
                    if next_kind == SyntaxKind::FOOTNOTE_DEFINITION
                        && !self.output.ends_with("\n\n")
                    {
                        self.output.push('\n');
                    }
                }
            }

            SyntaxKind::HTML_BLOCK => {
                // Check if this is a directive comment
                if let Some(directive) = extract_directive_from_node(node) {
                    // Process the directive to update tracker state
                    self.directive_tracker.process_directive(&directive);

                    // Track when we enter an ignore region to preserve content
                    if matches!(directive, crate::directives::Directive::Start(_))
                        && self.directive_tracker.is_formatting_ignored()
                        && self.ignore_region_start.is_none()
                    {
                        self.ignore_region_start = Some(self.output.len());
                    }
                }

                // Output HTML block exactly as written
                let text = node.text().to_string();
                self.output.push_str(&text);
                if !text.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::COMMENT => {
                let text = node.text().to_string();

                // Check if this is a directive
                if let Some(directive) = extract_directive_from_node(node) {
                    // Process the directive to update tracker state
                    self.directive_tracker.process_directive(&directive);

                    // Track when we enter an ignore region to preserve content
                    if matches!(directive, crate::directives::Directive::Start(_))
                        && self.directive_tracker.is_formatting_ignored()
                        && self.ignore_region_start.is_none()
                    {
                        self.ignore_region_start = Some(self.output.len());
                    }
                }

                // Always output the comment itself
                self.output.push_str(&text);
                if !text.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::LATEX_COMMAND => {
                // Standalone LaTeX commands - preserve exactly as written
                let text = node.text().to_string();
                self.output.push_str(&text);
                // Don't add extra newlines for standalone LaTeX commands
            }

            SyntaxKind::TEX_BLOCK => {
                log::trace!("Formatting TeX block");
                // Raw blocks (LaTeX commands, etc.) - preserve verbatim
                // Just output all content as-is
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Token(t) => {
                            self.output.push_str(t.text());
                        }
                        rowan::NodeOrToken::Node(_) => {
                            // No child nodes in the simplified structure
                        }
                    }
                }

                // Ensure newline at end of raw block
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::BLOCK_QUOTE => {
                log::trace!("Formatting blockquote");
                // Determine nesting depth by counting ancestor BlockQuote nodes (including self)
                let depth = BlockQuote::cast(node.clone())
                    .map(|bq| bq.depth())
                    .unwrap_or(1);

                // Prefixes for quoted content and blank quoted lines
                let base_indent = " ".repeat(indent);
                let content_prefix = format!("{}{}", base_indent, "> ".repeat(depth)); // includes trailing space
                let blank_prefix = content_prefix.trim_end().to_string(); // no trailing space

                // Format children (paragraphs, blank lines) with proper > prefix per depth
                // NOTE: BlockQuoteMarker tokens are in the tree for losslessness, but we ignore
                // them during formatting and add prefixes dynamically instead.
                let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);

                for child in node.children() {
                    match child.kind() {
                        // Skip BlockQuoteMarker tokens - we add prefixes dynamically
                        SyntaxKind::BLOCK_QUOTE_MARKER => continue,

                        SyntaxKind::PARAGRAPH => match wrap_mode {
                            WrapMode::Preserve => {
                                // Build paragraph text while skipping BlockQuoteMarker tokens
                                // (they're in the tree for losslessness but we add prefixes dynamically)
                                let mut lines_text = String::new();
                                let mut skip_next_whitespace = false;
                                for item in child.children_with_tokens() {
                                    match item {
                                        NodeOrToken::Token(t)
                                            if t.kind() == SyntaxKind::BLOCK_QUOTE_MARKER =>
                                        {
                                            // Skip marker - we add these dynamically
                                            // Also skip the following whitespace (part of marker syntax)
                                            skip_next_whitespace = true;
                                        }
                                        NodeOrToken::Token(t)
                                            if t.kind() == SyntaxKind::WHITESPACE
                                                && skip_next_whitespace =>
                                        {
                                            // Skip whitespace after marker
                                            skip_next_whitespace = false;
                                        }
                                        NodeOrToken::Token(t) => {
                                            skip_next_whitespace = false;
                                            lines_text.push_str(t.text());
                                        }
                                        NodeOrToken::Node(n) => {
                                            skip_next_whitespace = false;
                                            lines_text.push_str(&n.text().to_string());
                                        }
                                    }
                                }

                                for line in lines_text.lines() {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(line);
                                    self.output.push('\n');
                                }
                            }
                            WrapMode::Reflow => {
                                let width =
                                    self.config.line_width.saturating_sub(content_prefix.len());
                                let lines = self.wrapped_lines_for_paragraph(&child, width);
                                for line in lines {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(&line);
                                    self.output.push('\n');
                                }
                            }
                            WrapMode::Sentence => {
                                let lines = self.sentence_lines_for_paragraph(&child);
                                for line in lines {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(&line);
                                    self.output.push('\n');
                                }
                            }
                        },
                        SyntaxKind::ALERT => {
                            let marker = child
                                .children_with_tokens()
                                .filter_map(|item| item.into_token())
                                .find(|tok| tok.kind() == SyntaxKind::ALERT_MARKER)
                                .map(|tok| tok.text().to_string())
                                .unwrap_or_else(|| "[!NOTE]".to_string());

                            self.output.push_str(&content_prefix);
                            self.output.push_str(&marker);
                            self.output.push('\n');

                            for alert_child in child.children() {
                                match alert_child.kind() {
                                    SyntaxKind::PARAGRAPH => match wrap_mode {
                                        WrapMode::Preserve => {
                                            let text = alert_child.text().to_string();
                                            for line in text.lines() {
                                                self.output.push_str(&content_prefix);
                                                self.output.push_str(line);
                                                self.output.push('\n');
                                            }
                                        }
                                        WrapMode::Reflow => {
                                            let width = self
                                                .config
                                                .line_width
                                                .saturating_sub(content_prefix.len());
                                            for line in self
                                                .wrapped_lines_for_paragraph(&alert_child, width)
                                            {
                                                self.output.push_str(&content_prefix);
                                                self.output.push_str(&line);
                                                self.output.push('\n');
                                            }
                                        }
                                        WrapMode::Sentence => {
                                            for line in
                                                self.sentence_lines_for_paragraph(&alert_child)
                                            {
                                                self.output.push_str(&content_prefix);
                                                self.output.push_str(&line);
                                                self.output.push('\n');
                                            }
                                        }
                                    },
                                    SyntaxKind::BLANK_LINE => {
                                        self.output.push_str(&blank_prefix);
                                        self.output.push('\n');
                                    }
                                    _ => {
                                        let saved_output = self.output.clone();
                                        let saved_line_width = self.config.line_width;
                                        self.output.clear();
                                        self.config.line_width = self
                                            .config
                                            .line_width
                                            .saturating_sub(content_prefix.len());
                                        self.format_node_sync(&alert_child, indent);
                                        let rendered = self.output.clone();
                                        self.config.line_width = saved_line_width;
                                        self.output = saved_output;

                                        for line in rendered.lines() {
                                            if line.is_empty() {
                                                self.output.push_str(&blank_prefix);
                                            } else if line.starts_with("> ") {
                                                self.output.push_str(&base_indent);
                                                self.output.push_str(line);
                                            } else {
                                                self.output.push_str(&content_prefix);
                                                self.output.push_str(line);
                                            }
                                            self.output.push('\n');
                                        }
                                    }
                                }
                            }
                        }
                        SyntaxKind::BLANK_LINE => {
                            self.output.push_str(&blank_prefix);
                            self.output.push('\n');
                        }
                        SyntaxKind::HORIZONTAL_RULE => {
                            self.output.push_str(&content_prefix);
                            let available_width =
                                self.config.line_width.saturating_sub(content_prefix.len());
                            self.output
                                .push_str(&self.horizontal_rule_text(available_width));
                            self.output.push('\n');
                        }
                        SyntaxKind::HEADING => {
                            // Format heading with blockquote prefix
                            let heading_text = self.format_heading(&child);
                            for line in heading_text.lines() {
                                self.output.push_str(&content_prefix);
                                self.output.push_str(line);
                                self.output.push('\n');
                            }
                            if let Some(next) = child.next_sibling()
                                && next.kind() != SyntaxKind::BLANK_LINE
                                && is_block_element(next.kind())
                            {
                                self.output.push_str(&blank_prefix);
                                self.output.push('\n');
                            }
                        }
                        SyntaxKind::LIST => {
                            // Format list with blockquote prefix
                            // Save current output, format list to temp, then prefix each line
                            let saved_output = self.output.clone();
                            let saved_line_width = self.config.line_width;
                            self.output.clear();
                            self.config.line_width =
                                self.config.line_width.saturating_sub(content_prefix.len());
                            self.format_node_sync(&child, indent);
                            let list_output = self.output.clone();
                            self.config.line_width = saved_line_width;
                            self.output = saved_output;

                            for line in list_output.lines() {
                                if line.is_empty() {
                                    self.output.push_str(&blank_prefix);
                                } else if line.starts_with("> ") {
                                    self.output.push_str(&base_indent);
                                    self.output.push_str(line);
                                } else {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(line);
                                }
                                self.output.push('\n');
                            }
                        }
                        SyntaxKind::CODE_BLOCK => {
                            // Format code block with blockquote prefix
                            // Save current output, format code block to temp, then prefix each line
                            let saved_output = self.output.clone();
                            self.output.clear();
                            self.format_node_sync(&child, indent);
                            let code_output = self.output.clone();
                            self.output = saved_output;

                            for line in code_output.lines() {
                                if line.is_empty() {
                                    self.output.push_str(&blank_prefix);
                                } else {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(line);
                                }
                                self.output.push('\n');
                            }
                        }
                        SyntaxKind::TEX_BLOCK => {
                            // Keep raw TeX content verbatim, but preserve blockquote prefixes.
                            let saved_output = self.output.clone();
                            self.output.clear();
                            self.format_node_sync(&child, indent);
                            let tex_output = self.output.clone();
                            self.output = saved_output;

                            for line in tex_output.lines() {
                                if line.is_empty() {
                                    self.output.push_str(&blank_prefix);
                                } else {
                                    self.output.push_str(&content_prefix);
                                    self.output.push_str(line);
                                }
                                self.output.push('\n');
                            }
                        }
                        _ => {
                            // Handle other content within block quotes
                            self.format_node_sync(&child, indent);
                        }
                    }
                }
            }

            SyntaxKind::PARAGRAPH => {
                let text = node.text().to_string();
                log::debug!("Formatting paragraph, text length: {}", text.len());
                let paragraph_indent = " ".repeat(indent);

                if self.is_grid_table_continuation_paragraph(node) {
                    if indent > 0 {
                        for (i, line) in text.lines().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                            }
                            self.output.push_str(&paragraph_indent);
                            self.output.push_str(line.trim_start());
                        }
                    } else {
                        self.output.push_str(&text);
                    }
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }

                if self.config.extensions.bookdown_references
                    && paragraphs::is_bookdown_text_reference(node)
                {
                    if indent > 0 {
                        for (i, line) in text.lines().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                            }
                            self.output.push_str(&paragraph_indent);
                            self.output.push_str(line.trim_start());
                        }
                    } else {
                        self.output.push_str(&text);
                    }
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }

                let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);
                let preserve_newlines_for_latex =
                    self.fenced_div_depth > 0 && self.contains_latex_command(node);
                if preserve_newlines_for_latex && self.fenced_div_depth > 0 {
                    if indent > 0 {
                        for (i, line) in text.lines().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                            }
                            self.output.push_str(&paragraph_indent);
                            self.output.push_str(line.trim_start());
                        }
                    } else {
                        self.output.push_str(&text);
                    }
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }
                log::debug!(
                    "Paragraph wrap mode: {:?}, line_width: {}",
                    wrap_mode,
                    line_width
                );
                match wrap_mode {
                    WrapMode::Preserve => {
                        log::trace!("Preserving paragraph line breaks");
                        if indent > 0 {
                            for (i, line) in text.lines().enumerate() {
                                if i > 0 {
                                    self.output.push('\n');
                                }
                                self.output.push_str(&paragraph_indent);
                                self.output.push_str(line.trim_start());
                            }
                        } else {
                            self.output.push_str(&text);
                        }
                        if !self.output.ends_with('\n') {
                            self.output.push('\n');
                        }
                    }
                    WrapMode::Reflow => {
                        log::trace!("Reflowing paragraph to {} width", line_width);
                        let lines = self.wrapped_lines_for_paragraph(node, line_width);

                        for (i, line) in lines.iter().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                            }
                            if indent > 0 {
                                self.output.push_str(&paragraph_indent);
                            }
                            self.output.push_str(line);
                        }
                    }
                    WrapMode::Sentence => {
                        log::trace!("Wrapping paragraph by sentence");
                        let lines = self.sentence_lines_for_paragraph(node);

                        for (i, line) in lines.iter().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                            }
                            if indent > 0 {
                                self.output.push_str(&paragraph_indent);
                            }
                            self.output.push_str(line);
                        }
                    }
                }

                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::FIGURE => {
                // Figure is a standalone image - format the inline content directly
                log::debug!("Formatting figure");
                let text = self.format_inline_node(node);
                let trimmed = text.trim();
                if indent > 0 {
                    self.output.push_str(&" ".repeat(indent));
                }
                self.output.push_str(trimmed);
                self.output.push('\n');
            }

            SyntaxKind::PLAIN => {
                // Plain is like PARAGRAPH but for tight contexts (definition lists, table cells)
                // Apply wrapping with continuation indentation
                let text = node.text().to_string();
                log::debug!("Formatting Plain block, text length: {}", text.len());

                let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);
                let needs_indent = indent > 0
                    && (self.output.ends_with('\n') || self.output.is_empty())
                    && !self.output.ends_with(":   ");
                match wrap_mode {
                    WrapMode::Preserve => {
                        if needs_indent {
                            for line in text.lines() {
                                self.output.push_str(&" ".repeat(indent));
                                self.output.push_str(line.trim_start());
                                self.output.push('\n');
                            }
                        } else {
                            self.output.push_str(&text);
                            if !self.output.ends_with('\n') {
                                self.output.push('\n');
                            }
                        }
                    }
                    WrapMode::Reflow => {
                        log::trace!("Reflowing Plain block to {} width", line_width);
                        let in_definition = self.output.ends_with(":   ");
                        let preserve_ambiguous_definition_emphasis =
                            in_definition && text.contains(r"\|*") && text.contains(".*");
                        let lines = if in_definition {
                            if preserve_ambiguous_definition_emphasis {
                                text.lines().map(ToString::to_string).collect()
                            } else {
                                let marker_len = ":   ".len();
                                let marker_indent = indent.saturating_sub(4);
                                let first_line_space =
                                    line_width.saturating_sub(marker_indent + marker_len);
                                let continuation_width = line_width.saturating_sub(indent);
                                let widths = [first_line_space, continuation_width];
                                self.wrapped_lines_for_paragraph_with_widths(node, &widths)
                            }
                        } else {
                            self.wrapped_lines_for_paragraph(node, line_width)
                        };

                        for (i, line) in lines.iter().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                                // Add continuation indent for wrapped lines
                                self.output.push_str(&" ".repeat(indent));
                            } else if needs_indent {
                                self.output.push_str(&" ".repeat(indent));
                            }
                            let rendered = if i > 0 && indent > 0 {
                                line.trim_start()
                            } else {
                                line.as_str()
                            };
                            self.output.push_str(rendered);
                        }

                        if !self.output.ends_with('\n') {
                            self.output.push('\n');
                        }
                    }
                    WrapMode::Sentence => {
                        log::trace!("Wrapping Plain block by sentence");
                        let in_definition = self.output.ends_with(":   ");
                        let preserve_ambiguous_definition_emphasis =
                            in_definition && text.contains(r"\|*") && text.contains(".*");
                        let lines = if preserve_ambiguous_definition_emphasis {
                            text.lines().map(ToString::to_string).collect()
                        } else {
                            self.sentence_lines_for_paragraph(node)
                        };

                        for (i, line) in lines.iter().enumerate() {
                            if i > 0 {
                                self.output.push('\n');
                                self.output.push_str(&" ".repeat(indent));
                            } else if needs_indent {
                                self.output.push_str(&" ".repeat(indent));
                            }
                            let rendered = if i > 0 && indent > 0 {
                                line.trim_start()
                            } else {
                                line.as_str()
                            };
                            self.output.push_str(rendered);
                        }

                        if !self.output.ends_with('\n') {
                            self.output.push('\n');
                        }
                    }
                }
            }

            SyntaxKind::LIST => {
                self.format_list(node, indent);
            }

            SyntaxKind::DEFINITION_LIST => {
                if self.is_grid_table_caption_definition_list(node) {
                    self.output.push_str(&node.text().to_string());
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }
                // Add blank line before top-level definition lists
                if indent == 0 && !self.output.is_empty() && !self.output.ends_with("\n\n") {
                    self.output.push('\n');
                }
                let mut saw_item = false;
                for child in node.children() {
                    if child.kind() == SyntaxKind::BLANK_LINE {
                        continue;
                    }
                    if child.kind() == SyntaxKind::DEFINITION_ITEM {
                        if saw_item && !self.output.ends_with("\n\n") {
                            self.output.push('\n');
                        }
                        saw_item = true;
                    }
                    self.format_node_sync(&child, indent);
                }
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::LINE_BLOCK => {
                log::debug!("Formatting line block");
                // Add blank line before line blocks if not at start
                if !self.output.is_empty() && !self.output.ends_with("\n\n") {
                    self.output.push('\n');
                }

                // Format each line preserving line breaks and leading spaces
                for child in node.children() {
                    if child.kind() == SyntaxKind::LINE_BLOCK_LINE {
                        // Get the text content, preserving leading spaces
                        let text = child.text().to_string();
                        if text.trim_end() == "|" {
                            self.output.push('|');
                            self.output.push('\n');
                            continue;
                        }
                        // The text might start with "| " from the marker, or be continuation
                        // We need to skip the marker if present and output the rest
                        let content = if let Some(stripped) = text.strip_prefix("| ") {
                            stripped
                        } else {
                            // Continuation line - output as-is but with proper marker
                            text.trim_start()
                        };

                        // Output the marker
                        // Check if content is empty or just whitespace/newline
                        let content_trimmed = content.trim();
                        if content_trimmed.is_empty() {
                            // Empty line block line - just output "|"
                            self.output.push('|');
                        } else {
                            // Normal line - output "| " followed by content
                            self.output.push_str("| ");
                            self.output.push_str(content.trim_end());
                        }
                        self.output.push('\n');
                    }
                }

                // Add blank line after if followed by block element
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                }
            }

            SyntaxKind::DEFINITION_ITEM => {
                let is_compact_by_structure = DefinitionItem::cast(node.clone())
                    .map(|item| item.is_compact())
                    .unwrap_or(true);
                let mut has_blank_between_term_and_first_definition = false;
                let mut seen_term = false;
                let mut seen_definition = false;

                for child in node.children() {
                    match child.kind() {
                        SyntaxKind::TERM => {
                            seen_term = true;
                        }
                        SyntaxKind::BLANK_LINE => {
                            if seen_term && !seen_definition {
                                has_blank_between_term_and_first_definition = true;
                            }
                        }
                        SyntaxKind::DEFINITION => {
                            seen_definition = true;
                        }
                        _ => {}
                    }
                }

                let is_compact =
                    is_compact_by_structure && !has_blank_between_term_and_first_definition;
                let mut saw_term = false;

                for child in node.children() {
                    match child.kind() {
                        SyntaxKind::BLANK_LINE => {
                            // Ignore source blank lines and normalize based on AST structure.
                        }
                        SyntaxKind::TERM => {
                            self.format_node_sync(&child, indent);
                            saw_term = true;
                        }
                        SyntaxKind::DEFINITION => {
                            if saw_term {
                                if is_compact {
                                    if !self.output.ends_with('\n') {
                                        self.output.push('\n');
                                    }
                                } else if !self.output.ends_with("\n\n") {
                                    self.output.push('\n');
                                }
                            } else if !self.output.is_empty() && !self.output.ends_with('\n') {
                                self.output.push('\n');
                            }
                            self.format_node_sync(&child, indent);
                        }
                        _ => self.format_node_sync(&child, indent),
                    }
                }
            }

            SyntaxKind::TERM => {
                // Format term - just emit text with newline
                for child in node.children_with_tokens() {
                    match child {
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::TEXT => {
                            self.output.push_str(tok.text());
                        }
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::NEWLINE => {
                            self.output.push('\n');
                        }
                        NodeOrToken::Node(n) => {
                            self.format_node_sync(&n, indent);
                        }
                        _ => {}
                    }
                }
            }

            SyntaxKind::DEFINITION => {
                // Format definition with marker and content
                // The definition marker itself is at the base indent level
                // Definition content is indented 4 spaces from the margin
                let def_indent = indent + 4;
                let wrap_mode = self.config.wrap.clone().unwrap_or(WrapMode::Reflow);

                // Emit base indentation before the marker
                if indent > 0 {
                    self.output.push_str(&" ".repeat(indent));
                }
                self.output.push_str(":   ");

                // Collect children to determine lazy continuation
                let children: Vec<_> = node.children_with_tokens().collect();
                let mut first_para_idx = None;

                // Find first paragraph immediately after initial text (lazy continuation)
                // It's only lazy if there's no BlankLine before it
                let mut text_idx = None;
                for (i, child) in children.iter().enumerate() {
                    if let NodeOrToken::Token(tok) = child
                        && tok.kind() == SyntaxKind::TEXT
                    {
                        text_idx = Some(i);
                    }
                }

                // Check if there's a paragraph immediately after TEXT+NEWLINE (no BlankLine)
                if let Some(tidx) = text_idx {
                    for (i, child) in children.iter().enumerate().skip(tidx + 1) {
                        if let NodeOrToken::Node(n) = child {
                            match n.kind() {
                                SyntaxKind::PARAGRAPH => {
                                    first_para_idx = Some(i);
                                    break;
                                }
                                SyntaxKind::BLANK_LINE => {
                                    // BlankLine before paragraph - not lazy
                                    break;
                                }
                                _ => {}
                            }
                        }
                    }
                }

                for (i, child) in children.iter().enumerate() {
                    match child {
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::TEXT => {
                            self.output.push_str(tok.text());
                        }
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::NEWLINE => {
                            // If next child is the first lazy paragraph, add space instead
                            if first_para_idx.is_some_and(|idx| i + 1 == idx) {
                                self.output.push(' ');
                            } else {
                                self.output.push('\n');
                            }
                        }
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::DEFINITION_MARKER => {
                            // Skip - we already added `:   `
                        }
                        NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::WHITESPACE => {
                            // Skip - we normalize spacing
                        }
                        NodeOrToken::Node(n) => {
                            // Handle continuation content with proper indentation
                            match n.kind() {
                                SyntaxKind::CODE_BLOCK => {
                                    if self.output.ends_with(":   ") {
                                        self.format_container_code_block(
                                            n, "", def_indent, true, true, false,
                                        );
                                    } else {
                                        // Add blank line before code block if needed
                                        if !self.output.ends_with("\n\n") {
                                            self.output.push('\n');
                                        }
                                        self.format_indented_code_block(n, def_indent);
                                    }
                                }
                                SyntaxKind::PLAIN => {
                                    // Plain block in definition - format inline with potential wrapping
                                    // Already handled by Plain formatter above
                                    if let Some((heading_line, remainder)) =
                                        self.leading_atx_heading_with_remainder(n)
                                    {
                                        self.output.push_str(&heading_line);
                                        self.output.push('\n');
                                        self.output.push('\n');
                                        for line in
                                            self.wrap_text_for_indent(&remainder, def_indent)
                                        {
                                            self.output.push_str(&" ".repeat(def_indent));
                                            self.output.push_str(line.trim_start());
                                            self.output.push('\n');
                                        }
                                    } else {
                                        self.format_node_sync(n, def_indent);
                                    }
                                }
                                SyntaxKind::PARAGRAPH => {
                                    if first_para_idx == Some(i) {
                                        // First paragraph - lazy continuation (inline, wrapped)
                                        let marker_len = ":   ".len();
                                        let first_line_space = self
                                            .config
                                            .line_width
                                            .saturating_sub(indent + marker_len);
                                        let available_width =
                                            self.config.line_width.saturating_sub(def_indent);
                                        let widths = [first_line_space, available_width];

                                        let lines = match wrap_mode {
                                            WrapMode::Preserve => {
                                                let text = n.text().to_string();
                                                text.lines().map(|line| line.to_string()).collect()
                                            }
                                            WrapMode::Reflow => self
                                                .wrapped_lines_for_paragraph_with_widths(
                                                    n, &widths,
                                                ),
                                            WrapMode::Sentence => {
                                                self.sentence_lines_for_paragraph(n)
                                            }
                                        };

                                        if !lines.is_empty() {
                                            self.output.push_str(&lines[0]);
                                            self.output.push('\n');
                                            for line in lines.iter().skip(1) {
                                                self.output.push_str(&" ".repeat(def_indent));
                                                self.output.push_str(line.trim_start());
                                                self.output.push('\n');
                                            }
                                        }
                                    } else {
                                        // Subsequent paragraphs - indented continuation
                                        if !self.output.ends_with("\n\n") {
                                            self.output.push('\n');
                                        }
                                        self.format_list_continuation_paragraph(n, def_indent);
                                    }
                                }
                                SyntaxKind::BLANK_LINE => {
                                    // Normalize blank lines in definitions to just newlines
                                    // (strip trailing whitespace)
                                    let is_before_first_para =
                                        first_para_idx.is_some_and(|idx| i < idx);

                                    if !is_before_first_para {
                                        self.output.push('\n');
                                    }
                                }
                                SyntaxKind::LIST => {
                                    let start = self.output.len();
                                    self.format_node_sync(n, def_indent);

                                    if self.output[..start].ends_with(":   ")
                                        && self.output[start..].starts_with(&" ".repeat(def_indent))
                                    {
                                        self.output.drain(start..start + def_indent);
                                    }
                                }
                                SyntaxKind::BLOCK_QUOTE => {
                                    if self.output.ends_with(":   ") {
                                        let mut pieces: Vec<String> = Vec::new();
                                        let block_text = n.text().to_string();
                                        for line in block_text.lines() {
                                            let trimmed = line.trim_start();
                                            let content =
                                                if let Some(rest) = trimmed.strip_prefix('>') {
                                                    rest.trim_start()
                                                } else {
                                                    trimmed
                                                };
                                            if !content.is_empty() {
                                                pieces.push(content.to_string());
                                            }
                                        }

                                        self.output.push_str("> ");
                                        self.output.push_str(&pieces.join(" "));
                                        self.output.push('\n');

                                        if let Some(next_non_blank) =
                                            node.children().skip(i + 1).find(|sibling| {
                                                sibling.kind() != SyntaxKind::BLANK_LINE
                                            })
                                            && is_block_element(next_non_blank.kind())
                                            && !self.output.ends_with("\n\n")
                                        {
                                            self.output.push('\n');
                                        }
                                    } else {
                                        self.format_node_sync(n, def_indent);
                                    }
                                }
                                _ => {
                                    self.format_node_sync(n, def_indent);
                                }
                            }
                        }
                        _ => {}
                    }
                }
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
            }

            SyntaxKind::SIMPLE_TABLE => {
                log::trace!("Formatting simple table");
                let formatted = tables::format_simple_table(node, &self.config);
                self.output.push_str(&formatted);

                // Ensure blank line after if followed by block element
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                }
            }

            SyntaxKind::MULTILINE_TABLE => {
                // Format multiline table with proper alignment and column widths
                let formatted = tables::format_multiline_table(node, &self.config);
                self.output.push_str(&formatted);
            }

            SyntaxKind::PIPE_TABLE => {
                // Format pipe table with proper alignment
                let formatted = tables::format_pipe_table(node, &self.config);
                self.output.push_str(&formatted);
            }

            SyntaxKind::GRID_TABLE => {
                if let Some(next) = node.next_sibling()
                    && self.is_grid_table_continuation_paragraph(&next)
                {
                    self.output.push_str(&node.text().to_string());
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }
                // Format grid table with proper alignment and borders
                let formatted = tables::format_grid_table(node, &self.config);
                self.output.push_str(&formatted);
            }

            SyntaxKind::INLINE_MATH => {
                // Check if this is display math (has DisplayMathMarker)
                let is_display_math = node.children_with_tokens().any(|t| {
                    matches!(t, NodeOrToken::Token(tok) if tok.kind() == SyntaxKind::DISPLAY_MATH_MARKER)
                });

                // Get the actual content (TEXT token, not node)
                let content = node
                    .children_with_tokens()
                    .find_map(|c| match c {
                        NodeOrToken::Token(t) if t.kind() == SyntaxKind::TEXT => {
                            Some(t.text().to_string())
                        }
                        _ => None,
                    })
                    .unwrap_or_default();

                // Get original marker to determine input format
                let original_marker = node
                    .children_with_tokens()
                    .find_map(|t| match t {
                        NodeOrToken::Token(tok)
                            if tok.kind() == SyntaxKind::INLINE_MATH_MARKER
                                || tok.kind() == SyntaxKind::DISPLAY_MATH_MARKER =>
                        {
                            Some(tok.text().to_string())
                        }
                        _ => None,
                    })
                    .unwrap_or_else(|| "$".to_string());

                // Determine output format based on config
                use crate::config::MathDelimiterStyle;
                let (open, close) = match self.config.math_delimiter_style {
                    MathDelimiterStyle::Preserve => {
                        // Keep original format
                        if is_display_math {
                            match original_marker.as_str() {
                                "\\[" => (r"\[", r"\]"),
                                "\\\\[" => (r"\\[", r"\\]"),
                                _ => ("$$", "$$"), // Default to $$
                            }
                        } else {
                            match original_marker.as_str() {
                                "$`" => ("$`", "`$"),
                                r"\(" => (r"\(", r"\)"),
                                r"\\(" => (r"\\(", r"\\)"),
                                _ => ("$", "$"), // Default to $
                            }
                        }
                    }
                    MathDelimiterStyle::Dollars => {
                        // Normalize to dollars
                        if is_display_math {
                            ("$$", "$$")
                        } else {
                            ("$", "$")
                        }
                    }
                    MathDelimiterStyle::Backslash => {
                        // Normalize to single backslash
                        if is_display_math {
                            (r"\[", r"\]")
                        } else {
                            (r"\(", r"\)")
                        }
                    }
                };

                // Output formatted math
                if is_display_math {
                    self.output.push_str(open);
                    self.output.push(' ');
                    self.output.push_str(&content);
                    self.output.push(' ');
                    self.output.push_str(close);
                } else {
                    self.output.push_str(open);
                    self.output.push_str(&content);
                    self.output.push_str(close);
                }
            }

            SyntaxKind::LIST_ITEM => {
                self.format_list_item(node, indent);
            }

            SyntaxKind::FENCED_DIV => {
                let Some(fenced_div) = FencedDiv::cast(node.clone()) else {
                    self.output.push_str(&node.text().to_string());
                    return;
                };

                let opening_has_trailing_inline_text =
                    fenced_div.opening_fence().is_some_and(|open| {
                        let mut saw_info = false;
                        for child in open.syntax().children_with_tokens() {
                            match child {
                                rowan::NodeOrToken::Node(n) if n.kind() == SyntaxKind::DIV_INFO => {
                                    saw_info = true;
                                }
                                rowan::NodeOrToken::Token(t)
                                    if saw_info && t.kind() == SyntaxKind::TEXT =>
                                {
                                    let trimmed = t.text().trim();
                                    if !trimmed.is_empty() && !trimmed.chars().all(|c| c == ':') {
                                        return true;
                                    }
                                }
                                _ => {}
                            }
                        }
                        false
                    });
                if opening_has_trailing_inline_text {
                    // Preserve malformed one-line div text verbatim to keep parser shape stable
                    // across format passes. Trimming can shift boundary ownership of following
                    // blank lines and break idempotency.
                    self.output.push_str(&node.text().to_string());
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }

                let has_close = fenced_div.has_closing_fence();
                let has_content = fenced_div
                    .body_blocks()
                    .any(|child| child.kind() != SyntaxKind::BLANK_LINE);
                let leading_blank_lines = fenced_div
                    .body_blocks()
                    .take_while(|child| child.kind() == SyntaxKind::BLANK_LINE)
                    .count();

                // Preserve malformed one-line divs verbatim. Patterns like
                // `::: {.callout} inline :::` can parse as an opening fence with
                // trailing text but no body/closing node; normalizing them creates
                // unstable nesting and loses inline content.
                if !has_close && !has_content {
                    if let Some(open) = fenced_div.opening_fence() {
                        self.output
                            .push_str(open.syntax().text().to_string().trim_end_matches('\n'));
                    } else {
                        self.output
                            .push_str(node.text().to_string().trim_end_matches('\n'));
                    }
                    if !self.output.ends_with('\n') {
                        self.output.push('\n');
                    }
                    return;
                }

                let source_opening_colons = fenced_div
                    .opening_fence()
                    .map(|open| {
                        open.syntax()
                            .text()
                            .to_string()
                            .trim_start()
                            .chars()
                            .take_while(|&c| c == ':')
                            .count()
                    })
                    .unwrap_or(3)
                    .max(3);
                let in_list_item = node
                    .ancestors()
                    .any(|ancestor| ancestor.kind() == SyntaxKind::LIST_ITEM);
                let depth_encoded_colons = 3 + (self.fenced_div_depth * 2);
                let opening_colons = if in_list_item {
                    source_opening_colons
                } else {
                    depth_encoded_colons
                };
                let colons = ":".repeat(opening_colons);

                let attributes = fenced_div.info_text();
                // Emit normalized opening fence
                if !has_close && !has_content {
                    self.output.push_str(&" ".repeat(indent));
                    if let Some(attrs) = &attributes
                        && !attrs.is_empty()
                    {
                        self.output.push_str(&colons);
                        self.output.push(' ');
                        self.output.push_str(attrs);
                        self.output.push('\n');
                        return;
                    }
                } else {
                    self.output.push_str(&" ".repeat(indent));
                    self.output.push_str(&colons);
                    if let Some(attrs) = &attributes
                        && !attrs.is_empty()
                    {
                        self.output.push(' ');
                        self.output.push_str(attrs);
                    }
                    self.output.push('\n');
                }

                // Increment depth for nested content
                self.fenced_div_depth += 1;

                // Process content
                let content_children: Vec<_> = node
                    .children()
                    .filter(|child| {
                        !matches!(
                            child.kind(),
                            SyntaxKind::DIV_FENCE_OPEN
                                | SyntaxKind::DIV_INFO
                                | SyntaxKind::DIV_FENCE_CLOSE
                        )
                    })
                    .collect();

                let end = content_children.len();
                let first_non_blank_kind = content_children[0..end]
                    .iter()
                    .find(|child| child.kind() != SyntaxKind::BLANK_LINE)
                    .map(|child| child.kind());
                let should_strip_leading_blanks = matches!(
                    first_non_blank_kind,
                    Some(
                        SyntaxKind::PARAGRAPH
                            | SyntaxKind::PLAIN
                            | SyntaxKind::LIST
                            | SyntaxKind::LIST_ITEM
                    )
                );
                let start = if should_strip_leading_blanks {
                    leading_blank_lines
                } else {
                    0
                };

                for (idx, child) in content_children[start..end].iter().enumerate() {
                    if child.kind() == SyntaxKind::BLANK_LINE {
                        if idx < leading_blank_lines
                            && matches!(
                                first_non_blank_kind,
                                Some(SyntaxKind::LIST | SyntaxKind::LIST_ITEM)
                            )
                        {
                            continue;
                        }
                        self.output.push('\n');
                    } else if child.kind() == SyntaxKind::CODE_BLOCK && indent > 0 {
                        self.format_indented_code_block(child, indent);
                        if let Some(next) = content_children[start..end].get(idx + 1)
                            && ((next.kind() == SyntaxKind::PARAGRAPH
                                && next.text().to_string().trim_start().starts_with(":::"))
                                || (next.kind() == SyntaxKind::PLAIN
                                    && next.text().to_string().trim_start().starts_with(":::"))
                                || next.kind() == SyntaxKind::FENCED_DIV)
                            && !self.output.ends_with("\n\n")
                        {
                            self.output.push('\n');
                        }
                    } else {
                        self.format_node_sync(child, indent);
                    }
                }

                // Decrement depth after processing content
                self.fenced_div_depth -= 1;

                // Emit closing fence using the opener's colon count.
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
                self.output.push_str(&" ".repeat(indent));
                self.output.push_str(&":".repeat(opening_colons));
                self.output.push('\n');

                // Reset blank line tracking so outer blocks don't suppress separation.
                self.consecutive_blank_lines = 0;

                // Ensure blank line after if followed by block element
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && !self.output.ends_with("\n\n")
                {
                    // In list items, keep separator for continuation block content
                    // (e.g. list marker or paragraph) but avoid adding extra space
                    // before nested structural blocks that already manage spacing.
                    let needs_separator = if in_list_item {
                        matches!(
                            next.kind(),
                            SyntaxKind::PARAGRAPH | SyntaxKind::PLAIN | SyntaxKind::LIST
                        )
                    } else {
                        true
                    };
                    if needs_separator {
                        self.output.push('\n');
                        self.consecutive_blank_lines = 1;
                    }
                }
            }

            SyntaxKind::INLINE_MATH_MARKER => {
                // Output inline math as $...$ or $$...$$ (on the same line)
                self.output.push_str(node.text().to_string().trim());
            }

            SyntaxKind::DISPLAY_MATH => {
                // Display math ($$...$$) - format on separate lines
                // Even though it's parsed as inline, it should display as block-level

                let Some(display_math) = DisplayMath::cast(node.clone()) else {
                    self.output.push_str(&node.text().to_string());
                    return;
                };

                let math_content = Some(display_math.content());

                // Default to $$ if markers not found
                let opening_value = display_math
                    .opening_marker()
                    .unwrap_or_else(|| "$$".to_string());
                let closing_value = display_math
                    .closing_marker()
                    .unwrap_or_else(|| "$$".to_string());
                let opening = opening_value.as_str();
                let closing_from_tree = closing_value.as_str();
                let is_environment = display_math.is_environment_form();

                // Apply delimiter style preference
                use crate::config::MathDelimiterStyle;
                let (open, close) = if is_environment {
                    (opening, closing_from_tree)
                } else {
                    match self.config.math_delimiter_style {
                        MathDelimiterStyle::Preserve => (opening, closing_from_tree),
                        MathDelimiterStyle::Dollars => ("$$", "$$"),
                        MathDelimiterStyle::Backslash => (r"\[", r"\]"),
                    }
                };

                if is_environment {
                    self.output.push_str(open);
                    if let Some(content) = math_content {
                        self.output.push_str(&content);
                        if !content.ends_with('\n') {
                            self.output.push('\n');
                        }
                    }
                    self.output.push_str(close);
                    self.output.push('\n');
                    return;
                }

                // Opening fence
                self.output.push('\n');
                self.output.push_str(open);
                self.output.push('\n');

                // Math content
                if let Some(content) = math_content {
                    let math_indent = self.config.math_indent;
                    for line in content.trim().lines() {
                        self.output.push_str(&" ".repeat(math_indent));
                        self.output.push_str(line.trim_end());
                        self.output.push('\n');
                    }
                }

                // Closing fence
                self.output.push_str(close);
                self.output.push('\n');
            }

            SyntaxKind::CODE_BLOCK => {
                log::trace!("Formatting code block");

                // Add blank line before code block if it follows a paragraph
                // This matches Pandoc's formatting behavior
                if let Some(prev_sibling) = node.prev_sibling()
                    && prev_sibling.kind() == SyntaxKind::PARAGRAPH
                {
                    // Only add blank line if we don't already have one
                    if !self.output.ends_with("\n\n") && !self.output.ends_with("\n \n") {
                        self.output.push('\n');
                    }
                }

                // Normalize code blocks to use backticks
                self.format_code_block(node);
            }

            SyntaxKind::YAML_METADATA
            | SyntaxKind::PANDOC_TITLE_BLOCK
            | SyntaxKind::MMD_TITLE_BLOCK => {
                // Preserve these blocks as-is
                let text = node.text().to_string();
                self.output.push_str(&text);
                // Ensure these blocks end with appropriate spacing
                if !text.ends_with('\n') {
                    self.output.push('\n');
                }
                // Ensure blank line after if followed by block element.
                if let Some(next) = node.next_sibling()
                    && is_block_element(next.kind())
                    && !self.output.ends_with("\n\n")
                {
                    self.output.push('\n');
                    self.consecutive_blank_lines = 1;
                }
            }

            SyntaxKind::BLANK_LINE => {
                // BlankLine nodes preserve exact whitespace in the CST for losslessness
                // But when formatting, we normalize to just newlines (no trailing spaces)
                // Drop blank lines at beginning of document output.
                if self.output.is_empty() {
                    return;
                }
                // Limit consecutive blank lines to 1
                if self.consecutive_blank_lines < 1 {
                    self.output.push('\n');
                    self.consecutive_blank_lines += 1;
                }
            }

            SyntaxKind::EMPHASIS => {
                // Normalize emphasis to always use single asterisks
                self.output.push('*');
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Node(n) => self.format_node_sync(&n, indent),
                        rowan::NodeOrToken::Token(t) => {
                            if t.kind() != SyntaxKind::EMPHASIS_MARKER {
                                self.output.push_str(t.text());
                            }
                        }
                    }
                }
                self.output.push('*');
            }

            SyntaxKind::STRONG => {
                // Normalize strong emphasis to always use double asterisks
                self.output.push_str("**");
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Node(n) => self.format_node_sync(&n, indent),
                        rowan::NodeOrToken::Token(t) => {
                            if t.kind() != SyntaxKind::STRONG_MARKER {
                                self.output.push_str(t.text());
                            }
                        }
                    }
                }
                self.output.push_str("**");
            }

            SyntaxKind::STRIKEOUT => {
                // Format strikeout with tildes
                self.output.push_str("~~");
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Node(n) => self.format_node_sync(&n, indent),
                        rowan::NodeOrToken::Token(t) => {
                            if t.kind() != SyntaxKind::STRIKEOUT_MARKER {
                                self.output.push_str(t.text());
                            }
                        }
                    }
                }
                self.output.push_str("~~");
            }

            SyntaxKind::SUPERSCRIPT => {
                // Format superscript with carets
                self.output.push('^');
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Node(n) => self.format_node_sync(&n, indent),
                        rowan::NodeOrToken::Token(t) => {
                            if t.kind() != SyntaxKind::SUPERSCRIPT_MARKER {
                                self.output.push_str(t.text());
                            }
                        }
                    }
                }
                self.output.push('^');
            }

            SyntaxKind::SUBSCRIPT => {
                // Format subscript with tildes
                self.output.push('~');
                for child in node.children_with_tokens() {
                    match child {
                        rowan::NodeOrToken::Node(n) => self.format_node_sync(&n, indent),
                        rowan::NodeOrToken::Token(t) => {
                            if t.kind() != SyntaxKind::SUBSCRIPT_MARKER {
                                self.output.push_str(t.text());
                            }
                        }
                    }
                }
                self.output.push('~');
            }

            _ => {
                // Fallback: append node text (should be rare with children_with_tokens above)
                self.output.push_str(&node.text().to_string());
            }
        }
    }
}

fn normalize_attribute_text(attr_text: &str) -> String {
    let Some(inner) = attr_text
        .strip_prefix('{')
        .and_then(|s| s.strip_suffix('}'))
    else {
        return attr_text.to_string();
    };
    let Some(attrs) = parse_attribute_content(inner) else {
        return attr_text.to_string();
    };

    let mut out = String::from("{");
    if let Some(id) = attrs.identifier {
        out.push('#');
        out.push_str(&id);
    }
    for class in attrs.classes {
        if out.len() > 1 {
            out.push(' ');
        }
        if class.starts_with('=') {
            out.push_str(&class);
        } else {
            out.push('.');
            out.push_str(&class);
        }
    }
    for (key, value) in attrs.key_values {
        if out.len() > 1 {
            out.push(' ');
        }
        out.push_str(&key);
        out.push('=');
        out.push('"');
        out.push_str(&value.replace('"', "\\\""));
        out.push('"');
    }
    out.push('}');
    out
}