panache-parser 0.1.0

Lossless CST parser and syntax wrappers for Pandoc markdown, Quarto, and RMarkdown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use globset::GlobBuilder;
use serde::{Deserialize, Deserializer, Serialize};

mod formatter_presets;
pub use formatter_presets::FormatterPresetMetadata;

/// The flavor of Markdown to parse and format.
/// Each flavor has a different set of default extensions enabled.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum Flavor {
    /// Standard Pandoc Markdown (default extensions enabled)
    #[default]
    Pandoc,
    /// Quarto (Pandoc + Quarto-specific extensions)
    Quarto,
    /// R Markdown (Pandoc + R-specific extensions)
    #[serde(rename = "rmarkdown")]
    RMarkdown,
    /// GitHub Flavored Markdown
    Gfm,
    /// CommonMark
    CommonMark,
    /// MultiMarkdown
    #[serde(rename = "multimarkdown")]
    MultiMarkdown,
}

/// Pandoc/Markdown extensions configuration.
/// Each field represents a specific Pandoc extension.
/// Extensions marked with a comment indicate implementation status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct Extensions {
    // ===== Block-level extensions =====

    // Headings
    /// Require blank line before headers (default: enabled)
    #[serde(alias = "blank_before_header")]
    pub blank_before_header: bool,
    /// Full attribute syntax on headers {#id .class key=value}
    #[serde(alias = "header_attributes")]
    pub header_attributes: bool,
    /// Auto-generate identifiers from headings
    pub auto_identifiers: bool,
    /// Use GitHub's algorithm for auto-generated heading identifiers
    pub gfm_auto_identifiers: bool,
    /// Implicit header references ([Heading] links to header)
    pub implicit_header_references: bool,

    // Block quotes
    /// Require blank line before blockquotes (default: enabled)
    #[serde(alias = "blank_before_blockquote")]
    pub blank_before_blockquote: bool,

    // Lists
    /// Fancy list markers (roman numerals, letters, etc.)
    #[serde(alias = "fancy_lists")]
    pub fancy_lists: bool,
    /// Start ordered lists at arbitrary numbers
    pub startnum: bool,
    /// Example lists with (@) markers
    #[serde(alias = "example_lists")]
    pub example_lists: bool,
    /// GitHub-style task lists - [ ] and - [x]
    #[serde(alias = "task_lists")]
    pub task_lists: bool,
    /// Term/definition syntax
    #[serde(alias = "definition_lists")]
    pub definition_lists: bool,

    // Code blocks
    /// Fenced code blocks with backticks
    #[serde(alias = "backtick_code_blocks")]
    pub backtick_code_blocks: bool,
    /// Fenced code blocks with tildes
    #[serde(alias = "fenced_code_blocks")]
    pub fenced_code_blocks: bool,
    /// Attributes on fenced code blocks {.language #id}
    #[serde(alias = "fenced_code_attributes")]
    pub fenced_code_attributes: bool,
    /// Executable code syntax (currently fenced chunks like ```{r} / ```{python})
    pub executable_code: bool,
    /// R Markdown inline executable code (`...`r ...)
    pub rmarkdown_inline_code: bool,
    /// Quarto inline executable code (`...`{r} ...)
    pub quarto_inline_code: bool,
    /// Attributes on inline code
    #[serde(alias = "inline_code_attributes")]
    pub inline_code_attributes: bool,

    // Tables
    /// Simple table syntax
    #[serde(alias = "simple_tables")]
    pub simple_tables: bool,
    /// Multiline cell content in tables
    #[serde(alias = "multiline_tables")]
    pub multiline_tables: bool,
    /// Grid-style tables
    #[serde(alias = "grid_tables")]
    pub grid_tables: bool,
    /// Pipe tables (GitHub/PHP Markdown style)
    #[serde(alias = "pipe_tables")]
    pub pipe_tables: bool,
    /// Table captions
    #[serde(alias = "table_captions")]
    pub table_captions: bool,

    // Divs
    /// Fenced divs ::: {.class}
    #[serde(alias = "fenced_divs")]
    pub fenced_divs: bool,
    /// HTML <div> elements
    #[serde(alias = "native_divs")]
    pub native_divs: bool,

    // Other block elements
    /// Line blocks for poetry | prefix
    #[serde(alias = "line_blocks")]
    pub line_blocks: bool,

    // ===== Inline elements =====

    // Emphasis
    /// Underscores don't trigger emphasis in snake_case
    #[serde(alias = "intraword_underscores")]
    pub intraword_underscores: bool,
    /// Strikethrough ~~text~~
    pub strikeout: bool,
    /// Superscript and subscript ^super^ ~sub~
    pub superscript: bool,
    pub subscript: bool,

    // Links
    /// Inline links [text](url)
    #[serde(alias = "inline_links")]
    pub inline_links: bool,
    /// Reference links [text][ref]
    #[serde(alias = "reference_links")]
    pub reference_links: bool,
    /// Shortcut reference links [ref] without second []
    #[serde(alias = "shortcut_reference_links")]
    pub shortcut_reference_links: bool,
    /// Attributes on links [text](url){.class}
    #[serde(alias = "link_attributes")]
    pub link_attributes: bool,
    /// Automatic links <http://example.com>
    pub autolinks: bool,

    // Images
    /// Inline images ![alt](url)
    #[serde(alias = "inline_images")]
    pub inline_images: bool,
    /// Paragraph with just image becomes figure
    #[serde(alias = "implicit_figures")]
    pub implicit_figures: bool,

    // Math
    /// Dollar-delimited math $x$ and $$equation$$
    #[serde(alias = "tex_math_dollars")]
    pub tex_math_dollars: bool,
    /// [NON-DEFAULT] GFM math: inline $`...`$ and fenced ``` math blocks
    #[serde(alias = "tex_math_gfm")]
    pub tex_math_gfm: bool,
    /// [NON-DEFAULT] Single backslash math \(...\) and \[...\] (RMarkdown default)
    #[serde(alias = "tex_math_single_backslash")]
    pub tex_math_single_backslash: bool,
    /// [NON-DEFAULT] Double backslash math \\(...\\) and \\[...\\]
    #[serde(alias = "tex_math_double_backslash")]
    pub tex_math_double_backslash: bool,

    // Footnotes
    /// Inline footnotes ^[text]
    #[serde(alias = "inline_footnotes")]
    pub inline_footnotes: bool,
    /// Reference footnotes `[^1]` (requires footnote parsing)
    pub footnotes: bool,

    // Citations
    /// Citation syntax [@cite]
    pub citations: bool,

    // Spans
    /// Bracketed spans [text]{.class}
    #[serde(alias = "bracketed_spans")]
    pub bracketed_spans: bool,
    /// HTML <span> elements
    #[serde(alias = "native_spans")]
    pub native_spans: bool,

    // ===== Metadata =====
    /// YAML metadata block
    #[serde(alias = "yaml_metadata_block")]
    pub yaml_metadata_block: bool,
    /// Pandoc title block (Title/Author/Date)
    #[serde(alias = "pandoc_title_block")]
    pub pandoc_title_block: bool,
    /// [NON-DEFAULT] MultiMarkdown metadata/title block (Key: Value ...)
    pub mmd_title_block: bool,

    // ===== Raw content =====
    /// Raw HTML blocks and inline
    #[serde(alias = "raw_html")]
    pub raw_html: bool,
    /// Markdown inside HTML blocks
    #[serde(alias = "markdown_in_html_blocks")]
    pub markdown_in_html_blocks: bool,
    /// LaTeX commands and environments
    #[serde(alias = "raw_tex")]
    pub raw_tex: bool,
    /// Generic raw blocks with {=format} syntax
    #[serde(alias = "raw_attribute")]
    pub raw_attribute: bool,

    // ===== Escapes and special characters =====
    /// Backslash escapes any symbol
    #[serde(alias = "all_symbols_escapable")]
    pub all_symbols_escapable: bool,
    /// Backslash at line end = hard line break
    #[serde(alias = "escaped_line_breaks")]
    pub escaped_line_breaks: bool,

    // ===== NON-DEFAULT EXTENSIONS =====
    // These are disabled by default in Pandoc
    /// [NON-DEFAULT] Bare URLs become links
    #[serde(alias = "autolink_bare_uris")]
    pub autolink_bare_uris: bool,
    /// [NON-DEFAULT] Newline = <br>
    #[serde(alias = "hard_line_breaks")]
    pub hard_line_breaks: bool,
    /// [NON-DEFAULT] MultiMarkdown style heading identifiers [my-id]
    pub mmd_header_identifiers: bool,
    /// [NON-DEFAULT] MultiMarkdown key=value attributes on reference defs
    pub mmd_link_attributes: bool,
    /// [NON-DEFAULT] GitHub/CommonMark alerts in blockquotes (`> [!NOTE]`)
    pub alerts: bool,
    /// [NON-DEFAULT] :emoji: syntax
    pub emoji: bool,
    /// [NON-DEFAULT] Highlighted ==text==
    pub mark: bool,

    // ===== Quarto-specific extensions =====
    /// Quarto callout blocks (.callout-note, etc.)
    #[serde(alias = "quarto_callouts")]
    pub quarto_callouts: bool,
    /// Quarto cross-references @fig-id, @tbl-id
    #[serde(alias = "quarto_crossrefs")]
    pub quarto_crossrefs: bool,
    /// Quarto shortcodes {{< name args >}}
    #[serde(alias = "quarto_shortcodes")]
    pub quarto_shortcodes: bool,
    /// Bookdown references \@ref(label) and (\#label)
    pub bookdown_references: bool,
    /// Bookdown equation references in LaTeX math blocks (\#eq:label)
    pub bookdown_equation_references: bool,
}

impl Default for Extensions {
    fn default() -> Self {
        Self::for_flavor(Flavor::default())
    }
}

impl Extensions {
    fn none_defaults() -> Self {
        Self {
            alerts: false,
            all_symbols_escapable: false,
            auto_identifiers: false,
            autolink_bare_uris: false,
            autolinks: false,
            backtick_code_blocks: false,
            blank_before_blockquote: false,
            blank_before_header: false,
            bookdown_references: false,
            bookdown_equation_references: false,
            bracketed_spans: false,
            citations: false,
            definition_lists: false,
            emoji: false,
            escaped_line_breaks: false,
            example_lists: false,
            executable_code: false,
            rmarkdown_inline_code: false,
            quarto_inline_code: false,
            fancy_lists: false,
            fenced_code_attributes: false,
            fenced_code_blocks: false,
            fenced_divs: false,
            footnotes: false,
            gfm_auto_identifiers: false,
            grid_tables: false,
            hard_line_breaks: false,
            header_attributes: false,
            implicit_figures: false,
            implicit_header_references: false,
            inline_code_attributes: false,
            inline_footnotes: false,
            inline_images: false,
            inline_links: false,
            intraword_underscores: false,
            line_blocks: false,
            link_attributes: false,
            mark: false,
            markdown_in_html_blocks: false,
            mmd_header_identifiers: false,
            mmd_link_attributes: false,
            mmd_title_block: false,
            multiline_tables: false,
            native_divs: false,
            native_spans: false,
            pandoc_title_block: false,
            pipe_tables: false,
            quarto_callouts: false,
            quarto_crossrefs: false,
            quarto_shortcodes: false,
            raw_attribute: false,
            raw_html: false,
            raw_tex: false,
            reference_links: false,
            shortcut_reference_links: false,
            simple_tables: false,
            startnum: false,
            strikeout: false,
            subscript: false,
            superscript: false,
            table_captions: false,
            task_lists: false,
            tex_math_dollars: false,
            tex_math_double_backslash: false,
            tex_math_gfm: false,
            tex_math_single_backslash: false,
            yaml_metadata_block: false,
        }
    }

    /// Get the default extension set for a given flavor.
    pub fn for_flavor(flavor: Flavor) -> Self {
        match flavor {
            Flavor::Pandoc => Self::pandoc_defaults(),
            Flavor::Quarto => Self::quarto_defaults(),
            Flavor::RMarkdown => Self::rmarkdown_defaults(),
            Flavor::Gfm => Self::gfm_defaults(),
            Flavor::CommonMark => Self::commonmark_defaults(),
            Flavor::MultiMarkdown => Self::multimarkdown_defaults(),
        }
    }

    fn pandoc_defaults() -> Self {
        Self {
            // Block-level - enabled by default in Pandoc
            auto_identifiers: true,
            blank_before_blockquote: true,
            blank_before_header: true,
            gfm_auto_identifiers: false,
            header_attributes: true,
            implicit_header_references: true,

            // Lists
            definition_lists: true,
            example_lists: true,
            fancy_lists: true,
            startnum: true,
            task_lists: true,

            // Code
            backtick_code_blocks: true,
            executable_code: false,
            rmarkdown_inline_code: false,
            quarto_inline_code: false,
            fenced_code_attributes: true,
            fenced_code_blocks: true,
            inline_code_attributes: true,

            // Tables
            grid_tables: true,
            multiline_tables: true,
            pipe_tables: true,
            simple_tables: true,
            table_captions: true,

            // Divs
            fenced_divs: true,
            native_divs: true,

            // Other blocks
            line_blocks: true,

            // Inline
            intraword_underscores: true,
            strikeout: true,
            subscript: true,
            superscript: true,

            // Links
            autolinks: true,
            inline_links: true,
            link_attributes: true,
            reference_links: true,
            shortcut_reference_links: true,

            // Images
            implicit_figures: true,
            inline_images: true,

            // Math
            tex_math_dollars: true,
            tex_math_double_backslash: false,
            tex_math_gfm: false,
            tex_math_single_backslash: false,

            // Footnotes
            footnotes: true,
            inline_footnotes: true,

            // Citations
            citations: true,

            // Spans
            bracketed_spans: true,
            native_spans: true,

            // Metadata
            mmd_title_block: false,
            pandoc_title_block: true,
            yaml_metadata_block: true,

            // Raw
            markdown_in_html_blocks: false,
            raw_attribute: true,
            raw_html: true,
            raw_tex: true,

            // Escapes
            all_symbols_escapable: true,
            escaped_line_breaks: true,

            // Non-default
            alerts: false,
            autolink_bare_uris: false,
            emoji: false,
            hard_line_breaks: false,
            mark: false,
            mmd_header_identifiers: false,
            mmd_link_attributes: false,

            // Quarto/Bookdown-specific
            bookdown_references: false,
            bookdown_equation_references: false,
            quarto_callouts: false,
            quarto_crossrefs: false,
            quarto_shortcodes: false,
        }
    }

