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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
pub mod code_block_tools;
pub mod config;
pub mod doc_comment_lint;
pub mod embedded_lint;
pub mod exit_codes;
pub mod filtered_lines;
pub mod fix_coordinator;
pub mod inline_config;
pub mod linguist_data;
pub mod lint_context;
pub mod markdownlint_config;
pub mod profiling;
pub mod rule;
#[cfg(feature = "native")]
pub mod vscode;
pub mod workspace_index;
#[macro_use]
pub mod rule_config;
#[macro_use]
pub mod rule_config_serde;
pub mod rules;
pub mod types;
pub mod utils;

// Native-only modules (require tokio, tower-lsp, etc.)
#[cfg(feature = "native")]
pub mod lsp;
#[cfg(feature = "native")]
pub mod output;
#[cfg(feature = "native")]
pub mod parallel;
#[cfg(feature = "native")]
pub mod performance;

// WASM module
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
pub mod wasm;

pub use rules::heading_utils::{Heading, HeadingStyle};
pub use rules::*;

pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
use crate::rule::{LintResult, Rule, RuleCategory};
use crate::utils::calculate_indentation_width_default;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

/// Content characteristics for efficient rule filtering
#[derive(Debug, Default)]
struct ContentCharacteristics {
    has_headings: bool,    // # or setext headings
    has_lists: bool,       // *, -, +, 1. etc
    has_links: bool,       // [text](url) or [text][ref]
    has_code: bool,        // ``` or ~~~ or indented code
    has_emphasis: bool,    // * or _ for emphasis
    has_html: bool,        // < > tags
    has_tables: bool,      // | pipes
    has_blockquotes: bool, // > markers
    has_images: bool,      // ![alt](url)
}

/// Check if a line has enough leading whitespace to be an indented code block.
/// Indented code blocks require 4+ columns of leading whitespace (with proper tab expansion).
fn has_potential_indented_code_indent(line: &str) -> bool {
    calculate_indentation_width_default(line) >= 4
}

impl ContentCharacteristics {
    fn analyze(content: &str) -> Self {
        let mut chars = Self { ..Default::default() };

        // Quick single-pass analysis
        let mut has_atx_heading = false;
        let mut has_setext_heading = false;

        for line in content.lines() {
            let trimmed = line.trim();

            // Headings: ATX (#) or Setext (underlines)
            if !has_atx_heading && trimmed.starts_with('#') {
                has_atx_heading = true;
            }
            if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
                has_setext_heading = true;
            }

            // Quick character-based detection (more efficient than regex)
            // Include patterns without spaces to enable user-intention detection (MD030)
            if !chars.has_lists
                && (line.contains("* ")
                    || line.contains("- ")
                    || line.contains("+ ")
                    || trimmed.starts_with("* ")
                    || trimmed.starts_with("- ")
                    || trimmed.starts_with("+ ")
                    || trimmed.starts_with('*')
                    || trimmed.starts_with('-')
                    || trimmed.starts_with('+'))
            {
                chars.has_lists = true;
            }
            // Ordered lists: line starts with digit, or blockquote line contains digit followed by period
            if !chars.has_lists
                && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
                    && (line.contains(". ") || line.contains('.')))
                    || (trimmed.starts_with('>')
                        && trimmed.chars().any(|c| c.is_ascii_digit())
                        && (trimmed.contains(". ") || trimmed.contains('.'))))
            {
                chars.has_lists = true;
            }
            if !chars.has_links
                && (line.contains('[')
                    || line.contains("http://")
                    || line.contains("https://")
                    || line.contains("ftp://")
                    || line.contains("www."))
            {
                chars.has_links = true;
            }
            if !chars.has_images && line.contains("![") {
                chars.has_images = true;
            }
            if !chars.has_code
                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
            {
                chars.has_code = true;
            }
            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
                chars.has_emphasis = true;
            }
            if !chars.has_html && line.contains('<') {
                chars.has_html = true;
            }
            if !chars.has_tables && line.contains('|') {
                chars.has_tables = true;
            }
            if !chars.has_blockquotes && line.starts_with('>') {
                chars.has_blockquotes = true;
            }
        }

        chars.has_headings = has_atx_heading || has_setext_heading;
        chars
    }

    /// Check if a rule should be skipped based on content characteristics
    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
        match rule.category() {
            RuleCategory::Heading => !self.has_headings,
            RuleCategory::List => !self.has_lists,
            RuleCategory::Link => !self.has_links && !self.has_images,
            RuleCategory::Image => !self.has_images,
            RuleCategory::CodeBlock => !self.has_code,
            RuleCategory::Html => !self.has_html,
            RuleCategory::Emphasis => !self.has_emphasis,
            RuleCategory::Blockquote => !self.has_blockquotes,
            RuleCategory::Table => !self.has_tables,
            // Always check these categories as they apply to all content
            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
        }
    }
}

