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    // Export inline disable data to the FileIndex so cross-file checks honor
288    // `<!-- rumdl-disable -->` blocks on the lint-cache fast path, exactly as
289    // lint_and_index does on the normal path.
290    let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
291    file_index.file_disabled_rules = file_disabled;
292    file_index.persistent_transitions = persistent_transitions;
293    file_index.line_disabled_rules = line_disabled;
294
295    // Only call contribute_to_index for cross-file rules (no rule checking!)
296    time_section!("index: contribute cross-file data", {
297        for rule in rules {
298            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
299                rule.contribute_to_index(&lint_ctx, &mut file_index);
300            }
301        }
302    });
303
304    file_index
305}
306
307/// Lint a file and contribute to workspace index for cross-file analysis
308///
309/// This variant performs linting and optionally populates a `FileIndex` with data
310/// needed for cross-file validation. The FileIndex is populated during linting,
311/// avoiding duplicate parsing.
312///
313/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
314#[cfg_attr(test, allow(unused_variables))]
315pub fn lint_and_index(
316    content: &str,
317    rules: &[Box<dyn Rule>],
318    verbose: bool,
319    flavor: crate::config::MarkdownFlavor,
320    source_file: Option<std::path::PathBuf>,
321    config: Option<&crate::config::Config>,
322) -> (LintResult, crate::workspace_index::FileIndex) {
323    let mut warnings = Vec::new();
324    // Compute content hash for change detection
325    let content_hash = compute_content_hash(content);
326    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
327
328    // Early return for empty content
329    if content.is_empty() {
330        return (Ok(warnings), file_index);
331    }
332
333    // Parse LintContext once (includes inline config parsing)
334    let lint_ctx = time_function!(
335        "lint: parse lint context",
336        crate::lint_context::LintContext::new(content, flavor, source_file)
337    );
338    let inline_config = lint_ctx.inline_config();
339
340    // Export inline config data to FileIndex for cross-file rule filtering
341    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
342    file_index.file_disabled_rules = file_disabled;
343    file_index.persistent_transitions = persistent_transitions;
344    file_index.line_disabled_rules = line_disabled;
345
346    // Analyze content characteristics for rule filtering
347    let characteristics = time_function!(
348        "lint: analyze content characteristics",
349        ContentCharacteristics::analyze(content)
350    );
351
352    // Filter rules based on content characteristics
353    let applicable_rules: Vec<_> = rules
354        .iter()
355        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
356        .collect();
357
358    // Calculate skipped rules count before consuming applicable_rules
359    #[cfg(not(test))]
360    let total_rules = rules.len();
361    #[cfg(not(test))]
362    let applicable_count = applicable_rules.len();
363
364    #[cfg(not(target_arch = "wasm32"))]
365    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
366
367    // Automatic inline config support: merge inline overrides into config once,
368    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
369    let inline_overrides = inline_config.get_all_rule_configs();
370    let merged_config = if !inline_overrides.is_empty() {
371        config.map(|c| c.merge_with_inline_config(inline_config))
372    } else {
373        None
374    };
375    let effective_config = merged_config.as_ref().or(config);
376
377    // Cache recreated rules for rules with inline overrides
378    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
379        std::collections::HashMap::new();
380
381    // Pre-create rules that have inline config overrides
382    if let Some(cfg) = effective_config {
383        for rule_name in inline_overrides.keys() {
384            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
385                recreated_rules.insert(rule_name.clone(), recreated);
386            }
387        }
388    }
389
390    {
391        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
392        for rule in &applicable_rules {
393            #[cfg(not(target_arch = "wasm32"))]
394            let rule_start = Instant::now();
395
396            // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
397            if rule.should_skip(&lint_ctx) {
398                continue;
399            }
400
401            // Use recreated rule if inline config overrides exist for this rule
402            let effective_rule: &dyn crate::rule::Rule = recreated_rules
403                .get(rule.name())
404                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
405
406            // Run single-file check with the effective rule (possibly with inline config applied)
407            let result = effective_rule.check(&lint_ctx);
408
409            match result {
410                Ok(rule_warnings) => {
411                    // Filter out warnings inside kramdown extension blocks (Layer 3 safety net)
412                    // and warnings for rules disabled via inline comments
413                    let filtered_warnings: Vec<_> = rule_warnings
414                        .into_iter()
415                        .filter(|warning| {
416                            // Layer 3: Suppress warnings inside kramdown extension blocks
417                            if lint_ctx
418                                .line_info(warning.line)
419                                .is_some_and(|info| info.in_kramdown_extension_block)
420                            {
421                                return false;
422                            }
423
424                            // Use the warning's rule_name if available, otherwise use the rule's name
425                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
426
427                            // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
428                            let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
429                                &rule_name_to_check[..dash_pos]
430                            } else {
431                                rule_name_to_check
432                            };
433
434                            // Check if the rule is disabled at any line in the warning's range.
435                            // Multi-line warnings (e.g., reflow) report on the first line,
436                            // but inline disable comments may appear later in the range.
437                            // Guard: if end_line < line (e.g., end_line=0), fall back to
438                            // checking only the warning's line to match original behavior.
439                            {
440                                let end = if warning.end_line >= warning.line {
441                                    warning.end_line
442                                } else {
443                                    warning.line
444                                };
445                                !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
446                            }
447                        })
448                        .map(|mut warning| {
449                            // Apply severity override from config if present
450                            if let Some(cfg) = config {
451                                let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
452                                if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
453                                    warning.severity = override_severity;
454                                }
455                            }
456                            warning
457                        })
458                        .collect();
459                    warnings.extend(filtered_warnings);
460                }
461                Err(e) => {
462                    log::error!("Error checking rule {}: {}", rule.name(), e);
463                    return (Err(e), file_index);
464                }
465            }
466
467            #[cfg(not(target_arch = "wasm32"))]
468            {
469                let rule_duration = rule_start.elapsed();
470                if profile_rules {
471                    eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
472                }
473
474                #[cfg(not(test))]
475                if verbose && rule_duration.as_millis() > 500 {
476                    log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
477                }
478            }
479        }
480    }
481
482    // Contribute to index for cross-file rules (done after all rules checked)
483    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
484    // rules need to extract data from every file in the workspace, regardless of whether
485    // that file has content that would trigger the rule. For example, MD051 needs to
486    // index headings from files that have no links (like target.md) so that links
487    // FROM other files TO those headings can be validated.
488    time_section!("lint: contribute cross-file data", {
489        for rule in rules {
490            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
491                rule.contribute_to_index(&lint_ctx, &mut file_index);
492            }
493        }
494    });
495
496    #[cfg(not(test))]
497    if verbose {
498        let skipped_rules = total_rules - applicable_count;
499        if skipped_rules > 0 {
500            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
501        }
502    }
503
504    (Ok(warnings), file_index)
505}
506
507/// Run cross-file checks for rules that need workspace-wide validation
508///
509/// This should be called after all files have been linted and the WorkspaceIndex
510/// has been built from the accumulated FileIndex data.
511///
512/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
513/// The FileIndex was already populated during contribute_to_index in the linting phase.
514///
515/// Rules can use workspace_index methods for cross-file validation:
516/// - `get_file(path)` - to look up headings in target files (for MD051)
517///
518/// Returns additional warnings from cross-file validation.
519pub fn run_cross_file_checks(
520    file_path: &std::path::Path,
521    file_index: &crate::workspace_index::FileIndex,
522    rules: &[Box<dyn Rule>],
523    workspace_index: &crate::workspace_index::WorkspaceIndex,
524    config: Option<&crate::config::Config>,
525) -> LintResult {
526    use crate::rule::CrossFileScope;
527
528    let mut warnings = Vec::new();
529
530    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
531    // attributed to `file_path` (the file holding the link), so a rule ignored
532    // for that file must not emit them. This applies on every path; single-file
533    // rule filtering does not cover cross-file checks because they run over the
534    // config group's full rule set, and cross-file rules share link data.
535    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
536
537    // Only check rules that need cross-file analysis
538    for rule in rules {
539        if rule.cross_file_scope() != CrossFileScope::Workspace {
540            continue;
541        }
542
543        if ignored_rules_for_file
544            .as_ref()
545            .is_some_and(|ignored| ignored.contains(rule.name()))
546        {
547            continue;
548        }
549
550        match time_function!(
551            "workspace: cross-file rule check",
552            rule.cross_file_check(file_path, file_index, workspace_index)
553        ) {
554            Ok(rule_warnings) => {
555                // Filter cross-file warnings based on inline config stored in file_index
556                let filtered: Vec<_> = rule_warnings
557                    .into_iter()
558                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
559                    .map(|mut warning| {
560                        // Apply severity override from config if present
561                        if let Some(cfg) = config
562                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
563                        {
564                            warning.severity = override_severity;
565                        }
566                        warning
567                    })
568                    .collect();
569                warnings.extend(filtered);
570            }
571            Err(e) => {
572                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
573                return Err(e);
574            }
575        }
576    }
577
578    Ok(warnings)
579}
580
581/// Get the profiling report
582pub fn get_profiling_report() -> String {
583    profiling::get_report()
584}
585
586/// Reset the profiling data
587pub fn reset_profiling() {
588    profiling::reset()
589}
590
591/// Get regex cache statistics for performance monitoring
592pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
593    crate::utils::regex_cache::get_cache_stats()
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use crate::rule::Rule;
600    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
601
602    #[test]
603    fn test_content_characteristics_analyze() {
604        // Test empty content
605        let chars = ContentCharacteristics::analyze("");
606        assert!(!chars.has_headings);
607        assert!(!chars.has_lists);
608        assert!(!chars.has_links);
609        assert!(!chars.has_code);
610        assert!(!chars.has_emphasis);
611        assert!(!chars.has_html);
612        assert!(!chars.has_tables);
613        assert!(!chars.has_blockquotes);
614        assert!(!chars.has_images);
615
616        // Test content with headings
617        let chars = ContentCharacteristics::analyze("# Heading");
618        assert!(chars.has_headings);
619
620        // Test setext headings
621        let chars = ContentCharacteristics::analyze("Heading\n=======");
622        assert!(chars.has_headings);
623
624        // Blockquoted ATX headings emit fragment anchors, so Heading-category
625        // rules (MD051/MD080) must run for blockquote-only documents.
626        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
627        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
628        let chars = ContentCharacteristics::analyze(">> # Nested");
629        assert!(
630            chars.has_headings,
631            "nested-blockquote ATX heading must set has_headings"
632        );
633        // A tab after the blockquote marker is also a valid heading
634        // (`parse_blockquote_prefix` accepts it).
635        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
636        assert!(
637            chars.has_headings,
638            "tab-separated blockquote ATX heading must set has_headings"
639        );
640
641        // Test lists
642        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
643        assert!(chars.has_lists);
644
645        // Test ordered lists
646        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
647        assert!(chars.has_lists);
648
649        // Test links
650        let chars = ContentCharacteristics::analyze("[link](url)");
651        assert!(chars.has_links);
652
653        // Test URLs
654        let chars = ContentCharacteristics::analyze("Visit https://example.com");
655        assert!(chars.has_links);
656
657        // Test images
658        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
659        assert!(chars.has_images);
660
661        // Test code
662        let chars = ContentCharacteristics::analyze("`inline code`");
663        assert!(chars.has_code);
664
665        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
666        assert!(chars.has_code);
667
668        // Test indented code blocks (4 spaces)
669        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
670        assert!(chars.has_code);
671
672        // Test tab-indented code blocks
673        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
674        assert!(chars.has_code);
675
676        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
677        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
678        assert!(chars.has_code);
679
680        // Test 1 space + tab (also 4 columns due to tab expansion)
681        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
682        assert!(chars.has_code);
683
684        // Test emphasis
685        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
686        assert!(chars.has_emphasis);
687
688        // Test HTML
689        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
690        assert!(chars.has_html);
691
692        // Test tables
693        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
694        assert!(chars.has_tables);
695
696        // Test blockquotes
697        let chars = ContentCharacteristics::analyze("> Quote");
698        assert!(chars.has_blockquotes);
699
700        // Test mixed content
701        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)";
702        let chars = ContentCharacteristics::analyze(content);
703        assert!(chars.has_headings);
704        assert!(chars.has_lists);
705        assert!(chars.has_links);
706        assert!(chars.has_code);
707        assert!(chars.has_emphasis);
708        assert!(chars.has_html);
709        assert!(chars.has_tables);
710        assert!(chars.has_blockquotes);
711        assert!(chars.has_images);
712    }
713
714    #[test]
715    fn test_content_characteristics_should_skip_rule() {
716        let chars = ContentCharacteristics {
717            has_headings: true,
718            has_lists: false,
719            has_links: true,
720            has_code: false,
721            has_emphasis: true,
722            has_html: false,
723            has_tables: true,
724            has_blockquotes: false,
725            has_images: false,
726        };
727
728        // Create test rules for different categories
729        let heading_rule = MD001HeadingIncrement::default();
730        assert!(!chars.should_skip_rule(&heading_rule));
731
732        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
733        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
734
735        // Test skipping based on content
736        let chars_no_headings = ContentCharacteristics {
737            has_headings: false,
738            ..Default::default()
739        };
740        assert!(chars_no_headings.should_skip_rule(&heading_rule));
741    }
742
743    #[test]
744    fn test_lint_empty_content() {
745        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
746
747        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
748        assert!(result.is_ok());
749        assert!(result.unwrap().is_empty());
750    }
751
752    #[test]
753    fn test_lint_with_violations() {
754        let content = "## Level 2\n#### Level 4"; // Skips level 3
755        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
756
757        let result = lint(
758            content,
759            &rules,
760            false,
761            crate::config::MarkdownFlavor::Standard,
762            None,
763            None,
764        );
765        assert!(result.is_ok());
766        let warnings = result.unwrap();
767        assert!(!warnings.is_empty());
768        // Check the rule field of LintWarning struct
769        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
770    }
771
772    #[test]
773    fn test_lint_with_inline_disable() {
774        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
775        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
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        let warnings = result.unwrap();
787        assert!(warnings.is_empty()); // Should be disabled by inline comment
788    }
789
790    #[test]
791    fn test_lint_rule_filtering() {
792        // Content with no lists
793        let content = "# Heading\nJust text";
794        let rules: Vec<Box<dyn Rule>> = vec![
795            Box::new(MD001HeadingIncrement::default()),
796            // A list-related rule would be skipped
797        ];
798
799        let result = lint(
800            content,
801            &rules,
802            false,
803            crate::config::MarkdownFlavor::Standard,
804            None,
805            None,
806        );
807        assert!(result.is_ok());
808    }
809
810    #[test]
811    fn test_get_profiling_report() {
812        // Just test that it returns a string without panicking
813        let report = get_profiling_report();
814        assert!(!report.is_empty());
815        assert!(report.contains("Profiling"));
816    }
817
818    #[test]
819    fn test_reset_profiling() {
820        // Test that reset_profiling doesn't panic
821        reset_profiling();
822
823        // After reset, report should indicate no measurements or profiling disabled
824        let report = get_profiling_report();
825        assert!(report.contains("disabled") || report.contains("no measurements"));
826    }
827
828    #[test]
829    fn test_get_regex_cache_stats() {
830        let stats = get_regex_cache_stats();
831        // Stats should be a valid HashMap (might be empty)
832        assert!(stats.is_empty() || !stats.is_empty());
833
834        // If not empty, all values should be positive
835        for count in stats.values() {
836            assert!(*count > 0);
837        }
838    }
839
840    #[test]
841    fn test_content_characteristics_edge_cases() {
842        // Test setext heading edge case
843        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
844        assert!(!chars.has_headings);
845
846        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
847        assert!(chars.has_headings);
848
849        // Test list detection - we now include potential list patterns (with or without space)
850        // to support user-intention detection in MD030
851        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
852        assert!(chars.has_lists); // Run list rules to be safe
853
854        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
855        assert!(chars.has_lists); // Run list rules for user-intention detection
856
857        // Test blockquote must be at start of line
858        let chars = ContentCharacteristics::analyze("text > not a quote");
859        assert!(!chars.has_blockquotes);
860    }
861}