1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use crate::utils::range_utils::{LineIndex, calculate_match_range};
6use regex::Regex;
7use std::collections::HashMap;
8use std::ops::Range;
9use std::sync::LazyLock;
10use std::sync::RwLock;
11
12mod md026_config;
13use md026_config::{DEFAULT_PUNCTUATION, MD026Config};
14
15static ATX_HEADING_UNIFIED: LazyLock<Regex> =
17 LazyLock::new(|| Regex::new(r"^( {0,3})(#{1,6})(\s+)(.+?)(\s+#{1,6})?$").unwrap());
18
19static QUICK_PUNCTUATION_CHECK: LazyLock<Regex> =
21 LazyLock::new(|| Regex::new(&format!(r"[{}]", regex::escape(DEFAULT_PUNCTUATION))).unwrap());
22
23static PUNCTUATION_REGEX_CACHE: LazyLock<RwLock<HashMap<String, Regex>>> =
25 LazyLock::new(|| RwLock::new(HashMap::new()));
26
27#[derive(Clone, Default)]
29pub struct MD026NoTrailingPunctuation {
30 config: MD026Config,
31}
32
33impl MD026NoTrailingPunctuation {
34 pub fn new(punctuation: Option<String>) -> Self {
35 Self {
36 config: MD026Config {
37 punctuation: punctuation.unwrap_or_else(|| DEFAULT_PUNCTUATION.to_string()),
38 },
39 }
40 }
41
42 pub fn from_config_struct(config: MD026Config) -> Self {
43 Self { config }
44 }
45
46 #[inline]
47 fn get_punctuation_regex(&self) -> Result<Regex, regex::Error> {
48 {
50 let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
51 if let Some(cached_regex) = cache.get(&self.config.punctuation) {
52 return Ok(cached_regex.clone());
53 }
54 }
55
56 let pattern = format!(r"([{}]+)$", regex::escape(&self.config.punctuation));
58 let regex = Regex::new(&pattern)?;
59
60 {
61 let mut cache = PUNCTUATION_REGEX_CACHE.write().unwrap();
62 cache.insert(self.config.punctuation.clone(), regex.clone());
63 }
64
65 Ok(regex)
66 }
67
68 #[inline]
69 fn has_trailing_punctuation(&self, text: &str, re: &Regex) -> bool {
70 let trimmed = text.trim();
71 re.is_match(trimmed)
72 }
73
74 #[inline]
75 fn get_line_byte_range(&self, content: &str, line_num: usize, line_index: &LineIndex) -> Range<usize> {
76 let start_pos = line_index.get_line_start_byte(line_num).unwrap_or(content.len());
77
78 let line = content.lines().nth(line_num - 1).unwrap_or("");
80
81 Range {
82 start: start_pos,
83 end: start_pos + line.len(),
84 }
85 }
86
87 #[inline]
89 fn remove_trailing_punctuation(&self, text: &str, re: &Regex) -> String {
90 re.replace_all(text.trim(), "").to_string()
91 }
92
93 #[inline]
95 fn fix_atx_heading(&self, line: &str, re: &Regex) -> String {
96 if let Some(captures) = ATX_HEADING_UNIFIED.captures(line) {
97 let indentation = captures.get(1).unwrap().as_str();
98 let hashes = captures.get(2).unwrap().as_str();
99 let space = captures.get(3).unwrap().as_str();
100 let content = captures.get(4).unwrap().as_str();
101
102 let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
105 let before_id = &content[..id_pos];
107 let id_part = &content[id_pos..];
108 let fixed_before = self.remove_trailing_punctuation(before_id, re);
109 format!("{fixed_before}{id_part}")
110 } else {
111 self.remove_trailing_punctuation(content, re)
113 };
114
115 if let Some(trailing) = captures.get(5) {
117 return format!(
118 "{}{}{}{}{}",
119 indentation,
120 hashes,
121 space,
122 fixed_content,
123 trailing.as_str()
124 );
125 }
126
127 return format!("{indentation}{hashes}{space}{fixed_content}");
128 }
129
130 line.to_string()
132 }
133
134 #[inline]
136 fn fix_setext_heading(&self, content_line: &str, re: &Regex) -> String {
137 let trimmed = content_line.trim_end();
138 let mut whitespace = "";
139
140 if content_line.len() > trimmed.len() {
142 whitespace = &content_line[trimmed.len()..];
143 }
144
145 format!("{}{}", self.remove_trailing_punctuation(trimmed, re), whitespace)
147 }
148}
149
150impl Rule for MD026NoTrailingPunctuation {
151 fn name(&self) -> &'static str {
152 "MD026"
153 }
154
155 fn description(&self) -> &'static str {
156 "Trailing punctuation in heading"
157 }
158
159 fn category(&self) -> RuleCategory {
160 RuleCategory::Heading
161 }
162
163 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
164 if !ctx.likely_has_headings() {
166 return true;
167 }
168 let punctuation = &self.config.punctuation;
170 !punctuation.chars().any(|p| ctx.content.contains(p))
171 }
172
173 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
174 let content = ctx.content;
175
176 if content.is_empty() {
178 return Ok(Vec::new());
179 }
180
181 if self.config.punctuation == DEFAULT_PUNCTUATION {
184 if !QUICK_PUNCTUATION_CHECK.is_match(content) {
185 return Ok(Vec::new());
186 }
187 } else {
188 let has_custom_punctuation = self.config.punctuation.chars().any(|c| content.contains(c));
190 if !has_custom_punctuation {
191 return Ok(Vec::new());
192 }
193 }
194
195 let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
197 if !has_headings {
198 return Ok(Vec::new());
199 }
200
201 let mut warnings = Vec::new();
202 let re = match self.get_punctuation_regex() {
203 Ok(regex) => regex,
204 Err(_) => return Ok(warnings),
205 };
206
207 let line_index = &ctx.line_index;
209
210 for (line_num, line_info) in ctx.lines.iter().enumerate() {
212 if let Some(heading) = &line_info.heading {
213 if !heading.is_valid {
215 continue;
216 }
217
218 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
220 continue;
221 }
222
223 let text_to_check = heading.text.clone();
227
228 if self.has_trailing_punctuation(&text_to_check, &re) {
229 if let Some(punctuation_match) = re.find(&text_to_check) {
231 let line = line_info.content(ctx.content);
232
233 let punctuation_pos_in_text = punctuation_match.start();
235 let text_pos_in_line = line.find(&heading.text).unwrap_or(heading.content_column);
236 let punctuation_start_in_line = text_pos_in_line + punctuation_pos_in_text;
237 let punctuation_len = punctuation_match.len();
238
239 let (start_line, start_col, end_line, end_col) = calculate_match_range(
240 line_num + 1, line,
242 punctuation_start_in_line,
243 punctuation_len,
244 );
245
246 let last_char = text_to_check.chars().last().unwrap_or(' ');
247 warnings.push(LintWarning {
248 rule_name: Some(self.name().to_string()),
249 line: start_line,
250 column: start_col,
251 end_line,
252 end_column: end_col,
253 message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
254 severity: Severity::Warning,
255 fix: Some(Fix {
256 range: self.get_line_byte_range(content, line_num + 1, line_index),
257 replacement: if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
258 self.fix_atx_heading(line, &re)
259 } else {
260 self.fix_setext_heading(line, &re)
261 },
262 }),
263 });
264 }
265 }
266 }
267 }
268
269 Ok(warnings)
270 }
271
272 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
273 if self.should_skip(ctx) {
274 return Ok(ctx.content.to_string());
275 }
276 let warnings = self.check(ctx)?;
277 if warnings.is_empty() {
278 return Ok(ctx.content.to_string());
279 }
280 let warnings =
281 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
282 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
283 .map_err(crate::rule::LintError::InvalidInput)
284 }
285
286 fn as_any(&self) -> &dyn std::any::Any {
287 self
288 }
289
290 fn default_config_section(&self) -> Option<(String, toml::Value)> {
291 let json_value = serde_json::to_value(&self.config).ok()?;
292 Some((
293 self.name().to_string(),
294 crate::rule_config_serde::json_to_toml_value(&json_value)?,
295 ))
296 }
297
298 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
299 where
300 Self: Sized,
301 {
302 let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
303 Box::new(Self::from_config_struct(rule_config))
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use crate::lint_context::LintContext;
311
312 #[test]
313 fn test_no_trailing_punctuation() {
314 let rule = MD026NoTrailingPunctuation::new(None);
315 let content = "# This is a heading\n\n## Another heading";
316 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
317 let result = rule.check(&ctx).unwrap();
318 assert!(result.is_empty(), "Headings without punctuation should not be flagged");
319 }
320
321 #[test]
322 fn test_trailing_period() {
323 let rule = MD026NoTrailingPunctuation::new(None);
324 let content = "# This is a heading.\n\n## Another one.";
325 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
326 let result = rule.check(&ctx).unwrap();
327 assert_eq!(result.len(), 2);
328 assert_eq!(result[0].line, 1);
329 assert_eq!(result[0].column, 20);
330 assert!(result[0].message.contains("ends with punctuation '.'"));
331 assert_eq!(result[1].line, 3);
332 assert_eq!(result[1].column, 15);
333 }
334
335 #[test]
336 fn test_trailing_comma() {
337 let rule = MD026NoTrailingPunctuation::new(None);
338 let content = "# Heading,\n## Sub-heading,";
339 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
340 let result = rule.check(&ctx).unwrap();
341 assert_eq!(result.len(), 2);
342 assert!(result[0].message.contains("ends with punctuation ','"));
343 }
344
345 #[test]
346 fn test_trailing_semicolon() {
347 let rule = MD026NoTrailingPunctuation::new(None);
348 let content = "# Title;\n## Subtitle;";
349 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
350 let result = rule.check(&ctx).unwrap();
351 assert_eq!(result.len(), 2);
352 assert!(result[0].message.contains("ends with punctuation ';'"));
353 }
354
355 #[test]
356 fn test_custom_punctuation() {
357 let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
358 let content = "# Important!\n## Regular heading.";
359 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
360 let result = rule.check(&ctx).unwrap();
361 assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
362 assert_eq!(result[0].line, 1);
363 assert!(result[0].message.contains("ends with punctuation '!'"));
364 }
365
366 #[test]
367 fn test_legitimate_question_mark() {
368 let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
369 let content = "# What is this?\n# This is bad.";
370 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
371 let result = rule.check(&ctx).unwrap();
372 assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
374 }
375
376 #[test]
377 fn test_question_marks_not_in_default() {
378 let rule = MD026NoTrailingPunctuation::new(None);
379 let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
380 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
381 let result = rule.check(&ctx).unwrap();
382 assert!(result.is_empty(), "Question marks are not in default punctuation list");
383 }
384
385 #[test]
386 fn test_colons_in_default() {
387 let rule = MD026NoTrailingPunctuation::new(None);
388 let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
389 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
390 let result = rule.check(&ctx).unwrap();
391 assert_eq!(
392 result.len(),
393 4,
394 "Colons are in default punctuation list and should be flagged"
395 );
396 }
397
398 #[test]
399 fn test_fix_atx_headings() {
400 let rule = MD026NoTrailingPunctuation::new(None);
401 let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
402 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
403 let fixed = rule.fix(&ctx).unwrap();
404 assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
405 }
406
407 #[test]
408 fn test_fix_setext_headings() {
409 let rule = MD026NoTrailingPunctuation::new(None);
410 let content = "Title.\n======\n\nSubtitle,\n---------";
411 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
412 let fixed = rule.fix(&ctx).unwrap();
413 assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
414 }
415
416 #[test]
417 fn test_fix_preserves_trailing_hashes() {
418 let rule = MD026NoTrailingPunctuation::new(None);
419 let content = "# Title. #\n## Subtitle, ##";
420 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
421 let fixed = rule.fix(&ctx).unwrap();
422 assert_eq!(fixed, "# Title #\n## Subtitle ##");
423 }
424
425 #[test]
426 fn test_indented_headings() {
427 let rule = MD026NoTrailingPunctuation::new(None);
428 let content = " # Title.\n ## Subtitle.";
429 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
430 let result = rule.check(&ctx).unwrap();
431 assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
432 }
433
434 #[test]
435 fn test_deeply_indented_ignored() {
436 let rule = MD026NoTrailingPunctuation::new(None);
437 let content = " # This is code.";
438 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
439 let result = rule.check(&ctx).unwrap();
440 assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
441 }
442
443 #[test]
444 fn test_multiple_punctuation() {
445 let rule = MD026NoTrailingPunctuation::new(None);
446 let content = "# Title...";
447 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
448 let result = rule.check(&ctx).unwrap();
449 assert_eq!(result.len(), 1);
450 assert_eq!(result[0].column, 8); }
452
453 #[test]
454 fn test_empty_content() {
455 let rule = MD026NoTrailingPunctuation::new(None);
456 let content = "";
457 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
458 let result = rule.check(&ctx).unwrap();
459 assert!(result.is_empty());
460 }
461
462 #[test]
463 fn test_no_headings() {
464 let rule = MD026NoTrailingPunctuation::new(None);
465 let content = "This is just text.\nMore text with punctuation.";
466 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
467 let result = rule.check(&ctx).unwrap();
468 assert!(result.is_empty(), "Non-heading lines should not be checked");
469 }
470
471 #[test]
472 fn test_get_punctuation_regex() {
473 let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
474 let regex = rule.get_punctuation_regex().unwrap();
475 assert!(regex.is_match("text!"));
476 assert!(regex.is_match("text?"));
477 assert!(!regex.is_match("text."));
478 }
479
480 #[test]
481 fn test_regex_caching() {
482 let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
483 let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
484
485 let _regex1 = rule1.get_punctuation_regex().unwrap();
487 let _regex2 = rule2.get_punctuation_regex().unwrap();
488
489 let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
491 assert!(cache.contains_key("!"));
492 }
493
494 #[test]
495 fn test_config_from_toml() {
496 let mut config = crate::config::Config::default();
497 let mut rule_config = crate::config::RuleConfig::default();
498 rule_config
499 .values
500 .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
501 config.rules.insert("MD026".to_string(), rule_config);
502
503 let rule = MD026NoTrailingPunctuation::from_config(&config);
504 let content = "# Title!\n# Another?";
505 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
506 let result = rule.check(&ctx).unwrap();
507 assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
508 }
509
510 #[test]
511 fn test_fix_removes_punctuation() {
512 let rule = MD026NoTrailingPunctuation::new(None);
513 let content = "# Title. \n## Subtitle, ";
514 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
515 let fixed = rule.fix(&ctx).unwrap();
516 assert_eq!(fixed, "# Title\n## Subtitle");
518 }
519
520 #[test]
521 fn test_final_newline_preservation() {
522 let rule = MD026NoTrailingPunctuation::new(None);
523 let content = "# Title.\n";
524 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
525 let fixed = rule.fix(&ctx).unwrap();
526 assert_eq!(fixed, "# Title\n");
527
528 let content_no_newline = "# Title.";
529 let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
530 let fixed2 = rule.fix(&ctx2).unwrap();
531 assert_eq!(fixed2, "# Title");
532 }
533}