/// Compute content hash for incremental indexing change detection
///
/// Uses blake3 for native builds (fast, cryptographic-strength hash)
/// Falls back to std::hash for WASM builds
#[cfg(feature = "native")]
fn compute_content_hash(content: &str) -> String {
    blake3::hash(content.as_bytes()).to_hex().to_string()
}

/// Compute content hash for WASM builds using std::hash
#[cfg(not(feature = "native"))]
fn compute_content_hash(content: &str) -> String {
    use std::hash::{DefaultHasher, Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    content.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// Lint a file against the given rules with intelligent rule filtering
/// Assumes the provided `rules` vector contains the final,
/// configured, and filtered set of rules to be executed.
pub fn lint(
    content: &str,
    rules: &[Box<dyn Rule>],
    verbose: bool,
    flavor: crate::config::MarkdownFlavor,
    source_file: Option<std::path::PathBuf>,
    config: Option<&crate::config::Config>,
) -> LintResult {
    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
    result
}

/// Build FileIndex only (no linting) for cross-file analysis on cache hits
///
/// This is a lightweight function that only builds the FileIndex without running
/// any rules. Used when we have a cache hit but still need the FileIndex for
/// cross-file validation.
///
/// This avoids the overhead of re-running all rules when only the index data is needed.
pub fn build_file_index_only(
    content: &str,
    rules: &[Box<dyn Rule>],
    flavor: crate::config::MarkdownFlavor,
    source_file: Option<std::path::PathBuf>,
) -> crate::workspace_index::FileIndex {
    // Compute content hash for change detection
    let content_hash = compute_content_hash(content);
    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);

    // Early return for empty content
    if content.is_empty() {
        return file_index;
    }

    // Parse LintContext once with the provided flavor
    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);

    // Only call contribute_to_index for cross-file rules (no rule checking!)
    for rule in rules {
        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
            rule.contribute_to_index(&lint_ctx, &mut file_index);
        }
    }

    file_index
}

