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 encoding;
57pub mod exit_codes;
58pub mod filtered_lines;
59pub mod fix_coordinator;
60pub mod inline_config;
61pub mod linguist_data;
62pub mod lint_context;
63pub mod markdownlint_config;
64pub mod merge_conflict;
65pub mod profiling;
66pub mod rule;
67#[cfg(feature = "colored")]
68pub mod vscode;
69pub mod workspace_index;
70#[macro_use]
71pub mod rule_config;
72#[macro_use]
73pub mod rule_config_serde;
74pub mod rules;
75pub mod types;
76pub mod utils;
77
78#[cfg(feature = "native")]
80pub mod lsp;
81#[cfg(feature = "colored")]
82pub mod output;
83
84#[cfg(feature = "wasm")]
86pub mod wasm;
87
88pub use rules::heading_utils::HeadingStyle;
89pub use rules::*;
90
91pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
92use crate::rule::{LintResult, Rule, RuleCategory};
93use crate::utils::calculate_indentation_width_default;
94#[cfg(not(target_arch = "wasm32"))]
95use std::time::Instant;
96
97#[derive(Debug, Default)]
99struct ContentCharacteristics {
100 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, }
110
111fn has_potential_indented_code_indent(line: &str) -> bool {
114 calculate_indentation_width_default(line) >= 4
115}
116
117impl ContentCharacteristics {
118 fn analyze(content: &str) -> Self {
119 let mut chars = Self { ..Default::default() };
120
121 let mut has_atx_heading = false;
123 let mut has_setext_heading = false;
124
125 for line in content.lines() {
126 let trimmed = line.trim();
127
128 if !has_atx_heading
135 && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
136 {
137 has_atx_heading = true;
138 }
139 let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
142 if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
143 has_setext_heading = true;
144 }
145
146 if !chars.has_lists
149 && (line.contains("* ")
150 || line.contains("- ")
151 || line.contains("+ ")
152 || trimmed.starts_with("* ")
153 || trimmed.starts_with("- ")
154 || trimmed.starts_with("+ ")
155 || trimmed.starts_with('*')
156 || trimmed.starts_with('-')
157 || trimmed.starts_with('+'))
158 {
159 chars.has_lists = true;
160 }
161 if !chars.has_lists
165 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
166 || (trimmed.starts_with('>')
167 && trimmed.chars().any(|c| c.is_ascii_digit())
168 && trimmed.contains(['.', ')'])))
169 {
170 chars.has_lists = true;
171 }
172 if !chars.has_links
173 && (line.contains('[')
174 || line.contains("http://")
175 || line.contains("https://")
176 || line.contains("ftp://")
177 || line.contains("www."))
178 {
179 chars.has_links = true;
180 }
181 if !chars.has_images && line.contains("![") {
182 chars.has_images = true;
183 }
184 if !chars.has_code
185 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
186 {
187 chars.has_code = true;
188 }
189 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
190 chars.has_emphasis = true;
191 }
192 if !chars.has_html && line.contains('<') {
193 chars.has_html = true;
194 }
195 if !chars.has_tables && line.contains('|') {
196 chars.has_tables = true;
197 }
198 if !chars.has_blockquotes && line.starts_with('>') {
199 chars.has_blockquotes = true;
200 }
201 }
202
203 chars.has_headings = has_atx_heading || has_setext_heading;
204 chars
205 }
206
207 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
209 match rule.category() {
210 RuleCategory::Heading => !self.has_headings,
211 RuleCategory::List => !self.has_lists,
212 RuleCategory::Link => !self.has_links && !self.has_images,
213 RuleCategory::Image => !self.has_images,
214 RuleCategory::CodeBlock => !self.has_code,
215 RuleCategory::Html => !self.has_html,
216 RuleCategory::Emphasis => !self.has_emphasis,
217 RuleCategory::Blockquote => !self.has_blockquotes,
218 RuleCategory::Table => !self.has_tables,
219 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
221 }
222 }
223}
224
225#[cfg(feature = "native")]
230fn compute_content_hash(content: &str) -> String {
231 #[cfg(feature = "profiling")]
232 let start = std::time::Instant::now();
233 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
234 #[cfg(feature = "profiling")]
235 profiling::record_duration("index: hash content", start.elapsed());
236 hash
237}
238
239#[cfg(not(feature = "native"))]
241fn compute_content_hash(content: &str) -> String {
242 use std::hash::{DefaultHasher, Hash, Hasher};
243 let mut hasher = DefaultHasher::new();
244 content.hash(&mut hasher);
245 format!("{:016x}", hasher.finish())
246}
247
248pub fn lint(
252 content: &str,
253 rules: &[Box<dyn Rule>],
254 verbose: bool,
255 flavor: crate::config::MarkdownFlavor,
256 source_file: Option<std::path::PathBuf>,
257 config: Option<&crate::config::Config>,
258) -> LintResult {
259 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
260 result
261}
262
263pub fn build_file_index_only(
271 content: &str,
272 rules: &[Box<dyn Rule>],
273 flavor: crate::config::MarkdownFlavor,
274 source_file: Option<std::path::PathBuf>,
275) -> crate::workspace_index::FileIndex {
276 build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
277}
278
279pub fn build_file_index_only_with_config(
288 content: &str,
289 rules: &[Box<dyn Rule>],
290 flavor: crate::config::MarkdownFlavor,
291 source_file: Option<std::path::PathBuf>,
292 config: &crate::config::Config,
293) -> crate::workspace_index::FileIndex {
294 let conflicted = crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some();
295 build_index(content, rules, flavor, source_file, conflicted)
296}
297
298pub fn build_file_index_only_for_selection(
303 content: &str,
304 selection: &[Box<dyn Rule>],
305 flavor: crate::config::MarkdownFlavor,
306 source_file: Option<std::path::PathBuf>,
307 config: &crate::config::Config,
308) -> crate::workspace_index::FileIndex {
309 let conflicted =
310 crate::merge_conflict::detect_for_rules(content, selection, config, source_file.as_deref()).is_some();
311 build_index(content, selection, flavor, source_file, conflicted)
312}
313
314fn build_index(
315 content: &str,
316 rules: &[Box<dyn Rule>],
317 flavor: crate::config::MarkdownFlavor,
318 source_file: Option<std::path::PathBuf>,
319 conflicted: bool,
320) -> crate::workspace_index::FileIndex {
321 let content_hash = compute_content_hash(content);
323 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
324
325 if conflicted {
328 return file_index;
329 }
330
331 if content.is_empty() {
333 return file_index;
334 }
335
336 let lint_ctx = time_function!(
338 "index: parse lint context",
339 crate::lint_context::LintContext::new(content, flavor, source_file)
340 );
341
342 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
346 file_index.file_disabled_rules = file_disabled;
347 file_index.persistent_transitions = persistent_transitions;
348 file_index.line_disabled_rules = line_disabled;
349
350 time_section!("index: contribute cross-file data", {
352 for rule in rules {
353 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
354 rule.contribute_to_index(&lint_ctx, &mut file_index);
355 }
356 }
357 });
358
359 file_index
360}
361
362fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
372 if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
373 return;
374 }
375 fn conform(fix: &mut crate::rule::Fix) {
376 if fix.replacement.contains('\n') {
377 fix.replacement =
378 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
379 }
380 for extra in &mut fix.additional_edits {
381 conform(extra);
382 }
383 }
384 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
385 conform(fix);
386 }
387}
388
389fn retain_reportable_warnings(
397 lint_ctx: &crate::lint_context::LintContext,
398 config: Option<&crate::config::Config>,
399 rule_name: &str,
400 rule_warnings: Vec<crate::rule::LintWarning>,
401 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
402) -> Vec<crate::rule::LintWarning> {
403 let inline_config = lint_ctx.inline_config();
404 let mut kept = Vec::with_capacity(rule_warnings.len());
405
406 for mut warning in rule_warnings {
407 if lint_ctx
408 .line_info(warning.line)
409 .is_some_and(|info| info.in_kramdown_extension_block)
410 {
411 continue;
412 }
413
414 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
416
417 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
419 &rule_name_to_check[..dash_pos]
420 } else {
421 rule_name_to_check
422 };
423
424 let end = if warning.end_line >= warning.line {
430 warning.end_line
431 } else {
432 warning.line
433 };
434 let disabled_at = (warning.line..=end).find_map(|line| {
435 inline_config
436 .disabling_layer(base_rule_name, line)
437 .map(|layer| (line, layer))
438 });
439 if let Some((line, layer)) = disabled_at {
440 if let Some(record) = suppressed.as_deref_mut() {
441 record.push(crate::rule::SuppressedWarning {
442 rule_name: base_rule_name.to_string(),
443 line,
444 layer,
445 });
446 }
447 continue;
448 }
449
450 if let Some(cfg) = config
452 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
453 {
454 warning.severity = override_severity;
455 }
456
457 kept.push(warning);
458 }
459
460 kept
461}
462
463#[cfg_attr(test, allow(unused_variables))]
471#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
473 content: &str,
474 rules: &[Box<dyn Rule>],
475 verbose: bool,
476 flavor: crate::config::MarkdownFlavor,
477 source_file: Option<std::path::PathBuf>,
478 config: Option<&crate::config::Config>,
479) -> (LintResult, crate::workspace_index::FileIndex) {
480 lint_and_index_with_paths(
481 content,
482 rules,
483 verbose,
484 flavor,
485 DocumentPaths::same(source_file.as_deref()),
486 config,
487 )
488}
489
490#[derive(Debug, Clone, Copy, Default)]
492pub struct DocumentPaths<'a> {
493 pub config_path: Option<&'a std::path::Path>,
495 pub source_file: Option<&'a std::path::Path>,
497 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
499 pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
501}
502
503impl<'a> DocumentPaths<'a> {
504 pub fn same(path: Option<&'a std::path::Path>) -> Self {
506 Self {
507 config_path: path,
508 source_file: path,
509 link_target_policy: None,
510 invalid_utf8: None,
511 }
512 }
513}
514
515#[cfg_attr(test, allow(unused_variables))]
522pub fn lint_and_index_with_paths(
523 content: &str,
524 rules: &[Box<dyn Rule>],
525 verbose: bool,
526 flavor: crate::config::MarkdownFlavor,
527 paths: DocumentPaths<'_>,
528 config: Option<&crate::config::Config>,
529) -> (LintResult, crate::workspace_index::FileIndex) {
530 let mut warnings = Vec::new();
531 let content_hash = compute_content_hash(content);
533 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
534
535 let conflict = config.map_or_else(
536 || {
537 crate::merge_conflict::detect_for_rules(
538 content,
539 rules,
540 &crate::config::Config::default(),
541 paths.config_path,
542 )
543 },
544 |config| crate::merge_conflict::detect_for_rules(content, rules, config, paths.config_path),
545 );
546 if let Some(conflict) = conflict {
547 return (Ok(vec![conflict]), file_index);
548 }
549
550 if content.is_empty() {
552 return (Ok(warnings), file_index);
553 }
554
555 let ignored_for_file = match (config, paths.config_path) {
562 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
563 _ => std::collections::HashSet::new(),
564 };
565
566 let lint_ctx = time_function!(
568 "lint: parse lint context",
569 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
570 );
571 let lint_ctx = match paths.link_target_policy {
572 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
573 None => lint_ctx,
574 };
575 let lint_ctx = match paths.invalid_utf8 {
576 Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
577 None => lint_ctx,
578 };
579 let inline_config = lint_ctx.inline_config();
580
581 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
583 file_index.file_disabled_rules = file_disabled;
584 file_index.persistent_transitions = persistent_transitions;
585 file_index.line_disabled_rules = line_disabled;
586
587 let characteristics = time_function!(
589 "lint: analyze content characteristics",
590 ContentCharacteristics::analyze(content)
591 );
592
593 let applicable_rules: Vec<_> = rules
595 .iter()
596 .filter(|rule| !ignored_for_file.contains(rule.name()))
597 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
598 .collect();
599
600 #[cfg(not(test))]
602 let total_rules = rules.len();
603 #[cfg(not(test))]
604 let applicable_count = applicable_rules.len();
605
606 #[cfg(not(target_arch = "wasm32"))]
607 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
608
609 let inline_overrides = inline_config.get_all_rule_configs();
612 let merged_config = if !inline_overrides.is_empty() {
613 config.map(|c| c.merge_with_inline_config(inline_config))
614 } else {
615 None
616 };
617 let effective_config = merged_config.as_ref().or(config);
618
619 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
621 std::collections::HashMap::new();
622
623 if let Some(cfg) = effective_config {
625 for rule_name in inline_overrides.keys() {
626 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
627 recreated_rules.insert(rule_name.clone(), recreated);
628 }
629 }
630 }
631
632 let suppression_observers: Vec<_> = applicable_rules
636 .iter()
637 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
638 .collect();
639 let mut suppressed = Vec::new();
640
641 {
642 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
643 for rule in &applicable_rules {
644 #[cfg(not(target_arch = "wasm32"))]
645 let rule_start = Instant::now();
646
647 if rule.should_skip(&lint_ctx) {
649 continue;
650 }
651
652 let effective_rule: &dyn crate::rule::Rule = recreated_rules
654 .get(rule.name())
655 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
656
657 let result = effective_rule.check(&lint_ctx);
659
660 match result {
661 Ok(rule_warnings) => {
662 let record = if suppression_observers.is_empty() {
663 None
664 } else {
665 Some(&mut suppressed)
666 };
667 let filtered_warnings =
668 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
669 warnings.extend(filtered_warnings);
670 }
671 Err(e) => {
672 log::error!("Error checking rule {}: {}", rule.name(), e);
673 return (Err(e), file_index);
674 }
675 }
676
677 #[cfg(not(target_arch = "wasm32"))]
678 {
679 let rule_duration = rule_start.elapsed();
680 if profile_rules {
681 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
682 }
683
684 #[cfg(not(test))]
685 if verbose && rule_duration.as_millis() > 500 {
686 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
687 }
688 }
689 }
690 }
691
692 if !suppression_observers.is_empty() {
695 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
696
697 let report = crate::rule::SuppressionReport {
702 suppressed,
703 judged_rules: rules
704 .iter()
705 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
706 .filter(|rule| !ignored_for_file.contains(rule.name()))
707 .map(|rule| rule.name().to_string())
708 .collect(),
709 };
710
711 for rule in &suppression_observers {
712 match rule.check_suppressions(&lint_ctx, &report) {
713 Ok(rule_warnings) => {
714 let filtered_warnings =
715 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
716 warnings.extend(filtered_warnings);
717 }
718 Err(e) => {
719 log::error!("Error checking rule {}: {}", rule.name(), e);
720 return (Err(e), file_index);
721 }
722 }
723 }
724 }
725
726 time_section!("lint: contribute cross-file data", {
734 for rule in rules {
735 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
736 rule.contribute_to_index(&lint_ctx, &mut file_index);
737 }
738 }
739 });
740
741 #[cfg(not(test))]
742 if verbose {
743 let skipped_rules = total_rules - applicable_count;
744 if skipped_rules > 0 {
745 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
746 }
747 }
748
749 if paths.invalid_utf8.is_some() {
750 crate::encoding::settle_lossy_warnings(&mut warnings);
751 }
752
753 conform_fix_line_endings(content, &mut warnings);
754
755 (Ok(warnings), file_index)
756}
757
758pub fn run_cross_file_checks(
771 file_path: &std::path::Path,
772 file_index: &crate::workspace_index::FileIndex,
773 rules: &[Box<dyn Rule>],
774 workspace_index: &crate::workspace_index::WorkspaceIndex,
775 config: Option<&crate::config::Config>,
776) -> LintResult {
777 use crate::rule::CrossFileScope;
778
779 let mut warnings = Vec::new();
780
781 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
787
788 for rule in rules {
790 if rule.cross_file_scope() != CrossFileScope::Workspace {
791 continue;
792 }
793
794 if ignored_rules_for_file
795 .as_ref()
796 .is_some_and(|ignored| ignored.contains(rule.name()))
797 {
798 continue;
799 }
800
801 match time_function!(
802 "workspace: cross-file rule check",
803 rule.cross_file_check(file_path, file_index, workspace_index)
804 ) {
805 Ok(rule_warnings) => {
806 let filtered: Vec<_> = rule_warnings
808 .into_iter()
809 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
810 .map(|mut warning| {
811 if let Some(cfg) = config
813 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
814 {
815 warning.severity = override_severity;
816 }
817 warning
818 })
819 .collect();
820 warnings.extend(filtered);
821 }
822 Err(e) => {
823 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
824 return Err(e);
825 }
826 }
827 }
828
829 Ok(warnings)
830}
831
832pub fn get_profiling_report() -> String {
834 profiling::get_report()
835}
836
837pub fn reset_profiling() {
839 profiling::reset()
840}
841
842pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
844 crate::utils::regex_cache::get_cache_stats()
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850 use crate::rule::Rule;
851 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
852
853 #[test]
854 fn test_content_characteristics_analyze() {
855 let chars = ContentCharacteristics::analyze("");
857 assert!(!chars.has_headings);
858 assert!(!chars.has_lists);
859 assert!(!chars.has_links);
860 assert!(!chars.has_code);
861 assert!(!chars.has_emphasis);
862 assert!(!chars.has_html);
863 assert!(!chars.has_tables);
864 assert!(!chars.has_blockquotes);
865 assert!(!chars.has_images);
866
867 let chars = ContentCharacteristics::analyze("# Heading");
869 assert!(chars.has_headings);
870
871 let chars = ContentCharacteristics::analyze("Heading\n=======");
873 assert!(chars.has_headings);
874
875 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
878 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
879 let chars = ContentCharacteristics::analyze(">> # Nested");
880 assert!(
881 chars.has_headings,
882 "nested-blockquote ATX heading must set has_headings"
883 );
884 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
887 assert!(
888 chars.has_headings,
889 "tab-separated blockquote ATX heading must set has_headings"
890 );
891
892 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
894 assert!(chars.has_lists);
895
896 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
898 assert!(chars.has_lists);
899
900 let chars = ContentCharacteristics::analyze("[link](url)");
902 assert!(chars.has_links);
903
904 let chars = ContentCharacteristics::analyze("Visit https://example.com");
906 assert!(chars.has_links);
907
908 let chars = ContentCharacteristics::analyze("");
910 assert!(chars.has_images);
911
912 let chars = ContentCharacteristics::analyze("`inline code`");
914 assert!(chars.has_code);
915
916 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
917 assert!(chars.has_code);
918
919 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
921 assert!(chars.has_code);
922
923 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
925 assert!(chars.has_code);
926
927 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
929 assert!(chars.has_code);
930
931 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
933 assert!(chars.has_code);
934
935 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
937 assert!(chars.has_emphasis);
938
939 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
941 assert!(chars.has_html);
942
943 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
945 assert!(chars.has_tables);
946
947 let chars = ContentCharacteristics::analyze("> Quote");
949 assert!(chars.has_blockquotes);
950
951 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
953 let chars = ContentCharacteristics::analyze(content);
954 assert!(chars.has_headings);
955 assert!(chars.has_lists);
956 assert!(chars.has_links);
957 assert!(chars.has_code);
958 assert!(chars.has_emphasis);
959 assert!(chars.has_html);
960 assert!(chars.has_tables);
961 assert!(chars.has_blockquotes);
962 assert!(chars.has_images);
963 }
964
965 #[test]
966 fn test_content_characteristics_parenthesized_ordered_list() {
967 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
968 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
969 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
970 }
971
972 #[test]
973 fn test_content_characteristics_should_skip_rule() {
974 let chars = ContentCharacteristics {
975 has_headings: true,
976 has_lists: false,
977 has_links: true,
978 has_code: false,
979 has_emphasis: true,
980 has_html: false,
981 has_tables: true,
982 has_blockquotes: false,
983 has_images: false,
984 };
985
986 let heading_rule = MD001HeadingIncrement::default();
988 assert!(!chars.should_skip_rule(&heading_rule));
989
990 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
991 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
995 has_headings: false,
996 ..Default::default()
997 };
998 assert!(chars_no_headings.should_skip_rule(&heading_rule));
999 }
1000
1001 #[test]
1002 fn test_lint_empty_content() {
1003 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1004
1005 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1006 assert!(result.is_ok());
1007 assert!(result.unwrap().is_empty());
1008 }
1009
1010 #[test]
1011 fn test_lint_with_violations() {
1012 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1014
1015 let result = lint(
1016 content,
1017 &rules,
1018 false,
1019 crate::config::MarkdownFlavor::Standard,
1020 None,
1021 None,
1022 );
1023 assert!(result.is_ok());
1024 let warnings = result.unwrap();
1025 assert!(!warnings.is_empty());
1026 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1028 }
1029
1030 #[test]
1031 fn test_lint_with_inline_disable() {
1032 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1033 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1034
1035 let result = lint(
1036 content,
1037 &rules,
1038 false,
1039 crate::config::MarkdownFlavor::Standard,
1040 None,
1041 None,
1042 );
1043 assert!(result.is_ok());
1044 let warnings = result.unwrap();
1045 assert!(warnings.is_empty()); }
1047
1048 #[test]
1049 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1050 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1054 for content in [
1055 "Title\n-\n\ntitle\n-\n",
1056 "Title\n=\n\ntitle\n=\n",
1057 "> Title\n> ===\n\n> title\n> ===\n",
1058 "> Title\n> -\n\n> title\n> -\n",
1059 ] {
1060 let warnings = lint(
1061 content,
1062 &rules,
1063 false,
1064 crate::config::MarkdownFlavor::Standard,
1065 None,
1066 None,
1067 )
1068 .unwrap();
1069 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1070 assert_eq!(lines, [4], "{content:?}");
1071 }
1072 }
1073
1074 #[test]
1075 fn test_lint_rule_filtering() {
1076 let content = "# Heading\nJust text";
1078 let rules: Vec<Box<dyn Rule>> = vec![
1079 Box::new(MD001HeadingIncrement::default()),
1080 ];
1082
1083 let result = lint(
1084 content,
1085 &rules,
1086 false,
1087 crate::config::MarkdownFlavor::Standard,
1088 None,
1089 None,
1090 );
1091 assert!(result.is_ok());
1092 }
1093
1094 #[test]
1095 fn test_get_profiling_report() {
1096 let report = get_profiling_report();
1098 assert!(!report.is_empty());
1099 assert!(report.contains("Profiling"));
1100 }
1101
1102 #[test]
1103 fn test_reset_profiling() {
1104 reset_profiling();
1106
1107 let report = get_profiling_report();
1109 assert!(report.contains("disabled") || report.contains("no measurements"));
1110 }
1111
1112 #[test]
1113 fn test_get_regex_cache_stats() {
1114 let stats = get_regex_cache_stats();
1115 assert!(stats.is_empty() || !stats.is_empty());
1117
1118 for count in stats.values() {
1120 assert!(*count > 0);
1121 }
1122 }
1123
1124 #[test]
1125 fn test_content_characteristics_edge_cases() {
1126 for content in [
1129 "Title\n-",
1130 "Title\n=",
1131 "Title\n--",
1132 "> Title\n> ===",
1133 ">\tTitle\n>\t-",
1134 ">> Title\n>>-",
1135 ] {
1136 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1137 }
1138 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1139 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1140 }
1141
1142 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");
1152 assert!(!chars.has_blockquotes);
1153 }
1154
1155 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";
1161
1162 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1164 let config = crate::config::Config::default();
1165 let rules = crate::rules::all_rules(&config);
1166 let warnings = lint(
1167 content,
1168 &rules,
1169 false,
1170 crate::config::MarkdownFlavor::Standard,
1171 None,
1172 Some(&config),
1173 )
1174 .unwrap();
1175 let mut out = Vec::new();
1176 for warning in warnings {
1177 let Some(fix) = warning.fix else { continue };
1178 let rule = warning.rule_name.clone().unwrap_or_default();
1179 let mut stack = vec![fix];
1180 while let Some(fix) = stack.pop() {
1181 out.push((rule.clone(), fix.replacement.clone()));
1182 stack.extend(fix.additional_edits);
1183 }
1184 }
1185 out
1186 }
1187
1188 fn has_bare_lf(text: &str) -> bool {
1189 let bytes = text.as_bytes();
1190 bytes
1191 .iter()
1192 .enumerate()
1193 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1194 }
1195
1196 #[test]
1197 fn fix_replacements_use_the_documents_crlf_line_ending() {
1198 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1199 let replacements = fix_replacements(&crlf);
1200
1201 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1202 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1203
1204 let mut crlf_rules: Vec<_> = replacements
1207 .iter()
1208 .filter(|(_, r)| r.contains("\r\n"))
1209 .map(|(rule, _)| rule.as_str())
1210 .collect();
1211 crlf_rules.sort_unstable();
1212 crlf_rules.dedup();
1213 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1214 assert!(
1215 crlf_rules.contains(&rule),
1216 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1217 );
1218 }
1219 }
1220
1221 #[test]
1222 fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1223 let lf = fix_replacements(LINE_INSERTING_FIXES);
1225 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1226 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1227
1228 let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1231 assert_eq!(
1232 crate::utils::detect_line_ending_enum(&mixed),
1233 crate::utils::LineEnding::Mixed
1234 );
1235 let mixed = fix_replacements(&mixed);
1236 assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1237 }
1238}