rumdl 0.1.88

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
//! Go-to-definition, find-references, and rename for markdown links
//!
//! Provides navigation features for the LSP server:
//!
//! - **Go to definition** -- jump from a `[text](file.md#heading)` link to the
//!   target file and heading.
//!
//! - **Find references** -- from a heading, find all links pointing to it across
//!   the workspace.
//!
//! - **Rename** -- rename a heading and update all links that reference it.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use tower_lsp::lsp_types::*;

use super::completion::{byte_to_utf16_offset, normalize_path, utf16_to_byte_offset};
use super::server::RumdlLanguageServer;
use crate::utils::anchor_styles::AnchorStyle;
use crate::workspace_index::PROTOCOL_DOMAIN_REGEX;

/// Full link target extracted from a markdown link `[text](file_path#anchor)`.
///
/// Unlike `LinkTargetInfo` (used for completion, which returns content up to the
/// cursor), this struct contains the complete file path and anchor regardless of
/// where the cursor sits within the link target.
struct FullLinkTarget {
    /// The file path portion (before `#`), may be empty for same-file anchors
    file_path: String,
    /// The anchor/fragment portion (after `#`), empty when absent
    anchor: String,
}

/// Strip a CommonMark link title from a link target.
///
/// Link titles start after whitespace followed by `"`, `'`, or `(`.
/// E.g., `guide.md "My Title"` -> `guide.md`
fn strip_link_title(target: &str) -> &str {
    for (i, _) in target.match_indices(' ') {
        let after = &target[i + 1..];
        if after.starts_with('"') || after.starts_with('\'') || after.starts_with('(') {
            return target[..i].trim_end();
        }
    }
    target
}

/// Check whether a link target is an external URL (has a protocol or `www.` prefix).
///
/// External URLs like `https://example.com` or `mailto:user@host` have no
/// corresponding local file, so go-to-definition and find-references should
/// return `None` for them.
fn is_external_url(target: &str) -> bool {
    PROTOCOL_DOMAIN_REGEX.is_match(target)
}

/// Find the position of the closing `)` that balances with the opening `(`.
///
/// CommonMark allows balanced parentheses in link destinations, e.g.
/// `[text](file(1).md)`. This helper tracks nesting depth to find the
/// correct closing paren.
fn find_balanced_close_paren(s: &str) -> Option<usize> {
    let mut depth: usize = 0;
    for (i, ch) in s.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => {
                if depth == 0 {
                    return Some(i);
                }
                depth -= 1;
            }
            _ => {}
        }
    }
    None
}

/// Detect the full link target when the cursor is anywhere inside `](...)`.
///
/// Scans backward from the cursor to find `](` and forward to find the closing
/// `)`, then extracts the complete file path and optional anchor.
fn detect_full_link_target(text: &str, position: Position) -> Option<FullLinkTarget> {
    let line_num = position.line as usize;
    let utf16_cursor = position.character as usize;

    let lines: Vec<&str> = text.lines().collect();
    if line_num >= lines.len() {
        return None;
    }
    let line = lines[line_num];

    // Convert UTF-16 cursor to byte offset
    let byte_cursor = utf16_to_byte_offset(line, utf16_cursor)?;

    let before_cursor = &line[..byte_cursor];

    // Find the last `](` before the cursor
    let link_open = before_cursor.rfind("](")?;
    let content_start = link_open + 2;

    // Find the balanced closing `)` after the content start
    let after_open = &line[content_start..];
    let close_paren = find_balanced_close_paren(after_open)?;

    let raw_content = &after_open[..close_paren];

    // Verify the cursor is within the link target (between `](` and `)`)
    let content_end = content_start + close_paren;
    if byte_cursor < content_start || byte_cursor > content_end {
        return None;
    }

    // Heuristic: odd number of backticks before `](` suggests code span
    let backtick_count = before_cursor[..link_open].chars().filter(|&c| c == '`').count();
    if backtick_count % 2 != 0 {
        return None;
    }

    // Strip angle brackets: [text](<path.md>) -> path.md
    let content = raw_content.trim();
    let content = if content.starts_with('<') && content.ends_with('>') {
        &content[1..content.len() - 1]
    } else {
        content
    };

    // Strip link title: guide.md "Title" -> guide.md
    let content = strip_link_title(content);

    // Split on first `#` to separate file path from anchor
    if let Some(hash_pos) = content.find('#') {
        Some(FullLinkTarget {
            file_path: content[..hash_pos].to_string(),
            anchor: content[hash_pos + 1..].to_string(),
        })
    } else {
        Some(FullLinkTarget {
            file_path: content.to_string(),
            anchor: String::new(),
        })
    }
}

/// Find same-file fragment-only links (e.g., `[text](#anchor)`) in the given content.
///
/// Uses pulldown-cmark to parse the document, which natively skips code blocks
/// and code spans, eliminating false positives from literal `](#...)` text.
fn find_same_file_fragment_links(content: &str, uri: &Url, anchor: &str) -> Vec<Location> {
    use pulldown_cmark::{Event, Parser, Tag};

    let options = crate::utils::rumdl_parser_options();

    let parser = Parser::new_ext(content, options).into_offset_iter();

    let mut locations = Vec::new();

    for (event, range) in parser {
        if let Event::Start(Tag::Link { dest_url, .. }) = event {
            // Fragment-only: destination is exactly `#something`.
            // This catches all link types (inline, reference, collapsed, shortcut)
            // since pulldown-cmark resolves reference destinations for us.
            if let Some(frag) = dest_url.strip_prefix('#')
                && frag.eq_ignore_ascii_case(anchor)
            {
                // Convert byte offset to line/column (UTF-16 for LSP)
                let byte_start = range.start;
                let line_idx = content[..byte_start].matches('\n').count();
                let line_start = content[..byte_start].rfind('\n').map_or(0, |p| p + 1);
                let line_text = content[line_start..].split('\n').next().unwrap_or("");
                let character = byte_to_utf16_offset(line_text, byte_start - line_start);

                locations.push(Location {
                    uri: uri.clone(),
                    range: Range {
                        start: Position {
                            line: line_idx as u32,
                            character,
                        },
                        end: Position {
                            line: line_idx as u32,
                            character,
                        },
                    },
                });
            }
        }
    }
    locations
}

/// Detect a reference-style link at the cursor and resolve it to a `FullLinkTarget`.
///
/// Handles three CommonMark reference link forms:
/// - Full reference: `[text][ref-id]`
/// - Collapsed reference: `[text][]`
/// - Shortcut reference: `[text]`
///
/// Also handles cursor on a reference definition line: `[ref-id]: target.md`
///
/// Returns `None` if the cursor is not on a reference link or the reference
/// definition cannot be found in the document.
fn detect_ref_link_target(text: &str, position: Position) -> Option<FullLinkTarget> {
    let line_num = position.line as usize;
    let utf16_cursor = position.character as usize;

    let lines: Vec<&str> = text.lines().collect();
    if line_num >= lines.len() {
        return None;
    }
    let line = lines[line_num];
    let byte_cursor = utf16_to_byte_offset(line, utf16_cursor)?;

    // First, check if cursor is on a reference definition line: `[ref-id]: target`
    if let Some(target) = detect_ref_definition(line) {
        return Some(target);
    }

    // Detect reference link usage and resolve it
    let ref_id = detect_ref_link_usage(line, byte_cursor)?;
    resolve_reference_to_target(text, &ref_id)
}

