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 !inline_config.is_rule_disabled(
355 base_rule_name,
356 warning.line, )
358 })
359 .map(|mut warning| {
360 if let Some(cfg) = config {
362 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
363 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
364 warning.severity = override_severity;
365 }
366 }
367 warning
368 })
369 .collect();
370 warnings.extend(filtered_warnings);
371 }
372 Err(e) => {
373 log::error!("Error checking rule {}: {}", rule.name(), e);
374 return (Err(e), file_index);
375 }
376 }
377
378 #[cfg(not(target_arch = "wasm32"))]
379 {
380 let rule_duration = _rule_start.elapsed();
381 if profile_rules {
382 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
383 }
384
385 #[cfg(not(test))]
386 if _verbose && rule_duration.as_millis() > 500 {
387 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
388 }
389 }
390 }
391
392 for rule in rules {
399 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
400 rule.contribute_to_index(&lint_ctx, &mut file_index);
401 }
402 }
403
404 #[cfg(not(test))]
405 if _verbose {
406 let skipped_rules = _total_rules - _applicable_count;
407 if skipped_rules > 0 {
408 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
409 }
410 }
411
412 (Ok(warnings), file_index)
413}
414
415pub fn run_cross_file_checks(
428 file_path: &std::path::Path,
429 file_index: &crate::workspace_index::FileIndex,
430 rules: &[Box<dyn Rule>],
431 workspace_index: &crate::workspace_index::WorkspaceIndex,
432 config: Option<&crate::config::Config>,
433) -> LintResult {
434 use crate::rule::CrossFileScope;
435
436 let mut warnings = Vec::new();
437
438 for rule in rules {
440 if rule.cross_file_scope() != CrossFileScope::Workspace {
441 continue;
442 }
443
444 match rule.cross_file_check(file_path, file_index, workspace_index) {
445 Ok(rule_warnings) => {
446 let filtered: Vec<_> = rule_warnings
448 .into_iter()
449 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
450 .map(|mut warning| {
451 if let Some(cfg) = config
453 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
454 {
455 warning.severity = override_severity;
456 }
457 warning
458 })
459 .collect();
460 warnings.extend(filtered);
461 }
462 Err(e) => {
463 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
464 return Err(e);
465 }
466 }
467 }
468
469 Ok(warnings)
470}
471
472pub fn get_profiling_report() -> String {
474 profiling::get_report()
475}
476
477pub fn reset_profiling() {
479 profiling::reset()
480}
481
482pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
484 crate::utils::regex_cache::get_cache_stats()
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490 use crate::rule::Rule;
491 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
492
493 #[test]
494 fn test_content_characteristics_analyze() {
495 let chars = ContentCharacteristics::analyze("");
497 assert!(!chars.has_headings);
498 assert!(!chars.has_lists);
499 assert!(!chars.has_links);
500 assert!(!chars.has_code);
501 assert!(!chars.has_emphasis);
502 assert!(!chars.has_html);
503 assert!(!chars.has_tables);
504 assert!(!chars.has_blockquotes);
505 assert!(!chars.has_images);
506
507 let chars = ContentCharacteristics::analyze("# Heading");
509 assert!(chars.has_headings);
510
511 let chars = ContentCharacteristics::analyze("Heading\n=======");
513 assert!(chars.has_headings);
514
515 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
517 assert!(chars.has_lists);
518
519 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
521 assert!(chars.has_lists);
522
523 let chars = ContentCharacteristics::analyze("[link](url)");
525 assert!(chars.has_links);
526
527 let chars = ContentCharacteristics::analyze("Visit https://example.com");
529 assert!(chars.has_links);
530
531 let chars = ContentCharacteristics::analyze("");
533 assert!(chars.has_images);
534
535 let chars = ContentCharacteristics::analyze("`inline code`");
537 assert!(chars.has_code);
538
539 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
540 assert!(chars.has_code);
541
542 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
544 assert!(chars.has_code);
545
546 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
548 assert!(chars.has_code);
549
550 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
552 assert!(chars.has_code);
553
554 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
556 assert!(chars.has_code);
557
558 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
560 assert!(chars.has_emphasis);
561
562 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
564 assert!(chars.has_html);
565
566 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
568 assert!(chars.has_tables);
569
570 let chars = ContentCharacteristics::analyze("> Quote");
572 assert!(chars.has_blockquotes);
573
574 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
576 let chars = ContentCharacteristics::analyze(content);
577 assert!(chars.has_headings);
578 assert!(chars.has_lists);
579 assert!(chars.has_links);
580 assert!(chars.has_code);
581 assert!(chars.has_emphasis);
582 assert!(chars.has_html);
583 assert!(chars.has_tables);
584 assert!(chars.has_blockquotes);
585 assert!(chars.has_images);
586 }
587
588 #[test]
589 fn test_content_characteristics_should_skip_rule() {
590 let chars = ContentCharacteristics {
591 has_headings: true,
592 has_lists: false,
593 has_links: true,
594 has_code: false,
595 has_emphasis: true,
596 has_html: false,
597 has_tables: true,
598 has_blockquotes: false,
599 has_images: false,
600 };
601
602 let heading_rule = MD001HeadingIncrement::default();
604 assert!(!chars.should_skip_rule(&heading_rule));
605
606 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
607 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
611 has_headings: false,
612 ..Default::default()
613 };
614 assert!(chars_no_headings.should_skip_rule(&heading_rule));
615 }
616
617 #[test]
618 fn test_lint_empty_content() {
619 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
620
621 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
622 assert!(result.is_ok());
623 assert!(result.unwrap().is_empty());
624 }
625
626 #[test]
627 fn test_lint_with_violations() {
628 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
630
631 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
632 assert!(result.is_ok());
633 let warnings = result.unwrap();
634 assert!(!warnings.is_empty());
635 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
637 }
638
639 #[test]
640 fn test_lint_with_inline_disable() {
641 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
642 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
643
644 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
645 assert!(result.is_ok());
646 let warnings = result.unwrap();
647 assert!(warnings.is_empty()); }
649
650 #[test]
651 fn test_lint_rule_filtering() {
652 let content = "# Heading\nJust text";
654 let rules: Vec<Box<dyn Rule>> = vec![
655 Box::new(MD001HeadingIncrement::default()),
656 ];
658
659 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
660 assert!(result.is_ok());
661 }
662
663 #[test]
664 fn test_get_profiling_report() {
665 let report = get_profiling_report();
667 assert!(!report.is_empty());
668 assert!(report.contains("Profiling"));
669 }
670
671 #[test]
672 fn test_reset_profiling() {
673 reset_profiling();
675
676 let report = get_profiling_report();
678 assert!(report.contains("disabled") || report.contains("no measurements"));
679 }
680
681 #[test]
682 fn test_get_regex_cache_stats() {
683 let stats = get_regex_cache_stats();
684 assert!(stats.is_empty() || !stats.is_empty());
686
687 for count in stats.values() {
689 assert!(*count > 0);
690 }
691 }
692
693 #[test]
694 fn test_content_characteristics_edge_cases() {
695 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
698
699 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
701
702 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");
712 assert!(!chars.has_blockquotes);
713 }
714}