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]
97 fn remove_trailing_punctuation(&self, text: &str, re: &Regex) -> String {
98 let mut result = text.trim().to_string();
99 loop {
100 let stripped = re.replace(&result, "").into_owned();
101 if stripped.len() == result.len() {
102 return stripped;
104 }
105 let trimmed = stripped.trim_end();
108 if trimmed.len() != stripped.len() && re.is_match(trimmed) {
109 result = trimmed.to_string();
110 } else {
111 return stripped;
112 }
113 }
114 }
115
116 #[inline]
118 fn fix_atx_heading(&self, line: &str, re: &Regex) -> String {
119 if let Some(captures) = ATX_HEADING_UNIFIED.captures(line) {
120 let indentation = captures.get(1).unwrap().as_str();
121 let hashes = captures.get(2).unwrap().as_str();
122 let space = captures.get(3).unwrap().as_str();
123 let content = captures.get(4).unwrap().as_str();
124
125 let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
128 let before_id = &content[..id_pos];
130 let id_part = &content[id_pos..];
131 let fixed_before = self.remove_trailing_punctuation(before_id, re);
132 format!("{fixed_before}{id_part}")
133 } else {
134 self.remove_trailing_punctuation(content, re)
136 };
137
138 if let Some(trailing) = captures.get(5) {
140 return format!(
141 "{}{}{}{}{}",
142 indentation,
143 hashes,
144 space,
145 fixed_content,
146 trailing.as_str()
147 );
148 }
149
150 return format!("{indentation}{hashes}{space}{fixed_content}");
151 }
152
153 line.to_string()
155 }
156
157 #[inline]
159 fn fix_setext_heading(&self, content_line: &str, re: &Regex) -> String {
160 let trimmed = content_line.trim_end();
161 let mut whitespace = "";
162
163 if content_line.len() > trimmed.len() {
165 whitespace = &content_line[trimmed.len()..];
166 }
167
168 format!("{}{}", self.remove_trailing_punctuation(trimmed, re), whitespace)
170 }
171}
172
173impl Rule for MD026NoTrailingPunctuation {
174 fn name(&self) -> &'static str {
175 "MD026"
176 }
177
178 fn description(&self) -> &'static str {
179 "Trailing punctuation in heading"
180 }
181
182 fn category(&self) -> RuleCategory {
183 RuleCategory::Heading
184 }
185
186 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
187 if !ctx.likely_has_headings() {
189 return true;
190 }
191 let punctuation = &self.config.punctuation;
193 !punctuation.chars().any(|p| ctx.content.contains(p))
194 }
195
196 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
197 let content = ctx.content;
198
199 if content.is_empty() {
201 return Ok(Vec::new());
202 }
203
204 if self.config.punctuation == DEFAULT_PUNCTUATION {
207 if !QUICK_PUNCTUATION_CHECK.is_match(content) {
208 return Ok(Vec::new());
209 }
210 } else {
211 let has_custom_punctuation = self.config.punctuation.chars().any(|c| content.contains(c));
213 if !has_custom_punctuation {
214 return Ok(Vec::new());
215 }
216 }
217
218 let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
220 if !has_headings {
221 return Ok(Vec::new());
222 }
223
224 let mut warnings = Vec::new();
225 let Ok(re) = self.get_punctuation_regex() else {
226 return Ok(warnings);
227 };
228
229 let line_index = &ctx.line_index;
231
232 for (line_num, line_info) in ctx.lines.iter().enumerate() {
234 if let Some(heading) = &line_info.heading {
235 if !heading.is_valid {
237 continue;
238 }
239
240 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
242 continue;
243 }
244
245 let text_to_check = heading.text.clone();
249
250 if self.has_trailing_punctuation(&text_to_check, &re) {
251 if let Some(punctuation_match) = re.find(&text_to_check) {
253 let line = line_info.content(ctx.content);
254
255 let punctuation_pos_in_text = punctuation_match.start();
257 let text_pos_in_line = line.find(&heading.text).unwrap_or(heading.content_column);
258 let punctuation_start_in_line = text_pos_in_line + punctuation_pos_in_text;
259 let punctuation_len = punctuation_match.len();
260
261 let (start_line, start_col, end_line, end_col) = calculate_match_range(
262 line_num + 1, line,
264 punctuation_start_in_line,
265 punctuation_len,
266 );
267
268 let last_char = text_to_check.chars().last().unwrap_or(' ');
269 warnings.push(LintWarning {
270 rule_name: Some(self.name().to_string()),
271 line: start_line,
272 column: start_col,
273 end_line,
274 end_column: end_col,
275 message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
276 severity: Severity::Warning,
277 fix: Some(Fix::new(
278 self.get_line_byte_range(content, line_num + 1, line_index),
279 if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
280 self.fix_atx_heading(line, &re)
281 } else {
282 self.fix_setext_heading(line, &re)
283 },
284 )),
285 });
286 }
287 }
288 }
289 }
290
291 Ok(warnings)
292 }
293
294 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
295 if self.should_skip(ctx) {
296 return Ok(ctx.content.to_string());
297 }
298 let warnings = self.check(ctx)?;
299 if warnings.is_empty() {
300 return Ok(ctx.content.to_string());
301 }
302 let warnings =
303 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
304 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
305 .map_err(crate::rule::LintError::InvalidInput)
306 }
307
308 fn as_any(&self) -> &dyn std::any::Any {
309 self
310 }
311
312 fn default_config_section(&self) -> Option<(String, toml::Value)> {
313 let json_value = serde_json::to_value(&self.config).ok()?;
314 Some((
315 self.name().to_string(),
316 crate::rule_config_serde::json_to_toml_value(&json_value)?,
317 ))
318 }
319
320 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
321 where
322 Self: Sized,
323 {
324 let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
325 Box::new(Self::from_config_struct(rule_config))
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332 use crate::lint_context::LintContext;
333
334 #[test]
335 fn test_no_trailing_punctuation() {
336 let rule = MD026NoTrailingPunctuation::new(None);
337 let content = "# This is a heading\n\n## Another heading";
338 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
339 let result = rule.check(&ctx).unwrap();
340 assert!(result.is_empty(), "Headings without punctuation should not be flagged");
341 }
342
343 #[test]
344 fn test_trailing_period() {
345 let rule = MD026NoTrailingPunctuation::new(None);
346 let content = "# This is a heading.\n\n## Another one.";
347 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
348 let result = rule.check(&ctx).unwrap();
349 assert_eq!(result.len(), 2);
350 assert_eq!(result[0].line, 1);
351 assert_eq!(result[0].column, 20);
352 assert!(result[0].message.contains("ends with punctuation '.'"));
353 assert_eq!(result[1].line, 3);
354 assert_eq!(result[1].column, 15);
355 }
356
357 #[test]
358 fn test_trailing_comma() {
359 let rule = MD026NoTrailingPunctuation::new(None);
360 let content = "# Heading,\n## Sub-heading,";
361 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
362 let result = rule.check(&ctx).unwrap();
363 assert_eq!(result.len(), 2);
364 assert!(result[0].message.contains("ends with punctuation ','"));
365 }
366
367 #[test]
368 fn test_trailing_semicolon() {
369 let rule = MD026NoTrailingPunctuation::new(None);
370 let content = "# Title;\n## Subtitle;";
371 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
372 let result = rule.check(&ctx).unwrap();
373 assert_eq!(result.len(), 2);
374 assert!(result[0].message.contains("ends with punctuation ';'"));
375 }
376
377 #[test]
378 fn test_custom_punctuation() {
379 let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
380 let content = "# Important!\n## Regular heading.";
381 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
382 let result = rule.check(&ctx).unwrap();
383 assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
384 assert_eq!(result[0].line, 1);
385 assert!(result[0].message.contains("ends with punctuation '!'"));
386 }
387
388 #[test]
389 fn test_legitimate_question_mark() {
390 let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
391 let content = "# What is this?\n# This is bad.";
392 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
393 let result = rule.check(&ctx).unwrap();
394 assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
396 }
397
398 #[test]
399 fn test_question_marks_not_in_default() {
400 let rule = MD026NoTrailingPunctuation::new(None);
401 let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
402 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
403 let result = rule.check(&ctx).unwrap();
404 assert!(result.is_empty(), "Question marks are not in default punctuation list");
405 }
406
407 #[test]
408 fn test_colons_in_default() {
409 let rule = MD026NoTrailingPunctuation::new(None);
410 let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
411 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
412 let result = rule.check(&ctx).unwrap();
413 assert_eq!(
414 result.len(),
415 4,
416 "Colons are in default punctuation list and should be flagged"
417 );
418 }
419
420 #[test]
421 fn test_fix_atx_headings() {
422 let rule = MD026NoTrailingPunctuation::new(None);
423 let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
424 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
425 let fixed = rule.fix(&ctx).unwrap();
426 assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
427 }
428
429 #[test]
430 fn test_fix_setext_headings() {
431 let rule = MD026NoTrailingPunctuation::new(None);
432 let content = "Title.\n======\n\nSubtitle,\n---------";
433 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
434 let fixed = rule.fix(&ctx).unwrap();
435 assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
436 }
437
438 #[test]
439 fn test_fix_preserves_trailing_hashes() {
440 let rule = MD026NoTrailingPunctuation::new(None);
441 let content = "# Title. #\n## Subtitle, ##";
442 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
443 let fixed = rule.fix(&ctx).unwrap();
444 assert_eq!(fixed, "# Title #\n## Subtitle ##");
445 }
446
447 #[test]
448 fn test_indented_headings() {
449 let rule = MD026NoTrailingPunctuation::new(None);
450 let content = " # Title.\n ## Subtitle.";
451 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
452 let result = rule.check(&ctx).unwrap();
453 assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
454 }
455
456 #[test]
457 fn test_deeply_indented_ignored() {
458 let rule = MD026NoTrailingPunctuation::new(None);
459 let content = " # This is code.";
460 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
461 let result = rule.check(&ctx).unwrap();
462 assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
463 }
464
465 #[test]
466 fn test_multiple_punctuation() {
467 let rule = MD026NoTrailingPunctuation::new(None);
468 let content = "# Title...";
469 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
470 let result = rule.check(&ctx).unwrap();
471 assert_eq!(result.len(), 1);
472 assert_eq!(result[0].column, 8); }
474
475 #[test]
476 fn test_empty_content() {
477 let rule = MD026NoTrailingPunctuation::new(None);
478 let content = "";
479 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
480 let result = rule.check(&ctx).unwrap();
481 assert!(result.is_empty());
482 }
483
484 #[test]
485 fn test_no_headings() {
486 let rule = MD026NoTrailingPunctuation::new(None);
487 let content = "This is just text.\nMore text with punctuation.";
488 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
489 let result = rule.check(&ctx).unwrap();
490 assert!(result.is_empty(), "Non-heading lines should not be checked");
491 }
492
493 #[test]
494 fn test_get_punctuation_regex() {
495 let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
496 let regex = rule.get_punctuation_regex().unwrap();
497 assert!(regex.is_match("text!"));
498 assert!(regex.is_match("text?"));
499 assert!(!regex.is_match("text."));
500 }
501
502 #[test]
503 fn test_regex_caching() {
504 let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
505 let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
506
507 let _regex1 = rule1.get_punctuation_regex().unwrap();
509 let _regex2 = rule2.get_punctuation_regex().unwrap();
510
511 let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
513 assert!(cache.contains_key("!"));
514 }
515
516 #[test]
517 fn test_config_from_toml() {
518 let mut config = crate::config::Config::default();
519 let mut rule_config = crate::config::RuleConfig::default();
520 rule_config
521 .values
522 .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
523 config.rules.insert("MD026".to_string(), rule_config);
524
525 let rule = MD026NoTrailingPunctuation::from_config(&config);
526 let content = "# Title!\n# Another?";
527 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
528 let result = rule.check(&ctx).unwrap();
529 assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
530 }
531
532 #[test]
533 fn test_fix_removes_punctuation() {
534 let rule = MD026NoTrailingPunctuation::new(None);
535 let content = "# Title. \n## Subtitle, ";
536 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
537 let fixed = rule.fix(&ctx).unwrap();
538 assert_eq!(fixed, "# Title\n## Subtitle");
540 }
541
542 #[test]
543 fn test_final_newline_preservation() {
544 let rule = MD026NoTrailingPunctuation::new(None);
545 let content = "# Title.\n";
546 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
547 let fixed = rule.fix(&ctx).unwrap();
548 assert_eq!(fixed, "# Title\n");
549
550 let content_no_newline = "# Title.";
551 let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
552 let fixed2 = rule.fix(&ctx2).unwrap();
553 assert_eq!(fixed2, "# Title");
554 }
555}