1pub mod code_block_tools;
2pub mod config;
3pub mod doc_comment_lint;
4pub mod embedded_lint;
5pub mod exit_codes;
6pub mod filtered_lines;
7pub mod fix_coordinator;
8pub mod inline_config;
9pub mod linguist_data;
10pub mod lint_context;
11pub mod markdownlint_config;
12pub mod profiling;
13pub mod rule;
14#[cfg(feature = "native")]
15pub mod vscode;
16pub mod workspace_index;
17#[macro_use]
18pub mod rule_config;
19#[macro_use]
20pub mod rule_config_serde;
21pub mod rules;
22pub mod types;
23pub mod utils;
24
25#[cfg(feature = "native")]
27pub mod lsp;
28#[cfg(feature = "native")]
29pub mod output;
30#[cfg(feature = "native")]
31pub mod parallel;
32#[cfg(feature = "native")]
33pub mod performance;
34
35#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
37pub mod wasm;
38
39pub use rules::heading_utils::{Heading, HeadingStyle};
40pub use rules::*;
41
42pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
43use crate::rule::{LintResult, Rule, RuleCategory};
44use crate::utils::element_cache::ElementCache;
45#[cfg(not(target_arch = "wasm32"))]
46use std::time::Instant;
47
48#[derive(Debug, Default)]
50struct ContentCharacteristics {
51 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, }
61
62fn has_potential_indented_code_indent(line: &str) -> bool {
65 ElementCache::calculate_indentation_width_default(line) >= 4
66}
67
68impl ContentCharacteristics {
69 fn analyze(content: &str) -> Self {
70 let mut chars = Self { ..Default::default() };
71
72 let mut has_atx_heading = false;
74 let mut has_setext_heading = false;
75
76 for line in content.lines() {
77 let trimmed = line.trim();
78
79 if !has_atx_heading && trimmed.starts_with('#') {
81 has_atx_heading = true;
82 }
83 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
84 has_setext_heading = true;
85 }
86
87 if !chars.has_lists
90 && (line.contains("* ")
91 || line.contains("- ")
92 || line.contains("+ ")
93 || trimmed.starts_with("* ")
94 || trimmed.starts_with("- ")
95 || trimmed.starts_with("+ ")
96 || trimmed.starts_with('*')
97 || trimmed.starts_with('-')
98 || trimmed.starts_with('+'))
99 {
100 chars.has_lists = true;
101 }
102 if !chars.has_lists
104 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
105 && (line.contains(". ") || line.contains('.')))
106 || (trimmed.starts_with('>')
107 && trimmed.chars().any(|c| c.is_ascii_digit())
108 && (trimmed.contains(". ") || trimmed.contains('.'))))
109 {
110 chars.has_lists = true;
111 }
112 if !chars.has_links
113 && (line.contains('[')
114 || line.contains("http://")
115 || line.contains("https://")
116 || line.contains("ftp://")
117 || line.contains("www."))
118 {
119 chars.has_links = true;
120 }
121 if !chars.has_images && line.contains("![") {
122 chars.has_images = true;
123 }
124 if !chars.has_code
125 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
126 {
127 chars.has_code = true;
128 }
129 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
130 chars.has_emphasis = true;
131 }
132 if !chars.has_html && line.contains('<') {
133 chars.has_html = true;
134 }
135 if !chars.has_tables && line.contains('|') {
136 chars.has_tables = true;
137 }
138 if !chars.has_blockquotes && line.starts_with('>') {
139 chars.has_blockquotes = true;
140 }
141 }
142
143 chars.has_headings = has_atx_heading || has_setext_heading;
144 chars
145 }
146
147 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
149 match rule.category() {
150 RuleCategory::Heading => !self.has_headings,
151 RuleCategory::List => !self.has_lists,
152 RuleCategory::Link => !self.has_links && !self.has_images,
153 RuleCategory::Image => !self.has_images,
154 RuleCategory::CodeBlock => !self.has_code,
155 RuleCategory::Html => !self.has_html,
156 RuleCategory::Emphasis => !self.has_emphasis,
157 RuleCategory::Blockquote => !self.has_blockquotes,
158 RuleCategory::Table => !self.has_tables,
159 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
161 }
162 }
163}
164
165#[cfg(feature = "native")]
170fn compute_content_hash(content: &str) -> String {
171 blake3::hash(content.as_bytes()).to_hex().to_string()
172}
173
174#[cfg(not(feature = "native"))]
176fn compute_content_hash(content: &str) -> String {
177 use std::hash::{DefaultHasher, Hash, Hasher};
178 let mut hasher = DefaultHasher::new();
179 content.hash(&mut hasher);
180 format!("{:016x}", hasher.finish())
181}
182
183pub fn lint(
187 content: &str,
188 rules: &[Box<dyn Rule>],
189 verbose: bool,
190 flavor: crate::config::MarkdownFlavor,
191 config: Option<&crate::config::Config>,
192) -> LintResult {
193 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
195 result
196}
197
198pub fn build_file_index_only(
206 content: &str,
207 rules: &[Box<dyn Rule>],
208 flavor: crate::config::MarkdownFlavor,
209) -> crate::workspace_index::FileIndex {
210 let content_hash = compute_content_hash(content);
212 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
213
214 if content.is_empty() {
216 return file_index;
217 }
218
219 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
221
222 for rule in rules {
224 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
225 rule.contribute_to_index(&lint_ctx, &mut file_index);
226 }
227 }
228
229 file_index
230}
231
232pub fn lint_and_index(
240 content: &str,
241 rules: &[Box<dyn Rule>],
242 _verbose: bool,
243 flavor: crate::config::MarkdownFlavor,
244 source_file: Option<std::path::PathBuf>,
245 config: Option<&crate::config::Config>,
246) -> (LintResult, crate::workspace_index::FileIndex) {
247 let mut warnings = Vec::new();
248 let content_hash = compute_content_hash(content);
250 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
251
252 #[cfg(not(target_arch = "wasm32"))]
253 let _overall_start = Instant::now();
254
255 if content.is_empty() {
257 return (Ok(warnings), file_index);
258 }
259
260 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
262 let inline_config = lint_ctx.inline_config();
263
264 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
266 file_index.file_disabled_rules = file_disabled;
267 file_index.persistent_transitions = persistent_transitions;
268 file_index.line_disabled_rules = line_disabled;
269
270 let characteristics = ContentCharacteristics::analyze(content);
272
273 let applicable_rules: Vec<_> = rules
275 .iter()
276 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
277 .collect();
278
279 let _total_rules = rules.len();
281 let _applicable_count = applicable_rules.len();
282
283 #[cfg(not(target_arch = "wasm32"))]
284 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
285 #[cfg(target_arch = "wasm32")]
286 let profile_rules = false;
287
288 let inline_overrides = inline_config.get_all_rule_configs();
291 let merged_config = if !inline_overrides.is_empty() {
292 config.map(|c| c.merge_with_inline_config(inline_config))
293 } else {
294 None
295 };
296 let effective_config = merged_config.as_ref().or(config);
297
298 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
300 std::collections::HashMap::new();
301
302 if let Some(cfg) = effective_config {
304 for rule_name in inline_overrides.keys() {
305 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
306 recreated_rules.insert(rule_name.clone(), recreated);
307 }
308 }
309 }
310
311 for rule in &applicable_rules {
312 #[cfg(not(target_arch = "wasm32"))]
313 let _rule_start = Instant::now();
314
315 if rule.should_skip(&lint_ctx) {
317 continue;
318 }
319
320 let effective_rule: &dyn crate::rule::Rule = recreated_rules
322 .get(rule.name())
323 .map(|r| r.as_ref())
324 .unwrap_or(rule.as_ref());
325
326 let result = effective_rule.check(&lint_ctx);
328
329 match result {
330 Ok(rule_warnings) => {
331 let filtered_warnings: Vec<_> = rule_warnings
334 .into_iter()
335 .filter(|warning| {
336 if lint_ctx
338 .line_info(warning.line)
339 .is_some_and(|info| info.in_kramdown_extension_block)
340 {
341 return false;
342 }
343
344 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
346
347 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
349 &rule_name_to_check[..dash_pos]
350 } else {
351 rule_name_to_check
352 };
353
354 {
360 let end = if warning.end_line >= warning.line {
361 warning.end_line
362 } else {
363 warning.line
364 };
365 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
366 }
367 })
368 .map(|mut warning| {
369 if let Some(cfg) = config {
371 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
372 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
373 warning.severity = override_severity;
374 }
375 }
376 warning
377 })
378 .collect();
379 warnings.extend(filtered_warnings);
380 }
381 Err(e) => {
382 log::error!("Error checking rule {}: {}", rule.name(), e);
383 return (Err(e), file_index);
384 }
385 }
386
387 #[cfg(not(target_arch = "wasm32"))]
388 {
389 let rule_duration = _rule_start.elapsed();
390 if profile_rules {
391 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
392 }
393
394 #[cfg(not(test))]
395 if _verbose && rule_duration.as_millis() > 500 {
396 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
397 }
398 }
399 }
400
401 for rule in rules {
408 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
409 rule.contribute_to_index(&lint_ctx, &mut file_index);
410 }
411 }
412
413 #[cfg(not(test))]
414 if _verbose {
415 let skipped_rules = _total_rules - _applicable_count;
416 if skipped_rules > 0 {
417 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
418 }
419 }
420
421 (Ok(warnings), file_index)
422}
423
424pub fn run_cross_file_checks(
437 file_path: &std::path::Path,
438 file_index: &crate::workspace_index::FileIndex,
439 rules: &[Box<dyn Rule>],
440 workspace_index: &crate::workspace_index::WorkspaceIndex,
441 config: Option<&crate::config::Config>,
442) -> LintResult {
443 use crate::rule::CrossFileScope;
444
445 let mut warnings = Vec::new();
446
447 for rule in rules {
449 if rule.cross_file_scope() != CrossFileScope::Workspace {
450 continue;
451 }
452
453 match rule.cross_file_check(file_path, file_index, workspace_index) {
454 Ok(rule_warnings) => {
455 let filtered: Vec<_> = rule_warnings
457 .into_iter()
458 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
459 .map(|mut warning| {
460 if let Some(cfg) = config
462 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
463 {
464 warning.severity = override_severity;
465 }
466 warning
467 })
468 .collect();
469 warnings.extend(filtered);
470 }
471 Err(e) => {
472 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
473 return Err(e);
474 }
475 }
476 }
477
478 Ok(warnings)
479}
480
481pub fn get_profiling_report() -> String {
483 profiling::get_report()
484}
485
486pub fn reset_profiling() {
488 profiling::reset()
489}
490
491pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
493 crate::utils::regex_cache::get_cache_stats()
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499 use crate::rule::Rule;
500 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
501
502 #[test]
503 fn test_content_characteristics_analyze() {
504 let chars = ContentCharacteristics::analyze("");
506 assert!(!chars.has_headings);
507 assert!(!chars.has_lists);
508 assert!(!chars.has_links);
509 assert!(!chars.has_code);
510 assert!(!chars.has_emphasis);
511 assert!(!chars.has_html);
512 assert!(!chars.has_tables);
513 assert!(!chars.has_blockquotes);
514 assert!(!chars.has_images);
515
516 let chars = ContentCharacteristics::analyze("# Heading");
518 assert!(chars.has_headings);
519
520 let chars = ContentCharacteristics::analyze("Heading\n=======");
522 assert!(chars.has_headings);
523
524 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
526 assert!(chars.has_lists);
527
528 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
530 assert!(chars.has_lists);
531
532 let chars = ContentCharacteristics::analyze("[link](url)");
534 assert!(chars.has_links);
535
536 let chars = ContentCharacteristics::analyze("Visit https://example.com");
538 assert!(chars.has_links);
539
540 let chars = ContentCharacteristics::analyze("");
542 assert!(chars.has_images);
543
544 let chars = ContentCharacteristics::analyze("`inline code`");
546 assert!(chars.has_code);
547
548 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
549 assert!(chars.has_code);
550
551 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
553 assert!(chars.has_code);
554
555 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
557 assert!(chars.has_code);
558
559 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
561 assert!(chars.has_code);
562
563 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
565 assert!(chars.has_code);
566
567 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
569 assert!(chars.has_emphasis);
570
571 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
573 assert!(chars.has_html);
574
575 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
577 assert!(chars.has_tables);
578
579 let chars = ContentCharacteristics::analyze("> Quote");
581 assert!(chars.has_blockquotes);
582
583 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
585 let chars = ContentCharacteristics::analyze(content);
586 assert!(chars.has_headings);
587 assert!(chars.has_lists);
588 assert!(chars.has_links);
589 assert!(chars.has_code);
590 assert!(chars.has_emphasis);
591 assert!(chars.has_html);
592 assert!(chars.has_tables);
593 assert!(chars.has_blockquotes);
594 assert!(chars.has_images);
595 }
596
597 #[test]
598 fn test_content_characteristics_should_skip_rule() {
599 let chars = ContentCharacteristics {
600 has_headings: true,
601 has_lists: false,
602 has_links: true,
603 has_code: false,
604 has_emphasis: true,
605 has_html: false,
606 has_tables: true,
607 has_blockquotes: false,
608 has_images: false,
609 };
610
611 let heading_rule = MD001HeadingIncrement::default();
613 assert!(!chars.should_skip_rule(&heading_rule));
614
615 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
616 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
620 has_headings: false,
621 ..Default::default()
622 };
623 assert!(chars_no_headings.should_skip_rule(&heading_rule));
624 }
625
626 #[test]
627 fn test_lint_empty_content() {
628 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
629
630 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
631 assert!(result.is_ok());
632 assert!(result.unwrap().is_empty());
633 }
634
635 #[test]
636 fn test_lint_with_violations() {
637 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
639
640 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
641 assert!(result.is_ok());
642 let warnings = result.unwrap();
643 assert!(!warnings.is_empty());
644 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
646 }
647
648 #[test]
649 fn test_lint_with_inline_disable() {
650 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
651 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
652
653 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
654 assert!(result.is_ok());
655 let warnings = result.unwrap();
656 assert!(warnings.is_empty()); }
658
659 #[test]
660 fn test_lint_rule_filtering() {
661 let content = "# Heading\nJust text";
663 let rules: Vec<Box<dyn Rule>> = vec![
664 Box::new(MD001HeadingIncrement::default()),
665 ];
667
668 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
669 assert!(result.is_ok());
670 }
671
672 #[test]
673 fn test_get_profiling_report() {
674 let report = get_profiling_report();
676 assert!(!report.is_empty());
677 assert!(report.contains("Profiling"));
678 }
679
680 #[test]
681 fn test_reset_profiling() {
682 reset_profiling();
684
685 let report = get_profiling_report();
687 assert!(report.contains("disabled") || report.contains("no measurements"));
688 }
689
690 #[test]
691 fn test_get_regex_cache_stats() {
692 let stats = get_regex_cache_stats();
693 assert!(stats.is_empty() || !stats.is_empty());
695
696 for count in stats.values() {
698 assert!(*count > 0);
699 }
700 }
701
702 #[test]
703 fn test_content_characteristics_edge_cases() {
704 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
707
708 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
710
711 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");
721 assert!(!chars.has_blockquotes);
722 }
723}