1pub mod config;
2pub mod exit_codes;
3pub mod filtered_lines;
4pub mod fix_coordinator;
5pub mod inline_config;
6pub mod lint_context;
7pub mod markdownlint_config;
8pub mod profiling;
9pub mod rule;
10#[cfg(feature = "native")]
11pub mod vscode;
12pub mod workspace_index;
13#[macro_use]
14pub mod rule_config;
15#[macro_use]
16pub mod rule_config_serde;
17pub mod rules;
18pub mod types;
19pub mod utils;
20
21#[cfg(feature = "native")]
23pub mod lsp;
24#[cfg(feature = "native")]
25pub mod output;
26#[cfg(feature = "native")]
27pub mod parallel;
28#[cfg(feature = "native")]
29pub mod performance;
30
31#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
33pub mod wasm;
34
35pub use rules::heading_utils::{Heading, HeadingStyle};
36pub use rules::*;
37
38pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
39use crate::rule::{LintResult, Rule, RuleCategory};
40use crate::utils::element_cache::ElementCache;
41#[cfg(not(target_arch = "wasm32"))]
42use std::time::Instant;
43
44#[derive(Debug, Default)]
46struct ContentCharacteristics {
47 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, }
57
58fn has_potential_indented_code_indent(line: &str) -> bool {
61 ElementCache::calculate_indentation_width_default(line) >= 4
62}
63
64impl ContentCharacteristics {
65 fn analyze(content: &str) -> Self {
66 let mut chars = Self { ..Default::default() };
67
68 let mut has_atx_heading = false;
70 let mut has_setext_heading = false;
71
72 for line in content.lines() {
73 let trimmed = line.trim();
74
75 if !has_atx_heading && trimmed.starts_with('#') {
77 has_atx_heading = true;
78 }
79 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
80 has_setext_heading = true;
81 }
82
83 if !chars.has_lists
86 && (line.contains("* ")
87 || line.contains("- ")
88 || line.contains("+ ")
89 || trimmed.starts_with("* ")
90 || trimmed.starts_with("- ")
91 || trimmed.starts_with("+ ")
92 || trimmed.starts_with('*')
93 || trimmed.starts_with('-')
94 || trimmed.starts_with('+'))
95 {
96 chars.has_lists = true;
97 }
98 if !chars.has_lists
100 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
101 && (line.contains(". ") || line.contains('.')))
102 || (trimmed.starts_with('>')
103 && trimmed.chars().any(|c| c.is_ascii_digit())
104 && (trimmed.contains(". ") || trimmed.contains('.'))))
105 {
106 chars.has_lists = true;
107 }
108 if !chars.has_links
109 && (line.contains('[')
110 || line.contains("http://")
111 || line.contains("https://")
112 || line.contains("ftp://")
113 || line.contains("www."))
114 {
115 chars.has_links = true;
116 }
117 if !chars.has_images && line.contains("![") {
118 chars.has_images = true;
119 }
120 if !chars.has_code
121 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
122 {
123 chars.has_code = true;
124 }
125 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
126 chars.has_emphasis = true;
127 }
128 if !chars.has_html && line.contains('<') {
129 chars.has_html = true;
130 }
131 if !chars.has_tables && line.contains('|') {
132 chars.has_tables = true;
133 }
134 if !chars.has_blockquotes && line.starts_with('>') {
135 chars.has_blockquotes = true;
136 }
137 }
138
139 chars.has_headings = has_atx_heading || has_setext_heading;
140 chars
141 }
142
143 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
145 match rule.category() {
146 RuleCategory::Heading => !self.has_headings,
147 RuleCategory::List => !self.has_lists,
148 RuleCategory::Link => !self.has_links && !self.has_images,
149 RuleCategory::Image => !self.has_images,
150 RuleCategory::CodeBlock => !self.has_code,
151 RuleCategory::Html => !self.has_html,
152 RuleCategory::Emphasis => !self.has_emphasis,
153 RuleCategory::Blockquote => !self.has_blockquotes,
154 RuleCategory::Table => !self.has_tables,
155 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
157 }
158 }
159}
160
161#[cfg(feature = "native")]
166fn compute_content_hash(content: &str) -> String {
167 blake3::hash(content.as_bytes()).to_hex().to_string()
168}
169
170#[cfg(not(feature = "native"))]
172fn compute_content_hash(content: &str) -> String {
173 use std::hash::{DefaultHasher, Hash, Hasher};
174 let mut hasher = DefaultHasher::new();
175 content.hash(&mut hasher);
176 format!("{:016x}", hasher.finish())
177}
178
179pub fn lint(
183 content: &str,
184 rules: &[Box<dyn Rule>],
185 verbose: bool,
186 flavor: crate::config::MarkdownFlavor,
187 config: Option<&crate::config::Config>,
188) -> LintResult {
189 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
191 result
192}
193
194pub fn build_file_index_only(
202 content: &str,
203 rules: &[Box<dyn Rule>],
204 flavor: crate::config::MarkdownFlavor,
205) -> crate::workspace_index::FileIndex {
206 let content_hash = compute_content_hash(content);
208 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
209
210 if content.is_empty() {
212 return file_index;
213 }
214
215 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
217
218 for rule in rules {
220 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
221 rule.contribute_to_index(&lint_ctx, &mut file_index);
222 }
223 }
224
225 file_index
226}
227
228pub fn lint_and_index(
236 content: &str,
237 rules: &[Box<dyn Rule>],
238 _verbose: bool,
239 flavor: crate::config::MarkdownFlavor,
240 source_file: Option<std::path::PathBuf>,
241 config: Option<&crate::config::Config>,
242) -> (LintResult, crate::workspace_index::FileIndex) {
243 let mut warnings = Vec::new();
244 let content_hash = compute_content_hash(content);
246 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
247
248 #[cfg(not(target_arch = "wasm32"))]
249 let _overall_start = Instant::now();
250
251 if content.is_empty() {
253 return (Ok(warnings), file_index);
254 }
255
256 let inline_config = crate::inline_config::InlineConfig::from_content(content);
258
259 let (file_disabled, line_disabled) = inline_config.export_for_file_index();
261 file_index.file_disabled_rules = file_disabled;
262 file_index.line_disabled_rules = line_disabled;
263
264 let characteristics = ContentCharacteristics::analyze(content);
266
267 let applicable_rules: Vec<_> = rules
269 .iter()
270 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
271 .collect();
272
273 let _total_rules = rules.len();
275 let _applicable_count = applicable_rules.len();
276
277 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
279
280 #[cfg(not(target_arch = "wasm32"))]
281 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
282 #[cfg(target_arch = "wasm32")]
283 let profile_rules = false;
284
285 for rule in &applicable_rules {
286 #[cfg(not(target_arch = "wasm32"))]
287 let _rule_start = Instant::now();
288
289 let result = rule.check(&lint_ctx);
291
292 match result {
293 Ok(rule_warnings) => {
294 let filtered_warnings: Vec<_> = rule_warnings
296 .into_iter()
297 .filter(|warning| {
298 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
300
301 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
303 &rule_name_to_check[..dash_pos]
304 } else {
305 rule_name_to_check
306 };
307
308 !inline_config.is_rule_disabled(
309 base_rule_name,
310 warning.line, )
312 })
313 .map(|mut warning| {
314 if let Some(cfg) = config {
316 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
317 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
318 warning.severity = override_severity;
319 }
320 }
321 warning
322 })
323 .collect();
324 warnings.extend(filtered_warnings);
325 }
326 Err(e) => {
327 log::error!("Error checking rule {}: {}", rule.name(), e);
328 return (Err(e), file_index);
329 }
330 }
331
332 #[cfg(not(target_arch = "wasm32"))]
333 {
334 let rule_duration = _rule_start.elapsed();
335 if profile_rules {
336 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
337 }
338
339 #[cfg(not(test))]
340 if _verbose && rule_duration.as_millis() > 500 {
341 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
342 }
343 }
344 }
345
346 for rule in rules {
353 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
354 rule.contribute_to_index(&lint_ctx, &mut file_index);
355 }
356 }
357
358 #[cfg(not(test))]
359 if _verbose {
360 let skipped_rules = _total_rules - _applicable_count;
361 if skipped_rules > 0 {
362 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
363 }
364 }
365
366 (Ok(warnings), file_index)
367}
368
369pub fn run_cross_file_checks(
382 file_path: &std::path::Path,
383 file_index: &crate::workspace_index::FileIndex,
384 rules: &[Box<dyn Rule>],
385 workspace_index: &crate::workspace_index::WorkspaceIndex,
386 config: Option<&crate::config::Config>,
387) -> LintResult {
388 use crate::rule::CrossFileScope;
389
390 let mut warnings = Vec::new();
391
392 for rule in rules {
394 if rule.cross_file_scope() != CrossFileScope::Workspace {
395 continue;
396 }
397
398 match rule.cross_file_check(file_path, file_index, workspace_index) {
399 Ok(rule_warnings) => {
400 let filtered: Vec<_> = rule_warnings
402 .into_iter()
403 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
404 .map(|mut warning| {
405 if let Some(cfg) = config
407 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
408 {
409 warning.severity = override_severity;
410 }
411 warning
412 })
413 .collect();
414 warnings.extend(filtered);
415 }
416 Err(e) => {
417 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
418 return Err(e);
419 }
420 }
421 }
422
423 Ok(warnings)
424}
425
426pub fn get_profiling_report() -> String {
428 profiling::get_report()
429}
430
431pub fn reset_profiling() {
433 profiling::reset()
434}
435
436pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
438 crate::utils::regex_cache::get_cache_stats()
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use crate::rule::Rule;
445 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
446
447 #[test]
448 fn test_content_characteristics_analyze() {
449 let chars = ContentCharacteristics::analyze("");
451 assert!(!chars.has_headings);
452 assert!(!chars.has_lists);
453 assert!(!chars.has_links);
454 assert!(!chars.has_code);
455 assert!(!chars.has_emphasis);
456 assert!(!chars.has_html);
457 assert!(!chars.has_tables);
458 assert!(!chars.has_blockquotes);
459 assert!(!chars.has_images);
460
461 let chars = ContentCharacteristics::analyze("# Heading");
463 assert!(chars.has_headings);
464
465 let chars = ContentCharacteristics::analyze("Heading\n=======");
467 assert!(chars.has_headings);
468
469 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
471 assert!(chars.has_lists);
472
473 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
475 assert!(chars.has_lists);
476
477 let chars = ContentCharacteristics::analyze("[link](url)");
479 assert!(chars.has_links);
480
481 let chars = ContentCharacteristics::analyze("Visit https://example.com");
483 assert!(chars.has_links);
484
485 let chars = ContentCharacteristics::analyze("");
487 assert!(chars.has_images);
488
489 let chars = ContentCharacteristics::analyze("`inline code`");
491 assert!(chars.has_code);
492
493 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
494 assert!(chars.has_code);
495
496 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
498 assert!(chars.has_code);
499
500 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
502 assert!(chars.has_code);
503
504 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
506 assert!(chars.has_code);
507
508 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
510 assert!(chars.has_code);
511
512 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
514 assert!(chars.has_emphasis);
515
516 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
518 assert!(chars.has_html);
519
520 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
522 assert!(chars.has_tables);
523
524 let chars = ContentCharacteristics::analyze("> Quote");
526 assert!(chars.has_blockquotes);
527
528 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
530 let chars = ContentCharacteristics::analyze(content);
531 assert!(chars.has_headings);
532 assert!(chars.has_lists);
533 assert!(chars.has_links);
534 assert!(chars.has_code);
535 assert!(chars.has_emphasis);
536 assert!(chars.has_html);
537 assert!(chars.has_tables);
538 assert!(chars.has_blockquotes);
539 assert!(chars.has_images);
540 }
541
542 #[test]
543 fn test_content_characteristics_should_skip_rule() {
544 let chars = ContentCharacteristics {
545 has_headings: true,
546 has_lists: false,
547 has_links: true,
548 has_code: false,
549 has_emphasis: true,
550 has_html: false,
551 has_tables: true,
552 has_blockquotes: false,
553 has_images: false,
554 };
555
556 let heading_rule = MD001HeadingIncrement::default();
558 assert!(!chars.should_skip_rule(&heading_rule));
559
560 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
561 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
565 has_headings: false,
566 ..Default::default()
567 };
568 assert!(chars_no_headings.should_skip_rule(&heading_rule));
569 }
570
571 #[test]
572 fn test_lint_empty_content() {
573 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
574
575 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
576 assert!(result.is_ok());
577 assert!(result.unwrap().is_empty());
578 }
579
580 #[test]
581 fn test_lint_with_violations() {
582 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
584
585 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
586 assert!(result.is_ok());
587 let warnings = result.unwrap();
588 assert!(!warnings.is_empty());
589 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
591 }
592
593 #[test]
594 fn test_lint_with_inline_disable() {
595 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
596 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
597
598 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
599 assert!(result.is_ok());
600 let warnings = result.unwrap();
601 assert!(warnings.is_empty()); }
603
604 #[test]
605 fn test_lint_rule_filtering() {
606 let content = "# Heading\nJust text";
608 let rules: Vec<Box<dyn Rule>> = vec![
609 Box::new(MD001HeadingIncrement::default()),
610 ];
612
613 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
614 assert!(result.is_ok());
615 }
616
617 #[test]
618 fn test_get_profiling_report() {
619 let report = get_profiling_report();
621 assert!(!report.is_empty());
622 assert!(report.contains("Profiling"));
623 }
624
625 #[test]
626 fn test_reset_profiling() {
627 reset_profiling();
629
630 let report = get_profiling_report();
632 assert!(report.contains("disabled") || report.contains("no measurements"));
633 }
634
635 #[test]
636 fn test_get_regex_cache_stats() {
637 let stats = get_regex_cache_stats();
638 assert!(stats.is_empty() || !stats.is_empty());
640
641 for count in stats.values() {
643 assert!(*count > 0);
644 }
645 }
646
647 #[test]
648 fn test_content_characteristics_edge_cases() {
649 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
652
653 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
655
656 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");
666 assert!(!chars.has_blockquotes);
667 }
668}