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/// Normalize a path by resolving . and .. components
15fn normalize_path(path: &Path) -> PathBuf {
16    let mut result = PathBuf::new();
17    for component in path.components() {
18        match component {
19            Component::CurDir => {} // Skip .
20            Component::ParentDir => {
21                result.pop(); // Go up one level for ..
22            }
23            c => result.push(c.as_os_str()),
24        }
25    }
26    result
27}
28
29/// Rule MD051: Link fragments
30///
31/// See [docs/md051.md](../../docs/md051.md) for full documentation, configuration, and examples.
32///
33/// This rule validates that link anchors (the part after #) exist in the current document.
34/// Only applies to internal document links (like #heading), not to external URLs or cross-file links.
35#[derive(Clone)]
36pub struct MD051LinkFragments {
37    /// Anchor style to use for validation
38    anchor_style: AnchorStyle,
39}
40
41impl Default for MD051LinkFragments {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl MD051LinkFragments {
48    pub fn new() -> Self {
49        Self {
50            anchor_style: AnchorStyle::GitHub,
51        }
52    }
53
54    /// Create with specific anchor style
55    pub fn with_anchor_style(style: AnchorStyle) -> Self {
56        Self { anchor_style: style }
57    }
58
59    /// Extract all valid heading anchors from the document
60    /// Returns (markdown_anchors, html_anchors) where markdown_anchors are lowercased
61    /// for case-insensitive matching, and html_anchors are case-sensitive
62    fn extract_headings_from_context(
63        &self,
64        ctx: &crate::lint_context::LintContext,
65    ) -> (HashSet<String>, HashSet<String>) {
66        let mut markdown_headings = HashSet::with_capacity(32);
67        let mut html_anchors = HashSet::with_capacity(16);
68        let mut fragment_counts = std::collections::HashMap::new();
69
70        for line_info in &ctx.lines {
71            if line_info.in_front_matter {
72                continue;
73            }
74
75            // Extract HTML anchor tags with id/name attributes
76            if !line_info.in_code_block {
77                let content = line_info.content(ctx.content);
78                let bytes = content.as_bytes();
79
80                // Skip lines without HTML tags or id/name attributes
81                if bytes.contains(&b'<') && (content.contains("id=") || content.contains("name=")) {
82                    // HTML spec: only the first id attribute per element is valid
83                    // Process element by element to handle multiple id attributes correctly
84                    let mut pos = 0;
85                    while pos < content.len() {
86                        if let Some(start) = content[pos..].find('<') {
87                            let tag_start = pos + start;
88                            if let Some(end) = content[tag_start..].find('>') {
89                                let tag_end = tag_start + end + 1;
90                                let tag = &content[tag_start..tag_end];
91
92                                // Extract first id or name attribute from this tag
93                                if let Some(caps) = HTML_ANCHOR_PATTERN.find(tag) {
94                                    let matched_text = caps.as_str();
95                                    if let Some(caps) = HTML_ANCHOR_PATTERN.captures(matched_text)
96                                        && let Some(id_match) = caps.get(1)
97                                    {
98                                        let id = id_match.as_str();
99                                        if !id.is_empty() {
100                                            html_anchors.insert(id.to_string());
101                                        }
102                                    }
103                                }
104                                pos = tag_end;
105                            } else {
106                                break;
107                            }
108                        } else {
109                            break;
110                        }
111                    }
112                }
113            }
114
115            // Extract markdown heading anchors
116            if let Some(heading) = &line_info.heading {
117                // Custom ID from {#custom-id} syntax
118                if let Some(custom_id) = &heading.custom_id {
119                    markdown_headings.insert(custom_id.to_lowercase());
120                }
121
122                // Generate anchor from heading text
123                // The anchor generation algorithm handles markdown formatting and HTML tags correctly
124                let fragment = self.anchor_style.generate_fragment(&heading.text);
125
126                if !fragment.is_empty() {
127                    // Handle duplicate headings by appending -1, -2, etc.
128                    let final_fragment = if let Some(count) = fragment_counts.get_mut(&fragment) {
129                        let suffix = *count;
130                        *count += 1;
131                        format!("{fragment}-{suffix}")
132                    } else {
133                        fragment_counts.insert(fragment.clone(), 1);
134                        fragment
135                    };
136                    markdown_headings.insert(final_fragment);
137                }
138            }
139        }
140
141        (markdown_headings, html_anchors)
142    }
143
144    /// Fast check if URL is external (doesn't need to be validated)
145    #[inline]
146    fn is_external_url_fast(url: &str) -> bool {
147        // Quick prefix checks for common protocols
148        url.starts_with("http://")
149            || url.starts_with("https://")
150            || url.starts_with("ftp://")
151            || url.starts_with("mailto:")
152            || url.starts_with("tel:")
153            || url.starts_with("//")
154    }
155
156    /// Check if URL is a cross-file link (contains a file path before #)
157    #[inline]
158    fn is_cross_file_link(url: &str) -> bool {
159        if let Some(fragment_pos) = url.find('#') {
160            let path_part = &url[..fragment_pos];
161
162            // If there's no path part, it's just a fragment (#heading)
163            if path_part.is_empty() {
164                return false;
165            }
166
167            // Check for Liquid syntax used by Jekyll and other static site generators
168            // Liquid tags: {% ... %} for control flow and includes
169            // Liquid variables: {{ ... }} for outputting values
170            // These are template directives that reference external content and should be skipped
171            // We check for proper bracket order to avoid false positives
172            if let Some(tag_start) = path_part.find("{%")
173                && path_part[tag_start + 2..].contains("%}")
174            {
175                return true;
176            }
177            if let Some(var_start) = path_part.find("{{")
178                && path_part[var_start + 2..].contains("}}")
179            {
180                return true;
181            }
182
183            // Check if it's an absolute path (starts with /)
184            // These are links to other pages on the same site
185            if path_part.starts_with('/') {
186                return true;
187            }
188
189            // Check if it looks like a file path:
190            // - Contains a file extension (dot followed by letters)
191            // - Contains path separators
192            // - Contains relative path indicators
193            path_part.contains('.')
194                && (
195                    // Has file extension pattern (handle query parameters by splitting on them first)
196                    {
197                    let clean_path = path_part.split('?').next().unwrap_or(path_part);
198                    // Handle files starting with dot
199                    if let Some(after_dot) = clean_path.strip_prefix('.') {
200                        let dots_count = clean_path.matches('.').count();
201                        if dots_count == 1 {
202                            // Could be ".ext" (file extension) or ".hidden" (hidden file)
203                            // Treat short alphanumeric suffixes as file extensions
204                            !after_dot.is_empty() && after_dot.len() <= 10 &&
205                            after_dot.chars().all(|c| c.is_ascii_alphanumeric())
206                        } else {
207                            // Hidden file with extension like ".hidden.txt"
208                            clean_path.split('.').next_back().is_some_and(|ext| {
209                                !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
210                            })
211                        }
212                    } else {
213                        // Regular file path
214                        clean_path.split('.').next_back().is_some_and(|ext| {
215                            !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
216                        })
217                    }
218                } ||
219                // Or contains path separators
220                path_part.contains('/') || path_part.contains('\\') ||
221                // Or starts with relative path indicators
222                path_part.starts_with("./") || path_part.starts_with("../")
223                )
224        } else {
225            false
226        }
227    }
228}
229
230impl Rule for MD051LinkFragments {
231    fn name(&self) -> &'static str {
232        "MD051"
233    }
234
235    fn description(&self) -> &'static str {
236        "Link fragments should reference valid headings"
237    }
238
239    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
240        // Skip if no link fragments present
241        if !ctx.likely_has_links_or_images() {
242            return true;
243        }
244        // Check for # character (fragments)
245        !ctx.has_char('#')
246    }
247
248    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
249        let mut warnings = Vec::new();
250
251        if ctx.content.is_empty() || ctx.links.is_empty() || self.should_skip(ctx) {
252            return Ok(warnings);
253        }
254
255        let (markdown_headings, html_anchors) = self.extract_headings_from_context(ctx);
256
257        for link in &ctx.links {
258            if link.is_reference {
259                continue;
260            }
261
262            // Skip wiki-links - they reference other files and may have their own fragment validation
263            if matches!(link.link_type, LinkType::WikiLink { .. }) {
264                continue;
265            }
266
267            // Skip links inside Jinja templates
268            if ctx.is_in_jinja_range(link.byte_offset) {
269                continue;
270            }
271
272            let url = &link.url;
273
274            // Skip links without fragments or external URLs
275            if !url.contains('#') || Self::is_external_url_fast(url) {
276                continue;
277            }
278
279            // Skip mdbook template placeholders ({{#VARIABLE}})
280            // mdbook uses {{#VARIABLE}} syntax where # is part of the template, not a fragment
281            if url.contains("{{#") && url.contains("}}") {
282                continue;
283            }
284
285            // Skip Quarto/RMarkdown cross-references (@fig-, @tbl-, @sec-, @eq-, etc.)
286            // These are special cross-reference syntax, not HTML anchors
287            // Format: @prefix-identifier or just @identifier
288            if url.starts_with('@') {
289                continue;
290            }
291
292            // Cross-file links are valid if the file exists (not checked here)
293            if Self::is_cross_file_link(url) {
294                continue;
295            }
296
297            let Some(fragment_pos) = url.find('#') else {
298                continue;
299            };
300
301            let fragment = &url[fragment_pos + 1..];
302
303            // Skip Liquid template variables and filters
304            if (url.contains("{{") && fragment.contains('|')) || fragment.ends_with("}}") || fragment.ends_with("%}") {
305                continue;
306            }
307
308            if fragment.is_empty() {
309                continue;
310            }
311
312            // Validate fragment against document headings
313            // HTML anchors are case-sensitive, markdown anchors are case-insensitive
314            let found = if html_anchors.contains(fragment) {
315                true
316            } else {
317                let fragment_lower = fragment.to_lowercase();
318                markdown_headings.contains(&fragment_lower)
319            };
320
321            if !found {
322                warnings.push(LintWarning {
323                    rule_name: Some(self.name().to_string()),
324                    message: format!("Link anchor '#{fragment}' does not exist in document headings"),
325                    line: link.line,
326                    column: link.start_col + 1,
327                    end_line: link.line,
328                    end_column: link.end_col + 1,
329                    severity: Severity::Warning,
330                    fix: None,
331                });
332            }
333        }
334
335        Ok(warnings)
336    }
337
338    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
339        // MD051 does not provide auto-fix
340        // Link fragment corrections require human judgment to avoid incorrect fixes
341        Ok(ctx.content.to_string())
342    }
343
344    fn as_any(&self) -> &dyn std::any::Any {
345        self
346    }
347
348    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
349    where
350        Self: Sized,
351    {
352        // Config keys are normalized to kebab-case by the config system
353        let anchor_style = if let Some(rule_config) = config.rules.get("MD051") {
354            if let Some(style_str) = rule_config.values.get("anchor-style").and_then(|v| v.as_str()) {
355                match style_str.to_lowercase().as_str() {
356                    "kramdown" => AnchorStyle::Kramdown,
357                    "kramdown-gfm" => AnchorStyle::KramdownGfm,
358                    "jekyll" => AnchorStyle::KramdownGfm, // Backward compatibility alias
359                    _ => AnchorStyle::GitHub,
360                }
361            } else {
362                AnchorStyle::GitHub
363            }
364        } else {
365            AnchorStyle::GitHub
366        };
367
368        Box::new(MD051LinkFragments::with_anchor_style(anchor_style))
369    }
370
371    fn category(&self) -> RuleCategory {
372        RuleCategory::Link
373    }
374
375    fn cross_file_scope(&self) -> CrossFileScope {
376        CrossFileScope::Workspace
377    }
378
379    fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, file_index: &mut FileIndex) {
380        let mut fragment_counts = HashMap::new();
381
382        // Extract headings (for other files to reference)
383        for (line_idx, line_info) in ctx.lines.iter().enumerate() {
384            if line_info.in_front_matter {
385                continue;
386            }
387
388            if let Some(heading) = &line_info.heading {
389                let fragment = self.anchor_style.generate_fragment(&heading.text);
390
391                if !fragment.is_empty() {
392                    // Handle duplicate headings
393                    let final_fragment = if let Some(count) = fragment_counts.get_mut(&fragment) {
394                        let suffix = *count;
395                        *count += 1;
396                        format!("{fragment}-{suffix}")
397                    } else {
398                        fragment_counts.insert(fragment.clone(), 1);
399                        fragment
400                    };
401
402                    file_index.add_heading(HeadingIndex {
403                        text: heading.text.clone(),
404                        auto_anchor: final_fragment,
405                        custom_anchor: heading.custom_id.clone(),
406                        line: line_idx + 1, // 1-indexed
407                    });
408                }
409            }
410        }
411
412        // Extract cross-file links (for validation against other files)
413        for link in &ctx.links {
414            if link.is_reference {
415                continue;
416            }
417
418            let url = &link.url;
419
420            // Skip external URLs
421            if Self::is_external_url_fast(url) {
422                continue;
423            }
424
425            // Only process cross-file links with fragments
426            if Self::is_cross_file_link(url)
427                && let Some(fragment_pos) = url.find('#')
428            {
429                let path_part = &url[..fragment_pos];
430                let fragment = &url[fragment_pos + 1..];
431
432                // Skip empty fragments or template syntax
433                if fragment.is_empty() || fragment.contains("{{") || fragment.contains("{%") {
434                    continue;
435                }
436
437                file_index.add_cross_file_link(CrossFileLinkIndex {
438                    target_path: path_part.to_string(),
439                    fragment: fragment.to_string(),
440                    line: link.line,
441                    column: link.start_col + 1,
442                });
443            }
444        }
445    }
446
447    fn cross_file_check(
448        &self,
449        file_path: &Path,
450        file_index: &FileIndex,
451        workspace_index: &crate::workspace_index::WorkspaceIndex,
452    ) -> LintResult {
453        let mut warnings = Vec::new();
454
455        // Check each cross-file link in this file
456        for cross_link in &file_index.cross_file_links {
457            // Skip cross-file links without fragments - nothing to validate
458            if cross_link.fragment.is_empty() {
459                continue;
460            }
461
462            // Resolve the target file path relative to the current file
463            let target_path = if let Some(parent) = file_path.parent() {
464                parent.join(&cross_link.target_path)
465            } else {
466                Path::new(&cross_link.target_path).to_path_buf()
467            };
468
469            // Normalize the path (remove . and ..)
470            let target_path = normalize_path(&target_path);
471
472            // Look up the target file in the workspace index
473            if let Some(target_file_index) = workspace_index.get_file(&target_path) {
474                // Check if the fragment matches any heading in the target file (O(1) lookup)
475                if !target_file_index.has_anchor(&cross_link.fragment) {
476                    warnings.push(LintWarning {
477                        rule_name: Some(self.name().to_string()),
478                        line: cross_link.line,
479                        column: cross_link.column,
480                        end_line: cross_link.line,
481                        end_column: cross_link.column + cross_link.target_path.len() + 1 + cross_link.fragment.len(),
482                        message: format!(
483                            "Link fragment '{}' not found in '{}'",
484                            cross_link.fragment, cross_link.target_path
485                        ),
486                        severity: Severity::Warning,
487                        fix: None,
488                    });
489                }
490            }
491            // If target file not in index, skip (could be external file or not in workspace)
492        }
493
494        Ok(warnings)
495    }
496
497    fn default_config_section(&self) -> Option<(String, toml::Value)> {
498        let value: toml::Value = toml::from_str(
499            r#"
500# Anchor generation style to match your target platform
501# Options: "github" (default), "kramdown-gfm", "kramdown"
502# Note: "jekyll" is accepted as an alias for "kramdown-gfm" (backward compatibility)
503anchor-style = "github"
504"#,
505        )
506        .ok()?;
507        Some(("MD051".to_string(), value))
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514    use crate::lint_context::LintContext;
515
516    #[test]
517    fn test_quarto_cross_references() {
518        let rule = MD051LinkFragments::new();
519
520        // Test that Quarto cross-references are skipped
521        let content = r#"# Test Document
522
523## Figures
524
525See [@fig-plot] for the visualization.
526
527More details in [@tbl-results] and [@sec-methods].
528
529The equation [@eq-regression] shows the relationship.
530
531Reference to [@lst-code] for implementation."#;
532        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
533        let result = rule.check(&ctx).unwrap();
534        assert!(
535            result.is_empty(),
536            "Quarto cross-references (@fig-, @tbl-, @sec-, @eq-) should not trigger MD051 warnings. Got {} warnings",
537            result.len()
538        );
539
540        // Test that normal anchors still work
541        let content_with_anchor = r#"# Test
542
543See [link](#test) for details."#;
544        let ctx_anchor = LintContext::new(content_with_anchor, crate::config::MarkdownFlavor::Quarto, None);
545        let result_anchor = rule.check(&ctx_anchor).unwrap();
546        assert!(result_anchor.is_empty(), "Valid anchor should not trigger warning");
547
548        // Test that invalid anchors are still flagged
549        let content_invalid = r#"# Test
550
551See [link](#nonexistent) for details."#;
552        let ctx_invalid = LintContext::new(content_invalid, crate::config::MarkdownFlavor::Quarto, None);
553        let result_invalid = rule.check(&ctx_invalid).unwrap();
554        assert_eq!(result_invalid.len(), 1, "Invalid anchor should still trigger warning");
555    }
556
557    // Cross-file validation tests
558    #[test]
559    fn test_cross_file_scope() {
560        let rule = MD051LinkFragments::new();
561        assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
562    }
563
564    #[test]
565    fn test_contribute_to_index_extracts_headings() {
566        let rule = MD051LinkFragments::new();
567        let content = "# First Heading\n\n# Second { #custom }\n\n## Third";
568        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
569
570        let mut file_index = FileIndex::new();
571        rule.contribute_to_index(&ctx, &mut file_index);
572
573        assert_eq!(file_index.headings.len(), 3);
574        assert_eq!(file_index.headings[0].text, "First Heading");
575        assert_eq!(file_index.headings[0].auto_anchor, "first-heading");
576        assert!(file_index.headings[0].custom_anchor.is_none());
577
578        assert_eq!(file_index.headings[1].text, "Second");
579        assert_eq!(file_index.headings[1].custom_anchor, Some("custom".to_string()));
580
581        assert_eq!(file_index.headings[2].text, "Third");
582    }
583
584    #[test]
585    fn test_contribute_to_index_extracts_cross_file_links() {
586        let rule = MD051LinkFragments::new();
587        let content = "See [docs](other.md#installation) and [more](../guide.md#getting-started)";
588        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
589
590        let mut file_index = FileIndex::new();
591        rule.contribute_to_index(&ctx, &mut file_index);
592
593        assert_eq!(file_index.cross_file_links.len(), 2);
594        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
595        assert_eq!(file_index.cross_file_links[0].fragment, "installation");
596        assert_eq!(file_index.cross_file_links[1].target_path, "../guide.md");
597        assert_eq!(file_index.cross_file_links[1].fragment, "getting-started");
598    }
599
600    #[test]
601    fn test_cross_file_check_valid_fragment() {
602        use crate::workspace_index::WorkspaceIndex;
603
604        let rule = MD051LinkFragments::new();
605
606        // Build workspace index with target file
607        let mut workspace_index = WorkspaceIndex::new();
608        let mut target_file_index = FileIndex::new();
609        target_file_index.add_heading(HeadingIndex {
610            text: "Installation Guide".to_string(),
611            auto_anchor: "installation-guide".to_string(),
612            custom_anchor: None,
613            line: 1,
614        });
615        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
616
617        // Create a FileIndex for the file being checked
618        let mut current_file_index = FileIndex::new();
619        current_file_index.add_cross_file_link(CrossFileLinkIndex {
620            target_path: "install.md".to_string(),
621            fragment: "installation-guide".to_string(),
622            line: 3,
623            column: 5,
624        });
625
626        let warnings = rule
627            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
628            .unwrap();
629
630        // Should find no warnings since fragment exists
631        assert!(warnings.is_empty());
632    }
633
634    #[test]
635    fn test_cross_file_check_invalid_fragment() {
636        use crate::workspace_index::WorkspaceIndex;
637
638        let rule = MD051LinkFragments::new();
639
640        // Build workspace index with target file
641        let mut workspace_index = WorkspaceIndex::new();
642        let mut target_file_index = FileIndex::new();
643        target_file_index.add_heading(HeadingIndex {
644            text: "Installation Guide".to_string(),
645            auto_anchor: "installation-guide".to_string(),
646            custom_anchor: None,
647            line: 1,
648        });
649        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
650
651        // Create a FileIndex with a cross-file link pointing to non-existent fragment
652        let mut current_file_index = FileIndex::new();
653        current_file_index.add_cross_file_link(CrossFileLinkIndex {
654            target_path: "install.md".to_string(),
655            fragment: "nonexistent".to_string(),
656            line: 3,
657            column: 5,
658        });
659
660        let warnings = rule
661            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
662            .unwrap();
663
664        // Should find one warning since fragment doesn't exist
665        assert_eq!(warnings.len(), 1);
666        assert!(warnings[0].message.contains("nonexistent"));
667        assert!(warnings[0].message.contains("install.md"));
668    }
669
670    #[test]
671    fn test_cross_file_check_custom_anchor_match() {
672        use crate::workspace_index::WorkspaceIndex;
673
674        let rule = MD051LinkFragments::new();
675
676        // Build workspace index with target file that has custom anchor
677        let mut workspace_index = WorkspaceIndex::new();
678        let mut target_file_index = FileIndex::new();
679        target_file_index.add_heading(HeadingIndex {
680            text: "Installation Guide".to_string(),
681            auto_anchor: "installation-guide".to_string(),
682            custom_anchor: Some("install".to_string()),
683            line: 1,
684        });
685        workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
686
687        // Link uses custom anchor
688        let mut current_file_index = FileIndex::new();
689        current_file_index.add_cross_file_link(CrossFileLinkIndex {
690            target_path: "install.md".to_string(),
691            fragment: "install".to_string(),
692            line: 3,
693            column: 5,
694        });
695
696        let warnings = rule
697            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
698            .unwrap();
699
700        // Should find no warnings since custom anchor matches
701        assert!(warnings.is_empty());
702    }
703
704    #[test]
705    fn test_cross_file_check_target_not_in_workspace() {
706        use crate::workspace_index::WorkspaceIndex;
707
708        let rule = MD051LinkFragments::new();
709
710        // Empty workspace index
711        let workspace_index = WorkspaceIndex::new();
712
713        // Link to file not in workspace
714        let mut current_file_index = FileIndex::new();
715        current_file_index.add_cross_file_link(CrossFileLinkIndex {
716            target_path: "external.md".to_string(),
717            fragment: "heading".to_string(),
718            line: 3,
719            column: 5,
720        });
721
722        let warnings = rule
723            .cross_file_check(Path::new("docs/readme.md"), &current_file_index, &workspace_index)
724            .unwrap();
725
726        // Should not warn about files not in workspace
727        assert!(warnings.is_empty());
728    }
729}