rumdl 0.3.3

A fast Markdown linter and formatter written in Rust
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
use crate::config::MarkdownFlavor;
use crate::utils::code_block_utils::CodeBlockUtils;
use crate::utils::parser_options::rumdl_parser_options_for;
#[cfg(test)]
use pulldown_cmark::BrokenLink;
use pulldown_cmark::{Event, LinkType, Tag, TagEnd};
use regex::Regex;
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::LazyLock;

use super::document_parser::ParserDefinition;
use super::types::*;

// Comprehensive link pattern that captures both inline and reference links
// Use (?s) flag to make . match newlines.
//
// Title alternatives include all three CommonMark §6.7 delimiter forms:
// `"..."` (group 4), `'...'` (group 5), and `(...)` (group 6). The paren form
// is required so MkDocs admonition fallbacks (which only fire when
// pulldown-cmark misses the link) don't silently drop a `[t](url (title))`
// title — that would let MD054 auto-fix rewrite the link without it,
// changing semantics.
static LINK_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(?sx)
        \[((?:[^\[\]\\]|\\.)*)\]          # Link text in group 1 (optimized - no nested brackets to prevent catastrophic backtracking)
        (?:
            \((?:<([^<>\n]*)>|([^\s)"']*))(?:\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|\(((?:[^()\\]|\\.)*)\)))?\)  # URL in group 2 (angle) or 3 (bare), title in 4 (dq) / 5 (sq) / 6 (paren)
            |
            \[([^\]]*)\]      # Reference ID in group 7
        )"#
    ).unwrap()
});

// Image pattern (similar to links but with ! prefix)
// Use (?s) flag to make . match newlines.
//
// Mirrors LINK_PATTERN's title-form alternatives so the MkDocs fallback
// recognizes paren-form titles in `![alt](url (title))` images.
static IMAGE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(?sx)
        !\[((?:[^\[\]\\]|\\.)*)\]         # Alt text in group 1 (optimized - no nested brackets to prevent catastrophic backtracking)
        (?:
            \((?:<([^<>\n]*)>|([^\s)"']*))(?:\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|\(((?:[^()\\]|\\.)*)\)))?\)  # URL in group 2 (angle) or 3 (bare), title in 4 (dq) / 5 (sq) / 6 (paren)
            |
            \[([^\]]*)\]      # Reference ID in group 7
        )"#
    ).unwrap()
});

/// The link and image patterns rumdl falls back to when pulldown-cmark does not
/// report a construct. Exposed so a rule that has to scan text the parser
/// deliberately skipped (MD091, over HTML blocks) recognizes exactly what rumdl
/// recognizes elsewhere, rather than hand-rolling a second grammar that drifts.
pub(crate) fn link_pattern() -> &'static Regex {
    &LINK_PATTERN
}

/// See [`link_pattern`].
pub(crate) fn image_pattern() -> &'static Regex {
    &IMAGE_PATTERN
}

/// Pulldown-cmark's offset_iter range for `Collapsed` links and images covers
/// only the `[text]` portion, omitting the trailing `[]` that distinguishes
/// the collapsed form from a shortcut. Extend the end offset to include those
/// two bytes so consumers see the full syntactic span (notably MD054's
/// auto-fix, which replaces the entire link span when converting styles).
pub(super) fn extend_collapsed_byte_end(content: &str, link_type: LinkType, byte_end: usize) -> usize {
    if !matches!(link_type, LinkType::Collapsed) {
        return byte_end;
    }
    let bytes = content.as_bytes();
    if bytes.get(byte_end) == Some(&b'[') && bytes.get(byte_end + 1) == Some(&b']') {
        byte_end + 2
    } else {
        byte_end
    }
}

// Reference definition pattern
//
// Mirrors the CommonMark §4.7 grammar closely enough for downstream consumers
// (MD053, MD057, the MD054 round-trip pass) to see every valid ref def:
//
// - **Label** (group 1) ends at the first `]` that is *not* backslash-escaped,
//   so `\]` stays inside the label (`[a\[\]]: url` is one definition). A scan
//   that stops at any `]` fails the whole anchored match and drops the
//   definition, which makes MD034 lint the destination as a bare URL and hides
//   it from MD053. The label is captured raw: CommonMark normalization
//   case-folds and collapses whitespace but does not unescape, and
//   pulldown-cmark reports the raw id, so both sides must agree to match.
//
// - **Destination** has two §6.6 forms: a bare sequence containing no spaces
//   (group 3), or an angle-bracketed sequence that may contain spaces but no
//   line endings or unescaped `<`/`>` (group 2). Without the angle form,
//   destinations like `<./has space.md>` (which `format_url_destination`
//   emits whenever the URL would otherwise be unparseable inline) silently
//   drop out of `ctx.reference_defs`.
//
// - **Title** has three §4.7 delimiter forms — `"..."` (group 4), `'...'`
//   (group 5), and `(...)` (group 6). All three branches permit backslash
//   escapes so titles like `"he said \"hi\""`, `'it\'s fine'`, or
//   `(title \(x\))` parse — per spec, an unescaped delimiter would
//   otherwise terminate the title prematurely.
//
// Round-trip safety: the angle-bracket destination and the double/single
// quoted title forms accept `\<delim>` (and `\\`) so that values emitted
// by `format_url_destination` / `format_title` (e.g. `<a\<b\>c>` or
// `"he said \"hi\""`) re-parse on the next lint pass instead of dropping
// out of `ctx.reference_defs` and breaking MD053/MD057 follow-ups.
static REF_DEF_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(?m)^[ ]{0,3}\[((?:[^\]\\]|\\.)+)\]:\s*(?:<((?:[^<>\n\\]|\\.)*)>|([^\s<][^\s]*))(?:\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|\(((?:[^()\\]|\\.)*)\)))?$"#,
    )
    .unwrap()
});

// CommonMark §4.7 allows a reference definition's title to appear on the line
// immediately after the destination. This matches a line that is *only* such a
// title (double-quoted, single-quoted, or parenthesised), with the same escape
// handling as `REF_DEF_PATTERN`. The capture groups mirror the title groups
// (1 = "...", 2 = '...', 3 = (...)) so the same unescape path applies.
static REF_DEF_TITLE_CONTINUATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"^\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|\(((?:[^()\\]|\\.)*)\))\s*$"#).unwrap()
});

/// How many of the lines a paragraph opens with are link reference definitions.
/// Those definitions are not the paragraph's text (CommonMark 4.7), so its text
/// starts below them. A definition may carry its destination, and the title
/// after that, on the lines below its label, so the lines are read together the
/// way the parser reads them: the text starts where its first block starts, and
/// a paragraph of definitions alone has no text at all. A footnote definition
/// is a block of its own rather than a reference definition, and ends the count.
pub(super) fn leading_reference_definition_lines(lines: &[&str]) -> usize {
    if !lines.first().is_some_and(|line| line.trim_start().starts_with('[')) {
        return 0;
    }
    let text = lines.join("\n");
    let first_block = pulldown_cmark::Parser::new_ext(&text, rumdl_parser_options_for(&text))
        .into_offset_iter()
        .next()
        .map_or(text.len(), |(_, range)| range.start);
    text[..first_block].matches('\n').count() + usize::from(first_block == text.len())
}

