rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/// Rule MD011: No reversed link syntax
///
/// See [docs/md011.md](../../docs/md011.md) for full documentation, configuration, and examples.
use crate::filtered_lines::FilteredLinesExt;
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::utils::range_utils::calculate_match_range;
use crate::utils::regex_cache::get_cached_regex;
use crate::utils::skip_context::is_in_math_context;

// Reversed link detection pattern
const REVERSED_LINK_REGEX_STR: &str = r"(^|[^\\])\(([^()]+)\)\[([^\]]+)\]";

/// Classification of a link component
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinkComponent {
    /// Clear URL: has protocol, www., mailto:, or path prefix
    ClearUrl,
    /// Multiple words or sentence-like (likely link text, not URL)
    MultiWord,
    /// Single word - could be either URL or text
    Ambiguous,
}

/// Information about a detected reversed link pattern
#[derive(Debug, Clone)]
struct ReversedLinkInfo {
    /// Content found in parentheses
    paren_content: String,
    /// Content found in square brackets
    bracket_content: String,
    /// Classification of parentheses content
    paren_type: LinkComponent,
    /// Classification of bracket content
    bracket_type: LinkComponent,
}

impl ReversedLinkInfo {
    /// Determine the correct order: returns (text, url)
    fn correct_order(&self) -> (&str, &str) {
        use LinkComponent::*;

        match (self.paren_type, self.bracket_type) {
            // One side is clearly a URL - that's the URL
            (ClearUrl, _) => (&self.bracket_content, &self.paren_content),
            (_, ClearUrl) => (&self.paren_content, &self.bracket_content),

            // One side is multi-word - that's the text, other is URL
            (MultiWord, _) => (&self.paren_content, &self.bracket_content),
            (_, MultiWord) => (&self.bracket_content, &self.paren_content),

            // Both ambiguous: assume standard reversed pattern (url)[text]
            (Ambiguous, Ambiguous) => (&self.bracket_content, &self.paren_content),
        }
    }
}

#[derive(Clone)]
pub struct MD011NoReversedLinks;

impl MD011NoReversedLinks {
    /// Classify a link component as URL, multi-word text, or ambiguous
    fn classify_component(s: &str) -> LinkComponent {
        let trimmed = s.trim();

        // Check for clear URL indicators
        if trimmed.starts_with("http://")
            || trimmed.starts_with("https://")
            || trimmed.starts_with("ftp://")
            || trimmed.starts_with("www.")
            || (trimmed.starts_with("mailto:") && trimmed.contains('@'))
            || (trimmed.starts_with('/') && trimmed.len() > 1)
            || (trimmed.starts_with("./") || trimmed.starts_with("../"))
            || (trimmed.starts_with('#') && trimmed.len() > 1 && !trimmed[1..].contains(' '))
        {
            return LinkComponent::ClearUrl;
        }

        // Multi-word text is likely a description, not a URL
        if trimmed.contains(' ') {
            return LinkComponent::MultiWord;
        }

        // Single word - could be either
        LinkComponent::Ambiguous
    }
}

