1pub mod code_block_tools;
2pub mod config;
3pub mod exit_codes;
4pub mod filtered_lines;
5pub mod fix_coordinator;
6pub mod inline_config;
7pub mod linguist_data;
8pub mod lint_context;
9pub mod markdownlint_config;
10pub mod profiling;
11pub mod rule;
12#[cfg(feature = "native")]
13pub mod vscode;
14pub mod workspace_index;
15#[macro_use]
16pub mod rule_config;
17#[macro_use]
18pub mod rule_config_serde;
19pub mod rules;
20pub mod types;
21pub mod utils;
22
23#[cfg(feature = "native")]
25pub mod lsp;
26#[cfg(feature = "native")]
27pub mod output;
28#[cfg(feature = "native")]
29pub mod parallel;
30#[cfg(feature = "native")]
31pub mod performance;
32
33#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
35pub mod wasm;
36
37pub use rules::heading_utils::{Heading, HeadingStyle};
38pub use rules::*;
39
40pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
41use crate::rule::{LintResult, Rule, RuleCategory};
42use crate::utils::element_cache::ElementCache;
43#[cfg(not(target_arch = "wasm32"))]
44use std::time::Instant;
45
46#[derive(Debug, Default)]
48struct ContentCharacteristics {
49 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, }
59
60fn has_potential_indented_code_indent(line: &str) -> bool {
63 ElementCache::calculate_indentation_width_default(line) >= 4
64}
65
66impl ContentCharacteristics {
67 fn analyze(content: &str) -> Self {
68 let mut chars = Self { ..Default::default() };
69
70 let mut has_atx_heading = false;
72 let mut has_setext_heading = false;
73
74 for line in content.lines() {
75 let trimmed = line.trim();
76
77 if !has_atx_heading && trimmed.starts_with('#') {
79 has_atx_heading = true;
80 }
81 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
82 has_setext_heading = true;
83 }
84
85 if !chars.has_lists
88 && (line.contains("* ")
89 || line.contains("- ")
90 || line.contains("+ ")
91 || trimmed.starts_with("* ")
92 || trimmed.starts_with("- ")
93 || trimmed.starts_with("+ ")
94 || trimmed.starts_with('*')
95 || trimmed.starts_with('-')
96 || trimmed.starts_with('+'))
97 {
98 chars.has_lists = true;
99 }
100 if !chars.has_lists
102 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
103 && (line.contains(". ") || line.contains('.')))
104 || (trimmed.starts_with('>')
105 && trimmed.chars().any(|c| c.is_ascii_digit())
106 && (trimmed.contains(". ") || trimmed.contains('.'))))
107 {
108 chars.has_lists = true;
109 }
110 if !chars.has_links
111 && (line.contains('[')
112 || line.contains("http://")
113 || line.contains("https://")
114 || line.contains("ftp://")
115 || line.contains("www."))
116 {
117 chars.has_links = true;
118 }
119 if !chars.has_images && line.contains("![") {
120 chars.has_images = true;
121 }
122 if !chars.has_code
123 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
124 {
125 chars.has_code = true;
126 }
127 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
128 chars.has_emphasis = true;
129 }
130 if !chars.has_html && line.contains('<') {
131 chars.has_html = true;
132 }
133 if !chars.has_tables && line.contains('|') {
134 chars.has_tables = true;
135 }
136 if !chars.has_blockquotes && line.starts_with('>') {
137 chars.has_blockquotes = true;
138 }
139 }
140
141 chars.has_headings = has_atx_heading || has_setext_heading;
142 chars
143 }
144
145 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
147 match rule.category() {
148 RuleCategory::Heading => !self.has_headings,
149 RuleCategory::List => !self.has_lists,
150 RuleCategory::Link => !self.has_links && !self.has_images,
151 RuleCategory::Image => !self.has_images,
152 RuleCategory::CodeBlock => !self.has_code,
153 RuleCategory::Html => !self.has_html,
154 RuleCategory::Emphasis => !self.has_emphasis,
155 RuleCategory::Blockquote => !self.has_blockquotes,
156 RuleCategory::Table => !self.has_tables,
157 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
159 }
160 }
161}
162
163#[cfg(feature = "native")]
168fn compute_content_hash(content: &str) -> String {
169 blake3::hash(content.as_bytes()).to_hex().to_string()
170}
171
172#[cfg(not(feature = "native"))]
174fn compute_content_hash(content: &str) -> String {
175 use std::hash::{DefaultHasher, Hash, Hasher};
176 let mut hasher = DefaultHasher::new();
177 content.hash(&mut hasher);
178 format!("{:016x}", hasher.finish())
179}
180
181pub fn lint(
185 content: &str,
186 rules: &[Box<dyn Rule>],
187 verbose: bool,
188 flavor: crate::config::MarkdownFlavor,
189 config: Option<&crate::config::Config>,
190) -> LintResult {
191 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
193 result
194}
195
196pub fn build_file_index_only(
204 content: &str,
205 rules: &[Box<dyn Rule>],
206 flavor: crate::config::MarkdownFlavor,
207) -> crate::workspace_index::FileIndex {
208 let content_hash = compute_content_hash(content);
210 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
211
212 if content.is_empty() {
214 return file_index;
215 }
216
217 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
219
220 for rule in rules {
222 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
223 rule.contribute_to_index(&lint_ctx, &mut file_index);
224 }
225 }
226
227 file_index
228}
229
230pub fn lint_and_index(
238 content: &str,
239 rules: &[Box<dyn Rule>],
240 _verbose: bool,
241 flavor: crate::config::MarkdownFlavor,
242 source_file: Option<std::path::PathBuf>,
243 config: Option<&crate::config::Config>,
244) -> (LintResult, crate::workspace_index::FileIndex) {
245 let mut warnings = Vec::new();
246 let content_hash = compute_content_hash(content);
248 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
249
250 #[cfg(not(target_arch = "wasm32"))]
251 let _overall_start = Instant::now();
252
253 if content.is_empty() {
255 return (Ok(warnings), file_index);
256 }
257
258 let inline_config = crate::inline_config::InlineConfig::from_content(content);
260
261 let (file_disabled, line_disabled) = inline_config.export_for_file_index();
263 file_index.file_disabled_rules = file_disabled;
264 file_index.line_disabled_rules = line_disabled;
265
266 let characteristics = ContentCharacteristics::analyze(content);
268
269 let applicable_rules: Vec<_> = rules
271 .iter()
272 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
273 .collect();
274
275 let _total_rules = rules.len();
277 let _applicable_count = applicable_rules.len();
278
279 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
281
282 #[cfg(not(target_arch = "wasm32"))]
283 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
284 #[cfg(target_arch = "wasm32")]
285 let profile_rules = false;
286
287 let inline_overrides = inline_config.get_all_rule_configs();
290 let merged_config = if !inline_overrides.is_empty() {
291 config.map(|c| c.merge_with_inline_config(&inline_config))
292 } else {
293 None
294 };
295 let effective_config = merged_config.as_ref().or(config);
296
297 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
299 std::collections::HashMap::new();
300
301 if let Some(cfg) = effective_config {
303 for rule_name in inline_overrides.keys() {
304 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
305 recreated_rules.insert(rule_name.clone(), recreated);
306 }
307 }
308 }
309
310 for rule in &applicable_rules {
311 #[cfg(not(target_arch = "wasm32"))]
312 let _rule_start = Instant::now();
313
314 if rule.should_skip(&lint_ctx) {
316 continue;
317 }
318
319 let effective_rule: &dyn crate::rule::Rule = recreated_rules
321 .get(rule.name())
322 .map(|r| r.as_ref())
323 .unwrap_or(rule.as_ref());
324
325 let result = effective_rule.check(&lint_ctx);
327
328 match result {
329 Ok(rule_warnings) => {
330 let filtered_warnings: Vec<_> = rule_warnings
332 .into_iter()
333 .filter(|warning| {
334 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
336
337 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
339 &rule_name_to_check[..dash_pos]
340 } else {
341 rule_name_to_check
342 };
343
344 !inline_config.is_rule_disabled(
345 base_rule_name,
346 warning.line, )
348 })
349 .map(|mut warning| {
350 if let Some(cfg) = config {
352 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
353 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
354 warning.severity = override_severity;
355 }
356 }
357 warning
358 })
359 .collect();
360 warnings.extend(filtered_warnings);
361 }
362 Err(e) => {
363 log::error!("Error checking rule {}: {}", rule.name(), e);
364 return (Err(e), file_index);
365 }
366 }
367
368 #[cfg(not(target_arch = "wasm32"))]
369 {
370 let rule_duration = _rule_start.elapsed();
371 if profile_rules {
372 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
373 }
374
375 #[cfg(not(test))]
376 if _verbose && rule_duration.as_millis() > 500 {
377 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
378 }
379 }
380 }
381
382 for rule in rules {
389 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
390 rule.contribute_to_index(&lint_ctx, &mut file_index);
391 }
392 }
393
394 #[cfg(not(test))]
395 if _verbose {
396 let skipped_rules = _total_rules - _applicable_count;
397 if skipped_rules > 0 {
398 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
399 }
400 }
401
402 (Ok(warnings), file_index)
403}
404
405pub fn run_cross_file_checks(
418 file_path: &std::path::Path,
419 file_index: &crate::workspace_index::FileIndex,
420 rules: &[Box<dyn Rule>],
421 workspace_index: &crate::workspace_index::WorkspaceIndex,
422 config: Option<&crate::config::Config>,
423) -> LintResult {
424 use crate::rule::CrossFileScope;
425
426 let mut warnings = Vec::new();
427
428 for rule in rules {
430 if rule.cross_file_scope() != CrossFileScope::Workspace {
431 continue;
432 }
433
434 match rule.cross_file_check(file_path, file_index, workspace_index) {
435 Ok(rule_warnings) => {
436 let filtered: Vec<_> = rule_warnings
438 .into_iter()
439 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
440 .map(|mut warning| {
441 if let Some(cfg) = config
443 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
444 {
445 warning.severity = override_severity;
446 }
447 warning
448 })
449 .collect();
450 warnings.extend(filtered);
451 }
452 Err(e) => {
453 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
454 return Err(e);
455 }
456 }
457 }
458
459 Ok(warnings)
460}
461
462pub fn get_profiling_report() -> String {
464 profiling::get_report()
465}
466
467pub fn reset_profiling() {
469 profiling::reset()
470}
471
472pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
474 crate::utils::regex_cache::get_cache_stats()
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480 use crate::rule::Rule;
481 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
482
483 #[test]
484 fn test_content_characteristics_analyze() {
485 let chars = ContentCharacteristics::analyze("");
487 assert!(!chars.has_headings);
488 assert!(!chars.has_lists);
489 assert!(!chars.has_links);
490 assert!(!chars.has_code);
491 assert!(!chars.has_emphasis);
492 assert!(!chars.has_html);
493 assert!(!chars.has_tables);
494 assert!(!chars.has_blockquotes);
495 assert!(!chars.has_images);
496
497 let chars = ContentCharacteristics::analyze("# Heading");
499 assert!(chars.has_headings);
500
501 let chars = ContentCharacteristics::analyze("Heading\n=======");
503 assert!(chars.has_headings);
504
505 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
507 assert!(chars.has_lists);
508
509 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
511 assert!(chars.has_lists);
512
513 let chars = ContentCharacteristics::analyze("[link](url)");
515 assert!(chars.has_links);
516
517 let chars = ContentCharacteristics::analyze("Visit https://example.com");
519 assert!(chars.has_links);
520
521 let chars = ContentCharacteristics::analyze("");
523 assert!(chars.has_images);
524
525 let chars = ContentCharacteristics::analyze("`inline code`");
527 assert!(chars.has_code);
528
529 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
530 assert!(chars.has_code);
531
532 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
534 assert!(chars.has_code);
535
536 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
538 assert!(chars.has_code);
539
540 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
542 assert!(chars.has_code);
543
544 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
546 assert!(chars.has_code);
547
548 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
550 assert!(chars.has_emphasis);
551
552 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
554 assert!(chars.has_html);
555
556 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
558 assert!(chars.has_tables);
559
560 let chars = ContentCharacteristics::analyze("> Quote");
562 assert!(chars.has_blockquotes);
563
564 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
566 let chars = ContentCharacteristics::analyze(content);
567 assert!(chars.has_headings);
568 assert!(chars.has_lists);
569 assert!(chars.has_links);
570 assert!(chars.has_code);
571 assert!(chars.has_emphasis);
572 assert!(chars.has_html);
573 assert!(chars.has_tables);
574 assert!(chars.has_blockquotes);
575 assert!(chars.has_images);
576 }
577
578 #[test]
579 fn test_content_characteristics_should_skip_rule() {
580 let chars = ContentCharacteristics {
581 has_headings: true,
582 has_lists: false,
583 has_links: true,
584 has_code: false,
585 has_emphasis: true,
586 has_html: false,
587 has_tables: true,
588 has_blockquotes: false,
589 has_images: false,
590 };
591
592 let heading_rule = MD001HeadingIncrement::default();
594 assert!(!chars.should_skip_rule(&heading_rule));
595
596 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
597 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
601 has_headings: false,
602 ..Default::default()
603 };
604 assert!(chars_no_headings.should_skip_rule(&heading_rule));
605 }
606
607 #[test]
608 fn test_lint_empty_content() {
609 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
610
611 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
612 assert!(result.is_ok());
613 assert!(result.unwrap().is_empty());
614 }
615
616 #[test]
617 fn test_lint_with_violations() {
618 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
620
621 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
622 assert!(result.is_ok());
623 let warnings = result.unwrap();
624 assert!(!warnings.is_empty());
625 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
627 }
628
629 #[test]
630 fn test_lint_with_inline_disable() {
631 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
632 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
633
634 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
635 assert!(result.is_ok());
636 let warnings = result.unwrap();
637 assert!(warnings.is_empty()); }
639
640 #[test]
641 fn test_lint_rule_filtering() {
642 let content = "# Heading\nJust text";
644 let rules: Vec<Box<dyn Rule>> = vec![
645 Box::new(MD001HeadingIncrement::default()),
646 ];
648
649 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
650 assert!(result.is_ok());
651 }
652
653 #[test]
654 fn test_get_profiling_report() {
655 let report = get_profiling_report();
657 assert!(!report.is_empty());
658 assert!(report.contains("Profiling"));
659 }
660
661 #[test]
662 fn test_reset_profiling() {
663 reset_profiling();
665
666 let report = get_profiling_report();
668 assert!(report.contains("disabled") || report.contains("no measurements"));
669 }
670
671 #[test]
672 fn test_get_regex_cache_stats() {
673 let stats = get_regex_cache_stats();
674 assert!(stats.is_empty() || !stats.is_empty());
676
677 for count in stats.values() {
679 assert!(*count > 0);
680 }
681 }
682
683 #[test]
684 fn test_content_characteristics_edge_cases() {
685 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
688
689 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
691
692 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");
702 assert!(!chars.has_blockquotes);
703 }
704}