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