impl Rule for MD011NoReversedLinks {
    fn name(&self) -> &'static str {
        "MD011"
    }

    fn description(&self) -> &'static str {
        "Reversed link syntax"
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Link
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let mut warnings = Vec::new();

        let line_index = &ctx.line_index;

        // Use filtered_lines() to automatically skip front-matter and Obsidian comments
        for filtered_line in ctx
            .filtered_lines()
            .skip_front_matter()
            .skip_jsx_expressions()
            .skip_mdx_comments()
            .skip_obsidian_comments()
        {
            let line_num = filtered_line.line_num;
            let line = filtered_line.content;

            let byte_pos = line_index.get_line_start_byte(line_num).unwrap_or(0);

            let mut last_end = 0;

            while let Some(cap) = get_cached_regex(REVERSED_LINK_REGEX_STR)
                .ok()
                .and_then(|re| re.captures(&line[last_end..]))
            {
                let match_obj = cap.get(0).unwrap();
                let prechar = &cap[1];
                let paren_content = cap[2].to_string();
                let bracket_content = cap[3].to_string();

                // Skip wiki-link patterns: if bracket content starts with [ or ends with ]
                // This handles cases like (url)[[wiki-link]] being misdetected
                if bracket_content.starts_with('[') || bracket_content.ends_with(']') {
                    last_end += match_obj.end();
                    continue;
                }

                // Skip footnote references: [^footnote]
                // This prevents false positives like [link](url)[^footnote]
                if bracket_content.starts_with('^') {
                    last_end += match_obj.end();
                    continue;
                }

                // Skip Dataview inline fields in Obsidian flavor
                // Pattern: (field:: value)[text] is valid Obsidian syntax, not a reversed link
                if ctx.flavor == crate::config::MarkdownFlavor::Obsidian && paren_content.contains("::") {
                    last_end += match_obj.end();
                    continue;
                }

                // Check if the brackets at the end are escaped
                if bracket_content.ends_with('\\') {
                    last_end += match_obj.end();
                    continue;
                }

                // Manual negative lookahead: skip if followed by (
                // This prevents matching (text)[ref](url) patterns
                let end_pos = last_end + match_obj.end();
                if end_pos < line.len() && line[end_pos..].starts_with('(') {
                    last_end += match_obj.end();
                    continue;
                }

                // Calculate the actual position
                let match_start = last_end + match_obj.start() + prechar.len();
                let match_byte_pos = byte_pos + match_start;

                // Skip if in code block, inline code, HTML comments, math contexts, or Jinja templates
                if ctx.is_in_code_block_or_span(match_byte_pos)
                    || ctx.is_in_html_comment(match_byte_pos)
                    || is_in_math_context(ctx, match_byte_pos)
                    || ctx.is_in_jinja_range(match_byte_pos)
                {
                    last_end += match_obj.end();
                    continue;
                }

                // Classify both components and determine correct order
                let paren_type = Self::classify_component(&paren_content);
                let bracket_type = Self::classify_component(&bracket_content);

                let info = ReversedLinkInfo {
                    paren_content,
                    bracket_content,
                    paren_type,
                    bracket_type,
                };

                let (text, url) = info.correct_order();

                // Calculate the range for the actual reversed link (excluding prechar)
                let actual_length = match_obj.len() - prechar.len();
                let (start_line, start_col, end_line, end_col) =
                    calculate_match_range(line_num, line, match_start, actual_length);

                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    message: format!("Reversed link syntax: use [{text}]({url}) instead"),
                    line: start_line,
                    column: start_col,
                    end_line,
                    end_column: end_col,
                    severity: Severity::Error,
                    fix: Some(Fix {
                        range: {
                            let match_start_byte = byte_pos + match_start;
                            let match_end_byte = match_start_byte + actual_length;
                            match_start_byte..match_end_byte
                        },
                        replacement: format!("[{text}]({url})"),
                    }),
                });

                last_end += match_obj.end();
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        let warnings = self.check(ctx)?;
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
        if warnings.is_empty() {
            return Ok(ctx.content.to_string());
        }

        let mut content = ctx.content.to_string();
        // Apply fixes in reverse order to preserve byte offsets
        let mut fixes: Vec<_> = warnings.iter().filter_map(|w| w.fix.as_ref()).collect();
        fixes.sort_by(|a, b| b.range.start.cmp(&a.range.start));

        for fix in fixes {
            if fix.range.start < content.len() && fix.range.end <= content.len() {
                content.replace_range(fix.range.clone(), &fix.replacement);
            }
        }
        Ok(content)
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        ctx.content.is_empty() || !ctx.likely_has_links_or_images()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        Box::new(MD011NoReversedLinks)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lint_context::LintContext;

    #[test]
    fn test_md011_basic() {
        let rule = MD011NoReversedLinks;

        // Should detect reversed links
        let content = "(http://example.com)[Example]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].line, 1);

        // Should not detect correct links
        let content = "[Example](http://example.com)\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn test_md011_with_escaped_brackets() {
        let rule = MD011NoReversedLinks;

        // Should not detect if brackets are escaped
        let content = "(url)[text\\]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn test_md011_no_false_positive_with_reference_link() {
        let rule = MD011NoReversedLinks;

        // Should not detect (text)[ref](url) as reversed
        let content = "(text)[ref](url)\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn test_md011_fix() {
        let rule = MD011NoReversedLinks;

        let content = "(http://example.com)[Example]\n(another/url)[text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "[Example](http://example.com)\n[text](another/url)\n");
    }

    #[test]
    fn test_md011_in_code_block() {
        let rule = MD011NoReversedLinks;

        let content = "```\n(url)[text]\n```\n(url)[text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].line, 4);
    }

    #[test]
    fn test_md011_inline_code() {
        let rule = MD011NoReversedLinks;

        let content = "`(url)[text]` and (url)[text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].column, 19);
    }

    #[test]
    fn test_md011_no_false_positive_with_footnote() {
        let rule = MD011NoReversedLinks;

        // Should not detect [link](url)[^footnote] as reversed - this is valid markdown
        // The [^footnote] is a footnote reference, not part of a reversed link
        let content = "Some text with [a link](https://example.com/)[^ft].\n\n[^ft]: Note.\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0);

        // Also test with multiple footnotes
        let content = "[link1](url1)[^1] and [link2](url2)[^2]\n\n[^1]: First\n[^2]: Second\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0);

        // But should still detect actual reversed links
        let content = "(url)[text] and [link](url)[^footnote]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].line, 1);
        assert_eq!(warnings[0].column, 1);
    }

    #[test]
    fn test_md011_skip_dataview_inline_fields_obsidian() {
        let rule = MD011NoReversedLinks;

        // Dataview inline field pattern: (field:: value)[text]
        // In Obsidian flavor, this should NOT be flagged as a reversed link
        let content = "(status:: active)[link text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(
            warnings.len(),
            0,
            "Should not flag Dataview inline field in Obsidian flavor"
        );

        // Multiple inline fields
        let content = "(author:: John)[read more] and (date:: 2024-01-01)[link]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0, "Should not flag multiple Dataview inline fields");

        // Mixed content: Dataview field and actual reversed link
        let content = "(status:: done)[info] (url)[text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1, "Should flag reversed link but not Dataview field");
        assert_eq!(warnings[0].column, 23);
    }

    #[test]
    fn test_md011_flag_dataview_in_standard_flavor() {
        let rule = MD011NoReversedLinks;

        // In Standard flavor, (field:: value)[text] is treated as a reversed link
        // because Dataview is Obsidian-specific
        let content = "(status:: active)[link text]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(
            warnings.len(),
            1,
            "Should flag Dataview-like pattern in Standard flavor"
        );
    }

    #[test]
    fn test_md011_dataview_bracket_syntax_obsidian() {
        let rule = MD011NoReversedLinks;

        // Dataview also supports [field:: value] syntax inside brackets
        // The pattern (field:: value)[text] should be skipped in Obsidian
        let content = "Task has (priority:: high)[see details]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0, "Should skip Dataview field with spaces");

        // Field with no value (just key::)
        let content = "(completed::)[marker]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0, "Should skip Dataview field with empty value");
    }

    #[test]
    fn test_md011_fix_skips_obsidian_comments() {
        let rule = MD011NoReversedLinks;

        // Reversed link inside Obsidian comment block should not be modified by fix()
        let content = "%%\n(http://example.com)[hidden link]\n%%\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);

        // check() should produce no warnings (Obsidian comment is skipped)
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 0, "check() should skip Obsidian comment content");

        // fix() should not modify content inside Obsidian comments
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, content,
            "fix() should not modify reversed links inside Obsidian comments"
        );
    }

    #[test]
    fn test_md011_fix_skips_obsidian_comments_with_surrounding_content() {
        let rule = MD011NoReversedLinks;

        // Mix of Obsidian comment and real reversed link
        let content = "%%\n(http://example.com)[hidden]\n%%\n\n(http://real.com)[visible]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);

        // check() should only flag the visible one
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1, "check() should only flag visible reversed link");
        assert_eq!(warnings[0].line, 5);

        // fix() should only fix the visible one, leaving comment content untouched
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "%%\n(http://example.com)[hidden]\n%%\n\n[visible](http://real.com)\n",
            "fix() should only modify visible reversed links"
        );
    }

    #[test]
    fn test_md011_fix_skips_dataview_fields_obsidian() {
        let rule = MD011NoReversedLinks;

        // Dataview inline field should not be modified by fix()
        let content = "(status:: active)[link text]\n(http://example.com)[real link]\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);

        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1, "check() should only flag the real reversed link");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "(status:: active)[link text]\n[real link](http://example.com)\n",
            "fix() should not modify Dataview inline fields"
        );
    }
}