1use crate::lint_context::LintContext;
2use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
3use pulldown_cmark::LinkType;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7enum WhitespaceIssue {
8 Leading,
9 Trailing,
10 Both,
11}
12
13impl WhitespaceIssue {
14 fn message(self, is_image: bool) -> String {
15 let element = if is_image { "Image" } else { "Link" };
16 match self {
17 WhitespaceIssue::Leading => {
18 format!("{element} destination has leading whitespace")
19 }
20 WhitespaceIssue::Trailing => {
21 format!("{element} destination has trailing whitespace")
22 }
23 WhitespaceIssue::Both => {
24 format!("{element} destination has leading and trailing whitespace")
25 }
26 }
27 }
28}
29
30#[derive(Debug, Default, Clone)]
44pub struct MD062LinkDestinationWhitespace;
45
46impl MD062LinkDestinationWhitespace {
47 pub fn new() -> Self {
48 Self
49 }
50
51 fn extract_destination_info<'a>(&self, raw_link: &'a str) -> Option<(usize, usize, &'a str)> {
54 let mut bracket_depth = 0;
57 let mut paren_start = None;
58
59 for (i, c) in raw_link.char_indices() {
60 match c {
61 '[' => bracket_depth += 1,
62 ']' => {
63 bracket_depth -= 1;
64 if bracket_depth == 0 {
65 let rest = &raw_link[i + 1..];
67 if rest.starts_with('(') {
68 paren_start = Some(i + 1);
69 }
70 break;
71 }
72 }
73 _ => {}
74 }
75 }
76
77 let paren_start = paren_start?;
78
79 let dest_content_start = paren_start + 1; let rest = &raw_link[dest_content_start..];
82
83 let mut depth = 1;
85 let mut in_angle_brackets = false;
86 let mut dest_content_end = None;
87
88 for (i, c) in rest.char_indices() {
89 match c {
90 '<' if !in_angle_brackets => in_angle_brackets = true,
91 '>' if in_angle_brackets => in_angle_brackets = false,
92 '(' if !in_angle_brackets => depth += 1,
93 ')' if !in_angle_brackets => {
94 depth -= 1;
95 if depth == 0 {
96 dest_content_end = Some(i);
97 break;
98 }
99 }
100 _ => {}
101 }
102 }
103
104 let dest_content_end = dest_content_end?;
108
109 let dest_content = &rest[..dest_content_end];
110
111 Some((dest_content_start, dest_content_start + dest_content_end, dest_content))
112 }
113
114 fn check_destination_whitespace(&self, full_dest: &str) -> Option<WhitespaceIssue> {
117 if full_dest.is_empty() {
118 return None;
119 }
120
121 let first_char = full_dest.chars().next();
122 let last_char = full_dest.chars().last();
123
124 let has_leading = first_char.is_some_and(|c| c.is_whitespace());
125
126 let has_trailing = if last_char.is_some_and(|c| c.is_whitespace()) {
128 true
129 } else if let Some(title_start) = full_dest.find(['"', '\'']) {
130 let url_portion = &full_dest[..title_start];
131 url_portion.ends_with(char::is_whitespace)
132 } else {
133 false
134 };
135
136 match (has_leading, has_trailing) {
137 (true, true) => Some(WhitespaceIssue::Both),
138 (true, false) => Some(WhitespaceIssue::Leading),
139 (false, true) => Some(WhitespaceIssue::Trailing),
140 (false, false) => None,
141 }
142 }
143
144 fn create_fix(&self, raw_link: &str) -> Option<String> {
146 let (dest_start, dest_end, _) = self.extract_destination_info(raw_link)?;
147
148 let full_dest_content = &raw_link[dest_start..dest_end];
150
151 let (url_part, title_part) = if let Some(title_start) = full_dest_content.find(['"', '\'']) {
153 let url = full_dest_content[..title_start].trim();
154 let title = &full_dest_content[title_start..];
155 (url, Some(title.trim()))
156 } else {
157 (full_dest_content.trim(), None)
158 };
159
160 let text_part = &raw_link[..dest_start]; let mut fixed = String::with_capacity(raw_link.len());
164 fixed.push_str(text_part);
165 fixed.push_str(url_part);
166 if let Some(title) = title_part {
167 fixed.push(' ');
168 fixed.push_str(title);
169 }
170 fixed.push(')');
171
172 if fixed != raw_link { Some(fixed) } else { None }
174 }
175}
176
177impl Rule for MD062LinkDestinationWhitespace {
178 fn name(&self) -> &'static str {
179 "MD062"
180 }
181
182 fn description(&self) -> &'static str {
183 "Link destination should not have leading or trailing whitespace"
184 }
185
186 fn category(&self) -> RuleCategory {
187 RuleCategory::Link
188 }
189
190 fn should_skip(&self, ctx: &LintContext) -> bool {
191 ctx.content.is_empty() || !ctx.likely_has_links_or_images()
192 }
193
194 fn check(&self, ctx: &LintContext) -> LintResult {
195 let mut warnings = Vec::new();
196
197 for link in &ctx.links {
199 if link.is_reference || !matches!(link.link_type, LinkType::Inline) {
201 continue;
202 }
203
204 if ctx.is_in_jinja_range(link.byte_offset) {
206 continue;
207 }
208
209 let raw_link = &ctx.content[link.byte_offset..link.byte_end];
211
212 if let Some((_, _, raw_dest)) = self.extract_destination_info(raw_link)
214 && let Some(issue) = self.check_destination_whitespace(raw_dest)
215 && let Some(fixed) = self.create_fix(raw_link)
216 {
217 warnings.push(LintWarning {
218 rule_name: Some(self.name().to_string()),
219 line: link.line,
220 column: link.start_col + 1,
221 end_line: link.line,
222 end_column: link.end_col + 1,
223 message: issue.message(false),
224 severity: Severity::Warning,
225 fix: Some(Fix {
226 range: link.byte_offset..link.byte_end,
227 replacement: fixed,
228 }),
229 });
230 }
231 }
232
233 for image in &ctx.images {
235 if image.is_reference || !matches!(image.link_type, LinkType::Inline) {
237 continue;
238 }
239
240 if ctx.is_in_jinja_range(image.byte_offset) {
242 continue;
243 }
244
245 let raw_image = &ctx.content[image.byte_offset..image.byte_end];
247
248 let link_portion = raw_image.strip_prefix('!').unwrap_or(raw_image);
250
251 if let Some((_, _, raw_dest)) = self.extract_destination_info(link_portion)
253 && let Some(issue) = self.check_destination_whitespace(raw_dest)
254 && let Some(fixed_link) = self.create_fix(link_portion)
255 {
256 let fixed = format!("!{fixed_link}");
257 warnings.push(LintWarning {
258 rule_name: Some(self.name().to_string()),
259 line: image.line,
260 column: image.start_col + 1,
261 end_line: image.line,
262 end_column: image.end_col + 1,
263 message: issue.message(true),
264 severity: Severity::Warning,
265 fix: Some(Fix {
266 range: image.byte_offset..image.byte_end,
267 replacement: fixed,
268 }),
269 });
270 }
271 }
272
273 Ok(warnings)
274 }
275
276 fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
277 let warnings = self.check(ctx)?;
278
279 if warnings.is_empty() {
280 return Ok(ctx.content.to_string());
281 }
282
283 let mut content = ctx.content.to_string();
284 let mut fixes: Vec<_> = warnings
285 .into_iter()
286 .filter_map(|w| w.fix.map(|f| (f.range.start, f.range.end, f.replacement)))
287 .collect();
288
289 fixes.sort_by_key(|(start, _, _)| *start);
291
292 for (start, end, replacement) in fixes.into_iter().rev() {
293 content.replace_range(start..end, &replacement);
294 }
295
296 Ok(content)
297 }
298
299 fn as_any(&self) -> &dyn std::any::Any {
300 self
301 }
302
303 fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
304 where
305 Self: Sized,
306 {
307 Box::new(Self)
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use crate::config::MarkdownFlavor;
315
316 #[test]
317 fn test_no_whitespace() {
318 let rule = MD062LinkDestinationWhitespace::new();
319 let content = "[link](https://example.com)";
320 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
321 let warnings = rule.check(&ctx).unwrap();
322 assert!(warnings.is_empty());
323 }
324
325 #[test]
326 fn test_leading_whitespace() {
327 let rule = MD062LinkDestinationWhitespace::new();
328 let content = "[link]( https://example.com)";
329 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
330 let warnings = rule.check(&ctx).unwrap();
331 assert_eq!(warnings.len(), 1);
332 assert_eq!(
333 warnings[0].fix.as_ref().unwrap().replacement,
334 "[link](https://example.com)"
335 );
336 }
337
338 #[test]
339 fn test_trailing_whitespace() {
340 let rule = MD062LinkDestinationWhitespace::new();
341 let content = "[link](https://example.com )";
342 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
343 let warnings = rule.check(&ctx).unwrap();
344 assert_eq!(warnings.len(), 1);
345 assert_eq!(
346 warnings[0].fix.as_ref().unwrap().replacement,
347 "[link](https://example.com)"
348 );
349 }
350
351 #[test]
352 fn test_both_whitespace() {
353 let rule = MD062LinkDestinationWhitespace::new();
354 let content = "[link]( https://example.com )";
355 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
356 let warnings = rule.check(&ctx).unwrap();
357 assert_eq!(warnings.len(), 1);
358 assert_eq!(
359 warnings[0].fix.as_ref().unwrap().replacement,
360 "[link](https://example.com)"
361 );
362 }
363
364 #[test]
365 fn test_multiple_spaces() {
366 let rule = MD062LinkDestinationWhitespace::new();
367 let content = "[link]( https://example.com )";
368 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
369 let warnings = rule.check(&ctx).unwrap();
370 assert_eq!(warnings.len(), 1);
371 assert_eq!(
372 warnings[0].fix.as_ref().unwrap().replacement,
373 "[link](https://example.com)"
374 );
375 }
376
377 #[test]
378 fn test_with_title() {
379 let rule = MD062LinkDestinationWhitespace::new();
380 let content = "[link]( https://example.com \"title\")";
381 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
382 let warnings = rule.check(&ctx).unwrap();
383 assert_eq!(warnings.len(), 1);
384 assert_eq!(
385 warnings[0].fix.as_ref().unwrap().replacement,
386 "[link](https://example.com \"title\")"
387 );
388 }
389
390 #[test]
391 fn test_image_leading_whitespace() {
392 let rule = MD062LinkDestinationWhitespace::new();
393 let content = "";
394 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
395 let warnings = rule.check(&ctx).unwrap();
396 assert_eq!(warnings.len(), 1);
397 assert_eq!(
398 warnings[0].fix.as_ref().unwrap().replacement,
399 ""
400 );
401 }
402
403 #[test]
404 fn test_multiple_links() {
405 let rule = MD062LinkDestinationWhitespace::new();
406 let content = "[a]( url1) and [b](url2 ) here";
407 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
408 let warnings = rule.check(&ctx).unwrap();
409 assert_eq!(warnings.len(), 2);
410 }
411
412 #[test]
413 fn test_fix() {
414 let rule = MD062LinkDestinationWhitespace::new();
415 let content = "[link]( https://example.com ) and ";
416 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
417 let fixed = rule.fix(&ctx).unwrap();
418 assert_eq!(fixed, "[link](https://example.com) and ");
419 }
420
421 #[test]
422 fn test_reference_links_skipped() {
423 let rule = MD062LinkDestinationWhitespace::new();
424 let content = "[link][ref]\n\n[ref]: https://example.com";
425 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
426 let warnings = rule.check(&ctx).unwrap();
427 assert!(warnings.is_empty());
428 }
429
430 #[test]
431 fn test_nested_brackets() {
432 let rule = MD062LinkDestinationWhitespace::new();
433 let content = "[text [nested]]( https://example.com)";
434 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
435 let warnings = rule.check(&ctx).unwrap();
436 assert_eq!(warnings.len(), 1);
437 }
438
439 #[test]
440 fn test_empty_destination() {
441 let rule = MD062LinkDestinationWhitespace::new();
442 let content = "[link]()";
443 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
444 let warnings = rule.check(&ctx).unwrap();
445 assert!(warnings.is_empty());
446 }
447
448 #[test]
449 fn test_tabs_and_newlines() {
450 let rule = MD062LinkDestinationWhitespace::new();
451 let content = "[link](\thttps://example.com\t)";
452 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
453 let warnings = rule.check(&ctx).unwrap();
454 assert_eq!(warnings.len(), 1);
455 assert_eq!(
456 warnings[0].fix.as_ref().unwrap().replacement,
457 "[link](https://example.com)"
458 );
459 }
460
461 #[test]
464 fn test_trailing_whitespace_after_title() {
465 let rule = MD062LinkDestinationWhitespace::new();
466 let content = "[link](https://example.com \"title\" )";
467 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
468 let warnings = rule.check(&ctx).unwrap();
469 assert_eq!(warnings.len(), 1);
470 assert_eq!(
471 warnings[0].fix.as_ref().unwrap().replacement,
472 "[link](https://example.com \"title\")"
473 );
474 }
475
476 #[test]
477 fn test_leading_and_trailing_with_title() {
478 let rule = MD062LinkDestinationWhitespace::new();
479 let content = "[link]( https://example.com \"title\" )";
480 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
481 let warnings = rule.check(&ctx).unwrap();
482 assert_eq!(warnings.len(), 1);
483 assert_eq!(
484 warnings[0].fix.as_ref().unwrap().replacement,
485 "[link](https://example.com \"title\")"
486 );
487 }
488
489 #[test]
490 fn test_multiple_spaces_before_title() {
491 let rule = MD062LinkDestinationWhitespace::new();
492 let content = "[link](https://example.com \"title\")";
493 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
494 let warnings = rule.check(&ctx).unwrap();
495 assert_eq!(warnings.len(), 1);
496 assert_eq!(
497 warnings[0].fix.as_ref().unwrap().replacement,
498 "[link](https://example.com \"title\")"
499 );
500 }
501
502 #[test]
503 fn test_single_quote_title() {
504 let rule = MD062LinkDestinationWhitespace::new();
505 let content = "[link]( https://example.com 'title')";
506 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
507 let warnings = rule.check(&ctx).unwrap();
508 assert_eq!(warnings.len(), 1);
509 assert_eq!(
510 warnings[0].fix.as_ref().unwrap().replacement,
511 "[link](https://example.com 'title')"
512 );
513 }
514
515 #[test]
516 fn test_single_quote_title_trailing_space() {
517 let rule = MD062LinkDestinationWhitespace::new();
518 let content = "[link](https://example.com 'title' )";
519 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
520 let warnings = rule.check(&ctx).unwrap();
521 assert_eq!(warnings.len(), 1);
522 assert_eq!(
523 warnings[0].fix.as_ref().unwrap().replacement,
524 "[link](https://example.com 'title')"
525 );
526 }
527
528 #[test]
529 fn test_wikipedia_style_url() {
530 let rule = MD062LinkDestinationWhitespace::new();
532 let content = "[wiki]( https://en.wikipedia.org/wiki/Rust_(programming_language) )";
533 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
534 let warnings = rule.check(&ctx).unwrap();
535 assert_eq!(warnings.len(), 1);
536 assert_eq!(
537 warnings[0].fix.as_ref().unwrap().replacement,
538 "[wiki](https://en.wikipedia.org/wiki/Rust_(programming_language))"
539 );
540 }
541
542 #[test]
543 fn test_angle_bracket_url_no_warning() {
544 let rule = MD062LinkDestinationWhitespace::new();
546 let content = "[link](<https://example.com/path with spaces>)";
547 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
548 let warnings = rule.check(&ctx).unwrap();
549 assert!(warnings.is_empty());
551 }
552
553 #[test]
554 fn test_image_with_title() {
555 let rule = MD062LinkDestinationWhitespace::new();
556 let content = "";
557 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
558 let warnings = rule.check(&ctx).unwrap();
559 assert_eq!(warnings.len(), 1);
560 assert_eq!(
561 warnings[0].fix.as_ref().unwrap().replacement,
562 ""
563 );
564 }
565
566 #[test]
567 fn test_only_whitespace_in_destination() {
568 let rule = MD062LinkDestinationWhitespace::new();
569 let content = "[link]( )";
570 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
571 let warnings = rule.check(&ctx).unwrap();
572 assert_eq!(warnings.len(), 1);
573 assert_eq!(warnings[0].fix.as_ref().unwrap().replacement, "[link]()");
574 }
575
576 #[test]
577 fn test_code_block_skipped() {
578 let rule = MD062LinkDestinationWhitespace::new();
579 let content = "```\n[link]( https://example.com )\n```";
580 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
581 let warnings = rule.check(&ctx).unwrap();
582 assert!(warnings.is_empty());
583 }
584
585 #[test]
586 fn test_inline_code_not_skipped() {
587 let rule = MD062LinkDestinationWhitespace::new();
589 let content = "text `[link]( url )` more text";
590 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
591 let warnings = rule.check(&ctx).unwrap();
592 assert!(warnings.is_empty());
594 }
595
596 #[test]
597 fn test_valid_link_with_title_no_warning() {
598 let rule = MD062LinkDestinationWhitespace::new();
599 let content = "[link](https://example.com \"Title\")";
600 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
601 let warnings = rule.check(&ctx).unwrap();
602 assert!(warnings.is_empty());
603 }
604
605 #[test]
606 fn test_mixed_links_on_same_line() {
607 let rule = MD062LinkDestinationWhitespace::new();
608 let content = "[good](https://example.com) and [bad]( https://example.com ) here";
609 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
610 let warnings = rule.check(&ctx).unwrap();
611 assert_eq!(warnings.len(), 1);
612 assert_eq!(
613 warnings[0].fix.as_ref().unwrap().replacement,
614 "[bad](https://example.com)"
615 );
616 }
617
618 #[test]
619 fn test_fix_multiple_on_same_line() {
620 let rule = MD062LinkDestinationWhitespace::new();
621 let content = "[a]( url1 ) and [b]( url2 )";
622 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
623 let fixed = rule.fix(&ctx).unwrap();
624 assert_eq!(fixed, "[a](url1) and [b](url2)");
625 }
626
627 #[test]
628 fn test_complex_nested_brackets() {
629 let rule = MD062LinkDestinationWhitespace::new();
630 let content = "[text [with [deeply] nested] brackets]( https://example.com )";
631 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
632 let warnings = rule.check(&ctx).unwrap();
633 assert_eq!(warnings.len(), 1);
634 }
635
636 #[test]
637 fn test_url_with_query_params() {
638 let rule = MD062LinkDestinationWhitespace::new();
639 let content = "[link]( https://example.com?foo=bar&baz=qux )";
640 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
641 let warnings = rule.check(&ctx).unwrap();
642 assert_eq!(warnings.len(), 1);
643 assert_eq!(
644 warnings[0].fix.as_ref().unwrap().replacement,
645 "[link](https://example.com?foo=bar&baz=qux)"
646 );
647 }
648
649 #[test]
650 fn test_url_with_fragment() {
651 let rule = MD062LinkDestinationWhitespace::new();
652 let content = "[link]( https://example.com#section )";
653 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
654 let warnings = rule.check(&ctx).unwrap();
655 assert_eq!(warnings.len(), 1);
656 assert_eq!(
657 warnings[0].fix.as_ref().unwrap().replacement,
658 "[link](https://example.com#section)"
659 );
660 }
661
662 #[test]
663 fn test_relative_path() {
664 let rule = MD062LinkDestinationWhitespace::new();
665 let content = "[link]( ./path/to/file.md )";
666 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
667 let warnings = rule.check(&ctx).unwrap();
668 assert_eq!(warnings.len(), 1);
669 assert_eq!(
670 warnings[0].fix.as_ref().unwrap().replacement,
671 "[link](./path/to/file.md)"
672 );
673 }
674
675 #[test]
676 fn test_unmatched_angle_bracket_in_destination() {
677 let rule = MD062LinkDestinationWhitespace::new();
681 let content = "[]( \"<)";
682 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
683 let warnings = rule.check(&ctx).unwrap();
684 assert!(
685 warnings.is_empty(),
686 "Should not warn when closing paren is masked by angle bracket"
687 );
688
689 let fixed = rule.fix(&ctx).unwrap();
691 assert_eq!(fixed, content);
692 }
693
694 #[test]
695 fn test_unicode_whitespace_in_destination() {
696 let rule = MD062LinkDestinationWhitespace::new();
698 let content = "[](\u{2000}\"<)";
699 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
700 let warnings = rule.check(&ctx).unwrap();
701 assert!(
702 warnings.is_empty(),
703 "Should not warn when angle bracket masks closing paren"
704 );
705
706 let fixed = rule.fix(&ctx).unwrap();
707 assert_eq!(fixed, content, "Fix must be idempotent for unparseable links");
708 }
709
710 #[test]
711 fn test_autolink_not_affected() {
712 let rule = MD062LinkDestinationWhitespace::new();
714 let content = "<https://example.com>";
715 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
716 let warnings = rule.check(&ctx).unwrap();
717 assert!(warnings.is_empty());
718 }
719}