Skip to main content

rumdl_lib/
lib.rs

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