/// Link facts from the shared source analysis, before context filtering.
/// Regex fallback and code_span filtering happen in the finalize phase.
pub(super) struct ParsedLinks<'a> {
    pub link_byte_ranges: Vec<(usize, usize)>,
    pub links: Vec<ParsedLink<'a>>,
    pub images: Vec<ParsedImage<'a>>,
    pub broken_links: Vec<BrokenLinkInfo>,
    pub footnote_refs: Vec<FootnoteRef>,
    pub link_found_positions: HashSet<usize>,
    pub image_found_positions: HashSet<usize>,
}

/// Independent parser path used to compare the shared parse in tests.
#[cfg(test)]
pub(super) fn parse_links_images_pulldown<'a>(
    content: &'a str,
    lines: &[LineInfo],
    code_blocks: &[(usize, usize)],
    flavor: MarkdownFlavor,
    html_comment_ranges: &[crate::utils::skip_context::ByteRange],
) -> ParsedLinks<'a> {
    let mut broken_links = Vec::new();
    let options = rumdl_parser_options_for(content);

    let parser = pulldown_cmark::Parser::new_with_broken_link_callback(
        content,
        options,
        Some(|link: BrokenLink<'_>| {
            let span_end = extend_collapsed_byte_end(content, link.link_type, link.span.end);
            broken_links.push(BrokenLinkInfo {
                reference: link.reference.to_string(),
                span: link.span.start..span_end,
                link_type: link.link_type,
            });
            None
        }),
    )
    .into_offset_iter();

    let mut result = collect_links_images(
        content,
        lines,
        code_blocks,
        flavor,
        html_comment_ranges,
        parser,
        Vec::new(),
    );
    result.broken_links = broken_links;
    result
}

