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};
40#[cfg(not(target_arch = "wasm32"))]
41use std::time::Instant;
42
43#[derive(Debug, Default)]
45struct ContentCharacteristics {
46 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, }
56
57impl ContentCharacteristics {
58 fn analyze(content: &str) -> Self {
59 let mut chars = Self { ..Default::default() };
60
61 let mut has_atx_heading = false;
63 let mut has_setext_heading = false;
64
65 for line in content.lines() {
66 let trimmed = line.trim();
67
68 if !has_atx_heading && trimmed.starts_with('#') {
70 has_atx_heading = true;
71 }
72 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
73 has_setext_heading = true;
74 }
75
76 if !chars.has_lists && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
78 chars.has_lists = true;
79 }
80 if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
81 chars.has_lists = true;
82 }
83 if !chars.has_links
84 && (line.contains('[')
85 || line.contains("http://")
86 || line.contains("https://")
87 || line.contains("ftp://"))
88 {
89 chars.has_links = true;
90 }
91 if !chars.has_images && line.contains("![") {
92 chars.has_images = true;
93 }
94 if !chars.has_code && (line.contains('`') || line.contains("~~~")) {
95 chars.has_code = true;
96 }
97 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
98 chars.has_emphasis = true;
99 }
100 if !chars.has_html && line.contains('<') {
101 chars.has_html = true;
102 }
103 if !chars.has_tables && line.contains('|') {
104 chars.has_tables = true;
105 }
106 if !chars.has_blockquotes && line.starts_with('>') {
107 chars.has_blockquotes = true;
108 }
109 }
110
111 chars.has_headings = has_atx_heading || has_setext_heading;
112 chars
113 }
114
115 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
117 match rule.category() {
118 RuleCategory::Heading => !self.has_headings,
119 RuleCategory::List => !self.has_lists,
120 RuleCategory::Link => !self.has_links && !self.has_images,
121 RuleCategory::Image => !self.has_images,
122 RuleCategory::CodeBlock => !self.has_code,
123 RuleCategory::Html => !self.has_html,
124 RuleCategory::Emphasis => !self.has_emphasis,
125 RuleCategory::Blockquote => !self.has_blockquotes,
126 RuleCategory::Table => !self.has_tables,
127 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
129 }
130 }
131}
132
133#[cfg(feature = "native")]
138fn compute_content_hash(content: &str) -> String {
139 blake3::hash(content.as_bytes()).to_hex().to_string()
140}
141
142#[cfg(not(feature = "native"))]
144fn compute_content_hash(content: &str) -> String {
145 use std::hash::{DefaultHasher, Hash, Hasher};
146 let mut hasher = DefaultHasher::new();
147 content.hash(&mut hasher);
148 format!("{:016x}", hasher.finish())
149}
150
151pub fn lint(
155 content: &str,
156 rules: &[Box<dyn Rule>],
157 verbose: bool,
158 flavor: crate::config::MarkdownFlavor,
159) -> LintResult {
160 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor);
162 result
163}
164
165pub fn build_file_index_only(
173 content: &str,
174 rules: &[Box<dyn Rule>],
175 flavor: crate::config::MarkdownFlavor,
176) -> crate::workspace_index::FileIndex {
177 let content_hash = compute_content_hash(content);
179 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
180
181 if content.is_empty() {
183 return file_index;
184 }
185
186 let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
188
189 for rule in rules {
191 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
192 rule.contribute_to_index(&lint_ctx, &mut file_index);
193 }
194 }
195
196 file_index
197}
198
199pub fn lint_and_index(
207 content: &str,
208 rules: &[Box<dyn Rule>],
209 _verbose: bool,
210 flavor: crate::config::MarkdownFlavor,
211) -> (LintResult, crate::workspace_index::FileIndex) {
212 let mut warnings = Vec::new();
213 let content_hash = compute_content_hash(content);
215 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
216
217 #[cfg(not(target_arch = "wasm32"))]
218 let _overall_start = Instant::now();
219
220 if content.is_empty() {
222 return (Ok(warnings), file_index);
223 }
224
225 let inline_config = crate::inline_config::InlineConfig::from_content(content);
227
228 let characteristics = ContentCharacteristics::analyze(content);
230
231 let applicable_rules: Vec<_> = rules
233 .iter()
234 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
235 .collect();
236
237 let _total_rules = rules.len();
239 let _applicable_count = applicable_rules.len();
240
241 let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
243
244 #[cfg(not(target_arch = "wasm32"))]
245 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
246 #[cfg(target_arch = "wasm32")]
247 let profile_rules = false;
248
249 for rule in &applicable_rules {
250 #[cfg(not(target_arch = "wasm32"))]
251 let _rule_start = Instant::now();
252
253 let result = rule.check(&lint_ctx);
255
256 match result {
257 Ok(rule_warnings) => {
258 let filtered_warnings: Vec<_> = rule_warnings
260 .into_iter()
261 .filter(|warning| {
262 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
264
265 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
267 &rule_name_to_check[..dash_pos]
268 } else {
269 rule_name_to_check
270 };
271
272 !inline_config.is_rule_disabled(
273 base_rule_name,
274 warning.line, )
276 })
277 .collect();
278 warnings.extend(filtered_warnings);
279 }
280 Err(e) => {
281 log::error!("Error checking rule {}: {}", rule.name(), e);
282 return (Err(e), file_index);
283 }
284 }
285
286 #[cfg(not(target_arch = "wasm32"))]
287 {
288 let rule_duration = _rule_start.elapsed();
289 if profile_rules {
290 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
291 }
292
293 #[cfg(not(test))]
294 if _verbose && rule_duration.as_millis() > 500 {
295 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
296 }
297 }
298 }
299
300 for rule in rules {
307 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
308 rule.contribute_to_index(&lint_ctx, &mut file_index);
309 }
310 }
311
312 #[cfg(not(test))]
313 if _verbose {
314 let skipped_rules = _total_rules - _applicable_count;
315 if skipped_rules > 0 {
316 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
317 }
318 }
319
320 (Ok(warnings), file_index)
321}
322
323pub fn run_cross_file_checks(
336 file_path: &std::path::Path,
337 file_index: &crate::workspace_index::FileIndex,
338 rules: &[Box<dyn Rule>],
339 workspace_index: &crate::workspace_index::WorkspaceIndex,
340) -> LintResult {
341 use crate::rule::CrossFileScope;
342
343 let mut warnings = Vec::new();
344
345 for rule in rules {
347 if rule.cross_file_scope() != CrossFileScope::Workspace {
348 continue;
349 }
350
351 match rule.cross_file_check(file_path, file_index, workspace_index) {
352 Ok(rule_warnings) => {
353 warnings.extend(rule_warnings);
357 }
358 Err(e) => {
359 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
360 return Err(e);
361 }
362 }
363 }
364
365 Ok(warnings)
366}
367
368pub fn get_profiling_report() -> String {
370 profiling::get_report()
371}
372
373pub fn reset_profiling() {
375 profiling::reset()
376}
377
378pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
380 crate::utils::regex_cache::get_cache_stats()
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386 use crate::rule::Rule;
387 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
388
389 #[test]
390 fn test_content_characteristics_analyze() {
391 let chars = ContentCharacteristics::analyze("");
393 assert!(!chars.has_headings);
394 assert!(!chars.has_lists);
395 assert!(!chars.has_links);
396 assert!(!chars.has_code);
397 assert!(!chars.has_emphasis);
398 assert!(!chars.has_html);
399 assert!(!chars.has_tables);
400 assert!(!chars.has_blockquotes);
401 assert!(!chars.has_images);
402
403 let chars = ContentCharacteristics::analyze("# Heading");
405 assert!(chars.has_headings);
406
407 let chars = ContentCharacteristics::analyze("Heading\n=======");
409 assert!(chars.has_headings);
410
411 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
413 assert!(chars.has_lists);
414
415 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
417 assert!(chars.has_lists);
418
419 let chars = ContentCharacteristics::analyze("[link](url)");
421 assert!(chars.has_links);
422
423 let chars = ContentCharacteristics::analyze("Visit https://example.com");
425 assert!(chars.has_links);
426
427 let chars = ContentCharacteristics::analyze("");
429 assert!(chars.has_images);
430
431 let chars = ContentCharacteristics::analyze("`inline code`");
433 assert!(chars.has_code);
434
435 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
436 assert!(chars.has_code);
437
438 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
440 assert!(chars.has_emphasis);
441
442 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
444 assert!(chars.has_html);
445
446 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
448 assert!(chars.has_tables);
449
450 let chars = ContentCharacteristics::analyze("> Quote");
452 assert!(chars.has_blockquotes);
453
454 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
456 let chars = ContentCharacteristics::analyze(content);
457 assert!(chars.has_headings);
458 assert!(chars.has_lists);
459 assert!(chars.has_links);
460 assert!(chars.has_code);
461 assert!(chars.has_emphasis);
462 assert!(chars.has_html);
463 assert!(chars.has_tables);
464 assert!(chars.has_blockquotes);
465 assert!(chars.has_images);
466 }
467
468 #[test]
469 fn test_content_characteristics_should_skip_rule() {
470 let chars = ContentCharacteristics {
471 has_headings: true,
472 has_lists: false,
473 has_links: true,
474 has_code: false,
475 has_emphasis: true,
476 has_html: false,
477 has_tables: true,
478 has_blockquotes: false,
479 has_images: false,
480 };
481
482 let heading_rule = MD001HeadingIncrement;
484 assert!(!chars.should_skip_rule(&heading_rule));
485
486 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
487 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
491 has_headings: false,
492 ..Default::default()
493 };
494 assert!(chars_no_headings.should_skip_rule(&heading_rule));
495 }
496
497 #[test]
498 fn test_lint_empty_content() {
499 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
500
501 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
502 assert!(result.is_ok());
503 assert!(result.unwrap().is_empty());
504 }
505
506 #[test]
507 fn test_lint_with_violations() {
508 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
510
511 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
512 assert!(result.is_ok());
513 let warnings = result.unwrap();
514 assert!(!warnings.is_empty());
515 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
517 }
518
519 #[test]
520 fn test_lint_with_inline_disable() {
521 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
522 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
523
524 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
525 assert!(result.is_ok());
526 let warnings = result.unwrap();
527 assert!(warnings.is_empty()); }
529
530 #[test]
531 fn test_lint_rule_filtering() {
532 let content = "# Heading\nJust text";
534 let rules: Vec<Box<dyn Rule>> = vec![
535 Box::new(MD001HeadingIncrement),
536 ];
538
539 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
540 assert!(result.is_ok());
541 }
542
543 #[test]
544 fn test_get_profiling_report() {
545 let report = get_profiling_report();
547 assert!(!report.is_empty());
548 assert!(report.contains("Profiling"));
549 }
550
551 #[test]
552 fn test_reset_profiling() {
553 reset_profiling();
555
556 let report = get_profiling_report();
558 assert!(report.contains("disabled") || report.contains("no measurements"));
559 }
560
561 #[test]
562 fn test_get_regex_cache_stats() {
563 let stats = get_regex_cache_stats();
564 assert!(stats.is_empty() || !stats.is_empty());
566
567 for count in stats.values() {
569 assert!(*count > 0);
570 }
571 }
572
573 #[test]
574 fn test_content_characteristics_edge_cases() {
575 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
578
579 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
581
582 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
585
586 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
588
589 let chars = ContentCharacteristics::analyze("text > not a quote");
591 assert!(!chars.has_blockquotes);
592 }
593}