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                let marker_idx = if matches!(
328                    heading.style,
329                    crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
330                ) {
331                    line_num + 1
332                } else {
333                    line_num
334                };
335                if ctx.lines.get(marker_idx).is_some_and(|marker_line| {
336                    ctx.is_inside_template_code(marker_line.byte_offset + marker_line.indent)
337                }) {
338                    continue;
339                }
340                // Skip deeply indented headings (they're code blocks)
341                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
342                    continue;
343                }
344
345                // LintContext already strips Kramdown IDs from heading.text
346                // So we just check the heading text directly for trailing punctuation
347                // This correctly flags "# Heading." even if it has {#id}
348                let text_to_check = heading.text.as_str();
349
350                let Some(run) = self.trailing_punctuation_run(text_to_check, &re) else {
351                    continue;
352                };
353                let line = line_info.content(ctx.content);
354
355                // The run closes the heading's display text, so in the source
356                // it sits at the end of the text range, whichever line of a
357                // Setext heading that ends on, unless an anchor element written
358                // inside the run keeps the two apart. Then the whole text is
359                // reported, and the punctuation is left in place.
360                let range = parsed.text_byte_range(ctx.content);
361                let run_text = &text_to_check[run.clone()];
362                let run_start = range
363                    .end
364                    .checked_sub(run_text.len())
365                    .filter(|&start| ctx.content.get(start..range.end) == Some(run_text));
366                if run_start.is_some_and(|start| ctx.overlaps_template_code(start, range.end)) {
367                    continue;
368                }
369                let (start_line, start_col) = ctx.offset_to_line_col(run_start.unwrap_or(range.start));
370                let (end_line, end_col) = ctx.offset_to_line_col(range.end);
371
372                let line_range = ctx.line_content_byte_range(line_num + 1);
373                let fix = if matches!(heading.style, crate::lint_context::HeadingStyle::ATX)
374                    && !ctx.overlaps_template_code(line_range.start, line_range.end)
375                {
376                    Some(Fix::new(line_range, self.fix_atx_heading(line, &re)))
377                } else {
378                    // Template-bearing ATX headings use the mapped source run too:
379                    // an anchor lookalike inside a template value is not an ID.
380                    // The fix deletes the removed text where it stands, so an
381                    // attribute list or anchor element after it, and the
382                    // indentation of a heading written inside a container, stay
383                    // as they are. Whitespace between two runs of punctuation
384                    // goes with them, a line break included; where the source
385                    // reads differently, only the run itself goes.
386                    run_start.map(|start| {
387                        let fixed = self.remove_trailing_punctuation(text_to_check, &re);
388                        let removed = text_to_check.trim().strip_prefix(fixed.as_str()).unwrap_or(run_text);
389                        Fix::new(
390                            removed_source_range(ctx.content, range.end, removed).unwrap_or(start..range.end),
391                            String::new(),
392                        )
393                    })
394                };
395
396                let fix = fix.filter(|fix| !ctx.overlaps_template_code(fix.range.start, fix.range.end));
397
398                let last_char = text_to_check.chars().last().unwrap_or(' ');
399                warnings.push(LintWarning {
400                    rule_name: Some(self.name().to_string()),
401                    line: start_line,
402                    column: start_col,
403                    end_line,
404                    end_column: end_col,
405                    message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
406                    severity: Severity::Warning,
407                    fix,
408                });
409            }
410        }
411
412        Ok(warnings)
413    }
414
415    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
416        if self.should_skip(ctx) {
417            return Ok(ctx.content.to_string());
418        }
419        let warnings = self.check(ctx)?;
420        if warnings.is_empty() {
421            return Ok(ctx.content.to_string());
422        }
423        let warnings =
424            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
425        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
426            .map_err(crate::rule::LintError::InvalidInput)
427    }
428
429    fn as_any(&self) -> &dyn std::any::Any {
430        self
431    }
432
433    crate::impl_rule_config_sections!(MD026Config);
434
435    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
436    where
437        Self: Sized,
438    {
439        let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
440
441        // Check if punctuation was explicitly set in the config; the Gherkin flavor drops
442        // the colon from it, and an override the user asked for is worth reporting.
443        let punctuation_explicit = config
444            .rules
445            .get("MD026")
446            .is_some_and(|rule_cfg| rule_cfg.values.contains_key("punctuation"));
447
448        Box::new(Self::build(rule_config, punctuation_explicit))
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455    use crate::lint_context::LintContext;
456
457    #[test]
458    fn test_no_trailing_punctuation() {
459        let rule = MD026NoTrailingPunctuation::new(None);
460        let content = "# This is a heading\n\n## Another heading";
461        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
462        let result = rule.check(&ctx).unwrap();
463        assert!(result.is_empty(), "Headings without punctuation should not be flagged");
464    }
465
466    #[test]
467    fn test_trailing_period() {
468        let rule = MD026NoTrailingPunctuation::new(None);
469        let content = "# This is a heading.\n\n## Another one.";
470        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
471        let result = rule.check(&ctx).unwrap();
472        assert_eq!(result.len(), 2);
473        assert_eq!(result[0].line, 1);
474        assert_eq!(result[0].column, 20);
475        assert!(result[0].message.contains("ends with punctuation '.'"));
476        assert_eq!(result[1].line, 3);
477        assert_eq!(result[1].column, 15);
478    }
479
480    #[test]
481    fn test_trailing_comma() {
482        let rule = MD026NoTrailingPunctuation::new(None);
483        let content = "# Heading,\n## Sub-heading,";
484        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
485        let result = rule.check(&ctx).unwrap();
486        assert_eq!(result.len(), 2);
487        assert!(result[0].message.contains("ends with punctuation ','"));
488    }
489
490    #[test]
491    fn test_trailing_semicolon() {
492        let rule = MD026NoTrailingPunctuation::new(None);
493        let content = "# Title;\n## Subtitle;";
494        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
495        let result = rule.check(&ctx).unwrap();
496        assert_eq!(result.len(), 2);
497        assert!(result[0].message.contains("ends with punctuation ';'"));
498    }
499
500    #[test]
501    fn test_custom_punctuation() {
502        let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
503        let content = "# Important!\n## Regular heading.";
504        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
505        let result = rule.check(&ctx).unwrap();
506        assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
507        assert_eq!(result[0].line, 1);
508        assert!(result[0].message.contains("ends with punctuation '!'"));
509    }
510
511    #[test]
512    fn test_legitimate_question_mark() {
513        let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
514        let content = "# What is this?\n# This is bad.";
515        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
516        let result = rule.check(&ctx).unwrap();
517        // With custom punctuation, legitimate punctuation exceptions don't apply
518        assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
519    }
520
521    #[test]
522    fn test_question_marks_not_in_default() {
523        let rule = MD026NoTrailingPunctuation::new(None);
524        let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
525        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
526        let result = rule.check(&ctx).unwrap();
527        assert!(result.is_empty(), "Question marks are not in default punctuation list");
528    }
529
530    #[test]
531    fn test_colons_in_default() {
532        let rule = MD026NoTrailingPunctuation::new(None);
533        let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
534        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
535        let result = rule.check(&ctx).unwrap();
536        assert_eq!(
537            result.len(),
538            4,
539            "Colons are in default punctuation list and should be flagged"
540        );
541    }
542
543    #[test]
544    fn test_fix_atx_headings() {
545        let rule = MD026NoTrailingPunctuation::new(None);
546        let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
547        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
548        let fixed = rule.fix(&ctx).unwrap();
549        assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
550    }
551
552    #[test]
553    fn test_fix_setext_headings() {
554        let rule = MD026NoTrailingPunctuation::new(None);
555        let content = "Title.\n======\n\nSubtitle,\n---------";
556        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
557        let fixed = rule.fix(&ctx).unwrap();
558        assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
559    }
560
561    #[test]
562    fn test_fix_preserves_trailing_hashes() {
563        let rule = MD026NoTrailingPunctuation::new(None);
564        let content = "# Title. #\n## Subtitle, ##";
565        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
566        let fixed = rule.fix(&ctx).unwrap();
567        assert_eq!(fixed, "# Title #\n## Subtitle ##");
568    }
569
570    #[test]
571    fn test_indented_headings() {
572        let rule = MD026NoTrailingPunctuation::new(None);
573        let content = "   # Title.\n  ## Subtitle.";
574        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
575        let result = rule.check(&ctx).unwrap();
576        assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
577    }
578
579    #[test]
580    fn test_deeply_indented_ignored() {
581        let rule = MD026NoTrailingPunctuation::new(None);
582        let content = "    # This is code.";
583        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
584        let result = rule.check(&ctx).unwrap();
585        assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
586    }
587
588    #[test]
589    fn test_multiple_punctuation() {
590        let rule = MD026NoTrailingPunctuation::new(None);
591        let content = "# Title...";
592        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
593        let result = rule.check(&ctx).unwrap();
594        assert_eq!(result.len(), 1);
595        assert_eq!(result[0].column, 8); // Points to first period
596    }
597
598    #[test]
599    fn test_empty_content() {
600        let rule = MD026NoTrailingPunctuation::new(None);
601        let content = "";
602        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
603        let result = rule.check(&ctx).unwrap();
604        assert!(result.is_empty());
605    }
606
607    #[test]
608    fn test_no_headings() {
609        let rule = MD026NoTrailingPunctuation::new(None);
610        let content = "This is just text.\nMore text with punctuation.";
611        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
612        let result = rule.check(&ctx).unwrap();
613        assert!(result.is_empty(), "Non-heading lines should not be checked");
614    }
615
616    #[test]
617    fn test_get_punctuation_regex() {
618        let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
619        let regex = rule.get_punctuation_regex(&rule.config.punctuation).unwrap();
620        assert!(regex.is_match("text!"));
621        assert!(regex.is_match("text?"));
622        assert!(!regex.is_match("text."));
623    }
624
625    #[test]
626    fn test_regex_caching() {
627        let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
628        let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
629
630        // Both should get the same cached regex
631        let _regex1 = rule1.get_punctuation_regex(&rule1.config.punctuation).unwrap();
632        let _regex2 = rule2.get_punctuation_regex(&rule2.config.punctuation).unwrap();
633
634        // Check cache has the entry
635        let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
636        assert!(cache.contains_key("!"));
637    }
638
639    #[test]
640    fn test_config_from_toml() {
641        let mut config = crate::config::Config::default();
642        let mut rule_config = crate::config::RuleConfig::default();
643        rule_config
644            .values
645            .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
646        config.rules.insert("MD026".to_string(), rule_config);
647
648        let rule = MD026NoTrailingPunctuation::from_config(&config);
649        let content = "# Title!\n# Another?";
650        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
651        let result = rule.check(&ctx).unwrap();
652        assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
653    }
654
655    #[test]
656    fn test_fix_removes_punctuation() {
657        let rule = MD026NoTrailingPunctuation::new(None);
658        let content = "# Title.   \n## Subtitle,  ";
659        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
660        let fixed = rule.fix(&ctx).unwrap();
661        // The current implementation doesn't preserve trailing whitespace after punctuation removal
662        assert_eq!(fixed, "# Title\n## Subtitle");
663    }
664
665    #[test]
666    fn test_final_newline_preservation() {
667        let rule = MD026NoTrailingPunctuation::new(None);
668        let content = "# Title.\n";
669        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
670        let fixed = rule.fix(&ctx).unwrap();
671        assert_eq!(fixed, "# Title\n");
672
673        let content_no_newline = "# Title.";
674        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
675        let fixed2 = rule.fix(&ctx2).unwrap();
676        assert_eq!(fixed2, "# Title");
677    }
678
679    /// The whole MDG matrix in one place, against the Standard behavior it departs from.
680    ///
681    /// The rule's pattern is `([<punctuation>]+)$`, so taking the colon out of the set is
682    /// the entire flavor difference: no heading whose last character is a colon can match
683    /// any more, and `## Scenario!:` is left exactly as its author wrote it.
684    #[test]
685    fn test_mdg_punctuation_matrix() {
686        let rule = MD026NoTrailingPunctuation::new(None);
687        // (input, standard warnings, standard fix, MDG warnings, MDG fix)
688        let cases = [
689            ("## Notes:\n", 1, "## Notes\n", 0, "## Notes:\n"),
690            ("## Scenario!:\n", 1, "## Scenario\n", 0, "## Scenario!:\n"),
691            ("# Scenario! :\n", 1, "# Scenario\n", 0, "# Scenario! :\n"),
692            ("## Scenario!\n", 1, "## Scenario\n", 1, "## Scenario\n"),
693            ("## Notes::\n", 1, "## Notes\n", 0, "## Notes::\n"),
694            (
695                "# Feature: Checkout:\n",
696                1,
697                "# Feature: Checkout\n",
698                0,
699                "# Feature: Checkout:\n",
700            ),
701            ("### Rule.:\n", 1, "### Rule\n", 0, "### Rule.:\n"),
702        ];
703
704        for (input, standard_count, standard_fixed, mdg_count, mdg_fixed) in cases {
705            for (flavor, count, expected) in [
706                (crate::config::MarkdownFlavor::Standard, standard_count, standard_fixed),
707                (crate::config::MarkdownFlavor::MDG, mdg_count, mdg_fixed),
708            ] {
709                let ctx = LintContext::new(input, flavor, None);
710                assert_eq!(
711                    rule.check(&ctx).unwrap().len(),
712                    count,
713                    "{flavor:?} warning count for {input:?}"
714                );
715
716                let fixed = rule.fix(&ctx).unwrap();
717                assert_eq!(fixed, expected, "{flavor:?} fix for {input:?}");
718
719                let fixed_ctx = LintContext::new(&fixed, flavor, None);
720                assert!(
721                    rule.check(&fixed_ctx).unwrap().is_empty(),
722                    "{flavor:?} left a warning on the fixed {input:?}"
723                );
724                assert_eq!(
725                    rule.fix(&fixed_ctx).unwrap(),
726                    fixed,
727                    "{flavor:?} fix for {input:?} should be idempotent"
728                );
729            }
730        }
731    }
732
733    /// The colon leaves the effective set whatever `punctuation` says, so a future change
734    /// to the default cannot put it back; only an explicit setting is worth reporting.
735    #[test]
736    fn test_mdg_reports_an_explicitly_configured_colon_once() {
737        fn configured(punctuation: &str) -> MD026NoTrailingPunctuation {
738            let mut config = crate::config::Config::default();
739            let mut rule_config = crate::config::RuleConfig::default();
740            rule_config
741                .values
742                .insert("punctuation".to_string(), toml::Value::String(punctuation.to_string()));
743            config.rules.insert("MD026".to_string(), rule_config);
744
745            MD026NoTrailingPunctuation::from_config(&config)
746                .as_any()
747                .downcast_ref::<MD026NoTrailingPunctuation>()
748                .expect("MD026::from_config builds an MD026NoTrailingPunctuation")
749                .clone()
750        }
751
752        let explicit = configured(".,;:!");
753        assert_eq!(
754            explicit.effective_punctuation(crate::config::MarkdownFlavor::Standard),
755            ".,;:!"
756        );
757        assert_eq!(
758            explicit.effective_punctuation(crate::config::MarkdownFlavor::MDG),
759            ".,;!"
760        );
761        assert!(
762            !explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::Standard),
763            "a non-Gherkin file never reports the override"
764        );
765        assert!(explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG));
766
767        let emitted_by_check = configured(".,;:!");
768        let ctx = LintContext::new("## Scenario!\n", crate::config::MarkdownFlavor::MDG, None);
769        assert_eq!(emitted_by_check.check(&ctx).unwrap().len(), 1);
770
771        let emitted_before_skip = configured(".,;:!");
772        let only_protected_punctuation = LintContext::new("#### Examples:\n", crate::config::MarkdownFlavor::MDG, None);
773        assert!(
774            emitted_before_skip.should_skip(&only_protected_punctuation),
775            "the post-override punctuation set has nothing to inspect"
776        );
777
778        let explicit_without_colon = configured(".,;!");
779        assert!(
780            !explicit_without_colon.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
781            "nothing is overridden when the configured set has no colon"
782        );
783
784        let default = MD026NoTrailingPunctuation::new(None);
785        assert_eq!(
786            default.effective_punctuation(crate::config::MarkdownFlavor::MDG),
787            ".,;!",
788            "the colon leaves the default set too"
789        );
790        assert!(
791            !default.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
792            "the default set is not an explicit configuration, so it is silent"
793        );
794    }
795
796    #[test]
797    fn test_mdg_exempts_a_lone_colon_behind_whitespace() {
798        // The colon is not punctuation under MDG, and it is the last character here, so
799        // there is nothing for the `$`-anchored pattern to match. Standard still strips it,
800        // keeping the whitespace that preceded it.
801        let rule = MD026NoTrailingPunctuation::new(None);
802        let content = "# Scenario :\n## Notes:\n";
803
804        let standard_ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
805        let standard = rule.check(&standard_ctx).unwrap();
806        assert_eq!(standard.len(), 2);
807        assert_eq!((standard[0].line, standard[0].column), (1, 12));
808        assert_eq!((standard[1].line, standard[1].column), (2, 9));
809        let standard_fixed = rule.fix(&standard_ctx).unwrap();
810        assert_eq!(standard_fixed, "# Scenario \n## Notes\n");
811        let standard_fixed_ctx = LintContext::new(&standard_fixed, crate::config::MarkdownFlavor::Standard, None);
812        assert_eq!(
813            rule.fix(&standard_fixed_ctx).unwrap(),
814            standard_fixed,
815            "Standard fix should be idempotent"
816        );
817
818        let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
819        assert!(rule.check(&mdg_ctx).unwrap().is_empty());
820        assert_eq!(
821            rule.fix(&mdg_ctx).unwrap(),
822            content,
823            "MDG leaves headings whose only trailing punctuation is the colon untouched"
824        );
825    }
826
827    #[test]
828    fn test_mdg_does_not_exempt_a_full_width_colon() {
829        // Gherkin only recognizes the ASCII colon, so a full-width one carries
830        // no structural meaning and stays in the punctuation set.
831        let rule = MD026NoTrailingPunctuation::new(Some(".,;:!?:".to_string()));
832        assert_eq!(
833            rule.effective_punctuation(crate::config::MarkdownFlavor::MDG),
834            ".,;!?:",
835            "only the ASCII colon leaves the set"
836        );
837
838        let content = "## Scenario:\n";
839        for flavor in [
840            crate::config::MarkdownFlavor::MDG,
841            crate::config::MarkdownFlavor::Standard,
842        ] {
843            let ctx = LintContext::new(content, flavor, None);
844            assert_eq!(rule.check(&ctx).unwrap().len(), 1, "{flavor:?} must flag the `:`");
845            assert_eq!(rule.fix(&ctx).unwrap(), "## Scenario\n");
846        }
847    }
848}