Skip to main content

rumdl_lib/
lib.rs

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