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 let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
141 if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
142 has_setext_heading = true;
143 }
144
145 if !chars.has_lists
148 && (line.contains("* ")
149 || line.contains("- ")
150 || line.contains("+ ")
151 || trimmed.starts_with("* ")
152 || trimmed.starts_with("- ")
153 || trimmed.starts_with("+ ")
154 || trimmed.starts_with('*')
155 || trimmed.starts_with('-')
156 || trimmed.starts_with('+'))
157 {
158 chars.has_lists = true;
159 }
160 if !chars.has_lists
164 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
165 || (trimmed.starts_with('>')
166 && trimmed.chars().any(|c| c.is_ascii_digit())
167 && trimmed.contains(['.', ')'])))
168 {
169 chars.has_lists = true;
170 }
171 if !chars.has_links
172 && (line.contains('[')
173 || line.contains("http://")
174 || line.contains("https://")
175 || line.contains("ftp://")
176 || line.contains("www."))
177 {
178 chars.has_links = true;
179 }
180 if !chars.has_images && line.contains("![") {
181 chars.has_images = true;
182 }
183 if !chars.has_code
184 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
185 {
186 chars.has_code = true;
187 }
188 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
189 chars.has_emphasis = true;
190 }
191 if !chars.has_html && line.contains('<') {
192 chars.has_html = true;
193 }
194 if !chars.has_tables && line.contains('|') {
195 chars.has_tables = true;
196 }
197 if !chars.has_blockquotes && line.starts_with('>') {
198 chars.has_blockquotes = true;
199 }
200 }
201
202 chars.has_headings = has_atx_heading || has_setext_heading;
203 chars
204 }
205
206 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
208 match rule.category() {
209 RuleCategory::Heading => !self.has_headings,
210 RuleCategory::List => !self.has_lists,
211 RuleCategory::Link => !self.has_links && !self.has_images,
212 RuleCategory::Image => !self.has_images,
213 RuleCategory::CodeBlock => !self.has_code,
214 RuleCategory::Html => !self.has_html,
215 RuleCategory::Emphasis => !self.has_emphasis,
216 RuleCategory::Blockquote => !self.has_blockquotes,
217 RuleCategory::Table => !self.has_tables,
218 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
220 }
221 }
222}
223
224#[cfg(feature = "native")]
229fn compute_content_hash(content: &str) -> String {
230 #[cfg(feature = "profiling")]
231 let start = std::time::Instant::now();
232 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
233 #[cfg(feature = "profiling")]
234 profiling::record_duration("index: hash content", start.elapsed());
235 hash
236}
237
238#[cfg(not(feature = "native"))]
240fn compute_content_hash(content: &str) -> String {
241 use std::hash::{DefaultHasher, Hash, Hasher};
242 let mut hasher = DefaultHasher::new();
243 content.hash(&mut hasher);
244 format!("{:016x}", hasher.finish())
245}
246
247pub fn lint(
251 content: &str,
252 rules: &[Box<dyn Rule>],
253 verbose: bool,
254 flavor: crate::config::MarkdownFlavor,
255 source_file: Option<std::path::PathBuf>,
256 config: Option<&crate::config::Config>,
257) -> LintResult {
258 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
259 result
260}
261
262pub fn build_file_index_only(
270 content: &str,
271 rules: &[Box<dyn Rule>],
272 flavor: crate::config::MarkdownFlavor,
273 source_file: Option<std::path::PathBuf>,
274) -> crate::workspace_index::FileIndex {
275 build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
276}
277
278pub fn build_file_index_only_with_config(
281 content: &str,
282 rules: &[Box<dyn Rule>],
283 flavor: crate::config::MarkdownFlavor,
284 source_file: Option<std::path::PathBuf>,
285 config: &crate::config::Config,
286) -> crate::workspace_index::FileIndex {
287 let content_hash = compute_content_hash(content);
289 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
290
291 if crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some() {
292 return file_index;
293 }
294
295 if content.is_empty() {
297 return file_index;
298 }
299
300 let lint_ctx = time_function!(
302 "index: parse lint context",
303 crate::lint_context::LintContext::new(content, flavor, source_file)
304 );
305
306 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
310 file_index.file_disabled_rules = file_disabled;
311 file_index.persistent_transitions = persistent_transitions;
312 file_index.line_disabled_rules = line_disabled;
313
314 time_section!("index: contribute cross-file data", {
316 for rule in rules {
317 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
318 rule.contribute_to_index(&lint_ctx, &mut file_index);
319 }
320 }
321 });
322
323 file_index
324}
325
326fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
336 if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
337 return;
338 }
339 fn conform(fix: &mut crate::rule::Fix) {
340 if fix.replacement.contains('\n') {
341 fix.replacement =
342 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
343 }
344 for extra in &mut fix.additional_edits {
345 conform(extra);
346 }
347 }
348 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
349 conform(fix);
350 }
351}
352
353fn retain_reportable_warnings(
361 lint_ctx: &crate::lint_context::LintContext,
362 config: Option<&crate::config::Config>,
363 rule_name: &str,
364 rule_warnings: Vec<crate::rule::LintWarning>,
365 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
366) -> Vec<crate::rule::LintWarning> {
367 let inline_config = lint_ctx.inline_config();
368 let mut kept = Vec::with_capacity(rule_warnings.len());
369
370 for mut warning in rule_warnings {
371 if lint_ctx
372 .line_info(warning.line)
373 .is_some_and(|info| info.in_kramdown_extension_block)
374 {
375 continue;
376 }
377
378 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
380
381 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
383 &rule_name_to_check[..dash_pos]
384 } else {
385 rule_name_to_check
386 };
387
388 let end = if warning.end_line >= warning.line {
394 warning.end_line
395 } else {
396 warning.line
397 };
398 let disabled_at = (warning.line..=end).find_map(|line| {
399 inline_config
400 .disabling_layer(base_rule_name, line)
401 .map(|layer| (line, layer))
402 });
403 if let Some((line, layer)) = disabled_at {
404 if let Some(record) = suppressed.as_deref_mut() {
405 record.push(crate::rule::SuppressedWarning {
406 rule_name: base_rule_name.to_string(),
407 line,
408 layer,
409 });
410 }
411 continue;
412 }
413
414 if let Some(cfg) = config
416 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
417 {
418 warning.severity = override_severity;
419 }
420
421 kept.push(warning);
422 }
423
424 kept
425}
426
427#[cfg_attr(test, allow(unused_variables))]
435#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
437 content: &str,
438 rules: &[Box<dyn Rule>],
439 verbose: bool,
440 flavor: crate::config::MarkdownFlavor,
441 source_file: Option<std::path::PathBuf>,
442 config: Option<&crate::config::Config>,
443) -> (LintResult, crate::workspace_index::FileIndex) {
444 lint_and_index_with_paths(
445 content,
446 rules,
447 verbose,
448 flavor,
449 DocumentPaths::same(source_file.as_deref()),
450 config,
451 )
452}
453
454#[derive(Debug, Clone, Copy, Default)]
456pub struct DocumentPaths<'a> {
457 pub config_path: Option<&'a std::path::Path>,
459 pub source_file: Option<&'a std::path::Path>,
461 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
463}
464
465impl<'a> DocumentPaths<'a> {
466 pub fn same(path: Option<&'a std::path::Path>) -> Self {
468 Self {
469 config_path: path,
470 source_file: path,
471 link_target_policy: None,
472 }
473 }
474}
475
476#[cfg_attr(test, allow(unused_variables))]
483pub fn lint_and_index_with_paths(
484 content: &str,
485 rules: &[Box<dyn Rule>],
486 verbose: bool,
487 flavor: crate::config::MarkdownFlavor,
488 paths: DocumentPaths<'_>,
489 config: Option<&crate::config::Config>,
490) -> (LintResult, crate::workspace_index::FileIndex) {
491 let mut warnings = Vec::new();
492 let content_hash = compute_content_hash(content);
494 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
495
496 let conflict = config.map_or_else(
497 || {
498 crate::merge_conflict::detect_for_rules(
499 content,
500 rules,
501 &crate::config::Config::default(),
502 paths.config_path,
503 )
504 },
505 |config| crate::merge_conflict::detect_for_rules(content, rules, config, paths.config_path),
506 );
507 if let Some(conflict) = conflict {
508 return (Ok(vec![conflict]), file_index);
509 }
510
511 if content.is_empty() {
513 return (Ok(warnings), file_index);
514 }
515
516 let ignored_for_file = match (config, paths.config_path) {
523 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
524 _ => std::collections::HashSet::new(),
525 };
526
527 let lint_ctx = time_function!(
529 "lint: parse lint context",
530 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
531 );
532 let lint_ctx = match paths.link_target_policy {
533 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
534 None => lint_ctx,
535 };
536 let inline_config = lint_ctx.inline_config();
537
538 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
540 file_index.file_disabled_rules = file_disabled;
541 file_index.persistent_transitions = persistent_transitions;
542 file_index.line_disabled_rules = line_disabled;
543
544 let characteristics = time_function!(
546 "lint: analyze content characteristics",
547 ContentCharacteristics::analyze(content)
548 );
549
550 let applicable_rules: Vec<_> = rules
552 .iter()
553 .filter(|rule| !ignored_for_file.contains(rule.name()))
554 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
555 .collect();
556
557 #[cfg(not(test))]
559 let total_rules = rules.len();
560 #[cfg(not(test))]
561 let applicable_count = applicable_rules.len();
562
563 #[cfg(not(target_arch = "wasm32"))]
564 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
565
566 let inline_overrides = inline_config.get_all_rule_configs();
569 let merged_config = if !inline_overrides.is_empty() {
570 config.map(|c| c.merge_with_inline_config(inline_config))
571 } else {
572 None
573 };
574 let effective_config = merged_config.as_ref().or(config);
575
576 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
578 std::collections::HashMap::new();
579
580 if let Some(cfg) = effective_config {
582 for rule_name in inline_overrides.keys() {
583 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
584 recreated_rules.insert(rule_name.clone(), recreated);
585 }
586 }
587 }
588
589 let suppression_observers: Vec<_> = applicable_rules
593 .iter()
594 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
595 .collect();
596 let mut suppressed = Vec::new();
597
598 {
599 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
600 for rule in &applicable_rules {
601 #[cfg(not(target_arch = "wasm32"))]
602 let rule_start = Instant::now();
603
604 if rule.should_skip(&lint_ctx) {
606 continue;
607 }
608
609 let effective_rule: &dyn crate::rule::Rule = recreated_rules
611 .get(rule.name())
612 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
613
614 let result = effective_rule.check(&lint_ctx);
616
617 match result {
618 Ok(rule_warnings) => {
619 let record = if suppression_observers.is_empty() {
620 None
621 } else {
622 Some(&mut suppressed)
623 };
624 let filtered_warnings =
625 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
626 warnings.extend(filtered_warnings);
627 }
628 Err(e) => {
629 log::error!("Error checking rule {}: {}", rule.name(), e);
630 return (Err(e), file_index);
631 }
632 }
633
634 #[cfg(not(target_arch = "wasm32"))]
635 {
636 let rule_duration = rule_start.elapsed();
637 if profile_rules {
638 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
639 }
640
641 #[cfg(not(test))]
642 if verbose && rule_duration.as_millis() > 500 {
643 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
644 }
645 }
646 }
647 }
648
649 if !suppression_observers.is_empty() {
652 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
653
654 let report = crate::rule::SuppressionReport {
659 suppressed,
660 judged_rules: rules
661 .iter()
662 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
663 .filter(|rule| !ignored_for_file.contains(rule.name()))
664 .map(|rule| rule.name().to_string())
665 .collect(),
666 };
667
668 for rule in &suppression_observers {
669 match rule.check_suppressions(&lint_ctx, &report) {
670 Ok(rule_warnings) => {
671 let filtered_warnings =
672 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
673 warnings.extend(filtered_warnings);
674 }
675 Err(e) => {
676 log::error!("Error checking rule {}: {}", rule.name(), e);
677 return (Err(e), file_index);
678 }
679 }
680 }
681 }
682
683 time_section!("lint: contribute cross-file data", {
691 for rule in rules {
692 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
693 rule.contribute_to_index(&lint_ctx, &mut file_index);
694 }
695 }
696 });
697
698 #[cfg(not(test))]
699 if verbose {
700 let skipped_rules = total_rules - applicable_count;
701 if skipped_rules > 0 {
702 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
703 }
704 }
705
706 conform_fix_line_endings(content, &mut warnings);
707
708 (Ok(warnings), file_index)
709}
710
711pub fn run_cross_file_checks(
724 file_path: &std::path::Path,
725 file_index: &crate::workspace_index::FileIndex,
726 rules: &[Box<dyn Rule>],
727 workspace_index: &crate::workspace_index::WorkspaceIndex,
728 config: Option<&crate::config::Config>,
729) -> LintResult {
730 use crate::rule::CrossFileScope;
731
732 let mut warnings = Vec::new();
733
734 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
740
741 for rule in rules {
743 if rule.cross_file_scope() != CrossFileScope::Workspace {
744 continue;
745 }
746
747 if ignored_rules_for_file
748 .as_ref()
749 .is_some_and(|ignored| ignored.contains(rule.name()))
750 {
751 continue;
752 }
753
754 match time_function!(
755 "workspace: cross-file rule check",
756 rule.cross_file_check(file_path, file_index, workspace_index)
757 ) {
758 Ok(rule_warnings) => {
759 let filtered: Vec<_> = rule_warnings
761 .into_iter()
762 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
763 .map(|mut warning| {
764 if let Some(cfg) = config
766 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
767 {
768 warning.severity = override_severity;
769 }
770 warning
771 })
772 .collect();
773 warnings.extend(filtered);
774 }
775 Err(e) => {
776 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
777 return Err(e);
778 }
779 }
780 }
781
782 Ok(warnings)
783}
784
785pub fn get_profiling_report() -> String {
787 profiling::get_report()
788}
789
790pub fn reset_profiling() {
792 profiling::reset()
793}
794
795pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
797 crate::utils::regex_cache::get_cache_stats()
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803 use crate::rule::Rule;
804 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
805
806 #[test]
807 fn test_content_characteristics_analyze() {
808 let chars = ContentCharacteristics::analyze("");
810 assert!(!chars.has_headings);
811 assert!(!chars.has_lists);
812 assert!(!chars.has_links);
813 assert!(!chars.has_code);
814 assert!(!chars.has_emphasis);
815 assert!(!chars.has_html);
816 assert!(!chars.has_tables);
817 assert!(!chars.has_blockquotes);
818 assert!(!chars.has_images);
819
820 let chars = ContentCharacteristics::analyze("# Heading");
822 assert!(chars.has_headings);
823
824 let chars = ContentCharacteristics::analyze("Heading\n=======");
826 assert!(chars.has_headings);
827
828 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
831 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
832 let chars = ContentCharacteristics::analyze(">> # Nested");
833 assert!(
834 chars.has_headings,
835 "nested-blockquote ATX heading must set has_headings"
836 );
837 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
840 assert!(
841 chars.has_headings,
842 "tab-separated blockquote ATX heading must set has_headings"
843 );
844
845 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
847 assert!(chars.has_lists);
848
849 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
851 assert!(chars.has_lists);
852
853 let chars = ContentCharacteristics::analyze("[link](url)");
855 assert!(chars.has_links);
856
857 let chars = ContentCharacteristics::analyze("Visit https://example.com");
859 assert!(chars.has_links);
860
861 let chars = ContentCharacteristics::analyze("");
863 assert!(chars.has_images);
864
865 let chars = ContentCharacteristics::analyze("`inline code`");
867 assert!(chars.has_code);
868
869 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
870 assert!(chars.has_code);
871
872 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
874 assert!(chars.has_code);
875
876 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
878 assert!(chars.has_code);
879
880 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
882 assert!(chars.has_code);
883
884 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
886 assert!(chars.has_code);
887
888 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
890 assert!(chars.has_emphasis);
891
892 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
894 assert!(chars.has_html);
895
896 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
898 assert!(chars.has_tables);
899
900 let chars = ContentCharacteristics::analyze("> Quote");
902 assert!(chars.has_blockquotes);
903
904 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
906 let chars = ContentCharacteristics::analyze(content);
907 assert!(chars.has_headings);
908 assert!(chars.has_lists);
909 assert!(chars.has_links);
910 assert!(chars.has_code);
911 assert!(chars.has_emphasis);
912 assert!(chars.has_html);
913 assert!(chars.has_tables);
914 assert!(chars.has_blockquotes);
915 assert!(chars.has_images);
916 }
917
918 #[test]
919 fn test_content_characteristics_parenthesized_ordered_list() {
920 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
921 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
922 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
923 }
924
925 #[test]
926 fn test_content_characteristics_should_skip_rule() {
927 let chars = ContentCharacteristics {
928 has_headings: true,
929 has_lists: false,
930 has_links: true,
931 has_code: false,
932 has_emphasis: true,
933 has_html: false,
934 has_tables: true,
935 has_blockquotes: false,
936 has_images: false,
937 };
938
939 let heading_rule = MD001HeadingIncrement::default();
941 assert!(!chars.should_skip_rule(&heading_rule));
942
943 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
944 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
948 has_headings: false,
949 ..Default::default()
950 };
951 assert!(chars_no_headings.should_skip_rule(&heading_rule));
952 }
953
954 #[test]
955 fn test_lint_empty_content() {
956 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
957
958 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
959 assert!(result.is_ok());
960 assert!(result.unwrap().is_empty());
961 }
962
963 #[test]
964 fn test_lint_with_violations() {
965 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
967
968 let result = lint(
969 content,
970 &rules,
971 false,
972 crate::config::MarkdownFlavor::Standard,
973 None,
974 None,
975 );
976 assert!(result.is_ok());
977 let warnings = result.unwrap();
978 assert!(!warnings.is_empty());
979 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
981 }
982
983 #[test]
984 fn test_lint_with_inline_disable() {
985 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
986 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
987
988 let result = lint(
989 content,
990 &rules,
991 false,
992 crate::config::MarkdownFlavor::Standard,
993 None,
994 None,
995 );
996 assert!(result.is_ok());
997 let warnings = result.unwrap();
998 assert!(warnings.is_empty()); }
1000
1001 #[test]
1002 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1003 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1007 for content in [
1008 "Title\n-\n\ntitle\n-\n",
1009 "Title\n=\n\ntitle\n=\n",
1010 "> Title\n> ===\n\n> title\n> ===\n",
1011 "> Title\n> -\n\n> title\n> -\n",
1012 ] {
1013 let warnings = lint(
1014 content,
1015 &rules,
1016 false,
1017 crate::config::MarkdownFlavor::Standard,
1018 None,
1019 None,
1020 )
1021 .unwrap();
1022 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1023 assert_eq!(lines, [4], "{content:?}");
1024 }
1025 }
1026
1027 #[test]
1028 fn test_lint_rule_filtering() {
1029 let content = "# Heading\nJust text";
1031 let rules: Vec<Box<dyn Rule>> = vec![
1032 Box::new(MD001HeadingIncrement::default()),
1033 ];
1035
1036 let result = lint(
1037 content,
1038 &rules,
1039 false,
1040 crate::config::MarkdownFlavor::Standard,
1041 None,
1042 None,
1043 );
1044 assert!(result.is_ok());
1045 }
1046
1047 #[test]
1048 fn test_get_profiling_report() {
1049 let report = get_profiling_report();
1051 assert!(!report.is_empty());
1052 assert!(report.contains("Profiling"));
1053 }
1054
1055 #[test]
1056 fn test_reset_profiling() {
1057 reset_profiling();
1059
1060 let report = get_profiling_report();
1062 assert!(report.contains("disabled") || report.contains("no measurements"));
1063 }
1064
1065 #[test]
1066 fn test_get_regex_cache_stats() {
1067 let stats = get_regex_cache_stats();
1068 assert!(stats.is_empty() || !stats.is_empty());
1070
1071 for count in stats.values() {
1073 assert!(*count > 0);
1074 }
1075 }
1076
1077 #[test]
1078 fn test_content_characteristics_edge_cases() {
1079 for content in [
1082 "Title\n-",
1083 "Title\n=",
1084 "Title\n--",
1085 "> Title\n> ===",
1086 ">\tTitle\n>\t-",
1087 ">> Title\n>>-",
1088 ] {
1089 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1090 }
1091 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1092 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1093 }
1094
1095 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");
1105 assert!(!chars.has_blockquotes);
1106 }
1107
1108 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";
1114
1115 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1117 let config = crate::config::Config::default();
1118 let rules = crate::rules::all_rules(&config);
1119 let warnings = lint(
1120 content,
1121 &rules,
1122 false,
1123 crate::config::MarkdownFlavor::Standard,
1124 None,
1125 Some(&config),
1126 )
1127 .unwrap();
1128 let mut out = Vec::new();
1129 for warning in warnings {
1130 let Some(fix) = warning.fix else { continue };
1131 let rule = warning.rule_name.clone().unwrap_or_default();
1132 let mut stack = vec![fix];
1133 while let Some(fix) = stack.pop() {
1134 out.push((rule.clone(), fix.replacement.clone()));
1135 stack.extend(fix.additional_edits);
1136 }
1137 }
1138 out
1139 }
1140
1141 fn has_bare_lf(text: &str) -> bool {
1142 let bytes = text.as_bytes();
1143 bytes
1144 .iter()
1145 .enumerate()
1146 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1147 }
1148
1149 #[test]
1150 fn fix_replacements_use_the_documents_crlf_line_ending() {
1151 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1152 let replacements = fix_replacements(&crlf);
1153
1154 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1155 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1156
1157 let mut crlf_rules: Vec<_> = replacements
1160 .iter()
1161 .filter(|(_, r)| r.contains("\r\n"))
1162 .map(|(rule, _)| rule.as_str())
1163 .collect();
1164 crlf_rules.sort_unstable();
1165 crlf_rules.dedup();
1166 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1167 assert!(
1168 crlf_rules.contains(&rule),
1169 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1170 );
1171 }
1172 }
1173
1174 #[test]
1175 fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1176 let lf = fix_replacements(LINE_INSERTING_FIXES);
1178 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1179 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1180
1181 let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1184 assert_eq!(
1185 crate::utils::detect_line_ending_enum(&mixed),
1186 crate::utils::LineEnding::Mixed
1187 );
1188 let mixed = fix_replacements(&mixed);
1189 assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1190 }
1191}