rumdl_lib/rules/
md012_no_multiple_blanks.rs

1use crate::filtered_lines::FilteredLinesExt;
2use crate::utils::LineIndex;
3use crate::utils::range_utils::calculate_line_range;
4use std::collections::HashSet;
5use toml;
6
7use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, Severity};
8use crate::rule_config_serde::RuleConfig;
9
10mod md012_config;
11use md012_config::MD012Config;
12
13/// Rule MD012: No multiple consecutive blank lines
14///
15/// See [docs/md012.md](../../docs/md012.md) for full documentation, configuration, and examples.
16
17#[derive(Debug, Clone, Default)]
18pub struct MD012NoMultipleBlanks {
19    config: MD012Config,
20}
21
22impl MD012NoMultipleBlanks {
23    pub fn new(maximum: usize) -> Self {
24        use crate::types::PositiveUsize;
25        Self {
26            config: MD012Config {
27                maximum: PositiveUsize::new(maximum).unwrap_or(PositiveUsize::from_const(1)),
28            },
29        }
30    }
31
32    pub const fn from_config_struct(config: MD012Config) -> Self {
33        Self { config }
34    }
35
36    /// Generate warnings for excess blank lines, handling common logic for all contexts
37    fn generate_excess_warnings(
38        &self,
39        blank_start: usize,
40        blank_count: usize,
41        lines: &[&str],
42        lines_to_check: &HashSet<usize>,
43        line_index: &LineIndex,
44    ) -> Vec<LintWarning> {
45        let mut warnings = Vec::new();
46
47        let location = if blank_start == 0 {
48            "at start of file"
49        } else {
50            "between content"
51        };
52
53        for i in self.config.maximum.get()..blank_count {
54            let excess_line_num = blank_start + i;
55            if lines_to_check.contains(&excess_line_num) {
56                let excess_line = excess_line_num + 1;
57                let excess_line_content = lines.get(excess_line_num).unwrap_or(&"");
58                let (start_line, start_col, end_line, end_col) = calculate_line_range(excess_line, excess_line_content);
59                warnings.push(LintWarning {
60                    rule_name: Some(self.name().to_string()),
61                    severity: Severity::Warning,
62                    message: format!("Multiple consecutive blank lines {location}"),
63                    line: start_line,
64                    column: start_col,
65                    end_line,
66                    end_column: end_col,
67                    fix: Some(Fix {
68                        range: {
69                            let line_start = line_index.get_line_start_byte(excess_line).unwrap_or(0);
70                            let line_end = line_index
71                                .get_line_start_byte(excess_line + 1)
72                                .unwrap_or(line_start + 1);
73                            line_start..line_end
74                        },
75                        replacement: String::new(),
76                    }),
77                });
78            }
79        }
80
81        warnings
82    }
83}
84
85impl Rule for MD012NoMultipleBlanks {
86    fn name(&self) -> &'static str {
87        "MD012"
88    }
89
90    fn description(&self) -> &'static str {
91        "Multiple consecutive blank lines"
92    }
93
94    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
95        let content = ctx.content;
96
97        // Early return for empty content
98        if content.is_empty() {
99            return Ok(Vec::new());
100        }
101
102        // Quick check for consecutive newlines or potential whitespace-only lines before processing
103        // Look for multiple consecutive lines that could be blank (empty or whitespace-only)
104        let lines: Vec<&str> = content.lines().collect();
105        let has_potential_blanks = lines
106            .windows(2)
107            .any(|pair| pair[0].trim().is_empty() && pair[1].trim().is_empty());
108
109        // Also check for blanks at EOF (markdownlint behavior)
110        // Content is normalized to LF at I/O boundary
111        let ends_with_multiple_newlines = content.ends_with("\n\n");
112
113        if !has_potential_blanks && !ends_with_multiple_newlines {
114            return Ok(Vec::new());
115        }
116
117        let line_index = &ctx.line_index;
118
119        let mut warnings = Vec::new();
120
121        // Single-pass algorithm with immediate counter reset
122        let mut blank_count = 0;
123        let mut blank_start = 0;
124        let mut last_line_num: Option<usize> = None;
125
126        // Use HashSet for O(1) lookups of lines that need to be checked
127        let mut lines_to_check: HashSet<usize> = HashSet::new();
128
129        // Use filtered_lines to automatically skip front-matter and code blocks
130        // The in_code_block field in LineInfo is pre-computed using pulldown-cmark
131        // and correctly handles both fenced code blocks and indented code blocks
132        for filtered_line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
133            let line_num = filtered_line.line_num - 1; // Convert 1-based to 0-based for internal tracking
134            let line = filtered_line.content;
135
136            // Detect when lines were skipped (e.g., code block content)
137            // If we jump more than 1 line, there was content between, which breaks blank sequences
138            if let Some(last) = last_line_num
139                && line_num > last + 1
140            {
141                // Lines were skipped (code block or similar)
142                // Generate warnings for any accumulated blanks before the skip
143                if blank_count > self.config.maximum.get() {
144                    warnings.extend(self.generate_excess_warnings(
145                        blank_start,
146                        blank_count,
147                        &lines,
148                        &lines_to_check,
149                        line_index,
150                    ));
151                }
152                blank_count = 0;
153                lines_to_check.clear();
154            }
155            last_line_num = Some(line_num);
156
157            if line.trim().is_empty() {
158                if blank_count == 0 {
159                    blank_start = line_num;
160                }
161                blank_count += 1;
162                // Store line numbers that exceed the limit
163                if blank_count > self.config.maximum.get() {
164                    lines_to_check.insert(line_num);
165                }
166            } else {
167                if blank_count > self.config.maximum.get() {
168                    warnings.extend(self.generate_excess_warnings(
169                        blank_start,
170                        blank_count,
171                        &lines,
172                        &lines_to_check,
173                        line_index,
174                    ));
175                }
176                blank_count = 0;
177                lines_to_check.clear();
178            }
179        }
180
181        // Handle trailing blanks at EOF
182        // Main loop only reports mid-document blanks (between content)
183        // EOF handler reports trailing blanks with stricter rules (any blank at EOF is flagged)
184        //
185        // The blank_count at end of loop might include blanks BEFORE a code block at EOF,
186        // which aren't truly "trailing blanks". We need to verify the actual last line is blank.
187        let last_line_is_blank = lines.last().is_some_and(|l| l.trim().is_empty());
188
189        // Check for trailing blank lines
190        // EOF semantics: ANY blank line at EOF should be flagged (stricter than mid-document)
191        // Only fire if the actual last line(s) of the file are blank
192        if blank_count > 0 && last_line_is_blank {
193            let location = "at end of file";
194
195            // Report on the last line (which is blank)
196            let report_line = lines.len();
197
198            // Calculate fix: remove all trailing blank lines
199            // Find where the trailing blanks start (blank_count tells us how many consecutive blanks)
200            let fix_start = line_index
201                .get_line_start_byte(report_line - blank_count + 1)
202                .unwrap_or(0);
203            let fix_end = content.len();
204
205            // Report one warning for the excess blank lines at EOF
206            warnings.push(LintWarning {
207                rule_name: Some(self.name().to_string()),
208                severity: Severity::Warning,
209                message: format!("Multiple consecutive blank lines {location}"),
210                line: report_line,
211                column: 1,
212                end_line: report_line,
213                end_column: 1,
214                fix: Some(Fix {
215                    range: fix_start..fix_end,
216                    // The fix_start already points to the first blank line, which is AFTER
217                    // the last content line's newline. So we just remove everything from
218                    // fix_start to end, and the last content line's newline is preserved.
219                    replacement: String::new(),
220                }),
221            });
222        }
223
224        Ok(warnings)
225    }
226
227    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
228        let content = ctx.content;
229
230        let mut result = Vec::new();
231        let mut blank_count = 0;
232
233        let mut in_code_block = false;
234        let mut code_block_blanks = Vec::new();
235        let mut in_front_matter = false;
236
237        // Process ALL lines (don't skip front-matter in fix mode)
238        for filtered_line in ctx.filtered_lines() {
239            let line = filtered_line.content;
240
241            // Pass through front-matter lines unchanged
242            if filtered_line.line_info.in_front_matter {
243                if !in_front_matter {
244                    // Entering front-matter: flush any accumulated blanks
245                    let allowed_blanks = blank_count.min(self.config.maximum.get());
246                    if allowed_blanks > 0 {
247                        result.extend(vec![""; allowed_blanks]);
248                    }
249                    blank_count = 0;
250                    in_front_matter = true;
251                }
252                result.push(line);
253                continue;
254            } else if in_front_matter {
255                // Exiting front-matter
256                in_front_matter = false;
257            }
258
259            // Track code blocks
260            if line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~") {
261                // Handle accumulated blank lines before code block
262                if !in_code_block {
263                    let allowed_blanks = blank_count.min(self.config.maximum.get());
264                    if allowed_blanks > 0 {
265                        result.extend(vec![""; allowed_blanks]);
266                    }
267                    blank_count = 0;
268                } else {
269                    // Add accumulated blank lines inside code block
270                    result.append(&mut code_block_blanks);
271                }
272                in_code_block = !in_code_block;
273                result.push(line);
274                continue;
275            }
276
277            if in_code_block {
278                if line.trim().is_empty() {
279                    code_block_blanks.push(line);
280                } else {
281                    result.append(&mut code_block_blanks);
282                    result.push(line);
283                }
284            } else if line.trim().is_empty() {
285                blank_count += 1;
286            } else {
287                // Add allowed blank lines before content
288                let allowed_blanks = blank_count.min(self.config.maximum.get());
289                if allowed_blanks > 0 {
290                    result.extend(vec![""; allowed_blanks]);
291                }
292                blank_count = 0;
293                result.push(line);
294            }
295        }
296
297        // Trailing blank lines at EOF are removed entirely (matching markdownlint-cli)
298
299        // Join lines and handle final newline
300        let mut output = result.join("\n");
301        if content.ends_with('\n') {
302            output.push('\n');
303        }
304
305        Ok(output)
306    }
307
308    fn as_any(&self) -> &dyn std::any::Any {
309        self
310    }
311
312    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
313        // Skip if content is empty or doesn't have newlines (single line can't have multiple blanks)
314        ctx.content.is_empty() || !ctx.has_char('\n')
315    }
316
317    fn default_config_section(&self) -> Option<(String, toml::Value)> {
318        let default_config = MD012Config::default();
319        let json_value = serde_json::to_value(&default_config).ok()?;
320        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
321
322        if let toml::Value::Table(table) = toml_value {
323            if !table.is_empty() {
324                Some((MD012Config::RULE_NAME.to_string(), toml::Value::Table(table)))
325            } else {
326                None
327            }
328        } else {
329            None
330        }
331    }
332
333    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
334    where
335        Self: Sized,
336    {
337        let rule_config = crate::rule_config_serde::load_rule_config::<MD012Config>(config);
338        Box::new(Self::from_config_struct(rule_config))
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use crate::lint_context::LintContext;
346
347    #[test]
348    fn test_single_blank_line_allowed() {
349        let rule = MD012NoMultipleBlanks::default();
350        let content = "Line 1\n\nLine 2\n\nLine 3";
351        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
352        let result = rule.check(&ctx).unwrap();
353        assert!(result.is_empty());
354    }
355
356    #[test]
357    fn test_multiple_blank_lines_flagged() {
358        let rule = MD012NoMultipleBlanks::default();
359        let content = "Line 1\n\n\nLine 2\n\n\n\nLine 3";
360        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
361        let result = rule.check(&ctx).unwrap();
362        assert_eq!(result.len(), 3); // 1 extra in first gap, 2 extra in second gap
363        assert_eq!(result[0].line, 3);
364        assert_eq!(result[1].line, 6);
365        assert_eq!(result[2].line, 7);
366    }
367
368    #[test]
369    fn test_custom_maximum() {
370        let rule = MD012NoMultipleBlanks::new(2);
371        let content = "Line 1\n\n\nLine 2\n\n\n\nLine 3";
372        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
373        let result = rule.check(&ctx).unwrap();
374        assert_eq!(result.len(), 1); // Only the fourth blank line is excessive
375        assert_eq!(result[0].line, 7);
376    }
377
378    #[test]
379    fn test_fix_multiple_blank_lines() {
380        let rule = MD012NoMultipleBlanks::default();
381        let content = "Line 1\n\n\nLine 2\n\n\n\nLine 3";
382        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
383        let fixed = rule.fix(&ctx).unwrap();
384        assert_eq!(fixed, "Line 1\n\nLine 2\n\nLine 3");
385    }
386
387    #[test]
388    fn test_blank_lines_in_code_block() {
389        let rule = MD012NoMultipleBlanks::default();
390        let content = "Before\n\n```\ncode\n\n\n\nmore code\n```\n\nAfter";
391        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
392        let result = rule.check(&ctx).unwrap();
393        assert!(result.is_empty()); // Blank lines inside code blocks are ignored
394    }
395
396    #[test]
397    fn test_fix_preserves_code_block_blanks() {
398        let rule = MD012NoMultipleBlanks::default();
399        let content = "Before\n\n\n```\ncode\n\n\n\nmore code\n```\n\n\nAfter";
400        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
401        let fixed = rule.fix(&ctx).unwrap();
402        assert_eq!(fixed, "Before\n\n```\ncode\n\n\n\nmore code\n```\n\nAfter");
403    }
404
405    #[test]
406    fn test_blank_lines_in_front_matter() {
407        let rule = MD012NoMultipleBlanks::default();
408        let content = "---\ntitle: Test\n\n\nauthor: Me\n---\n\nContent";
409        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
410        let result = rule.check(&ctx).unwrap();
411        assert!(result.is_empty()); // Blank lines in front matter are ignored
412    }
413
414    #[test]
415    fn test_blank_lines_at_start() {
416        let rule = MD012NoMultipleBlanks::default();
417        let content = "\n\n\nContent";
418        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
419        let result = rule.check(&ctx).unwrap();
420        assert_eq!(result.len(), 2);
421        assert!(result[0].message.contains("at start of file"));
422    }
423
424    #[test]
425    fn test_blank_lines_at_end() {
426        let rule = MD012NoMultipleBlanks::default();
427        let content = "Content\n\n\n";
428        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
429        let result = rule.check(&ctx).unwrap();
430        assert_eq!(result.len(), 1);
431        assert!(result[0].message.contains("at end of file"));
432    }
433
434    #[test]
435    fn test_single_blank_at_eof_flagged() {
436        // Markdownlint behavior: ANY blank lines at EOF are flagged
437        let rule = MD012NoMultipleBlanks::default();
438        let content = "Content\n\n";
439        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
440        let result = rule.check(&ctx).unwrap();
441        assert_eq!(result.len(), 1);
442        assert!(result[0].message.contains("at end of file"));
443    }
444
445    #[test]
446    fn test_whitespace_only_lines() {
447        let rule = MD012NoMultipleBlanks::default();
448        let content = "Line 1\n  \n\t\nLine 2";
449        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
450        let result = rule.check(&ctx).unwrap();
451        assert_eq!(result.len(), 1); // Whitespace-only lines count as blank
452    }
453
454    #[test]
455    fn test_indented_code_blocks() {
456        // Per markdownlint-cli reference: blank lines inside indented code blocks are valid
457        let rule = MD012NoMultipleBlanks::default();
458        let content = "Text\n\n    code\n    \n    \n    more code\n\nText";
459        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
460        let result = rule.check(&ctx).unwrap();
461        assert!(result.is_empty(), "Should not flag blanks inside indented code blocks");
462    }
463
464    #[test]
465    fn test_blanks_in_indented_code_block() {
466        // Per markdownlint-cli reference: blank lines inside indented code blocks are valid
467        let content = "    code line 1\n\n\n    code line 2\n";
468        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
469        let rule = MD012NoMultipleBlanks::default();
470        let warnings = rule.check(&ctx).unwrap();
471        assert!(warnings.is_empty(), "Should not flag blanks in indented code");
472    }
473
474    #[test]
475    fn test_blanks_in_indented_code_block_with_heading() {
476        // Per markdownlint-cli reference: blank lines inside indented code blocks are valid
477        let content = "# Heading\n\n    code line 1\n\n\n    code line 2\n\nMore text\n";
478        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
479        let rule = MD012NoMultipleBlanks::default();
480        let warnings = rule.check(&ctx).unwrap();
481        assert!(
482            warnings.is_empty(),
483            "Should not flag blanks in indented code after heading"
484        );
485    }
486
487    #[test]
488    fn test_blanks_after_indented_code_block_flagged() {
489        // Blanks AFTER an indented code block end should still be flagged
490        let content = "# Heading\n\n    code line\n\n\n\nMore text\n";
491        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
492        let rule = MD012NoMultipleBlanks::default();
493        let warnings = rule.check(&ctx).unwrap();
494        // There are 3 blank lines after the code block, so 2 extra should be flagged
495        assert_eq!(warnings.len(), 2, "Should flag blanks after indented code block ends");
496    }
497
498    #[test]
499    fn test_fix_with_final_newline() {
500        let rule = MD012NoMultipleBlanks::default();
501        let content = "Line 1\n\n\nLine 2\n";
502        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
503        let fixed = rule.fix(&ctx).unwrap();
504        assert_eq!(fixed, "Line 1\n\nLine 2\n");
505        assert!(fixed.ends_with('\n'));
506    }
507
508    #[test]
509    fn test_empty_content() {
510        let rule = MD012NoMultipleBlanks::default();
511        let content = "";
512        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
513        let result = rule.check(&ctx).unwrap();
514        assert!(result.is_empty());
515    }
516
517    #[test]
518    fn test_nested_code_blocks() {
519        let rule = MD012NoMultipleBlanks::default();
520        let content = "Before\n\n~~~\nouter\n\n```\ninner\n\n\n```\n\n~~~\n\nAfter";
521        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
522        let result = rule.check(&ctx).unwrap();
523        assert!(result.is_empty());
524    }
525
526    #[test]
527    fn test_unclosed_code_block() {
528        let rule = MD012NoMultipleBlanks::default();
529        let content = "Before\n\n```\ncode\n\n\n\nno closing fence";
530        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
531        let result = rule.check(&ctx).unwrap();
532        assert!(result.is_empty()); // Unclosed code blocks still preserve blank lines
533    }
534
535    #[test]
536    fn test_mixed_fence_styles() {
537        let rule = MD012NoMultipleBlanks::default();
538        let content = "Before\n\n```\ncode\n\n\n~~~\n\nAfter";
539        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
540        let result = rule.check(&ctx).unwrap();
541        assert!(result.is_empty()); // Mixed fence styles should work
542    }
543
544    #[test]
545    fn test_config_from_toml() {
546        let mut config = crate::config::Config::default();
547        let mut rule_config = crate::config::RuleConfig::default();
548        rule_config
549            .values
550            .insert("maximum".to_string(), toml::Value::Integer(3));
551        config.rules.insert("MD012".to_string(), rule_config);
552
553        let rule = MD012NoMultipleBlanks::from_config(&config);
554        let content = "Line 1\n\n\n\nLine 2"; // 3 blank lines
555        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
556        let result = rule.check(&ctx).unwrap();
557        assert!(result.is_empty()); // 3 blank lines allowed with maximum=3
558    }
559
560    #[test]
561    fn test_blank_lines_between_sections() {
562        let rule = MD012NoMultipleBlanks::default();
563        let content = "# Section 1\n\nContent\n\n\n# Section 2\n\nContent";
564        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
565        let result = rule.check(&ctx).unwrap();
566        assert_eq!(result.len(), 1);
567        assert_eq!(result[0].line, 5);
568    }
569
570    #[test]
571    fn test_fix_preserves_indented_code() {
572        let rule = MD012NoMultipleBlanks::default();
573        let content = "Text\n\n\n    code\n    \n    more code\n\n\nText";
574        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
575        let fixed = rule.fix(&ctx).unwrap();
576        // The fix removes the extra blank line, but this is expected behavior
577        assert_eq!(fixed, "Text\n\n    code\n\n    more code\n\nText");
578    }
579
580    #[test]
581    fn test_edge_case_only_blanks() {
582        let rule = MD012NoMultipleBlanks::default();
583        let content = "\n\n\n";
584        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
585        let result = rule.check(&ctx).unwrap();
586        // With the new EOF handling, we report once at EOF
587        assert_eq!(result.len(), 1);
588        assert!(result[0].message.contains("at end of file"));
589    }
590
591    // Regression tests for blanks after code blocks (GitHub issue #199 related)
592
593    #[test]
594    fn test_blanks_after_fenced_code_block_mid_document() {
595        // This is the pattern from React repo test files that was being missed
596        let rule = MD012NoMultipleBlanks::default();
597        let content = "## Input\n\n```javascript\ncode\n```\n\n\n## Error\n";
598        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
599        let result = rule.check(&ctx).unwrap();
600        // Should flag the double blank between code block and next heading
601        assert_eq!(result.len(), 1, "Should detect blanks after code block");
602        assert_eq!(result[0].line, 7, "Warning should be on line 7 (second blank)");
603        assert!(result[0].message.contains("between content"));
604    }
605
606    #[test]
607    fn test_blanks_after_code_block_at_eof() {
608        // Trailing blanks after code block at end of file
609        let rule = MD012NoMultipleBlanks::default();
610        let content = "# Heading\n\n```\ncode\n```\n\n\n";
611        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
612        let result = rule.check(&ctx).unwrap();
613        // Should flag the trailing blanks at EOF
614        assert_eq!(result.len(), 1, "Should detect trailing blanks after code block");
615        assert!(result[0].message.contains("at end of file"));
616    }
617
618    #[test]
619    fn test_single_blank_after_code_block_allowed() {
620        // Single blank after code block is allowed (default max=1)
621        let rule = MD012NoMultipleBlanks::default();
622        let content = "## Input\n\n```\ncode\n```\n\n## Output\n";
623        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
624        let result = rule.check(&ctx).unwrap();
625        assert!(result.is_empty(), "Single blank after code block should be allowed");
626    }
627
628    #[test]
629    fn test_multiple_code_blocks_with_blanks() {
630        // Multiple code blocks, each followed by blanks
631        let rule = MD012NoMultipleBlanks::default();
632        let content = "```\ncode1\n```\n\n\n```\ncode2\n```\n\n\nEnd\n";
633        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
634        let result = rule.check(&ctx).unwrap();
635        // Should flag both double-blank sequences
636        assert_eq!(result.len(), 2, "Should detect blanks after both code blocks");
637    }
638
639    #[test]
640    fn test_whitespace_only_lines_after_code_block_at_eof() {
641        // Whitespace-only lines (not just empty) after code block at EOF
642        // This matches the React repo pattern where lines have trailing spaces
643        let rule = MD012NoMultipleBlanks::default();
644        let content = "```\ncode\n```\n   \n   \n";
645        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
646        let result = rule.check(&ctx).unwrap();
647        assert_eq!(result.len(), 1, "Should detect whitespace-only trailing blanks");
648        assert!(result[0].message.contains("at end of file"));
649    }
650
651    // Tests for warning-based fix (used by LSP formatting)
652
653    #[test]
654    fn test_warning_fix_removes_single_trailing_blank() {
655        // Regression test for issue #265: LSP formatting should work for EOF blanks
656        let rule = MD012NoMultipleBlanks::default();
657        let content = "hello foobar hello.\n\n";
658        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
659        let warnings = rule.check(&ctx).unwrap();
660
661        assert_eq!(warnings.len(), 1);
662        assert!(warnings[0].fix.is_some(), "Warning should have a fix attached");
663
664        let fix = warnings[0].fix.as_ref().unwrap();
665        // The fix should remove the trailing blank line
666        assert_eq!(fix.replacement, "", "Replacement should be empty");
667
668        // Apply the fix and verify result
669        let fixed = crate::utils::fix_utils::apply_warning_fixes(content, &warnings).unwrap();
670        assert_eq!(fixed, "hello foobar hello.\n", "Should end with single newline");
671    }
672
673    #[test]
674    fn test_warning_fix_removes_multiple_trailing_blanks() {
675        let rule = MD012NoMultipleBlanks::default();
676        let content = "content\n\n\n\n";
677        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
678        let warnings = rule.check(&ctx).unwrap();
679
680        assert_eq!(warnings.len(), 1);
681        assert!(warnings[0].fix.is_some());
682
683        let fixed = crate::utils::fix_utils::apply_warning_fixes(content, &warnings).unwrap();
684        assert_eq!(fixed, "content\n", "Should end with single newline");
685    }
686
687    #[test]
688    fn test_warning_fix_preserves_content_newline() {
689        // Ensure the fix doesn't remove the content line's trailing newline
690        let rule = MD012NoMultipleBlanks::default();
691        let content = "line1\nline2\n\n";
692        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
693        let warnings = rule.check(&ctx).unwrap();
694
695        let fixed = crate::utils::fix_utils::apply_warning_fixes(content, &warnings).unwrap();
696        assert_eq!(fixed, "line1\nline2\n", "Should preserve all content lines");
697    }
698
699    #[test]
700    fn test_warning_fix_mid_document_blanks() {
701        // Test that mid-document blank line fixes also work via warnings
702        let rule = MD012NoMultipleBlanks::default();
703        // Content with 2 extra blank lines (3 blank lines total, should reduce to 1)
704        let content = "# Heading\n\n\n\nParagraph\n";
705        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
706        let warnings = rule.check(&ctx).unwrap();
707
708        // With maximum=1 (default), 3 consecutive blanks produces 2 warnings
709        assert_eq!(warnings.len(), 2, "Should have 2 warnings for 2 extra blank lines");
710        assert!(warnings[0].fix.is_some());
711        assert!(warnings[1].fix.is_some());
712
713        let fixed = crate::utils::fix_utils::apply_warning_fixes(content, &warnings).unwrap();
714        assert_eq!(fixed, "# Heading\n\nParagraph\n", "Should reduce to single blank");
715    }
716}