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, None);
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, None);
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 source_file: Option<std::path::PathBuf>,
212) -> (LintResult, crate::workspace_index::FileIndex) {
213 let mut warnings = Vec::new();
214 let content_hash = compute_content_hash(content);
216 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
217
218 #[cfg(not(target_arch = "wasm32"))]
219 let _overall_start = Instant::now();
220
221 if content.is_empty() {
223 return (Ok(warnings), file_index);
224 }
225
226 let inline_config = crate::inline_config::InlineConfig::from_content(content);
228
229 let (file_disabled, line_disabled) = inline_config.export_for_file_index();
231 file_index.file_disabled_rules = file_disabled;
232 file_index.line_disabled_rules = line_disabled;
233
234 let characteristics = ContentCharacteristics::analyze(content);
236
237 let applicable_rules: Vec<_> = rules
239 .iter()
240 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
241 .collect();
242
243 let _total_rules = rules.len();
245 let _applicable_count = applicable_rules.len();
246
247 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
249
250 #[cfg(not(target_arch = "wasm32"))]
251 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
252 #[cfg(target_arch = "wasm32")]
253 let profile_rules = false;
254
255 for rule in &applicable_rules {
256 #[cfg(not(target_arch = "wasm32"))]
257 let _rule_start = Instant::now();
258
259 let result = rule.check(&lint_ctx);
261
262 match result {
263 Ok(rule_warnings) => {
264 let filtered_warnings: Vec<_> = rule_warnings
266 .into_iter()
267 .filter(|warning| {
268 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
270
271 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
273 &rule_name_to_check[..dash_pos]
274 } else {
275 rule_name_to_check
276 };
277
278 !inline_config.is_rule_disabled(
279 base_rule_name,
280 warning.line, )
282 })
283 .collect();
284 warnings.extend(filtered_warnings);
285 }
286 Err(e) => {
287 log::error!("Error checking rule {}: {}", rule.name(), e);
288 return (Err(e), file_index);
289 }
290 }
291
292 #[cfg(not(target_arch = "wasm32"))]
293 {
294 let rule_duration = _rule_start.elapsed();
295 if profile_rules {
296 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
297 }
298
299 #[cfg(not(test))]
300 if _verbose && rule_duration.as_millis() > 500 {
301 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
302 }
303 }
304 }
305
306 for rule in rules {
313 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
314 rule.contribute_to_index(&lint_ctx, &mut file_index);
315 }
316 }
317
318 #[cfg(not(test))]
319 if _verbose {
320 let skipped_rules = _total_rules - _applicable_count;
321 if skipped_rules > 0 {
322 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
323 }
324 }
325
326 (Ok(warnings), file_index)
327}
328
329pub fn run_cross_file_checks(
342 file_path: &std::path::Path,
343 file_index: &crate::workspace_index::FileIndex,
344 rules: &[Box<dyn Rule>],
345 workspace_index: &crate::workspace_index::WorkspaceIndex,
346) -> LintResult {
347 use crate::rule::CrossFileScope;
348
349 let mut warnings = Vec::new();
350
351 for rule in rules {
353 if rule.cross_file_scope() != CrossFileScope::Workspace {
354 continue;
355 }
356
357 match rule.cross_file_check(file_path, file_index, workspace_index) {
358 Ok(rule_warnings) => {
359 let filtered: Vec<_> = rule_warnings
361 .into_iter()
362 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
363 .collect();
364 warnings.extend(filtered);
365 }
366 Err(e) => {
367 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
368 return Err(e);
369 }
370 }
371 }
372
373 Ok(warnings)
374}
375
376pub fn get_profiling_report() -> String {
378 profiling::get_report()
379}
380
381pub fn reset_profiling() {
383 profiling::reset()
384}
385
386pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
388 crate::utils::regex_cache::get_cache_stats()
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394 use crate::rule::Rule;
395 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
396
397 #[test]
398 fn test_content_characteristics_analyze() {
399 let chars = ContentCharacteristics::analyze("");
401 assert!(!chars.has_headings);
402 assert!(!chars.has_lists);
403 assert!(!chars.has_links);
404 assert!(!chars.has_code);
405 assert!(!chars.has_emphasis);
406 assert!(!chars.has_html);
407 assert!(!chars.has_tables);
408 assert!(!chars.has_blockquotes);
409 assert!(!chars.has_images);
410
411 let chars = ContentCharacteristics::analyze("# Heading");
413 assert!(chars.has_headings);
414
415 let chars = ContentCharacteristics::analyze("Heading\n=======");
417 assert!(chars.has_headings);
418
419 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
421 assert!(chars.has_lists);
422
423 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
425 assert!(chars.has_lists);
426
427 let chars = ContentCharacteristics::analyze("[link](url)");
429 assert!(chars.has_links);
430
431 let chars = ContentCharacteristics::analyze("Visit https://example.com");
433 assert!(chars.has_links);
434
435 let chars = ContentCharacteristics::analyze("");
437 assert!(chars.has_images);
438
439 let chars = ContentCharacteristics::analyze("`inline code`");
441 assert!(chars.has_code);
442
443 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
444 assert!(chars.has_code);
445
446 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
448 assert!(chars.has_emphasis);
449
450 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
452 assert!(chars.has_html);
453
454 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
456 assert!(chars.has_tables);
457
458 let chars = ContentCharacteristics::analyze("> Quote");
460 assert!(chars.has_blockquotes);
461
462 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
464 let chars = ContentCharacteristics::analyze(content);
465 assert!(chars.has_headings);
466 assert!(chars.has_lists);
467 assert!(chars.has_links);
468 assert!(chars.has_code);
469 assert!(chars.has_emphasis);
470 assert!(chars.has_html);
471 assert!(chars.has_tables);
472 assert!(chars.has_blockquotes);
473 assert!(chars.has_images);
474 }
475
476 #[test]
477 fn test_content_characteristics_should_skip_rule() {
478 let chars = ContentCharacteristics {
479 has_headings: true,
480 has_lists: false,
481 has_links: true,
482 has_code: false,
483 has_emphasis: true,
484 has_html: false,
485 has_tables: true,
486 has_blockquotes: false,
487 has_images: false,
488 };
489
490 let heading_rule = MD001HeadingIncrement;
492 assert!(!chars.should_skip_rule(&heading_rule));
493
494 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
495 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
499 has_headings: false,
500 ..Default::default()
501 };
502 assert!(chars_no_headings.should_skip_rule(&heading_rule));
503 }
504
505 #[test]
506 fn test_lint_empty_content() {
507 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
508
509 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
510 assert!(result.is_ok());
511 assert!(result.unwrap().is_empty());
512 }
513
514 #[test]
515 fn test_lint_with_violations() {
516 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
518
519 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
520 assert!(result.is_ok());
521 let warnings = result.unwrap();
522 assert!(!warnings.is_empty());
523 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
525 }
526
527 #[test]
528 fn test_lint_with_inline_disable() {
529 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
530 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
531
532 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
533 assert!(result.is_ok());
534 let warnings = result.unwrap();
535 assert!(warnings.is_empty()); }
537
538 #[test]
539 fn test_lint_rule_filtering() {
540 let content = "# Heading\nJust text";
542 let rules: Vec<Box<dyn Rule>> = vec![
543 Box::new(MD001HeadingIncrement),
544 ];
546
547 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
548 assert!(result.is_ok());
549 }
550
551 #[test]
552 fn test_get_profiling_report() {
553 let report = get_profiling_report();
555 assert!(!report.is_empty());
556 assert!(report.contains("Profiling"));
557 }
558
559 #[test]
560 fn test_reset_profiling() {
561 reset_profiling();
563
564 let report = get_profiling_report();
566 assert!(report.contains("disabled") || report.contains("no measurements"));
567 }
568
569 #[test]
570 fn test_get_regex_cache_stats() {
571 let stats = get_regex_cache_stats();
572 assert!(stats.is_empty() || !stats.is_empty());
574
575 for count in stats.values() {
577 assert!(*count > 0);
578 }
579 }
580
581 #[test]
582 fn test_content_characteristics_edge_cases() {
583 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
586
587 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
589
590 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
593
594 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
596
597 let chars = ContentCharacteristics::analyze("text > not a quote");
599 assert!(!chars.has_blockquotes);
600 }
601}