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 embedded_lint;
55pub mod exit_codes;
56pub mod filtered_lines;
57pub mod fix_coordinator;
58pub mod inline_config;
59pub mod linguist_data;
60pub mod lint_context;
61pub mod markdownlint_config;
62pub mod profiling;
63pub mod rule;
64#[cfg(feature = "colored")]
65pub mod vscode;
66pub mod workspace_index;
67#[macro_use]
68pub mod rule_config;
69#[macro_use]
70pub mod rule_config_serde;
71pub mod rules;
72pub mod types;
73pub mod utils;
74
75#[cfg(feature = "native")]
77pub mod lsp;
78#[cfg(feature = "colored")]
79pub mod output;
80#[cfg(feature = "native")]
81pub mod performance;
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 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
139 has_setext_heading = true;
140 }
141
142 if !chars.has_lists
145 && (line.contains("* ")
146 || line.contains("- ")
147 || line.contains("+ ")
148 || trimmed.starts_with("* ")
149 || trimmed.starts_with("- ")
150 || trimmed.starts_with("+ ")
151 || trimmed.starts_with('*')
152 || trimmed.starts_with('-')
153 || trimmed.starts_with('+'))
154 {
155 chars.has_lists = true;
156 }
157 if !chars.has_lists
159 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
160 && (line.contains(". ") || line.contains('.')))
161 || (trimmed.starts_with('>')
162 && trimmed.chars().any(|c| c.is_ascii_digit())
163 && (trimmed.contains(". ") || trimmed.contains('.'))))
164 {
165 chars.has_lists = true;
166 }
167 if !chars.has_links
168 && (line.contains('[')
169 || line.contains("http://")
170 || line.contains("https://")
171 || line.contains("ftp://")
172 || line.contains("www."))
173 {
174 chars.has_links = true;
175 }
176 if !chars.has_images && line.contains("![") {
177 chars.has_images = true;
178 }
179 if !chars.has_code
180 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
181 {
182 chars.has_code = true;
183 }
184 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
185 chars.has_emphasis = true;
186 }
187 if !chars.has_html && line.contains('<') {
188 chars.has_html = true;
189 }
190 if !chars.has_tables && line.contains('|') {
191 chars.has_tables = true;
192 }
193 if !chars.has_blockquotes && line.starts_with('>') {
194 chars.has_blockquotes = true;
195 }
196 }
197
198 chars.has_headings = has_atx_heading || has_setext_heading;
199 chars
200 }
201
202 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
204 match rule.category() {
205 RuleCategory::Heading => !self.has_headings,
206 RuleCategory::List => !self.has_lists,
207 RuleCategory::Link => !self.has_links && !self.has_images,
208 RuleCategory::Image => !self.has_images,
209 RuleCategory::CodeBlock => !self.has_code,
210 RuleCategory::Html => !self.has_html,
211 RuleCategory::Emphasis => !self.has_emphasis,
212 RuleCategory::Blockquote => !self.has_blockquotes,
213 RuleCategory::Table => !self.has_tables,
214 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
216 }
217 }
218}
219
220#[cfg(feature = "native")]
225fn compute_content_hash(content: &str) -> String {
226 #[cfg(feature = "profiling")]
227 let start = std::time::Instant::now();
228 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
229 #[cfg(feature = "profiling")]
230 profiling::record_duration("index: hash content", start.elapsed());
231 hash
232}
233
234#[cfg(not(feature = "native"))]
236fn compute_content_hash(content: &str) -> String {
237 use std::hash::{DefaultHasher, Hash, Hasher};
238 let mut hasher = DefaultHasher::new();
239 content.hash(&mut hasher);
240 format!("{:016x}", hasher.finish())
241}
242
243pub fn lint(
247 content: &str,
248 rules: &[Box<dyn Rule>],
249 verbose: bool,
250 flavor: crate::config::MarkdownFlavor,
251 source_file: Option<std::path::PathBuf>,
252 config: Option<&crate::config::Config>,
253) -> LintResult {
254 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
255 result
256}
257
258pub fn build_file_index_only(
266 content: &str,
267 rules: &[Box<dyn Rule>],
268 flavor: crate::config::MarkdownFlavor,
269 source_file: Option<std::path::PathBuf>,
270) -> crate::workspace_index::FileIndex {
271 let content_hash = compute_content_hash(content);
273 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
274
275 if content.is_empty() {
277 return file_index;
278 }
279
280 let lint_ctx = time_function!(
282 "index: parse lint context",
283 crate::lint_context::LintContext::new(content, flavor, source_file)
284 );
285
286 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
290 file_index.file_disabled_rules = file_disabled;
291 file_index.persistent_transitions = persistent_transitions;
292 file_index.line_disabled_rules = line_disabled;
293
294 time_section!("index: contribute cross-file data", {
296 for rule in rules {
297 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
298 rule.contribute_to_index(&lint_ctx, &mut file_index);
299 }
300 }
301 });
302
303 file_index
304}
305
306#[cfg_attr(test, allow(unused_variables))]
314pub fn lint_and_index(
315 content: &str,
316 rules: &[Box<dyn Rule>],
317 verbose: bool,
318 flavor: crate::config::MarkdownFlavor,
319 source_file: Option<std::path::PathBuf>,
320 config: Option<&crate::config::Config>,
321) -> (LintResult, crate::workspace_index::FileIndex) {
322 let mut warnings = Vec::new();
323 let content_hash = compute_content_hash(content);
325 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
326
327 if content.is_empty() {
329 return (Ok(warnings), file_index);
330 }
331
332 let lint_ctx = time_function!(
334 "lint: parse lint context",
335 crate::lint_context::LintContext::new(content, flavor, source_file)
336 );
337 let inline_config = lint_ctx.inline_config();
338
339 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
341 file_index.file_disabled_rules = file_disabled;
342 file_index.persistent_transitions = persistent_transitions;
343 file_index.line_disabled_rules = line_disabled;
344
345 let characteristics = time_function!(
347 "lint: analyze content characteristics",
348 ContentCharacteristics::analyze(content)
349 );
350
351 let applicable_rules: Vec<_> = rules
353 .iter()
354 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
355 .collect();
356
357 #[cfg(not(test))]
359 let total_rules = rules.len();
360 #[cfg(not(test))]
361 let applicable_count = applicable_rules.len();
362
363 #[cfg(not(target_arch = "wasm32"))]
364 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
365
366 let inline_overrides = inline_config.get_all_rule_configs();
369 let merged_config = if !inline_overrides.is_empty() {
370 config.map(|c| c.merge_with_inline_config(inline_config))
371 } else {
372 None
373 };
374 let effective_config = merged_config.as_ref().or(config);
375
376 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
378 std::collections::HashMap::new();
379
380 if let Some(cfg) = effective_config {
382 for rule_name in inline_overrides.keys() {
383 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
384 recreated_rules.insert(rule_name.clone(), recreated);
385 }
386 }
387 }
388
389 {
390 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
391 for rule in &applicable_rules {
392 #[cfg(not(target_arch = "wasm32"))]
393 let rule_start = Instant::now();
394
395 if rule.should_skip(&lint_ctx) {
397 continue;
398 }
399
400 let effective_rule: &dyn crate::rule::Rule = recreated_rules
402 .get(rule.name())
403 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
404
405 let result = effective_rule.check(&lint_ctx);
407
408 match result {
409 Ok(rule_warnings) => {
410 let filtered_warnings: Vec<_> = rule_warnings
413 .into_iter()
414 .filter(|warning| {
415 if lint_ctx
417 .line_info(warning.line)
418 .is_some_and(|info| info.in_kramdown_extension_block)
419 {
420 return false;
421 }
422
423 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
425
426 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
428 &rule_name_to_check[..dash_pos]
429 } else {
430 rule_name_to_check
431 };
432
433 {
439 let end = if warning.end_line >= warning.line {
440 warning.end_line
441 } else {
442 warning.line
443 };
444 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
445 }
446 })
447 .map(|mut warning| {
448 if let Some(cfg) = config {
450 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
451 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
452 warning.severity = override_severity;
453 }
454 }
455 warning
456 })
457 .collect();
458 warnings.extend(filtered_warnings);
459 }
460 Err(e) => {
461 log::error!("Error checking rule {}: {}", rule.name(), e);
462 return (Err(e), file_index);
463 }
464 }
465
466 #[cfg(not(target_arch = "wasm32"))]
467 {
468 let rule_duration = rule_start.elapsed();
469 if profile_rules {
470 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
471 }
472
473 #[cfg(not(test))]
474 if verbose && rule_duration.as_millis() > 500 {
475 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
476 }
477 }
478 }
479 }
480
481 time_section!("lint: contribute cross-file data", {
488 for rule in rules {
489 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
490 rule.contribute_to_index(&lint_ctx, &mut file_index);
491 }
492 }
493 });
494
495 #[cfg(not(test))]
496 if verbose {
497 let skipped_rules = total_rules - applicable_count;
498 if skipped_rules > 0 {
499 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
500 }
501 }
502
503 (Ok(warnings), file_index)
504}
505
506pub fn run_cross_file_checks(
519 file_path: &std::path::Path,
520 file_index: &crate::workspace_index::FileIndex,
521 rules: &[Box<dyn Rule>],
522 workspace_index: &crate::workspace_index::WorkspaceIndex,
523 config: Option<&crate::config::Config>,
524) -> LintResult {
525 use crate::rule::CrossFileScope;
526
527 let mut warnings = Vec::new();
528
529 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
535
536 for rule in rules {
538 if rule.cross_file_scope() != CrossFileScope::Workspace {
539 continue;
540 }
541
542 if ignored_rules_for_file
543 .as_ref()
544 .is_some_and(|ignored| ignored.contains(rule.name()))
545 {
546 continue;
547 }
548
549 match time_function!(
550 "workspace: cross-file rule check",
551 rule.cross_file_check(file_path, file_index, workspace_index)
552 ) {
553 Ok(rule_warnings) => {
554 let filtered: Vec<_> = rule_warnings
556 .into_iter()
557 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
558 .map(|mut warning| {
559 if let Some(cfg) = config
561 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
562 {
563 warning.severity = override_severity;
564 }
565 warning
566 })
567 .collect();
568 warnings.extend(filtered);
569 }
570 Err(e) => {
571 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
572 return Err(e);
573 }
574 }
575 }
576
577 Ok(warnings)
578}
579
580pub fn get_profiling_report() -> String {
582 profiling::get_report()
583}
584
585pub fn reset_profiling() {
587 profiling::reset()
588}
589
590pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
592 crate::utils::regex_cache::get_cache_stats()
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 use crate::rule::Rule;
599 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
600
601 #[test]
602 fn test_content_characteristics_analyze() {
603 let chars = ContentCharacteristics::analyze("");
605 assert!(!chars.has_headings);
606 assert!(!chars.has_lists);
607 assert!(!chars.has_links);
608 assert!(!chars.has_code);
609 assert!(!chars.has_emphasis);
610 assert!(!chars.has_html);
611 assert!(!chars.has_tables);
612 assert!(!chars.has_blockquotes);
613 assert!(!chars.has_images);
614
615 let chars = ContentCharacteristics::analyze("# Heading");
617 assert!(chars.has_headings);
618
619 let chars = ContentCharacteristics::analyze("Heading\n=======");
621 assert!(chars.has_headings);
622
623 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
626 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
627 let chars = ContentCharacteristics::analyze(">> # Nested");
628 assert!(
629 chars.has_headings,
630 "nested-blockquote ATX heading must set has_headings"
631 );
632 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
635 assert!(
636 chars.has_headings,
637 "tab-separated blockquote ATX heading must set has_headings"
638 );
639
640 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
642 assert!(chars.has_lists);
643
644 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
646 assert!(chars.has_lists);
647
648 let chars = ContentCharacteristics::analyze("[link](url)");
650 assert!(chars.has_links);
651
652 let chars = ContentCharacteristics::analyze("Visit https://example.com");
654 assert!(chars.has_links);
655
656 let chars = ContentCharacteristics::analyze("");
658 assert!(chars.has_images);
659
660 let chars = ContentCharacteristics::analyze("`inline code`");
662 assert!(chars.has_code);
663
664 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
665 assert!(chars.has_code);
666
667 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
669 assert!(chars.has_code);
670
671 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
673 assert!(chars.has_code);
674
675 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
677 assert!(chars.has_code);
678
679 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
681 assert!(chars.has_code);
682
683 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
685 assert!(chars.has_emphasis);
686
687 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
689 assert!(chars.has_html);
690
691 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
693 assert!(chars.has_tables);
694
695 let chars = ContentCharacteristics::analyze("> Quote");
697 assert!(chars.has_blockquotes);
698
699 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
701 let chars = ContentCharacteristics::analyze(content);
702 assert!(chars.has_headings);
703 assert!(chars.has_lists);
704 assert!(chars.has_links);
705 assert!(chars.has_code);
706 assert!(chars.has_emphasis);
707 assert!(chars.has_html);
708 assert!(chars.has_tables);
709 assert!(chars.has_blockquotes);
710 assert!(chars.has_images);
711 }
712
713 #[test]
714 fn test_content_characteristics_should_skip_rule() {
715 let chars = ContentCharacteristics {
716 has_headings: true,
717 has_lists: false,
718 has_links: true,
719 has_code: false,
720 has_emphasis: true,
721 has_html: false,
722 has_tables: true,
723 has_blockquotes: false,
724 has_images: false,
725 };
726
727 let heading_rule = MD001HeadingIncrement::default();
729 assert!(!chars.should_skip_rule(&heading_rule));
730
731 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
732 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
736 has_headings: false,
737 ..Default::default()
738 };
739 assert!(chars_no_headings.should_skip_rule(&heading_rule));
740 }
741
742 #[test]
743 fn test_lint_empty_content() {
744 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
745
746 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
747 assert!(result.is_ok());
748 assert!(result.unwrap().is_empty());
749 }
750
751 #[test]
752 fn test_lint_with_violations() {
753 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
755
756 let result = lint(
757 content,
758 &rules,
759 false,
760 crate::config::MarkdownFlavor::Standard,
761 None,
762 None,
763 );
764 assert!(result.is_ok());
765 let warnings = result.unwrap();
766 assert!(!warnings.is_empty());
767 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
769 }
770
771 #[test]
772 fn test_lint_with_inline_disable() {
773 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
774 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
775
776 let result = lint(
777 content,
778 &rules,
779 false,
780 crate::config::MarkdownFlavor::Standard,
781 None,
782 None,
783 );
784 assert!(result.is_ok());
785 let warnings = result.unwrap();
786 assert!(warnings.is_empty()); }
788
789 #[test]
790 fn test_lint_rule_filtering() {
791 let content = "# Heading\nJust text";
793 let rules: Vec<Box<dyn Rule>> = vec![
794 Box::new(MD001HeadingIncrement::default()),
795 ];
797
798 let result = lint(
799 content,
800 &rules,
801 false,
802 crate::config::MarkdownFlavor::Standard,
803 None,
804 None,
805 );
806 assert!(result.is_ok());
807 }
808
809 #[test]
810 fn test_get_profiling_report() {
811 let report = get_profiling_report();
813 assert!(!report.is_empty());
814 assert!(report.contains("Profiling"));
815 }
816
817 #[test]
818 fn test_reset_profiling() {
819 reset_profiling();
821
822 let report = get_profiling_report();
824 assert!(report.contains("disabled") || report.contains("no measurements"));
825 }
826
827 #[test]
828 fn test_get_regex_cache_stats() {
829 let stats = get_regex_cache_stats();
830 assert!(stats.is_empty() || !stats.is_empty());
832
833 for count in stats.values() {
835 assert!(*count > 0);
836 }
837 }
838
839 #[test]
840 fn test_content_characteristics_edge_cases() {
841 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
844
845 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
847
848 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");
858 assert!(!chars.has_blockquotes);
859 }
860}