/// Detect whether the cursor is on a reference link usage and return the ref ID.
///
/// Recognises:
/// - `[text][ref-id]` — full reference (returns `ref-id`)
/// - `[text][]`       — collapsed reference (returns `text`)
/// - `[text]`         — shortcut reference (returns `text`, only when no `(` follows)
fn detect_ref_link_usage(line: &str, byte_cursor: usize) -> Option<String> {
    // Heuristic: odd number of backticks before cursor suggests code span
    let backtick_count = line[..byte_cursor].chars().filter(|&c| c == '`').count();
    if backtick_count % 2 != 0 {
        return None;
    }

    // Skip reference definitions (lines like `[ref]: target`)
    let trimmed = line.trim_start();
    if trimmed.starts_with('[')
        && let Some(colon_pos) = trimmed.find("]:")
        && colon_pos == trimmed.find(']').unwrap_or(0)
    {
        return None;
    }

    let before = &line[..byte_cursor];

    // Find the nearest `[` before cursor
    let open = before.rfind('[')?;

    // Find its matching `]`
    let from_open = &line[open..];
    let rel_close = from_open.find(']')?;
    let close = open + rel_close;

    // Cursor must be within this bracket pair
    if byte_cursor > close {
        return None;
    }

    let bracket_content = &line[open + 1..close];

    // Check if this bracket pair is the second part of `[text][ref-id]`
    // i.e. a `]` immediately precedes our `[`
    if open > 0 && line.as_bytes()[open - 1] == b']' {
        if bracket_content.is_empty() {
            // Collapsed: `[text][]` — ref ID is the text from the first bracket
            let text_open = line[..open - 1].rfind('[')?;
            let text_content = &line[text_open + 1..open - 1];
            return Some(text_content.to_lowercase());
        }
        // Full reference: `[text][ref-id]` — cursor is in [ref-id]
        return Some(bracket_content.to_lowercase());
    }

    // Cursor is in the first (or only) bracket pair
    let after_close = &line[close + 1..];

    // Full reference `[text][ref-id]`: cursor is on [text], extract ref-id
    if after_close.starts_with('[')
        && let Some(ref_close) = after_close[1..].find(']')
    {
        let ref_id = &after_close[1..=ref_close];
        if !ref_id.is_empty() {
            return Some(ref_id.to_lowercase());
        }
    }

    // Collapsed reference `[text][]`: cursor is on [text]
    if after_close.starts_with("[]") {
        return Some(bracket_content.to_lowercase());
    }

    // Shortcut reference `[text]`: no `(` or `[` follows
    if !after_close.starts_with('(') && !after_close.starts_with('[') && !bracket_content.is_empty() {
        return Some(bracket_content.to_lowercase());
    }

    None
}

/// Detect a reference definition on the current line: `[ref-id]: target.md#anchor`
///
/// Returns a `FullLinkTarget` if the line is a reference definition.
fn detect_ref_definition(line: &str) -> Option<FullLinkTarget> {
    use regex::Regex;
    use std::sync::LazyLock;

    static REF_DEF_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"^[ ]{0,3}\[([^\]]+)\]:\s+<?([^>\s]+)>?"#).unwrap());

    let caps = REF_DEF_RE.captures(line)?;
    let target = caps.get(2)?.as_str();

    // Split on first `#` to separate file path from anchor
    if let Some(hash_pos) = target.find('#') {
        Some(FullLinkTarget {
            file_path: target[..hash_pos].to_string(),
            anchor: target[hash_pos + 1..].to_string(),
        })
    } else {
        Some(FullLinkTarget {
            file_path: target.to_string(),
            anchor: String::new(),
        })
    }
}

/// Compute byte ranges of fenced code blocks and code spans using pulldown-cmark.
///
/// Reference definitions inside these ranges should be ignored because
/// CommonMark does not recognise them as definitions.
fn code_byte_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
    use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};

    let parser = Parser::new_ext(text, Options::empty()).into_offset_iter();
    let mut ranges = Vec::new();
    let mut code_block_start: Option<usize> = None;

    for (event, range) in parser {
        match &event {
            Event::Start(Tag::CodeBlock(_)) => {
                code_block_start = Some(range.start);
            }
            Event::End(TagEnd::CodeBlock) => {
                if let Some(start) = code_block_start.take() {
                    ranges.push(start..range.end);
                }
            }
            Event::Code(_) => {
                ranges.push(range);
            }
            _ => {}
        }
    }
    ranges
}

/// Scan the document for a reference definition `[ref_id]: target` and
/// return the parsed target.
///
/// Definitions inside fenced code blocks and code spans are skipped,
/// matching CommonMark semantics.
fn resolve_reference_to_target(text: &str, ref_id: &str) -> Option<FullLinkTarget> {
    use regex::Regex;
    use std::sync::LazyLock;

    static REF_DEF_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"(?m)^[ ]{0,3}\[([^\]]+)\]:\s+<?([^>\s]+)>?"#).unwrap());

    let code_ranges = code_byte_ranges(text);

    for caps in REF_DEF_RE.captures_iter(text) {
        let Some(id) = caps.get(1) else { continue };

        // Skip definitions that fall inside code blocks or code spans
        let match_start = caps.get(0).map_or(0, |m| m.start());
        if code_ranges.iter().any(|r| r.contains(&match_start)) {
            continue;
        }

        if !id.as_str().eq_ignore_ascii_case(ref_id) {
            continue;
        }

        let Some(target) = caps.get(2) else { continue };
        let target = target.as_str();
        return if let Some(hash_pos) = target.find('#') {
            Some(FullLinkTarget {
                file_path: target[..hash_pos].to_string(),
                anchor: target[hash_pos + 1..].to_string(),
            })
        } else {
            Some(FullLinkTarget {
                file_path: target.to_string(),
                anchor: String::new(),
            })
        };
    }

    None
}

impl RumdlLanguageServer {
    /// Handle `textDocument/definition` requests.
    ///
    /// When the cursor is on a markdown link `[text](target.md#anchor)`, resolves
    /// the target file path and optional heading anchor, then returns a `Location`
    /// pointing to the target.
    pub(super) async fn handle_goto_definition(&self, uri: &Url, position: Position) -> Option<GotoDefinitionResponse> {
        let text = self.get_document_content(uri).await?;

        let link = detect_full_link_target(&text, position).or_else(|| detect_ref_link_target(&text, position))?;

        // External URLs have no local file to navigate to
        if is_external_url(&link.file_path) {
            return None;
        }

        self.resolve_link_target(uri, &link).await
    }

    /// Handle `textDocument/hover` requests.
    ///
    /// When the cursor is on a markdown link, shows a preview of the target:
    /// - External URLs: shows the URL
    /// - Local files without anchor: shows the file path and first lines
    /// - Local files with anchor: shows the heading and content below it
    pub(super) async fn handle_hover(&self, uri: &Url, position: Position) -> Option<Hover> {
        let text = self.get_document_content(uri).await?;

        let link = detect_full_link_target(&text, position).or_else(|| detect_ref_link_target(&text, position))?;

        // External URLs: show the URL itself
        if is_external_url(&link.file_path) {
            return Some(Hover {
                contents: HoverContents::Markup(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: format!("**External link**\n\n{}", link.file_path),
                }),
                range: None,
            });
        }

        let current_file = uri.to_file_path().ok()?;
        let current_dir = current_file.parent()?.to_path_buf();

        let target_path = if link.file_path.is_empty() {
            current_file.clone()
        } else {
            normalize_path(&current_dir.join(&link.file_path))
        };

        // Read target file content
        let target_uri = Url::from_file_path(&target_path).ok()?;
        let target_content = self.get_document_content(&target_uri).await?;

