Skip to main content

rumdl_lib/rules/
md034_no_bare_urls.rs

1/// Rule MD034: No unformatted URLs
2///
3/// See [docs/md034.md](../../docs/md034.md) for full documentation, configuration, and examples.
4use std::sync::LazyLock;
5
6use regex::Regex;
7
8use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
9use crate::utils::range_utils::calculate_url_range;
10use crate::utils::regex_cache::{
11    EMAIL_PATTERN, URL_IPV6_REGEX, URL_QUICK_CHECK_REGEX, URL_STANDARD_REGEX, URL_WWW_REGEX, XMPP_URI_REGEX,
12};
13
14use crate::filtered_lines::FilteredLinesExt;
15use crate::lint_context::LintContext;
16
17// MD034-specific pre-compiled regex patterns for markdown constructs
18static CUSTOM_PROTOCOL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
19    Regex::new(r#"(?:grpc|ws|wss|ssh|git|svn|file|data|javascript|vscode|chrome|about|slack|discord|matrix|irc|redis|mongodb|postgresql|mysql|kafka|nats|amqp|mqtt|custom|app|api|service)://"#).unwrap()
20});
21static MARKDOWN_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
22    Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#).unwrap()
23});
24static MARKDOWN_EMPTY_LINK_REGEX: LazyLock<Regex> =
25    LazyLock::new(|| Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(\)"#).unwrap());
26static MARKDOWN_EMPTY_REF_REGEX: LazyLock<Regex> =
27    LazyLock::new(|| Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\[\]"#).unwrap());
28static ANGLE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
29    Regex::new(
30        r#"<((?:https?|ftps?)://(?:\[[0-9a-fA-F:]+(?:%[a-zA-Z0-9]+)?\]|[^>]+)|xmpp:[^>]+|[^@\s]+@[^@\s]+\.[^@\s>]+)>"#,
31    )
32    .unwrap()
33});
34static BADGE_LINK_LINE_REGEX: LazyLock<Regex> =
35    LazyLock::new(|| Regex::new(r#"^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$"#).unwrap());
36static MARKDOWN_IMAGE_REGEX: LazyLock<Regex> =
37    LazyLock::new(|| Regex::new(r#"!\s*\[([^\]]*)\]\s*\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#).unwrap());
38static MULTILINE_LINK_CONTINUATION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"^[^\[]*\]\(.*\)"#).unwrap());
39static SHORTCUT_REF_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"\[([^\[\]]+)\]"#).unwrap());
40
41/// Reusable buffers for check_line to reduce allocations
42#[derive(Default)]
43struct LineCheckBuffers {
44    markdown_link_ranges: Vec<(usize, usize)>,
45    image_ranges: Vec<(usize, usize)>,
46    urls_found: Vec<(usize, usize, String)>,
47}
48
49#[derive(Default, Clone)]
50pub struct MD034NoBareUrls;
51
52impl MD034NoBareUrls {
53    #[inline]
54    pub fn should_skip_content(&self, content: &str) -> bool {
55        // Skip if content has no URLs, XMPP URIs, or email addresses
56        // Fast byte scanning for common URL/email/xmpp indicators
57        let bytes = content.as_bytes();
58        let has_colon = bytes.contains(&b':');
59        let has_at = bytes.contains(&b'@');
60        let has_www = content.contains("www.");
61        !has_colon && !has_at && !has_www
62    }
63
64    /// Remove trailing punctuation that is likely sentence punctuation, not part of the URL
65    fn trim_trailing_punctuation<'a>(&self, url: &'a str) -> &'a str {
66        let mut trimmed = url;
67
68        // Check for balanced parentheses - if we have unmatched closing parens, they're likely punctuation
69        let open_parens = url.chars().filter(|&c| c == '(').count();
70        let close_parens = url.chars().filter(|&c| c == ')').count();
71
72        if close_parens > open_parens {
73            // Find the last balanced closing paren position
74            let mut balance = 0;
75            let mut last_balanced_pos = url.len();
76
77            for (byte_idx, c) in url.char_indices() {
78                if c == '(' {
79                    balance += 1;
80                } else if c == ')' {
81                    balance -= 1;
82                    if balance < 0 {
83                        // Found an unmatched closing paren
84                        last_balanced_pos = byte_idx;
85                        break;
86                    }
87                }
88            }
89
90            trimmed = &trimmed[..last_balanced_pos];
91        }
92
93        // Trim specific punctuation only if not followed by more URL-like chars
94        while let Some(last_char) = trimmed.chars().last() {
95            if matches!(last_char, '.' | ',' | ';' | ':' | '!' | '?') {
96                // Check if this looks like it could be part of the URL
97                // For ':' specifically, keep it if followed by digits (port number)
98                if last_char == ':' && trimmed.len() > 1 {
99                    // Don't trim
100                    break;
101                }
102                trimmed = &trimmed[..trimmed.len() - 1];
103            } else {
104                break;
105            }
106        }
107
108        trimmed
109    }
110
111    fn check_line(
112        &self,
113        line: &str,
114        ctx: &LintContext,
115        line_number: usize,
116        code_spans: &[crate::lint_context::CodeSpan],
117        buffers: &mut LineCheckBuffers,
118    ) -> Vec<LintWarning> {
119        let mut warnings = Vec::new();
120
121        // Skip lines inside HTML blocks - URLs in HTML attributes should not be linted
122        if ctx.line_info(line_number).is_some_and(|info| info.in_html_block) {
123            return warnings;
124        }
125
126        // Skip lines that are continuations of multiline markdown links
127        // Pattern: text](url) without a leading [
128        if MULTILINE_LINK_CONTINUATION_REGEX.is_match(line) {
129            return warnings;
130        }
131
132        // Quick check - does this line potentially have a URL or email?
133        let has_quick_check = URL_QUICK_CHECK_REGEX.is_match(line);
134        let has_www = line.contains("www.");
135        let has_at = line.contains('@');
136
137        if !has_quick_check && !has_at && !has_www {
138            return warnings;
139        }
140
141        // Clear and reuse buffers instead of allocating new ones
142        buffers.markdown_link_ranges.clear();
143        buffers.image_ranges.clear();
144
145        let has_bracket = line.contains('[');
146        let has_angle = line.contains('<');
147        let has_bang = line.contains('!');
148
149        if has_bracket {
150            for mat in MARKDOWN_LINK_REGEX.find_iter(line) {
151                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
152            }
153
154            // Also include empty link patterns like [text]() and [text][]
155            for mat in MARKDOWN_EMPTY_LINK_REGEX.find_iter(line) {
156                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
157            }
158
159            for mat in MARKDOWN_EMPTY_REF_REGEX.find_iter(line) {
160                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
161            }
162
163            // Also exclude shortcut reference links like [URL]
164            for mat in SHORTCUT_REF_REGEX.find_iter(line) {
165                let end = mat.end();
166                let next_non_ws = line[end..].bytes().find(|b| !b.is_ascii_whitespace());
167                if next_non_ws == Some(b'(') || next_non_ws == Some(b'[') {
168                    continue;
169                }
170                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
171            }
172
173            // Check if this line contains only a badge link (common pattern)
174            if has_bang && BADGE_LINK_LINE_REGEX.is_match(line) {
175                return warnings;
176            }
177        }
178
179        if has_angle {
180            for mat in ANGLE_LINK_REGEX.find_iter(line) {
181                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
182            }
183        }
184
185        // Find all markdown images for exclusion
186        if has_bang && has_bracket {
187            for mat in MARKDOWN_IMAGE_REGEX.find_iter(line) {
188                buffers.image_ranges.push((mat.start(), mat.end()));
189            }
190        }
191
192        // Find bare URLs
193        buffers.urls_found.clear();
194
195        // First, find IPv6 URLs (they need special handling)
196        for mat in URL_IPV6_REGEX.find_iter(line) {
197            let url_str = mat.as_str();
198            buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
199        }
200
201        // Then find regular URLs
202        for mat in URL_STANDARD_REGEX.find_iter(line) {
203            let url_str = mat.as_str();
204
205            // Skip if it's an IPv6 URL (already handled)
206            if url_str.contains("://[") {
207                continue;
208            }
209
210            // Skip malformed IPv6-like URLs
211            // Check for IPv6-like patterns that are malformed
212            if let Some(host_start) = url_str.find("://") {
213                let after_protocol = &url_str[host_start + 3..];
214                // If it looks like IPv6 (has :: or multiple :) but no brackets, skip if followed by ]
215                if after_protocol.contains("::") || after_protocol.chars().filter(|&c| c == ':').count() > 1 {
216                    // Check if the next byte after our match is ] (ASCII, so byte check is safe)
217                    if line.as_bytes().get(mat.end()) == Some(&b']') {
218                        // This is likely a malformed IPv6 URL like "https://::1]:8080"
219                        continue;
220                    }
221                }
222            }
223
224            buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
225        }
226
227        // Find www URLs without protocol (e.g., www.example.com)
228        for mat in URL_WWW_REGEX.find_iter(line) {
229            let url_str = mat.as_str();
230            let start_pos = mat.start();
231            let end_pos = mat.end();
232
233            // Skip if preceded by / or @ (likely part of a full URL)
234            if start_pos > 0 {
235                let prev_char = line.as_bytes().get(start_pos - 1).copied();
236                if prev_char == Some(b'/') || prev_char == Some(b'@') {
237                    continue;
238                }
239            }
240
241            // Skip if inside angle brackets (autolink syntax like <www.example.com>)
242            if start_pos > 0 && end_pos < line.len() {
243                let prev_char = line.as_bytes().get(start_pos - 1).copied();
244                let next_char = line.as_bytes().get(end_pos).copied();
245                if prev_char == Some(b'<') && next_char == Some(b'>') {
246                    continue;
247                }
248            }
249
250            buffers.urls_found.push((start_pos, end_pos, url_str.to_string()));
251        }
252
253        // Find XMPP URIs (GFM extended autolinks: xmpp:user@domain/resource)
254        for mat in XMPP_URI_REGEX.find_iter(line) {
255            let uri_str = mat.as_str();
256            let start_pos = mat.start();
257            let end_pos = mat.end();
258
259            // Skip if inside angle brackets (already properly formatted: <xmpp:user@domain>)
260            if start_pos > 0 && end_pos < line.len() {
261                let prev_char = line.as_bytes().get(start_pos - 1).copied();
262                let next_char = line.as_bytes().get(end_pos).copied();
263                if prev_char == Some(b'<') && next_char == Some(b'>') {
264                    continue;
265                }
266            }
267
268            buffers.urls_found.push((start_pos, end_pos, uri_str.to_string()));
269        }
270
271        // Process found URLs
272        for &(start, _end, ref url_str) in &buffers.urls_found {
273            // Skip custom protocols
274            if CUSTOM_PROTOCOL_REGEX.is_match(url_str) {
275                continue;
276            }
277
278            // Check if this URL is inside a markdown link, angle bracket, or image
279            // We check if the URL starts within a construct, not if it's entirely contained.
280            // This handles cases where URL detection may include trailing characters
281            // that extend past the construct boundary (e.g., parentheses).
282            // Linear scan is correct here because ranges can overlap/nest (e.g., [[1]](url))
283            let is_inside_construct = buffers
284                .markdown_link_ranges
285                .iter()
286                .any(|&(s, e)| start >= s && start < e)
287                || buffers.image_ranges.iter().any(|&(s, e)| start >= s && start < e);
288
289            if is_inside_construct {
290                continue;
291            }
292
293            // Calculate absolute byte position for context-aware checks
294            let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
295            let absolute_pos = line_start_byte + start;
296
297            // Check if URL is inside an HTML tag (handles multiline tags correctly)
298            if ctx.is_in_html_tag(absolute_pos) {
299                continue;
300            }
301
302            // Check if URL is a JSX component attribute value (e.g. `<Card href="..."/>`).
303            // These are string props, not bare prose; wrapping them in angle brackets
304            // would produce invalid JSX. No-op for non-JSX flavors.
305            if ctx.is_in_jsx_component_tag(absolute_pos) {
306                continue;
307            }
308
309            // Check if we're inside an HTML comment
310            if ctx.is_in_html_comment(absolute_pos) || ctx.is_in_mdx_comment(absolute_pos) {
311                continue;
312            }
313
314            // Check if we're inside a Hugo/Quarto shortcode
315            if ctx.is_in_shortcode(absolute_pos) {
316                continue;
317            }
318
319            // Skip URLs inside Pandoc line blocks (`| text`) or YAML metadata blocks.
320            // Both constructs treat their content as literal/structured text where bare
321            // URLs are intentional and should not be reformatted.
322            if ctx.flavor.is_pandoc_compatible()
323                && (ctx.is_in_line_block(absolute_pos) || ctx.is_in_pandoc_metadata(absolute_pos))
324            {
325                continue;
326            }
327
328            // Clean up the URL by removing trailing punctuation
329            let trimmed_url = self.trim_trailing_punctuation(url_str);
330
331            // Only report if we have a valid URL after trimming
332            if !trimmed_url.is_empty() && trimmed_url != "//" {
333                let trimmed_len = trimmed_url.len();
334                let (start_line, start_col, end_line, end_col) =
335                    calculate_url_range(line_number, line, start, trimmed_len);
336
337                // For www URLs without protocol, add https:// prefix in the fix
338                let replacement = if trimmed_url.starts_with("www.") {
339                    format!("<https://{trimmed_url}>")
340                } else {
341                    format!("<{trimmed_url}>")
342                };
343
344                warnings.push(LintWarning {
345                    rule_name: Some("MD034".to_string()),
346                    line: start_line,
347                    column: start_col,
348                    end_line,
349                    end_column: end_col,
350                    message: format!("URL without angle brackets or link formatting: '{trimmed_url}'"),
351                    severity: Severity::Warning,
352                    fix: Some(Fix::new(
353                        {
354                            let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
355                            (line_start_byte + start)..(line_start_byte + start + trimmed_len)
356                        },
357                        replacement,
358                    )),
359                });
360            }
361        }
362
363        // Check for bare email addresses
364        for cap in EMAIL_PATTERN.captures_iter(line) {
365            if let Some(mat) = cap.get(0) {
366                let email = mat.as_str();
367                let start = mat.start();
368                let end = mat.end();
369
370                // Skip if email is part of an XMPP URI (xmpp:user@domain)
371                // Check character boundary to avoid panics with multi-byte UTF-8
372                if start >= 5 && line.is_char_boundary(start - 5) && &line[start - 5..start] == "xmpp:" {
373                    continue;
374                }
375
376                // Check if email is inside angle brackets or markdown link
377                let mut is_inside_construct = false;
378                for &(link_start, link_end) in &buffers.markdown_link_ranges {
379                    if start >= link_start && end <= link_end {
380                        is_inside_construct = true;
381                        break;
382                    }
383                }
384
385                if !is_inside_construct {
386                    // Calculate absolute byte position for context-aware checks
387                    let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
388                    let absolute_pos = line_start_byte + start;
389
390                    // Check if email is inside an HTML tag (handles multiline tags)
391                    if ctx.is_in_html_tag(absolute_pos) {
392                        continue;
393                    }
394
395                    // Check if email is a JSX component attribute value (e.g.
396                    // `<Contact email="..."/>`). No-op for non-JSX flavors.
397                    if ctx.is_in_jsx_component_tag(absolute_pos) {
398                        continue;
399                    }
400
401                    // Skip emails inside Pandoc line blocks or YAML metadata blocks.
402                    if ctx.flavor.is_pandoc_compatible()
403                        && (ctx.is_in_line_block(absolute_pos) || ctx.is_in_pandoc_metadata(absolute_pos))
404                    {
405                        continue;
406                    }
407
408                    // Check if email is inside a code span (byte offsets handle multi-line spans)
409                    let is_in_code_span = code_spans
410                        .iter()
411                        .any(|span| absolute_pos >= span.byte_offset && absolute_pos < span.byte_end);
412
413                    if !is_in_code_span {
414                        let email_len = end - start;
415                        let (start_line, start_col, end_line, end_col) =
416                            calculate_url_range(line_number, line, start, email_len);
417
418                        warnings.push(LintWarning {
419                            rule_name: Some("MD034".to_string()),
420                            line: start_line,
421                            column: start_col,
422                            end_line,
423                            end_column: end_col,
424                            message: format!("Email address without angle brackets or link formatting: '{email}'"),
425                            severity: Severity::Warning,
426                            fix: Some(Fix::new(
427                                (line_start_byte + start)..(line_start_byte + end),
428                                format!("<{email}>"),
429                            )),
430                        });
431                    }
432                }
433            }
434        }
435
436        warnings
437    }
438}
439
440impl Rule for MD034NoBareUrls {
441    #[inline]
442    fn name(&self) -> &'static str {
443        "MD034"
444    }
445
446    fn as_any(&self) -> &dyn std::any::Any {
447        self
448    }
449
450    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
451    where
452        Self: Sized,
453    {
454        Box::new(MD034NoBareUrls)
455    }
456
457    #[inline]
458    fn category(&self) -> RuleCategory {
459        RuleCategory::Link
460    }
461
462    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
463        !ctx.likely_has_links_or_images() && self.should_skip_content(ctx.content)
464    }
465
466    #[inline]
467    fn description(&self) -> &'static str {
468        "No bare URLs - wrap URLs in angle brackets"
469    }
470
471    fn check(&self, ctx: &LintContext) -> LintResult {
472        let mut warnings = Vec::new();
473        let content = ctx.content;
474
475        // Quick skip for content without URLs
476        if self.should_skip_content(content) {
477            return Ok(warnings);
478        }
479
480        // Get code spans for exclusion
481        let code_spans = ctx.code_spans();
482
483        // Reference-definition lines are detected by rumdl's shared parser (which
484        // understands blockquote-prefixed definitions and the full CommonMark
485        // grammar), so their destination URLs are not flagged as bare URLs.
486        let ref_def_lines: std::collections::HashSet<usize> =
487            ctx.reference_definitions().iter().map(|def| def.line).collect();
488
489        // Allocate reusable buffers once instead of per-line to reduce allocations
490        let mut buffers = LineCheckBuffers::default();
491
492        // Iterate over content lines, automatically skipping front matter, code blocks,
493        // and Obsidian comments (when in Obsidian flavor)
494        // This uses the filtered iterator API which centralizes the skip logic
495        for line in ctx
496            .filtered_lines()
497            .skip_front_matter()
498            .skip_code_blocks()
499            .skip_jsx_expressions()
500            .skip_mdx_comments()
501            .skip_obsidian_comments()
502        {
503            // Skip MyST colon-fence directive openers (`:::{name} <arg>`). The text
504            // after the directive name is an opaque argument (a URL, path, or label),
505            // not markdown prose, so a bare URL there must not be wrapped in angle
506            // brackets. Directive body lines are not openers, so they fall through to
507            // `check_line` and are linted as usual.
508            if ctx.is_myst_colon_directive_opener_line(line.line_num) {
509                continue;
510            }
511
512            // Skip reference-definition lines (`[id]: url`, including inside blockquotes).
513            if ref_def_lines.contains(&line.line_num) {
514                continue;
515            }
516
517            let mut line_warnings = self.check_line(line.content, ctx, line.line_num, &code_spans, &mut buffers);
518
519            // Filter out warnings that are inside code spans (handles multi-line spans via byte offsets)
520            line_warnings.retain(|warning| {
521                !code_spans.iter().any(|span| {
522                    if let Some(fix) = &warning.fix {
523                        // Byte-offset check handles both single-line and multi-line code spans
524                        fix.range.start >= span.byte_offset && fix.range.start < span.byte_end
525                    } else {
526                        span.line == warning.line
527                            && span.end_line == warning.line
528                            && warning.column > 0
529                            && (warning.column - 1) >= span.start_col
530                            && (warning.column - 1) < span.end_col
531                    }
532                })
533            });
534
535            line_warnings.retain(|warning| {
536                if let Some(fix) = &warning.fix {
537                    // Check if the fix range falls inside any parsed link's byte range
538                    !ctx.links().iter().any(|link| {
539                        !(link.is_reference && link.url.is_empty())
540                            && fix.range.start >= link.byte_offset
541                            && fix.range.end <= link.byte_end
542                    })
543                } else {
544                    true
545                }
546            });
547
548            // Filter out warnings where the URL is inside an Obsidian comment (%%...%%)
549            // This handles inline comments like: text %%https://hidden.com%% text
550            line_warnings.retain(|warning| !ctx.is_position_in_obsidian_comment(warning.line, warning.column));
551
552            warnings.extend(line_warnings);
553        }
554
555        Ok(warnings)
556    }
557
558    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
559        let mut content = ctx.content.to_string();
560        let warnings = self.check(ctx)?;
561        let mut warnings =
562            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
563
564        // Sort warnings by position to ensure consistent fix application
565        warnings.sort_by_key(|w| w.fix.as_ref().map_or(0, |f| f.range.start));
566
567        // Apply fixes in reverse order to maintain positions
568        for warning in warnings.iter().rev() {
569            if let Some(fix) = &warning.fix {
570                let start = fix.range.start;
571                let end = fix.range.end;
572                content.replace_range(start..end, &fix.replacement);
573            }
574        }
575
576        Ok(content)
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    #[test]
585    fn test_shortcut_ref_at_end_of_line_no_trailing_chars() {
586        let rule = MD034NoBareUrls;
587        let content = "See [https://example.com]";
588        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
589        let result = rule.check(&ctx).unwrap();
590        assert!(
591            result.is_empty(),
592            "[URL] at end of line should be treated as shortcut ref: {result:?}"
593        );
594    }
595
596    #[test]
597    fn test_shortcut_ref_multiple_spaces_before_paren() {
598        let rule = MD034NoBareUrls;
599        let content = "[text]  (https://example.com)";
600        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
601        let result = rule.check(&ctx).unwrap();
602        // [text]  (url) — the spaces between ] and ( mean this should be treated
603        // as shortcut ref then bare parens, NOT a markdown link. URL may still be bare.
604        // This test verifies consistent behavior with the FancyRegex that had (?!\s*[\[(])
605        let _ = result; // Just verify no panic; the exact warning count depends on other rules
606    }
607
608    #[test]
609    fn test_shortcut_ref_tab_before_bracket() {
610        let rule = MD034NoBareUrls;
611        let content = "[https://example.com]\t[other]";
612        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
613        let result = rule.check(&ctx).unwrap();
614        // Tab between ] and [ does not form a full reference link in Markdown.
615        // The first [URL] is a shortcut ref containing a bare URL, so MD034 warns.
616        // This test verifies consistent behavior and no panic with tab characters.
617        assert_eq!(
618            result.len(),
619            1,
620            "Bare URL inside shortcut ref should be detected: {result:?}"
621        );
622    }
623
624    #[test]
625    fn test_shortcut_ref_followed_by_punctuation() {
626        let rule = MD034NoBareUrls;
627        let content = "[https://example.com], see also other things.";
628        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
629        let result = rule.check(&ctx).unwrap();
630        assert!(
631            result.is_empty(),
632            "[URL] followed by comma should be treated as shortcut ref: {result:?}"
633        );
634    }
635
636    #[test]
637    fn test_url_in_backticks_inside_mdx_component_not_flagged() {
638        // Exact reproduction from issue #572: URL inside inline code within an MDX
639        // component body must not be flagged. The same URL in backticks outside the
640        // component is already handled correctly and serves as a control.
641        let rule = MD034NoBareUrls;
642        let content = "# Test\n\nControl: `https://rumdl.example.com/` is fine here.\n\n<ParamField path=\"--stuff\">\n  This URL `https://rumdl.example.com/` must not be flagged.\n</ParamField>\n";
643        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
644        let result = rule.check(&ctx).unwrap();
645        assert!(
646            result.is_empty(),
647            "URL in backticks inside MDX component must not be flagged: {result:?}"
648        );
649    }
650
651    #[test]
652    fn test_bare_url_inside_mdx_component_still_flagged() {
653        // A bare URL (not in backticks) inside an MDX component body must still be flagged.
654        // This ensures the fix for issue #572 only suppresses properly code-spanned URLs.
655        let rule = MD034NoBareUrls;
656        let content =
657            "# Test\n\n<ParamField path=\"--stuff\">\n  Visit https://rumdl.example.com/ for details.\n</ParamField>\n";
658        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
659        let result = rule.check(&ctx).unwrap();
660        assert_eq!(
661            result.len(),
662            1,
663            "Bare URL in MDX component body must still be flagged: {result:?}"
664        );
665    }
666
667    #[test]
668    fn test_url_in_backticks_inside_nested_mdx_component_not_flagged() {
669        // Nested MDX components must also respect code spans.
670        let rule = MD034NoBareUrls;
671        let content = "<Outer>\n  <Inner>\n    Check `https://example.com/` here.\n  </Inner>\n</Outer>\n";
672        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
673        let result = rule.check(&ctx).unwrap();
674        assert!(
675            result.is_empty(),
676            "URL in backticks inside nested MDX component must not be flagged: {result:?}"
677        );
678    }
679
680    /// Issue #678: a URL inside a fenced code block that is nested within a JSX/MDX
681    /// component (e.g. `<Steps><Step>`) is code, not bare prose. It must not be
682    /// flagged, and `fix` must not rewrite it (which would corrupt the command).
683    #[test]
684    fn test_url_in_fenced_code_block_inside_jsx_not_flagged() {
685        let rule = MD034NoBareUrls;
686        let content = "# Title\n\n<Steps>\n  <Step title=\"Send a request\">\n```bash\ncurl https://example.com/api\n```\n  </Step>\n</Steps>\n";
687        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
688        let result = rule.check(&ctx).unwrap();
689        assert!(
690            result.is_empty(),
691            "URL in a fenced code block nested in a JSX component must not be flagged: {result:?}"
692        );
693    }
694
695    /// The same code block must be left byte-for-byte intact by `fix` (no
696    /// `<https://...>` rewrite that breaks a copy-pasteable command).
697    #[test]
698    fn test_fix_does_not_rewrite_url_in_fenced_code_block_inside_jsx() {
699        let rule = MD034NoBareUrls;
700        let content = "# Title\n\n<Steps>\n  <Step title=\"Send a request\">\n```bash\ncurl https://example.com/api\n```\n  </Step>\n</Steps>\n";
701        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
702        let fixed = rule.fix(&ctx).unwrap();
703        assert_eq!(
704            fixed, content,
705            "fix must not rewrite a URL inside a JSX-nested fenced code block"
706        );
707    }
708
709    /// Control: a bare URL in the JSX *body* (outside any fence) is genuine prose
710    /// and must still be flagged, so the fence exemption is not over-broad.
711    #[test]
712    fn test_bare_url_in_jsx_body_outside_fence_still_flagged() {
713        let rule = MD034NoBareUrls;
714        let content = "# Title\n\n<Steps>\n  <Step title=\"Send a request\">\n  Visit https://example.com/api now.\n  </Step>\n</Steps>\n";
715        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
716        let result = rule.check(&ctx).unwrap();
717        assert_eq!(
718            result.len(),
719            1,
720            "A bare URL in the JSX body (not in a fence) must still be flagged: {result:?}"
721        );
722    }
723
724    /// A `<!--` inside a fenced code block is literal, not a comment opener, so it
725    /// must not pair with a later `-->` to form a comment range that masks a real
726    /// bare URL between them (the code-block counterpart to the code-span fix).
727    #[test]
728    fn test_bare_url_not_masked_by_comment_delimiter_in_code_block() {
729        let rule = MD034NoBareUrls;
730        let content =
731            "# T\n\n```text\n<!-- literal opener, not a comment\n```\n\nhttps://example.com should be flagged\n\n-->\n";
732        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
733        let result = rule.check(&ctx).unwrap();
734        assert_eq!(result.len(), 1, "the bare URL must still be flagged: {result:?}");
735        assert!(
736            result[0].message.contains("example.com"),
737            "the flagged URL must be the bare one: {result:?}"
738        );
739    }
740
741    /// Only *fenced* code blocks suppress `<!--`/`-->` as literal. A real HTML
742    /// comment indented inside a MkDocs admonition (which pulldown-cmark
743    /// misclassifies as an indented code block) must still be recognized as a
744    /// comment, so its bare URL stays skipped.
745    #[test]
746    fn test_bare_url_in_indented_comment_in_admonition_still_skipped() {
747        let rule = MD034NoBareUrls;
748        let content = "# T\n\n!!! note\n    Some text.\n\n    <!--\n    https://example.com\n    -->\n";
749        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
750        let result = rule.check(&ctx).unwrap();
751        assert!(
752            result.is_empty(),
753            "URL inside an indented HTML comment in an admonition must not be flagged: {result:?}"
754        );
755    }
756
757    /// Issue #649: a URL that is a JSX component attribute value (e.g. `href="..."`)
758    /// is a string prop, not bare prose. Wrapping it in angle brackets produces
759    /// invalid JSX, so MD034 must not flag it under the MDX flavor.
760    #[test]
761    fn test_url_in_jsx_component_attribute_not_flagged() {
762        let rule = MD034NoBareUrls;
763        let content = "<Card title=\"Docs\" href=\"https://example.com/docs\" />\n";
764        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
765        let result = rule.check(&ctx).unwrap();
766        assert!(
767            result.is_empty(),
768            "URL in a JSX component attribute must not be flagged: {result:?}"
769        );
770    }
771
772    /// The same exemption must apply when the JSX opening tag spans multiple lines.
773    #[test]
774    fn test_url_in_multiline_jsx_component_attribute_not_flagged() {
775        let rule = MD034NoBareUrls;
776        let content = "<Card\n  title=\"Docs\"\n  href=\"https://example.com/docs\"\n/>\n";
777        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
778        let result = rule.check(&ctx).unwrap();
779        assert!(
780            result.is_empty(),
781            "URL in a multi-line JSX component attribute must not be flagged: {result:?}"
782        );
783    }
784
785    /// The exemption is surgical: a URL in the component's *attributes* is skipped,
786    /// but a bare URL in the component's *body* is genuine prose and still flagged.
787    #[test]
788    fn test_jsx_attribute_url_skipped_but_body_url_flagged() {
789        let rule = MD034NoBareUrls;
790        let content = "<Card href=\"https://attr.example.com\">\n  Visit https://body.example.com now.\n</Card>\n";
791        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
792        let result = rule.check(&ctx).unwrap();
793        assert_eq!(
794            result.len(),
795            1,
796            "Only the body URL must be flagged, not the attribute URL: {result:?}"
797        );
798        assert!(
799            result[0].message.contains("body.example.com"),
800            "The flagged URL must be the body one: {result:?}"
801        );
802    }
803
804    /// The email path has the same JSX-attribute blind spot; an email used as a
805    /// JSX component attribute value must not be flagged either.
806    #[test]
807    fn test_email_in_jsx_component_attribute_not_flagged() {
808        let rule = MD034NoBareUrls;
809        let content = "<Contact email=\"hello@example.com\" />\n";
810        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
811        let result = rule.check(&ctx).unwrap();
812        assert!(
813            result.is_empty(),
814            "Email in a JSX component attribute must not be flagged: {result:?}"
815        );
816    }
817
818    /// Control: under the Standard flavor `<Card .../>` is parsed as an HTML tag,
819    /// so the attribute URL is already covered by the existing HTML-tag guard.
820    /// This locks in that the two flavors agree.
821    #[test]
822    fn test_jsx_attribute_url_not_flagged_in_standard_flavor() {
823        let rule = MD034NoBareUrls;
824        let content = "<Card href=\"https://example.com/docs\" />\n";
825        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
826        let result = rule.check(&ctx).unwrap();
827        assert!(
828            result.is_empty(),
829            "URL in a tag attribute must not be flagged under Standard flavor either: {result:?}"
830        );
831    }
832
833    /// URLs inside Pandoc line blocks (`| text`) must not be flagged as bare URLs.
834    #[test]
835    fn test_pandoc_skips_urls_in_line_blocks() {
836        use crate::config::MarkdownFlavor;
837        use crate::lint_context::LintContext;
838        let rule = MD034NoBareUrls;
839        let content = "| See https://example.com\n| For details\n";
840        let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
841        let result = rule.check(&ctx).unwrap();
842        assert!(
843            result.is_empty(),
844            "MD034 should skip URLs in Pandoc line blocks: {result:?}"
845        );
846    }
847
848    /// URLs inside Pandoc YAML metadata blocks must not be flagged.
849    #[test]
850    fn test_pandoc_skips_urls_in_metadata() {
851        use crate::config::MarkdownFlavor;
852        use crate::lint_context::LintContext;
853        let rule = MD034NoBareUrls;
854        let content = "---\nhomepage: https://example.com\n---\n\nBody.\n";
855        let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
856        let result = rule.check(&ctx).unwrap();
857        assert!(
858            result.is_empty(),
859            "MD034 should skip URLs in Pandoc YAML metadata: {result:?}"
860        );
861    }
862
863    /// Standard flavor must still flag bare URLs in lines starting with `|`
864    /// (which are not interpreted as line blocks).
865    #[test]
866    fn test_standard_still_flags_urls_in_pipe_prefixed_lines() {
867        use crate::config::MarkdownFlavor;
868        use crate::lint_context::LintContext;
869        let rule = MD034NoBareUrls;
870        let content = "| See https://example.com\n";
871        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
872        let result = rule.check(&ctx).unwrap();
873        assert!(
874            !result.is_empty(),
875            "MD034 should still flag URLs in pipe-prefixed lines under Standard flavor"
876        );
877    }
878
879    #[test]
880    fn test_url_in_backticks_after_fenced_code_block_inside_mdx_not_flagged() {
881        // A fenced code block inside a JSX component must not misalign the code-span
882        // offset map. The URL in backticks that appears *after* the code block must
883        // still be recognised as being inside a code span.
884        let rule = MD034NoBareUrls;
885        let content = "\
886<Component>
887Some intro text.
888
889```
890example code here
891```
892
893Check `https://example.com/` here.
894</Component>
895";
896        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
897        let result = rule.check(&ctx).unwrap();
898        assert!(
899            result.is_empty(),
900            "URL in backticks after a fenced code block inside MDX must not be flagged: {result:?}"
901        );
902    }
903
904    /// Issue #642: a URL given as the argument of a MyST colon-fence directive
905    /// (`:::{name} <url>`) is the directive's opaque argument, not markdown prose,
906    /// and must not be wrapped in angle brackets.
907    #[test]
908    fn test_myst_colon_directive_argument_url_not_flagged() {
909        use crate::config::MarkdownFlavor;
910        use crate::lint_context::LintContext;
911        let rule = MD034NoBareUrls;
912        let content = "\
913:::{anywidget} https://cdn.jsdelivr.net/npm/repo-review-webapp@1.1.3/dist/repo-review-anywidget.mjs
914{
915  \"deps\": [\"repo-review~=1.1.0\"]
916}
917:::
918";
919        let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
920        let result = rule.check(&ctx).unwrap();
921        assert!(
922            result.is_empty(),
923            "URL argument on a MyST colon directive opener must not be flagged: {result:?}"
924        );
925    }
926
927    /// A nested MyST colon directive opener also carries an opaque argument.
928    #[test]
929    fn test_myst_nested_colon_directive_argument_url_not_flagged() {
930        use crate::config::MarkdownFlavor;
931        use crate::lint_context::LintContext;
932        let rule = MD034NoBareUrls;
933        let content = "\
934::::{grid}
935:::{card} https://example.com/card-target
936Some caption.
937:::
938::::
939";
940        let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
941        let result = rule.check(&ctx).unwrap();
942        assert!(
943            result.is_empty(),
944            "URL argument on a nested MyST colon directive opener must not be flagged: {result:?}"
945        );
946    }
947
948    /// A bare URL in the *body* of a content directive (e.g. `{note}`) is genuine
949    /// prose and must still be flagged. The opener exemption must not leak to the body.
950    #[test]
951    fn test_myst_directive_body_url_still_flagged() {
952        use crate::config::MarkdownFlavor;
953        use crate::lint_context::LintContext;
954        let rule = MD034NoBareUrls;
955        let content = "\
956:::{note}
957See https://example.com/docs for more details.
958:::
959";
960        let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
961        let result = rule.check(&ctx).unwrap();
962        assert_eq!(
963            result.len(),
964            1,
965            "Bare URL in a MyST directive body must still be flagged: {result:?}"
966        );
967    }
968
969    /// An unclosed colon directive (no terminating `:::`) still has its opener
970    /// argument treated as opaque: the URL must not be flagged.
971    #[test]
972    fn test_myst_unclosed_colon_directive_argument_url_not_flagged() {
973        use crate::config::MarkdownFlavor;
974        use crate::lint_context::LintContext;
975        let rule = MD034NoBareUrls;
976        let content = "\
977:::{anywidget} https://example.com/widget.mjs
978Some trailing content with no closing fence.
979";
980        let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
981        let result = rule.check(&ctx).unwrap();
982        assert!(
983            result.is_empty(),
984            "URL argument on an unclosed MyST colon directive opener must not be flagged: {result:?}"
985        );
986    }
987
988    /// The colon-directive exemption is MyST-specific: under the Standard flavor a
989    /// `:::{...}` line is ordinary text and a bare URL on it must still be flagged.
990    #[test]
991    fn test_colon_directive_url_flagged_in_standard_flavor() {
992        use crate::config::MarkdownFlavor;
993        use crate::lint_context::LintContext;
994        let rule = MD034NoBareUrls;
995        let content = ":::{anywidget} https://example.com/widget.mjs\n";
996        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
997        let result = rule.check(&ctx).unwrap();
998        assert_eq!(
999            result.len(),
1000            1,
1001            "Under Standard flavor a bare URL on a `:::` line must still be flagged: {result:?}"
1002        );
1003    }
1004
1005    #[test]
1006    fn test_md034_complex_link() {
1007        let rule = MD034NoBareUrls;
1008
1009        // Case 1: Balanced brackets in code span.
1010        // We should flag the bare URL at the end, but NOT the one inside the link.
1011        let content = "Check [link `code [with brackets]` text](http://example.com) and see http://bare.com.\n";
1012        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1013        let result = rule.check(&ctx).unwrap();
1014        assert_eq!(result.len(), 1, "Should flag exactly 1 URL (the bare one): {result:?}");
1015        assert!(result[0].message.contains("bare.com"));
1016
1017        // Case 2: Unbalanced brackets in code span.
1018        // We should flag the bare URL at the end, but NOT the one inside the link.
1019        let content2 = "Check [link `code [` text](http://example.com) and see http://bare.com.\n";
1020        let ctx2 = crate::lint_context::LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1021        let result2 = rule.check(&ctx2).unwrap();
1022        assert_eq!(
1023            result2.len(),
1024            1,
1025            "Should flag exactly 1 URL (the bare one): {result2:?}"
1026        );
1027        assert!(result2[0].message.contains("bare.com"));
1028    }
1029}