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