Skip to main content

rumdl_lib/rules/
md051_link_fragments.rs

1use crate::lint_context::{LineInfo, LintContext};
2use crate::rule::{CrossFileScope, FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
3use crate::rule_config_serde::RuleConfig;
4use crate::utils::anchor_styles::AnchorStyle;
5use crate::utils::frontmatter_values;
6use crate::utils::header_id_utils::{HTML_BLOCK_OPEN_TAG, HTML_OPEN_TAG, html_tag_attribute, is_backslash_escaped};
7use crate::utils::range_utils::byte_to_char_count;
8use crate::workspace_index::{CrossFileLinkIndex, FileIndex, HeadingIndex, LinkOrigin};
9use pulldown_cmark::LinkType;
10use regex::Regex;
11use serde::{Deserialize, Serialize};
12use std::collections::{HashMap, HashSet};
13use std::path::Path;
14use std::sync::LazyLock;
15
16/// Configuration for MD051 (Link fragments)
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
18#[serde(rename_all = "kebab-case")]
19pub struct MD051Config {
20    /// Anchor generation style to match the target platform
21    #[serde(default, alias = "anchor_style")]
22    pub anchor_style: AnchorStyle,
23
24    /// Match link fragments against headings case-insensitively.
25    ///
26    /// rumdl defaults to `true` (permissive matching), which deviates from
27    /// markdownlint's default of `false`. Set this to `false` for strict
28    /// markdownlint parity.
29    #[serde(default = "default_ignore_case", alias = "ignore_case")]
30    pub ignore_case: bool,
31
32    /// Optional regex applied to the fragment text (without the leading `#`).
33    /// Fragments that match are skipped — useful for runtime-generated anchors
34    /// (e.g., footnote IDs) that aren't visible to the linter.
35    #[serde(default, alias = "ignored_pattern")]
36    pub ignored_pattern: Option<String>,
37
38    /// Also check fragments in path-shaped frontmatter values.
39    ///
40    /// Off by default, because frontmatter has no syntax marking a value as a
41    /// link: a path-shaped value is only a guess at one. Static-site generators
42    /// also resolve frontmatter paths from the site root rather than the
43    /// document's own directory, so checking them like body links reports
44    /// working paths as broken.
45    ///
46    /// Enable it for projects whose frontmatter links really are relative to
47    /// the document, and use `ignore-frontmatter-fields` for the keys that are
48    /// not.
49    ///
50    /// Example:
51    /// ```toml
52    /// [MD051]
53    /// check-frontmatter = true
54    /// ignore-frontmatter-fields = ["image", "cover"]
55    /// ```
56    #[serde(default)]
57    pub check_frontmatter: bool,
58
59    /// Top-level frontmatter keys whose values are not checked. Matched
60    /// case-insensitively. A parent key excludes its whole subtree. Applies
61    /// only when `check-frontmatter` is enabled.
62    #[serde(default)]
63    pub ignore_frontmatter_fields: Vec<String>,
64}
65
66fn default_ignore_case() -> bool {
67    true
68}
69
70impl Default for MD051Config {
71    fn default() -> Self {
72        Self {
73            anchor_style: AnchorStyle::default(),
74            ignore_case: true,
75            ignored_pattern: None,
76            check_frontmatter: false,
77            ignore_frontmatter_fields: Vec::new(),
78        }
79    }
80}
81
82impl RuleConfig for MD051Config {
83    const RULE_NAME: &'static str = "MD051";
84}
85
86/// Hand `record` every fragment that reaches an HTML element written on one line.
87///
88/// An element is reached through its `id`; an `<a>` element also through its
89/// `name`, the only element whose `name` fragment navigation honours. Markup
90/// inside a code span or an HTML comment is not rendered, markup inside an
91/// image description is alt text, and a backslash-escaped `<` is text, so none
92/// of these defines a target; the scan resumes just past such a `<`, since the
93/// text may hold a real tag of its own. Inside an HTML block CommonMark
94/// processes no escapes, so a backslash before a tag there is text of its own
95/// and the tag is real, and the browser's tokenizer decides what a tag name is.
96fn for_each_html_anchor_target(ctx: &LintContext, line_info: &LineInfo, mut record: impl FnMut(&str)) {
97    let content = line_info.content(ctx.content);
98    if !content.contains('<') {
99        return;
100    }
101
102    let escapes_apply = !line_info.in_html_block;
103    let open_tags: &Regex = if line_info.in_html_block {
104        &HTML_BLOCK_OPEN_TAG
105    } else {
106        &HTML_OPEN_TAG
107    };
108    let mut pos = 0;
109    while let Some(tag) = open_tags.captures_at(content, pos) {
110        let whole = tag.get(0).unwrap();
111        let byte_pos = line_info.byte_offset + whole.start();
112        if ctx.is_in_code_span_byte(byte_pos)
113            || ctx.is_in_html_comment(byte_pos)
114            || ctx.image_containing(byte_pos).is_some()
115            || (escapes_apply && is_backslash_escaped(content, whole.start()))
116        {
117            // The tag is text, and text may hold a tag of its own past its `<`.
118            pos = whole.start() + 1;
119            continue;
120        }
121        pos = whole.end();
122
123        if let Some(id) = html_tag_attribute(whole.as_str(), "id") {
124            record(id);
125        }
126        if tag[1].eq_ignore_ascii_case("a")
127            && let Some(name) = html_tag_attribute(whole.as_str(), "name")
128        {
129            record(name);
130        }
131    }
132}
133
134// Attribute anchor pattern for kramdown/MkDocs { #id } syntax
135// Matches {#id} or { #id } with optional spaces, supports multiple anchors
136// Also supports classes and attributes: { #id .class key=value }
137static ATTR_ANCHOR_PATTERN: LazyLock<Regex> =
138    LazyLock::new(|| Regex::new(r#"\{\s*#([a-zA-Z0-9_][a-zA-Z0-9_-]*)[^}]*\}"#).unwrap());
139
140// Material for MkDocs setting anchor pattern: <!-- md:setting NAME -->
141// Used in headings to generate anchors for configuration option references
142static MD_SETTING_PATTERN: LazyLock<Regex> =
143    LazyLock::new(|| Regex::new(r"<!--\s*md:setting\s+([^\s]+)\s*-->").unwrap());
144
145/// Rule MD051: Link fragments
146///
147/// See [docs/md051.md](../../docs/md051.md) for full documentation, configuration, and examples.
148///
149/// This rule validates that link anchors (the part after #) point to existing headings.
150/// Supports both same-document anchors and cross-file fragment links when linting a workspace.
151#[derive(Clone)]
152pub struct MD051LinkFragments {
153    config: MD051Config,
154    /// Pre-compiled `ignored_pattern` regex. `None` if the user did not set the
155    /// option, or if the pattern failed to compile (a `log::warn!` is emitted
156    /// once at construction time so the user can fix the config).
157    ignored_pattern_regex: Option<Regex>,
158    /// `ignore_frontmatter_fields` lowercased for case-insensitive matching.
159    ignored_front_matter_fields: HashSet<String>,
160    /// Whether `config.anchor_style` was chosen rather than derived from a
161    /// flavor. Unpinned, the style follows the flavor of the file being
162    /// checked; see [`MD051LinkFragments::anchor_style`].
163    anchor_style_pinned: bool,
164}
165
166/// Anchor sets extracted from a single document, with parallel lowercase and
167/// case-preserving storage. The `*_exact` sets are empty unless
168/// `ignore_case = false` so the default permissive path costs no extra
169/// allocations.
170struct AnchorSets {
171    markdown_headings: HashSet<String>,
172    markdown_headings_exact: HashSet<String>,
173    html_anchors: HashSet<String>,
174    html_anchors_exact: HashSet<String>,
175}
176
177impl Default for MD051LinkFragments {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183impl MD051LinkFragments {
184    pub fn new() -> Self {
185        Self::from_config_struct(MD051Config::default())
186    }
187
188    /// Create with specific anchor style (other options use defaults)
189    pub fn with_anchor_style(style: AnchorStyle) -> Self {
190        Self::from_config_struct(MD051Config {
191            anchor_style: style,
192            ..MD051Config::default()
193        })
194    }
195
196    /// Create from a fully-populated config struct.
197    ///
198    /// Compiles `ignored_pattern` once. An invalid regex is logged via
199    /// `log::warn!` and the rule falls back to "no filter" so linting still
200    /// works rather than silently swallowing every fragment.
201    pub fn from_config_struct(config: MD051Config) -> Self {
202        Self::from_config_struct_from(config, false)
203    }
204
205    /// [`Self::from_config_struct`], told whether a message about `ignored_pattern`
206    /// may quote it. See [`crate::rule_config_serde::compile_config_regex`].
207    fn from_config_struct_from(config: MD051Config, values_withheld: bool) -> Self {
208        Self::build(config, values_withheld, true)
209    }
210
211    /// The shared constructor. `anchor_style_pinned` is false only when the
212    /// style in `config` was derived from a flavor rather than chosen by the
213    /// user, which is what lets [`Self::anchor_style`] re-derive it per file.
214    fn build(config: MD051Config, values_withheld: bool, anchor_style_pinned: bool) -> Self {
215        let ignored_pattern_regex = config.ignored_pattern.as_deref().and_then(|pattern| {
216            crate::rule_config_serde::compile_config_regex(pattern, "MD051", "ignored-pattern", values_withheld)
217        });
218        let ignored_front_matter_fields = config
219            .ignore_frontmatter_fields
220            .iter()
221            .map(|field| field.to_lowercase())
222            .collect();
223        Self {
224            config,
225            ignored_pattern_regex,
226            ignored_front_matter_fields,
227            anchor_style_pinned,
228        }
229    }
230
231    /// The anchor style to generate fragments with for the file in `ctx`.
232    ///
233    /// A style the user pinned applies to every file. Otherwise it follows the
234    /// flavor the file is parsed with, which `per-file-flavor` can make
235    /// different from the global flavor the rule was constructed with, so it
236    /// cannot be settled until a file is in hand.
237    fn anchor_style(&self, ctx: &crate::lint_context::LintContext) -> AnchorStyle {
238        if self.anchor_style_pinned {
239            self.config.anchor_style
240        } else {
241            AnchorStyle::for_flavor(ctx.flavor)
242        }
243    }
244
245    /// Insert a heading fragment with deduplication.
246    /// When `use_underscore_dedup` is true (Python-Markdown/MkDocs), the primary suffix
247    /// uses `_N` and `-N` is registered as a fallback. Otherwise, only `-N` is used.
248    ///
249    /// Empty fragments (from CJK-only headings) are handled specially for Python-Markdown:
250    /// the first empty slug gets `_1`, the second `_2`, etc. (matching Python-Markdown's
251    /// `unique()` function which always enters the dedup loop for falsy IDs).
252    fn insert_deduplicated_fragment(
253        fragment: String,
254        fragment_counts: &mut HashMap<String, usize>,
255        markdown_headings: &mut HashSet<String>,
256        mut markdown_headings_exact: Option<&mut HashSet<String>>,
257        use_underscore_dedup: bool,
258    ) {
259        // Slugs from generate_fragment are already lowercase, so the exact set
260        // ends up identical to the lowercased set for slugs. The exact set is
261        // only meaningfully different for case-preserving custom IDs (handled
262        // by the caller). Skipping the parallel inserts when the caller passes
263        // None avoids unnecessary allocations on the default ignore_case=true path.
264        let mut also_insert_exact = |form: &str| {
265            if let Some(set) = markdown_headings_exact.as_deref_mut() {
266                set.insert(form.to_string());
267            }
268        };
269
270        if fragment.is_empty() {
271            if !use_underscore_dedup {
272                return;
273            }
274            // Python-Markdown: empty slug → _1, _2, _3, ...
275            let count = fragment_counts.entry(fragment).or_insert(0);
276            *count += 1;
277            let formed = format!("_{count}");
278            also_insert_exact(&formed);
279            markdown_headings.insert(formed);
280            return;
281        }
282        if let Some(count) = fragment_counts.get_mut(&fragment) {
283            let suffix = *count;
284            *count += 1;
285            if use_underscore_dedup {
286                // Python-Markdown primary: heading_1, heading_2
287                let underscore_form = format!("{fragment}_{suffix}");
288                also_insert_exact(&underscore_form);
289                markdown_headings.insert(underscore_form);
290                // Also accept GitHub-style for compatibility
291                let dash_form = format!("{fragment}-{suffix}");
292                also_insert_exact(&dash_form);
293                markdown_headings.insert(dash_form);
294            } else {
295                // GitHub-style: heading-1, heading-2
296                let form = format!("{fragment}-{suffix}");
297                also_insert_exact(&form);
298                markdown_headings.insert(form);
299            }
300        } else {
301            fragment_counts.insert(fragment.clone(), 1);
302            also_insert_exact(&fragment);
303            markdown_headings.insert(fragment);
304        }
305    }
306
307    /// Add a heading to the cross-file index with proper deduplication.
308    /// When `use_underscore_dedup` is true (Python-Markdown/MkDocs), the primary anchor
309    /// uses `_N` and `-N` is registered as a fallback alias.
310    ///
311    /// Empty fragments (from CJK-only headings) get `_1`, `_2`, etc. in Python-Markdown mode.
312    ///
313    /// `is_setext` is carried into the index because the LSP locates a heading's
314    /// text from it: a Setext heading has no `#` markers to skip past.
315    #[allow(clippy::too_many_arguments)]
316    fn add_heading_to_index(
317        fragment: &str,
318        text: &str,
319        custom_anchor: Option<String>,
320        line: usize,
321        is_setext: bool,
322        fragment_counts: &mut HashMap<String, usize>,
323        file_index: &mut FileIndex,
324        use_underscore_dedup: bool,
325    ) {
326        if fragment.is_empty() {
327            if !use_underscore_dedup {
328                return;
329            }
330            // Python-Markdown: empty slug → _1, _2, _3, ...
331            let count = fragment_counts.entry(fragment.to_string()).or_insert(0);
332            *count += 1;
333            file_index.add_heading(HeadingIndex {
334                text: text.to_string(),
335                auto_anchor: format!("_{count}"),
336                custom_anchor,
337                line,
338                is_setext,
339            });
340            return;
341        }
342        if let Some(count) = fragment_counts.get_mut(fragment) {
343            let suffix = *count;
344            *count += 1;
345            let (primary, alias) = if use_underscore_dedup {
346                // Python-Markdown primary: heading_1; GitHub fallback: heading-1
347                (format!("{fragment}_{suffix}"), Some(format!("{fragment}-{suffix}")))
348            } else {
349                // GitHub-style primary: heading-1
350                (format!("{fragment}-{suffix}"), None)
351            };
352            file_index.add_heading(HeadingIndex {
353                text: text.to_string(),
354                auto_anchor: primary,
355                custom_anchor,
356                line,
357                is_setext,
358            });
359            if let Some(alias_anchor) = alias {
360                let heading_idx = file_index.headings.len() - 1;
361                file_index.add_anchor_alias(&alias_anchor, heading_idx);
362            }
363        } else {
364            fragment_counts.insert(fragment.to_string(), 1);
365            file_index.add_heading(HeadingIndex {
366                text: text.to_string(),
367                auto_anchor: fragment.to_string(),
368                custom_anchor,
369                line,
370                is_setext,
371            });
372        }
373    }
374
375    /// Extract all valid heading anchors from the document.
376    ///
377    /// Returns parallel lowercase + case-preserving sets so the same-document
378    /// check can honor `ignore_case` consistently with cross-file lookups.
379    /// The `*_exact` sets are only populated when `ignore_case = false` to
380    /// avoid unnecessary allocations on the default permissive path.
381    fn extract_headings_from_context(&self, ctx: &crate::lint_context::LintContext) -> AnchorSets {
382        let track_exact = !self.config.ignore_case;
383        let mut markdown_headings = HashSet::with_capacity(32);
384        let mut markdown_headings_exact = if track_exact {
385            HashSet::with_capacity(32)
386        } else {
387            HashSet::new()
388        };
389        let mut html_anchors = HashSet::with_capacity(16);
390        let mut html_anchors_exact = if track_exact {
391            HashSet::with_capacity(16)
392        } else {
393            HashSet::new()
394        };
395        let mut fragment_counts = std::collections::HashMap::new();
396        let anchor_style = self.anchor_style(ctx);
397        let use_underscore_dedup = anchor_style == AnchorStyle::PythonMarkdown;
398
399        for (line_idx, line_info) in ctx.lines.iter().enumerate() {
400            if line_info.in_front_matter {
401                continue;
402            }
403
404            // Skip code blocks for anchor extraction
405            if line_info.in_code_block {
406                continue;
407            }
408
409            let content = line_info.content(ctx.content);
410
411            for_each_html_anchor_target(ctx, line_info, |id| {
412                html_anchors.insert(id.to_lowercase());
413                if track_exact {
414                    html_anchors_exact.insert(id.to_string());
415                }
416            });
417
418            // Extract attribute anchors { #id } from non-heading lines
419            // Headings already have custom_id extracted below
420            let parsed_heading = ctx.heading_on_line(line_idx + 1);
421            if parsed_heading.is_none() && content.contains('{') && content.contains('#') {
422                for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
423                    if let Some(id_match) = caps.get(1) {
424                        let id = id_match.as_str();
425                        markdown_headings.insert(id.to_lowercase());
426                        if track_exact {
427                            markdown_headings_exact.insert(id.to_string());
428                        }
429                    }
430                }
431            }
432
433            // Extract Markdown heading anchors, including headings in blockquotes.
434            if let Some(parsed) = parsed_heading {
435                let heading = parsed.heading;
436                // Custom ID from {#custom-id} syntax
437                if let Some(custom_id) = &heading.custom_id {
438                    markdown_headings.insert(custom_id.to_lowercase());
439                    if track_exact {
440                        markdown_headings_exact.insert(custom_id.clone());
441                    }
442                }
443
444                // The slug text keeps the whitespace an anchor element leaves at
445                // either end, which GitHub and kramdown slug to a hyphen. HTML
446                // tags are left for the anchor styles, which know that `<->` and
447                // `<FILE>` are not tags.
448                let fragment = anchor_style.generate_fragment(&heading.slug_text);
449
450                Self::insert_deduplicated_fragment(
451                    fragment,
452                    &mut fragment_counts,
453                    &mut markdown_headings,
454                    track_exact.then_some(&mut markdown_headings_exact),
455                    use_underscore_dedup,
456                );
457            }
458        }
459
460        AnchorSets {
461            markdown_headings,
462            markdown_headings_exact,
463            html_anchors,
464            html_anchors_exact,
465        }
466    }
467
468    /// Fast check if URL is external (doesn't need to be validated)
469    #[inline]
470    fn is_external_url_fast(url: &str) -> bool {
471        // Quick prefix checks for common protocols
472        url.starts_with("http://")
473            || url.starts_with("https://")
474            || url.starts_with("ftp://")
475            || url.starts_with("mailto:")
476            || url.starts_with("tel:")
477            || url.starts_with("//")
478    }
479
480    /// Check if a path part (without fragment or query) is an extension-less path
481    ///
482    /// Extension-less paths are potential cross-file links that need resolution
483    /// with markdown extensions (e.g., `page#section` -> `page.md#section`).
484    ///
485    /// We recognize them as extension-less if:
486    /// 1. Path has no extension (no dot)
487    /// 2. Path is not empty
488    /// 3. Path doesn't look like query syntax
489    /// 4. Path contains at least one alphanumeric character (valid filename)
490    /// 5. Path contains only valid path characters (alphanumeric, slashes, hyphens, underscores)
491    ///
492    /// Optimized: single pass through characters to check both conditions.
493    #[inline]
494    fn is_extensionless_path(path_part: &str) -> bool {
495        // Quick rejections for common non-extension-less cases
496        if path_part.is_empty() || path_part.contains('.') || path_part.contains('&') || path_part.contains('=') {
497            return false;
498        }
499
500        // Single pass: check for alphanumeric and validate all characters
501        let mut has_alphanumeric = false;
502        for c in path_part.chars() {
503            if c.is_alphanumeric() {
504                has_alphanumeric = true;
505            } else if !matches!(c, '/' | '\\' | '-' | '_') {
506                // Invalid character found - early exit
507                return false;
508            }
509        }
510
511        // Must have at least one alphanumeric character to be a valid filename
512        has_alphanumeric
513    }
514
515    /// Check if URL is a cross-file link (contains a file path before #)
516    #[inline]
517    fn is_cross_file_link(url: &str) -> bool {
518        if let Some(fragment_pos) = url.find('#') {
519            let path_part = &url[..fragment_pos];
520
521            // If there's no path part, it's just a fragment (#heading)
522            if path_part.is_empty() {
523                return false;
524            }
525
526            // Check for Liquid syntax used by Jekyll and other static site generators
527            // Liquid tags: {% ... %} for control flow and includes
528            // Liquid variables: {{ ... }} for outputting values
529            // These are template directives that reference external content and should be skipped
530            // We check for proper bracket order to avoid false positives
531            if let Some(tag_start) = path_part.find("{%")
532                && path_part[tag_start + 2..].contains("%}")
533            {
534                return true;
535            }
536            if let Some(var_start) = path_part.find("{{")
537                && path_part[var_start + 2..].contains("}}")
538            {
539                return true;
540            }
541
542            // Check if it's an absolute path (starts with /)
543            // These are links to other pages on the same site
544            if path_part.starts_with('/') {
545                return true;
546            }
547
548            // A query string belongs to the destination, not to the path it names,
549            // so `page.md?raw=true` and `page?raw=true` name `page.md` and `page`.
550            let path_part = path_part.split('?').next().unwrap_or(path_part);
551
552            // A destination that is only a query and a fragment stays on this page
553            if path_part.is_empty() {
554                return false;
555            }
556
557            // Check if it looks like a file path:
558            // - Contains a file extension (dot followed by letters)
559            // - Contains path separators
560            // - Contains relative path indicators
561            // - OR is an extension-less path with a fragment (GitHub-style: page#section)
562            let has_extension = path_part.contains('.')
563                && (
564                    // Has file extension pattern
565                    {
566                    // Handle files starting with dot
567                    if let Some(after_dot) = path_part.strip_prefix('.') {
568                        let dots_count = path_part.matches('.').count();
569                        if dots_count == 1 {
570                            // Could be ".ext" (file extension) or ".hidden" (hidden file)
571                            // Treat short alphanumeric suffixes as file extensions
572                            !after_dot.is_empty() && after_dot.len() <= 10 &&
573                            after_dot.chars().all(|c| c.is_ascii_alphanumeric())
574                        } else {
575                            // Hidden file with extension like ".hidden.txt"
576                            path_part.split('.').next_back().is_some_and(|ext| {
577                                !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
578                            })
579                        }
580                    } else {
581                        // Regular file path
582                        path_part.split('.').next_back().is_some_and(|ext| {
583                            !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
584                        })
585                    }
586                } ||
587                // Or contains path separators
588                path_part.contains('/') || path_part.contains('\\') ||
589                // Or starts with relative path indicators
590                path_part.starts_with("./") || path_part.starts_with("../")
591                );
592
593            // Extension-less paths with fragments are potential cross-file links
594            // This supports GitHub-style links like [link](page#section) that resolve to page.md#section
595            let is_extensionless = Self::is_extensionless_path(path_part);
596
597            has_extension || is_extensionless
598        } else {
599            false
600        }
601    }
602
603    /// Whether this document has frontmatter the rule is configured to check.
604    ///
605    /// Gates the body-link early exits, which would otherwise skip a document
606    /// whose only links sit in its frontmatter.
607    fn checks_front_matter_of(&self, ctx: &crate::lint_context::LintContext) -> bool {
608        self.config.check_frontmatter && ctx.front_matter_end_line() > 0
609    }
610
611    /// Frontmatter values that read as link destinations, or nothing when the
612    /// rule is not configured to check frontmatter.
613    fn front_matter_links(&self, ctx: &crate::lint_context::LintContext) -> Vec<frontmatter_values::FrontMatterLink> {
614        if !self.checks_front_matter_of(ctx) {
615            return Vec::new();
616        }
617        frontmatter_values::link_destinations(ctx)
618            .into_iter()
619            .filter(|link| !link.field_is_in(&self.ignored_front_matter_fields))
620            .collect()
621    }
622
623    /// Whether this rule's configuration reports a link written at `origin`.
624    ///
625    /// Applied when reading the workspace index rather than when building it:
626    /// the index holds one entry per file while `check_frontmatter` and
627    /// `ignore_front_matter_fields` resolve per file, so a link is indexed
628    /// wherever it was written and every reader answers for itself.
629    fn reports_link_from(&self, origin: &LinkOrigin) -> bool {
630        match origin {
631            LinkOrigin::Body => true,
632            LinkOrigin::FrontMatter { field } => {
633                self.config.check_frontmatter
634                    && !field
635                        .as_ref()
636                        .is_some_and(|field| self.ignored_front_matter_fields.contains(field))
637            }
638        }
639    }
640
641    /// Whether a fragment is one the flavor or the configuration resolves
642    /// outside the document's own anchors.
643    fn fragment_is_exempt(&self, ctx: &crate::lint_context::LintContext, fragment: &str) -> bool {
644        // MkDocs runtime-generated anchors:
645        // - #fn:NAME, #fnref:NAME from the footnotes extension
646        // - #+key.path or #+key:value from Material for MkDocs option references
647        //   (e.g., #+type:abstract, #+toc.slugify, #+pymdownx.highlight.anchor_linenums)
648        if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
649            && (fragment.starts_with("fn:")
650                || fragment.starts_with("fnref:")
651                || (fragment.starts_with('+') && (fragment.contains('.') || fragment.contains(':'))))
652        {
653            return true;
654        }
655
656        // Fragments matching the user-configured ignored_pattern
657        self.ignored_pattern_regex
658            .as_ref()
659            .is_some_and(|re| re.is_match(fragment))
660    }
661
662    /// Whether a fragment names an anchor this document defines. Both HTML and
663    /// markdown anchors honor the `ignore_case` option, mirroring markdownlint
664    /// and the cross-file path.
665    fn fragment_resolves(&self, fragment: &str, anchors: &AnchorSets) -> bool {
666        if self.config.ignore_case {
667            let lower = fragment.to_lowercase();
668            anchors.html_anchors.contains(&lower) || anchors.markdown_headings.contains(&lower)
669        } else {
670            anchors.html_anchors_exact.contains(fragment) || anchors.markdown_headings_exact.contains(fragment)
671        }
672    }
673
674    /// Report frontmatter fragments that name no anchor in this document.
675    ///
676    /// Only a fragment-only value is resolved here. A value that carries a path
677    /// (`page.md#section`) is a cross-file link: `contribute_to_index` hands it
678    /// to the workspace index and `cross_file_check` resolves it against the
679    /// target file's anchors.
680    fn check_front_matter(
681        &self,
682        ctx: &crate::lint_context::LintContext,
683        links: &[frontmatter_values::FrontMatterLink],
684        anchors: &AnchorSets,
685        warnings: &mut Vec<LintWarning>,
686    ) {
687        for link in links {
688            let line = ctx.lines[link.line - 1].content(ctx.content);
689            let Some(fragment) = line[link.range.clone()].strip_prefix('#') else {
690                continue;
691            };
692            if fragment.is_empty() {
693                continue;
694            }
695
696            // Pandoc and Quarto slugs diverge from GitHub style for headings
697            // that contain punctuation.
698            if ctx.flavor.is_pandoc_compatible() && ctx.has_pandoc_slug(fragment) {
699                continue;
700            }
701
702            if self.fragment_is_exempt(ctx, fragment) || self.fragment_resolves(fragment, anchors) {
703                continue;
704            }
705
706            let column = byte_to_char_count(line, link.range.start);
707            warnings.push(LintWarning {
708                rule_name: Some(self.name().to_string()),
709                message: format!("Link anchor '#{fragment}' does not exist in document headings"),
710                line: link.line,
711                column,
712                end_line: link.line,
713                end_column: column + 1 + fragment.chars().count(),
714                severity: Severity::Error,
715                fix: None,
716            });
717        }
718    }
719}
720
721impl Rule for MD051LinkFragments {
722    fn name(&self) -> &'static str {
723        "MD051"
724    }
725
726    fn description(&self) -> &'static str {
727        "Link fragments should reference valid headings"
728    }
729
730    fn fix_capability(&self) -> FixCapability {
731        FixCapability::Unfixable
732    }
733
734    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
735        // Skip if no link fragments present. A document whose only links sit in
736        // its frontmatter has no link syntax to find, so that shortcut only
737        // applies when frontmatter is not being checked.
738        if !ctx.likely_has_links_or_images() && !self.checks_front_matter_of(ctx) {
739            return true;
740        }
741        // Check for # character (fragments)
742        !ctx.has_char('#')
743    }
744
745    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
746        let mut warnings = Vec::new();
747
748        if ctx.content.is_empty() || self.should_skip(ctx) {
749            return Ok(warnings);
750        }
751
752        let front_matter_links = self.front_matter_links(ctx);
753        if ctx.links().is_empty() && front_matter_links.is_empty() {
754            return Ok(warnings);
755        }
756
757        let anchors = self.extract_headings_from_context(ctx);
758
759        for link in ctx.links() {
760            if link.is_reference {
761                continue;
762            }
763
764            // Skip links inside PyMdown blocks (MkDocs flavor)
765            if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
766                continue;
767            }
768
769            // Skip wiki-links - they reference other files and may have their own fragment validation
770            if matches!(link.link_type, LinkType::WikiLink { .. }) {
771                continue;
772            }
773
774            // Skip links inside Jinja templates
775            if ctx.is_in_jinja_range(link.byte_offset) {
776                continue;
777            }
778
779            // Skip Pandoc/Quarto citations ([@citation], @citation)
780            // Citations are bibliography references, not link fragments
781            if ctx.flavor.is_pandoc_compatible() && ctx.is_in_citation(link.byte_offset) {
782                continue;
783            }
784
785            // Skip links inside shortcodes ({{< ... >}} or {{% ... %}})
786            // Shortcodes may contain template syntax that looks like fragment links
787            if ctx.is_in_shortcode(link.byte_offset) {
788                continue;
789            }
790
791            let url = &link.url;
792
793            // Skip links without fragments or external URLs
794            if !url.contains('#') || Self::is_external_url_fast(url) {
795                continue;
796            }
797
798            // Skip mdbook template placeholders ({{#VARIABLE}})
799            // mdbook uses {{#VARIABLE}} syntax where # is part of the template, not a fragment
800            if url.contains("{{#") && url.contains("}}") {
801                continue;
802            }
803
804            // Resolve link fragments against Pandoc heading slugs. Pandoc/Quarto
805            // auto-generate slugs that diverge from GitHub style for headings that
806            // contain punctuation (e.g. `# 5. Five Things` becomes `5.-five-things`
807            // under Pandoc but `5-five-things` under GitHub). Treat such fragments
808            // as resolved when running under a Pandoc-compatible flavor.
809            if ctx.flavor.is_pandoc_compatible()
810                && let Some(frag) = url.strip_prefix('#')
811                && ctx.has_pandoc_slug(frag)
812            {
813                continue;
814            }
815
816            // Skip Quarto/RMarkdown cross-references (@fig-, @tbl-, @sec-, @eq-, etc.)
817            // These are special cross-reference syntax, not HTML anchors
818            // Format: @prefix-identifier or just @identifier
819            if url.starts_with('@') {
820                continue;
821            }
822
823            // Cross-file links are valid if the file exists (not checked here)
824            if Self::is_cross_file_link(url) {
825                continue;
826            }
827
828            let Some(fragment_pos) = url.find('#') else {
829                continue;
830            };
831
832            let fragment = &url[fragment_pos + 1..];
833
834            // Skip Liquid template variables and filters
835            if (url.contains("{{") && fragment.contains('|')) || fragment.ends_with("}}") || fragment.ends_with("%}") {
836                continue;
837            }
838
839            if fragment.is_empty() {
840                continue;
841            }
842
843            if self.fragment_is_exempt(ctx, fragment) {
844                continue;
845            }
846
847            if !self.fragment_resolves(fragment, &anchors) {
848                warnings.push(LintWarning {
849                    rule_name: Some(self.name().to_string()),
850                    message: format!("Link anchor '#{fragment}' does not exist in document headings"),
851                    line: link.line,
852                    column: link.start_col + 1,
853                    end_line: link.end_line,
854                    end_column: link.end_col + 1,
855                    severity: Severity::Error,
856                    fix: None,
857                });
858            }
859        }
860
861        self.check_front_matter(ctx, &front_matter_links, &anchors, &mut warnings);
862
863        Ok(warnings)
864    }
865
866    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
867        // MD051 does not provide auto-fix
868        // Link fragment corrections require human judgment to avoid incorrect fixes
869        Ok(ctx.content.to_string())
870    }
871
872    fn as_any(&self) -> &dyn std::any::Any {
873        self
874    }
875
876    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
877    where
878        Self: Sized,
879    {
880        let mut rule_config = crate::rule_config_serde::load_rule_config::<MD051Config>(config);
881
882        // When no explicit anchor style is configured (the user didn't override the default),
883        // the style follows the flavor's native anchor generation. The global flavor settles
884        // it here for `rumdl config`; a file `per-file-flavor` gives another flavor re-derives
885        // it in `anchor_style()`.
886        let explicit_style_present = config
887            .rules
888            .get("MD051")
889            .is_some_and(|rc| rc.values.contains_key("anchor-style") || rc.values.contains_key("anchor_style"));
890        if !explicit_style_present {
891            rule_config.anchor_style = AnchorStyle::for_flavor(config.global.flavor);
892        }
893
894        Box::new(MD051LinkFragments::build(
895            rule_config,
896            config.withheld_rule_values.contains("MD051"),
897            explicit_style_present,
898        ))
899    }
900
901    fn category(&self) -> RuleCategory {
902        RuleCategory::Link
903    }
904
905    fn skippable_by_category(&self) -> bool {
906        // A frontmatter fragment is a link this rule resolves, and the document
907        // holding it needs no link syntax anywhere else.
908        !self.config.check_frontmatter
909    }
910
911    fn cross_file_scope(&self) -> CrossFileScope {
912        CrossFileScope::Workspace
913    }
914
915    fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, file_index: &mut FileIndex) {
916        let mut fragment_counts = HashMap::new();
917        let anchor_style = self.anchor_style(ctx);
918        let use_underscore_dedup = anchor_style == AnchorStyle::PythonMarkdown;
919
920        // Extract headings, HTML anchors, and attribute anchors (for other files to reference)
921        for (line_idx, line_info) in ctx.lines.iter().enumerate() {
922            if line_info.in_front_matter {
923                continue;
924            }
925
926            // Skip code blocks for anchor extraction
927            if line_info.in_code_block {
928                continue;
929            }
930
931            let content = line_info.content(ctx.content);
932
933            for_each_html_anchor_target(ctx, line_info, |id| file_index.add_html_anchor(id));
934
935            // Extract attribute anchors { #id } on non-heading lines
936            // Headings already have custom_id extracted via heading.custom_id
937            let parsed_heading = ctx.heading_on_line(line_idx + 1);
938            if parsed_heading.is_none() && content.contains('{') && content.contains('#') {
939                for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
940                    if let Some(id_match) = caps.get(1) {
941                        file_index.add_attribute_anchor(id_match.as_str());
942                    }
943                }
944            }
945
946            // Extract heading anchors, including headings in blockquotes.
947            if let Some(parsed) = parsed_heading {
948                let heading = parsed.heading;
949                let fragment = anchor_style.generate_fragment(&heading.slug_text);
950
951                Self::add_heading_to_index(
952                    &fragment,
953                    &heading.text,
954                    heading.custom_id.clone(),
955                    line_idx + 1,
956                    parsed.is_setext(),
957                    &mut fragment_counts,
958                    file_index,
959                    use_underscore_dedup,
960                );
961
962                // Extract Material for MkDocs setting anchors from headings.
963                // These are rendered as anchors at build time by Material's JS.
964                // Most references use #+key.path format (handled by the skip logic in check()),
965                // but this extraction enables cross-file validation for direct #key.path references.
966                if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
967                    && let Some(caps) = MD_SETTING_PATTERN.captures(content)
968                    && let Some(name) = caps.get(1)
969                {
970                    file_index.add_html_anchor(name.as_str());
971                }
972            }
973        }
974
975        // Extract cross-file links (for validation against other files)
976        for link in ctx.links() {
977            if link.is_reference {
978                continue;
979            }
980
981            // Skip links inside PyMdown blocks (MkDocs flavor)
982            if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
983                continue;
984            }
985
986            // Skip wiki-links - they use a different linking system and are not validated
987            // as relative file paths
988            if matches!(link.link_type, LinkType::WikiLink { .. }) {
989                continue;
990            }
991
992            let url = &link.url;
993
994            // Skip external URLs
995            if Self::is_external_url_fast(url) {
996                continue;
997            }
998
999            // Only process cross-file links with fragments
1000            if Self::is_cross_file_link(url)
1001                && let Some(fragment_pos) = url.find('#')
1002            {
1003                let path_part = &url[..fragment_pos];
1004                let fragment = &url[fragment_pos + 1..];
1005
1006                // Skip empty fragments or template syntax
1007                if fragment.is_empty() || fragment.contains("{{") || fragment.contains("{%") {
1008                    continue;
1009                }
1010
1011                file_index.add_cross_file_link(CrossFileLinkIndex {
1012                    target_path: path_part.to_string(),
1013                    fragment: fragment.to_string(),
1014                    line: link.line,
1015                    column: link.start_col + 1,
1016                    origin: LinkOrigin::Body,
1017                });
1018            }
1019        }
1020
1021        // Extract cross-file links from frontmatter values that carry a
1022        // fragment. Deliberately not filtered by `check_frontmatter` or
1023        // `ignore_front_matter_fields`: the index is shared by a whole
1024        // workspace whose files can resolve different configurations, so each
1025        // link is recorded with where it was written and `cross_file_check`
1026        // decides what to report.
1027        for link in frontmatter_values::link_destinations(ctx) {
1028            let line = ctx.lines[link.line - 1].content(ctx.content);
1029            let value = &line[link.range.clone()];
1030
1031            if Self::is_external_url_fast(value) || !Self::is_cross_file_link(value) {
1032                continue;
1033            }
1034
1035            let Some(fragment_pos) = value.find('#') else {
1036                continue;
1037            };
1038            let path_part = &value[..fragment_pos];
1039            let fragment = &value[fragment_pos + 1..];
1040
1041            // Skip empty fragments or template syntax
1042            if fragment.is_empty() || fragment.contains("{{") || fragment.contains("{%") {
1043                continue;
1044            }
1045
1046            file_index.add_cross_file_link(CrossFileLinkIndex {
1047                target_path: path_part.to_string(),
1048                fragment: fragment.to_string(),
1049                line: link.line,
1050                column: byte_to_char_count(line, link.range.start),
1051                origin: LinkOrigin::FrontMatter { field: link.field },
1052            });
1053        }
1054    }
1055
1056    fn cross_file_check(
1057        &self,
1058        file_path: &Path,
1059        file_index: &FileIndex,
1060        workspace_index: &crate::workspace_index::WorkspaceIndex,
1061    ) -> LintResult {
1062        let mut warnings = Vec::new();
1063
1064        let ignored_pattern = self.ignored_pattern_regex.as_ref();
1065        let ignore_case = self.config.ignore_case;
1066
1067        // Check each cross-file link in this file
1068        for cross_link in &file_index.cross_file_links {
1069            // Skip cross-file links without fragments - nothing to validate
1070            if cross_link.fragment.is_empty() {
1071                continue;
1072            }
1073
1074            // The index records every link; this file's own configuration
1075            // decides which of them it reports.
1076            if !self.reports_link_from(&cross_link.origin) {
1077                continue;
1078            }
1079
1080            // Honor `ignored-pattern`: skip fragments matching the configured regex.
1081            if ignored_pattern.is_some_and(|re| re.is_match(&cross_link.fragment)) {
1082                continue;
1083            }
1084
1085            // The message keeps the destination as written; the lookup uses the
1086            // file the link names.
1087            let target_paths_to_try =
1088                crate::workspace_index::link_target_candidates(file_path, &cross_link.target_path);
1089
1090            // Try to find the target file in the workspace index
1091            let mut target_file_index = None;
1092
1093            for target_path in &target_paths_to_try {
1094                if let Some(index) = workspace_index.get_file(target_path) {
1095                    target_file_index = Some(index);
1096                    break;
1097                }
1098            }
1099
1100            if let Some(target_file_index) = target_file_index {
1101                // Check if the fragment matches any heading in the target file (O(1) lookup)
1102                if !target_file_index.has_anchor_with_case(&cross_link.fragment, ignore_case) {
1103                    warnings.push(LintWarning {
1104                        rule_name: Some(self.name().to_string()),
1105                        line: cross_link.line,
1106                        column: cross_link.column,
1107                        end_line: cross_link.line,
1108                        end_column: cross_link.column
1109                            + cross_link.target_path.chars().count()
1110                            + 1
1111                            + cross_link.fragment.chars().count(),
1112                        message: format!(
1113                            "Link fragment '{}' not found in '{}'",
1114                            cross_link.fragment, cross_link.target_path
1115                        ),
1116                        severity: Severity::Error,
1117                        fix: None,
1118                    });
1119                }
1120            }
1121            // If target file not in index, skip (could be external file or not in workspace)
1122        }
1123
1124        Ok(warnings)
1125    }
1126
1127    crate::impl_rule_config_sections!(MD051Config);
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132    use super::*;
1133    use crate::lint_context::LintContext;
1134    use std::path::PathBuf;
1135
1136    /// An em dash collapses to one hyphen under Python-Markdown and to nothing
1137    /// (leaving both surrounding spaces as hyphens) under GitHub, so exactly one
1138    /// of these two links is invalid and which one names the style in force.
1139    const ANCHOR_STYLE_PROBE: &str = "### Getting Started — Advanced\n\n\
1140        [python-markdown slug](#getting-started-advanced)\n\
1141        [github slug](#getting-started--advanced)\n";
1142
1143    fn flagged_fragment(rule: &dyn Rule, flavor: crate::config::MarkdownFlavor) -> String {
1144        let ctx = LintContext::new(ANCHOR_STYLE_PROBE, flavor, None);
1145        let warnings = rule.check(&ctx).unwrap();
1146        assert_eq!(
1147            warnings.len(),
1148            1,
1149            "exactly one of the two links must be invalid under any style: {warnings:?}"
1150        );
1151        warnings[0].message.clone()
1152    }
1153
1154    /// An unpinned anchor style follows the flavor of the file being checked,
1155    /// not the global flavor the rule was constructed with. `per-file-flavor`
1156    /// makes those differ, and the style is decided per file.
1157    #[test]
1158    fn test_unpinned_anchor_style_follows_the_file_flavor() {
1159        let rule_from_global = |flavor| {
1160            let mut config = crate::config::Config::default();
1161            config.global.flavor = flavor;
1162            MD051LinkFragments::from_config(&config)
1163        };
1164
1165        // Global standard: construction settles on GitHub anchors.
1166        let standard_global = rule_from_global(crate::config::MarkdownFlavor::Standard);
1167        // A file the global flavor applies to keeps them, so the Python-Markdown
1168        // slug is the one that does not exist.
1169        assert!(
1170            flagged_fragment(standard_global.as_ref(), crate::config::MarkdownFlavor::Standard)
1171                .contains("#getting-started-advanced'"),
1172            "a standard file must be checked against GitHub anchors"
1173        );
1174        // A file `per-file-flavor` parses as MkDocs is checked against
1175        // Python-Markdown anchors, so the GitHub slug is the missing one.
1176        assert!(
1177            flagged_fragment(standard_global.as_ref(), crate::config::MarkdownFlavor::MkDocs)
1178                .contains("#getting-started--advanced'"),
1179            "a mkdocs file must be checked against Python-Markdown anchors even under a standard global flavor"
1180        );
1181
1182        // The same in reverse: a standard file under a MkDocs global flavor.
1183        let mkdocs_global = rule_from_global(crate::config::MarkdownFlavor::MkDocs);
1184        assert!(
1185            flagged_fragment(mkdocs_global.as_ref(), crate::config::MarkdownFlavor::MkDocs)
1186                .contains("#getting-started--advanced'"),
1187            "a mkdocs file must be checked against Python-Markdown anchors"
1188        );
1189        assert!(
1190            flagged_fragment(mkdocs_global.as_ref(), crate::config::MarkdownFlavor::Standard)
1191                .contains("#getting-started-advanced'"),
1192            "a standard file must be checked against GitHub anchors even under a mkdocs global flavor"
1193        );
1194    }
1195
1196    /// Control for the above: a style the user pinned is theirs, and applies to
1197    /// every file whatever flavor it is parsed with.
1198    #[test]
1199    fn test_pinned_anchor_style_ignores_the_file_flavor() {
1200        let mut config = crate::config::Config::default();
1201        config.global.flavor = crate::config::MarkdownFlavor::Standard;
1202        let mut rule_config = crate::config::RuleConfig::default();
1203        rule_config
1204            .values
1205            .insert("anchor-style".to_string(), toml::Value::String("github".to_string()));
1206        config.rules.insert("MD051".to_string(), rule_config);
1207        let rule = MD051LinkFragments::from_config(&config);
1208
1209        for flavor in [
1210            crate::config::MarkdownFlavor::Standard,
1211            crate::config::MarkdownFlavor::MkDocs,
1212            crate::config::MarkdownFlavor::Kramdown,
1213        ] {
1214            assert!(
1215                flagged_fragment(rule.as_ref(), flavor).contains("#getting-started-advanced'"),
1216                "pinned github anchors must survive a {flavor:?} file"
1217            );
1218        }
1219    }
1220
1221    /// Directly constructed rules are pinned: nothing derived their style from a
1222    /// flavor, so there is nothing to re-derive.
1223    #[test]
1224    fn test_directly_constructed_rule_keeps_its_anchor_style() {
1225        let rule = MD051LinkFragments::from_config_struct(MD051Config {
1226            anchor_style: AnchorStyle::PythonMarkdown,
1227            ..Default::default()
1228        });
1229        assert!(
1230            flagged_fragment(&rule, crate::config::MarkdownFlavor::Standard).contains("#getting-started--advanced'"),
1231            "an explicitly constructed Python-Markdown rule must not follow the file flavor"
1232        );
1233    }
1234
1235    #[test]
1236    fn test_quarto_cross_references() {
1237        let rule = MD051LinkFragments::new();
1238
1239        // Test that Quarto cross-references are skipped
1240        let content = r#"# Test Document
1241
1242## Figures
1243
1244See [@fig-plot] for the visualization.
1245
1246More details in [@tbl-results] and [@sec-methods].
1247
1248The equation [@eq-regression] shows the relationship.
1249
1250Reference to [@lst-code] for implementation."#;
1251        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
1252        let result = rule.check(&ctx).unwrap();
1253        assert!(
1254            result.is_empty(),
1255            "Quarto cross-references (@fig-, @tbl-, @sec-, @eq-) should not trigger MD051 warnings. Got {} warnings",
1256            result.len()
1257        );
1258
1259        // Test that normal anchors still work
1260        let content_with_anchor = r#"# Test
1261
1262See [link](#test) for details."#;
1263        let ctx_anchor = LintContext::new(content_with_anchor, crate::config::MarkdownFlavor::Quarto, None);
1264        let result_anchor = rule.check(&ctx_anchor).unwrap();
1265        assert!(result_anchor.is_empty(), "Valid anchor should not trigger warning");
1266
1267        // Test that invalid anchors are still flagged
1268        let content_invalid = r#"# Test
1269
1270See [link](#nonexistent) for details."#;
1271        let ctx_invalid = LintContext::new(content_invalid, crate::config::MarkdownFlavor::Quarto, None);
1272        let result_invalid = rule.check(&ctx_invalid).unwrap();
1273        assert_eq!(result_invalid.len(), 1, "Invalid anchor should still trigger warning");
1274    }
1275
1276    #[test]
1277    fn test_jsx_in_heading_anchor() {
1278        // Issue #510: JSX/HTML tags in headings should be stripped for anchor generation
1279        let rule = MD051LinkFragments::new();
1280
1281        // Self-closing JSX tag
1282        let content = "# Test\n\n### `retentionPolicy`<Component />\n\n[link](#retentionpolicy)\n";
1283        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1284        let result = rule.check(&ctx).unwrap();
1285        assert!(
1286            result.is_empty(),
1287            "JSX self-closing tag should be stripped from anchor: got {result:?}"
1288        );
1289
1290        // JSX with attributes
1291        let content2 =
1292            "### retentionPolicy<HeaderTag type=\"danger\" text=\"required\" />\n\n[link](#retentionpolicy)\n";
1293        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1294        let result2 = rule.check(&ctx2).unwrap();
1295        assert!(
1296            result2.is_empty(),
1297            "JSX tag with attributes should be stripped from anchor: got {result2:?}"
1298        );
1299
1300        // HTML tags with inner text preserved
1301        let content3 = "### Test <span>extra</span>\n\n[link](#test-extra)\n";
1302        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
1303        let result3 = rule.check(&ctx3).unwrap();
1304        assert!(
1305            result3.is_empty(),
1306            "HTML tag content should be preserved in anchor: got {result3:?}"
1307        );
1308    }
1309
1310    // Cross-file validation tests
1311    #[test]
1312    fn test_cross_file_scope() {
1313        let rule = MD051LinkFragments::new();
1314        assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
1315    }
1316
1317    #[test]
1318    fn test_contribute_to_index_extracts_headings() {
1319        let rule = MD051LinkFragments::new();
1320        let content = "# First Heading\n\n# Second { #custom }\n\n## Third";
1321        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1322
1323        let mut file_index = FileIndex::new();
1324        rule.contribute_to_index(&ctx, &mut file_index);
1325
1326        assert_eq!(file_index.headings.len(), 3);
1327        assert_eq!(file_index.headings[0].text, "First Heading");
1328        assert_eq!(file_index.headings[0].auto_anchor, "first-heading");
1329        assert!(file_index.headings[0].custom_anchor.is_none());
1330
1331        assert_eq!(file_index.headings[1].text, "Second");
1332        assert_eq!(file_index.headings[1].custom_anchor, Some("custom".to_string()));
1333
1334        assert_eq!(file_index.headings[2].text, "Third");
1335    }
1336
1337    #[test]
1338    fn test_contribute_to_index_extracts_cross_file_links() {
1339        let rule = MD051LinkFragments::new();
1340        let content = "See [docs](other.md#installation) and [more](../guide.md#getting-started)";
1341        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1342
1343        let mut file_index = FileIndex::new();
1344        rule.contribute_to_index(&ctx, &mut file_index);
1345
1346        assert_eq!(file_index.cross_file_links.len(), 2);
1347        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
1348        assert_eq!(file_index.cross_file_links[0].fragment, "installation");
1349        assert_eq!(file_index.cross_file_links[1].target_path, "../guide.md");
1350        assert_eq!(file_index.cross_file_links[1].fragment, "getting-started");
1351    }
1352
1353    /// The LSP locates a heading's text from `is_setext`, since a Setext heading
1354    /// has no `#` markers to skip past. Reporting every heading as ATX puts rename
1355    /// and prepare-rename on the wrong span.
1356    #[test]
1357    fn test_contribute_to_index_records_setext_headings() {
1358        let rule = MD051LinkFragments::new();
1359        let content = "Setext One\n==========\n\nSetext Two\n----------\n\n### Atx Three\n";
1360        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1361
1362        let mut file_index = FileIndex::new();
1363        rule.contribute_to_index(&ctx, &mut file_index);
1364
1365        let styles: Vec<(&str, bool)> = file_index
1366            .headings
1367            .iter()
1368            .map(|h| (h.text.as_str(), h.is_setext))
1369            .collect();
1370        assert_eq!(
1371            styles,
1372            vec![("Setext One", true), ("Setext Two", true), ("Atx Three", false)]
1373        );
1374    }
1375
1376    /// The workspace index holds one entry per file while `check-frontmatter`
1377    /// resolves per file, so a frontmatter link is indexed however the indexing
1378    /// file was configured and the reading file's own settings decide whether
1379    /// to report it. Indexing it conditionally instead makes the answer depend
1380    /// on which configuration happened to build the index: with the rule
1381    /// disabled it hides a real broken link, and with it enabled it reports one
1382    /// in a file configured not to check frontmatter.
1383    #[test]
1384    fn test_a_frontmatter_link_is_indexed_regardless_of_the_indexing_config() {
1385        let content = "---\nlink: 'other.md#nope'\n---\n\n# Real\n";
1386        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1387
1388        for check_frontmatter in [true, false] {
1389            let rule = MD051LinkFragments::from_config_struct(MD051Config {
1390                check_frontmatter,
1391                ..Default::default()
1392            });
1393            let mut file_index = FileIndex::new();
1394            rule.contribute_to_index(&ctx, &mut file_index);
1395
1396            assert_eq!(
1397                file_index.cross_file_links.len(),
1398                1,
1399                "check_frontmatter = {check_frontmatter} changed what was indexed"
1400            );
1401            assert_eq!(
1402                file_index.cross_file_links[0].origin,
1403                LinkOrigin::FrontMatter {
1404                    field: Some("link".to_string())
1405                },
1406            );
1407        }
1408    }
1409
1410    /// The other half of the same seam: a frontmatter link the index always
1411    /// carries is reported only by a file configured to check frontmatter, and
1412    /// `ignore-frontmatter-fields` excludes it by the field recorded with it.
1413    #[test]
1414    fn test_cross_file_check_applies_this_files_frontmatter_config() {
1415        use crate::workspace_index::WorkspaceIndex;
1416
1417        let mut workspace_index = WorkspaceIndex::new();
1418        let mut target = FileIndex::new();
1419        target.add_heading(HeadingIndex {
1420            text: "Real".to_string(),
1421            auto_anchor: "real".to_string(),
1422            custom_anchor: None,
1423            line: 1,
1424            is_setext: false,
1425        });
1426        workspace_index.insert_file(PathBuf::from("docs/other.md"), target);
1427
1428        let mut file_index = FileIndex::new();
1429        file_index.add_cross_file_link(CrossFileLinkIndex {
1430            target_path: "other.md".to_string(),
1431            fragment: "nope".to_string(),
1432            line: 2,
1433            column: 7,
1434            origin: LinkOrigin::FrontMatter {
1435                field: Some("link".to_string()),
1436            },
1437        });
1438        // The positive control: a body link to the same missing anchor is
1439        // reported under every configuration below, so a zero above is the
1440        // frontmatter filter and not an index or path-resolution failure.
1441        file_index.add_cross_file_link(CrossFileLinkIndex {
1442            target_path: "other.md".to_string(),
1443            fragment: "nope".to_string(),
1444            line: 6,
1445            column: 5,
1446            origin: LinkOrigin::Body,
1447        });
1448
1449        let count = |config: MD051Config| {
1450            MD051LinkFragments::from_config_struct(config)
1451                .cross_file_check(Path::new("docs/readme.md"), &file_index, &workspace_index)
1452                .unwrap()
1453                .len()
1454        };
1455
1456        assert_eq!(
1457            count(MD051Config {
1458                check_frontmatter: true,
1459                ..Default::default()
1460            }),
1461            2,
1462            "checking frontmatter should report both the frontmatter and body links"
1463        );
1464        assert_eq!(
1465            count(MD051Config {
1466                check_frontmatter: false,
1467                ..Default::default()
1468            }),
1469            1,
1470            "not checking frontmatter should leave only the body link"
1471        );
1472        assert_eq!(
1473            count(MD051Config {
1474                check_frontmatter: true,
1475                ignore_frontmatter_fields: vec!["LINK".to_string()],
1476                ..Default::default()
1477            }),
1478            1,
1479            "an ignored field should be matched case-insensitively"
1480        );
1481    }
1482
1483    #[test]
1484    fn test_cross_file_check_valid_fragment() {
1485        use crate::workspace_index::WorkspaceIndex;
1486
1487        let rule = MD051LinkFragments::new();
1488
1489        // Build workspace index with target file
1490        let mut workspace_index = WorkspaceIndex::new();
1491        let mut target_file_index = FileIndex::new();
1492        target_file_index.add_heading(HeadingIndex {
1493            text: "Installation Guide".to_string(),
1494            auto_anchor: "installation-guide".to_string(),
1495            custom_anchor: None,
1496            line: 1,
1497            is_setext: false,
1498        });
1499        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1500
1501        // Create a FileIndex for the file being checked
1502        let mut current_file_index = FileIndex::new();
1503        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1504            target_path: "install.md".to_string(),
1505            fragment: "installation-guide".to_string(),
1506            line: 3,
1507            column: 5,
1508            origin: LinkOrigin::Body,
1509        });
1510
1511        let warnings = rule
1512            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1513            .unwrap();
1514
1515        // Should find no warnings since fragment exists
1516        assert!(warnings.is_empty());
1517    }
1518
1519    #[test]
1520    fn test_cross_file_check_invalid_fragment() {
1521        use crate::workspace_index::WorkspaceIndex;
1522
1523        let rule = MD051LinkFragments::new();
1524
1525        // Build workspace index with target file
1526        let mut workspace_index = WorkspaceIndex::new();
1527        let mut target_file_index = FileIndex::new();
1528        target_file_index.add_heading(HeadingIndex {
1529            text: "Installation Guide".to_string(),
1530            auto_anchor: "installation-guide".to_string(),
1531            custom_anchor: None,
1532            line: 1,
1533            is_setext: false,
1534        });
1535        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1536
1537        // Create a FileIndex with a cross-file link pointing to non-existent fragment
1538        let mut current_file_index = FileIndex::new();
1539        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1540            target_path: "install.md".to_string(),
1541            fragment: "nonexistent".to_string(),
1542            line: 3,
1543            column: 5,
1544            origin: LinkOrigin::Body,
1545        });
1546
1547        let warnings = rule
1548            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1549            .unwrap();
1550
1551        // Should find one warning since fragment doesn't exist
1552        assert_eq!(warnings.len(), 1);
1553        assert!(warnings[0].message.contains("nonexistent"));
1554        assert!(warnings[0].message.contains("install.md"));
1555    }
1556
1557    #[test]
1558    fn test_cross_file_check_custom_anchor_match() {
1559        use crate::workspace_index::WorkspaceIndex;
1560
1561        let rule = MD051LinkFragments::new();
1562
1563        // Build workspace index with target file that has custom anchor
1564        let mut workspace_index = WorkspaceIndex::new();
1565        let mut target_file_index = FileIndex::new();
1566        target_file_index.add_heading(HeadingIndex {
1567            text: "Installation Guide".to_string(),
1568            auto_anchor: "installation-guide".to_string(),
1569            custom_anchor: Some("install".to_string()),
1570            line: 1,
1571            is_setext: false,
1572        });
1573        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1574
1575        // Link uses custom anchor
1576        let mut current_file_index = FileIndex::new();
1577        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1578            target_path: "install.md".to_string(),
1579            fragment: "install".to_string(),
1580            line: 3,
1581            column: 5,
1582            origin: LinkOrigin::Body,
1583        });
1584
1585        let warnings = rule
1586            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1587            .unwrap();
1588
1589        // Should find no warnings since custom anchor matches
1590        assert!(warnings.is_empty());
1591    }
1592
1593    #[test]
1594    fn test_cross_file_check_target_not_in_workspace() {
1595        use crate::workspace_index::WorkspaceIndex;
1596
1597        let rule = MD051LinkFragments::new();
1598
1599        // Empty workspace index
1600        let workspace_index = WorkspaceIndex::new();
1601
1602        // Link to file not in workspace
1603        let mut current_file_index = FileIndex::new();
1604        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1605            target_path: "external.md".to_string(),
1606            fragment: "heading".to_string(),
1607            line: 3,
1608            column: 5,
1609            origin: LinkOrigin::Body,
1610        });
1611
1612        let warnings = rule
1613            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1614            .unwrap();
1615
1616        // Should not warn about files not in workspace
1617        assert!(warnings.is_empty());
1618    }
1619
1620    #[test]
1621    fn test_wikilinks_skipped_in_check() {
1622        // Wikilinks should not trigger MD051 warnings for missing fragments
1623        let rule = MD051LinkFragments::new();
1624
1625        let content = r#"# Test Document
1626
1627## Valid Heading
1628
1629[[Microsoft#Windows OS]]
1630[[SomePage#section]]
1631[[page|Display Text]]
1632[[path/to/page#section]]
1633"#;
1634        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1635        let result = rule.check(&ctx).unwrap();
1636
1637        assert!(
1638            result.is_empty(),
1639            "Wikilinks should not trigger MD051 warnings. Got: {result:?}"
1640        );
1641    }
1642
1643    #[test]
1644    fn test_wikilinks_not_added_to_cross_file_index() {
1645        // Wikilinks should not be added to the cross-file link index
1646        let rule = MD051LinkFragments::new();
1647
1648        let content = r#"# Test Document
1649
1650[[Microsoft#Windows OS]]
1651[[SomePage#section]]
1652[Regular Link](other.md#section)
1653"#;
1654        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1655
1656        let mut file_index = FileIndex::new();
1657        rule.contribute_to_index(&ctx, &mut file_index);
1658
1659        // Should only have one cross-file link (the regular markdown link)
1660        // Wikilinks should not be added
1661        let cross_file_links = &file_index.cross_file_links;
1662        assert_eq!(
1663            cross_file_links.len(),
1664            1,
1665            "Only regular markdown links should be indexed, not wikilinks. Got: {cross_file_links:?}"
1666        );
1667        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
1668        assert_eq!(file_index.cross_file_links[0].fragment, "section");
1669    }
1670
1671    #[test]
1672    fn test_pandoc_flavor_skips_citations() {
1673        // Pandoc citations ([@key]) are bibliography references, not link fragments.
1674        // MD051 should skip them under Pandoc flavor, mirroring the Quarto skip behavior
1675        // tested in test_quarto_cross_references.
1676        let rule = MD051LinkFragments::new();
1677        let content = "# Test Document\n\nSee [@smith2020] for details.\n";
1678        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1679        let result = rule.check(&ctx).unwrap();
1680        assert!(
1681            result.is_empty(),
1682            "MD051 should skip Pandoc citations under Pandoc flavor: {result:?}"
1683        );
1684    }
1685
1686    #[test]
1687    fn md051_pandoc_resolves_pandoc_slug_diverging_from_github() {
1688        // The Pandoc heading slug for `# 5. Five Things` is `5.-five-things` (the
1689        // dot is preserved per Pandoc's rule of keeping `.`/`_`/`-`), whereas the
1690        // GitHub anchor for the same heading is `5-five-things` (the dot is
1691        // stripped). A link to `#5.-five-things` would be flagged under the
1692        // GitHub default but must be accepted under Pandoc-compatible flavors via
1693        // the `has_pandoc_slug` short-circuit.
1694        use crate::config::MarkdownFlavor;
1695        let rule = MD051LinkFragments::new();
1696        let content = "# 5. Five Things\n\nSee [details](#5.-five-things).\n";
1697
1698        // Sanity check: under Standard flavor (GitHub anchor style), the
1699        // divergent fragment is reported as an unknown anchor.
1700        let ctx_std = LintContext::new(content, MarkdownFlavor::Standard, None);
1701        let std_result = rule.check(&ctx_std).unwrap();
1702        assert_eq!(
1703            std_result.len(),
1704            1,
1705            "Standard flavor should flag the Pandoc-style fragment: {std_result:?}"
1706        );
1707
1708        // Under Pandoc flavor, the Pandoc slug guard should resolve it.
1709        let ctx_pandoc = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1710        let pandoc_result = rule.check(&ctx_pandoc).unwrap();
1711        assert!(
1712            pandoc_result.is_empty(),
1713            "Pandoc flavor should resolve `#5.-five-things` against the heading slug: {pandoc_result:?}"
1714        );
1715    }
1716
1717    /// A link whose text contains an email address must still be checked under
1718    /// Pandoc — the `@` embedded in a word is not a citation marker, so the
1719    /// citation guard must not silence MD051 on a missing fragment.
1720    #[test]
1721    fn md051_pandoc_flags_missing_fragment_with_email_in_link_text() {
1722        use crate::config::MarkdownFlavor;
1723        let rule = MD051LinkFragments::new();
1724        let content = "# Title\n\n[contact user@example.com](#missing)\n";
1725
1726        let ctx_std = LintContext::new(content, MarkdownFlavor::Standard, None);
1727        let std_result = rule.check(&ctx_std).unwrap();
1728        assert_eq!(
1729            std_result.len(),
1730            1,
1731            "Standard flavor must flag the missing fragment: {std_result:?}"
1732        );
1733
1734        let ctx_pandoc = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1735        let pandoc_result = rule.check(&ctx_pandoc).unwrap();
1736        assert_eq!(
1737            pandoc_result.len(),
1738            1,
1739            "Pandoc flavor must also flag the missing fragment — link text with embedded email is not a citation: {pandoc_result:?}"
1740        );
1741    }
1742
1743    /// `[see @smith2020](#missing)` is a Markdown link, not a citation —
1744    /// Pandoc prefers the link interpretation when `[...]` is immediately
1745    /// followed by `(...)`. MD051 must still flag the missing fragment.
1746    #[test]
1747    fn md051_pandoc_flags_missing_fragment_with_citation_in_link_text() {
1748        use crate::config::MarkdownFlavor;
1749        let rule = MD051LinkFragments::new();
1750        let content = "# Title\n\n[see @smith2020](#missing)\n";
1751
1752        let ctx_std = LintContext::new(content, MarkdownFlavor::Standard, None);
1753        let std_result = rule.check(&ctx_std).unwrap();
1754        assert_eq!(
1755            std_result.len(),
1756            1,
1757            "Standard flavor must flag the missing fragment: {std_result:?}"
1758        );
1759
1760        let ctx_pandoc = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1761        let pandoc_result = rule.check(&ctx_pandoc).unwrap();
1762        assert_eq!(
1763            pandoc_result.len(),
1764            1,
1765            "Pandoc flavor must flag the missing fragment — `[label](url)` is a link, not a citation: {pandoc_result:?}"
1766        );
1767    }
1768
1769    /// Pandoc's auto_identifiers extension disambiguates duplicate headings by
1770    /// appending `-1`, `-2`, etc. A link to `#a.-1` must resolve against the
1771    /// second `# A.` heading.
1772    #[test]
1773    fn md051_pandoc_resolves_duplicate_heading_suffix_slug() {
1774        use crate::config::MarkdownFlavor;
1775        let rule = MD051LinkFragments::new();
1776        let content = "# A.\n\nfirst\n\n# A.\n\nsecond\n\n[first](#a.) and [second](#a.-1).\n";
1777
1778        let ctx_pandoc = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1779        let pandoc_result = rule.check(&ctx_pandoc).unwrap();
1780        assert!(
1781            pandoc_result.is_empty(),
1782            "Pandoc flavor should resolve `#a.` and `#a.-1` against duplicate headings: {pandoc_result:?}"
1783        );
1784
1785        let ctx_quarto = LintContext::new(content, MarkdownFlavor::Quarto, None);
1786        let quarto_result = rule.check(&ctx_quarto).unwrap();
1787        assert!(
1788            quarto_result.is_empty(),
1789            "Quarto flavor should also resolve duplicate-heading suffix slugs: {quarto_result:?}"
1790        );
1791    }
1792
1793    /// A link to `#a.-2` with only two `# A.` headings must still be flagged —
1794    /// only `-1` exists when there are two duplicates.
1795    #[test]
1796    fn md051_pandoc_flags_overshoot_duplicate_suffix() {
1797        use crate::config::MarkdownFlavor;
1798        let rule = MD051LinkFragments::new();
1799        let content = "# A.\n\n# A.\n\n[overshoot](#a.-2)\n";
1800
1801        let ctx_pandoc = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1802        let pandoc_result = rule.check(&ctx_pandoc).unwrap();
1803        assert_eq!(
1804            pandoc_result.len(),
1805            1,
1806            "Pandoc must flag `#a.-2` when only `-1` exists (two duplicates): {pandoc_result:?}"
1807        );
1808    }
1809
1810    fn front_matter_checked() -> MD051Config {
1811        MD051Config {
1812            check_frontmatter: true,
1813            ..MD051Config::default()
1814        }
1815    }
1816
1817    fn check_front_matter(content: &str, config: MD051Config) -> Vec<LintWarning> {
1818        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1819        MD051LinkFragments::from_config_struct(config).check(&ctx).unwrap()
1820    }
1821
1822    #[test]
1823    fn a_broken_frontmatter_fragment_is_reported_when_enabled() {
1824        let content = "---\nanchor: '#missing'\nvalid: '#title'\n---\n\n# Title\n";
1825        let result = check_front_matter(content, front_matter_checked());
1826
1827        assert_eq!(
1828            result.len(),
1829            1,
1830            "Only the unresolved fragment is reported. Got: {result:?}"
1831        );
1832        assert_eq!(
1833            result[0].message,
1834            "Link anchor '#missing' does not exist in document headings"
1835        );
1836        assert_eq!(result[0].line, 2);
1837        assert_eq!(result[0].column, 10, "The warning points at the value, not the key");
1838        assert_eq!(result[0].end_column, 18);
1839    }
1840
1841    #[test]
1842    fn frontmatter_fragments_are_not_checked_by_default() {
1843        let content = "---\nanchor: '#missing'\n---\n\n# Title\n";
1844        let result = check_front_matter(content, MD051Config::default());
1845
1846        assert!(
1847            result.is_empty(),
1848            "Frontmatter is only checked on request. Got: {result:?}"
1849        );
1850    }
1851
1852    #[test]
1853    fn an_ignored_frontmatter_field_is_not_checked() {
1854        let content = "---\nhero: '#missing'\nanchor: '#other'\n---\n\n# Title\n";
1855        let config = MD051Config {
1856            check_frontmatter: true,
1857            ignore_frontmatter_fields: vec!["Hero".to_string()],
1858            ..MD051Config::default()
1859        };
1860        let result = check_front_matter(content, config);
1861
1862        assert_eq!(
1863            result.len(),
1864            1,
1865            "The ignored field is skipped and the other is not. Got: {result:?}"
1866        );
1867        assert_eq!(result[0].line, 3);
1868    }
1869
1870    #[test]
1871    fn the_ignored_pattern_applies_to_frontmatter_fragments() {
1872        let content = "---\nnote: '#fn:1'\nanchor: '#missing'\n---\n\n# Title\n";
1873        let config = MD051Config {
1874            check_frontmatter: true,
1875            ignored_pattern: Some("^fn:".to_string()),
1876            ..MD051Config::default()
1877        };
1878        let result = check_front_matter(content, config);
1879
1880        assert_eq!(
1881            result.len(),
1882            1,
1883            "The matching fragment is skipped and the other is not. Got: {result:?}"
1884        );
1885        assert_eq!(result[0].line, 3);
1886    }
1887
1888    #[test]
1889    fn a_frontmatter_fragment_honors_ignore_case() {
1890        let content = "---\nanchor: '#Title'\n---\n\n# Title\n";
1891
1892        let permissive = check_front_matter(content, front_matter_checked());
1893        assert!(
1894            permissive.is_empty(),
1895            "The default resolves a case mismatch. Got: {permissive:?}"
1896        );
1897
1898        let strict = check_front_matter(
1899            content,
1900            MD051Config {
1901                check_frontmatter: true,
1902                ignore_case: false,
1903                ..MD051Config::default()
1904            },
1905        );
1906        assert_eq!(strict.len(), 1, "Strict matching reports it. Got: {strict:?}");
1907    }
1908
1909    #[test]
1910    fn prose_in_frontmatter_is_not_read_as_a_fragment() {
1911        let content = "---\ntitle: Node.js\ntags: ci/cd\n---\n\n# Title\n";
1912        let result = check_front_matter(content, front_matter_checked());
1913
1914        assert!(
1915            result.is_empty(),
1916            "Only path-shaped values are destinations. Got: {result:?}"
1917        );
1918    }
1919
1920    #[test]
1921    fn a_frontmatter_path_with_a_fragment_is_validated_across_files() {
1922        let rule = MD051LinkFragments::from_config_struct(front_matter_checked());
1923        let source = "---\ntemplate: other.md#missing\nvalid: other.md#target\n---\n\n# Source\n";
1924
1925        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
1926        let mut source_index = FileIndex::default();
1927        rule.contribute_to_index(&source_ctx, &mut source_index);
1928
1929        let target_ctx = LintContext::new("# Target\n", crate::config::MarkdownFlavor::Standard, None);
1930        let mut target_index = FileIndex::default();
1931        rule.contribute_to_index(&target_ctx, &mut target_index);
1932
1933        let source_path = PathBuf::from("docs/source.md");
1934        let mut workspace = crate::workspace_index::WorkspaceIndex::new();
1935        workspace.insert_file(source_path.clone(), source_index.clone());
1936        workspace.insert_file(PathBuf::from("docs/other.md"), target_index);
1937
1938        let warnings = rule.cross_file_check(&source_path, &source_index, &workspace).unwrap();
1939
1940        assert_eq!(
1941            warnings.len(),
1942            1,
1943            "Only the unresolved fragment is reported. Got: {warnings:?}"
1944        );
1945        assert_eq!(warnings[0].message, "Link fragment 'missing' not found in 'other.md'");
1946        assert_eq!(warnings[0].line, 2);
1947        assert_eq!(warnings[0].column, 11);
1948    }
1949
1950    #[test]
1951    fn a_query_string_does_not_hide_the_target_file() {
1952        let rule = MD051LinkFragments::new();
1953        let source = "# Source\n\n- [a](other.md?raw=true#missing)\n- [b](other.md?raw=true#target)\n";
1954
1955        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
1956        let mut source_index = FileIndex::default();
1957        rule.contribute_to_index(&source_ctx, &mut source_index);
1958
1959        let target_ctx = LintContext::new("# Target\n", crate::config::MarkdownFlavor::Standard, None);
1960        let mut target_index = FileIndex::default();
1961        rule.contribute_to_index(&target_ctx, &mut target_index);
1962
1963        let source_path = PathBuf::from("docs/source.md");
1964        let mut workspace = crate::workspace_index::WorkspaceIndex::new();
1965        workspace.insert_file(source_path.clone(), source_index.clone());
1966        workspace.insert_file(PathBuf::from("docs/other.md"), target_index);
1967
1968        let warnings = rule.cross_file_check(&source_path, &source_index, &workspace).unwrap();
1969
1970        assert_eq!(
1971            warnings.len(),
1972            1,
1973            "The query is stripped to find the file, so both fragments resolve against it. Got: {warnings:?}"
1974        );
1975        assert_eq!(
1976            warnings[0].message,
1977            "Link fragment 'missing' not found in 'other.md?raw=true'"
1978        );
1979        assert_eq!(warnings[0].line, 3);
1980    }
1981
1982    #[test]
1983    fn a_query_string_does_not_hide_an_extensionless_target_file() {
1984        let rule = MD051LinkFragments::new();
1985        let source = "# Source\n\n- [a](other?raw=true#target)\n- [b](other#target)\n- [c](other?raw=true#absent)\n";
1986
1987        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
1988        let same_document = rule.check(&source_ctx).unwrap();
1989        assert!(
1990            same_document.is_empty(),
1991            "Every fragment here belongs to another file, so none is a missing anchor of this one. Got: {same_document:?}"
1992        );
1993
1994        let mut source_index = FileIndex::default();
1995        rule.contribute_to_index(&source_ctx, &mut source_index);
1996
1997        let target_ctx = LintContext::new("# Other\n\n## Target\n", crate::config::MarkdownFlavor::Standard, None);
1998        let mut target_index = FileIndex::default();
1999        rule.contribute_to_index(&target_ctx, &mut target_index);
2000
2001        let source_path = PathBuf::from("docs/source.md");
2002        let mut workspace = crate::workspace_index::WorkspaceIndex::new();
2003        workspace.insert_file(source_path.clone(), source_index.clone());
2004        workspace.insert_file(PathBuf::from("docs/other.md"), target_index);
2005
2006        let warnings = rule.cross_file_check(&source_path, &source_index, &workspace).unwrap();
2007
2008        assert_eq!(
2009            warnings.len(),
2010            1,
2011            "The query is stripped before the markdown extension is added. Got: {warnings:?}"
2012        );
2013        assert_eq!(
2014            warnings[0].message,
2015            "Link fragment 'absent' not found in 'other?raw=true'"
2016        );
2017        assert_eq!(warnings[0].line, 5);
2018    }
2019
2020    #[test]
2021    fn a_destination_that_is_only_a_query_stays_on_this_page() {
2022        let rule = MD051LinkFragments::new();
2023        let source = "# Source\n\n## Here\n\n- [a](?raw=true#here)\n- [b](?raw=true#nowhere)\n";
2024
2025        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
2026        let warnings = rule.check(&source_ctx).unwrap();
2027
2028        assert_eq!(
2029            warnings.len(),
2030            1,
2031            "Only the absent anchor is reported. Got: {warnings:?}"
2032        );
2033        assert_eq!(
2034            warnings[0].message,
2035            "Link anchor '#nowhere' does not exist in document headings"
2036        );
2037        assert_eq!(warnings[0].line, 6);
2038
2039        let mut source_index = FileIndex::default();
2040        rule.contribute_to_index(&source_ctx, &mut source_index);
2041        assert!(
2042            source_index.cross_file_links.is_empty(),
2043            "A query with no path names no other file. Got: {:?}",
2044            source_index.cross_file_links
2045        );
2046    }
2047
2048    #[test]
2049    fn blockquote_syntax_inside_raw_html_does_not_create_an_anchor() {
2050        let rule = MD051LinkFragments::new();
2051        let source = "<div>\n> ## Hidden\n</div>\n\n[link](#hidden)\n";
2052        let ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
2053
2054        let warnings = rule.check(&ctx).unwrap();
2055        assert_eq!(
2056            warnings.len(),
2057            1,
2058            "raw HTML must not satisfy the fragment: {warnings:?}"
2059        );
2060
2061        let mut file_index = FileIndex::default();
2062        rule.contribute_to_index(&ctx, &mut file_index);
2063        assert!(
2064            file_index.headings.is_empty(),
2065            "raw HTML must not enter the workspace index"
2066        );
2067    }
2068
2069    #[test]
2070    fn a_frontmatter_path_carrying_a_query_is_indexed() {
2071        let rule = MD051LinkFragments::from_config_struct(front_matter_checked());
2072        let source = "---\ntemplate: docs/other.md?raw=true#missing\n---\n\n# Source\n";
2073
2074        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
2075        let mut source_index = FileIndex::default();
2076        rule.contribute_to_index(&source_ctx, &mut source_index);
2077
2078        assert_eq!(source_index.cross_file_links.len(), 1);
2079        assert_eq!(source_index.cross_file_links[0].target_path, "docs/other.md?raw=true");
2080        assert_eq!(source_index.cross_file_links[0].fragment, "missing");
2081    }
2082
2083    /// Frontmatter is only checked on request. The link is still indexed, so a
2084    /// file that does request it can resolve the same target, but a rule left
2085    /// at its defaults reports nothing.
2086    #[test]
2087    fn frontmatter_cross_file_paths_are_not_reported_by_default() {
2088        use crate::workspace_index::WorkspaceIndex;
2089
2090        let rule = MD051LinkFragments::new();
2091        let source = "---\ntemplate: other.md#missing\n---\n\n# Source\n";
2092
2093        let source_ctx = LintContext::new(source, crate::config::MarkdownFlavor::Standard, None);
2094        let mut source_index = FileIndex::default();
2095        rule.contribute_to_index(&source_ctx, &mut source_index);
2096        assert_eq!(source_index.cross_file_links.len(), 1);
2097
2098        let mut workspace_index = WorkspaceIndex::new();
2099        let mut target = FileIndex::new();
2100        target.add_heading(HeadingIndex {
2101            text: "Present".to_string(),
2102            auto_anchor: "present".to_string(),
2103            custom_anchor: None,
2104            line: 1,
2105            is_setext: false,
2106        });
2107        workspace_index.insert_file(PathBuf::from("other.md"), target);
2108
2109        let warnings = rule
2110            .cross_file_check(Path::new("source.md"), &source_index, &workspace_index)
2111            .unwrap();
2112        assert!(
2113            warnings.is_empty(),
2114            "Frontmatter is only checked on request. Got: {warnings:?}"
2115        );
2116
2117        // The target and the missing anchor are both real, so requesting the
2118        // check does report it. Without this the empty result above would also
2119        // pass on an unresolvable path.
2120        let checking = MD051LinkFragments::from_config_struct(MD051Config {
2121            check_frontmatter: true,
2122            ..Default::default()
2123        });
2124        assert_eq!(
2125            checking
2126                .cross_file_check(Path::new("source.md"), &source_index, &workspace_index)
2127                .unwrap()
2128                .len(),
2129            1
2130        );
2131    }
2132}