/// Read link facts from the shared document parse. Line-dependent filtering is
/// deferred until the context has classified containers and HTML comments.
pub(super) fn collect_links_images<'a>(
    content: &'a str,
    lines: &[LineInfo],
    code_blocks: &[(usize, usize)],
    flavor: MarkdownFlavor,
    html_comment_ranges: &[crate::utils::skip_context::ByteRange],
    events: impl Iterator<Item = (Event<'a>, std::ops::Range<usize>)>,
    broken_links: Vec<BrokenLinkInfo>,
) -> ParsedLinks<'a> {
    use crate::utils::skip_context::{is_in_html_comment_ranges, is_mkdocs_snippet_line};

    let mut positions = super::source_positions::SourcePositions::new(content, lines);

    let mut link_byte_ranges = Vec::new();
    let mut links = Vec::with_capacity(content.len() / 500);
    let mut images = Vec::with_capacity(content.len() / 1000);
    let mut footnote_refs = Vec::new();
    let mut link_found_positions = HashSet::new();
    let mut image_found_positions = HashSet::new();

    type StackEntry<'b> = (
        usize,
        pulldown_cmark::CowStr<'b>,
        LinkType,
        pulldown_cmark::CowStr<'b>,
        pulldown_cmark::CowStr<'b>,
    );

    /// A link the parser has opened but not yet closed.
    ///
    /// `label_end` grows to the furthest byte any event inside the label
    /// reaches, which is where the inline parse puts the label's closing
    /// bracket.
    struct OpenLink<'b> {
        start: usize,
        label_end: usize,
        url: pulldown_cmark::CowStr<'b>,
        link_type: LinkType,
        id: pulldown_cmark::CowStr<'b>,
        title: pulldown_cmark::CowStr<'b>,
    }

    let mut link_stack: Vec<OpenLink<'a>> = Vec::new();
    let mut image_stack: Vec<StackEntry<'a>> = Vec::new();
    let mut link_text_chunks: Vec<(String, usize, usize)> = Vec::new();

    for (event, range) in events {
        // The label of an open link ends at the last byte the events inside it
        // reach, nested image events included. The link's own Start and End
        // span the whole link, destination and title included, so they say
        // nothing about where the label closes. A collapsed image's range
        // stops short of its `[]`, which is part of the label, so its span is
        // extended the way the image's own record is. The Start carries the
        // link type and shares the End's range, so the Start is where the
        // extension is applied.
        if let Some(open) = link_stack.last_mut()
            && !matches!(&event, Event::Start(Tag::Link { .. }) | Event::End(TagEnd::Link))
        {
            let event_end = match &event {
                Event::Start(Tag::Image { link_type, .. }) => extend_collapsed_byte_end(content, *link_type, range.end),
                _ => range.end,
            };
            open.label_end = open.label_end.max(event_end);
        }

        match event {
            Event::Start(Tag::Link {
                link_type,
                dest_url,
                title,
                id,
            }) => {
                link_stack.push(OpenLink {
                    start: range.start,
                    label_end: range.start + 1,
                    url: dest_url,
                    link_type,
                    id,
                    title,
                });
                link_text_chunks.clear();
            }
            Event::Start(Tag::Image {
                link_type,
                dest_url,
                title,
                id,
            }) => {
                image_stack.push((range.start, dest_url, link_type, id, title));
            }
            // Only wikilinks read these chunks; every other link and image
            // takes its text from the source between its own brackets.
            Event::Text(text)
                if link_stack
                    .last()
                    .is_some_and(|link| matches!(link.link_type, LinkType::WikiLink { .. })) =>
            {
                link_text_chunks.push((text.to_string(), range.start, range.end));
            }
            Event::Code(code)
                if link_stack
                    .last()
                    .is_some_and(|link| matches!(link.link_type, LinkType::WikiLink { .. })) =>
            {
                let code_text = format!("`{code}`");
                link_text_chunks.push((code_text, range.start, range.end));
            }
            Event::End(TagEnd::Link) => {
                if let Some(OpenLink {
                    start: start_pos,
                    label_end,
                    url,
                    link_type,
                    id: ref_id,
                    title,
                }) = link_stack.pop()
                {
                    let span_end = extend_collapsed_byte_end(content, link_type, range.end);
                    // Track link byte range for heading detection
                    link_byte_ranges.push((start_pos, span_end));

                    if is_in_html_comment_ranges(html_comment_ranges, start_pos) {
                        link_text_chunks.clear();
                        continue;
                    }

                    let (line_idx, line_num, col_start) = positions.position(start_pos);

                    if is_mkdocs_snippet_line(lines[line_idx].content(content), flavor) {
                        link_text_chunks.clear();
                        continue;
                    }

                    let (_, end_line_num, col_end) = positions.position(span_end);

                    let is_reference = matches!(
                        link_type,
                        LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut
                    );

                    // The text is the source between the brackets, so escaping,
                    // code spans and inline HTML are preserved as written. The
                    // closing bracket comes from the inline parse rather than
                    // from a second scan of the bytes, which is what keeps a
                    // label such as `<i title="[">x</i>` or a code span holding
                    // `](` from being read as ending somewhere else.
                    let link_text = if matches!(link_type, LinkType::WikiLink { .. }) {
                        if !link_text_chunks.is_empty() {
                            let text: String = link_text_chunks.iter().map(|(t, _, _)| t.as_str()).collect();
                            Cow::Owned(text)
                        } else {
                            Cow::Owned(url.to_string())
                        }
                    } else if matches!(link_type, LinkType::Autolink | LinkType::Email) {
                        // An autolink is written between angle brackets and has
                        // no label to read.
                        Cow::Borrowed("")
                    } else {
                        // Events cover the label's inline content, so they stop
                        // at the last of it. What follows is filler the parse
                        // carries no event for: whitespace ending the label, or
                        // the blockquote marker on a continuation line. Filler
                        // holds no inline content, so the first bracket from
                        // there is the label's own.
                        let close = label_end + content[label_end..].find(']').unwrap_or(0);
                        debug_assert!(
                            close < span_end && content.as_bytes().get(close) == Some(&b']'),
                            "link label at {start_pos} does not close on a bracket inside its own span: {:?}",
                            &content[start_pos..span_end.min(content.len())]
                        );
                        Cow::Borrowed(&content[start_pos + 1..close])
                    };

                    let reference_id = if is_reference && !ref_id.is_empty() {
                        Some(Cow::Owned(ref_id.to_lowercase()))
                    } else if is_reference {
                        Some(Cow::Owned(link_text.to_lowercase()))
                    } else {
                        None
                    };

                    link_found_positions.insert(start_pos);

                    // Pulldown-cmark exposes the same empty `CowStr` for both
                    // `[t](url)` (no title) and `[t](url "")` (explicit empty
                    // title), so we must rescan the source span when the
                    // parsed title is empty. Reference-style links carry their
                    // title in the *definition*, not at the use site, so the
                    // span scan only applies to inline links.
                    let title_field = if !title.is_empty() {
                        Some(source_cow(title))
                    } else if matches!(link_type, LinkType::Inline)
                        && has_explicit_empty_inline_title(&content[start_pos..range.end.min(content.len())])
                    {
                        Some(Cow::Borrowed(""))
                    } else {
                        None
                    };

                    links.push(ParsedLink {
                        line: line_num,
                        end_line: end_line_num,
                        start_col: col_start,
                        end_col: col_end,
                        byte_offset: start_pos,
                        byte_end: span_end,
                        text: link_text,
                        url: source_cow(url),
                        title: title_field,
                        is_reference,
                        reference_id,
                        link_type,
                    });

                    link_text_chunks.clear();
                }
            }
            Event::End(TagEnd::Image) => {
                if let Some((start_pos, url, link_type, ref_id, title)) = image_stack.pop() {
                    let span_end = extend_collapsed_byte_end(content, link_type, range.end);

                    if CodeBlockUtils::is_in_code_block(code_blocks, start_pos) {
                        continue;
                    }

                    // Skip code_span check here; deferred to finalize phase
                    // where code_spans are available.

                    if is_in_html_comment_ranges(html_comment_ranges, start_pos) {
                        continue;
                    }

                    let (_, line_num, col_start) = positions.position(start_pos);
                    let (_, end_line_num, col_end) = positions.position(span_end);

                    let is_reference = matches!(
                        link_type,
                        LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut
                    );

                    let alt_text = if matches!(link_type, LinkType::WikiLink { .. }) {
                        // An embed has no alt-text slot. `![[note]]` transcludes
                        // the target's content, and the pipe in `![[img.png|100]]`
                        // sets the rendered dimensions, not a description.
                        Cow::Borrowed("")
                    } else if start_pos < content.len() {
                        let image_bytes = &content.as_bytes()[start_pos..range.end.min(content.len())];

                        let mut close_pos = None;
                        let mut depth = 0;

                        if image_bytes.len() > 2 {
                            for (i, &byte) in image_bytes.iter().enumerate().skip(2) {
                                let mut backslash_count = 0;
                                let mut j = i;
                                while j > 0 && image_bytes[j - 1] == b'\\' {
                                    backslash_count += 1;
                                    j -= 1;
                                }
                                let is_escaped = backslash_count % 2 != 0;

                                if !is_escaped {
                                    if byte == b'[' {
                                        depth += 1;
                                    } else if byte == b']' {
                                        if depth == 0 {
                                            close_pos = Some(i);
                                            break;
                                        } else {
                                            depth -= 1;
                                        }
                                    }
                                }
                            }
                        }

                        if let Some(pos) = close_pos {
                            Cow::Borrowed(std::str::from_utf8(&image_bytes[2..pos]).unwrap_or(""))
                        } else {
                            Cow::Borrowed("")
                        }
                    } else {
                        Cow::Borrowed("")
                    };

                    let url = source_cow(url);

                    let reference_id = if is_reference && !ref_id.is_empty() {
                        Some(Cow::Owned(ref_id.to_lowercase()))
                    } else if is_reference {
                        Some(Cow::Owned(alt_text.to_lowercase()))
                    } else {
                        None
                    };

                    image_found_positions.insert(start_pos);

                    // Same explicit-empty-title disambiguation as the link
                    // path above: `![alt](url "")` must round-trip with its
                    // delimiters intact, so we rescan the span when the
                    // pulldown-cmark title comes back empty.
                    let title_field = if !title.is_empty() {
                        Some(source_cow(title))
                    } else if matches!(link_type, LinkType::Inline)
                        && has_explicit_empty_inline_title(&content[start_pos..range.end.min(content.len())])
                    {
                        Some(Cow::Borrowed(""))
                    } else {
                        None
                    };

                    images.push(ParsedImage {
                        line: line_num,
                        end_line: end_line_num,
                        start_col: col_start,
                        end_col: col_end,
                        byte_offset: start_pos,
                        byte_end: span_end,
                        alt_text,
                        url,
                        title: title_field,
                        is_reference,
                        reference_id,
                        link_type,
                    });
                }
            }
            Event::FootnoteReference(footnote_id) => {
                if is_in_html_comment_ranges(html_comment_ranges, range.start) {
                    continue;
                }

                let line_num = super::source_positions::line_index(lines, range.start) + 1;
                footnote_refs.push(FootnoteRef {
                    id: footnote_id.to_string(),
                    line: line_num,
                    byte_offset: range.start,
                });
            }
            _ => {}
        }
    }

    ParsedLinks {
        link_byte_ranges,
        links,
        images,
        broken_links,
        footnote_refs,
        link_found_positions,
        image_found_positions,
    }
}

