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
50extern crate alloc;
51
52pub mod code_block_tools;
53pub mod config;
54#[cfg(any(feature = "native", feature = "wasi"))]
55#[doc(hidden)]
56pub mod custom_rules;
57pub mod discovery;
58pub mod doc_comment_lint;
59pub mod document_run;
60pub mod embedded_lint;
61pub mod encoding;
62pub mod exit_codes;
63pub mod filtered_lines;
64pub mod fix_coordinator;
65pub mod inline_config;
66pub mod linguist_data;
67pub mod lint_context;
68pub mod markdownlint_config;
69mod mdx_parser;
70pub mod merge_conflict;
71pub mod profiling;
72pub mod rule;
73pub mod unused_assets;
74#[cfg(feature = "colored")]
75pub mod vscode;
76pub mod workspace_index;
77#[macro_use]
78pub mod rule_config;
79#[macro_use]
80pub mod rule_config_serde;
81pub mod rules;
82#[doc(hidden)]
83pub mod source_paths;
84pub mod types;
85pub mod utils;
86
87// Native-only modules (require tokio, tower-lsp, etc.)
88#[cfg(feature = "native")]
89pub mod lsp;
90#[cfg(feature = "colored")]
91pub mod output;
92
93// WASM module
94#[cfg(feature = "wasm")]
95pub mod wasm;
96
97pub use rules::heading_utils::HeadingStyle;
98pub use rules::*;
99
100pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
101use crate::rule::{LintResult, Rule, RuleCategory};
102use crate::utils::calculate_indentation_width_default;
103#[cfg(not(target_arch = "wasm32"))]
104use std::time::Instant;
105
106/// Content characteristics for efficient rule filtering
107#[derive(Debug, Default)]
108struct ContentCharacteristics {
109    has_headings: bool,    // # or setext headings
110    has_lists: bool,       // *, -, +, 1. etc
111    has_links: bool,       // [text](url) or [text][ref]
112    has_code: bool,        // ``` or ~~~ or indented code
113    has_emphasis: bool,    // * or _ for emphasis
114    has_html: bool,        // < > tags
115    has_tables: bool,      // | pipes
116    has_blockquotes: bool, // > markers
117    has_images: bool,      // ![alt](url)
118}
119
120/// Check if a line has enough leading whitespace to be an indented code block.
121/// Indented code blocks require 4+ columns of leading whitespace (with proper tab expansion).
122fn has_potential_indented_code_indent(line: &str) -> bool {
123    calculate_indentation_width_default(line) >= 4
124}
125
126impl ContentCharacteristics {
127    fn analyze(content: &str) -> Self {
128        let mut chars = Self { ..Default::default() };
129
130        // Quick single-pass analysis
131        let mut has_atx_heading = false;
132        let mut has_setext_heading = false;
133
134        for line in content.lines() {
135            let trimmed = line.trim();
136
137            // Headings: ATX (#) or Setext (underlines). A blockquoted ATX
138            // heading (`> ## Title`) still emits a fragment anchor, so rules
139            // like MD051/MD080 must run for blockquote-only documents too.
140            // An ATX heading may also follow the marker of a list item the line
141            // opens (`- ## Title`, `1. # Title`), so list marker characters are
142            // stripped as well.
143            // Stripping `>`/space/tab and marker characters is a coarse,
144            // deliberately over-inclusive prefilter check (it must never skip a
145            // rule that has work; `parse_blockquote_prefix` also accepts a tab
146            // marker).
147            if !has_atx_heading
148                && (trimmed.starts_with('#')
149                    || trimmed
150                        .trim_start_matches([
151                            '>', ' ', '\t', '-', '+', '*', '.', ')', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
152                        ])
153                        .starts_with('#'))
154            {
155                has_atx_heading = true;
156            }
157            // A setext underline can be a single `=` or `-`, and one inside a
158            // blockquote follows the quote's markers.
159            let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
160            if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
161                has_setext_heading = true;
162            }
163
164            // Quick character-based detection (more efficient than regex)
165            // Include patterns without spaces to enable user-intention detection (MD030)
166            if !chars.has_lists
167                && (line.contains("* ")
168                    || line.contains("- ")
169                    || line.contains("+ ")
170                    || trimmed.starts_with("* ")
171                    || trimmed.starts_with("- ")
172                    || trimmed.starts_with("+ ")
173                    || trimmed.starts_with('*')
174                    || trimmed.starts_with('-')
175                    || trimmed.starts_with('+'))
176            {
177                chars.has_lists = true;
178            }
179            // Ordered lists: a line whose text starts with a digit (a marker may
180            // be indented), or a blockquote line holding one, and either marker
181            // delimiter (`.` or `)`) after it
182            if !chars.has_lists
183                && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
184                    || (trimmed.starts_with('>')
185                        && trimmed.chars().any(|c| c.is_ascii_digit())
186                        && trimmed.contains(['.', ')'])))
187            {
188                chars.has_lists = true;
189            }
190            if !chars.has_links
191                && (line.contains('[')
192                    || line.contains("http://")
193                    || line.contains("https://")
194                    || line.contains("ftp://")
195                    || line.contains("www."))
196            {
197                chars.has_links = true;
198            }
199            if !chars.has_images && line.contains("![") {
200                chars.has_images = true;
201            }
202            if !chars.has_code
203                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
204            {
205                chars.has_code = true;
206            }
207            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
208                chars.has_emphasis = true;
209            }
210            if !chars.has_html && line.contains('<') {
211                chars.has_html = true;
212            }
213            if !chars.has_tables && line.contains('|') {
214                chars.has_tables = true;
215            }
216            if !chars.has_blockquotes && line.starts_with('>') {
217                chars.has_blockquotes = true;
218            }
219        }
220
221        chars.has_headings = has_atx_heading || has_setext_heading;
222        chars
223    }
224
225    /// Check if a rule should be skipped based on content characteristics
226    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
227        match rule.category() {
228            RuleCategory::Heading => !self.has_headings,
229            RuleCategory::List => !self.has_lists,
230            RuleCategory::Link => !self.has_links && !self.has_images,
231            RuleCategory::Image => !self.has_images,
232            RuleCategory::CodeBlock => !self.has_code,
233            RuleCategory::Html => !self.has_html,
234            RuleCategory::Emphasis => !self.has_emphasis,
235            RuleCategory::Blockquote => !self.has_blockquotes,
236            RuleCategory::Table => !self.has_tables,
237            // Always check these categories as they apply to all content
238            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
239        }
240    }
241}
242
243/// Compute content hash for incremental indexing change detection
244///
245/// Uses blake3 for native builds (fast, cryptographic-strength hash)
246/// Falls back to std::hash for WASM builds
247#[cfg(feature = "native")]
248fn compute_content_hash(content: &str) -> String {
249    #[cfg(feature = "profiling")]
250    let start = std::time::Instant::now();
251    let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
252    #[cfg(feature = "profiling")]
253    profiling::record_duration("index: hash content", start.elapsed());
254    hash
255}
256
257/// Compute content hash for WASM builds using std::hash
258#[cfg(not(feature = "native"))]
259fn compute_content_hash(content: &str) -> String {
260    use std::hash::{DefaultHasher, Hash, Hasher};
261    let mut hasher = DefaultHasher::new();
262    content.hash(&mut hasher);
263    format!("{:016x}", hasher.finish())
264}
265
266/// Lint a file against the given rules with intelligent rule filtering
267/// Assumes the provided `rules` vector contains the final,
268/// configured, and filtered set of rules to be executed.
269///
270/// A leading UTF-8 BOM is ignored for parsing and diagnostic columns. Returned
271/// fix byte ranges address `content` exactly as supplied, including that BOM.
272pub fn lint(
273    content: &str,
274    rules: &[Box<dyn Rule>],
275    verbose: bool,
276    flavor: crate::config::MarkdownFlavor,
277    source_file: Option<std::path::PathBuf>,
278    config: Option<&crate::config::Config>,
279) -> LintResult {
280    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
281    result
282}
283
284/// Build FileIndex only (no linting) for cross-file analysis on cache hits
285///
286/// This is a lightweight function that only builds the FileIndex without running
287/// any rules. Used when we have a cache hit but still need the FileIndex for
288/// cross-file validation.
289///
290/// This avoids the overhead of re-running all rules when only the index data is needed.
291pub fn build_file_index_only(
292    content: &str,
293    rules: &[Box<dyn Rule>],
294    flavor: crate::config::MarkdownFlavor,
295    source_file: Option<std::path::PathBuf>,
296) -> crate::workspace_index::FileIndex {
297    build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
298}
299
300/// Build an index using the document's conflict-marker configuration.
301/// This keeps cache hits and workspace scans consistent with ordinary linting.
302///
303/// `rules` contributes the cross-file data and may be a role-scoped subset, so
304/// configuration decides whether a conflicted document indexes. A caller holding
305/// the invocation's resolved rule selection wants
306/// `build_file_index_only_for_selection` instead, so the index agrees with what
307/// that run reports.
308pub fn build_file_index_only_with_config(
309    content: &str,
310    rules: &[Box<dyn Rule>],
311    flavor: crate::config::MarkdownFlavor,
312    source_file: Option<std::path::PathBuf>,
313    config: &crate::config::Config,
314) -> crate::workspace_index::FileIndex {
315    let conflicted = crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some();
316    build_index(content, rules, flavor, source_file, conflicted)
317}
318
319/// Build an index for a run whose resolved rule selection is `selection`.
320/// The list that decides whether the run reports MD092 decides whether the
321/// document indexes, so a run that dropped the rule indexes a conflicted
322/// document like any other file rather than reporting links into it as broken.
323pub fn build_file_index_only_for_selection(
324    content: &str,
325    selection: &[Box<dyn Rule>],
326    flavor: crate::config::MarkdownFlavor,
327    source_file: Option<std::path::PathBuf>,
328    config: &crate::config::Config,
329) -> crate::workspace_index::FileIndex {
330    let conflicted =
331        crate::merge_conflict::detect_for_rules(content, selection, config, source_file.as_deref()).is_some();
332    build_index(content, selection, flavor, source_file, conflicted)
333}
334
335fn build_index(
336    content: &str,
337    rules: &[Box<dyn Rule>],
338    flavor: crate::config::MarkdownFlavor,
339    source_file: Option<std::path::PathBuf>,
340    conflicted: bool,
341) -> crate::workspace_index::FileIndex {
342    // Compute content hash for change detection
343    let content_hash = compute_content_hash(content);
344    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
345
346    // A conflicted document indexes as nothing, so a link into it reports its
347    // fragment as missing rather than resolving against half-merged headings.
348    if conflicted {
349        return file_index;
350    }
351
352    // The hash covers the supplied text; parsing reads the text after the mark.
353    let content = crate::utils::bom::strip_bom(content);
354
355    // Early return for empty content
356    if content.is_empty() {
357        return file_index;
358    }
359
360    // Parse LintContext once with the provided flavor
361    let lint_ctx = time_function!(
362        "index: parse lint context",
363        crate::lint_context::LintContext::new(content, flavor, source_file)
364    );
365
366    // Export inline disable data to the FileIndex so cross-file checks honor
367    // `<!-- rumdl-disable -->` blocks on the lint-cache fast path, exactly as
368    // lint_and_index does on the normal path.
369    let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
370    file_index.file_disabled_rules = file_disabled;
371    file_index.persistent_transitions = persistent_transitions;
372    file_index.line_disabled_rules = line_disabled;
373
374    // Only call contribute_to_index for cross-file rules (no rule checking!)
375    time_section!("index: contribute cross-file data", {
376        for rule in rules {
377            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
378                rule.contribute_to_index(&lint_ctx, &mut file_index);
379            }
380        }
381    });
382
383    file_index
384}
385
386/// Rewrite every fix replacement in the document's own line ending.
387///
388/// Rules build a fix on LF text, so a line ending they insert is `\n`, and the
389/// CLI really does hand them LF: it normalises a file on read and restores the
390/// endings on write. The LSP and wasm lint the editor's or host's text as it is,
391/// and a quick fix that inserted a bare `\n` into a CRLF document left it with
392/// mixed endings. Conforming here, where every rule's warnings meet, settles it
393/// for every caller and every rule at once. In a document with mixed endings a
394/// fix takes the ending of the line it follows, as `rumdl fmt` writes it.
395fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
396    if !content.contains('\r') {
397        return;
398    }
399    let mixed = match crate::utils::detect_line_ending_enum(content) {
400        crate::utils::LineEnding::Lf => return,
401        crate::utils::LineEnding::Crlf => false,
402        crate::utils::LineEnding::Mixed => true,
403    };
404    fn conform(content: &str, mixed: bool, fix: &mut crate::rule::Fix) {
405        if fix.replacement.contains('\n')
406            && (!mixed || crate::utils::line_ending_before(content, fix.range.start) == "\r\n")
407        {
408            fix.replacement =
409                crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
410        }
411        for extra in &mut fix.additional_edits {
412            conform(content, mixed, extra);
413        }
414    }
415    for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
416        conform(content, mixed, fix);
417    }
418}
419
420/// Drop the warnings a document silences, and apply any configured severity override
421/// to the rest.
422///
423/// A warning is dropped when it sits in a kramdown extension block or when an inline
424/// comment disables its rule somewhere in its range. `suppressed`, when given,
425/// collects what the inline comments removed, for the rules that report on them. A
426/// kramdown extension block is not an inline comment, so what it drops is left out.
427pub(crate) fn retain_reportable_warnings(
428    lint_ctx: &crate::lint_context::LintContext,
429    config: Option<&crate::config::Config>,
430    rule_name: &str,
431    rule_warnings: Vec<crate::rule::LintWarning>,
432    mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
433) -> Vec<crate::rule::LintWarning> {
434    let inline_config = lint_ctx.inline_config();
435    let mut kept = Vec::with_capacity(rule_warnings.len());
436
437    for mut warning in rule_warnings {
438        if lint_ctx
439            .line_info(warning.line)
440            .is_some_and(|info| info.in_kramdown_extension_block)
441        {
442            continue;
443        }
444
445        // Use the warning's rule_name if available, otherwise use the rule's name
446        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
447
448        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
449        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
450            &rule_name_to_check[..dash_pos]
451        } else {
452            rule_name_to_check
453        };
454
455        // Check if the rule is disabled at any line in the warning's range.
456        // Multi-line warnings (e.g., reflow) report on the first line,
457        // but inline disable comments may appear later in the range.
458        // Guard: if end_line < line (e.g., end_line=0), fall back to
459        // checking only the warning's line to match original behavior.
460        let end = if warning.end_line >= warning.line {
461            warning.end_line
462        } else {
463            warning.line
464        };
465        let disabled_at = (warning.line..=end).find_map(|line| {
466            inline_config
467                .disabling_layer(base_rule_name, line)
468                .map(|layer| (line, layer))
469        });
470        if let Some((line, layer)) = disabled_at {
471            if let Some(record) = suppressed.as_deref_mut() {
472                record.push(crate::rule::SuppressedWarning {
473                    rule_name: base_rule_name.to_string(),
474                    line,
475                    layer,
476                });
477            }
478            continue;
479        }
480
481        // Apply severity override from config if present
482        if let Some(cfg) = config
483            && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
484        {
485            warning.severity = override_severity;
486        }
487
488        kept.push(warning);
489    }
490
491    kept
492}
493
494/// Lint a file and contribute to workspace index for cross-file analysis
495///
496/// This variant performs linting and optionally populates a `FileIndex` with data
497/// needed for cross-file validation. The FileIndex is populated during linting,
498/// avoiding duplicate parsing.
499///
500/// Fix byte ranges in the warnings address `content`, including a leading BOM;
501/// diagnostic columns describe the Markdown after that encoding marker.
502///
503/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
504#[cfg_attr(test, allow(unused_variables))]
505#[allow(clippy::needless_pass_by_value)] // Public compatibility: callers already pass an owned path.
506pub fn lint_and_index(
507    content: &str,
508    rules: &[Box<dyn Rule>],
509    verbose: bool,
510    flavor: crate::config::MarkdownFlavor,
511    source_file: Option<std::path::PathBuf>,
512    config: Option<&crate::config::Config>,
513) -> (LintResult, crate::workspace_index::FileIndex) {
514    lint_and_index_with_paths(
515        content,
516        rules,
517        verbose,
518        flavor,
519        DocumentPaths::same(source_file.as_deref()),
520        config,
521    )
522}
523
524/// The two path roles involved in document processing.
525#[derive(Clone, Copy, Default)]
526pub struct DocumentPaths<'a> {
527    /// Logical path used for per-file configuration matching.
528    pub config_path: Option<&'a std::path::Path>,
529    /// Native path exposed to filesystem-aware rules.
530    pub source_file: Option<&'a std::path::Path>,
531    /// Run-scoped virtual paths visible to filesystem-aware link rules.
532    pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
533    /// The invalid UTF-8 sequences a lossily decoded document was read with.
534    pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
535    /// Rules selected for built-in Markdown fences in this run. Kept separate
536    /// because code-block-only mode has no outer document rules.
537    pub embedded_rules: Option<&'a [Box<dyn crate::rule::Rule>]>,
538    /// Current nesting depth; adapters start at zero.
539    pub embedded_depth: usize,
540}
541
542impl std::fmt::Debug for DocumentPaths<'_> {
543    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
544        f.debug_struct("DocumentPaths")
545            .field("config_path", &self.config_path)
546            .field("source_file", &self.source_file)
547            .field("link_target_policy", &self.link_target_policy)
548            .field("invalid_utf8", &self.invalid_utf8)
549            .field("embedded_rules", &self.embedded_rules.map(<[_]>::len))
550            .field("embedded_depth", &self.embedded_depth)
551            .finish()
552    }
553}
554
555impl<'a> DocumentPaths<'a> {
556    /// Use one native path for both roles.
557    pub fn same(path: Option<&'a std::path::Path>) -> Self {
558        Self {
559            config_path: path,
560            source_file: path,
561            ..Default::default()
562        }
563    }
564}
565
566/// Lint a document while keeping configuration matching separate from filesystem context.
567///
568/// `paths.config_path` selects per-file ignores and other path-scoped configuration.
569/// `paths.source_file` is exposed to rules that need a real filesystem location. Native
570/// adapters normally pass the same path for both; virtual adapters can supply only
571/// `config_path` without accidentally enabling filesystem-dependent rule behavior.
572#[cfg_attr(test, allow(unused_variables))]
573pub fn lint_and_index_with_paths(
574    content: &str,
575    rules: &[Box<dyn Rule>],
576    verbose: bool,
577    flavor: crate::config::MarkdownFlavor,
578    paths: DocumentPaths<'_>,
579    config: Option<&crate::config::Config>,
580) -> (LintResult, crate::workspace_index::FileIndex) {
581    let result = analyze_document(content, rules, verbose, flavor, paths, config, None);
582    (result.warnings, result.file_index)
583}
584
585#[allow(clippy::too_many_arguments)]
586pub(crate) fn analyze_document(
587    content: &str,
588    rules: &[Box<dyn Rule>],
589    verbose: bool,
590    flavor: crate::config::MarkdownFlavor,
591    paths: DocumentPaths<'_>,
592    config: Option<&crate::config::Config>,
593    prepare_fixes: Option<usize>,
594) -> document_run::DocumentFormatResult {
595    analyze_scanned_document(
596        &crate::merge_conflict::ConflictScan::new(content),
597        rules,
598        verbose,
599        flavor,
600        paths,
601        config,
602        prepare_fixes,
603    )
604}
605
606pub(crate) fn analyze_scanned_document(
607    scan: &crate::merge_conflict::ConflictScan<'_>,
608    rules: &[Box<dyn Rule>],
609    verbose: bool,
610    flavor: crate::config::MarkdownFlavor,
611    paths: DocumentPaths<'_>,
612    config: Option<&crate::config::Config>,
613    prepare_fixes: Option<usize>,
614) -> document_run::DocumentFormatResult {
615    use document_run::DocumentFormatResult;
616    let content = scan.content();
617    // Compute content hash for change detection
618    let content_hash = compute_content_hash(content);
619    let file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
620
621    let conflict = config.map_or_else(
622        || scan.detect_for_rules(rules, &crate::config::Config::default(), paths.config_path),
623        |config| scan.detect_for_rules(rules, config, paths.config_path),
624    );
625    if let Some(conflict) = conflict {
626        return DocumentFormatResult::without_fixes(Ok(vec![conflict]), file_index);
627    }
628
629    // The supplied text keeps its mark; everything below reads the analysis text.
630    let carrier = content;
631    let content = crate::utils::bom::strip_bom(carrier);
632
633    // Early return for empty content
634    if content.is_empty() {
635        return DocumentFormatResult::without_fixes(Ok(Vec::new()), file_index);
636    }
637
638    // Parse LintContext once (includes inline config parsing)
639    let lint_ctx = time_function!(
640        "lint: parse lint context",
641        crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
642            .with_merge_conflicts(scan.markers())
643    );
644    let lint_ctx = match paths.link_target_policy {
645        Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
646        None => lint_ctx,
647    };
648    let lint_ctx = match paths.invalid_utf8 {
649        Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
650        None => lint_ctx,
651    };
652    let (warnings, file_index, checked_rules) = check_document_context(
653        &lint_ctx,
654        rules,
655        verbose,
656        paths,
657        config,
658        file_index,
659        prepare_fixes.is_some(),
660        Default::default(),
661    );
662    let mut remaining_warnings = None;
663    let fixes = if warnings.as_ref().is_ok_and(|warnings| !warnings.is_empty())
664        && paths.invalid_utf8.is_none()
665        && let (Some(max_iterations), Some(config), Some(checks)) = (prepare_fixes, config, checked_rules)
666    {
667        let mut fixed = content.to_string();
668        let mut on_stable = |ctx: &crate::lint_context::LintContext<'_>,
669                             checks: &mut fix_coordinator::RawRuleChecks| {
670            if ctx.content != content {
671                let index = crate::workspace_index::FileIndex::with_hash(compute_content_hash(ctx.content));
672                remaining_warnings = Some(
673                    check_document_context(
674                        ctx,
675                        rules,
676                        false,
677                        paths,
678                        Some(config),
679                        index,
680                        false,
681                        std::mem::take(checks),
682                    )
683                    .0,
684                );
685            }
686        };
687        let result = fix_coordinator::FixCoordinator::new().apply_fixes_with_analysis(
688            rules,
689            &mut fixed,
690            config,
691            max_iterations,
692            paths,
693            Some((&lint_ctx, &checks)),
694            Some(&mut on_stable),
695        );
696        if crate::utils::bom::has_bom(carrier) {
697            fixed.insert(0, crate::utils::bom::BOM);
698        }
699        Some(Ok((fixed, result)))
700    } else {
701        None
702    };
703    // Raw rule checks stay in analysis coordinates throughout the fix loop.
704    // Only findings leaving this boundary address the caller's supplied bytes.
705    let shift = crate::utils::bom::bom_len(carrier);
706    let mut warnings = warnings;
707    if let Ok(warnings) = &mut warnings {
708        crate::utils::bom::restore_fix_offsets(warnings, shift);
709    }
710    if let Some(Ok(warnings)) = &mut remaining_warnings {
711        crate::utils::bom::restore_fix_offsets(warnings, shift);
712    }
713    DocumentFormatResult {
714        warnings,
715        file_index,
716        fixes,
717        remaining_warnings,
718    }
719}
720
721/// Report findings from the current source, consuming raw checks made by the
722/// fix loop on this exact context. All report filtering and index contributions
723/// go through the same path as a standalone lint.
724#[allow(clippy::too_many_arguments)]
725fn check_document_context(
726    lint_ctx: &crate::lint_context::LintContext<'_>,
727    rules: &[Box<dyn Rule>],
728    verbose: bool,
729    paths: DocumentPaths<'_>,
730    config: Option<&crate::config::Config>,
731    mut file_index: crate::workspace_index::FileIndex,
732    collect_fix_checks: bool,
733    mut cached_checks: fix_coordinator::RawRuleChecks,
734) -> (
735    LintResult,
736    crate::workspace_index::FileIndex,
737    Option<fix_coordinator::FixCheckResults>,
738) {
739    let content = lint_ctx.content;
740    let mut warnings = Vec::new();
741    // The rules `per-file-ignores` takes away for this file. It decides what this
742    // file REPORTS, and nothing else: the index contribution at the end of this
743    // function deliberately keeps running every cross-file rule, because a file's
744    // headings and links belong to the workspace rather than to its own report.
745    // Dropping a rule from the index instead would break the links pointing HERE,
746    // in files that never named it.
747    let ignored_for_file = match (config, paths.config_path) {
748        (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
749        _ => std::collections::HashSet::new(),
750    };
751    let inline_config = lint_ctx.inline_config();
752
753    // Export inline config data to FileIndex for cross-file rule filtering
754    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
755    file_index.file_disabled_rules = file_disabled;
756    file_index.persistent_transitions = persistent_transitions;
757    file_index.line_disabled_rules = line_disabled;
758
759    // Analyze content characteristics for rule filtering
760    let characteristics = time_function!(
761        "lint: analyze content characteristics",
762        ContentCharacteristics::analyze(content)
763    );
764
765    // Filter rules based on per-file-ignores and content characteristics
766    let applicable_rules: Vec<_> = rules
767        .iter()
768        .filter(|rule| !ignored_for_file.contains(rule.name()))
769        .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
770        .collect();
771
772    // Calculate skipped rules count before consuming applicable_rules
773    #[cfg(not(test))]
774    let total_rules = rules.len();
775    #[cfg(not(test))]
776    let applicable_count = applicable_rules.len();
777
778    #[cfg(not(target_arch = "wasm32"))]
779    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
780
781    // Automatic inline config support: merge inline overrides into config once,
782    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
783    let inline_overrides = inline_config.get_all_rule_configs();
784    let merged_config = if !inline_overrides.is_empty() {
785        config.map(|c| c.merge_with_inline_config(inline_config))
786    } else {
787        None
788    };
789    let effective_config = merged_config.as_ref().or(config);
790
791    // Cache recreated rules for rules with inline overrides
792    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
793        std::collections::HashMap::new();
794
795    // Pre-create rules that have inline config overrides
796    if let Some(cfg) = effective_config {
797        for rule_name in inline_overrides.keys() {
798            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
799                recreated_rules.insert(rule_name.clone(), recreated);
800            }
801        }
802    }
803
804    // A rule reporting on the run's inline disable comments needs to know what they
805    // removed, which costs a record per suppressed warning, so it is only kept when
806    // such a rule is going to read it.
807    let suppression_observers: Vec<_> = applicable_rules
808        .iter()
809        .filter(|rule| rule.observes_suppressions() && !rule.should_skip(lint_ctx))
810        .collect();
811    let mut suppressed = Vec::new();
812    // Raw checks precede severity, suppression and report-limit filtering.
813    // Reusing the report instead could hide a fixable finding from the engine.
814    let mut checked_rules = collect_fix_checks.then(std::collections::HashMap::new);
815
816    {
817        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
818        for rule in &applicable_rules {
819            #[cfg(not(target_arch = "wasm32"))]
820            let rule_start = (profile_rules || verbose).then(Instant::now);
821
822            // Use the same effective configuration for skip decisions and checks.
823            // Otherwise an inline stricter limit can be skipped using the base
824            // rule's looser limit, losing both findings and suppression evidence.
825            let effective_rule: &dyn crate::rule::Rule = recreated_rules
826                .get(rule.name())
827                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
828            if effective_rule.should_skip(lint_ctx) {
829                continue;
830            }
831
832            // Run single-file check with the effective rule (possibly with inline config applied)
833            let result = cached_checks
834                .remove(&fix_coordinator::rule_check_key(rule.as_ref()))
835                .map_or_else(|| effective_rule.check(lint_ctx), Ok);
836
837            match result {
838                Ok(rule_warnings) => {
839                    if let Some(checks) = &mut checked_rules {
840                        checks.insert(
841                            fix_coordinator::rule_check_key(rule.as_ref()),
842                            fix_coordinator::FixPlan::capture(effective_rule, lint_ctx, &rule_warnings),
843                        );
844                    }
845                    let record = if suppression_observers.is_empty() {
846                        None
847                    } else {
848                        Some(&mut suppressed)
849                    };
850                    let filtered_warnings =
851                        retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, record);
852                    warnings.extend(filtered_warnings);
853                }
854                Err(e) => {
855                    log::error!("Error checking rule {}: {}", rule.name(), e);
856                    return (Err(e), file_index, checked_rules);
857                }
858            }
859
860            #[cfg(not(target_arch = "wasm32"))]
861            {
862                if let Some(rule_start) = rule_start {
863                    let rule_duration = rule_start.elapsed();
864                    if profile_rules {
865                        eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
866                    }
867
868                    #[cfg(not(test))]
869                    if verbose && rule_duration.as_millis() > 500 {
870                        log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
871                    }
872                }
873            }
874        }
875    }
876
877    // Embedded findings must reach the parent's suppression filter before its
878    // observers run. They carry no document fix ranges; formatting is handled
879    // by the verified embedded write-back path.
880    if let (Some(embedded_rules), Some(config)) = (paths.embedded_rules, config)
881        && !embedded_rules.is_empty()
882    {
883        let embedded_rules: Vec<_> = embedded_rules
884            .iter()
885            .filter(|rule| !ignored_for_file.contains(rule.name()))
886            .map(|rule| dyn_clone::clone_box(&**rule))
887            .collect();
888        let embedded = crate::embedded_lint::check_embedded_markdown_blocks_raw(
889            content,
890            &embedded_rules,
891            config,
892            paths.embedded_depth,
893        );
894        let record = (!suppression_observers.is_empty()).then_some(&mut suppressed);
895        warnings.extend(retain_reportable_warnings(
896            lint_ctx,
897            Some(config),
898            "embedded-markdown",
899            embedded,
900            record,
901        ));
902    }
903
904    // Report on the inline disable comments, now that every single-file rule has run
905    // and the suppressions are complete.
906    if !suppression_observers.is_empty() {
907        let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
908
909        // A workspace-scope rule has its warnings filtered after this point, and for a
910        // single-file run not at all, so its findings never reach the report and
911        // nothing can be concluded about a comment naming it. A rule this file
912        // ignores does not report either, for the same reason.
913        let report = crate::rule::SuppressionReport {
914            suppressed,
915            judged_rules: rules
916                .iter()
917                .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
918                .filter(|rule| !ignored_for_file.contains(rule.name()))
919                .map(|rule| rule.name().to_string())
920                .collect(),
921        };
922
923        for rule in &suppression_observers {
924            match rule.check_suppressions(lint_ctx, &report) {
925                Ok(rule_warnings) => {
926                    let filtered_warnings =
927                        retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, None);
928                    warnings.extend(filtered_warnings);
929                }
930                Err(e) => {
931                    log::error!("Error checking rule {}: {}", rule.name(), e);
932                    return (Err(e), file_index, checked_rules);
933                }
934            }
935        }
936    }
937
938    // Contribute to index for cross-file rules (done after all rules checked)
939    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
940    // rules need to extract data from every file in the workspace, regardless of whether
941    // that file has content that would trigger the rule, and regardless of what this
942    // file's own configuration reports. For example, MD051 needs to index headings from
943    // files that have no links (like target.md) so that links FROM other files TO those
944    // headings can be validated - including from a file that ignores MD051 itself.
945    time_section!("lint: contribute cross-file data", {
946        for rule in rules {
947            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
948                rule.contribute_to_index(lint_ctx, &mut file_index);
949            }
950        }
951    });
952
953    #[cfg(not(test))]
954    if verbose {
955        let skipped_rules = total_rules - applicable_count;
956        if skipped_rules > 0 {
957            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
958        }
959    }
960
961    if paths.invalid_utf8.is_some() {
962        crate::encoding::settle_lossy_warnings(&mut warnings);
963    }
964
965    conform_fix_line_endings(content, &mut warnings);
966
967    (Ok(warnings), file_index, checked_rules)
968}
969
970/// Run cross-file checks for rules that need workspace-wide validation
971///
972/// This should be called after all files have been linted and the WorkspaceIndex
973/// has been built from the accumulated FileIndex data.
974///
975/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
976/// The FileIndex was already populated during contribute_to_index in the linting phase.
977///
978/// Rules can use workspace_index methods for cross-file validation:
979/// - `get_file(path)` - to look up headings in target files (for MD051)
980///
981/// Returns additional warnings from cross-file validation.
982pub fn run_cross_file_checks(
983    file_path: &std::path::Path,
984    file_index: &crate::workspace_index::FileIndex,
985    rules: &[Box<dyn Rule>],
986    workspace_index: &crate::workspace_index::WorkspaceIndex,
987    config: Option<&crate::config::Config>,
988) -> LintResult {
989    use crate::rule::CrossFileScope;
990
991    let mut warnings = Vec::new();
992
993    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
994    // attributed to `file_path` (the file holding the link), so a rule ignored
995    // for that file must not emit them. This applies on every path; single-file
996    // rule filtering does not cover cross-file checks because they run over the
997    // config group's full rule set, and cross-file rules share link data.
998    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
999
1000    // Only check rules that need cross-file analysis
1001    for rule in rules {
1002        if rule.cross_file_scope() != CrossFileScope::Workspace {
1003            continue;
1004        }
1005
1006        if ignored_rules_for_file
1007            .as_ref()
1008            .is_some_and(|ignored| ignored.contains(rule.name()))
1009        {
1010            continue;
1011        }
1012
1013        match time_function!(
1014            "workspace: cross-file rule check",
1015            rule.cross_file_check(file_path, file_index, workspace_index)
1016        ) {
1017            Ok(rule_warnings) => {
1018                // Filter cross-file warnings based on inline config stored in file_index
1019                let filtered: Vec<_> = rule_warnings
1020                    .into_iter()
1021                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
1022                    .map(|mut warning| {
1023                        // Apply severity override from config if present
1024                        if let Some(cfg) = config
1025                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
1026                        {
1027                            warning.severity = override_severity;
1028                        }
1029                        warning
1030                    })
1031                    .collect();
1032                warnings.extend(filtered);
1033            }
1034            Err(e) => {
1035                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
1036                return Err(e);
1037            }
1038        }
1039    }
1040
1041    Ok(warnings)
1042}
1043
1044/// Get the profiling report
1045pub fn get_profiling_report() -> String {
1046    profiling::get_report()
1047}
1048
1049/// Reset the profiling data
1050pub fn reset_profiling() {
1051    profiling::reset()
1052}
1053
1054/// Get regex cache statistics for performance monitoring
1055pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
1056    crate::utils::regex_cache::get_cache_stats()
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061    use super::*;
1062    use crate::rule::Rule;
1063    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
1064
1065    #[test]
1066    fn test_content_characteristics_analyze() {
1067        // Test empty content
1068        let chars = ContentCharacteristics::analyze("");
1069        assert!(!chars.has_headings);
1070        assert!(!chars.has_lists);
1071        assert!(!chars.has_links);
1072        assert!(!chars.has_code);
1073        assert!(!chars.has_emphasis);
1074        assert!(!chars.has_html);
1075        assert!(!chars.has_tables);
1076        assert!(!chars.has_blockquotes);
1077        assert!(!chars.has_images);
1078
1079        // Test content with headings
1080        let chars = ContentCharacteristics::analyze("# Heading");
1081        assert!(chars.has_headings);
1082
1083        // Test setext headings
1084        let chars = ContentCharacteristics::analyze("Heading\n=======");
1085        assert!(chars.has_headings);
1086
1087        // Blockquoted ATX headings emit fragment anchors, so Heading-category
1088        // rules (MD051/MD080) must run for blockquote-only documents.
1089        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
1090        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
1091        let chars = ContentCharacteristics::analyze(">> # Nested");
1092        assert!(
1093            chars.has_headings,
1094            "nested-blockquote ATX heading must set has_headings"
1095        );
1096        // A tab after the blockquote marker is also a valid heading
1097        // (`parse_blockquote_prefix` accepts it).
1098        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
1099        assert!(
1100            chars.has_headings,
1101            "tab-separated blockquote ATX heading must set has_headings"
1102        );
1103
1104        // Test lists
1105        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
1106        assert!(chars.has_lists);
1107
1108        // Test ordered lists
1109        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
1110        assert!(chars.has_lists);
1111
1112        // Test links
1113        let chars = ContentCharacteristics::analyze("[link](url)");
1114        assert!(chars.has_links);
1115
1116        // Test URLs
1117        let chars = ContentCharacteristics::analyze("Visit https://example.com");
1118        assert!(chars.has_links);
1119
1120        // Test images
1121        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
1122        assert!(chars.has_images);
1123
1124        // Test code
1125        let chars = ContentCharacteristics::analyze("`inline code`");
1126        assert!(chars.has_code);
1127
1128        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
1129        assert!(chars.has_code);
1130
1131        // Test indented code blocks (4 spaces)
1132        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
1133        assert!(chars.has_code);
1134
1135        // Test tab-indented code blocks
1136        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
1137        assert!(chars.has_code);
1138
1139        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
1140        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
1141        assert!(chars.has_code);
1142
1143        // Test 1 space + tab (also 4 columns due to tab expansion)
1144        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
1145        assert!(chars.has_code);
1146
1147        // Test emphasis
1148        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
1149        assert!(chars.has_emphasis);
1150
1151        // Test HTML
1152        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
1153        assert!(chars.has_html);
1154
1155        // Test tables
1156        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
1157        assert!(chars.has_tables);
1158
1159        // Test blockquotes
1160        let chars = ContentCharacteristics::analyze("> Quote");
1161        assert!(chars.has_blockquotes);
1162
1163        // Test mixed content
1164        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)";
1165        let chars = ContentCharacteristics::analyze(content);
1166        assert!(chars.has_headings);
1167        assert!(chars.has_lists);
1168        assert!(chars.has_links);
1169        assert!(chars.has_code);
1170        assert!(chars.has_emphasis);
1171        assert!(chars.has_html);
1172        assert!(chars.has_tables);
1173        assert!(chars.has_blockquotes);
1174        assert!(chars.has_images);
1175    }
1176
1177    #[test]
1178    fn test_content_characteristics_parenthesized_ordered_list() {
1179        assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
1180        assert!(ContentCharacteristics::analyze("  1) indented first\n  2) second").has_lists);
1181        assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
1182    }
1183
1184    #[test]
1185    fn test_content_characteristics_should_skip_rule() {
1186        let chars = ContentCharacteristics {
1187            has_headings: true,
1188            has_lists: false,
1189            has_links: true,
1190            has_code: false,
1191            has_emphasis: true,
1192            has_html: false,
1193            has_tables: true,
1194            has_blockquotes: false,
1195            has_images: false,
1196        };
1197
1198        // Create test rules for different categories
1199        let heading_rule = MD001HeadingIncrement::default();
1200        assert!(!chars.should_skip_rule(&heading_rule));
1201
1202        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
1203        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
1204
1205        // Test skipping based on content
1206        let chars_no_headings = ContentCharacteristics {
1207            has_headings: false,
1208            ..Default::default()
1209        };
1210        assert!(chars_no_headings.should_skip_rule(&heading_rule));
1211    }
1212
1213    #[test]
1214    fn test_lint_empty_content() {
1215        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1216
1217        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1218        assert!(result.is_ok());
1219        assert!(result.unwrap().is_empty());
1220    }
1221
1222    #[test]
1223    fn test_lint_with_violations() {
1224        let content = "## Level 2\n#### Level 4"; // Skips level 3
1225        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1226
1227        let result = lint(
1228            content,
1229            &rules,
1230            false,
1231            crate::config::MarkdownFlavor::Standard,
1232            None,
1233            None,
1234        );
1235        assert!(result.is_ok());
1236        let warnings = result.unwrap();
1237        assert!(!warnings.is_empty());
1238        // Check the rule field of LintWarning struct
1239        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1240    }
1241
1242    #[test]
1243    fn test_lint_with_inline_disable() {
1244        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1245        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1246
1247        let result = lint(
1248            content,
1249            &rules,
1250            false,
1251            crate::config::MarkdownFlavor::Standard,
1252            None,
1253            None,
1254        );
1255        assert!(result.is_ok());
1256        let warnings = result.unwrap();
1257        assert!(warnings.is_empty()); // Should be disabled by inline comment
1258    }
1259
1260    #[test]
1261    fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1262        // Each document holds two headings with the same anchor and nothing else
1263        // that looks like a heading, so the heading rules run only if the
1264        // prefilter recognizes the underline.
1265        let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1266        for content in [
1267            "Title\n-\n\ntitle\n-\n",
1268            "Title\n=\n\ntitle\n=\n",
1269            "> Title\n> ===\n\n> title\n> ===\n",
1270            "> Title\n> -\n\n> title\n> -\n",
1271        ] {
1272            let warnings = lint(
1273                content,
1274                &rules,
1275                false,
1276                crate::config::MarkdownFlavor::Standard,
1277                None,
1278                None,
1279            )
1280            .unwrap();
1281            let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1282            assert_eq!(lines, [4], "{content:?}");
1283        }
1284    }
1285
1286    #[test]
1287    fn test_lint_rule_filtering() {
1288        // Content with no lists
1289        let content = "# Heading\nJust text";
1290        let rules: Vec<Box<dyn Rule>> = vec![
1291            Box::new(MD001HeadingIncrement::default()),
1292            // A list-related rule would be skipped
1293        ];
1294
1295        let result = lint(
1296            content,
1297            &rules,
1298            false,
1299            crate::config::MarkdownFlavor::Standard,
1300            None,
1301            None,
1302        );
1303        assert!(result.is_ok());
1304    }
1305
1306    #[test]
1307    fn test_get_profiling_report() {
1308        // Just test that it returns a string without panicking
1309        let report = get_profiling_report();
1310        assert!(!report.is_empty());
1311        assert!(report.contains("Profiling"));
1312    }
1313
1314    #[test]
1315    fn test_reset_profiling() {
1316        // Test that reset_profiling doesn't panic
1317        reset_profiling();
1318
1319        // After reset, report should indicate no measurements or profiling disabled
1320        let report = get_profiling_report();
1321        assert!(report.contains("disabled") || report.contains("no measurements"));
1322    }
1323
1324    #[test]
1325    fn test_get_regex_cache_stats() {
1326        let stats = get_regex_cache_stats();
1327        // Stats should be a valid HashMap (might be empty)
1328        assert!(stats.is_empty() || !stats.is_empty());
1329
1330        // If not empty, all values should be positive
1331        for count in stats.values() {
1332            assert!(*count > 0);
1333        }
1334    }
1335
1336    #[test]
1337    fn test_content_characteristics_edge_cases() {
1338        // A setext underline is any run of `=` or `-`, a single character
1339        // included, and one in a blockquote follows the quote's markers.
1340        for content in [
1341            "Title\n-",
1342            "Title\n=",
1343            "Title\n--",
1344            "> Title\n> ===",
1345            ">\tTitle\n>\t-",
1346            ">> Title\n>>-",
1347        ] {
1348            assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1349        }
1350        // An ATX heading after a list marker counts as well.
1351        for content in ["- ## Title", "1. # Title", "- - # Title", "> - ## Title", "10) # Title"] {
1352            assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1353        }
1354        for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1355            assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1356        }
1357
1358        // Test list detection - we now include potential list patterns (with or without space)
1359        // to support user-intention detection in MD030
1360        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
1361        assert!(chars.has_lists); // Run list rules to be safe
1362
1363        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
1364        assert!(chars.has_lists); // Run list rules for user-intention detection
1365
1366        // Test blockquote must be at start of line
1367        let chars = ContentCharacteristics::analyze("text > not a quote");
1368        assert!(!chars.has_blockquotes);
1369    }
1370
1371    /// One document that draws a line-inserting fix from every rule known to
1372    /// write a bare `\n` into its replacement: MD071 (blank line after front
1373    /// matter), MD022 (blank lines around headings), MD032 (around lists),
1374    /// MD031 (around fences), MD014 (dollar prompts), MD058 (around tables) and
1375    /// MD047 (final newline).
1376    const LINE_INSERTING_FIXES: &str = "---\ntitle: x\n---\n# Heading\ntext\n## Sub\n- item\ntext\n```sh\n$ ls\n```\ntext\n| a | b |\n|---|---|\n| 1 | 2 |\ntext";
1377
1378    /// Every fix replacement (and additional edit) of every warning, keyed by rule.
1379    fn fix_replacements(content: &str) -> Vec<(String, String)> {
1380        let config = crate::config::Config::default();
1381        let rules = crate::rules::all_rules(&config);
1382        let warnings = lint(
1383            content,
1384            &rules,
1385            false,
1386            crate::config::MarkdownFlavor::Standard,
1387            None,
1388            Some(&config),
1389        )
1390        .unwrap();
1391        let mut out = Vec::new();
1392        for warning in warnings {
1393            let Some(fix) = warning.fix else { continue };
1394            let rule = warning.rule_name.clone().unwrap_or_default();
1395            let mut stack = vec![fix];
1396            while let Some(fix) = stack.pop() {
1397                out.push((rule.clone(), fix.replacement.clone()));
1398                stack.extend(fix.additional_edits);
1399            }
1400        }
1401        out
1402    }
1403
1404    fn has_bare_lf(text: &str) -> bool {
1405        let bytes = text.as_bytes();
1406        bytes
1407            .iter()
1408            .enumerate()
1409            .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1410    }
1411
1412    #[test]
1413    fn fix_replacements_use_the_documents_crlf_line_ending() {
1414        let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1415        let replacements = fix_replacements(&crlf);
1416
1417        let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1418        assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1419
1420        // Positive control: the rules this document was written for did fire and
1421        // did insert a line ending, so the assertion above examined real fixes.
1422        let mut crlf_rules: Vec<_> = replacements
1423            .iter()
1424            .filter(|(_, r)| r.contains("\r\n"))
1425            .map(|(rule, _)| rule.as_str())
1426            .collect();
1427        crlf_rules.sort_unstable();
1428        crlf_rules.dedup();
1429        for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1430            assert!(
1431                crlf_rules.contains(&rule),
1432                "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1433            );
1434        }
1435    }
1436
1437    #[test]
1438    fn fix_replacements_stay_lf_for_lf_documents() {
1439        // The same rules on the LF document write `\n`, untouched.
1440        let lf = fix_replacements(LINE_INSERTING_FIXES);
1441        assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1442        assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1443    }
1444
1445    #[test]
1446    fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1447        // Every other line ends in CRLF.
1448        let mixed: String = LINE_INSERTING_FIXES
1449            .split_inclusive('\n')
1450            .enumerate()
1451            .map(|(i, line)| {
1452                if i % 2 == 0 {
1453                    line.replace('\n', "\r\n")
1454                } else {
1455                    line.to_string()
1456                }
1457            })
1458            .collect();
1459        assert_eq!(
1460            crate::utils::detect_line_ending_enum(&mixed),
1461            crate::utils::LineEnding::Mixed
1462        );
1463
1464        // The ending of the line holding the byte before `offset`, by line.
1465        let ending_before = |offset: usize| {
1466            let target = offset.saturating_sub(1);
1467            let mut start = 0;
1468            let mut last_ending = "\n";
1469            for line in mixed.split_inclusive('\n') {
1470                let ending = if line.ends_with("\r\n") {
1471                    "\r\n"
1472                } else if line.ends_with('\n') {
1473                    "\n"
1474                } else {
1475                    last_ending
1476                };
1477                if target < start + line.len() {
1478                    return ending;
1479                }
1480                last_ending = ending;
1481                start += line.len();
1482            }
1483            last_ending
1484        };
1485
1486        let config = crate::config::Config::default();
1487        let rules = crate::rules::all_rules(&config);
1488        let warnings = lint(
1489            &mixed,
1490            &rules,
1491            false,
1492            crate::config::MarkdownFlavor::Standard,
1493            None,
1494            Some(&config),
1495        )
1496        .unwrap();
1497        let mut seen = [false, false];
1498        let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1499        while let Some(fix) = stack.pop() {
1500            if fix.replacement.contains('\n') {
1501                let crlf = ending_before(fix.range.start) == "\r\n";
1502                seen[usize::from(crlf)] = true;
1503                assert_eq!(
1504                    has_bare_lf(&fix.replacement),
1505                    !crlf,
1506                    "replacement {:?} at {} in {mixed:?}",
1507                    fix.replacement,
1508                    fix.range.start
1509                );
1510            }
1511            stack.extend(fix.additional_edits);
1512        }
1513        assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1514    }
1515}
1516
1517#[doc(hidden)]
1518pub mod format_proof;