rumdl_lib/rules/
md026_no_trailing_punctuation.rs

1/// Rule MD026: No trailing punctuation in headings
2///
3/// See [docs/md026.md](../../docs/md026.md) for full documentation, configuration, and examples.
4use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, 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
15// Optimized single regex for all ATX heading types (normal, closed, indented 1-3 spaces)
16static ATX_HEADING_UNIFIED: LazyLock<Regex> =
17    LazyLock::new(|| Regex::new(r"^( {0,3})(#{1,6})(\s+)(.+?)(\s+#{1,6})?$").unwrap());
18
19// Fast check patterns for early returns - match defaults
20static QUICK_PUNCTUATION_CHECK: LazyLock<Regex> =
21    LazyLock::new(|| Regex::new(&format!(r"[{}]", regex::escape(DEFAULT_PUNCTUATION))).unwrap());
22
23// Regex cache for punctuation patterns
24static PUNCTUATION_REGEX_CACHE: LazyLock<RwLock<HashMap<String, Regex>>> =
25    LazyLock::new(|| RwLock::new(HashMap::new()));
26
27/// Rule MD026: Trailing punctuation in heading
28#[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        // Check cache first
49        {
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        // Compile and cache the regex
57        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        // Find the line length
79        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    // Remove trailing punctuation from text
88    #[inline]
89    fn remove_trailing_punctuation(&self, text: &str, re: &Regex) -> String {
90        re.replace_all(text.trim(), "").to_string()
91    }
92
93    // Optimized ATX heading fix using unified regex
94    #[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            // Check if content ends with a custom header ID like {#my-id}
103            // If so, we need to fix punctuation before the ID
104            let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
105                // Has a custom ID - fix punctuation before it
106                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                // No custom ID - just remove trailing punctuation
112                self.remove_trailing_punctuation(content, re)
113            };
114
115            // Preserve any trailing hashes if present
116            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        // Fallback if no regex matches
131        line.to_string()
132    }
133
134    // Fix a setext heading by removing trailing punctuation from the content line
135    #[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        // Preserve trailing whitespace
141        if content_line.len() > trimmed.len() {
142            whitespace = &content_line[trimmed.len()..];
143        }
144
145        // Remove punctuation and preserve whitespace
146        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 should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
160        // Skip if no heading markers
161        if !ctx.likely_has_headings() {
162            return true;
163        }
164        // Skip if none of the configured punctuation exists
165        let punctuation = &self.config.punctuation;
166        !punctuation.chars().any(|p| ctx.content.contains(p))
167    }
168
169    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
170        let content = ctx.content;
171
172        // Early returns for performance
173        if content.is_empty() {
174            return Ok(Vec::new());
175        }
176
177        // Quick check for any punctuation we care about
178        // For custom punctuation, we need to check differently
179        if self.config.punctuation == DEFAULT_PUNCTUATION {
180            if !QUICK_PUNCTUATION_CHECK.is_match(content) {
181                return Ok(Vec::new());
182            }
183        } else {
184            // For custom punctuation, check if any of those characters exist
185            let has_custom_punctuation = self.config.punctuation.chars().any(|c| content.contains(c));
186            if !has_custom_punctuation {
187                return Ok(Vec::new());
188            }
189        }
190
191        // Check if we have any headings from pre-computed line info
192        let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
193        if !has_headings {
194            return Ok(Vec::new());
195        }
196
197        let mut warnings = Vec::new();
198        let re = match self.get_punctuation_regex() {
199            Ok(regex) => regex,
200            Err(_) => return Ok(warnings),
201        };
202
203        // Create LineIndex for correct byte position calculations across all line ending types
204        let line_index = &ctx.line_index;
205
206        // Use pre-computed heading information from LintContext
207        for (line_num, line_info) in ctx.lines.iter().enumerate() {
208            if let Some(heading) = &line_info.heading {
209                // Skip deeply indented headings (they're code blocks)
210                if line_info.indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
211                    continue;
212                }
213
214                // LintContext already strips Kramdown IDs from heading.text
215                // So we just check the heading text directly for trailing punctuation
216                // This correctly flags "# Heading." even if it has {#id}
217                let text_to_check = heading.text.clone();
218
219                if self.has_trailing_punctuation(&text_to_check, &re) {
220                    // Find the trailing punctuation
221                    if let Some(punctuation_match) = re.find(&text_to_check) {
222                        let line = &line_info.content;
223
224                        // For ATX headings, find the punctuation position in the line
225                        let punctuation_pos_in_text = punctuation_match.start();
226                        let text_pos_in_line = line.find(&heading.text).unwrap_or(heading.content_column);
227                        let punctuation_start_in_line = text_pos_in_line + punctuation_pos_in_text;
228                        let punctuation_len = punctuation_match.len();
229
230                        let (start_line, start_col, end_line, end_col) = calculate_match_range(
231                            line_num + 1, // Convert to 1-indexed
232                            line,
233                            punctuation_start_in_line,
234                            punctuation_len,
235                        );
236
237                        let last_char = text_to_check.chars().last().unwrap_or(' ');
238                        warnings.push(LintWarning {
239                            rule_name: Some(self.name().to_string()),
240                            line: start_line,
241                            column: start_col,
242                            end_line,
243                            end_column: end_col,
244                            message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
245                            severity: Severity::Warning,
246                            fix: Some(Fix {
247                                range: self.get_line_byte_range(content, line_num + 1, line_index),
248                                replacement: if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
249                                    self.fix_atx_heading(line, &re)
250                                } else {
251                                    self.fix_setext_heading(line, &re)
252                                },
253                            }),
254                        });
255                    }
256                }
257            }
258        }
259
260        Ok(warnings)
261    }
262
263    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
264        let content = ctx.content;
265
266        // Fast path optimizations
267        if content.is_empty() {
268            return Ok(content.to_string());
269        }
270
271        // Quick check for punctuation
272        // For custom punctuation, we need to check differently
273        if self.config.punctuation == DEFAULT_PUNCTUATION {
274            if !QUICK_PUNCTUATION_CHECK.is_match(content) {
275                return Ok(content.to_string());
276            }
277        } else {
278            // For custom punctuation, check if any of those characters exist
279            let has_custom_punctuation = self.config.punctuation.chars().any(|c| content.contains(c));
280            if !has_custom_punctuation {
281                return Ok(content.to_string());
282            }
283        }
284
285        // Check if we have any headings from pre-computed line info
286        let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
287        if !has_headings {
288            return Ok(content.to_string());
289        }
290
291        let re = match self.get_punctuation_regex() {
292            Ok(regex) => regex,
293            Err(_) => return Ok(content.to_string()),
294        };
295
296        let lines: Vec<&str> = content.lines().collect();
297        let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
298
299        // Use pre-computed heading information from LintContext
300        for (line_num, line_info) in ctx.lines.iter().enumerate() {
301            if let Some(heading) = &line_info.heading {
302                // Skip deeply indented headings (they're code blocks)
303                if line_info.indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
304                    continue;
305                }
306
307                // LintContext already strips custom header IDs from heading.text
308                // So we just check the heading text directly for trailing punctuation
309                let text_to_check = heading.text.clone();
310
311                // Check and fix trailing punctuation
312                if self.has_trailing_punctuation(&text_to_check, &re) {
313                    fixed_lines[line_num] = if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
314                        self.fix_atx_heading(&line_info.content, &re)
315                    } else {
316                        self.fix_setext_heading(&line_info.content, &re)
317                    };
318                }
319            }
320        }
321
322        // Reconstruct content preserving line endings
323        let mut result = String::with_capacity(content.len());
324        for (i, line) in fixed_lines.iter().enumerate() {
325            result.push_str(line);
326            if i < fixed_lines.len() - 1 || content.ends_with('\n') {
327                result.push('\n');
328            }
329        }
330
331        Ok(result)
332    }
333
334    fn as_any(&self) -> &dyn std::any::Any {
335        self
336    }
337
338    fn default_config_section(&self) -> Option<(String, toml::Value)> {
339        let json_value = serde_json::to_value(&self.config).ok()?;
340        Some((
341            self.name().to_string(),
342            crate::rule_config_serde::json_to_toml_value(&json_value)?,
343        ))
344    }
345
346    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
347    where
348        Self: Sized,
349    {
350        let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
351        Box::new(Self::from_config_struct(rule_config))
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::lint_context::LintContext;
359
360    #[test]
361    fn test_no_trailing_punctuation() {
362        let rule = MD026NoTrailingPunctuation::new(None);
363        let content = "# This is a heading\n\n## Another heading";
364        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
365        let result = rule.check(&ctx).unwrap();
366        assert!(result.is_empty(), "Headings without punctuation should not be flagged");
367    }
368
369    #[test]
370    fn test_trailing_period() {
371        let rule = MD026NoTrailingPunctuation::new(None);
372        let content = "# This is a heading.\n\n## Another one.";
373        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
374        let result = rule.check(&ctx).unwrap();
375        assert_eq!(result.len(), 2);
376        assert_eq!(result[0].line, 1);
377        assert_eq!(result[0].column, 20);
378        assert!(result[0].message.contains("ends with punctuation '.'"));
379        assert_eq!(result[1].line, 3);
380        assert_eq!(result[1].column, 15);
381    }
382
383    #[test]
384    fn test_trailing_comma() {
385        let rule = MD026NoTrailingPunctuation::new(None);
386        let content = "# Heading,\n## Sub-heading,";
387        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
388        let result = rule.check(&ctx).unwrap();
389        assert_eq!(result.len(), 2);
390        assert!(result[0].message.contains("ends with punctuation ','"));
391    }
392
393    #[test]
394    fn test_trailing_semicolon() {
395        let rule = MD026NoTrailingPunctuation::new(None);
396        let content = "# Title;\n## Subtitle;";
397        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
398        let result = rule.check(&ctx).unwrap();
399        assert_eq!(result.len(), 2);
400        assert!(result[0].message.contains("ends with punctuation ';'"));
401    }
402
403    #[test]
404    fn test_custom_punctuation() {
405        let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
406        let content = "# Important!\n## Regular heading.";
407        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
408        let result = rule.check(&ctx).unwrap();
409        assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
410        assert_eq!(result[0].line, 1);
411        assert!(result[0].message.contains("ends with punctuation '!'"));
412    }
413
414    #[test]
415    fn test_legitimate_question_mark() {
416        let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
417        let content = "# What is this?\n# This is bad.";
418        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
419        let result = rule.check(&ctx).unwrap();
420        // With custom punctuation, legitimate punctuation exceptions don't apply
421        assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
422    }
423
424    #[test]
425    fn test_question_marks_not_in_default() {
426        let rule = MD026NoTrailingPunctuation::new(None);
427        let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
428        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
429        let result = rule.check(&ctx).unwrap();
430        assert!(result.is_empty(), "Question marks are not in default punctuation list");
431    }
432
433    #[test]
434    fn test_colons_in_default() {
435        let rule = MD026NoTrailingPunctuation::new(None);
436        let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
437        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
438        let result = rule.check(&ctx).unwrap();
439        assert_eq!(
440            result.len(),
441            4,
442            "Colons are in default punctuation list and should be flagged"
443        );
444    }
445
446    #[test]
447    fn test_fix_atx_headings() {
448        let rule = MD026NoTrailingPunctuation::new(None);
449        let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
450        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
451        let fixed = rule.fix(&ctx).unwrap();
452        assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
453    }
454
455    #[test]
456    fn test_fix_setext_headings() {
457        let rule = MD026NoTrailingPunctuation::new(None);
458        let content = "Title.\n======\n\nSubtitle,\n---------";
459        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
460        let fixed = rule.fix(&ctx).unwrap();
461        assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
462    }
463
464    #[test]
465    fn test_fix_preserves_trailing_hashes() {
466        let rule = MD026NoTrailingPunctuation::new(None);
467        let content = "# Title. #\n## Subtitle, ##";
468        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
469        let fixed = rule.fix(&ctx).unwrap();
470        assert_eq!(fixed, "# Title #\n## Subtitle ##");
471    }
472
473    #[test]
474    fn test_indented_headings() {
475        let rule = MD026NoTrailingPunctuation::new(None);
476        let content = "   # Title.\n  ## Subtitle.";
477        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
478        let result = rule.check(&ctx).unwrap();
479        assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
480    }
481
482    #[test]
483    fn test_deeply_indented_ignored() {
484        let rule = MD026NoTrailingPunctuation::new(None);
485        let content = "    # This is code.";
486        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
487        let result = rule.check(&ctx).unwrap();
488        assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
489    }
490
491    #[test]
492    fn test_multiple_punctuation() {
493        let rule = MD026NoTrailingPunctuation::new(None);
494        let content = "# Title...";
495        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
496        let result = rule.check(&ctx).unwrap();
497        assert_eq!(result.len(), 1);
498        assert_eq!(result[0].column, 8); // Points to first period
499    }
500
501    #[test]
502    fn test_empty_content() {
503        let rule = MD026NoTrailingPunctuation::new(None);
504        let content = "";
505        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
506        let result = rule.check(&ctx).unwrap();
507        assert!(result.is_empty());
508    }
509
510    #[test]
511    fn test_no_headings() {
512        let rule = MD026NoTrailingPunctuation::new(None);
513        let content = "This is just text.\nMore text with punctuation.";
514        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
515        let result = rule.check(&ctx).unwrap();
516        assert!(result.is_empty(), "Non-heading lines should not be checked");
517    }
518
519    #[test]
520    fn test_get_punctuation_regex() {
521        let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
522        let regex = rule.get_punctuation_regex().unwrap();
523        assert!(regex.is_match("text!"));
524        assert!(regex.is_match("text?"));
525        assert!(!regex.is_match("text."));
526    }
527
528    #[test]
529    fn test_regex_caching() {
530        let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
531        let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
532
533        // Both should get the same cached regex
534        let _regex1 = rule1.get_punctuation_regex().unwrap();
535        let _regex2 = rule2.get_punctuation_regex().unwrap();
536
537        // Check cache has the entry
538        let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
539        assert!(cache.contains_key("!"));
540    }
541
542    #[test]
543    fn test_config_from_toml() {
544        let mut config = crate::config::Config::default();
545        let mut rule_config = crate::config::RuleConfig::default();
546        rule_config
547            .values
548            .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
549        config.rules.insert("MD026".to_string(), rule_config);
550
551        let rule = MD026NoTrailingPunctuation::from_config(&config);
552        let content = "# Title!\n# Another?";
553        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
554        let result = rule.check(&ctx).unwrap();
555        assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
556    }
557
558    #[test]
559    fn test_fix_removes_punctuation() {
560        let rule = MD026NoTrailingPunctuation::new(None);
561        let content = "# Title.   \n## Subtitle,  ";
562        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
563        let fixed = rule.fix(&ctx).unwrap();
564        // The current implementation doesn't preserve trailing whitespace after punctuation removal
565        assert_eq!(fixed, "# Title\n## Subtitle");
566    }
567
568    #[test]
569    fn test_final_newline_preservation() {
570        let rule = MD026NoTrailingPunctuation::new(None);
571        let content = "# Title.\n";
572        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
573        let fixed = rule.fix(&ctx).unwrap();
574        assert_eq!(fixed, "# Title\n");
575
576        let content_no_newline = "# Title.";
577        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard);
578        let fixed2 = rule.fix(&ctx2).unwrap();
579        assert_eq!(fixed2, "# Title");
580    }
581}