        let preview = if !link.anchor.is_empty() {
            self.build_anchor_preview(&target_path, &link.anchor, &target_content)
                .await
        } else {
            self.build_file_preview(&target_path, &target_content)
        };

        Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: preview,
            }),
            range: None,
        })
    }

    /// Build a hover preview for a link targeting a specific heading anchor.
    ///
    /// Finds the heading line in the file and extracts up to 15 lines of content
    /// below it (stopping at the next heading of equal or higher level).
    async fn build_anchor_preview(&self, file_path: &Path, anchor: &str, content: &str) -> String {
        let lines: Vec<&str> = content.lines().collect();

        // Look up the heading line from the workspace index
        let heading_line = self.resolve_heading_line(file_path, anchor).await;

        let Some(heading_line_0indexed) = heading_line else {
            let display_path = file_path.file_name().unwrap_or(file_path.as_os_str());
            return format!("{}#{}\n\n*Heading not found*", display_path.to_string_lossy(), anchor);
        };

        let start = heading_line_0indexed as usize;
        if start >= lines.len() {
            let display_path = file_path.file_name().unwrap_or(file_path.as_os_str());
            return format!("{}#{}", display_path.to_string_lossy(), anchor);
        }

        // Determine the heading level of the target heading
        let heading_level = lines[start].chars().take_while(|&c| c == '#').count();

        // Collect lines: the heading + up to 15 lines of content below it,
        // stopping at the next heading of equal or higher level.
        // Track whether we stopped due to reaching the line limit vs section end.
        let max_lines = 15;
        let mut preview_lines: Vec<&str> = vec![lines[start]];
        let mut in_fenced_code_block = false;
        let mut hit_line_limit = false;

        for (i, line) in lines.iter().skip(start + 1).enumerate() {
            if i >= max_lines {
                hit_line_limit = true;
                break;
            }

            // Track fenced code blocks to avoid false heading detection
            let trimmed = line.trim_start();
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_fenced_code_block = !in_fenced_code_block;
            }

            if !in_fenced_code_block {
                let line_level = trimmed.chars().take_while(|&c| c == '#').count();
                // ATX heading requires a space after the `#` characters (or be empty)
                let after_hashes = &trimmed[trimmed.len().min(line_level)..];
                let is_atx_heading = line_level > 0 && (after_hashes.is_empty() || after_hashes.starts_with(' '));
                if is_atx_heading && line_level <= heading_level {
                    break;
                }
            }

            preview_lines.push(line);
        }

        let mut preview = preview_lines.join("\n");
        if hit_line_limit {
            preview.push_str("\n\n...");
        }
        preview
    }

    /// Build a hover preview for a link targeting a whole file (no anchor).
    ///
    /// Shows the file name and the first 15 lines of content.
    fn build_file_preview(&self, file_path: &Path, content: &str) -> String {
        let display_path = file_path.file_name().unwrap_or(file_path.as_os_str());
        let lines: Vec<&str> = content.lines().collect();
        let max_lines = 15;
        let preview_lines: Vec<&str> = lines.iter().take(max_lines).copied().collect();

        let mut preview = format!("**{}**\n\n{}", display_path.to_string_lossy(), preview_lines.join("\n"));
        if lines.len() > max_lines {
            preview.push_str("\n\n...");
        }
        preview
    }

    /// Handle `textDocument/references` requests.
    ///
    /// When the cursor is on a heading, finds all links across the workspace that
    /// reference this heading. When the cursor is on a link, finds all other links
    /// that point to the same target.
    pub(super) async fn handle_references(&self, uri: &Url, position: Position) -> Option<Vec<Location>> {
        let text = self.get_document_content(uri).await?;
        let current_file = uri.to_file_path().ok()?;

        // Check if cursor is on a heading by consulting the workspace index.
        // This avoids false positives from `#` lines inside code blocks.
        let heading_line_1indexed = (position.line as usize) + 1;
        let heading_anchor = {
            let index = self.workspace_index.read().await;
            index.get_file(&current_file).and_then(|file_index| {
                file_index
                    .headings
                    .iter()
                    .find(|h| h.line == heading_line_1indexed)
                    .map(|h| h.custom_anchor.clone().unwrap_or_else(|| h.auto_anchor.clone()))
            })
        };

        if let Some(anchor) = heading_anchor {
            // Find cross-file references
            let mut locations = self
                .find_references_to_target(&current_file, &anchor)
                .await
                .unwrap_or_default();

            // Also find same-file fragment-only links (e.g., [text](#anchor))
            let same_file = find_same_file_fragment_links(&text, uri, &anchor);
            locations.extend(same_file);

            return if locations.is_empty() { None } else { Some(locations) };
        }

        // Check if cursor is on a link (inline or reference-style)
        if let Some(link) = detect_full_link_target(&text, position).or_else(|| detect_ref_link_target(&text, position))
        {
            // External URLs have no local file to find references for
            if is_external_url(&link.file_path) {
                return None;
            }

            let current_dir = current_file.parent()?.to_path_buf();
            let target_path = if link.file_path.is_empty() {
                current_file.clone()
            } else {
                normalize_path(&current_dir.join(&link.file_path))
            };

            return self.find_references_to_target(&target_path, &link.anchor).await;
        }

        // Fallback: find all cross-file references pointing to the current file,
        // regardless of fragment. This handles the common case where a user opens
        // a target file and invokes find-references to discover what links to it.
        self.find_all_references_to_file(&current_file).await
    }

    /// Find all links across the workspace that point to `target_file`,
    /// regardless of the fragment/anchor.
    ///
    /// This is the fallback for find-references when the cursor is not on a
    /// heading or a link: it returns every cross-file link whose resolved path
    /// matches `target_file`.
    async fn find_all_references_to_file(&self, target_file: &Path) -> Option<Vec<Location>> {
        let index = self.workspace_index.read().await;
        let mut locations = Vec::new();

        for (source_path, file_index) in index.files() {
            let source_dir = source_path.parent().unwrap_or(Path::new(""));

            let matching_links: Vec<_> = file_index
                .cross_file_links
                .iter()
                .filter(|link| {
                    let resolved_target = normalize_path(&source_dir.join(&link.target_path));
                    resolved_target == *target_file
                })
                .collect();

            if matching_links.is_empty() {
                continue;
            }

            let Ok(source_uri) = Url::from_file_path(source_path) else {
                continue;
            };

            let source_content = tokio::fs::read_to_string(source_path).await.ok();
            let source_lines: Vec<&str> = source_content
                .as_deref()
                .map(|c| c.lines().collect())
                .unwrap_or_default();

            for link in matching_links {
                let line = (link.line.saturating_sub(1)) as u32;
                let byte_col_0indexed = link.column.saturating_sub(1);

                let character = source_lines
                    .get(line as usize)
                    .map_or(byte_col_0indexed as u32, |line_text| {
                        let clamped = byte_col_0indexed.min(line_text.len());
                        byte_to_utf16_offset(line_text, clamped)
                    });

                locations.push(Location {
                    uri: source_uri.clone(),
                    range: Range {
                        start: Position { line, character },
                        end: Position { line, character },
                    },
                });
            }
        }

        if locations.is_empty() { None } else { Some(locations) }
    }

    /// Resolve a `FullLinkTarget` to a `GotoDefinitionResponse`.
    ///
    /// Shared between inline links and reference-style links to avoid
    /// duplicating the path resolution and heading lookup logic.
    async fn resolve_link_target(&self, uri: &Url, link: &FullLinkTarget) -> Option<GotoDefinitionResponse> {
        let current_file = uri.to_file_path().ok()?;
        let current_dir = current_file.parent()?.to_path_buf();

        let target_path = if link.file_path.is_empty() {
            current_file.clone()
        } else {
            normalize_path(&current_dir.join(&link.file_path))
        };

        let target_uri = Url::from_file_path(&target_path).ok()?;

        let target_line = if link.anchor.is_empty() {
            0
        } else {
            self.resolve_heading_line(&target_path, &link.anchor).await.unwrap_or(0)
        };

        let target_position = Position {
            line: target_line,
            character: 0,
        };
        let range = Range {
            start: target_position,
            end: target_position,
        };

        Some(GotoDefinitionResponse::Scalar(Location { uri: target_uri, range }))
    }

    /// Look up a heading's line number (0-indexed for LSP) in the workspace index.
    async fn resolve_heading_line(&self, file_path: &Path, anchor: &str) -> Option<u32> {
        let index = self.workspace_index.read().await;
        let file_index = index.get_file(file_path)?;
        let heading = file_index.get_heading_by_anchor(anchor)?;
        // HeadingIndex.line is 1-indexed; LSP is 0-indexed
        Some((heading.line.saturating_sub(1)) as u32)
    }

    /// Find all links across the workspace that point to `target_path` with
    /// the given `fragment` (anchor).
    ///
    /// An empty fragment matches links that target the file without an anchor.
    async fn find_references_to_target(&self, target_path: &Path, fragment: &str) -> Option<Vec<Location>> {
        let index = self.workspace_index.read().await;
        let mut locations = Vec::new();

        for (source_path, file_index) in index.files() {
            let source_dir = source_path.parent().unwrap_or(Path::new(""));

            // Collect matching links for this file before loading content
            let matching_links: Vec<_> = file_index
                .cross_file_links
                .iter()
                .filter(|link| {
                    let resolved_target = normalize_path(&source_dir.join(&link.target_path));
                    resolved_target == *target_path && link.fragment.eq_ignore_ascii_case(fragment)
                })
                .collect();

            if matching_links.is_empty() {
                continue;
            }

            let Ok(source_uri) = Url::from_file_path(source_path) else {
                continue;
            };

            // Load source content for byte→UTF-16 column conversion.
            // We read the file directly instead of using get_document_content
            // to avoid acquiring additional locks while holding the workspace
            // index read lock.
            let source_content = tokio::fs::read_to_string(source_path).await.ok();
            let source_lines: Vec<&str> = source_content
                .as_deref()
                .map(|c| c.lines().collect())
                .unwrap_or_default();

            for link in matching_links {
                // CrossFileLinkIndex uses 1-indexed line/column; LSP uses 0-indexed
                let line = (link.line.saturating_sub(1)) as u32;
                let byte_col_0indexed = link.column.saturating_sub(1);

                // Convert byte column to UTF-16 code units using the actual line text
                let character = source_lines
                    .get(line as usize)
                    .map_or(byte_col_0indexed as u32, |line_text| {
                        let clamped = byte_col_0indexed.min(line_text.len());
                        byte_to_utf16_offset(line_text, clamped)
                    });

                locations.push(Location {
                    uri: source_uri.clone(),
                    range: Range {
                        start: Position { line, character },
                        end: Position { line, character },
                    },
                });
            }
        }

        if locations.is_empty() { None } else { Some(locations) }
    }

    // =========================================================================
    // Rename support
    // =========================================================================

    /// Handle `textDocument/prepareRename` requests.
    ///
    /// Validates that the cursor is on a heading and returns the renameable
    /// text range (excluding `#` markers, leading whitespace, and custom anchors).
    pub(super) async fn handle_prepare_rename(&self, uri: &Url, position: Position) -> Option<PrepareRenameResponse> {
        let text = self.get_document_content(uri).await?;
        let current_file = uri.to_file_path().ok()?;

        let heading_line_1indexed = (position.line as usize) + 1;

        let heading_info = {
            let index = self.workspace_index.read().await;
            index.get_file(&current_file).and_then(|file_index| {
                file_index
                    .headings
                    .iter()
                    .find(|h| h.line == heading_line_1indexed)
                    .cloned()
            })
        }?;

        let lines: Vec<&str> = text.lines().collect();
        let line_text = lines.get(position.line as usize)?;

        let (text_start, text_end) = if heading_info.is_setext {
            // Setext heading: the entire line is the heading text
            let trimmed_start = line_text.len() - line_text.trim_start().len();
            let trimmed_end = line_text.trim_end().len();
            (trimmed_start, trimmed_end)
        } else {
            let start = find_heading_text_start(line_text)?;
            let end = find_heading_text_end(line_text, start);
            (start, end)
        };

        if text_start >= text_end {
            return None;
        }

        let start_char = byte_to_utf16_offset(line_text, text_start);
        let end_char = byte_to_utf16_offset(line_text, text_end);

        Some(PrepareRenameResponse::Range(Range {
            start: Position {
                line: position.line,
                character: start_char,
            },
            end: Position {
                line: position.line,
                character: end_char,
            },
        }))
    }

    /// Handle `textDocument/rename` requests.
    ///
    /// When a heading is renamed, generates a `WorkspaceEdit` that:
    /// 1. Replaces the heading text in the source file
    /// 2. Updates all cross-file links referencing the old anchor
    /// 3. Updates all same-file fragment links referencing the old anchor
    ///
    /// If the heading has a custom anchor (`{#id}`), only the heading text is
    /// changed — links reference the custom ID which remains unchanged.
    pub(super) async fn handle_rename(&self, uri: &Url, position: Position, new_name: &str) -> Option<WorkspaceEdit> {
        // Reject empty or whitespace-only names
        if new_name.trim().is_empty() {
            return None;
        }

        let text = self.get_document_content(uri).await?;
        let current_file = uri.to_file_path().ok()?;

        let heading_line_1indexed = (position.line as usize) + 1;

        let heading_info = {
            let index = self.workspace_index.read().await;
            index.get_file(&current_file).and_then(|file_index| {
                file_index
                    .headings
                    .iter()
                    .find(|h| h.line == heading_line_1indexed)
                    .cloned()
            })
        }?;

        let has_custom_anchor = heading_info.custom_anchor.is_some();
        let old_anchor = heading_info
            .custom_anchor
            .as_deref()
            .unwrap_or(&heading_info.auto_anchor);

        let lines: Vec<&str> = text.lines().collect();
        let line_text = lines.get(position.line as usize)?;

        let (text_start, text_end) = if heading_info.is_setext {
            let trimmed_start = line_text.len() - line_text.trim_start().len();
            let trimmed_end = line_text.trim_end().len();
            (trimmed_start, trimmed_end)
        } else {
            let start = find_heading_text_start(line_text)?;
            let end = find_heading_text_end(line_text, start);
            (start, end)
        };

        let start_char = byte_to_utf16_offset(line_text, text_start);
        let end_char = byte_to_utf16_offset(line_text, text_end);

        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        // Edit 1: Replace heading text
        changes.entry(uri.clone()).or_default().push(TextEdit {
            range: Range {
                start: Position {
                    line: position.line,
                    character: start_char,
                },
                end: Position {
                    line: position.line,
                    character: end_char,
                },
            },
            new_text: new_name.to_string(),
        });

        // If heading has a custom anchor, links reference the custom ID.
        // Renaming the heading text doesn't change the anchor, so no link updates needed.
        if has_custom_anchor {
            return Some(WorkspaceEdit {
                changes: Some(changes),
                ..Default::default()
            });
        }

        let new_anchor = AnchorStyle::GitHub.generate_fragment(new_name);

        // Check for anchor collision with existing headings in the same file
        {
            let index = self.workspace_index.read().await;
            if let Some(file_index) = index.get_file(&current_file) {
                let collision = file_index.headings.iter().any(|h| {
                    h.line != heading_line_1indexed
                        && (h.auto_anchor.eq_ignore_ascii_case(&new_anchor)
                            || h.custom_anchor
                                .as_deref()
                                .is_some_and(|ca| ca.eq_ignore_ascii_case(&new_anchor)))
                });
                if collision {
                    log::warn!("Rename refused: anchor '{new_anchor}' would collide with existing heading");
                    return None;
                }
            }
        }

        // Collect cross-file link data while holding the lock, then release it
        let cross_file_matches = self.collect_cross_file_link_matches(&current_file, old_anchor).await;

        // Process cross-file matches (file I/O without holding the lock)
        for (source_path, matching_links) in &cross_file_matches {
            // Skip the current file — same-file links are handled separately
            if *source_path == current_file {
                continue;
            }

            let Ok(source_uri) = Url::from_file_path(source_path) else {
                continue;
            };

            // Try editor buffer first, fall back to disk
            let source_content = if let Some(content) = self.get_document_content(&source_uri).await {
                content
            } else {
                match tokio::fs::read_to_string(source_path).await {
                    Ok(c) => c,
                    Err(_) => continue,
                }
            };

            let source_lines: Vec<&str> = source_content.lines().collect();

            // Group links by line to avoid duplicate edits when multiple links
            // on the same line reference the same anchor
            let mut seen_lines: std::collections::HashSet<usize> = std::collections::HashSet::new();
            for link in matching_links {
                let line_idx = link.line.saturating_sub(1);
                if !seen_lines.insert(line_idx) {
                    continue; // already processed this line
                }
                let Some(line_content) = source_lines.get(line_idx) else {
                    continue;
                };

                let edits = find_all_anchor_edits_in_link(line_content, line_idx as u32, old_anchor, &new_anchor);
                changes.entry(source_uri.clone()).or_default().extend(edits);
            }
        }

        // Same-file fragment links (#anchor)
        collect_same_file_anchor_edits(uri, &text, old_anchor, &new_anchor, &mut changes);

        // Same-file reference definitions ([ref]: #anchor)
        collect_same_file_ref_def_edits(uri, &text, old_anchor, &new_anchor, &mut changes);

        Some(WorkspaceEdit {
            changes: Some(changes),
            ..Default::default()
        })
    }

    /// Collect cross-file link matches from the workspace index.
    ///
    /// Returns the data needed to compute edits without holding the lock
    /// during file I/O.
    async fn collect_cross_file_link_matches(
        &self,
        target_path: &Path,
        old_anchor: &str,
    ) -> Vec<(PathBuf, Vec<crate::workspace_index::CrossFileLinkIndex>)> {
        let index = self.workspace_index.read().await;
        let mut result = Vec::new();

        for (source_path, file_index) in index.files() {
            let source_dir = source_path.parent().unwrap_or(Path::new(""));

            let matching: Vec<_> = file_index
                .cross_file_links
                .iter()
                .filter(|link| {
                    let resolved = normalize_path(&source_dir.join(&link.target_path));
                    resolved == *target_path && link.fragment.eq_ignore_ascii_case(old_anchor)
                })
                .cloned()
                .collect();

            if !matching.is_empty() {
                result.push((source_path.to_path_buf(), matching));
            }
        }

        result
    }
}

