1#![warn(unreachable_pub)]
2#![warn(clippy::pedantic)]
3#![allow(clippy::doc_markdown)]
7#![allow(clippy::must_use_candidate)]
8#![allow(clippy::missing_errors_doc)]
9#![allow(clippy::missing_panics_doc)]
10#![allow(clippy::too_many_lines)]
11#![allow(clippy::if_not_else)]
12#![allow(clippy::similar_names)]
13#![allow(clippy::wildcard_imports)]
14#![allow(clippy::case_sensitive_file_extension_comparisons)]
15#![allow(clippy::doc_link_with_quotes)]
16#![allow(clippy::needless_raw_string_hashes)]
17#![allow(clippy::trivially_copy_pass_by_ref)]
18#![allow(clippy::struct_excessive_bools)]
19#![allow(clippy::fn_params_excessive_bools)]
20#![allow(clippy::elidable_lifetime_names)]
21#![allow(clippy::return_self_not_must_use)]
22#![allow(clippy::redundant_else)]
23#![allow(clippy::single_match_else)]
24#![allow(clippy::needless_continue)]
25#![allow(clippy::semicolon_if_nothing_returned)]
26#![allow(clippy::ignored_unit_patterns)]
27#![allow(clippy::unreadable_literal)]
28#![allow(clippy::implicit_hasher)]
29#![allow(clippy::ref_option)]
30#![allow(clippy::struct_field_names)]
31#![allow(clippy::unused_self)]
32#![allow(clippy::unnested_or_patterns)]
33#![allow(clippy::cast_precision_loss)]
34#![allow(clippy::cast_sign_loss)]
35#![allow(clippy::cast_possible_wrap)]
36#![allow(clippy::cast_possible_truncation)]
37#![allow(clippy::cast_lossless)]
38#![allow(clippy::items_after_statements)]
39#![allow(clippy::match_same_arms)]
40#![allow(clippy::format_push_string)]
41#![allow(clippy::no_effect_underscore_binding)]
44#![allow(clippy::default_trait_access)]
46#![allow(clippy::manual_string_new)]
49
50pub mod code_block_tools;
51pub mod config;
52pub mod doc_comment_lint;
53pub mod embedded_lint;
54pub mod exit_codes;
55pub mod filtered_lines;
56pub mod fix_coordinator;
57pub mod inline_config;
58pub mod linguist_data;
59pub mod lint_context;
60pub mod markdownlint_config;
61pub mod profiling;
62pub mod rule;
63#[cfg(feature = "native")]
64pub mod vscode;
65pub mod workspace_index;
66#[macro_use]
67pub mod rule_config;
68#[macro_use]
69pub mod rule_config_serde;
70pub mod rules;
71pub mod types;
72pub mod utils;
73
74#[cfg(feature = "native")]
76pub mod lsp;
77#[cfg(feature = "native")]
78pub mod output;
79#[cfg(feature = "native")]
80pub mod parallel;
81#[cfg(feature = "native")]
82pub mod performance;
83
84#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
86pub mod wasm;
87
88pub use rules::heading_utils::HeadingStyle;
89pub use rules::*;
90
91pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
92use crate::rule::{LintResult, Rule, RuleCategory};
93use crate::utils::calculate_indentation_width_default;
94#[cfg(not(target_arch = "wasm32"))]
95use std::time::Instant;
96
97#[derive(Debug, Default)]
99struct ContentCharacteristics {
100 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, }
110
111fn has_potential_indented_code_indent(line: &str) -> bool {
114 calculate_indentation_width_default(line) >= 4
115}
116
117impl ContentCharacteristics {
118 fn analyze(content: &str) -> Self {
119 let mut chars = Self { ..Default::default() };
120
121 let mut has_atx_heading = false;
123 let mut has_setext_heading = false;
124
125 for line in content.lines() {
126 let trimmed = line.trim();
127
128 if !has_atx_heading && trimmed.starts_with('#') {
130 has_atx_heading = true;
131 }
132 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
133 has_setext_heading = true;
134 }
135
136 if !chars.has_lists
139 && (line.contains("* ")
140 || line.contains("- ")
141 || line.contains("+ ")
142 || trimmed.starts_with("* ")
143 || trimmed.starts_with("- ")
144 || trimmed.starts_with("+ ")
145 || trimmed.starts_with('*')
146 || trimmed.starts_with('-')
147 || trimmed.starts_with('+'))
148 {
149 chars.has_lists = true;
150 }
151 if !chars.has_lists
153 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
154 && (line.contains(". ") || line.contains('.')))
155 || (trimmed.starts_with('>')
156 && trimmed.chars().any(|c| c.is_ascii_digit())
157 && (trimmed.contains(". ") || trimmed.contains('.'))))
158 {
159 chars.has_lists = true;
160 }
161 if !chars.has_links
162 && (line.contains('[')
163 || line.contains("http://")
164 || line.contains("https://")
165 || line.contains("ftp://")
166 || line.contains("www."))
167 {
168 chars.has_links = true;
169 }
170 if !chars.has_images && line.contains("![") {
171 chars.has_images = true;
172 }
173 if !chars.has_code
174 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
175 {
176 chars.has_code = true;
177 }
178 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
179 chars.has_emphasis = true;
180 }
181 if !chars.has_html && line.contains('<') {
182 chars.has_html = true;
183 }
184 if !chars.has_tables && line.contains('|') {
185 chars.has_tables = true;
186 }
187 if !chars.has_blockquotes && line.starts_with('>') {
188 chars.has_blockquotes = true;
189 }
190 }
191
192 chars.has_headings = has_atx_heading || has_setext_heading;
193 chars
194 }
195
196 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
198 match rule.category() {
199 RuleCategory::Heading => !self.has_headings,
200 RuleCategory::List => !self.has_lists,
201 RuleCategory::Link => !self.has_links && !self.has_images,
202 RuleCategory::Image => !self.has_images,
203 RuleCategory::CodeBlock => !self.has_code,
204 RuleCategory::Html => !self.has_html,
205 RuleCategory::Emphasis => !self.has_emphasis,
206 RuleCategory::Blockquote => !self.has_blockquotes,
207 RuleCategory::Table => !self.has_tables,
208 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
210 }
211 }
212}
213
214#[cfg(feature = "native")]
219fn compute_content_hash(content: &str) -> String {
220 blake3::hash(content.as_bytes()).to_hex().to_string()
221}
222
223#[cfg(not(feature = "native"))]
225fn compute_content_hash(content: &str) -> String {
226 use std::hash::{DefaultHasher, Hash, Hasher};
227 let mut hasher = DefaultHasher::new();
228 content.hash(&mut hasher);
229 format!("{:016x}", hasher.finish())
230}
231
232pub fn lint(
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 {
243 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
244 result
245}
246
247pub fn build_file_index_only(
255 content: &str,
256 rules: &[Box<dyn Rule>],
257 flavor: crate::config::MarkdownFlavor,
258 source_file: Option<std::path::PathBuf>,
259) -> crate::workspace_index::FileIndex {
260 let content_hash = compute_content_hash(content);
262 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
263
264 if content.is_empty() {
266 return file_index;
267 }
268
269 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
271
272 for rule in rules {
274 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
275 rule.contribute_to_index(&lint_ctx, &mut file_index);
276 }
277 }
278
279 file_index
280}
281
282#[cfg_attr(test, allow(unused_variables))]
290pub fn lint_and_index(
291 content: &str,
292 rules: &[Box<dyn Rule>],
293 verbose: bool,
294 flavor: crate::config::MarkdownFlavor,
295 source_file: Option<std::path::PathBuf>,
296 config: Option<&crate::config::Config>,
297) -> (LintResult, crate::workspace_index::FileIndex) {
298 let mut warnings = Vec::new();
299 let content_hash = compute_content_hash(content);
301 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
302
303 if content.is_empty() {
305 return (Ok(warnings), file_index);
306 }
307
308 let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
310 let inline_config = lint_ctx.inline_config();
311
312 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
314 file_index.file_disabled_rules = file_disabled;
315 file_index.persistent_transitions = persistent_transitions;
316 file_index.line_disabled_rules = line_disabled;
317
318 let characteristics = ContentCharacteristics::analyze(content);
320
321 let applicable_rules: Vec<_> = rules
323 .iter()
324 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
325 .collect();
326
327 #[cfg(not(test))]
329 let total_rules = rules.len();
330 #[cfg(not(test))]
331 let applicable_count = applicable_rules.len();
332
333 #[cfg(not(target_arch = "wasm32"))]
334 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
335
336 let inline_overrides = inline_config.get_all_rule_configs();
339 let merged_config = if !inline_overrides.is_empty() {
340 config.map(|c| c.merge_with_inline_config(inline_config))
341 } else {
342 None
343 };
344 let effective_config = merged_config.as_ref().or(config);
345
346 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
348 std::collections::HashMap::new();
349
350 if let Some(cfg) = effective_config {
352 for rule_name in inline_overrides.keys() {
353 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
354 recreated_rules.insert(rule_name.clone(), recreated);
355 }
356 }
357 }
358
359 for rule in &applicable_rules {
360 #[cfg(not(target_arch = "wasm32"))]
361 let rule_start = Instant::now();
362
363 if rule.should_skip(&lint_ctx) {
365 continue;
366 }
367
368 let effective_rule: &dyn crate::rule::Rule = recreated_rules
370 .get(rule.name())
371 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
372
373 let result = effective_rule.check(&lint_ctx);
375
376 match result {
377 Ok(rule_warnings) => {
378 let filtered_warnings: Vec<_> = rule_warnings
381 .into_iter()
382 .filter(|warning| {
383 if lint_ctx
385 .line_info(warning.line)
386 .is_some_and(|info| info.in_kramdown_extension_block)
387 {
388 return false;
389 }
390
391 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
393
394 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
396 &rule_name_to_check[..dash_pos]
397 } else {
398 rule_name_to_check
399 };
400
401 {
407 let end = if warning.end_line >= warning.line {
408 warning.end_line
409 } else {
410 warning.line
411 };
412 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
413 }
414 })
415 .map(|mut warning| {
416 if let Some(cfg) = config {
418 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
419 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
420 warning.severity = override_severity;
421 }
422 }
423 warning
424 })
425 .collect();
426 warnings.extend(filtered_warnings);
427 }
428 Err(e) => {
429 log::error!("Error checking rule {}: {}", rule.name(), e);
430 return (Err(e), file_index);
431 }
432 }
433
434 #[cfg(not(target_arch = "wasm32"))]
435 {
436 let rule_duration = rule_start.elapsed();
437 if profile_rules {
438 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
439 }
440
441 #[cfg(not(test))]
442 if verbose && rule_duration.as_millis() > 500 {
443 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
444 }
445 }
446 }
447
448 for rule in rules {
455 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
456 rule.contribute_to_index(&lint_ctx, &mut file_index);
457 }
458 }
459
460 #[cfg(not(test))]
461 if verbose {
462 let skipped_rules = total_rules - applicable_count;
463 if skipped_rules > 0 {
464 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
465 }
466 }
467
468 (Ok(warnings), file_index)
469}
470
471pub fn run_cross_file_checks(
484 file_path: &std::path::Path,
485 file_index: &crate::workspace_index::FileIndex,
486 rules: &[Box<dyn Rule>],
487 workspace_index: &crate::workspace_index::WorkspaceIndex,
488 config: Option<&crate::config::Config>,
489) -> LintResult {
490 use crate::rule::CrossFileScope;
491
492 let mut warnings = Vec::new();
493
494 for rule in rules {
496 if rule.cross_file_scope() != CrossFileScope::Workspace {
497 continue;
498 }
499
500 match rule.cross_file_check(file_path, file_index, workspace_index) {
501 Ok(rule_warnings) => {
502 let filtered: Vec<_> = rule_warnings
504 .into_iter()
505 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
506 .map(|mut warning| {
507 if let Some(cfg) = config
509 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
510 {
511 warning.severity = override_severity;
512 }
513 warning
514 })
515 .collect();
516 warnings.extend(filtered);
517 }
518 Err(e) => {
519 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
520 return Err(e);
521 }
522 }
523 }
524
525 Ok(warnings)
526}
527
528pub fn get_profiling_report() -> String {
530 profiling::get_report()
531}
532
533pub fn reset_profiling() {
535 profiling::reset()
536}
537
538pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
540 crate::utils::regex_cache::get_cache_stats()
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546 use crate::rule::Rule;
547 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
548
549 #[test]
550 fn test_content_characteristics_analyze() {
551 let chars = ContentCharacteristics::analyze("");
553 assert!(!chars.has_headings);
554 assert!(!chars.has_lists);
555 assert!(!chars.has_links);
556 assert!(!chars.has_code);
557 assert!(!chars.has_emphasis);
558 assert!(!chars.has_html);
559 assert!(!chars.has_tables);
560 assert!(!chars.has_blockquotes);
561 assert!(!chars.has_images);
562
563 let chars = ContentCharacteristics::analyze("# Heading");
565 assert!(chars.has_headings);
566
567 let chars = ContentCharacteristics::analyze("Heading\n=======");
569 assert!(chars.has_headings);
570
571 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
573 assert!(chars.has_lists);
574
575 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
577 assert!(chars.has_lists);
578
579 let chars = ContentCharacteristics::analyze("[link](url)");
581 assert!(chars.has_links);
582
583 let chars = ContentCharacteristics::analyze("Visit https://example.com");
585 assert!(chars.has_links);
586
587 let chars = ContentCharacteristics::analyze("");
589 assert!(chars.has_images);
590
591 let chars = ContentCharacteristics::analyze("`inline code`");
593 assert!(chars.has_code);
594
595 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
596 assert!(chars.has_code);
597
598 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
600 assert!(chars.has_code);
601
602 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
604 assert!(chars.has_code);
605
606 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
608 assert!(chars.has_code);
609
610 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
612 assert!(chars.has_code);
613
614 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
616 assert!(chars.has_emphasis);
617
618 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
620 assert!(chars.has_html);
621
622 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
624 assert!(chars.has_tables);
625
626 let chars = ContentCharacteristics::analyze("> Quote");
628 assert!(chars.has_blockquotes);
629
630 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
632 let chars = ContentCharacteristics::analyze(content);
633 assert!(chars.has_headings);
634 assert!(chars.has_lists);
635 assert!(chars.has_links);
636 assert!(chars.has_code);
637 assert!(chars.has_emphasis);
638 assert!(chars.has_html);
639 assert!(chars.has_tables);
640 assert!(chars.has_blockquotes);
641 assert!(chars.has_images);
642 }
643
644 #[test]
645 fn test_content_characteristics_should_skip_rule() {
646 let chars = ContentCharacteristics {
647 has_headings: true,
648 has_lists: false,
649 has_links: true,
650 has_code: false,
651 has_emphasis: true,
652 has_html: false,
653 has_tables: true,
654 has_blockquotes: false,
655 has_images: false,
656 };
657
658 let heading_rule = MD001HeadingIncrement::default();
660 assert!(!chars.should_skip_rule(&heading_rule));
661
662 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
663 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
667 has_headings: false,
668 ..Default::default()
669 };
670 assert!(chars_no_headings.should_skip_rule(&heading_rule));
671 }
672
673 #[test]
674 fn test_lint_empty_content() {
675 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
676
677 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
678 assert!(result.is_ok());
679 assert!(result.unwrap().is_empty());
680 }
681
682 #[test]
683 fn test_lint_with_violations() {
684 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
686
687 let result = lint(
688 content,
689 &rules,
690 false,
691 crate::config::MarkdownFlavor::Standard,
692 None,
693 None,
694 );
695 assert!(result.is_ok());
696 let warnings = result.unwrap();
697 assert!(!warnings.is_empty());
698 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
700 }
701
702 #[test]
703 fn test_lint_with_inline_disable() {
704 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
705 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
706
707 let result = lint(
708 content,
709 &rules,
710 false,
711 crate::config::MarkdownFlavor::Standard,
712 None,
713 None,
714 );
715 assert!(result.is_ok());
716 let warnings = result.unwrap();
717 assert!(warnings.is_empty()); }
719
720 #[test]
721 fn test_lint_rule_filtering() {
722 let content = "# Heading\nJust text";
724 let rules: Vec<Box<dyn Rule>> = vec![
725 Box::new(MD001HeadingIncrement::default()),
726 ];
728
729 let result = lint(
730 content,
731 &rules,
732 false,
733 crate::config::MarkdownFlavor::Standard,
734 None,
735 None,
736 );
737 assert!(result.is_ok());
738 }
739
740 #[test]
741 fn test_get_profiling_report() {
742 let report = get_profiling_report();
744 assert!(!report.is_empty());
745 assert!(report.contains("Profiling"));
746 }
747
748 #[test]
749 fn test_reset_profiling() {
750 reset_profiling();
752
753 let report = get_profiling_report();
755 assert!(report.contains("disabled") || report.contains("no measurements"));
756 }
757
758 #[test]
759 fn test_get_regex_cache_stats() {
760 let stats = get_regex_cache_stats();
761 assert!(stats.is_empty() || !stats.is_empty());
763
764 for count in stats.values() {
766 assert!(*count > 0);
767 }
768 }
769
770 #[test]
771 fn test_content_characteristics_edge_cases() {
772 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
775
776 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
778
779 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");
789 assert!(!chars.has_blockquotes);
790 }
791}