/// Retain borrowed source slices and move decoded strings out of the backend.
fn source_cow(value: pulldown_cmark::CowStr<'_>) -> Cow<'_, str> {
    match value {
        pulldown_cmark::CowStr::Borrowed(value) => Cow::Borrowed(value),
        pulldown_cmark::CowStr::Boxed(value) => Cow::Owned(value.into()),
        pulldown_cmark::CowStr::Inlined(value) => Cow::Owned(value.to_string()),
    }
}

/// True when a regex-fallback match sits in raw HTML, where CommonMark parses no
/// markdown and the construct renders as literal text.
///
/// MkDocs containers are the exception: an admonition body, a content tab and a
/// `markdown="1"` block all hold real markdown, and the last of those is marked
/// `in_html_block` as well.
fn is_literal_html_context(line_info: &LineInfo) -> bool {
    line_info.in_html_block && !line_info.in_mkdocs_container()
}

/// Contexts where a link-looking string must not enter the link index.
pub(super) struct LinkExclusions<'a> {
    pub code_blocks: &'a [(usize, usize)],
    pub code_spans: &'a [(usize, usize)],
    pub html_comment_ranges: &'a [crate::utils::skip_context::ByteRange],
    pub mdx: Option<&'a super::mdx::MdxContext>,
}

/// Links, images and footnote references after context filtering.
///
/// `links` and `images` hold only constructs a CommonMark renderer turns into a
/// link or image. A reference whose label has no definition renders as literal
/// text, so it is kept apart in `unresolved_links` and `unresolved_images` for
/// the few readers that need the candidates (the undefined-reference rule and
/// the line-wrapping and fix-safety guards).
pub(super) struct FinalizedLinks<'a> {
    pub links: Vec<ParsedLink<'a>>,
    pub images: Vec<ParsedImage<'a>>,
    pub unresolved_links: Vec<ParsedLink<'a>>,
    pub unresolved_images: Vec<ParsedImage<'a>>,
    pub broken_links: Vec<BrokenLinkInfo>,
    pub footnote_refs: Vec<FootnoteRef>,
}

/// Canonical form of a reference label: the stripped text with every whitespace
/// run collapsed to one space (CommonMark 4.7). Case folding is left to the
/// consumer, which compares with a Unicode case fold.
fn collapse_label(label: &str) -> String {
    label.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Offset of the label's opening bracket in the source of a full reference
/// (`[text][label]`, with or without a leading `!`): the last `[` that is not
/// backslash-escaped, since a label cannot contain an unescaped bracket.
pub(crate) fn reference_label_start(source: &str) -> Option<usize> {
    let mut open = None;
    let mut chars = source.char_indices();
    while let Some((i, c)) = chars.next() {
        match c {
            '\\' => {
                chars.next();
            }
            '[' => open = Some(i),
            _ => {}
        }
    }
    open
}

pub(super) fn fold_label(label: &str) -> String {
    unicase::UniCase::new(collapse_label(label)).to_folded_case()
}

/// Decides whether a reference label has a definition, the one test that
/// separates a rendered reference link from literal bracket text.
///
/// The answer never depends on the destination: `[r]: <>` defines `r` with an
/// empty URL and its references are links.
struct ReferenceResolver<'c> {
    content: &'c str,
    lines: &'c [LineInfo],
    html_comment_ranges: &'c [crate::utils::skip_context::ByteRange],
    mdx: Option<&'c super::mdx::MdxContext>,
    flavor: MarkdownFlavor,
    /// Folded heading texts, read only for the Pandoc flavors, where a heading
    /// is an implicit definition of the reference that carries its text.
    heading_labels: std::cell::OnceCell<HashSet<String>>,
    /// The parser's own definitions, built on first use. Construction runs the
    /// parser's first pass, which collects every definition, so the lookup
    /// applies its label normalisation and Unicode case fold and sees
    /// multi-line definitions while ignoring `[r]: /x` in code and raw HTML.
    parser: std::cell::OnceCell<pulldown_cmark::Parser<'c>>,
    /// Folded labels defined where the parser cannot see them: inside a
    /// `markdown="1"` element or a MkDocs container (and, for MDX, anywhere the
    /// MDX reader finds a definition).
    container_defs: std::cell::OnceCell<HashSet<String>>,
}

impl<'c> ReferenceResolver<'c> {
    fn new(
        content: &'c str,
        lines: &'c [LineInfo],
        html_comment_ranges: &'c [crate::utils::skip_context::ByteRange],
        mdx: Option<&'c super::mdx::MdxContext>,
        flavor: MarkdownFlavor,
    ) -> Self {
        Self {
            content,
            lines,
            html_comment_ranges,
            mdx,
            flavor,
            heading_labels: std::cell::OnceCell::new(),
            parser: std::cell::OnceCell::new(),
            container_defs: std::cell::OnceCell::new(),
        }
    }

    fn container_defs(&self) -> &HashSet<String> {
        self.container_defs.get_or_init(|| {
            if let Some(mdx) = self.mdx {
                return mdx
                    .reference_defs(self.content)
                    .iter()
                    .map(|def| fold_label(&def.id))
                    .collect();
            }
            // A MkDocs container indents its body, and the markdown renderer strips
            // that indent before reading the definitions. Reading the container
            // lines with their indent removed through the parser gives the same
            // normalisation, titles and continuation lines as top-level text.
            //
            // Markdown renderers for these containers read a definition anywhere,
            // even straight after a paragraph line, which the CommonMark parser
            // does not, so single-line definitions are also matched line by line.
            let mut body = String::new();
            let mut defs = HashSet::new();
            for line in self.lines.iter().filter(|line| {
                line.in_mkdocs_container()
                    && !line.in_code_block
                    && !crate::utils::skip_context::is_in_html_comment_ranges(
                        self.html_comment_ranges,
                        line.byte_offset,
                    )
            }) {
                let text = line.content(self.content).trim();
                if let Some(id) = REF_DEF_PATTERN
                    .captures(text)
                    .and_then(|cap| cap.get(1))
                    .map(|m| m.as_str())
                    .filter(|id| !id.starts_with('^'))
                {
                    defs.insert(fold_label(id));
                }
                body.push_str(text);
                body.push('\n');
            }
            if !body.is_empty() {
                let parser = pulldown_cmark::Parser::new_ext(&body, rumdl_parser_options_for(&body));
                defs.extend(
                    parser
                        .reference_definitions()
                        .iter()
                        .map(|(label, _)| fold_label(label)),
                );
            }
            defs
        })
    }

    /// `parser_reported_missing` is true for a label the parser's resolution
    /// callback already rejected, which makes the parser lookup redundant.
    fn is_defined(&self, label: &str, parser_reported_missing: bool) -> bool {
        if self.container_defs().contains(&fold_label(label)) {
            return true;
        }
        if self.flavor.is_pandoc_compatible()
            && self
                .heading_labels
                .get_or_init(|| {
                    self.lines
                        .iter()
                        .filter_map(|line| line.heading.as_ref())
                        .map(|heading| fold_label(&heading.text))
                        .collect()
                })
                .contains(&fold_label(label))
        {
            return true;
        }
        if parser_reported_missing || self.mdx.is_some() {
            return false;
        }
        let parser = self
            .parser
            .get_or_init(|| pulldown_cmark::Parser::new_ext(self.content, rumdl_parser_options_for(self.content)));
        parser.reference_definitions().get(&collapse_label(label)).is_some()
    }
}

