rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
/// Rule MD063: Heading capitalization
///
/// See [docs/md063.md](../../docs/md063.md) for full documentation, configuration, and examples.
///
/// This rule enforces consistent capitalization styles for markdown headings.
/// It supports title case, sentence case, and all caps styles.
///
/// **Note:** This rule is disabled by default. Enable it in your configuration:
/// ```toml
/// [MD063]
/// enabled = true
/// style = "title_case"
/// ```
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::utils::range_utils::LineIndex;
use regex::Regex;
use std::collections::HashSet;
use std::ops::Range;
use std::sync::LazyLock;

mod md063_config;
pub use md063_config::{HeadingCapStyle, MD063Config};

// Regex to match inline code spans (backticks)
static INLINE_CODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`+[^`]+`+").unwrap());

// Regex to match markdown links [text](url) or [text][ref]
static LINK_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\([^)]*\)|\[([^\]]*)\]\[[^\]]*\]").unwrap());

// Regex to match inline HTML tags commonly used in headings
// Matches paired tags: <tag>content</tag>, <tag attr="val">content</tag>
// Matches self-closing: <tag/>, <tag />
// Uses explicit list of common inline tags to avoid backreference (not supported in Rust regex)
static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    // Common inline HTML tags used in documentation headings
    let tags = "kbd|abbr|code|span|sub|sup|mark|cite|dfn|var|samp|small|strong|em|b|i|u|s|q|br|wbr";
    let pattern = format!(r"<({tags})(?:\s[^>]*)?>.*?</({tags})>|<({tags})(?:\s[^>]*)?\s*/?>");
    Regex::new(&pattern).unwrap()
});

// Regex to match custom header IDs {#id}
static CUSTOM_ID_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s*\{#[^}]+\}\s*$").unwrap());

/// Represents a segment of heading text
#[derive(Debug, Clone)]
enum HeadingSegment {
    /// Regular text that should be capitalized
    Text(String),
    /// Inline code that should be preserved as-is
    Code(String),
    /// Link with text that may be capitalized and URL that's preserved
    Link {
        full: String,
        text_start: usize,
        text_end: usize,
    },
    /// Inline HTML tag that should be preserved as-is
    Html(String),
}

/// Rule MD063: Heading capitalization
#[derive(Clone)]
pub struct MD063HeadingCapitalization {
    config: MD063Config,
    lowercase_set: HashSet<String>,
    /// Multi-word proper names from MD044 that must survive sentence-case transformation.
    /// Populated via `from_config` when both rules are active.
    proper_names: Vec<String>,
}

impl Default for MD063HeadingCapitalization {
    fn default() -> Self {
        Self::new()
    }
}

impl MD063HeadingCapitalization {
    pub fn new() -> Self {
        let config = MD063Config::default();
        let lowercase_set = config.lowercase_words.iter().cloned().collect();
        Self {
            config,
            lowercase_set,
            proper_names: Vec::new(),
        }
    }

    pub fn from_config_struct(config: MD063Config) -> Self {
        let lowercase_set = config.lowercase_words.iter().cloned().collect();
        Self {
            config,
            lowercase_set,
            proper_names: Vec::new(),
        }
    }

    /// Match `pattern_lower` at `start` in `text` using Unicode-aware lowercasing.
    /// Returns the end byte offset in `text` when the match succeeds.
    ///
    /// This avoids converting the full `text` to lowercase and then reusing those
    /// offsets on the original string, which can panic for case-fold expansions
    /// (e.g. `İ` -> `i̇`).
    fn match_case_insensitive_at(text: &str, start: usize, pattern_lower: &str) -> Option<usize> {
        if start > text.len() || !text.is_char_boundary(start) || pattern_lower.is_empty() {
            return None;
        }

        let mut matched_bytes = 0;

        for (offset, ch) in text[start..].char_indices() {
            if matched_bytes >= pattern_lower.len() {
                break;
            }

            let lowered: String = ch.to_lowercase().collect();
            if !pattern_lower[matched_bytes..].starts_with(&lowered) {
                return None;
            }

            matched_bytes += lowered.len();

            if matched_bytes == pattern_lower.len() {
                return Some(start + offset + ch.len_utf8());
            }
        }

        None
    }

    /// Find the next case-insensitive match of `pattern_lower` in `text`,
    /// returning byte offsets in the ORIGINAL string.
    fn find_case_insensitive_match(text: &str, pattern_lower: &str, search_start: usize) -> Option<(usize, usize)> {
        if pattern_lower.is_empty() || search_start >= text.len() || !text.is_char_boundary(search_start) {
            return None;
        }

        for (offset, _) in text[search_start..].char_indices() {
            let start = search_start + offset;
            if let Some(end) = Self::match_case_insensitive_at(text, start, pattern_lower) {
                return Some((start, end));
            }
        }

        None
    }

    /// Build a map from word byte-position → canonical form for all proper names
    /// that appear in the heading text (case-insensitive phrase match).
    ///
    /// This is used in `apply_sentence_case` so that words belonging to a proper
    /// name phrase are never lowercased to begin with.
    fn proper_name_canonical_forms(&self, text: &str) -> std::collections::HashMap<usize, &str> {
        let mut map = std::collections::HashMap::new();

        for name in &self.proper_names {
            if name.is_empty() {
                continue;
            }
            let name_lower = name.to_lowercase();
            let canonical_words: Vec<&str> = name.split_whitespace().collect();
            if canonical_words.is_empty() {
                continue;
            }
            let mut search_start = 0;

            while search_start < text.len() {
                let Some((abs_pos, end_pos)) = Self::find_case_insensitive_match(text, &name_lower, search_start)
                else {
                    break;
                };

                // Require word boundaries
                let before_ok = abs_pos == 0 || !text[..abs_pos].chars().last().is_some_and(|c| c.is_alphanumeric());
                let after_ok =
                    end_pos >= text.len() || !text[end_pos..].chars().next().is_some_and(|c| c.is_alphanumeric());

                if before_ok && after_ok {
                    // Map each word in the matched region to its canonical form.
                    // We zip the words found in the text slice with the words of the
                    // canonical name so that every word gets the right casing.
                    let text_slice = &text[abs_pos..end_pos];
                    let mut word_idx = 0;
                    let mut slice_offset = 0;

                    for text_word in text_slice.split_whitespace() {
                        if let Some(w_rel) = text_slice[slice_offset..].find(text_word) {
                            let word_abs = abs_pos + slice_offset + w_rel;
                            if let Some(&canonical_word) = canonical_words.get(word_idx) {
                                map.insert(word_abs, canonical_word);
                            }
                            slice_offset += w_rel + text_word.len();
                            word_idx += 1;
                        }
                    }
                }

                // Advance by one Unicode scalar value to allow overlapping matches
                // while staying on a UTF-8 char boundary.
                search_start = abs_pos + text[abs_pos..].chars().next().map_or(1, |c| c.len_utf8());
            }
        }

        map
    }

    /// Check if a word has internal capitals (like "iPhone", "macOS", "GitHub", "iOS")
    fn has_internal_capitals(&self, word: &str) -> bool {
        let chars: Vec<char> = word.chars().collect();
        if chars.len() < 2 {
            return false;
        }

        let first = chars[0];
        let rest = &chars[1..];
        let has_upper_in_rest = rest.iter().any(|c| c.is_uppercase());
        let has_lower_in_rest = rest.iter().any(|c| c.is_lowercase());

        // Case 1: Mixed case after first character (like "iPhone", "macOS", "GitHub", "JavaScript")
        if has_upper_in_rest && has_lower_in_rest {
            return true;
        }

        // Case 2: Lowercase first + uppercase in rest (like "iOS", "eBay")
        if first.is_lowercase() && has_upper_in_rest {
            return true;
        }

        false
    }

    /// Check if a word is an all-caps acronym (2+ consecutive uppercase letters)
    /// Examples: "API", "GPU", "HTTP2", "IO" return true
    /// Examples: "A", "iPhone", "npm" return false
    fn is_all_caps_acronym(&self, word: &str) -> bool {
        // Skip single-letter words (handled by title case rules)
        if word.len() < 2 {
            return false;
        }

        let mut consecutive_upper = 0;
        let mut max_consecutive = 0;

        for c in word.chars() {
            if c.is_uppercase() {
                consecutive_upper += 1;
                max_consecutive = max_consecutive.max(consecutive_upper);
            } else if c.is_lowercase() {
                // Any lowercase letter means not all-caps
                return false;
            } else {
                // Non-letter (number, punctuation) - reset counter but don't fail
                consecutive_upper = 0;
            }
        }

        // Must have at least 2 consecutive uppercase letters
        max_consecutive >= 2
    }

    /// Check if a word should be preserved as-is
    fn should_preserve_word(&self, word: &str) -> bool {
        // Check ignore_words list (case-sensitive exact match)
        if self.config.ignore_words.iter().any(|w| w == word) {
            return true;
        }

        // Check if word has internal capitals and preserve_cased_words is enabled
        if self.config.preserve_cased_words && self.has_internal_capitals(word) {
            return true;
        }

        // Check if word is an all-caps acronym (2+ consecutive uppercase)
        if self.config.preserve_cased_words && self.is_all_caps_acronym(word) {
            return true;
        }

        // Preserve caret notation for control characters (^A, ^Z, ^@, etc.)
        if self.is_caret_notation(word) {
            return true;
        }

        false
    }

    /// Check if a word is caret notation for control characters (e.g., ^A, ^C, ^Z)
    fn is_caret_notation(&self, word: &str) -> bool {
        let chars: Vec<char> = word.chars().collect();
        // Pattern: ^ followed by uppercase letter or @[\]^_
        if chars.len() >= 2 && chars[0] == '^' {
            let second = chars[1];
            // Control characters: ^@ (NUL) through ^_ (US), which includes ^A-^Z
            if second.is_ascii_uppercase() || "@[\\]^_".contains(second) {
                return true;
            }
        }
        false
    }

    /// Check if a word is a "lowercase word" (articles, prepositions, etc.)
    fn is_lowercase_word(&self, word: &str) -> bool {
        self.lowercase_set.contains(&word.to_lowercase())
    }

    /// Apply title case to a single word
    fn title_case_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
        if word.is_empty() {
            return word.to_string();
        }

        // Preserve words in ignore list or with internal capitals
        if self.should_preserve_word(word) {
            return word.to_string();
        }

        // First and last words are always capitalized
        if is_first || is_last {
            return self.capitalize_first(word);
        }

        // Check if it's a lowercase word (articles, prepositions, etc.)
        if self.is_lowercase_word(word) {
            return Self::lowercase_preserving_composition(word);
        }

        // Regular word - capitalize first letter
        self.capitalize_first(word)
    }

    /// Apply canonical proper-name casing while preserving any trailing punctuation
    /// attached to the original whitespace token (e.g. `javascript,` -> `JavaScript,`).
    fn apply_canonical_form_to_word(word: &str, canonical: &str) -> String {
        let canonical_lower = canonical.to_lowercase();
        if canonical_lower.is_empty() {
            return canonical.to_string();
        }

        if let Some(end_pos) = Self::match_case_insensitive_at(word, 0, &canonical_lower) {
            let mut out = String::with_capacity(canonical.len() + word.len().saturating_sub(end_pos));
            out.push_str(canonical);
            out.push_str(&word[end_pos..]);
            out
        } else {
            canonical.to_string()
        }
    }

    /// Capitalize the first letter of a word, handling Unicode properly
    fn capitalize_first(&self, word: &str) -> String {
        if word.is_empty() {
            return String::new();
        }

        // Find the first alphabetic character to capitalize
        let first_alpha_pos = word.find(|c: char| c.is_alphabetic());
        let Some(pos) = first_alpha_pos else {
            return word.to_string();
        };

        let prefix = &word[..pos];
        let mut chars = word[pos..].chars();
        let first = chars.next().unwrap();
        // Use composition-preserving uppercase to avoid decomposing
        // precomposed characters (e.g., ῷ → Ω + combining marks + Ι)
        let first_upper = Self::uppercase_preserving_composition(&first.to_string());
        let rest: String = chars.collect();
        let rest_lower = Self::lowercase_preserving_composition(&rest);
        format!("{prefix}{first_upper}{rest_lower}")
    }

    /// Lowercase a string character-by-character, preserving precomposed
    /// characters that would decompose during case conversion.
    fn lowercase_preserving_composition(s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        for c in s.chars() {
            let lower: String = c.to_lowercase().collect();
            if lower.chars().count() == 1 {
                result.push_str(&lower);
            } else {
                // Lowercasing would decompose this character; keep original
                result.push(c);
            }
        }
        result
    }

    /// Uppercase a string character-by-character, preserving precomposed
    /// characters that would decompose during case conversion.
    /// For example, ῷ (U+1FF7) would decompose into Ω + combining marks + Ι
    /// via to_uppercase(); this function keeps á¿· unchanged instead.
    fn uppercase_preserving_composition(s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        for c in s.chars() {
            let upper: String = c.to_uppercase().collect();
            if upper.chars().count() == 1 {
                result.push_str(&upper);
            } else {
                // Uppercasing would decompose this character; keep original
                result.push(c);
            }
        }
        result
    }

    /// Apply title case to text, using our own title-case logic.
    /// We avoid the external titlecase crate because it decomposes
    /// precomposed Unicode characters during case conversion.
    fn apply_title_case(&self, text: &str) -> String {
        let canonical_forms = self.proper_name_canonical_forms(text);

        let original_words: Vec<&str> = text.split_whitespace().collect();
        let total_words = original_words.len();

        // Pre-compute byte position of each word for canonical form lookup.
        // Use usize::MAX as sentinel for unfound words so canonical_forms.get() returns None.
        let mut word_positions: Vec<usize> = Vec::with_capacity(original_words.len());
        let mut pos = 0;
        for word in &original_words {
            if let Some(rel) = text[pos..].find(word) {
                word_positions.push(pos + rel);
                pos = pos + rel + word.len();
            } else {
                word_positions.push(usize::MAX);
            }
        }

        let result_words: Vec<String> = original_words
            .iter()
            .enumerate()
            .map(|(i, word)| {
                let is_first = i == 0;
                let is_last = i == total_words - 1;

                // Words that are part of an MD044 proper name use the canonical form directly.
                if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
                    return Self::apply_canonical_form_to_word(word, canonical);
                }

                // Preserve words in ignore list or with internal capitals
                if self.should_preserve_word(word) {
                    return (*word).to_string();
                }

                // Handle hyphenated words
                if word.contains('-') {
                    return self.handle_hyphenated_word(word, is_first, is_last);
                }

                self.title_case_word(word, is_first, is_last)
            })
            .collect();

        result_words.join(" ")
    }

    /// Handle hyphenated words like "self-documenting"
    fn handle_hyphenated_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
        let parts: Vec<&str> = word.split('-').collect();
        let total_parts = parts.len();

        let result_parts: Vec<String> = parts
            .iter()
            .enumerate()
            .map(|(i, part)| {
                // First part of first word and last part of last word get special treatment
                let part_is_first = is_first && i == 0;
                let part_is_last = is_last && i == total_parts - 1;
                self.title_case_word(part, part_is_first, part_is_last)
            })
            .collect();

        result_parts.join("-")
    }

    /// Apply sentence case to text
    fn apply_sentence_case(&self, text: &str) -> String {
        if text.is_empty() {
            return text.to_string();
        }

        let canonical_forms = self.proper_name_canonical_forms(text);
        let mut result = String::new();
        let mut current_pos = 0;
        let mut is_first_word = true;

        // Use original text positions to preserve whitespace correctly
        for word in text.split_whitespace() {
            if let Some(pos) = text[current_pos..].find(word) {
                let abs_pos = current_pos + pos;

                // Preserve whitespace before this word
                result.push_str(&text[current_pos..abs_pos]);

                // Words that are part of an MD044 proper name use the canonical form
                // directly, bypassing sentence-case lowercasing entirely.
                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
                    is_first_word = false;
                } else if is_first_word {
                    // Check if word should be preserved BEFORE any capitalization
                    if self.should_preserve_word(word) {
                        // Preserve ignore-words exactly as-is, even at start
                        result.push_str(word);
                    } else {
                        // First word: capitalize first letter, lowercase rest
                        let mut chars = word.chars();
                        if let Some(first) = chars.next() {
                            result.push_str(&Self::uppercase_preserving_composition(&first.to_string()));
                            let rest: String = chars.collect();
                            result.push_str(&Self::lowercase_preserving_composition(&rest));
                        }
                    }
                    is_first_word = false;
                } else {
                    // Non-first words: preserve if needed, otherwise lowercase
                    if self.should_preserve_word(word) {
                        result.push_str(word);
                    } else {
                        result.push_str(&Self::lowercase_preserving_composition(word));
                    }
                }

                current_pos = abs_pos + word.len();
            }
        }

        // Preserve any trailing whitespace
        if current_pos < text.len() {
            result.push_str(&text[current_pos..]);
        }

        result
    }

    /// Apply all caps to text (preserve whitespace)
    fn apply_all_caps(&self, text: &str) -> String {
        if text.is_empty() {
            return text.to_string();
        }

        let canonical_forms = self.proper_name_canonical_forms(text);
        let mut result = String::new();
        let mut current_pos = 0;

        // Use original text positions to preserve whitespace correctly
        for word in text.split_whitespace() {
            if let Some(pos) = text[current_pos..].find(word) {
                let abs_pos = current_pos + pos;

                // Preserve whitespace before this word
                result.push_str(&text[current_pos..abs_pos]);

                // Words that are part of an MD044 proper name use the canonical form directly.
                // This prevents oscillation with MD044 when all-caps style is active.
                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
                } else if self.should_preserve_word(word) {
                    result.push_str(word);
                } else {
                    result.push_str(&Self::uppercase_preserving_composition(word));
                }

                current_pos = abs_pos + word.len();
            }
        }

        // Preserve any trailing whitespace
        if current_pos < text.len() {
            result.push_str(&text[current_pos..]);
        }

        result
    }

    /// Parse heading text into segments
    fn parse_segments(&self, text: &str) -> Vec<HeadingSegment> {
        let mut segments = Vec::new();
        let mut last_end = 0;

        // Collect all special regions (code and links)
        let mut special_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();

        // Find inline code spans
        for mat in INLINE_CODE_REGEX.find_iter(text) {
            special_regions.push((mat.start(), mat.end(), HeadingSegment::Code(mat.as_str().to_string())));
        }

        // Find links
        for caps in LINK_REGEX.captures_iter(text) {
            let full_match = caps.get(0).unwrap();
            let text_match = caps.get(1).or_else(|| caps.get(2));

            if let Some(text_m) = text_match {
                special_regions.push((
                    full_match.start(),
                    full_match.end(),
                    HeadingSegment::Link {
                        full: full_match.as_str().to_string(),
                        text_start: text_m.start() - full_match.start(),
                        text_end: text_m.end() - full_match.start(),
                    },
                ));
            }
        }

        // Find inline HTML tags
        for mat in HTML_TAG_REGEX.find_iter(text) {
            special_regions.push((mat.start(), mat.end(), HeadingSegment::Html(mat.as_str().to_string())));
        }

        // Sort by start position
        special_regions.sort_by_key(|(start, _, _)| *start);

        // Remove overlapping regions (code takes precedence)
        let mut filtered_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();
        for region in special_regions {
            let overlaps = filtered_regions.iter().any(|(s, e, _)| region.0 < *e && region.1 > *s);
            if !overlaps {
                filtered_regions.push(region);
            }
        }

        // Build segments
        for (start, end, segment) in filtered_regions {
            // Add text before this special region
            if start > last_end {
                let text_segment = &text[last_end..start];
                if !text_segment.is_empty() {
                    segments.push(HeadingSegment::Text(text_segment.to_string()));
                }
            }
            segments.push(segment);
            last_end = end;
        }

        // Add remaining text
        if last_end < text.len() {
            let remaining = &text[last_end..];
            if !remaining.is_empty() {
                segments.push(HeadingSegment::Text(remaining.to_string()));
            }
        }

        // If no segments were found, treat the whole thing as text
        if segments.is_empty() && !text.is_empty() {
            segments.push(HeadingSegment::Text(text.to_string()));
        }

        segments
    }

    /// Apply capitalization to heading text
    fn apply_capitalization(&self, text: &str) -> String {
        // Strip custom ID if present and re-add later
        let (main_text, custom_id) = if let Some(mat) = CUSTOM_ID_REGEX.find(text) {
            (&text[..mat.start()], Some(mat.as_str()))
        } else {
            (text, None)
        };

        // Parse into segments
        let segments = self.parse_segments(main_text);

        // Count text segments to determine first/last word context
        let text_segments: Vec<usize> = segments
            .iter()
            .enumerate()
            .filter_map(|(i, s)| matches!(s, HeadingSegment::Text(_)).then_some(i))
            .collect();

        // Determine if the first segment overall is a text segment
        // For sentence case: if heading starts with code/link, the first text segment
        // should NOT capitalize its first word (the heading already has a "first element")
        let first_segment_is_text = segments
            .first()
            .map(|s| matches!(s, HeadingSegment::Text(_)))
            .unwrap_or(false);

        // Determine if the last segment overall is a text segment
        // If the last segment is Code or Link, then the last text segment should NOT
        // treat its last word as the heading's last word (for lowercase-words respect)
        let last_segment_is_text = segments
            .last()
            .map(|s| matches!(s, HeadingSegment::Text(_)))
            .unwrap_or(false);

        // Apply capitalization to each segment
        let mut result_parts: Vec<String> = Vec::new();

        for (i, segment) in segments.iter().enumerate() {
            match segment {
                HeadingSegment::Text(t) => {
                    let is_first_text = text_segments.first() == Some(&i);
                    // A text segment is "last" only if it's the last text segment AND
                    // the last segment overall is also text. If there's Code/Link after,
                    // the last word should respect lowercase-words.
                    let is_last_text = text_segments.last() == Some(&i) && last_segment_is_text;

                    let capitalized = match self.config.style {
                        HeadingCapStyle::TitleCase => self.apply_title_case_segment(t, is_first_text, is_last_text),
                        HeadingCapStyle::SentenceCase => {
                            // For sentence case, only capitalize first word if:
                            // 1. This is the first text segment, AND
                            // 2. The heading actually starts with text (not code/link)
                            if is_first_text && first_segment_is_text {
                                self.apply_sentence_case(t)
                            } else {
                                // Non-first segments OR heading starts with code/link
                                self.apply_sentence_case_non_first(t)
                            }
                        }
                        HeadingCapStyle::AllCaps => self.apply_all_caps(t),
                    };
                    result_parts.push(capitalized);
                }
                HeadingSegment::Code(c) => {
                    result_parts.push(c.clone());
                }
                HeadingSegment::Link {
                    full,
                    text_start,
                    text_end,
                } => {
                    // Apply capitalization to link text only
                    let link_text = &full[*text_start..*text_end];
                    let capitalized_text = match self.config.style {
                        HeadingCapStyle::TitleCase => self.apply_title_case(link_text),
                        // For sentence case, apply same preservation logic as non-first text
                        // This preserves acronyms (API), brand names (iPhone), etc.
                        HeadingCapStyle::SentenceCase => self.apply_sentence_case_non_first(link_text),
                        HeadingCapStyle::AllCaps => self.apply_all_caps(link_text),
                    };

                    let mut new_link = String::new();
                    new_link.push_str(&full[..*text_start]);
                    new_link.push_str(&capitalized_text);
                    new_link.push_str(&full[*text_end..]);
                    result_parts.push(new_link);
                }
                HeadingSegment::Html(h) => {
                    // Preserve HTML tags as-is (like code)
                    result_parts.push(h.clone());
                }
            }
        }

        let mut result = result_parts.join("");

        // Re-add custom ID if present
        if let Some(id) = custom_id {
            result.push_str(id);
        }

        result
    }

    /// Apply title case to a text segment with first/last awareness
    fn apply_title_case_segment(&self, text: &str, is_first_segment: bool, is_last_segment: bool) -> String {
        let canonical_forms = self.proper_name_canonical_forms(text);
        let words: Vec<&str> = text.split_whitespace().collect();
        let total_words = words.len();

        if total_words == 0 {
            return text.to_string();
        }

        // Pre-compute byte position of each word so we can look up canonical forms.
        // Use usize::MAX as sentinel for unfound words so canonical_forms.get() returns None.
        let mut word_positions: Vec<usize> = Vec::with_capacity(words.len());
        let mut pos = 0;
        for word in &words {
            if let Some(rel) = text[pos..].find(word) {
                word_positions.push(pos + rel);
                pos = pos + rel + word.len();
            } else {
                word_positions.push(usize::MAX);
            }
        }

        let result_words: Vec<String> = words
            .iter()
            .enumerate()
            .map(|(i, word)| {
                let is_first = is_first_segment && i == 0;
                let is_last = is_last_segment && i == total_words - 1;

                // Words that are part of an MD044 proper name use the canonical form directly.
                if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
                    return Self::apply_canonical_form_to_word(word, canonical);
                }

                // Handle hyphenated words
                if word.contains('-') {
                    return self.handle_hyphenated_word(word, is_first, is_last);
                }

                self.title_case_word(word, is_first, is_last)
            })
            .collect();

        // Preserve original spacing
        let mut result = String::new();
        let mut word_iter = result_words.iter();
        let mut in_word = false;

        for c in text.chars() {
            if c.is_whitespace() {
                if in_word {
                    in_word = false;
                }
                result.push(c);
            } else if !in_word {
                if let Some(word) = word_iter.next() {
                    result.push_str(word);
                }
                in_word = true;
            }
        }

        result
    }

    /// Apply sentence case to non-first segments (just lowercase, preserve whitespace)
    fn apply_sentence_case_non_first(&self, text: &str) -> String {
        if text.is_empty() {
            return text.to_string();
        }

        let canonical_forms = self.proper_name_canonical_forms(text);
        let mut result = String::new();
        let mut current_pos = 0;

        // Iterate over words in the original text so byte positions are consistent
        // with the positions in canonical_forms (built from the same text).
        for word in text.split_whitespace() {
            if let Some(pos) = text[current_pos..].find(word) {
                let abs_pos = current_pos + pos;

                // Preserve whitespace before this word
                result.push_str(&text[current_pos..abs_pos]);

                // Words that are part of an MD044 proper name use the canonical form directly.
                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
                } else if self.should_preserve_word(word) {
                    result.push_str(word);
                } else {
                    result.push_str(&Self::lowercase_preserving_composition(word));
                }

                current_pos = abs_pos + word.len();
            }
        }

        // Preserve any trailing whitespace
        if current_pos < text.len() {
            result.push_str(&text[current_pos..]);
        }

        result
    }

    /// Get byte range for a line
    fn get_line_byte_range(&self, content: &str, line_num: usize, line_index: &LineIndex) -> Range<usize> {
        let start_pos = line_index.get_line_start_byte(line_num).unwrap_or(content.len());
        let line = content.lines().nth(line_num - 1).unwrap_or("");
        Range {
            start: start_pos,
            end: start_pos + line.len(),
        }
    }

    /// Fix an ATX heading line
    fn fix_atx_heading(&self, _line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
        // Parse the line to preserve structure
        let indent = " ".repeat(heading.marker_column);
        let hashes = "#".repeat(heading.level as usize);

        // Apply capitalization to the text
        let fixed_text = self.apply_capitalization(&heading.raw_text);

        // Reconstruct with closing sequence if present
        let closing = &heading.closing_sequence;
        if heading.has_closing_sequence {
            format!("{indent}{hashes} {fixed_text} {closing}")
        } else {
            format!("{indent}{hashes} {fixed_text}")
        }
    }

    /// Fix a Setext heading line
    fn fix_setext_heading(&self, line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
        // Apply capitalization to the text
        let fixed_text = self.apply_capitalization(&heading.raw_text);

        // Preserve leading whitespace from original line
        let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();

        format!("{leading_ws}{fixed_text}")
    }
}

impl Rule for MD063HeadingCapitalization {
    fn name(&self) -> &'static str {
        "MD063"
    }

    fn description(&self) -> &'static str {
        "Heading capitalization"
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Heading
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        !ctx.likely_has_headings() || !ctx.lines.iter().any(|line| line.heading.is_some())
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let content = ctx.content;

        if content.is_empty() {
            return Ok(Vec::new());
        }

        let mut warnings = Vec::new();
        let line_index = &ctx.line_index;

        for (line_num, line_info) in ctx.lines.iter().enumerate() {
            if let Some(heading) = &line_info.heading {
                // Check level filter
                if heading.level < self.config.min_level || heading.level > self.config.max_level {
                    continue;
                }

                // Skip headings in code blocks (indented headings)
                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
                    continue;
                }

                // Apply capitalization and compare
                let original_text = &heading.raw_text;
                let fixed_text = self.apply_capitalization(original_text);

                if original_text != &fixed_text {
                    let line = line_info.content(ctx.content);
                    let style_name = match self.config.style {
                        HeadingCapStyle::TitleCase => "title case",
                        HeadingCapStyle::SentenceCase => "sentence case",
                        HeadingCapStyle::AllCaps => "ALL CAPS",
                    };

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: line_num + 1,
                        column: heading.content_column + 1,
                        end_line: line_num + 1,
                        end_column: heading.content_column + 1 + original_text.len(),
                        message: format!("Heading should use {style_name}: '{original_text}' -> '{fixed_text}'"),
                        severity: Severity::Warning,
                        fix: Some(Fix {
                            range: self.get_line_byte_range(content, line_num + 1, line_index),
                            replacement: match heading.style {
                                crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
                                _ => self.fix_setext_heading(line, heading),
                            },
                        }),
                    });
                }
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        let content = ctx.content;

        if content.is_empty() {
            return Ok(content.to_string());
        }

        let lines = ctx.raw_lines();
        let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();

        for (line_num, line_info) in ctx.lines.iter().enumerate() {
            // Skip lines where the rule is disabled via inline config
            if ctx.is_rule_disabled(self.name(), line_num + 1) {
                continue;
            }

            if let Some(heading) = &line_info.heading {
                // Check level filter
                if heading.level < self.config.min_level || heading.level > self.config.max_level {
                    continue;
                }

                // Skip headings in code blocks
                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
                    continue;
                }

                let original_text = &heading.raw_text;
                let fixed_text = self.apply_capitalization(original_text);

                if original_text != &fixed_text {
                    let line = line_info.content(ctx.content);
                    fixed_lines[line_num] = match heading.style {
                        crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
                        _ => self.fix_setext_heading(line, heading),
                    };
                }
            }
        }

        // Reconstruct content preserving line endings
        let mut result = String::with_capacity(content.len());
        for (i, line) in fixed_lines.iter().enumerate() {
            result.push_str(line);
            if i < fixed_lines.len() - 1 || content.ends_with('\n') {
                result.push('\n');
            }
        }

        Ok(result)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let json_value = serde_json::to_value(&self.config).ok()?;
        Some((
            self.name().to_string(),
            crate::rule_config_serde::json_to_toml_value(&json_value)?,
        ))
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD063Config>(config);
        let md044_config =
            crate::rule_config_serde::load_rule_config::<crate::rules::md044_proper_names::MD044Config>(config);
        let mut rule = Self::from_config_struct(rule_config);
        rule.proper_names = md044_config.names;
        Box::new(rule)
    }
}

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

    fn create_rule() -> MD063HeadingCapitalization {
        let config = MD063Config {
            enabled: true,
            ..Default::default()
        };
        MD063HeadingCapitalization::from_config_struct(config)
    }

    fn create_rule_with_style(style: HeadingCapStyle) -> MD063HeadingCapitalization {
        let config = MD063Config {
            enabled: true,
            style,
            ..Default::default()
        };
        MD063HeadingCapitalization::from_config_struct(config)
    }

    // Title case tests
    #[test]
    fn test_title_case_basic() {
        let rule = create_rule();
        let content = "# hello world\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].message.contains("Hello World"));
    }

    #[test]
    fn test_title_case_lowercase_words() {
        let rule = create_rule();
        let content = "# the quick brown fox\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // "The" should be capitalized (first word), "quick", "brown", "fox" should be capitalized
        assert!(result[0].message.contains("The Quick Brown Fox"));
    }

    #[test]
    fn test_title_case_already_correct() {
        let rule = create_rule();
        let content = "# The Quick Brown Fox\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Already correct heading should not be flagged");
    }

    #[test]
    fn test_title_case_hyphenated() {
        let rule = create_rule();
        let content = "# self-documenting code\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].message.contains("Self-Documenting Code"));
    }

    // Sentence case tests
    #[test]
    fn test_sentence_case_basic() {
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# The Quick Brown Fox\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].message.contains("The quick brown fox"));
    }

    #[test]
    fn test_sentence_case_already_correct() {
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# The quick brown fox\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());
    }

    // All caps tests
    #[test]
    fn test_all_caps_basic() {
        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
        let content = "# hello world\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].message.contains("HELLO WORLD"));
    }

    // Preserve tests
    #[test]
    fn test_preserve_ignore_words() {
        let config = MD063Config {
            enabled: true,
            ignore_words: vec!["iPhone".to_string(), "macOS".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        let content = "# using iPhone on macOS\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // iPhone and macOS should be preserved
        assert!(result[0].message.contains("iPhone"));
        assert!(result[0].message.contains("macOS"));
    }

    #[test]
    fn test_preserve_cased_words() {
        let rule = create_rule();
        let content = "# using GitHub actions\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // GitHub should be preserved (has internal capital)
        assert!(result[0].message.contains("GitHub"));
    }

    // Inline code tests
    #[test]
    fn test_inline_code_preserved() {
        let rule = create_rule();
        let content = "# using `const` in javascript\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // `const` should be preserved, rest capitalized
        assert!(result[0].message.contains("`const`"));
        assert!(result[0].message.contains("Javascript") || result[0].message.contains("JavaScript"));
    }

    // Level filter tests
    #[test]
    fn test_level_filter() {
        let config = MD063Config {
            enabled: true,
            min_level: 2,
            max_level: 4,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        let content = "# h1 heading\n## h2 heading\n### h3 heading\n##### h5 heading\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Only h2 and h3 should be flagged (h1 < min_level, h5 > max_level)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 2); // h2
        assert_eq!(result[1].line, 3); // h3
    }

    // Fix tests
    #[test]
    fn test_fix_atx_heading() {
        let rule = create_rule();
        let content = "# hello world\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "# Hello World\n");
    }

    #[test]
    fn test_fix_multiple_headings() {
        let rule = create_rule();
        let content = "# first heading\n\n## second heading\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "# First Heading\n\n## Second Heading\n");
    }

    // Setext heading tests
    #[test]
    fn test_setext_heading() {
        let rule = create_rule();
        let content = "hello world\n============\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].message.contains("Hello World"));
    }

    // Custom ID tests
    #[test]
    fn test_custom_id_preserved() {
        let rule = create_rule();
        let content = "# getting started {#intro}\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // Custom ID should be preserved
        assert!(result[0].message.contains("{#intro}"));
    }

    // Acronym preservation tests
    #[test]
    fn test_preserve_all_caps_acronyms() {
        let rule = create_rule();
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Basic acronyms should be preserved
        let fixed = rule.fix(&ctx("# using API in production\n")).unwrap();
        assert_eq!(fixed, "# Using API in Production\n");

        // Multiple acronyms
        let fixed = rule.fix(&ctx("# API and GPU integration\n")).unwrap();
        assert_eq!(fixed, "# API and GPU Integration\n");

        // Two-letter acronyms
        let fixed = rule.fix(&ctx("# IO performance guide\n")).unwrap();
        assert_eq!(fixed, "# IO Performance Guide\n");

        // Acronyms with numbers
        let fixed = rule.fix(&ctx("# HTTP2 and MD5 hashing\n")).unwrap();
        assert_eq!(fixed, "# HTTP2 and MD5 Hashing\n");
    }

    #[test]
    fn test_preserve_acronyms_in_hyphenated_words() {
        let rule = create_rule();
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Acronyms at start of hyphenated word
        let fixed = rule.fix(&ctx("# API-driven architecture\n")).unwrap();
        assert_eq!(fixed, "# API-Driven Architecture\n");

        // Multiple acronyms with hyphens
        let fixed = rule.fix(&ctx("# GPU-accelerated CPU-intensive tasks\n")).unwrap();
        assert_eq!(fixed, "# GPU-Accelerated CPU-Intensive Tasks\n");
    }

    #[test]
    fn test_single_letters_not_treated_as_acronyms() {
        let rule = create_rule();
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Single uppercase letters should follow title case rules, not be preserved
        let fixed = rule.fix(&ctx("# i am a heading\n")).unwrap();
        assert_eq!(fixed, "# I Am a Heading\n");
    }

    #[test]
    fn test_lowercase_terms_need_ignore_words() {
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Without ignore_words: npm gets capitalized
        let rule = create_rule();
        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
        assert_eq!(fixed, "# Using Npm Packages\n");

        // With ignore_words: npm preserved
        let config = MD063Config {
            enabled: true,
            ignore_words: vec!["npm".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);
        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
        assert_eq!(fixed, "# Using npm Packages\n");
    }

    #[test]
    fn test_acronyms_with_mixed_case_preserved() {
        let rule = create_rule();
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Both acronyms (API, GPU) and mixed-case (GitHub) should be preserved
        let fixed = rule.fix(&ctx("# using API with GitHub\n")).unwrap();
        assert_eq!(fixed, "# Using API with GitHub\n");
    }

    #[test]
    fn test_real_world_acronyms() {
        let rule = create_rule();
        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);

        // Common technical acronyms from tested repositories
        let content = "# FFI bindings for CPU optimization\n";
        let fixed = rule.fix(&ctx(content)).unwrap();
        assert_eq!(fixed, "# FFI Bindings for CPU Optimization\n");

        let content = "# DOM manipulation and SSR rendering\n";
        let fixed = rule.fix(&ctx(content)).unwrap();
        assert_eq!(fixed, "# DOM Manipulation and SSR Rendering\n");

        let content = "# CVE security and RNN models\n";
        let fixed = rule.fix(&ctx(content)).unwrap();
        assert_eq!(fixed, "# CVE Security and RNN Models\n");
    }

    #[test]
    fn test_is_all_caps_acronym() {
        let rule = create_rule();

        // Should return true for all-caps with 2+ letters
        assert!(rule.is_all_caps_acronym("API"));
        assert!(rule.is_all_caps_acronym("IO"));
        assert!(rule.is_all_caps_acronym("GPU"));
        assert!(rule.is_all_caps_acronym("HTTP2")); // Numbers don't break it

        // Should return false for single letters
        assert!(!rule.is_all_caps_acronym("A"));
        assert!(!rule.is_all_caps_acronym("I"));

        // Should return false for words with lowercase
        assert!(!rule.is_all_caps_acronym("Api"));
        assert!(!rule.is_all_caps_acronym("npm"));
        assert!(!rule.is_all_caps_acronym("iPhone"));
    }

    #[test]
    fn test_sentence_case_ignore_words_first_word() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            ignore_words: vec!["nvim".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // "nvim" as first word should be preserved exactly
        let content = "# nvim config\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "nvim in ignore-words should not be flagged. Got: {result:?}"
        );

        // Verify fix also preserves it
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "# nvim config\n");
    }

    #[test]
    fn test_sentence_case_ignore_words_not_first() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            ignore_words: vec!["nvim".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // "nvim" in middle should also be preserved
        let content = "# Using nvim editor\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "nvim in ignore-words should be preserved. Got: {result:?}"
        );
    }

    #[test]
    fn test_preserve_cased_words_ios() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // "iOS" should be preserved (has mixed case: lowercase 'i' + uppercase 'OS')
        let content = "## This is iOS\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "iOS should be preserved with preserve-cased-words. Got: {result:?}"
        );

        // Verify fix also preserves it
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "## This is iOS\n");
    }

    #[test]
    fn test_preserve_cased_words_ios_title_case() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // "iOS" should be preserved in title case too
        let content = "# developing for iOS\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "# Developing for iOS\n");
    }

    #[test]
    fn test_has_internal_capitals_ios() {
        let rule = create_rule();

        // iOS should be detected as having internal capitals
        assert!(
            rule.has_internal_capitals("iOS"),
            "iOS has mixed case (lowercase i, uppercase OS)"
        );

        // Other mixed-case words
        assert!(rule.has_internal_capitals("iPhone"));
        assert!(rule.has_internal_capitals("macOS"));
        assert!(rule.has_internal_capitals("GitHub"));
        assert!(rule.has_internal_capitals("JavaScript"));
        assert!(rule.has_internal_capitals("eBay"));

        // All-caps should NOT be detected (handled by is_all_caps_acronym)
        assert!(!rule.has_internal_capitals("API"));
        assert!(!rule.has_internal_capitals("GPU"));

        // All-lowercase should NOT be detected
        assert!(!rule.has_internal_capitals("npm"));
        assert!(!rule.has_internal_capitals("config"));

        // Regular capitalized words should NOT be detected
        assert!(!rule.has_internal_capitals("The"));
        assert!(!rule.has_internal_capitals("Hello"));
    }

    #[test]
    fn test_lowercase_words_before_trailing_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec![
                "a".to_string(),
                "an".to_string(),
                "and".to_string(),
                "at".to_string(),
                "but".to_string(),
                "by".to_string(),
                "for".to_string(),
                "from".to_string(),
                "into".to_string(),
                "nor".to_string(),
                "on".to_string(),
                "onto".to_string(),
                "or".to_string(),
                "the".to_string(),
                "to".to_string(),
                "upon".to_string(),
                "via".to_string(),
                "vs".to_string(),
                "with".to_string(),
                "without".to_string(),
            ],
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Test: "subtitle with a `app`" (all lowercase input)
        // Expected fix: "Subtitle With a `app`" - capitalize "Subtitle" and "With",
        // but keep "a" lowercase (it's in lowercase-words and not the last word)
        // Incorrect: "Subtitle with A `app`" (would incorrectly capitalize "a")
        let content = "## subtitle with a `app`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag it
        assert!(!result.is_empty(), "Should flag incorrect capitalization");
        let fixed = rule.fix(&ctx).unwrap();
        // "a" should remain lowercase (not "A") because inline code at end doesn't change lowercase-words behavior
        assert!(
            fixed.contains("with a `app`"),
            "Expected 'with a `app`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("with A `app`"),
            "Should not capitalize 'a' to 'A'. Got: {fixed:?}"
        );
        // "Subtitle" should be capitalized, "with" and "a" should remain lowercase (they're in lowercase-words)
        assert!(
            fixed.contains("Subtitle with a `app`"),
            "Expected 'Subtitle with a `app`' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_lowercase_words_preserved_before_trailing_code_variant() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Another variant: "Title with the `code`"
        let content = "## Title with the `code`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "the" should remain lowercase
        assert!(
            fixed.contains("with the `code`"),
            "Expected 'with the `code`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("with The `code`"),
            "Should not capitalize 'the' to 'The'. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_last_word_capitalized_when_no_trailing_code() {
        // Verify that when there's NO trailing code, the last word IS capitalized
        // (even if it's in lowercase-words) - this is the normal title case behavior
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // "title with a word" - "word" is last, should be capitalized
        // "a" is in lowercase-words and not last, so should be lowercase
        let content = "## title with a word\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "a" should be lowercase, "word" should be capitalized (it's last)
        assert!(
            fixed.contains("With a Word"),
            "Expected 'With a Word' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_multiple_lowercase_words_before_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec![
                "a".to_string(),
                "the".to_string(),
                "with".to_string(),
                "for".to_string(),
            ],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Multiple lowercase words before code - all should remain lowercase
        let content = "## Guide for the `user`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("for the `user`"),
            "Expected 'for the `user`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("For The `user`"),
            "Should not capitalize lowercase words before code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_code_in_middle_normal_rules_apply() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Code in the middle - normal title case rules apply (last word capitalized)
        let content = "## Using `const` for the code\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "for" and "the" should be lowercase (middle), "code" should be capitalized (last)
        assert!(
            fixed.contains("for the Code"),
            "Expected 'for the Code' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_link_at_end_same_as_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Link at the end - same behavior as code (lowercase words before should remain lowercase)
        let content = "## Guide for the [link](./page.md)\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "for" and "the" should remain lowercase (not last word because link follows)
        assert!(
            fixed.contains("for the [Link]"),
            "Expected 'for the [Link]' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("for The [Link]"),
            "Should not capitalize 'the' before link. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_multiple_code_segments() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Multiple code segments - last segment is code, so lowercase words before should remain lowercase
        let content = "## Using `const` with a `variable`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "a" should remain lowercase (not last word because code follows)
        assert!(
            fixed.contains("with a `variable`"),
            "Expected 'with a `variable`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("with A `variable`"),
            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_code_and_link_combination() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Code then link - last segment is link, so lowercase words before code should remain lowercase
        let content = "## Guide for the `code` [link](./page.md)\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "for" and "the" should remain lowercase (not last word because link follows)
        assert!(
            fixed.contains("for the `code`"),
            "Expected 'for the `code`' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_text_after_code_capitalizes_last() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Code in middle, text after - last word should be capitalized
        let content = "## Using `const` for the code\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "for" and "the" should be lowercase, "code" is last word, should be capitalized
        assert!(
            fixed.contains("for the Code"),
            "Expected 'for the Code' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_preserve_cased_words_with_trailing_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Preserve-cased words should still work with trailing code
        let content = "## Guide for iOS `app`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "iOS" should be preserved, "for" should be lowercase
        assert!(
            fixed.contains("for iOS `app`"),
            "Expected 'for iOS `app`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("For iOS `app`"),
            "Should not capitalize 'for' before trailing code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_ignore_words_with_trailing_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
            ignore_words: vec!["npm".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Ignore-words should still work with trailing code
        let content = "## Using npm with a `script`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "npm" should be preserved, "with" and "a" should be lowercase
        assert!(
            fixed.contains("npm with a `script`"),
            "Expected 'npm with a `script`' but got: {fixed:?}"
        );
        assert!(
            !fixed.contains("with A `script`"),
            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_empty_text_segment_edge_case() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "with".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Edge case: code at start, then text with lowercase word, then code at end
        let content = "## `start` with a `end`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "with" is first word in text segment, so capitalized (correct)
        // "a" should remain lowercase (not last word because code follows) - this is the key test
        assert!(fixed.contains("a `end`"), "Expected 'a `end`' but got: {fixed:?}");
        assert!(
            !fixed.contains("A `end`"),
            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_sentence_case_with_trailing_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            lowercase_words: vec!["a".to_string(), "the".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Sentence case should also respect lowercase words before code
        let content = "## guide for the `user`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // First word capitalized, rest lowercase including "the" before code
        assert!(
            fixed.contains("Guide for the `user`"),
            "Expected 'Guide for the `user`' but got: {fixed:?}"
        );
    }

    #[test]
    fn test_hyphenated_word_before_code() {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);

        // Hyphenated word before code - last part should respect lowercase-words
        let content = "## Self-contained with a `feature`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // "with" and "a" should remain lowercase (not last word because code follows)
        assert!(
            fixed.contains("with a `feature`"),
            "Expected 'with a `feature`' but got: {fixed:?}"
        );
    }

    // Issue #228: Sentence case with inline code at heading start
    // When a heading starts with inline code, the first word after the code
    // should NOT be capitalized because the heading already has a "first element"

    #[test]
    fn test_sentence_case_code_at_start_basic() {
        // The exact case from issue #228
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# `rumdl` is a linter\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should be correct as-is: code is first, "is" stays lowercase
        assert!(
            result.is_empty(),
            "Heading with code at start should not flag 'is' for capitalization. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_code_at_start_incorrect_capitalization() {
        // Verify we detect incorrect capitalization after code at start
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# `rumdl` Is a Linter\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should flag: "Is" and "Linter" should be lowercase
        assert_eq!(result.len(), 1, "Should detect incorrect capitalization");
        assert!(
            result[0].message.contains("`rumdl` is a linter"),
            "Should suggest lowercase after code. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_code_at_start_fix() {
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# `rumdl` Is A Linter\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("# `rumdl` is a linter"),
            "Should fix to lowercase after code. Got: {fixed:?}"
        );
    }

    #[test]
    fn test_sentence_case_text_at_start_still_capitalizes() {
        // Ensure normal headings still capitalize first word
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# the quick brown fox\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(
            result[0].message.contains("The quick brown fox"),
            "Text-first heading should capitalize first word. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_link_at_start() {
        // Links at start: link text is lowercased, following text also lowercase
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        // Use lowercase link text to avoid link text case flagging
        let content = "# [api](api.md) reference guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "reference" should be lowercase (link is first)
        assert!(
            result.is_empty(),
            "Heading with link at start should not capitalize 'reference'. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_link_preserves_acronyms() {
        // Acronyms in link text should be preserved (API, HTTP, etc.)
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# [API](api.md) Reference Guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // "API" should be preserved (acronym), "Reference Guide" should be lowercased
        assert!(
            result[0].message.contains("[API](api.md) reference guide"),
            "Should preserve acronym 'API' but lowercase following text. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_link_preserves_brand_names() {
        // Brand names with internal capitals should be preserved
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);
        let content = "# [iPhone](iphone.md) Features Guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // "iPhone" should be preserved, "Features Guide" should be lowercased
        assert!(
            result[0].message.contains("[iPhone](iphone.md) features guide"),
            "Should preserve 'iPhone' but lowercase following text. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_link_lowercases_regular_words() {
        // Regular words in link text should be lowercased
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# [Documentation](docs.md) Reference\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        // "Documentation" should be lowercased (regular word)
        assert!(
            result[0].message.contains("[documentation](docs.md) reference"),
            "Should lowercase regular link text. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_link_at_start_correct_already() {
        // Link with correct casing should not be flagged
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# [API](api.md) reference guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Correctly cased heading with link should not be flagged. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_link_github_preserved() {
        // GitHub should be preserved (internal capitals)
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);
        let content = "# [GitHub](gh.md) Repository Setup\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert!(
            result[0].message.contains("[GitHub](gh.md) repository setup"),
            "Should preserve 'GitHub'. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_multiple_code_spans() {
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# `foo` and `bar` are methods\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // All text after first code should be lowercase
        assert!(
            result.is_empty(),
            "Should not capitalize words between/after code spans. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_code_only_heading() {
        // Heading with only code, no text
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# `rumdl`\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Code-only heading should be fine. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_code_at_end() {
        // Heading ending with code, text before should still capitalize first word
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# install the `rumdl` tool\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "install" should be capitalized (first word), rest lowercase
        assert_eq!(result.len(), 1);
        assert!(
            result[0].message.contains("Install the `rumdl` tool"),
            "First word should still be capitalized when text comes first. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_code_in_middle() {
        // Code in middle, text at start should capitalize first word
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# using the `rumdl` linter for markdown\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "using" should be capitalized, rest lowercase
        assert_eq!(result.len(), 1);
        assert!(
            result[0].message.contains("Using the `rumdl` linter for markdown"),
            "First word should be capitalized. Got: {:?}",
            result[0].message
        );
    }

    #[test]
    fn test_sentence_case_preserved_word_after_code() {
        // Preserved words (like iPhone) should stay preserved even after code
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            preserve_cased_words: true,
            ..Default::default()
        };
        let rule = MD063HeadingCapitalization::from_config_struct(config);
        let content = "# `swift` iPhone development\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "iPhone" should be preserved, "development" lowercase
        assert!(
            result.is_empty(),
            "Preserved words after code should stay. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_title_case_code_at_start_still_capitalizes() {
        // Title case should still capitalize words even after code at start
        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
        let content = "# `api` quick start guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Title case: all major words capitalized
        assert_eq!(result.len(), 1);
        assert!(
            result[0].message.contains("Quick Start Guide") || result[0].message.contains("quick Start Guide"),
            "Title case should capitalize major words after code. Got: {:?}",
            result[0].message
        );
    }

    // ======== HTML TAG TESTS ========

    #[test]
    fn test_sentence_case_html_tag_at_start() {
        // HTML tag at start: text after should NOT capitalize first word
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# <kbd>Ctrl</kbd> is a Modifier Key\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "is", "a", "Modifier", "Key" should all be lowercase (except preserved words)
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# <kbd>Ctrl</kbd> is a modifier key\n",
            "Text after HTML at start should be lowercase"
        );
    }

    #[test]
    fn test_sentence_case_html_tag_preserves_content() {
        // Content inside HTML tags should be preserved as-is
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# The <abbr>API</abbr> documentation guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // "The" is first, "API" inside tag preserved, rest lowercase
        assert!(
            result.is_empty(),
            "HTML tag content should be preserved. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_html_tag_at_start_with_acronym() {
        // HTML tag at start with acronym content
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# <abbr>API</abbr> Documentation Guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# <abbr>API</abbr> documentation guide\n",
            "Text after HTML at start should be lowercase, HTML content preserved"
        );
    }

    #[test]
    fn test_sentence_case_html_tag_in_middle() {
        // HTML tag in middle: first word still capitalized
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# using the <code>config</code> File\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# Using the <code>config</code> file\n",
            "First word capitalized, HTML preserved, rest lowercase"
        );
    }

    #[test]
    fn test_html_tag_strong_emphasis() {
        // <strong> tag handling
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# The <strong>Bold</strong> Way\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# The <strong>Bold</strong> way\n",
            "<strong> tag content should be preserved"
        );
    }

    #[test]
    fn test_html_tag_with_attributes() {
        // HTML tags with attributes should still be detected
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# <span class=\"highlight\">Important</span> Notice Here\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# <span class=\"highlight\">Important</span> notice here\n",
            "HTML tag with attributes should be preserved"
        );
    }

    #[test]
    fn test_multiple_html_tags() {
        // Multiple HTML tags in heading
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to Copy Text\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy text\n",
            "Multiple HTML tags should all be preserved"
        );
    }

    #[test]
    fn test_html_and_code_mixed() {
        // Mix of HTML tags and inline code
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# <kbd>Ctrl</kbd>+`v` Paste command\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# <kbd>Ctrl</kbd>+`v` paste command\n",
            "HTML and code should both be preserved"
        );
    }

    #[test]
    fn test_self_closing_html_tag() {
        // Self-closing tags like <br/>
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "# Line one<br/>Line Two Here\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "# Line one<br/>line two here\n",
            "Self-closing HTML tags should be preserved"
        );
    }

    #[test]
    fn test_title_case_with_html_tags() {
        // Title case with HTML tags
        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
        let content = "# the <kbd>ctrl</kbd> key is a modifier\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        // "the" as first word should be "The", content inside <kbd> preserved
        assert!(
            fixed.contains("<kbd>ctrl</kbd>"),
            "HTML tag content should be preserved in title case. Got: {fixed}"
        );
        assert!(
            fixed.starts_with("# The ") || fixed.starts_with("# the "),
            "Title case should work with HTML. Got: {fixed}"
        );
    }

    // ======== CARET NOTATION TESTS ========

    #[test]
    fn test_sentence_case_preserves_caret_notation() {
        // Caret notation for control characters should be preserved
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
        let content = "## Ctrl+A, Ctrl+R output ^A, ^R on zsh\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should not flag - ^A and ^R are preserved
        assert!(
            result.is_empty(),
            "Caret notation should be preserved. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_sentence_case_caret_notation_various() {
        // Various caret notation patterns
        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);

        // ^C for interrupt
        let content = "## Press ^C to cancel\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "^C should be preserved. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );

        // ^Z for suspend
        let content = "## Use ^Z for background\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "^Z should be preserved. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );

        // ^[ for escape
        let content = "## Press ^[ for escape\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "^[ should be preserved. Got: {:?}",
            result.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_caret_notation_detection() {
        let rule = create_rule();

        // Valid caret notation
        assert!(rule.is_caret_notation("^A"));
        assert!(rule.is_caret_notation("^Z"));
        assert!(rule.is_caret_notation("^C"));
        assert!(rule.is_caret_notation("^@")); // NUL
        assert!(rule.is_caret_notation("^[")); // ESC
        assert!(rule.is_caret_notation("^]")); // GS
        assert!(rule.is_caret_notation("^^")); // RS
        assert!(rule.is_caret_notation("^_")); // US

        // Not caret notation
        assert!(!rule.is_caret_notation("^a")); // lowercase
        assert!(!rule.is_caret_notation("A")); // no caret
        assert!(!rule.is_caret_notation("^")); // caret alone
        assert!(!rule.is_caret_notation("^1")); // digit
    }

    // MD044 proper names integration tests
    //
    // When MD063 (sentence case) and MD044 (proper names) are both active, MD063 must
    // preserve the exact capitalization of MD044 proper names rather than lowercasing them.
    // Without this, the two rules oscillate: MD044 re-capitalizes what MD063 lowercases.

    fn create_sentence_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::SentenceCase,
            ..Default::default()
        };
        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
        rule.proper_names = names;
        rule
    }

    #[test]
    fn test_sentence_case_preserves_single_word_proper_name() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
        // "javascript" in non-first position should become "JavaScript", not "javascript"
        let content = "# installing javascript\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("JavaScript"),
            "Fix should preserve proper name 'JavaScript', got: {fix_text:?}"
        );
        assert!(
            !fix_text.contains("javascript"),
            "Fix should not have lowercase 'javascript', got: {fix_text:?}"
        );
    }

    #[test]
    fn test_sentence_case_preserves_multi_word_proper_name() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
        // "Good Application" is a proper name; sentence case must not lowercase "Application"
        let content = "# using good application features\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("Good Application"),
            "Fix should preserve 'Good Application' as a phrase, got: {fix_text:?}"
        );
    }

    #[test]
    fn test_sentence_case_proper_name_at_start_of_heading() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
        // The proper name "Good Application" starts the heading; both words must be canonical
        let content = "# good application overview\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("Good Application"),
            "Fix should produce 'Good Application' at start of heading, got: {fix_text:?}"
        );
        assert!(
            fix_text.contains("overview"),
            "Non-proper-name word 'overview' should be lowercase, got: {fix_text:?}"
        );
    }

    #[test]
    fn test_sentence_case_with_proper_names_no_oscillation() {
        // This is the core convergence test: applying the fix once must produce
        // output that is already correct (no further changes needed).
        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);

        // First application of fix
        let content = "# installing good application on your system\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();

        // The fixed heading should contain the proper name preserved
        assert!(
            fixed_heading.contains("Good Application"),
            "After fix, proper name must be preserved: {fixed_heading:?}"
        );

        // Second application: must produce no further warnings (convergence)
        let fixed_line = format!("{fixed_heading}\n");
        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
        let result2 = rule.check(&ctx2).unwrap();
        assert!(
            result2.is_empty(),
            "After one fix, heading must already satisfy both MD063 and MD044 - no oscillation. \
             Second pass warnings: {result2:?}"
        );
    }

    #[test]
    fn test_sentence_case_proper_names_already_correct() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
        // Heading already has correct sentence case with proper name preserved
        let content = "# Installing Good Application\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Correct sentence-case heading with proper name should not be flagged, got: {result:?}"
        );
    }

    #[test]
    fn test_sentence_case_multiple_proper_names_in_heading() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["TypeScript".to_string(), "React".to_string()]);
        let content = "# using typescript with react\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("TypeScript"),
            "Fix should preserve 'TypeScript', got: {fix_text:?}"
        );
        assert!(
            fix_text.contains("React"),
            "Fix should preserve 'React', got: {fix_text:?}"
        );
    }

    #[test]
    fn test_sentence_case_unicode_casefold_expansion_before_proper_name() {
        // Regression for Unicode case-fold expansion: `İ` lowercases to `i̇` (2 code points),
        // so matching offsets must be computed from the original text, not from a lowercased copy.
        let rule = create_sentence_case_rule_with_proper_names(vec!["Österreich".to_string()]);
        let content = "# İ österreich guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        // Should not panic and should preserve canonical proper-name casing.
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag heading for canonical proper-name casing");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("Österreich"),
            "Fix should preserve canonical 'Österreich', got: {fix_text:?}"
        );
    }

    #[test]
    fn test_sentence_case_preserves_trailing_punctuation_on_proper_name() {
        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
        let content = "# using javascript, today\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("JavaScript,"),
            "Fix should preserve trailing punctuation, got: {fix_text:?}"
        );
    }

    // Title case + MD044 conflict tests
    //
    // In title case, short words like "the", "a", "of" are kept lowercase by MD063.
    // If those words are part of an MD044 proper name (e.g. "The Rolling Stones"),
    // the same oscillation problem occurs.  The fix must extend to title case too.

    fn create_title_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
        let config = MD063Config {
            enabled: true,
            style: HeadingCapStyle::TitleCase,
            ..Default::default()
        };
        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
        rule.proper_names = names;
        rule
    }

    #[test]
    fn test_title_case_preserves_proper_name_with_lowercase_article() {
        // "The" is in the lowercase_words list for title case, so "the" in the middle
        // of a heading would normally stay lowercase.  But "The Rolling Stones" is a
        // proper name that must be capitalised exactly.
        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
        let content = "# listening to the rolling stones today\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("The Rolling Stones"),
            "Fix should preserve proper name 'The Rolling Stones', got: {fix_text:?}"
        );
    }

    #[test]
    fn test_title_case_proper_name_no_oscillation() {
        // One fix pass must produce output that title case already accepts.
        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
        let content = "# listening to the rolling stones today\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();

        let fixed_line = format!("{fixed_heading}\n");
        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
        let result2 = rule.check(&ctx2).unwrap();
        assert!(
            result2.is_empty(),
            "After one title-case fix, heading must already satisfy both rules. \
             Second pass warnings: {result2:?}"
        );
    }

    #[test]
    fn test_title_case_unicode_casefold_expansion_before_proper_name() {
        let rule = create_title_case_rule_with_proper_names(vec!["Österreich".to_string()]);
        let content = "# İ österreich guide\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("Österreich"),
            "Fix should preserve canonical proper-name casing, got: {fix_text:?}"
        );
    }

    // End-to-end integration test: from_config wires MD044 names into MD063
    //
    // This tests the actual code path used in production, where both rules are
    // configured in a rumdl.toml and the rule registry calls from_config.

    #[test]
    fn test_from_config_loads_md044_names_into_md063() {
        use crate::config::{Config, RuleConfig};
        use crate::rule::Rule;
        use std::collections::BTreeMap;

        let mut config = Config::default();

        // Configure MD063 with sentence_case
        let mut md063_values = BTreeMap::new();
        md063_values.insert("style".to_string(), toml::Value::String("sentence_case".to_string()));
        md063_values.insert("enabled".to_string(), toml::Value::Boolean(true));
        config.rules.insert(
            "MD063".to_string(),
            RuleConfig {
                values: md063_values,
                severity: None,
            },
        );

        // Configure MD044 with a proper name
        let mut md044_values = BTreeMap::new();
        md044_values.insert(
            "names".to_string(),
            toml::Value::Array(vec![toml::Value::String("Good Application".to_string())]),
        );
        config.rules.insert(
            "MD044".to_string(),
            RuleConfig {
                values: md044_values,
                severity: None,
            },
        );

        // Build MD063 via the production code path
        let rule = MD063HeadingCapitalization::from_config(&config);

        // Verify MD044 names were loaded: the fix must preserve "Good Application"
        let content = "# using good application features\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
        assert!(
            fix_text.contains("Good Application"),
            "from_config should wire MD044 names into MD063; fix should preserve \
             'Good Application', got: {fix_text:?}"
        );
    }

    #[test]
    fn test_title_case_short_word_not_confused_with_substring() {
        // Verify that short preposition matching ("in") does not trigger on
        // substrings of longer words ("insert"). Title case must capitalize
        // "insert" while keeping "in" lowercase.
        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);

        // "in" is a short preposition (should be lowercase in title case)
        // "insert" contains "in" as substring but is a regular word (should be capitalized)
        let content = "# in the insert\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix = result[0].fix.as_ref().expect("Fix should be present");
        // "In" capitalized as first word, "the" lowercase as article, "Insert" capitalized
        assert!(
            fix.replacement.contains("In the Insert"),
            "Expected 'In the Insert', got: {:?}",
            fix.replacement
        );
    }

    #[test]
    fn test_title_case_or_not_confused_with_orchestra() {
        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);

        // "or" is a conjunction (should be lowercase in title case)
        // "orchestra" contains "or" as substring but is a regular word
        let content = "# or the orchestra\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix = result[0].fix.as_ref().expect("Fix should be present");
        // "Or" capitalized as first word, "the" lowercase, "Orchestra" capitalized
        assert!(
            fix.replacement.contains("Or the Orchestra"),
            "Expected 'Or the Orchestra', got: {:?}",
            fix.replacement
        );
    }

    #[test]
    fn test_all_caps_preserves_all_words() {
        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);

        let content = "# in the insert\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading");
        let fix = result[0].fix.as_ref().expect("Fix should be present");
        assert!(
            fix.replacement.contains("IN THE INSERT"),
            "All caps should uppercase all words, got: {:?}",
            fix.replacement
        );
    }
}