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::rule_config_serde::FlavorOverrideNotice;
6use crate::utils::regex_cache::{EMOJI_SHORTCODE_REGEX, HTML_ENTITY_REGEX};
7use regex::Regex;
8use std::collections::HashMap;
9use std::ops::Range;
10use std::sync::LazyLock;
11use std::sync::RwLock;
12
13mod md026_config;
14use md026_config::{DEFAULT_PUNCTUATION, MD026Config};
15
16// Optimized single regex for all ATX heading types (normal, closed, indented 1-3 spaces)
17static ATX_HEADING_UNIFIED: LazyLock<Regex> =
18    LazyLock::new(|| Regex::new(r"^( {0,3})(#{1,6})(\s+)(.+?)(\s+#{1,6})?$").unwrap());
19
20// Fast check patterns for early returns - match defaults
21static QUICK_PUNCTUATION_CHECK: LazyLock<Regex> =
22    LazyLock::new(|| Regex::new(&format!(r"[{}]", regex::escape(DEFAULT_PUNCTUATION))).unwrap());
23
24// Regex cache for punctuation patterns
25static PUNCTUATION_REGEX_CACHE: LazyLock<RwLock<HashMap<String, Regex>>> =
26    LazyLock::new(|| RwLock::new(HashMap::new()));
27
28/// Reports the MDG punctuation override once per process, across every config group.
29static MDG_PUNCTUATION_OVERRIDE: FlavorOverrideNotice = FlavorOverrideNotice::new();
30
31/// Rule MD026: Trailing punctuation in heading
32#[derive(Clone)]
33pub struct MD026NoTrailingPunctuation {
34    config: MD026Config,
35    // A Gherkin structure is an ATX heading spelled `Keyword: name`, so the colon after the
36    // keyword is what makes the keyword a keyword. Dropping it from the punctuation set for
37    // that flavor keeps the rule from ever deleting it, however `punctuation` is configured.
38    mdg_punctuation: String,
39    // Whether the colon the Gherkin flavor drops was asked for rather than inherited from
40    // the default.
41    colon_configured_explicitly: bool,
42}
43
44impl Default for MD026NoTrailingPunctuation {
45    fn default() -> Self {
46        Self::new(None)
47    }
48}
49
50impl MD026NoTrailingPunctuation {
51    pub fn new(punctuation: Option<String>) -> Self {
52        let explicit = punctuation.is_some();
53        Self::build(
54            MD026Config {
55                punctuation: punctuation.unwrap_or_else(|| DEFAULT_PUNCTUATION.to_string()),
56            },
57            explicit,
58        )
59    }
60
61    pub fn from_config_struct(config: MD026Config) -> Self {
62        Self::build(config, false)
63    }
64
65    fn build(config: MD026Config, punctuation_explicit: bool) -> Self {
66        let colon_configured_explicitly = punctuation_explicit && config.punctuation.contains(':');
67        let mdg_punctuation = config.punctuation.replace(':', "");
68
69        Self {
70            config,
71            mdg_punctuation,
72            colon_configured_explicitly,
73        }
74    }
75
76    /// The punctuation set the flavor actually enforces.
77    #[inline]
78    fn effective_punctuation(&self, flavor: crate::config::MarkdownFlavor) -> &str {
79        if flavor == crate::config::MarkdownFlavor::MDG {
80            &self.mdg_punctuation
81        } else {
82            &self.config.punctuation
83        }
84    }
85
86    /// Whether MDG is overriding a colon that came from explicit configuration.
87    fn mdg_colon_override_applies(&self, flavor: crate::config::MarkdownFlavor) -> bool {
88        flavor == crate::config::MarkdownFlavor::MDG && self.colon_configured_explicitly
89    }
90
91    /// Report the effective punctuation override before any content-based
92    /// shortcut can skip this rule. Direct `check` callers also pass through
93    /// here; the shared notice keeps it process-local and one-shot even when a
94    /// run creates separate rule instances for multiple config groups.
95    fn warn_once_about_mdg_colon_override(&self, flavor: crate::config::MarkdownFlavor) {
96        if self.mdg_colon_override_applies(flavor) {
97            MDG_PUNCTUATION_OVERRIDE.report(
98                "MD026",
99                "punctuation",
100                &self.config.punctuation,
101                &self.mdg_punctuation,
102                "the ASCII colon after a Gherkin keyword is structural",
103            );
104        }
105    }
106
107    #[inline]
108    fn get_punctuation_regex(&self, punctuation: &str) -> Result<Regex, regex::Error> {
109        // Check cache first
110        {
111            let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
112            if let Some(cached_regex) = cache.get(punctuation) {
113                return Ok(cached_regex.clone());
114            }
115        }
116
117        // Compile and cache the regex
118        let pattern = format!(r"([{}]+)$", regex::escape(punctuation));
119        let regex = Regex::new(&pattern)?;
120
121        {
122            let mut cache = PUNCTUATION_REGEX_CACHE.write().unwrap();
123            cache.insert(punctuation.to_string(), regex.clone());
124        }
125
126        Ok(regex)
127    }
128
129    /// The run of punctuation that ends `text`, as a byte range.
130    ///
131    /// A punctuation character that closes an HTML entity reference (`&amp;`, `&#59;`,
132    /// `&#x3B;`) or an emoji shortcode (`:tada:`) is that construct's delimiter, not
133    /// punctuation: removing it would turn the construct into literal text. The run
134    /// therefore starts after the last such construct, so `Fish &amp;` has no run and
135    /// `Fish &amp;.` has the run `.`.
136    ///
137    /// A backslash-escaped opener (`\&amp;`, `\:tada:`) renders as literal text, so
138    /// its closing character is ordinary punctuation and counts toward the run.
139    fn trailing_punctuation_run(&self, text: &str, re: &Regex) -> Option<Range<usize>> {
140        let mut start = re.find(text)?.start();
141        let constructs = HTML_ENTITY_REGEX
142            .find_iter(text)
143            .chain(EMOJI_SHORTCODE_REGEX.find_iter(text));
144        for construct in constructs {
145            if Self::is_backslash_escaped(text, construct.start()) {
146                continue;
147            }
148            start = start.max(construct.end());
149        }
150        (start < text.len()).then_some(start..text.len())
151    }
152
153    /// True when the character at `pos` is preceded by an odd number of backslashes,
154    /// which escapes it: `\&` is a literal ampersand while `\\&` is an escaped
155    /// backslash followed by a live one.
156    fn is_backslash_escaped(text: &str, pos: usize) -> bool {
157        text[..pos].bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1
158    }
159
160    // Remove trailing punctuation from text.
161    //
162    // A single removal is not enough when punctuation is separated from the end by
163    // interior whitespace (e.g. `. :`): removing `:` leaves `. `, whose trailing space
164    // then exposes `.`, so a second fix pass would change the result again. This keeps
165    // stripping while trimming the exposed whitespace reveals further trailing
166    // punctuation, making one fix call fully converge (idempotent). Trailing whitespace
167    // that does not hide more punctuation is preserved, matching the single-punctuation
168    // behavior (e.g. `Title :` -> `Title `).
169    #[inline]
170    fn remove_trailing_punctuation(&self, text: &str, re: &Regex) -> String {
171        let mut result = text.trim().to_string();
172        loop {
173            let Some(run) = self.trailing_punctuation_run(&result, re) else {
174                // No trailing punctuation run at the very end.
175                return result;
176            };
177            result.truncate(run.start);
178            // Continue only if trimming the whitespace exposed by this removal reveals
179            // more trailing punctuation; otherwise keep the result (whitespace and all).
180            let trimmed_len = result.trim_end().len();
181            if trimmed_len != result.len() && self.trailing_punctuation_run(&result[..trimmed_len], re).is_some() {
182                result.truncate(trimmed_len);
183            } else {
184                return result;
185            }
186        }
187    }
188
189    // Optimized ATX heading fix using unified regex
190    #[inline]
191    fn fix_atx_heading(&self, line: &str, re: &Regex) -> String {
192        if let Some(captures) = ATX_HEADING_UNIFIED.captures(line) {
193            let indentation = captures.get(1).unwrap().as_str();
194            let hashes = captures.get(2).unwrap().as_str();
195            let space = captures.get(3).unwrap().as_str();
196            let content = captures.get(4).unwrap().as_str();
197
198            // Check if content ends with a custom header ID like {#my-id}
199            // If so, we need to fix punctuation before the ID
200            let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
201                // Has a custom ID - fix punctuation before it
202                let before_id = &content[..id_pos];
203                let id_part = &content[id_pos..];
204                let fixed_before = self.remove_trailing_punctuation(before_id, re);
205                format!("{fixed_before}{id_part}")
206            } else {
207                // No custom ID - just remove trailing punctuation
208                self.remove_trailing_punctuation(content, re)
209            };
210
211            // Preserve any trailing hashes if present
212            if let Some(trailing) = captures.get(5) {
213                return format!(
214                    "{}{}{}{}{}",
215                    indentation,
216                    hashes,
217                    space,
218                    fixed_content,
219                    trailing.as_str()
220                );
221            }
222
223            return format!("{indentation}{hashes}{space}{fixed_content}");
224        }
225
226        // Fallback if no regex matches
227        line.to_string()
228    }
229}
230
231/// The bytes of `source` before `end` that `removed`, a suffix of a heading's
232/// display text, is written as, read backwards together: a whitespace run of
233/// the text is the whitespace run of the source it renders, a line ending and
234/// the indentation below it included, and any other character is itself. None
235/// where the source reads differently, as it does when an anchor element sits
236/// inside the removed text.
237fn removed_source_range(source: &str, end: usize, removed: &str) -> Option<Range<usize>> {
238    let mut source = source.get(..end)?;
239    let mut rest = removed;
240    while !rest.is_empty() {
241        let text = rest.trim_end();
242        if text.len() < rest.len() {
243            let trimmed = source.trim_end();
244            if trimmed.len() == source.len() {
245                return None;
246            }
247            source = trimmed;
248            rest = text;
249        } else {
250            let ch = rest.chars().next_back()?;
251            source = source.strip_suffix(ch)?;
252            rest = &rest[..rest.len() - ch.len_utf8()];
253        }
254    }
255    Some(source.len()..end)
256}
257
258impl Rule for MD026NoTrailingPunctuation {
259    fn name(&self) -> &'static str {
260        "MD026"
261    }
262
263    fn description(&self) -> &'static str {
264        "Trailing punctuation in heading"
265    }
266
267    fn category(&self) -> RuleCategory {
268        RuleCategory::Heading
269    }
270
271    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
272        self.warn_once_about_mdg_colon_override(ctx.flavor);
273
274        // Skip if no heading markers
275        if !ctx.likely_has_headings() {
276            return true;
277        }
278        // Skip if none of the configured punctuation exists
279        let punctuation = self.effective_punctuation(ctx.flavor);
280        !punctuation.chars().any(|p| ctx.content.contains(p))
281    }
282
283    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
284        let content = ctx.content;
285        let punctuation = self.effective_punctuation(ctx.flavor);
286
287        self.warn_once_about_mdg_colon_override(ctx.flavor);
288
289        // Early returns for performance
290        if content.is_empty() {
291            return Ok(Vec::new());
292        }
293
294        // Quick check for any punctuation we care about
295        // For custom punctuation, we need to check differently
296        if punctuation == DEFAULT_PUNCTUATION {
297            if !QUICK_PUNCTUATION_CHECK.is_match(content) {
298                return Ok(Vec::new());
299            }
300        } else {
301            // For custom punctuation, check if any of those characters exist
302            let has_custom_punctuation = punctuation.chars().any(|c| content.contains(c));
303            if !has_custom_punctuation {
304                return Ok(Vec::new());
305            }
306        }
307
308        // Check if we have any headings from pre-computed line info
309        let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
310        if !has_headings {
311            return Ok(Vec::new());
312        }
313
314        let mut warnings = Vec::new();
315        let Ok(re) = self.get_punctuation_regex(punctuation) else {
316            return Ok(warnings);
317        };
318
319        // Use pre-computed heading information from LintContext
320        for (line_num, line_info) in ctx.lines.iter().enumerate() {
321            // A Setext heading is recorded on the last line of its text, and the
322            // parsed form locates where that text ends.
323            if line_info.heading.is_some()
324                && let Some(parsed) = ctx.heading_on_line(line_num + 1)
325            {
326                let heading = parsed.heading;
327                // Skip deeply indented headings (they're code blocks)
328                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
329                    continue;
330                }
331
332                // LintContext already strips Kramdown IDs from heading.text
333                // So we just check the heading text directly for trailing punctuation
334                // This correctly flags "# Heading." even if it has {#id}
335                let text_to_check = heading.text.as_str();
336
337                let Some(run) = self.trailing_punctuation_run(text_to_check, &re) else {
338                    continue;
339                };
340                let line = line_info.content(ctx.content);
341
342                // The run closes the heading's display text, so in the source
343                // it sits at the end of the text range, whichever line of a
344                // Setext heading that ends on, unless an anchor element written
345                // inside the run keeps the two apart. Then the whole text is
346                // reported, and the punctuation is left in place.
347                let range = parsed.text_byte_range(ctx.content);
348                let run_text = &text_to_check[run.clone()];
349                let run_start = range
350                    .end
351                    .checked_sub(run_text.len())
352                    .filter(|&start| ctx.content.get(start..range.end) == Some(run_text));
353                let (start_line, start_col) = ctx.offset_to_line_col(run_start.unwrap_or(range.start));
354                let (end_line, end_col) = ctx.offset_to_line_col(range.end);
355
356                let fix = if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
357                    Some(Fix::new(
358                        ctx.line_content_byte_range(line_num + 1),
359                        self.fix_atx_heading(line, &re),
360                    ))
361                } else {
362                    // The fix deletes the removed text where it stands, so an
363                    // attribute list or anchor element after it, and the
364                    // indentation of a heading written inside a container, stay
365                    // as they are. Whitespace between two runs of punctuation
366                    // goes with them, a line break included; where the source
367                    // reads differently, only the run itself goes.
368                    run_start.map(|start| {
369                        let fixed = self.remove_trailing_punctuation(text_to_check, &re);
370                        let removed = text_to_check.trim().strip_prefix(fixed.as_str()).unwrap_or(run_text);
371                        Fix::new(
372                            removed_source_range(ctx.content, range.end, removed).unwrap_or(start..range.end),
373                            String::new(),
374                        )
375                    })
376                };
377
378                let last_char = text_to_check.chars().last().unwrap_or(' ');
379                warnings.push(LintWarning {
380                    rule_name: Some(self.name().to_string()),
381                    line: start_line,
382                    column: start_col,
383                    end_line,
384                    end_column: end_col,
385                    message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
386                    severity: Severity::Warning,
387                    fix,
388                });
389            }
390        }
391
392        Ok(warnings)
393    }
394
395    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
396        if self.should_skip(ctx) {
397            return Ok(ctx.content.to_string());
398        }
399        let warnings = self.check(ctx)?;
400        if warnings.is_empty() {
401            return Ok(ctx.content.to_string());
402        }
403        let warnings =
404            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
405        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
406            .map_err(crate::rule::LintError::InvalidInput)
407    }
408
409    fn as_any(&self) -> &dyn std::any::Any {
410        self
411    }
412
413    crate::impl_rule_config_sections!(MD026Config);
414
415    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
416    where
417        Self: Sized,
418    {
419        let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
420
421        // Check if punctuation was explicitly set in the config; the Gherkin flavor drops
422        // the colon from it, and an override the user asked for is worth reporting.
423        let punctuation_explicit = config
424            .rules
425            .get("MD026")
426            .is_some_and(|rule_cfg| rule_cfg.values.contains_key("punctuation"));
427
428        Box::new(Self::build(rule_config, punctuation_explicit))
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use crate::lint_context::LintContext;
436
437    #[test]
438    fn test_no_trailing_punctuation() {
439        let rule = MD026NoTrailingPunctuation::new(None);
440        let content = "# This is a heading\n\n## Another heading";
441        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
442        let result = rule.check(&ctx).unwrap();
443        assert!(result.is_empty(), "Headings without punctuation should not be flagged");
444    }
445
446    #[test]
447    fn test_trailing_period() {
448        let rule = MD026NoTrailingPunctuation::new(None);
449        let content = "# This is a heading.\n\n## Another one.";
450        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
451        let result = rule.check(&ctx).unwrap();
452        assert_eq!(result.len(), 2);
453        assert_eq!(result[0].line, 1);
454        assert_eq!(result[0].column, 20);
455        assert!(result[0].message.contains("ends with punctuation '.'"));
456        assert_eq!(result[1].line, 3);
457        assert_eq!(result[1].column, 15);
458    }
459
460    #[test]
461    fn test_trailing_comma() {
462        let rule = MD026NoTrailingPunctuation::new(None);
463        let content = "# Heading,\n## Sub-heading,";
464        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
465        let result = rule.check(&ctx).unwrap();
466        assert_eq!(result.len(), 2);
467        assert!(result[0].message.contains("ends with punctuation ','"));
468    }
469
470    #[test]
471    fn test_trailing_semicolon() {
472        let rule = MD026NoTrailingPunctuation::new(None);
473        let content = "# Title;\n## Subtitle;";
474        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
475        let result = rule.check(&ctx).unwrap();
476        assert_eq!(result.len(), 2);
477        assert!(result[0].message.contains("ends with punctuation ';'"));
478    }
479
480    #[test]
481    fn test_custom_punctuation() {
482        let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
483        let content = "# Important!\n## Regular heading.";
484        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
485        let result = rule.check(&ctx).unwrap();
486        assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
487        assert_eq!(result[0].line, 1);
488        assert!(result[0].message.contains("ends with punctuation '!'"));
489    }
490
491    #[test]
492    fn test_legitimate_question_mark() {
493        let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
494        let content = "# What is this?\n# This is bad.";
495        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
496        let result = rule.check(&ctx).unwrap();
497        // With custom punctuation, legitimate punctuation exceptions don't apply
498        assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
499    }
500
501    #[test]
502    fn test_question_marks_not_in_default() {
503        let rule = MD026NoTrailingPunctuation::new(None);
504        let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
505        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
506        let result = rule.check(&ctx).unwrap();
507        assert!(result.is_empty(), "Question marks are not in default punctuation list");
508    }
509
510    #[test]
511    fn test_colons_in_default() {
512        let rule = MD026NoTrailingPunctuation::new(None);
513        let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
514        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
515        let result = rule.check(&ctx).unwrap();
516        assert_eq!(
517            result.len(),
518            4,
519            "Colons are in default punctuation list and should be flagged"
520        );
521    }
522
523    #[test]
524    fn test_fix_atx_headings() {
525        let rule = MD026NoTrailingPunctuation::new(None);
526        let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
527        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
528        let fixed = rule.fix(&ctx).unwrap();
529        assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
530    }
531
532    #[test]
533    fn test_fix_setext_headings() {
534        let rule = MD026NoTrailingPunctuation::new(None);
535        let content = "Title.\n======\n\nSubtitle,\n---------";
536        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
537        let fixed = rule.fix(&ctx).unwrap();
538        assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
539    }
540
541    #[test]
542    fn test_fix_preserves_trailing_hashes() {
543        let rule = MD026NoTrailingPunctuation::new(None);
544        let content = "# Title. #\n## Subtitle, ##";
545        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
546        let fixed = rule.fix(&ctx).unwrap();
547        assert_eq!(fixed, "# Title #\n## Subtitle ##");
548    }
549
550    #[test]
551    fn test_indented_headings() {
552        let rule = MD026NoTrailingPunctuation::new(None);
553        let content = "   # Title.\n  ## Subtitle.";
554        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
555        let result = rule.check(&ctx).unwrap();
556        assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
557    }
558
559    #[test]
560    fn test_deeply_indented_ignored() {
561        let rule = MD026NoTrailingPunctuation::new(None);
562        let content = "    # This is code.";
563        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
564        let result = rule.check(&ctx).unwrap();
565        assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
566    }
567
568    #[test]
569    fn test_multiple_punctuation() {
570        let rule = MD026NoTrailingPunctuation::new(None);
571        let content = "# Title...";
572        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
573        let result = rule.check(&ctx).unwrap();
574        assert_eq!(result.len(), 1);
575        assert_eq!(result[0].column, 8); // Points to first period
576    }
577
578    #[test]
579    fn test_empty_content() {
580        let rule = MD026NoTrailingPunctuation::new(None);
581        let content = "";
582        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
583        let result = rule.check(&ctx).unwrap();
584        assert!(result.is_empty());
585    }
586
587    #[test]
588    fn test_no_headings() {
589        let rule = MD026NoTrailingPunctuation::new(None);
590        let content = "This is just text.\nMore text with punctuation.";
591        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
592        let result = rule.check(&ctx).unwrap();
593        assert!(result.is_empty(), "Non-heading lines should not be checked");
594    }
595
596    #[test]
597    fn test_get_punctuation_regex() {
598        let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
599        let regex = rule.get_punctuation_regex(&rule.config.punctuation).unwrap();
600        assert!(regex.is_match("text!"));
601        assert!(regex.is_match("text?"));
602        assert!(!regex.is_match("text."));
603    }
604
605    #[test]
606    fn test_regex_caching() {
607        let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
608        let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
609
610        // Both should get the same cached regex
611        let _regex1 = rule1.get_punctuation_regex(&rule1.config.punctuation).unwrap();
612        let _regex2 = rule2.get_punctuation_regex(&rule2.config.punctuation).unwrap();
613
614        // Check cache has the entry
615        let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
616        assert!(cache.contains_key("!"));
617    }
618
619    #[test]
620    fn test_config_from_toml() {
621        let mut config = crate::config::Config::default();
622        let mut rule_config = crate::config::RuleConfig::default();
623        rule_config
624            .values
625            .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
626        config.rules.insert("MD026".to_string(), rule_config);
627
628        let rule = MD026NoTrailingPunctuation::from_config(&config);
629        let content = "# Title!\n# Another?";
630        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
631        let result = rule.check(&ctx).unwrap();
632        assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
633    }
634
635    #[test]
636    fn test_fix_removes_punctuation() {
637        let rule = MD026NoTrailingPunctuation::new(None);
638        let content = "# Title.   \n## Subtitle,  ";
639        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
640        let fixed = rule.fix(&ctx).unwrap();
641        // The current implementation doesn't preserve trailing whitespace after punctuation removal
642        assert_eq!(fixed, "# Title\n## Subtitle");
643    }
644
645    #[test]
646    fn test_final_newline_preservation() {
647        let rule = MD026NoTrailingPunctuation::new(None);
648        let content = "# Title.\n";
649        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
650        let fixed = rule.fix(&ctx).unwrap();
651        assert_eq!(fixed, "# Title\n");
652
653        let content_no_newline = "# Title.";
654        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
655        let fixed2 = rule.fix(&ctx2).unwrap();
656        assert_eq!(fixed2, "# Title");
657    }
658
659    /// The whole MDG matrix in one place, against the Standard behavior it departs from.
660    ///
661    /// The rule's pattern is `([<punctuation>]+)$`, so taking the colon out of the set is
662    /// the entire flavor difference: no heading whose last character is a colon can match
663    /// any more, and `## Scenario!:` is left exactly as its author wrote it.
664    #[test]
665    fn test_mdg_punctuation_matrix() {
666        let rule = MD026NoTrailingPunctuation::new(None);
667        // (input, standard warnings, standard fix, MDG warnings, MDG fix)
668        let cases = [
669            ("## Notes:\n", 1, "## Notes\n", 0, "## Notes:\n"),
670            ("## Scenario!:\n", 1, "## Scenario\n", 0, "## Scenario!:\n"),
671            ("# Scenario! :\n", 1, "# Scenario\n", 0, "# Scenario! :\n"),
672            ("## Scenario!\n", 1, "## Scenario\n", 1, "## Scenario\n"),
673            ("## Notes::\n", 1, "## Notes\n", 0, "## Notes::\n"),
674            (
675                "# Feature: Checkout:\n",
676                1,
677                "# Feature: Checkout\n",
678                0,
679                "# Feature: Checkout:\n",
680            ),
681            ("### Rule.:\n", 1, "### Rule\n", 0, "### Rule.:\n"),
682        ];
683
684        for (input, standard_count, standard_fixed, mdg_count, mdg_fixed) in cases {
685            for (flavor, count, expected) in [
686                (crate::config::MarkdownFlavor::Standard, standard_count, standard_fixed),
687                (crate::config::MarkdownFlavor::MDG, mdg_count, mdg_fixed),
688            ] {
689                let ctx = LintContext::new(input, flavor, None);
690                assert_eq!(
691                    rule.check(&ctx).unwrap().len(),
692                    count,
693                    "{flavor:?} warning count for {input:?}"
694                );
695
696                let fixed = rule.fix(&ctx).unwrap();
697                assert_eq!(fixed, expected, "{flavor:?} fix for {input:?}");
698
699                let fixed_ctx = LintContext::new(&fixed, flavor, None);
700                assert!(
701                    rule.check(&fixed_ctx).unwrap().is_empty(),
702                    "{flavor:?} left a warning on the fixed {input:?}"
703                );
704                assert_eq!(
705                    rule.fix(&fixed_ctx).unwrap(),
706                    fixed,
707                    "{flavor:?} fix for {input:?} should be idempotent"
708                );
709            }
710        }
711    }
712
713    /// The colon leaves the effective set whatever `punctuation` says, so a future change
714    /// to the default cannot put it back; only an explicit setting is worth reporting.
715    #[test]
716    fn test_mdg_reports_an_explicitly_configured_colon_once() {
717        fn configured(punctuation: &str) -> MD026NoTrailingPunctuation {
718            let mut config = crate::config::Config::default();
719            let mut rule_config = crate::config::RuleConfig::default();
720            rule_config
721                .values
722                .insert("punctuation".to_string(), toml::Value::String(punctuation.to_string()));
723            config.rules.insert("MD026".to_string(), rule_config);
724
725            MD026NoTrailingPunctuation::from_config(&config)
726                .as_any()
727                .downcast_ref::<MD026NoTrailingPunctuation>()
728                .expect("MD026::from_config builds an MD026NoTrailingPunctuation")
729                .clone()
730        }
731
732        let explicit = configured(".,;:!");
733        assert_eq!(
734            explicit.effective_punctuation(crate::config::MarkdownFlavor::Standard),
735            ".,;:!"
736        );
737        assert_eq!(
738            explicit.effective_punctuation(crate::config::MarkdownFlavor::MDG),
739            ".,;!"
740        );
741        assert!(
742            !explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::Standard),
743            "a non-Gherkin file never reports the override"
744        );
745        assert!(explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG));
746
747        let emitted_by_check = configured(".,;:!");
748        let ctx = LintContext::new("## Scenario!\n", crate::config::MarkdownFlavor::MDG, None);
749        assert_eq!(emitted_by_check.check(&ctx).unwrap().len(), 1);
750
751        let emitted_before_skip = configured(".,;:!");
752        let only_protected_punctuation = LintContext::new("#### Examples:\n", crate::config::MarkdownFlavor::MDG, None);
753        assert!(
754            emitted_before_skip.should_skip(&only_protected_punctuation),
755            "the post-override punctuation set has nothing to inspect"
756        );
757
758        let explicit_without_colon = configured(".,;!");
759        assert!(
760            !explicit_without_colon.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
761            "nothing is overridden when the configured set has no colon"
762        );
763
764        let default = MD026NoTrailingPunctuation::new(None);
765        assert_eq!(
766            default.effective_punctuation(crate::config::MarkdownFlavor::MDG),
767            ".,;!",
768            "the colon leaves the default set too"
769        );
770        assert!(
771            !default.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
772            "the default set is not an explicit configuration, so it is silent"
773        );
774    }
775
776    #[test]
777    fn test_mdg_exempts_a_lone_colon_behind_whitespace() {
778        // The colon is not punctuation under MDG, and it is the last character here, so
779        // there is nothing for the `$`-anchored pattern to match. Standard still strips it,
780        // keeping the whitespace that preceded it.
781        let rule = MD026NoTrailingPunctuation::new(None);
782        let content = "# Scenario :\n## Notes:\n";
783
784        let standard_ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
785        let standard = rule.check(&standard_ctx).unwrap();
786        assert_eq!(standard.len(), 2);
787        assert_eq!((standard[0].line, standard[0].column), (1, 12));
788        assert_eq!((standard[1].line, standard[1].column), (2, 9));
789        let standard_fixed = rule.fix(&standard_ctx).unwrap();
790        assert_eq!(standard_fixed, "# Scenario \n## Notes\n");
791        let standard_fixed_ctx = LintContext::new(&standard_fixed, crate::config::MarkdownFlavor::Standard, None);
792        assert_eq!(
793            rule.fix(&standard_fixed_ctx).unwrap(),
794            standard_fixed,
795            "Standard fix should be idempotent"
796        );
797
798        let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
799        assert!(rule.check(&mdg_ctx).unwrap().is_empty());
800        assert_eq!(
801            rule.fix(&mdg_ctx).unwrap(),
802            content,
803            "MDG leaves headings whose only trailing punctuation is the colon untouched"
804        );
805    }
806
807    #[test]
808    fn test_mdg_does_not_exempt_a_full_width_colon() {
809        // Gherkin only recognizes the ASCII colon, so a full-width one carries
810        // no structural meaning and stays in the punctuation set.
811        let rule = MD026NoTrailingPunctuation::new(Some(".,;:!?:".to_string()));
812        assert_eq!(
813            rule.effective_punctuation(crate::config::MarkdownFlavor::MDG),
814            ".,;!?:",
815            "only the ASCII colon leaves the set"
816        );
817
818        let content = "## Scenario:\n";
819        for flavor in [
820            crate::config::MarkdownFlavor::MDG,
821            crate::config::MarkdownFlavor::Standard,
822        ] {
823            let ctx = LintContext::new(content, flavor, None);
824            assert_eq!(rule.check(&ctx).unwrap().len(), 1, "{flavor:?} must flag the `:`");
825            assert_eq!(rule.fix(&ctx).unwrap(), "## Scenario\n");
826        }
827    }
828}