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
99 && line.chars().next().is_some_and(|c| c.is_ascii_digit())
100 && (line.contains(". ") || line.contains('.'))
101 {
102 chars.has_lists = true;
103 }
104 if !chars.has_links
105 && (line.contains('[')
106 || line.contains("http://")
107 || line.contains("https://")
108 || line.contains("ftp://")
109 || line.contains("www."))
110 {
111 chars.has_links = true;
112 }
113 if !chars.has_images && line.contains("![") {
114 chars.has_images = true;
115 }
116 if !chars.has_code
117 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
118 {
119 chars.has_code = true;
120 }
121 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
122 chars.has_emphasis = true;
123 }
124 if !chars.has_html && line.contains('<') {
125 chars.has_html = true;
126 }
127 if !chars.has_tables && line.contains('|') {
128 chars.has_tables = true;
129 }
130 if !chars.has_blockquotes && line.starts_with('>') {
131 chars.has_blockquotes = true;
132 }
133 }
134
135 chars.has_headings = has_atx_heading || has_setext_heading;
136 chars
137 }
138
139 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
141 match rule.category() {
142 RuleCategory::Heading => !self.has_headings,
143 RuleCategory::List => !self.has_lists,
144 RuleCategory::Link => !self.has_links && !self.has_images,
145 RuleCategory::Image => !self.has_images,
146 RuleCategory::CodeBlock => !self.has_code,
147 RuleCategory::Html => !self.has_html,
148 RuleCategory::Emphasis => !self.has_emphasis,
149 RuleCategory::Blockquote => !self.has_blockquotes,
150 RuleCategory::Table => !self.has_tables,
151 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
153 }
154 }
155}
156
157#[cfg(feature = "native")]
162fn compute_content_hash(content: &str) -> String {
163 blake3::hash(content.as_bytes()).to_hex().to_string()
164}
165
166#[cfg(not(feature = "native"))]
168fn compute_content_hash(content: &str) -> String {
169 use std::hash::{DefaultHasher, Hash, Hasher};
170 let mut hasher = DefaultHasher::new();
171 content.hash(&mut hasher);
172 format!("{:016x}", hasher.finish())
173}
174
175pub fn lint(
179 content: &str,
180 rules: &[Box<dyn Rule>],
181 verbose: bool,
182 flavor: crate::config::MarkdownFlavor,
183 config: Option<&crate::config::Config>,
184) -> LintResult {
185 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
187 result
188}
189
190pub fn build_file_index_only(
198 content: &str,
199 rules: &[Box<dyn Rule>],
200 flavor: crate::config::MarkdownFlavor,
201) -> crate::workspace_index::FileIndex {
202 let content_hash = compute_content_hash(content);
204 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
205
206 if content.is_empty() {
208 return file_index;
209 }
210
211 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
213
214 for rule in rules {
216 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
217 rule.contribute_to_index(&lint_ctx, &mut file_index);
218 }
219 }
220
221 file_index
222}
223
224pub fn lint_and_index(
232 content: &str,
233 rules: &[Box<dyn Rule>],
234 _verbose: bool,
235 flavor: crate::config::MarkdownFlavor,
236 source_file: Option<std::path::PathBuf>,
237 config: Option<&crate::config::Config>,
238) -> (LintResult, crate::workspace_index::FileIndex) {
239 let mut warnings = Vec::new();
240 let content_hash = compute_content_hash(content);
242 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
243
244 #[cfg(not(target_arch = "wasm32"))]
245 let _overall_start = Instant::now();
246
247 if content.is_empty() {
249 return (Ok(warnings), file_index);
250 }
251
252 let inline_config = crate::inline_config::InlineConfig::from_content(content);
254
255 let (file_disabled, line_disabled) = inline_config.export_for_file_index();
257 file_index.file_disabled_rules = file_disabled;
258 file_index.line_disabled_rules = line_disabled;
259
260 let characteristics = ContentCharacteristics::analyze(content);
262
263 let applicable_rules: Vec<_> = rules
265 .iter()
266 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
267 .collect();
268
269 let _total_rules = rules.len();
271 let _applicable_count = applicable_rules.len();
272
273 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
275
276 #[cfg(not(target_arch = "wasm32"))]
277 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
278 #[cfg(target_arch = "wasm32")]
279 let profile_rules = false;
280
281 for rule in &applicable_rules {
282 #[cfg(not(target_arch = "wasm32"))]
283 let _rule_start = Instant::now();
284
285 let result = rule.check(&lint_ctx);
287
288 match result {
289 Ok(rule_warnings) => {
290 let filtered_warnings: Vec<_> = rule_warnings
292 .into_iter()
293 .filter(|warning| {
294 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
296
297 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
299 &rule_name_to_check[..dash_pos]
300 } else {
301 rule_name_to_check
302 };
303
304 !inline_config.is_rule_disabled(
305 base_rule_name,
306 warning.line, )
308 })
309 .map(|mut warning| {
310 if let Some(cfg) = config {
312 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
313 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
314 warning.severity = override_severity;
315 }
316 }
317 warning
318 })
319 .collect();
320 warnings.extend(filtered_warnings);
321 }
322 Err(e) => {
323 log::error!("Error checking rule {}: {}", rule.name(), e);
324 return (Err(e), file_index);
325 }
326 }
327
328 #[cfg(not(target_arch = "wasm32"))]
329 {
330 let rule_duration = _rule_start.elapsed();
331 if profile_rules {
332 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
333 }
334
335 #[cfg(not(test))]
336 if _verbose && rule_duration.as_millis() > 500 {
337 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
338 }
339 }
340 }
341
342 for rule in rules {
349 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
350 rule.contribute_to_index(&lint_ctx, &mut file_index);
351 }
352 }
353
354 #[cfg(not(test))]
355 if _verbose {
356 let skipped_rules = _total_rules - _applicable_count;
357 if skipped_rules > 0 {
358 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
359 }
360 }
361
362 (Ok(warnings), file_index)
363}
364
365pub fn run_cross_file_checks(
378 file_path: &std::path::Path,
379 file_index: &crate::workspace_index::FileIndex,
380 rules: &[Box<dyn Rule>],
381 workspace_index: &crate::workspace_index::WorkspaceIndex,
382 config: Option<&crate::config::Config>,
383) -> LintResult {
384 use crate::rule::CrossFileScope;
385
386 let mut warnings = Vec::new();
387
388 for rule in rules {
390 if rule.cross_file_scope() != CrossFileScope::Workspace {
391 continue;
392 }
393
394 match rule.cross_file_check(file_path, file_index, workspace_index) {
395 Ok(rule_warnings) => {
396 let filtered: Vec<_> = rule_warnings
398 .into_iter()
399 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
400 .map(|mut warning| {
401 if let Some(cfg) = config
403 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
404 {
405 warning.severity = override_severity;
406 }
407 warning
408 })
409 .collect();
410 warnings.extend(filtered);
411 }
412 Err(e) => {
413 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
414 return Err(e);
415 }
416 }
417 }
418
419 Ok(warnings)
420}
421
422pub fn get_profiling_report() -> String {
424 profiling::get_report()
425}
426
427pub fn reset_profiling() {
429 profiling::reset()
430}
431
432pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
434 crate::utils::regex_cache::get_cache_stats()
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440 use crate::rule::Rule;
441 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
442
443 #[test]
444 fn test_content_characteristics_analyze() {
445 let chars = ContentCharacteristics::analyze("");
447 assert!(!chars.has_headings);
448 assert!(!chars.has_lists);
449 assert!(!chars.has_links);
450 assert!(!chars.has_code);
451 assert!(!chars.has_emphasis);
452 assert!(!chars.has_html);
453 assert!(!chars.has_tables);
454 assert!(!chars.has_blockquotes);
455 assert!(!chars.has_images);
456
457 let chars = ContentCharacteristics::analyze("# Heading");
459 assert!(chars.has_headings);
460
461 let chars = ContentCharacteristics::analyze("Heading\n=======");
463 assert!(chars.has_headings);
464
465 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
467 assert!(chars.has_lists);
468
469 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
471 assert!(chars.has_lists);
472
473 let chars = ContentCharacteristics::analyze("[link](url)");
475 assert!(chars.has_links);
476
477 let chars = ContentCharacteristics::analyze("Visit https://example.com");
479 assert!(chars.has_links);
480
481 let chars = ContentCharacteristics::analyze("");
483 assert!(chars.has_images);
484
485 let chars = ContentCharacteristics::analyze("`inline code`");
487 assert!(chars.has_code);
488
489 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
490 assert!(chars.has_code);
491
492 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
494 assert!(chars.has_code);
495
496 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
498 assert!(chars.has_code);
499
500 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
502 assert!(chars.has_code);
503
504 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
506 assert!(chars.has_code);
507
508 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
510 assert!(chars.has_emphasis);
511
512 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
514 assert!(chars.has_html);
515
516 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
518 assert!(chars.has_tables);
519
520 let chars = ContentCharacteristics::analyze("> Quote");
522 assert!(chars.has_blockquotes);
523
524 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
526 let chars = ContentCharacteristics::analyze(content);
527 assert!(chars.has_headings);
528 assert!(chars.has_lists);
529 assert!(chars.has_links);
530 assert!(chars.has_code);
531 assert!(chars.has_emphasis);
532 assert!(chars.has_html);
533 assert!(chars.has_tables);
534 assert!(chars.has_blockquotes);
535 assert!(chars.has_images);
536 }
537
538 #[test]
539 fn test_content_characteristics_should_skip_rule() {
540 let chars = ContentCharacteristics {
541 has_headings: true,
542 has_lists: false,
543 has_links: true,
544 has_code: false,
545 has_emphasis: true,
546 has_html: false,
547 has_tables: true,
548 has_blockquotes: false,
549 has_images: false,
550 };
551
552 let heading_rule = MD001HeadingIncrement::default();
554 assert!(!chars.should_skip_rule(&heading_rule));
555
556 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
557 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
561 has_headings: false,
562 ..Default::default()
563 };
564 assert!(chars_no_headings.should_skip_rule(&heading_rule));
565 }
566
567 #[test]
568 fn test_lint_empty_content() {
569 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
570
571 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
572 assert!(result.is_ok());
573 assert!(result.unwrap().is_empty());
574 }
575
576 #[test]
577 fn test_lint_with_violations() {
578 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
580
581 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
582 assert!(result.is_ok());
583 let warnings = result.unwrap();
584 assert!(!warnings.is_empty());
585 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
587 }
588
589 #[test]
590 fn test_lint_with_inline_disable() {
591 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
592 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
593
594 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
595 assert!(result.is_ok());
596 let warnings = result.unwrap();
597 assert!(warnings.is_empty()); }
599
600 #[test]
601 fn test_lint_rule_filtering() {
602 let content = "# Heading\nJust text";
604 let rules: Vec<Box<dyn Rule>> = vec![
605 Box::new(MD001HeadingIncrement::default()),
606 ];
608
609 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
610 assert!(result.is_ok());
611 }
612
613 #[test]
614 fn test_get_profiling_report() {
615 let report = get_profiling_report();
617 assert!(!report.is_empty());
618 assert!(report.contains("Profiling"));
619 }
620
621 #[test]
622 fn test_reset_profiling() {
623 reset_profiling();
625
626 let report = get_profiling_report();
628 assert!(report.contains("disabled") || report.contains("no measurements"));
629 }
630
631 #[test]
632 fn test_get_regex_cache_stats() {
633 let stats = get_regex_cache_stats();
634 assert!(stats.is_empty() || !stats.is_empty());
636
637 for count in stats.values() {
639 assert!(*count > 0);
640 }
641 }
642
643 #[test]
644 fn test_content_characteristics_edge_cases() {
645 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
648
649 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
651
652 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");
662 assert!(!chars.has_blockquotes);
663 }
664}