/// Lint a file and contribute to workspace index for cross-file analysis
///
/// This variant performs linting and optionally populates a `FileIndex` with data
/// needed for cross-file validation. The FileIndex is populated during linting,
/// avoiding duplicate parsing.
///
/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
pub fn lint_and_index(
    content: &str,
    rules: &[Box<dyn Rule>],
    _verbose: bool,
    flavor: crate::config::MarkdownFlavor,
    source_file: Option<std::path::PathBuf>,
    config: Option<&crate::config::Config>,
) -> (LintResult, crate::workspace_index::FileIndex) {
    let mut warnings = Vec::new();
    // Compute content hash for change detection
    let content_hash = compute_content_hash(content);
    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);

    #[cfg(not(target_arch = "wasm32"))]
    let _overall_start = Instant::now();

    // Early return for empty content
    if content.is_empty() {
        return (Ok(warnings), file_index);
    }

    // Parse LintContext once (includes inline config parsing)
    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
    let inline_config = lint_ctx.inline_config();

    // Export inline config data to FileIndex for cross-file rule filtering
    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
    file_index.file_disabled_rules = file_disabled;
    file_index.persistent_transitions = persistent_transitions;
    file_index.line_disabled_rules = line_disabled;

    // Analyze content characteristics for rule filtering
    let characteristics = ContentCharacteristics::analyze(content);

    // Filter rules based on content characteristics
    let applicable_rules: Vec<_> = rules
        .iter()
        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
        .collect();

    // Calculate skipped rules count before consuming applicable_rules
    let _total_rules = rules.len();
    let _applicable_count = applicable_rules.len();

    #[cfg(not(target_arch = "wasm32"))]
    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
    #[cfg(target_arch = "wasm32")]
    let profile_rules = false;

    // Automatic inline config support: merge inline overrides into config once,
    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
    let inline_overrides = inline_config.get_all_rule_configs();
    let merged_config = if !inline_overrides.is_empty() {
        config.map(|c| c.merge_with_inline_config(inline_config))
    } else {
        None
    };
    let effective_config = merged_config.as_ref().or(config);

    // Cache recreated rules for rules with inline overrides
    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
        std::collections::HashMap::new();

    // Pre-create rules that have inline config overrides
    if let Some(cfg) = effective_config {
        for rule_name in inline_overrides.keys() {
            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
                recreated_rules.insert(rule_name.clone(), recreated);
            }
        }
    }

    for rule in &applicable_rules {
        #[cfg(not(target_arch = "wasm32"))]
        let _rule_start = Instant::now();

        // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
        if rule.should_skip(&lint_ctx) {
            continue;
        }

        // Use recreated rule if inline config overrides exist for this rule
        let effective_rule: &dyn crate::rule::Rule = recreated_rules
            .get(rule.name())
            .map(|r| r.as_ref())
            .unwrap_or(rule.as_ref());

        // Run single-file check with the effective rule (possibly with inline config applied)
        let result = effective_rule.check(&lint_ctx);

        match result {
            Ok(rule_warnings) => {
                // Filter out warnings inside kramdown extension blocks (Layer 3 safety net)
                // and warnings for rules disabled via inline comments
                let filtered_warnings: Vec<_> = rule_warnings
                    .into_iter()
                    .filter(|warning| {
                        // Layer 3: Suppress warnings inside kramdown extension blocks
                        if lint_ctx
                            .line_info(warning.line)
                            .is_some_and(|info| info.in_kramdown_extension_block)
                        {
                            return false;
                        }

                        // Use the warning's rule_name if available, otherwise use the rule's name
                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());

                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
                            &rule_name_to_check[..dash_pos]
                        } else {
                            rule_name_to_check
                        };

                        // Check if the rule is disabled at any line in the warning's range.
                        // Multi-line warnings (e.g., reflow) report on the first line,
                        // but inline disable comments may appear later in the range.
                        // Guard: if end_line < line (e.g., end_line=0), fall back to
                        // checking only the warning's line to match original behavior.
                        {
                            let end = if warning.end_line >= warning.line {
                                warning.end_line
                            } else {
                                warning.line
                            };
                            !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
                        }
                    })
                    .map(|mut warning| {
                        // Apply severity override from config if present
                        if let Some(cfg) = config {
                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
                            if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
                                warning.severity = override_severity;
                            }
                        }
                        warning
                    })
                    .collect();
                warnings.extend(filtered_warnings);
            }
            Err(e) => {
                log::error!("Error checking rule {}: {}", rule.name(), e);
                return (Err(e), file_index);
            }
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let rule_duration = _rule_start.elapsed();
            if profile_rules {
                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
            }

            #[cfg(not(test))]
            if _verbose && rule_duration.as_millis() > 500 {
                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
            }
        }
    }

    // Contribute to index for cross-file rules (done after all rules checked)
    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
    // rules need to extract data from every file in the workspace, regardless of whether
    // that file has content that would trigger the rule. For example, MD051 needs to
    // index headings from files that have no links (like target.md) so that links
    // FROM other files TO those headings can be validated.
    for rule in rules {
        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
            rule.contribute_to_index(&lint_ctx, &mut file_index);
        }
    }

    #[cfg(not(test))]
    if _verbose {
        let skipped_rules = _total_rules - _applicable_count;
        if skipped_rules > 0 {
            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
        }
    }

    (Ok(warnings), file_index)
}

