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 source_file: Option<std::path::PathBuf>,
192 config: Option<&crate::config::Config>,
193) -> LintResult {
194 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, 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 source_file: Option<std::path::PathBuf>,
210) -> crate::workspace_index::FileIndex {
211 let content_hash = compute_content_hash(content);
213 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
214
215 if content.is_empty() {
217 return file_index;
218 }
219
220 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
222
223 for rule in rules {
225 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
226 rule.contribute_to_index(&lint_ctx, &mut file_index);
227 }
228 }
229
230 file_index
231}
232
233pub fn lint_and_index(
241 content: &str,
242 rules: &[Box<dyn Rule>],
243 _verbose: bool,
244 flavor: crate::config::MarkdownFlavor,
245 source_file: Option<std::path::PathBuf>,
246 config: Option<&crate::config::Config>,
247) -> (LintResult, crate::workspace_index::FileIndex) {
248 let mut warnings = Vec::new();
249 let content_hash = compute_content_hash(content);
251 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
252
253 #[cfg(not(target_arch = "wasm32"))]
254 let _overall_start = Instant::now();
255
256 if content.is_empty() {
258 return (Ok(warnings), file_index);
259 }
260
261 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
263 let inline_config = lint_ctx.inline_config();
264
265 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
267 file_index.file_disabled_rules = file_disabled;
268 file_index.persistent_transitions = persistent_transitions;
269 file_index.line_disabled_rules = line_disabled;
270
271 let characteristics = ContentCharacteristics::analyze(content);
273
274 let applicable_rules: Vec<_> = rules
276 .iter()
277 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
278 .collect();
279
280 let _total_rules = rules.len();
282 let _applicable_count = applicable_rules.len();
283
284 #[cfg(not(target_arch = "wasm32"))]
285 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
286 #[cfg(target_arch = "wasm32")]
287 let profile_rules = false;
288
289 let inline_overrides = inline_config.get_all_rule_configs();
292 let merged_config = if !inline_overrides.is_empty() {
293 config.map(|c| c.merge_with_inline_config(inline_config))
294 } else {
295 None
296 };
297 let effective_config = merged_config.as_ref().or(config);
298
299 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
301 std::collections::HashMap::new();
302
303 if let Some(cfg) = effective_config {
305 for rule_name in inline_overrides.keys() {
306 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
307 recreated_rules.insert(rule_name.clone(), recreated);
308 }
309 }
310 }
311
312 for rule in &applicable_rules {
313 #[cfg(not(target_arch = "wasm32"))]
314 let _rule_start = Instant::now();
315
316 if rule.should_skip(&lint_ctx) {
318 continue;
319 }
320
321 let effective_rule: &dyn crate::rule::Rule = recreated_rules
323 .get(rule.name())
324 .map(|r| r.as_ref())
325 .unwrap_or(rule.as_ref());
326
327 let result = effective_rule.check(&lint_ctx);
329
330 match result {
331 Ok(rule_warnings) => {
332 let filtered_warnings: Vec<_> = rule_warnings
335 .into_iter()
336 .filter(|warning| {
337 if lint_ctx
339 .line_info(warning.line)
340 .is_some_and(|info| info.in_kramdown_extension_block)
341 {
342 return false;
343 }
344
345 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
347
348 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
350 &rule_name_to_check[..dash_pos]
351 } else {
352 rule_name_to_check
353 };
354
355 {
361 let end = if warning.end_line >= warning.line {
362 warning.end_line
363 } else {
364 warning.line
365 };
366 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
367 }
368 })
369 .map(|mut warning| {
370 if let Some(cfg) = config {
372 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
373 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
374 warning.severity = override_severity;
375 }
376 }
377 warning
378 })
379 .collect();
380 warnings.extend(filtered_warnings);
381 }
382 Err(e) => {
383 log::error!("Error checking rule {}: {}", rule.name(), e);
384 return (Err(e), file_index);
385 }
386 }
387
388 #[cfg(not(target_arch = "wasm32"))]
389 {
390 let rule_duration = _rule_start.elapsed();
391 if profile_rules {
392 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
393 }
394
395 #[cfg(not(test))]
396 if _verbose && rule_duration.as_millis() > 500 {
397 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
398 }
399 }
400 }
401
402 for rule in rules {
409 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
410 rule.contribute_to_index(&lint_ctx, &mut file_index);
411 }
412 }
413
414 #[cfg(not(test))]
415 if _verbose {
416 let skipped_rules = _total_rules - _applicable_count;
417 if skipped_rules > 0 {
418 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
419 }
420 }
421
422 (Ok(warnings), file_index)
423}
424
425pub fn run_cross_file_checks(
438 file_path: &std::path::Path,
439 file_index: &crate::workspace_index::FileIndex,
440 rules: &[Box<dyn Rule>],
441 workspace_index: &crate::workspace_index::WorkspaceIndex,
442 config: Option<&crate::config::Config>,
443) -> LintResult {
444 use crate::rule::CrossFileScope;
445
446 let mut warnings = Vec::new();
447
448 for rule in rules {
450 if rule.cross_file_scope() != CrossFileScope::Workspace {
451 continue;
452 }
453
454 match rule.cross_file_check(file_path, file_index, workspace_index) {
455 Ok(rule_warnings) => {
456 let filtered: Vec<_> = rule_warnings
458 .into_iter()
459 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
460 .map(|mut warning| {
461 if let Some(cfg) = config
463 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
464 {
465 warning.severity = override_severity;
466 }
467 warning
468 })
469 .collect();
470 warnings.extend(filtered);
471 }
472 Err(e) => {
473 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
474 return Err(e);
475 }
476 }
477 }
478
479 Ok(warnings)
480}
481
482pub fn get_profiling_report() -> String {
484 profiling::get_report()
485}
486
487pub fn reset_profiling() {
489 profiling::reset()
490}
491
492pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
494 crate::utils::regex_cache::get_cache_stats()
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500 use crate::rule::Rule;
501 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
502
503 #[test]
504 fn test_content_characteristics_analyze() {
505 let chars = ContentCharacteristics::analyze("");
507 assert!(!chars.has_headings);
508 assert!(!chars.has_lists);
509 assert!(!chars.has_links);
510 assert!(!chars.has_code);
511 assert!(!chars.has_emphasis);
512 assert!(!chars.has_html);
513 assert!(!chars.has_tables);
514 assert!(!chars.has_blockquotes);
515 assert!(!chars.has_images);
516
517 let chars = ContentCharacteristics::analyze("# Heading");
519 assert!(chars.has_headings);
520
521 let chars = ContentCharacteristics::analyze("Heading\n=======");
523 assert!(chars.has_headings);
524
525 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
527 assert!(chars.has_lists);
528
529 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
531 assert!(chars.has_lists);
532
533 let chars = ContentCharacteristics::analyze("[link](url)");
535 assert!(chars.has_links);
536
537 let chars = ContentCharacteristics::analyze("Visit https://example.com");
539 assert!(chars.has_links);
540
541 let chars = ContentCharacteristics::analyze("");
543 assert!(chars.has_images);
544
545 let chars = ContentCharacteristics::analyze("`inline code`");
547 assert!(chars.has_code);
548
549 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
550 assert!(chars.has_code);
551
552 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
554 assert!(chars.has_code);
555
556 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
558 assert!(chars.has_code);
559
560 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
562 assert!(chars.has_code);
563
564 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
566 assert!(chars.has_code);
567
568 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
570 assert!(chars.has_emphasis);
571
572 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
574 assert!(chars.has_html);
575
576 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
578 assert!(chars.has_tables);
579
580 let chars = ContentCharacteristics::analyze("> Quote");
582 assert!(chars.has_blockquotes);
583
584 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
586 let chars = ContentCharacteristics::analyze(content);
587 assert!(chars.has_headings);
588 assert!(chars.has_lists);
589 assert!(chars.has_links);
590 assert!(chars.has_code);
591 assert!(chars.has_emphasis);
592 assert!(chars.has_html);
593 assert!(chars.has_tables);
594 assert!(chars.has_blockquotes);
595 assert!(chars.has_images);
596 }
597
598 #[test]
599 fn test_content_characteristics_should_skip_rule() {
600 let chars = ContentCharacteristics {
601 has_headings: true,
602 has_lists: false,
603 has_links: true,
604 has_code: false,
605 has_emphasis: true,
606 has_html: false,
607 has_tables: true,
608 has_blockquotes: false,
609 has_images: false,
610 };
611
612 let heading_rule = MD001HeadingIncrement::default();
614 assert!(!chars.should_skip_rule(&heading_rule));
615
616 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
617 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
621 has_headings: false,
622 ..Default::default()
623 };
624 assert!(chars_no_headings.should_skip_rule(&heading_rule));
625 }
626
627 #[test]
628 fn test_lint_empty_content() {
629 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
630
631 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
632 assert!(result.is_ok());
633 assert!(result.unwrap().is_empty());
634 }
635
636 #[test]
637 fn test_lint_with_violations() {
638 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
640
641 let result = lint(
642 content,
643 &rules,
644 false,
645 crate::config::MarkdownFlavor::Standard,
646 None,
647 None,
648 );
649 assert!(result.is_ok());
650 let warnings = result.unwrap();
651 assert!(!warnings.is_empty());
652 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
654 }
655
656 #[test]
657 fn test_lint_with_inline_disable() {
658 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
659 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
660
661 let result = lint(
662 content,
663 &rules,
664 false,
665 crate::config::MarkdownFlavor::Standard,
666 None,
667 None,
668 );
669 assert!(result.is_ok());
670 let warnings = result.unwrap();
671 assert!(warnings.is_empty()); }
673
674 #[test]
675 fn test_lint_rule_filtering() {
676 let content = "# Heading\nJust text";
678 let rules: Vec<Box<dyn Rule>> = vec![
679 Box::new(MD001HeadingIncrement::default()),
680 ];
682
683 let result = lint(
684 content,
685 &rules,
686 false,
687 crate::config::MarkdownFlavor::Standard,
688 None,
689 None,
690 );
691 assert!(result.is_ok());
692 }
693
694 #[test]
695 fn test_get_profiling_report() {
696 let report = get_profiling_report();
698 assert!(!report.is_empty());
699 assert!(report.contains("Profiling"));
700 }
701
702 #[test]
703 fn test_reset_profiling() {
704 reset_profiling();
706
707 let report = get_profiling_report();
709 assert!(report.contains("disabled") || report.contains("no measurements"));
710 }
711
712 #[test]
713 fn test_get_regex_cache_stats() {
714 let stats = get_regex_cache_stats();
715 assert!(stats.is_empty() || !stats.is_empty());
717
718 for count in stats.values() {
720 assert!(*count > 0);
721 }
722 }
723
724 #[test]
725 fn test_content_characteristics_edge_cases() {
726 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
729
730 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
732
733 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");
743 assert!(!chars.has_blockquotes);
744 }
745}