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;
9static HTML_ANCHOR_PATTERN: LazyLock<Regex> =
12 LazyLock::new(|| Regex::new(r#"\b(?:id|name)\s*=\s*["']([^"']+)["']"#).unwrap());
13
14static ATTR_ANCHOR_PATTERN: LazyLock<Regex> =
18 LazyLock::new(|| Regex::new(r#"\{\s*#([a-zA-Z0-9_][a-zA-Z0-9_-]*)[^}]*\}"#).unwrap());
19
20static MD_SETTING_PATTERN: LazyLock<Regex> =
23 LazyLock::new(|| Regex::new(r"<!--\s*md:setting\s+([^\s]+)\s*-->").unwrap());
24
25fn normalize_path(path: &Path) -> PathBuf {
27 let mut result = PathBuf::new();
28 for component in path.components() {
29 match component {
30 Component::CurDir => {} Component::ParentDir => {
32 result.pop(); }
34 c => result.push(c.as_os_str()),
35 }
36 }
37 result
38}
39
40#[derive(Clone)]
47pub struct MD051LinkFragments {
48 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 pub fn with_anchor_style(style: AnchorStyle) -> Self {
67 Self { anchor_style: style }
68 }
69
70 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 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 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 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 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 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 markdown_headings.insert(format!("{fragment}_{suffix}"));
135 markdown_headings.insert(format!("{fragment}-{suffix}"));
137 } else {
138 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 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 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 (format!("{fragment}_{suffix}"), Some(format!("{fragment}-{suffix}")))
183 } else {
184 (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 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 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 if bytes.contains(&b'<') && (content.contains("id=") || content.contains("name=")) {
237 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 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 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 markdown_headings.insert(id_match.as_str().to_lowercase());
276 }
277 }
278 }
279
280 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 if let Some(heading) = &line_info.heading {
301 if let Some(custom_id) = &heading.custom_id {
303 markdown_headings.insert(custom_id.to_lowercase());
304 }
305
306 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 #[inline]
325 fn is_external_url_fast(url: &str) -> bool {
326 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 #[inline]
343 fn resolve_path_with_extensions(path: &Path, extensions: &[&str]) -> Vec<PathBuf> {
344 if path.extension().is_none() {
345 let mut paths = Vec::with_capacity(extensions.len() + 1);
347 paths.push(path.to_path_buf());
349 for ext in extensions {
351 let path_with_ext = path.with_extension(&ext[1..]); paths.push(path_with_ext);
353 }
354 paths
355 } else {
356 vec![path.to_path_buf()]
358 }
359 }
360
361 #[inline]
375 fn is_extensionless_path(path_part: &str) -> bool {
376 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 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 return false;
394 }
395 }
396
397 has_alphanumeric
399 }
400
401 #[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 path_part.is_empty() {
409 return false;
410 }
411
412 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 if path_part.starts_with('/') {
431 return true;
432 }
433
434 let has_extension = path_part.contains('.')
440 && (
441 {
443 let clean_path = path_part.split('?').next().unwrap_or(path_part);
444 if let Some(after_dot) = clean_path.strip_prefix('.') {
446 let dots_count = clean_path.matches('.').count();
447 if dots_count == 1 {
448 !after_dot.is_empty() && after_dot.len() <= 10 &&
451 after_dot.chars().all(|c| c.is_ascii_alphanumeric())
452 } else {
453 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 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 path_part.contains('/') || path_part.contains('\\') ||
467 path_part.starts_with("./") || path_part.starts_with("../")
469 );
470
471 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 if !ctx.likely_has_links_or_images() {
494 return true;
495 }
496 !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 if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
516 continue;
517 }
518
519 if matches!(link.link_type, LinkType::WikiLink { .. }) {
521 continue;
522 }
523
524 if ctx.is_in_jinja_range(link.byte_offset) {
526 continue;
527 }
528
529 if ctx.flavor == crate::config::MarkdownFlavor::Quarto && ctx.is_in_citation(link.byte_offset) {
532 continue;
533 }
534
535 if ctx.is_in_shortcode(link.byte_offset) {
538 continue;
539 }
540
541 let url = &link.url;
542
543 if !url.contains('#') || Self::is_external_url_fast(url) {
545 continue;
546 }
547
548 if url.contains("{{#") && url.contains("}}") {
551 continue;
552 }
553
554 if url.starts_with('@') {
558 continue;
559 }
560
561 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 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 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 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 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 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 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 for (line_idx, line_info) in ctx.lines.iter().enumerate() {
671 if line_info.in_front_matter {
672 continue;
673 }
674
675 if line_info.in_code_block {
677 continue;
678 }
679
680 let content = line_info.content(ctx.content);
681
682 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 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 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 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 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 for link in &ctx.links {
763 if link.is_reference {
764 continue;
765 }
766
767 if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
769 continue;
770 }
771
772 if matches!(link.link_type, LinkType::WikiLink { .. }) {
775 continue;
776 }
777
778 let url = &link.url;
779
780 if Self::is_external_url_fast(url) {
782 continue;
783 }
784
785 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 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 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 for cross_link in &file_index.cross_file_links {
830 if cross_link.fragment.is_empty() {
832 continue;
833 }
834
835 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 let base_target_path = normalize_path(&base_target_path);
844
845 let target_paths_to_try = Self::resolve_path_with_extensions(&base_target_path, MARKDOWN_EXTENSIONS);
848
849 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 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 }
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 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 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 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 #[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 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 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"), ¤t_file_index, &workspace_index)
1015 .unwrap();
1016
1017 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 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 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"), ¤t_file_index, &workspace_index)
1050 .unwrap();
1051
1052 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 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 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"), ¤t_file_index, &workspace_index)
1087 .unwrap();
1088
1089 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 let workspace_index = WorkspaceIndex::new();
1101
1102 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"), ¤t_file_index, &workspace_index)
1113 .unwrap();
1114
1115 assert!(warnings.is_empty());
1117 }
1118
1119 #[test]
1120 fn test_wikilinks_skipped_in_check() {
1121 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 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 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}