1use crate::rule::{CrossFileScope, FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::rule_config_serde::RuleConfig;
3use crate::utils::anchor_styles::AnchorStyle;
4use crate::workspace_index::{CrossFileLinkIndex, FileIndex, HeadingIndex};
5use pulldown_cmark::LinkType;
6use regex::Regex;
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, HashSet};
9use std::path::{Component, Path, PathBuf};
10use std::sync::LazyLock;
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
14#[serde(rename_all = "kebab-case")]
15pub struct MD051Config {
16 #[serde(default, alias = "anchor_style")]
18 pub anchor_style: AnchorStyle,
19
20 #[serde(default = "default_ignore_case", alias = "ignore_case")]
26 pub ignore_case: bool,
27
28 #[serde(default, alias = "ignored_pattern")]
32 pub ignored_pattern: Option<String>,
33}
34
35fn default_ignore_case() -> bool {
36 true
37}
38
39impl Default for MD051Config {
40 fn default() -> Self {
41 Self {
42 anchor_style: AnchorStyle::default(),
43 ignore_case: true,
44 ignored_pattern: None,
45 }
46 }
47}
48
49impl RuleConfig for MD051Config {
50 const RULE_NAME: &'static str = "MD051";
51}
52static HTML_ANCHOR_PATTERN: LazyLock<Regex> =
55 LazyLock::new(|| Regex::new(r#"\b(?:id|name)\s*=\s*["']([^"']+)["']"#).unwrap());
56
57static ATTR_ANCHOR_PATTERN: LazyLock<Regex> =
61 LazyLock::new(|| Regex::new(r#"\{\s*#([a-zA-Z0-9_][a-zA-Z0-9_-]*)[^}]*\}"#).unwrap());
62
63static MD_SETTING_PATTERN: LazyLock<Regex> =
66 LazyLock::new(|| Regex::new(r"<!--\s*md:setting\s+([^\s]+)\s*-->").unwrap());
67
68fn normalize_path(path: &Path) -> PathBuf {
70 let mut result = PathBuf::new();
71 for component in path.components() {
72 match component {
73 Component::CurDir => {} Component::ParentDir => {
75 result.pop(); }
77 c => result.push(c.as_os_str()),
78 }
79 }
80 result
81}
82
83#[derive(Clone)]
90pub struct MD051LinkFragments {
91 config: MD051Config,
92 ignored_pattern_regex: Option<Regex>,
96}
97
98struct AnchorSets {
103 markdown_headings: HashSet<String>,
104 markdown_headings_exact: HashSet<String>,
105 html_anchors: HashSet<String>,
106 html_anchors_exact: HashSet<String>,
107}
108
109impl Default for MD051LinkFragments {
110 fn default() -> Self {
111 Self::new()
112 }
113}
114
115impl MD051LinkFragments {
116 pub fn new() -> Self {
117 Self::from_config_struct(MD051Config::default())
118 }
119
120 pub fn with_anchor_style(style: AnchorStyle) -> Self {
122 Self::from_config_struct(MD051Config {
123 anchor_style: style,
124 ..MD051Config::default()
125 })
126 }
127
128 pub fn from_config_struct(config: MD051Config) -> Self {
134 let ignored_pattern_regex = config
135 .ignored_pattern
136 .as_deref()
137 .and_then(|pattern| match Regex::new(pattern) {
138 Ok(re) => Some(re),
139 Err(err) => {
140 log::warn!(
141 "Invalid ignored_pattern regex for MD051 ('{pattern}'): {err}. Falling back to no filter."
142 );
143 None
144 }
145 });
146 Self {
147 config,
148 ignored_pattern_regex,
149 }
150 }
151
152 fn parse_blockquote_heading(bq_content: &str) -> Option<(String, Option<String>)> {
156 static BQ_ATX_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.*)$").unwrap());
157
158 let trimmed = bq_content.trim();
159 let caps = BQ_ATX_HEADING_RE.captures(trimmed)?;
160 let mut rest = caps.get(2).map_or("", |m| m.as_str()).to_string();
161
162 let rest_trimmed = rest.trim_end();
164 if let Some(last_hash_pos) = rest_trimmed.rfind('#') {
165 let after_hashes = &rest_trimmed[last_hash_pos..];
166 if after_hashes.chars().all(|c| c == '#') {
167 let mut hash_start = last_hash_pos;
169 while hash_start > 0 && rest_trimmed.as_bytes()[hash_start - 1] == b'#' {
170 hash_start -= 1;
171 }
172 if hash_start == 0
174 || rest_trimmed
175 .as_bytes()
176 .get(hash_start - 1)
177 .is_some_and(u8::is_ascii_whitespace)
178 {
179 rest = rest_trimmed[..hash_start].trim_end().to_string();
180 }
181 }
182 }
183
184 let (clean_text, custom_id) = crate::utils::header_id_utils::extract_header_id(&rest);
185 Some((clean_text, custom_id))
186 }
187
188 fn insert_deduplicated_fragment(
196 fragment: String,
197 fragment_counts: &mut HashMap<String, usize>,
198 markdown_headings: &mut HashSet<String>,
199 mut markdown_headings_exact: Option<&mut HashSet<String>>,
200 use_underscore_dedup: bool,
201 ) {
202 let mut also_insert_exact = |form: &str| {
208 if let Some(set) = markdown_headings_exact.as_deref_mut() {
209 set.insert(form.to_string());
210 }
211 };
212
213 if fragment.is_empty() {
214 if !use_underscore_dedup {
215 return;
216 }
217 let count = fragment_counts.entry(fragment).or_insert(0);
219 *count += 1;
220 let formed = format!("_{count}");
221 also_insert_exact(&formed);
222 markdown_headings.insert(formed);
223 return;
224 }
225 if let Some(count) = fragment_counts.get_mut(&fragment) {
226 let suffix = *count;
227 *count += 1;
228 if use_underscore_dedup {
229 let underscore_form = format!("{fragment}_{suffix}");
231 also_insert_exact(&underscore_form);
232 markdown_headings.insert(underscore_form);
233 let dash_form = format!("{fragment}-{suffix}");
235 also_insert_exact(&dash_form);
236 markdown_headings.insert(dash_form);
237 } else {
238 let form = format!("{fragment}-{suffix}");
240 also_insert_exact(&form);
241 markdown_headings.insert(form);
242 }
243 } else {
244 fragment_counts.insert(fragment.clone(), 1);
245 also_insert_exact(&fragment);
246 markdown_headings.insert(fragment);
247 }
248 }
249
250 fn add_heading_to_index(
256 fragment: &str,
257 text: &str,
258 custom_anchor: Option<String>,
259 line: usize,
260 fragment_counts: &mut HashMap<String, usize>,
261 file_index: &mut FileIndex,
262 use_underscore_dedup: bool,
263 ) {
264 if fragment.is_empty() {
265 if !use_underscore_dedup {
266 return;
267 }
268 let count = fragment_counts.entry(fragment.to_string()).or_insert(0);
270 *count += 1;
271 file_index.add_heading(HeadingIndex {
272 text: text.to_string(),
273 auto_anchor: format!("_{count}"),
274 custom_anchor,
275 line,
276 is_setext: false,
277 });
278 return;
279 }
280 if let Some(count) = fragment_counts.get_mut(fragment) {
281 let suffix = *count;
282 *count += 1;
283 let (primary, alias) = if use_underscore_dedup {
284 (format!("{fragment}_{suffix}"), Some(format!("{fragment}-{suffix}")))
286 } else {
287 (format!("{fragment}-{suffix}"), None)
289 };
290 file_index.add_heading(HeadingIndex {
291 text: text.to_string(),
292 auto_anchor: primary,
293 custom_anchor,
294 line,
295 is_setext: false,
296 });
297 if let Some(alias_anchor) = alias {
298 let heading_idx = file_index.headings.len() - 1;
299 file_index.add_anchor_alias(&alias_anchor, heading_idx);
300 }
301 } else {
302 fragment_counts.insert(fragment.to_string(), 1);
303 file_index.add_heading(HeadingIndex {
304 text: text.to_string(),
305 auto_anchor: fragment.to_string(),
306 custom_anchor,
307 line,
308 is_setext: false,
309 });
310 }
311 }
312
313 fn extract_headings_from_context(&self, ctx: &crate::lint_context::LintContext) -> AnchorSets {
320 let track_exact = !self.config.ignore_case;
321 let mut markdown_headings = HashSet::with_capacity(32);
322 let mut markdown_headings_exact = if track_exact {
323 HashSet::with_capacity(32)
324 } else {
325 HashSet::new()
326 };
327 let mut html_anchors = HashSet::with_capacity(16);
328 let mut html_anchors_exact = if track_exact {
329 HashSet::with_capacity(16)
330 } else {
331 HashSet::new()
332 };
333 let mut fragment_counts = std::collections::HashMap::new();
334 let use_underscore_dedup = self.config.anchor_style == AnchorStyle::PythonMarkdown;
335
336 for line_info in &ctx.lines {
337 if line_info.in_front_matter {
338 continue;
339 }
340
341 if line_info.in_code_block {
343 continue;
344 }
345
346 let content = line_info.content(ctx.content);
347 let bytes = content.as_bytes();
348
349 if bytes.contains(&b'<') && (content.contains("id=") || content.contains("name=")) {
351 let mut pos = 0;
354 while pos < content.len() {
355 if let Some(start) = content[pos..].find('<') {
356 let tag_start = pos + start;
357 if let Some(end) = content[tag_start..].find('>') {
358 let tag_end = tag_start + end + 1;
359 let tag = &content[tag_start..tag_end];
360
361 if let Some(caps) = HTML_ANCHOR_PATTERN.find(tag) {
363 let matched_text = caps.as_str();
364 if let Some(caps) = HTML_ANCHOR_PATTERN.captures(matched_text)
365 && let Some(id_match) = caps.get(1)
366 {
367 let id = id_match.as_str();
368 if !id.is_empty() {
369 html_anchors.insert(id.to_lowercase());
370 if track_exact {
371 html_anchors_exact.insert(id.to_string());
372 }
373 }
374 }
375 }
376 pos = tag_end;
377 } else {
378 break;
379 }
380 } else {
381 break;
382 }
383 }
384 }
385
386 if line_info.heading.is_none() && content.contains('{') && content.contains('#') {
389 for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
390 if let Some(id_match) = caps.get(1) {
391 let id = id_match.as_str();
392 markdown_headings.insert(id.to_lowercase());
393 if track_exact {
394 markdown_headings_exact.insert(id.to_string());
395 }
396 }
397 }
398 }
399
400 if line_info.heading.is_none()
404 && let Some(bq) = &line_info.blockquote
405 && let Some((clean_text, custom_id)) = Self::parse_blockquote_heading(&bq.content)
406 {
407 if let Some(id) = custom_id {
408 markdown_headings.insert(id.to_lowercase());
409 if track_exact {
410 markdown_headings_exact.insert(id);
411 }
412 }
413 let fragment = self.config.anchor_style.generate_fragment(&clean_text);
414 Self::insert_deduplicated_fragment(
415 fragment,
416 &mut fragment_counts,
417 &mut markdown_headings,
418 track_exact.then_some(&mut markdown_headings_exact),
419 use_underscore_dedup,
420 );
421 }
422
423 if let Some(heading) = &line_info.heading {
425 if let Some(custom_id) = &heading.custom_id {
427 markdown_headings.insert(custom_id.to_lowercase());
428 if track_exact {
429 markdown_headings_exact.insert(custom_id.clone());
430 }
431 }
432
433 let fragment = self.config.anchor_style.generate_fragment(&heading.text);
437
438 Self::insert_deduplicated_fragment(
439 fragment,
440 &mut fragment_counts,
441 &mut markdown_headings,
442 track_exact.then_some(&mut markdown_headings_exact),
443 use_underscore_dedup,
444 );
445 }
446 }
447
448 AnchorSets {
449 markdown_headings,
450 markdown_headings_exact,
451 html_anchors,
452 html_anchors_exact,
453 }
454 }
455
456 #[inline]
458 fn is_external_url_fast(url: &str) -> bool {
459 url.starts_with("http://")
461 || url.starts_with("https://")
462 || url.starts_with("ftp://")
463 || url.starts_with("mailto:")
464 || url.starts_with("tel:")
465 || url.starts_with("//")
466 }
467
468 #[inline]
476 fn resolve_path_with_extensions(path: &Path, extensions: &[&str]) -> Vec<PathBuf> {
477 if path.extension().is_none() {
478 let mut paths = Vec::with_capacity(extensions.len() + 1);
480 paths.push(path.to_path_buf());
482 for ext in extensions {
484 let path_with_ext = path.with_extension(&ext[1..]); paths.push(path_with_ext);
486 }
487 paths
488 } else {
489 vec![path.to_path_buf()]
491 }
492 }
493
494 #[inline]
508 fn is_extensionless_path(path_part: &str) -> bool {
509 if path_part.is_empty()
511 || path_part.contains('.')
512 || path_part.contains('?')
513 || path_part.contains('&')
514 || path_part.contains('=')
515 {
516 return false;
517 }
518
519 let mut has_alphanumeric = false;
521 for c in path_part.chars() {
522 if c.is_alphanumeric() {
523 has_alphanumeric = true;
524 } else if !matches!(c, '/' | '\\' | '-' | '_') {
525 return false;
527 }
528 }
529
530 has_alphanumeric
532 }
533
534 #[inline]
536 fn is_cross_file_link(url: &str) -> bool {
537 if let Some(fragment_pos) = url.find('#') {
538 let path_part = &url[..fragment_pos];
539
540 if path_part.is_empty() {
542 return false;
543 }
544
545 if let Some(tag_start) = path_part.find("{%")
551 && path_part[tag_start + 2..].contains("%}")
552 {
553 return true;
554 }
555 if let Some(var_start) = path_part.find("{{")
556 && path_part[var_start + 2..].contains("}}")
557 {
558 return true;
559 }
560
561 if path_part.starts_with('/') {
564 return true;
565 }
566
567 let has_extension = path_part.contains('.')
573 && (
574 {
576 let clean_path = path_part.split('?').next().unwrap_or(path_part);
577 if let Some(after_dot) = clean_path.strip_prefix('.') {
579 let dots_count = clean_path.matches('.').count();
580 if dots_count == 1 {
581 !after_dot.is_empty() && after_dot.len() <= 10 &&
584 after_dot.chars().all(|c| c.is_ascii_alphanumeric())
585 } else {
586 clean_path.split('.').next_back().is_some_and(|ext| {
588 !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
589 })
590 }
591 } else {
592 clean_path.split('.').next_back().is_some_and(|ext| {
594 !ext.is_empty() && ext.len() <= 10 && ext.chars().all(|c| c.is_ascii_alphanumeric())
595 })
596 }
597 } ||
598 path_part.contains('/') || path_part.contains('\\') ||
600 path_part.starts_with("./") || path_part.starts_with("../")
602 );
603
604 let is_extensionless = Self::is_extensionless_path(path_part);
607
608 has_extension || is_extensionless
609 } else {
610 false
611 }
612 }
613}
614
615impl Rule for MD051LinkFragments {
616 fn name(&self) -> &'static str {
617 "MD051"
618 }
619
620 fn description(&self) -> &'static str {
621 "Link fragments should reference valid headings"
622 }
623
624 fn fix_capability(&self) -> FixCapability {
625 FixCapability::Unfixable
626 }
627
628 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
629 if !ctx.likely_has_links_or_images() {
631 return true;
632 }
633 !ctx.has_char('#')
635 }
636
637 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
638 let mut warnings = Vec::new();
639
640 if ctx.content.is_empty() || ctx.links.is_empty() || self.should_skip(ctx) {
641 return Ok(warnings);
642 }
643
644 let AnchorSets {
645 markdown_headings,
646 markdown_headings_exact,
647 html_anchors,
648 html_anchors_exact,
649 } = self.extract_headings_from_context(ctx);
650 let ignored_pattern = self.ignored_pattern_regex.as_ref();
651
652 for link in &ctx.links {
653 if link.is_reference {
654 continue;
655 }
656
657 if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
659 continue;
660 }
661
662 if matches!(link.link_type, LinkType::WikiLink { .. }) {
664 continue;
665 }
666
667 if ctx.is_in_jinja_range(link.byte_offset) {
669 continue;
670 }
671
672 if ctx.flavor == crate::config::MarkdownFlavor::Quarto && ctx.is_in_citation(link.byte_offset) {
675 continue;
676 }
677
678 if ctx.is_in_shortcode(link.byte_offset) {
681 continue;
682 }
683
684 let url = &link.url;
685
686 if !url.contains('#') || Self::is_external_url_fast(url) {
688 continue;
689 }
690
691 if url.contains("{{#") && url.contains("}}") {
694 continue;
695 }
696
697 if url.starts_with('@') {
701 continue;
702 }
703
704 if Self::is_cross_file_link(url) {
706 continue;
707 }
708
709 let Some(fragment_pos) = url.find('#') else {
710 continue;
711 };
712
713 let fragment = &url[fragment_pos + 1..];
714
715 if (url.contains("{{") && fragment.contains('|')) || fragment.ends_with("}}") || fragment.ends_with("%}") {
717 continue;
718 }
719
720 if fragment.is_empty() {
721 continue;
722 }
723
724 if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
729 && (fragment.starts_with("fn:")
730 || fragment.starts_with("fnref:")
731 || (fragment.starts_with('+') && (fragment.contains('.') || fragment.contains(':'))))
732 {
733 continue;
734 }
735
736 if ignored_pattern.is_some_and(|re| re.is_match(fragment)) {
738 continue;
739 }
740
741 let found = if self.config.ignore_case {
745 let lower = fragment.to_lowercase();
746 html_anchors.contains(&lower) || markdown_headings.contains(&lower)
747 } else {
748 html_anchors_exact.contains(fragment) || markdown_headings_exact.contains(fragment)
749 };
750
751 if !found {
752 warnings.push(LintWarning {
753 rule_name: Some(self.name().to_string()),
754 message: format!("Link anchor '#{fragment}' does not exist in document headings"),
755 line: link.line,
756 column: link.start_col + 1,
757 end_line: link.line,
758 end_column: link.end_col + 1,
759 severity: Severity::Error,
760 fix: None,
761 });
762 }
763 }
764
765 Ok(warnings)
766 }
767
768 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
769 Ok(ctx.content.to_string())
772 }
773
774 fn as_any(&self) -> &dyn std::any::Any {
775 self
776 }
777
778 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
779 where
780 Self: Sized,
781 {
782 let mut rule_config = crate::rule_config_serde::load_rule_config::<MD051Config>(config);
783
784 let explicit_style_present = config
787 .rules
788 .get("MD051")
789 .is_some_and(|rc| rc.values.contains_key("anchor-style") || rc.values.contains_key("anchor_style"));
790 if !explicit_style_present {
791 rule_config.anchor_style = match config.global.flavor {
792 crate::config::MarkdownFlavor::MkDocs => AnchorStyle::PythonMarkdown,
793 crate::config::MarkdownFlavor::Kramdown => AnchorStyle::KramdownGfm,
794 _ => AnchorStyle::GitHub,
795 };
796 }
797
798 Box::new(MD051LinkFragments::from_config_struct(rule_config))
799 }
800
801 fn category(&self) -> RuleCategory {
802 RuleCategory::Link
803 }
804
805 fn cross_file_scope(&self) -> CrossFileScope {
806 CrossFileScope::Workspace
807 }
808
809 fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, file_index: &mut FileIndex) {
810 let mut fragment_counts = HashMap::new();
811 let use_underscore_dedup = self.config.anchor_style == AnchorStyle::PythonMarkdown;
812
813 for (line_idx, line_info) in ctx.lines.iter().enumerate() {
815 if line_info.in_front_matter {
816 continue;
817 }
818
819 if line_info.in_code_block {
821 continue;
822 }
823
824 let content = line_info.content(ctx.content);
825
826 if content.contains('<') && (content.contains("id=") || content.contains("name=")) {
828 let mut pos = 0;
829 while pos < content.len() {
830 if let Some(start) = content[pos..].find('<') {
831 let tag_start = pos + start;
832 if let Some(end) = content[tag_start..].find('>') {
833 let tag_end = tag_start + end + 1;
834 let tag = &content[tag_start..tag_end];
835
836 if let Some(caps) = HTML_ANCHOR_PATTERN.captures(tag)
837 && let Some(id_match) = caps.get(1)
838 {
839 file_index.add_html_anchor(id_match.as_str());
840 }
841 pos = tag_end;
842 } else {
843 break;
844 }
845 } else {
846 break;
847 }
848 }
849 }
850
851 if line_info.heading.is_none() && content.contains('{') && content.contains('#') {
854 for caps in ATTR_ANCHOR_PATTERN.captures_iter(content) {
855 if let Some(id_match) = caps.get(1) {
856 file_index.add_attribute_anchor(id_match.as_str());
857 }
858 }
859 }
860
861 if line_info.heading.is_none()
863 && let Some(bq) = &line_info.blockquote
864 && let Some((clean_text, custom_id)) = Self::parse_blockquote_heading(&bq.content)
865 {
866 let fragment = self.config.anchor_style.generate_fragment(&clean_text);
867 Self::add_heading_to_index(
868 &fragment,
869 &clean_text,
870 custom_id,
871 line_idx + 1,
872 &mut fragment_counts,
873 file_index,
874 use_underscore_dedup,
875 );
876 }
877
878 if let Some(heading) = &line_info.heading {
880 let fragment = self.config.anchor_style.generate_fragment(&heading.text);
881
882 Self::add_heading_to_index(
883 &fragment,
884 &heading.text,
885 heading.custom_id.clone(),
886 line_idx + 1,
887 &mut fragment_counts,
888 file_index,
889 use_underscore_dedup,
890 );
891
892 if ctx.flavor == crate::config::MarkdownFlavor::MkDocs
897 && let Some(caps) = MD_SETTING_PATTERN.captures(content)
898 && let Some(name) = caps.get(1)
899 {
900 file_index.add_html_anchor(name.as_str());
901 }
902 }
903 }
904
905 for link in &ctx.links {
907 if link.is_reference {
908 continue;
909 }
910
911 if ctx.line_info(link.line).is_some_and(|info| info.in_pymdown_block) {
913 continue;
914 }
915
916 if matches!(link.link_type, LinkType::WikiLink { .. }) {
919 continue;
920 }
921
922 let url = &link.url;
923
924 if Self::is_external_url_fast(url) {
926 continue;
927 }
928
929 if Self::is_cross_file_link(url)
931 && let Some(fragment_pos) = url.find('#')
932 {
933 let path_part = &url[..fragment_pos];
934 let fragment = &url[fragment_pos + 1..];
935
936 if fragment.is_empty() || fragment.contains("{{") || fragment.contains("{%") {
938 continue;
939 }
940
941 file_index.add_cross_file_link(CrossFileLinkIndex {
942 target_path: path_part.to_string(),
943 fragment: fragment.to_string(),
944 line: link.line,
945 column: link.start_col + 1,
946 });
947 }
948 }
949 }
950
951 fn cross_file_check(
952 &self,
953 file_path: &Path,
954 file_index: &FileIndex,
955 workspace_index: &crate::workspace_index::WorkspaceIndex,
956 ) -> LintResult {
957 let mut warnings = Vec::new();
958
959 const MARKDOWN_EXTENSIONS: &[&str] = &[
961 ".md",
962 ".markdown",
963 ".mdx",
964 ".mkd",
965 ".mkdn",
966 ".mdown",
967 ".mdwn",
968 ".qmd",
969 ".rmd",
970 ];
971
972 let ignored_pattern = self.ignored_pattern_regex.as_ref();
973 let ignore_case = self.config.ignore_case;
974
975 for cross_link in &file_index.cross_file_links {
977 if cross_link.fragment.is_empty() {
979 continue;
980 }
981
982 if ignored_pattern.is_some_and(|re| re.is_match(&cross_link.fragment)) {
984 continue;
985 }
986
987 let base_target_path = if let Some(parent) = file_path.parent() {
989 parent.join(&cross_link.target_path)
990 } else {
991 Path::new(&cross_link.target_path).to_path_buf()
992 };
993
994 let base_target_path = normalize_path(&base_target_path);
996
997 let target_paths_to_try = Self::resolve_path_with_extensions(&base_target_path, MARKDOWN_EXTENSIONS);
1000
1001 let mut target_file_index = None;
1003
1004 for target_path in &target_paths_to_try {
1005 if let Some(index) = workspace_index.get_file(target_path) {
1006 target_file_index = Some(index);
1007 break;
1008 }
1009 }
1010
1011 if let Some(target_file_index) = target_file_index {
1012 if !target_file_index.has_anchor_with_case(&cross_link.fragment, ignore_case) {
1014 warnings.push(LintWarning {
1015 rule_name: Some(self.name().to_string()),
1016 line: cross_link.line,
1017 column: cross_link.column,
1018 end_line: cross_link.line,
1019 end_column: cross_link.column + cross_link.target_path.len() + 1 + cross_link.fragment.len(),
1020 message: format!(
1021 "Link fragment '{}' not found in '{}'",
1022 cross_link.fragment, cross_link.target_path
1023 ),
1024 severity: Severity::Error,
1025 fix: None,
1026 });
1027 }
1028 }
1029 }
1031
1032 Ok(warnings)
1033 }
1034
1035 fn default_config_section(&self) -> Option<(String, toml::Value)> {
1036 let table = crate::rule_config_serde::config_schema_table(&MD051Config::default())?;
1037 if table.is_empty() {
1038 None
1039 } else {
1040 Some((MD051Config::RULE_NAME.to_string(), toml::Value::Table(table)))
1041 }
1042 }
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047 use super::*;
1048 use crate::lint_context::LintContext;
1049
1050 #[test]
1051 fn test_quarto_cross_references() {
1052 let rule = MD051LinkFragments::new();
1053
1054 let content = r#"# Test Document
1056
1057## Figures
1058
1059See [@fig-plot] for the visualization.
1060
1061More details in [@tbl-results] and [@sec-methods].
1062
1063The equation [@eq-regression] shows the relationship.
1064
1065Reference to [@lst-code] for implementation."#;
1066 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
1067 let result = rule.check(&ctx).unwrap();
1068 assert!(
1069 result.is_empty(),
1070 "Quarto cross-references (@fig-, @tbl-, @sec-, @eq-) should not trigger MD051 warnings. Got {} warnings",
1071 result.len()
1072 );
1073
1074 let content_with_anchor = r#"# Test
1076
1077See [link](#test) for details."#;
1078 let ctx_anchor = LintContext::new(content_with_anchor, crate::config::MarkdownFlavor::Quarto, None);
1079 let result_anchor = rule.check(&ctx_anchor).unwrap();
1080 assert!(result_anchor.is_empty(), "Valid anchor should not trigger warning");
1081
1082 let content_invalid = r#"# Test
1084
1085See [link](#nonexistent) for details."#;
1086 let ctx_invalid = LintContext::new(content_invalid, crate::config::MarkdownFlavor::Quarto, None);
1087 let result_invalid = rule.check(&ctx_invalid).unwrap();
1088 assert_eq!(result_invalid.len(), 1, "Invalid anchor should still trigger warning");
1089 }
1090
1091 #[test]
1092 fn test_jsx_in_heading_anchor() {
1093 let rule = MD051LinkFragments::new();
1095
1096 let content = "# Test\n\n### `retentionPolicy`<Component />\n\n[link](#retentionpolicy)\n";
1098 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1099 let result = rule.check(&ctx).unwrap();
1100 assert!(
1101 result.is_empty(),
1102 "JSX self-closing tag should be stripped from anchor: got {result:?}"
1103 );
1104
1105 let content2 =
1107 "### retentionPolicy<HeaderTag type=\"danger\" text=\"required\" />\n\n[link](#retentionpolicy)\n";
1108 let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1109 let result2 = rule.check(&ctx2).unwrap();
1110 assert!(
1111 result2.is_empty(),
1112 "JSX tag with attributes should be stripped from anchor: got {result2:?}"
1113 );
1114
1115 let content3 = "### Test <span>extra</span>\n\n[link](#test-extra)\n";
1117 let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
1118 let result3 = rule.check(&ctx3).unwrap();
1119 assert!(
1120 result3.is_empty(),
1121 "HTML tag content should be preserved in anchor: got {result3:?}"
1122 );
1123 }
1124
1125 #[test]
1127 fn test_cross_file_scope() {
1128 let rule = MD051LinkFragments::new();
1129 assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
1130 }
1131
1132 #[test]
1133 fn test_contribute_to_index_extracts_headings() {
1134 let rule = MD051LinkFragments::new();
1135 let content = "# First Heading\n\n# Second { #custom }\n\n## Third";
1136 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1137
1138 let mut file_index = FileIndex::new();
1139 rule.contribute_to_index(&ctx, &mut file_index);
1140
1141 assert_eq!(file_index.headings.len(), 3);
1142 assert_eq!(file_index.headings[0].text, "First Heading");
1143 assert_eq!(file_index.headings[0].auto_anchor, "first-heading");
1144 assert!(file_index.headings[0].custom_anchor.is_none());
1145
1146 assert_eq!(file_index.headings[1].text, "Second");
1147 assert_eq!(file_index.headings[1].custom_anchor, Some("custom".to_string()));
1148
1149 assert_eq!(file_index.headings[2].text, "Third");
1150 }
1151
1152 #[test]
1153 fn test_contribute_to_index_extracts_cross_file_links() {
1154 let rule = MD051LinkFragments::new();
1155 let content = "See [docs](other.md#installation) and [more](../guide.md#getting-started)";
1156 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1157
1158 let mut file_index = FileIndex::new();
1159 rule.contribute_to_index(&ctx, &mut file_index);
1160
1161 assert_eq!(file_index.cross_file_links.len(), 2);
1162 assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
1163 assert_eq!(file_index.cross_file_links[0].fragment, "installation");
1164 assert_eq!(file_index.cross_file_links[1].target_path, "../guide.md");
1165 assert_eq!(file_index.cross_file_links[1].fragment, "getting-started");
1166 }
1167
1168 #[test]
1169 fn test_cross_file_check_valid_fragment() {
1170 use crate::workspace_index::WorkspaceIndex;
1171
1172 let rule = MD051LinkFragments::new();
1173
1174 let mut workspace_index = WorkspaceIndex::new();
1176 let mut target_file_index = FileIndex::new();
1177 target_file_index.add_heading(HeadingIndex {
1178 text: "Installation Guide".to_string(),
1179 auto_anchor: "installation-guide".to_string(),
1180 custom_anchor: None,
1181 line: 1,
1182 is_setext: false,
1183 });
1184 workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1185
1186 let mut current_file_index = FileIndex::new();
1188 current_file_index.add_cross_file_link(CrossFileLinkIndex {
1189 target_path: "install.md".to_string(),
1190 fragment: "installation-guide".to_string(),
1191 line: 3,
1192 column: 5,
1193 });
1194
1195 let warnings = rule
1196 .cross_file_check(Path::new("docs/readme.md"), ¤t_file_index, &workspace_index)
1197 .unwrap();
1198
1199 assert!(warnings.is_empty());
1201 }
1202
1203 #[test]
1204 fn test_cross_file_check_invalid_fragment() {
1205 use crate::workspace_index::WorkspaceIndex;
1206
1207 let rule = MD051LinkFragments::new();
1208
1209 let mut workspace_index = WorkspaceIndex::new();
1211 let mut target_file_index = FileIndex::new();
1212 target_file_index.add_heading(HeadingIndex {
1213 text: "Installation Guide".to_string(),
1214 auto_anchor: "installation-guide".to_string(),
1215 custom_anchor: None,
1216 line: 1,
1217 is_setext: false,
1218 });
1219 workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1220
1221 let mut current_file_index = FileIndex::new();
1223 current_file_index.add_cross_file_link(CrossFileLinkIndex {
1224 target_path: "install.md".to_string(),
1225 fragment: "nonexistent".to_string(),
1226 line: 3,
1227 column: 5,
1228 });
1229
1230 let warnings = rule
1231 .cross_file_check(Path::new("docs/readme.md"), ¤t_file_index, &workspace_index)
1232 .unwrap();
1233
1234 assert_eq!(warnings.len(), 1);
1236 assert!(warnings[0].message.contains("nonexistent"));
1237 assert!(warnings[0].message.contains("install.md"));
1238 }
1239
1240 #[test]
1241 fn test_cross_file_check_custom_anchor_match() {
1242 use crate::workspace_index::WorkspaceIndex;
1243
1244 let rule = MD051LinkFragments::new();
1245
1246 let mut workspace_index = WorkspaceIndex::new();
1248 let mut target_file_index = FileIndex::new();
1249 target_file_index.add_heading(HeadingIndex {
1250 text: "Installation Guide".to_string(),
1251 auto_anchor: "installation-guide".to_string(),
1252 custom_anchor: Some("install".to_string()),
1253 line: 1,
1254 is_setext: false,
1255 });
1256 workspace_index.insert_file(PathBuf::from("docs/install.md"), target_file_index);
1257
1258 let mut current_file_index = FileIndex::new();
1260 current_file_index.add_cross_file_link(CrossFileLinkIndex {
1261 target_path: "install.md".to_string(),
1262 fragment: "install".to_string(),
1263 line: 3,
1264 column: 5,
1265 });
1266
1267 let warnings = rule
1268 .cross_file_check(Path::new("docs/readme.md"), ¤t_file_index, &workspace_index)
1269 .unwrap();
1270
1271 assert!(warnings.is_empty());
1273 }
1274
1275 #[test]
1276 fn test_cross_file_check_target_not_in_workspace() {
1277 use crate::workspace_index::WorkspaceIndex;
1278
1279 let rule = MD051LinkFragments::new();
1280
1281 let workspace_index = WorkspaceIndex::new();
1283
1284 let mut current_file_index = FileIndex::new();
1286 current_file_index.add_cross_file_link(CrossFileLinkIndex {
1287 target_path: "external.md".to_string(),
1288 fragment: "heading".to_string(),
1289 line: 3,
1290 column: 5,
1291 });
1292
1293 let warnings = rule
1294 .cross_file_check(Path::new("docs/readme.md"), ¤t_file_index, &workspace_index)
1295 .unwrap();
1296
1297 assert!(warnings.is_empty());
1299 }
1300
1301 #[test]
1302 fn test_wikilinks_skipped_in_check() {
1303 let rule = MD051LinkFragments::new();
1305
1306 let content = r#"# Test Document
1307
1308## Valid Heading
1309
1310[[Microsoft#Windows OS]]
1311[[SomePage#section]]
1312[[page|Display Text]]
1313[[path/to/page#section]]
1314"#;
1315 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1316 let result = rule.check(&ctx).unwrap();
1317
1318 assert!(
1319 result.is_empty(),
1320 "Wikilinks should not trigger MD051 warnings. Got: {result:?}"
1321 );
1322 }
1323
1324 #[test]
1325 fn test_wikilinks_not_added_to_cross_file_index() {
1326 let rule = MD051LinkFragments::new();
1328
1329 let content = r#"# Test Document
1330
1331[[Microsoft#Windows OS]]
1332[[SomePage#section]]
1333[Regular Link](other.md#section)
1334"#;
1335 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1336
1337 let mut file_index = FileIndex::new();
1338 rule.contribute_to_index(&ctx, &mut file_index);
1339
1340 let cross_file_links = &file_index.cross_file_links;
1343 assert_eq!(
1344 cross_file_links.len(),
1345 1,
1346 "Only regular markdown links should be indexed, not wikilinks. Got: {cross_file_links:?}"
1347 );
1348 assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
1349 assert_eq!(file_index.cross_file_links[0].fragment, "section");
1350 }
1351}