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 profiling;
64pub mod rule;
65#[cfg(feature = "colored")]
66pub mod vscode;
67pub mod workspace_index;
68#[macro_use]
69pub mod rule_config;
70#[macro_use]
71pub mod rule_config_serde;
72pub mod rules;
73pub mod types;
74pub mod utils;
75
76#[cfg(feature = "native")]
78pub mod lsp;
79#[cfg(feature = "colored")]
80pub mod output;
81
82#[cfg(feature = "wasm")]
84pub mod wasm;
85
86pub use rules::heading_utils::HeadingStyle;
87pub use rules::*;
88
89pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
90use crate::rule::{LintResult, Rule, RuleCategory};
91use crate::utils::calculate_indentation_width_default;
92#[cfg(not(target_arch = "wasm32"))]
93use std::time::Instant;
94
95#[derive(Debug, Default)]
97struct ContentCharacteristics {
98 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, }
108
109fn has_potential_indented_code_indent(line: &str) -> bool {
112 calculate_indentation_width_default(line) >= 4
113}
114
115impl ContentCharacteristics {
116 fn analyze(content: &str) -> Self {
117 let mut chars = Self { ..Default::default() };
118
119 let mut has_atx_heading = false;
121 let mut has_setext_heading = false;
122
123 for line in content.lines() {
124 let trimmed = line.trim();
125
126 if !has_atx_heading
133 && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
134 {
135 has_atx_heading = true;
136 }
137 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
138 has_setext_heading = true;
139 }
140
141 if !chars.has_lists
144 && (line.contains("* ")
145 || line.contains("- ")
146 || line.contains("+ ")
147 || trimmed.starts_with("* ")
148 || trimmed.starts_with("- ")
149 || trimmed.starts_with("+ ")
150 || trimmed.starts_with('*')
151 || trimmed.starts_with('-')
152 || trimmed.starts_with('+'))
153 {
154 chars.has_lists = true;
155 }
156 if !chars.has_lists
158 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
159 && (line.contains(". ") || line.contains('.')))
160 || (trimmed.starts_with('>')
161 && trimmed.chars().any(|c| c.is_ascii_digit())
162 && (trimmed.contains(". ") || trimmed.contains('.'))))
163 {
164 chars.has_lists = true;
165 }
166 if !chars.has_links
167 && (line.contains('[')
168 || line.contains("http://")
169 || line.contains("https://")
170 || line.contains("ftp://")
171 || line.contains("www."))
172 {
173 chars.has_links = true;
174 }
175 if !chars.has_images && line.contains("![") {
176 chars.has_images = true;
177 }
178 if !chars.has_code
179 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
180 {
181 chars.has_code = true;
182 }
183 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
184 chars.has_emphasis = true;
185 }
186 if !chars.has_html && line.contains('<') {
187 chars.has_html = true;
188 }
189 if !chars.has_tables && line.contains('|') {
190 chars.has_tables = true;
191 }
192 if !chars.has_blockquotes && line.starts_with('>') {
193 chars.has_blockquotes = true;
194 }
195 }
196
197 chars.has_headings = has_atx_heading || has_setext_heading;
198 chars
199 }
200
201 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
203 match rule.category() {
204 RuleCategory::Heading => !self.has_headings,
205 RuleCategory::List => !self.has_lists,
206 RuleCategory::Link => !self.has_links && !self.has_images,
207 RuleCategory::Image => !self.has_images,
208 RuleCategory::CodeBlock => !self.has_code,
209 RuleCategory::Html => !self.has_html,
210 RuleCategory::Emphasis => !self.has_emphasis,
211 RuleCategory::Blockquote => !self.has_blockquotes,
212 RuleCategory::Table => !self.has_tables,
213 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
215 }
216 }
217}
218
219#[cfg(feature = "native")]
224fn compute_content_hash(content: &str) -> String {
225 #[cfg(feature = "profiling")]
226 let start = std::time::Instant::now();
227 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
228 #[cfg(feature = "profiling")]
229 profiling::record_duration("index: hash content", start.elapsed());
230 hash
231}
232
233#[cfg(not(feature = "native"))]
235fn compute_content_hash(content: &str) -> String {
236 use std::hash::{DefaultHasher, Hash, Hasher};
237 let mut hasher = DefaultHasher::new();
238 content.hash(&mut hasher);
239 format!("{:016x}", hasher.finish())
240}
241
242pub fn lint(
246 content: &str,
247 rules: &[Box<dyn Rule>],
248 verbose: bool,
249 flavor: crate::config::MarkdownFlavor,
250 source_file: Option<std::path::PathBuf>,
251 config: Option<&crate::config::Config>,
252) -> LintResult {
253 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
254 result
255}
256
257pub fn build_file_index_only(
265 content: &str,
266 rules: &[Box<dyn Rule>],
267 flavor: crate::config::MarkdownFlavor,
268 source_file: Option<std::path::PathBuf>,
269) -> crate::workspace_index::FileIndex {
270 let content_hash = compute_content_hash(content);
272 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
273
274 if content.is_empty() {
276 return file_index;
277 }
278
279 let lint_ctx = time_function!(
281 "index: parse lint context",
282 crate::lint_context::LintContext::new(content, flavor, source_file)
283 );
284
285 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
289 file_index.file_disabled_rules = file_disabled;
290 file_index.persistent_transitions = persistent_transitions;
291 file_index.line_disabled_rules = line_disabled;
292
293 time_section!("index: contribute cross-file data", {
295 for rule in rules {
296 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
297 rule.contribute_to_index(&lint_ctx, &mut file_index);
298 }
299 }
300 });
301
302 file_index
303}
304
305fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
315 if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
316 return;
317 }
318 fn conform(fix: &mut crate::rule::Fix) {
319 if fix.replacement.contains('\n') {
320 fix.replacement =
321 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
322 }
323 for extra in &mut fix.additional_edits {
324 conform(extra);
325 }
326 }
327 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
328 conform(fix);
329 }
330}
331
332fn retain_reportable_warnings(
340 lint_ctx: &crate::lint_context::LintContext,
341 config: Option<&crate::config::Config>,
342 rule_name: &str,
343 rule_warnings: Vec<crate::rule::LintWarning>,
344 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
345) -> Vec<crate::rule::LintWarning> {
346 let inline_config = lint_ctx.inline_config();
347 let mut kept = Vec::with_capacity(rule_warnings.len());
348
349 for mut warning in rule_warnings {
350 if lint_ctx
351 .line_info(warning.line)
352 .is_some_and(|info| info.in_kramdown_extension_block)
353 {
354 continue;
355 }
356
357 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
359
360 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
362 &rule_name_to_check[..dash_pos]
363 } else {
364 rule_name_to_check
365 };
366
367 let end = if warning.end_line >= warning.line {
373 warning.end_line
374 } else {
375 warning.line
376 };
377 let disabled_at = (warning.line..=end).find_map(|line| {
378 inline_config
379 .disabling_layer(base_rule_name, line)
380 .map(|layer| (line, layer))
381 });
382 if let Some((line, layer)) = disabled_at {
383 if let Some(record) = suppressed.as_deref_mut() {
384 record.push(crate::rule::SuppressedWarning {
385 rule_name: base_rule_name.to_string(),
386 line,
387 layer,
388 });
389 }
390 continue;
391 }
392
393 if let Some(cfg) = config
395 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
396 {
397 warning.severity = override_severity;
398 }
399
400 kept.push(warning);
401 }
402
403 kept
404}
405
406#[cfg_attr(test, allow(unused_variables))]
414#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
416 content: &str,
417 rules: &[Box<dyn Rule>],
418 verbose: bool,
419 flavor: crate::config::MarkdownFlavor,
420 source_file: Option<std::path::PathBuf>,
421 config: Option<&crate::config::Config>,
422) -> (LintResult, crate::workspace_index::FileIndex) {
423 lint_and_index_with_paths(
424 content,
425 rules,
426 verbose,
427 flavor,
428 DocumentPaths::same(source_file.as_deref()),
429 config,
430 )
431}
432
433#[derive(Debug, Clone, Copy, Default)]
435pub struct DocumentPaths<'a> {
436 pub config_path: Option<&'a std::path::Path>,
438 pub source_file: Option<&'a std::path::Path>,
440}
441
442impl<'a> DocumentPaths<'a> {
443 pub fn same(path: Option<&'a std::path::Path>) -> Self {
445 Self {
446 config_path: path,
447 source_file: path,
448 }
449 }
450}
451
452#[cfg_attr(test, allow(unused_variables))]
459pub fn lint_and_index_with_paths(
460 content: &str,
461 rules: &[Box<dyn Rule>],
462 verbose: bool,
463 flavor: crate::config::MarkdownFlavor,
464 paths: DocumentPaths<'_>,
465 config: Option<&crate::config::Config>,
466) -> (LintResult, crate::workspace_index::FileIndex) {
467 let mut warnings = Vec::new();
468 let content_hash = compute_content_hash(content);
470 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
471
472 if content.is_empty() {
474 return (Ok(warnings), file_index);
475 }
476
477 let ignored_for_file = match (config, paths.config_path) {
484 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
485 _ => std::collections::HashSet::new(),
486 };
487
488 let lint_ctx = time_function!(
490 "lint: parse lint context",
491 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
492 );
493 let inline_config = lint_ctx.inline_config();
494
495 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
497 file_index.file_disabled_rules = file_disabled;
498 file_index.persistent_transitions = persistent_transitions;
499 file_index.line_disabled_rules = line_disabled;
500
501 let characteristics = time_function!(
503 "lint: analyze content characteristics",
504 ContentCharacteristics::analyze(content)
505 );
506
507 let applicable_rules: Vec<_> = rules
509 .iter()
510 .filter(|rule| !ignored_for_file.contains(rule.name()))
511 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
512 .collect();
513
514 #[cfg(not(test))]
516 let total_rules = rules.len();
517 #[cfg(not(test))]
518 let applicable_count = applicable_rules.len();
519
520 #[cfg(not(target_arch = "wasm32"))]
521 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
522
523 let inline_overrides = inline_config.get_all_rule_configs();
526 let merged_config = if !inline_overrides.is_empty() {
527 config.map(|c| c.merge_with_inline_config(inline_config))
528 } else {
529 None
530 };
531 let effective_config = merged_config.as_ref().or(config);
532
533 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
535 std::collections::HashMap::new();
536
537 if let Some(cfg) = effective_config {
539 for rule_name in inline_overrides.keys() {
540 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
541 recreated_rules.insert(rule_name.clone(), recreated);
542 }
543 }
544 }
545
546 let suppression_observers: Vec<_> = applicable_rules
550 .iter()
551 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
552 .collect();
553 let mut suppressed = Vec::new();
554
555 {
556 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
557 for rule in &applicable_rules {
558 #[cfg(not(target_arch = "wasm32"))]
559 let rule_start = Instant::now();
560
561 if rule.should_skip(&lint_ctx) {
563 continue;
564 }
565
566 let effective_rule: &dyn crate::rule::Rule = recreated_rules
568 .get(rule.name())
569 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
570
571 let result = effective_rule.check(&lint_ctx);
573
574 match result {
575 Ok(rule_warnings) => {
576 let record = if suppression_observers.is_empty() {
577 None
578 } else {
579 Some(&mut suppressed)
580 };
581 let filtered_warnings =
582 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
583 warnings.extend(filtered_warnings);
584 }
585 Err(e) => {
586 log::error!("Error checking rule {}: {}", rule.name(), e);
587 return (Err(e), file_index);
588 }
589 }
590
591 #[cfg(not(target_arch = "wasm32"))]
592 {
593 let rule_duration = rule_start.elapsed();
594 if profile_rules {
595 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
596 }
597
598 #[cfg(not(test))]
599 if verbose && rule_duration.as_millis() > 500 {
600 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
601 }
602 }
603 }
604 }
605
606 if !suppression_observers.is_empty() {
609 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
610
611 let report = crate::rule::SuppressionReport {
616 suppressed,
617 judged_rules: rules
618 .iter()
619 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
620 .filter(|rule| !ignored_for_file.contains(rule.name()))
621 .map(|rule| rule.name().to_string())
622 .collect(),
623 };
624
625 for rule in &suppression_observers {
626 match rule.check_suppressions(&lint_ctx, &report) {
627 Ok(rule_warnings) => {
628 let filtered_warnings =
629 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
630 warnings.extend(filtered_warnings);
631 }
632 Err(e) => {
633 log::error!("Error checking rule {}: {}", rule.name(), e);
634 return (Err(e), file_index);
635 }
636 }
637 }
638 }
639
640 time_section!("lint: contribute cross-file data", {
648 for rule in rules {
649 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
650 rule.contribute_to_index(&lint_ctx, &mut file_index);
651 }
652 }
653 });
654
655 #[cfg(not(test))]
656 if verbose {
657 let skipped_rules = total_rules - applicable_count;
658 if skipped_rules > 0 {
659 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
660 }
661 }
662
663 conform_fix_line_endings(content, &mut warnings);
664
665 (Ok(warnings), file_index)
666}
667
668pub fn run_cross_file_checks(
681 file_path: &std::path::Path,
682 file_index: &crate::workspace_index::FileIndex,
683 rules: &[Box<dyn Rule>],
684 workspace_index: &crate::workspace_index::WorkspaceIndex,
685 config: Option<&crate::config::Config>,
686) -> LintResult {
687 use crate::rule::CrossFileScope;
688
689 let mut warnings = Vec::new();
690
691 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
697
698 for rule in rules {
700 if rule.cross_file_scope() != CrossFileScope::Workspace {
701 continue;
702 }
703
704 if ignored_rules_for_file
705 .as_ref()
706 .is_some_and(|ignored| ignored.contains(rule.name()))
707 {
708 continue;
709 }
710
711 match time_function!(
712 "workspace: cross-file rule check",
713 rule.cross_file_check(file_path, file_index, workspace_index)
714 ) {
715 Ok(rule_warnings) => {
716 let filtered: Vec<_> = rule_warnings
718 .into_iter()
719 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
720 .map(|mut warning| {
721 if let Some(cfg) = config
723 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
724 {
725 warning.severity = override_severity;
726 }
727 warning
728 })
729 .collect();
730 warnings.extend(filtered);
731 }
732 Err(e) => {
733 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
734 return Err(e);
735 }
736 }
737 }
738
739 Ok(warnings)
740}
741
742pub fn get_profiling_report() -> String {
744 profiling::get_report()
745}
746
747pub fn reset_profiling() {
749 profiling::reset()
750}
751
752pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
754 crate::utils::regex_cache::get_cache_stats()
755}
756
757#[cfg(test)]
758mod tests {
759 use super::*;
760 use crate::rule::Rule;
761 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
762
763 #[test]
764 fn test_content_characteristics_analyze() {
765 let chars = ContentCharacteristics::analyze("");
767 assert!(!chars.has_headings);
768 assert!(!chars.has_lists);
769 assert!(!chars.has_links);
770 assert!(!chars.has_code);
771 assert!(!chars.has_emphasis);
772 assert!(!chars.has_html);
773 assert!(!chars.has_tables);
774 assert!(!chars.has_blockquotes);
775 assert!(!chars.has_images);
776
777 let chars = ContentCharacteristics::analyze("# Heading");
779 assert!(chars.has_headings);
780
781 let chars = ContentCharacteristics::analyze("Heading\n=======");
783 assert!(chars.has_headings);
784
785 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
788 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
789 let chars = ContentCharacteristics::analyze(">> # Nested");
790 assert!(
791 chars.has_headings,
792 "nested-blockquote ATX heading must set has_headings"
793 );
794 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
797 assert!(
798 chars.has_headings,
799 "tab-separated blockquote ATX heading must set has_headings"
800 );
801
802 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
804 assert!(chars.has_lists);
805
806 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
808 assert!(chars.has_lists);
809
810 let chars = ContentCharacteristics::analyze("[link](url)");
812 assert!(chars.has_links);
813
814 let chars = ContentCharacteristics::analyze("Visit https://example.com");
816 assert!(chars.has_links);
817
818 let chars = ContentCharacteristics::analyze("");
820 assert!(chars.has_images);
821
822 let chars = ContentCharacteristics::analyze("`inline code`");
824 assert!(chars.has_code);
825
826 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
827 assert!(chars.has_code);
828
829 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
831 assert!(chars.has_code);
832
833 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
835 assert!(chars.has_code);
836
837 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
839 assert!(chars.has_code);
840
841 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
843 assert!(chars.has_code);
844
845 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
847 assert!(chars.has_emphasis);
848
849 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
851 assert!(chars.has_html);
852
853 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
855 assert!(chars.has_tables);
856
857 let chars = ContentCharacteristics::analyze("> Quote");
859 assert!(chars.has_blockquotes);
860
861 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
863 let chars = ContentCharacteristics::analyze(content);
864 assert!(chars.has_headings);
865 assert!(chars.has_lists);
866 assert!(chars.has_links);
867 assert!(chars.has_code);
868 assert!(chars.has_emphasis);
869 assert!(chars.has_html);
870 assert!(chars.has_tables);
871 assert!(chars.has_blockquotes);
872 assert!(chars.has_images);
873 }
874
875 #[test]
876 fn test_content_characteristics_should_skip_rule() {
877 let chars = ContentCharacteristics {
878 has_headings: true,
879 has_lists: false,
880 has_links: true,
881 has_code: false,
882 has_emphasis: true,
883 has_html: false,
884 has_tables: true,
885 has_blockquotes: false,
886 has_images: false,
887 };
888
889 let heading_rule = MD001HeadingIncrement::default();
891 assert!(!chars.should_skip_rule(&heading_rule));
892
893 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
894 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
898 has_headings: false,
899 ..Default::default()
900 };
901 assert!(chars_no_headings.should_skip_rule(&heading_rule));
902 }
903
904 #[test]
905 fn test_lint_empty_content() {
906 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
907
908 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
909 assert!(result.is_ok());
910 assert!(result.unwrap().is_empty());
911 }
912
913 #[test]
914 fn test_lint_with_violations() {
915 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
917
918 let result = lint(
919 content,
920 &rules,
921 false,
922 crate::config::MarkdownFlavor::Standard,
923 None,
924 None,
925 );
926 assert!(result.is_ok());
927 let warnings = result.unwrap();
928 assert!(!warnings.is_empty());
929 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
931 }
932
933 #[test]
934 fn test_lint_with_inline_disable() {
935 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
936 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
937
938 let result = lint(
939 content,
940 &rules,
941 false,
942 crate::config::MarkdownFlavor::Standard,
943 None,
944 None,
945 );
946 assert!(result.is_ok());
947 let warnings = result.unwrap();
948 assert!(warnings.is_empty()); }
950
951 #[test]
952 fn test_lint_rule_filtering() {
953 let content = "# Heading\nJust text";
955 let rules: Vec<Box<dyn Rule>> = vec![
956 Box::new(MD001HeadingIncrement::default()),
957 ];
959
960 let result = lint(
961 content,
962 &rules,
963 false,
964 crate::config::MarkdownFlavor::Standard,
965 None,
966 None,
967 );
968 assert!(result.is_ok());
969 }
970
971 #[test]
972 fn test_get_profiling_report() {
973 let report = get_profiling_report();
975 assert!(!report.is_empty());
976 assert!(report.contains("Profiling"));
977 }
978
979 #[test]
980 fn test_reset_profiling() {
981 reset_profiling();
983
984 let report = get_profiling_report();
986 assert!(report.contains("disabled") || report.contains("no measurements"));
987 }
988
989 #[test]
990 fn test_get_regex_cache_stats() {
991 let stats = get_regex_cache_stats();
992 assert!(stats.is_empty() || !stats.is_empty());
994
995 for count in stats.values() {
997 assert!(*count > 0);
998 }
999 }
1000
1001 #[test]
1002 fn test_content_characteristics_edge_cases() {
1003 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
1006
1007 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
1009
1010 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");
1020 assert!(!chars.has_blockquotes);
1021 }
1022
1023 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";
1029
1030 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1032 let config = crate::config::Config::default();
1033 let rules = crate::rules::all_rules(&config);
1034 let warnings = lint(
1035 content,
1036 &rules,
1037 false,
1038 crate::config::MarkdownFlavor::Standard,
1039 None,
1040 Some(&config),
1041 )
1042 .unwrap();
1043 let mut out = Vec::new();
1044 for warning in warnings {
1045 let Some(fix) = warning.fix else { continue };
1046 let rule = warning.rule_name.clone().unwrap_or_default();
1047 let mut stack = vec![fix];
1048 while let Some(fix) = stack.pop() {
1049 out.push((rule.clone(), fix.replacement.clone()));
1050 stack.extend(fix.additional_edits);
1051 }
1052 }
1053 out
1054 }
1055
1056 fn has_bare_lf(text: &str) -> bool {
1057 let bytes = text.as_bytes();
1058 bytes
1059 .iter()
1060 .enumerate()
1061 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1062 }
1063
1064 #[test]
1065 fn fix_replacements_use_the_documents_crlf_line_ending() {
1066 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1067 let replacements = fix_replacements(&crlf);
1068
1069 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1070 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1071
1072 let mut crlf_rules: Vec<_> = replacements
1075 .iter()
1076 .filter(|(_, r)| r.contains("\r\n"))
1077 .map(|(rule, _)| rule.as_str())
1078 .collect();
1079 crlf_rules.sort_unstable();
1080 crlf_rules.dedup();
1081 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1082 assert!(
1083 crlf_rules.contains(&rule),
1084 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1085 );
1086 }
1087 }
1088
1089 #[test]
1090 fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1091 let lf = fix_replacements(LINE_INSERTING_FIXES);
1093 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1094 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1095
1096 let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1099 assert_eq!(
1100 crate::utils::detect_line_ending_enum(&mixed),
1101 crate::utils::LineEnding::Mixed
1102 );
1103 let mixed = fix_replacements(&mixed);
1104 assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1105 }
1106}