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 lsp;
8pub mod markdownlint_config;
9pub mod output;
10pub mod parallel;
11pub mod performance;
12pub mod profiling;
13pub mod rule;
14pub mod vscode;
15#[macro_use]
16pub mod rule_config;
17#[macro_use]
18pub mod rule_config_serde;
19pub mod rules;
20pub mod types;
21pub mod utils;
22
23pub use rules::heading_utils::{Heading, HeadingStyle};
24pub use rules::*;
25
26pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
27use crate::rule::{LintResult, Rule, RuleCategory};
28use std::time::Instant;
29
30#[derive(Debug, Default)]
32struct ContentCharacteristics {
33 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, }
43
44impl ContentCharacteristics {
45 fn analyze(content: &str) -> Self {
46 let mut chars = Self { ..Default::default() };
47
48 let mut has_atx_heading = false;
50 let mut has_setext_heading = false;
51
52 for line in content.lines() {
53 let trimmed = line.trim();
54
55 if !has_atx_heading && trimmed.starts_with('#') {
57 has_atx_heading = true;
58 }
59 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
60 has_setext_heading = true;
61 }
62
63 if !chars.has_lists && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
65 chars.has_lists = true;
66 }
67 if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
68 chars.has_lists = true;
69 }
70 if !chars.has_links
71 && (line.contains('[')
72 || line.contains("http://")
73 || line.contains("https://")
74 || line.contains("ftp://"))
75 {
76 chars.has_links = true;
77 }
78 if !chars.has_images && line.contains("![") {
79 chars.has_images = true;
80 }
81 if !chars.has_code && (line.contains('`') || line.contains("~~~")) {
82 chars.has_code = true;
83 }
84 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
85 chars.has_emphasis = true;
86 }
87 if !chars.has_html && line.contains('<') {
88 chars.has_html = true;
89 }
90 if !chars.has_tables && line.contains('|') {
91 chars.has_tables = true;
92 }
93 if !chars.has_blockquotes && line.starts_with('>') {
94 chars.has_blockquotes = true;
95 }
96 }
97
98 chars.has_headings = has_atx_heading || has_setext_heading;
99 chars
100 }
101
102 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
104 match rule.category() {
105 RuleCategory::Heading => !self.has_headings,
106 RuleCategory::List => !self.has_lists,
107 RuleCategory::Link => !self.has_links && !self.has_images,
108 RuleCategory::Image => !self.has_images,
109 RuleCategory::CodeBlock => !self.has_code,
110 RuleCategory::Html => !self.has_html,
111 RuleCategory::Emphasis => !self.has_emphasis,
112 RuleCategory::Blockquote => !self.has_blockquotes,
113 RuleCategory::Table => !self.has_tables,
114 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
116 }
117 }
118}
119
120pub fn lint(
124 content: &str,
125 rules: &[Box<dyn Rule>],
126 _verbose: bool,
127 flavor: crate::config::MarkdownFlavor,
128) -> LintResult {
129 let mut warnings = Vec::new();
130 let _overall_start = Instant::now();
131
132 if content.is_empty() {
134 return Ok(warnings);
135 }
136
137 let inline_config = crate::inline_config::InlineConfig::from_content(content);
139
140 let characteristics = ContentCharacteristics::analyze(content);
142
143 let applicable_rules: Vec<_> = rules
145 .iter()
146 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
147 .collect();
148
149 let _total_rules = rules.len();
151 let _applicable_count = applicable_rules.len();
152
153 let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
155
156 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
157
158 for rule in applicable_rules {
159 let _rule_start = Instant::now();
160
161 let result = rule.check(&lint_ctx);
162
163 match result {
164 Ok(rule_warnings) => {
165 let filtered_warnings: Vec<_> = rule_warnings
167 .into_iter()
168 .filter(|warning| {
169 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
171
172 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
174 &rule_name_to_check[..dash_pos]
175 } else {
176 rule_name_to_check
177 };
178
179 !inline_config.is_rule_disabled(
180 base_rule_name,
181 warning.line, )
183 })
184 .collect();
185 warnings.extend(filtered_warnings);
186 }
187 Err(e) => {
188 log::error!("Error checking rule {}: {}", rule.name(), e);
189 return Err(e);
190 }
191 }
192
193 let rule_duration = _rule_start.elapsed();
194 if profile_rules {
195 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
196 }
197
198 #[cfg(not(test))]
199 if _verbose && rule_duration.as_millis() > 500 {
200 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
201 }
202 }
203
204 #[cfg(not(test))]
205 if _verbose {
206 let skipped_rules = _total_rules - _applicable_count;
207 if skipped_rules > 0 {
208 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
209 }
210 }
211
212 Ok(warnings)
213}
214
215pub fn get_profiling_report() -> String {
217 profiling::get_report()
218}
219
220pub fn reset_profiling() {
222 profiling::reset()
223}
224
225pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
227 crate::utils::regex_cache::get_cache_stats()
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use crate::rule::Rule;
234 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
235
236 #[test]
237 fn test_content_characteristics_analyze() {
238 let chars = ContentCharacteristics::analyze("");
240 assert!(!chars.has_headings);
241 assert!(!chars.has_lists);
242 assert!(!chars.has_links);
243 assert!(!chars.has_code);
244 assert!(!chars.has_emphasis);
245 assert!(!chars.has_html);
246 assert!(!chars.has_tables);
247 assert!(!chars.has_blockquotes);
248 assert!(!chars.has_images);
249
250 let chars = ContentCharacteristics::analyze("# Heading");
252 assert!(chars.has_headings);
253
254 let chars = ContentCharacteristics::analyze("Heading\n=======");
256 assert!(chars.has_headings);
257
258 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
260 assert!(chars.has_lists);
261
262 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
264 assert!(chars.has_lists);
265
266 let chars = ContentCharacteristics::analyze("[link](url)");
268 assert!(chars.has_links);
269
270 let chars = ContentCharacteristics::analyze("Visit https://example.com");
272 assert!(chars.has_links);
273
274 let chars = ContentCharacteristics::analyze("");
276 assert!(chars.has_images);
277
278 let chars = ContentCharacteristics::analyze("`inline code`");
280 assert!(chars.has_code);
281
282 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
283 assert!(chars.has_code);
284
285 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
287 assert!(chars.has_emphasis);
288
289 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
291 assert!(chars.has_html);
292
293 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
295 assert!(chars.has_tables);
296
297 let chars = ContentCharacteristics::analyze("> Quote");
299 assert!(chars.has_blockquotes);
300
301 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
303 let chars = ContentCharacteristics::analyze(content);
304 assert!(chars.has_headings);
305 assert!(chars.has_lists);
306 assert!(chars.has_links);
307 assert!(chars.has_code);
308 assert!(chars.has_emphasis);
309 assert!(chars.has_html);
310 assert!(chars.has_tables);
311 assert!(chars.has_blockquotes);
312 assert!(chars.has_images);
313 }
314
315 #[test]
316 fn test_content_characteristics_should_skip_rule() {
317 let chars = ContentCharacteristics {
318 has_headings: true,
319 has_lists: false,
320 has_links: true,
321 has_code: false,
322 has_emphasis: true,
323 has_html: false,
324 has_tables: true,
325 has_blockquotes: false,
326 has_images: false,
327 };
328
329 let heading_rule = MD001HeadingIncrement;
331 assert!(!chars.should_skip_rule(&heading_rule));
332
333 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
334 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
338 has_headings: false,
339 ..Default::default()
340 };
341 assert!(chars_no_headings.should_skip_rule(&heading_rule));
342 }
343
344 #[test]
345 fn test_lint_empty_content() {
346 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
347
348 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
349 assert!(result.is_ok());
350 assert!(result.unwrap().is_empty());
351 }
352
353 #[test]
354 fn test_lint_with_violations() {
355 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
357
358 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
359 assert!(result.is_ok());
360 let warnings = result.unwrap();
361 assert!(!warnings.is_empty());
362 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
364 }
365
366 #[test]
367 fn test_lint_with_inline_disable() {
368 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
369 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
370
371 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
372 assert!(result.is_ok());
373 let warnings = result.unwrap();
374 assert!(warnings.is_empty()); }
376
377 #[test]
378 fn test_lint_rule_filtering() {
379 let content = "# Heading\nJust text";
381 let rules: Vec<Box<dyn Rule>> = vec![
382 Box::new(MD001HeadingIncrement),
383 ];
385
386 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
387 assert!(result.is_ok());
388 }
389
390 #[test]
391 fn test_get_profiling_report() {
392 let report = get_profiling_report();
394 assert!(!report.is_empty());
395 assert!(report.contains("Profiling"));
396 }
397
398 #[test]
399 fn test_reset_profiling() {
400 reset_profiling();
402
403 let report = get_profiling_report();
405 assert!(report.contains("disabled") || report.contains("no measurements"));
406 }
407
408 #[test]
409 fn test_get_regex_cache_stats() {
410 let stats = get_regex_cache_stats();
411 assert!(stats.is_empty() || !stats.is_empty());
413
414 for count in stats.values() {
416 assert!(*count > 0);
417 }
418 }
419
420 #[test]
421 fn test_content_characteristics_edge_cases() {
422 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
425
426 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
428
429 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
432
433 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
435
436 let chars = ContentCharacteristics::analyze("text > not a quote");
438 assert!(!chars.has_blockquotes);
439 }
440}