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