    fn quarto_defaults() -> Self {
        let mut ext = Self::pandoc_defaults();

        ext.executable_code = true;
        ext.rmarkdown_inline_code = true;
        ext.quarto_inline_code = true;
        ext.quarto_callouts = true;
        ext.quarto_crossrefs = true;
        ext.quarto_shortcodes = true;

        ext
    }

    fn rmarkdown_defaults() -> Self {
        let mut ext = Self::pandoc_defaults();

        ext.bookdown_references = true;
        ext.bookdown_equation_references = true;
        ext.executable_code = true;
        ext.rmarkdown_inline_code = true;
        ext.quarto_inline_code = false;
        ext.tex_math_dollars = true;
        ext.tex_math_single_backslash = true;

        ext
    }

    fn gfm_defaults() -> Self {
        let mut ext = Self::none_defaults();

        ext.alerts = true;
        ext.auto_identifiers = true;
        ext.autolink_bare_uris = true;
        ext.backtick_code_blocks = true;
        ext.emoji = true;
        ext.fenced_code_blocks = true;
        ext.footnotes = true;
        ext.gfm_auto_identifiers = true;
        ext.pipe_tables = true;
        ext.raw_html = true;
        ext.strikeout = true;
        ext.task_lists = true;
        ext.tex_math_dollars = true;
        ext.tex_math_gfm = true;
        ext.yaml_metadata_block = true;

        ext
    }

    fn commonmark_defaults() -> Self {
        let mut ext = Self::none_defaults();
        ext.raw_html = true;
        ext
    }

    fn multimarkdown_defaults() -> Self {
        let mut ext = Self::none_defaults();

        ext.all_symbols_escapable = true;
        ext.auto_identifiers = true;
        ext.backtick_code_blocks = true;
        ext.definition_lists = true;
        ext.footnotes = true;
        ext.implicit_figures = true;
        ext.implicit_header_references = true;
        ext.intraword_underscores = true;
        ext.mmd_header_identifiers = true;
        ext.mmd_link_attributes = true;
        ext.mmd_title_block = true;
        ext.pipe_tables = true;
        ext.raw_attribute = true;
        ext.raw_html = true;
        ext.reference_links = true;
        ext.shortcut_reference_links = true;
        ext.subscript = true;
        ext.superscript = true;
        ext.tex_math_dollars = true;
        ext.tex_math_double_backslash = true;

        ext
    }

    /// Merge user-specified extension overrides with flavor defaults.
    ///
    /// This is used to support partial extension overrides in config files.
    /// For example, if a user specifies `flavor = "quarto"` and then sets
    /// `[extensions] quarto-crossrefs = false`, we want all other extensions
    /// to use Quarto defaults, not Pandoc defaults.
    ///
    /// # Arguments
    /// * `user_overrides` - Map of extension names to their user-specified values
    /// * `flavor` - The flavor to use for default values
    ///
    /// # Returns
    /// A new Extensions struct with flavor defaults merged with user overrides
    pub fn merge_with_flavor(user_overrides: HashMap<String, bool>, flavor: Flavor) -> Self {
        let defaults = Self::for_flavor(flavor);
        Self::merge_overrides(defaults, user_overrides)
    }

    fn merge_overrides(base: Extensions, user_overrides: HashMap<String, bool>) -> Self {
        use serde_json::{Map, Value};

        let defaults_value =
            serde_json::to_value(&base).expect("Failed to serialize extension defaults");

        let mut merged = if let Value::Object(obj) = defaults_value {
            obj
        } else {
            Map::new()
        };

        // Apply user overrides (normalize snake_case to kebab-case for consistency)
        for (key, value) in user_overrides {
            // Normalize: convert snake_case to kebab-case
            let normalized_key = key.replace('_', "-");
            merged.insert(normalized_key, Value::Bool(value));
        }

        // Deserialize back to Extensions
        serde_json::from_value(Value::Object(merged))
            .expect("Failed to deserialize merged extensions")
    }
}

/// Configuration for an external code formatter.
#[derive(Debug, Clone, PartialEq)]
pub struct FormatterConfig {
    /// Command to execute (e.g., "black", "air", "rustfmt")
    pub cmd: String,
    /// Arguments to pass to the command (e.g., ["-", "--line-length=80"])
    pub args: Vec<String>,
    /// Whether this formatter is enabled (deprecated, kept for backwards compatibility)
    pub enabled: bool,
    /// Whether the formatter reads from stdin (true) or requires a file path (false)
    pub stdin: bool,
}

/// NEW: Language → Formatter mapping value (single formatter or chain)
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum FormatterValue {
    /// Single formatter: r = "air"
    Single(String),
    /// Multiple formatters (sequential): python = ["isort", "black"]
    Multiple(Vec<String>),
}

/// NEW: Named formatter definition (formatters.NAME sections in new format)
/// OLD: Language-specific formatter config (formatters.LANG sections in old format)
///
/// In new format, if the definition name matches a built-in preset, unspecified fields
/// will inherit from that preset. This allows partial overrides like:
///
/// ```toml
/// [formatters.air]
/// args = ["format", "--custom"]  # Overrides args, inherits cmd/stdin from built-in "air"
/// ```
///
/// Additionally, you can modify arguments incrementally using `prepend-args` and `append-args`:
///
/// ```toml
/// [formatters.air]
/// append-args = ["-i", "2"]  # Adds args to end: ["format", "{}", "-i", "2"]
/// ```
#[derive(Debug, Clone, Deserialize, PartialEq, Default)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct FormatterDefinition {
    /// Reference to a built-in preset (e.g., "air", "black") - OLD FORMAT ONLY
    /// In new format, presets are referenced directly in [formatters] mapping
    pub preset: Option<String>,
    /// Custom command to execute (None = inherit from preset if name matches)
    pub cmd: Option<String>,
    /// Arguments to pass (None = inherit from preset if name matches)
    pub args: Option<Vec<String>>,
    /// Arguments to prepend to base args (from preset or explicit args)
    #[serde(alias = "prepend_args")]
    pub prepend_args: Option<Vec<String>>,
    /// Arguments to append to base args (from preset or explicit args)
    #[serde(alias = "append_args")]
    pub append_args: Option<Vec<String>>,
    /// Whether the formatter reads from stdin (None = inherit from preset if name matches)
    pub stdin: Option<bool>,
    /// DEPRECATED: Whether formatter is enabled (old format only)
    pub enabled: Option<bool>,
}

/// Internal struct for deserializing FormatterConfig with preset support.
#[derive(Debug, Deserialize)]
#[serde(default)]
struct RawFormatterConfig {
    /// Preset name (e.g., "air", "ruff") - mutually exclusive with cmd
    preset: Option<String>,
    /// Command to execute
    cmd: Option<String>,
    /// Arguments to pass to the command
    args: Option<Vec<String>>,
    /// Whether this formatter is enabled
    enabled: bool,
    /// Whether the formatter reads from stdin
    stdin: bool,
}

impl Default for RawFormatterConfig {
    fn default() -> Self {
        Self {
            preset: None,
            cmd: None,
            args: None,
            enabled: true,
            stdin: true,
        }
    }
}

impl<'de> Deserialize<'de> for FormatterConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawFormatterConfig::deserialize(deserializer)?;

        // Check mutual exclusivity of preset and cmd
        if raw.preset.is_some() && raw.cmd.is_some() {
            return Err(serde::de::Error::custom(
                "FormatterConfig: 'preset' and 'cmd' are mutually exclusive - use one or the other",
            ));
        }

        // If preset is specified, resolve it
        if let Some(preset_name) = raw.preset {
            let preset = get_formatter_preset(&preset_name).ok_or_else(|| {
                let available = formatter_preset_names().join(", ");
                serde::de::Error::custom(format!(
                    "Unknown formatter preset: '{}'. Available presets: {}",
                    preset_name, available
                ))
            })?;

            // Return the preset, but respect enabled field if explicitly set
            Ok(FormatterConfig {
                cmd: preset.cmd,
                args: preset.args,
                enabled: raw.enabled,
                stdin: preset.stdin,
            })
        } else if let Some(cmd) = raw.cmd {
            // Custom configuration
            Ok(FormatterConfig {
                cmd,
                args: raw.args.unwrap_or_default(),
                enabled: raw.enabled,
                stdin: raw.stdin,
            })
        } else {
            // No preset and no cmd - return empty config
            // This can happen with Default::default()
            Ok(FormatterConfig {
                cmd: String::new(),
                args: raw.args.unwrap_or_default(),
                enabled: raw.enabled,
                stdin: raw.stdin,
            })
        }
    }
}

impl Default for FormatterConfig {
    fn default() -> Self {
        Self {
            cmd: String::new(),
            args: Vec::new(),
            enabled: true,
            stdin: true,
        }
    }
}

/// Get a built-in formatter preset by name.
/// Returns None if the preset doesn't exist.
pub fn get_formatter_preset(name: &str) -> Option<FormatterConfig> {
    formatter_presets::get_formatter_preset(name)
}

/// Canonical built-in formatter preset names used for docs and diagnostics.
pub fn formatter_preset_names() -> &'static [&'static str] {
    formatter_presets::formatter_preset_names()
}

pub fn formatter_preset_supported_languages(name: &str) -> Option<&'static [&'static str]> {
    formatter_presets::formatter_preset_supported_languages(name)
}

pub fn formatter_preset_metadata(name: &str) -> Option<&'static FormatterPresetMetadata> {
    formatter_presets::formatter_preset_metadata(name)
}

pub fn all_formatter_preset_metadata() -> &'static [FormatterPresetMetadata] {
    formatter_presets::all_formatter_preset_metadata()
}

pub fn formatter_presets_for_language(language: &str) -> Vec<&'static FormatterPresetMetadata> {
    formatter_presets::formatter_presets_for_language(language)
}

fn normalize_formatter_language(language: &str) -> String {
    language.trim().to_ascii_lowercase().replace('_', "-")
}

fn validate_formatter_language_for_preset(lang: &str, formatter_name: &str) -> Result<(), String> {
    let Some(supported) = formatter_preset_supported_languages(formatter_name) else {
        return Ok(()); // custom formatter or unknown preset handled elsewhere
    };

    let normalized_lang = normalize_formatter_language(lang);
    let matches = supported
        .iter()
        .any(|supported_lang| *supported_lang == normalized_lang);

    if matches {
        return Ok(());
    }

    Err(format!(
        "Language '{}': formatter '{}' does not support this language. Supported languages: {}",
        lang,
        formatter_name,
        supported.join(", ")
    ))
}

/// Get the default formatters HashMap with built-in presets.
/// Currently includes R (air) and Python (ruff).
pub fn default_formatters() -> HashMap<String, FormatterConfig> {
    let mut map = HashMap::new();
    map.insert("r".to_string(), get_formatter_preset("air").unwrap());
    map.insert("python".to_string(), get_formatter_preset("ruff").unwrap());
    map
}

/// Style for formatting math delimiters
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum MathDelimiterStyle {
    /// Preserve original delimiter style (\(...\) stays \(...\), $...$ stays $...$)
    #[default]
    Preserve,
    /// Normalize all to dollar syntax ($...$ and $$...$$)
    Dollars,
    /// Normalize all to backslash syntax (\(...\) and \[...\])
    Backslash,
}

/// Tab stop handling for formatter output.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum TabStopMode {
    /// Normalize tabs to spaces (4-column tab stop).
    #[default]
    Normalize,
    /// Preserve tabs in literal code spans/blocks.
    Preserve,
}

/// Formatting style configuration.
/// Groups all style-related settings together.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct StyleConfig {
    /// Text wrapping mode
    pub wrap: Option<WrapMode>,
    /// Blank line handling between blocks
    pub blank_lines: BlankLines,
    /// Math delimiter style preference
    pub math_delimiter_style: MathDelimiterStyle,
    /// Math indentation (spaces)
    pub math_indent: usize,
    /// Tab stop handling (normalize or preserve)
    pub tab_stops: TabStopMode,
    /// Tab width for expanding tabs when normalizing
    pub tab_width: usize,
    /// Use panache-native greedy wrapping instead of textwrap.
    pub built_in_greedy_wrap: bool,
}

impl Default for StyleConfig {
    fn default() -> Self {
        Self {
            wrap: Some(WrapMode::Reflow),
            blank_lines: BlankLines::Collapse,
            math_delimiter_style: MathDelimiterStyle::default(),
            math_indent: 0,
            tab_stops: TabStopMode::Normalize,
            tab_width: 4,
            built_in_greedy_wrap: true,
        }
    }
}

impl StyleConfig {
    // No flavor-specific defaults needed - just use field defaults
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum PandocCompat {
    /// Alias for Panache's pinned newest supported Pandoc-compat behavior.
    ///
    /// This is intentionally NOT "floating upstream latest". It resolves to
    /// a concrete version that Panache has verified, and is bumped manually.
    #[serde(rename = "latest")]
    Latest,
    /// Match Pandoc 3.7 behavior for ambiguous syntax edge cases.
    #[serde(rename = "3.7", alias = "3-7", alias = "v3.7", alias = "v3-7")]
    V3_7,
    /// Match Pandoc 3.9 behavior for ambiguous syntax edge cases.
    #[default]
    #[serde(rename = "3.9", alias = "3-9", alias = "v3.9", alias = "v3-9")]
    V3_9,
}

impl PandocCompat {
    /// Pinned target for `latest`.
    pub const PINNED_LATEST: Self = Self::V3_9;

