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') {
373 return;
374 }
375 let mixed = match crate::utils::detect_line_ending_enum(content) {
376 crate::utils::LineEnding::Lf => return,
377 crate::utils::LineEnding::Crlf => false,
378 crate::utils::LineEnding::Mixed => true,
379 };
380 fn conform(content: &str, mixed: bool, fix: &mut crate::rule::Fix) {
381 if fix.replacement.contains('\n')
382 && (!mixed || crate::utils::line_ending_before(content, fix.range.start) == "\r\n")
383 {
384 fix.replacement =
385 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
386 }
387 for extra in &mut fix.additional_edits {
388 conform(content, mixed, extra);
389 }
390 }
391 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
392 conform(content, mixed, fix);
393 }
394}
395
396pub(crate) fn retain_reportable_warnings(
404 lint_ctx: &crate::lint_context::LintContext,
405 config: Option<&crate::config::Config>,
406 rule_name: &str,
407 rule_warnings: Vec<crate::rule::LintWarning>,
408 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
409) -> Vec<crate::rule::LintWarning> {
410 let inline_config = lint_ctx.inline_config();
411 let mut kept = Vec::with_capacity(rule_warnings.len());
412
413 for mut warning in rule_warnings {
414 if lint_ctx
415 .line_info(warning.line)
416 .is_some_and(|info| info.in_kramdown_extension_block)
417 {
418 continue;
419 }
420
421 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
423
424 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
426 &rule_name_to_check[..dash_pos]
427 } else {
428 rule_name_to_check
429 };
430
431 let end = if warning.end_line >= warning.line {
437 warning.end_line
438 } else {
439 warning.line
440 };
441 let disabled_at = (warning.line..=end).find_map(|line| {
442 inline_config
443 .disabling_layer(base_rule_name, line)
444 .map(|layer| (line, layer))
445 });
446 if let Some((line, layer)) = disabled_at {
447 if let Some(record) = suppressed.as_deref_mut() {
448 record.push(crate::rule::SuppressedWarning {
449 rule_name: base_rule_name.to_string(),
450 line,
451 layer,
452 });
453 }
454 continue;
455 }
456
457 if let Some(cfg) = config
459 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
460 {
461 warning.severity = override_severity;
462 }
463
464 kept.push(warning);
465 }
466
467 kept
468}
469
470#[cfg_attr(test, allow(unused_variables))]
478#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
480 content: &str,
481 rules: &[Box<dyn Rule>],
482 verbose: bool,
483 flavor: crate::config::MarkdownFlavor,
484 source_file: Option<std::path::PathBuf>,
485 config: Option<&crate::config::Config>,
486) -> (LintResult, crate::workspace_index::FileIndex) {
487 lint_and_index_with_paths(
488 content,
489 rules,
490 verbose,
491 flavor,
492 DocumentPaths::same(source_file.as_deref()),
493 config,
494 )
495}
496
497#[derive(Debug, Clone, Copy, Default)]
499pub struct DocumentPaths<'a> {
500 pub config_path: Option<&'a std::path::Path>,
502 pub source_file: Option<&'a std::path::Path>,
504 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
506 pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
508}
509
510impl<'a> DocumentPaths<'a> {
511 pub fn same(path: Option<&'a std::path::Path>) -> Self {
513 Self {
514 config_path: path,
515 source_file: path,
516 link_target_policy: None,
517 invalid_utf8: None,
518 }
519 }
520}
521
522#[cfg_attr(test, allow(unused_variables))]
529pub fn lint_and_index_with_paths(
530 content: &str,
531 rules: &[Box<dyn Rule>],
532 verbose: bool,
533 flavor: crate::config::MarkdownFlavor,
534 paths: DocumentPaths<'_>,
535 config: Option<&crate::config::Config>,
536) -> (LintResult, crate::workspace_index::FileIndex) {
537 let mut warnings = Vec::new();
538 let content_hash = compute_content_hash(content);
540 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
541
542 let conflict = config.map_or_else(
543 || {
544 crate::merge_conflict::detect_for_rules(
545 content,
546 rules,
547 &crate::config::Config::default(),
548 paths.config_path,
549 )
550 },
551 |config| crate::merge_conflict::detect_for_rules(content, rules, config, paths.config_path),
552 );
553 if let Some(conflict) = conflict {
554 return (Ok(vec![conflict]), file_index);
555 }
556
557 if content.is_empty() {
559 return (Ok(warnings), file_index);
560 }
561
562 let ignored_for_file = match (config, paths.config_path) {
569 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
570 _ => std::collections::HashSet::new(),
571 };
572
573 let lint_ctx = time_function!(
575 "lint: parse lint context",
576 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
577 );
578 let lint_ctx = match paths.link_target_policy {
579 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
580 None => lint_ctx,
581 };
582 let lint_ctx = match paths.invalid_utf8 {
583 Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
584 None => lint_ctx,
585 };
586 let inline_config = lint_ctx.inline_config();
587
588 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
590 file_index.file_disabled_rules = file_disabled;
591 file_index.persistent_transitions = persistent_transitions;
592 file_index.line_disabled_rules = line_disabled;
593
594 let characteristics = time_function!(
596 "lint: analyze content characteristics",
597 ContentCharacteristics::analyze(content)
598 );
599
600 let applicable_rules: Vec<_> = rules
602 .iter()
603 .filter(|rule| !ignored_for_file.contains(rule.name()))
604 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
605 .collect();
606
607 #[cfg(not(test))]
609 let total_rules = rules.len();
610 #[cfg(not(test))]
611 let applicable_count = applicable_rules.len();
612
613 #[cfg(not(target_arch = "wasm32"))]
614 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
615
616 let inline_overrides = inline_config.get_all_rule_configs();
619 let merged_config = if !inline_overrides.is_empty() {
620 config.map(|c| c.merge_with_inline_config(inline_config))
621 } else {
622 None
623 };
624 let effective_config = merged_config.as_ref().or(config);
625
626 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
628 std::collections::HashMap::new();
629
630 if let Some(cfg) = effective_config {
632 for rule_name in inline_overrides.keys() {
633 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
634 recreated_rules.insert(rule_name.clone(), recreated);
635 }
636 }
637 }
638
639 let suppression_observers: Vec<_> = applicable_rules
643 .iter()
644 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
645 .collect();
646 let mut suppressed = Vec::new();
647
648 {
649 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
650 for rule in &applicable_rules {
651 #[cfg(not(target_arch = "wasm32"))]
652 let rule_start = Instant::now();
653
654 if rule.should_skip(&lint_ctx) {
656 continue;
657 }
658
659 let effective_rule: &dyn crate::rule::Rule = recreated_rules
661 .get(rule.name())
662 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
663
664 let result = effective_rule.check(&lint_ctx);
666
667 match result {
668 Ok(rule_warnings) => {
669 let record = if suppression_observers.is_empty() {
670 None
671 } else {
672 Some(&mut suppressed)
673 };
674 let filtered_warnings =
675 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
676 warnings.extend(filtered_warnings);
677 }
678 Err(e) => {
679 log::error!("Error checking rule {}: {}", rule.name(), e);
680 return (Err(e), file_index);
681 }
682 }
683
684 #[cfg(not(target_arch = "wasm32"))]
685 {
686 let rule_duration = rule_start.elapsed();
687 if profile_rules {
688 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
689 }
690
691 #[cfg(not(test))]
692 if verbose && rule_duration.as_millis() > 500 {
693 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
694 }
695 }
696 }
697 }
698
699 if !suppression_observers.is_empty() {
702 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
703
704 let report = crate::rule::SuppressionReport {
709 suppressed,
710 judged_rules: rules
711 .iter()
712 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
713 .filter(|rule| !ignored_for_file.contains(rule.name()))
714 .map(|rule| rule.name().to_string())
715 .collect(),
716 };
717
718 for rule in &suppression_observers {
719 match rule.check_suppressions(&lint_ctx, &report) {
720 Ok(rule_warnings) => {
721 let filtered_warnings =
722 retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
723 warnings.extend(filtered_warnings);
724 }
725 Err(e) => {
726 log::error!("Error checking rule {}: {}", rule.name(), e);
727 return (Err(e), file_index);
728 }
729 }
730 }
731 }
732
733 time_section!("lint: contribute cross-file data", {
741 for rule in rules {
742 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
743 rule.contribute_to_index(&lint_ctx, &mut file_index);
744 }
745 }
746 });
747
748 #[cfg(not(test))]
749 if verbose {
750 let skipped_rules = total_rules - applicable_count;
751 if skipped_rules > 0 {
752 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
753 }
754 }
755
756 if paths.invalid_utf8.is_some() {
757 crate::encoding::settle_lossy_warnings(&mut warnings);
758 }
759
760 conform_fix_line_endings(content, &mut warnings);
761
762 (Ok(warnings), file_index)
763}
764
765pub fn run_cross_file_checks(
778 file_path: &std::path::Path,
779 file_index: &crate::workspace_index::FileIndex,
780 rules: &[Box<dyn Rule>],
781 workspace_index: &crate::workspace_index::WorkspaceIndex,
782 config: Option<&crate::config::Config>,
783) -> LintResult {
784 use crate::rule::CrossFileScope;
785
786 let mut warnings = Vec::new();
787
788 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
794
795 for rule in rules {
797 if rule.cross_file_scope() != CrossFileScope::Workspace {
798 continue;
799 }
800
801 if ignored_rules_for_file
802 .as_ref()
803 .is_some_and(|ignored| ignored.contains(rule.name()))
804 {
805 continue;
806 }
807
808 match time_function!(
809 "workspace: cross-file rule check",
810 rule.cross_file_check(file_path, file_index, workspace_index)
811 ) {
812 Ok(rule_warnings) => {
813 let filtered: Vec<_> = rule_warnings
815 .into_iter()
816 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
817 .map(|mut warning| {
818 if let Some(cfg) = config
820 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
821 {
822 warning.severity = override_severity;
823 }
824 warning
825 })
826 .collect();
827 warnings.extend(filtered);
828 }
829 Err(e) => {
830 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
831 return Err(e);
832 }
833 }
834 }
835
836 Ok(warnings)
837}
838
839pub fn get_profiling_report() -> String {
841 profiling::get_report()
842}
843
844pub fn reset_profiling() {
846 profiling::reset()
847}
848
849pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
851 crate::utils::regex_cache::get_cache_stats()
852}
853
854#[cfg(test)]
855mod tests {
856 use super::*;
857 use crate::rule::Rule;
858 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
859
860 #[test]
861 fn test_content_characteristics_analyze() {
862 let chars = ContentCharacteristics::analyze("");
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 let chars = ContentCharacteristics::analyze("# Heading");
876 assert!(chars.has_headings);
877
878 let chars = ContentCharacteristics::analyze("Heading\n=======");
880 assert!(chars.has_headings);
881
882 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
885 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
886 let chars = ContentCharacteristics::analyze(">> # Nested");
887 assert!(
888 chars.has_headings,
889 "nested-blockquote ATX heading must set has_headings"
890 );
891 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
894 assert!(
895 chars.has_headings,
896 "tab-separated blockquote ATX heading must set has_headings"
897 );
898
899 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
901 assert!(chars.has_lists);
902
903 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
905 assert!(chars.has_lists);
906
907 let chars = ContentCharacteristics::analyze("[link](url)");
909 assert!(chars.has_links);
910
911 let chars = ContentCharacteristics::analyze("Visit https://example.com");
913 assert!(chars.has_links);
914
915 let chars = ContentCharacteristics::analyze("");
917 assert!(chars.has_images);
918
919 let chars = ContentCharacteristics::analyze("`inline code`");
921 assert!(chars.has_code);
922
923 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
924 assert!(chars.has_code);
925
926 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
928 assert!(chars.has_code);
929
930 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
932 assert!(chars.has_code);
933
934 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
936 assert!(chars.has_code);
937
938 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
940 assert!(chars.has_code);
941
942 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
944 assert!(chars.has_emphasis);
945
946 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
948 assert!(chars.has_html);
949
950 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
952 assert!(chars.has_tables);
953
954 let chars = ContentCharacteristics::analyze("> Quote");
956 assert!(chars.has_blockquotes);
957
958 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
960 let chars = ContentCharacteristics::analyze(content);
961 assert!(chars.has_headings);
962 assert!(chars.has_lists);
963 assert!(chars.has_links);
964 assert!(chars.has_code);
965 assert!(chars.has_emphasis);
966 assert!(chars.has_html);
967 assert!(chars.has_tables);
968 assert!(chars.has_blockquotes);
969 assert!(chars.has_images);
970 }
971
972 #[test]
973 fn test_content_characteristics_parenthesized_ordered_list() {
974 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
975 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
976 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
977 }
978
979 #[test]
980 fn test_content_characteristics_should_skip_rule() {
981 let chars = ContentCharacteristics {
982 has_headings: true,
983 has_lists: false,
984 has_links: true,
985 has_code: false,
986 has_emphasis: true,
987 has_html: false,
988 has_tables: true,
989 has_blockquotes: false,
990 has_images: false,
991 };
992
993 let heading_rule = MD001HeadingIncrement::default();
995 assert!(!chars.should_skip_rule(&heading_rule));
996
997 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
998 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
1002 has_headings: false,
1003 ..Default::default()
1004 };
1005 assert!(chars_no_headings.should_skip_rule(&heading_rule));
1006 }
1007
1008 #[test]
1009 fn test_lint_empty_content() {
1010 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1011
1012 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1013 assert!(result.is_ok());
1014 assert!(result.unwrap().is_empty());
1015 }
1016
1017 #[test]
1018 fn test_lint_with_violations() {
1019 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1021
1022 let result = lint(
1023 content,
1024 &rules,
1025 false,
1026 crate::config::MarkdownFlavor::Standard,
1027 None,
1028 None,
1029 );
1030 assert!(result.is_ok());
1031 let warnings = result.unwrap();
1032 assert!(!warnings.is_empty());
1033 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1035 }
1036
1037 #[test]
1038 fn test_lint_with_inline_disable() {
1039 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1040 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1041
1042 let result = lint(
1043 content,
1044 &rules,
1045 false,
1046 crate::config::MarkdownFlavor::Standard,
1047 None,
1048 None,
1049 );
1050 assert!(result.is_ok());
1051 let warnings = result.unwrap();
1052 assert!(warnings.is_empty()); }
1054
1055 #[test]
1056 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1057 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1061 for content in [
1062 "Title\n-\n\ntitle\n-\n",
1063 "Title\n=\n\ntitle\n=\n",
1064 "> Title\n> ===\n\n> title\n> ===\n",
1065 "> Title\n> -\n\n> title\n> -\n",
1066 ] {
1067 let warnings = lint(
1068 content,
1069 &rules,
1070 false,
1071 crate::config::MarkdownFlavor::Standard,
1072 None,
1073 None,
1074 )
1075 .unwrap();
1076 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1077 assert_eq!(lines, [4], "{content:?}");
1078 }
1079 }
1080
1081 #[test]
1082 fn test_lint_rule_filtering() {
1083 let content = "# Heading\nJust text";
1085 let rules: Vec<Box<dyn Rule>> = vec![
1086 Box::new(MD001HeadingIncrement::default()),
1087 ];
1089
1090 let result = lint(
1091 content,
1092 &rules,
1093 false,
1094 crate::config::MarkdownFlavor::Standard,
1095 None,
1096 None,
1097 );
1098 assert!(result.is_ok());
1099 }
1100
1101 #[test]
1102 fn test_get_profiling_report() {
1103 let report = get_profiling_report();
1105 assert!(!report.is_empty());
1106 assert!(report.contains("Profiling"));
1107 }
1108
1109 #[test]
1110 fn test_reset_profiling() {
1111 reset_profiling();
1113
1114 let report = get_profiling_report();
1116 assert!(report.contains("disabled") || report.contains("no measurements"));
1117 }
1118
1119 #[test]
1120 fn test_get_regex_cache_stats() {
1121 let stats = get_regex_cache_stats();
1122 assert!(stats.is_empty() || !stats.is_empty());
1124
1125 for count in stats.values() {
1127 assert!(*count > 0);
1128 }
1129 }
1130
1131 #[test]
1132 fn test_content_characteristics_edge_cases() {
1133 for content in [
1136 "Title\n-",
1137 "Title\n=",
1138 "Title\n--",
1139 "> Title\n> ===",
1140 ">\tTitle\n>\t-",
1141 ">> Title\n>>-",
1142 ] {
1143 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1144 }
1145 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1146 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1147 }
1148
1149 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");
1159 assert!(!chars.has_blockquotes);
1160 }
1161
1162 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";
1168
1169 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1171 let config = crate::config::Config::default();
1172 let rules = crate::rules::all_rules(&config);
1173 let warnings = lint(
1174 content,
1175 &rules,
1176 false,
1177 crate::config::MarkdownFlavor::Standard,
1178 None,
1179 Some(&config),
1180 )
1181 .unwrap();
1182 let mut out = Vec::new();
1183 for warning in warnings {
1184 let Some(fix) = warning.fix else { continue };
1185 let rule = warning.rule_name.clone().unwrap_or_default();
1186 let mut stack = vec![fix];
1187 while let Some(fix) = stack.pop() {
1188 out.push((rule.clone(), fix.replacement.clone()));
1189 stack.extend(fix.additional_edits);
1190 }
1191 }
1192 out
1193 }
1194
1195 fn has_bare_lf(text: &str) -> bool {
1196 let bytes = text.as_bytes();
1197 bytes
1198 .iter()
1199 .enumerate()
1200 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1201 }
1202
1203 #[test]
1204 fn fix_replacements_use_the_documents_crlf_line_ending() {
1205 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1206 let replacements = fix_replacements(&crlf);
1207
1208 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1209 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1210
1211 let mut crlf_rules: Vec<_> = replacements
1214 .iter()
1215 .filter(|(_, r)| r.contains("\r\n"))
1216 .map(|(rule, _)| rule.as_str())
1217 .collect();
1218 crlf_rules.sort_unstable();
1219 crlf_rules.dedup();
1220 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1221 assert!(
1222 crlf_rules.contains(&rule),
1223 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1224 );
1225 }
1226 }
1227
1228 #[test]
1229 fn fix_replacements_stay_lf_for_lf_documents() {
1230 let lf = fix_replacements(LINE_INSERTING_FIXES);
1232 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1233 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1234 }
1235
1236 #[test]
1237 fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1238 let mixed: String = LINE_INSERTING_FIXES
1240 .split_inclusive('\n')
1241 .enumerate()
1242 .map(|(i, line)| {
1243 if i % 2 == 0 {
1244 line.replace('\n', "\r\n")
1245 } else {
1246 line.to_string()
1247 }
1248 })
1249 .collect();
1250 assert_eq!(
1251 crate::utils::detect_line_ending_enum(&mixed),
1252 crate::utils::LineEnding::Mixed
1253 );
1254
1255 let ending_before = |offset: usize| {
1257 let target = offset.saturating_sub(1);
1258 let mut start = 0;
1259 let mut last_ending = "\n";
1260 for line in mixed.split_inclusive('\n') {
1261 let ending = if line.ends_with("\r\n") {
1262 "\r\n"
1263 } else if line.ends_with('\n') {
1264 "\n"
1265 } else {
1266 last_ending
1267 };
1268 if target < start + line.len() {
1269 return ending;
1270 }
1271 last_ending = ending;
1272 start += line.len();
1273 }
1274 last_ending
1275 };
1276
1277 let config = crate::config::Config::default();
1278 let rules = crate::rules::all_rules(&config);
1279 let warnings = lint(
1280 &mixed,
1281 &rules,
1282 false,
1283 crate::config::MarkdownFlavor::Standard,
1284 None,
1285 Some(&config),
1286 )
1287 .unwrap();
1288 let mut seen = [false, false];
1289 let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1290 while let Some(fix) = stack.pop() {
1291 if fix.replacement.contains('\n') {
1292 let crlf = ending_before(fix.range.start) == "\r\n";
1293 seen[usize::from(crlf)] = true;
1294 assert_eq!(
1295 has_bare_lf(&fix.replacement),
1296 !crlf,
1297 "replacement {:?} at {} in {mixed:?}",
1298 fix.replacement,
1299 fix.range.start
1300 );
1301 }
1302 stack.extend(fix.additional_edits);
1303 }
1304 assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1305 }
1306}