1pub mod code_block_tools;
2pub mod config;
3pub mod embedded_lint;
4pub mod exit_codes;
5pub mod filtered_lines;
6pub mod fix_coordinator;
7pub mod inline_config;
8pub mod linguist_data;
9pub mod lint_context;
10pub mod markdownlint_config;
11pub mod profiling;
12pub mod rule;
13#[cfg(feature = "native")]
14pub mod vscode;
15pub mod workspace_index;
16#[macro_use]
17pub mod rule_config;
18#[macro_use]
19pub mod rule_config_serde;
20pub mod rules;
21pub mod types;
22pub mod utils;
23
24#[cfg(feature = "native")]
26pub mod lsp;
27#[cfg(feature = "native")]
28pub mod output;
29#[cfg(feature = "native")]
30pub mod parallel;
31#[cfg(feature = "native")]
32pub mod performance;
33
34#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
36pub mod wasm;
37
38pub use rules::heading_utils::{Heading, HeadingStyle};
39pub use rules::*;
40
41pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
42use crate::rule::{LintResult, Rule, RuleCategory};
43use crate::utils::element_cache::ElementCache;
44#[cfg(not(target_arch = "wasm32"))]
45use std::time::Instant;
46
47#[derive(Debug, Default)]
49struct ContentCharacteristics {
50 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, }
60
61fn has_potential_indented_code_indent(line: &str) -> bool {
64 ElementCache::calculate_indentation_width_default(line) >= 4
65}
66
67impl ContentCharacteristics {
68 fn analyze(content: &str) -> Self {
69 let mut chars = Self { ..Default::default() };
70
71 let mut has_atx_heading = false;
73 let mut has_setext_heading = false;
74
75 for line in content.lines() {
76 let trimmed = line.trim();
77
78 if !has_atx_heading && trimmed.starts_with('#') {
80 has_atx_heading = true;
81 }
82 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
83 has_setext_heading = true;
84 }
85
86 if !chars.has_lists
89 && (line.contains("* ")
90 || line.contains("- ")
91 || line.contains("+ ")
92 || trimmed.starts_with("* ")
93 || trimmed.starts_with("- ")
94 || trimmed.starts_with("+ ")
95 || trimmed.starts_with('*')
96 || trimmed.starts_with('-')
97 || trimmed.starts_with('+'))
98 {
99 chars.has_lists = true;
100 }
101 if !chars.has_lists
103 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
104 && (line.contains(". ") || line.contains('.')))
105 || (trimmed.starts_with('>')
106 && trimmed.chars().any(|c| c.is_ascii_digit())
107 && (trimmed.contains(". ") || trimmed.contains('.'))))
108 {
109 chars.has_lists = true;
110 }
111 if !chars.has_links
112 && (line.contains('[')
113 || line.contains("http://")
114 || line.contains("https://")
115 || line.contains("ftp://")
116 || line.contains("www."))
117 {
118 chars.has_links = true;
119 }
120 if !chars.has_images && line.contains("![") {
121 chars.has_images = true;
122 }
123 if !chars.has_code
124 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
125 {
126 chars.has_code = true;
127 }
128 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
129 chars.has_emphasis = true;
130 }
131 if !chars.has_html && line.contains('<') {
132 chars.has_html = true;
133 }
134 if !chars.has_tables && line.contains('|') {
135 chars.has_tables = true;
136 }
137 if !chars.has_blockquotes && line.starts_with('>') {
138 chars.has_blockquotes = true;
139 }
140 }
141
142 chars.has_headings = has_atx_heading || has_setext_heading;
143 chars
144 }
145
146 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
148 match rule.category() {
149 RuleCategory::Heading => !self.has_headings,
150 RuleCategory::List => !self.has_lists,
151 RuleCategory::Link => !self.has_links && !self.has_images,
152 RuleCategory::Image => !self.has_images,
153 RuleCategory::CodeBlock => !self.has_code,
154 RuleCategory::Html => !self.has_html,
155 RuleCategory::Emphasis => !self.has_emphasis,
156 RuleCategory::Blockquote => !self.has_blockquotes,
157 RuleCategory::Table => !self.has_tables,
158 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
160 }
161 }
162}
163
164#[cfg(feature = "native")]
169fn compute_content_hash(content: &str) -> String {
170 blake3::hash(content.as_bytes()).to_hex().to_string()
171}
172
173#[cfg(not(feature = "native"))]
175fn compute_content_hash(content: &str) -> String {
176 use std::hash::{DefaultHasher, Hash, Hasher};
177 let mut hasher = DefaultHasher::new();
178 content.hash(&mut hasher);
179 format!("{:016x}", hasher.finish())
180}
181
182pub fn lint(
186 content: &str,
187 rules: &[Box<dyn Rule>],
188 verbose: bool,
189 flavor: crate::config::MarkdownFlavor,
190 config: Option<&crate::config::Config>,
191) -> LintResult {
192 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
194 result
195}
196
197pub fn build_file_index_only(
205 content: &str,
206 rules: &[Box<dyn Rule>],
207 flavor: crate::config::MarkdownFlavor,
208) -> crate::workspace_index::FileIndex {
209 let content_hash = compute_content_hash(content);
211 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
212
213 if content.is_empty() {
215 return file_index;
216 }
217
218 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
220
221 for rule in rules {
223 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
224 rule.contribute_to_index(&lint_ctx, &mut file_index);
225 }
226 }
227
228 file_index
229}
230
231pub fn lint_and_index(
239 content: &str,
240 rules: &[Box<dyn Rule>],
241 _verbose: bool,
242 flavor: crate::config::MarkdownFlavor,
243 source_file: Option<std::path::PathBuf>,
244 config: Option<&crate::config::Config>,
245) -> (LintResult, crate::workspace_index::FileIndex) {
246 let mut warnings = Vec::new();
247 let content_hash = compute_content_hash(content);
249 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
250
251 #[cfg(not(target_arch = "wasm32"))]
252 let _overall_start = Instant::now();
253
254 if content.is_empty() {
256 return (Ok(warnings), file_index);
257 }
258
259 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
261 let inline_config = lint_ctx.inline_config();
262
263 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
265 file_index.file_disabled_rules = file_disabled;
266 file_index.persistent_transitions = persistent_transitions;
267 file_index.line_disabled_rules = line_disabled;
268
269 let characteristics = ContentCharacteristics::analyze(content);
271
272 let applicable_rules: Vec<_> = rules
274 .iter()
275 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
276 .collect();
277
278 let _total_rules = rules.len();
280 let _applicable_count = applicable_rules.len();
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
333 .into_iter()
334 .filter(|warning| {
335 if lint_ctx
337 .line_info(warning.line)
338 .is_some_and(|info| info.in_kramdown_extension_block)
339 {
340 return false;
341 }
342
343 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
345
346 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
348 &rule_name_to_check[..dash_pos]
349 } else {
350 rule_name_to_check
351 };
352
353 !inline_config.is_rule_disabled(
354 base_rule_name,
355 warning.line, )
357 })
358 .map(|mut warning| {
359 if let Some(cfg) = config {
361 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
362 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
363 warning.severity = override_severity;
364 }
365 }
366 warning
367 })
368 .collect();
369 warnings.extend(filtered_warnings);
370 }
371 Err(e) => {
372 log::error!("Error checking rule {}: {}", rule.name(), e);
373 return (Err(e), file_index);
374 }
375 }
376
377 #[cfg(not(target_arch = "wasm32"))]
378 {
379 let rule_duration = _rule_start.elapsed();
380 if profile_rules {
381 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
382 }
383
384 #[cfg(not(test))]
385 if _verbose && rule_duration.as_millis() > 500 {
386 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
387 }
388 }
389 }
390
391 for rule in rules {
398 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
399 rule.contribute_to_index(&lint_ctx, &mut file_index);
400 }
401 }
402
403 #[cfg(not(test))]
404 if _verbose {
405 let skipped_rules = _total_rules - _applicable_count;
406 if skipped_rules > 0 {
407 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
408 }
409 }
410
411 (Ok(warnings), file_index)
412}
413
414pub fn run_cross_file_checks(
427 file_path: &std::path::Path,
428 file_index: &crate::workspace_index::FileIndex,
429 rules: &[Box<dyn Rule>],
430 workspace_index: &crate::workspace_index::WorkspaceIndex,
431 config: Option<&crate::config::Config>,
432) -> LintResult {
433 use crate::rule::CrossFileScope;
434
435 let mut warnings = Vec::new();
436
437 for rule in rules {
439 if rule.cross_file_scope() != CrossFileScope::Workspace {
440 continue;
441 }
442
443 match rule.cross_file_check(file_path, file_index, workspace_index) {
444 Ok(rule_warnings) => {
445 let filtered: Vec<_> = rule_warnings
447 .into_iter()
448 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
449 .map(|mut warning| {
450 if let Some(cfg) = config
452 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
453 {
454 warning.severity = override_severity;
455 }
456 warning
457 })
458 .collect();
459 warnings.extend(filtered);
460 }
461 Err(e) => {
462 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
463 return Err(e);
464 }
465 }
466 }
467
468 Ok(warnings)
469}
470
471pub fn get_profiling_report() -> String {
473 profiling::get_report()
474}
475
476pub fn reset_profiling() {
478 profiling::reset()
479}
480
481pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
483 crate::utils::regex_cache::get_cache_stats()
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use crate::rule::Rule;
490 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
491
492 #[test]
493 fn test_content_characteristics_analyze() {
494 let chars = ContentCharacteristics::analyze("");
496 assert!(!chars.has_headings);
497 assert!(!chars.has_lists);
498 assert!(!chars.has_links);
499 assert!(!chars.has_code);
500 assert!(!chars.has_emphasis);
501 assert!(!chars.has_html);
502 assert!(!chars.has_tables);
503 assert!(!chars.has_blockquotes);
504 assert!(!chars.has_images);
505
506 let chars = ContentCharacteristics::analyze("# Heading");
508 assert!(chars.has_headings);
509
510 let chars = ContentCharacteristics::analyze("Heading\n=======");
512 assert!(chars.has_headings);
513
514 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
516 assert!(chars.has_lists);
517
518 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
520 assert!(chars.has_lists);
521
522 let chars = ContentCharacteristics::analyze("[link](url)");
524 assert!(chars.has_links);
525
526 let chars = ContentCharacteristics::analyze("Visit https://example.com");
528 assert!(chars.has_links);
529
530 let chars = ContentCharacteristics::analyze("");
532 assert!(chars.has_images);
533
534 let chars = ContentCharacteristics::analyze("`inline code`");
536 assert!(chars.has_code);
537
538 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
539 assert!(chars.has_code);
540
541 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
543 assert!(chars.has_code);
544
545 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
547 assert!(chars.has_code);
548
549 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
551 assert!(chars.has_code);
552
553 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
555 assert!(chars.has_code);
556
557 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
559 assert!(chars.has_emphasis);
560
561 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
563 assert!(chars.has_html);
564
565 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
567 assert!(chars.has_tables);
568
569 let chars = ContentCharacteristics::analyze("> Quote");
571 assert!(chars.has_blockquotes);
572
573 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
575 let chars = ContentCharacteristics::analyze(content);
576 assert!(chars.has_headings);
577 assert!(chars.has_lists);
578 assert!(chars.has_links);
579 assert!(chars.has_code);
580 assert!(chars.has_emphasis);
581 assert!(chars.has_html);
582 assert!(chars.has_tables);
583 assert!(chars.has_blockquotes);
584 assert!(chars.has_images);
585 }
586
587 #[test]
588 fn test_content_characteristics_should_skip_rule() {
589 let chars = ContentCharacteristics {
590 has_headings: true,
591 has_lists: false,
592 has_links: true,
593 has_code: false,
594 has_emphasis: true,
595 has_html: false,
596 has_tables: true,
597 has_blockquotes: false,
598 has_images: false,
599 };
600
601 let heading_rule = MD001HeadingIncrement::default();
603 assert!(!chars.should_skip_rule(&heading_rule));
604
605 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
606 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
610 has_headings: false,
611 ..Default::default()
612 };
613 assert!(chars_no_headings.should_skip_rule(&heading_rule));
614 }
615
616 #[test]
617 fn test_lint_empty_content() {
618 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
619
620 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
621 assert!(result.is_ok());
622 assert!(result.unwrap().is_empty());
623 }
624
625 #[test]
626 fn test_lint_with_violations() {
627 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
629
630 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
631 assert!(result.is_ok());
632 let warnings = result.unwrap();
633 assert!(!warnings.is_empty());
634 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
636 }
637
638 #[test]
639 fn test_lint_with_inline_disable() {
640 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
641 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
642
643 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
644 assert!(result.is_ok());
645 let warnings = result.unwrap();
646 assert!(warnings.is_empty()); }
648
649 #[test]
650 fn test_lint_rule_filtering() {
651 let content = "# Heading\nJust text";
653 let rules: Vec<Box<dyn Rule>> = vec![
654 Box::new(MD001HeadingIncrement::default()),
655 ];
657
658 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
659 assert!(result.is_ok());
660 }
661
662 #[test]
663 fn test_get_profiling_report() {
664 let report = get_profiling_report();
666 assert!(!report.is_empty());
667 assert!(report.contains("Profiling"));
668 }
669
670 #[test]
671 fn test_reset_profiling() {
672 reset_profiling();
674
675 let report = get_profiling_report();
677 assert!(report.contains("disabled") || report.contains("no measurements"));
678 }
679
680 #[test]
681 fn test_get_regex_cache_stats() {
682 let stats = get_regex_cache_stats();
683 assert!(stats.is_empty() || !stats.is_empty());
685
686 for count in stats.values() {
688 assert!(*count > 0);
689 }
690 }
691
692 #[test]
693 fn test_content_characteristics_edge_cases() {
694 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
697
698 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
700
701 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");
711 assert!(!chars.has_blockquotes);
712 }
713}