/// Find the byte offset where ATX heading text starts (after `#` markers and space).
fn find_heading_text_start(line: &str) -> Option<usize> {
    let trimmed = line.trim_start();
    if !trimmed.starts_with('#') {
        return None;
    }
    let leading_ws = line.len() - trimmed.len();
    let hash_count = trimmed.bytes().take_while(|&b| b == b'#').count();
    if hash_count > 6 {
        return None;
    }
    let after_hashes = leading_ws + hash_count;
    // ATX headings require a space after #
    if line.as_bytes().get(after_hashes) == Some(&b' ') {
        Some(after_hashes + 1)
    } else if after_hashes == line.len() {
        // Empty heading: just "##"
        Some(after_hashes)
    } else {
        None
    }
}

/// Find the byte offset where ATX heading text ends.
///
/// Handles:
/// - Custom anchor syntax `{#id}` at end of heading
/// - Closing ATX markers (`## Heading ##`)
fn find_heading_text_end(line: &str, text_start: usize) -> usize {
    let text_portion = &line[text_start..];

    // Check for custom anchor syntax {#id} at end
    if let Some(brace_pos) = text_portion.rfind("{#") {
        // Verify the brace pair is at the end (after trimming)
        if let Some(close_pos) = text_portion[brace_pos..].find('}') {
            let after_brace = text_portion[brace_pos + close_pos + 1..].trim();
            if after_brace.is_empty() {
                let before_brace = text_portion[..brace_pos].trim_end();
                return text_start + before_brace.len();
            }
        }
    }

    // Check for closing ATX markers (trailing ###)
    let trimmed_end = text_portion.trim_end();
    if let Some(last_non_hash_pos) = trimmed_end.rfind(|c: char| c != '#') {
        let after_last = &trimmed_end[last_non_hash_pos..];
        // The character at last_non_hash_pos must be a space for this to be a closing sequence
        let last_char = trimmed_end[last_non_hash_pos..].chars().next().unwrap();
        if last_char == ' ' && after_last.len() > 1 {
            // Closing ATX: trim the space and trailing hashes
            return text_start + last_non_hash_pos;
        }
    }

    text_start + trimmed_end.len()
}

