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
160 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
161 || (trimmed.starts_with('>')
162 && trimmed.chars().any(|c| c.is_ascii_digit())
163 && trimmed.contains(['.', ')'])))
164 {
165 chars.has_lists = true;
166 }
167 if !chars.has_links
168 && (line.contains('[')
169 || line.contains("http://")
170 || line.contains("https://")
171 || line.contains("ftp://")
172 || line.contains("www."))
173 {
174 chars.has_links = true;
175 }
176 if !chars.has_images && line.contains("![") {
177 chars.has_images = true;
178 }
179 if !chars.has_code
180 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
181 {
182 chars.has_code = true;
183 }
184 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
185 chars.has_emphasis = true;
186 }
187 if !chars.has_html && line.contains('<') {
188 chars.has_html = true;
189 }
190 if !chars.has_tables && line.contains('|') {
191 chars.has_tables = true;
192 }
193 if !chars.has_blockquotes && line.starts_with('>') {
194 chars.has_blockquotes = true;
195 }
196 }
197
198 chars.has_headings = has_atx_heading || has_setext_heading;
199 chars
200 }
201
202 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
204 match rule.category() {
205 RuleCategory::Heading => !self.has_headings,
206 RuleCategory::List => !self.has_lists,
207 RuleCategory::Link => !self.has_links && !self.has_images,
208 RuleCategory::Image => !self.has_images,
209 RuleCategory::CodeBlock => !self.has_code,
210 RuleCategory::Html => !self.has_html,
211 RuleCategory::Emphasis => !self.has_emphasis,
212 RuleCategory::Blockquote => !self.has_blockquotes,
213 RuleCategory::Table => !self.has_tables,
214 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
216 }
217 }
218}
219
220#[cfg(feature = "native")]
225fn compute_content_hash(content: &str) -> String {
226 #[cfg(feature = "profiling")]
227 let start = std::time::Instant::now();
228 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
229 #[cfg(feature = "profiling")]
230 profiling::record_duration("index: hash content", start.elapsed());
231 hash
232}
233
234#[cfg(not(feature = "native"))]
236fn compute_content_hash(content: &str) -> String {
237 use std::hash::{DefaultHasher, Hash, Hasher};
238 let mut hasher = DefaultHasher::new();
239 content.hash(&mut hasher);
240 format!("{:016x}", hasher.finish())
241}
242
243pub fn lint(
247 content: &str,
248 rules: &[Box<dyn Rule>],
249 verbose: bool,
250 flavor: crate::config::MarkdownFlavor,
251 source_file: Option<std::path::PathBuf>,
252 config: Option<&crate::config::Config>,
253) -> LintResult {
254 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
255 result
256}
257
258pub fn build_file_index_only(
266 content: &str,
267 rules: &[Box<dyn Rule>],
268 flavor: crate::config::MarkdownFlavor,
269 source_file: Option<std::path::PathBuf>,
270) -> crate::workspace_index::FileIndex {
271 let content_hash = compute_content_hash(content);
273 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
274
275 if content.is_empty() {
277 return file_index;
278 }
279
280 let lint_ctx = time_function!(
282 "index: parse lint context",
283 crate::lint_context::LintContext::new(content, flavor, source_file)
284 );
285
286 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
290 file_index.file_disabled_rules = file_disabled;
291 file_index.persistent_transitions = persistent_transitions;
292 file_index.line_disabled_rules = line_disabled;
293
294 time_section!("index: contribute cross-file data", {
296 for rule in rules {
297 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
298 rule.contribute_to_index(&lint_ctx, &mut file_index);
299 }
300 }
301 });
302
303 file_index
304}
305
306fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
316 if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
317 return;
318 }
319 fn conform(fix: &mut crate::rule::Fix) {
320 if fix.replacement.contains('\n') {
321 fix.replacement =
322 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
323 }
324 for extra in &mut fix.additional_edits {
325 conform(extra);
326 }
327 }
328 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
329 conform(fix);
330 }
331}
332
333fn retain_reportable_warnings(
341 lint_ctx: &crate::lint_context::LintContext,
342 config: Option<&crate::config::Config>,
343 rule_name: &str,
344 rule_warnings: Vec<crate::rule::LintWarning>,
345 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
346) -> Vec<crate::rule::LintWarning> {
347 let inline_config = lint_ctx.inline_config();
348 let mut kept = Vec::with_capacity(rule_warnings.len());
349
350 for mut warning in rule_warnings {
351 if lint_ctx
352 .line_info(warning.line)
353 .is_some_and(|info| info.in_kramdown_extension_block)
354 {
355 continue;
356 }
357
358 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
360
361 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
363 &rule_name_to_check[..dash_pos]
364 } else {
365 rule_name_to_check
366 };
367
368 let end = if warning.end_line >= warning.line {
374 warning.end_line
375 } else {
376 warning.line
377 };
378 let disabled_at = (warning.line..=end).find_map(|line| {
379 inline_config
380 .disabling_layer(base_rule_name, line)
381 .map(|layer| (line, layer))
382 });
383 if let Some((line, layer)) = disabled_at {
384 if let Some(record) = suppressed.as_deref_mut() {
385 record.push(crate::rule::SuppressedWarning {
386 rule_name: base_rule_name.to_string(),
387 line,
388 layer,
389 });
390 }
391 continue;
392 }
393
394 if let Some(cfg) = config
396 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
397 {
398 warning.severity = override_severity;
399 }
400
401 kept.push(warning);
402 }
403
404 kept
405}
406
407#[cfg_attr(test, allow(unused_variables))]
415#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
417 content: &str,
418 rules: &[Box<dyn Rule>],
419 verbose: bool,
420 flavor: crate::config::MarkdownFlavor,
421 source_file: Option<std::path::PathBuf>,
422 config: Option<&crate::config::Config>,
423) -> (LintResult, crate::workspace_index::FileIndex) {
424 lint_and_index_with_paths(
425 content,
426 rules,
427 verbose,
428 flavor,
429 DocumentPaths::same(source_file.as_deref()),
430 config,
431 )
432}
433
434#[derive(Debug, Clone, Copy, Default)]
436pub struct DocumentPaths<'a> {
437 pub config_path: Option<&'a std::path::Path>,
439 pub source_file: Option<&'a std::path::Path>,
441 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
443}
444
445impl<'a> DocumentPaths<'a> {
446 pub fn same(path: Option<&'a std::path::Path>) -> Self {
448 Self {
449 config_path: path,
450 source_file: path,
451 link_target_policy: None,
452 }
453 }
454}
455
456#[cfg_attr(test, allow(unused_variables))]
463pub fn lint_and_index_with_paths(
464 content: &str,
465 rules: &[Box<dyn Rule>],
466 verbose: bool,
467 flavor: crate::config::MarkdownFlavor,
468 paths: DocumentPaths<'_>,
469 config: Option<&crate::config::Config>,
470) -> (LintResult, crate::workspace_index::FileIndex) {
471 let mut warnings = Vec::new();
472 let content_hash = compute_content_hash(content);
474 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
475
476 if content.is_empty() {
478 return (Ok(warnings), file_index);
479 }
480
481 let ignored_for_file = match (config, paths.config_path) {
488 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
489 _ => std::collections::HashSet::new(),
490 };
491
492 let lint_ctx = time_function!(
494 "lint: parse lint context",
495 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
496 );
497 let lint_ctx = match paths.link_target_policy {
498 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
499 None => lint_ctx,
500 };
501 let inline_config = lint_ctx.inline_config();
502
503 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
505 file_index.file_disabled_rules = file_disabled;
506 file_index.persistent_transitions = persistent_transitions;
507 file_index.line_disabled_rules = line_disabled;
508
509 let characteristics = time_function!(
511 "lint: analyze content characteristics",
512 ContentCharacteristics::analyze(content)
513 );
514
515 let applicable_rules: Vec<_> = rules
517 .iter()
518 .filter(|rule| !ignored_for_file.contains(rule.name()))
519 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
520 .collect();
521
522 #[cfg(not(test))]
524 let total_rules = rules.len();
525 #[cfg(not(test))]
526 let applicable_count = applicable_rules.len();
527
528 #[cfg(not(target_arch = "wasm32"))]
529 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
530
531 let inline_overrides = inline_config.get_all_rule_configs();
534 let merged_config = if !inline_overrides.is_empty() {
535 config.map(|c| c.merge_with_inline_config(inline_config))
536 } else {
537 None
538 };
539 let effective_config = merged_config.as_ref().or(config);
540
541 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
543 std::collections::HashMap::new();
544
545 if let Some(cfg) = effective_config {
547 for rule_name in inline_overrides.keys() {
548 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
549 recreated_rules.insert(rule_name.clone(), recreated);
550 }
551 }
552 }
553
554 let suppression_observers: Vec<_> = applicable_rules
558 .iter()
559 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
560 .collect();
561 let mut suppressed = Vec::new();
562
563 {
564 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
565 for rule in &applicable_rules {
566 #[cfg(not(target_arch = "wasm32"))]
567 let rule_start = Instant::now();
568
569 if rule.should_skip(&lint_ctx) {
571 continue;
572 }
573
574 let effective_rule: &dyn crate::rule::Rule = recreated_rules
576 .get(rule.name())
577 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
578
579 let result = effective_rule.check(&lint_ctx);
581
582 match result {
583 Ok(rule_warnings) => {
584 let record = if suppression_observers.is_empty() {
585 None
586 } else {
587 Some(&mut suppressed)
588 };
589 let filtered_warnings =
590 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
591 warnings.extend(filtered_warnings);
592 }
593 Err(e) => {
594 log::error!("Error checking rule {}: {}", rule.name(), e);
595 return (Err(e), file_index);
596 }
597 }
598
599 #[cfg(not(target_arch = "wasm32"))]
600 {
601 let rule_duration = rule_start.elapsed();
602 if profile_rules {
603 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
604 }
605
606 #[cfg(not(test))]
607 if verbose && rule_duration.as_millis() > 500 {
608 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
609 }
610 }
611 }
612 }
613
614 if !suppression_observers.is_empty() {
617 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
618
619 let report = crate::rule::SuppressionReport {
624 suppressed,
625 judged_rules: rules
626 .iter()
627 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
628 .filter(|rule| !ignored_for_file.contains(rule.name()))
629 .map(|rule| rule.name().to_string())
630 .collect(),
631 };
632
633 for rule in &suppression_observers {
634 match rule.check_suppressions(&lint_ctx, &report) {
635 Ok(rule_warnings) => {
636 let filtered_warnings =
637 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
638 warnings.extend(filtered_warnings);
639 }
640 Err(e) => {
641 log::error!("Error checking rule {}: {}", rule.name(), e);
642 return (Err(e), file_index);
643 }
644 }
645 }
646 }
647
648 time_section!("lint: contribute cross-file data", {
656 for rule in rules {
657 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
658 rule.contribute_to_index(&lint_ctx, &mut file_index);
659 }
660 }
661 });
662
663 #[cfg(not(test))]
664 if verbose {
665 let skipped_rules = total_rules - applicable_count;
666 if skipped_rules > 0 {
667 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
668 }
669 }
670
671 conform_fix_line_endings(content, &mut warnings);
672
673 (Ok(warnings), file_index)
674}
675
676pub fn run_cross_file_checks(
689 file_path: &std::path::Path,
690 file_index: &crate::workspace_index::FileIndex,
691 rules: &[Box<dyn Rule>],
692 workspace_index: &crate::workspace_index::WorkspaceIndex,
693 config: Option<&crate::config::Config>,
694) -> LintResult {
695 use crate::rule::CrossFileScope;
696
697 let mut warnings = Vec::new();
698
699 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
705
706 for rule in rules {
708 if rule.cross_file_scope() != CrossFileScope::Workspace {
709 continue;
710 }
711
712 if ignored_rules_for_file
713 .as_ref()
714 .is_some_and(|ignored| ignored.contains(rule.name()))
715 {
716 continue;
717 }
718
719 match time_function!(
720 "workspace: cross-file rule check",
721 rule.cross_file_check(file_path, file_index, workspace_index)
722 ) {
723 Ok(rule_warnings) => {
724 let filtered: Vec<_> = rule_warnings
726 .into_iter()
727 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
728 .map(|mut warning| {
729 if let Some(cfg) = config
731 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
732 {
733 warning.severity = override_severity;
734 }
735 warning
736 })
737 .collect();
738 warnings.extend(filtered);
739 }
740 Err(e) => {
741 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
742 return Err(e);
743 }
744 }
745 }
746
747 Ok(warnings)
748}
749
750pub fn get_profiling_report() -> String {
752 profiling::get_report()
753}
754
755pub fn reset_profiling() {
757 profiling::reset()
758}
759
760pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
762 crate::utils::regex_cache::get_cache_stats()
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768 use crate::rule::Rule;
769 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
770
771 #[test]
772 fn test_content_characteristics_analyze() {
773 let chars = ContentCharacteristics::analyze("");
775 assert!(!chars.has_headings);
776 assert!(!chars.has_lists);
777 assert!(!chars.has_links);
778 assert!(!chars.has_code);
779 assert!(!chars.has_emphasis);
780 assert!(!chars.has_html);
781 assert!(!chars.has_tables);
782 assert!(!chars.has_blockquotes);
783 assert!(!chars.has_images);
784
785 let chars = ContentCharacteristics::analyze("# Heading");
787 assert!(chars.has_headings);
788
789 let chars = ContentCharacteristics::analyze("Heading\n=======");
791 assert!(chars.has_headings);
792
793 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
796 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
797 let chars = ContentCharacteristics::analyze(">> # Nested");
798 assert!(
799 chars.has_headings,
800 "nested-blockquote ATX heading must set has_headings"
801 );
802 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
805 assert!(
806 chars.has_headings,
807 "tab-separated blockquote ATX heading must set has_headings"
808 );
809
810 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
812 assert!(chars.has_lists);
813
814 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
816 assert!(chars.has_lists);
817
818 let chars = ContentCharacteristics::analyze("[link](url)");
820 assert!(chars.has_links);
821
822 let chars = ContentCharacteristics::analyze("Visit https://example.com");
824 assert!(chars.has_links);
825
826 let chars = ContentCharacteristics::analyze("");
828 assert!(chars.has_images);
829
830 let chars = ContentCharacteristics::analyze("`inline code`");
832 assert!(chars.has_code);
833
834 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
835 assert!(chars.has_code);
836
837 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
839 assert!(chars.has_code);
840
841 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
843 assert!(chars.has_code);
844
845 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
847 assert!(chars.has_code);
848
849 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
851 assert!(chars.has_code);
852
853 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
855 assert!(chars.has_emphasis);
856
857 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
859 assert!(chars.has_html);
860
861 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
863 assert!(chars.has_tables);
864
865 let chars = ContentCharacteristics::analyze("> Quote");
867 assert!(chars.has_blockquotes);
868
869 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
871 let chars = ContentCharacteristics::analyze(content);
872 assert!(chars.has_headings);
873 assert!(chars.has_lists);
874 assert!(chars.has_links);
875 assert!(chars.has_code);
876 assert!(chars.has_emphasis);
877 assert!(chars.has_html);
878 assert!(chars.has_tables);
879 assert!(chars.has_blockquotes);
880 assert!(chars.has_images);
881 }
882
883 #[test]
884 fn test_content_characteristics_parenthesized_ordered_list() {
885 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
886 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
887 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
888 }
889
890 #[test]
891 fn test_content_characteristics_should_skip_rule() {
892 let chars = ContentCharacteristics {
893 has_headings: true,
894 has_lists: false,
895 has_links: true,
896 has_code: false,
897 has_emphasis: true,
898 has_html: false,
899 has_tables: true,
900 has_blockquotes: false,
901 has_images: false,
902 };
903
904 let heading_rule = MD001HeadingIncrement::default();
906 assert!(!chars.should_skip_rule(&heading_rule));
907
908 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
909 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
913 has_headings: false,
914 ..Default::default()
915 };
916 assert!(chars_no_headings.should_skip_rule(&heading_rule));
917 }
918
919 #[test]
920 fn test_lint_empty_content() {
921 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
922
923 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
924 assert!(result.is_ok());
925 assert!(result.unwrap().is_empty());
926 }
927
928 #[test]
929 fn test_lint_with_violations() {
930 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
932
933 let result = lint(
934 content,
935 &rules,
936 false,
937 crate::config::MarkdownFlavor::Standard,
938 None,
939 None,
940 );
941 assert!(result.is_ok());
942 let warnings = result.unwrap();
943 assert!(!warnings.is_empty());
944 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
946 }
947
948 #[test]
949 fn test_lint_with_inline_disable() {
950 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
951 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
952
953 let result = lint(
954 content,
955 &rules,
956 false,
957 crate::config::MarkdownFlavor::Standard,
958 None,
959 None,
960 );
961 assert!(result.is_ok());
962 let warnings = result.unwrap();
963 assert!(warnings.is_empty()); }
965
966 #[test]
967 fn test_lint_rule_filtering() {
968 let content = "# Heading\nJust text";
970 let rules: Vec<Box<dyn Rule>> = vec![
971 Box::new(MD001HeadingIncrement::default()),
972 ];
974
975 let result = lint(
976 content,
977 &rules,
978 false,
979 crate::config::MarkdownFlavor::Standard,
980 None,
981 None,
982 );
983 assert!(result.is_ok());
984 }
985
986 #[test]
987 fn test_get_profiling_report() {
988 let report = get_profiling_report();
990 assert!(!report.is_empty());
991 assert!(report.contains("Profiling"));
992 }
993
994 #[test]
995 fn test_reset_profiling() {
996 reset_profiling();
998
999 let report = get_profiling_report();
1001 assert!(report.contains("disabled") || report.contains("no measurements"));
1002 }
1003
1004 #[test]
1005 fn test_get_regex_cache_stats() {
1006 let stats = get_regex_cache_stats();
1007 assert!(stats.is_empty() || !stats.is_empty());
1009
1010 for count in stats.values() {
1012 assert!(*count > 0);
1013 }
1014 }
1015
1016 #[test]
1017 fn test_content_characteristics_edge_cases() {
1018 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
1021
1022 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
1024
1025 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");
1035 assert!(!chars.has_blockquotes);
1036 }
1037
1038 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";
1044
1045 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1047 let config = crate::config::Config::default();
1048 let rules = crate::rules::all_rules(&config);
1049 let warnings = lint(
1050 content,
1051 &rules,
1052 false,
1053 crate::config::MarkdownFlavor::Standard,
1054 None,
1055 Some(&config),
1056 )
1057 .unwrap();
1058 let mut out = Vec::new();
1059 for warning in warnings {
1060 let Some(fix) = warning.fix else { continue };
1061 let rule = warning.rule_name.clone().unwrap_or_default();
1062 let mut stack = vec![fix];
1063 while let Some(fix) = stack.pop() {
1064 out.push((rule.clone(), fix.replacement.clone()));
1065 stack.extend(fix.additional_edits);
1066 }
1067 }
1068 out
1069 }
1070
1071 fn has_bare_lf(text: &str) -> bool {
1072 let bytes = text.as_bytes();
1073 bytes
1074 .iter()
1075 .enumerate()
1076 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1077 }
1078
1079 #[test]
1080 fn fix_replacements_use_the_documents_crlf_line_ending() {
1081 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1082 let replacements = fix_replacements(&crlf);
1083
1084 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1085 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1086
1087 let mut crlf_rules: Vec<_> = replacements
1090 .iter()
1091 .filter(|(_, r)| r.contains("\r\n"))
1092 .map(|(rule, _)| rule.as_str())
1093 .collect();
1094 crlf_rules.sort_unstable();
1095 crlf_rules.dedup();
1096 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1097 assert!(
1098 crlf_rules.contains(&rule),
1099 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1100 );
1101 }
1102 }
1103
1104 #[test]
1105 fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1106 let lf = fix_replacements(LINE_INSERTING_FIXES);
1108 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1109 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1110
1111 let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1114 assert_eq!(
1115 crate::utils::detect_line_ending_enum(&mixed),
1116 crate::utils::LineEnding::Mixed
1117 );
1118 let mixed = fix_replacements(&mixed);
1119 assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1120 }
1121}