    pub fn effective(self) -> Self {
        match self {
            Self::Latest => Self::PINNED_LATEST,
            other => other,
        }
    }
}

/// Parser configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(default, rename_all = "kebab-case")]
pub struct ParserConfig {
    /// Compatibility target for ambiguous Pandoc behavior.
    pub pandoc_compat: PandocCompat,
}

impl ParserConfig {
    pub fn effective_pandoc_compat(&self) -> PandocCompat {
        self.pandoc_compat.effective()
    }
}

/// Linter configuration.
/// Preferred shape is `[lint.rules] rule-name = true/false`.
/// Legacy `[lint] rule-name = true/false` is still supported (deprecated).
#[derive(Debug, Clone, Serialize, PartialEq, Default)]
pub struct LintConfig {
    pub rules: HashMap<String, bool>,
}

impl LintConfig {
    fn normalize_rule_name(name: &str) -> String {
        name.trim().to_lowercase().replace('_', "-")
    }

    fn normalize(mut self) -> Self {
        self.rules = self
            .rules
            .into_iter()
            .map(|(name, enabled)| (Self::normalize_rule_name(&name), enabled))
            .collect();
        self
    }

    pub fn is_rule_enabled(&self, rule_name: &str) -> bool {
        let normalized = Self::normalize_rule_name(rule_name);
        self.rules.get(&normalized).copied().unwrap_or(true)
    }
}

impl<'de> Deserialize<'de> for LintConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = toml::Value::deserialize(deserializer)?;
        let mut rules = HashMap::new();
        let mut used_legacy_shape = false;

        let mut table = value
            .as_table()
            .cloned()
            .ok_or_else(|| serde::de::Error::custom("expected [lint] table"))?;

        // New shape: [lint.rules]
        if let Some(rules_value) = table.remove("rules") {
            let rules_table = rules_value
                .as_table()
                .ok_or_else(|| serde::de::Error::custom("[lint.rules] must be a table"))?;
            for (name, enabled) in rules_table {
                let enabled = enabled.as_bool().ok_or_else(|| {
                    serde::de::Error::custom(format!(
                        "[lint.rules] entry '{}' must be true or false",
                        name
                    ))
                })?;
                rules.insert(name.clone(), enabled);
            }
        }

        // Legacy shape: [lint] rule-name = true/false
        for (name, enabled) in table {
            let enabled = enabled.as_bool().ok_or_else(|| {
                serde::de::Error::custom(format!(
                    "Unsupported [lint] key '{}'; use [lint.rules] for rule toggles",
                    name
                ))
            })?;
            used_legacy_shape = true;
            rules.insert(name, enabled);
        }

        if used_legacy_shape {
            eprintln!(
                "Warning: [lint] rule = true/false is deprecated; use [lint.rules] rule = true/false."
            );
        }

        Ok(Self { rules }.normalize())
    }
}

/// Internal deserialization struct that allows for optional fields
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawConfig {
    #[serde(default)]
    flavor: Flavor,
    #[serde(default)]
    extensions: Option<toml::Value>,
    #[serde(default)]
    line_ending: Option<LineEnding>,
    #[serde(default = "default_line_width")]
    line_width: usize,
    #[serde(default)]
    pandoc_compat: Option<PandocCompat>,

    // New preferred formatting section
    #[serde(default)]
    #[serde(rename = "format")]
    format_section: Option<StyleConfig>,

    // DEPRECATED: [style] section (kept for backwards compatibility)
    #[serde(default)]
    style: Option<StyleConfig>,

    // DEPRECATED: Old top-level style fields (kept for backwards compatibility)
    #[serde(default)]
    math_indent: usize,
    #[serde(default)]
    math_delimiter_style: MathDelimiterStyle,
    #[serde(default)]
    wrap: Option<WrapMode>,
    #[serde(default = "default_blank_lines")]
    blank_lines: BlankLines,
    #[serde(default)]
    tab_stops: TabStopMode,
    #[serde(default = "default_tab_width")]
    tab_width: usize,
    // Parser configuration (deprecated home for pandoc-compat)
    #[serde(default)]
    parser: Option<ParserConfig>,

    // NEW: Language → Formatter(s) mapping
    // This will be a raw Value that we'll parse manually to handle both formats
    #[serde(default)]
    formatters: Option<toml::Value>,

    /// Max parallel external tool invocations (formatters/linters) per document.
    #[serde(default)]
    external_max_parallel: Option<usize>,

    #[serde(default)]
    linters: HashMap<String, String>,
    #[serde(default)]
    lint: Option<LintConfig>,
    #[serde(default)]
    cache_dir: Option<String>,
    #[serde(default)]
    exclude: Option<Vec<String>>,
    #[serde(default)]
    extend_exclude: Vec<String>,
    #[serde(default)]
    include: Option<Vec<String>>,
    #[serde(default)]
    extend_include: Vec<String>,
    #[serde(default)]
    flavor_overrides: HashMap<String, Flavor>,
}

fn default_line_width() -> usize {
    80
}

fn default_external_max_parallel() -> usize {
    // Conservative cap: documents may have hundreds of code blocks.
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .clamp(1, 8)
}

fn default_blank_lines() -> BlankLines {
    BlankLines::Collapse
}

fn default_tab_width() -> usize {
    4
}

pub const DEFAULT_EXCLUDE_PATTERNS: &[&str] = &[
    ".Rproj.user/",
    ".bzr/",
    ".cache/",
    ".devevn/",
    ".direnv/",
    ".git/",
    ".hg/",
    ".julia/",
    ".mypy_cache/",
    ".nox/",
    ".pytest_cache/",
    ".ruff_cache/",
    ".svn/",
    ".tmp/",
    ".tox/",
    ".venv/",
    ".vscode/",
    "_book/",
    "_build/",
    "_freeze/",
    "_site/",
    "build/",
    "dist/",
    "node_modules/",
    "renv/",
    "target/",
    "tests/testthat/_snaps",
    "**/LICENSE.md",
];

pub const DEFAULT_INCLUDE_PATTERNS: &[&str] =
    &["*.md", "*.qmd", "*.Rmd", "*.markdown", "*.mdown", "*.mkd"];
const MARKDOWN_FAMILY_EXTENSIONS: &[&str] = &["md", "markdown", "mdown", "mkd"];

/// Resolve a single formatter name to a FormatterConfig.
///
/// Resolve a formatter name to a FormatterConfig.
///
/// Resolution order:
/// 1. Check if it's a named definition in formatter_definitions
///    - If name matches a built-in preset, inherit unspecified fields from preset
///    - If name doesn't match preset, require full cmd specification
/// 2. Fall back to built-in preset (no custom definition)
/// 3. Error if neither found
///
/// # Examples
///
/// ```toml
/// # Partial override - inherits cmd/stdin from built-in "air"
/// [formatters.air]
/// args = ["format", "--custom"]
///
/// # Append args to preset - final: ["format", "{}", "-i", "2"]
/// [formatters.air]
/// append_args = ["-i", "2"]
///
/// # Full custom - no preset match, requires cmd
/// [formatters.custom-fmt]
/// cmd = "my-formatter"
/// args = ["--flag"]
/// ```
fn resolve_formatter_name(
    name: &str,
    formatter_definitions: &HashMap<String, FormatterDefinition>,
) -> Result<FormatterConfig, String> {
    // Check for named definition first
    if let Some(definition) = formatter_definitions.get(name) {
        // Named definition exists - resolve it

        // NEW FORMAT: preset field not allowed in named definitions
        // (Use direct preset reference in [formatters] mapping instead)
        if definition.preset.is_some() {
            return Err(format!(
                "Formatter '{}': 'preset' field not allowed in named definitions. Use [formatters] mapping instead (e.g., `lang = \"{}\"`).",
                name, name
            ));
        }

        // Try to load built-in preset as base (if name matches)
        let preset = get_formatter_preset(name);

        // Build config by applying overrides to preset (or requiring cmd if no preset)
        match (preset, &definition.cmd) {
            // Case 1: Preset exists - use as base and apply overrides
            (Some(mut base_config), _) => {
                // Override cmd if specified
                if let Some(cmd) = &definition.cmd {
                    base_config.cmd = cmd.clone();
                }
                // Override args if specified
                if let Some(args) = &definition.args {
                    base_config.args = args.clone();
                }
                // Override stdin if specified
                if let Some(stdin) = definition.stdin {
                    base_config.stdin = stdin;
                }

                // Apply prepend_args and append_args modifiers
                apply_arg_modifiers(&mut base_config.args, definition);

                Ok(base_config)
            }
            // Case 2: No preset, but cmd specified - full custom formatter
            (None, Some(cmd)) => {
                let mut args = definition.args.clone().unwrap_or_default();

                // Apply prepend_args and append_args modifiers
                apply_arg_modifiers(&mut args, definition);

                Ok(FormatterConfig {
                    cmd: cmd.clone(),
                    args,
                    enabled: true,
                    stdin: definition.stdin.unwrap_or(true),
                })
            }
            // Case 3: No preset, no cmd - error
            (None, None) => Err(format!(
                "Formatter '{}': must specify 'cmd' field (not a known preset)",
                name
            )),
        }
    } else {
        // Not a named definition - check built-in presets
        get_formatter_preset(name).ok_or_else(|| {
            format!(
                "Unknown formatter '{}': not a named definition or built-in preset. \
                 Define it in [formatters.{}] section or use a known preset.",
                name, name
            )
        })
    }
}

/// Apply prepend_args and append_args modifiers to an argument list.
///
/// Modifiers are applied in order: prepend_args + base_args + append_args
/// If no base args exist, they're treated as empty (user responsibility).
fn apply_arg_modifiers(args: &mut Vec<String>, definition: &FormatterDefinition) {
    // Prepend args if specified
    if let Some(prepend) = &definition.prepend_args {
        let mut new_args = prepend.clone();
        new_args.append(args);
        *args = new_args;
    }

    // Append args if specified
    if let Some(append) = &definition.append_args {
        args.extend_from_slice(append);
    }
}

/// Resolve a language's formatter value (single or multiple) to a list of FormatterConfigs.
fn resolve_language_formatters(
    lang: &str,
    value: &FormatterValue,
    formatter_definitions: &HashMap<String, FormatterDefinition>,
) -> Result<Vec<FormatterConfig>, String> {
    let formatter_names = match value {
        FormatterValue::Single(name) => vec![name.as_str()],
        FormatterValue::Multiple(names) => names.iter().map(|s| s.as_str()).collect(),
    };

    // Resolve each formatter name
    formatter_names
        .into_iter()
        .map(|name| {
            // Language guards apply only to built-in presets. Named formatter
            // definitions are user-owned and may be intentionally reused across
            // languages (e.g. a custom "prettier" definition).
            if !formatter_definitions.contains_key(name) {
                validate_formatter_language_for_preset(lang, name)?;
            }
            resolve_formatter_name(name, formatter_definitions)
                .map_err(|e| format!("Language '{}': {}", lang, e))
        })
        .collect()
}

impl RawConfig {
    /// Finalize into Config, applying flavor-based defaults where needed
    fn finalize(self) -> Config {
        let parser_from_section = self.parser.unwrap_or_default();
        let parser_pandoc_compat = parser_from_section.pandoc_compat;

        let resolved_pandoc_compat = if let Some(pandoc_compat) = self.pandoc_compat {
            if parser_pandoc_compat != PandocCompat::default()
                && parser_pandoc_compat != pandoc_compat
            {
                eprintln!(
                    "Warning: Both top-level 'pandoc-compat' and [parser].pandoc-compat are set. Using top-level 'pandoc-compat'."
                );
            }
            pandoc_compat
        } else {
            if parser_pandoc_compat != PandocCompat::default() {
                eprintln!(
                    "Warning: [parser].pandoc-compat is deprecated. Please use top-level 'pandoc-compat'."
                );
            }
            parser_pandoc_compat
        };

        // Check for deprecated top-level style fields
        let has_deprecated_fields = self.wrap.is_some()
            || self.math_indent != 0
            || self.math_delimiter_style != MathDelimiterStyle::default()
            || self.blank_lines != default_blank_lines()
            || self.tab_stops != TabStopMode::Normalize
            || self.tab_width != default_tab_width();

        if has_deprecated_fields && self.format_section.is_none() && self.style.is_none() {
            eprintln!(
                "Warning: top-level style fields (wrap, math-indent, etc.) \
                 are deprecated. Please move them under [format] section. \
                 See documentation for the new format."
            );
        }

        // Merge formatting config: prefer [format], then deprecated [style], then old top-level fields.
        let style = if let Some(format_config) = self.format_section {
            if self.style.is_some() {
                eprintln!(
                    "Warning: Both [format] and deprecated [style] sections found. \
                     Using [format] section."
                );
            }
            if has_deprecated_fields {
                eprintln!(
                    "Warning: Both [format] section and top-level style fields found. \
                     Using [format] section and ignoring top-level fields."
                );
            }

            format_config
        } else if let Some(style_config) = self.style {
            eprintln!("Warning: [style] section is deprecated. Please use [format] instead.");
            if has_deprecated_fields {
                eprintln!(
                    "Warning: Both deprecated [style] section and top-level style fields found. \
                     Using [style] section and ignoring top-level fields."
                );
            }
            style_config
        } else {
            // Old format - construct StyleConfig from top-level fields
            StyleConfig {
                wrap: self.wrap.or(Some(WrapMode::Reflow)),
                blank_lines: self.blank_lines,
                math_delimiter_style: self.math_delimiter_style,
                math_indent: self.math_indent,
                tab_stops: self.tab_stops,
                tab_width: self.tab_width,
                built_in_greedy_wrap: true,
            }
        };

        Config {
            extensions: resolve_extensions_for_flavor(self.extensions.as_ref(), self.flavor),
            line_ending: self.line_ending.or(Some(LineEnding::Auto)),
            flavor: self.flavor,
            line_width: self.line_width,
            wrap: style.wrap,
            blank_lines: style.blank_lines,
            math_delimiter_style: style.math_delimiter_style,
            math_indent: style.math_indent,
            tab_stops: style.tab_stops,
            tab_width: style.tab_width,
            formatters: resolve_formatters(self.formatters),
            linters: self.linters,
            lint: self.lint.unwrap_or_default().normalize(),
            cache_dir: self.cache_dir,
            external_max_parallel: self
                .external_max_parallel
                .unwrap_or_else(default_external_max_parallel),
            parser: ParserConfig {
                pandoc_compat: resolved_pandoc_compat,
            },
            built_in_greedy_wrap: style.built_in_greedy_wrap,
            exclude: self.exclude,
            extend_exclude: self.extend_exclude,
            include: self.include,
            extend_include: self.extend_include,
            flavor_overrides: self.flavor_overrides,
        }
    }
}