/// Find ALL `#anchor` occurrences inside links on a given line and create TextEdits.
///
/// Searches specifically within the URL portion of links (after `](` or after `]: `)
/// to avoid matching `#` in link display text. Returns all matches, not just the first.
fn find_all_anchor_edits_in_link(line: &str, line_num: u32, old_anchor: &str, new_anchor: &str) -> Vec<TextEdit> {
    let target = format!("#{old_anchor}");
    let target_lower = target.to_lowercase();
    let mut edits = Vec::new();

    // Search for the anchor in the URL portion of links
    // Look for ](url#anchor) patterns
    let mut search_start = 0;
    while search_start < line.len() {
        // Find the next `](` which starts a link URL
        if let Some(paren_start) = line[search_start..].find("](") {
            let url_start = search_start + paren_start + 2;
            // Find the closing `)`
            if let Some(paren_end) = line[url_start..].find(')') {
                let url_portion = &line[url_start..url_start + paren_end];
                if let Some(hash_pos) = url_portion.to_lowercase().find(&target_lower) {
                    let anchor_start = url_start + hash_pos + 1; // after #
                    let anchor_end = anchor_start + old_anchor.len();

                    let start_char = byte_to_utf16_offset(line, anchor_start);
                    let end_char = byte_to_utf16_offset(line, anchor_end);

                    edits.push(TextEdit {
                        range: Range {
                            start: Position {
                                line: line_num,
                                character: start_char,
                            },
                            end: Position {
                                line: line_num,
                                character: end_char,
                            },
                        },
                        new_text: new_anchor.to_string(),
                    });
                }
                search_start = url_start + paren_end + 1;
            } else {
                break;
            }
        } else {
            break;
        }
    }

    // Also check reference definitions: [ref]: file.md#anchor
    if let Some(colon_pos) = line.find("]: ") {
        let def_target = &line[colon_pos + 3..];
        if let Some(hash_pos) = def_target.to_lowercase().find(&target_lower) {
            let anchor_start = colon_pos + 3 + hash_pos + 1; // after #
            let anchor_end = anchor_start + old_anchor.len();
            if anchor_end <= line.len() {
                let start_char = byte_to_utf16_offset(line, anchor_start);
                let end_char = byte_to_utf16_offset(line, anchor_end);

                edits.push(TextEdit {
                    range: Range {
                        start: Position {
                            line: line_num,
                            character: start_char,
                        },
                        end: Position {
                            line: line_num,
                            character: end_char,
                        },
                    },
                    new_text: new_anchor.to_string(),
                });
            }
        }
    }

    edits
}

/// Collect text edits for same-file fragment-only links (`[text](#anchor)`).
///
/// Uses pulldown-cmark to parse links, then searches within the URL portion
/// for the fragment to replace.
fn collect_same_file_anchor_edits(
    uri: &Url,
    content: &str,
    old_anchor: &str,
    new_anchor: &str,
    changes: &mut HashMap<Url, Vec<TextEdit>>,
) {
    use pulldown_cmark::{Event, Parser, Tag};

    let options = crate::utils::rumdl_parser_options();

    let parser = Parser::new_ext(content, options).into_offset_iter();

    for (event, range) in parser {
        if let Event::Start(Tag::Link { dest_url, .. }) = event
            && let Some(frag) = dest_url.strip_prefix('#')
            && frag.eq_ignore_ascii_case(old_anchor)
        {
            // Find the `#fragment` in the raw source within the link range
            let link_source = &content[range.start..range.end];
            if let Some(anchor_byte_in_source) = find_fragment_in_link_source(link_source, old_anchor) {
                let anchor_start_byte = range.start + anchor_byte_in_source;
                let anchor_end_byte = anchor_start_byte + old_anchor.len();

                let line_idx = content[..anchor_start_byte].matches('\n').count();
                let line_start = content[..anchor_start_byte].rfind('\n').map_or(0, |p| p + 1);
                let line_end = content[line_start..]
                    .find('\n')
                    .map_or(content.len(), |p| line_start + p);
                let line_text = &content[line_start..line_end];

                let start_char = byte_to_utf16_offset(line_text, anchor_start_byte - line_start);
                let end_char = byte_to_utf16_offset(line_text, anchor_end_byte - line_start);

                changes.entry(uri.clone()).or_default().push(TextEdit {
                    range: Range {
                        start: Position {
                            line: line_idx as u32,
                            character: start_char,
                        },
                        end: Position {
                            line: line_idx as u32,
                            character: end_char,
                        },
                    },
                    new_text: new_anchor.to_string(),
                });
            }
        }
    }
}

