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 invalid headings (e.g., `#NoSpace` which lacks required space after #)
210                if !heading.is_valid {
211                    continue;
212                }
213
214                // Skip deeply indented headings (they're code blocks)
215                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
216                    continue;
217                }
218
219                // LintContext already strips Kramdown IDs from heading.text
220                // So we just check the heading text directly for trailing punctuation
221                // This correctly flags "# Heading." even if it has {#id}
222                let text_to_check = heading.text.clone();
223
224                if self.has_trailing_punctuation(&text_to_check, &re) {
225                    // Find the trailing punctuation
226                    if let Some(punctuation_match) = re.find(&text_to_check) {
227                        let line = line_info.content(ctx.content);
228
229                        // For ATX headings, find the punctuation position in the line
230                        let punctuation_pos_in_text = punctuation_match.start();
231                        let text_pos_in_line = line.find(&heading.text).unwrap_or(heading.content_column);
232                        let punctuation_start_in_line = text_pos_in_line + punctuation_pos_in_text;
233                        let punctuation_len = punctuation_match.len();
234
235                        let (start_line, start_col, end_line, end_col) = calculate_match_range(
236                            line_num + 1, // Convert to 1-indexed
237                            line,
238                            punctuation_start_in_line,
239                            punctuation_len,
240                        );
241
242                        let last_char = text_to_check.chars().last().unwrap_or(' ');
243                        warnings.push(LintWarning {
244                            rule_name: Some(self.name().to_string()),
245                            line: start_line,
246                            column: start_col,
247                            end_line,
248                            end_column: end_col,
249                            message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
250                            severity: Severity::Warning,
251                            fix: Some(Fix {
252                                range: self.get_line_byte_range(content, line_num + 1, line_index),
253                                replacement: if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
254                                    self.fix_atx_heading(line, &re)
255                                } else {
256                                    self.fix_setext_heading(line, &re)
257                                },
258                            }),
259                        });
260                    }
261                }
262            }
263        }
264
265        Ok(warnings)
266    }
267
268    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
269        let content = ctx.content;
270
271        // Fast path optimizations
272        if content.is_empty() {
273            return Ok(content.to_string());
274        }
275
276        // Quick check for punctuation
277        // For custom punctuation, we need to check differently
278        if self.config.punctuation == DEFAULT_PUNCTUATION {
279            if !QUICK_PUNCTUATION_CHECK.is_match(content) {
280                return Ok(content.to_string());
281            }
282        } else {
283            // For custom punctuation, check if any of those characters exist
284            let has_custom_punctuation = self.config.punctuation.chars().any(|c| content.contains(c));
285            if !has_custom_punctuation {
286                return Ok(content.to_string());
287            }
288        }
289
290        // Check if we have any headings from pre-computed line info
291        let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
292        if !has_headings {
293            return Ok(content.to_string());
294        }
295
296        let re = match self.get_punctuation_regex() {
297            Ok(regex) => regex,
298            Err(_) => return Ok(content.to_string()),
299        };
300
301        let lines: Vec<&str> = content.lines().collect();
302        let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
303
304        // Use pre-computed heading information from LintContext
305        for (line_num, line_info) in ctx.lines.iter().enumerate() {
306            if let Some(heading) = &line_info.heading {
307                // Skip invalid headings (e.g., `#NoSpace` which lacks required space after #)
308                if !heading.is_valid {
309                    continue;
310                }
311
312                // Skip deeply indented headings (they're code blocks)
313                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
314                    continue;
315                }
316
317                // LintContext already strips custom header IDs from heading.text
318                // So we just check the heading text directly for trailing punctuation
319                let text_to_check = heading.text.clone();
320
321                // Check and fix trailing punctuation
322                if self.has_trailing_punctuation(&text_to_check, &re) {
323                    fixed_lines[line_num] = if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
324                        self.fix_atx_heading(line_info.content(ctx.content), &re)
325                    } else {
326                        self.fix_setext_heading(line_info.content(ctx.content), &re)
327                    };
328                }
329            }
330        }
331
332        // Reconstruct content preserving line endings
333        let mut result = String::with_capacity(content.len());
334        for (i, line) in fixed_lines.iter().enumerate() {
335            result.push_str(line);
336            if i < fixed_lines.len() - 1 || content.ends_with('\n') {
337                result.push('\n');
338            }
339        }
340
341        Ok(result)
342    }
343
344    fn as_any(&self) -> &dyn std::any::Any {
345        self
346    }
347
348    fn default_config_section(&self) -> Option<(String, toml::Value)> {
349        let json_value = serde_json::to_value(&self.config).ok()?;
350        Some((
351            self.name().to_string(),
352            crate::rule_config_serde::json_to_toml_value(&json_value)?,
353        ))
354    }
355
356    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
357    where
358        Self: Sized,
359    {
360        let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
361        Box::new(Self::from_config_struct(rule_config))
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::lint_context::LintContext;
369
370    #[test]
371    fn test_no_trailing_punctuation() {
372        let rule = MD026NoTrailingPunctuation::new(None);
373        let content = "# This is a heading\n\n## Another heading";
374        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
375        let result = rule.check(&ctx).unwrap();
376        assert!(result.is_empty(), "Headings without punctuation should not be flagged");
377    }
378
379    #[test]
380    fn test_trailing_period() {
381        let rule = MD026NoTrailingPunctuation::new(None);
382        let content = "# This is a heading.\n\n## Another one.";
383        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
384        let result = rule.check(&ctx).unwrap();
385        assert_eq!(result.len(), 2);
386        assert_eq!(result[0].line, 1);
387        assert_eq!(result[0].column, 20);
388        assert!(result[0].message.contains("ends with punctuation '.'"));
389        assert_eq!(result[1].line, 3);
390        assert_eq!(result[1].column, 15);
391    }
392
393    #[test]
394    fn test_trailing_comma() {
395        let rule = MD026NoTrailingPunctuation::new(None);
396        let content = "# Heading,\n## Sub-heading,";
397        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
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_trailing_semicolon() {
405        let rule = MD026NoTrailingPunctuation::new(None);
406        let content = "# Title;\n## Subtitle;";
407        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
408        let result = rule.check(&ctx).unwrap();
409        assert_eq!(result.len(), 2);
410        assert!(result[0].message.contains("ends with punctuation ';'"));
411    }
412
413    #[test]
414    fn test_custom_punctuation() {
415        let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
416        let content = "# Important!\n## Regular heading.";
417        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
418        let result = rule.check(&ctx).unwrap();
419        assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
420        assert_eq!(result[0].line, 1);
421        assert!(result[0].message.contains("ends with punctuation '!'"));
422    }
423
424    #[test]
425    fn test_legitimate_question_mark() {
426        let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
427        let content = "# What is this?\n# This is bad.";
428        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
429        let result = rule.check(&ctx).unwrap();
430        // With custom punctuation, legitimate punctuation exceptions don't apply
431        assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
432    }
433
434    #[test]
435    fn test_question_marks_not_in_default() {
436        let rule = MD026NoTrailingPunctuation::new(None);
437        let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
438        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
439        let result = rule.check(&ctx).unwrap();
440        assert!(result.is_empty(), "Question marks are not in default punctuation list");
441    }
442
443    #[test]
444    fn test_colons_in_default() {
445        let rule = MD026NoTrailingPunctuation::new(None);
446        let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
447        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
448        let result = rule.check(&ctx).unwrap();
449        assert_eq!(
450            result.len(),
451            4,
452            "Colons are in default punctuation list and should be flagged"
453        );
454    }
455
456    #[test]
457    fn test_fix_atx_headings() {
458        let rule = MD026NoTrailingPunctuation::new(None);
459        let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
460        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
461        let fixed = rule.fix(&ctx).unwrap();
462        assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
463    }
464
465    #[test]
466    fn test_fix_setext_headings() {
467        let rule = MD026NoTrailingPunctuation::new(None);
468        let content = "Title.\n======\n\nSubtitle,\n---------";
469        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
470        let fixed = rule.fix(&ctx).unwrap();
471        assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
472    }
473
474    #[test]
475    fn test_fix_preserves_trailing_hashes() {
476        let rule = MD026NoTrailingPunctuation::new(None);
477        let content = "# Title. #\n## Subtitle, ##";
478        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
479        let fixed = rule.fix(&ctx).unwrap();
480        assert_eq!(fixed, "# Title #\n## Subtitle ##");
481    }
482
483    #[test]
484    fn test_indented_headings() {
485        let rule = MD026NoTrailingPunctuation::new(None);
486        let content = "   # Title.\n  ## Subtitle.";
487        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
488        let result = rule.check(&ctx).unwrap();
489        assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
490    }
491
492    #[test]
493    fn test_deeply_indented_ignored() {
494        let rule = MD026NoTrailingPunctuation::new(None);
495        let content = "    # This is code.";
496        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
497        let result = rule.check(&ctx).unwrap();
498        assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
499    }
500
501    #[test]
502    fn test_multiple_punctuation() {
503        let rule = MD026NoTrailingPunctuation::new(None);
504        let content = "# Title...";
505        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
506        let result = rule.check(&ctx).unwrap();
507        assert_eq!(result.len(), 1);
508        assert_eq!(result[0].column, 8); // Points to first period
509    }
510
511    #[test]
512    fn test_empty_content() {
513        let rule = MD026NoTrailingPunctuation::new(None);
514        let content = "";
515        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
516        let result = rule.check(&ctx).unwrap();
517        assert!(result.is_empty());
518    }
519
520    #[test]
521    fn test_no_headings() {
522        let rule = MD026NoTrailingPunctuation::new(None);
523        let content = "This is just text.\nMore text with punctuation.";
524        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
525        let result = rule.check(&ctx).unwrap();
526        assert!(result.is_empty(), "Non-heading lines should not be checked");
527    }
528
529    #[test]
530    fn test_get_punctuation_regex() {
531        let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
532        let regex = rule.get_punctuation_regex().unwrap();
533        assert!(regex.is_match("text!"));
534        assert!(regex.is_match("text?"));
535        assert!(!regex.is_match("text."));
536    }
537
538    #[test]
539    fn test_regex_caching() {
540        let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
541        let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
542
543        // Both should get the same cached regex
544        let _regex1 = rule1.get_punctuation_regex().unwrap();
545        let _regex2 = rule2.get_punctuation_regex().unwrap();
546
547        // Check cache has the entry
548        let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
549        assert!(cache.contains_key("!"));
550    }
551
552    #[test]
553    fn test_config_from_toml() {
554        let mut config = crate::config::Config::default();
555        let mut rule_config = crate::config::RuleConfig::default();
556        rule_config
557            .values
558            .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
559        config.rules.insert("MD026".to_string(), rule_config);
560
561        let rule = MD026NoTrailingPunctuation::from_config(&config);
562        let content = "# Title!\n# Another?";
563        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
564        let result = rule.check(&ctx).unwrap();
565        assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
566    }
567
568    #[test]
569    fn test_fix_removes_punctuation() {
570        let rule = MD026NoTrailingPunctuation::new(None);
571        let content = "# Title.   \n## Subtitle,  ";
572        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
573        let fixed = rule.fix(&ctx).unwrap();
574        // The current implementation doesn't preserve trailing whitespace after punctuation removal
575        assert_eq!(fixed, "# Title\n## Subtitle");
576    }
577
578    #[test]
579    fn test_final_newline_preservation() {
580        let rule = MD026NoTrailingPunctuation::new(None);
581        let content = "# Title.\n";
582        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
583        let fixed = rule.fix(&ctx).unwrap();
584        assert_eq!(fixed, "# Title\n");
585
586        let content_no_newline = "# Title.";
587        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
588        let fixed2 = rule.fix(&ctx2).unwrap();
589        assert_eq!(fixed2, "# Title");
590    }
591}