1#![warn(unreachable_pub)]
2#![warn(clippy::pedantic)]
3#![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#![allow(clippy::no_effect_underscore_binding)]
44#![allow(clippy::default_trait_access)]
46#![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 exit_codes;
57pub mod filtered_lines;
58pub mod fix_coordinator;
59pub mod inline_config;
60pub mod linguist_data;
61pub mod lint_context;
62pub mod markdownlint_config;
63pub mod merge_conflict;
64pub mod profiling;
65pub mod rule;
66#[cfg(feature = "colored")]
67pub mod vscode;
68pub mod workspace_index;
69#[macro_use]
70pub mod rule_config;
71#[macro_use]
72pub mod rule_config_serde;
73pub mod rules;
74pub mod types;
75pub mod utils;
76
77#[cfg(feature = "native")]
79pub mod lsp;
80#[cfg(feature = "colored")]
81pub mod output;
82
83#[cfg(feature = "wasm")]
85pub mod wasm;
86
87pub use rules::heading_utils::HeadingStyle;
88pub use rules::*;
89
90pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
91use crate::rule::{LintResult, Rule, RuleCategory};
92use crate::utils::calculate_indentation_width_default;
93#[cfg(not(target_arch = "wasm32"))]
94use std::time::Instant;
95
96#[derive(Debug, Default)]
98struct ContentCharacteristics {
99 has_headings: bool, has_lists: bool, has_links: bool, has_code: bool, has_emphasis: bool, has_html: bool, has_tables: bool, has_blockquotes: bool, has_images: bool, }
109
110fn has_potential_indented_code_indent(line: &str) -> bool {
113 calculate_indentation_width_default(line) >= 4
114}
115
116impl ContentCharacteristics {
117 fn analyze(content: &str) -> Self {
118 let mut chars = Self { ..Default::default() };
119
120 let mut has_atx_heading = false;
122 let mut has_setext_heading = false;
123
124 for line in content.lines() {
125 let trimmed = line.trim();
126
127 if !has_atx_heading
134 && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
135 {
136 has_atx_heading = true;
137 }
138 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
139 has_setext_heading = true;
140 }
141
142 if !chars.has_lists
145 && (line.contains("* ")
146 || line.contains("- ")
147 || line.contains("+ ")
148 || trimmed.starts_with("* ")
149 || trimmed.starts_with("- ")
150 || trimmed.starts_with("+ ")
151 || trimmed.starts_with('*')
152 || trimmed.starts_with('-')
153 || trimmed.starts_with('+'))
154 {
155 chars.has_lists = true;
156 }
157 if !chars.has_lists
161 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
162 || (trimmed.starts_with('>')
163 && trimmed.chars().any(|c| c.is_ascii_digit())
164 && trimmed.contains(['.', ')'])))
165 {
166 chars.has_lists = true;
167 }
168 if !chars.has_links
169 && (line.contains('[')
170 || line.contains("http://")
171 || line.contains("https://")
172 || line.contains("ftp://")
173 || line.contains("www."))
174 {
175 chars.has_links = true;
176 }
177 if !chars.has_images && line.contains("![") {
178 chars.has_images = true;
179 }
180 if !chars.has_code
181 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
182 {
183 chars.has_code = true;
184 }
185 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
186 chars.has_emphasis = true;
187 }
188 if !chars.has_html && line.contains('<') {
189 chars.has_html = true;
190 }
191 if !chars.has_tables && line.contains('|') {
192 chars.has_tables = true;
193 }
194 if !chars.has_blockquotes && line.starts_with('>') {
195 chars.has_blockquotes = true;
196 }
197 }
198
199 chars.has_headings = has_atx_heading || has_setext_heading;
200 chars
201 }
202
203 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
205 match rule.category() {
206 RuleCategory::Heading => !self.has_headings,
207 RuleCategory::List => !self.has_lists,
208 RuleCategory::Link => !self.has_links && !self.has_images,
209 RuleCategory::Image => !self.has_images,
210 RuleCategory::CodeBlock => !self.has_code,
211 RuleCategory::Html => !self.has_html,
212 RuleCategory::Emphasis => !self.has_emphasis,
213 RuleCategory::Blockquote => !self.has_blockquotes,
214 RuleCategory::Table => !self.has_tables,
215 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
217 }
218 }
219}
220
221#[cfg(feature = "native")]
226fn compute_content_hash(content: &str) -> String {
227 #[cfg(feature = "profiling")]
228 let start = std::time::Instant::now();
229 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
230 #[cfg(feature = "profiling")]
231 profiling::record_duration("index: hash content", start.elapsed());
232 hash
233}
234
235#[cfg(not(feature = "native"))]
237fn compute_content_hash(content: &str) -> String {
238 use std::hash::{DefaultHasher, Hash, Hasher};
239 let mut hasher = DefaultHasher::new();
240 content.hash(&mut hasher);
241 format!("{:016x}", hasher.finish())
242}
243
244pub fn lint(
248 content: &str,
249 rules: &[Box<dyn Rule>],
250 verbose: bool,
251 flavor: crate::config::MarkdownFlavor,
252 source_file: Option<std::path::PathBuf>,
253 config: Option<&crate::config::Config>,
254) -> LintResult {
255 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
256 result
257}
258
259pub fn build_file_index_only(
267 content: &str,
268 rules: &[Box<dyn Rule>],
269 flavor: crate::config::MarkdownFlavor,
270 source_file: Option<std::path::PathBuf>,
271) -> crate::workspace_index::FileIndex {
272 let content_hash = compute_content_hash(content);
274 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
275
276 if crate::merge_conflict::detect(content).is_some() {
277 return file_index;
278 }
279
280 if content.is_empty() {
282 return file_index;
283 }
284
285 let lint_ctx = time_function!(
287 "index: parse lint context",
288 crate::lint_context::LintContext::new(content, flavor, source_file)
289 );
290
291 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
295 file_index.file_disabled_rules = file_disabled;
296 file_index.persistent_transitions = persistent_transitions;
297 file_index.line_disabled_rules = line_disabled;
298
299 time_section!("index: contribute cross-file data", {
301 for rule in rules {
302 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
303 rule.contribute_to_index(&lint_ctx, &mut file_index);
304 }
305 }
306 });
307
308 file_index
309}
310
311fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
321 if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
322 return;
323 }
324 fn conform(fix: &mut crate::rule::Fix) {
325 if fix.replacement.contains('\n') {
326 fix.replacement =
327 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
328 }
329 for extra in &mut fix.additional_edits {
330 conform(extra);
331 }
332 }
333 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
334 conform(fix);
335 }
336}
337
338fn retain_reportable_warnings(
346 lint_ctx: &crate::lint_context::LintContext,
347 config: Option<&crate::config::Config>,
348 rule_name: &str,
349 rule_warnings: Vec<crate::rule::LintWarning>,
350 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
351) -> Vec<crate::rule::LintWarning> {
352 let inline_config = lint_ctx.inline_config();
353 let mut kept = Vec::with_capacity(rule_warnings.len());
354
355 for mut warning in rule_warnings {
356 if lint_ctx
357 .line_info(warning.line)
358 .is_some_and(|info| info.in_kramdown_extension_block)
359 {
360 continue;
361 }
362
363 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
365
366 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
368 &rule_name_to_check[..dash_pos]
369 } else {
370 rule_name_to_check
371 };
372
373 let end = if warning.end_line >= warning.line {
379 warning.end_line
380 } else {
381 warning.line
382 };
383 let disabled_at = (warning.line..=end).find_map(|line| {
384 inline_config
385 .disabling_layer(base_rule_name, line)
386 .map(|layer| (line, layer))
387 });
388 if let Some((line, layer)) = disabled_at {
389 if let Some(record) = suppressed.as_deref_mut() {
390 record.push(crate::rule::SuppressedWarning {
391 rule_name: base_rule_name.to_string(),
392 line,
393 layer,
394 });
395 }
396 continue;
397 }
398
399 if let Some(cfg) = config
401 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
402 {
403 warning.severity = override_severity;
404 }
405
406 kept.push(warning);
407 }
408
409 kept
410}
411
412#[cfg_attr(test, allow(unused_variables))]
420#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
422 content: &str,
423 rules: &[Box<dyn Rule>],
424 verbose: bool,
425 flavor: crate::config::MarkdownFlavor,
426 source_file: Option<std::path::PathBuf>,
427 config: Option<&crate::config::Config>,
428) -> (LintResult, crate::workspace_index::FileIndex) {
429 lint_and_index_with_paths(
430 content,
431 rules,
432 verbose,
433 flavor,
434 DocumentPaths::same(source_file.as_deref()),
435 config,
436 )
437}
438
439#[derive(Debug, Clone, Copy, Default)]
441pub struct DocumentPaths<'a> {
442 pub config_path: Option<&'a std::path::Path>,
444 pub source_file: Option<&'a std::path::Path>,
446 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
448}
449
450impl<'a> DocumentPaths<'a> {
451 pub fn same(path: Option<&'a std::path::Path>) -> Self {
453 Self {
454 config_path: path,
455 source_file: path,
456 link_target_policy: None,
457 }
458 }
459}
460
461#[cfg_attr(test, allow(unused_variables))]
468pub fn lint_and_index_with_paths(
469 content: &str,
470 rules: &[Box<dyn Rule>],
471 verbose: bool,
472 flavor: crate::config::MarkdownFlavor,
473 paths: DocumentPaths<'_>,
474 config: Option<&crate::config::Config>,
475) -> (LintResult, crate::workspace_index::FileIndex) {
476 let mut warnings = Vec::new();
477 let content_hash = compute_content_hash(content);
479 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
480
481 if let Some(conflict) = crate::merge_conflict::detect(content) {
482 return (Ok(vec![conflict]), file_index);
483 }
484
485 if content.is_empty() {
487 return (Ok(warnings), file_index);
488 }
489
490 let ignored_for_file = match (config, paths.config_path) {
497 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
498 _ => std::collections::HashSet::new(),
499 };
500
501 let lint_ctx = time_function!(
503 "lint: parse lint context",
504 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
505 );
506 let lint_ctx = match paths.link_target_policy {
507 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
508 None => lint_ctx,
509 };
510 let inline_config = lint_ctx.inline_config();
511
512 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
514 file_index.file_disabled_rules = file_disabled;
515 file_index.persistent_transitions = persistent_transitions;
516 file_index.line_disabled_rules = line_disabled;
517
518 let characteristics = time_function!(
520 "lint: analyze content characteristics",
521 ContentCharacteristics::analyze(content)
522 );
523
524 let applicable_rules: Vec<_> = rules
526 .iter()
527 .filter(|rule| !ignored_for_file.contains(rule.name()))
528 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
529 .collect();
530
531 #[cfg(not(test))]
533 let total_rules = rules.len();
534 #[cfg(not(test))]
535 let applicable_count = applicable_rules.len();
536
537 #[cfg(not(target_arch = "wasm32"))]
538 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
539
540 let inline_overrides = inline_config.get_all_rule_configs();
543 let merged_config = if !inline_overrides.is_empty() {
544 config.map(|c| c.merge_with_inline_config(inline_config))
545 } else {
546 None
547 };
548 let effective_config = merged_config.as_ref().or(config);
549
550 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
552 std::collections::HashMap::new();
553
554 if let Some(cfg) = effective_config {
556 for rule_name in inline_overrides.keys() {
557 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
558 recreated_rules.insert(rule_name.clone(), recreated);
559 }
560 }
561 }
562
563 let suppression_observers: Vec<_> = applicable_rules
567 .iter()
568 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
569 .collect();
570 let mut suppressed = Vec::new();
571
572 {
573 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
574 for rule in &applicable_rules {
575 #[cfg(not(target_arch = "wasm32"))]
576 let rule_start = Instant::now();
577
578 if rule.should_skip(&lint_ctx) {
580 continue;
581 }
582
583 let effective_rule: &dyn crate::rule::Rule = recreated_rules
585 .get(rule.name())
586 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
587
588 let result = effective_rule.check(&lint_ctx);
590
591 match result {
592 Ok(rule_warnings) => {
593 let record = if suppression_observers.is_empty() {
594 None
595 } else {
596 Some(&mut suppressed)
597 };
598 let filtered_warnings =
599 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
600 warnings.extend(filtered_warnings);
601 }
602 Err(e) => {
603 log::error!("Error checking rule {}: {}", rule.name(), e);
604 return (Err(e), file_index);
605 }
606 }
607
608 #[cfg(not(target_arch = "wasm32"))]
609 {
610 let rule_duration = rule_start.elapsed();
611 if profile_rules {
612 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
613 }
614
615 #[cfg(not(test))]
616 if verbose && rule_duration.as_millis() > 500 {
617 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
618 }
619 }
620 }
621 }
622
623 if !suppression_observers.is_empty() {
626 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
627
628 let report = crate::rule::SuppressionReport {
633 suppressed,
634 judged_rules: rules
635 .iter()
636 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
637 .filter(|rule| !ignored_for_file.contains(rule.name()))
638 .map(|rule| rule.name().to_string())
639 .collect(),
640 };
641
642 for rule in &suppression_observers {
643 match rule.check_suppressions(&lint_ctx, &report) {
644 Ok(rule_warnings) => {
645 let filtered_warnings =
646 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
647 warnings.extend(filtered_warnings);
648 }
649 Err(e) => {
650 log::error!("Error checking rule {}: {}", rule.name(), e);
651 return (Err(e), file_index);
652 }
653 }
654 }
655 }
656
657 time_section!("lint: contribute cross-file data", {
665 for rule in rules {
666 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
667 rule.contribute_to_index(&lint_ctx, &mut file_index);
668 }
669 }
670 });
671
672 #[cfg(not(test))]
673 if verbose {
674 let skipped_rules = total_rules - applicable_count;
675 if skipped_rules > 0 {
676 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
677 }
678 }
679
680 conform_fix_line_endings(content, &mut warnings);
681
682 (Ok(warnings), file_index)
683}
684
685pub fn run_cross_file_checks(
698 file_path: &std::path::Path,
699 file_index: &crate::workspace_index::FileIndex,
700 rules: &[Box<dyn Rule>],
701 workspace_index: &crate::workspace_index::WorkspaceIndex,
702 config: Option<&crate::config::Config>,
703) -> LintResult {
704 use crate::rule::CrossFileScope;
705
706 let mut warnings = Vec::new();
707
708 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
714
715 for rule in rules {
717 if rule.cross_file_scope() != CrossFileScope::Workspace {
718 continue;
719 }
720
721 if ignored_rules_for_file
722 .as_ref()
723 .is_some_and(|ignored| ignored.contains(rule.name()))
724 {
725 continue;
726 }
727
728 match time_function!(
729 "workspace: cross-file rule check",
730 rule.cross_file_check(file_path, file_index, workspace_index)
731 ) {
732 Ok(rule_warnings) => {
733 let filtered: Vec<_> = rule_warnings
735 .into_iter()
736 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
737 .map(|mut warning| {
738 if let Some(cfg) = config
740 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
741 {
742 warning.severity = override_severity;
743 }
744 warning
745 })
746 .collect();
747 warnings.extend(filtered);
748 }
749 Err(e) => {
750 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
751 return Err(e);
752 }
753 }
754 }
755
756 Ok(warnings)
757}
758
759pub fn get_profiling_report() -> String {
761 profiling::get_report()
762}
763
764pub fn reset_profiling() {
766 profiling::reset()
767}
768
769pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
771 crate::utils::regex_cache::get_cache_stats()
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777 use crate::rule::Rule;
778 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
779
780 #[test]
781 fn test_content_characteristics_analyze() {
782 let chars = ContentCharacteristics::analyze("");
784 assert!(!chars.has_headings);
785 assert!(!chars.has_lists);
786 assert!(!chars.has_links);
787 assert!(!chars.has_code);
788 assert!(!chars.has_emphasis);
789 assert!(!chars.has_html);
790 assert!(!chars.has_tables);
791 assert!(!chars.has_blockquotes);
792 assert!(!chars.has_images);
793
794 let chars = ContentCharacteristics::analyze("# Heading");
796 assert!(chars.has_headings);
797
798 let chars = ContentCharacteristics::analyze("Heading\n=======");
800 assert!(chars.has_headings);
801
802 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
805 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
806 let chars = ContentCharacteristics::analyze(">> # Nested");
807 assert!(
808 chars.has_headings,
809 "nested-blockquote ATX heading must set has_headings"
810 );
811 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
814 assert!(
815 chars.has_headings,
816 "tab-separated blockquote ATX heading must set has_headings"
817 );
818
819 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
821 assert!(chars.has_lists);
822
823 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
825 assert!(chars.has_lists);
826
827 let chars = ContentCharacteristics::analyze("[link](url)");
829 assert!(chars.has_links);
830
831 let chars = ContentCharacteristics::analyze("Visit https://example.com");
833 assert!(chars.has_links);
834
835 let chars = ContentCharacteristics::analyze("");
837 assert!(chars.has_images);
838
839 let chars = ContentCharacteristics::analyze("`inline code`");
841 assert!(chars.has_code);
842
843 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
844 assert!(chars.has_code);
845
846 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
848 assert!(chars.has_code);
849
850 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
852 assert!(chars.has_code);
853
854 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
856 assert!(chars.has_code);
857
858 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
860 assert!(chars.has_code);
861
862 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
864 assert!(chars.has_emphasis);
865
866 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
868 assert!(chars.has_html);
869
870 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
872 assert!(chars.has_tables);
873
874 let chars = ContentCharacteristics::analyze("> Quote");
876 assert!(chars.has_blockquotes);
877
878 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
880 let chars = ContentCharacteristics::analyze(content);
881 assert!(chars.has_headings);
882 assert!(chars.has_lists);
883 assert!(chars.has_links);
884 assert!(chars.has_code);
885 assert!(chars.has_emphasis);
886 assert!(chars.has_html);
887 assert!(chars.has_tables);
888 assert!(chars.has_blockquotes);
889 assert!(chars.has_images);
890 }
891
892 #[test]
893 fn test_content_characteristics_parenthesized_ordered_list() {
894 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
895 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
896 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
897 }
898
899 #[test]
900 fn test_content_characteristics_should_skip_rule() {
901 let chars = ContentCharacteristics {
902 has_headings: true,
903 has_lists: false,
904 has_links: true,
905 has_code: false,
906 has_emphasis: true,
907 has_html: false,
908 has_tables: true,
909 has_blockquotes: false,
910 has_images: false,
911 };
912
913 let heading_rule = MD001HeadingIncrement::default();
915 assert!(!chars.should_skip_rule(&heading_rule));
916
917 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
918 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
922 has_headings: false,
923 ..Default::default()
924 };
925 assert!(chars_no_headings.should_skip_rule(&heading_rule));
926 }
927
928 #[test]
929 fn test_lint_empty_content() {
930 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
931
932 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
933 assert!(result.is_ok());
934 assert!(result.unwrap().is_empty());
935 }
936
937 #[test]
938 fn test_lint_with_violations() {
939 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
941
942 let result = lint(
943 content,
944 &rules,
945 false,
946 crate::config::MarkdownFlavor::Standard,
947 None,
948 None,
949 );
950 assert!(result.is_ok());
951 let warnings = result.unwrap();
952 assert!(!warnings.is_empty());
953 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
955 }
956
957 #[test]
958 fn test_lint_with_inline_disable() {
959 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
960 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
961
962 let result = lint(
963 content,
964 &rules,
965 false,
966 crate::config::MarkdownFlavor::Standard,
967 None,
968 None,
969 );
970 assert!(result.is_ok());
971 let warnings = result.unwrap();
972 assert!(warnings.is_empty()); }
974
975 #[test]
976 fn test_lint_rule_filtering() {
977 let content = "# Heading\nJust text";
979 let rules: Vec<Box<dyn Rule>> = vec![
980 Box::new(MD001HeadingIncrement::default()),
981 ];
983
984 let result = lint(
985 content,
986 &rules,
987 false,
988 crate::config::MarkdownFlavor::Standard,
989 None,
990 None,
991 );
992 assert!(result.is_ok());
993 }
994
995 #[test]
996 fn test_get_profiling_report() {
997 let report = get_profiling_report();
999 assert!(!report.is_empty());
1000 assert!(report.contains("Profiling"));
1001 }
1002
1003 #[test]
1004 fn test_reset_profiling() {
1005 reset_profiling();
1007
1008 let report = get_profiling_report();
1010 assert!(report.contains("disabled") || report.contains("no measurements"));
1011 }
1012
1013 #[test]
1014 fn test_get_regex_cache_stats() {
1015 let stats = get_regex_cache_stats();
1016 assert!(stats.is_empty() || !stats.is_empty());
1018
1019 for count in stats.values() {
1021 assert!(*count > 0);
1022 }
1023 }
1024
1025 #[test]
1026 fn test_content_characteristics_edge_cases() {
1027 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
1030
1031 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
1033
1034 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(chars.has_lists); let chars = ContentCharacteristics::analyze("1.Item"); assert!(chars.has_lists); let chars = ContentCharacteristics::analyze("text > not a quote");
1044 assert!(!chars.has_blockquotes);
1045 }
1046
1047 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";
1053
1054 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1056 let config = crate::config::Config::default();
1057 let rules = crate::rules::all_rules(&config);
1058 let warnings = lint(
1059 content,
1060 &rules,
1061 false,
1062 crate::config::MarkdownFlavor::Standard,
1063 None,
1064 Some(&config),
1065 )
1066 .unwrap();
1067 let mut out = Vec::new();
1068 for warning in warnings {
1069 let Some(fix) = warning.fix else { continue };
1070 let rule = warning.rule_name.clone().unwrap_or_default();
1071 let mut stack = vec![fix];
1072 while let Some(fix) = stack.pop() {
1073 out.push((rule.clone(), fix.replacement.clone()));
1074 stack.extend(fix.additional_edits);
1075 }
1076 }
1077 out
1078 }
1079
1080 fn has_bare_lf(text: &str) -> bool {
1081 let bytes = text.as_bytes();
1082 bytes
1083 .iter()
1084 .enumerate()
1085 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1086 }
1087
1088 #[test]
1089 fn fix_replacements_use_the_documents_crlf_line_ending() {
1090 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1091 let replacements = fix_replacements(&crlf);
1092
1093 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1094 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1095
1096 let mut crlf_rules: Vec<_> = replacements
1099 .iter()
1100 .filter(|(_, r)| r.contains("\r\n"))
1101 .map(|(rule, _)| rule.as_str())
1102 .collect();
1103 crlf_rules.sort_unstable();
1104 crlf_rules.dedup();
1105 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1106 assert!(
1107 crlf_rules.contains(&rule),
1108 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1109 );
1110 }
1111 }
1112
1113 #[test]
1114 fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1115 let lf = fix_replacements(LINE_INSERTING_FIXES);
1117 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1118 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1119
1120 let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1123 assert_eq!(
1124 crate::utils::detect_line_ending_enum(&mixed),
1125 crate::utils::LineEnding::Mixed
1126 );
1127 let mixed = fix_replacements(&mixed);
1128 assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1129 }
1130}