/// Find the anchor text position within a link's raw source.
///
/// For inline links like `[text](#anchor)`, searches after `(#`.
/// For reference definitions resolved by pulldown-cmark, the raw source
/// includes the `[text]` portion, so we search for `#anchor` within `(...)`.
/// Falls back to finding `#anchor` after any `(` or `]: ` pattern.
fn find_fragment_in_link_source(source: &str, anchor: &str) -> Option<usize> {
    let target = format!("#{anchor}");
    let target_lower = target.to_lowercase();

    // Try inline link: find `(#anchor` within `(...)`
    if let Some(paren_pos) = source.find('(') {
        let after_paren = &source[paren_pos + 1..];
        if let Some(hash_pos) = after_paren.to_lowercase().find(&target_lower) {
            // Return position of anchor text (after #)
            return Some(paren_pos + 1 + hash_pos + 1);
        }
    }

    // Fallback: search anywhere in the source (for edge cases)
    if let Some(pos) = source.to_lowercase().find(&target_lower) {
        return Some(pos + 1); // after #
    }

    None
}

/// Collect text edits for same-file reference definitions that point to fragments.
///
/// Handles lines like `[ref]: #anchor` where the anchor needs updating.
fn collect_same_file_ref_def_edits(
    uri: &Url,
    content: &str,
    old_anchor: &str,
    new_anchor: &str,
    changes: &mut HashMap<Url, Vec<TextEdit>>,
) {
    let target = format!("#{old_anchor}");
    let target_lower = target.to_lowercase();

    for (line_idx, line) in content.lines().enumerate() {
        // Match reference definition pattern: [ref]: #anchor
        let trimmed = line.trim_start();
        if !trimmed.starts_with('[') {
            continue;
        }
        if let Some(colon_pos) = trimmed.find("]: ") {
            let def_target = trimmed[colon_pos + 3..].trim();
            // Only fragment-only definitions
            if let Some(frag) = def_target.strip_prefix('#') {
                // Strip any trailing title
                let frag = frag.split_whitespace().next().unwrap_or(frag);
                if frag.eq_ignore_ascii_case(old_anchor) {
                    // Find the position in the original line
                    if let Some(hash_pos) = line.to_lowercase().find(&target_lower) {
                        let anchor_start = hash_pos + 1;
                        let anchor_end = anchor_start + old_anchor.len();

                        let start_char = byte_to_utf16_offset(line, anchor_start);
                        let end_char = byte_to_utf16_offset(line, anchor_end);

                        changes.entry(uri.clone()).or_default().push(TextEdit {
                            range: Range {
                                start: Position {
                                    line: line_idx as u32,
                                    character: start_char,
                                },
                                end: Position {
                                    line: line_idx as u32,
                                    character: end_char,
                                },
                            },
                            new_text: new_anchor.to_string(),
                        });
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn test_detect_full_link_target_file_only() {
        let text = "See [link](guide.md) here.\n";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "");
    }

    #[test]
    fn test_detect_full_link_target_file_with_anchor() {
        let text = "See [link](guide.md#install) here.\n";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_detect_full_link_target_same_file_anchor() {
        let text = "See [below](#configuration) here.\n";
        let position = Position { line: 0, character: 15 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "");
        assert_eq!(link.anchor, "configuration");
    }

    #[test]
    fn test_detect_full_link_target_cursor_outside_link() {
        let text = "Just some text here.\n";
        let position = Position { line: 0, character: 5 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_none());
    }

    #[test]
    fn test_detect_full_link_target_cursor_at_start_of_target() {
        let text = "See [link](guide.md) here.\n";
        // Cursor right after `](`
        let position = Position { line: 0, character: 11 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_full_link_target_cursor_at_end_of_target() {
        let text = "See [link](guide.md) here.\n";
        // Cursor right before `)`
        let position = Position { line: 0, character: 19 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_full_link_target_in_code_span() {
        let text = "See `[link](guide.md)` here.\n";
        let position = Position { line: 0, character: 15 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_none(), "Should not detect links inside code spans");
    }

    #[test]
    fn test_detect_full_link_target_with_title() {
        let text = r#"See [link](guide.md "Title") here."#;
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "");
    }

    #[test]
    fn test_detect_full_link_target_with_single_quote_title() {
        let text = "See [link](guide.md 'Title') here.";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_full_link_target_with_paren_title() {
        let text = "See [link](guide.md (Title)) here.";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_full_link_target_with_title_and_anchor() {
        let text = r#"See [link](guide.md#install "Install Guide") here."#;
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_detect_full_link_target_angle_brackets() {
        let text = "See [link](<guide.md>) here.";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "");
    }

    #[test]
    fn test_detect_full_link_target_angle_brackets_with_anchor() {
        let text = "See [link](<guide.md#install>) here.";
        let position = Position { line: 0, character: 14 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_strip_link_title_double_quotes() {
        assert_eq!(strip_link_title(r#"file.md "Title""#), "file.md");
    }

    #[test]
    fn test_strip_link_title_single_quotes() {
        assert_eq!(strip_link_title("file.md 'Title'"), "file.md");
    }

    #[test]
    fn test_strip_link_title_parens() {
        assert_eq!(strip_link_title("file.md (Title)"), "file.md");
    }

    #[test]
    fn test_strip_link_title_no_title() {
        assert_eq!(strip_link_title("file.md"), "file.md");
    }

    #[test]
    fn test_strip_link_title_with_spaces_in_path() {
        // Space not followed by title delimiter should not strip
        assert_eq!(strip_link_title("my file.md"), "my file.md");
    }

    #[test]
    fn test_find_same_file_fragment_links_basic() {
        let content = "# Heading\n\nSee [below](#heading) for details.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 1);
        assert_eq!(locations[0].range.start.line, 2);
    }

    #[test]
    fn test_find_same_file_fragment_links_case_insensitive() {
        let content = "See [link](#HEADING) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 1);
    }

    #[test]
    fn test_find_same_file_fragment_links_multiple() {
        let content = "See [a](#heading) and [b](#heading) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 2);
    }

    #[test]
    fn test_find_same_file_fragment_links_no_match() {
        let content = "See [link](#other) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 0);
    }

    // =========================================================================
    // Balanced parentheses
    // =========================================================================

    #[test]
    fn test_find_balanced_close_paren_simple() {
        assert_eq!(find_balanced_close_paren("file.md)"), Some(7));
    }

    #[test]
    fn test_find_balanced_close_paren_nested() {
        // file(1).md)  — the inner `(1)` should not terminate the search
        assert_eq!(find_balanced_close_paren("file(1).md)"), Some(10));
    }

    #[test]
    fn test_find_balanced_close_paren_double_nested() {
        assert_eq!(find_balanced_close_paren("a(b(c)).md)"), Some(10));
    }

    #[test]
    fn test_find_balanced_close_paren_no_close() {
        assert_eq!(find_balanced_close_paren("file.md"), None);
    }

    #[test]
    fn test_detect_full_link_target_nested_parens() {
        let text = "See [manpage](file(1).md) here.\n";
        // Cursor on "file(1).md"
        let position = Position { line: 0, character: 18 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some(), "Should handle balanced parens in link target");
        let link = result.unwrap();
        assert_eq!(link.file_path, "file(1).md");
        assert_eq!(link.anchor, "");
    }

    #[test]
    fn test_detect_full_link_target_double_nested_parens() {
        let text = "See [x](a(b(c)).md) here.\n";
        let position = Position { line: 0, character: 12 };
        let result = detect_full_link_target(text, position);
        assert!(result.is_some(), "Should handle double-nested parens");
        let link = result.unwrap();
        assert_eq!(link.file_path, "a(b(c)).md");
    }

    // =========================================================================
    // URL vs file-path distinction
    // =========================================================================

    #[test]
    fn test_is_external_url_https() {
        assert!(is_external_url("https://example.com/page"));
    }

    #[test]
    fn test_is_external_url_http() {
        assert!(is_external_url("http://example.com/page"));
    }

    #[test]
    fn test_is_external_url_mailto() {
        assert!(is_external_url("mailto:user@example.com"));
    }

    #[test]
    fn test_is_external_url_www() {
        assert!(is_external_url("www.example.com"));
    }

    #[test]
    fn test_is_external_url_relative_path() {
        assert!(!is_external_url("guide.md"));
    }

    #[test]
    fn test_is_external_url_empty() {
        assert!(!is_external_url(""));
    }

    #[test]
    fn test_is_external_url_fragment_only() {
        assert!(!is_external_url("#heading"));
    }

    // =========================================================================
    // Code block / code span filtering in find_same_file_fragment_links
    // =========================================================================

    #[test]
    fn test_find_same_file_fragment_links_skips_code_blocks() {
        let content = "# Heading\n\n```\nSee [link](#heading) in code.\n```\n\nReal [link](#heading) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 1, "Should only find the link outside the code block");
        assert_eq!(
            locations[0].range.start.line, 6,
            "Should be on the line after the code block"
        );
    }

    #[test]
    fn test_find_same_file_fragment_links_skips_code_spans() {
        let content = "See `[link](#heading)` and [real](#heading) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 1, "Should only find the link outside the code span");
    }

    #[test]
    fn test_find_same_file_fragment_links_includes_reference_links() {
        let content = "See [text][ref] and [inline](#heading) here.\n\n[ref]: #heading\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(
            locations.len(),
            2,
            "Should find both inline and reference-style fragment links"
        );
    }

    #[test]
    fn test_find_same_file_fragment_links_utf16_position() {
        // Emoji before the link: "🎉 " is 4 bytes / 2 UTF-16 code units + 1 space
        let content = "🎉 [link](#heading) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let locations = find_same_file_fragment_links(content, &uri, "heading");
        assert_eq!(locations.len(), 1);
        // '🎉' is 2 UTF-16 code units + ' ' is 1 = character 3
        assert_eq!(
            locations[0].range.start.character, 3,
            "Character position should be in UTF-16 code units, not bytes"
        );
    }

    // =========================================================================
    // Reference-style link detection
    // =========================================================================

    #[test]
    fn test_detect_ref_definition_basic() {
        let result = detect_ref_definition("[guide]: guide.md");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "");
    }

    #[test]
    fn test_detect_ref_definition_with_anchor() {
        let result = detect_ref_definition("[guide]: guide.md#install");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_detect_ref_definition_indented() {
        let result = detect_ref_definition("   [guide]: guide.md");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_ref_definition_not_a_definition() {
        let result = detect_ref_definition("Some [text] here");
        assert!(result.is_none());
    }

    #[test]
    fn test_resolve_reference_to_target_basic() {
        let text = "See [guide] for info.\n\n[guide]: guide.md\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_resolve_reference_to_target_case_insensitive() {
        let text = "See [Guide] here.\n\n[guide]: guide.md\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_some());
    }

    #[test]
    fn test_resolve_reference_to_target_with_anchor() {
        let text = "[ref]: guide.md#install\n";
        let result = resolve_reference_to_target(text, "ref");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_resolve_reference_to_target_not_found() {
        let text = "No definitions here.\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_none());
    }

    #[test]
    fn test_resolve_reference_to_target_skips_code_block() {
        let text = "See [guide] here.\n\n```\n[guide]: wrong.md\n```\n\n[guide]: correct.md\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(link.file_path, "correct.md", "Should skip definition inside code block");
    }

    #[test]
    fn test_resolve_reference_to_target_only_in_code_block() {
        let text = "See [guide] here.\n\n```\n[guide]: guide.md\n```\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_none(), "Should not find definition inside code block");
    }

    #[test]
    fn test_resolve_reference_to_target_skips_indented_code_block() {
        let text = "See [guide] here.\n\n    [guide]: wrong.md\n\n[guide]: correct.md\n";
        let result = resolve_reference_to_target(text, "guide");
        assert!(result.is_some());
        let link = result.unwrap();
        assert_eq!(
            link.file_path, "correct.md",
            "Should skip definition inside indented code block"
        );
    }

    #[test]
    fn test_detect_ref_link_usage_full_reference() {
        // [text][ref-id]  — cursor on "text"
        let line = "See [guide text][guide] here.";
        let result = detect_ref_link_usage(line, 8);
        assert_eq!(result.as_deref(), Some("guide"));
    }

    #[test]
    fn test_detect_ref_link_usage_collapsed_reference() {
        // [text][]  — cursor on "text"
        let line = "See [guide][] here.";
        let result = detect_ref_link_usage(line, 7);
        assert_eq!(result.as_deref(), Some("guide"));
    }

    #[test]
    fn test_detect_ref_link_usage_shortcut_reference() {
        // [text]  — cursor on "text"
        let line = "See [guide] here.";
        let result = detect_ref_link_usage(line, 7);
        assert_eq!(result.as_deref(), Some("guide"));
    }

    #[test]
    fn test_detect_ref_link_usage_cursor_in_second_bracket() {
        // [text][ref-id]  — cursor on "ref-id" (second bracket pair)
        let line = "See [text][guide] here.";
        // Cursor at 'g' in "guide" (index 11)
        let result = detect_ref_link_usage(line, 11);
        assert_eq!(result.as_deref(), Some("guide"));
    }

    #[test]
    fn test_detect_ref_link_usage_cursor_in_empty_second_bracket() {
        // [text][]  — cursor in the empty second bracket
        let line = "See [guide][] here.";
        // Cursor at index 12 (between the empty [])
        let result = detect_ref_link_usage(line, 12);
        assert_eq!(result.as_deref(), Some("guide"));
    }

    #[test]
    fn test_detect_ref_link_usage_not_inline_link() {
        // Should not match `[text](url)` — that's an inline link, not a reference
        let line = "See [link](guide.md) here.";
        let result = detect_ref_link_usage(line, 7);
        assert!(result.is_none(), "Should not match inline links");
    }

    #[test]
    fn test_detect_ref_link_usage_in_code_span() {
        let line = "See `[guide]` here.";
        let result = detect_ref_link_usage(line, 8);
        assert!(result.is_none(), "Should not match inside code spans");
    }

    #[test]
    fn test_detect_ref_link_target_full_reference() {
        let text = "See [click here][guide] for info.\n\n[guide]: guide.md#install\n";
        // Cursor on "click here"
        let position = Position { line: 0, character: 8 };
        let result = detect_ref_link_target(text, position);
        assert!(result.is_some(), "Should resolve full reference link");
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_detect_ref_link_target_collapsed_reference() {
        let text = "See [guide][] for info.\n\n[guide]: guide.md\n";
        let position = Position { line: 0, character: 7 };
        let result = detect_ref_link_target(text, position);
        assert!(result.is_some(), "Should resolve collapsed reference link");
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
    }

    #[test]
    fn test_detect_ref_link_target_definition_line() {
        let text = "[guide]: guide.md#install\n";
        // Cursor on the definition line
        let position = Position { line: 0, character: 5 };
        let result = detect_ref_link_target(text, position);
        assert!(result.is_some(), "Should resolve reference definition line");
        let link = result.unwrap();
        assert_eq!(link.file_path, "guide.md");
        assert_eq!(link.anchor, "install");
    }

    #[test]
    fn test_detect_ref_link_target_external_url() {
        let text = "See [example] for info.\n\n[example]: https://example.com\n";
        let position = Position { line: 0, character: 7 };
        let result = detect_ref_link_target(text, position);
        assert!(result.is_some());
        let link = result.unwrap();
        // The target is an external URL — is_external_url should catch this at the handler level
        assert!(is_external_url(&link.file_path));
    }

    // =========================================================================
    // Heading text range helpers (for rename)
    // =========================================================================

    #[test]
    fn test_find_heading_text_start_atx() {
        assert_eq!(find_heading_text_start("# Heading"), Some(2));
        assert_eq!(find_heading_text_start("## Heading"), Some(3));
        assert_eq!(find_heading_text_start("### Heading"), Some(4));
    }

    #[test]
    fn test_find_heading_text_start_no_space() {
        // Invalid ATX heading (no space after #)
        assert_eq!(find_heading_text_start("#NoSpace"), None);
    }

    #[test]
    fn test_find_heading_text_start_not_heading() {
        assert_eq!(find_heading_text_start("Just text"), None);
        assert_eq!(find_heading_text_start(""), None);
    }

    #[test]
    fn test_find_heading_text_start_leading_whitespace() {
        assert_eq!(find_heading_text_start("  ## Heading"), Some(5));
    }

    #[test]
    fn test_find_heading_text_start_empty_heading() {
        assert_eq!(find_heading_text_start("##"), Some(2));
    }

    #[test]
    fn test_find_heading_text_end_simple() {
        let line = "## Hello World";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "Hello World");
    }

    #[test]
    fn test_find_heading_text_end_with_custom_anchor() {
        let line = "## Guide {#install}";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "Guide");
    }

    #[test]
    fn test_find_heading_text_end_with_closing_atx() {
        let line = "## Hello ##";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "Hello");
    }

    #[test]
    fn test_find_heading_text_end_with_trailing_spaces() {
        let line = "## Hello   ";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "Hello");
    }

    #[test]
    fn test_find_heading_text_end_unicode() {
        let line = "## 日本語";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "日本語");
    }

    #[test]
    fn test_find_heading_text_end_unicode_with_closing() {
        let line = "## 日本語 ##";
        let start = find_heading_text_start(line).unwrap();
        let end = find_heading_text_end(line, start);
        assert_eq!(&line[start..end], "日本語");
    }

    // =========================================================================
    // Anchor edit in link helpers (for rename)
    // =========================================================================

    #[test]
    fn test_find_all_anchor_edits_in_link_inline() {
        let line = "See [link](guide.md#getting-started) here.";
        let edits = find_all_anchor_edits_in_link(line, 0, "getting-started", "quick-start");
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "quick-start");
        let start = edits[0].range.start.character as usize;
        let end = edits[0].range.end.character as usize;
        assert_eq!(&line[start..end], "getting-started");
    }

    #[test]
    fn test_find_all_anchor_edits_in_link_ignores_display_text() {
        // The `#getting-started` appears in the display text too
        let line = "See [#getting-started info](guide.md#getting-started) here.";
        let edits = find_all_anchor_edits_in_link(line, 0, "getting-started", "quick-start");
        assert_eq!(edits.len(), 1);
        // Should match the URL portion, not the display text
        let start = edits[0].range.start.character as usize;
        let end = edits[0].range.end.character as usize;
        assert_eq!(&line[start..end], "getting-started");
        assert!(start > 30, "Should match in the URL, not the display text");
    }

    #[test]
    fn test_find_all_anchor_edits_in_link_ref_definition() {
        let line = "[guide]: guide.md#getting-started";
        let edits = find_all_anchor_edits_in_link(line, 5, "getting-started", "quick-start");
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "quick-start");
        assert_eq!(edits[0].range.start.line, 5);
    }

    #[test]
    fn test_find_all_anchor_edits_in_link_no_match() {
        let line = "See [link](guide.md#other-section) here.";
        let edits = find_all_anchor_edits_in_link(line, 0, "getting-started", "quick-start");
        assert!(edits.is_empty());
    }

    #[test]
    fn test_find_all_anchor_edits_in_link_multiple_on_same_line() {
        let line = "See [a](guide.md#heading) and [b](guide.md#heading) here.";
        let edits = find_all_anchor_edits_in_link(line, 0, "heading", "new-heading");
        assert_eq!(edits.len(), 2, "Should find both anchors on the same line");
        // Edits should target different positions
        assert_ne!(edits[0].range.start.character, edits[1].range.start.character,);
    }

    // =========================================================================
    // Same-file anchor edits (for rename)
    // =========================================================================

    #[test]
    fn test_collect_same_file_anchor_edits_inline() {
        let content = "# Getting Started\n\nSee [below](#getting-started) for details.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_anchor_edits(&uri, content, "getting-started", "quick-start", &mut changes);

        let edits = changes.get(&uri).expect("Should have edits for the URI");
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "quick-start");
    }

    #[test]
    fn test_collect_same_file_anchor_edits_multiple() {
        let content = "# Heading\n\n[a](#heading) and [b](#heading).\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_anchor_edits(&uri, content, "heading", "new-heading", &mut changes);

        let edits = changes.get(&uri).expect("Should have edits");
        assert_eq!(edits.len(), 2);
    }

    #[test]
    fn test_collect_same_file_anchor_edits_no_match() {
        let content = "# Heading\n\n[a](#other) here.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_anchor_edits(&uri, content, "heading", "new-heading", &mut changes);

        assert!(changes.is_empty());
    }

    // =========================================================================
    // Same-file reference definition edits (for rename)
    // =========================================================================

    #[test]
    fn test_collect_same_file_ref_def_edits_basic() {
        let content = "# Heading\n\n[ref]: #heading\n\nSee [ref] for info.\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_ref_def_edits(&uri, content, "heading", "new-heading", &mut changes);

        let edits = changes.get(&uri).expect("Should have edits");
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "new-heading");
    }

    #[test]
    fn test_collect_same_file_ref_def_edits_no_match() {
        let content = "[ref]: #other\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_ref_def_edits(&uri, content, "heading", "new-heading", &mut changes);

        assert!(changes.is_empty());
    }

    #[test]
    fn test_collect_same_file_ref_def_edits_not_fragment_only() {
        // Reference definitions pointing to files shouldn't be caught here
        let content = "[ref]: guide.md#heading\n";
        let uri = Url::parse("file:///test.md").unwrap();
        let mut changes: HashMap<Url, Vec<TextEdit>> = HashMap::new();

        collect_same_file_ref_def_edits(&uri, content, "heading", "new-heading", &mut changes);

        // This targets same-file fragment-only defs, so file.md#heading is not matched
        assert!(changes.is_empty());
    }

    // =========================================================================
    // find_fragment_in_link_source (for rename)
    // =========================================================================

    #[test]
    fn test_find_fragment_in_link_source_inline() {
        let source = "[text](#getting-started)";
        let pos = find_fragment_in_link_source(source, "getting-started");
        assert!(pos.is_some());
        let pos = pos.unwrap();
        assert_eq!(&source[pos..pos + "getting-started".len()], "getting-started");
    }

    #[test]
    fn test_find_fragment_in_link_source_with_hash_in_text() {
        // Display text contains #, but anchor is in URL
        let source = "[C# Guide](#c-guide)";
        let pos = find_fragment_in_link_source(source, "c-guide");
        assert!(pos.is_some());
        let pos = pos.unwrap();
        assert_eq!(&source[pos..pos + "c-guide".len()], "c-guide");
    }
}