fn parse_flavor_key(s: &str) -> Option<Flavor> {
    match s.replace('_', "-").to_lowercase().as_str() {
        "pandoc" => Some(Flavor::Pandoc),
        "quarto" => Some(Flavor::Quarto),
        "rmarkdown" | "r-markdown" => Some(Flavor::RMarkdown),
        "gfm" => Some(Flavor::Gfm),
        "common-mark" | "commonmark" => Some(Flavor::CommonMark),
        "multimarkdown" | "multi-markdown" => Some(Flavor::MultiMarkdown),
        _ => None,
    }
}

fn resolve_extensions_for_flavor(
    extensions_value: Option<&toml::Value>,
    flavor: Flavor,
) -> Extensions {
    let Some(value) = extensions_value else {
        return Extensions::for_flavor(flavor);
    };

    let Some(table) = value.as_table() else {
        eprintln!("Warning: [extensions] must be a table; using flavor defaults.");
        return Extensions::for_flavor(flavor);
    };

    let mut global_overrides = HashMap::new();
    let mut flavor_overrides = HashMap::new();

    for (key, val) in table {
        if let Some(enabled) = val.as_bool() {
            global_overrides.insert(key.clone(), enabled);
            continue;
        }

        let Some(flavor_table) = val.as_table() else {
            eprintln!(
                "Warning: [extensions] entry '{}' must be a boolean or table; ignoring.",
                key
            );
            continue;
        };

        let Some(target_flavor) = parse_flavor_key(key) else {
            eprintln!(
                "Warning: [extensions.{}] is not a known flavor table; ignoring.",
                key
            );
            continue;
        };

        if target_flavor != flavor {
            continue;
        }

        for (sub_key, sub_val) in flavor_table {
            let Some(enabled) = sub_val.as_bool() else {
                eprintln!(
                    "Warning: [extensions.{}] entry '{}' must be true or false; ignoring.",
                    key, sub_key
                );
                continue;
            };
            flavor_overrides.insert(sub_key.clone(), enabled);
        }
    }

    let base = Extensions::merge_with_flavor(global_overrides, flavor);
    Extensions::merge_overrides(base, flavor_overrides)
}

/// Resolve formatter configuration from both old and new formats.
/// Returns HashMap<String, Vec<FormatterConfig>> for language → formatter(s) mapping.
fn resolve_formatters(
    raw_formatters: Option<toml::Value>,
) -> HashMap<String, Vec<FormatterConfig>> {
    let Some(value) = raw_formatters else {
        return HashMap::new();
    };

    // Try to determine which format this is
    let toml::Value::Table(table) = value else {
        eprintln!("Warning: Invalid formatters configuration - expected table");
        return HashMap::new();
    };

    // Strategy: Detect old format vs new format
    // Old format: ALL entries are tables with preset/cmd/args (language-specific configs)
    // New format: Mix of strings/arrays (language mappings) and optionally tables (named definitions)

    let has_string_or_array = table
        .values()
        .any(|v| matches!(v, toml::Value::String(_) | toml::Value::Array(_)));

    if has_string_or_array {
        // New format detected (has language mappings as strings/arrays)
        resolve_new_format_formatters(table)
    } else {
        // Old format (all entries are tables)
        resolve_old_format_formatters(table)
    }
}

/// Resolve new format: [formatters] = { r = "air", python = ["isort", "black"] }
/// Plus optional [formatters.air] and [formatters.isort] definitions.
fn resolve_new_format_formatters(
    table: toml::map::Map<String, toml::Value>,
) -> HashMap<String, Vec<FormatterConfig>> {
    let mut mappings = HashMap::new();
    let mut definitions = HashMap::new();

    // First pass: separate mappings from definitions
    for (key, value) in table {
        match &value {
            toml::Value::String(_) | toml::Value::Array(_) => {
                // This is a language mapping
                let formatter_value: Result<FormatterValue, _> = value.try_into();
                match formatter_value {
                    Ok(fv) => {
                        mappings.insert(key, fv);
                    }
                    Err(e) => {
                        eprintln!("Error parsing formatter value for '{}': {}", key, e);
                    }
                }
            }
            toml::Value::Table(_) => {
                // This is a named formatter definition
                let definition: Result<FormatterDefinition, _> = value.try_into();
                match definition {
                    Ok(def) => {
                        definitions.insert(key, def);
                    }
                    Err(e) => {
                        eprintln!("Error parsing formatter definition '{}': {}", key, e);
                    }
                }
            }
            _ => {
                eprintln!(
                    "Warning: Invalid formatter entry '{}' - must be string, array, or table",
                    key
                );
            }
        }
    }

    // Second pass: resolve mappings using definitions
    let mut resolved = HashMap::new();
    for (lang, value) in mappings {
        match resolve_language_formatters(&lang, &value, &definitions) {
            Ok(configs) if !configs.is_empty() => {
                resolved.insert(lang, configs);
            }
            Ok(_) => {} // Empty list
            Err(e) => {
                eprintln!("Error resolving formatters for language '{}': {}", lang, e);
                eprintln!("Skipping formatter for '{}'", lang);
            }
        }
    }

    resolved
}

/// Resolve old format: [formatters.r] with preset/cmd fields directly.
fn resolve_old_format_formatters(
    table: toml::map::Map<String, toml::Value>,
) -> HashMap<String, Vec<FormatterConfig>> {
    eprintln!(
        "Warning: Old formatter configuration format detected. \
         Please migrate to the new format with [formatters] section. \
         See documentation for the new format."
    );

    let mut resolved = HashMap::new();
    for (lang, value) in table {
        let definition: Result<FormatterDefinition, _> = value.try_into();
        match definition {
            Ok(def) => {
                // Skip if disabled (old format only)
                // enabled is Option<bool> now, so check for Some(false)
                if def.enabled == Some(false) {
                    continue;
                }

                match resolve_old_format_definition(&lang, &def) {
                    Ok(config) => {
                        resolved.insert(lang, vec![config]);
                    }
                    Err(e) => {
                        eprintln!("Error in old formatter config for '{}': {}", lang, e);
                        eprintln!("Skipping formatter for '{}'", lang);
                    }
                }
            }
            Err(e) => {
                eprintln!("Error parsing old formatter config for '{}': {}", lang, e);
            }
        }
    }

    resolved
}

/// Resolve old-format formatter definition (inline preset/cmd in formatters.LANG).
fn resolve_old_format_definition(
    _lang: &str,
    definition: &FormatterDefinition,
) -> Result<FormatterConfig, String> {
    // Check for conflicts
    if definition.preset.is_some() && definition.cmd.is_some() {
        return Err("'preset' and 'cmd' are mutually exclusive".to_string());
    }

    if let Some(preset_name) = &definition.preset {
        // Resolve preset
        let preset = get_formatter_preset(preset_name).ok_or_else(|| {
            let available = formatter_preset_names().join(", ");
            format!(
                "Unknown formatter preset '{}'. Available presets: {}",
                preset_name, available
            )
        })?;

        let mut args = definition.args.clone().unwrap_or(preset.args);

        // Apply prepend/append modifiers
        apply_arg_modifiers(&mut args, definition);

        Ok(FormatterConfig {
            cmd: preset.cmd,
            args,
            enabled: true, // enabled field checked by caller
            stdin: preset.stdin,
        })
    } else if let Some(cmd) = &definition.cmd {
        // Custom command
        let mut args = definition.args.clone().unwrap_or_default();

        // Apply prepend/append modifiers
        apply_arg_modifiers(&mut args, definition);

        Ok(FormatterConfig {
            cmd: cmd.clone(),
            args,
            enabled: true,
            stdin: definition.stdin.unwrap_or(true),
        })
    } else {
        Err("must specify either 'preset' or 'cmd'".to_string())
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    pub flavor: Flavor,
    pub extensions: Extensions,
    pub line_ending: Option<LineEnding>,
    pub line_width: usize,
    pub math_indent: usize,
    pub math_delimiter_style: MathDelimiterStyle,
    pub tab_stops: TabStopMode,
    pub tab_width: usize,
    pub wrap: Option<WrapMode>,
    pub blank_lines: BlankLines,
    /// Language → Formatter(s) mapping (supports multiple formatters per language)
    pub formatters: HashMap<String, Vec<FormatterConfig>>,
    pub linters: HashMap<String, String>,
    /// Max parallel external tool invocations (formatters/linters) per document.
    pub external_max_parallel: usize,
    /// Parser configuration (experimental)
    pub parser: ParserConfig,
    /// Linter rule toggles.
    pub lint: LintConfig,
    /// Optional CLI cache directory override.
    pub cache_dir: Option<String>,
    pub built_in_greedy_wrap: bool,
    pub exclude: Option<Vec<String>>,
    pub extend_exclude: Vec<String>,
    pub include: Option<Vec<String>>,
    pub extend_include: Vec<String>,
    pub flavor_overrides: HashMap<String, Flavor>,
}

impl<'de> Deserialize<'de> for Config {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        RawConfig::deserialize(deserializer).map(|raw| raw.finalize())
    }
}

impl Default for Config {
    fn default() -> Self {
        let flavor = Flavor::default();
        Self {
            flavor,
            extensions: Extensions::for_flavor(flavor),
            line_ending: Some(LineEnding::Auto),
            line_width: 80,
            math_indent: 0,
            math_delimiter_style: MathDelimiterStyle::default(),
            tab_stops: TabStopMode::Normalize,
            tab_width: 4,
            wrap: Some(WrapMode::Reflow),
            blank_lines: BlankLines::Collapse,
            formatters: HashMap::new(), // Opt-in: empty by default
            linters: HashMap::new(),    // Opt-in: empty by default
            external_max_parallel: default_external_max_parallel(),
            parser: ParserConfig::default(),
            lint: LintConfig::default(),
            cache_dir: None,
            built_in_greedy_wrap: true,
            exclude: None,
            extend_exclude: Vec::new(),
            include: None,
            extend_include: Vec::new(),
            flavor_overrides: HashMap::new(),
        }
    }
}

#[derive(Default, Clone)]
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    pub fn math_indent(mut self, indent: usize) -> Self {
        self.config.math_indent = indent;
        self
    }

    pub fn tab_stops(mut self, mode: TabStopMode) -> Self {
        self.config.tab_stops = mode;
        self
    }

    pub fn tab_width(mut self, width: usize) -> Self {
        self.config.tab_width = width;
        self
    }

    pub fn line_width(mut self, width: usize) -> Self {
        self.config.line_width = width;
        self
    }

    pub fn line_ending(mut self, ending: LineEnding) -> Self {
        self.config.line_ending = Some(ending);
        self
    }

    pub fn blank_lines(mut self, mode: BlankLines) -> Self {
        self.config.blank_lines = mode;
        self
    }

    pub fn build(self) -> Config {
        self.config
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum WrapMode {
    Preserve,
    Reflow,
    Sentence,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum LineEnding {
    Auto,
    Lf,
    Crlf,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum BlankLines {
    /// Preserve original blank lines (any number)
    Preserve,
    /// Collapse multiple consecutive blank lines to a single blank line
    Collapse,
}

const CANDIDATE_NAMES: &[&str] = &[".panache.toml", "panache.toml"];

/// Check for deprecated snake_case extension names and warn users.
fn check_deprecated_extension_names(s: &str, path: &Path) {
    // Parse as generic TOML to inspect raw keys
    let Ok(toml_value) = toml::from_str::<toml::Value>(s) else {
        return; // If TOML is invalid, let the main parser handle the error
    };

    let Some(extensions_table) = toml_value
        .as_table()
        .and_then(|t| t.get("extensions"))
        .and_then(|v| v.as_table())
    else {
        return; // No [extensions] section
    };

    // List of all extension field names that should be kebab-case
    let deprecated_names: Vec<&str> = extensions_table
        .keys()
        .filter(|k| k.contains('_'))
        .map(|k| k.as_str())
        .collect();

    if !deprecated_names.is_empty() {
        eprintln!(
            "Warning: Deprecated snake_case extension names found in {}:",
            path.display()
        );
        eprintln!("  The following extensions use deprecated snake_case naming:");
        for name in &deprecated_names {
            let kebab = name.replace('_', "-");
            eprintln!("    {} -> {} (use kebab-case)", name, kebab);
        }
        eprintln!("  Snake_case extension names are deprecated and will be removed in v1.0.0.");
        eprintln!(
            "  Please update your config to use kebab-case (e.g., quarto-crossrefs instead of quarto_crossrefs)."
        );
    }
}

/// Check for deprecated snake_case formatter field names and warn users.
fn check_deprecated_formatter_names(s: &str, path: &Path) {
    // Parse as generic TOML to inspect raw keys
    let Ok(toml_value) = toml::from_str::<toml::Value>(s) else {
        return;
    };

    let Some(formatters_table) = toml_value
        .as_table()
        .and_then(|t| t.get("formatters"))
        .and_then(|v| v.as_table())
    else {
        return; // No [formatters] section
    };

    // Check each formatter definition for deprecated field names
    let mut found_deprecated = false;
    for (formatter_name, formatter_value) in formatters_table {
        if let Some(formatter_def) = formatter_value.as_table() {
            let deprecated_fields: Vec<&str> = formatter_def
                .keys()
                .filter(|k| matches!(k.as_str(), "prepend_args" | "append_args"))
                .map(|k| k.as_str())
                .collect();

            if !deprecated_fields.is_empty() {
                if !found_deprecated {
                    eprintln!(
                        "Warning: Deprecated snake_case formatter field names found in {}:",
                        path.display()
                    );
                    found_deprecated = true;
                }
                eprintln!("  In [formatters.{}]:", formatter_name);
                for field in deprecated_fields {
                    let kebab = field.replace('_', "-");
                    eprintln!("    {} -> {}", field, kebab);
                }
            }
        }
    }

    if found_deprecated {
        eprintln!(
            "  Snake_case formatter field names are deprecated and will be removed in v1.0.0."
        );
        eprintln!(
            "  Please update your config to use kebab-case (e.g., prepend-args instead of prepend_args)."
        );
    }
}

/// Check for deprecated code-block style configuration and warn users.
fn check_deprecated_code_block_style_options(s: &str, path: &Path) {
    let Ok(toml_value) = toml::from_str::<toml::Value>(s) else {
        return;
    };
    let Some(root) = toml_value.as_table() else {
        return;
    };

    let top_level = root.contains_key("code-blocks");
    let format_nested = root
        .get("format")
        .and_then(|v| v.as_table())
        .is_some_and(|format| format.contains_key("code-blocks"));
    let style_nested = root
        .get("style")
        .and_then(|v| v.as_table())
        .is_some_and(|style| style.contains_key("code-blocks"));

    if top_level || format_nested || style_nested {
        eprintln!(
            "Warning: Deprecated code block style options found in {}:",
            path.display()
        );
        if format_nested {
            eprintln!("  - [format.code-blocks]");
        }
        if top_level {
            eprintln!("  - [code-blocks]");
        }
        if style_nested {
            eprintln!("  - [style.code-blocks]");
        }
        eprintln!("  These options are now no-ops and will be removed in a future release.");
    }
}

fn parse_config_str(s: &str, path: &Path) -> io::Result<Config> {
    // Check for deprecated names before parsing
    check_deprecated_extension_names(s, path);
    check_deprecated_formatter_names(s, path);
    check_deprecated_code_block_style_options(s, path);

    let config: Config = toml::from_str(s).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("invalid config {}: {e}", path.display()),
        )
    })?;

    Ok(config)
}

