Skip to main content

rumdl_lib/rules/
md028_no_blanks_blockquote.rs

1/// Rule MD028: No blank lines inside blockquotes
2///
3/// This rule flags blank lines that appear to be inside a blockquote but lack the > marker.
4/// It uses heuristics to distinguish between paragraph breaks within a blockquote
5/// and intentional separators between distinct blockquotes.
6///
7/// GFM Alerts (GitHub Flavored Markdown) are automatically detected and excluded:
8/// - `> [!NOTE]`, `> [!TIP]`, `> [!IMPORTANT]`, `> [!WARNING]`, `> [!CAUTION]`
9///   These alerts MUST be separated by blank lines to render correctly on GitHub.
10///
11/// Obsidian Callouts are also supported when using the Obsidian flavor:
12/// - Any `> [!TYPE]` pattern is recognized as a callout
13/// - Foldable syntax is supported: `> [!NOTE]+` (expanded) or `> [!NOTE]-` (collapsed)
14///
15/// See [docs/md028.md](../../docs/md028.md) for full documentation, configuration, and examples.
16use crate::config::MarkdownFlavor;
17use crate::lint_context::LineInfo;
18use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
19use crate::rule_config_serde::{RuleConfig, load_rule_config};
20use crate::utils::range_utils::calculate_line_range;
21use serde::{Deserialize, Serialize};
22
23/// GFM Alert types supported by GitHub
24/// Reference: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
25const GFM_ALERT_TYPES: &[&str] = &["NOTE", "TIP", "IMPORTANT", "WARNING", "CAUTION"];
26
27/// Configuration for MD028 (Blank line inside blockquote)
28#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
29#[serde(rename_all = "kebab-case")]
30pub struct MD028Config {
31    /// Enable auto-fix to merge blockquotes separated by a blank line.
32    /// Defaults to false: filling the blank line with `>` merges two
33    /// blockquotes into one, and the detection cannot verify whether the author
34    /// meant a single quote with an accidental gap or two distinct quotes.
35    /// `check()` still warns either way; users opt into the merge with
36    /// `fix = true`.
37    #[serde(default)]
38    pub fix: bool,
39}
40
41impl RuleConfig for MD028Config {
42    const RULE_NAME: &'static str = "MD028";
43}
44
45#[derive(Clone, Default)]
46pub struct MD028NoBlanksBlockquote {
47    config: MD028Config,
48}
49
50impl MD028NoBlanksBlockquote {
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    pub fn with_config(config: MD028Config) -> Self {
56        Self { config }
57    }
58
59    /// Construct with auto-fix explicitly enabled or disabled.
60    pub fn with_fix(fix: bool) -> Self {
61        Self {
62            config: MD028Config { fix },
63        }
64    }
65
66    /// Check if a line is a blockquote line (has > markers)
67    #[inline]
68    fn is_blockquote_line(line: &str) -> bool {
69        // Fast path: check for '>' character before doing any string operations
70        if !line.as_bytes().contains(&b'>') {
71            return false;
72        }
73        line.trim_start().starts_with('>')
74    }
75
76    /// Get the blockquote level (number of > markers) and leading whitespace
77    /// Returns (level, whitespace_end_idx)
78    fn get_blockquote_info(line: &str) -> (usize, usize) {
79        let bytes = line.as_bytes();
80        let mut i = 0;
81
82        // Skip leading whitespace
83        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
84            i += 1;
85        }
86
87        let whitespace_end = i;
88        let mut level = 0;
89
90        // Count '>' markers
91        while i < bytes.len() {
92            if bytes[i] == b'>' {
93                level += 1;
94                i += 1;
95            } else if bytes[i] == b' ' || bytes[i] == b'\t' {
96                i += 1;
97            } else {
98                break;
99            }
100        }
101
102        (level, whitespace_end)
103    }
104
105    /// Check if a line is in a skip context (HTML comment, code block, HTML block, or frontmatter)
106    #[inline]
107    fn is_in_skip_context(line_infos: &[LineInfo], idx: usize) -> bool {
108        if let Some(li) = line_infos.get(idx) {
109            li.in_html_comment || li.in_mdx_comment || li.in_code_block || li.in_html_block || li.in_front_matter
110        } else {
111            false
112        }
113    }
114
115    /// Check if there's substantive content between two blockquote sections
116    /// This helps distinguish between paragraph breaks and separate blockquotes.
117    /// Lines in skip contexts (HTML comments, code blocks, frontmatter) count as
118    /// separating content because they represent non-blockquote material between quotes.
119    fn has_content_between(lines: &[&str], line_infos: &[LineInfo], start: usize, end: usize) -> bool {
120        for (offset, line) in lines[start..end].iter().enumerate() {
121            let idx = start + offset;
122            // Non-blank lines in skip contexts (HTML comments, code blocks, frontmatter)
123            // are separating content between blockquotes
124            if Self::is_in_skip_context(line_infos, idx) {
125                if !line.trim().is_empty() {
126                    return true;
127                }
128                continue;
129            }
130            let trimmed = line.trim();
131            // If there's any non-blank, non-blockquote content, these are separate quotes
132            if !trimmed.is_empty() && !trimmed.starts_with('>') {
133                return true;
134            }
135        }
136        false
137    }
138
139    /// Check if a blockquote line is a GFM alert start
140    /// GFM alerts have the format: `> [!TYPE]` where TYPE is NOTE, TIP, IMPORTANT, WARNING, or CAUTION
141    /// Reference: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
142    #[inline]
143    fn is_gfm_alert_line(line: &str) -> bool {
144        // Fast path: must contain '[!' pattern
145        if !line.contains("[!") {
146            return false;
147        }
148
149        // Extract content after the > marker(s)
150        let trimmed = line.trim_start();
151        if !trimmed.starts_with('>') {
152            return false;
153        }
154
155        // Skip all > markers and whitespace to get to content
156        let content = trimmed
157            .trim_start_matches('>')
158            .trim_start_matches([' ', '\t'])
159            .trim_start_matches('>')
160            .trim_start();
161
162        // Check for GFM alert pattern: [!TYPE]
163        if !content.starts_with("[!") {
164            return false;
165        }
166
167        // Extract the alert type
168        if let Some(end_bracket) = content.find(']') {
169            let alert_type = &content[2..end_bracket];
170            return GFM_ALERT_TYPES.iter().any(|&t| t.eq_ignore_ascii_case(alert_type));
171        }
172
173        false
174    }
175
176    /// Check if a blockquote line is an Obsidian callout
177    /// Obsidian callouts have the format: `> [!TYPE]` where TYPE can be any string
178    /// Obsidian also supports foldable callouts: `> [!TYPE]+` (expanded) or `> [!TYPE]-` (collapsed)
179    /// Reference: https://help.obsidian.md/callouts
180    #[inline]
181    fn is_obsidian_callout_line(line: &str) -> bool {
182        // Fast path: must contain '[!' pattern
183        if !line.contains("[!") {
184            return false;
185        }
186
187        // Extract content after the > marker(s)
188        let trimmed = line.trim_start();
189        if !trimmed.starts_with('>') {
190            return false;
191        }
192
193        // Skip all > markers and whitespace to get to content
194        let content = trimmed
195            .trim_start_matches('>')
196            .trim_start_matches([' ', '\t'])
197            .trim_start_matches('>')
198            .trim_start();
199
200        // Check for Obsidian callout pattern: [!TYPE] or [!TYPE]+ or [!TYPE]-
201        if !content.starts_with("[!") {
202            return false;
203        }
204
205        // Find the closing bracket - must have at least one char for TYPE
206        if let Some(end_bracket) = content.find(']') {
207            // TYPE must be at least one character
208            if end_bracket > 2 {
209                // Verify the type contains only valid characters (alphanumeric, hyphen, underscore)
210                let alert_type = &content[2..end_bracket];
211                return !alert_type.is_empty()
212                    && alert_type.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_');
213            }
214        }
215
216        false
217    }
218
219    /// Check if a line is a callout/alert based on the flavor
220    /// For Obsidian flavor: accepts any [!TYPE] pattern
221    /// For other flavors: only accepts GFM alert types
222    #[inline]
223    fn is_callout_line(line: &str, flavor: MarkdownFlavor) -> bool {
224        match flavor {
225            MarkdownFlavor::Obsidian => Self::is_obsidian_callout_line(line),
226            _ => Self::is_gfm_alert_line(line),
227        }
228    }
229
230    /// Find the first line of a blockquote block starting from a given line
231    /// Scans backwards to find where this blockquote block begins
232    fn find_blockquote_start(lines: &[&str], line_infos: &[LineInfo], from_idx: usize) -> Option<usize> {
233        if from_idx >= lines.len() {
234            return None;
235        }
236
237        // Start from the given line and scan backwards
238        let mut start_idx = from_idx;
239
240        for i in (0..=from_idx).rev() {
241            // Skip lines in skip contexts
242            if Self::is_in_skip_context(line_infos, i) {
243                continue;
244            }
245
246            let line = lines[i];
247
248            // If it's a blockquote line, update start
249            if Self::is_blockquote_line(line) {
250                start_idx = i;
251            } else if line.trim().is_empty() {
252                // Blank line - check if previous content was blockquote
253                // If we haven't found any blockquote yet, continue
254                if start_idx == from_idx && !Self::is_blockquote_line(lines[from_idx]) {
255                    continue;
256                }
257                // Otherwise, blank line ends this blockquote block
258                break;
259            } else {
260                // Non-blockquote, non-blank line - this ends the blockquote block
261                break;
262            }
263        }
264
265        // Return start only if it's actually a blockquote line and not in a skip context
266        if Self::is_blockquote_line(lines[start_idx]) && !Self::is_in_skip_context(line_infos, start_idx) {
267            Some(start_idx)
268        } else {
269            None
270        }
271    }
272
273    /// Check if a blockquote block (starting at given index) is a callout/alert
274    /// For Obsidian flavor: accepts any [!TYPE] pattern
275    /// For other flavors: only accepts GFM alert types
276    fn is_callout_block(
277        lines: &[&str],
278        line_infos: &[LineInfo],
279        blockquote_line_idx: usize,
280        flavor: MarkdownFlavor,
281    ) -> bool {
282        // Find the start of this blockquote block
283        if let Some(start_idx) = Self::find_blockquote_start(lines, line_infos, blockquote_line_idx) {
284            // Check if the first line of the block is a callout/alert
285            return Self::is_callout_line(lines[start_idx], flavor);
286        }
287        false
288    }
289
290    /// Analyze context to determine if quotes are likely the same or different
291    fn are_likely_same_blockquote(
292        lines: &[&str],
293        line_infos: &[LineInfo],
294        blank_idx: usize,
295        flavor: MarkdownFlavor,
296    ) -> bool {
297        // Look for patterns that suggest these are the same blockquote:
298        // 1. Only one blank line between them (multiple blanks suggest separation)
299        // 2. Same indentation level
300        // 3. No content between them
301        // 4. Similar blockquote levels
302
303        // Note: We flag ALL blank lines between blockquotes, matching markdownlint behavior.
304        // Even multiple consecutive blank lines are flagged as they can be ambiguous
305        // (some parsers treat them as one blockquote, others as separate blockquotes).
306
307        // Find previous and next blockquote lines using fast byte scanning
308        let mut prev_quote_idx = None;
309        let mut next_quote_idx = None;
310
311        // Scan backwards for previous blockquote, skipping lines in skip contexts
312        for i in (0..blank_idx).rev() {
313            if Self::is_in_skip_context(line_infos, i) {
314                continue;
315            }
316            let line = lines[i];
317            // Fast check: if no '>' character, skip
318            if line.as_bytes().contains(&b'>') && Self::is_blockquote_line(line) {
319                prev_quote_idx = Some(i);
320                break;
321            }
322        }
323
324        // Scan forwards for next blockquote, skipping lines in skip contexts
325        for (i, line) in lines.iter().enumerate().skip(blank_idx + 1) {
326            if Self::is_in_skip_context(line_infos, i) {
327                continue;
328            }
329            // Fast check: if no '>' character, skip
330            if line.as_bytes().contains(&b'>') && Self::is_blockquote_line(line) {
331                next_quote_idx = Some(i);
332                break;
333            }
334        }
335
336        let (Some(prev_idx), Some(next_idx)) = (prev_quote_idx, next_quote_idx) else {
337            return false;
338        };
339
340        // Callout/Alert check: If either blockquote is a callout/alert, treat them as
341        // intentionally separate blockquotes. Callouts MUST be separated by blank lines
342        // to render correctly.
343        // For Obsidian flavor: any [!TYPE] is a callout
344        // For other flavors: only GFM alert types (NOTE, TIP, IMPORTANT, WARNING, CAUTION)
345        let prev_is_callout = Self::is_callout_block(lines, line_infos, prev_idx, flavor);
346        let next_is_callout = Self::is_callout_block(lines, line_infos, next_idx, flavor);
347        if prev_is_callout || next_is_callout {
348            return false;
349        }
350
351        // Check for content between blockquotes
352        if Self::has_content_between(lines, line_infos, prev_idx + 1, next_idx) {
353            return false;
354        }
355
356        // Get blockquote info once per line to avoid repeated parsing
357        let (prev_level, prev_whitespace_end) = Self::get_blockquote_info(lines[prev_idx]);
358        let (next_level, next_whitespace_end) = Self::get_blockquote_info(lines[next_idx]);
359
360        // Different levels suggest different contexts
361        // But next_level > prev_level could be nested continuation
362        if next_level < prev_level {
363            return false;
364        }
365
366        // Check indentation consistency using byte indices
367        let prev_line = lines[prev_idx];
368        let next_line = lines[next_idx];
369        let prev_indent = &prev_line[..prev_whitespace_end];
370        let next_indent = &next_line[..next_whitespace_end];
371
372        // Different indentation indicates separate blockquote contexts
373        // Same indentation with no content between = same blockquote (blank line inside)
374        prev_indent == next_indent
375    }
376
377    /// Check if a blank line is problematic (inside a blockquote)
378    fn is_problematic_blank_line(
379        lines: &[&str],
380        line_infos: &[LineInfo],
381        index: usize,
382        flavor: MarkdownFlavor,
383    ) -> Option<(usize, String)> {
384        let current_line = lines[index];
385
386        // Must be a blank line (no content, no > markers)
387        if !current_line.trim().is_empty() || Self::is_blockquote_line(current_line) {
388            return None;
389        }
390
391        // Use heuristics to determine if this blank line is inside a blockquote
392        // or if it's an intentional separator between blockquotes
393        if !Self::are_likely_same_blockquote(lines, line_infos, index, flavor) {
394            return None;
395        }
396
397        // This blank line appears to be inside a blockquote
398        // Find the appropriate fix using optimized parsing, skipping lines in skip contexts
399        for i in (0..index).rev() {
400            if Self::is_in_skip_context(line_infos, i) {
401                continue;
402            }
403            let line = lines[i];
404            // Fast check: if no '>' character, skip
405            if line.as_bytes().contains(&b'>') && Self::is_blockquote_line(line) {
406                let (level, whitespace_end) = Self::get_blockquote_info(line);
407                let indent = &line[..whitespace_end];
408                let mut fix = String::with_capacity(indent.len() + level);
409                fix.push_str(indent);
410                for _ in 0..level {
411                    fix.push('>');
412                }
413                return Some((level, fix));
414            }
415        }
416
417        None
418    }
419}
420
421impl Rule for MD028NoBlanksBlockquote {
422    fn name(&self) -> &'static str {
423        "MD028"
424    }
425
426    fn description(&self) -> &'static str {
427        "Blank line inside blockquote"
428    }
429
430    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
431        // Early return for content without blockquotes
432        if !ctx.content.contains('>') {
433            return Ok(Vec::new());
434        }
435
436        let mut warnings = Vec::new();
437
438        // Get all lines
439        let lines = ctx.raw_lines();
440
441        // Pre-scan to find blank lines and blockquote lines for faster processing
442        let mut blank_line_indices = Vec::new();
443        let mut has_blockquotes = false;
444
445        for (line_idx, line) in lines.iter().enumerate() {
446            // Skip lines in non-markdown content contexts
447            if line_idx < ctx.lines.len() {
448                let li = &ctx.lines[line_idx];
449                if li.in_code_block || li.in_html_comment || li.in_mdx_comment || li.in_html_block || li.in_front_matter
450                {
451                    continue;
452                }
453            }
454
455            if line.trim().is_empty() {
456                blank_line_indices.push(line_idx);
457            } else if Self::is_blockquote_line(line) {
458                has_blockquotes = true;
459            }
460        }
461
462        // If no blockquotes found, no need to check blank lines
463        if !has_blockquotes {
464            return Ok(Vec::new());
465        }
466
467        // Only check blank lines that could be problematic
468        for &line_idx in &blank_line_indices {
469            let line_num = line_idx + 1;
470
471            // Check if this is a problematic blank line inside a blockquote
472            if let Some((level, fix_content)) = Self::is_problematic_blank_line(lines, &ctx.lines, line_idx, ctx.flavor)
473            {
474                let line = lines[line_idx];
475                let (start_line, start_col, end_line, end_col) = calculate_line_range(line_num, line);
476
477                warnings.push(LintWarning {
478                    rule_name: Some(self.name().to_string()),
479                    message: format!("Blank line inside blockquote (level {level})"),
480                    line: start_line,
481                    column: start_col,
482                    end_line,
483                    end_column: end_col,
484                    severity: Severity::Warning,
485                    // Auto-fix is opt-in: merging blockquotes changes meaning, so
486                    // attach the fix only when the user enabled it.
487                    fix: if self.config.fix {
488                        Some(Fix::new(
489                            ctx.line_index
490                                .line_col_to_byte_range_with_length(line_num, 1, line.len()),
491                            fix_content,
492                        ))
493                    } else {
494                        None
495                    },
496                });
497            }
498        }
499
500        Ok(warnings)
501    }
502
503    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
504        // Auto-fix is opt-in: when disabled (default), merging blockquotes is a
505        // no-op. check() still reports the warning without a fix.
506        if !self.config.fix || self.should_skip(ctx) {
507            return Ok(ctx.content.to_string());
508        }
509        let warnings = self.check(ctx)?;
510        if warnings.is_empty() {
511            return Ok(ctx.content.to_string());
512        }
513        let warnings =
514            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
515        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
516            .map_err(crate::rule::LintError::InvalidInput)
517    }
518
519    /// Get the category of this rule for selective processing
520    fn category(&self) -> RuleCategory {
521        RuleCategory::Blockquote
522    }
523
524    /// Check if this rule should be skipped
525    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
526        !ctx.likely_has_blockquotes()
527    }
528
529    fn as_any(&self) -> &dyn std::any::Any {
530        self
531    }
532
533    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
534    where
535        Self: Sized,
536    {
537        let rule_config: MD028Config = load_rule_config(config);
538        Box::new(MD028NoBlanksBlockquote::with_config(rule_config))
539    }
540
541    crate::impl_rule_config_sections!(MD028Config);
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547    use crate::lint_context::LintContext;
548
549    #[test]
550    fn test_default_warns_but_does_not_merge_blockquotes() {
551        // Through the production config path, MD028's autofix is opt-in. Two
552        // same-level adjacent blockquotes separated by a blank line are two
553        // distinct blockquotes per CommonMark; merging them changes meaning, and
554        // the heuristic cannot verify the author's intent. So check() still
555        // warns, but the warning carries no inline fix and fmt is a no-op.
556        let rule = MD028NoBlanksBlockquote::from_config(&crate::config::Config::default());
557        let content = "> Quote by Alice.\n\n> Quote by Bob.\n";
558        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
559
560        let warnings = rule.check(&ctx).unwrap();
561        assert_eq!(warnings.len(), 1, "detection should still fire by default");
562        assert!(warnings[0].fix.is_none(), "default warnings must not carry a fix");
563
564        let fixed = rule.fix(&ctx).unwrap();
565        assert_eq!(fixed, content, "default fmt must not merge distinct blockquotes");
566    }
567
568    #[test]
569    fn test_fix_enabled_merges_blockquotes() {
570        // With fix = true, the autofix merges the blockquotes (the helpful case:
571        // rejoining a quote with a continuation that had an accidental gap).
572        let rule = MD028NoBlanksBlockquote::with_fix(true);
573        let content = "> A quote\n\n> its continuation\n";
574        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
575        let fixed = rule.fix(&ctx).unwrap();
576        assert_eq!(fixed, "> A quote\n>\n> its continuation\n");
577    }
578
579    #[test]
580    fn test_no_blockquotes() {
581        let rule = MD028NoBlanksBlockquote::with_fix(true);
582        let content = "This is regular text\n\nWith blank lines\n\nBut no blockquotes";
583        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
584        let result = rule.check(&ctx).unwrap();
585        assert!(result.is_empty(), "Should not flag content without blockquotes");
586    }
587
588    #[test]
589    fn test_valid_blockquote_no_blanks() {
590        let rule = MD028NoBlanksBlockquote::with_fix(true);
591        let content = "> This is a blockquote\n> With multiple lines\n> But no blank lines";
592        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
593        let result = rule.check(&ctx).unwrap();
594        assert!(result.is_empty(), "Should not flag blockquotes without blank lines");
595    }
596
597    #[test]
598    fn test_blockquote_with_empty_line_marker() {
599        let rule = MD028NoBlanksBlockquote::with_fix(true);
600        // Lines with just > are valid and should NOT be flagged
601        let content = "> First line\n>\n> Third line";
602        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
603        let result = rule.check(&ctx).unwrap();
604        assert!(result.is_empty(), "Should not flag lines with just > marker");
605    }
606
607    #[test]
608    fn test_blockquote_with_empty_line_marker_and_space() {
609        let rule = MD028NoBlanksBlockquote::with_fix(true);
610        // Lines with > and space are also valid
611        let content = "> First line\n> \n> Third line";
612        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
613        let result = rule.check(&ctx).unwrap();
614        assert!(result.is_empty(), "Should not flag lines with > and space");
615    }
616
617    #[test]
618    fn test_blank_line_in_blockquote() {
619        let rule = MD028NoBlanksBlockquote::with_fix(true);
620        // Truly blank line (no >) inside blockquote should be flagged
621        let content = "> First line\n\n> Third line";
622        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
623        let result = rule.check(&ctx).unwrap();
624        assert_eq!(result.len(), 1, "Should flag truly blank line inside blockquote");
625        assert_eq!(result[0].line, 2);
626        assert!(result[0].message.contains("Blank line inside blockquote"));
627    }
628
629    #[test]
630    fn test_multiple_blank_lines() {
631        let rule = MD028NoBlanksBlockquote::with_fix(true);
632        let content = "> First\n\n\n> Fourth";
633        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
634        let result = rule.check(&ctx).unwrap();
635        // With proper indentation checking, both blank lines are flagged as they're within the same blockquote
636        assert_eq!(result.len(), 2, "Should flag each blank line within the blockquote");
637        assert_eq!(result[0].line, 2);
638        assert_eq!(result[1].line, 3);
639    }
640
641    #[test]
642    fn test_nested_blockquote_blank() {
643        let rule = MD028NoBlanksBlockquote::with_fix(true);
644        let content = ">> Nested quote\n\n>> More nested";
645        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
646        let result = rule.check(&ctx).unwrap();
647        assert_eq!(result.len(), 1);
648        assert_eq!(result[0].line, 2);
649    }
650
651    #[test]
652    fn test_nested_blockquote_with_marker() {
653        let rule = MD028NoBlanksBlockquote::with_fix(true);
654        // Lines with >> are valid
655        let content = ">> Nested quote\n>>\n>> More nested";
656        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
657        let result = rule.check(&ctx).unwrap();
658        assert!(result.is_empty(), "Should not flag lines with >> marker");
659    }
660
661    #[test]
662    fn test_fix_single_blank() {
663        let rule = MD028NoBlanksBlockquote::with_fix(true);
664        let content = "> First\n\n> Third";
665        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
666        let fixed = rule.fix(&ctx).unwrap();
667        assert_eq!(fixed, "> First\n>\n> Third");
668    }
669
670    #[test]
671    fn test_fix_nested_blank() {
672        let rule = MD028NoBlanksBlockquote::with_fix(true);
673        let content = ">> Nested\n\n>> More";
674        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
675        let fixed = rule.fix(&ctx).unwrap();
676        assert_eq!(fixed, ">> Nested\n>>\n>> More");
677    }
678
679    #[test]
680    fn test_fix_with_indentation() {
681        let rule = MD028NoBlanksBlockquote::with_fix(true);
682        let content = "  > Indented quote\n\n  > More";
683        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
684        let fixed = rule.fix(&ctx).unwrap();
685        assert_eq!(fixed, "  > Indented quote\n  >\n  > More");
686    }
687
688    #[test]
689    fn test_mixed_levels() {
690        let rule = MD028NoBlanksBlockquote::with_fix(true);
691        // Blank lines between different levels
692        let content = "> Level 1\n\n>> Level 2\n\n> Level 1 again";
693        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
694        let result = rule.check(&ctx).unwrap();
695        // Line 2 is a blank between > and >>, level 1 to level 2, considered inside level 1
696        // Line 4 is a blank between >> and >, level 2 to level 1, NOT inside blockquote
697        assert_eq!(result.len(), 1);
698        assert_eq!(result[0].line, 2);
699    }
700
701    #[test]
702    fn test_blockquote_with_code_block() {
703        let rule = MD028NoBlanksBlockquote::with_fix(true);
704        let content = "> Quote with code:\n> ```\n> code\n> ```\n>\n> More quote";
705        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
706        let result = rule.check(&ctx).unwrap();
707        // Line 5 has > marker, so it's not a blank line
708        assert!(result.is_empty(), "Should not flag line with > marker");
709    }
710
711    #[test]
712    fn test_category() {
713        let rule = MD028NoBlanksBlockquote::with_fix(true);
714        assert_eq!(rule.category(), RuleCategory::Blockquote);
715    }
716
717    #[test]
718    fn test_should_skip() {
719        let rule = MD028NoBlanksBlockquote::with_fix(true);
720        let ctx1 = LintContext::new("No blockquotes here", crate::config::MarkdownFlavor::Standard, None);
721        assert!(rule.should_skip(&ctx1));
722
723        let ctx2 = LintContext::new("> Has blockquote", crate::config::MarkdownFlavor::Standard, None);
724        assert!(!rule.should_skip(&ctx2));
725    }
726
727    #[test]
728    fn test_empty_content() {
729        let rule = MD028NoBlanksBlockquote::with_fix(true);
730        let content = "";
731        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
732        let result = rule.check(&ctx).unwrap();
733        assert!(result.is_empty());
734    }
735
736    #[test]
737    fn test_blank_after_blockquote() {
738        let rule = MD028NoBlanksBlockquote::with_fix(true);
739        let content = "> Quote\n\nNot a quote";
740        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
741        let result = rule.check(&ctx).unwrap();
742        assert!(result.is_empty(), "Blank line after blockquote ends is valid");
743    }
744
745    #[test]
746    fn test_blank_before_blockquote() {
747        let rule = MD028NoBlanksBlockquote::with_fix(true);
748        let content = "Not a quote\n\n> Quote";
749        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
750        let result = rule.check(&ctx).unwrap();
751        assert!(result.is_empty(), "Blank line before blockquote starts is valid");
752    }
753
754    #[test]
755    fn test_preserve_trailing_newline() {
756        let rule = MD028NoBlanksBlockquote::with_fix(true);
757        let content = "> Quote\n\n> More\n";
758        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
759        let fixed = rule.fix(&ctx).unwrap();
760        assert!(fixed.ends_with('\n'));
761
762        let content_no_newline = "> Quote\n\n> More";
763        let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
764        let fixed2 = rule.fix(&ctx2).unwrap();
765        assert!(!fixed2.ends_with('\n'));
766    }
767
768    #[test]
769    fn test_document_structure_extension() {
770        let rule = MD028NoBlanksBlockquote::with_fix(true);
771        let ctx = LintContext::new("> test", crate::config::MarkdownFlavor::Standard, None);
772        // Test that the rule works correctly with blockquotes
773        let result = rule.check(&ctx).unwrap();
774        assert!(result.is_empty(), "Should not flag valid blockquote");
775
776        // Test that rule skips content without blockquotes
777        let ctx2 = LintContext::new("no blockquote", crate::config::MarkdownFlavor::Standard, None);
778        assert!(rule.should_skip(&ctx2), "Should skip content without blockquotes");
779    }
780
781    #[test]
782    fn test_deeply_nested_blank() {
783        let rule = MD028NoBlanksBlockquote::with_fix(true);
784        let content = ">>> Deep nest\n\n>>> More deep";
785        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
786        let result = rule.check(&ctx).unwrap();
787        assert_eq!(result.len(), 1);
788
789        let fixed = rule.fix(&ctx).unwrap();
790        assert_eq!(fixed, ">>> Deep nest\n>>>\n>>> More deep");
791    }
792
793    #[test]
794    fn test_deeply_nested_with_marker() {
795        let rule = MD028NoBlanksBlockquote::with_fix(true);
796        // Lines with >>> are valid
797        let content = ">>> Deep nest\n>>>\n>>> More deep";
798        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
799        let result = rule.check(&ctx).unwrap();
800        assert!(result.is_empty(), "Should not flag lines with >>> marker");
801    }
802
803    #[test]
804    fn test_complex_blockquote_structure() {
805        let rule = MD028NoBlanksBlockquote::with_fix(true);
806        // Line with > is valid, not a blank line
807        let content = "> Level 1\n> > Nested properly\n>\n> Back to level 1";
808        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
809        let result = rule.check(&ctx).unwrap();
810        assert!(result.is_empty(), "Should not flag line with > marker");
811    }
812
813    #[test]
814    fn test_complex_with_blank() {
815        let rule = MD028NoBlanksBlockquote::with_fix(true);
816        // Blank line between different nesting levels is not flagged
817        // (going from >> back to > is a context change)
818        let content = "> Level 1\n> > Nested\n\n> Back to level 1";
819        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
820        let result = rule.check(&ctx).unwrap();
821        assert_eq!(
822            result.len(),
823            0,
824            "Blank between different nesting levels is not inside blockquote"
825        );
826    }
827
828    // ==================== GFM Alert Tests ====================
829    // GitHub Flavored Markdown alerts use the syntax > [!TYPE] where TYPE is
830    // NOTE, TIP, IMPORTANT, WARNING, or CAUTION. These alerts MUST be separated
831    // by blank lines to render correctly on GitHub.
832    // Reference: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
833
834    #[test]
835    fn test_gfm_alert_detection_note() {
836        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!NOTE]"));
837        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!NOTE] Additional text"));
838        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line(">  [!NOTE]"));
839        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!note]")); // case insensitive
840        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!Note]")); // mixed case
841    }
842
843    #[test]
844    fn test_gfm_alert_detection_all_types() {
845        // All five GFM alert types
846        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!NOTE]"));
847        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!TIP]"));
848        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!IMPORTANT]"));
849        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!WARNING]"));
850        assert!(MD028NoBlanksBlockquote::is_gfm_alert_line("> [!CAUTION]"));
851    }
852
853    #[test]
854    fn test_gfm_alert_detection_not_alert() {
855        // These should NOT be detected as GFM alerts
856        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("> Regular blockquote"));
857        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("> [!INVALID]"));
858        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("> [NOTE]")); // missing !
859        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("> [!]")); // empty type
860        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("Regular text [!NOTE]")); // not blockquote
861        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("")); // empty
862        assert!(!MD028NoBlanksBlockquote::is_gfm_alert_line("> ")); // empty blockquote
863    }
864
865    #[test]
866    fn test_gfm_alerts_separated_by_blank_line() {
867        // Issue #126 use case: Two GFM alerts separated by blank line should NOT be flagged
868        let rule = MD028NoBlanksBlockquote::with_fix(true);
869        let content = "> [!TIP]\n> Here's a github tip\n\n> [!NOTE]\n> Here's a github note";
870        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
871        let result = rule.check(&ctx).unwrap();
872        assert!(result.is_empty(), "Should not flag blank line between GFM alerts");
873    }
874
875    #[test]
876    fn test_gfm_alerts_all_five_types_separated() {
877        // All five alert types in sequence, each separated by blank lines
878        let rule = MD028NoBlanksBlockquote::with_fix(true);
879        let content = r#"> [!NOTE]
880> Note content
881
882> [!TIP]
883> Tip content
884
885> [!IMPORTANT]
886> Important content
887
888> [!WARNING]
889> Warning content
890
891> [!CAUTION]
892> Caution content"#;
893        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
894        let result = rule.check(&ctx).unwrap();
895        assert!(
896            result.is_empty(),
897            "Should not flag blank lines between any GFM alert types"
898        );
899    }
900
901    #[test]
902    fn test_gfm_alert_with_multiple_lines() {
903        // GFM alert with multiple content lines, then another alert
904        let rule = MD028NoBlanksBlockquote::with_fix(true);
905        let content = r#"> [!WARNING]
906> This is a warning
907> with multiple lines
908> of content
909
910> [!NOTE]
911> This is a note"#;
912        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
913        let result = rule.check(&ctx).unwrap();
914        assert!(
915            result.is_empty(),
916            "Should not flag blank line between multi-line GFM alerts"
917        );
918    }
919
920    #[test]
921    fn test_gfm_alert_followed_by_regular_blockquote() {
922        // GFM alert followed by regular blockquote - should NOT flag
923        let rule = MD028NoBlanksBlockquote::with_fix(true);
924        let content = "> [!TIP]\n> A helpful tip\n\n> Regular blockquote";
925        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
926        let result = rule.check(&ctx).unwrap();
927        assert!(result.is_empty(), "Should not flag blank line after GFM alert");
928    }
929
930    #[test]
931    fn test_regular_blockquote_followed_by_gfm_alert() {
932        // Regular blockquote followed by GFM alert - should NOT flag
933        let rule = MD028NoBlanksBlockquote::with_fix(true);
934        let content = "> Regular blockquote\n\n> [!NOTE]\n> Important note";
935        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
936        let result = rule.check(&ctx).unwrap();
937        assert!(result.is_empty(), "Should not flag blank line before GFM alert");
938    }
939
940    #[test]
941    fn test_regular_blockquotes_still_flagged() {
942        // Regular blockquotes (not GFM alerts) should still be flagged
943        let rule = MD028NoBlanksBlockquote::with_fix(true);
944        let content = "> First blockquote\n\n> Second blockquote";
945        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
946        let result = rule.check(&ctx).unwrap();
947        assert_eq!(
948            result.len(),
949            1,
950            "Should still flag blank line between regular blockquotes"
951        );
952    }
953
954    #[test]
955    fn test_gfm_alert_blank_line_within_same_alert() {
956        // Blank line WITHIN a single GFM alert should still be flagged
957        // (this is a missing > marker inside the alert)
958        let rule = MD028NoBlanksBlockquote::with_fix(true);
959        let content = "> [!NOTE]\n> First paragraph\n\n> Second paragraph of same note";
960        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
961        let result = rule.check(&ctx).unwrap();
962        // The second > line is NOT a new alert, so this is a blank within the same blockquote
963        // However, since the first blockquote is a GFM alert, and the second is just continuation,
964        // this could be ambiguous. Current implementation: if first is alert, don't flag.
965        // This is acceptable - user can use > marker on blank line if they want continuation.
966        assert!(
967            result.is_empty(),
968            "GFM alert status propagates to subsequent blockquote lines"
969        );
970    }
971
972    #[test]
973    fn test_gfm_alert_case_insensitive() {
974        let rule = MD028NoBlanksBlockquote::with_fix(true);
975        let content = "> [!note]\n> lowercase\n\n> [!TIP]\n> uppercase\n\n> [!Warning]\n> mixed";
976        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
977        let result = rule.check(&ctx).unwrap();
978        assert!(result.is_empty(), "GFM alert detection should be case insensitive");
979    }
980
981    #[test]
982    fn test_gfm_alert_with_nested_blockquote() {
983        // GFM alert doesn't support nesting, but test behavior
984        let rule = MD028NoBlanksBlockquote::with_fix(true);
985        let content = "> [!NOTE]\n> > Nested quote inside alert\n\n> [!TIP]\n> Tip";
986        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
987        let result = rule.check(&ctx).unwrap();
988        assert!(
989            result.is_empty(),
990            "Should not flag blank between alerts even with nested content"
991        );
992    }
993
994    #[test]
995    fn test_gfm_alert_indented() {
996        let rule = MD028NoBlanksBlockquote::with_fix(true);
997        // Indented GFM alerts (e.g., in a list context)
998        let content = "  > [!NOTE]\n  > Indented note\n\n  > [!TIP]\n  > Indented tip";
999        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1000        let result = rule.check(&ctx).unwrap();
1001        assert!(result.is_empty(), "Should not flag blank between indented GFM alerts");
1002    }
1003
1004    #[test]
1005    fn test_gfm_alert_mixed_with_regular_content() {
1006        // Mixed document with GFM alerts and regular content
1007        let rule = MD028NoBlanksBlockquote::with_fix(true);
1008        let content = r#"# Heading
1009
1010Some paragraph.
1011
1012> [!NOTE]
1013> Important note
1014
1015More paragraph text.
1016
1017> [!WARNING]
1018> Be careful!
1019
1020Final text."#;
1021        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1022        let result = rule.check(&ctx).unwrap();
1023        assert!(
1024            result.is_empty(),
1025            "GFM alerts in mixed document should not trigger warnings"
1026        );
1027    }
1028
1029    #[test]
1030    fn test_gfm_alert_fix_not_applied() {
1031        // When we have GFM alerts, fix should not modify the blank lines
1032        let rule = MD028NoBlanksBlockquote::with_fix(true);
1033        let content = "> [!TIP]\n> Tip\n\n> [!NOTE]\n> Note";
1034        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1035        let fixed = rule.fix(&ctx).unwrap();
1036        assert_eq!(fixed, content, "Fix should not modify blank lines between GFM alerts");
1037    }
1038
1039    #[test]
1040    fn test_gfm_alert_multiple_blank_lines_between() {
1041        // Multiple blank lines between GFM alerts should not be flagged
1042        let rule = MD028NoBlanksBlockquote::with_fix(true);
1043        let content = "> [!NOTE]\n> Note\n\n\n> [!TIP]\n> Tip";
1044        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1045        let result = rule.check(&ctx).unwrap();
1046        assert!(
1047            result.is_empty(),
1048            "Should not flag multiple blank lines between GFM alerts"
1049        );
1050    }
1051
1052    // ==================== Obsidian Callout Tests ====================
1053    // Obsidian callouts use the same > [!TYPE] syntax as GFM alerts, but support
1054    // any custom type (not just NOTE, TIP, IMPORTANT, WARNING, CAUTION).
1055    // They also support foldable callouts with + or - suffix.
1056    // Reference: https://help.obsidian.md/callouts
1057
1058    #[test]
1059    fn test_obsidian_callout_detection() {
1060        // Obsidian callouts should be detected
1061        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!NOTE]"));
1062        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!info]"));
1063        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!todo]"));
1064        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!success]"));
1065        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!question]"));
1066        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!failure]"));
1067        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!danger]"));
1068        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!bug]"));
1069        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!example]"));
1070        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!quote]"));
1071        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!cite]"));
1072    }
1073
1074    #[test]
1075    fn test_obsidian_callout_custom_types() {
1076        // Obsidian supports custom callout types
1077        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!custom]"));
1078        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!my-callout]"));
1079        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!my_callout]"));
1080        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!MyCallout]"));
1081        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!callout123]"));
1082    }
1083
1084    #[test]
1085    fn test_obsidian_callout_foldable() {
1086        // Obsidian supports foldable callouts with + or -
1087        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!NOTE]+ Expanded"));
1088        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line(
1089            "> [!NOTE]- Collapsed"
1090        ));
1091        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!WARNING]+"));
1092        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!TIP]-"));
1093    }
1094
1095    #[test]
1096    fn test_obsidian_callout_with_title() {
1097        // Obsidian callouts can have custom titles
1098        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line(
1099            "> [!NOTE] Custom Title"
1100        ));
1101        assert!(MD028NoBlanksBlockquote::is_obsidian_callout_line(
1102            "> [!WARNING]+ Be Careful!"
1103        ));
1104    }
1105
1106    #[test]
1107    fn test_obsidian_callout_invalid() {
1108        // Invalid callout patterns
1109        assert!(!MD028NoBlanksBlockquote::is_obsidian_callout_line(
1110            "> Regular blockquote"
1111        ));
1112        assert!(!MD028NoBlanksBlockquote::is_obsidian_callout_line("> [NOTE]")); // missing !
1113        assert!(!MD028NoBlanksBlockquote::is_obsidian_callout_line("> [!]")); // empty type
1114        assert!(!MD028NoBlanksBlockquote::is_obsidian_callout_line(
1115            "Regular text [!NOTE]"
1116        )); // not blockquote
1117        assert!(!MD028NoBlanksBlockquote::is_obsidian_callout_line("")); // empty
1118    }
1119
1120    #[test]
1121    fn test_obsidian_callouts_separated_by_blank_line() {
1122        // Obsidian callouts separated by blank line should NOT be flagged
1123        let rule = MD028NoBlanksBlockquote::with_fix(true);
1124        let content = "> [!info]\n> Some info\n\n> [!todo]\n> A todo item";
1125        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1126        let result = rule.check(&ctx).unwrap();
1127        assert!(
1128            result.is_empty(),
1129            "Should not flag blank line between Obsidian callouts"
1130        );
1131    }
1132
1133    #[test]
1134    fn test_obsidian_custom_callouts_separated() {
1135        // Custom Obsidian callouts should also be recognized
1136        let rule = MD028NoBlanksBlockquote::with_fix(true);
1137        let content = "> [!my-custom]\n> Custom content\n\n> [!another_custom]\n> More content";
1138        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1139        let result = rule.check(&ctx).unwrap();
1140        assert!(
1141            result.is_empty(),
1142            "Should not flag blank line between custom Obsidian callouts"
1143        );
1144    }
1145
1146    #[test]
1147    fn test_obsidian_foldable_callouts_separated() {
1148        // Foldable Obsidian callouts should also be recognized
1149        let rule = MD028NoBlanksBlockquote::with_fix(true);
1150        let content = "> [!NOTE]+ Expanded\n> Content\n\n> [!WARNING]- Collapsed\n> Warning content";
1151        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1152        let result = rule.check(&ctx).unwrap();
1153        assert!(
1154            result.is_empty(),
1155            "Should not flag blank line between foldable Obsidian callouts"
1156        );
1157    }
1158
1159    #[test]
1160    fn test_obsidian_custom_not_recognized_in_standard_flavor() {
1161        // Custom callout types should NOT be recognized in Standard flavor
1162        // (only GFM alert types are recognized)
1163        let rule = MD028NoBlanksBlockquote::with_fix(true);
1164        let content = "> [!info]\n> Info content\n\n> [!todo]\n> Todo content";
1165        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1166        let result = rule.check(&ctx).unwrap();
1167        // In Standard flavor, [!info] and [!todo] are NOT GFM alerts, so this is flagged
1168        assert_eq!(
1169            result.len(),
1170            1,
1171            "Custom callout types should be flagged in Standard flavor"
1172        );
1173    }
1174
1175    #[test]
1176    fn test_obsidian_gfm_alerts_work_in_both_flavors() {
1177        // GFM alert types should work in both Standard and Obsidian flavors
1178        let rule = MD028NoBlanksBlockquote::with_fix(true);
1179        let content = "> [!NOTE]\n> Note\n\n> [!WARNING]\n> Warning";
1180
1181        // Standard flavor
1182        let ctx_standard = LintContext::new(content, MarkdownFlavor::Standard, None);
1183        let result_standard = rule.check(&ctx_standard).unwrap();
1184        assert!(result_standard.is_empty(), "GFM alerts should work in Standard flavor");
1185
1186        // Obsidian flavor
1187        let ctx_obsidian = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1188        let result_obsidian = rule.check(&ctx_obsidian).unwrap();
1189        assert!(
1190            result_obsidian.is_empty(),
1191            "GFM alerts should also work in Obsidian flavor"
1192        );
1193    }
1194
1195    #[test]
1196    fn test_obsidian_callout_all_builtin_types() {
1197        // Test all built-in Obsidian callout types
1198        let rule = MD028NoBlanksBlockquote::with_fix(true);
1199        let content = r#"> [!note]
1200> Note
1201
1202> [!abstract]
1203> Abstract
1204
1205> [!summary]
1206> Summary
1207
1208> [!info]
1209> Info
1210
1211> [!todo]
1212> Todo
1213
1214> [!tip]
1215> Tip
1216
1217> [!success]
1218> Success
1219
1220> [!question]
1221> Question
1222
1223> [!warning]
1224> Warning
1225
1226> [!failure]
1227> Failure
1228
1229> [!danger]
1230> Danger
1231
1232> [!bug]
1233> Bug
1234
1235> [!example]
1236> Example
1237
1238> [!quote]
1239> Quote"#;
1240        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1241        let result = rule.check(&ctx).unwrap();
1242        assert!(result.is_empty(), "All Obsidian callout types should be recognized");
1243    }
1244
1245    #[test]
1246    fn test_obsidian_fix_not_applied_to_callouts() {
1247        // Fix should not modify blank lines between Obsidian callouts
1248        let rule = MD028NoBlanksBlockquote::with_fix(true);
1249        let content = "> [!info]\n> Info\n\n> [!todo]\n> Todo";
1250        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1251        let fixed = rule.fix(&ctx).unwrap();
1252        assert_eq!(
1253            fixed, content,
1254            "Fix should not modify blank lines between Obsidian callouts"
1255        );
1256    }
1257
1258    #[test]
1259    fn test_obsidian_regular_blockquotes_still_flagged() {
1260        // Regular blockquotes (not callouts) should still be flagged in Obsidian flavor
1261        let rule = MD028NoBlanksBlockquote::with_fix(true);
1262        let content = "> First blockquote\n\n> Second blockquote";
1263        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1264        let result = rule.check(&ctx).unwrap();
1265        assert_eq!(
1266            result.len(),
1267            1,
1268            "Regular blockquotes should still be flagged in Obsidian flavor"
1269        );
1270    }
1271
1272    #[test]
1273    fn test_obsidian_callout_mixed_with_regular_blockquote() {
1274        // Callout followed by regular blockquote - should NOT flag (callout takes precedence)
1275        let rule = MD028NoBlanksBlockquote::with_fix(true);
1276        let content = "> [!note]\n> Note content\n\n> Regular blockquote";
1277        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
1278        let result = rule.check(&ctx).unwrap();
1279        assert!(
1280            result.is_empty(),
1281            "Should not flag blank after callout even if followed by regular blockquote"
1282        );
1283    }
1284
1285    // ==================== HTML Comment Skip Tests ====================
1286    // Blockquote-like content inside HTML comments should not be linted.
1287
1288    #[test]
1289    fn test_html_comment_blockquotes_not_flagged() {
1290        let rule = MD028NoBlanksBlockquote::with_fix(true);
1291        let content = "## Responses\n\n<!--\n> First response text here.\n> <br>— Person One\n\n> Second response text here.\n> <br>— Person Two\n-->\n\nThe above responses are currently disabled.\n";
1292        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1293        let result = rule.check(&ctx).unwrap();
1294        assert!(
1295            result.is_empty(),
1296            "Should not flag blank lines inside HTML comments, got: {result:?}"
1297        );
1298    }
1299
1300    #[test]
1301    fn test_fix_preserves_html_comment_content() {
1302        let rule = MD028NoBlanksBlockquote::with_fix(true);
1303        let content = "<!--\n> First quote\n\n> Second quote\n-->\n";
1304        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1305        let fixed = rule.fix(&ctx).unwrap();
1306        assert_eq!(fixed, content, "Fix should not modify content inside HTML comments");
1307    }
1308
1309    #[test]
1310    fn test_multiline_html_comment_with_blockquotes() {
1311        let rule = MD028NoBlanksBlockquote::with_fix(true);
1312        let content = "# Title\n\n<!--\n> Quote A\n> Line 2\n\n> Quote B\n> Line 2\n\n> Quote C\n-->\n\nSome text\n";
1313        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1314        let result = rule.check(&ctx).unwrap();
1315        assert!(
1316            result.is_empty(),
1317            "Should not flag any blank lines inside HTML comments, got: {result:?}"
1318        );
1319    }
1320
1321    #[test]
1322    fn test_blockquotes_outside_html_comment_still_flagged() {
1323        let rule = MD028NoBlanksBlockquote::with_fix(true);
1324        let content = "> First quote\n\n> Second quote\n\n<!--\n> Commented quote A\n\n> Commented quote B\n-->\n";
1325        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1326        let result = rule.check(&ctx).unwrap();
1327        // The blank line between the first two blockquotes (outside comment) should be flagged
1328        // but none inside the HTML comment (lines 7 is the blank between commented quotes)
1329        for w in &result {
1330            assert!(
1331                w.line < 5,
1332                "Warning at line {} should not be inside HTML comment",
1333                w.line
1334            );
1335        }
1336        assert!(
1337            !result.is_empty(),
1338            "Should still flag blank line between blockquotes outside HTML comment"
1339        );
1340    }
1341
1342    #[test]
1343    fn test_frontmatter_blockquote_like_content_not_flagged() {
1344        let rule = MD028NoBlanksBlockquote::with_fix(true);
1345        let content = "---\n> not a real blockquote\n\n> also not real\n---\n\n# Title\n";
1346        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1347        let result = rule.check(&ctx).unwrap();
1348        assert!(
1349            result.is_empty(),
1350            "Should not flag content inside frontmatter, got: {result:?}"
1351        );
1352    }
1353
1354    #[test]
1355    fn test_comment_boundary_does_not_leak_into_adjacent_blockquotes() {
1356        // A real blockquote before a comment should not be matched with
1357        // a blockquote inside the comment across the <!-- boundary
1358        let rule = MD028NoBlanksBlockquote::with_fix(true);
1359        let content = "> real quote\n\n<!--\n> commented quote\n-->\n";
1360        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1361        let result = rule.check(&ctx).unwrap();
1362        assert!(
1363            result.is_empty(),
1364            "Should not match blockquotes across HTML comment boundaries, got: {result:?}"
1365        );
1366    }
1367
1368    #[test]
1369    fn test_blockquote_after_comment_boundary_not_matched() {
1370        // A blockquote inside a comment should not be matched with
1371        // a blockquote after the comment across the --> boundary
1372        let rule = MD028NoBlanksBlockquote::with_fix(true);
1373        let content = "<!--\n> commented quote\n-->\n\n> real quote\n";
1374        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1375        let result = rule.check(&ctx).unwrap();
1376        assert!(
1377            result.is_empty(),
1378            "Should not match blockquotes across HTML comment boundaries, got: {result:?}"
1379        );
1380    }
1381
1382    #[test]
1383    fn test_fix_preserves_comment_boundary_content() {
1384        // Verify fix doesn't modify content when blockquotes straddle a comment boundary
1385        let rule = MD028NoBlanksBlockquote::with_fix(true);
1386        let content = "> real quote\n\n<!--\n> commented quote A\n\n> commented quote B\n-->\n\n> another real quote\n";
1387        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1388        let fixed = rule.fix(&ctx).unwrap();
1389        assert_eq!(
1390            fixed, content,
1391            "Fix should not modify content when blockquotes are separated by comment boundaries"
1392        );
1393    }
1394
1395    #[test]
1396    fn test_inline_html_comment_does_not_suppress_warning() {
1397        // Inline HTML comments on a blockquote line should NOT suppress warnings -
1398        // only multi-line HTML comment blocks should
1399        let rule = MD028NoBlanksBlockquote::with_fix(true);
1400        let content = "> quote with <!-- inline comment -->\n\n> continuation\n";
1401        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1402        let result = rule.check(&ctx).unwrap();
1403        // This should still be flagged since the blockquotes are not inside an HTML comment block
1404        assert!(
1405            !result.is_empty(),
1406            "Should still flag blank lines between blockquotes with inline HTML comments"
1407        );
1408    }
1409
1410    // ==================== Skip Context Scanning Tests ====================
1411    // Verify that backward/forward scanning in are_likely_same_blockquote()
1412    // and is_problematic_blank_line() properly skips lines in HTML comments,
1413    // code blocks, and frontmatter.
1414
1415    #[test]
1416    fn test_comment_with_blockquote_markers_on_delimiters() {
1417        // The backward scan should not find blockquote lines on HTML comment
1418        // delimiter lines, preventing false positives
1419        let rule = MD028NoBlanksBlockquote::with_fix(true);
1420        let content = "<!-- > not a real blockquote\n\n> also not real -->\n\n> real quote A\n\n> real quote B";
1421        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1422        let result = rule.check(&ctx).unwrap();
1423        // Only the blank between "real quote A" and "real quote B" (line 6) should be flagged
1424        assert_eq!(
1425            result.len(),
1426            1,
1427            "Should only warn about blank between real quotes, got: {result:?}"
1428        );
1429        assert_eq!(result[0].line, 6, "Warning should be on line 6 (between real quotes)");
1430    }
1431
1432    #[test]
1433    fn test_commented_blockquote_between_real_blockquotes() {
1434        // A commented-out blockquote between two real blockquotes should act
1435        // as non-blockquote content, preventing them from being considered
1436        // the same blockquote
1437        let rule = MD028NoBlanksBlockquote::with_fix(true);
1438        let content = "> real A\n\n<!-- > commented -->\n\n> real B";
1439        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1440        let result = rule.check(&ctx).unwrap();
1441        assert!(
1442            result.is_empty(),
1443            "Should NOT warn when non-blockquote content (HTML comment) separates blockquotes, got: {result:?}"
1444        );
1445    }
1446
1447    #[test]
1448    fn test_code_block_with_blockquote_markers_between_real_blockquotes() {
1449        // Blockquote markers inside code blocks should be ignored by scanning
1450        let rule = MD028NoBlanksBlockquote::with_fix(true);
1451        let content = "> real A\n\n```\n> not a blockquote\n```\n\n> real B";
1452        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1453        let result = rule.check(&ctx).unwrap();
1454        assert!(
1455            result.is_empty(),
1456            "Should NOT warn when code block with > markers separates blockquotes, got: {result:?}"
1457        );
1458    }
1459
1460    #[test]
1461    fn test_frontmatter_with_blockquote_markers_does_not_cause_false_positive() {
1462        // Blockquote-like lines in frontmatter should be ignored by scanning
1463        let rule = MD028NoBlanksBlockquote::with_fix(true);
1464        let content = "---\n> frontmatter value\n---\n\n> real quote A\n\n> real quote B";
1465        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1466        let result = rule.check(&ctx).unwrap();
1467        // Only the blank between the two real blockquotes should be flagged
1468        assert_eq!(
1469            result.len(),
1470            1,
1471            "Should only flag the blank between real quotes, got: {result:?}"
1472        );
1473        assert_eq!(result[0].line, 6, "Warning should be on line 6 (between real quotes)");
1474    }
1475
1476    #[test]
1477    fn test_fix_does_not_modify_comment_separated_blockquotes() {
1478        // Fix should not add > markers when blockquotes are separated by HTML comments
1479        let rule = MD028NoBlanksBlockquote::with_fix(true);
1480        let content = "> real A\n\n<!-- > commented -->\n\n> real B";
1481        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1482        let fixed = rule.fix(&ctx).unwrap();
1483        assert_eq!(
1484            fixed, content,
1485            "Fix should not modify content when blockquotes are separated by HTML comment"
1486        );
1487    }
1488
1489    #[test]
1490    fn test_fix_works_correctly_with_comment_before_real_blockquotes() {
1491        // Fix should correctly handle the case where a comment with > markers
1492        // precedes two real blockquotes that have a blank between them
1493        let rule = MD028NoBlanksBlockquote::with_fix(true);
1494        let content = "<!-- > not a real blockquote\n\n> also not real -->\n\n> real quote A\n\n> real quote B";
1495        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1496        let fixed = rule.fix(&ctx).unwrap();
1497        // The blank between the two real quotes should be fixed
1498        assert!(
1499            fixed.contains("> real quote A\n>\n> real quote B"),
1500            "Fix should add > marker between real quotes, got: {fixed}"
1501        );
1502        // The content inside the comment should be untouched
1503        assert!(
1504            fixed.contains("<!-- > not a real blockquote"),
1505            "Fix should not modify comment content"
1506        );
1507    }
1508
1509    #[test]
1510    fn test_html_block_with_angle_brackets_not_flagged() {
1511        // HTML blocks can contain `>` characters (e.g., in nested tags or template syntax)
1512        // that look like blockquote markers. These should be skipped.
1513        let rule = MD028NoBlanksBlockquote::with_fix(true);
1514        let content = "<div>\n> not a real blockquote\n\n> also not real\n</div>";
1515        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1516        let result = rule.check(&ctx).unwrap();
1517
1518        assert!(
1519            result.is_empty(),
1520            "Lines inside HTML blocks should not trigger MD028. Got: {result:?}"
1521        );
1522    }
1523
1524    // ==================== Roundtrip Safety Tests ====================
1525    // Verify that fix() output, when re-checked, produces zero warnings.
1526
1527    #[test]
1528    fn test_roundtrip_single_blank() {
1529        let rule = MD028NoBlanksBlockquote::with_fix(true);
1530        let content = "> First\n\n> Third";
1531        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1532        let fixed = rule.fix(&ctx).unwrap();
1533        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1534        let warnings = rule.check(&ctx2).unwrap();
1535        assert!(
1536            warnings.is_empty(),
1537            "Roundtrip should produce zero warnings, got: {warnings:?}"
1538        );
1539    }
1540
1541    #[test]
1542    fn test_roundtrip_multiple_blanks() {
1543        let rule = MD028NoBlanksBlockquote::with_fix(true);
1544        let content = "> First\n\n\n> Fourth";
1545        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1546        let fixed = rule.fix(&ctx).unwrap();
1547        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1548        let warnings = rule.check(&ctx2).unwrap();
1549        assert!(
1550            warnings.is_empty(),
1551            "Roundtrip should produce zero warnings, got: {warnings:?}"
1552        );
1553    }
1554
1555    #[test]
1556    fn test_roundtrip_nested() {
1557        let rule = MD028NoBlanksBlockquote::with_fix(true);
1558        let content = ">> Nested\n\n>> More";
1559        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1560        let fixed = rule.fix(&ctx).unwrap();
1561        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1562        let warnings = rule.check(&ctx2).unwrap();
1563        assert!(
1564            warnings.is_empty(),
1565            "Roundtrip should produce zero warnings, got: {warnings:?}"
1566        );
1567    }
1568
1569    #[test]
1570    fn test_roundtrip_indented() {
1571        let rule = MD028NoBlanksBlockquote::with_fix(true);
1572        let content = "  > Indented\n\n  > More";
1573        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1574        let fixed = rule.fix(&ctx).unwrap();
1575        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1576        let warnings = rule.check(&ctx2).unwrap();
1577        assert!(
1578            warnings.is_empty(),
1579            "Roundtrip should produce zero warnings, got: {warnings:?}"
1580        );
1581    }
1582
1583    #[test]
1584    fn test_roundtrip_deeply_nested() {
1585        let rule = MD028NoBlanksBlockquote::with_fix(true);
1586        let content = ">>> Deep\n\n>>> More";
1587        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1588        let fixed = rule.fix(&ctx).unwrap();
1589        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1590        let warnings = rule.check(&ctx2).unwrap();
1591        assert!(
1592            warnings.is_empty(),
1593            "Roundtrip should produce zero warnings, got: {warnings:?}"
1594        );
1595    }
1596
1597    #[test]
1598    fn test_roundtrip_multi_blockquotes() {
1599        let rule = MD028NoBlanksBlockquote::with_fix(true);
1600        let content = "> First\n> Line\n\n> Second\n> Line\n\n> Third\n";
1601        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1602        let fixed = rule.fix(&ctx).unwrap();
1603        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
1604        let warnings = rule.check(&ctx2).unwrap();
1605        assert!(
1606            warnings.is_empty(),
1607            "Roundtrip should produce zero warnings, got: {warnings:?}"
1608        );
1609    }
1610
1611    #[test]
1612    fn test_roundtrip_idempotent() {
1613        let rule = MD028NoBlanksBlockquote::with_fix(true);
1614        let content = "> First\n\n> Second\n\n> Third\n";
1615        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1616        let fixed1 = rule.fix(&ctx).unwrap();
1617        let ctx2 = LintContext::new(&fixed1, crate::config::MarkdownFlavor::Standard, None);
1618        let fixed2 = rule.fix(&ctx2).unwrap();
1619        assert_eq!(fixed1, fixed2, "Fix should be idempotent");
1620    }
1621
1622    #[test]
1623    fn test_html_block_does_not_leak_into_adjacent_blockquotes() {
1624        // Blockquotes after an HTML block should still be checked
1625        let rule = MD028NoBlanksBlockquote::with_fix(true);
1626        let content =
1627            "<details>\n<summary>Click</summary>\n> inside html block\n</details>\n\n> real quote A\n\n> real quote B";
1628        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1629        let result = rule.check(&ctx).unwrap();
1630
1631        // Only the blank between "real quote A" and "real quote B" should be flagged
1632        assert_eq!(
1633            result.len(),
1634            1,
1635            "Expected 1 warning for blank between real blockquotes after HTML block. Got: {result:?}"
1636        );
1637    }
1638}