/// Run cross-file checks for rules that need workspace-wide validation
///
/// This should be called after all files have been linted and the WorkspaceIndex
/// has been built from the accumulated FileIndex data.
///
/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
/// The FileIndex was already populated during contribute_to_index in the linting phase.
///
/// Rules can use workspace_index methods for cross-file validation:
/// - `get_file(path)` - to look up headings in target files (for MD051)
///
/// Returns additional warnings from cross-file validation.
pub fn run_cross_file_checks(
    file_path: &std::path::Path,
    file_index: &crate::workspace_index::FileIndex,
    rules: &[Box<dyn Rule>],
    workspace_index: &crate::workspace_index::WorkspaceIndex,
    config: Option<&crate::config::Config>,
) -> LintResult {
    use crate::rule::CrossFileScope;

    let mut warnings = Vec::new();

    // Only check rules that need cross-file analysis
    for rule in rules {
        if rule.cross_file_scope() != CrossFileScope::Workspace {
            continue;
        }

        match rule.cross_file_check(file_path, file_index, workspace_index) {
            Ok(rule_warnings) => {
                // Filter cross-file warnings based on inline config stored in file_index
                let filtered: Vec<_> = rule_warnings
                    .into_iter()
                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
                    .map(|mut warning| {
                        // Apply severity override from config if present
                        if let Some(cfg) = config
                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
                        {
                            warning.severity = override_severity;
                        }
                        warning
                    })
                    .collect();
                warnings.extend(filtered);
            }
            Err(e) => {
                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
                return Err(e);
            }
        }
    }

    Ok(warnings)
}

/// Get the profiling report
pub fn get_profiling_report() -> String {
    profiling::get_report()
}

/// Reset the profiling data
pub fn reset_profiling() {
    profiling::reset()
}

