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 && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
85 chars.has_lists = true;
86 }
87 if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
88 chars.has_lists = true;
89 }
90 if !chars.has_links
91 && (line.contains('[')
92 || line.contains("http://")
93 || line.contains("https://")
94 || line.contains("ftp://")
95 || line.contains("www."))
96 {
97 chars.has_links = true;
98 }
99 if !chars.has_images && line.contains("![") {
100 chars.has_images = true;
101 }
102 if !chars.has_code
103 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
104 {
105 chars.has_code = true;
106 }
107 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
108 chars.has_emphasis = true;
109 }
110 if !chars.has_html && line.contains('<') {
111 chars.has_html = true;
112 }
113 if !chars.has_tables && line.contains('|') {
114 chars.has_tables = true;
115 }
116 if !chars.has_blockquotes && line.starts_with('>') {
117 chars.has_blockquotes = true;
118 }
119 }
120
121 chars.has_headings = has_atx_heading || has_setext_heading;
122 chars
123 }
124
125 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
127 match rule.category() {
128 RuleCategory::Heading => !self.has_headings,
129 RuleCategory::List => !self.has_lists,
130 RuleCategory::Link => !self.has_links && !self.has_images,
131 RuleCategory::Image => !self.has_images,
132 RuleCategory::CodeBlock => !self.has_code,
133 RuleCategory::Html => !self.has_html,
134 RuleCategory::Emphasis => !self.has_emphasis,
135 RuleCategory::Blockquote => !self.has_blockquotes,
136 RuleCategory::Table => !self.has_tables,
137 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
139 }
140 }
141}
142
143#[cfg(feature = "native")]
148fn compute_content_hash(content: &str) -> String {
149 blake3::hash(content.as_bytes()).to_hex().to_string()
150}
151
152#[cfg(not(feature = "native"))]
154fn compute_content_hash(content: &str) -> String {
155 use std::hash::{DefaultHasher, Hash, Hasher};
156 let mut hasher = DefaultHasher::new();
157 content.hash(&mut hasher);
158 format!("{:016x}", hasher.finish())
159}
160
161pub fn lint(
165 content: &str,
166 rules: &[Box<dyn Rule>],
167 verbose: bool,
168 flavor: crate::config::MarkdownFlavor,
169 config: Option<&crate::config::Config>,
170) -> LintResult {
171 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
173 result
174}
175
176pub fn build_file_index_only(
184 content: &str,
185 rules: &[Box<dyn Rule>],
186 flavor: crate::config::MarkdownFlavor,
187) -> crate::workspace_index::FileIndex {
188 let content_hash = compute_content_hash(content);
190 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
191
192 if content.is_empty() {
194 return file_index;
195 }
196
197 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
199
200 for rule in rules {
202 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
203 rule.contribute_to_index(&lint_ctx, &mut file_index);
204 }
205 }
206
207 file_index
208}
209
210pub fn lint_and_index(
218 content: &str,
219 rules: &[Box<dyn Rule>],
220 _verbose: bool,
221 flavor: crate::config::MarkdownFlavor,
222 source_file: Option<std::path::PathBuf>,
223 config: Option<&crate::config::Config>,
224) -> (LintResult, crate::workspace_index::FileIndex) {
225 let mut warnings = Vec::new();
226 let content_hash = compute_content_hash(content);
228 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
229
230 #[cfg(not(target_arch = "wasm32"))]
231 let _overall_start = Instant::now();
232
233 if content.is_empty() {
235 return (Ok(warnings), file_index);
236 }
237
238 let inline_config = crate::inline_config::InlineConfig::from_content(content);
240
241 let (file_disabled, line_disabled) = inline_config.export_for_file_index();
243 file_index.file_disabled_rules = file_disabled;
244 file_index.line_disabled_rules = line_disabled;
245
246 let characteristics = ContentCharacteristics::analyze(content);
248
249 let applicable_rules: Vec<_> = rules
251 .iter()
252 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
253 .collect();
254
255 let _total_rules = rules.len();
257 let _applicable_count = applicable_rules.len();
258
259 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
261
262 #[cfg(not(target_arch = "wasm32"))]
263 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
264 #[cfg(target_arch = "wasm32")]
265 let profile_rules = false;
266
267 for rule in &applicable_rules {
268 #[cfg(not(target_arch = "wasm32"))]
269 let _rule_start = Instant::now();
270
271 let result = rule.check(&lint_ctx);
273
274 match result {
275 Ok(rule_warnings) => {
276 let filtered_warnings: Vec<_> = rule_warnings
278 .into_iter()
279 .filter(|warning| {
280 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
282
283 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
285 &rule_name_to_check[..dash_pos]
286 } else {
287 rule_name_to_check
288 };
289
290 !inline_config.is_rule_disabled(
291 base_rule_name,
292 warning.line, )
294 })
295 .map(|mut warning| {
296 if let Some(cfg) = config {
298 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
299 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
300 warning.severity = override_severity;
301 }
302 }
303 warning
304 })
305 .collect();
306 warnings.extend(filtered_warnings);
307 }
308 Err(e) => {
309 log::error!("Error checking rule {}: {}", rule.name(), e);
310 return (Err(e), file_index);
311 }
312 }
313
314 #[cfg(not(target_arch = "wasm32"))]
315 {
316 let rule_duration = _rule_start.elapsed();
317 if profile_rules {
318 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
319 }
320
321 #[cfg(not(test))]
322 if _verbose && rule_duration.as_millis() > 500 {
323 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
324 }
325 }
326 }
327
328 for rule in rules {
335 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
336 rule.contribute_to_index(&lint_ctx, &mut file_index);
337 }
338 }
339
340 #[cfg(not(test))]
341 if _verbose {
342 let skipped_rules = _total_rules - _applicable_count;
343 if skipped_rules > 0 {
344 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
345 }
346 }
347
348 (Ok(warnings), file_index)
349}
350
351pub fn run_cross_file_checks(
364 file_path: &std::path::Path,
365 file_index: &crate::workspace_index::FileIndex,
366 rules: &[Box<dyn Rule>],
367 workspace_index: &crate::workspace_index::WorkspaceIndex,
368 config: Option<&crate::config::Config>,
369) -> LintResult {
370 use crate::rule::CrossFileScope;
371
372 let mut warnings = Vec::new();
373
374 for rule in rules {
376 if rule.cross_file_scope() != CrossFileScope::Workspace {
377 continue;
378 }
379
380 match rule.cross_file_check(file_path, file_index, workspace_index) {
381 Ok(rule_warnings) => {
382 let filtered: Vec<_> = rule_warnings
384 .into_iter()
385 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
386 .map(|mut warning| {
387 if let Some(cfg) = config
389 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
390 {
391 warning.severity = override_severity;
392 }
393 warning
394 })
395 .collect();
396 warnings.extend(filtered);
397 }
398 Err(e) => {
399 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
400 return Err(e);
401 }
402 }
403 }
404
405 Ok(warnings)
406}
407
408pub fn get_profiling_report() -> String {
410 profiling::get_report()
411}
412
413pub fn reset_profiling() {
415 profiling::reset()
416}
417
418pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
420 crate::utils::regex_cache::get_cache_stats()
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426 use crate::rule::Rule;
427 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
428
429 #[test]
430 fn test_content_characteristics_analyze() {
431 let chars = ContentCharacteristics::analyze("");
433 assert!(!chars.has_headings);
434 assert!(!chars.has_lists);
435 assert!(!chars.has_links);
436 assert!(!chars.has_code);
437 assert!(!chars.has_emphasis);
438 assert!(!chars.has_html);
439 assert!(!chars.has_tables);
440 assert!(!chars.has_blockquotes);
441 assert!(!chars.has_images);
442
443 let chars = ContentCharacteristics::analyze("# Heading");
445 assert!(chars.has_headings);
446
447 let chars = ContentCharacteristics::analyze("Heading\n=======");
449 assert!(chars.has_headings);
450
451 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
453 assert!(chars.has_lists);
454
455 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
457 assert!(chars.has_lists);
458
459 let chars = ContentCharacteristics::analyze("[link](url)");
461 assert!(chars.has_links);
462
463 let chars = ContentCharacteristics::analyze("Visit https://example.com");
465 assert!(chars.has_links);
466
467 let chars = ContentCharacteristics::analyze("");
469 assert!(chars.has_images);
470
471 let chars = ContentCharacteristics::analyze("`inline code`");
473 assert!(chars.has_code);
474
475 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
476 assert!(chars.has_code);
477
478 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
480 assert!(chars.has_code);
481
482 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
484 assert!(chars.has_code);
485
486 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
488 assert!(chars.has_code);
489
490 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
492 assert!(chars.has_code);
493
494 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
496 assert!(chars.has_emphasis);
497
498 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
500 assert!(chars.has_html);
501
502 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
504 assert!(chars.has_tables);
505
506 let chars = ContentCharacteristics::analyze("> Quote");
508 assert!(chars.has_blockquotes);
509
510 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
512 let chars = ContentCharacteristics::analyze(content);
513 assert!(chars.has_headings);
514 assert!(chars.has_lists);
515 assert!(chars.has_links);
516 assert!(chars.has_code);
517 assert!(chars.has_emphasis);
518 assert!(chars.has_html);
519 assert!(chars.has_tables);
520 assert!(chars.has_blockquotes);
521 assert!(chars.has_images);
522 }
523
524 #[test]
525 fn test_content_characteristics_should_skip_rule() {
526 let chars = ContentCharacteristics {
527 has_headings: true,
528 has_lists: false,
529 has_links: true,
530 has_code: false,
531 has_emphasis: true,
532 has_html: false,
533 has_tables: true,
534 has_blockquotes: false,
535 has_images: false,
536 };
537
538 let heading_rule = MD001HeadingIncrement::default();
540 assert!(!chars.should_skip_rule(&heading_rule));
541
542 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
543 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
547 has_headings: false,
548 ..Default::default()
549 };
550 assert!(chars_no_headings.should_skip_rule(&heading_rule));
551 }
552
553 #[test]
554 fn test_lint_empty_content() {
555 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
556
557 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
558 assert!(result.is_ok());
559 assert!(result.unwrap().is_empty());
560 }
561
562 #[test]
563 fn test_lint_with_violations() {
564 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
566
567 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
568 assert!(result.is_ok());
569 let warnings = result.unwrap();
570 assert!(!warnings.is_empty());
571 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
573 }
574
575 #[test]
576 fn test_lint_with_inline_disable() {
577 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
578 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
579
580 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
581 assert!(result.is_ok());
582 let warnings = result.unwrap();
583 assert!(warnings.is_empty()); }
585
586 #[test]
587 fn test_lint_rule_filtering() {
588 let content = "# Heading\nJust text";
590 let rules: Vec<Box<dyn Rule>> = vec![
591 Box::new(MD001HeadingIncrement::default()),
592 ];
594
595 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
596 assert!(result.is_ok());
597 }
598
599 #[test]
600 fn test_get_profiling_report() {
601 let report = get_profiling_report();
603 assert!(!report.is_empty());
604 assert!(report.contains("Profiling"));
605 }
606
607 #[test]
608 fn test_reset_profiling() {
609 reset_profiling();
611
612 let report = get_profiling_report();
614 assert!(report.contains("disabled") || report.contains("no measurements"));
615 }
616
617 #[test]
618 fn test_get_regex_cache_stats() {
619 let stats = get_regex_cache_stats();
620 assert!(stats.is_empty() || !stats.is_empty());
622
623 for count in stats.values() {
625 assert!(*count > 0);
626 }
627 }
628
629 #[test]
630 fn test_content_characteristics_edge_cases() {
631 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
634
635 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
637
638 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
641
642 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
644
645 let chars = ContentCharacteristics::analyze("text > not a quote");
647 assert!(!chars.has_blockquotes);
648 }
649}