fn read_config(path: &Path) -> io::Result<Config> {
    log::debug!("Reading config from: {}", path.display());
    let s = fs::read_to_string(path)?;
    let config = parse_config_str(&s, path)?;
    log::debug!("Loaded config from: {}", path.display());
    Ok(config)
}

fn find_in_tree(start_dir: &Path) -> Option<PathBuf> {
    for dir in start_dir.ancestors() {
        for name in CANDIDATE_NAMES {
            let p = dir.join(name);
            if p.is_file() {
                return Some(p);
            }
        }
    }
    None
}

fn xdg_config_path() -> Option<PathBuf> {
    if let Ok(xdg) = env::var("XDG_CONFIG_HOME") {
        let p = Path::new(&xdg).join("panache").join("config.toml");
        if p.is_file() {
            return Some(p);
        }
    }
    if let Ok(home) = env::var("HOME") {
        let p = Path::new(&home)
            .join(".config")
            .join("panache")
            .join("config.toml");
        if p.is_file() {
            return Some(p);
        }
    }
    None
}

/// Load configuration with precedence:
/// 1) explicit path (error if unreadable/invalid)
/// 2) walk up from start_dir: .panache.toml, panache.toml
/// 3) XDG: $XDG_CONFIG_HOME/panache/config.toml or ~/.config/panache/config.toml
/// 4) default config
///
/// Flavor detection logic (when input_file is provided):
/// - .qmd files: Always use Quarto flavor
/// - .Rmd files: Always use RMarkdown flavor
/// - Markdown-family files (.md/.markdown/.mdown/.mkd): Use most-specific
///   `flavor-overrides` match when provided, else use `flavor` from config
/// - Other extensions: Use `flavor` from config
///
/// The `flavor` config field determines the default flavor for stdin and files
/// without a matching extension override.
pub fn load(
    explicit: Option<&Path>,
    start_dir: &Path,
    input_file: Option<&Path>,
) -> io::Result<(Config, Option<PathBuf>)> {
    let (mut cfg, cfg_path) = if let Some(path) = explicit {
        let cfg = read_config(path)?;
        (cfg, Some(path.to_path_buf()))
    } else if let Some(p) = find_in_tree(start_dir)
        && let Ok(cfg) = read_config(&p)
    {
        (cfg, Some(p))
    } else if let Some(p) = xdg_config_path()
        && let Ok(cfg) = read_config(&p)
    {
        (cfg, Some(p))
    } else {
        log::debug!("No config file found, using defaults");
        (Config::default(), None)
    };

    if let Some(flavor) = detect_flavor(input_file, cfg_path.as_deref(), &cfg) {
        cfg.flavor = flavor;
        cfg.extensions = if let Some(path) = cfg_path.as_deref() {
            fs::read_to_string(path)
                .ok()
                .and_then(|s| toml::from_str::<toml::Value>(&s).ok())
                .map(|root| resolve_extensions_for_flavor(root.get("extensions"), flavor))
                .unwrap_or_else(|| Extensions::for_flavor(flavor))
        } else {
            Extensions::for_flavor(flavor)
        };
    }

    Ok((cfg, cfg_path))
}

fn detect_flavor(
    input_file: Option<&Path>,
    cfg_path: Option<&Path>,
    cfg: &Config,
) -> Option<Flavor> {
    let input_path = input_file?;
    let ext = input_path.extension().and_then(|e| e.to_str())?;
    let ext_lower = ext.to_lowercase();

    match ext_lower.as_str() {
        "qmd" => {
            log::debug!("Using Quarto flavor for .qmd file");
            Some(Flavor::Quarto)
        }
        "rmd" => {
            log::debug!("Using RMarkdown flavor for .Rmd file");
            Some(Flavor::RMarkdown)
        }
        _ if MARKDOWN_FAMILY_EXTENSIONS.contains(&ext_lower.as_str()) => {
            let base_dir = cfg_path.and_then(Path::parent);
            let override_flavor =
                detect_flavor_override(input_path, base_dir, &cfg.flavor_overrides);
            let final_flavor = override_flavor.unwrap_or(cfg.flavor);
            if let Some(flavor) = override_flavor {
                log::debug!(
                    "Using {:?} flavor for {} (matched flavor-overrides)",
                    flavor,
                    input_path.display()
                );
            } else {
                log::debug!(
                    "Using {:?} flavor for {} (from config)",
                    final_flavor,
                    input_path.display()
                );
            }
            Some(final_flavor)
        }
        _ => None,
    }
}

fn detect_flavor_override(
    input_path: &Path,
    base_dir: Option<&Path>,
    overrides: &HashMap<String, Flavor>,
) -> Option<Flavor> {
    if overrides.is_empty() {
        return None;
    }

    let full_path = normalize_path_for_matching(input_path);
    let rel_path = base_dir
        .and_then(|base| input_path.strip_prefix(base).ok())
        .map(normalize_path_for_matching);
    let file_name = input_path
        .file_name()
        .and_then(|name| name.to_str())
        .map(|name| name.to_string());

    let mut best: Option<((usize, usize, usize), Flavor)> = None;
    for (pattern, flavor) in overrides {
        let matched = glob_matches_path(pattern, &full_path)
            || rel_path
                .as_deref()
                .is_some_and(|relative| glob_matches_path(pattern, relative))
            || file_name
                .as_deref()
                .is_some_and(|name| glob_matches_path(pattern, name));
        if !matched {
            continue;
        }

        let score = pattern_specificity(pattern);
        if best.is_none_or(|(best_score, _)| score > best_score) {
            best = Some((score, *flavor));
        }
    }

    best.map(|(_, flavor)| flavor)
}