/// Get regex cache statistics for performance monitoring
pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
    crate::utils::regex_cache::get_cache_stats()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rule::Rule;
    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};

    #[test]
    fn test_content_characteristics_analyze() {
        // Test empty content
        let chars = ContentCharacteristics::analyze("");
        assert!(!chars.has_headings);
        assert!(!chars.has_lists);
        assert!(!chars.has_links);
        assert!(!chars.has_code);
        assert!(!chars.has_emphasis);
        assert!(!chars.has_html);
        assert!(!chars.has_tables);
        assert!(!chars.has_blockquotes);
        assert!(!chars.has_images);

        // Test content with headings
        let chars = ContentCharacteristics::analyze("# Heading");
        assert!(chars.has_headings);

        // Test setext headings
        let chars = ContentCharacteristics::analyze("Heading\n=======");
        assert!(chars.has_headings);

        // Test lists
        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
        assert!(chars.has_lists);

        // Test ordered lists
        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
        assert!(chars.has_lists);

        // Test links
        let chars = ContentCharacteristics::analyze("[link](url)");
        assert!(chars.has_links);

        // Test URLs
        let chars = ContentCharacteristics::analyze("Visit https://example.com");
        assert!(chars.has_links);

        // Test images
        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
        assert!(chars.has_images);

        // Test code
        let chars = ContentCharacteristics::analyze("`inline code`");
        assert!(chars.has_code);

        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
        assert!(chars.has_code);

        // Test indented code blocks (4 spaces)
        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
        assert!(chars.has_code);

        // Test tab-indented code blocks
        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
        assert!(chars.has_code);

        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
        assert!(chars.has_code);

        // Test 1 space + tab (also 4 columns due to tab expansion)
        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
        assert!(chars.has_code);

        // Test emphasis
        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
        assert!(chars.has_emphasis);

        // Test HTML
        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
        assert!(chars.has_html);

        // Test tables
        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
        assert!(chars.has_tables);

        // Test blockquotes
        let chars = ContentCharacteristics::analyze("> Quote");
        assert!(chars.has_blockquotes);

        // Test mixed content
        let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n![image](img.png)";
        let chars = ContentCharacteristics::analyze(content);
        assert!(chars.has_headings);
        assert!(chars.has_lists);
        assert!(chars.has_links);
        assert!(chars.has_code);
        assert!(chars.has_emphasis);
        assert!(chars.has_html);
        assert!(chars.has_tables);
        assert!(chars.has_blockquotes);
        assert!(chars.has_images);
    }

    #[test]
    fn test_content_characteristics_should_skip_rule() {
        let chars = ContentCharacteristics {
            has_headings: true,
            has_lists: false,
            has_links: true,
            has_code: false,
            has_emphasis: true,
            has_html: false,
            has_tables: true,
            has_blockquotes: false,
            has_images: false,
        };

        // Create test rules for different categories
        let heading_rule = MD001HeadingIncrement::default();
        assert!(!chars.should_skip_rule(&heading_rule));

        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run

        // Test skipping based on content
        let chars_no_headings = ContentCharacteristics {
            has_headings: false,
            ..Default::default()
        };
        assert!(chars_no_headings.should_skip_rule(&heading_rule));
    }

    #[test]
    fn test_lint_empty_content() {
        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];

        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_lint_with_violations() {
        let content = "## Level 2\n#### Level 4"; // Skips level 3
        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];

        let result = lint(
            content,
            &rules,
            false,
            crate::config::MarkdownFlavor::Standard,
            None,
            None,
        );
        assert!(result.is_ok());
        let warnings = result.unwrap();
        assert!(!warnings.is_empty());
        // Check the rule field of LintWarning struct
        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
    }

    #[test]
    fn test_lint_with_inline_disable() {
        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];

        let result = lint(
            content,
            &rules,
            false,
            crate::config::MarkdownFlavor::Standard,
            None,
            None,
        );
        assert!(result.is_ok());
        let warnings = result.unwrap();
        assert!(warnings.is_empty()); // Should be disabled by inline comment
    }

    #[test]
    fn test_lint_rule_filtering() {
        // Content with no lists
        let content = "# Heading\nJust text";
        let rules: Vec<Box<dyn Rule>> = vec![
            Box::new(MD001HeadingIncrement::default()),
            // A list-related rule would be skipped
        ];

        let result = lint(
            content,
            &rules,
            false,
            crate::config::MarkdownFlavor::Standard,
            None,
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_get_profiling_report() {
        // Just test that it returns a string without panicking
        let report = get_profiling_report();
        assert!(!report.is_empty());
        assert!(report.contains("Profiling"));
    }

    #[test]
    fn test_reset_profiling() {
        // Test that reset_profiling doesn't panic
        reset_profiling();

        // After reset, report should indicate no measurements or profiling disabled
        let report = get_profiling_report();
        assert!(report.contains("disabled") || report.contains("no measurements"));
    }

    #[test]
    fn test_get_regex_cache_stats() {
        let stats = get_regex_cache_stats();
        // Stats should be a valid HashMap (might be empty)
        assert!(stats.is_empty() || !stats.is_empty());

        // If not empty, all values should be positive
        for count in stats.values() {
            assert!(*count > 0);
        }
    }

    #[test]
    fn test_content_characteristics_edge_cases() {
        // Test setext heading edge case
        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
        assert!(!chars.has_headings);

        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
        assert!(chars.has_headings);

        // Test list detection - we now include potential list patterns (with or without space)
        // to support user-intention detection in MD030
        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
        assert!(chars.has_lists); // Run list rules to be safe

        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
        assert!(chars.has_lists); // Run list rules for user-intention detection

        // Test blockquote must be at start of line
        let chars = ContentCharacteristics::analyze("text > not a quote");
        assert!(!chars.has_blockquotes);
    }
}