Skip to main content

rumdl_lib/
lib.rs

1pub mod code_block_tools;
2pub mod config;
3pub mod exit_codes;
4pub mod filtered_lines;
5pub mod fix_coordinator;
6pub mod inline_config;
7pub mod linguist_data;
8pub mod lint_context;
9pub mod markdownlint_config;
10pub mod profiling;
11pub mod rule;
12#[cfg(feature = "native")]
13pub mod vscode;
14pub mod workspace_index;
15#[macro_use]
16pub mod rule_config;
17#[macro_use]
18pub mod rule_config_serde;
19pub mod rules;
20pub mod types;
21pub mod utils;
22
23// Native-only modules (require tokio, tower-lsp, etc.)
24#[cfg(feature = "native")]
25pub mod lsp;
26#[cfg(feature = "native")]
27pub mod output;
28#[cfg(feature = "native")]
29pub mod parallel;
30#[cfg(feature = "native")]
31pub mod performance;
32
33// WASM module
34#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
35pub mod wasm;
36
37pub use rules::heading_utils::{Heading, HeadingStyle};
38pub use rules::*;
39
40pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
41use crate::rule::{LintResult, Rule, RuleCategory};
42use crate::utils::element_cache::ElementCache;
43#[cfg(not(target_arch = "wasm32"))]
44use std::time::Instant;
45
46/// Content characteristics for efficient rule filtering
47#[derive(Debug, Default)]
48struct ContentCharacteristics {
49    has_headings: bool,    // # or setext headings
50    has_lists: bool,       // *, -, +, 1. etc
51    has_links: bool,       // [text](url) or [text][ref]
52    has_code: bool,        // ``` or ~~~ or indented code
53    has_emphasis: bool,    // * or _ for emphasis
54    has_html: bool,        // < > tags
55    has_tables: bool,      // | pipes
56    has_blockquotes: bool, // > markers
57    has_images: bool,      // ![alt](url)
58}
59
60/// Check if a line has enough leading whitespace to be an indented code block.
61/// Indented code blocks require 4+ columns of leading whitespace (with proper tab expansion).
62fn has_potential_indented_code_indent(line: &str) -> bool {
63    ElementCache::calculate_indentation_width_default(line) >= 4
64}
65
66impl ContentCharacteristics {
67    fn analyze(content: &str) -> Self {
68        let mut chars = Self { ..Default::default() };
69
70        // Quick single-pass analysis
71        let mut has_atx_heading = false;
72        let mut has_setext_heading = false;
73
74        for line in content.lines() {
75            let trimmed = line.trim();
76
77            // Headings: ATX (#) or Setext (underlines)
78            if !has_atx_heading && trimmed.starts_with('#') {
79                has_atx_heading = true;
80            }
81            if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
82                has_setext_heading = true;
83            }
84
85            // Quick character-based detection (more efficient than regex)
86            // Include patterns without spaces to enable user-intention detection (MD030)
87            if !chars.has_lists
88                && (line.contains("* ")
89                    || line.contains("- ")
90                    || line.contains("+ ")
91                    || trimmed.starts_with("* ")
92                    || trimmed.starts_with("- ")
93                    || trimmed.starts_with("+ ")
94                    || trimmed.starts_with('*')
95                    || trimmed.starts_with('-')
96                    || trimmed.starts_with('+'))
97            {
98                chars.has_lists = true;
99            }
100            // Ordered lists: line starts with digit, or blockquote line contains digit followed by period
101            if !chars.has_lists
102                && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
103                    && (line.contains(". ") || line.contains('.')))
104                    || (trimmed.starts_with('>')
105                        && trimmed.chars().any(|c| c.is_ascii_digit())
106                        && (trimmed.contains(". ") || trimmed.contains('.'))))
107            {
108                chars.has_lists = true;
109            }
110            if !chars.has_links
111                && (line.contains('[')
112                    || line.contains("http://")
113                    || line.contains("https://")
114                    || line.contains("ftp://")
115                    || line.contains("www."))
116            {
117                chars.has_links = true;
118            }
119            if !chars.has_images && line.contains("![") {
120                chars.has_images = true;
121            }
122            if !chars.has_code
123                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
124            {
125                chars.has_code = true;
126            }
127            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
128                chars.has_emphasis = true;
129            }
130            if !chars.has_html && line.contains('<') {
131                chars.has_html = true;
132            }
133            if !chars.has_tables && line.contains('|') {
134                chars.has_tables = true;
135            }
136            if !chars.has_blockquotes && line.starts_with('>') {
137                chars.has_blockquotes = true;
138            }
139        }
140
141        chars.has_headings = has_atx_heading || has_setext_heading;
142        chars
143    }
144
145    /// Check if a rule should be skipped based on content characteristics
146    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
147        match rule.category() {
148            RuleCategory::Heading => !self.has_headings,
149            RuleCategory::List => !self.has_lists,
150            RuleCategory::Link => !self.has_links && !self.has_images,
151            RuleCategory::Image => !self.has_images,
152            RuleCategory::CodeBlock => !self.has_code,
153            RuleCategory::Html => !self.has_html,
154            RuleCategory::Emphasis => !self.has_emphasis,
155            RuleCategory::Blockquote => !self.has_blockquotes,
156            RuleCategory::Table => !self.has_tables,
157            // Always check these categories as they apply to all content
158            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
159        }
160    }
161}
162
163/// Compute content hash for incremental indexing change detection
164///
165/// Uses blake3 for native builds (fast, cryptographic-strength hash)
166/// Falls back to std::hash for WASM builds
167#[cfg(feature = "native")]
168fn compute_content_hash(content: &str) -> String {
169    blake3::hash(content.as_bytes()).to_hex().to_string()
170}
171
172/// Compute content hash for WASM builds using std::hash
173#[cfg(not(feature = "native"))]
174fn compute_content_hash(content: &str) -> String {
175    use std::hash::{DefaultHasher, Hash, Hasher};
176    let mut hasher = DefaultHasher::new();
177    content.hash(&mut hasher);
178    format!("{:016x}", hasher.finish())
179}
180
181/// Lint a file against the given rules with intelligent rule filtering
182/// Assumes the provided `rules` vector contains the final,
183/// configured, and filtered set of rules to be executed.
184pub fn lint(
185    content: &str,
186    rules: &[Box<dyn Rule>],
187    verbose: bool,
188    flavor: crate::config::MarkdownFlavor,
189    config: Option<&crate::config::Config>,
190) -> LintResult {
191    // Use lint_and_index but discard the FileIndex for backward compatibility
192    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
193    result
194}
195
196/// Build FileIndex only (no linting) for cross-file analysis on cache hits
197///
198/// This is a lightweight function that only builds the FileIndex without running
199/// any rules. Used when we have a cache hit but still need the FileIndex for
200/// cross-file validation.
201///
202/// This avoids the overhead of re-running all rules when only the index data is needed.
203pub fn build_file_index_only(
204    content: &str,
205    rules: &[Box<dyn Rule>],
206    flavor: crate::config::MarkdownFlavor,
207) -> crate::workspace_index::FileIndex {
208    // Compute content hash for change detection
209    let content_hash = compute_content_hash(content);
210    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
211
212    // Early return for empty content
213    if content.is_empty() {
214        return file_index;
215    }
216
217    // Parse LintContext once with the provided flavor
218    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
219
220    // Only call contribute_to_index for cross-file rules (no rule checking!)
221    for rule in rules {
222        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
223            rule.contribute_to_index(&lint_ctx, &mut file_index);
224        }
225    }
226
227    file_index
228}
229
230/// Lint a file and contribute to workspace index for cross-file analysis
231///
232/// This variant performs linting and optionally populates a `FileIndex` with data
233/// needed for cross-file validation. The FileIndex is populated during linting,
234/// avoiding duplicate parsing.
235///
236/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
237pub fn lint_and_index(
238    content: &str,
239    rules: &[Box<dyn Rule>],
240    _verbose: bool,
241    flavor: crate::config::MarkdownFlavor,
242    source_file: Option<std::path::PathBuf>,
243    config: Option<&crate::config::Config>,
244) -> (LintResult, crate::workspace_index::FileIndex) {
245    let mut warnings = Vec::new();
246    // Compute content hash for change detection
247    let content_hash = compute_content_hash(content);
248    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
249
250    #[cfg(not(target_arch = "wasm32"))]
251    let _overall_start = Instant::now();
252
253    // Early return for empty content
254    if content.is_empty() {
255        return (Ok(warnings), file_index);
256    }
257
258    // Parse LintContext once (includes inline config parsing)
259    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
260    let inline_config = lint_ctx.inline_config();
261
262    // Export inline config data to FileIndex for cross-file rule filtering
263    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
264    file_index.file_disabled_rules = file_disabled;
265    file_index.persistent_transitions = persistent_transitions;
266    file_index.line_disabled_rules = line_disabled;
267
268    // Analyze content characteristics for rule filtering
269    let characteristics = ContentCharacteristics::analyze(content);
270
271    // Filter rules based on content characteristics
272    let applicable_rules: Vec<_> = rules
273        .iter()
274        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
275        .collect();
276
277    // Calculate skipped rules count before consuming applicable_rules
278    let _total_rules = rules.len();
279    let _applicable_count = applicable_rules.len();
280
281    #[cfg(not(target_arch = "wasm32"))]
282    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
283    #[cfg(target_arch = "wasm32")]
284    let profile_rules = false;
285
286    // Automatic inline config support: merge inline overrides into config once,
287    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
288    let inline_overrides = inline_config.get_all_rule_configs();
289    let merged_config = if !inline_overrides.is_empty() {
290        config.map(|c| c.merge_with_inline_config(inline_config))
291    } else {
292        None
293    };
294    let effective_config = merged_config.as_ref().or(config);
295
296    // Cache recreated rules for rules with inline overrides
297    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
298        std::collections::HashMap::new();
299
300    // Pre-create rules that have inline config overrides
301    if let Some(cfg) = effective_config {
302        for rule_name in inline_overrides.keys() {
303            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
304                recreated_rules.insert(rule_name.clone(), recreated);
305            }
306        }
307    }
308
309    for rule in &applicable_rules {
310        #[cfg(not(target_arch = "wasm32"))]
311        let _rule_start = Instant::now();
312
313        // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
314        if rule.should_skip(&lint_ctx) {
315            continue;
316        }
317
318        // Use recreated rule if inline config overrides exist for this rule
319        let effective_rule: &dyn crate::rule::Rule = recreated_rules
320            .get(rule.name())
321            .map(|r| r.as_ref())
322            .unwrap_or(rule.as_ref());
323
324        // Run single-file check with the effective rule (possibly with inline config applied)
325        let result = effective_rule.check(&lint_ctx);
326
327        match result {
328            Ok(rule_warnings) => {
329                // Filter out warnings inside kramdown extension blocks (Layer 3 safety net)
330                // and warnings for rules disabled via inline comments
331                let filtered_warnings: Vec<_> = rule_warnings
332                    .into_iter()
333                    .filter(|warning| {
334                        // Layer 3: Suppress warnings inside kramdown extension blocks
335                        if lint_ctx
336                            .line_info(warning.line)
337                            .is_some_and(|info| info.in_kramdown_extension_block)
338                        {
339                            return false;
340                        }
341
342                        // Use the warning's rule_name if available, otherwise use the rule's name
343                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
344
345                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
346                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
347                            &rule_name_to_check[..dash_pos]
348                        } else {
349                            rule_name_to_check
350                        };
351
352                        !inline_config.is_rule_disabled(
353                            base_rule_name,
354                            warning.line, // Already 1-indexed
355                        )
356                    })
357                    .map(|mut warning| {
358                        // Apply severity override from config if present
359                        if let Some(cfg) = config {
360                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
361                            if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
362                                warning.severity = override_severity;
363                            }
364                        }
365                        warning
366                    })
367                    .collect();
368                warnings.extend(filtered_warnings);
369            }
370            Err(e) => {
371                log::error!("Error checking rule {}: {}", rule.name(), e);
372                return (Err(e), file_index);
373            }
374        }
375
376        #[cfg(not(target_arch = "wasm32"))]
377        {
378            let rule_duration = _rule_start.elapsed();
379            if profile_rules {
380                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
381            }
382
383            #[cfg(not(test))]
384            if _verbose && rule_duration.as_millis() > 500 {
385                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
386            }
387        }
388    }
389
390    // Contribute to index for cross-file rules (done after all rules checked)
391    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
392    // rules need to extract data from every file in the workspace, regardless of whether
393    // that file has content that would trigger the rule. For example, MD051 needs to
394    // index headings from files that have no links (like target.md) so that links
395    // FROM other files TO those headings can be validated.
396    for rule in rules {
397        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
398            rule.contribute_to_index(&lint_ctx, &mut file_index);
399        }
400    }
401
402    #[cfg(not(test))]
403    if _verbose {
404        let skipped_rules = _total_rules - _applicable_count;
405        if skipped_rules > 0 {
406            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
407        }
408    }
409
410    (Ok(warnings), file_index)
411}
412
413/// Run cross-file checks for rules that need workspace-wide validation
414///
415/// This should be called after all files have been linted and the WorkspaceIndex
416/// has been built from the accumulated FileIndex data.
417///
418/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
419/// The FileIndex was already populated during contribute_to_index in the linting phase.
420///
421/// Rules can use workspace_index methods for cross-file validation:
422/// - `get_file(path)` - to look up headings in target files (for MD051)
423///
424/// Returns additional warnings from cross-file validation.
425pub fn run_cross_file_checks(
426    file_path: &std::path::Path,
427    file_index: &crate::workspace_index::FileIndex,
428    rules: &[Box<dyn Rule>],
429    workspace_index: &crate::workspace_index::WorkspaceIndex,
430    config: Option<&crate::config::Config>,
431) -> LintResult {
432    use crate::rule::CrossFileScope;
433
434    let mut warnings = Vec::new();
435
436    // Only check rules that need cross-file analysis
437    for rule in rules {
438        if rule.cross_file_scope() != CrossFileScope::Workspace {
439            continue;
440        }
441
442        match rule.cross_file_check(file_path, file_index, workspace_index) {
443            Ok(rule_warnings) => {
444                // Filter cross-file warnings based on inline config stored in file_index
445                let filtered: Vec<_> = rule_warnings
446                    .into_iter()
447                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
448                    .map(|mut warning| {
449                        // Apply severity override from config if present
450                        if let Some(cfg) = config
451                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
452                        {
453                            warning.severity = override_severity;
454                        }
455                        warning
456                    })
457                    .collect();
458                warnings.extend(filtered);
459            }
460            Err(e) => {
461                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
462                return Err(e);
463            }
464        }
465    }
466
467    Ok(warnings)
468}
469
470/// Get the profiling report
471pub fn get_profiling_report() -> String {
472    profiling::get_report()
473}
474
475/// Reset the profiling data
476pub fn reset_profiling() {
477    profiling::reset()
478}
479
480/// Get regex cache statistics for performance monitoring
481pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
482    crate::utils::regex_cache::get_cache_stats()
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::rule::Rule;
489    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
490
491    #[test]
492    fn test_content_characteristics_analyze() {
493        // Test empty content
494        let chars = ContentCharacteristics::analyze("");
495        assert!(!chars.has_headings);
496        assert!(!chars.has_lists);
497        assert!(!chars.has_links);
498        assert!(!chars.has_code);
499        assert!(!chars.has_emphasis);
500        assert!(!chars.has_html);
501        assert!(!chars.has_tables);
502        assert!(!chars.has_blockquotes);
503        assert!(!chars.has_images);
504
505        // Test content with headings
506        let chars = ContentCharacteristics::analyze("# Heading");
507        assert!(chars.has_headings);
508
509        // Test setext headings
510        let chars = ContentCharacteristics::analyze("Heading\n=======");
511        assert!(chars.has_headings);
512
513        // Test lists
514        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
515        assert!(chars.has_lists);
516
517        // Test ordered lists
518        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
519        assert!(chars.has_lists);
520
521        // Test links
522        let chars = ContentCharacteristics::analyze("[link](url)");
523        assert!(chars.has_links);
524
525        // Test URLs
526        let chars = ContentCharacteristics::analyze("Visit https://example.com");
527        assert!(chars.has_links);
528
529        // Test images
530        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
531        assert!(chars.has_images);
532
533        // Test code
534        let chars = ContentCharacteristics::analyze("`inline code`");
535        assert!(chars.has_code);
536
537        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
538        assert!(chars.has_code);
539
540        // Test indented code blocks (4 spaces)
541        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
542        assert!(chars.has_code);
543
544        // Test tab-indented code blocks
545        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
546        assert!(chars.has_code);
547
548        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
549        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
550        assert!(chars.has_code);
551
552        // Test 1 space + tab (also 4 columns due to tab expansion)
553        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
554        assert!(chars.has_code);
555
556        // Test emphasis
557        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
558        assert!(chars.has_emphasis);
559
560        // Test HTML
561        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
562        assert!(chars.has_html);
563
564        // Test tables
565        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
566        assert!(chars.has_tables);
567
568        // Test blockquotes
569        let chars = ContentCharacteristics::analyze("> Quote");
570        assert!(chars.has_blockquotes);
571
572        // Test mixed content
573        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)";
574        let chars = ContentCharacteristics::analyze(content);
575        assert!(chars.has_headings);
576        assert!(chars.has_lists);
577        assert!(chars.has_links);
578        assert!(chars.has_code);
579        assert!(chars.has_emphasis);
580        assert!(chars.has_html);
581        assert!(chars.has_tables);
582        assert!(chars.has_blockquotes);
583        assert!(chars.has_images);
584    }
585
586    #[test]
587    fn test_content_characteristics_should_skip_rule() {
588        let chars = ContentCharacteristics {
589            has_headings: true,
590            has_lists: false,
591            has_links: true,
592            has_code: false,
593            has_emphasis: true,
594            has_html: false,
595            has_tables: true,
596            has_blockquotes: false,
597            has_images: false,
598        };
599
600        // Create test rules for different categories
601        let heading_rule = MD001HeadingIncrement::default();
602        assert!(!chars.should_skip_rule(&heading_rule));
603
604        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
605        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
606
607        // Test skipping based on content
608        let chars_no_headings = ContentCharacteristics {
609            has_headings: false,
610            ..Default::default()
611        };
612        assert!(chars_no_headings.should_skip_rule(&heading_rule));
613    }
614
615    #[test]
616    fn test_lint_empty_content() {
617        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
618
619        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
620        assert!(result.is_ok());
621        assert!(result.unwrap().is_empty());
622    }
623
624    #[test]
625    fn test_lint_with_violations() {
626        let content = "## Level 2\n#### Level 4"; // Skips level 3
627        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
628
629        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
630        assert!(result.is_ok());
631        let warnings = result.unwrap();
632        assert!(!warnings.is_empty());
633        // Check the rule field of LintWarning struct
634        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
635    }
636
637    #[test]
638    fn test_lint_with_inline_disable() {
639        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
640        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
641
642        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
643        assert!(result.is_ok());
644        let warnings = result.unwrap();
645        assert!(warnings.is_empty()); // Should be disabled by inline comment
646    }
647
648    #[test]
649    fn test_lint_rule_filtering() {
650        // Content with no lists
651        let content = "# Heading\nJust text";
652        let rules: Vec<Box<dyn Rule>> = vec![
653            Box::new(MD001HeadingIncrement::default()),
654            // A list-related rule would be skipped
655        ];
656
657        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
658        assert!(result.is_ok());
659    }
660
661    #[test]
662    fn test_get_profiling_report() {
663        // Just test that it returns a string without panicking
664        let report = get_profiling_report();
665        assert!(!report.is_empty());
666        assert!(report.contains("Profiling"));
667    }
668
669    #[test]
670    fn test_reset_profiling() {
671        // Test that reset_profiling doesn't panic
672        reset_profiling();
673
674        // After reset, report should indicate no measurements or profiling disabled
675        let report = get_profiling_report();
676        assert!(report.contains("disabled") || report.contains("no measurements"));
677    }
678
679    #[test]
680    fn test_get_regex_cache_stats() {
681        let stats = get_regex_cache_stats();
682        // Stats should be a valid HashMap (might be empty)
683        assert!(stats.is_empty() || !stats.is_empty());
684
685        // If not empty, all values should be positive
686        for count in stats.values() {
687            assert!(*count > 0);
688        }
689    }
690
691    #[test]
692    fn test_content_characteristics_edge_cases() {
693        // Test setext heading edge case
694        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
695        assert!(!chars.has_headings);
696
697        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
698        assert!(chars.has_headings);
699
700        // Test list detection - we now include potential list patterns (with or without space)
701        // to support user-intention detection in MD030
702        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
703        assert!(chars.has_lists); // Run list rules to be safe
704
705        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
706        assert!(chars.has_lists); // Run list rules for user-intention detection
707
708        // Test blockquote must be at start of line
709        let chars = ContentCharacteristics::analyze("text > not a quote");
710        assert!(!chars.has_blockquotes);
711    }
712}