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