/// Phase B: Filter images by code_spans, run regex fallbacks, and sort results.
/// Requires code_spans which are computed after heading detection.
pub(super) fn finalize_links_and_images<'a>(
    content: &'a str,
    lines: &[LineInfo],
    flavor: MarkdownFlavor,
    exclusions: &LinkExclusions<'_>,
    mut result: ParsedLinks<'a>,
) -> FinalizedLinks<'a> {
    use crate::utils::skip_context::{is_in_html_comment_ranges, is_mkdocs_snippet_line};

    let mut positions = super::source_positions::SourcePositions::new(content, lines);

    let LinkExclusions {
        code_blocks,
        code_spans,
        html_comment_ranges,
        mdx,
    } = *exclusions;

    let resolver = ReferenceResolver::new(content, lines, html_comment_ranges, mdx, flavor);
    let mut unresolved_links: Vec<ParsedLink<'a>> = Vec::new();
    let mut unresolved_images: Vec<ParsedImage<'a>> = Vec::new();

    // Filter out images that fall inside code spans (deferred from Phase A)
    result
        .images
        .retain(|img| !super::LintContext::binary_search_ranges(code_spans, img.byte_offset));

    // Convert broken links to ParsedLink and add them to result.links
    for broken in &result.broken_links {
        let start_pos = broken.span.start;
        let span_end = broken.span.end;

        if is_in_html_comment_ranges(html_comment_ranges, start_pos) {
            continue;
        }

        let (line_idx, line_num, col_start) = positions.position(start_pos);

        if is_mkdocs_snippet_line(lines[line_idx].content(content), flavor) {
            continue;
        }

        let (_, end_line_num, col_end) = positions.position(span_end);

        let raw_span = &content[broken.span.clone()];
        let is_image = raw_span.starts_with('!');
        let bracketed = if is_image { &raw_span[1..] } else { raw_span };
        let link_text = if bracketed.starts_with('[') {
            let mut depth = 0;
            let mut close_pos = None;
            for (i, byte) in bracketed.bytes().enumerate().skip(1) {
                if byte == b'[' {
                    depth += 1;
                } else if byte == b']' {
                    if depth == 0 {
                        close_pos = Some(i);
                        break;
                    } else {
                        depth -= 1;
                    }
                }
            }
            if let Some(pos) = close_pos {
                &bracketed[1..pos]
            } else {
                ""
            }
        } else {
            ""
        };

        let defined = resolver.is_defined(&broken.reference, true);
        let is_reference = true;
        let reference_id = Some(Cow::Owned(broken.reference.to_lowercase()));

        if is_image {
            (if defined {
                &mut result.images
            } else {
                &mut unresolved_images
            })
            .push(ParsedImage {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: start_pos,
                byte_end: span_end,
                alt_text: Cow::Owned(link_text.to_string()),
                url: Cow::Borrowed(""),
                title: None,
                is_reference,
                reference_id,
                link_type: broken.link_type,
            });
            result.image_found_positions.insert(start_pos);
        } else {
            (if defined {
                &mut result.links
            } else {
                &mut unresolved_links
            })
            .push(ParsedLink {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: start_pos,
                byte_end: span_end,
                text: Cow::Owned(link_text.to_string()),
                url: Cow::Borrowed(""),
                title: None,
                is_reference,
                reference_id,
                link_type: broken.link_type,
            });
            result.link_found_positions.insert(start_pos);
        }
    }

    // Regex fallback for links: find undefined references missed by pulldown-cmark

    let needs_links = memchr::memchr_iter(b'[', content.as_bytes()).any(|start| {
        !result.link_found_positions.contains(&start)
            && (start == 0 || !matches!(content.as_bytes()[start - 1], b'\\' | b'!'))
    });
    // Every regex match starts at '['. If every possible start is already
    // handled by the parser or rejected by the native prefix checks, the
    // fallback cannot add a link. Keep all other cases on the native regex.

    let matches = needs_links
        .then(|| LINK_PATTERN.find_iter(content))
        .into_iter()
        .flatten();

    for full_match in matches {
        let match_start = full_match.start();
        let match_end = full_match.end();

        if mdx.is_some_and(|mdx| !mdx.contains_text(match_start, match_end)) {
            continue;
        }

        if result.link_found_positions.contains(&match_start) {
            continue;
        }

        if match_start > 0 && content.as_bytes().get(match_start - 1) == Some(&b'\\') {
            continue;
        }

        if match_start > 0 && content.as_bytes().get(match_start - 1) == Some(&b'!') {
            continue;
        }

        if CodeBlockUtils::is_in_code_block(code_blocks, match_start) {
            continue;
        }

        if super::LintContext::binary_search_ranges(code_spans, match_start) {
            continue;
        }

        if is_in_html_comment_ranges(html_comment_ranges, match_start) {
            continue;
        }

        let (line_idx, line_num, col_start) = positions.position(match_start);

        if is_mkdocs_snippet_line(lines[line_idx].content(content), flavor) {
            continue;
        }

        if lines.get(line_idx).is_some_and(is_literal_html_context) {
            continue;
        }

        let (_, end_line_num, col_end) = positions.position(match_end);

        // Match discovery retains the native regex traversal, including spans
        // already covered by parser links. Extract groups only when this match
        // survives the same exclusions and can enter the fallback index.
        let cap = LINK_PATTERN
            .captures_at(content, match_start)
            .expect("the same regex already found this match");
        debug_assert_eq!(cap.get(0).unwrap().range(), full_match.range());
        let text = cap.get(1).map_or("", |m| m.as_str());

        if let Some(ref_id) = cap.get(7) {
            let ref_id_str = ref_id.as_str();
            let normalized_ref = if ref_id_str.is_empty() {
                Cow::Owned(text.to_lowercase())
            } else {
                Cow::Owned(ref_id_str.to_lowercase())
            };
            let defined = resolver.is_defined(if ref_id_str.is_empty() { text } else { ref_id_str }, false);

            (if defined {
                &mut result.links
            } else {
                &mut unresolved_links
            })
            .push(ParsedLink {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: match_start,
                byte_end: match_end,
                text: Cow::Borrowed(text),
                url: Cow::Borrowed(""),
                title: None,
                is_reference: true,
                reference_id: Some(normalized_ref),
                link_type: LinkType::Reference,
            });
        } else if let Some(line_info) = lines.get(line_idx)
            && line_info.in_mkdocs_container()
        {
            // Inline links inside MkDocs admonitions/tabs that pulldown-cmark missed
            // because it treated the indented content as code blocks. All three
            // CommonMark §6.7 title delimiter forms must be recognized so links
            // like `[x](url (title))` don't get auto-fixed without their title.
            // CommonMark §6.1 backslash escapes are unescaped to match the
            // pulldown-cmark path (see `unescape_commonmark_punctuation`).
            let url = cap
                .get(2)
                .or_else(|| cap.get(3))
                .map_or(String::new(), |m| unescape_commonmark_punctuation(m.as_str().trim()));
            let title = cap
                .get(4)
                .or_else(|| cap.get(5))
                .or_else(|| cap.get(6))
                .map(|m| Cow::Owned(unescape_commonmark_punctuation(m.as_str())));
            result.links.push(ParsedLink {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: match_start,
                byte_end: match_end,
                text: Cow::Borrowed(text),
                url: Cow::Owned(url),
                title,
                is_reference: false,
                reference_id: None,
                link_type: LinkType::Inline,
            });
        }
    }

    // Regex fallback for images: find undefined references missed by pulldown-cmark

    let needs_images = memchr::memchr_iter(b'!', content.as_bytes()).any(|start| {
        content.as_bytes().get(start + 1) == Some(&b'[')
            && !result.image_found_positions.contains(&start)
            && (start == 0 || content.as_bytes()[start - 1] != b'\\')
    });

    let matches = needs_images
        .then(|| IMAGE_PATTERN.find_iter(content))
        .into_iter()
        .flatten();

    for full_match in matches {
        let match_start = full_match.start();
        let match_end = full_match.end();

        if mdx.is_some_and(|mdx| !mdx.contains_text(match_start, match_end)) {
            continue;
        }

        if result.image_found_positions.contains(&match_start) {
            continue;
        }

        if match_start > 0 && content.as_bytes().get(match_start - 1) == Some(&b'\\') {
            continue;
        }

        if CodeBlockUtils::is_in_code_block(code_blocks, match_start)
            || super::LintContext::binary_search_ranges(code_spans, match_start)
            || is_in_html_comment_ranges(html_comment_ranges, match_start)
        {
            continue;
        }

        let (line_idx, line_num, col_start) = positions.position(match_start);

        if lines.get(line_idx).is_some_and(is_literal_html_context) {
            continue;
        }

        let (_, end_line_num, col_end) = positions.position(match_end);
        let cap = IMAGE_PATTERN
            .captures_at(content, match_start)
            .expect("the same regex already found this match");
        debug_assert_eq!(cap.get(0).unwrap().range(), full_match.range());
        let alt_text = cap.get(1).map_or("", |m| m.as_str());

        if let Some(ref_id) = cap.get(7) {
            let ref_id_str = ref_id.as_str();
            let normalized_ref = if ref_id_str.is_empty() {
                Cow::Owned(alt_text.to_lowercase())
            } else {
                Cow::Owned(ref_id_str.to_lowercase())
            };
            let defined = resolver.is_defined(if ref_id_str.is_empty() { alt_text } else { ref_id_str }, false);

            (if defined {
                &mut result.images
            } else {
                &mut unresolved_images
            })
            .push(ParsedImage {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: match_start,
                byte_end: match_end,
                alt_text: Cow::Borrowed(alt_text),
                url: Cow::Borrowed(""),
                title: None,
                is_reference: true,
                reference_id: Some(normalized_ref),
                link_type: LinkType::Reference,
            });
        } else if let Some(line_info) = lines.get(line_idx)
            && line_info.in_mkdocs_container()
        {
            // Inline images inside MkDocs admonitions/tabs that pulldown-cmark missed
            // because it treated the indented content as code blocks. All three
            // CommonMark §6.7 title delimiter forms must be recognized so images
            // like `![alt](url (title))` don't lose their title on auto-fix.
            // CommonMark §6.1 backslash escapes are unescaped to match the
            // pulldown-cmark path (see `unescape_commonmark_punctuation`).
            let url = cap
                .get(2)
                .or_else(|| cap.get(3))
                .map_or(String::new(), |m| unescape_commonmark_punctuation(m.as_str().trim()));
            let title = cap
                .get(4)
                .or_else(|| cap.get(5))
                .or_else(|| cap.get(6))
                .map(|m| Cow::Owned(unescape_commonmark_punctuation(m.as_str())));
            result.images.push(ParsedImage {
                line: line_num,
                end_line: end_line_num,
                start_col: col_start,
                end_col: col_end,
                byte_offset: match_start,
                byte_end: match_end,
                alt_text: Cow::Borrowed(alt_text),
                url: Cow::Owned(url),
                title,
                is_reference: false,
                reference_id: None,
                link_type: LinkType::Inline,
            });
        }
    }

    // Sort by line number so binary search consumers work correctly.
    result.links.sort_by_key(|l| (l.line, l.byte_offset));
    result.images.sort_by_key(|i| (i.line, i.byte_offset));
    unresolved_links.sort_by_key(|l| (l.line, l.byte_offset));
    unresolved_images.sort_by_key(|i| (i.line, i.byte_offset));

    FinalizedLinks {
        links: result.links,
        images: result.images,
        unresolved_links,
        unresolved_images,
        broken_links: result.broken_links,
        footnote_refs: result.footnote_refs,
    }
}

