Skip to main content

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, 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
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    //
89    // A single removal is not enough when punctuation is separated from the end by
90    // interior whitespace (e.g. `. :`): removing `:` leaves `. `, whose trailing space
91    // then exposes `.`, so a second fix pass would change the result again. This keeps
92    // stripping while trimming the exposed whitespace reveals further trailing
93    // punctuation, making one fix call fully converge (idempotent). Trailing whitespace
94    // that does not hide more punctuation is preserved, matching the single-punctuation
95    // behavior (e.g. `Title :` -> `Title `).
96    #[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                // No trailing punctuation run at the very end.
103                return stripped;
104            }
105            // Continue only if trimming the whitespace exposed by this removal reveals
106            // more trailing punctuation; otherwise keep the result (whitespace and all).
107            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    // Optimized ATX heading fix using unified regex
117    #[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            // Check if content ends with a custom header ID like {#my-id}
126            // If so, we need to fix punctuation before the ID
127            let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
128                // Has a custom ID - fix punctuation before it
129                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                // No custom ID - just remove trailing punctuation
135                self.remove_trailing_punctuation(content, re)
136            };
137
138            // Preserve any trailing hashes if present
139            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        // Fallback if no regex matches
154        line.to_string()
155    }
156
157    // Fix a setext heading by removing trailing punctuation from the content line
158    #[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        // Preserve trailing whitespace
164        if content_line.len() > trimmed.len() {
165            whitespace = &content_line[trimmed.len()..];
166        }
167
168        // Remove punctuation and preserve whitespace
169        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        // Skip if no heading markers
188        if !ctx.likely_has_headings() {
189            return true;
190        }
191        // Skip if none of the configured punctuation exists
192        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        // Early returns for performance
200        if content.is_empty() {
201            return Ok(Vec::new());
202        }
203
204        // Quick check for any punctuation we care about
205        // For custom punctuation, we need to check differently
206        if self.config.punctuation == DEFAULT_PUNCTUATION {
207            if !QUICK_PUNCTUATION_CHECK.is_match(content) {
208                return Ok(Vec::new());
209            }
210        } else {
211            // For custom punctuation, check if any of those characters exist
212            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        // Check if we have any headings from pre-computed line info
219        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        // Create LineIndex for correct byte position calculations across all line ending types
230        let line_index = &ctx.line_index;
231
232        // Use pre-computed heading information from LintContext
233        for (line_num, line_info) in ctx.lines.iter().enumerate() {
234            if let Some(heading) = &line_info.heading {
235                // Skip invalid headings (e.g., `#NoSpace` which lacks required space after #)
236                if !heading.is_valid {
237                    continue;
238                }
239
240                // Skip deeply indented headings (they're code blocks)
241                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
242                    continue;
243                }
244
245                // LintContext already strips Kramdown IDs from heading.text
246                // So we just check the heading text directly for trailing punctuation
247                // This correctly flags "# Heading." even if it has {#id}
248                let text_to_check = heading.text.clone();
249
250                if self.has_trailing_punctuation(&text_to_check, &re) {
251                    // Find the trailing punctuation
252                    if let Some(punctuation_match) = re.find(&text_to_check) {
253                        let line = line_info.content(ctx.content);
254
255                        // For ATX headings, find the punctuation position in the line
256                        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, // Convert to 1-indexed
263                            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    crate::impl_rule_config_methods!(MD026Config);
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::lint_context::LintContext;
319
320    #[test]
321    fn test_no_trailing_punctuation() {
322        let rule = MD026NoTrailingPunctuation::new(None);
323        let content = "# This is a heading\n\n## Another heading";
324        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
325        let result = rule.check(&ctx).unwrap();
326        assert!(result.is_empty(), "Headings without punctuation should not be flagged");
327    }
328
329    #[test]
330    fn test_trailing_period() {
331        let rule = MD026NoTrailingPunctuation::new(None);
332        let content = "# This is a heading.\n\n## Another one.";
333        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
334        let result = rule.check(&ctx).unwrap();
335        assert_eq!(result.len(), 2);
336        assert_eq!(result[0].line, 1);
337        assert_eq!(result[0].column, 20);
338        assert!(result[0].message.contains("ends with punctuation '.'"));
339        assert_eq!(result[1].line, 3);
340        assert_eq!(result[1].column, 15);
341    }
342
343    #[test]
344    fn test_trailing_comma() {
345        let rule = MD026NoTrailingPunctuation::new(None);
346        let content = "# Heading,\n## Sub-heading,";
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!(result[0].message.contains("ends with punctuation ','"));
351    }
352
353    #[test]
354    fn test_trailing_semicolon() {
355        let rule = MD026NoTrailingPunctuation::new(None);
356        let content = "# Title;\n## Subtitle;";
357        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
358        let result = rule.check(&ctx).unwrap();
359        assert_eq!(result.len(), 2);
360        assert!(result[0].message.contains("ends with punctuation ';'"));
361    }
362
363    #[test]
364    fn test_custom_punctuation() {
365        let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
366        let content = "# Important!\n## Regular heading.";
367        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
368        let result = rule.check(&ctx).unwrap();
369        assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
370        assert_eq!(result[0].line, 1);
371        assert!(result[0].message.contains("ends with punctuation '!'"));
372    }
373
374    #[test]
375    fn test_legitimate_question_mark() {
376        let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
377        let content = "# What is this?\n# This is bad.";
378        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
379        let result = rule.check(&ctx).unwrap();
380        // With custom punctuation, legitimate punctuation exceptions don't apply
381        assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
382    }
383
384    #[test]
385    fn test_question_marks_not_in_default() {
386        let rule = MD026NoTrailingPunctuation::new(None);
387        let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
388        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
389        let result = rule.check(&ctx).unwrap();
390        assert!(result.is_empty(), "Question marks are not in default punctuation list");
391    }
392
393    #[test]
394    fn test_colons_in_default() {
395        let rule = MD026NoTrailingPunctuation::new(None);
396        let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
397        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
398        let result = rule.check(&ctx).unwrap();
399        assert_eq!(
400            result.len(),
401            4,
402            "Colons are in default punctuation list and should be flagged"
403        );
404    }
405
406    #[test]
407    fn test_fix_atx_headings() {
408        let rule = MD026NoTrailingPunctuation::new(None);
409        let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
410        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
411        let fixed = rule.fix(&ctx).unwrap();
412        assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
413    }
414
415    #[test]
416    fn test_fix_setext_headings() {
417        let rule = MD026NoTrailingPunctuation::new(None);
418        let content = "Title.\n======\n\nSubtitle,\n---------";
419        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
420        let fixed = rule.fix(&ctx).unwrap();
421        assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
422    }
423
424    #[test]
425    fn test_fix_preserves_trailing_hashes() {
426        let rule = MD026NoTrailingPunctuation::new(None);
427        let content = "# Title. #\n## Subtitle, ##";
428        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
429        let fixed = rule.fix(&ctx).unwrap();
430        assert_eq!(fixed, "# Title #\n## Subtitle ##");
431    }
432
433    #[test]
434    fn test_indented_headings() {
435        let rule = MD026NoTrailingPunctuation::new(None);
436        let content = "   # Title.\n  ## Subtitle.";
437        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
438        let result = rule.check(&ctx).unwrap();
439        assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
440    }
441
442    #[test]
443    fn test_deeply_indented_ignored() {
444        let rule = MD026NoTrailingPunctuation::new(None);
445        let content = "    # This is code.";
446        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
447        let result = rule.check(&ctx).unwrap();
448        assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
449    }
450
451    #[test]
452    fn test_multiple_punctuation() {
453        let rule = MD026NoTrailingPunctuation::new(None);
454        let content = "# Title...";
455        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
456        let result = rule.check(&ctx).unwrap();
457        assert_eq!(result.len(), 1);
458        assert_eq!(result[0].column, 8); // Points to first period
459    }
460
461    #[test]
462    fn test_empty_content() {
463        let rule = MD026NoTrailingPunctuation::new(None);
464        let content = "";
465        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
466        let result = rule.check(&ctx).unwrap();
467        assert!(result.is_empty());
468    }
469
470    #[test]
471    fn test_no_headings() {
472        let rule = MD026NoTrailingPunctuation::new(None);
473        let content = "This is just text.\nMore text with punctuation.";
474        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
475        let result = rule.check(&ctx).unwrap();
476        assert!(result.is_empty(), "Non-heading lines should not be checked");
477    }
478
479    #[test]
480    fn test_get_punctuation_regex() {
481        let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
482        let regex = rule.get_punctuation_regex().unwrap();
483        assert!(regex.is_match("text!"));
484        assert!(regex.is_match("text?"));
485        assert!(!regex.is_match("text."));
486    }
487
488    #[test]
489    fn test_regex_caching() {
490        let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
491        let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
492
493        // Both should get the same cached regex
494        let _regex1 = rule1.get_punctuation_regex().unwrap();
495        let _regex2 = rule2.get_punctuation_regex().unwrap();
496
497        // Check cache has the entry
498        let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
499        assert!(cache.contains_key("!"));
500    }
501
502    #[test]
503    fn test_config_from_toml() {
504        let mut config = crate::config::Config::default();
505        let mut rule_config = crate::config::RuleConfig::default();
506        rule_config
507            .values
508            .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
509        config.rules.insert("MD026".to_string(), rule_config);
510
511        let rule = MD026NoTrailingPunctuation::from_config(&config);
512        let content = "# Title!\n# Another?";
513        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
514        let result = rule.check(&ctx).unwrap();
515        assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
516    }
517
518    #[test]
519    fn test_fix_removes_punctuation() {
520        let rule = MD026NoTrailingPunctuation::new(None);
521        let content = "# Title.   \n## Subtitle,  ";
522        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
523        let fixed = rule.fix(&ctx).unwrap();
524        // The current implementation doesn't preserve trailing whitespace after punctuation removal
525        assert_eq!(fixed, "# Title\n## Subtitle");
526    }
527
528    #[test]
529    fn test_final_newline_preservation() {
530        let rule = MD026NoTrailingPunctuation::new(None);
531        let content = "# Title.\n";
532        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
533        let fixed = rule.fix(&ctx).unwrap();
534        assert_eq!(fixed, "# Title\n");
535
536        let content_no_newline = "# Title.";
537        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
538        let fixed2 = rule.fix(&ctx2).unwrap();
539        assert_eq!(fixed2, "# Title");
540    }
541}