Skip to main content

rumdl_lib/rules/
md032_blanks_around_lists.rs

1use crate::lint_context::LazyContLine;
2use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
3use crate::utils::blockquote::{content_after_blockquote, effective_indent_in_blockquote};
4use crate::utils::calculate_indentation_width_default;
5use crate::utils::pandoc;
6use crate::utils::range_utils::{LineIndex, calculate_line_range};
7use crate::utils::regex_cache::BLOCKQUOTE_PREFIX_RE;
8use regex::Regex;
9use std::sync::LazyLock;
10
11mod md032_config;
12pub(super) use md032_config::MD032Config;
13
14// Detects ordered list items starting with a number other than 1
15static ORDERED_LIST_NON_ONE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*([2-9]|\d{2,})\.\s").unwrap());
16
17/// Check if a line is a thematic break (horizontal rule)
18/// Per CommonMark: 0-3 spaces of indentation, then 3+ of same char (-, *, _), optionally with spaces between
19fn is_thematic_break(line: &str) -> bool {
20    // Per CommonMark, thematic breaks can have 0-3 spaces of indentation (< 4 columns)
21    if calculate_indentation_width_default(line) > 3 {
22        return false;
23    }
24
25    let trimmed = line.trim();
26    if trimmed.len() < 3 {
27        return false;
28    }
29
30    let chars: Vec<char> = trimmed.chars().collect();
31    let first_non_space = chars.iter().find(|&&c| c != ' ');
32
33    if let Some(&marker) = first_non_space {
34        if marker != '-' && marker != '*' && marker != '_' {
35            return false;
36        }
37        let marker_count = chars.iter().filter(|&&c| c == marker).count();
38        let other_count = chars.iter().filter(|&&c| c != marker && c != ' ').count();
39        marker_count >= 3 && other_count == 0
40    } else {
41        false
42    }
43}
44
45/// Rule MD032: Lists should be surrounded by blank lines
46///
47/// This rule enforces that lists are surrounded by blank lines, which improves document
48/// readability and ensures consistent rendering across different Markdown processors.
49///
50/// ## Purpose
51///
52/// - **Readability**: Blank lines create visual separation between lists and surrounding content
53/// - **Parsing**: Many Markdown parsers require blank lines around lists for proper rendering
54/// - **Consistency**: Ensures uniform document structure and appearance
55/// - **Compatibility**: Improves compatibility across different Markdown implementations
56///
57/// ## Examples
58///
59/// ### Correct
60///
61/// ```markdown
62/// This is a paragraph of text.
63///
64/// - Item 1
65/// - Item 2
66/// - Item 3
67///
68/// This is another paragraph.
69/// ```
70///
71/// ### Incorrect
72///
73/// ```markdown
74/// This is a paragraph of text.
75/// - Item 1
76/// - Item 2
77/// - Item 3
78/// This is another paragraph.
79/// ```
80///
81/// ## Behavior Details
82///
83/// This rule checks for the following:
84///
85/// - **List Start**: There should be a blank line before the first item in a list
86///   (unless the list is at the beginning of the document or after front matter)
87/// - **List End**: There should be a blank line after the last item in a list
88///   (unless the list is at the end of the document)
89/// - **Nested Lists**: Properly handles nested lists and list continuations
90/// - **List Types**: Works with ordered lists, unordered lists, and all valid list markers (-, *, +)
91///
92/// ## Special Cases
93///
94/// This rule handles several special cases:
95///
96/// - **Front Matter**: YAML front matter is detected and skipped
97/// - **Code Blocks**: Lists inside code blocks are ignored
98/// - **List Content**: Indented content belonging to list items is properly recognized as part of the list
99/// - **Document Boundaries**: Lists at the beginning or end of the document have adjusted requirements
100///
101/// ## Fix Behavior
102///
103/// When applying automatic fixes, this rule:
104/// - Adds a blank line before the first list item when needed
105/// - Adds a blank line after the last list item when needed
106/// - Preserves document structure and existing content
107///
108/// ## Performance Optimizations
109///
110/// The rule includes several optimizations:
111/// - Fast path checks before applying more expensive regex operations
112/// - Efficient list item detection
113/// - Pre-computation of code block lines to avoid redundant processing
114#[derive(Debug, Clone, Default)]
115pub struct MD032BlanksAroundLists {
116    config: MD032Config,
117}
118
119impl MD032BlanksAroundLists {
120    pub fn from_config_struct(config: MD032Config) -> Self {
121        Self { config }
122    }
123}
124
125impl MD032BlanksAroundLists {
126    /// Check if a blank line should be required before a list based on the previous line context
127    fn should_require_blank_line_before(
128        ctx: &crate::lint_context::LintContext,
129        prev_line_num: usize,
130        current_line_num: usize,
131    ) -> bool {
132        // Always require blank lines after code blocks, front matter, etc.
133        if ctx
134            .line_info(prev_line_num)
135            .is_some_and(|info| info.in_code_block || info.in_front_matter)
136        {
137            return true;
138        }
139
140        // Always allow nested lists (lists indented within other list items)
141        if Self::is_nested_list(ctx, prev_line_num, current_line_num) {
142            return false;
143        }
144
145        // Default: require blank line (matching markdownlint's behavior)
146        true
147    }
148
149    /// Check if the current list is nested within another list item
150    fn is_nested_list(
151        ctx: &crate::lint_context::LintContext,
152        prev_line_num: usize,    // 1-indexed
153        current_line_num: usize, // 1-indexed
154    ) -> bool {
155        // Check if current line is indented (typical for nested lists)
156        if current_line_num > 0 && current_line_num - 1 < ctx.lines.len() {
157            let current_line = &ctx.lines[current_line_num - 1];
158            if current_line.indent >= 2 {
159                // Check if previous line is a list item or list content
160                if prev_line_num > 0 && prev_line_num - 1 < ctx.lines.len() {
161                    let prev_line = &ctx.lines[prev_line_num - 1];
162                    // Previous line is a list item or indented content
163                    if prev_line.list_item.is_some() || prev_line.indent >= 2 {
164                        return true;
165                    }
166                }
167            }
168        }
169        false
170    }
171
172    /// Check if a lazy continuation fix should be applied to a line.
173    /// Returns false for lines inside code blocks, front matter, or HTML comments.
174    fn should_apply_lazy_fix(ctx: &crate::lint_context::LintContext, line_num: usize) -> bool {
175        ctx.lines
176            .get(line_num.saturating_sub(1))
177            .is_some_and(|li| !li.in_code_block && !li.in_front_matter && !li.in_html_comment && !li.in_mdx_comment)
178    }
179
180    /// Calculate the fix for a lazy continuation line.
181    /// Returns the byte range to replace and the replacement string.
182    fn calculate_lazy_continuation_fix(
183        ctx: &crate::lint_context::LintContext,
184        line_num: usize,
185        lazy_info: &LazyContLine,
186    ) -> Option<Fix> {
187        let line_info = ctx.lines.get(line_num.saturating_sub(1))?;
188        let line_content = line_info.content(ctx.content);
189
190        if lazy_info.blockquote_level == 0 {
191            // Regular list (no blockquote): replace leading whitespace with proper indent
192            let start_byte = line_info.byte_offset;
193            let end_byte = start_byte + lazy_info.current_indent;
194            let replacement = " ".repeat(lazy_info.expected_indent);
195
196            Some(Fix::new(start_byte..end_byte, replacement))
197        } else {
198            // List inside blockquote: preserve blockquote prefix, fix indent after it
199            let after_bq = content_after_blockquote(line_content, lazy_info.blockquote_level);
200            let prefix_byte_len = line_content.len().saturating_sub(after_bq.len());
201            if prefix_byte_len == 0 {
202                return None;
203            }
204
205            let current_indent = after_bq.len() - after_bq.trim_start().len();
206            let start_byte = line_info.byte_offset + prefix_byte_len;
207            let end_byte = start_byte + current_indent;
208            let replacement = " ".repeat(lazy_info.expected_indent);
209
210            Some(Fix::new(start_byte..end_byte, replacement))
211        }
212    }
213
214    /// Apply a lazy continuation fix to a single line.
215    /// Replaces the current indentation with the expected indentation.
216    fn apply_lazy_fix_to_line(line: &str, lazy_info: &LazyContLine) -> String {
217        if lazy_info.blockquote_level == 0 {
218            // Regular list: strip current indent, add expected indent
219            let content = line.trim_start();
220            format!("{}{}", " ".repeat(lazy_info.expected_indent), content)
221        } else {
222            // Blockquote list: preserve blockquote prefix, fix indent after it
223            let after_bq = content_after_blockquote(line, lazy_info.blockquote_level);
224            let prefix_len = line.len().saturating_sub(after_bq.len());
225            if prefix_len == 0 {
226                return line.to_string();
227            }
228
229            let prefix = &line[..prefix_len];
230            let rest = after_bq.trim_start();
231            format!("{}{}{}", prefix, " ".repeat(lazy_info.expected_indent), rest)
232        }
233    }
234
235    /// Find the first non-transparent line before the given line (1-indexed).
236    /// Returns (line_num, is_blank) where:
237    /// - line_num is the 1-indexed line of actual content (0 if start of document)
238    /// - is_blank is true if that line is blank (meaning separation exists)
239    ///
240    /// Transparent elements (HTML comments, Quarto div markers) are skipped,
241    /// matching markdownlint-cli behavior.
242    fn find_preceding_content(ctx: &crate::lint_context::LintContext, before_line: usize) -> (usize, bool) {
243        let is_pandoc = ctx.flavor.is_pandoc_compatible();
244        for line_num in (1..before_line).rev() {
245            let idx = line_num - 1;
246            if let Some(info) = ctx.lines.get(idx) {
247                // Skip HTML/MDX comment lines - they're transparent
248                if info.in_html_comment || info.in_mdx_comment {
249                    continue;
250                }
251                // Skip Pandoc/Quarto div markers in Pandoc-compatible flavor - they're transparent
252                if is_pandoc {
253                    let trimmed = info.content(ctx.content).trim();
254                    if pandoc::is_div_open(trimmed) || pandoc::is_div_close(trimmed) {
255                        continue;
256                    }
257                }
258                return (line_num, info.is_blank);
259            }
260        }
261        // Start of document = effectively blank-separated
262        (0, true)
263    }
264
265    /// Find the first non-transparent line after the given line (1-indexed).
266    /// Returns (line_num, is_blank) where:
267    /// - line_num is the 1-indexed line of actual content (0 if end of document)
268    /// - is_blank is true if that line is blank (meaning separation exists)
269    ///
270    /// Transparent elements (HTML comments, Quarto div markers) are skipped.
271    fn find_following_content(ctx: &crate::lint_context::LintContext, after_line: usize) -> (usize, bool) {
272        let is_pandoc = ctx.flavor.is_pandoc_compatible();
273        let num_lines = ctx.lines.len();
274        for line_num in (after_line + 1)..=num_lines {
275            let idx = line_num - 1;
276            if let Some(info) = ctx.lines.get(idx) {
277                // Skip HTML/MDX comment lines - they're transparent
278                if info.in_html_comment || info.in_mdx_comment {
279                    continue;
280                }
281                // Skip Pandoc/Quarto div markers in Pandoc-compatible flavor - they're transparent
282                if is_pandoc {
283                    let trimmed = info.content(ctx.content).trim();
284                    if pandoc::is_div_open(trimmed) || pandoc::is_div_close(trimmed) {
285                        continue;
286                    }
287                }
288                return (line_num, info.is_blank);
289            }
290        }
291        // End of document = effectively blank-separated
292        (0, true)
293    }
294
295    // Convert centralized list blocks to the format expected by perform_checks
296    fn convert_list_blocks(&self, ctx: &crate::lint_context::LintContext) -> Vec<(usize, usize, String)> {
297        let mut blocks: Vec<(usize, usize, String)> = Vec::new();
298
299        for block in &ctx.list_blocks {
300            // Skip list blocks inside footnote definitions
301            if ctx
302                .line_info(block.start_line)
303                .is_some_and(|info| info.in_footnote_definition)
304            {
305                continue;
306            }
307
308            // For MD032, we need to check if there are code blocks that should
309            // split the list into separate segments
310
311            // Simple approach: if there's a fenced code block between list items,
312            // split at that point
313            let mut segments: Vec<(usize, usize)> = Vec::new();
314            let mut current_start = block.start_line;
315            let mut prev_item_line = 0;
316
317            // Helper to get blockquote level (count of '>' chars) from a line
318            let get_blockquote_level = |line_num: usize| -> usize {
319                if line_num == 0 || line_num > ctx.lines.len() {
320                    return 0;
321                }
322                let line_content = ctx.lines[line_num - 1].content(ctx.content);
323                BLOCKQUOTE_PREFIX_RE
324                    .find(line_content)
325                    .map_or(0, |m| m.as_str().chars().filter(|&c| c == '>').count())
326            };
327
328            let mut prev_bq_level = 0;
329
330            for &item_line in &block.item_lines {
331                let current_bq_level = get_blockquote_level(item_line);
332
333                if prev_item_line > 0 {
334                    // Check if blockquote level changed between items
335                    let blockquote_level_changed = prev_bq_level != current_bq_level;
336
337                    // Check if there's a standalone code fence between prev_item_line and item_line
338                    // A code fence that's indented as part of a list item should NOT split the list
339                    let mut has_standalone_code_fence = false;
340
341                    // Calculate minimum indentation for list item content
342                    let min_indent_for_content = if block.is_ordered {
343                        // For ordered lists, content should be indented at least to align with text after marker
344                        // e.g., "1. " = 3 chars, so content should be indented 3+ spaces
345                        3 // Minimum for "1. "
346                    } else {
347                        // For unordered lists, content should be indented at least 2 spaces
348                        2 // For "- " or "* "
349                    };
350
351                    for check_line in (prev_item_line + 1)..item_line {
352                        if check_line - 1 < ctx.lines.len() {
353                            let line = &ctx.lines[check_line - 1];
354                            let line_content = line.content(ctx.content);
355                            if line.in_code_block
356                                && (line_content.trim().starts_with("```") || line_content.trim().starts_with("~~~"))
357                            {
358                                // Check if this code fence is indented as part of the list item
359                                // If it's indented enough to be part of the list item, it shouldn't split
360                                if line.indent < min_indent_for_content {
361                                    has_standalone_code_fence = true;
362                                    break;
363                                }
364                            }
365                        }
366                    }
367
368                    if has_standalone_code_fence || blockquote_level_changed {
369                        // End current segment before this item
370                        segments.push((current_start, prev_item_line));
371                        current_start = item_line;
372                    }
373                }
374                prev_item_line = item_line;
375                prev_bq_level = current_bq_level;
376            }
377
378            // Add the final segment
379            // For the last segment, end at the last list item (not the full block end)
380            if prev_item_line > 0 {
381                segments.push((current_start, prev_item_line));
382            }
383
384            // Check if this list block was split by code fences
385            let has_code_fence_splits = segments.len() > 1 && {
386                // Check if any segments were created due to code fences
387                let mut found_fence = false;
388                for i in 0..segments.len() - 1 {
389                    let seg_end = segments[i].1;
390                    let next_start = segments[i + 1].0;
391                    // Check if there's a code fence between these segments
392                    for check_line in (seg_end + 1)..next_start {
393                        if check_line - 1 < ctx.lines.len() {
394                            let line = &ctx.lines[check_line - 1];
395                            let line_content = line.content(ctx.content);
396                            if line.in_code_block
397                                && (line_content.trim().starts_with("```") || line_content.trim().starts_with("~~~"))
398                            {
399                                found_fence = true;
400                                break;
401                            }
402                        }
403                    }
404                    if found_fence {
405                        break;
406                    }
407                }
408                found_fence
409            };
410
411            // Convert segments to blocks
412            for (start, end) in &segments {
413                // Extend the end to include any continuation lines immediately after the last item
414                let mut actual_end = *end;
415
416                // If this list was split by code fences, don't extend any segments
417                // They should remain as individual list items for MD032 purposes
418                if !has_code_fence_splits && *end < block.end_line {
419                    // Get the blockquote level for this block
420                    let block_bq_level = block.blockquote_prefix.chars().filter(|&c| c == '>').count();
421
422                    // For blockquote lists, use a simpler min_continuation_indent
423                    // (the content column without the blockquote prefix portion)
424                    let min_continuation_indent = if block_bq_level > 0 {
425                        // For lists in blockquotes, content should align with text after marker
426                        if block.is_ordered {
427                            block.max_marker_width
428                        } else {
429                            2 // "- " or "* "
430                        }
431                    } else {
432                        ctx.lines
433                            .get(*end - 1)
434                            .and_then(|line_info| line_info.list_item.as_ref())
435                            .map_or(2, |item| item.content_column)
436                    };
437
438                    for check_line in (*end + 1)..=block.end_line {
439                        if check_line - 1 < ctx.lines.len() {
440                            let line = &ctx.lines[check_line - 1];
441                            let line_content = line.content(ctx.content);
442                            // Stop at next list item or non-continuation content
443                            if block.item_lines.contains(&check_line) || line.heading.is_some() {
444                                break;
445                            }
446                            // Don't extend through code blocks
447                            if line.in_code_block {
448                                break;
449                            }
450
451                            // Calculate effective indent for blockquote lines
452                            let effective_indent =
453                                effective_indent_in_blockquote(line_content, block_bq_level, line.indent);
454
455                            // Include indented continuation if indent meets threshold
456                            if effective_indent >= min_continuation_indent {
457                                actual_end = check_line;
458                            }
459                            // Include lazy continuation lines for structural purposes
460                            // Per CommonMark, only paragraph text can be lazy continuation
461                            // Thematic breaks, code fences, etc. cannot be lazy continuations
462                            // Always include lazy lines in block range - the config controls whether to WARN
463                            else if !line.is_blank
464                                && line.heading.is_none()
465                                && !block.item_lines.contains(&check_line)
466                                && !is_thematic_break(line_content)
467                            {
468                                // This is a lazy continuation line - include it in the block range
469                                actual_end = check_line;
470                            } else if !line.is_blank {
471                                // Non-blank line that's not a continuation - stop here
472                                break;
473                            }
474                        }
475                    }
476                }
477
478                blocks.push((*start, actual_end, block.blockquote_prefix.clone()));
479            }
480        }
481
482        // Filter out lists entirely inside HTML comments
483        blocks.retain(|(start, end, _)| {
484            // Check if ALL lines of this block are inside HTML comments
485            let all_in_comment = (*start..=*end).all(|line_num| {
486                ctx.lines
487                    .get(line_num - 1)
488                    .is_some_and(|info| info.in_html_comment || info.in_mdx_comment)
489            });
490            !all_in_comment
491        });
492
493        blocks
494    }
495
496    fn perform_checks(
497        &self,
498        ctx: &crate::lint_context::LintContext,
499        lines: &[&str],
500        list_blocks: &[(usize, usize, String)],
501        line_index: &LineIndex,
502    ) -> Vec<LintWarning> {
503        let mut warnings = Vec::new();
504        let num_lines = lines.len();
505
506        // Check for ordered lists starting with non-1 that aren't recognized as lists
507        // These need blank lines before them to be parsed as lists by CommonMark
508        for (line_idx, line) in lines.iter().enumerate() {
509            let line_num = line_idx + 1;
510
511            // Skip if this line is already part of a recognized list
512            let is_in_list = list_blocks
513                .iter()
514                .any(|(start, end, _)| line_num >= *start && line_num <= *end);
515            if is_in_list {
516                continue;
517            }
518
519            // Skip if in code block, front matter, or HTML comment
520            if ctx.line_info(line_num).is_some_and(|info| {
521                info.in_code_block
522                    || info.in_front_matter
523                    || info.in_html_comment
524                    || info.in_mdx_comment
525                    || info.in_html_block
526                    || info.in_jsx_block
527            }) {
528                continue;
529            }
530
531            // Check if this line starts with a number other than 1
532            if ORDERED_LIST_NON_ONE_RE.is_match(line) {
533                // Check if there's a blank line before this
534                if line_idx > 0 {
535                    let prev_line = lines[line_idx - 1];
536                    let prev_is_blank = is_blank_in_context(prev_line);
537                    let prev_excluded = ctx
538                        .line_info(line_idx)
539                        .is_some_and(|info| info.in_code_block || info.in_front_matter);
540
541                    // Check if previous line looks like a sentence continuation
542                    // If the previous line is non-blank text that doesn't end with a sentence
543                    // terminator, this is likely a paragraph continuation, not a list item
544                    // e.g., "...in Chapter\n19. For now..." is a broken sentence, not a list
545                    let prev_trimmed = prev_line.trim();
546                    let is_sentence_continuation = !prev_is_blank
547                        && !prev_trimmed.is_empty()
548                        && !prev_trimmed.ends_with('.')
549                        && !prev_trimmed.ends_with('!')
550                        && !prev_trimmed.ends_with('?')
551                        && !prev_trimmed.ends_with(':')
552                        && !prev_trimmed.ends_with(';')
553                        && !prev_trimmed.ends_with('>')
554                        && !prev_trimmed.ends_with('-')
555                        && !prev_trimmed.ends_with('*');
556
557                    if !prev_is_blank && !prev_excluded && !is_sentence_continuation {
558                        // This ordered list item starting with non-1 needs a blank line before it
559                        let (start_line, start_col, end_line, end_col) = calculate_line_range(line_num, line);
560
561                        let bq_prefix = ctx.blockquote_prefix_for_blank_line(line_idx);
562                        warnings.push(LintWarning {
563                            line: start_line,
564                            column: start_col,
565                            end_line,
566                            end_column: end_col,
567                            severity: Severity::Warning,
568                            rule_name: Some(self.name().to_string()),
569                            message: "Ordered list starting with non-1 should be preceded by blank line".to_string(),
570                            fix: Some(Fix::new(
571                                line_index.line_col_to_byte_range_with_length(line_num, 1, 0),
572                                format!("{bq_prefix}\n"),
573                            )),
574                        });
575                    }
576
577                    // Also check if a blank line is needed AFTER this ordered list item
578                    // This ensures single-pass idempotency
579                    if line_idx + 1 < num_lines {
580                        let next_line = lines[line_idx + 1];
581                        let next_is_blank = is_blank_in_context(next_line);
582                        let next_excluded = ctx.line_info(line_idx + 2).is_some_and(|info| info.in_front_matter);
583
584                        if !next_is_blank && !next_excluded && !next_line.trim().is_empty() {
585                            // Check if next line is a continuation of this ordered list
586                            // Only other ordered items or indented continuations count;
587                            // unordered list markers are a different list requiring separation
588                            let next_trimmed = next_line.trim_start();
589                            let next_is_ordered_content = ORDERED_LIST_NON_ONE_RE.is_match(next_line)
590                                || next_line.starts_with("1. ")
591                                || (next_line.len() > next_trimmed.len()
592                                    && !next_trimmed.starts_with("- ")
593                                    && !next_trimmed.starts_with("* ")
594                                    && !next_trimmed.starts_with("+ ")); // indented continuation (not a nested unordered list)
595
596                            if !next_is_ordered_content {
597                                let (start_line, start_col, end_line, end_col) = calculate_line_range(line_num, line);
598                                let bq_prefix = ctx.blockquote_prefix_for_blank_line(line_idx);
599                                warnings.push(LintWarning {
600                                    line: start_line,
601                                    column: start_col,
602                                    end_line,
603                                    end_column: end_col,
604                                    severity: Severity::Warning,
605                                    rule_name: Some(self.name().to_string()),
606                                    message: "List should be followed by blank line".to_string(),
607                                    fix: Some(Fix::new(
608                                        line_index.line_col_to_byte_range_with_length(line_num + 1, 1, 0),
609                                        format!("{bq_prefix}\n"),
610                                    )),
611                                });
612                            }
613                        }
614                    }
615                }
616            }
617        }
618
619        for &(start_line, end_line, ref prefix) in list_blocks {
620            // Skip lists that start inside HTML/MDX comments
621            if ctx
622                .line_info(start_line)
623                .is_some_and(|info| info.in_html_comment || info.in_mdx_comment)
624            {
625                continue;
626            }
627
628            if start_line > 1 {
629                // Look past HTML comments to find actual preceding content
630                let (content_line, has_blank_separation) = Self::find_preceding_content(ctx, start_line);
631
632                // If blank separation exists (through HTML comments), no warning needed
633                if !has_blank_separation && content_line > 0 {
634                    let prev_line_str = lines[content_line - 1];
635                    let is_prev_excluded = ctx
636                        .line_info(content_line)
637                        .is_some_and(|info| info.in_code_block || info.in_front_matter);
638                    let prev_prefix = BLOCKQUOTE_PREFIX_RE.find(prev_line_str).map_or("", |m| m.as_str());
639                    let prefixes_match = prev_prefix.trim() == prefix.trim();
640
641                    // Only require blank lines for content in the same context (same blockquote level)
642                    // and when the context actually requires it
643                    let should_require = Self::should_require_blank_line_before(ctx, content_line, start_line);
644                    if !is_prev_excluded && prefixes_match && should_require {
645                        // Calculate precise character range for the entire list line that needs a blank line before it
646                        let (start_line, start_col, end_line, end_col) =
647                            calculate_line_range(start_line, lines[start_line - 1]);
648
649                        warnings.push(LintWarning {
650                            line: start_line,
651                            column: start_col,
652                            end_line,
653                            end_column: end_col,
654                            severity: Severity::Warning,
655                            rule_name: Some(self.name().to_string()),
656                            message: "List should be preceded by blank line".to_string(),
657                            fix: Some(Fix::new(
658                                line_index.line_col_to_byte_range_with_length(start_line, 1, 0),
659                                format!("{prefix}\n"),
660                            )),
661                        });
662                    }
663                }
664            }
665
666            if end_line < num_lines {
667                // Look past HTML comments to find actual following content
668                let (content_line, has_blank_separation) = Self::find_following_content(ctx, end_line);
669
670                // If blank separation exists (through HTML comments), no warning needed
671                if !has_blank_separation && content_line > 0 {
672                    let next_line_str = lines[content_line - 1];
673                    // Check if next line is excluded - front matter or indented code blocks within lists
674                    // We want blank lines before standalone code blocks, but not within list items
675                    let is_next_excluded = ctx.line_info(content_line).is_some_and(|info| info.in_front_matter)
676                        || (content_line <= ctx.lines.len()
677                            && ctx.lines[content_line - 1].in_code_block
678                            && ctx.lines[content_line - 1].indent >= 2);
679                    let next_prefix = BLOCKQUOTE_PREFIX_RE.find(next_line_str).map_or("", |m| m.as_str());
680
681                    // Check blockquote levels to detect boundary transitions
682                    // If the list ends inside a blockquote but the following line exits the blockquote
683                    // (fewer > chars in prefix), no blank line is needed - the blockquote boundary
684                    // provides semantic separation
685                    let end_line_str = lines[end_line - 1];
686                    let end_line_prefix = BLOCKQUOTE_PREFIX_RE.find(end_line_str).map_or("", |m| m.as_str());
687                    let end_line_bq_level = end_line_prefix.chars().filter(|&c| c == '>').count();
688                    let next_line_bq_level = next_prefix.chars().filter(|&c| c == '>').count();
689                    let exits_blockquote = end_line_bq_level > 0 && next_line_bq_level < end_line_bq_level;
690
691                    let prefixes_match = next_prefix.trim() == prefix.trim();
692
693                    // Do not warn when the immediately following line is a tight continuation
694                    // of the last list item. A tight continuation is any non-blank,
695                    // non-list-item line indented strictly past the last item's marker column.
696                    // Inserting a blank there would structurally separate the continuation
697                    // from its parent item.
698                    let is_tight_continuation_of_last_item = ctx
699                        .lines
700                        .get(end_line - 1)
701                        .and_then(|last_li| last_li.list_item.as_ref())
702                        .is_some_and(|last_item| {
703                            let marker_col = last_item.marker_column;
704                            ctx.lines.get(content_line - 1).is_some_and(|next_li| {
705                                !next_li.is_blank && next_li.list_item.is_none() && next_li.indent > marker_col
706                            })
707                        });
708
709                    // Only require blank lines for content in the same context (same blockquote level)
710                    // Skip if the following line exits a blockquote - boundary provides separation
711                    if !is_next_excluded && prefixes_match && !exits_blockquote && !is_tight_continuation_of_last_item {
712                        // Calculate precise character range for the last line of the list (not the line after)
713                        let (start_line_last, start_col_last, end_line_last, end_col_last) =
714                            calculate_line_range(end_line, lines[end_line - 1]);
715
716                        warnings.push(LintWarning {
717                            line: start_line_last,
718                            column: start_col_last,
719                            end_line: end_line_last,
720                            end_column: end_col_last,
721                            severity: Severity::Warning,
722                            rule_name: Some(self.name().to_string()),
723                            message: "List should be followed by blank line".to_string(),
724                            fix: Some(Fix::new(
725                                line_index.line_col_to_byte_range_with_length(end_line + 1, 1, 0),
726                                format!("{prefix}\n"),
727                            )),
728                        });
729                    }
730                }
731            }
732        }
733        warnings
734    }
735}
736
737impl Rule for MD032BlanksAroundLists {
738    fn name(&self) -> &'static str {
739        "MD032"
740    }
741
742    fn description(&self) -> &'static str {
743        "Lists should be surrounded by blank lines"
744    }
745
746    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
747        let lines = ctx.raw_lines();
748        let line_index = &ctx.line_index;
749
750        // Early return for empty content
751        if lines.is_empty() {
752            return Ok(Vec::new());
753        }
754
755        let list_blocks = self.convert_list_blocks(ctx);
756
757        if list_blocks.is_empty() {
758            return Ok(Vec::new());
759        }
760
761        let mut warnings = self.perform_checks(ctx, lines, &list_blocks, line_index);
762
763        // When lazy continuation is not allowed, detect and warn about lazy continuation
764        // lines WITHIN list blocks (text that continues a list item but with less
765        // indentation than expected). Lazy continuation at the END of list blocks is
766        // already handled by the segment extension logic above.
767        if !self.config.allow_lazy_continuation {
768            let lazy_cont_lines = ctx.lazy_continuation_lines();
769
770            for lazy_info in lazy_cont_lines.iter() {
771                let line_num = lazy_info.line_num;
772
773                // Only warn about lazy continuation lines that are WITHIN a list block
774                // (i.e., between list items). End-of-block lazy continuation is already
775                // handled by the existing "list should be followed by blank line" logic.
776                let is_within_block = list_blocks
777                    .iter()
778                    .any(|(start, end, _)| line_num >= *start && line_num <= *end);
779
780                if !is_within_block {
781                    continue;
782                }
783
784                // Get the expected indent for context in the warning message
785                let line_content = lines.get(line_num.saturating_sub(1)).unwrap_or(&"");
786                let (start_line, start_col, end_line, end_col) = calculate_line_range(line_num, line_content);
787
788                // Calculate fix: add proper indentation to the lazy continuation line
789                let fix = if Self::should_apply_lazy_fix(ctx, line_num) {
790                    Self::calculate_lazy_continuation_fix(ctx, line_num, lazy_info)
791                } else {
792                    None
793                };
794
795                warnings.push(LintWarning {
796                    line: start_line,
797                    column: start_col,
798                    end_line,
799                    end_column: end_col,
800                    severity: Severity::Warning,
801                    rule_name: Some(self.name().to_string()),
802                    message: "Lazy continuation line should be properly indented or preceded by blank line".to_string(),
803                    fix,
804                });
805            }
806        }
807
808        Ok(warnings)
809    }
810
811    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
812        Ok(self.fix_with_structure_impl(ctx))
813    }
814
815    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
816        // Skip if no list blocks exist (includes ordered and unordered lists)
817        // Note: list_blocks is pre-computed in LintContext, so this is already efficient
818        ctx.content.is_empty() || ctx.list_blocks.is_empty()
819    }
820
821    fn category(&self) -> RuleCategory {
822        RuleCategory::List
823    }
824
825    fn as_any(&self) -> &dyn std::any::Any {
826        self
827    }
828
829    crate::impl_rule_config_methods!(MD032Config);
830}
831
832impl MD032BlanksAroundLists {
833    /// Helper method for fixing implementation
834    fn fix_with_structure_impl(&self, ctx: &crate::lint_context::LintContext) -> String {
835        let lines = ctx.raw_lines();
836        let num_lines = lines.len();
837        if num_lines == 0 {
838            return String::new();
839        }
840
841        let list_blocks = self.convert_list_blocks(ctx);
842        if list_blocks.is_empty() {
843            return ctx.content.to_string();
844        }
845
846        // Phase 0: Collect lazy continuation line fixes (if not allowed)
847        // Map of line_num -> LazyContLine for applying fixes
848        let mut lazy_fixes: std::collections::BTreeMap<usize, LazyContLine> = std::collections::BTreeMap::new();
849        if !self.config.allow_lazy_continuation {
850            let lazy_cont_lines = ctx.lazy_continuation_lines();
851            for lazy_info in lazy_cont_lines.iter() {
852                let line_num = lazy_info.line_num;
853                // Only fix lines within a list block
854                let is_within_block = list_blocks
855                    .iter()
856                    .any(|(start, end, _)| line_num >= *start && line_num <= *end);
857                if !is_within_block {
858                    continue;
859                }
860                // Only fix if not in code block, front matter, or HTML comment
861                if !Self::should_apply_lazy_fix(ctx, line_num) {
862                    continue;
863                }
864                lazy_fixes.insert(line_num, lazy_info.clone());
865            }
866        }
867
868        let mut insertions: std::collections::BTreeMap<usize, String> = std::collections::BTreeMap::new();
869
870        // Phase 1: Identify needed insertions
871        for &(start_line, end_line, ref prefix) in &list_blocks {
872            // Skip lists where this rule is disabled by inline config
873            if ctx.inline_config().is_rule_disabled("MD032", start_line) {
874                continue;
875            }
876
877            // Skip lists that start inside HTML/MDX comments
878            if ctx
879                .line_info(start_line)
880                .is_some_and(|info| info.in_html_comment || info.in_mdx_comment)
881            {
882                continue;
883            }
884
885            // Check before block
886            if start_line > 1 {
887                // Look past HTML comments to find actual preceding content
888                let (content_line, has_blank_separation) = Self::find_preceding_content(ctx, start_line);
889
890                // If blank separation exists (through HTML comments), no fix needed
891                if !has_blank_separation && content_line > 0 {
892                    let prev_line_str = lines[content_line - 1];
893                    let is_prev_excluded = ctx
894                        .line_info(content_line)
895                        .is_some_and(|info| info.in_code_block || info.in_front_matter);
896                    let prev_prefix = BLOCKQUOTE_PREFIX_RE.find(prev_line_str).map_or("", |m| m.as_str());
897
898                    let should_require = Self::should_require_blank_line_before(ctx, content_line, start_line);
899                    // Compare trimmed prefixes to handle varying whitespace after > markers
900                    if !is_prev_excluded && prev_prefix.trim() == prefix.trim() && should_require {
901                        // Use centralized helper for consistent blockquote prefix (no trailing space)
902                        let bq_prefix = ctx.blockquote_prefix_for_blank_line(start_line - 1);
903                        insertions.insert(start_line, bq_prefix);
904                    }
905                }
906            }
907
908            // Check after block
909            if end_line < num_lines {
910                // Look past HTML comments to find actual following content
911                let (content_line, has_blank_separation) = Self::find_following_content(ctx, end_line);
912
913                // If blank separation exists (through HTML comments), no fix needed
914                if !has_blank_separation && content_line > 0 {
915                    let next_line_str = lines[content_line - 1];
916                    // Check if next line is excluded - in code block, front matter, or starts an indented code block
917                    let is_next_excluded = ctx
918                        .line_info(content_line)
919                        .is_some_and(|info| info.in_code_block || info.in_front_matter)
920                        || (content_line <= ctx.lines.len()
921                            && ctx.lines[content_line - 1].in_code_block
922                            && ctx.lines[content_line - 1].indent >= 2
923                            && (ctx.lines[content_line - 1]
924                                .content(ctx.content)
925                                .trim()
926                                .starts_with("```")
927                                || ctx.lines[content_line - 1]
928                                    .content(ctx.content)
929                                    .trim()
930                                    .starts_with("~~~")));
931                    let next_prefix = BLOCKQUOTE_PREFIX_RE.find(next_line_str).map_or("", |m| m.as_str());
932
933                    // Check blockquote levels to detect boundary transitions
934                    let end_line_str = lines[end_line - 1];
935                    let end_line_prefix = BLOCKQUOTE_PREFIX_RE.find(end_line_str).map_or("", |m| m.as_str());
936                    let end_line_bq_level = end_line_prefix.chars().filter(|&c| c == '>').count();
937                    let next_line_bq_level = next_prefix.chars().filter(|&c| c == '>').count();
938                    let exits_blockquote = end_line_bq_level > 0 && next_line_bq_level < end_line_bq_level;
939
940                    // Compare trimmed prefixes to handle varying whitespace after > markers
941                    // Skip if exiting a blockquote - boundary provides separation
942                    if !is_next_excluded && next_prefix.trim() == prefix.trim() && !exits_blockquote {
943                        // Use centralized helper for consistent blockquote prefix (no trailing space)
944                        let bq_prefix = ctx.blockquote_prefix_for_blank_line(end_line - 1);
945                        insertions.insert(end_line + 1, bq_prefix);
946                    }
947                }
948            }
949        }
950
951        // Phase 2: Reconstruct with insertions and lazy fixes
952        let mut result_lines: Vec<String> = Vec::with_capacity(num_lines + insertions.len());
953        for (i, line) in lines.iter().enumerate() {
954            let current_line_num = i + 1;
955            if let Some(prefix_to_insert) = insertions.get(&current_line_num)
956                && (result_lines.is_empty() || result_lines.last().unwrap() != prefix_to_insert)
957            {
958                result_lines.push(prefix_to_insert.clone());
959            }
960
961            // Apply lazy continuation fix if needed (skip if rule is disabled for this line)
962            if let Some(lazy_info) = lazy_fixes.get(&current_line_num)
963                && !ctx.inline_config().is_rule_disabled("MD032", current_line_num)
964            {
965                let fixed_line = Self::apply_lazy_fix_to_line(line, lazy_info);
966                result_lines.push(fixed_line);
967            } else {
968                result_lines.push(line.to_string());
969            }
970        }
971
972        // Preserve the final newline if the original content had one
973        let mut result = result_lines.join("\n");
974        if ctx.content.ends_with('\n') {
975            result.push('\n');
976        }
977        result
978    }
979}
980
981// Checks if a line is blank, considering blockquote context
982fn is_blank_in_context(line: &str) -> bool {
983    // A line is blank if it's empty or contains only whitespace,
984    // potentially after removing blockquote markers.
985    if let Some(m) = BLOCKQUOTE_PREFIX_RE.find(line) {
986        // If a blockquote prefix is found, check if the content *after* the prefix is blank.
987        line[m.end()..].trim().is_empty()
988    } else {
989        // No blockquote prefix, check the whole line for blankness.
990        line.trim().is_empty()
991    }
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997    use crate::lint_context::LintContext;
998    use crate::rule::Rule;
999
1000    fn lint(content: &str) -> Vec<LintWarning> {
1001        let rule = MD032BlanksAroundLists::default();
1002        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1003        rule.check(&ctx).expect("Lint check failed")
1004    }
1005
1006    fn fix(content: &str) -> String {
1007        let rule = MD032BlanksAroundLists::default();
1008        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1009        rule.fix(&ctx).expect("Lint fix failed")
1010    }
1011
1012    // Test that warnings include Fix objects
1013    fn check_warnings_have_fixes(content: &str) {
1014        let warnings = lint(content);
1015        for warning in &warnings {
1016            assert!(warning.fix.is_some(), "Warning should have fix: {warning:?}");
1017        }
1018    }
1019
1020    #[test]
1021    fn test_list_at_start() {
1022        // Per markdownlint-cli: trailing text without blank line is treated as lazy continuation
1023        // so NO warning is expected here
1024        let content = "- Item 1\n- Item 2\nText";
1025        let warnings = lint(content);
1026        assert_eq!(
1027            warnings.len(),
1028            0,
1029            "Trailing text is lazy continuation per CommonMark - no warning expected"
1030        );
1031    }
1032
1033    #[test]
1034    fn test_list_at_end() {
1035        let content = "Text\n- Item 1\n- Item 2";
1036        let warnings = lint(content);
1037        assert_eq!(
1038            warnings.len(),
1039            1,
1040            "Expected 1 warning for list at end without preceding blank line"
1041        );
1042        assert_eq!(
1043            warnings[0].line, 2,
1044            "Warning should be on the first line of the list (line 2)"
1045        );
1046        assert!(warnings[0].message.contains("preceded by blank line"));
1047
1048        // Test that warning has fix
1049        check_warnings_have_fixes(content);
1050
1051        let fixed_content = fix(content);
1052        assert_eq!(fixed_content, "Text\n\n- Item 1\n- Item 2");
1053
1054        // Verify fix resolves the issue
1055        let warnings_after_fix = lint(&fixed_content);
1056        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1057    }
1058
1059    #[test]
1060    fn test_list_in_middle() {
1061        // Per markdownlint-cli: only preceding blank line is required
1062        // Trailing text is treated as lazy continuation
1063        let content = "Text 1\n- Item 1\n- Item 2\nText 2";
1064        let warnings = lint(content);
1065        assert_eq!(
1066            warnings.len(),
1067            1,
1068            "Expected 1 warning for list needing preceding blank line (trailing text is lazy continuation)"
1069        );
1070        assert_eq!(warnings[0].line, 2, "Warning on line 2 (start)");
1071        assert!(warnings[0].message.contains("preceded by blank line"));
1072
1073        // Test that warnings have fixes
1074        check_warnings_have_fixes(content);
1075
1076        let fixed_content = fix(content);
1077        assert_eq!(fixed_content, "Text 1\n\n- Item 1\n- Item 2\nText 2");
1078
1079        // Verify fix resolves the issue
1080        let warnings_after_fix = lint(&fixed_content);
1081        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1082    }
1083
1084    #[test]
1085    fn test_correct_spacing() {
1086        let content = "Text 1\n\n- Item 1\n- Item 2\n\nText 2";
1087        let warnings = lint(content);
1088        assert_eq!(warnings.len(), 0, "Expected no warnings for correctly spaced list");
1089
1090        let fixed_content = fix(content);
1091        assert_eq!(fixed_content, content, "Fix should not change correctly spaced content");
1092    }
1093
1094    #[test]
1095    fn test_list_with_content() {
1096        // Per markdownlint-cli: only preceding blank line warning
1097        // Trailing text is lazy continuation
1098        let content = "Text\n* Item 1\n  Content\n* Item 2\n  More content\nText";
1099        let warnings = lint(content);
1100        assert_eq!(
1101            warnings.len(),
1102            1,
1103            "Expected 1 warning for list needing preceding blank line. Got: {warnings:?}"
1104        );
1105        assert_eq!(warnings[0].line, 2, "Warning should be on line 2 (start)");
1106        assert!(warnings[0].message.contains("preceded by blank line"));
1107
1108        // Test that warnings have fixes
1109        check_warnings_have_fixes(content);
1110
1111        let fixed_content = fix(content);
1112        let expected_fixed = "Text\n\n* Item 1\n  Content\n* Item 2\n  More content\nText";
1113        assert_eq!(
1114            fixed_content, expected_fixed,
1115            "Fix did not produce the expected output. Got:\n{fixed_content}"
1116        );
1117
1118        // Verify fix resolves the issue
1119        let warnings_after_fix = lint(&fixed_content);
1120        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1121    }
1122
1123    #[test]
1124    fn test_nested_list() {
1125        // Per markdownlint-cli: only preceding blank line warning
1126        let content = "Text\n- Item 1\n  - Nested 1\n- Item 2\nText";
1127        let warnings = lint(content);
1128        assert_eq!(
1129            warnings.len(),
1130            1,
1131            "Nested list block needs preceding blank only. Got: {warnings:?}"
1132        );
1133        assert_eq!(warnings[0].line, 2);
1134        assert!(warnings[0].message.contains("preceded by blank line"));
1135
1136        // Test that warnings have fixes
1137        check_warnings_have_fixes(content);
1138
1139        let fixed_content = fix(content);
1140        assert_eq!(fixed_content, "Text\n\n- Item 1\n  - Nested 1\n- Item 2\nText");
1141
1142        // Verify fix resolves the issue
1143        let warnings_after_fix = lint(&fixed_content);
1144        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1145    }
1146
1147    #[test]
1148    fn test_list_with_internal_blanks() {
1149        // Per markdownlint-cli: only preceding blank line warning
1150        let content = "Text\n* Item 1\n\n  More Item 1 Content\n* Item 2\nText";
1151        let warnings = lint(content);
1152        assert_eq!(
1153            warnings.len(),
1154            1,
1155            "List with internal blanks needs preceding blank only. Got: {warnings:?}"
1156        );
1157        assert_eq!(warnings[0].line, 2);
1158        assert!(warnings[0].message.contains("preceded by blank line"));
1159
1160        // Test that warnings have fixes
1161        check_warnings_have_fixes(content);
1162
1163        let fixed_content = fix(content);
1164        assert_eq!(
1165            fixed_content,
1166            "Text\n\n* Item 1\n\n  More Item 1 Content\n* Item 2\nText"
1167        );
1168
1169        // Verify fix resolves the issue
1170        let warnings_after_fix = lint(&fixed_content);
1171        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1172    }
1173
1174    #[test]
1175    fn test_ignore_code_blocks() {
1176        let content = "```\n- Not a list item\n```\nText";
1177        let warnings = lint(content);
1178        assert_eq!(warnings.len(), 0);
1179        let fixed_content = fix(content);
1180        assert_eq!(fixed_content, content);
1181    }
1182
1183    #[test]
1184    fn test_ignore_front_matter() {
1185        // Per markdownlint-cli: NO warnings - front matter is followed by list, trailing text is lazy continuation
1186        let content = "---\ntitle: Test\n---\n- List Item\nText";
1187        let warnings = lint(content);
1188        assert_eq!(
1189            warnings.len(),
1190            0,
1191            "Front matter test should have no MD032 warnings. Got: {warnings:?}"
1192        );
1193
1194        // No fixes needed since no warnings
1195        let fixed_content = fix(content);
1196        assert_eq!(fixed_content, content, "No changes when no warnings");
1197    }
1198
1199    #[test]
1200    fn test_multiple_lists() {
1201        // Our implementation treats "Text 2" and "Text 3" as lazy continuation within a single merged list block
1202        // (since both - and * are unordered markers and there's no structural separator)
1203        // markdownlint-cli sees them as separate lists with 3 warnings, but our behavior differs.
1204        // The key requirement is that the fix resolves all warnings.
1205        let content = "Text\n- List 1 Item 1\n- List 1 Item 2\nText 2\n* List 2 Item 1\nText 3";
1206        let warnings = lint(content);
1207        // At minimum we should warn about missing preceding blank for line 2
1208        assert!(
1209            !warnings.is_empty(),
1210            "Should have at least one warning for missing blank line. Got: {warnings:?}"
1211        );
1212
1213        // Test that warnings have fixes
1214        check_warnings_have_fixes(content);
1215
1216        let fixed_content = fix(content);
1217        // The fix should add blank lines before lists that need them
1218        let warnings_after_fix = lint(&fixed_content);
1219        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1220    }
1221
1222    #[test]
1223    fn test_adjacent_lists() {
1224        let content = "- List 1\n\n* List 2";
1225        let warnings = lint(content);
1226        assert_eq!(warnings.len(), 0);
1227        let fixed_content = fix(content);
1228        assert_eq!(fixed_content, content);
1229    }
1230
1231    #[test]
1232    fn test_list_in_blockquote() {
1233        // Per markdownlint-cli: 1 warning (preceding only, trailing is lazy continuation)
1234        let content = "> Quote line 1\n> - List item 1\n> - List item 2\n> Quote line 2";
1235        let warnings = lint(content);
1236        assert_eq!(
1237            warnings.len(),
1238            1,
1239            "Expected 1 warning for blockquoted list needing preceding blank. Got: {warnings:?}"
1240        );
1241        assert_eq!(warnings[0].line, 2);
1242
1243        // Test that warnings have fixes
1244        check_warnings_have_fixes(content);
1245
1246        let fixed_content = fix(content);
1247        // Fix should add blank line before list only (no trailing space per markdownlint-cli)
1248        assert_eq!(
1249            fixed_content, "> Quote line 1\n>\n> - List item 1\n> - List item 2\n> Quote line 2",
1250            "Fix for blockquoted list failed. Got:\n{fixed_content}"
1251        );
1252
1253        // Verify fix resolves the issue
1254        let warnings_after_fix = lint(&fixed_content);
1255        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1256    }
1257
1258    #[test]
1259    fn test_ordered_list() {
1260        // Per markdownlint-cli: 1 warning (preceding only)
1261        let content = "Text\n1. Item 1\n2. Item 2\nText";
1262        let warnings = lint(content);
1263        assert_eq!(warnings.len(), 1);
1264
1265        // Test that warnings have fixes
1266        check_warnings_have_fixes(content);
1267
1268        let fixed_content = fix(content);
1269        assert_eq!(fixed_content, "Text\n\n1. Item 1\n2. Item 2\nText");
1270
1271        // Verify fix resolves the issue
1272        let warnings_after_fix = lint(&fixed_content);
1273        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1274    }
1275
1276    #[test]
1277    fn test_no_double_blank_fix() {
1278        // Per markdownlint-cli: trailing text is lazy continuation, so NO warning needed
1279        let content = "Text\n\n- Item 1\n- Item 2\nText"; // Has preceding blank, trailing is lazy
1280        let warnings = lint(content);
1281        assert_eq!(
1282            warnings.len(),
1283            0,
1284            "Should have no warnings - properly preceded, trailing is lazy"
1285        );
1286
1287        let fixed_content = fix(content);
1288        assert_eq!(
1289            fixed_content, content,
1290            "No fix needed when no warnings. Got:\n{fixed_content}"
1291        );
1292
1293        let content2 = "Text\n- Item 1\n- Item 2\n\nText"; // Missing blank before
1294        let warnings2 = lint(content2);
1295        assert_eq!(warnings2.len(), 1);
1296        if !warnings2.is_empty() {
1297            assert_eq!(
1298                warnings2[0].line, 2,
1299                "Warning line for missing blank before should be the first line of the block"
1300            );
1301        }
1302
1303        // Test that warnings have fixes
1304        check_warnings_have_fixes(content2);
1305
1306        let fixed_content2 = fix(content2);
1307        assert_eq!(
1308            fixed_content2, "Text\n\n- Item 1\n- Item 2\n\nText",
1309            "Fix added extra blank before. Got:\n{fixed_content2}"
1310        );
1311    }
1312
1313    #[test]
1314    fn test_empty_input() {
1315        let content = "";
1316        let warnings = lint(content);
1317        assert_eq!(warnings.len(), 0);
1318        let fixed_content = fix(content);
1319        assert_eq!(fixed_content, "");
1320    }
1321
1322    #[test]
1323    fn test_only_list() {
1324        let content = "- Item 1\n- Item 2";
1325        let warnings = lint(content);
1326        assert_eq!(warnings.len(), 0);
1327        let fixed_content = fix(content);
1328        assert_eq!(fixed_content, content);
1329    }
1330
1331    // === COMPREHENSIVE FIX TESTS ===
1332
1333    #[test]
1334    fn test_fix_complex_nested_blockquote() {
1335        // Per markdownlint-cli: 1 warning (preceding only)
1336        let content = "> Text before\n> - Item 1\n>   - Nested item\n> - Item 2\n> Text after";
1337        let warnings = lint(content);
1338        assert_eq!(
1339            warnings.len(),
1340            1,
1341            "Should warn for missing preceding blank only. Got: {warnings:?}"
1342        );
1343
1344        // Test that warnings have fixes
1345        check_warnings_have_fixes(content);
1346
1347        let fixed_content = fix(content);
1348        // Per markdownlint-cli, blank lines in blockquotes have no trailing space
1349        let expected = "> Text before\n>\n> - Item 1\n>   - Nested item\n> - Item 2\n> Text after";
1350        assert_eq!(fixed_content, expected, "Fix should preserve blockquote structure");
1351
1352        let warnings_after_fix = lint(&fixed_content);
1353        assert_eq!(warnings_after_fix.len(), 0, "Fix should eliminate all warnings");
1354    }
1355
1356    #[test]
1357    fn test_fix_mixed_list_markers() {
1358        // Per markdownlint-cli: mixed markers may be treated as separate lists
1359        // The exact behavior depends on implementation details
1360        let content = "Text\n- Item 1\n* Item 2\n+ Item 3\nText";
1361        let warnings = lint(content);
1362        // At minimum, there should be a warning for the first list needing preceding blank
1363        assert!(
1364            !warnings.is_empty(),
1365            "Should have at least 1 warning for mixed marker list. Got: {warnings:?}"
1366        );
1367
1368        // Test that warnings have fixes
1369        check_warnings_have_fixes(content);
1370
1371        let fixed_content = fix(content);
1372        // The fix should add at least a blank line before the first list
1373        assert!(
1374            fixed_content.contains("Text\n\n-"),
1375            "Fix should add blank line before first list item"
1376        );
1377
1378        // Verify fix resolves the issue
1379        let warnings_after_fix = lint(&fixed_content);
1380        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1381    }
1382
1383    #[test]
1384    fn test_fix_ordered_list_with_different_numbers() {
1385        // Per markdownlint-cli: 1 warning (preceding only)
1386        let content = "Text\n1. First\n3. Third\n2. Second\nText";
1387        let warnings = lint(content);
1388        assert_eq!(warnings.len(), 1, "Should warn for missing preceding blank only");
1389
1390        // Test that warnings have fixes
1391        check_warnings_have_fixes(content);
1392
1393        let fixed_content = fix(content);
1394        let expected = "Text\n\n1. First\n3. Third\n2. Second\nText";
1395        assert_eq!(
1396            fixed_content, expected,
1397            "Fix should handle ordered lists with non-sequential numbers"
1398        );
1399
1400        // Verify fix resolves the issue
1401        let warnings_after_fix = lint(&fixed_content);
1402        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1403    }
1404
1405    #[test]
1406    fn test_fix_list_with_code_blocks_inside() {
1407        // Per markdownlint-cli: 1 warning (preceding only)
1408        let content = "Text\n- Item 1\n  ```\n  code\n  ```\n- Item 2\nText";
1409        let warnings = lint(content);
1410        assert_eq!(warnings.len(), 1, "Should warn for missing preceding blank only");
1411
1412        // Test that warnings have fixes
1413        check_warnings_have_fixes(content);
1414
1415        let fixed_content = fix(content);
1416        let expected = "Text\n\n- Item 1\n  ```\n  code\n  ```\n- Item 2\nText";
1417        assert_eq!(
1418            fixed_content, expected,
1419            "Fix should handle lists with internal code blocks"
1420        );
1421
1422        // Verify fix resolves the issue
1423        let warnings_after_fix = lint(&fixed_content);
1424        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1425    }
1426
1427    #[test]
1428    fn test_fix_deeply_nested_lists() {
1429        // Per markdownlint-cli: 1 warning (preceding only)
1430        let content = "Text\n- Level 1\n  - Level 2\n    - Level 3\n      - Level 4\n- Back to Level 1\nText";
1431        let warnings = lint(content);
1432        assert_eq!(warnings.len(), 1, "Should warn for missing preceding blank only");
1433
1434        // Test that warnings have fixes
1435        check_warnings_have_fixes(content);
1436
1437        let fixed_content = fix(content);
1438        let expected = "Text\n\n- Level 1\n  - Level 2\n    - Level 3\n      - Level 4\n- Back to Level 1\nText";
1439        assert_eq!(fixed_content, expected, "Fix should handle deeply nested lists");
1440
1441        // Verify fix resolves the issue
1442        let warnings_after_fix = lint(&fixed_content);
1443        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1444    }
1445
1446    #[test]
1447    fn test_fix_list_with_multiline_items() {
1448        // Per markdownlint-cli: trailing "Text" at indent=0 is lazy continuation
1449        // Only the preceding blank line is required
1450        let content = "Text\n- Item 1\n  continues here\n  and here\n- Item 2\n  also continues\nText";
1451        let warnings = lint(content);
1452        assert_eq!(
1453            warnings.len(),
1454            1,
1455            "Should only warn for missing blank before list (trailing text is lazy continuation)"
1456        );
1457
1458        // Test that warnings have fixes
1459        check_warnings_have_fixes(content);
1460
1461        let fixed_content = fix(content);
1462        let expected = "Text\n\n- Item 1\n  continues here\n  and here\n- Item 2\n  also continues\nText";
1463        assert_eq!(fixed_content, expected, "Fix should add blank before list only");
1464
1465        // Verify fix resolves the issue
1466        let warnings_after_fix = lint(&fixed_content);
1467        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1468    }
1469
1470    #[test]
1471    fn test_fix_list_at_document_boundaries() {
1472        // List at very start
1473        let content1 = "- Item 1\n- Item 2";
1474        let warnings1 = lint(content1);
1475        assert_eq!(
1476            warnings1.len(),
1477            0,
1478            "List at document start should not need blank before"
1479        );
1480        let fixed1 = fix(content1);
1481        assert_eq!(fixed1, content1, "No fix needed for list at start");
1482
1483        // List at very end
1484        let content2 = "Text\n- Item 1\n- Item 2";
1485        let warnings2 = lint(content2);
1486        assert_eq!(warnings2.len(), 1, "List at document end should need blank before");
1487        check_warnings_have_fixes(content2);
1488        let fixed2 = fix(content2);
1489        assert_eq!(
1490            fixed2, "Text\n\n- Item 1\n- Item 2",
1491            "Should add blank before list at end"
1492        );
1493    }
1494
1495    #[test]
1496    fn test_fix_preserves_existing_blank_lines() {
1497        let content = "Text\n\n\n- Item 1\n- Item 2\n\n\nText";
1498        let warnings = lint(content);
1499        assert_eq!(warnings.len(), 0, "Multiple blank lines should be preserved");
1500        let fixed_content = fix(content);
1501        assert_eq!(fixed_content, content, "Fix should not modify already correct content");
1502    }
1503
1504    #[test]
1505    fn test_fix_handles_tabs_and_spaces() {
1506        // Tab at line start = 4 spaces = indented code (not a list item per CommonMark)
1507        // Only the space-indented line is a real list item
1508        let content = "Text\n\t- Item with tab\n  - Item with spaces\nText";
1509        let warnings = lint(content);
1510        // Per markdownlint-cli: only line 3 (space-indented) is a list needing blanks
1511        assert!(!warnings.is_empty(), "Should warn for missing blank before list");
1512
1513        // Test that warnings have fixes
1514        check_warnings_have_fixes(content);
1515
1516        let fixed_content = fix(content);
1517        // Add blank before the actual list item (line 3), not the tab-indented code (line 2)
1518        // Trailing text is lazy continuation, so no blank after
1519        let expected = "Text\n\t- Item with tab\n\n  - Item with spaces\nText";
1520        assert_eq!(fixed_content, expected, "Fix should add blank before list item");
1521
1522        // Verify fix resolves the issue
1523        let warnings_after_fix = lint(&fixed_content);
1524        assert_eq!(warnings_after_fix.len(), 0, "Fix should resolve all warnings");
1525    }
1526
1527    #[test]
1528    fn test_fix_warning_objects_have_correct_ranges() {
1529        // Per markdownlint-cli: trailing text is lazy continuation, only 1 warning
1530        let content = "Text\n- Item 1\n- Item 2\nText";
1531        let warnings = lint(content);
1532        assert_eq!(warnings.len(), 1, "Only preceding blank warning expected");
1533
1534        // Check that each warning has a fix with a valid range
1535        for warning in &warnings {
1536            assert!(warning.fix.is_some(), "Warning should have fix");
1537            let fix = warning.fix.as_ref().unwrap();
1538            assert!(fix.range.start <= fix.range.end, "Fix range should be valid");
1539            assert!(
1540                !fix.replacement.is_empty() || fix.range.start == fix.range.end,
1541                "Fix should have replacement or be insertion"
1542            );
1543        }
1544    }
1545
1546    #[test]
1547    fn test_fix_idempotent() {
1548        // Per markdownlint-cli: trailing text is lazy continuation
1549        let content = "Text\n- Item 1\n- Item 2\nText";
1550
1551        // Apply fix once - only adds blank before (trailing text is lazy continuation)
1552        let fixed_once = fix(content);
1553        assert_eq!(fixed_once, "Text\n\n- Item 1\n- Item 2\nText");
1554
1555        // Apply fix again - should be unchanged
1556        let fixed_twice = fix(&fixed_once);
1557        assert_eq!(fixed_twice, fixed_once, "Fix should be idempotent");
1558
1559        // No warnings after fix
1560        let warnings_after_fix = lint(&fixed_once);
1561        assert_eq!(warnings_after_fix.len(), 0, "No warnings should remain after fix");
1562    }
1563
1564    #[test]
1565    fn test_fix_with_normalized_line_endings() {
1566        // In production, content is normalized to LF at I/O boundary
1567        // Unit tests should use LF input to reflect actual runtime behavior
1568        // Per markdownlint-cli: trailing text is lazy continuation, only 1 warning
1569        let content = "Text\n- Item 1\n- Item 2\nText";
1570        let warnings = lint(content);
1571        assert_eq!(warnings.len(), 1, "Should detect missing blank before list");
1572
1573        // Test that warnings have fixes
1574        check_warnings_have_fixes(content);
1575
1576        let fixed_content = fix(content);
1577        // Only adds blank before (trailing text is lazy continuation)
1578        let expected = "Text\n\n- Item 1\n- Item 2\nText";
1579        assert_eq!(fixed_content, expected, "Fix should work with normalized LF content");
1580    }
1581
1582    #[test]
1583    fn test_fix_preserves_final_newline() {
1584        // Per markdownlint-cli: trailing text is lazy continuation
1585        // Test with final newline
1586        let content_with_newline = "Text\n- Item 1\n- Item 2\nText\n";
1587        let fixed_with_newline = fix(content_with_newline);
1588        assert!(
1589            fixed_with_newline.ends_with('\n'),
1590            "Fix should preserve final newline when present"
1591        );
1592        // Only adds blank before (trailing text is lazy continuation)
1593        assert_eq!(fixed_with_newline, "Text\n\n- Item 1\n- Item 2\nText\n");
1594
1595        // Test without final newline
1596        let content_without_newline = "Text\n- Item 1\n- Item 2\nText";
1597        let fixed_without_newline = fix(content_without_newline);
1598        assert!(
1599            !fixed_without_newline.ends_with('\n'),
1600            "Fix should not add final newline when not present"
1601        );
1602        // Only adds blank before (trailing text is lazy continuation)
1603        assert_eq!(fixed_without_newline, "Text\n\n- Item 1\n- Item 2\nText");
1604    }
1605
1606    #[test]
1607    fn test_fix_multiline_list_items_no_indent() {
1608        let content = "## Configuration\n\nThis rule has the following configuration options:\n\n- `option1`: Description that continues\non the next line without indentation.\n- `option2`: Another description that also continues\non the next line.\n\n## Next Section";
1609
1610        let warnings = lint(content);
1611        // Should only warn about missing blank lines around the entire list, not between items
1612        assert_eq!(
1613            warnings.len(),
1614            0,
1615            "Should not warn for properly formatted list with multi-line items. Got: {warnings:?}"
1616        );
1617
1618        let fixed_content = fix(content);
1619        // Should not change the content since it's already correct
1620        assert_eq!(
1621            fixed_content, content,
1622            "Should not modify correctly formatted multi-line list items"
1623        );
1624    }
1625
1626    #[test]
1627    fn test_nested_list_with_lazy_continuation() {
1628        // Issue #188: Nested list following a lazy continuation line should not require blank lines
1629        // This matches markdownlint-cli behavior which does NOT warn on this pattern
1630        //
1631        // The key element is line 6 (`!=`), ternary...) which is a lazy continuation of line 5.
1632        // Line 6 contains `||` inside code spans, which should NOT be detected as a table separator.
1633        let content = r#"# Test
1634
1635- **Token Dispatch (Phase 3.2)**: COMPLETE. Extracts tokens from both:
1636  1. Switch/case dispatcher statements (original Phase 3.2)
1637  2. Inline conditionals - if/else, bitwise checks (`&`, `|`), comparison (`==`,
1638`!=`), ternary operators (`?:`), macros (`ISTOK`, `ISUNSET`), compound conditions (`&&`, `||`) (Phase 3.2.1)
1639     - 30 explicit tokens extracted, 23 dispatcher rules with embedded token
1640       references"#;
1641
1642        let warnings = lint(content);
1643        // No MD032 warnings should be generated - this is a valid nested list structure
1644        // with lazy continuation (line 6 has no indent but continues line 5)
1645        let md032_warnings: Vec<_> = warnings
1646            .iter()
1647            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1648            .collect();
1649        assert_eq!(
1650            md032_warnings.len(),
1651            0,
1652            "Should not warn for nested list with lazy continuation. Got: {md032_warnings:?}"
1653        );
1654    }
1655
1656    #[test]
1657    fn test_pipes_in_code_spans_not_detected_as_table() {
1658        // Pipes inside code spans should NOT break lists
1659        let content = r#"# Test
1660
1661- Item with `a | b` inline code
1662  - Nested item should work
1663
1664"#;
1665
1666        let warnings = lint(content);
1667        let md032_warnings: Vec<_> = warnings
1668            .iter()
1669            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1670            .collect();
1671        assert_eq!(
1672            md032_warnings.len(),
1673            0,
1674            "Pipes in code spans should not break lists. Got: {md032_warnings:?}"
1675        );
1676    }
1677
1678    #[test]
1679    fn test_multiple_code_spans_with_pipes() {
1680        // Multiple code spans with pipes should not break lists
1681        let content = r#"# Test
1682
1683- Item with `a | b` and `c || d` operators
1684  - Nested item should work
1685
1686"#;
1687
1688        let warnings = lint(content);
1689        let md032_warnings: Vec<_> = warnings
1690            .iter()
1691            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1692            .collect();
1693        assert_eq!(
1694            md032_warnings.len(),
1695            0,
1696            "Multiple code spans with pipes should not break lists. Got: {md032_warnings:?}"
1697        );
1698    }
1699
1700    #[test]
1701    fn test_actual_table_breaks_list() {
1702        // An actual table between list items SHOULD break the list
1703        let content = r#"# Test
1704
1705- Item before table
1706
1707| Col1 | Col2 |
1708|------|------|
1709| A    | B    |
1710
1711- Item after table
1712
1713"#;
1714
1715        let warnings = lint(content);
1716        // There should be NO MD032 warnings because both lists are properly surrounded by blank lines
1717        let md032_warnings: Vec<_> = warnings
1718            .iter()
1719            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1720            .collect();
1721        assert_eq!(
1722            md032_warnings.len(),
1723            0,
1724            "Both lists should be properly separated by blank lines. Got: {md032_warnings:?}"
1725        );
1726    }
1727
1728    #[test]
1729    fn test_thematic_break_not_lazy_continuation() {
1730        // Thematic breaks (HRs) cannot be lazy continuation per CommonMark
1731        // List followed by HR without blank line should warn
1732        let content = r#"- Item 1
1733- Item 2
1734***
1735
1736More text.
1737"#;
1738
1739        let warnings = lint(content);
1740        let md032_warnings: Vec<_> = warnings
1741            .iter()
1742            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1743            .collect();
1744        assert_eq!(
1745            md032_warnings.len(),
1746            1,
1747            "Should warn for list not followed by blank line before thematic break. Got: {md032_warnings:?}"
1748        );
1749        assert!(
1750            md032_warnings[0].message.contains("followed by blank line"),
1751            "Warning should be about missing blank after list"
1752        );
1753    }
1754
1755    #[test]
1756    fn test_thematic_break_with_blank_line() {
1757        // List followed by blank line then HR should NOT warn
1758        let content = r#"- Item 1
1759- Item 2
1760
1761***
1762
1763More text.
1764"#;
1765
1766        let warnings = lint(content);
1767        let md032_warnings: Vec<_> = warnings
1768            .iter()
1769            .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1770            .collect();
1771        assert_eq!(
1772            md032_warnings.len(),
1773            0,
1774            "Should not warn when list is properly followed by blank line. Got: {md032_warnings:?}"
1775        );
1776    }
1777
1778    #[test]
1779    fn test_various_thematic_break_styles() {
1780        // Test different HR styles are all recognized
1781        // Note: Spaced styles like "- - -" and "* * *" are excluded because they start
1782        // with list markers ("- " or "* ") which get parsed as list items by the
1783        // upstream CommonMark parser. That's a separate parsing issue.
1784        for hr in ["---", "***", "___"] {
1785            let content = format!(
1786                r#"- Item 1
1787- Item 2
1788{hr}
1789
1790More text.
1791"#
1792            );
1793
1794            let warnings = lint(&content);
1795            let md032_warnings: Vec<_> = warnings
1796                .iter()
1797                .filter(|w| w.rule_name.as_deref() == Some("MD032"))
1798                .collect();
1799            assert_eq!(
1800                md032_warnings.len(),
1801                1,
1802                "Should warn for HR style '{hr}' without blank line. Got: {md032_warnings:?}"
1803            );
1804        }
1805    }
1806
1807    // === LAZY CONTINUATION TESTS ===
1808
1809    fn lint_with_config(content: &str, config: MD032Config) -> Vec<LintWarning> {
1810        let rule = MD032BlanksAroundLists::from_config_struct(config);
1811        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1812        rule.check(&ctx).expect("Lint check failed")
1813    }
1814
1815    fn fix_with_config(content: &str, config: MD032Config) -> String {
1816        let rule = MD032BlanksAroundLists::from_config_struct(config);
1817        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1818        rule.fix(&ctx).expect("Lint fix failed")
1819    }
1820
1821    #[test]
1822    fn test_lazy_continuation_allowed_by_default() {
1823        // Default behavior: lazy continuation is allowed, no warning
1824        let content = "# Heading\n\n1. List\nSome text.";
1825        let warnings = lint(content);
1826        assert_eq!(
1827            warnings.len(),
1828            0,
1829            "Default behavior should allow lazy continuation. Got: {warnings:?}"
1830        );
1831    }
1832
1833    #[test]
1834    fn test_lazy_continuation_disallowed() {
1835        // With allow_lazy_continuation = false, should warn about lazy continuation
1836        let content = "# Heading\n\n1. List\nSome text.";
1837        let config = MD032Config {
1838            allow_lazy_continuation: false,
1839        };
1840        let warnings = lint_with_config(content, config);
1841        assert_eq!(
1842            warnings.len(),
1843            1,
1844            "Should warn when lazy continuation is disallowed. Got: {warnings:?}"
1845        );
1846        assert!(
1847            warnings[0].message.contains("Lazy continuation"),
1848            "Warning message should mention lazy continuation"
1849        );
1850        assert_eq!(warnings[0].line, 4, "Warning should be on the lazy line");
1851    }
1852
1853    #[test]
1854    fn test_lazy_continuation_fix() {
1855        // With allow_lazy_continuation = false, fix should add proper indentation
1856        let content = "# Heading\n\n1. List\nSome text.";
1857        let config = MD032Config {
1858            allow_lazy_continuation: false,
1859        };
1860        let fixed = fix_with_config(content, config.clone());
1861        // Fix adds proper indentation (3 spaces for "1. " marker width)
1862        assert_eq!(
1863            fixed, "# Heading\n\n1. List\n   Some text.",
1864            "Fix should add proper indentation to lazy continuation"
1865        );
1866
1867        // Verify no warnings after fix
1868        let warnings_after = lint_with_config(&fixed, config);
1869        assert_eq!(warnings_after.len(), 0, "No warnings should remain after fix");
1870    }
1871
1872    #[test]
1873    fn test_lazy_continuation_multiple_lines() {
1874        // Multiple lazy continuation lines - each gets its own warning
1875        let content = "- Item 1\nLine 2\nLine 3";
1876        let config = MD032Config {
1877            allow_lazy_continuation: false,
1878        };
1879        let warnings = lint_with_config(content, config.clone());
1880        // Both Line 2 and Line 3 are lazy continuation lines
1881        assert_eq!(
1882            warnings.len(),
1883            2,
1884            "Should warn for each lazy continuation line. Got: {warnings:?}"
1885        );
1886
1887        let fixed = fix_with_config(content, config.clone());
1888        // Fix adds proper indentation (2 spaces for "- " marker)
1889        assert_eq!(
1890            fixed, "- Item 1\n  Line 2\n  Line 3",
1891            "Fix should add proper indentation to lazy continuation lines"
1892        );
1893
1894        // Verify no warnings after fix
1895        let warnings_after = lint_with_config(&fixed, config);
1896        assert_eq!(warnings_after.len(), 0, "No warnings should remain after fix");
1897    }
1898
1899    #[test]
1900    fn test_lazy_continuation_with_indented_content() {
1901        // Indented content is valid continuation, not lazy continuation
1902        let content = "- Item 1\n  Indented content\nLazy text";
1903        let config = MD032Config {
1904            allow_lazy_continuation: false,
1905        };
1906        let warnings = lint_with_config(content, config);
1907        assert_eq!(
1908            warnings.len(),
1909            1,
1910            "Should warn for lazy text after indented content. Got: {warnings:?}"
1911        );
1912    }
1913
1914    #[test]
1915    fn test_lazy_continuation_properly_separated() {
1916        // With proper blank line, no warning even with strict config
1917        let content = "- Item 1\n\nSome text.";
1918        let config = MD032Config {
1919            allow_lazy_continuation: false,
1920        };
1921        let warnings = lint_with_config(content, config);
1922        assert_eq!(
1923            warnings.len(),
1924            0,
1925            "Should not warn when list is properly followed by blank line. Got: {warnings:?}"
1926        );
1927    }
1928
1929    // ==================== Comprehensive edge case tests ====================
1930
1931    #[test]
1932    fn test_lazy_continuation_ordered_list_parenthesis_marker() {
1933        // Ordered list with parenthesis marker (1) instead of period
1934        let content = "1) First item\nLazy continuation";
1935        let config = MD032Config {
1936            allow_lazy_continuation: false,
1937        };
1938        let warnings = lint_with_config(content, config.clone());
1939        assert_eq!(
1940            warnings.len(),
1941            1,
1942            "Should warn for lazy continuation with parenthesis marker"
1943        );
1944
1945        let fixed = fix_with_config(content, config);
1946        // Fix adds proper indentation (3 spaces for "1) " marker)
1947        assert_eq!(fixed, "1) First item\n   Lazy continuation");
1948    }
1949
1950    #[test]
1951    fn test_lazy_continuation_followed_by_another_list() {
1952        // Lazy continuation text followed by another list item
1953        // In CommonMark, "Some text" becomes part of Item 1's lazy continuation,
1954        // and "- Item 2" starts a new list item within the same list.
1955        // With allow_lazy_continuation = false, we warn about lazy continuation
1956        // even within valid list structure (issue #295).
1957        let content = "- Item 1\nSome text\n- Item 2";
1958        let config = MD032Config {
1959            allow_lazy_continuation: false,
1960        };
1961        let warnings = lint_with_config(content, config);
1962        // Should warn about lazy continuation on line 2
1963        assert_eq!(
1964            warnings.len(),
1965            1,
1966            "Should warn about lazy continuation within list. Got: {warnings:?}"
1967        );
1968        assert!(
1969            warnings[0].message.contains("Lazy continuation"),
1970            "Warning should be about lazy continuation"
1971        );
1972        assert_eq!(warnings[0].line, 2, "Warning should be on line 2");
1973    }
1974
1975    #[test]
1976    fn test_lazy_continuation_multiple_in_document() {
1977        // Loose list (blank line between items) with lazy continuation
1978        // In CommonMark, this is a single loose list, not two separate lists.
1979        // "Lazy 1" is lazy continuation of Item 1
1980        // "Lazy 2" is lazy continuation of Item 2
1981        let content = "- Item 1\nLazy 1\n\n- Item 2\nLazy 2";
1982        let config = MD032Config {
1983            allow_lazy_continuation: false,
1984        };
1985        let warnings = lint_with_config(content, config.clone());
1986        // Expect 2 warnings for both lazy continuation lines
1987        assert_eq!(
1988            warnings.len(),
1989            2,
1990            "Should warn for both lazy continuations. Got: {warnings:?}"
1991        );
1992
1993        let fixed = fix_with_config(content, config.clone());
1994        // Auto-fix should add proper indentation to both lazy continuation lines
1995        assert!(
1996            fixed.contains("  Lazy 1"),
1997            "Fixed content should have indented 'Lazy 1'. Got: {fixed:?}"
1998        );
1999        assert!(
2000            fixed.contains("  Lazy 2"),
2001            "Fixed content should have indented 'Lazy 2'. Got: {fixed:?}"
2002        );
2003
2004        let warnings_after = lint_with_config(&fixed, config);
2005        // No warnings after fix: both lazy lines are properly indented
2006        assert_eq!(
2007            warnings_after.len(),
2008            0,
2009            "All warnings should be fixed after auto-fix. Got: {warnings_after:?}"
2010        );
2011    }
2012
2013    #[test]
2014    fn test_lazy_continuation_end_of_document_no_newline() {
2015        // Lazy continuation at end of document without trailing newline
2016        let content = "- Item\nNo trailing newline";
2017        let config = MD032Config {
2018            allow_lazy_continuation: false,
2019        };
2020        let warnings = lint_with_config(content, config.clone());
2021        assert_eq!(warnings.len(), 1, "Should warn even at end of document");
2022
2023        let fixed = fix_with_config(content, config);
2024        // Fix adds proper indentation (2 spaces for "- " marker)
2025        assert_eq!(fixed, "- Item\n  No trailing newline");
2026    }
2027
2028    #[test]
2029    fn test_lazy_continuation_thematic_break_still_needs_blank() {
2030        // Thematic break after list without blank line still triggers MD032
2031        // The thematic break ends the list, but MD032 requires blank line separation
2032        let content = "- Item 1\n---";
2033        let config = MD032Config {
2034            allow_lazy_continuation: false,
2035        };
2036        let warnings = lint_with_config(content, config.clone());
2037        // Should warn because list needs blank line before thematic break
2038        assert_eq!(
2039            warnings.len(),
2040            1,
2041            "List should need blank line before thematic break. Got: {warnings:?}"
2042        );
2043
2044        // Verify fix adds blank line
2045        let fixed = fix_with_config(content, config);
2046        assert_eq!(fixed, "- Item 1\n\n---");
2047    }
2048
2049    #[test]
2050    fn test_lazy_continuation_heading_not_flagged() {
2051        // Heading after list should NOT be flagged as lazy continuation
2052        // (headings end lists per CommonMark)
2053        let content = "- Item 1\n# Heading";
2054        let config = MD032Config {
2055            allow_lazy_continuation: false,
2056        };
2057        let warnings = lint_with_config(content, config);
2058        // The warning should be about missing blank line, not lazy continuation
2059        // But headings interrupt lists, so the list ends at Item 1
2060        assert!(
2061            warnings.iter().all(|w| !w.message.contains("lazy")),
2062            "Heading should not trigger lazy continuation warning"
2063        );
2064    }
2065
2066    #[test]
2067    fn test_lazy_continuation_mixed_list_types() {
2068        // Mixed ordered and unordered with lazy continuation
2069        let content = "- Unordered\n1. Ordered\nLazy text";
2070        let config = MD032Config {
2071            allow_lazy_continuation: false,
2072        };
2073        let warnings = lint_with_config(content, config.clone());
2074        assert!(!warnings.is_empty(), "Should warn about structure issues");
2075    }
2076
2077    #[test]
2078    fn test_lazy_continuation_deep_nesting() {
2079        // Deep nested list with lazy continuation at end
2080        let content = "- Level 1\n  - Level 2\n    - Level 3\nLazy at root";
2081        let config = MD032Config {
2082            allow_lazy_continuation: false,
2083        };
2084        let warnings = lint_with_config(content, config.clone());
2085        assert!(
2086            !warnings.is_empty(),
2087            "Should warn about lazy continuation after nested list"
2088        );
2089
2090        let fixed = fix_with_config(content, config.clone());
2091        let warnings_after = lint_with_config(&fixed, config);
2092        assert_eq!(warnings_after.len(), 0, "No warnings should remain after fix");
2093    }
2094
2095    #[test]
2096    fn test_lazy_continuation_with_emphasis_in_text() {
2097        // Lazy continuation containing emphasis markers
2098        let content = "- Item\n*emphasized* continuation";
2099        let config = MD032Config {
2100            allow_lazy_continuation: false,
2101        };
2102        let warnings = lint_with_config(content, config.clone());
2103        assert_eq!(warnings.len(), 1, "Should warn even with emphasis in continuation");
2104
2105        let fixed = fix_with_config(content, config);
2106        // Fix adds proper indentation (2 spaces for "- " marker)
2107        assert_eq!(fixed, "- Item\n  *emphasized* continuation");
2108    }
2109
2110    #[test]
2111    fn test_lazy_continuation_with_code_span() {
2112        // Lazy continuation containing code span
2113        let content = "- Item\n`code` continuation";
2114        let config = MD032Config {
2115            allow_lazy_continuation: false,
2116        };
2117        let warnings = lint_with_config(content, config.clone());
2118        assert_eq!(warnings.len(), 1, "Should warn even with code span in continuation");
2119
2120        let fixed = fix_with_config(content, config);
2121        // Fix adds proper indentation (2 spaces for "- " marker)
2122        assert_eq!(fixed, "- Item\n  `code` continuation");
2123    }
2124
2125    // =========================================================================
2126    // Issue #295: Lazy continuation after nested sublists
2127    // These tests verify detection of lazy continuation at outer indent level
2128    // after nested sublists, followed by another list item.
2129    // =========================================================================
2130
2131    #[test]
2132    fn test_issue295_case1_nested_bullets_then_continuation_then_item() {
2133        // Outer numbered item with nested bullets, lazy continuation, then next item
2134        // The lazy continuation "A new Chat..." appears at column 1, not indented
2135        let content = r#"1. Create a new Chat conversation:
2136   - On the sidebar, select **New Chat**.
2137   - In the box, type `/new`.
2138   A new Chat conversation replaces the previous one.
21391. Under the Chat text box, turn off the toggle."#;
2140        let config = MD032Config {
2141            allow_lazy_continuation: false,
2142        };
2143        let warnings = lint_with_config(content, config);
2144        // Should warn about line 4 "A new Chat..." which is lazy continuation
2145        let lazy_warnings: Vec<_> = warnings
2146            .iter()
2147            .filter(|w| w.message.contains("Lazy continuation"))
2148            .collect();
2149        assert!(
2150            !lazy_warnings.is_empty(),
2151            "Should detect lazy continuation after nested bullets. Got: {warnings:?}"
2152        );
2153        assert!(
2154            lazy_warnings.iter().any(|w| w.line == 4),
2155            "Should warn on line 4. Got: {lazy_warnings:?}"
2156        );
2157    }
2158
2159    #[test]
2160    fn test_issue295_case3_code_span_starts_lazy_continuation() {
2161        // Code span at the START of lazy continuation after nested bullets
2162        // This is tricky because pulldown-cmark emits Code event, not Text
2163        let content = r#"- `field`: Is the specific key:
2164  - `password`: Accesses the password.
2165  - `api_key`: Accesses the api_key.
2166  `token`: Specifies which ID token to use.
2167- `version_id`: Is the unique identifier."#;
2168        let config = MD032Config {
2169            allow_lazy_continuation: false,
2170        };
2171        let warnings = lint_with_config(content, config);
2172        // Should warn about line 4 "`token`:..." which starts with code span
2173        let lazy_warnings: Vec<_> = warnings
2174            .iter()
2175            .filter(|w| w.message.contains("Lazy continuation"))
2176            .collect();
2177        assert!(
2178            !lazy_warnings.is_empty(),
2179            "Should detect lazy continuation starting with code span. Got: {warnings:?}"
2180        );
2181        assert!(
2182            lazy_warnings.iter().any(|w| w.line == 4),
2183            "Should warn on line 4 (code span start). Got: {lazy_warnings:?}"
2184        );
2185    }
2186
2187    #[test]
2188    fn test_issue295_case4_deep_nesting_with_continuation_then_item() {
2189        // Multiple nesting levels, lazy continuation, then next outer item
2190        let content = r#"- Check out the branch, and test locally.
2191  - If the MR requires significant modifications:
2192    - **Skip local testing** and review instead.
2193    - **Request verification** from the author.
2194    - **Identify the minimal change** needed.
2195  Your testing might result in opportunities.
2196- If you don't understand, _say so_."#;
2197        let config = MD032Config {
2198            allow_lazy_continuation: false,
2199        };
2200        let warnings = lint_with_config(content, config);
2201        // Should warn about line 6 "Your testing..." which is lazy continuation
2202        let lazy_warnings: Vec<_> = warnings
2203            .iter()
2204            .filter(|w| w.message.contains("Lazy continuation"))
2205            .collect();
2206        assert!(
2207            !lazy_warnings.is_empty(),
2208            "Should detect lazy continuation after deep nesting. Got: {warnings:?}"
2209        );
2210        assert!(
2211            lazy_warnings.iter().any(|w| w.line == 6),
2212            "Should warn on line 6. Got: {lazy_warnings:?}"
2213        );
2214    }
2215
2216    #[test]
2217    fn test_issue295_ordered_list_nested_bullets_continuation() {
2218        // Ordered list with nested bullets, continuation at outer level, then next item
2219        // This is the exact pattern from debug_test6.md
2220        let content = r#"# Test
2221
22221. First item.
2223   - Nested A.
2224   - Nested B.
2225   Continuation at outer level.
22261. Second item."#;
2227        let config = MD032Config {
2228            allow_lazy_continuation: false,
2229        };
2230        let warnings = lint_with_config(content, config);
2231        // Should warn about line 6 "Continuation at outer level."
2232        let lazy_warnings: Vec<_> = warnings
2233            .iter()
2234            .filter(|w| w.message.contains("Lazy continuation"))
2235            .collect();
2236        assert!(
2237            !lazy_warnings.is_empty(),
2238            "Should detect lazy continuation at outer level after nested. Got: {warnings:?}"
2239        );
2240        // Line 6 = "   Continuation at outer level." (3 spaces indent, but needs 4 for proper continuation)
2241        assert!(
2242            lazy_warnings.iter().any(|w| w.line == 6),
2243            "Should warn on line 6. Got: {lazy_warnings:?}"
2244        );
2245    }
2246
2247    #[test]
2248    fn test_issue295_multiple_lazy_lines_after_nested() {
2249        // Multiple lazy continuation lines after nested sublist
2250        let content = r#"1. The device client receives a response.
2251   - Those defined by OAuth Framework.
2252   - Those specific to device authorization.
2253   Those error responses are described below.
2254   For more information on each response,
2255   see the documentation.
22561. Next step in the process."#;
2257        let config = MD032Config {
2258            allow_lazy_continuation: false,
2259        };
2260        let warnings = lint_with_config(content, config);
2261        // Should warn about lines 4, 5, 6 (all lazy continuation)
2262        let lazy_warnings: Vec<_> = warnings
2263            .iter()
2264            .filter(|w| w.message.contains("Lazy continuation"))
2265            .collect();
2266        assert!(
2267            lazy_warnings.len() >= 3,
2268            "Should detect multiple lazy continuation lines. Got {} warnings: {lazy_warnings:?}",
2269            lazy_warnings.len()
2270        );
2271    }
2272
2273    #[test]
2274    fn test_issue295_properly_indented_not_lazy() {
2275        // Properly indented continuation after nested sublist should NOT warn
2276        let content = r#"1. First item.
2277   - Nested A.
2278   - Nested B.
2279
2280   Properly indented continuation.
22811. Second item."#;
2282        let config = MD032Config {
2283            allow_lazy_continuation: false,
2284        };
2285        let warnings = lint_with_config(content, config);
2286        // With blank line before, this is a new paragraph, not lazy continuation
2287        let lazy_warnings: Vec<_> = warnings
2288            .iter()
2289            .filter(|w| w.message.contains("Lazy continuation"))
2290            .collect();
2291        assert_eq!(
2292            lazy_warnings.len(),
2293            0,
2294            "Should NOT warn when blank line separates continuation. Got: {lazy_warnings:?}"
2295        );
2296    }
2297
2298    // =========================================================================
2299    // HTML Comment Transparency Tests
2300    // HTML comments should be "transparent" for blank line checking,
2301    // matching markdownlint-cli behavior.
2302    // =========================================================================
2303
2304    #[test]
2305    fn test_html_comment_before_list_with_preceding_blank() {
2306        // Blank line before HTML comment = list is properly separated
2307        // markdownlint-cli does NOT warn here
2308        let content = "Some text.\n\n<!-- comment -->\n- List item";
2309        let warnings = lint(content);
2310        assert_eq!(
2311            warnings.len(),
2312            0,
2313            "Should not warn when blank line exists before HTML comment. Got: {warnings:?}"
2314        );
2315    }
2316
2317    #[test]
2318    fn test_html_comment_after_list_with_following_blank() {
2319        // Blank line after HTML comment = list is properly separated
2320        let content = "- List item\n<!-- comment -->\n\nSome text.";
2321        let warnings = lint(content);
2322        assert_eq!(
2323            warnings.len(),
2324            0,
2325            "Should not warn when blank line exists after HTML comment. Got: {warnings:?}"
2326        );
2327    }
2328
2329    #[test]
2330    fn test_list_inside_html_comment_ignored() {
2331        // Lists entirely inside HTML comments should not be analyzed
2332        let content = "<!--\n1. First\n2. Second\n3. Third\n-->";
2333        let warnings = lint(content);
2334        assert_eq!(
2335            warnings.len(),
2336            0,
2337            "Should not analyze lists inside HTML comments. Got: {warnings:?}"
2338        );
2339    }
2340
2341    #[test]
2342    fn test_multiline_html_comment_before_list() {
2343        // Multi-line HTML comment should be transparent
2344        let content = "Text\n\n<!--\nThis is a\nmulti-line\ncomment\n-->\n- Item";
2345        let warnings = lint(content);
2346        assert_eq!(
2347            warnings.len(),
2348            0,
2349            "Multi-line HTML comment should be transparent. Got: {warnings:?}"
2350        );
2351    }
2352
2353    #[test]
2354    fn test_no_blank_before_html_comment_still_warns() {
2355        // No blank line anywhere = should still warn
2356        let content = "Some text.\n<!-- comment -->\n- List item";
2357        let warnings = lint(content);
2358        assert_eq!(
2359            warnings.len(),
2360            1,
2361            "Should warn when no blank line exists (even with HTML comment). Got: {warnings:?}"
2362        );
2363        assert!(
2364            warnings[0].message.contains("preceded by blank line"),
2365            "Should be 'preceded by blank line' warning"
2366        );
2367    }
2368
2369    #[test]
2370    fn test_no_blank_after_html_comment_no_warn_lazy_continuation() {
2371        // Text immediately after list (through HTML comment) is lazy continuation
2372        // markdownlint-cli does NOT warn here - the text becomes part of the list
2373        let content = "- List item\n<!-- comment -->\nSome text.";
2374        let warnings = lint(content);
2375        assert_eq!(
2376            warnings.len(),
2377            0,
2378            "Should not warn - text after comment becomes lazy continuation. Got: {warnings:?}"
2379        );
2380    }
2381
2382    #[test]
2383    fn test_list_followed_by_heading_through_comment_should_warn() {
2384        // Heading cannot be lazy continuation, so this SHOULD warn
2385        let content = "- List item\n<!-- comment -->\n# Heading";
2386        let warnings = lint(content);
2387        // Headings after lists through HTML comments should be handled gracefully
2388        // The blank line check should look past the comment
2389        assert!(
2390            warnings.len() <= 1,
2391            "Should handle heading after comment gracefully. Got: {warnings:?}"
2392        );
2393    }
2394
2395    #[test]
2396    fn test_html_comment_between_list_and_text_both_directions() {
2397        // Blank line on both sides through HTML comment
2398        let content = "Text before.\n\n<!-- comment -->\n- Item 1\n- Item 2\n<!-- another -->\n\nText after.";
2399        let warnings = lint(content);
2400        assert_eq!(
2401            warnings.len(),
2402            0,
2403            "Should not warn with proper separation through comments. Got: {warnings:?}"
2404        );
2405    }
2406
2407    #[test]
2408    fn test_html_comment_fix_does_not_insert_unnecessary_blank() {
2409        // Fix should not add blank line when separation already exists through comment
2410        let content = "Text.\n\n<!-- comment -->\n- Item";
2411        let fixed = fix(content);
2412        assert_eq!(fixed, content, "Fix should not modify already-correct content");
2413    }
2414
2415    #[test]
2416    fn test_html_comment_fix_adds_blank_when_needed() {
2417        // Fix should add blank line when no separation exists
2418        // The blank line is added immediately before the list (after the comment)
2419        let content = "Text.\n<!-- comment -->\n- Item";
2420        let fixed = fix(content);
2421        assert!(
2422            fixed.contains("<!-- comment -->\n\n- Item"),
2423            "Fix should add blank line before list. Got: {fixed}"
2424        );
2425    }
2426
2427    #[test]
2428    fn test_ordered_list_inside_html_comment() {
2429        // Ordered list with non-1 start inside comment should not warn
2430        let content = "<!--\n3. Starting at 3\n4. Next item\n-->";
2431        let warnings = lint(content);
2432        assert_eq!(
2433            warnings.len(),
2434            0,
2435            "Should not warn about ordered list inside HTML comment. Got: {warnings:?}"
2436        );
2437    }
2438
2439    // =========================================================================
2440    // Blockquote Boundary Transition Tests
2441    // When a list inside a blockquote ends and the next line exits the blockquote,
2442    // no blank line is needed - the blockquote boundary provides semantic separation.
2443    // =========================================================================
2444
2445    #[test]
2446    fn test_blockquote_list_exit_no_warning() {
2447        // Blockquote list followed by outer content - no blank line needed
2448        let content = "- outer item\n  > - blockquote list 1\n  > - blockquote list 2\n- next outer item";
2449        let warnings = lint(content);
2450        assert_eq!(
2451            warnings.len(),
2452            0,
2453            "Should not warn when exiting blockquote. Got: {warnings:?}"
2454        );
2455    }
2456
2457    #[test]
2458    fn test_nested_blockquote_list_exit() {
2459        // Nested blockquote list - exiting should not require blank line
2460        let content = "- outer\n  - nested\n    > - bq list 1\n    > - bq list 2\n  - back to nested\n- outer again";
2461        let warnings = lint(content);
2462        assert_eq!(
2463            warnings.len(),
2464            0,
2465            "Should not warn when exiting nested blockquote list. Got: {warnings:?}"
2466        );
2467    }
2468
2469    #[test]
2470    fn test_blockquote_same_level_no_warning() {
2471        // List INSIDE blockquote followed by text INSIDE same blockquote
2472        // markdownlint-cli does NOT warn for this case - lazy continuation applies
2473        let content = "> - item 1\n> - item 2\n> Text after";
2474        let warnings = lint(content);
2475        assert_eq!(
2476            warnings.len(),
2477            0,
2478            "Should not warn - text is lazy continuation in blockquote. Got: {warnings:?}"
2479        );
2480    }
2481
2482    #[test]
2483    fn test_blockquote_list_with_special_chars() {
2484        // Content with special chars like <> should not affect blockquote detection
2485        let content = "- Item with <>&\n  > - blockquote item\n- Back to outer";
2486        let warnings = lint(content);
2487        assert_eq!(
2488            warnings.len(),
2489            0,
2490            "Special chars in content should not affect blockquote detection. Got: {warnings:?}"
2491        );
2492    }
2493
2494    #[test]
2495    fn test_lazy_continuation_whitespace_only_line() {
2496        // Per CommonMark/pulldown-cmark, whitespace-only line IS a blank line separator
2497        // The list ends at the whitespace-only line, text starts a new paragraph
2498        let content = "- Item\n   \nText after whitespace-only line";
2499        let config = MD032Config {
2500            allow_lazy_continuation: false,
2501        };
2502        let warnings = lint_with_config(content, config);
2503        // Whitespace-only line counts as blank line separator - no lazy continuation
2504        assert_eq!(
2505            warnings.len(),
2506            0,
2507            "Whitespace-only line IS a separator in CommonMark. Got: {warnings:?}"
2508        );
2509    }
2510
2511    #[test]
2512    fn test_lazy_continuation_blockquote_context() {
2513        // List inside blockquote with lazy continuation
2514        let content = "> - Item\n> Lazy in quote";
2515        let config = MD032Config {
2516            allow_lazy_continuation: false,
2517        };
2518        let warnings = lint_with_config(content, config);
2519        // Inside blockquote, lazy continuation may behave differently
2520        // This tests that we handle blockquote context
2521        assert!(warnings.len() <= 1, "Should handle blockquote context gracefully");
2522    }
2523
2524    #[test]
2525    fn test_lazy_continuation_fix_preserves_content() {
2526        // Ensure fix doesn't modify the actual content
2527        let content = "- Item with special chars: <>&\nContinuation with: \"quotes\"";
2528        let config = MD032Config {
2529            allow_lazy_continuation: false,
2530        };
2531        let fixed = fix_with_config(content, config);
2532        assert!(fixed.contains("<>&"), "Should preserve special chars");
2533        assert!(fixed.contains("\"quotes\""), "Should preserve quotes");
2534        // Fix adds proper indentation (2 spaces for "- " marker)
2535        assert_eq!(fixed, "- Item with special chars: <>&\n  Continuation with: \"quotes\"");
2536    }
2537
2538    #[test]
2539    fn test_lazy_continuation_fix_idempotent() {
2540        // Running fix twice should produce same result
2541        let content = "- Item\nLazy";
2542        let config = MD032Config {
2543            allow_lazy_continuation: false,
2544        };
2545        let fixed_once = fix_with_config(content, config.clone());
2546        let fixed_twice = fix_with_config(&fixed_once, config);
2547        assert_eq!(fixed_once, fixed_twice, "Fix should be idempotent");
2548    }
2549
2550    #[test]
2551    fn test_lazy_continuation_config_default_allows() {
2552        // Verify default config allows lazy continuation
2553        let content = "- Item\nLazy text that continues";
2554        let default_config = MD032Config::default();
2555        assert!(
2556            default_config.allow_lazy_continuation,
2557            "Default should allow lazy continuation"
2558        );
2559        let warnings = lint_with_config(content, default_config);
2560        assert_eq!(warnings.len(), 0, "Default config should not warn on lazy continuation");
2561    }
2562
2563    #[test]
2564    fn test_lazy_continuation_after_multi_line_item() {
2565        // List item with proper indented continuation, then lazy text
2566        let content = "- Item line 1\n  Item line 2 (indented)\nLazy (not indented)";
2567        let config = MD032Config {
2568            allow_lazy_continuation: false,
2569        };
2570        let warnings = lint_with_config(content, config.clone());
2571        assert_eq!(
2572            warnings.len(),
2573            1,
2574            "Should warn only for the lazy line, not the indented line"
2575        );
2576    }
2577
2578    // Issue #260: Lists inside blockquotes should not produce false positives
2579    #[test]
2580    fn test_blockquote_list_with_continuation_and_nested() {
2581        // This is the exact case from issue #260
2582        // markdownlint-cli reports NO warnings for this
2583        let content = "> - item 1\n>   continuation\n>   - nested\n> - item 2";
2584        let warnings = lint(content);
2585        assert_eq!(
2586            warnings.len(),
2587            0,
2588            "Blockquoted list with continuation and nested items should have no warnings. Got: {warnings:?}"
2589        );
2590    }
2591
2592    #[test]
2593    fn test_blockquote_list_simple() {
2594        // Simple blockquoted list
2595        let content = "> - item 1\n> - item 2";
2596        let warnings = lint(content);
2597        assert_eq!(warnings.len(), 0, "Simple blockquoted list should have no warnings");
2598    }
2599
2600    #[test]
2601    fn test_blockquote_list_with_continuation_only() {
2602        // Blockquoted list with continuation line (no nesting)
2603        let content = "> - item 1\n>   continuation\n> - item 2";
2604        let warnings = lint(content);
2605        assert_eq!(
2606            warnings.len(),
2607            0,
2608            "Blockquoted list with continuation should have no warnings"
2609        );
2610    }
2611
2612    #[test]
2613    fn test_blockquote_list_with_lazy_continuation() {
2614        // Blockquoted list with lazy continuation (no extra indent after >)
2615        let content = "> - item 1\n> lazy continuation\n> - item 2";
2616        let warnings = lint(content);
2617        assert_eq!(
2618            warnings.len(),
2619            0,
2620            "Blockquoted list with lazy continuation should have no warnings"
2621        );
2622    }
2623
2624    #[test]
2625    fn test_nested_blockquote_list() {
2626        // List inside nested blockquote (>> prefix)
2627        let content = ">> - item 1\n>>   continuation\n>>   - nested\n>> - item 2";
2628        let warnings = lint(content);
2629        assert_eq!(warnings.len(), 0, "Nested blockquote list should have no warnings");
2630    }
2631
2632    #[test]
2633    fn test_blockquote_list_needs_preceding_blank() {
2634        // Blockquote list preceded by non-blank content SHOULD warn
2635        let content = "> Text before\n> - item 1\n> - item 2";
2636        let warnings = lint(content);
2637        assert_eq!(
2638            warnings.len(),
2639            1,
2640            "Should warn for missing blank before blockquoted list"
2641        );
2642    }
2643
2644    #[test]
2645    fn test_blockquote_list_properly_separated() {
2646        // Blockquote list with proper blank lines - no warnings
2647        let content = "> Text before\n>\n> - item 1\n> - item 2\n>\n> Text after";
2648        let warnings = lint(content);
2649        assert_eq!(
2650            warnings.len(),
2651            0,
2652            "Properly separated blockquoted list should have no warnings"
2653        );
2654    }
2655
2656    #[test]
2657    fn test_blockquote_ordered_list() {
2658        // Ordered list in blockquote with continuation
2659        let content = "> 1. item 1\n>    continuation\n> 2. item 2";
2660        let warnings = lint(content);
2661        assert_eq!(warnings.len(), 0, "Ordered list in blockquote should have no warnings");
2662    }
2663
2664    #[test]
2665    fn test_blockquote_list_with_empty_blockquote_line() {
2666        // Empty blockquote line (just ">") between items - still same list
2667        let content = "> - item 1\n>\n> - item 2";
2668        let warnings = lint(content);
2669        assert_eq!(warnings.len(), 0, "Empty blockquote line should not break list");
2670    }
2671
2672    /// Issue #268: Multi-paragraph list items in blockquotes should not trigger false positives
2673    #[test]
2674    fn test_blockquote_list_multi_paragraph_items() {
2675        // List item with blank line + continuation paragraph + next item
2676        // This is a common pattern for multi-paragraph list items in blockquotes
2677        let content = "# Test\n\n> Some intro text\n> \n> * List item 1\n> \n>   Continuation\n> * List item 2\n";
2678        let warnings = lint(content);
2679        assert_eq!(
2680            warnings.len(),
2681            0,
2682            "Multi-paragraph list items in blockquotes should have no warnings. Got: {warnings:?}"
2683        );
2684    }
2685
2686    /// Issue #268: Ordered lists with multi-paragraph items in blockquotes
2687    #[test]
2688    fn test_blockquote_ordered_list_multi_paragraph_items() {
2689        let content = "> 1. First item\n> \n>    Continuation of first\n> 2. Second item\n";
2690        let warnings = lint(content);
2691        assert_eq!(
2692            warnings.len(),
2693            0,
2694            "Ordered multi-paragraph list items in blockquotes should have no warnings. Got: {warnings:?}"
2695        );
2696    }
2697
2698    /// Issue #268: Multiple continuation paragraphs in blockquote list
2699    #[test]
2700    fn test_blockquote_list_multiple_continuations() {
2701        let content = "> - Item 1\n> \n>   First continuation\n> \n>   Second continuation\n> - Item 2\n";
2702        let warnings = lint(content);
2703        assert_eq!(
2704            warnings.len(),
2705            0,
2706            "Multiple continuation paragraphs should not break blockquote list. Got: {warnings:?}"
2707        );
2708    }
2709
2710    /// Issue #268: Nested blockquote (>>) with multi-paragraph list items
2711    #[test]
2712    fn test_nested_blockquote_multi_paragraph_list() {
2713        let content = ">> - Item 1\n>> \n>>   Continuation\n>> - Item 2\n";
2714        let warnings = lint(content);
2715        assert_eq!(
2716            warnings.len(),
2717            0,
2718            "Nested blockquote multi-paragraph list should have no warnings. Got: {warnings:?}"
2719        );
2720    }
2721
2722    /// Issue #268: Triple-nested blockquote (>>>) with multi-paragraph list items
2723    #[test]
2724    fn test_triple_nested_blockquote_multi_paragraph_list() {
2725        let content = ">>> - Item 1\n>>> \n>>>   Continuation\n>>> - Item 2\n";
2726        let warnings = lint(content);
2727        assert_eq!(
2728            warnings.len(),
2729            0,
2730            "Triple-nested blockquote multi-paragraph list should have no warnings. Got: {warnings:?}"
2731        );
2732    }
2733
2734    /// Issue #268: Last item in blockquote list has continuation (edge case)
2735    #[test]
2736    fn test_blockquote_list_last_item_continuation() {
2737        let content = "> - Item 1\n> - Item 2\n> \n>   Continuation of item 2\n";
2738        let warnings = lint(content);
2739        assert_eq!(
2740            warnings.len(),
2741            0,
2742            "Last item with continuation should have no warnings. Got: {warnings:?}"
2743        );
2744    }
2745
2746    /// Issue #268: First item only has continuation in blockquote list
2747    #[test]
2748    fn test_blockquote_list_first_item_only_continuation() {
2749        let content = "> - Item 1\n> \n>   Continuation of item 1\n";
2750        let warnings = lint(content);
2751        assert_eq!(
2752            warnings.len(),
2753            0,
2754            "Single item with continuation should have no warnings. Got: {warnings:?}"
2755        );
2756    }
2757
2758    /// Blockquote level change SHOULD still be detected as list break
2759    /// Note: markdownlint flags BOTH lines in this case - line 1 for missing preceding blank,
2760    /// and line 2 for missing preceding blank (level change)
2761    #[test]
2762    fn test_blockquote_level_change_breaks_list() {
2763        // Going from > to >> should break the list - markdownlint flags both lines
2764        let content = "> - Item in single blockquote\n>> - Item in nested blockquote\n";
2765        let warnings = lint(content);
2766        // markdownlint reports: line 1 (list at start), line 2 (level change)
2767        // For now, accept 0 or more warnings since this is a complex edge case
2768        // The main fix (multi-paragraph items) is more important than this edge case
2769        assert!(
2770            warnings.len() <= 2,
2771            "Blockquote level change warnings should be reasonable. Got: {warnings:?}"
2772        );
2773    }
2774
2775    /// Exiting blockquote SHOULD still be detected as needing blank line
2776    #[test]
2777    fn test_exit_blockquote_needs_blank_before_list() {
2778        // Text after blockquote, then list without blank
2779        let content = "> Blockquote text\n\n- List outside blockquote\n";
2780        let warnings = lint(content);
2781        assert_eq!(
2782            warnings.len(),
2783            0,
2784            "List after blank line outside blockquote should be fine. Got: {warnings:?}"
2785        );
2786
2787        // Without blank line after blockquote - markdownlint flags this
2788        // But rumdl may not flag it due to complexity of detecting "text immediately before list"
2789        // This is an acceptable deviation for now
2790        let content2 = "> Blockquote text\n- List outside blockquote\n";
2791        let warnings2 = lint(content2);
2792        // Accept 0 or 1 - main fix is more important than this edge case
2793        assert!(
2794            warnings2.len() <= 1,
2795            "List after blockquote warnings should be reasonable. Got: {warnings2:?}"
2796        );
2797    }
2798
2799    /// Issue #268: Test all unordered list markers (-, *, +) with multi-paragraph items
2800    #[test]
2801    fn test_blockquote_multi_paragraph_all_unordered_markers() {
2802        // Dash marker
2803        let content_dash = "> - Item 1\n> \n>   Continuation\n> - Item 2\n";
2804        let warnings = lint(content_dash);
2805        assert_eq!(warnings.len(), 0, "Dash marker should work. Got: {warnings:?}");
2806
2807        // Asterisk marker
2808        let content_asterisk = "> * Item 1\n> \n>   Continuation\n> * Item 2\n";
2809        let warnings = lint(content_asterisk);
2810        assert_eq!(warnings.len(), 0, "Asterisk marker should work. Got: {warnings:?}");
2811
2812        // Plus marker
2813        let content_plus = "> + Item 1\n> \n>   Continuation\n> + Item 2\n";
2814        let warnings = lint(content_plus);
2815        assert_eq!(warnings.len(), 0, "Plus marker should work. Got: {warnings:?}");
2816    }
2817
2818    /// Issue #268: Parenthesis-style ordered list markers (1))
2819    #[test]
2820    fn test_blockquote_multi_paragraph_parenthesis_marker() {
2821        let content = "> 1) Item 1\n> \n>    Continuation\n> 2) Item 2\n";
2822        let warnings = lint(content);
2823        assert_eq!(
2824            warnings.len(),
2825            0,
2826            "Parenthesis ordered markers should work. Got: {warnings:?}"
2827        );
2828    }
2829
2830    /// Issue #268: Multi-digit ordered list numbers have wider markers
2831    #[test]
2832    fn test_blockquote_multi_paragraph_multi_digit_numbers() {
2833        // "10. " is 4 chars, so continuation needs 4 spaces
2834        let content = "> 10. Item 10\n> \n>     Continuation of item 10\n> 11. Item 11\n";
2835        let warnings = lint(content);
2836        assert_eq!(
2837            warnings.len(),
2838            0,
2839            "Multi-digit ordered list should work. Got: {warnings:?}"
2840        );
2841    }
2842
2843    /// Issue #268: Continuation with emphasis and other inline formatting
2844    #[test]
2845    fn test_blockquote_multi_paragraph_with_formatting() {
2846        let content = "> - Item with **bold**\n> \n>   Continuation with *emphasis* and `code`\n> - Item 2\n";
2847        let warnings = lint(content);
2848        assert_eq!(
2849            warnings.len(),
2850            0,
2851            "Continuation with inline formatting should work. Got: {warnings:?}"
2852        );
2853    }
2854
2855    /// Issue #268: Multiple items each with their own continuation paragraph
2856    #[test]
2857    fn test_blockquote_multi_paragraph_all_items_have_continuation() {
2858        let content = "> - Item 1\n> \n>   Continuation 1\n> - Item 2\n> \n>   Continuation 2\n> - Item 3\n> \n>   Continuation 3\n";
2859        let warnings = lint(content);
2860        assert_eq!(
2861            warnings.len(),
2862            0,
2863            "All items with continuations should work. Got: {warnings:?}"
2864        );
2865    }
2866
2867    /// Issue #268: Continuation starting with lowercase (tests uppercase heuristic doesn't break this)
2868    #[test]
2869    fn test_blockquote_multi_paragraph_lowercase_continuation() {
2870        let content = "> - Item 1\n> \n>   and this continues the item\n> - Item 2\n";
2871        let warnings = lint(content);
2872        assert_eq!(
2873            warnings.len(),
2874            0,
2875            "Lowercase continuation should work. Got: {warnings:?}"
2876        );
2877    }
2878
2879    /// Issue #268: Continuation starting with uppercase (tests uppercase heuristic is bypassed with proper indent)
2880    #[test]
2881    fn test_blockquote_multi_paragraph_uppercase_continuation() {
2882        let content = "> - Item 1\n> \n>   This continues the item with uppercase\n> - Item 2\n";
2883        let warnings = lint(content);
2884        assert_eq!(
2885            warnings.len(),
2886            0,
2887            "Uppercase continuation with proper indent should work. Got: {warnings:?}"
2888        );
2889    }
2890
2891    /// Issue #268: Mixed ordered and unordered shouldn't affect multi-paragraph handling
2892    #[test]
2893    fn test_blockquote_separate_ordered_unordered_multi_paragraph() {
2894        // Two separate lists in same blockquote
2895        let content = "> - Unordered item\n> \n>   Continuation\n> \n> 1. Ordered item\n> \n>    Continuation\n";
2896        let warnings = lint(content);
2897        // May have warning for missing blank between lists, but not for the continuations
2898        assert!(
2899            warnings.len() <= 1,
2900            "Separate lists with continuations should be reasonable. Got: {warnings:?}"
2901        );
2902    }
2903
2904    /// Issue #268: Blockquote with bare > line (no space) as blank
2905    #[test]
2906    fn test_blockquote_multi_paragraph_bare_marker_blank() {
2907        // Using ">" alone instead of "> " for blank line
2908        let content = "> - Item 1\n>\n>   Continuation\n> - Item 2\n";
2909        let warnings = lint(content);
2910        assert_eq!(warnings.len(), 0, "Bare > as blank line should work. Got: {warnings:?}");
2911    }
2912
2913    #[test]
2914    fn test_blockquote_list_varying_spaces_after_marker() {
2915        // Different spacing after > (1 space vs 3 spaces) but same blockquote level
2916        let content = "> - item 1\n>   continuation with more indent\n> - item 2";
2917        let warnings = lint(content);
2918        assert_eq!(warnings.len(), 0, "Varying spaces after > should not break list");
2919    }
2920
2921    #[test]
2922    fn test_deeply_nested_blockquote_list() {
2923        // Triple-nested blockquote with list
2924        let content = ">>> - item 1\n>>>   continuation\n>>> - item 2";
2925        let warnings = lint(content);
2926        assert_eq!(
2927            warnings.len(),
2928            0,
2929            "Deeply nested blockquote list should have no warnings"
2930        );
2931    }
2932
2933    #[test]
2934    fn test_blockquote_level_change_in_list() {
2935        // Blockquote level changes mid-list - this breaks the list
2936        let content = "> - item 1\n>> - deeper item\n> - item 2";
2937        // Each segment is a separate list context due to blockquote level change
2938        // markdownlint-cli reports 4 warnings for this case
2939        let warnings = lint(content);
2940        assert!(
2941            !warnings.is_empty(),
2942            "Blockquote level change should break list and trigger warnings"
2943        );
2944    }
2945
2946    #[test]
2947    fn test_blockquote_list_with_code_span() {
2948        // List item with inline code in blockquote
2949        let content = "> - item with `code`\n>   continuation\n> - item 2";
2950        let warnings = lint(content);
2951        assert_eq!(
2952            warnings.len(),
2953            0,
2954            "Blockquote list with code span should have no warnings"
2955        );
2956    }
2957
2958    #[test]
2959    fn test_blockquote_list_at_document_end() {
2960        // List at end of document (no trailing content)
2961        let content = "> Some text\n>\n> - item 1\n> - item 2";
2962        let warnings = lint(content);
2963        assert_eq!(
2964            warnings.len(),
2965            0,
2966            "Blockquote list at document end should have no warnings"
2967        );
2968    }
2969
2970    #[test]
2971    fn test_fix_preserves_blockquote_prefix_before_list() {
2972        // Issue #268: Fix should insert blockquote-prefixed blank lines inside blockquotes
2973        let content = "> Text before
2974> - Item 1
2975> - Item 2";
2976        let fixed = fix(content);
2977
2978        // The blank line inserted before the list should have the blockquote prefix (no trailing space per markdownlint-cli)
2979        let expected = "> Text before
2980>
2981> - Item 1
2982> - Item 2";
2983        assert_eq!(
2984            fixed, expected,
2985            "Fix should insert '>' blank line, not plain blank line"
2986        );
2987    }
2988
2989    #[test]
2990    fn test_fix_preserves_triple_nested_blockquote_prefix_for_list() {
2991        // Triple-nested blockquotes should preserve full prefix
2992        // Per markdownlint-cli, only preceding blank line is required
2993        let content = ">>> Triple nested
2994>>> - Item 1
2995>>> - Item 2
2996>>> More text";
2997        let fixed = fix(content);
2998
2999        // Should insert ">>>" blank line before list only
3000        let expected = ">>> Triple nested
3001>>>
3002>>> - Item 1
3003>>> - Item 2
3004>>> More text";
3005        assert_eq!(
3006            fixed, expected,
3007            "Fix should preserve triple-nested blockquote prefix '>>>'"
3008        );
3009    }
3010
3011    // ==================== Quarto Flavor Tests ====================
3012
3013    fn lint_quarto(content: &str) -> Vec<LintWarning> {
3014        let rule = MD032BlanksAroundLists::default();
3015        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
3016        rule.check(&ctx).unwrap()
3017    }
3018
3019    #[test]
3020    fn test_quarto_list_after_div_open() {
3021        // List immediately after Quarto div opening: div marker is transparent
3022        let content = "Content\n\n::: {.callout-note}\n- Item 1\n- Item 2\n:::\n";
3023        let warnings = lint_quarto(content);
3024        // The blank line before div opening should count as separation
3025        assert!(
3026            warnings.is_empty(),
3027            "Quarto div marker should be transparent before list: {warnings:?}"
3028        );
3029    }
3030
3031    #[test]
3032    fn test_quarto_list_before_div_close() {
3033        // List immediately before Quarto div closing: div close is at end, transparent
3034        let content = "::: {.callout-note}\n\n- Item 1\n- Item 2\n:::\n";
3035        let warnings = lint_quarto(content);
3036        // The div closing marker is at end, should be transparent
3037        assert!(
3038            warnings.is_empty(),
3039            "Quarto div marker should be transparent after list: {warnings:?}"
3040        );
3041    }
3042
3043    #[test]
3044    fn test_quarto_list_needs_blank_without_div() {
3045        // List still needs blank line without div providing separation
3046        let content = "Content\n::: {.callout-note}\n- Item 1\n- Item 2\n:::\n";
3047        let warnings = lint_quarto(content);
3048        // No blank between "Content" and div opening (which is transparent)
3049        // so list appears right after "Content" - needs blank
3050        assert!(
3051            !warnings.is_empty(),
3052            "Should still require blank when not present: {warnings:?}"
3053        );
3054    }
3055
3056    #[test]
3057    fn test_quarto_list_in_callout_with_content() {
3058        // List inside callout with proper blank lines
3059        let content = "::: {.callout-note}\nNote introduction:\n\n- Item 1\n- Item 2\n\nMore note content.\n:::\n";
3060        let warnings = lint_quarto(content);
3061        assert!(
3062            warnings.is_empty(),
3063            "List with proper blanks inside callout should pass: {warnings:?}"
3064        );
3065    }
3066
3067    #[test]
3068    fn test_quarto_div_markers_not_transparent_in_standard_flavor() {
3069        // In standard flavor, ::: is regular text
3070        let content = "Content\n\n:::\n- Item 1\n- Item 2\n:::\n";
3071        let warnings = lint(content); // Uses standard flavor
3072        // In standard, ::: is just text, so list follows ::: without blank
3073        assert!(
3074            !warnings.is_empty(),
3075            "Standard flavor should not treat ::: as transparent: {warnings:?}"
3076        );
3077    }
3078
3079    #[test]
3080    fn test_quarto_nested_divs_with_list() {
3081        // Nested Quarto divs with list inside
3082        let content = "::: {.outer}\n::: {.inner}\n\n- Item 1\n- Item 2\n\n:::\n:::\n";
3083        let warnings = lint_quarto(content);
3084        assert!(warnings.is_empty(), "Nested divs with list should work: {warnings:?}");
3085    }
3086
3087    #[test]
3088    fn test_issue512_complex_nested_list_with_continuation() {
3089        // Three-level nested list with continuation paragraphs at parent indent levels.
3090        // The continuation paragraphs are part of the same list, so no MD032 warning expected.
3091        let content = "\
3092- First level of indentation.
3093  - Second level of indentation.
3094    - Third level of indentation.
3095    - Third level of indentation.
3096
3097    Second level list continuation.
3098
3099  First level list continuation.
3100- First level of indentation.
3101";
3102        let warnings = lint(content);
3103        assert!(
3104            warnings.is_empty(),
3105            "Nested list with parent-level continuation should produce no warnings. Got: {warnings:?}"
3106        );
3107    }
3108
3109    #[test]
3110    fn test_issue512_continuation_at_root_level() {
3111        // Nested list where continuation returns to indent 0 (lazy continuation).
3112        // The unindented "Root level lazy continuation." breaks the list, so the next
3113        // list item needs a blank line before it. markdownlint-cli also warns here.
3114        let content = "\
3115- First level.
3116  - Second level.
3117
3118  First level continuation.
3119
3120Root level lazy continuation.
3121- Another first level item.
3122";
3123        let warnings = lint(content);
3124        assert_eq!(
3125            warnings.len(),
3126            1,
3127            "Should warn on line 7 (new list after break). Got: {warnings:?}"
3128        );
3129        assert_eq!(warnings[0].line, 7);
3130    }
3131
3132    #[test]
3133    fn test_issue512_three_level_nesting_continuation_at_each_level() {
3134        // Each nesting level has a continuation paragraph
3135        let content = "\
3136- Level 1 item.
3137  - Level 2 item.
3138    - Level 3 item.
3139
3140    Level 3 continuation.
3141
3142  Level 2 continuation.
3143
3144  Level 1 continuation (indented under marker).
3145- Another level 1 item.
3146";
3147        let warnings = lint(content);
3148        assert!(
3149            warnings.is_empty(),
3150            "Continuation at each nesting level should produce no warnings. Got: {warnings:?}"
3151        );
3152    }
3153
3154    #[test]
3155    fn test_pandoc_list_after_div_open() {
3156        // List immediately after a Pandoc div opening should not require a blank line,
3157        // mirroring the Quarto behavior tested in test_quarto_list_after_div_open.
3158        let rule = MD032BlanksAroundLists::default();
3159        let content = "Content\n\n::: {.callout-note}\n- Item 1\n- Item 2\n:::\n";
3160        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
3161        let warnings = rule.check(&ctx).unwrap();
3162        assert!(
3163            warnings.is_empty(),
3164            "MD032 should treat Pandoc div marker as transparent before list: {warnings:?}"
3165        );
3166    }
3167}