/// True iff the source span of an *inline* link/image carries an explicit
/// empty title — `[t](url "")`, `[t](url '')`, or `[t](url ())`.
///
/// Pulldown-cmark collapses these into the same empty `CowStr<'_>` it emits
/// when a link has no title delimiter at all (`[t](url)`), so the parser-level
/// title alone can't tell them apart. The distinction matters for MD054's
/// auto-fix: a conversion to autolink (`<url>`) would silently drop the
/// `""`/`''`/`()` delimiters the author wrote, changing the document. The
/// planner's reachability check gates Autolink targets on `!has_title`, so
/// preserving "explicit empty" as `Some("")` (instead of collapsing to `None`)
/// is enough to block the unsafe rewrite.
///
/// The detector walks the span backwards from the closing `)` of the inline
/// link, skips optional CommonMark-permitted whitespace between the title and
/// the closing paren, and matches an empty `""`/`''`/`()` pair preceded by
/// the whitespace separator that distinguishes the title from the destination.
/// This is intentionally narrow — anything more elaborate (e.g. a non-empty
/// title) is already represented by pulldown-cmark and doesn't need rescue.
pub(super) fn has_explicit_empty_inline_title(span: &str) -> bool {
    span.strip_suffix(')').is_some_and(has_explicit_empty_title_ending)
}