fn normalize_path_for_matching(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn pattern_specificity(pattern: &str) -> (usize, usize, usize) {
    let literal_chars = pattern.chars().filter(|c| *c != '*' && *c != '?').count();
    let segment_count = pattern
        .split('/')
        .filter(|segment| !segment.is_empty())
        .count();
    let wildcard_count = pattern.chars().filter(|c| *c == '*' || *c == '?').count();
    (literal_chars, segment_count, usize::MAX - wildcard_count)
}

fn glob_matches_path(pattern: &str, path: &str) -> bool {
    let normalized_pattern = pattern.replace('\\', "/");
    GlobBuilder::new(&normalized_pattern)
        .literal_separator(true)
        .build()
        .map(|glob| glob.compile_matcher().is_match(path))
        .unwrap_or(false)
}

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

    #[test]
    fn missing_fields_uses_defaults() {
        let toml_str = r#"
            wrap = "reflow"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert_eq!(cfg.line_width, 80);
        // Formatters are opt-in, so empty by default
        assert!(cfg.formatters.is_empty());
        assert!(cfg.cache_dir.is_none());
    }

    #[test]
    fn formatter_config_basic() {
        let toml_str = r#"
            [formatters.python]
            cmd = "black"
            args = ["-"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let python_fmt = &cfg.formatters.get("python").unwrap()[0];
        assert_eq!(python_fmt.cmd, "black");
        assert_eq!(python_fmt.args, vec!["-"]);
        assert!(python_fmt.enabled);
    }

    #[test]
    fn formatter_config_multiple_languages() {
        let toml_str = r#"
            [formatters.r]
            cmd = "air"
            args = ["--preset=tidyverse"]
            
            [formatters.python]
            cmd = "black"
            args = ["-", "--line-length=88"]
            
            [formatters.rust]
            cmd = "rustfmt"
            enabled = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Old format detected - should have 2 formatters (rust disabled)
        assert_eq!(cfg.formatters.len(), 2);

        let r_fmt = &cfg.formatters.get("r").unwrap()[0];
        assert_eq!(r_fmt.cmd, "air");
        assert_eq!(r_fmt.args, vec!["--preset=tidyverse"]);
        assert!(r_fmt.enabled);

        let py_fmt = &cfg.formatters.get("python").unwrap()[0];
        assert_eq!(py_fmt.cmd, "black");
        assert_eq!(py_fmt.args.len(), 2);

        // rust is disabled in old format, so it shouldn't be in the map
        assert!(!cfg.formatters.contains_key("rust"));
    }

    #[test]
    fn cache_dir_parsing() {
        let toml_str = r#"
            cache-dir = ".panache/local-cache"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert_eq!(cfg.cache_dir.as_deref(), Some(".panache/local-cache"));
    }

    #[test]
    fn formatter_config_no_args() {
        let toml_str = r#"
            [formatters.rustfmt]
            cmd = "rustfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let fmt = &cfg.formatters.get("rustfmt").unwrap()[0];
        assert_eq!(fmt.cmd, "rustfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.enabled);
    }

    #[test]
    fn formatter_empty_cmd_is_valid() {
        // Empty cmd is technically valid in deserialization
        // Validation happens at runtime
        let toml_str = r#"
            [formatters.test]
            cmd = ""
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("test").unwrap()[0];
        assert_eq!(fmt.cmd, "");
    }

    #[test]
    fn preset_resolution_air() {
        let toml_str = r#"
            [formatters.r]
            preset = "air"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let r_fmt = &cfg.formatters.get("r").unwrap()[0];
        assert_eq!(r_fmt.cmd, "air");
        assert_eq!(r_fmt.args, vec!["format", "{}"]);
        assert!(!r_fmt.stdin);
        assert!(r_fmt.enabled);
    }

    #[test]
    fn preset_resolution_ruff() {
        let toml_str = r#"
            [formatters.python]
            preset = "ruff"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let py_fmt = &cfg.formatters.get("python").unwrap()[0];
        assert_eq!(py_fmt.cmd, "ruff");
        assert_eq!(
            py_fmt.args,
            vec!["format", "--stdin-filename", "stdin.py", "-"]
        );
        assert!(py_fmt.stdin);
        assert!(py_fmt.enabled);
    }

    #[test]
    fn preset_resolution_black() {
        let toml_str = r#"
            [formatters.python]
            preset = "black"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let py_fmt = &cfg.formatters.get("python").unwrap()[0];
        assert_eq!(py_fmt.cmd, "black");
        assert_eq!(py_fmt.args, vec!["-"]);
        assert!(py_fmt.stdin);
    }

    #[test]
    fn preset_resolution_sqlfmt() {
        let toml_str = r#"
            [formatters.sql]
            preset = "sqlfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("sql").unwrap()[0];
        assert_eq!(fmt.cmd, "sqlfmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_alejandra() {
        let toml_str = r#"
            [formatters.nix]
            preset = "alejandra"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("nix").unwrap()[0];
        assert_eq!(fmt.cmd, "alejandra");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_terraform_fmt() {
        let toml_str = r#"
            [formatters.hcl]
            preset = "terraform-fmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("hcl").unwrap()[0];
        assert_eq!(fmt.cmd, "terraform");
        assert_eq!(fmt.args, vec!["fmt", "-no-color", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_yamlfix() {
        let toml_str = r#"
            [formatters.yaml]
            preset = "yamlfix"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("yaml").unwrap()[0];
        assert_eq!(fmt.cmd, "yamlfix");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_gofmt() {
        let toml_str = r#"
            [formatters.go]
            preset = "gofmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("go").unwrap()[0];
        assert_eq!(fmt.cmd, "gofmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_gofumpt() {
        let toml_str = r#"
            [formatters.go]
            preset = "gofumpt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("go").unwrap()[0];
        assert_eq!(fmt.cmd, "gofumpt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_nixfmt() {
        let toml_str = r#"
            [formatters.nix]
            preset = "nixfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("nix").unwrap()[0];
        assert_eq!(fmt.cmd, "nixfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_gleam() {
        let toml_str = r#"
            [formatters.gleam]
            preset = "gleam"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("gleam").unwrap()[0];
        assert_eq!(fmt.cmd, "gleam");
        assert_eq!(fmt.args, vec!["format", "--stdin"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_yq() {
        let toml_str = r#"
            [formatters.yaml]
            preset = "yq"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("yaml").unwrap()[0];
        assert_eq!(fmt.cmd, "yq");
        assert_eq!(fmt.args, vec!["-P", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_asmfmt() {
        let toml_str = r#"
            [formatters.asm]
            preset = "asmfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("asm").unwrap()[0];
        assert_eq!(fmt.cmd, "asmfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_astyle() {
        let toml_str = r#"
            [formatters.cpp]
            preset = "astyle"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("cpp").unwrap()[0];
        assert_eq!(fmt.cmd, "astyle");
        assert_eq!(fmt.args, vec!["--quiet"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_autocorrect() {
        let toml_str = r#"
            [formatters.text]
            preset = "autocorrect"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("text").unwrap()[0];
        assert_eq!(fmt.cmd, "autocorrect");
        assert_eq!(fmt.args, vec!["--stdin"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_cmake_format() {
        let toml_str = r#"
            [formatters.cmake]
            preset = "cmake-format"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("cmake").unwrap()[0];
        assert_eq!(fmt.cmd, "cmake-format");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_cue_fmt() {
        let toml_str = r#"
            [formatters.cue]
            preset = "cue-fmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("cue").unwrap()[0];
        assert_eq!(fmt.cmd, "cue");
        assert_eq!(fmt.args, vec!["fmt", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_jsonnetfmt() {
        let toml_str = r#"
            [formatters.jsonnet]
            preset = "jsonnetfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("jsonnet").unwrap()[0];
        assert_eq!(fmt.cmd, "jsonnetfmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_dfmt() {
        let toml_str = r#"
            [formatters.d]
            preset = "dfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("d").unwrap()[0];
        assert_eq!(fmt.cmd, "dfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_efmt() {
        let toml_str = r#"
            [formatters.erl]
            preset = "efmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("erl").unwrap()[0];
        assert_eq!(fmt.cmd, "efmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_nginxfmt() {
        let toml_str = r#"
            [formatters.nginx]
            preset = "nginxfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("nginx").unwrap()[0];
        assert_eq!(fmt.cmd, "nginxfmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_tclfmt() {
        let toml_str = r#"
            [formatters.tcl]
            preset = "tclfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("tcl").unwrap()[0];
        assert_eq!(fmt.cmd, "tclfmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_tex_fmt() {
        let toml_str = r#"
            [formatters.tex]
            preset = "tex-fmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("tex").unwrap()[0];
        assert_eq!(fmt.cmd, "tex-fmt");
        assert_eq!(fmt.args, vec!["-s"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_typstyle() {
        let toml_str = r#"
            [formatters.typst]
            preset = "typstyle"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("typst").unwrap()[0];
        assert_eq!(fmt.cmd, "typstyle");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_gdformat() {
        let toml_str = r#"
            [formatters.gdscript]
            preset = "gdformat"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("gdscript").unwrap()[0];
        assert_eq!(fmt.cmd, "gdformat");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_hurlfmt() {
        let toml_str = r#"
            [formatters.hurl]
            preset = "hurlfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("hurl").unwrap()[0];
        assert_eq!(fmt.cmd, "hurlfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_ktfmt() {
        let toml_str = r#"
            [formatters.kotlin]
            preset = "ktfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("kotlin").unwrap()[0];
        assert_eq!(fmt.cmd, "ktfmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_leptosfmt() {
        let toml_str = r#"
            [formatters.rust]
            preset = "leptosfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("rust").unwrap()[0];
        assert_eq!(fmt.cmd, "leptosfmt");
        assert_eq!(fmt.args, vec!["--stdin"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_pycln() {
        let toml_str = r#"
            [formatters.python]
            preset = "pycln"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("python").unwrap()[0];
        assert_eq!(fmt.cmd, "pycln");
        assert_eq!(fmt.args, vec!["--silence", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_pyproject_fmt() {
        let toml_str = r#"
            [formatters.toml]
            preset = "pyproject-fmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("toml").unwrap()[0];
        assert_eq!(fmt.cmd, "pyproject-fmt");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_google_java_format() {
        let toml_str = r#"
            [formatters.java]
            preset = "google-java-format"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("java").unwrap()[0];
        assert_eq!(fmt.cmd, "google-java-format");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_racketfmt() {
        let toml_str = r#"
            [formatters.racket]
            preset = "racketfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("racket").unwrap()[0];
        assert_eq!(fmt.cmd, "raco");
        assert_eq!(fmt.args, vec!["fmt"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_rubyfmt() {
        let toml_str = r#"
            [formatters.ruby]
            preset = "rubyfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("ruby").unwrap()[0];
        assert_eq!(fmt.cmd, "rubyfmt");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_rufo() {
        let toml_str = r#"
            [formatters.ruby]
            preset = "rufo"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("ruby").unwrap()[0];
        assert_eq!(fmt.cmd, "rufo");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_bean_format() {
        let toml_str = r#"
            [formatters.beancount]
            preset = "bean-format"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("beancount").unwrap()[0];
        assert_eq!(fmt.cmd, "bean-format");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_beautysh() {
        let toml_str = r#"
            [formatters.bash]
            preset = "beautysh"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("bash").unwrap()[0];
        assert_eq!(fmt.cmd, "beautysh");
        assert_eq!(fmt.args, vec!["-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_cljfmt() {
        let toml_str = r#"
            [formatters.clojure]
            preset = "cljfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("clojure").unwrap()[0];
        assert_eq!(fmt.cmd, "cljfmt");
        assert_eq!(fmt.args, vec!["fix", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_fish_indent() {
        let toml_str = r#"
            [formatters.fish]
            preset = "fish_indent"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("fish").unwrap()[0];
        assert_eq!(fmt.cmd, "fish_indent");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_fixjson() {
        let toml_str = r#"
            [formatters.json]
            preset = "fixjson"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("json").unwrap()[0];
        assert_eq!(fmt.cmd, "fixjson");
        assert!(fmt.args.is_empty());
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_bibtex_tidy() {
        let toml_str = r#"
            [formatters.bibtex]
            preset = "bibtex-tidy"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("bibtex").unwrap()[0];
        assert_eq!(fmt.cmd, "bibtex-tidy");
        assert_eq!(fmt.args, vec!["--quiet"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_bpfmt() {
        let toml_str = r#"
            [formatters.bp]
            preset = "bpfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("bp").unwrap()[0];
        assert_eq!(fmt.cmd, "bpfmt");
        assert_eq!(fmt.args, vec!["-w", "{}"]);
        assert!(!fmt.stdin);
    }

    #[test]
    fn preset_resolution_bsfmt() {
        let toml_str = r#"
            [formatters.brs]
            preset = "bsfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("brs").unwrap()[0];
        assert_eq!(fmt.cmd, "bsfmt");
        assert_eq!(fmt.args, vec!["{}", "--write"]);
        assert!(!fmt.stdin);
    }

    #[test]
    fn preset_resolution_buf() {
        let toml_str = r#"
            [formatters.proto]
            preset = "buf"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("proto").unwrap()[0];
        assert_eq!(fmt.cmd, "buf");
        assert_eq!(fmt.args, vec!["format", "-w", "{}"]);
        assert!(!fmt.stdin);
    }

    #[test]
    fn preset_resolution_buildifier() {
        let toml_str = r#"
            [formatters.bazel]
            preset = "buildifier"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("bazel").unwrap()[0];
        assert_eq!(fmt.cmd, "buildifier");
        assert_eq!(fmt.args, vec!["-path", "{}", "-"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_resolution_cabal_fmt() {
        let toml_str = r#"
            [formatters.cabal]
            preset = "cabal-fmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("cabal").unwrap()[0];
        assert_eq!(fmt.cmd, "cabal-fmt");
        assert_eq!(fmt.args, vec!["--inplace", "{}"]);
        assert!(!fmt.stdin);
    }

    #[test]
    fn preset_resolution_prettier_typescript() {
        let toml_str = r#"
            [formatters.typescript]
            preset = "prettier"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmt = &cfg.formatters.get("typescript").unwrap()[0];
        assert_eq!(fmt.cmd, "prettier");
        assert_eq!(fmt.args, vec!["--stdin-filepath", "{}"]);
        assert!(fmt.stdin);
    }

    #[test]
    fn preset_and_cmd_mutually_exclusive() {
        let toml_str = r#"
            [formatters.r]
            preset = "air"
            cmd = "styler"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        // The formatter should be skipped (error logged), so r shouldn't be in the map
        assert!(!cfg.formatters.contains_key("r"));
    }

    #[test]
    fn unknown_preset_fails() {
        let toml_str = r#"
            [formatters.r]
            preset = "nonexistent"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        // The formatter should be skipped (error logged), so r shouldn't be in the map
        assert!(!cfg.formatters.contains_key("r"));
    }

    #[test]
    fn preset_language_mismatch_is_rejected() {
        let toml_str = r#"
            [formatters]
            python = "gofmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert!(!cfg.formatters.contains_key("python"));
    }

    #[test]
    fn preset_language_alias_is_accepted() {
        let toml_str = r#"
            [formatters]
            yml = "yamlfmt"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmts = cfg.formatters.get("yml").unwrap();
        assert_eq!(fmts.len(), 1);
        assert_eq!(fmts[0].cmd, "yamlfmt");
    }

    #[test]
    fn named_definition_skips_builtin_language_guard() {
        let toml_str = r#"
            [formatters]
            javascript = "prettier"

            [formatters.prettier]
            cmd = "prettier"
            args = ["--print-width=100"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        let fmts = cfg.formatters.get("javascript").unwrap();
        assert_eq!(fmts.len(), 1);
        assert_eq!(fmts[0].cmd, "prettier");
        assert_eq!(fmts[0].args, vec!["--print-width=100"]);
    }

    #[test]
    fn preset_metadata_lookup_contains_url() {
        let meta = formatter_preset_metadata("gofmt").unwrap();
        assert_eq!(meta.name, "gofmt");
        assert_eq!(meta.cmd, "gofmt");
        assert!(meta.url.contains("pkg.go.dev"));
    }

    #[test]
    fn preset_metadata_language_lookup_works() {
        let names: Vec<&str> = formatter_presets_for_language("yaml")
            .iter()
            .map(|meta| meta.name)
            .collect();
        assert!(names.contains(&"yamlfmt"));
        assert!(names.contains(&"yamlfix"));
        assert!(names.contains(&"yq"));
    }

    #[test]
    fn preset_metadata_language_lookup_includes_prettier_for_typescript() {
        let names: Vec<&str> = formatter_presets_for_language("typescript")
            .iter()
            .map(|meta| meta.name)
            .collect();
        assert!(names.contains(&"prettier"));
    }

    #[test]
    fn builtin_defaults_when_no_config() {
        let cfg = Config::default();
        // Formatters are opt-in, so empty by default
        assert!(cfg.formatters.is_empty());
        assert!(cfg.lint.is_rule_enabled("heading-hierarchy"));
        assert!(cfg.lint.is_rule_enabled("undefined-references"));
    }

    #[test]
    fn lint_config_allows_rule_toggles() {
        let toml_str = r#"
            [lint.rules]
            heading-hierarchy = false
            undefined-references = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert!(!cfg.lint.is_rule_enabled("heading-hierarchy"));
        assert!(!cfg.lint.is_rule_enabled("undefined-references"));
        assert!(cfg.lint.is_rule_enabled("duplicate-reference-labels"));
    }

    #[test]
    fn lint_config_normalizes_snake_case_rule_names() {
        let toml_str = r#"
            [lint.rules]
            undefined_references = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert!(!cfg.lint.is_rule_enabled("undefined-references"));
    }

    #[test]
    fn lint_config_legacy_top_level_rules_still_supported() {
        let toml_str = r#"
            [lint]
            undefined-references = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert!(!cfg.lint.is_rule_enabled("undefined-references"));
    }

    #[test]
    fn path_selector_fields_parse() {
        let toml_str = r#"
            exclude = ["tests/", "build/"]
            extend-exclude = ["snapshots/"]
            include = ["*.qmd"]
            extend-include = ["*.md"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert_eq!(
            cfg.exclude,
            Some(vec!["tests/".to_string(), "build/".to_string()])
        );
        assert_eq!(cfg.extend_exclude, vec!["snapshots/".to_string()]);
        assert_eq!(cfg.include, Some(vec!["*.qmd".to_string()]));
        assert_eq!(cfg.extend_include, vec!["*.md".to_string()]);
    }

    #[test]
    fn path_selector_fields_default_to_unset_or_empty() {
        let cfg = toml::from_str::<Config>("line-width = 100").unwrap();
        assert!(cfg.exclude.is_none());
        assert!(cfg.extend_exclude.is_empty());
        assert!(cfg.include.is_none());
        assert!(cfg.extend_include.is_empty());
    }

    #[test]
    fn default_exclude_patterns_include_license_md() {
        assert!(DEFAULT_EXCLUDE_PATTERNS.contains(&"**/LICENSE.md"));
    }

    #[test]
    fn flavor_overrides_parse() {
        let toml_str = r#"
            [flavor-overrides]
            "README.md" = "gfm"
            "docs/**/*.md" = "quarto"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert_eq!(cfg.flavor_overrides.get("README.md"), Some(&Flavor::Gfm));
        assert_eq!(
            cfg.flavor_overrides.get("docs/**/*.md"),
            Some(&Flavor::Quarto)
        );
    }

    #[test]
    fn flavor_override_uses_most_specific_match() {
        let mut overrides = HashMap::new();
        overrides.insert("docs/**/*.md".to_string(), Flavor::Pandoc);
        overrides.insert("docs/README.md".to_string(), Flavor::Gfm);
        let input = Path::new("/project/docs/README.md");

        let flavor = detect_flavor_override(input, Some(Path::new("/project")), &overrides);
        assert_eq!(flavor, Some(Flavor::Gfm));
    }

    #[test]
    fn detect_flavor_uses_override_for_markdown_family() {
        let mut cfg = Config {
            flavor: Flavor::Pandoc,
            ..Config::default()
        };
        cfg.flavor_overrides
            .insert("README.md".to_string(), Flavor::Gfm);

        let flavor = detect_flavor(
            Some(Path::new("/project/README.md")),
            Some(Path::new("/project/panache.toml")),
            &cfg,
        );
        assert_eq!(flavor, Some(Flavor::Gfm));
    }

    #[test]
    fn detect_flavor_keeps_qmd_rmd_extension_defaults() {
        let mut cfg = Config {
            flavor: Flavor::Gfm,
            ..Config::default()
        };
        cfg.flavor_overrides
            .insert("docs/**/*.qmd".to_string(), Flavor::Pandoc);
        cfg.flavor_overrides
            .insert("docs/**/*.Rmd".to_string(), Flavor::Quarto);

        let qmd_flavor = detect_flavor(
            Some(Path::new("/project/docs/chapter.qmd")),
            Some(Path::new("/project/panache.toml")),
            &cfg,
        );
        let rmd_flavor = detect_flavor(
            Some(Path::new("/project/docs/chapter.Rmd")),
            Some(Path::new("/project/panache.toml")),
            &cfg,
        );

        assert_eq!(qmd_flavor, Some(Flavor::Quarto));
        assert_eq!(rmd_flavor, Some(Flavor::RMarkdown));
    }

    #[test]
    fn user_config_adds_formatters() {
        let toml_str = r#"
            [formatters.r]
            cmd = "custom"
            args = ["--flag"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Only R should be configured
        assert_eq!(cfg.formatters.len(), 1);
        let r_fmt = &cfg.formatters.get("r").unwrap()[0];
        assert_eq!(r_fmt.cmd, "custom");
        assert_eq!(r_fmt.args, vec!["--flag"]);
    }

    #[test]
    fn empty_formatters_section_stays_empty() {
        let toml_str = r#"
            line_width = 100
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Formatters are opt-in, should be empty
        assert!(cfg.formatters.is_empty());
    }

    #[test]
    fn preset_with_enabled_false() {
        let toml_str = r#"
            [formatters.r]
            preset = "air"
            enabled = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        // Old format with enabled=false should not include the formatter
        assert!(!cfg.formatters.contains_key("r"));
    }

    #[test]
    fn default_flavor_is_pandoc() {
        let default_cfg = Config::default();
        assert_eq!(default_cfg.flavor, Flavor::Pandoc);
    }

    #[test]
    fn extensions_merge_with_flavor_quarto() {
        // Test that extension overrides properly merge with Quarto flavor defaults
        let toml_str = r#"
            flavor = "quarto"
            
            [extensions]
            quarto-crossrefs = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // The overridden extension should be false
        assert!(!cfg.extensions.quarto_crossrefs);

        // Other Quarto-specific extensions should still use Quarto defaults (true)
        assert!(cfg.extensions.quarto_callouts);
        assert!(cfg.extensions.quarto_shortcodes);

        // General Pandoc extensions should also use Quarto defaults
        assert!(cfg.extensions.citations);
        assert!(cfg.extensions.yaml_metadata_block);
        assert!(cfg.extensions.fenced_divs);
    }

    #[test]
    fn extensions_merge_with_flavor_pandoc() {
        // Test that extension overrides work with Pandoc flavor
        let toml_str = r#"
            flavor = "pandoc"
            
            [extensions]
            citations = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // The overridden extension should be false
        assert!(!cfg.extensions.citations);

        // Other Pandoc extensions should still use Pandoc defaults (true)
        assert!(cfg.extensions.yaml_metadata_block);
        assert!(cfg.extensions.fenced_divs);

        // Quarto extensions should be false in Pandoc flavor
        assert!(!cfg.extensions.quarto_crossrefs);
        assert!(!cfg.extensions.quarto_callouts);
    }

    #[test]
    fn extensions_no_override_uses_flavor_defaults() {
        // Test that omitting [extensions] uses flavor defaults
        let toml_str = r#"
            flavor = "quarto"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Should use Quarto defaults
        assert!(cfg.extensions.quarto_crossrefs);
        assert!(cfg.extensions.quarto_callouts);
        assert!(cfg.extensions.quarto_shortcodes);
    }

    #[test]
    fn extensions_empty_section_uses_flavor_defaults() {
        // Test that empty [extensions] section still uses flavor defaults
        let toml_str = r#"
            flavor = "quarto"
            
            [extensions]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Should use Quarto defaults
        assert!(cfg.extensions.quarto_crossrefs);
        assert!(cfg.extensions.quarto_callouts);
        assert!(cfg.extensions.quarto_shortcodes);
    }

    #[test]
    fn extensions_multiple_overrides() {
        // Test multiple extension overrides
        let toml_str = r#"
            flavor = "quarto"
            
            [extensions]
            quarto-crossrefs = false
            citations = false
            emoji = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Overridden extensions
        assert!(!cfg.extensions.quarto_crossrefs);
        assert!(!cfg.extensions.citations);
        assert!(cfg.extensions.emoji);

        // Other Quarto defaults should remain
        assert!(cfg.extensions.quarto_callouts);
        assert!(cfg.extensions.quarto_shortcodes);
    }

    #[test]
    fn extensions_per_flavor_override_wins_over_global() {
        let toml_str = r#"
            flavor = "gfm"

            [extensions]
            task-lists = false
            citations = true

            [extensions.gfm]
            task-lists = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(cfg.extensions.task_lists);
        assert!(cfg.extensions.citations);
    }

    #[test]
    fn extensions_per_flavor_table_is_ignored_for_other_flavors() {
        let toml_str = r#"
            flavor = "pandoc"

            [extensions]
            citations = false

            [extensions.gfm]
            citations = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(!cfg.extensions.citations);
    }

    #[test]
    fn extensions_per_flavor_commonmark_alias_works() {
        let toml_str = r#"
            flavor = "common-mark"

            [extensions]
            citations = true

            [extensions.commonmark]
            citations = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(!cfg.extensions.citations);
    }

    #[test]
    fn multimarkdown_flavor_enables_mmd_header_identifiers_by_default() {
        let cfg = toml::from_str::<Config>("flavor = \"multimarkdown\"").unwrap();

        assert_eq!(cfg.flavor, Flavor::MultiMarkdown);
        assert!(cfg.extensions.mmd_header_identifiers);
        assert!(cfg.extensions.mmd_title_block);
        assert!(cfg.extensions.mmd_link_attributes);
        assert!(!cfg.extensions.pandoc_title_block);
        assert!(cfg.extensions.tex_math_double_backslash);
        assert!(cfg.extensions.definition_lists);
        assert!(cfg.extensions.raw_attribute);
    }

    #[test]
    fn extensions_per_flavor_multimarkdown_table_works() {
        let toml_str = r#"
            flavor = "multimarkdown"

            [extensions]
            mmd-header-identifiers = false

            [extensions.multimarkdown]
            mmd-header-identifiers = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(cfg.extensions.mmd_header_identifiers);
    }

    #[test]
    fn extensions_per_flavor_multimarkdown_title_block_override_works() {
        let toml_str = r#"
            flavor = "multimarkdown"

            [extensions]
            mmd-title-block = false

            [extensions.multimarkdown]
            mmd-title-block = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(cfg.extensions.mmd_title_block);
    }

    #[test]
    fn extensions_per_flavor_multimarkdown_link_attributes_override_works() {
        let toml_str = r#"
            flavor = "multimarkdown"

            [extensions]
            mmd-link-attributes = false

            [extensions.multimarkdown]
            mmd-link-attributes = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert!(cfg.extensions.mmd_link_attributes);
    }

    #[test]
    fn alerts_enabled_by_default_for_gfm() {
        let cfg = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(cfg.extensions.alerts);
    }

    #[test]
    fn auto_identifiers_enabled_by_default_for_pandoc_and_gfm() {
        let pandoc = toml::from_str::<Config>("flavor = \"pandoc\"").unwrap();
        let gfm = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(pandoc.extensions.auto_identifiers);
        assert!(gfm.extensions.auto_identifiers);
    }

    #[test]
    fn gfm_auto_identifiers_enabled_by_default_only_for_gfm() {
        let pandoc = toml::from_str::<Config>("flavor = \"pandoc\"").unwrap();
        let gfm = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        let commonmark = toml::from_str::<Config>("flavor = \"common-mark\"").unwrap();

        assert!(!pandoc.extensions.gfm_auto_identifiers);
        assert!(gfm.extensions.gfm_auto_identifiers);
        assert!(!commonmark.extensions.gfm_auto_identifiers);
    }

    #[test]
    fn footnotes_enabled_by_default_for_gfm() {
        let cfg = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(cfg.extensions.footnotes);
    }

    #[test]
    fn fenced_code_blocks_enabled_by_default_for_gfm() {
        let cfg = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(cfg.extensions.backtick_code_blocks);
        assert!(cfg.extensions.fenced_code_blocks);
    }

    #[test]
    fn tex_math_gfm_enabled_by_default_for_gfm() {
        let cfg = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(cfg.extensions.tex_math_gfm);
    }

    #[test]
    fn executable_code_enabled_by_default_for_quarto_and_rmarkdown() {
        let quarto = toml::from_str::<Config>("flavor = \"quarto\"").unwrap();
        let rmarkdown = toml::from_str::<Config>("flavor = \"rmarkdown\"").unwrap();

        assert!(quarto.extensions.executable_code);
        assert!(rmarkdown.extensions.executable_code);
        assert!(quarto.extensions.quarto_inline_code);
        assert!(quarto.extensions.rmarkdown_inline_code);
        assert!(rmarkdown.extensions.rmarkdown_inline_code);
        assert!(!rmarkdown.extensions.quarto_inline_code);
    }

    #[test]
    fn bookdown_equation_references_enabled_by_default_only_for_rmarkdown() {
        let pandoc = toml::from_str::<Config>("flavor = \"pandoc\"").unwrap();
        let quarto = toml::from_str::<Config>("flavor = \"quarto\"").unwrap();
        let rmarkdown = toml::from_str::<Config>("flavor = \"rmarkdown\"").unwrap();

        assert!(!pandoc.extensions.bookdown_equation_references);
        assert!(!quarto.extensions.bookdown_equation_references);
        assert!(rmarkdown.extensions.bookdown_equation_references);
    }

    #[test]
    fn executable_code_disabled_by_default_for_pandoc_gfm_and_commonmark() {
        let pandoc = toml::from_str::<Config>("flavor = \"pandoc\"").unwrap();
        let gfm = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        let commonmark = toml::from_str::<Config>("flavor = \"common-mark\"").unwrap();

        assert!(!pandoc.extensions.executable_code);
        assert!(!gfm.extensions.executable_code);
        assert!(!commonmark.extensions.executable_code);
        assert!(!pandoc.extensions.quarto_inline_code);
        assert!(!pandoc.extensions.rmarkdown_inline_code);
        assert!(!gfm.extensions.quarto_inline_code);
        assert!(!gfm.extensions.rmarkdown_inline_code);
        assert!(!commonmark.extensions.quarto_inline_code);
        assert!(!commonmark.extensions.rmarkdown_inline_code);
    }

    #[test]
    fn gfm_disables_non_gfm_pandoc_extensions() {
        let cfg = toml::from_str::<Config>("flavor = \"gfm\"").unwrap();
        assert!(!cfg.extensions.citations);
        assert!(!cfg.extensions.definition_lists);
        assert!(!cfg.extensions.fenced_divs);
        assert!(!cfg.extensions.raw_tex);
    }

    #[test]
    fn commonmark_defaults_match_minimal_set() {
        let cfg = toml::from_str::<Config>("flavor = \"common-mark\"").unwrap();
        assert!(cfg.extensions.raw_html);
        assert!(!cfg.extensions.auto_identifiers);
        assert!(!cfg.extensions.autolinks);
        assert!(!cfg.extensions.inline_links);
        assert!(!cfg.extensions.reference_links);
    }

    #[test]
    fn alerts_disabled_by_default_for_pandoc() {
        let cfg = toml::from_str::<Config>("flavor = \"pandoc\"").unwrap();
        assert!(!cfg.extensions.alerts);
    }

    #[test]
    fn format_section_new_format() {
        let toml_str = r#"
            flavor = "quarto"
            
            [format]
            wrap = "sentence"
            built-in-greedy-wrap = true
            blank-lines = "collapse"
            math-delimiter-style = "dollars"
            math-indent = 2
            tab-stops = "preserve"
            tab-width = 4
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert_eq!(cfg.wrap, Some(WrapMode::Sentence));
        assert_eq!(cfg.blank_lines, BlankLines::Collapse);
        assert_eq!(cfg.math_delimiter_style, MathDelimiterStyle::Dollars);
        assert_eq!(cfg.math_indent, 2);
        assert_eq!(cfg.tab_stops, TabStopMode::Preserve);
        assert_eq!(cfg.tab_width, 4);
        assert!(cfg.built_in_greedy_wrap);
    }

    #[test]
    fn format_section_with_deprecated_code_blocks_is_accepted() {
        let toml_str = r#"
            flavor = "pandoc"
            
            [format]
            wrap = "preserve"
            
            [format.code-blocks]
            fence-style = "tilde"
            attribute-style = "explicit"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert_eq!(cfg.wrap, Some(WrapMode::Preserve));
        assert!(cfg.built_in_greedy_wrap);
    }

    #[test]
    fn backwards_compat_old_format_still_works() {
        let toml_str = r#"
            flavor = "quarto"
            wrap = "reflow"
            math-indent = 4
            
            [code-blocks]
            fence-style = "backtick"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Old format should still work
        assert_eq!(cfg.wrap, Some(WrapMode::Reflow));
        assert_eq!(cfg.math_indent, 4);
    }

    #[test]
    fn format_section_takes_precedence() {
        let toml_str = r#"
            flavor = "quarto"
            
            # Old format (should be ignored)
            wrap = "preserve"
            math-indent = 10
            
            # New format (should take precedence)
            [format]
            wrap = "sentence"
            math-indent = 2
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // New [format] section should win
        assert_eq!(cfg.wrap, Some(WrapMode::Sentence));
        assert_eq!(cfg.math_indent, 2);
    }

    #[test]
    fn deprecated_style_section_still_supported() {
        let toml_str = r#"
            [style]
            wrap = "preserve"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();
        assert_eq!(cfg.wrap, Some(WrapMode::Preserve));
    }
}

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

    #[test]
    fn test_deserialize_line_ending_in_config() {
        #[derive(Deserialize)]
        struct TestConfig {
            line_ending: LineEnding,
        }

        let cfg: TestConfig = toml::from_str(r#"line_ending = "lf""#).unwrap();
        assert_eq!(cfg.line_ending, LineEnding::Lf);

        let cfg2: TestConfig = toml::from_str(r#"line_ending = "auto""#).unwrap();
        assert_eq!(cfg2.line_ending, LineEnding::Auto);

        let cfg3: TestConfig = toml::from_str(r#"line_ending = "crlf""#).unwrap();
        assert_eq!(cfg3.line_ending, LineEnding::Crlf);
    }
}

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

    #[test]
    fn test_raw_config_line_ending() {
        // Must use hyphen (line-ending) not underscore due to #[serde(rename_all = "kebab-case")]
        let cfg: Config = toml::from_str(r#"line-ending = "lf""#).unwrap();
        assert_eq!(cfg.line_ending, Some(LineEnding::Lf));

        // Test that it goes through RawConfig properly
        let content = r#"
        line-ending = "crlf"
        line-width = 100
        "#;
        let cfg2: Config = toml::from_str(content).unwrap();
        assert_eq!(cfg2.line_ending, Some(LineEnding::Crlf));
        assert_eq!(cfg2.line_width, 100);
    }
}

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

    #[test]
    fn test_line_ending_field_name() {
        // The RawConfig uses #[serde(rename_all = "kebab-case")] so field names use hyphens
        let cfg: Config = toml::from_str(r#"line-ending = "lf""#).unwrap();
        assert_eq!(cfg.line_ending, Some(LineEnding::Lf));

        // Test all three values
        let cfg_auto: Config = toml::from_str(r#"line-ending = "auto""#).unwrap();
        assert_eq!(cfg_auto.line_ending, Some(LineEnding::Auto));

        let cfg_crlf: Config = toml::from_str(r#"line-ending = "crlf""#).unwrap();
        assert_eq!(cfg_crlf.line_ending, Some(LineEnding::Crlf));
    }
}

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

    #[test]
    fn deprecated_top_level_code_blocks_is_accepted_as_noop() {
        let toml_str = r#"
            flavor = "pandoc"
            
            [code-blocks]
            attribute-style = "explicit"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.flavor, Flavor::Pandoc);
    }

    #[test]
    fn deprecated_format_code_blocks_is_accepted_as_noop() {
        let toml_str = r#"
            flavor = "quarto"
            [format]
            wrap = "reflow"
            
            [format.code-blocks]
            attribute-style = "explicit"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.wrap, Some(WrapMode::Reflow));
    }

    #[test]
    fn no_code_blocks_config_still_parses() {
        let toml_str = r#"
            flavor = "quarto"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.flavor, Flavor::Quarto);
    }

    // ===== New Formatter Format Tests =====

    #[test]
    fn new_format_single_formatter() {
        let toml_str = r#"
            [formatters]
            r = "air"
            python = "black"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert_eq!(cfg.formatters.len(), 2);

        // Check R formatter (resolved from built-in preset)
        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["format", "{}"]);

        // Check Python formatter (resolved from built-in preset)
        let py_fmts = cfg.formatters.get("python").unwrap();
        assert_eq!(py_fmts.len(), 1);
        assert_eq!(py_fmts[0].cmd, "black");
    }

    #[test]
    fn new_format_multiple_formatters() {
        let toml_str = r#"
            [formatters]
            python = ["ruff", "black"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let py_fmts = cfg.formatters.get("python").unwrap();
        assert_eq!(py_fmts.len(), 2);
        assert_eq!(py_fmts[0].cmd, "ruff");
        assert_eq!(py_fmts[1].cmd, "black");
    }

    #[test]
    fn new_format_with_custom_definition() {
        let toml_str = r#"
            [formatters]
            r = "custom-air"
            
            [formatters.custom-air]
            cmd = "air"
            args = ["format", "--custom-flag"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["format", "--custom-flag"]);
    }

    #[test]
    fn new_format_empty_array() {
        let toml_str = r#"
            [formatters]
            r = []
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Empty array means no formatting for this language
        assert!(!cfg.formatters.contains_key("r"));
    }

    #[test]
    fn new_format_reusable_definition() {
        let toml_str = r#"
            [formatters]
            javascript = "prettier"
            typescript = "prettier"
            json = "prettier"
            
            [formatters.prettier]
            cmd = "prettier"
            args = ["--print-width=100"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        assert_eq!(cfg.formatters.len(), 3);

        // All should use the same prettier config
        for lang in ["javascript", "typescript", "json"] {
            let fmts = cfg.formatters.get(lang).unwrap();
            assert_eq!(fmts.len(), 1);
            assert_eq!(fmts[0].cmd, "prettier");
            assert_eq!(fmts[0].args, vec!["--print-width=100"]);
        }
    }

    // ===== Preset inheritance tests =====

    #[test]
    fn preset_inheritance_override_only_args() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            args = ["format", "--custom-flag", "{}"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // cmd and stdin inherited from built-in "air" preset
        assert_eq!(r_fmts[0].cmd, "air");
        assert!(!r_fmts[0].stdin);
        // args overridden
        assert_eq!(r_fmts[0].args, vec!["format", "--custom-flag", "{}"]);
    }

    #[test]
    fn preset_inheritance_override_only_cmd() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            cmd = "custom-air"
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // cmd overridden
        assert_eq!(r_fmts[0].cmd, "custom-air");
        // args and stdin inherited from built-in "air" preset
        assert_eq!(r_fmts[0].args, vec!["format", "{}"]);
        assert!(!r_fmts[0].stdin);
    }

    #[test]
    fn preset_inheritance_override_only_stdin() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            stdin = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // cmd and args inherited from built-in "air" preset
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["format", "{}"]);
        // stdin overridden
        assert!(r_fmts[0].stdin);
    }

    #[test]
    fn preset_inheritance_override_multiple_fields() {
        let toml_str = r#"
            [formatters]
            python = "black"
            
            [formatters.black]
            args = ["--line-length=100"]
            stdin = false
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let py_fmts = cfg.formatters.get("python").unwrap();
        assert_eq!(py_fmts.len(), 1);
        // cmd inherited
        assert_eq!(py_fmts[0].cmd, "black");
        // args and stdin overridden
        assert_eq!(py_fmts[0].args, vec!["--line-length=100"]);
        assert!(!py_fmts[0].stdin);
    }

    #[test]
    fn preset_inheritance_override_all_fields() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            cmd = "totally-different"
            args = ["custom"]
            stdin = true
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // All fields overridden (complete replacement)
        assert_eq!(r_fmts[0].cmd, "totally-different");
        assert_eq!(r_fmts[0].args, vec!["custom"]);
        assert!(r_fmts[0].stdin);
    }

    #[test]
    fn preset_inheritance_empty_definition_uses_preset() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            # Empty definition - should use preset as-is
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // All fields from built-in preset
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["format", "{}"]);
        assert!(!r_fmts[0].stdin);
    }

    #[test]
    fn preset_inheritance_unknown_name_without_cmd_errors() {
        let toml_str = r#"
            [formatters]
            r = "unknown-formatter"
            
            [formatters.unknown-formatter]
            args = ["--flag"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        // Should fail to resolve - unknown preset and no cmd
        // Error logged, formatter not included in map
        assert!(!cfg.formatters.contains_key("r"));
    }

    #[test]
    fn preset_inheritance_unknown_name_with_cmd_works() {
        let toml_str = r#"
            [formatters]
            r = "unknown-formatter"
            
            [formatters.unknown-formatter]
            cmd = "my-custom-formatter"
            args = ["--flag"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Should work - has cmd even though name doesn't match preset
        assert_eq!(r_fmts[0].cmd, "my-custom-formatter");
        assert_eq!(r_fmts[0].args, vec!["--flag"]);
        assert!(r_fmts[0].stdin); // default
    }

    // ===== Tests for append_args and prepend_args =====

    #[test]
    fn append_args_with_preset_inheritance() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            append-args = ["-i", "2"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Preset args: ["format", "{}"]
        // After append: ["format", "{}", "-i", "2"]
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["format", "{}", "-i", "2"]);
        assert!(!r_fmts[0].stdin);
    }

    #[test]
    fn prepend_args_with_preset_inheritance() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            prepend-args = ["--verbose"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Preset args: ["format", "{}"]
        // After prepend: ["--verbose", "format", "{}"]
        assert_eq!(r_fmts[0].cmd, "air");
        assert_eq!(r_fmts[0].args, vec!["--verbose", "format", "{}"]);
        assert!(!r_fmts[0].stdin);
    }

    #[test]
    fn both_prepend_and_append_args() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            prepend_args = ["--verbose"]
            append_args = ["-i", "2"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Preset args: ["format", "{}"]
        // After prepend + append: ["--verbose", "format", "{}", "-i", "2"]
        assert_eq!(r_fmts[0].args, vec!["--verbose", "format", "{}", "-i", "2"]);
    }

    #[test]
    fn append_args_with_explicit_args() {
        let toml_str = r#"
            [formatters]
            r = "custom"
            
            [formatters.custom]
            cmd = "shfmt"
            args = ["-filename", "$FILENAME"]
            append_args = ["-i", "2"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Explicit args with append: ["-filename", "$FILENAME", "-i", "2"]
        assert_eq!(r_fmts[0].cmd, "shfmt");
        assert_eq!(r_fmts[0].args, vec!["-filename", "$FILENAME", "-i", "2"]);
    }

    #[test]
    fn prepend_args_with_explicit_args() {
        let toml_str = r#"
            [formatters]
            r = "custom"
            
            [formatters.custom]
            cmd = "formatter"
            args = ["input.txt"]
            prepend_args = ["--config", "cfg.toml"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Explicit args with prepend: ["--config", "cfg.toml", "input.txt"]
        assert_eq!(r_fmts[0].args, vec!["--config", "cfg.toml", "input.txt"]);
    }

    #[test]
    fn args_override_with_append_still_applies() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            args = ["custom", "override"]
            append_args = ["--extra"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Overridden args + append: ["custom", "override", "--extra"]
        assert_eq!(r_fmts[0].args, vec!["custom", "override", "--extra"]);
    }

    #[test]
    fn empty_append_prepend_arrays() {
        let toml_str = r#"
            [formatters]
            r = "air"
            
            [formatters.air]
            prepend_args = []
            append_args = []
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // Empty modifiers = no-op, preset args unchanged
        assert_eq!(r_fmts[0].args, vec!["format", "{}"]);
    }

    #[test]
    fn modifiers_without_base_args() {
        let toml_str = r#"
            [formatters]
            r = "custom"
            
            [formatters.custom]
            cmd = "formatter"
            prepend_args = ["--flag"]
            append_args = ["--other"]
        "#;
        let cfg = toml::from_str::<Config>(toml_str).unwrap();

        let r_fmts = cfg.formatters.get("r").unwrap();
        assert_eq!(r_fmts.len(), 1);
        // No base args (no preset, no explicit args), modifiers create args from scratch
        // Result: ["--flag", "--other"]
        assert_eq!(r_fmts[0].args, vec!["--flag", "--other"]);
    }
}

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

    #[test]
    fn test_parser_config_default() {
        let cfg = Config::default();
        assert_eq!(cfg.parser.pandoc_compat, PandocCompat::V3_9);
    }

    #[test]
    fn test_parser_config_empty() {
        // Verify empty parser config deserializes correctly
        let toml_str = r#"
            [parser]
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.parser.pandoc_compat, PandocCompat::V3_9);
    }

    #[test]
    fn test_parser_config_pandoc_compat_latest() {
        let toml_str = r#"
            pandoc-compat = "latest"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.parser.pandoc_compat, PandocCompat::Latest);
        assert_eq!(cfg.parser.effective_pandoc_compat(), PandocCompat::V3_9);
    }

    #[test]
    fn test_parser_config_pandoc_compat_accepts_version_aliases() {
        for value in ["3.7", "3-7", "v3.7", "v3-7"] {
            let toml_str = format!("pandoc-compat = \"{}\"\n", value);
            let cfg: Config = toml::from_str(&toml_str).unwrap();
            assert_eq!(cfg.parser.pandoc_compat, PandocCompat::V3_7);
        }

        for value in ["3.9", "3-9", "v3.9", "v3-9"] {
            let toml_str = format!("pandoc-compat = \"{}\"\n", value);
            let cfg: Config = toml::from_str(&toml_str).unwrap();
            assert_eq!(cfg.parser.pandoc_compat, PandocCompat::V3_9);
        }
    }

    #[test]
    fn test_parser_config_pandoc_compat_parser_section_backwards_compat() {
        let toml_str = r#"
            [parser]
            pandoc-compat = "latest"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.parser.pandoc_compat, PandocCompat::Latest);
    }

    #[test]
    fn test_parser_config_pandoc_compat_top_level_takes_precedence() {
        let toml_str = r#"
            pandoc-compat = "3.7"

            [parser]
            pandoc-compat = "latest"
        "#;
        let cfg: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(cfg.parser.pandoc_compat, PandocCompat::V3_7);
    }
}

#[test]
fn test_snake_case_alias_backwards_compat() {
    // Verify that snake_case (old format) still works via aliases
    let toml_str = r#"
            flavor = "quarto"
            
            [extensions]
            quarto_crossrefs = false
            tex_math_dollars = true
            tex_math_gfm = true
        "#;
    let cfg = toml::from_str::<Config>(toml_str).unwrap();

    assert!(!cfg.extensions.quarto_crossrefs);
    assert!(cfg.extensions.tex_math_dollars);
    assert!(cfg.extensions.tex_math_gfm);
}

#[test]
fn test_kebab_case_new_format() {
    // Verify that kebab-case (new format) works
    let toml_str = r#"
            flavor = "quarto"
            
            [extensions]
            quarto-crossrefs = false
            tex-math-dollars = true
            tex-math-gfm = true
        "#;
    let cfg = toml::from_str::<Config>(toml_str).unwrap();

    assert!(!cfg.extensions.quarto_crossrefs);
    assert!(cfg.extensions.tex_math_dollars);
    assert!(cfg.extensions.tex_math_gfm);
}

#[test]
fn test_formatter_prepend_append_args_snake_case() {
    // Old format with snake_case
    let toml_str = r#"
            [formatters.test]
            cmd = "test"
            args = ["--middle"]
            prepend_args = ["--before"]
            append_args = ["--after"]
        "#;
    let cfg = toml::from_str::<Config>(toml_str).unwrap();
    let fmt = &cfg.formatters.get("test").unwrap()[0];

    assert_eq!(fmt.cmd, "test");
    assert_eq!(fmt.args, vec!["--before", "--middle", "--after"]);
}

#[test]
fn test_formatter_prepend_append_args_kebab_case() {
    // New format with kebab-case
    let toml_str = r#"
            [formatters.test]
            cmd = "test"
            args = ["--middle"]
            prepend-args = ["--before"]
            append-args = ["--after"]
        "#;
    let cfg = toml::from_str::<Config>(toml_str).unwrap();
    let fmt = &cfg.formatters.get("test").unwrap()[0];

    assert_eq!(fmt.cmd, "test");
    assert_eq!(fmt.args, vec!["--before", "--middle", "--after"]);
}