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