pub(super) fn has_explicit_empty_title_ending(span: &str) -> bool {
    let bytes = span.as_bytes();
    let mut i = bytes.len();
    while i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\n' | b'\r') {
        i -= 1;
    }
    if i < 2 {
        return false;
    }
    let close = bytes[i - 1];
    let open = match close {
        b'"' => b'"',
        b'\'' => b'\'',
        b')' => b'(',
        _ => return false,
    };
    if bytes[i - 2] != open {
        return false;
    }
    // The empty-title pair must be separated from the destination by at least
    // one whitespace byte — without that gap, the bytes belong to the
    // destination (e.g. an angle-bracketed URL ending in `""`) rather than
    // forming a title delimiter.
    if i < 3 {
        return false;
    }
    matches!(bytes[i - 3], b' ' | b'\t' | b'\n' | b'\r')
}

/// CommonMark §6.1 backslash escapes: a backslash followed by any ASCII
/// punctuation character represents that character literally; backslashes
/// before any other character (or at end of input) are preserved verbatim.
///
/// pulldown-cmark applies this transformation when it parses URLs and titles,
/// so downstream rules that read the parser's `Tag::Link`/`Tag::Image` values
/// see unescaped strings. The regex fallback in `parse_reference_defs` reads
/// the raw source slice between the destination/title delimiters, so it must
/// apply the same transform for the two views to agree. Without this, a
/// definition like `[id]: /path "with \"quote\""` would expose
/// `with \"quote\"` to MD054/MD053, and a transformer that copies that string
/// back into the document would either double-escape or leave the wrong
/// character count.
pub(super) fn unescape_commonmark_punctuation(input: &str) -> String {
    if !input.contains('\\') {
        return input.to_string();
    }
    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'\\' && i + 1 < bytes.len() && is_ascii_punctuation(bytes[i + 1]) {
            out.push(bytes[i + 1] as char);
            i += 2;
        } else {
            // Push the next UTF-8 scalar (could be multi-byte).
            let ch_len = utf8_char_len(b);
            out.push_str(&input[i..i + ch_len]);
            i += ch_len;
        }
    }
    out
}

#[inline]
fn is_ascii_punctuation(b: u8) -> bool {
    // CommonMark §2.1: ASCII punctuation = !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    matches!(
        b,
        b'!' | b'"'
            | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'('
            | b')'
            | b'*'
            | b'+'
            | b','
            | b'-'
            | b'.'
            | b'/'
            | b':'
            | b';'
            | b'<'
            | b'='
            | b'>'
            | b'?'
            | b'@'
            | b'['
            | b'\\'
            | b']'
            | b'^'
            | b'_'
            | b'`'
            | b'{'
            | b'|'
            | b'}'
            | b'~'
    )
}

#[inline]
fn utf8_char_len(first_byte: u8) -> usize {
    match first_byte {
        0x00..=0x7F => 1,
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF7 => 4,
        _ => 1, // Continuation/invalid byte; advance by 1 to avoid infinite loop.
    }
}

/// The destination of each definition the parser reads at `starts`, the
/// offsets of `[` opening labels, or `None` where it reads none.
///
/// The parser lists only the first definition of a label, so each label at
/// `starts` gets a prefix no other label in the document holds before the
/// document is parsed again. A prefix of ASCII characters other than
/// whitespace and brackets changes neither where a definition ends nor
/// whether its label is valid, so the parser then reads exactly the
/// definitions it read before and lists every one of them.
fn parser_destinations_at(content: &str, starts: &[usize]) -> Vec<Option<String>> {
    let longest_run = content.split(|c| c != '\x7f').map(str::len).max().unwrap_or(0);
    let marker = "\x7f".repeat(longest_run + 1);
    let mut relabeled = String::with_capacity(content.len() + starts.len() * (2 * marker.len() + 8));
    let mut copied = 0;
    for (index, &start) in starts.iter().enumerate() {
        relabeled.push_str(&content[copied..=start]);
        relabeled.push_str(&marker);
        relabeled.push_str(&index.to_string());
        relabeled.push_str(&marker);
        copied = start + 1;
    }
    relabeled.push_str(&content[copied..]);

    let mut destinations = vec![None; starts.len()];
    let parser = pulldown_cmark::Parser::new_ext(&relabeled, rumdl_parser_options_for(content));
    for (label, definition) in parser.reference_definitions().iter() {
        let index = label
            .strip_prefix(marker.as_str())
            .and_then(|rest| rest.split_once(marker.as_str()))
            .and_then(|(index, _)| index.parse::<usize>().ok());
        if let Some(slot) = index.and_then(|index| destinations.get_mut(index)) {
            *slot = Some(definition.dest.to_string());
        }
    }
    destinations
}

/// The destination of the definition `text` opens with, as the parser reads
/// it.
fn definition_destination(text: &str) -> Option<String> {
    let parser = pulldown_cmark::Parser::new_ext(text, rumdl_parser_options_for(text));
    parser
        .reference_definitions()
        .iter()
        .next()
        .map(|(_, definition)| definition.dest.to_string())
}

