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 if rule.should_skip(&lint_ctx) {
291 continue;
292 }
293
294 let result = rule.check(&lint_ctx);
296
297 match result {
298 Ok(rule_warnings) => {
299 let filtered_warnings: Vec<_> = rule_warnings
301 .into_iter()
302 .filter(|warning| {
303 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
305
306 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
308 &rule_name_to_check[..dash_pos]
309 } else {
310 rule_name_to_check
311 };
312
313 !inline_config.is_rule_disabled(
314 base_rule_name,
315 warning.line, )
317 })
318 .map(|mut warning| {
319 if let Some(cfg) = config {
321 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
322 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
323 warning.severity = override_severity;
324 }
325 }
326 warning
327 })
328 .collect();
329 warnings.extend(filtered_warnings);
330 }
331 Err(e) => {
332 log::error!("Error checking rule {}: {}", rule.name(), e);
333 return (Err(e), file_index);
334 }
335 }
336
337 #[cfg(not(target_arch = "wasm32"))]
338 {
339 let rule_duration = _rule_start.elapsed();
340 if profile_rules {
341 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
342 }
343
344 #[cfg(not(test))]
345 if _verbose && rule_duration.as_millis() > 500 {
346 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
347 }
348 }
349 }
350
351 for rule in rules {
358 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
359 rule.contribute_to_index(&lint_ctx, &mut file_index);
360 }
361 }
362
363 #[cfg(not(test))]
364 if _verbose {
365 let skipped_rules = _total_rules - _applicable_count;
366 if skipped_rules > 0 {
367 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
368 }
369 }
370
371 (Ok(warnings), file_index)
372}
373
374pub fn run_cross_file_checks(
387 file_path: &std::path::Path,
388 file_index: &crate::workspace_index::FileIndex,
389 rules: &[Box<dyn Rule>],
390 workspace_index: &crate::workspace_index::WorkspaceIndex,
391 config: Option<&crate::config::Config>,
392) -> LintResult {
393 use crate::rule::CrossFileScope;
394
395 let mut warnings = Vec::new();
396
397 for rule in rules {
399 if rule.cross_file_scope() != CrossFileScope::Workspace {
400 continue;
401 }
402
403 match rule.cross_file_check(file_path, file_index, workspace_index) {
404 Ok(rule_warnings) => {
405 let filtered: Vec<_> = rule_warnings
407 .into_iter()
408 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
409 .map(|mut warning| {
410 if let Some(cfg) = config
412 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
413 {
414 warning.severity = override_severity;
415 }
416 warning
417 })
418 .collect();
419 warnings.extend(filtered);
420 }
421 Err(e) => {
422 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
423 return Err(e);
424 }
425 }
426 }
427
428 Ok(warnings)
429}
430
431pub fn get_profiling_report() -> String {
433 profiling::get_report()
434}
435
436pub fn reset_profiling() {
438 profiling::reset()
439}
440
441pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
443 crate::utils::regex_cache::get_cache_stats()
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::rule::Rule;
450 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
451
452 #[test]
453 fn test_content_characteristics_analyze() {
454 let chars = ContentCharacteristics::analyze("");
456 assert!(!chars.has_headings);
457 assert!(!chars.has_lists);
458 assert!(!chars.has_links);
459 assert!(!chars.has_code);
460 assert!(!chars.has_emphasis);
461 assert!(!chars.has_html);
462 assert!(!chars.has_tables);
463 assert!(!chars.has_blockquotes);
464 assert!(!chars.has_images);
465
466 let chars = ContentCharacteristics::analyze("# Heading");
468 assert!(chars.has_headings);
469
470 let chars = ContentCharacteristics::analyze("Heading\n=======");
472 assert!(chars.has_headings);
473
474 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
476 assert!(chars.has_lists);
477
478 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
480 assert!(chars.has_lists);
481
482 let chars = ContentCharacteristics::analyze("[link](url)");
484 assert!(chars.has_links);
485
486 let chars = ContentCharacteristics::analyze("Visit https://example.com");
488 assert!(chars.has_links);
489
490 let chars = ContentCharacteristics::analyze("");
492 assert!(chars.has_images);
493
494 let chars = ContentCharacteristics::analyze("`inline code`");
496 assert!(chars.has_code);
497
498 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
499 assert!(chars.has_code);
500
501 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
503 assert!(chars.has_code);
504
505 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
507 assert!(chars.has_code);
508
509 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
511 assert!(chars.has_code);
512
513 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
515 assert!(chars.has_code);
516
517 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
519 assert!(chars.has_emphasis);
520
521 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
523 assert!(chars.has_html);
524
525 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
527 assert!(chars.has_tables);
528
529 let chars = ContentCharacteristics::analyze("> Quote");
531 assert!(chars.has_blockquotes);
532
533 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
535 let chars = ContentCharacteristics::analyze(content);
536 assert!(chars.has_headings);
537 assert!(chars.has_lists);
538 assert!(chars.has_links);
539 assert!(chars.has_code);
540 assert!(chars.has_emphasis);
541 assert!(chars.has_html);
542 assert!(chars.has_tables);
543 assert!(chars.has_blockquotes);
544 assert!(chars.has_images);
545 }
546
547 #[test]
548 fn test_content_characteristics_should_skip_rule() {
549 let chars = ContentCharacteristics {
550 has_headings: true,
551 has_lists: false,
552 has_links: true,
553 has_code: false,
554 has_emphasis: true,
555 has_html: false,
556 has_tables: true,
557 has_blockquotes: false,
558 has_images: false,
559 };
560
561 let heading_rule = MD001HeadingIncrement::default();
563 assert!(!chars.should_skip_rule(&heading_rule));
564
565 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
566 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
570 has_headings: false,
571 ..Default::default()
572 };
573 assert!(chars_no_headings.should_skip_rule(&heading_rule));
574 }
575
576 #[test]
577 fn test_lint_empty_content() {
578 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
579
580 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
581 assert!(result.is_ok());
582 assert!(result.unwrap().is_empty());
583 }
584
585 #[test]
586 fn test_lint_with_violations() {
587 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
589
590 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
591 assert!(result.is_ok());
592 let warnings = result.unwrap();
593 assert!(!warnings.is_empty());
594 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
596 }
597
598 #[test]
599 fn test_lint_with_inline_disable() {
600 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
601 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
602
603 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
604 assert!(result.is_ok());
605 let warnings = result.unwrap();
606 assert!(warnings.is_empty()); }
608
609 #[test]
610 fn test_lint_rule_filtering() {
611 let content = "# Heading\nJust text";
613 let rules: Vec<Box<dyn Rule>> = vec![
614 Box::new(MD001HeadingIncrement::default()),
615 ];
617
618 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
619 assert!(result.is_ok());
620 }
621
622 #[test]
623 fn test_get_profiling_report() {
624 let report = get_profiling_report();
626 assert!(!report.is_empty());
627 assert!(report.contains("Profiling"));
628 }
629
630 #[test]
631 fn test_reset_profiling() {
632 reset_profiling();
634
635 let report = get_profiling_report();
637 assert!(report.contains("disabled") || report.contains("no measurements"));
638 }
639
640 #[test]
641 fn test_get_regex_cache_stats() {
642 let stats = get_regex_cache_stats();
643 assert!(stats.is_empty() || !stats.is_empty());
645
646 for count in stats.values() {
648 assert!(*count > 0);
649 }
650 }
651
652 #[test]
653 fn test_content_characteristics_edge_cases() {
654 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
657
658 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
660
661 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");
671 assert!(!chars.has_blockquotes);
672 }
673}