Skip to main content

rumdl_lib/rules/
md051_link_fragments.rs

1use crate::rule::{CrossFileScope, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::utils::anchor_styles::AnchorStyle;
3use crate::workspace_index::{CrossFileLinkIndex, FileIndex, HeadingIndex};
4use pulldown_cmark::LinkType;
5use regex::Regex;
6use std::collections::{HashMap, HashSet};
7use std::path::{Component, Path, PathBuf};
8use std::sync::LazyLock;
9// HTML tags with id or name attributes (supports any HTML element, not just <a>)
10// This pattern only captures the first id/name attribute in a tag
11static HTML_ANCHOR_PATTERN: LazyLock<Regex> =
12    LazyLock::new(|| Regex::new(r#"\b(?:id|name)\s*=\s*["']([^"']+)["']"#).unwrap());
13
14// Attribute anchor pattern for kramdown/MkDocs { #id } syntax
15// Matches {#id} or { #id } with optional spaces, supports multiple anchors
16// Also supports classes and attributes: { #id .class key=value }
17static ATTR_ANCHOR_PATTERN: LazyLock<Regex> =
18    LazyLock::new(|| Regex::new(r#"\{\s*#([a-zA-Z0-9_][a-zA-Z0-9_-]*)[^}]*\}"#).unwrap());
19
20// Material for MkDocs setting anchor pattern: <!-- md:setting NAME -->
21// Used in headings to generate anchors for configuration option references
22static MD_SETTING_PATTERN: LazyLock<Regex> =
23    LazyLock::new(|| Regex::new(r"<!--\s*md:setting\s+([^\s]+)\s*-->").unwrap());
24
25/// Normalize a path by resolving . and .. components
26fn normalize_path(path: &Path) -> PathBuf {
27    let mut result = PathBuf::new();
28    for component in path.components() {
29        match component {
30            Component::CurDir => {} // Skip .
31            Component::ParentDir => {
32                result.pop(); // Go up one level for ..
33            }
34            c => result.push(c.as_os_str()),
35        }
36    }
37    result
38}
39
40/// Rule MD051: Link fragments
41///
42/// See [docs/md051.md](../../docs/md051.md) for full documentation, configuration, and examples.
43///
44/// This rule validates that link anchors (the part after #) point to existing headings.
45/// Supports both same-document anchors and cross-file fragment links when linting a workspace.
46#[derive(Clone)]
47pub struct MD051LinkFragments {
48    /// Anchor style to use for validation
49    anchor_style: AnchorStyle,
50}
51
52impl Default for MD051LinkFragments {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58impl MD051LinkFragments {
59    pub fn new() -> Self {
60        Self {
61            anchor_style: AnchorStyle::GitHub,
62        }
63    }
64
65    /// Create with specific anchor style
66    pub fn with_anchor_style(style: AnchorStyle) -> Self {
67        Self { anchor_style: style }
68    }
69
70    /// Parse ATX heading content from blockquote inner text.
71    /// Strips the leading `# ` marker, optional closing hash sequence, and extracts custom IDs.
72    /// Returns `(clean_text, custom_id)` or None if not a heading.
73    fn parse_blockquote_heading(bq_content: &str) -> Option<(String, Option<String>)> {
74        static BQ_ATX_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.*)$").unwrap());
75
76        let trimmed = bq_content.trim();
77        let caps = BQ_ATX_HEADING_RE.captures(trimmed)?;
78        let mut rest = caps.get(2).map_or("", |m| m.as_str()).to_string();
79
80        // Strip optional closing hash sequence (CommonMark: trailing `#`s preceded by a space)
81        let rest_trimmed = rest.trim_end();
82        if let Some(last_hash_pos) = rest_trimmed.rfind('#') {
83            let after_hashes = &rest_trimmed[last_hash_pos..];
84            if after_hashes.chars().all(|c| c == '#') {
85                // Find where the consecutive trailing hashes start
86                let mut hash_start = last_hash_pos;
87                while hash_start > 0 && rest_trimmed.as_bytes()[hash_start - 1] == b'#' {
88                    hash_start -= 1;
89                }
90                // Must be preceded by whitespace (or be the entire content)
91                if hash_start == 0
92                    || rest_trimmed
93                        .as_bytes()
94                        .get(hash_start - 1)
95                        .is_some_and(|b| b.is_ascii_whitespace())
96                {
97                    rest = rest_trimmed[..hash_start].trim_end().to_string();
98                }
99            }
100        }
101
102        let (clean_text, custom_id) = crate::utils::header_id_utils::extract_header_id(&rest);
103        Some((clean_text, custom_id))
104    }
105
106    /// Insert a heading fragment with deduplication.
107    /// When `use_underscore_dedup` is true (Python-Markdown/MkDocs), the primary suffix
108    /// uses `_N` and `-N` is registered as a fallback. Otherwise, only `-N` is used.
109    ///
110    /// Empty fragments (from CJK-only headings) are handled specially for Python-Markdown:
111    /// the first empty slug gets `_1`, the second `_2`, etc. (matching Python-Markdown's
112    /// `unique()` function which always enters the dedup loop for falsy IDs).
113    fn insert_deduplicated_fragment(
114        fragment: String,
115        fragment_counts: &mut HashMap<String, usize>,
116        markdown_headings: &mut HashSet<String>,
117        use_underscore_dedup: bool,
118    ) {
119        if fragment.is_empty() {
120            if !use_underscore_dedup {
121                return;
122            }
123            // Python-Markdown: empty slug → _1, _2, _3, ...
124            let count = fragment_counts.entry(fragment).or_insert(0);
125            *count += 1;
126            markdown_headings.insert(format!("_{count}"));
127            return;
128        }
129        if let Some(count) = fragment_counts.get_mut(&fragment) {
130            let suffix = *count;
131            *count += 1;
132            if use_underscore_dedup {
133                // Python-Markdown primary: heading_1, heading_2
134                markdown_headings.insert(format!("{fragment}_{suffix}"));
135                // Also accept GitHub-style for compatibility
136                markdown_headings.insert(format!("{fragment}-{suffix}"));
137            } else {
138                // GitHub-style: heading-1, heading-2
139                markdown_headings.insert(format!("{fragment}-{suffix}"));
140            }
141        } else {
142            fragment_counts.insert(fragment.clone(), 1);
143            markdown_headings.insert(fragment);
144        }
145    }
146
147    /// Add a heading to the cross-file index with proper deduplication.
148    /// When `use_underscore_dedup` is true (Python-Markdown/MkDocs), the primary anchor
149    /// uses `_N` and `-N` is registered as a fallback alias.
150    ///
151    /// Empty fragments (from CJK-only headings) get `_1`, `_2`, etc. in Python-Markdown mode.
152    fn add_heading_to_index(
153        fragment: &str,
154        text: &str,
155        custom_anchor: Option<String>,
156        line: usize,
157        fragment_counts: &mut HashMap<String, usize>,
158        file_index: &mut FileIndex,
159        use_underscore_dedup: bool,
160    ) {
161        if fragment.is_empty() {
162            if !use_underscore_dedup {
163                return;
164            }
165            // Python-Markdown: empty slug → _1, _2, _3, ...
166            let count = fragment_counts.entry(fragment.to_string()).or_insert(0);
167            *count += 1;
168            file_index.add_heading(HeadingIndex {
169                text: text.to_string(),
170                auto_anchor: format!("_{count}"),
171                custom_anchor,
172                line,
173                is_setext: false,
174            });
175            return;
176        }
177        if let Some(count) = fragment_counts.get_mut(fragment) {
178            let suffix = *count;
179            *count += 1;
180            let (primary, alias) = if use_underscore_dedup {
181                // Python-Markdown primary: heading_1; GitHub fallback: heading-1
182                (format!("{fragment}_{suffix}"), Some(format!("{fragment}-{suffix}")))
183            } else {
184                // GitHub-style primary: heading-1
185                (format!("{fragment}-{suffix}"), None)
186            };
187            file_index.add_heading(HeadingIndex {
188                text: text.to_string(),
189                auto_anchor: primary,
190                custom_anchor,
191                line,
192                is_setext: false,
193            });
194            if let Some(alias_anchor) = alias {
195                let heading_idx = file_index.headings.len() - 1;
196                file_index.add_anchor_alias(alias_anchor, heading_idx);
197            }
198        } else {
199            fragment_counts.insert(fragment.to_string(), 1);
200            file_index.add_heading(HeadingIndex {
201                text: text.to_string(),
202                auto_anchor: fragment.to_string(),
203                custom_anchor,
204                line,
205                is_setext: false,
206            });
207        }
208    }
209
210    /// Extract all valid heading anchors from the document
211    /// Returns (markdown_anchors, html_anchors) where markdown_anchors are lowercased
212    /// for case-insensitive matching, and html_anchors are case-sensitive
213    fn extract_headings_from_context(
214        &self,
215        ctx: &crate::lint_context::LintContext,
216    ) -> (HashSet<String>, HashSet<String>) {
217        let mut markdown_headings = HashSet::with_capacity(32);
218        let mut html_anchors = HashSet::with_capacity(16);
219        let mut fragment_counts = std::collections::HashMap::new();
220        let use_underscore_dedup = self.anchor_style == AnchorStyle::PythonMarkdown;
221
222        for line_info in &ctx.lines {
223            if line_info.in_front_matter {
224                continue;
225            }
226
227            // Skip code blocks for anchor extraction
228            if line_info.in_code_block {
229                continue;
230            }
231
232            let content = line_info.content(ctx.content);
233            let bytes = content.as_bytes();
234
235            // Extract HTML anchor tags with id/name attributes
236            if bytes.contains(&b'<') && (content.contains("id=") || content.contains("name=")) {
237                // HTML spec: only the first id attribute per element is valid
238                // Process element by element to handle multiple id attributes correctly
239                let mut pos = 0;
240                while pos < content.len() {
241                    if let Some(start) = content[pos..].find('<') {
242                        let tag_start = pos + start;
243                        if let Some(end) = content[tag_start..].find('>') {
244                            let tag_end = tag_start + end + 1;
245                            let tag = &content[tag_start..tag_end];
246
247                            // Extract first id or name attribute from this tag
248                            if let Some(caps) = HTML_ANCHOR_PATTERN.find(tag) {
249                                let matched_text = caps.as_str();
250                                if let Some(caps) = HTML_ANCHOR_PATTERN.captures(matched_text)
251                                    && let Some(id_match) = caps.get(1)
252                                {
253                                    let id = id_match.as_str();
254                                    if !id.is_empty() {
255                                        html_anchors.insert(id.to_string());
256                                    }
257                                }
258                            }
259                            pos = tag_end;
260                        } else {
261                            break;
262                        }
263                    } else {
264                        break;
265                    }
266                }
267            }
268
269            // Extract attribute anchors { #id } from non-heading lines
270            // Headings already have custom_id extracted below
271            if line_info.heading.is_none() && content.contains('{') && content.contains('#') {
272                for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
273                    if let Some(id_match) = caps.get(1) {
274                        // Add to markdown_headings (lowercased for case-insensitive matching)
275                        markdown_headings.insert(id_match.as_str().to_lowercase());
276                    }
277                }
278            }
279
280            // Extract heading anchors from blockquote content
281            // Blockquote headings (e.g., "> ## Heading") are not detected by the main heading parser
282            // because the regex operates on the full line, but they still generate valid anchors
283            if line_info.heading.is_none()
284                && let Some(bq) = &line_info.blockquote
285                && let Some((clean_text, custom_id)) = Self::parse_blockquote_heading(&bq.content)
286            {
287                if let Some(id) = custom_id {
288                    markdown_headings.insert(id.to_lowercase());
289                }
290                let fragment = self.anchor_style.generate_fragment(&clean_text);
291                Self::insert_deduplicated_fragment(
292                    fragment,
293                    &mut fragment_counts,
294                    &mut markdown_headings,
295                    use_underscore_dedup,
296                );
297            }
298
299            // Extract markdown heading anchors
300            if let Some(heading) = &line_info.heading {
301                // Custom ID from {#custom-id} syntax
302                if let Some(custom_id) = &heading.custom_id {
303                    markdown_headings.insert(custom_id.to_lowercase());
304                }
305
306                // Generate fragment directly from heading text
307                // Note: HTML stripping was removed because it interfered with arrow patterns
308                // like <-> and placeholders like <FILE>. The anchor styles handle these correctly.
309                let fragment = self.anchor_style.generate_fragment(&heading.text);
310
311                Self::insert_deduplicated_fragment(
312                    fragment,
313                    &mut fragment_counts,
314                    &mut markdown_headings,
315                    use_underscore_dedup,
316                );
317            }
318        }
319
320        (markdown_headings, html_anchors)
321    }
322
323    /// Fast check if URL is external (doesn't need to be validated)
324    #[inline]
325    fn is_external_url_fast(url: &str) -> bool {
326        // Quick prefix checks for common protocols
327        url.starts_with("http://")
328            || url.starts_with("https://")
329            || url.starts_with("ftp://")
330            || url.starts_with("mailto:")
331            || url.starts_with("tel:")
332            || url.starts_with("//")
333    }
334
335    /// Resolve a path by trying markdown extensions if it has no extension
336    ///
337    /// For extension-less paths (e.g., `page`), returns a list of paths to try:
338    /// 1. The original path (in case it's already in the index)
339    /// 2. The path with each markdown extension (e.g., `page.md`, `page.markdown`, etc.)
340    ///
341    /// For paths with extensions, returns just the original path.
342    #[inline]
343    fn resolve_path_with_extensions(path: &Path, extensions: &[&str]) -> Vec<PathBuf> {
344        if path.extension().is_none() {
345            // Extension-less path - try with markdown extensions
346            let mut paths = Vec::with_capacity(extensions.len() + 1);
347            // First try the exact path (in case it's already in the index)
348            paths.push(path.to_path_buf());
349            // Then try with each markdown extension
350            for ext in extensions {
351                let path_with_ext = path.with_extension(&ext[1..]); // Remove leading dot
352                paths.push(path_with_ext);
353            }
354            paths
355        } else {
356            // Path has extension - use as-is
357            vec![path.to_path_buf()]
358        }
359    }
360
361    /// Check if a path part (without fragment) is an extension-less path
362    ///
363    /// Extension-less paths are potential cross-file links that need resolution
364    /// with markdown extensions (e.g., `page#section` -> `page.md#section`).
365    ///
366    /// We recognize them as extension-less if:
367    /// 1. Path has no extension (no dot)
368    /// 2. Path is not empty
369    /// 3. Path doesn't look like a query parameter or special syntax
370    /// 4. Path contains at least one alphanumeric character (valid filename)
371    /// 5. Path contains only valid path characters (alphanumeric, slashes, hyphens, underscores)
372    ///
373    /// Optimized: single pass through characters to check both conditions.
374    #[inline]
375    fn is_extensionless_path(path_part: &str) -> bool {
376        // Quick rejections for common non-extension-less cases
377        if path_part.is_empty()
378            || path_part.contains('.')
379            || path_part.contains('?')
380            || path_part.contains('&')
381            || path_part.contains('=')
382        {
383            return false;
384        }
385
386        // Single pass: check for alphanumeric and validate all characters
387        let mut has_alphanumeric = false;
388        for c in path_part.chars() {
389            if c.is_alphanumeric() {
390                has_alphanumeric = true;
391            } else if !matches!(c, '/' | '\\' | '-' | '_') {
392                // Invalid character found - early exit
393                return false;
394            }
395        }
396
397        // Must have at least one alphanumeric character to be a valid filename
398        has_alphanumeric
399    }
400
401    /// Check if URL is a cross-file link (contains a file path before #)
402    #[inline]
403    fn is_cross_file_link(url: &str) -> bool {
404        if let Some(fragment_pos) = url.find('#') {
405            let path_part = &url[..fragment_pos];
406
407            // If there's no path part, it's just a fragment (#heading)
408            if path_part.is_empty() {
409                return false;
410            }
411
412            // Check for Liquid syntax used by Jekyll and other static site generators
413            // Liquid tags: {% ... %} for control flow and includes
414            // Liquid variables: {{ ... }} for outputting values
415            // These are template directives that reference external content and should be skipped
416            // We check for proper bracket order to avoid false positives
417            if let Some(tag_start) = path_part.find("{%")
418                && path_part[tag_start + 2..].contains("%}")
419            {
420                return true;
421            }
422            if let Some(var_start) = path_part.find("{{")
423                && path_part[var_start + 2..].contains("}}")
424            {
425                return true;
426            }
427
428            // Check if it's an absolute path (starts with /)
429            // These are links to other pages on the same site
430            if path_part.starts_with('/') {
431                return true;
432            }
433
434            // Check if it looks like a file path:
435            // - Contains a file extension (dot followed by letters)
436            // - Contains path separators
437            // - Contains relative path indicators
438            // - OR is an extension-less path with a fragment (GitHub-style: page#section)
439            let has_extension = path_part.contains('.')
440                && (
441                    // Has file extension pattern (handle query parameters by splitting on them first)
442                    {
443                    let clean_path = path_part.split('?').next().unwrap_or(path_part);
444                    // Handle files starting with dot
445                    if let Some(after_dot) = clean_path.strip_prefix('.') {
446                        let dots_count = clean_path.matches('.').count();
447                        if dots_count == 1 {
448                            // Could be ".ext" (file extension) or ".hidden" (hidden file)
449                            // Treat short alphanumeric suffixes as file extensions
450                            !after_dot.is_empty() && after_dot.len() <= 10 &&
451                            after_dot.chars().all(|c| c.is_ascii_alphanumeric())
452                        } else {
453                            // Hidden file with extension like ".hidden.txt"
454                            clean_path.split('.').next_back().is_some_and(|ext| {
455                                !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
456                            })
457                        }
458                    } else {
459                        // Regular file path
460                        clean_path.split('.').next_back().is_some_and(|ext| {
461                            !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
462                        })
463                    }
464                } ||
465                // Or contains path separators
466                path_part.contains('/') || path_part.contains('\\') ||
467                // Or starts with relative path indicators
468                path_part.starts_with("./") || path_part.starts_with("../")
469                );
470
471            // Extension-less paths with fragments are potential cross-file links
472            // This supports GitHub-style links like [link](page#section) that resolve to page.md#section
473            let is_extensionless = Self::is_extensionless_path(path_part);
474
475            has_extension || is_extensionless
476        } else {
477            false
478        }
479    }
480}
481
482impl Rule for MD051LinkFragments {
483    fn name(&self) -> &'static str {
484        "MD051"
485    }
486
487    fn description(&self) -> &'static str {
488        "Link fragments should reference valid headings"
489    }
490
491    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
492        // Skip if no link fragments present
493        if !ctx.likely_has_links_or_images() {
494            return true;
495        }
496        // Check for # character (fragments)
497        !ctx.has_char('#')
498    }
499
500    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
501        let mut warnings = Vec::new();
502
503        if ctx.content.is_empty() || ctx.links.is_empty() || self.should_skip(ctx) {
504            return Ok(warnings);
505        }
506
507        let (markdown_headings, html_anchors) = self.extract_headings_from_context(ctx);
508
509        for link in &ctx.links {
510            if link.is_reference {
511                continue;
512            }
513
514            // Skip links inside PyMdown blocks (MkDocs flavor)
515            if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
516                continue;
517            }
518
519            // Skip wiki-links - they reference other files and may have their own fragment validation
520            if matches!(link.link_type, LinkType::WikiLink { .. }) {
521                continue;
522            }
523
524            // Skip links inside Jinja templates
525            if ctx.is_in_jinja_range(link.byte_offset) {
526                continue;
527            }
528
529            // Skip Quarto/Pandoc citations ([@citation], @citation)
530            // Citations are bibliography references, not link fragments
531            if ctx.flavor == crate::config::MarkdownFlavor::Quarto && ctx.is_in_citation(link.byte_offset) {
532                continue;
533            }
534
535            // Skip links inside shortcodes ({{< ... >}} or {{% ... %}})
536            // Shortcodes may contain template syntax that looks like fragment links
537            if ctx.is_in_shortcode(link.byte_offset) {
538                continue;
539            }
540
541            let url = &link.url;
542
543            // Skip links without fragments or external URLs
544            if !url.contains('#') || Self::is_external_url_fast(url) {
545                continue;
546            }
547
548            // Skip mdbook template placeholders ({{#VARIABLE}})
549            // mdbook uses {{#VARIABLE}} syntax where # is part of the template, not a fragment
550            if url.contains("{{#") && url.contains("}}") {
551                continue;
552            }
553
554            // Skip Quarto/RMarkdown cross-references (@fig-, @tbl-, @sec-, @eq-, etc.)
555            // These are special cross-reference syntax, not HTML anchors
556            // Format: @prefix-identifier or just @identifier
557            if url.starts_with('@') {
558                continue;
559            }
560
561            // Cross-file links are valid if the file exists (not checked here)
562            if Self::is_cross_file_link(url) {
563                continue;
564            }
565
566            let Some(fragment_pos) = url.find('#') else {
567                continue;
568            };
569
570            let fragment = &url[fragment_pos + 1..];
571
572            // Skip Liquid template variables and filters
573            if (url.contains("{{") && fragment.contains('|')) || fragment.ends_with("}}") || fragment.ends_with("%}") {
574                continue;
575            }
576
577            if fragment.is_empty() {
578                continue;
579            }
580
581            // Skip MkDocs runtime-generated anchors:
582            // - #fn:NAME, #fnref:NAME from the footnotes extension
583            // - #+key.path or #+key:value from Material for MkDocs option references
584            //   (e.g., #+type:abstract, #+toc.slugify, #+pymdownx.highlight.anchor_linenums)
585            if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
586                && (fragment.starts_with("fn:")
587                    || fragment.starts_with("fnref:")
588                    || (fragment.starts_with('+') && (fragment.contains('.') || fragment.contains(':'))))
589            {
590                continue;
591            }
592
593            // Validate fragment against document headings
594            // HTML anchors are case-sensitive, markdown anchors are case-insensitive
595            let found = if html_anchors.contains(fragment) {
596                true
597            } else {
598                let fragment_lower = fragment.to_lowercase();
599                markdown_headings.contains(&fragment_lower)
600            };
601
602            if !found {
603                warnings.push(LintWarning {
604                    rule_name: Some(self.name().to_string()),
605                    message: format!("Link anchor '#{fragment}' does not exist in document headings"),
606                    line: link.line,
607                    column: link.start_col + 1,
608                    end_line: link.line,
609                    end_column: link.end_col + 1,
610                    severity: Severity::Error,
611                    fix: None,
612                });
613            }
614        }
615
616        Ok(warnings)
617    }
618
619    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
620        // MD051 does not provide auto-fix
621        // Link fragment corrections require human judgment to avoid incorrect fixes
622        Ok(ctx.content.to_string())
623    }
624
625    fn as_any(&self) -> &dyn std::any::Any {
626        self
627    }
628
629    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
630    where
631        Self: Sized,
632    {
633        // Config keys are normalized to kebab-case by the config system
634        let explicit_style = config
635            .rules
636            .get("MD051")
637            .and_then(|rc| rc.values.get("anchor-style"))
638            .and_then(|v| v.as_str())
639            .map(|style_str| match style_str.to_lowercase().as_str() {
640                "kramdown" => AnchorStyle::Kramdown,
641                "kramdown-gfm" | "jekyll" => AnchorStyle::KramdownGfm,
642                "python-markdown" | "python_markdown" | "mkdocs" => AnchorStyle::PythonMarkdown,
643                _ => AnchorStyle::GitHub,
644            });
645
646        // When a flavor is active and no explicit anchor style is configured,
647        // default to the flavor's native anchor generation
648        let anchor_style = explicit_style.unwrap_or(match config.global.flavor {
649            crate::config::MarkdownFlavor::MkDocs => AnchorStyle::PythonMarkdown,
650            crate::config::MarkdownFlavor::Kramdown => AnchorStyle::KramdownGfm,
651            _ => AnchorStyle::GitHub,
652        });
653
654        Box::new(MD051LinkFragments::with_anchor_style(anchor_style))
655    }
656
657    fn category(&self) -> RuleCategory {
658        RuleCategory::Link
659    }
660
661    fn cross_file_scope(&self) -> CrossFileScope {
662        CrossFileScope::Workspace
663    }
664
665    fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, file_index: &mut FileIndex) {
666        let mut fragment_counts = HashMap::new();
667        let use_underscore_dedup = self.anchor_style == AnchorStyle::PythonMarkdown;
668
669        // Extract headings, HTML anchors, and attribute anchors (for other files to reference)
670        for (line_idx, line_info) in ctx.lines.iter().enumerate() {
671            if line_info.in_front_matter {
672                continue;
673            }
674
675            // Skip code blocks for anchor extraction
676            if line_info.in_code_block {
677                continue;
678            }
679
680            let content = line_info.content(ctx.content);
681
682            // Extract HTML anchors (id or name attributes on any element)
683            if content.contains('<') && (content.contains("id=") || content.contains("name=")) {
684                let mut pos = 0;
685                while pos < content.len() {
686                    if let Some(start) = content[pos..].find('<') {
687                        let tag_start = pos + start;
688                        if let Some(end) = content[tag_start..].find('>') {
689                            let tag_end = tag_start + end + 1;
690                            let tag = &content[tag_start..tag_end];
691
692                            if let Some(caps) = HTML_ANCHOR_PATTERN.captures(tag)
693                                && let Some(id_match) = caps.get(1)
694                            {
695                                file_index.add_html_anchor(id_match.as_str().to_string());
696                            }
697                            pos = tag_end;
698                        } else {
699                            break;
700                        }
701                    } else {
702                        break;
703                    }
704                }
705            }
706
707            // Extract attribute anchors { #id } on non-heading lines
708            // Headings already have custom_id extracted via heading.custom_id
709            if line_info.heading.is_none() && content.contains("{") && content.contains("#") {
710                for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
711                    if let Some(id_match) = caps.get(1) {
712                        file_index.add_attribute_anchor(id_match.as_str().to_string());
713                    }
714                }
715            }
716
717            // Extract heading anchors from blockquote content
718            if line_info.heading.is_none()
719                && let Some(bq) = &line_info.blockquote
720                && let Some((clean_text, custom_id)) = Self::parse_blockquote_heading(&bq.content)
721            {
722                let fragment = self.anchor_style.generate_fragment(&clean_text);
723                Self::add_heading_to_index(
724                    &fragment,
725                    &clean_text,
726                    custom_id,
727                    line_idx + 1,
728                    &mut fragment_counts,
729                    file_index,
730                    use_underscore_dedup,
731                );
732            }
733
734            // Extract heading anchors
735            if let Some(heading) = &line_info.heading {
736                let fragment = self.anchor_style.generate_fragment(&heading.text);
737
738                Self::add_heading_to_index(
739                    &fragment,
740                    &heading.text,
741                    heading.custom_id.clone(),
742                    line_idx + 1,
743                    &mut fragment_counts,
744                    file_index,
745                    use_underscore_dedup,
746                );
747
748                // Extract Material for MkDocs setting anchors from headings.
749                // These are rendered as anchors at build time by Material's JS.
750                // Most references use #+key.path format (handled by the skip logic in check()),
751                // but this extraction enables cross-file validation for direct #key.path references.
752                if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
753                    && let Some(caps) = MD_SETTING_PATTERN.captures(content)
754                    && let Some(name) = caps.get(1)
755                {
756                    file_index.add_html_anchor(name.as_str().to_string());
757                }
758            }
759        }
760
761        // Extract cross-file links (for validation against other files)
762        for link in &ctx.links {
763            if link.is_reference {
764                continue;
765            }
766
767            // Skip links inside PyMdown blocks (MkDocs flavor)
768            if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
769                continue;
770            }
771
772            // Skip wiki-links - they use a different linking system and are not validated
773            // as relative file paths
774            if matches!(link.link_type, LinkType::WikiLink { .. }) {
775                continue;
776            }
777
778            let url = &link.url;
779
780            // Skip external URLs
781            if Self::is_external_url_fast(url) {
782                continue;
783            }
784
785            // Only process cross-file links with fragments
786            if Self::is_cross_file_link(url)
787                && let Some(fragment_pos) = url.find('#')
788            {
789                let path_part = &url[..fragment_pos];
790                let fragment = &url[fragment_pos + 1..];
791
792                // Skip empty fragments or template syntax
793                if fragment.is_empty() || fragment.contains("{{") || fragment.contains("{%") {
794                    continue;
795                }
796
797                file_index.add_cross_file_link(CrossFileLinkIndex {
798                    target_path: path_part.to_string(),
799                    fragment: fragment.to_string(),
800                    line: link.line,
801                    column: link.start_col + 1,
802                });
803            }
804        }
805    }
806
807    fn cross_file_check(
808        &self,
809        file_path: &Path,
810        file_index: &FileIndex,
811        workspace_index: &crate::workspace_index::WorkspaceIndex,
812    ) -> LintResult {
813        let mut warnings = Vec::new();
814
815        // Supported markdown file extensions (with leading dot, matching MD057)
816        const MARKDOWN_EXTENSIONS: &[&str] = &[
817            ".md",
818            ".markdown",
819            ".mdx",
820            ".mkd",
821            ".mkdn",
822            ".mdown",
823            ".mdwn",
824            ".qmd",
825            ".rmd",
826        ];
827
828        // Check each cross-file link in this file
829        for cross_link in &file_index.cross_file_links {
830            // Skip cross-file links without fragments - nothing to validate
831            if cross_link.fragment.is_empty() {
832                continue;
833            }
834
835            // Resolve the target file path relative to the current file
836            let base_target_path = if let Some(parent) = file_path.parent() {
837                parent.join(&cross_link.target_path)
838            } else {
839                Path::new(&cross_link.target_path).to_path_buf()
840            };
841
842            // Normalize the path (remove . and ..)
843            let base_target_path = normalize_path(&base_target_path);
844
845            // For extension-less paths, try resolving with markdown extensions
846            // This handles GitHub-style links like [link](page#section) -> page.md#section
847            let target_paths_to_try = Self::resolve_path_with_extensions(&base_target_path, MARKDOWN_EXTENSIONS);
848
849            // Try to find the target file in the workspace index
850            let mut target_file_index = None;
851
852            for target_path in &target_paths_to_try {
853                if let Some(index) = workspace_index.get_file(target_path) {
854                    target_file_index = Some(index);
855                    break;
856                }
857            }
858
859            if let Some(target_file_index) = target_file_index {
860                // Check if the fragment matches any heading in the target file (O(1) lookup)
861                if !target_file_index.has_anchor(&cross_link.fragment) {
862                    warnings.push(LintWarning {
863                        rule_name: Some(self.name().to_string()),
864                        line: cross_link.line,
865                        column: cross_link.column,
866                        end_line: cross_link.line,
867                        end_column: cross_link.column + cross_link.target_path.len() + 1 + cross_link.fragment.len(),
868                        message: format!(
869                            "Link fragment '{}' not found in '{}'",
870                            cross_link.fragment, cross_link.target_path
871                        ),
872                        severity: Severity::Error,
873                        fix: None,
874                    });
875                }
876            }
877            // If target file not in index, skip (could be external file or not in workspace)
878        }
879
880        Ok(warnings)
881    }
882
883    fn default_config_section(&self) -> Option<(String, toml::Value)> {
884        let value: toml::Value = toml::from_str(
885            r#"
886# Anchor generation style to match your target platform
887# Options: "github" (default), "kramdown-gfm", "kramdown"
888# Note: "jekyll" is accepted as an alias for "kramdown-gfm" (backward compatibility)
889anchor-style = "github"
890"#,
891        )
892        .ok()?;
893        Some(("MD051".to_string(), value))
894    }
895}
896
897#[cfg(test)]
898mod tests {
899    use super::*;
900    use crate::lint_context::LintContext;
901
902    #[test]
903    fn test_quarto_cross_references() {
904        let rule = MD051LinkFragments::new();
905
906        // Test that Quarto cross-references are skipped
907        let content = r#"# Test Document
908
909## Figures
910
911See [@fig-plot] for the visualization.
912
913More details in [@tbl-results] and [@sec-methods].
914
915The equation [@eq-regression] shows the relationship.
916
917Reference to [@lst-code] for implementation."#;
918        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
919        let result = rule.check(&ctx).unwrap();
920        assert!(
921            result.is_empty(),
922            "Quarto cross-references (@fig-, @tbl-, @sec-, @eq-) should not trigger MD051 warnings. Got {} warnings",
923            result.len()
924        );
925
926        // Test that normal anchors still work
927        let content_with_anchor = r#"# Test
928
929See [link](#test) for details."#;
930        let ctx_anchor = LintContext::new(content_with_anchor, crate::config::MarkdownFlavor::Quarto, None);
931        let result_anchor = rule.check(&ctx_anchor).unwrap();
932        assert!(result_anchor.is_empty(), "Valid anchor should not trigger warning");
933
934        // Test that invalid anchors are still flagged
935        let content_invalid = r#"# Test
936
937See [link](#nonexistent) for details."#;
938        let ctx_invalid = LintContext::new(content_invalid, crate::config::MarkdownFlavor::Quarto, None);
939        let result_invalid = rule.check(&ctx_invalid).unwrap();
940        assert_eq!(result_invalid.len(), 1, "Invalid anchor should still trigger warning");
941    }
942
943    // Cross-file validation tests
944    #[test]
945    fn test_cross_file_scope() {
946        let rule = MD051LinkFragments::new();
947        assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
948    }
949
950    #[test]
951    fn test_contribute_to_index_extracts_headings() {
952        let rule = MD051LinkFragments::new();
953        let content = "# First Heading\n\n# Second { #custom }\n\n## Third";
954        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
955
956        let mut file_index = FileIndex::new();
957        rule.contribute_to_index(&ctx, &mut file_index);
958
959        assert_eq!(file_index.headings.len(), 3);
960        assert_eq!(file_index.headings[0].text, "First Heading");
961        assert_eq!(file_index.headings[0].auto_anchor, "first-heading");
962        assert!(file_index.headings[0].custom_anchor.is_none());
963
964        assert_eq!(file_index.headings[1].text, "Second");
965        assert_eq!(file_index.headings[1].custom_anchor, Some("custom".to_string()));
966
967        assert_eq!(file_index.headings[2].text, "Third");
968    }
969
970    #[test]
971    fn test_contribute_to_index_extracts_cross_file_links() {
972        let rule = MD051LinkFragments::new();
973        let content = "See [docs](other.md#installation) and [more](../guide.md#getting-started)";
974        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
975
976        let mut file_index = FileIndex::new();
977        rule.contribute_to_index(&ctx, &mut file_index);
978
979        assert_eq!(file_index.cross_file_links.len(), 2);
980        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
981        assert_eq!(file_index.cross_file_links[0].fragment, "installation");
982        assert_eq!(file_index.cross_file_links[1].target_path, "../guide.md");
983        assert_eq!(file_index.cross_file_links[1].fragment, "getting-started");
984    }
985
986    #[test]
987    fn test_cross_file_check_valid_fragment() {
988        use crate::workspace_index::WorkspaceIndex;
989
990        let rule = MD051LinkFragments::new();
991
992        // Build workspace index with target file
993        let mut workspace_index = WorkspaceIndex::new();
994        let mut target_file_index = FileIndex::new();
995        target_file_index.add_heading(HeadingIndex {
996            text: "Installation Guide".to_string(),
997            auto_anchor: "installation-guide".to_string(),
998            custom_anchor: None,
999            line: 1,
1000            is_setext: false,
1001        });
1002        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1003
1004        // Create a FileIndex for the file being checked
1005        let mut current_file_index = FileIndex::new();
1006        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1007            target_path: "install.md".to_string(),
1008            fragment: "installation-guide".to_string(),
1009            line: 3,
1010            column: 5,
1011        });
1012
1013        let warnings = rule
1014            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1015            .unwrap();
1016
1017        // Should find no warnings since fragment exists
1018        assert!(warnings.is_empty());
1019    }
1020
1021    #[test]
1022    fn test_cross_file_check_invalid_fragment() {
1023        use crate::workspace_index::WorkspaceIndex;
1024
1025        let rule = MD051LinkFragments::new();
1026
1027        // Build workspace index with target file
1028        let mut workspace_index = WorkspaceIndex::new();
1029        let mut target_file_index = FileIndex::new();
1030        target_file_index.add_heading(HeadingIndex {
1031            text: "Installation Guide".to_string(),
1032            auto_anchor: "installation-guide".to_string(),
1033            custom_anchor: None,
1034            line: 1,
1035            is_setext: false,
1036        });
1037        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1038
1039        // Create a FileIndex with a cross-file link pointing to non-existent fragment
1040        let mut current_file_index = FileIndex::new();
1041        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1042            target_path: "install.md".to_string(),
1043            fragment: "nonexistent".to_string(),
1044            line: 3,
1045            column: 5,
1046        });
1047
1048        let warnings = rule
1049            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1050            .unwrap();
1051
1052        // Should find one warning since fragment doesn't exist
1053        assert_eq!(warnings.len(), 1);
1054        assert!(warnings[0].message.contains("nonexistent"));
1055        assert!(warnings[0].message.contains("install.md"));
1056    }
1057
1058    #[test]
1059    fn test_cross_file_check_custom_anchor_match() {
1060        use crate::workspace_index::WorkspaceIndex;
1061
1062        let rule = MD051LinkFragments::new();
1063
1064        // Build workspace index with target file that has custom anchor
1065        let mut workspace_index = WorkspaceIndex::new();
1066        let mut target_file_index = FileIndex::new();
1067        target_file_index.add_heading(HeadingIndex {
1068            text: "Installation Guide".to_string(),
1069            auto_anchor: "installation-guide".to_string(),
1070            custom_anchor: Some("install".to_string()),
1071            line: 1,
1072            is_setext: false,
1073        });
1074        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1075
1076        // Link uses custom anchor
1077        let mut current_file_index = FileIndex::new();
1078        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1079            target_path: "install.md".to_string(),
1080            fragment: "install".to_string(),
1081            line: 3,
1082            column: 5,
1083        });
1084
1085        let warnings = rule
1086            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1087            .unwrap();
1088
1089        // Should find no warnings since custom anchor matches
1090        assert!(warnings.is_empty());
1091    }
1092
1093    #[test]
1094    fn test_cross_file_check_target_not_in_workspace() {
1095        use crate::workspace_index::WorkspaceIndex;
1096
1097        let rule = MD051LinkFragments::new();
1098
1099        // Empty workspace index
1100        let workspace_index = WorkspaceIndex::new();
1101
1102        // Link to file not in workspace
1103        let mut current_file_index = FileIndex::new();
1104        current_file_index.add_cross_file_link(CrossFileLinkIndex {
1105            target_path: "external.md".to_string(),
1106            fragment: "heading".to_string(),
1107            line: 3,
1108            column: 5,
1109        });
1110
1111        let warnings = rule
1112            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
1113            .unwrap();
1114
1115        // Should not warn about files not in workspace
1116        assert!(warnings.is_empty());
1117    }
1118
1119    #[test]
1120    fn test_wikilinks_skipped_in_check() {
1121        // Wikilinks should not trigger MD051 warnings for missing fragments
1122        let rule = MD051LinkFragments::new();
1123
1124        let content = r#"# Test Document
1125
1126## Valid Heading
1127
1128[[Microsoft#Windows OS]]
1129[[SomePage#section]]
1130[[page|Display Text]]
1131[[path/to/page#section]]
1132"#;
1133        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1134        let result = rule.check(&ctx).unwrap();
1135
1136        assert!(
1137            result.is_empty(),
1138            "Wikilinks should not trigger MD051 warnings. Got: {result:?}"
1139        );
1140    }
1141
1142    #[test]
1143    fn test_wikilinks_not_added_to_cross_file_index() {
1144        // Wikilinks should not be added to the cross-file link index
1145        let rule = MD051LinkFragments::new();
1146
1147        let content = r#"# Test Document
1148
1149[[Microsoft#Windows OS]]
1150[[SomePage#section]]
1151[Regular Link](other.md#section)
1152"#;
1153        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1154
1155        let mut file_index = FileIndex::new();
1156        rule.contribute_to_index(&ctx, &mut file_index);
1157
1158        // Should only have one cross-file link (the regular markdown link)
1159        // Wikilinks should not be added
1160        let cross_file_links = &file_index.cross_file_links;
1161        assert_eq!(
1162            cross_file_links.len(),
1163            1,
1164            "Only regular markdown links should be indexed, not wikilinks. Got: {cross_file_links:?}"
1165        );
1166        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
1167        assert_eq!(file_index.cross_file_links[0].fragment, "section");
1168    }
1169}