/// The link reference definitions of a document: the lines written as one
/// that the Markdown parser reads as one, plus those the flavor reads where
/// the parser sees text.
///
/// A line shaped like a definition is text when it continues a paragraph, a
/// list item or a definition list term, or sits in a code block, heading,
/// table or HTML block. `parser_definitions`
/// holds the parser's first definition of each label; a repeated label's
/// definition is consumed by the parser without being listed there, so a
/// line not found among them is a definition exactly when the parser reads
/// one there once its label is unique. A line inside the title of another
/// definition, or in any block that swallows it, is then text. MkDocs
/// containers read definitions anywhere in their body, and
/// a definition straight after a Pandoc div fence, a container's opening or
/// closing marker, a kramdown block attribute list or extension block, or
/// after another such definition, is one where the flavor ends the block
/// before it.
pub(super) fn parse_reference_defs(
    content: &str,
    lines: &[LineInfo],
    flavor: MarkdownFlavor,
    parser_definitions: &[ParserDefinition],
) -> Vec<ReferenceDef> {
    let mut refs = Vec::with_capacity(lines.len() / 20);
    // Definitions the parser does not list, with their label offsets, to be
    // checked against the parser once every line is read.
    let mut unlisted: Vec<(usize, usize)> = Vec::new();
    // The last line of the latest definition the flavor alone reads.
    let mut flavor_definition_end: Option<usize> = None;

    for (line_idx, line_info) in lines.iter().enumerate() {
        if line_info.in_code_block {
            continue;
        }

        let line_num = line_idx + 1;

        // Reference definitions are document-global per CommonMark even inside a
        // blockquote (`> [id]: url`). Match the quoted content and offset the byte
        // positions past the blockquote prefix; plain lines are matched verbatim.
        let (line, base_offset) = match line_info.blockquote.as_deref() {
            Some(bq) => (bq.content.as_str(), line_info.byte_offset + bq.prefix.len()),
            None => (line_info.content(content), line_info.byte_offset),
        };

        if !line.trim_start_matches(' ').starts_with('[') {
            continue;
        }

        if let Some(cap) = REF_DEF_PATTERN.captures(line) {
            let id_raw = cap.get(1).unwrap().as_str();

            // Skip footnote definitions
            if id_raw.starts_with('^') {
                continue;
            }

            let id = id_raw.to_lowercase();
            // Group 2: <...> destination (angle-bracket content stripped).
            // Group 3: bare destination.
            // CommonMark §6.1: apply backslash unescape so the regex fallback
            // produces the same string as pulldown-cmark's parsed value.
            let url = unescape_commonmark_punctuation(
                cap.get(2)
                    .or_else(|| cap.get(3))
                    .expect("destination alternation always matches")
                    .as_str(),
            );
            // Group 4: "..." title, group 5: '...' title, group 6: (...) title.
            let title_match = cap.get(4).or_else(|| cap.get(5)).or_else(|| cap.get(6));

            let match_obj = cap.get(0).unwrap();
            let byte_offset = base_offset + match_obj.start();

            let mut byte_end = base_offset + match_obj.end();
            let mut title = title_match.map(|m| unescape_commonmark_punctuation(m.as_str()));
            let (mut title_byte_start, mut title_byte_end) = if let Some(m) = title_match {
                let start = base_offset + m.start().saturating_sub(1);
                let end = base_offset + m.end() + 1;
                (Some(start), Some(end))
            } else {
                (None, None)
            };

            // CommonMark §4.7: when the destination line carries no title, the
            // title may be on the immediately following line (no blank line
            // between, same blockquote context, not in a code block). Pull it in
            // so the whole definition is one reference definition.
            if title_match.is_none()
                && let Some(next) = lines.get(line_idx + 1)
                && !next.in_code_block
            {
                let cur_nesting = line_info.blockquote.as_deref().map_or(0, |bq| bq.nesting_level);
                let (next_line, next_base, next_nesting) = match next.blockquote.as_deref() {
                    Some(bq) => (
                        bq.content.as_str(),
                        next.byte_offset + bq.prefix.len(),
                        bq.nesting_level,
                    ),
                    None => (next.content(content), next.byte_offset, 0),
                };
                if next_nesting == cur_nesting
                    && let Some(tcap) = REF_DEF_TITLE_CONTINUATION.captures(next_line)
                {
                    let tmatch = tcap
                        .get(1)
                        .or_else(|| tcap.get(2))
                        .or_else(|| tcap.get(3))
                        .expect("title alternation always matches");
                    title = Some(unescape_commonmark_punctuation(tmatch.as_str()));
                    title_byte_start = Some(next_base + tmatch.start().saturating_sub(1));
                    title_byte_end = Some(next_base + tmatch.end() + 1);
                    byte_end = next.byte_offset + next.byte_len;
                }
            }

            let label_start =
                byte_offset + (match_obj.as_str().len() - match_obj.as_str().trim_start_matches(' ').len());
            let destination =
                match parser_definitions.binary_search_by_key(&label_start, |definition| definition.span.start) {
                    Ok(index) => parser_definitions[index].dest.clone(),
                    Err(_) => {
                        let after_flavor_marker = line_idx
                            .checked_sub(1)
                            .and_then(|previous| lines.get(previous))
                            .is_some_and(|previous| {
                                previous.is_container_marker
                                    || previous.is_kramdown_block_ial
                                    || previous.in_kramdown_extension_block
                                    || (flavor.is_pandoc_compatible() && previous.is_div_marker)
                            });
                        let read_by_flavor = line_info.in_mkdocs_container()
                            || after_flavor_marker
                            || flavor_definition_end.is_some_and(|end| end + 1 == line_idx);
                        if read_by_flavor {
                            let last_line = lines[line_idx..]
                                .iter()
                                .take_while(|line| line.byte_offset < byte_end)
                                .count();
                            flavor_definition_end = Some(line_idx + last_line.max(1) - 1);
                            let first_line_end = content[label_start..]
                                .find('\n')
                                .map_or(content.len(), |end| label_start + end);
                            definition_destination(&content[label_start..first_line_end]).unwrap_or_else(|| url.clone())
                        } else {
                            // Set once the parser has been asked about every such line.
                            unlisted.push((refs.len(), label_start));
                            String::new()
                        }
                    }
                };

            refs.push(ReferenceDef {
                line: line_num,
                id,
                url,
                destination,
                title,
                byte_offset,
                byte_end,
                title_byte_start,
                title_byte_end,
            });
        }
    }

    if !unlisted.is_empty() {
        let starts: Vec<usize> = unlisted.iter().map(|&(_, start)| start).collect();
        let mut read = vec![true; refs.len()];
        for (&(index, _), destination) in unlisted.iter().zip(parser_destinations_at(content, &starts)) {
            match destination {
                Some(destination) => refs[index].destination = destination,
                None => read[index] = false,
            }
        }
        let mut read = read.into_iter();
        refs.retain(|_| read.next().unwrap_or(true));
    }

    refs
}

/// A definition a link may resolve to, with its label folded for matching.
pub(super) struct DefinitionCandidate {
    pub(super) label: String,
    pub(super) definition: ParserDefinition,
}

/// The definitions links may resolve to, in source order: those the Markdown
/// parser reads, and those in `reference_defs` that only the flavor reads,
/// where it starts a block the parser continues. A label can occur more than
/// once; which occurrence a link resolves to depends on which of them are in
/// the document body, so the choice is left to the reader of this list.
pub(super) fn definition_candidates(
    content: &str,
    parser_definitions: Vec<ParserDefinition>,
    reference_defs: &[ReferenceDef],
) -> Vec<DefinitionCandidate> {
    let parser_starts: HashSet<usize> = parser_definitions.iter().map(|d| d.span.start).collect();
    let mut candidates: Vec<DefinitionCandidate> = parser_definitions
        .into_iter()
        .filter_map(|definition| {
            Some(DefinitionCandidate {
                label: fold_label(written_label(content, definition.span.start)?),
                definition,
            })
        })
        .collect();
    for def in reference_defs {
        let start = definition_label_start(content, def);
        if parser_starts.contains(&start) {
            continue;
        }
        candidates.push(DefinitionCandidate {
            label: fold_label(&def.id),
            definition: ParserDefinition {
                span: start..def.byte_end,
                dest: def.destination.clone(),
            },
        });
    }
    candidates.sort_by_key(|candidate| candidate.definition.span.start);
    candidates
}

/// Byte offset of the `[` opening the label of `def`.
pub(super) fn definition_label_start(content: &str, def: &ReferenceDef) -> usize {
    let rest = &content[def.byte_offset..];
    def.byte_offset + rest.len() - rest.trim_start_matches(' ').len()
}

/// The label of the definition whose `[` is at `start`, as written: up to
/// the first unescaped `]`.
fn written_label(content: &str, start: usize) -> Option<&str> {
    let rest = content.get(start..)?.strip_prefix('[')?;
    let mut escaped = false;
    for (i, c) in rest.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            ']' => return Some(&rest[..i]),
            _ => {}
        }
    }
    None
}