Skip to main content

rumdl_lib/rules/
md077_list_continuation_indent.rs

1//!
2//! Rule MD077: List continuation content indentation
3//!
4//! See [docs/md077.md](../../docs/md077.md) for full documentation, configuration, and examples.
5
6use std::ops::ControlFlow;
7
8use serde::{Deserialize, Serialize};
9
10use crate::lint_context::{LineInfo, LintContext};
11use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
12
13mod md077_config;
14use md077_config::MD077Config;
15
16/// How strictly MD077 enforces continuation-line indentation.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum ContinuationStyle {
20    /// Permit any continuation indent in `[0, content_column]` (CommonMark lazy
21    /// continuation). Only over-indentation and content that escapes the list
22    /// after a blank line are flagged.
23    #[default]
24    Any,
25    /// Require every continuation line to align to the item's content column.
26    /// Tight under-indented lazy continuation (which `any` permits) is also
27    /// flagged and snapped up to the content column.
28    Aligned,
29}
30
31/// Rule MD077: List continuation content indentation
32///
33/// In both tight continuation (no blank line) and loose continuation (after a
34/// blank line), content must not be **over-indented** beyond the item's content
35/// column. Additionally, in loose continuation content must not be
36/// **under-indented** below the content column (W+N rule), or it falls out of the
37/// list; tight under-indent is valid CommonMark lazy continuation and is left
38/// alone. Content indented to the content column + 4 or more is an indented code
39/// block, not continuation, and is not flagged.
40///
41/// Under the MkDocs flavor, a minimum of 4 spaces is enforced for ordered list
42/// items to satisfy Python-Markdown.
43///
44/// With `style = "aligned"`, tight under-indented continuation is additionally
45/// flagged and aligned to the content column (mdformat parity).
46#[derive(Clone, Default)]
47pub struct MD077ListContinuationIndent {
48    config: MD077Config,
49}
50
51impl MD077ListContinuationIndent {
52    /// Construct the rule with an explicit continuation style. `Default`
53    /// (`ContinuationStyle::Any`) preserves the historical behavior.
54    pub fn new(style: ContinuationStyle) -> Self {
55        Self {
56            config: MD077Config { style },
57        }
58    }
59
60    pub fn from_config_struct(config: MD077Config) -> Self {
61        Self { config }
62    }
63}
64
65impl MD077ListContinuationIndent {
66    /// Width of a GFM task checkbox prefix including its trailing space:
67    /// `[ ] `, `[x] `, or `[X] ` — always exactly 4 bytes.
68    const TASK_CHECKBOX_PREFIX_LEN: usize = 4;
69
70    /// Returns true if the item line starts a GFM task list item, i.e. its
71    /// content column begins with `[ ] `, `[x] `, or `[X] `. The trailing
72    /// space is part of the match — `- [ ]` with no body is an empty list
73    /// item, not a task.
74    ///
75    /// Task items have a second, conventionally-accepted continuation column
76    /// at `content_col + 4` (aligned after the checkbox). MD013 reflow
77    /// produces this column for wrapped task lines, so MD077 has to accept
78    /// it to avoid a fix loop with MD013.
79    ///
80    /// `content_col` is a byte offset into `line`, not a visual column. The
81    /// CommonMark list parser produces byte-offset content columns, and the
82    /// checkbox prefix `[ ] ` is pure ASCII, so this byte-level comparison
83    /// is correct. Leading indent mixing tabs and spaces is irrelevant here
84    /// because `content_col` already points past any leading whitespace.
85    fn is_task_list_item(line: &str, content_col: usize) -> bool {
86        line.as_bytes()
87            .get(content_col..content_col + Self::TASK_CHECKBOX_PREFIX_LEN)
88            .is_some_and(|window| matches!(window, b"[ ] " | b"[x] " | b"[X] "))
89    }
90
91    /// Check if a trimmed line is a block-level construct (not list continuation).
92    fn is_block_level_construct(trimmed: &str) -> bool {
93        // Footnote definition: [^label]:
94        if trimmed.starts_with("[^") && trimmed.contains("]:") {
95            return true;
96        }
97        // Abbreviation definition: *[text]:
98        if trimmed.starts_with("*[") && trimmed.contains("]:") {
99            return true;
100        }
101        // Reference link definition: [label]: url
102        // Must start with [ but not be a regular link, footnote, or abbreviation
103        if trimmed.starts_with('[') && !trimmed.starts_with("[^") && trimmed.contains("]: ") {
104            return true;
105        }
106        false
107    }
108
109    /// Check if a trimmed line is a fenced code block delimiter (opener or closer).
110    fn is_code_fence(trimmed: &str) -> bool {
111        let bytes = trimmed.as_bytes();
112        if bytes.len() < 3 {
113            return false;
114        }
115        let ch = bytes[0];
116        (ch == b'`' || ch == b'~') && bytes[1] == ch && bytes[2] == ch
117    }
118
119    /// Check if a trimmed line starts with a list marker (*, -, +, or ordered).
120    /// Used to avoid flagging deeply indented list items that the parser doesn't
121    /// recognize as list items (e.g., with indent=8 configured in MD007).
122    fn starts_with_list_marker(trimmed: &str) -> bool {
123        let bytes = trimmed.as_bytes();
124        match bytes.first() {
125            Some(b'*' | b'-' | b'+') => bytes.get(1).is_some_and(|&b| b == b' ' || b == b'\t'),
126            Some(b'0'..=b'9') => {
127                let rest = trimmed.trim_start_matches(|c: char| c.is_ascii_digit());
128                rest.starts_with(". ") || rest.starts_with(") ")
129            }
130            _ => false,
131        }
132    }
133
134    /// Given the line number of a fenced code block opener, walk forward and
135    /// return the line number of the matching closer. Returns the opener itself
136    /// if no following line is in the code block (degenerate single-line block).
137    fn find_fence_closer(ctx: &LintContext, opener_line: usize) -> usize {
138        let mut closer_line = opener_line;
139        for peek in (opener_line + 1)..=ctx.lines.len() {
140            let Some(peek_info) = ctx.line_info(peek) else { break };
141            if peek_info.in_code_block {
142                closer_line = peek;
143            } else {
144                break;
145            }
146        }
147        closer_line
148    }
149
150    /// Build an atomic fix that reindents a fenced code block from its opener
151    /// through its matching closer.
152    ///
153    /// - **Opener and closer** are moved to `required` (the list item's
154    ///   content column, which is what MD077 actually flagged).
155    /// - **Interior lines** are *promoted* to `required` only if they sit
156    ///   below it; interior content at or above `required` is left at its
157    ///   original column. This preserves authored interior indentation when
158    ///   possible while guaranteeing fence pairing: every non-blank line in
159    ///   the block ends at column ≥ `required`, so the block stays inside
160    ///   the list item's scope after the fix.
161    ///
162    /// Only used for the under-indent direction (`required > opener_actual`);
163    /// over-indented fences are intentionally left untouched (see the
164    /// over-indent pass in `check`), so there is no down-shift case to handle.
165    ///
166    /// Why a compound fix rather than three independent fixes? MD077 and
167    /// MD031 run in the same iterative fix loop. If we only moved the
168    /// delimiters, an intermediate state would have mismatched
169    /// opener/closer indentation and MD031 would misread the block as
170    /// unpaired, injecting stray blank lines (issue #574).
171    ///
172    /// Why `max(interior, required)` instead of `interior + delta`? The
173    /// delta-shift version was not idempotent: if interior started below
174    /// the list scope (e.g., col 0 under an opener at col 2 that needs to
175    /// move to col 3), delta-shift landed interior at col 1 — still below
176    /// the list scope — and the next MD077 pass would re-flag it
177    /// individually and snap it to `required`. The promote-up rule reaches
178    /// that end state in a single pass.
179    ///
180    /// Leading tabs are normalized to spaces: CommonMark expands a tab to
181    /// the next column that's a multiple of 4, so simply prepending spaces
182    /// before a tab would let the tab snap back and cancel the shift. We
183    /// replace the whole leading-whitespace byte range with spaces.
184    fn build_compound_fence_fix(
185        ctx: &LintContext,
186        opener_line: usize,
187        closer_line: usize,
188        opener_actual: usize,
189        required: usize,
190    ) -> Option<Fix> {
191        if required <= opener_actual {
192            return None;
193        }
194        let opener_info = ctx.line_info(opener_line)?;
195        let closer_info = ctx.line_info(closer_line)?;
196
197        let fix_start = opener_info.byte_offset;
198        let fix_end = closer_info.byte_offset + closer_info.byte_len;
199
200        let mut replacement = String::new();
201        for i in opener_line..=closer_line {
202            let info = ctx.line_info(i)?;
203            if i > opener_line {
204                replacement.push('\n');
205            }
206            let line = info.content(ctx.content);
207            if info.is_blank {
208                // Blank lines have no content to shift; preserve verbatim.
209                replacement.push_str(line);
210            } else {
211                let new_visual = if i == opener_line || i == closer_line {
212                    required
213                } else {
214                    info.visual_indent.max(required)
215                };
216                for _ in 0..new_visual {
217                    replacement.push(' ');
218                }
219                replacement.push_str(&line[info.indent..]);
220            }
221        }
222
223        Some(Fix::new(fix_start..fix_end, replacement))
224    }
225
226    /// Walk the continuation lines owned by a single list item, invoking
227    /// `per_line` for each *in-scope, non-blank, non-nested, non-skipped*
228    /// line with its pre-computed visual column and loose/tight state.
229    ///
230    /// This is the **single source of truth** for MD077's item-scope
231    /// traversal: both the sibling-column pre-pass and the main check loop
232    /// route through this method so their termination semantics cannot
233    /// drift. The callback sees only lines the rule actually needs to
234    /// reason about; it can return `ControlFlow::Break` for early exit.
235    ///
236    /// Termination conditions (applied before the callback fires):
237    /// - Headings and horizontal rules end the item unconditionally.
238    /// - After a blank line, content at or below the marker column has
239    ///   escaped the item; further lines are not delivered.
240    ///
241    /// Skipped silently (do not fire the callback):
242    /// - Blank lines (toggle `saw_blank`).
243    /// - Nested list items (reset `saw_blank`, track their content column).
244    /// - Lines inside any still-open nested item's scope: the walk keeps a
245    ///   stack of open nested (marker, content) columns, so a continuation
246    ///   of a middle nesting level defers to that level's own walk instead
247    ///   of being claimed by a shallower ancestor.
248    /// - Reference/footnote/abbreviation definitions and similar block
249    ///   constructs that aren't list continuation.
250    /// - Lines that `should_skip_line` rejects (code-block interior etc.).
251    fn walk_item_continuation<F>(
252        ctx: &LintContext,
253        item_line: usize,
254        range_end: usize,
255        marker_col: usize,
256        mut per_line: F,
257    ) where
258        F: FnMut(&ContinuationLine<'_>) -> ControlFlow<()>,
259    {
260        let mut saw_blank = false;
261        let mut saw_nested = false;
262        // Stack of open nested items as (marker_column, content_column),
263        // outermost first. A single scalar is not enough: with 3+ levels a
264        // continuation of a middle level sits below the innermost content
265        // column but at-or-past its own level's, and must still be skipped
266        // here so the owning level's walk evaluates it.
267        let mut nested_stack: Vec<(usize, usize)> = Vec::new();
268
269        for line_num in (item_line + 1)..=range_end {
270            let Some(info) = ctx.line_info(line_num) else {
271                continue;
272            };
273
274            let trimmed = info.content(ctx.content).trim_start();
275
276            if Self::should_skip_line(info, trimmed) {
277                continue;
278            }
279
280            if info.is_blank {
281                saw_blank = true;
282                continue;
283            }
284
285            if let Some(ref li) = info.list_item {
286                if li.marker_column > marker_col {
287                    // A sibling-or-shallower marker closes every nested item at
288                    // or past its column before this one opens.
289                    while nested_stack.last().is_some_and(|&(m, _)| m >= li.marker_column) {
290                        nested_stack.pop();
291                    }
292                    nested_stack.push((li.marker_column, li.content_column));
293                    // Sticky: once a nested child appears, every later line is a
294                    // (lazy) continuation of the deeper item, which owns it under
295                    // CommonMark. Ancestors must defer so the deepest item claims
296                    // and aligns it.
297                    saw_nested = true;
298                } else {
299                    nested_stack.clear();
300                }
301                saw_blank = false;
302                continue;
303            }
304
305            if info.heading.is_some() || info.is_horizontal_rule {
306                break;
307            }
308
309            if Self::is_block_level_construct(trimmed) {
310                continue;
311            }
312
313            let col = info.visual_indent;
314
315            // The line escapes every nested item whose content column it sits
316            // below; if any nested item stays open, the line is that item's
317            // continuation and its own walk owns the judgement.
318            while nested_stack.last().is_some_and(|&(_, c)| c > col) {
319                nested_stack.pop();
320            }
321            if !nested_stack.is_empty() {
322                continue;
323            }
324
325            if saw_blank && col <= marker_col {
326                break;
327            }
328
329            let line = ContinuationLine {
330                line_num,
331                info,
332                trimmed,
333                actual: col,
334                saw_blank,
335                saw_nested,
336            };
337            if per_line(&line).is_break() {
338                break;
339            }
340        }
341    }
342
343    /// Whether the item's owned continuation range holds a *latent* structural
344    /// construct: a list marker or table line the parser has not yet promoted to
345    /// its own block, but would once an earlier continuation line is reindented.
346    /// Such a promotion re-attributes the following lines to a different block
347    /// (different content column) and breaks single-pass idempotency, so the
348    /// caller skips the whole item when this returns true.
349    ///
350    /// Unlike [`walk_item_continuation`], this scans the full owned range and
351    /// does NOT stop at a heading or horizontal rule. A heading partway through
352    /// the continuation can itself be parse-unstable: an empty backtick run, for
353    /// instance, is read as a setext heading, and reindenting an earlier line
354    /// dissolves it and promotes a list marker that sits past it. Stopping at the
355    /// heading would hide that marker from this check and let the reindent break
356    /// idempotency. Lines already parsed as list items are real nested children,
357    /// not latent, and are handled by the walk's `saw_nested` logic instead.
358    fn item_range_has_latent_structure(ctx: &LintContext, item_line: usize, range_end: usize) -> bool {
359        (item_line + 1..=range_end).any(|line_num| {
360            ctx.line_info(line_num).is_some_and(|info| {
361                if info.is_blank || info.list_item.is_some() {
362                    return false;
363                }
364                let trimmed = info.content(ctx.content).trim_start();
365                !Self::should_skip_line(info, trimmed)
366                    && (Self::starts_with_list_marker(trimmed) || crate::utils::skip_context::is_table_line(trimmed))
367            })
368        })
369    }
370
371    /// Scan an item's owned range and report whether any *other* continuation
372    /// line in the item uses the content column or the post-checkbox column.
373    ///
374    /// Used exclusively for tie-breaking the auto-fix target when an
375    /// over-indented line is exactly equidistant from `content_col` and
376    /// `task_col`. In that case the author's intent is ambiguous, so we
377    /// snap to whichever valid column *they're already using* elsewhere in
378    /// the same item. When neither or both columns are in use, the caller
379    /// falls back to a canonical default.
380    fn sibling_column_usage(
381        ctx: &LintContext,
382        item_line: usize,
383        range_end: usize,
384        marker_col: usize,
385        content_col: usize,
386        task_col: usize,
387    ) -> (bool, bool) {
388        let mut uses_content = false;
389        let mut uses_task = false;
390
391        Self::walk_item_continuation(ctx, item_line, range_end, marker_col, |line| {
392            if line.actual == content_col {
393                uses_content = true;
394            }
395            if line.actual == task_col {
396                uses_task = true;
397            }
398            if uses_content && uses_task {
399                ControlFlow::Break(())
400            } else {
401                ControlFlow::Continue(())
402            }
403        });
404
405        (uses_content, uses_task)
406    }
407
408    /// Compute the auto-fix target for an over-indented continuation line.
409    /// Snaps to the nearer of the two valid columns (content_col / task_col)
410    /// for task items, and on an exact tie uses sibling-column context to
411    /// pick whichever column the author is already using elsewhere in this
412    /// item. Non-task items always snap to `required`.
413    fn compute_fix_target(
414        actual: usize,
415        required: usize,
416        task_col: Option<usize>,
417        uses_content_col: bool,
418        uses_task_col: bool,
419    ) -> usize {
420        let Some(t) = task_col else { return required };
421        match actual.abs_diff(t).cmp(&actual.abs_diff(required)) {
422            std::cmp::Ordering::Less => t,
423            std::cmp::Ordering::Greater => required,
424            std::cmp::Ordering::Equal => match (uses_task_col, uses_content_col) {
425                (true, false) => t,
426                _ => required,
427            },
428        }
429    }
430
431    /// Check if a line should be skipped (inside code, HTML, frontmatter, etc.)
432    ///
433    /// Code block *content* is skipped, but fence opener/closer lines are not —
434    /// their indentation matters for list continuation in MkDocs.
435    ///
436    /// Footnote-definition lines (the `[^id]:` line and its indented body) are
437    /// skipped too: a footnote body that follows a list is its own block, not
438    /// list continuation, so its indentation is MD068's concern, not MD077's.
439    /// Treating it as continuation produced false over-indent warnings and a
440    /// damaging auto-fix that reindented the body and then tripped MD068.
441    fn should_skip_line(info: &crate::lint_context::LineInfo, trimmed: &str) -> bool {
442        if info.in_code_block && !Self::is_code_fence(trimmed) {
443            return true;
444        }
445        info.in_front_matter
446            || info.in_footnote_definition
447            || info.in_html_block
448            || info.in_html_comment
449            || info.in_mdx_comment
450            || info.in_mkdocstrings
451            || info.in_esm_block
452            || info.in_math_block
453            || info.in_admonition
454            || info.in_content_tab
455            || info.in_pymdown_block
456            || info.in_definition_list
457            || info.in_mkdocs_html_markdown
458            || info.in_kramdown_extension_block
459    }
460
461    /// Build the warning for an over-indented continuation line. The fix is a
462    /// single-line rewrite of the leading whitespace to `fix_target`.
463    ///
464    /// The over-indent pass never delivers fenced-code lines here (it skips
465    /// anything `in_code_block`), so this builder does not need the compound
466    /// fence handling that `build_under_indent_warning` uses: moving an
467    /// over-indented fence's delimiters without its body would corrupt the code
468    /// content, so over-indented fenced blocks are deliberately left as-is.
469    fn build_over_indent_warning(
470        ctx: &LintContext,
471        line: &ContinuationLine<'_>,
472        fix_target: usize,
473        message: String,
474    ) -> LintWarning {
475        let line_content = line.info.content(ctx.content);
476        let fix_start = line.info.byte_offset;
477        let fix_end = fix_start + line.info.indent;
478        LintWarning {
479            rule_name: Some("MD077".to_string()),
480            line: line.line_num,
481            column: 1,
482            end_line: line.line_num,
483            end_column: line_content.chars().count() + 1,
484            message,
485            severity: Severity::Warning,
486            fix: Some(Fix::new(fix_start..fix_end, " ".repeat(fix_target))),
487        }
488    }
489
490    /// Build the warning for a loose-mode under-indented continuation line.
491    /// When the line is the opener of a fenced code block, emit a compound
492    /// fix that reindents opener + interior + closer atomically so MD031
493    /// doesn't see a transiently-broken fence pair (see #574).
494    ///
495    /// Returns the warning plus, when the fix is compound, the closer
496    /// line number so the caller can mark it flagged (preventing the
497    /// main loop from double-flagging the closer as its own under-indent
498    /// case). Keeping the "also flag this line" signal out of band keeps
499    /// this function pure — it reads from `ctx` only and returns a
500    /// plain value.
501    fn build_under_indent_warning(
502        ctx: &LintContext,
503        line: &ContinuationLine<'_>,
504        required: usize,
505        message: String,
506    ) -> UnderIndentOutcome {
507        let line_content = line.info.content(ctx.content);
508        let is_fence_opener = line.info.in_code_block
509            && Self::is_code_fence(line.trimmed)
510            && ctx.line_info(line.line_num - 1).is_none_or(|p| !p.in_code_block);
511
512        let (fix, warn_end_line, warn_end_column, compound_closer) = if is_fence_opener {
513            let closer_line = Self::find_fence_closer(ctx, line.line_num);
514            let fix = Self::build_compound_fence_fix(ctx, line.line_num, closer_line, line.actual, required);
515            let end_column = ctx
516                .line_info(closer_line)
517                .map_or(line_content.chars().count() + 1, |ci| {
518                    ci.content(ctx.content).chars().count() + 1
519                });
520            let extra_flag = (closer_line != line.line_num).then_some(closer_line);
521            (fix, closer_line, end_column, extra_flag)
522        } else {
523            let fix_start = line.info.byte_offset;
524            let fix_end = fix_start + line.info.indent;
525            let fix = Some(Fix::new(fix_start..fix_end, " ".repeat(required)));
526            (fix, line.line_num, line_content.chars().count() + 1, None)
527        };
528
529        UnderIndentOutcome {
530            warning: LintWarning {
531                rule_name: Some("MD077".to_string()),
532                line: line.line_num,
533                column: 1,
534                end_line: warn_end_line,
535                end_column: warn_end_column,
536                message,
537                severity: Severity::Warning,
538                fix,
539            },
540            also_flag_line: compound_closer,
541        }
542    }
543}
544
545/// A continuation line yielded by `walk_item_continuation`. Bundles the
546/// per-line facts both checker branches need so helper functions don't
547/// balloon their argument lists.
548struct ContinuationLine<'a> {
549    line_num: usize,
550    info: &'a LineInfo,
551    trimmed: &'a str,
552    actual: usize,
553    saw_blank: bool,
554    /// True once a nested child item has appeared earlier in this item's scope.
555    /// Subsequent lines are lazy continuation of the deeper item (which owns
556    /// them under CommonMark), so an ancestor must not claim them.
557    saw_nested: bool,
558}
559
560/// Result of `build_under_indent_warning`. Carries both the warning and,
561/// when the fix is compound (fence opener → promote-to-required over the
562/// whole block), the closer line so the caller can record it as already
563/// handled. This keeps the warning builder free of external mutation.
564struct UnderIndentOutcome {
565    warning: LintWarning,
566    also_flag_line: Option<usize>,
567}
568
569impl Rule for MD077ListContinuationIndent {
570    fn name(&self) -> &'static str {
571        "MD077"
572    }
573
574    fn description(&self) -> &'static str {
575        "List continuation content indentation"
576    }
577
578    fn check(&self, ctx: &LintContext) -> LintResult {
579        if ctx.content.is_empty() {
580            return Ok(Vec::new());
581        }
582
583        let strict_indent = ctx.flavor.requires_strict_list_indent();
584        let total_lines = ctx.lines.len();
585        let mut warnings = Vec::new();
586        let mut flagged_lines = std::collections::HashSet::new();
587
588        // Collect all list item lines sorted, with their content_column,
589        // marker_column, and — if the item is a GFM task — its post-checkbox
590        // column. Precomputing task_col here (instead of re-reading line_info
591        // inside the hot inner loop) keeps the per-item cost O(1).
592        //
593        // We need the owned range to extend past block.end_line because the
594        // parser excludes under-indented continuation from the block, and
595        // MD077 specifically has to evaluate those escaped lines.
596        let mut items: Vec<(usize, usize, usize, Option<usize>)> = Vec::new();
597        for block in &ctx.list_blocks {
598            for &item_line in &block.item_lines {
599                if let Some(info) = ctx.line_info(item_line)
600                    && let Some(ref li) = info.list_item
601                {
602                    let line = info.content(ctx.content);
603                    let task_col = Self::is_task_list_item(line, li.content_column)
604                        .then_some(li.content_column + Self::TASK_CHECKBOX_PREFIX_LEN);
605                    items.push((item_line, li.marker_column, li.content_column, task_col));
606                }
607            }
608        }
609        items.sort_unstable();
610        items.dedup_by_key(|&mut (ln, _, _, _)| ln);
611
612        // Precompute each item's owned-range end. The range ends at the line
613        // before the next item whose marker column is <= this item's (its next
614        // sibling or an ancestor), or the last line if none follows.
615        //
616        // The direct "scan forward for the next marker_col <= mine" is O(n^2) on
617        // a monotonically deepening list, where no later item ever qualifies so
618        // every item scans to the end. A monotonic stack (nearest
619        // smaller-or-equal marker column to the right) computes all range ends in
620        // one linear pass. Walking right-to-left, pop every stacked item whose
621        // marker column is strictly greater than the current one (they can never
622        // be the sibling/ancestor of anything further left that is <= current),
623        // leaving the nearest qualifying item on top.
624        let mut range_ends = vec![total_lines; items.len()];
625        let mut stack: Vec<usize> = Vec::new();
626        for i in (0..items.len()).rev() {
627            let marker_col = items[i].1;
628            while let Some(&top) = stack.last() {
629                if items[top].1 > marker_col {
630                    stack.pop();
631                } else {
632                    break;
633                }
634            }
635            range_ends[i] = stack.last().map_or(total_lines, |&j| items[j].0 - 1);
636            stack.push(i);
637        }
638
639        // Precompute each item's required indent and owned line range so both
640        // passes below scope identically.
641        let scoped: Vec<(usize, usize, usize, Option<usize>, usize, usize)> = items
642            .iter()
643            .enumerate()
644            .map(|(item_idx, &(item_line, marker_col, content_col, task_col))| {
645                let required = if strict_indent { content_col.max(4) } else { content_col };
646                (
647                    item_line,
648                    marker_col,
649                    content_col,
650                    task_col,
651                    required,
652                    range_ends[item_idx],
653                )
654            })
655            .collect();
656
657        // Precompute which lines can ever reach the per-line continuation
658        // callback. `walk_item_continuation` unconditionally skips (regardless of
659        // which item owns the line) blank lines, list-item lines, headings,
660        // horizontal rules, `should_skip_line` lines, and block-level constructs;
661        // only the lines that survive all of those can be flagged. An item whose
662        // owned range contains none of them produces no warning, so both passes
663        // can skip it without walking the range at all.
664        //
665        // This keeps a document of purely deeply-nested list items linear: such a
666        // document has no continuation prose, so every item skips its walk
667        // instead of re-scanning the whole tail (which was O(n^2) in the item
668        // count). Documents that do have continuation prose are unaffected - the
669        // guard only ever skips items that could not have produced a warning.
670        let prose_candidate_lines: Vec<usize> = (1..=total_lines)
671            .filter(|&line_num| {
672                let Some(info) = ctx.line_info(line_num) else {
673                    return false;
674                };
675                let trimmed = info.content(ctx.content).trim_start();
676                !Self::should_skip_line(info, trimmed)
677                    && !info.is_blank
678                    && info.list_item.is_none()
679                    && info.heading.is_none()
680                    && !info.is_horizontal_rule
681                    && !Self::is_block_level_construct(trimmed)
682            })
683            .collect();
684        // True when a continuation candidate falls in `(after_line, range_end]`,
685        // i.e. the half-open range `walk_item_continuation` actually visits.
686        let range_has_prose_candidate = |after_line: usize, range_end: usize| -> bool {
687            let start = prose_candidate_lines.partition_point(|&l| l <= after_line);
688            prose_candidate_lines.get(start).is_some_and(|&l| l <= range_end)
689        };
690
691        // Pass 1 - under-indented continuation.
692        //
693        // Loose under-indent (after a blank line) sits below the content column
694        // and would escape the list item; it is always flagged. Tight
695        // under-indent is valid CommonMark lazy continuation, so it is left
696        // alone under `style = "any"`.
697        //
698        // Under `style = "aligned"`, tight under-indent is additionally flagged
699        // and snapped up to the content column. MD077 scopes past the parser's
700        // block end (to catch escaped loose content), and the parser absorbs
701        // col-0 blockquotes, fences, and tables that sit tight under a list item
702        // as lazy continuation. Reindenting those would change the rendered
703        // structure, so the tight-aligned branch guards two ways: it skips lines
704        // the parser classified in place (code, blockquote - see
705        // `confirmed_structure`), and it bails on an item whose continuation
706        // holds a construct the parser would re-parse once indentation changes
707        // (a latent list marker or table - see `has_latent_structure`). Headings
708        // and horizontal rules already terminate the walk; reference/footnote/
709        // abbreviation definitions are skipped inside it. Erring toward skipping
710        // yields false negatives (safe) rather than structural false positives.
711        //
712        // This pass runs first so that a deeply nested item claims an ambiguous
713        // line - one that is under-indented for it yet over-indented for a
714        // shallower ancestor - before pass 2 can mis-attribute it to the
715        // ancestor as an over-indent and snap it the wrong way.
716        let aligned = self.config.style == ContinuationStyle::Aligned;
717        for &(item_line, marker_col, _content_col, _task_col, required, range_end) in &scoped {
718            // No continuation candidate in this item's range: it cannot produce a
719            // warning, so skip the walk (and the latent-structure scan) entirely.
720            if !range_has_prose_candidate(item_line, range_end) {
721                continue;
722            }
723            // "Latent structure": a line in this item's continuation that the
724            // parser has NOT yet promoted to a list item or table, but that
725            // would be once an earlier continuation line is reindented. Such a
726            // promotion re-attributes the following lines to a different block
727            // (different content column) and breaks single-pass idempotency, so
728            // reindenting anything in the item is unsafe and the whole item is
729            // skipped. This is a *prediction* of how the parser would re-parse
730            // after a fix, which is why it stays a heuristic (markers and tables
731            // are the only constructs the parser absorbs as lazy continuation
732            // rather than flagging on the line itself; code and blockquotes are
733            // classified in place and handled per line below). Well-formed prose
734            // continuation matches neither, so this only bails on pathological
735            // input (a safe false negative). Real nested items never reach the
736            // callback (the walk handles them via `saw_nested`).
737            let has_latent_structure = aligned && Self::item_range_has_latent_structure(ctx, item_line, range_end);
738            Self::walk_item_continuation(ctx, item_line, range_end, marker_col, |line| {
739                let actual = line.actual;
740                let under_indented = actual < required;
741                let loose_escape = line.saw_blank && under_indented;
742                // Don't reindent a line the parser classified in place as a code
743                // block (fenced or indented) or a blockquote: these are read
744                // straight from its per-line output, so the rule cannot drift
745                // from how rumdl parses the document. Headings and horizontal
746                // rules terminate the walk before the callback; latent list
747                // markers and tables are handled by `has_latent_structure`.
748                let confirmed_structure = line.info.in_code_block || line.info.blockquote.is_some();
749                let aligned_tight = aligned
750                    && !has_latent_structure
751                    && !line.saw_blank
752                    && !line.saw_nested
753                    && under_indented
754                    && !confirmed_structure;
755                if (loose_escape || aligned_tight) && flagged_lines.insert(line.line_num) {
756                    let message = if line.saw_blank {
757                        if strict_indent {
758                            format!(
759                                "Content inside list item needs {required} spaces of indentation \
760                                 for MkDocs compatibility (found {actual})",
761                            )
762                        } else {
763                            format!(
764                                "Content after blank line in list item needs {required} spaces of \
765                                 indentation to remain part of the list (found {actual})",
766                            )
767                        }
768                    } else {
769                        format!("Continuation line under-indented (expected {required}, found {actual})")
770                    };
771                    let outcome = Self::build_under_indent_warning(ctx, line, required, message);
772                    if let Some(closer_line) = outcome.also_flag_line {
773                        flagged_lines.insert(closer_line);
774                    }
775                    warnings.push(outcome.warning);
776                }
777                ControlFlow::Continue(())
778            });
779        }
780
781        // Pass 2 - over-indented continuation (tight or loose): prose pushed
782        // past the content column is snapped back. Fenced code blocks are
783        // skipped here (`!in_code_block`): an over-indented fence is cosmetic
784        // (the code still renders), and reindenting only its delimiters - the
785        // body is skipped by `should_skip_line` - would alter the literal code
786        // content. Indented code blocks (content column + 4 or more) are also
787        // `in_code_block`, so a blank line before such a body does not exempt
788        // it from being recognized as code rather than over-indented prose.
789        for &(item_line, marker_col, content_col, task_col, required, range_end) in &scoped {
790            // No continuation candidate in this item's range: nothing to flag.
791            if !range_has_prose_candidate(item_line, range_end) {
792                continue;
793            }
794            // For task items, gather sibling-column usage once so the auto-fix
795            // can tie-break equidistant over-indents toward whichever valid
796            // column the author is already using.
797            let (uses_content_col, uses_task_col) = match task_col {
798                Some(t) => Self::sibling_column_usage(ctx, item_line, range_end, marker_col, content_col, t),
799                None => (false, false),
800            };
801
802            Self::walk_item_continuation(ctx, item_line, range_end, marker_col, |line| {
803                let actual = line.actual;
804                if actual > required
805                    && !line.info.in_code_block
806                    && Some(actual) != task_col
807                    && !Self::starts_with_list_marker(line.trimmed)
808                    && flagged_lines.insert(line.line_num)
809                {
810                    let fix_target =
811                        Self::compute_fix_target(actual, required, task_col, uses_content_col, uses_task_col);
812                    let message = match task_col {
813                        Some(t) => format!(
814                            "Continuation line over-indented \
815                             (expected {required} or {t}, found {actual})"
816                        ),
817                        None => {
818                            format!("Continuation line over-indented (expected {required}, found {actual})")
819                        }
820                    };
821                    warnings.push(Self::build_over_indent_warning(ctx, line, fix_target, message));
822                }
823                ControlFlow::Continue(())
824            });
825        }
826
827        // The two passes emit independently, so order by position before
828        // returning - callers and tests expect document order.
829        warnings.sort_by_key(|w| (w.line, w.column));
830
831        Ok(warnings)
832    }
833
834    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
835        let warnings = self.check(ctx)?;
836        let warnings =
837            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
838        if warnings.is_empty() {
839            return Ok(ctx.content.to_string());
840        }
841
842        // Sort fixes by byte position descending to apply from end to start
843        let mut fixes: Vec<Fix> = warnings.into_iter().filter_map(|w| w.fix).collect();
844        fixes.sort_by_key(|f| std::cmp::Reverse(f.range.start));
845
846        let mut content = ctx.content.to_string();
847        for fix in fixes {
848            if fix.range.start <= content.len() && fix.range.end <= content.len() {
849                content.replace_range(fix.range, &fix.replacement);
850            }
851        }
852
853        Ok(content)
854    }
855
856    fn category(&self) -> RuleCategory {
857        RuleCategory::List
858    }
859
860    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
861        ctx.content.is_empty() || ctx.list_blocks.is_empty()
862    }
863
864    fn as_any(&self) -> &dyn std::any::Any {
865        self
866    }
867
868    crate::impl_rule_config_methods!(MD077Config);
869}
870
871#[cfg(test)]
872mod tests {
873    use super::*;
874    use crate::config::MarkdownFlavor;
875
876    fn check(content: &str) -> Vec<LintWarning> {
877        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
878        let rule = MD077ListContinuationIndent::default();
879        rule.check(&ctx).unwrap()
880    }
881
882    fn check_mkdocs(content: &str) -> Vec<LintWarning> {
883        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
884        let rule = MD077ListContinuationIndent::default();
885        rule.check(&ctx).unwrap()
886    }
887
888    fn fix(content: &str) -> String {
889        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
890        let rule = MD077ListContinuationIndent::default();
891        rule.fix(&ctx).unwrap()
892    }
893
894    fn fix_mkdocs(content: &str) -> String {
895        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
896        let rule = MD077ListContinuationIndent::default();
897        rule.fix(&ctx).unwrap()
898    }
899
900    fn aligned_rule() -> MD077ListContinuationIndent {
901        MD077ListContinuationIndent::new(ContinuationStyle::Aligned)
902    }
903
904    fn check_aligned(content: &str) -> Vec<LintWarning> {
905        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
906        aligned_rule().check(&ctx).unwrap()
907    }
908
909    fn check_aligned_mkdocs(content: &str) -> Vec<LintWarning> {
910        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
911        aligned_rule().check(&ctx).unwrap()
912    }
913
914    fn fix_aligned(content: &str) -> String {
915        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
916        aligned_rule().fix(&ctx).unwrap()
917    }
918
919    fn fix_aligned_quarto(content: &str) -> String {
920        let ctx = LintContext::new(content, MarkdownFlavor::Quarto, None);
921        aligned_rule().fix(&ctx).unwrap()
922    }
923
924    #[test]
925    fn aligned_idempotent_with_latent_marker_behind_unstable_heading() {
926        // Regression: an empty backtick run (`` ``\n`` ``) is parsed as a setext
927        // heading. That heading used to terminate the latent-structure walk
928        // before it reached the `- ` marker on the next line, so the marker was
929        // not detected as latent. Reindenting the `1. ` continuation then
930        // promoted `- ` to a real list item, producing a fresh under-indent
931        // violation on the second pass and breaking single-pass idempotency.
932        // The latent-structure scan now spans the full owned range, detects the
933        // marker, and leaves the (ambiguous) item alone.
934        let input = "1. \n``\n``\n- \n``";
935        let once = fix_aligned_quarto(input);
936        let twice = fix_aligned_quarto(&once);
937        assert_eq!(once, twice, "MD077 aligned fix must be idempotent (Quarto)");
938    }
939
940    // ── Tight continuation (no blank line) ─────────────────────────────
941
942    #[test]
943    fn tight_lazy_continuation_zero_indent_not_flagged() {
944        // Zero-indent lazy continuation is valid CommonMark
945        let content = "- Item\ncontinuation\n";
946        assert!(check(content).is_empty());
947    }
948
949    #[test]
950    fn tight_continuation_correct_indent_not_flagged() {
951        // Correctly indented tight continuation (aligns with content column)
952        let content = "1. Item\n   continuation\n";
953        assert!(check(content).is_empty());
954    }
955
956    #[test]
957    fn tight_continuation_over_indented_ordered() {
958        // "1. " = 3 chars, but continuation has 4 spaces
959        let content = "1. This is a list item with multiple lines.\n    The second line is over-indented.\n";
960        let warnings = check(content);
961        assert_eq!(warnings.len(), 1);
962        assert_eq!(warnings[0].line, 2);
963        assert!(warnings[0].message.contains("over-indented"));
964    }
965
966    #[test]
967    fn tight_continuation_over_indented_unordered() {
968        // "- " = 2 chars, but continuation has 3 spaces
969        let content = "- Item\n   over-indented\n";
970        let warnings = check(content);
971        assert_eq!(warnings.len(), 1);
972        assert_eq!(warnings[0].line, 2);
973    }
974
975    #[test]
976    fn tight_continuation_multiple_over_indented_lines() {
977        let content = "1. Item\n    line one\n    line two\n    line three\n";
978        let warnings = check(content);
979        assert_eq!(warnings.len(), 3);
980    }
981
982    #[test]
983    fn tight_continuation_mixed_correct_and_over() {
984        let content = "1. Item\n   correct\n    over-indented\n   correct again\n";
985        let warnings = check(content);
986        assert_eq!(warnings.len(), 1);
987        assert_eq!(warnings[0].line, 3);
988    }
989
990    #[test]
991    fn tight_continuation_nested_over_indented() {
992        // L2 "- " at column 2, content_column = 4. Continuation at 5 is over-indented for L2.
993        let content = "- L1\n  - L2\n     over-indented continuation of L2\n";
994        let warnings = check(content);
995        assert_eq!(warnings.len(), 1);
996        assert_eq!(warnings[0].line, 3);
997        // Must report expected=4 (L2's content_col), not expected=2 (L1's)
998        assert!(warnings[0].message.contains("expected 4"));
999        assert!(warnings[0].message.contains("found 5"));
1000    }
1001
1002    #[test]
1003    fn tight_continuation_nested_correct_indent_not_flagged() {
1004        // Continuation at 4 spaces is correct for L2 (content_col=4). Must NOT be
1005        // flagged as over-indented relative to L1 (content_col=2).
1006        let content = "- L1\n  - L2\n    correctly indented continuation of L2\n";
1007        assert!(check(content).is_empty());
1008    }
1009
1010    #[test]
1011    fn fix_tight_continuation_nested_over_indented() {
1012        // Fix should reduce to 4 spaces (L2's content_col), not 2 (L1's)
1013        let content = "- L1\n  - L2\n     over-indented continuation of L2\n";
1014        let fixed = fix(content);
1015        assert_eq!(fixed, "- L1\n  - L2\n    over-indented continuation of L2\n");
1016    }
1017
1018    #[test]
1019    fn tight_continuation_under_indented_not_flagged() {
1020        // 2 spaces instead of 3 for "1. " — under-indented, not over-indented.
1021        // Valid lazy continuation in CommonMark, so not flagged.
1022        let content = "1. Item\n  under-indented\n";
1023        assert!(check(content).is_empty());
1024    }
1025
1026    #[test]
1027    fn tight_continuation_tab_over_indented() {
1028        // A tab expands to 4 visual columns, which exceeds content_col=2 for "- "
1029        let content = "- Item\n\tover-indented\n";
1030        let warnings = check(content);
1031        assert_eq!(warnings.len(), 1);
1032    }
1033
1034    #[test]
1035    fn fix_tight_continuation_over_indented_ordered() {
1036        let content = "1. This is a list item with multiple lines.\n    The second line is over-indented.\n";
1037        let fixed = fix(content);
1038        assert_eq!(
1039            fixed,
1040            "1. This is a list item with multiple lines.\n   The second line is over-indented.\n"
1041        );
1042    }
1043
1044    #[test]
1045    fn fix_tight_continuation_over_indented_unordered() {
1046        let content = "- Item\n   over-indented\n";
1047        let fixed = fix(content);
1048        assert_eq!(fixed, "- Item\n  over-indented\n");
1049    }
1050
1051    #[test]
1052    fn fix_tight_continuation_multiple_lines() {
1053        let content = "1. Item\n    line one\n    line two\n";
1054        let fixed = fix(content);
1055        assert_eq!(fixed, "1. Item\n   line one\n   line two\n");
1056    }
1057
1058    #[test]
1059    fn tight_continuation_mkdocs_4space_ordered_not_flagged() {
1060        // MkDocs requires max(3, 4) = 4 spaces for "1. " items.
1061        // 4-space tight continuation is correct, not over-indented.
1062        let content = "1. Item\n    continuation\n";
1063        assert!(check_mkdocs(content).is_empty());
1064    }
1065
1066    #[test]
1067    fn tight_continuation_mkdocs_5space_ordered_flagged() {
1068        // 5 spaces exceeds the MkDocs required indent of 4
1069        let content = "1. Item\n     over-indented\n";
1070        let warnings = check_mkdocs(content);
1071        assert_eq!(warnings.len(), 1);
1072        assert!(warnings[0].message.contains("expected 4"));
1073        assert!(warnings[0].message.contains("found 5"));
1074    }
1075
1076    #[test]
1077    fn fix_tight_continuation_mkdocs_over_indented() {
1078        let content = "1. Item\n     over-indented\n";
1079        let fixed = fix_mkdocs(content);
1080        assert_eq!(fixed, "1. Item\n    over-indented\n");
1081    }
1082
1083    #[test]
1084    fn tight_continuation_deeply_indented_list_markers_not_flagged() {
1085        // Deeply indented list markers (e.g., indent=8 in MD007) may not be
1086        // recognized as list items by the parser. MD077 must not flag them.
1087        let content = "* Level 0\n        * Level 1\n                * Level 2\n";
1088        assert!(check(content).is_empty());
1089    }
1090
1091    #[test]
1092    fn tight_continuation_ordered_marker_not_flagged() {
1093        // Indented ordered list marker should not be flagged
1094        let content = "- Parent\n      1. Child item\n";
1095        assert!(check(content).is_empty());
1096    }
1097
1098    // ── Unordered list: correct indent after blank ────────────────────
1099
1100    #[test]
1101    fn unordered_correct_indent_no_warning() {
1102        let content = "- Item\n\n  continuation\n";
1103        assert!(check(content).is_empty());
1104    }
1105
1106    #[test]
1107    fn unordered_partial_indent_warns() {
1108        // Content with some indent (above marker column) but less than
1109        // content_column is likely an indentation mistake.
1110        let content = "- Item\n\n continuation\n";
1111        let warnings = check(content);
1112        assert_eq!(warnings.len(), 1);
1113        assert_eq!(warnings[0].line, 3);
1114        assert!(warnings[0].message.contains("2 spaces"));
1115        assert!(warnings[0].message.contains("found 1"));
1116    }
1117
1118    #[test]
1119    fn unordered_zero_indent_is_new_paragraph() {
1120        // Content at 0 indent after a top-level list is a new paragraph, not
1121        // under-indented continuation.
1122        let content = "- Item\n\ncontinuation\n";
1123        assert!(check(content).is_empty());
1124    }
1125
1126    // ── Ordered list: CommonMark W+N ──────────────────────────────────
1127
1128    #[test]
1129    fn ordered_3space_correct_commonmark() {
1130        // "1. " is 3 chars, content_column = 3
1131        let content = "1. Item\n\n   continuation\n";
1132        assert!(check(content).is_empty());
1133    }
1134
1135    #[test]
1136    fn ordered_2space_under_indent_commonmark() {
1137        let content = "1. Item\n\n  continuation\n";
1138        let warnings = check(content);
1139        assert_eq!(warnings.len(), 1);
1140        assert!(warnings[0].message.contains("3 spaces"));
1141        assert!(warnings[0].message.contains("found 2"));
1142    }
1143
1144    // ── Multi-digit ordered markers ───────────────────────────────────
1145
1146    #[test]
1147    fn multi_digit_marker_correct() {
1148        // "10. " is 4 chars, content_column = 4
1149        let content = "10. Item\n\n    continuation\n";
1150        assert!(check(content).is_empty());
1151    }
1152
1153    #[test]
1154    fn multi_digit_marker_under_indent() {
1155        let content = "10. Item\n\n   continuation\n";
1156        let warnings = check(content);
1157        assert_eq!(warnings.len(), 1);
1158        assert!(warnings[0].message.contains("4 spaces"));
1159    }
1160
1161    // ── MkDocs flavor: 4-space minimum ────────────────────────────────
1162
1163    #[test]
1164    fn mkdocs_3space_ordered_warns() {
1165        // In MkDocs mode, 3-space indent on "1. " is not enough
1166        let content = "1. Item\n\n   continuation\n";
1167        let warnings = check_mkdocs(content);
1168        assert_eq!(warnings.len(), 1);
1169        assert!(warnings[0].message.contains("4 spaces"));
1170        assert!(warnings[0].message.contains("MkDocs"));
1171    }
1172
1173    #[test]
1174    fn mkdocs_4space_ordered_no_warning() {
1175        let content = "1. Item\n\n    continuation\n";
1176        assert!(check_mkdocs(content).is_empty());
1177    }
1178
1179    #[test]
1180    fn mkdocs_unordered_2space_ok() {
1181        // Unordered "- " has content_column = 2; max(2, 4) = 4 in mkdocs
1182        let content = "- Item\n\n    continuation\n";
1183        assert!(check_mkdocs(content).is_empty());
1184    }
1185
1186    #[test]
1187    fn mkdocs_unordered_2space_warns() {
1188        // "- " has content_column 2; MkDocs requires max(2,4) = 4
1189        let content = "- Item\n\n  continuation\n";
1190        let warnings = check_mkdocs(content);
1191        assert_eq!(warnings.len(), 1);
1192        assert!(warnings[0].message.contains("4 spaces"));
1193    }
1194
1195    // ── Auto-fix ──────────────────────────────────────────────────────
1196
1197    #[test]
1198    fn fix_unordered_indent() {
1199        // Partial indent (above marker column, below content column) gets fixed
1200        let content = "- Item\n\n continuation\n";
1201        let fixed = fix(content);
1202        assert_eq!(fixed, "- Item\n\n  continuation\n");
1203    }
1204
1205    #[test]
1206    fn fix_ordered_indent() {
1207        let content = "1. Item\n\n continuation\n";
1208        let fixed = fix(content);
1209        assert_eq!(fixed, "1. Item\n\n   continuation\n");
1210    }
1211
1212    #[test]
1213    fn fix_mkdocs_indent() {
1214        let content = "1. Item\n\n   continuation\n";
1215        let fixed = fix_mkdocs(content);
1216        assert_eq!(fixed, "1. Item\n\n    continuation\n");
1217    }
1218
1219    // ── Nested lists: only flag continuation, not sub-items ───────────
1220
1221    #[test]
1222    fn nested_list_items_not_flagged() {
1223        let content = "- Parent\n\n  - Child\n";
1224        assert!(check(content).is_empty());
1225    }
1226
1227    #[test]
1228    fn nested_list_zero_indent_is_new_paragraph() {
1229        // Content at 0 indent ends the list, not continuation
1230        let content = "- Parent\n  - Child\n\ncontinuation of parent\n";
1231        assert!(check(content).is_empty());
1232    }
1233
1234    #[test]
1235    fn nested_list_partial_indent_flagged() {
1236        // Content with partial indent (above parent marker, below content col)
1237        let content = "- Parent\n  - Child\n\n continuation of parent\n";
1238        let warnings = check(content);
1239        assert_eq!(warnings.len(), 1);
1240        assert!(warnings[0].message.contains("2 spaces"));
1241    }
1242
1243    // ── Code blocks inside items ─────────────────────────────────────
1244
1245    #[test]
1246    fn code_block_correctly_indented_no_warning() {
1247        // Fence lines and content all at correct indent for "- " (content_column = 2)
1248        let content = "- Item\n\n  ```\n  code\n  ```\n";
1249        assert!(check(content).is_empty());
1250    }
1251
1252    #[test]
1253    fn code_fence_under_indented_warns() {
1254        // Fence opener has 1-space indent, but "- " needs 2.
1255        // Only the opener is flagged — its compound fix also covers the
1256        // interior content and the matching closer (see issue #574).
1257        let content = "- Item\n\n ```\n code\n ```\n";
1258        let warnings = check(content);
1259        assert_eq!(warnings.len(), 1);
1260        assert_eq!(warnings[0].line, 3);
1261    }
1262
1263    #[test]
1264    fn code_fence_under_indented_ordered_mkdocs() {
1265        // Ordered list in MkDocs: "1. " needs max(3, 4) = 4 spaces
1266        // Fence at 3 spaces is correct for CommonMark but wrong for MkDocs
1267        let content = "1. Item\n\n   ```toml\n   key = \"value\"\n   ```\n";
1268        assert!(check(content).is_empty()); // Standard mode: 3 is fine
1269        let warnings = check_mkdocs(content);
1270        assert_eq!(warnings.len(), 1); // MkDocs: opener's compound fix covers the whole block
1271        assert_eq!(warnings[0].line, 3);
1272        assert!(warnings[0].message.contains("4 spaces"));
1273        assert!(warnings[0].message.contains("MkDocs"));
1274    }
1275
1276    #[test]
1277    fn code_fence_tilde_under_indented() {
1278        let content = "- Item\n\n ~~~\n code\n ~~~\n";
1279        let warnings = check(content);
1280        assert_eq!(warnings.len(), 1); // Tilde fences: single compound-fix warning on opener
1281        assert_eq!(warnings[0].line, 3);
1282    }
1283
1284    // ── Multiple blank lines ──────────────────────────────────────────
1285
1286    #[test]
1287    fn multiple_blank_lines_zero_indent_is_new_paragraph() {
1288        // Even with multiple blanks, 0-indent content is a new paragraph
1289        let content = "- Item\n\n\ncontinuation\n";
1290        assert!(check(content).is_empty());
1291    }
1292
1293    #[test]
1294    fn multiple_blank_lines_partial_indent_flags() {
1295        let content = "- Item\n\n\n continuation\n";
1296        let warnings = check(content);
1297        assert_eq!(warnings.len(), 1);
1298    }
1299
1300    // ── Empty items: no continuation to check ─────────────────────────
1301
1302    #[test]
1303    fn empty_item_no_warning() {
1304        let content = "- \n- Second\n";
1305        assert!(check(content).is_empty());
1306    }
1307
1308    // ── Multiple items, only some under-indented ──────────────────────
1309
1310    #[test]
1311    fn multiple_items_mixed_indent() {
1312        let content = "1. First\n\n   correct continuation\n\n2. Second\n\n  wrong continuation\n";
1313        let warnings = check(content);
1314        assert_eq!(warnings.len(), 1);
1315        assert_eq!(warnings[0].line, 7);
1316    }
1317
1318    // ── Task list items ───────────────────────────────────────────────
1319
1320    #[test]
1321    fn task_list_correct_indent() {
1322        // "- [ ] " = content_column is typically at col 6
1323        let content = "- [ ] Task\n\n      continuation\n";
1324        assert!(check(content).is_empty());
1325    }
1326
1327    // ── Frontmatter skipped ───────────────────────────────────────────
1328
1329    #[test]
1330    fn frontmatter_not_flagged() {
1331        let content = "---\ntitle: test\n---\n\n- Item\n\n  continuation\n";
1332        assert!(check(content).is_empty());
1333    }
1334
1335    // ── Fix produces valid output with multiple fixes ─────────────────
1336
1337    #[test]
1338    fn fix_multiple_items() {
1339        let content = "1. First\n\n wrong1\n\n2. Second\n\n wrong2\n";
1340        let fixed = fix(content);
1341        assert_eq!(fixed, "1. First\n\n   wrong1\n\n2. Second\n\n   wrong2\n");
1342    }
1343
1344    #[test]
1345    fn fix_multiline_loose_continuation_all_lines() {
1346        let content = "1. Item\n\n  line one\n  line two\n  line three\n";
1347        let fixed = fix(content);
1348        assert_eq!(fixed, "1. Item\n\n   line one\n   line two\n   line three\n");
1349    }
1350
1351    // ── No false positive when content is after sibling item ──────────
1352
1353    #[test]
1354    fn sibling_item_boundary_respected() {
1355        // The "continuation" after a blank belongs to "- Second", not "- First"
1356        let content = "- First\n- Second\n\n  continuation\n";
1357        assert!(check(content).is_empty());
1358    }
1359
1360    // ── Blockquote-nested lists ────────────────────────────────────────
1361
1362    #[test]
1363    fn blockquote_list_correct_indent_no_warning() {
1364        // Lists inside blockquotes: visual_indent includes the blockquote
1365        // prefix, so comparisons work on raw line columns.
1366        let content = "> - Item\n>\n>   continuation\n";
1367        assert!(check(content).is_empty());
1368    }
1369
1370    #[test]
1371    fn blockquote_list_under_indent_no_false_positive() {
1372        // Under-indented continuation inside a blockquote: visual_indent
1373        // starts at 0 (the `>` char) which is <= marker_col, so the scan
1374        // breaks and no warning is emitted. This is a known false negative
1375        // (not a false positive), which is the safer default.
1376        let content = "> - Item\n>\n> continuation\n";
1377        assert!(check(content).is_empty());
1378    }
1379
1380    // ── Deep nesting (3+ levels) ──────────────────────────────────────
1381
1382    #[test]
1383    fn deep_nesting_correct_indent() {
1384        let content = "- L1\n  - L2\n    - L3\n\n      continuation of L3\n";
1385        assert!(check(content).is_empty());
1386    }
1387
1388    #[test]
1389    fn deep_nesting_under_indent() {
1390        // L3 starts at column 4 with "- " marker, content_column = 6
1391        // Continuation with 5 spaces is under-indented for L3.
1392        let content = "- L1\n  - L2\n    - L3\n\n     continuation of L3\n";
1393        let warnings = check(content);
1394        assert_eq!(warnings.len(), 1);
1395        assert!(warnings[0].message.contains("6 spaces"));
1396        assert!(warnings[0].message.contains("found 5"));
1397    }
1398
1399    #[test]
1400    fn deep_nesting_middle_level_continuation_bullets() {
1401        // A loose continuation of the MIDDLE level (L2, content_column = 4)
1402        // after a deeper L3 list is valid; the L1 walk must not claim it as
1403        // its own over-indented continuation (issue #739).
1404        let content = "- L1\n  - L2\n    - L3\n\n    continuation of L2\n";
1405        assert!(check(content).is_empty());
1406    }
1407
1408    #[test]
1409    fn deep_nesting_middle_level_continuation_ordered() {
1410        // Issue #739 repro: ordered lists, continuation of the level-2 item
1411        // (content_column = 6) after a level-3 bullet list.
1412        let content = "1. Level 1 item.\n1. Level 1 item:\n   1. Level 2 item.\n   1. Level 2 item.\n   1. Level 2 item:\n      - Level 3 item.\n      - Level 3 item.\n\n      Level 2 list continuation.\n1. Level 1 item.\n";
1413        assert!(check(content).is_empty());
1414    }
1415
1416    #[test]
1417    fn deep_nesting_outermost_continuation() {
1418        // A loose continuation of the OUTERMOST level (L1, content_column = 2)
1419        // past two open nested levels escapes both and stays valid.
1420        let content = "- L1\n  - L2\n    - L3\n\n  continuation of L1\n";
1421        assert!(check(content).is_empty());
1422    }
1423
1424    #[test]
1425    fn deep_nesting_between_levels_still_flagged() {
1426        // Col 3 sits strictly between L1's content column (2) and L2's (4):
1427        // the deepest applicable item (L2) claims it as loose under-indent.
1428        let content = "- L1\n  - L2\n    - L3\n\n   continuation\n";
1429        let warnings = check(content);
1430        assert_eq!(warnings.len(), 1);
1431        assert!(warnings[0].message.contains("4 spaces"));
1432        assert!(warnings[0].message.contains("found 3"));
1433    }
1434
1435    #[test]
1436    fn deep_nesting_beyond_deepest_still_flagged() {
1437        // Col 7 exceeds even L3's content column (6): over-indent for L3.
1438        let content = "- L1\n  - L2\n    - L3\n\n       continuation\n";
1439        let warnings = check(content);
1440        assert_eq!(warnings.len(), 1);
1441        assert!(warnings[0].message.contains("over-indented"));
1442        assert!(warnings[0].message.contains("expected 6, found 7"));
1443    }
1444
1445    #[test]
1446    fn four_levels_middle_continuation() {
1447        // Continuation of L2 (content_column = 4) after open L3 and L4 lists:
1448        // the walk must pop two deeper levels and still defer to L2.
1449        let content = "- L1\n  - L2\n    - L3\n      - L4\n\n    continuation of L2\n";
1450        assert!(check(content).is_empty());
1451    }
1452
1453    #[test]
1454    fn nested_sibling_closes_deeper_level() {
1455        // L2b closes L2a's deeper L3 list; a continuation at L2b's content
1456        // column belongs to L2b and stays valid.
1457        let content = "- L1\n  - L2a\n    - L3\n  - L2b\n\n    continuation of L2b\n";
1458        assert!(check(content).is_empty());
1459    }
1460
1461    #[test]
1462    fn deep_nesting_middle_level_continuation_fix_preserved() {
1463        // The valid middle-level continuation must survive fix() unchanged.
1464        let content = "- L1\n  - L2\n    - L3\n\n    continuation of L2\n";
1465        assert_eq!(fix(content), content);
1466    }
1467
1468    // ── Tab indentation ───────────────────────────────────────────────
1469
1470    #[test]
1471    fn loose_tab_continuation_over_indented() {
1472        // A tab expands to 4 visual columns, exceeding content_column = 2 for
1473        // "- ". Loose over-indent is flagged just like the tight tab case
1474        // (`tight_continuation_tab_over_indented`), and the fix normalizes the
1475        // tab down to the content-column indent.
1476        let content = "- Item\n\n\tcontinuation\n";
1477        let warnings = check(content);
1478        assert_eq!(warnings.len(), 1);
1479        assert_eq!(warnings[0].line, 3);
1480        assert_eq!(fix(content), "- Item\n\n  continuation\n");
1481    }
1482
1483    // ── Multiple continuation paragraphs ──────────────────────────────
1484
1485    #[test]
1486    fn multiple_continuations_correct() {
1487        let content = "- Item\n\n  para 1\n\n  para 2\n\n  para 3\n";
1488        assert!(check(content).is_empty());
1489    }
1490
1491    #[test]
1492    fn multiple_continuations_second_under_indent() {
1493        // First continuation is correct, second is under-indented
1494        let content = "- Item\n\n  para 1\n\n continuation 2\n";
1495        let warnings = check(content);
1496        assert_eq!(warnings.len(), 1);
1497        assert_eq!(warnings[0].line, 5);
1498    }
1499
1500    // ── Ordered list with `)` marker style ────────────────────────────
1501
1502    #[test]
1503    fn ordered_paren_marker_correct() {
1504        // "1) " is 3 chars, content_column = 3
1505        let content = "1) Item\n\n   continuation\n";
1506        assert!(check(content).is_empty());
1507    }
1508
1509    #[test]
1510    fn ordered_paren_marker_under_indent() {
1511        let content = "1) Item\n\n  continuation\n";
1512        let warnings = check(content);
1513        assert_eq!(warnings.len(), 1);
1514        assert!(warnings[0].message.contains("3 spaces"));
1515    }
1516
1517    // ── Star and plus markers ─────────────────────────────────────────
1518
1519    #[test]
1520    fn star_marker_correct() {
1521        let content = "* Item\n\n  continuation\n";
1522        assert!(check(content).is_empty());
1523    }
1524
1525    #[test]
1526    fn star_marker_under_indent() {
1527        let content = "* Item\n\n continuation\n";
1528        let warnings = check(content);
1529        assert_eq!(warnings.len(), 1);
1530    }
1531
1532    #[test]
1533    fn plus_marker_correct() {
1534        let content = "+ Item\n\n  continuation\n";
1535        assert!(check(content).is_empty());
1536    }
1537
1538    // ── Heading breaks scan ───────────────────────────────────────────
1539
1540    #[test]
1541    fn heading_after_list_no_warning() {
1542        let content = "- Item\n\n# Heading\n";
1543        assert!(check(content).is_empty());
1544    }
1545
1546    // ── Horizontal rule breaks scan ───────────────────────────────────
1547
1548    #[test]
1549    fn hr_after_list_no_warning() {
1550        let content = "- Item\n\n---\n";
1551        assert!(check(content).is_empty());
1552    }
1553
1554    // ── Reference link definitions skip ───────────────────────────────
1555
1556    #[test]
1557    fn reference_link_def_not_flagged() {
1558        let content = "- Item\n\n [link]: https://example.com\n";
1559        assert!(check(content).is_empty());
1560    }
1561
1562    // ── Footnote definitions skip ─────────────────────────────────────
1563
1564    #[test]
1565    fn footnote_def_not_flagged() {
1566        let content = "- Item\n\n [^1]: footnote text\n";
1567        assert!(check(content).is_empty());
1568    }
1569
1570    #[test]
1571    fn footnote_multiline_body_after_list_not_flagged() {
1572        // A footnote definition whose indented body follows a list must not be
1573        // read as over-indented list continuation. The 4-space body lines
1574        // belong to the footnote, not to `- This is a list.` (content col 2).
1575        let content = "# A list followed by a footnote\n\n\
1576                       Here is a paragraph.[^fn]\n\n\
1577                       - This is a list.\n\n\
1578                       [^fn]:\n\
1579                       \x20\x20\x20\x20Here is a footnote that spans multiple lines.\n\
1580                       \x20\x20\x20\x20It should thus be indented by at least four spaces.\n";
1581        assert!(check(content).is_empty());
1582    }
1583
1584    #[test]
1585    fn fix_footnote_multiline_body_after_list_is_noop() {
1586        // The false positive also produced a damaging auto-fix: reindenting the
1587        // footnote body from 4 spaces to 2 broke the footnote (then tripped
1588        // MD068). The fix must leave the footnote untouched.
1589        let content = "# A list followed by a footnote\n\n\
1590                       Here is a paragraph.[^fn]\n\n\
1591                       - This is a list.\n\n\
1592                       [^fn]:\n\
1593                       \x20\x20\x20\x20Here is a footnote that spans multiple lines.\n\
1594                       \x20\x20\x20\x20It should thus be indented by at least four spaces.\n";
1595        assert_eq!(fix(content), content);
1596    }
1597
1598    #[test]
1599    fn footnote_body_indented_past_list_content_col_not_flagged() {
1600        // Footnote body indented well past the list's content column (here a
1601        // single-space list marker would put content col at 2, body at 4) is
1602        // footnote content, not over-indented continuation.
1603        let content = "- Item\n\n[^fn]:\n    Body line one.\n    Body line two.\n";
1604        assert!(check(content).is_empty());
1605    }
1606
1607    #[test]
1608    fn list_inside_footnote_body_continuation_not_flagged() {
1609        // Accepted trade-off: a list living *inside* a footnote body is skipped
1610        // wholesale, so MD077 does not police its continuation indentation.
1611        // Consistent with MD007, which also skips footnote-internal content.
1612        let content = "Text.[^fn]\n\n[^fn]:\n\
1613                       \x20\x20\x20\x20- nested item\n\
1614                       \x20\x20\x20\x20\x20\x20\x20over-indented continuation\n";
1615        assert!(check(content).is_empty());
1616    }
1617
1618    #[test]
1619    fn footnote_multiline_body_after_list_not_flagged_mkdocs() {
1620        // Same protection under the MkDocs flavor. The body sits at 6 spaces,
1621        // past MkDocs's required indent of 4 for `- `, so without skipping
1622        // footnote content it would be flagged as over-indented continuation.
1623        let content = "Here is a paragraph.[^fn]\n\n\
1624                       - This is a list.\n\n\
1625                       [^fn]:\n\
1626                       \x20\x20\x20\x20\x20\x20Footnote body that spans\n\
1627                       \x20\x20\x20\x20\x20\x20multiple indented lines.\n";
1628        assert!(check_mkdocs(content).is_empty());
1629    }
1630
1631    // ── Fix preserves correct content ─────────────────────────────────
1632
1633    #[test]
1634    fn fix_deep_nesting() {
1635        let content = "- L1\n  - L2\n    - L3\n\n     under-indented\n";
1636        let fixed = fix(content);
1637        assert_eq!(fixed, "- L1\n  - L2\n    - L3\n\n      under-indented\n");
1638    }
1639
1640    #[test]
1641    fn fix_mkdocs_unordered() {
1642        // MkDocs: "- " has content_column 2, but MkDocs requires max(2,4) = 4
1643        let content = "- Item\n\n  continuation\n";
1644        let fixed = fix_mkdocs(content);
1645        assert_eq!(fixed, "- Item\n\n    continuation\n");
1646    }
1647
1648    #[test]
1649    fn fix_code_fence_indent() {
1650        // Fence opener, interior, and closer all shift by the same delta so
1651        // the parser keeps pairing the fences and MD031 doesn't misfire.
1652        let content = "- Item\n\n ```\n code\n ```\n";
1653        let fixed = fix(content);
1654        assert_eq!(fixed, "- Item\n\n  ```\n  code\n  ```\n");
1655    }
1656
1657    #[test]
1658    fn fix_mkdocs_code_fence_indent() {
1659        // MkDocs ordered list: fence at 3 spaces needs 4; interior shifts too
1660        let content = "1. Item\n\n   ```toml\n   key = \"val\"\n   ```\n";
1661        let fixed = fix_mkdocs(content);
1662        assert_eq!(fixed, "1. Item\n\n    ```toml\n    key = \"val\"\n    ```\n");
1663    }
1664
1665    // ── Empty document / whitespace-only ──────────────────────────────
1666
1667    #[test]
1668    fn empty_document_no_warning() {
1669        assert!(check("").is_empty());
1670    }
1671
1672    #[test]
1673    fn whitespace_only_no_warning() {
1674        assert!(check("   \n\n  \n").is_empty());
1675    }
1676
1677    // ── No list at all ────────────────────────────────────────────────
1678
1679    #[test]
1680    fn no_list_no_warning() {
1681        let content = "# Heading\n\nSome paragraph.\n\nAnother paragraph.\n";
1682        assert!(check(content).is_empty());
1683    }
1684
1685    // ── Multi-line continuation (additional coverage) ──────────────
1686
1687    #[test]
1688    fn multiline_continuation_all_lines_flagged() {
1689        let content = "1. This is a list item.\n\n  This is continuation text and\n  it has multiple lines.\n  This is yet another line.\n";
1690        let warnings = check(content);
1691        assert_eq!(warnings.len(), 3);
1692        assert_eq!(warnings[0].line, 3);
1693        assert_eq!(warnings[1].line, 4);
1694        assert_eq!(warnings[2].line, 5);
1695    }
1696
1697    #[test]
1698    fn multiline_continuation_with_frontmatter_fix() {
1699        let content = "---\ntitle: Heading\n---\n\nSome introductory text:\n\n1. This is a list item.\n\n  This is list continuation text and\n  it has multiple lines that aren't indented properly.\n  This is yet another line that isn't indented properly.\n1. This is a list item.\n\n  This is list continuation text and\n  it has multiple lines that aren't indented properly.\n  This is yet another line that isn't indented properly.\n";
1700        let fixed = fix(content);
1701        assert_eq!(
1702            fixed,
1703            "---\ntitle: Heading\n---\n\nSome introductory text:\n\n1. This is a list item.\n\n   This is list continuation text and\n   it has multiple lines that aren't indented properly.\n   This is yet another line that isn't indented properly.\n1. This is a list item.\n\n   This is list continuation text and\n   it has multiple lines that aren't indented properly.\n   This is yet another line that isn't indented properly.\n"
1704        );
1705    }
1706
1707    #[test]
1708    fn multiline_continuation_correct_indent_no_warning() {
1709        let content = "1. Item\n\n   line one\n   line two\n   line three\n";
1710        assert!(check(content).is_empty());
1711    }
1712
1713    #[test]
1714    fn multiline_continuation_mixed_indent() {
1715        let content = "1. Item\n\n   correct\n  wrong\n   correct\n";
1716        let warnings = check(content);
1717        assert_eq!(warnings.len(), 1);
1718        assert_eq!(warnings[0].line, 4);
1719    }
1720
1721    #[test]
1722    fn multiline_continuation_unordered() {
1723        let content = "- Item\n\n continuation 1\n continuation 2\n continuation 3\n";
1724        let warnings = check(content);
1725        assert_eq!(warnings.len(), 3);
1726        let fixed = fix(content);
1727        assert_eq!(
1728            fixed,
1729            "- Item\n\n  continuation 1\n  continuation 2\n  continuation 3\n"
1730        );
1731    }
1732
1733    #[test]
1734    fn multiline_continuation_two_items_fix() {
1735        let content = "1. First\n\n  cont a\n  cont b\n\n2. Second\n\n  cont c\n  cont d\n";
1736        let fixed = fix(content);
1737        assert_eq!(
1738            fixed,
1739            "1. First\n\n   cont a\n   cont b\n\n2. Second\n\n   cont c\n   cont d\n"
1740        );
1741    }
1742
1743    #[test]
1744    fn fence_fix_does_not_break_pairing_for_md031() {
1745        // Regression for issue #574: previously MD077 only reindented the
1746        // fence delimiter lines while leaving the code block's interior at
1747        // the old indent. Between iterations of the fix loop the parser
1748        // saw an opener-closer mismatch, and MD031 then injected stray
1749        // blank lines at the fence boundaries. MD077's compound fix must
1750        // now rewrite the whole block atomically so the fences stay paired.
1751        let content = "#### title\n\nabc\n\n\
1752                       1. ab\n\n\
1753                       \x20\x20`aabbccdd`\n\n\
1754                       2. cd\n\n\
1755                       \x20\x20`bbcc dd ee`\n\n\
1756                       \x20\x20```\n\
1757                       \x20\x20abcd\n\
1758                       \x20\x20ef gh\n\
1759                       \x20\x20```\n\n\
1760                       \x20\x20uu\n\n\
1761                       \x20\x20```\n\
1762                       \x20\x20cdef\n\
1763                       \x20\x20gh ij\n\
1764                       \x20\x20```\n";
1765        let expected = "#### title\n\nabc\n\n\
1766                        1. ab\n\n\
1767                        \x20\x20\x20`aabbccdd`\n\n\
1768                        2. cd\n\n\
1769                        \x20\x20\x20`bbcc dd ee`\n\n\
1770                        \x20\x20\x20```\n\
1771                        \x20\x20\x20abcd\n\
1772                        \x20\x20\x20ef gh\n\
1773                        \x20\x20\x20```\n\n\
1774                        \x20\x20\x20uu\n\n\
1775                        \x20\x20\x20```\n\
1776                        \x20\x20\x20cdef\n\
1777                        \x20\x20\x20gh ij\n\
1778                        \x20\x20\x20```\n";
1779        assert_eq!(fix(content), expected);
1780    }
1781
1782    #[test]
1783    fn multiline_continuation_separated_by_blank() {
1784        let content = "1. Item\n\n  para1 line1\n  para1 line2\n\n  para2 line1\n  para2 line2\n";
1785        let warnings = check(content);
1786        assert_eq!(warnings.len(), 4);
1787        let fixed = fix(content);
1788        assert_eq!(
1789            fixed,
1790            "1. Item\n\n   para1 line1\n   para1 line2\n\n   para2 line1\n   para2 line2\n"
1791        );
1792    }
1793
1794    #[test]
1795    fn tab_indented_fence_is_normalized_to_spaces() {
1796        // Leading tabs expand to the next multiple-of-4 column under
1797        // CommonMark, so simply prepending spaces before a tab would
1798        // silently no-op (the tab snaps back to column 4). The compound
1799        // fence fix must replace the leading whitespace with a fresh
1800        // (visual_indent + delta) run of spaces. A `100. ` item has
1801        // content_column = 5, so a tab-indented fence (visual col 4) is
1802        // under-indented by 1 and must end up at 5 spaces after the fix.
1803        let content = "100. ab\n\n\t```\n\tabcd\n\t```\n";
1804        let expected = "100. ab\n\n     ```\n     abcd\n     ```\n";
1805        assert_eq!(fix(content), expected);
1806    }
1807
1808    // ── Loose continuation (after a blank line): over-indent ──────────
1809    //
1810    // Over-indentation is a mistake in both tight and loose continuation:
1811    // the body looks aligned but isn't. A blank line between the marker and
1812    // the body must not exempt it. The only over-indent that is intentional
1813    // after a blank line is an indented code block (content column + 4 or
1814    // more), which the parser marks `in_code_block` and the rule skips.
1815
1816    #[test]
1817    fn loose_continuation_over_indented_flagged() {
1818        // "* " content column is 2; 3 spaces after a blank is over-indented
1819        // (the code-block threshold is content_col + 4 = 6).
1820        let content = "* Item\n\n   over-indented\n";
1821        let warnings = check(content);
1822        assert_eq!(warnings.len(), 1);
1823        assert_eq!(warnings[0].line, 3);
1824        assert!(warnings[0].message.contains("over-indented"));
1825        assert!(warnings[0].message.contains("expected 2"));
1826        assert!(warnings[0].message.contains("found 3"));
1827    }
1828
1829    #[test]
1830    fn loose_continuation_over_indented_multiline_mixed() {
1831        // Over, correct, over — only the two over-indented lines are flagged.
1832        let content = "* Item\n\n   over one\n  correct\n   over two\n";
1833        let warnings = check(content);
1834        assert_eq!(warnings.len(), 2);
1835        assert_eq!(warnings[0].line, 3);
1836        assert_eq!(warnings[1].line, 5);
1837    }
1838
1839    #[test]
1840    fn fix_loose_continuation_over_indented() {
1841        let content = "* Item\n\n   over one\n  correct\n   over two\n";
1842        let fixed = fix(content);
1843        assert_eq!(fixed, "* Item\n\n  over one\n  correct\n  over two\n");
1844    }
1845
1846    #[test]
1847    fn fix_tight_and_loose_items_normalized_identically() {
1848        // The reported document: a tight item and a loose item with the same
1849        // over-indented body must both normalize to the content column.
1850        let content = "---\ntitle: Heading\n---\n\nSome introductory text:\n\n\
1851                       * This is a list item.\n   This is list continuation text and\n  it has multiple lines that aren't indented properly.\n   This is yet another line that isn't indented properly.\n\n\
1852                       * This is a list item.\n\n   This is list continuation text and\n  it has multiple lines that aren't indented properly.\n   This is yet another line that isn't indented properly.\n";
1853        let expected = "---\ntitle: Heading\n---\n\nSome introductory text:\n\n\
1854                        * This is a list item.\n  This is list continuation text and\n  it has multiple lines that aren't indented properly.\n  This is yet another line that isn't indented properly.\n\n\
1855                        * This is a list item.\n\n  This is list continuation text and\n  it has multiple lines that aren't indented properly.\n  This is yet another line that isn't indented properly.\n";
1856        assert_eq!(fix(content), expected);
1857    }
1858
1859    #[test]
1860    fn multi_paragraph_item_loose_paragraph_over_indented() {
1861        // A tight first paragraph and a loose second paragraph (after an
1862        // internal blank line) are both over-indented; both must be flagged.
1863        let content = "* Item.\n   tight over\n\n   loose over\n";
1864        let warnings = check(content);
1865        assert_eq!(warnings.len(), 2);
1866        assert_eq!(warnings[0].line, 2);
1867        assert_eq!(warnings[1].line, 4);
1868    }
1869
1870    #[test]
1871    fn loose_indented_code_block_not_flagged() {
1872        // content_col = 2; a loose line at content_col + 4 (6 spaces) is a
1873        // CommonMark indented code block, not over-indented prose. The over-
1874        // indent check must never reach it (it is `in_code_block` and skipped).
1875        let content = "- Item\n\n      code line\n";
1876        assert!(check(content).is_empty());
1877    }
1878
1879    #[test]
1880    fn mkdocs_loose_over_indented_flagged() {
1881        // MkDocs requires max(3, 4) = 4 for "1. ". A loose line at 5 spaces is
1882        // over-indented (code-block threshold is content_col + 4 = 7).
1883        let content = "1. Item\n\n     over\n";
1884        let warnings = check_mkdocs(content);
1885        assert_eq!(warnings.len(), 1);
1886        assert_eq!(warnings[0].line, 3);
1887        assert!(warnings[0].message.contains("over-indented"));
1888        assert!(warnings[0].message.contains("expected 4"));
1889        assert!(warnings[0].message.contains("found 5"));
1890    }
1891
1892    #[test]
1893    fn task_list_loose_over_indented_flagged() {
1894        // "- [ ] " content_col = 2, task_col = 6. A loose line at 4 spaces is
1895        // neither valid column and below the code-block threshold (6); flagged.
1896        let content = "- [ ] Task\n\n    over\n";
1897        let warnings = check(content);
1898        assert_eq!(warnings.len(), 1);
1899        assert_eq!(warnings[0].line, 3);
1900    }
1901
1902    #[test]
1903    fn loose_over_indent_boundary_below_code_block_threshold_flagged() {
1904        // content_col = 2; 5 spaces (= content_col + 3) is the deepest loose
1905        // over-indent that is still prose. content_col + 4 (6 spaces) would be
1906        // an indented code block - see `loose_indented_code_block_not_flagged`.
1907        // This pins the boundary so a shift in the parser's threshold is caught.
1908        let content = "- Item\n\n     over\n";
1909        let warnings = check(content);
1910        assert_eq!(warnings.len(), 1);
1911        assert_eq!(warnings[0].line, 3);
1912        assert!(warnings[0].message.contains("expected 2"));
1913        assert!(warnings[0].message.contains("found 5"));
1914    }
1915
1916    #[test]
1917    fn loose_over_indent_does_not_steal_nested_under_indent() {
1918        // Inner content_col = 4, marker_col = 2. A loose continuation at column
1919        // 3 is under-indented for Inner yet over-indented for Outer (content_col
1920        // 2). The under-indent pass must claim it for Inner (snap *up* to 4,
1921        // preserving the apparent nesting), never letting the over-indent pass
1922        // mis-attribute it to Outer and snap it *down* to 2. This is the exact
1923        // ambiguity the two-pass ordering exists to resolve.
1924        let content = "- Outer\n  - Inner\n\n   continuation\n";
1925        let warnings = check(content);
1926        assert_eq!(warnings.len(), 1);
1927        assert_eq!(warnings[0].line, 4);
1928        assert!(warnings[0].message.contains("4 spaces"));
1929        assert!(warnings[0].message.contains("found 3"));
1930        assert_eq!(fix(content), "- Outer\n  - Inner\n\n    continuation\n");
1931    }
1932
1933    #[test]
1934    fn loose_over_indent_attributes_to_deepest_enclosing_item() {
1935        // Inner content_col = 4. A loose continuation at column 5 over-indents
1936        // Inner (the deepest item it sits within), so it is flagged against
1937        // Inner's column 4 - not Outer's column 2 - and snapped to 4.
1938        let content = "- Outer\n  - Inner\n\n     continuation\n";
1939        let warnings = check(content);
1940        assert_eq!(warnings.len(), 1);
1941        assert_eq!(warnings[0].line, 4);
1942        assert!(warnings[0].message.contains("expected 4"));
1943        assert!(warnings[0].message.contains("found 5"));
1944        assert_eq!(fix(content), "- Outer\n  - Inner\n\n    continuation\n");
1945    }
1946
1947    // ── Over-indented fenced code blocks are left untouched ───────────
1948    //
1949    // An over-indented fence is cosmetic: the code still renders inside the
1950    // list item. Reindenting only its delimiters (the body is skipped as code)
1951    // would change the literal code content, so the over-indent pass skips
1952    // anything `in_code_block`. The under-indent path still fixes fences, where
1953    // moving the block up is required to keep it inside the item.
1954
1955    #[test]
1956    fn loose_over_indented_fence_not_flagged() {
1957        let content = "- Item\n\n   ```\n   code\n   ```\n";
1958        assert!(check(content).is_empty());
1959        assert_eq!(fix(content), content);
1960    }
1961
1962    #[test]
1963    fn tight_over_indented_fence_not_flagged() {
1964        let content = "- Item\n   ```\n   code\n   ```\n";
1965        assert!(check(content).is_empty());
1966        assert_eq!(fix(content), content);
1967    }
1968
1969    #[test]
1970    fn over_indented_tilde_fence_not_flagged() {
1971        let content = "- Item\n\n   ~~~\n   code\n   ~~~\n";
1972        assert!(check(content).is_empty());
1973        assert_eq!(fix(content), content);
1974    }
1975
1976    #[test]
1977    fn fence_like_code_content_inside_fenced_block_not_flagged() {
1978        // A ``` line that is the *body* of a ~~~ block must not be treated as
1979        // over-indented continuation; rewriting it would corrupt code content.
1980        let content = "- Item\n\n  ~~~\n   ```\n  ~~~\n";
1981        assert!(check(content).is_empty());
1982        assert_eq!(fix(content), content);
1983    }
1984
1985    #[test]
1986    fn unterminated_over_indented_fence_not_flagged() {
1987        // No closing fence: the last code line must not be mistaken for a
1988        // closer and snapped to the content column.
1989        let content = "- Item\n\n   ```\n   code1\n     code2deeper\n";
1990        assert!(check(content).is_empty());
1991        assert_eq!(fix(content), content);
1992    }
1993
1994    // ── GFM task list items: post-checkbox continuation column ───────
1995    //
1996    // MD013's reflow indents wrapped task-list lines at `content_col + 4`
1997    // (the column after the checkbox). MD077 must accept that column for
1998    // both tight and loose continuation, for every marker flavour, so the
1999    // two rules don't fight over well-formed task items (issue #579).
2000
2001    #[test]
2002    fn task_list_tight_continuation_post_checkbox_reproducer_579() {
2003        // Exact reproducer from the bug report: content wraps to the
2004        // post-checkbox column (6) with no blank line.
2005        let content = "- [ ] Lorem ipsum dolor sit amet, consectetur adipiscing\n      tempor incididunt ut labore.\n";
2006        assert!(check(content).is_empty());
2007    }
2008
2009    #[test]
2010    fn task_list_tight_continuation_dash_unchecked() {
2011        let content = "- [ ] Task\n      continuation\n";
2012        assert!(check(content).is_empty());
2013    }
2014
2015    #[test]
2016    fn task_list_tight_continuation_dash_checked_lower() {
2017        let content = "- [x] Task\n      continuation\n";
2018        assert!(check(content).is_empty());
2019    }
2020
2021    #[test]
2022    fn task_list_tight_continuation_dash_checked_upper() {
2023        let content = "- [X] Task\n      continuation\n";
2024        assert!(check(content).is_empty());
2025    }
2026
2027    #[test]
2028    fn task_list_tight_continuation_star_marker() {
2029        let content = "* [ ] Task\n      continuation\n";
2030        assert!(check(content).is_empty());
2031    }
2032
2033    #[test]
2034    fn task_list_tight_continuation_plus_marker() {
2035        let content = "+ [ ] Task\n      continuation\n";
2036        assert!(check(content).is_empty());
2037    }
2038
2039    #[test]
2040    fn task_list_tight_continuation_content_column_still_valid() {
2041        // Column 2 is the CommonMark-canonical indent for "- " and remains
2042        // valid for task items too.
2043        let content = "- [ ] Task\n  continuation\n";
2044        assert!(check(content).is_empty());
2045    }
2046
2047    #[test]
2048    fn task_list_tight_continuation_between_columns_still_flagged() {
2049        // Column 4 matches neither content_col (2) nor post-checkbox (6).
2050        // A genuine indentation mistake — must remain flagged.
2051        let content = "- [ ] Task\n    continuation\n";
2052        let warnings = check(content);
2053        assert_eq!(warnings.len(), 1);
2054        // Task items advertise both valid columns to the user.
2055        assert!(warnings[0].message.contains("expected 2 or 6"));
2056        assert!(warnings[0].message.contains("found 4"));
2057    }
2058
2059    #[test]
2060    fn task_list_tight_continuation_overshoot_still_flagged() {
2061        // Column 7 overshoots the post-checkbox column. Genuine mistake.
2062        let content = "- [ ] Task\n       continuation\n";
2063        let warnings = check(content);
2064        assert_eq!(warnings.len(), 1);
2065        assert!(warnings[0].message.contains("expected 2 or 6"));
2066        assert!(warnings[0].message.contains("found 7"));
2067    }
2068
2069    // ── Task-list fix output: snap to nearer valid column ────────────
2070
2071    #[test]
2072    fn fix_task_list_overshoot_snaps_to_task_col() {
2073        // Col 7 is 1 away from post-checkbox (6), 5 away from content (2).
2074        // Snap to 6 — the author's intent was almost certainly the
2075        // post-checkbox alignment, not the content column.
2076        let content = "- [ ] Task\n       continuation\n";
2077        let fixed = fix(content);
2078        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2079    }
2080
2081    #[test]
2082    fn fix_task_list_col_5_snaps_to_task_col() {
2083        // Col 5 is 1 away from post-checkbox (6), 3 away from content (2).
2084        let content = "- [ ] Task\n     continuation\n";
2085        let fixed = fix(content);
2086        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2087    }
2088
2089    #[test]
2090    fn fix_task_list_col_3_snaps_to_content_col() {
2091        // Col 3 is 1 away from content (2), 3 away from post-checkbox (6).
2092        let content = "- [ ] Task\n   continuation\n";
2093        let fixed = fix(content);
2094        assert_eq!(fixed, "- [ ] Task\n  continuation\n");
2095    }
2096
2097    #[test]
2098    fn fix_task_list_col_4_ties_to_content_col() {
2099        // Col 4 is equidistant (±2) from both columns. Tie breaks to the
2100        // CommonMark-canonical content column — that's the default indent
2101        // MD077 would produce for a non-task item, so prefer it when the
2102        // author's intent is ambiguous.
2103        let content = "- [ ] Task\n    continuation\n";
2104        let fixed = fix(content);
2105        assert_eq!(fixed, "- [ ] Task\n  continuation\n");
2106    }
2107
2108    #[test]
2109    fn fix_task_list_ordered_overshoot_snaps_to_task_col() {
2110        // "1. [ ] " → content_col = 3, post-checkbox = 7.
2111        // Col 8 is nearer to 7.
2112        let content = "1. [ ] Task\n        continuation\n";
2113        let fixed = fix(content);
2114        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2115    }
2116
2117    #[test]
2118    fn fix_task_list_ordered_under_overshoot_snaps_to_content_col() {
2119        // "1. [ ] " → content_col = 3, post-checkbox = 7.
2120        // Col 4 is nearer to 3.
2121        let content = "1. [ ] Task\n    continuation\n";
2122        let fixed = fix(content);
2123        assert_eq!(fixed, "1. [ ] Task\n   continuation\n");
2124    }
2125
2126    #[test]
2127    fn task_list_tight_continuation_ordered_single_digit() {
2128        // "1. [ ] " → content_col = 3, post-checkbox = 7
2129        let content = "1. [ ] Task\n       continuation\n";
2130        assert!(check(content).is_empty());
2131    }
2132
2133    #[test]
2134    fn task_list_tight_continuation_ordered_multi_digit() {
2135        // "10. [ ] " → content_col = 4, post-checkbox = 8
2136        let content = "10. [ ] Task\n        continuation\n";
2137        assert!(check(content).is_empty());
2138    }
2139
2140    #[test]
2141    fn task_list_tight_continuation_nested_dash() {
2142        // Nested "  - [ ] " at marker_col=2 → content_col=4, post-checkbox=8
2143        let content = "- Parent\n  - [ ] Nested task\n        continuation\n";
2144        assert!(check(content).is_empty());
2145    }
2146
2147    #[test]
2148    fn task_list_loose_continuation_post_checkbox_column_not_flagged() {
2149        // Loose continuation (blank line) at col 6 is also valid. This
2150        // already passed before the fix, but pin the intent: the 6-space
2151        // indent is accepted because it's the task-alignment column, not
2152        // because the under-indent check happens to let it through.
2153        let content = "- [ ] Task\n\n      continuation\n";
2154        assert!(check(content).is_empty());
2155    }
2156
2157    #[test]
2158    fn task_list_empty_body_is_not_a_task() {
2159        // "- [ ]" with nothing after is an empty regular list item, not a
2160        // task. Column 4 continuation has no task alignment to justify it
2161        // and must still be flagged as over-indented. (Col 6 would turn
2162        // the continuation into an indented code block inside the item,
2163        // which is a different code path.)
2164        let content = "- [ ]\n    continuation\n";
2165        let warnings = check(content);
2166        assert_eq!(warnings.len(), 1);
2167        assert!(warnings[0].message.contains("found 4"));
2168    }
2169
2170    #[test]
2171    fn task_list_malformed_checkbox_is_not_a_task() {
2172        // `[~] ` is not a GFM checkbox; only `[ ] `, `[x] `, `[X] ` count.
2173        let content = "- [~] Not a task\n      continuation\n";
2174        let warnings = check(content);
2175        assert_eq!(warnings.len(), 1);
2176    }
2177
2178    // ── MkDocs flavor × task checkbox ─────────────────────────────────
2179    //
2180    // MkDocs strict-indent and task alignment interact: required_min is
2181    // max(content_col, 4), and post-checkbox is content_col + 4. Both are
2182    // independently valid; values between them are flagged.
2183
2184    #[test]
2185    fn task_list_mkdocs_unordered_required_min_valid() {
2186        // "- [ ]" MkDocs: required_min = max(2, 4) = 4, post-checkbox = 6.
2187        let content = "- [ ] Task\n    continuation\n";
2188        assert!(check_mkdocs(content).is_empty());
2189    }
2190
2191    #[test]
2192    fn task_list_mkdocs_unordered_post_checkbox_valid() {
2193        let content = "- [ ] Task\n      continuation\n";
2194        assert!(check_mkdocs(content).is_empty());
2195    }
2196
2197    #[test]
2198    fn task_list_mkdocs_unordered_between_flagged() {
2199        // Column 5 is between required_min=4 and post-checkbox=6.
2200        let content = "- [ ] Task\n     continuation\n";
2201        let warnings = check_mkdocs(content);
2202        assert_eq!(warnings.len(), 1);
2203    }
2204
2205    #[test]
2206    fn task_list_mkdocs_ordered_both_columns_valid() {
2207        // "1. [ ]" MkDocs: required_min = max(3, 4) = 4, post-checkbox = 7.
2208        let at_4 = "1. [ ] Task\n    continuation\n";
2209        assert!(check_mkdocs(at_4).is_empty());
2210        let at_7 = "1. [ ] Task\n       continuation\n";
2211        assert!(check_mkdocs(at_7).is_empty());
2212    }
2213
2214    #[test]
2215    fn task_list_mkdocs_ordered_between_flagged() {
2216        // Column 5 and 6 are between required_min=4 and post-checkbox=7.
2217        let at_5 = "1. [ ] Task\n     continuation\n";
2218        assert_eq!(check_mkdocs(at_5).len(), 1);
2219        let at_6 = "1. [ ] Task\n      continuation\n";
2220        assert_eq!(check_mkdocs(at_6).len(), 1);
2221    }
2222
2223    // ── Context-aware tie-break ──────────────────────────────────────
2224    //
2225    // When a flagged line is exactly equidistant from `content_col` and
2226    // `task_col`, the author's intent is ambiguous. Before picking a
2227    // canonical default, look at whether other continuation lines in the
2228    // same item already use one of the valid columns — if so, snap to the
2229    // column they're using so the fix preserves the author's visible
2230    // convention.
2231
2232    #[test]
2233    fn fix_task_list_tie_sibling_at_task_col_snaps_to_task_col() {
2234        // Col 4 is equidistant from content_col (2) and task_col (6).
2235        // A valid sibling at col 6 proves the author is aligning under the
2236        // checkbox, so the tie resolves to col 6.
2237        let content = "- [ ] Task\n      aligned continuation\n    tied continuation\n";
2238        let fixed = fix(content);
2239        assert_eq!(
2240            fixed,
2241            "- [ ] Task\n      aligned continuation\n      tied continuation\n"
2242        );
2243    }
2244
2245    #[test]
2246    fn fix_task_list_tie_sibling_at_content_col_snaps_to_content_col() {
2247        // Valid sibling at col 2 proves the author is aligning to the
2248        // content column, so the col-4 tie resolves to col 2.
2249        let content = "- [ ] Task\n  aligned continuation\n    tied continuation\n";
2250        let fixed = fix(content);
2251        assert_eq!(fixed, "- [ ] Task\n  aligned continuation\n  tied continuation\n");
2252    }
2253
2254    #[test]
2255    fn fix_task_list_tie_both_siblings_snaps_to_content_col() {
2256        // When siblings exist at both valid columns, the author's pattern
2257        // is self-contradictory. Fall back to the CommonMark-canonical
2258        // content column.
2259        let content = "- [ ] Task\n  at content col\n      at task col\n    tied continuation\n";
2260        let fixed = fix(content);
2261        assert_eq!(
2262            fixed,
2263            "- [ ] Task\n  at content col\n      at task col\n  tied continuation\n"
2264        );
2265    }
2266
2267    #[test]
2268    fn fix_task_list_tie_sees_task_col_through_tight_lazy_continuation() {
2269        // CommonMark allows tight lazy continuation at col ≤ marker_col
2270        // (zero-indent continuation) inside a list item. The pre-pass
2271        // must MIRROR the main check loop's termination semantics: in
2272        // tight mode (no preceding blank) col ≤ marker_col is NOT a
2273        // termination signal — the lazy line still belongs to the item.
2274        //
2275        // This test pins that mirroring: a `lazy` line at col 0 is
2276        // followed by a legitimate task-col sibling at col 6, then a
2277        // tied col-4 line. If the pre-pass terminated eagerly at the
2278        // lazy line, the task-col sibling would be missed and the tied
2279        // line would fall back to content column. With correct
2280        // mirroring, the task-col sibling is seen and the tie resolves
2281        // to col 6.
2282        let content = concat!("- [ ] Task\n", "lazy\n", "      aligned at task col\n", "    tied\n",);
2283        let fixed = fix(content);
2284        assert!(
2285            fixed.contains("\n      tied\n"),
2286            "tied line should snap to col 6 (task col) because a task-col \
2287             sibling is visible past the tight lazy-continuation line; got:\n{fixed}"
2288        );
2289    }
2290
2291    // ── Tab-indented task continuation ───────────────────────────────
2292    //
2293    // Leading tabs expand to the next column that's a multiple of 4 under
2294    // CommonMark. The fix replaces the leading whitespace bytes wholesale,
2295    // turning tabs into space-indented output.
2296
2297    #[test]
2298    fn task_list_tab_indented_continuation_flagged() {
2299        // Two tabs → visual col 8, which overshoots both valid columns
2300        // for `- [ ] ` (content_col=2, task_col=6).
2301        let content = "- [ ] Task\n\t\twrap\n";
2302        let warnings = check(content);
2303        assert_eq!(warnings.len(), 1);
2304        assert!(warnings[0].message.contains("expected 2 or 6"));
2305        assert!(warnings[0].message.contains("found 8"));
2306    }
2307
2308    #[test]
2309    fn fix_task_list_tab_indented_snaps_to_task_col() {
2310        // abs_diff(8, 6) = 2 < abs_diff(8, 2) = 6 → snap to task_col (6).
2311        let content = "- [ ] Task\n\t\twrap\n";
2312        let fixed = fix(content);
2313        assert_eq!(fixed, "- [ ] Task\n      wrap\n");
2314    }
2315
2316    #[test]
2317    fn fix_task_list_single_tab_equidistant_snaps_to_content_col() {
2318        // One tab → visual col 4, equidistant from content_col (2) and
2319        // task_col (6). No siblings → tie-break to content_col.
2320        let content = "- [ ] Task\n\twrap\n";
2321        let fixed = fix(content);
2322        assert_eq!(fixed, "- [ ] Task\n  wrap\n");
2323    }
2324
2325    // ── Blockquote × task-list ───────────────────────────────────────
2326    //
2327    // Blockquote-nested lists are a known limitation on MD077: the list
2328    // parser doesn't always expose them with the same column semantics as
2329    // top-level lists, and the rule prefers a false-negative default to
2330    // avoid spurious warnings inside blockquotes (see
2331    // `blockquote_list_under_indent_no_false_positive`). These tests pin
2332    // the current behavior so any future change is intentional.
2333
2334    #[test]
2335    fn task_list_blockquote_post_checkbox_not_flagged() {
2336        // Post-checkbox alignment inside a blockquote — accepted as valid.
2337        let content = "> - [ ] Task\n>       continuation\n";
2338        assert!(check(content).is_empty());
2339    }
2340
2341    #[test]
2342    fn task_list_blockquote_between_cols_documented_limitation() {
2343        // Col-4-equivalent inside a blockquote is silently accepted — a
2344        // known MD077 limitation on blockquote-nested lists, not a task-
2345        // list-specific choice. Pinning the current behavior.
2346        let content = "> - [ ] Task\n>     continuation\n";
2347        assert!(check(content).is_empty());
2348    }
2349
2350    #[test]
2351    fn task_list_blockquote_overshoot_documented_limitation() {
2352        // Overshoot inside a blockquote — same known limitation.
2353        let content = "> - [ ] Task\n>        continuation\n";
2354        assert!(check(content).is_empty());
2355    }
2356
2357    // ── MkDocs × task × fix output ───────────────────────────────────
2358    //
2359    // MkDocs strict-indent raises `required` to max(content_col, 4) while
2360    // task_col stays at content_col + 4. The snap logic operates on the
2361    // raised required, not on the underlying content_col.
2362
2363    #[test]
2364    fn fix_task_list_mkdocs_unordered_overshoot_snaps_to_task_col() {
2365        // `- [ ]` MkDocs: required=4, task_col=6. Col 7 → abs_diff(7,6)=1
2366        // < abs_diff(7,4)=3. Snap to task_col.
2367        let content = "- [ ] Task\n       continuation\n";
2368        let fixed = fix_mkdocs(content);
2369        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2370    }
2371
2372    #[test]
2373    fn fix_task_list_mkdocs_unordered_tie_snaps_to_required() {
2374        // `- [ ]` MkDocs: required=4, task_col=6. Col 5 → abs_diff(5,6)=1
2375        // == abs_diff(5,4)=1. Tie with no siblings → required (4).
2376        let content = "- [ ] Task\n     continuation\n";
2377        let fixed = fix_mkdocs(content);
2378        assert_eq!(fixed, "- [ ] Task\n    continuation\n");
2379    }
2380
2381    #[test]
2382    fn fix_task_list_mkdocs_ordered_overshoot_snaps_to_task_col() {
2383        // `1. [ ]` MkDocs: required=4, task_col=7. Col 8 → abs_diff(8,7)=1
2384        // < abs_diff(8,4)=4. Snap to task_col.
2385        let content = "1. [ ] Task\n        continuation\n";
2386        let fixed = fix_mkdocs(content);
2387        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2388    }
2389
2390    #[test]
2391    fn fix_task_list_mkdocs_ordered_near_required_snaps_to_required() {
2392        // `1. [ ]` MkDocs: required=4, task_col=7. Col 5 → abs_diff(5,7)=2
2393        // > abs_diff(5,4)=1. Snap to required (4). `1. [ ] Task\n     wrap`
2394        // has actual=5 which is over `required=4` so it's flagged in
2395        // strict mode, while in standard mode it falls under the lazy-
2396        // continuation window and isn't flagged at all.
2397        let content = "1. [ ] Task\n     continuation\n";
2398        let fixed = fix_mkdocs(content);
2399        assert_eq!(fixed, "1. [ ] Task\n    continuation\n");
2400    }
2401
2402    #[test]
2403    fn fix_task_list_mkdocs_ordered_between_cols_snaps_to_task_col() {
2404        // `1. [ ]` MkDocs: required=4, task_col=7. Col 6 → abs_diff(6,7)=1
2405        // < abs_diff(6,4)=2. Snap to task_col (7).
2406        let content = "1. [ ] Task\n      continuation\n";
2407        let fixed = fix_mkdocs(content);
2408        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2409    }
2410
2411    // ── Fix idempotency (property test) ──────────────────────────────
2412    //
2413    // A fix pass on already-fixed content must produce the same content
2414    // — otherwise MD077 would oscillate on repeated invocations. This is
2415    // the core property that issue #579 was about (MD077 vs. MD013 fix
2416    // loop), and the integration test covers the MD013 interaction. The
2417    // property tests below pin the *internal* idempotency of MD077's own
2418    // fix, so any future change that introduces oscillation fails fast.
2419
2420    fn assert_idempotent(content: &str) {
2421        let once = fix(content);
2422        let twice = fix(&once);
2423        assert_eq!(once, twice, "MD077 fix was not idempotent on input: {content:?}");
2424    }
2425
2426    fn assert_idempotent_mkdocs(content: &str) {
2427        let once = fix_mkdocs(content);
2428        let twice = fix_mkdocs(&once);
2429        assert_eq!(
2430            once, twice,
2431            "MD077 (MkDocs) fix was not idempotent on input: {content:?}"
2432        );
2433    }
2434
2435    #[test]
2436    fn idempotent_task_list_between_cols() {
2437        assert_idempotent("- [ ] Task\n    continuation\n");
2438    }
2439
2440    #[test]
2441    fn idempotent_task_list_overshoot() {
2442        assert_idempotent("- [ ] Task\n       continuation\n");
2443    }
2444
2445    #[test]
2446    fn idempotent_task_list_under_post_checkbox() {
2447        assert_idempotent("- [ ] Task\n   continuation\n");
2448    }
2449
2450    #[test]
2451    fn idempotent_task_list_near_post_checkbox() {
2452        assert_idempotent("- [ ] Task\n     continuation\n");
2453    }
2454
2455    #[test]
2456    fn idempotent_task_list_tab_overshoot() {
2457        assert_idempotent("- [ ] Task\n\t\twrap\n");
2458    }
2459
2460    #[test]
2461    fn idempotent_task_list_single_tab() {
2462        assert_idempotent("- [ ] Task\n\twrap\n");
2463    }
2464
2465    #[test]
2466    fn idempotent_task_list_ordered_overshoot() {
2467        assert_idempotent("1. [ ] Task\n        continuation\n");
2468    }
2469
2470    #[test]
2471    fn idempotent_task_list_ordered_under() {
2472        assert_idempotent("1. [ ] Task\n    continuation\n");
2473    }
2474
2475    #[test]
2476    fn idempotent_task_list_tie_with_sibling_at_task_col() {
2477        assert_idempotent("- [ ] Task\n      aligned\n    tied\n");
2478    }
2479
2480    #[test]
2481    fn idempotent_task_list_tie_with_sibling_at_content_col() {
2482        assert_idempotent("- [ ] Task\n  aligned\n    tied\n");
2483    }
2484
2485    #[test]
2486    fn idempotent_task_list_mkdocs_unordered_overshoot() {
2487        assert_idempotent_mkdocs("- [ ] Task\n       continuation\n");
2488    }
2489
2490    #[test]
2491    fn idempotent_task_list_mkdocs_unordered_tie() {
2492        assert_idempotent_mkdocs("- [ ] Task\n     continuation\n");
2493    }
2494
2495    #[test]
2496    fn idempotent_task_list_mkdocs_ordered_overshoot() {
2497        assert_idempotent_mkdocs("1. [ ] Task\n        continuation\n");
2498    }
2499
2500    #[test]
2501    fn idempotent_task_list_mkdocs_ordered_between() {
2502        assert_idempotent_mkdocs("1. [ ] Task\n      continuation\n");
2503    }
2504
2505    #[test]
2506    fn idempotent_task_list_reproducer_579() {
2507        // The exact reproducer from issue #579 already has correct indent
2508        // (col 6 = post-checkbox), so idempotency is trivially true. Pin
2509        // it anyway as a smoke test against future regressions.
2510        assert_idempotent(
2511            "- [ ] Lorem ipsum dolor sit amet, consectetur adipiscing\n      tempor incididunt ut labore.\n",
2512        );
2513    }
2514
2515    #[test]
2516    fn idempotent_non_task_list_still_holds() {
2517        // Non-task items never enter the task_col code path; sanity-check
2518        // that idempotency is preserved for them too.
2519        assert_idempotent("1. Item\n    over-indented\n");
2520        assert_idempotent("- Item\n\n continuation\n");
2521    }
2522
2523    // ── Non-task idempotency: loose-mode under-indent ────────────────
2524    //
2525    // When a blank line precedes the continuation (loose mode),
2526    // under-indented content is flagged and fixed up to the content
2527    // column. Idempotency pins that one pass of the fix is sufficient.
2528
2529    #[test]
2530    fn idempotent_non_task_loose_under_indent_ordered() {
2531        // 1. Item → content col 3; "  x" is 2 spaces, under content col.
2532        assert_idempotent("1. Item\n\n  continuation\n");
2533    }
2534
2535    #[test]
2536    fn idempotent_non_task_loose_under_indent_multi_digit() {
2537        // 10. Item → content col 4; single-space continuation needs 4.
2538        assert_idempotent("10. Item\n\n continuation\n");
2539    }
2540
2541    #[test]
2542    fn idempotent_non_task_tight_over_indent_ordered() {
2543        // Tight-mode over-indent: 5 spaces where content col is 3.
2544        assert_idempotent("1. Item\n     over-indented\n");
2545    }
2546
2547    // ── Non-task idempotency: fenced code block compound fix ─────────
2548    //
2549    // A fence opener that needs re-indenting is repaired by the
2550    // compound-fence fix which shifts opener + interior + closer
2551    // together. Idempotency pins that the compound fix settles in one
2552    // pass and does not oscillate between runs.
2553
2554    #[test]
2555    fn idempotent_non_task_fence_ordered_loose() {
2556        // 1. Item → content col 3; fence at col 2 needs to shift to 3.
2557        assert_idempotent("1. Item\n\n  ```rust\n  let x = 1;\n  ```\n");
2558    }
2559
2560    #[test]
2561    fn idempotent_non_task_fence_tilde_under_indent() {
2562        // Tilde fences use the same compound-fix path as backtick fences.
2563        // Interior below the list scope (col 0 here, required col 3) must
2564        // be promoted up in the same pass as the fence delimiters —
2565        // otherwise a second pass would flag the interior individually
2566        // and defeat idempotency.
2567        assert_idempotent("1. Item\n\n  ~~~\nplain text\n  ~~~\n");
2568    }
2569
2570    #[test]
2571    fn idempotent_non_task_fence_interior_above_required() {
2572        // Interior already above the required column must not be pushed
2573        // further up by the compound fix — authored interior indentation
2574        // is preserved when it doesn't threaten fence pairing.
2575        assert_idempotent("1. Item\n\n  ```\n    deeply indented code\n  ```\n");
2576    }
2577
2578    #[test]
2579    fn fence_fix_promotes_interior_below_scope_in_single_pass() {
2580        // Concrete behavioral check, not just idempotency:
2581        // interior at col 0 with opener at col 2, required 3, must land
2582        // at col 3 (same as opener) so fence pairing is preserved.
2583        let content = "1. Item\n\n  ```\ncode\n  ```\n";
2584        let fixed = fix(content);
2585        assert_eq!(fixed, "1. Item\n\n   ```\n   code\n   ```\n");
2586    }
2587
2588    #[test]
2589    fn fence_fix_preserves_interior_above_required() {
2590        // Opener at col 2 → col 3 (required). Interior at col 4 stays at
2591        // col 4 (above required, no need to push it).
2592        let content = "1. Item\n\n  ```\n    code\n  ```\n";
2593        let fixed = fix(content);
2594        assert_eq!(fixed, "1. Item\n\n   ```\n    code\n   ```\n");
2595    }
2596
2597    // ── Non-task idempotency: MkDocs strict-indent ───────────────────
2598    //
2599    // Under MkDocs flavor, continuation requires max(content_col, 4),
2600    // which can force a fix even when CommonMark would accept the
2601    // content. Pin idempotency for the non-task path there too.
2602
2603    #[test]
2604    fn idempotent_non_task_mkdocs_ordered_at_3_spaces() {
2605        // CommonMark-valid (3 spaces) but MkDocs demands 4 → fix runs.
2606        assert_idempotent_mkdocs("1. Item\n\n   continuation\n");
2607    }
2608
2609    #[test]
2610    fn idempotent_non_task_mkdocs_unordered_at_2_spaces() {
2611        // "- Item" → content col 2, but MkDocs raises the floor to 4.
2612        assert_idempotent_mkdocs("- Item\n\n  continuation\n");
2613    }
2614
2615    #[test]
2616    fn idempotent_non_task_mkdocs_fence_compound() {
2617        // MkDocs non-task fence: opener/interior/closer shift together.
2618        assert_idempotent_mkdocs("1. Item\n\n   ```toml\n   k = 1\n   ```\n");
2619    }
2620
2621    // ── style = "aligned" ──────────────────────────────────────────────
2622
2623    #[test]
2624    fn aligned_tight_zero_indent_continuation_flagged() {
2625        // The core #682 case: a tight 0-indent lazy continuation is valid
2626        // CommonMark (and accepted by `any`), but `aligned` requires it to sit
2627        // at the content column.
2628        let content = "- this is a long line\nthat continues on a second line\n";
2629        let warnings = check_aligned(content);
2630        assert_eq!(warnings.len(), 1);
2631        assert_eq!(warnings[0].line, 2);
2632        assert_eq!(
2633            fix_aligned(content),
2634            "- this is a long line\n  that continues on a second line\n"
2635        );
2636    }
2637
2638    #[test]
2639    fn aligned_full_issue_example_made_consistent() {
2640        // The full #682 example: every continuation line is snapped to the
2641        // content column, producing the consistent result the reporter wants.
2642        let content = "- this is a long line\n\
2643                       that continues on a second line\n\
2644                       - this is another long line\n\
2645                       \x20\x20that continues on the next line\n\
2646                       - yet again a long line\n\
2647                       and still inconsistently spaced\n\
2648                       \x20\x20and even worse\n";
2649        let expected = "- this is a long line\n\
2650                        \x20\x20that continues on a second line\n\
2651                        - this is another long line\n\
2652                        \x20\x20that continues on the next line\n\
2653                        - yet again a long line\n\
2654                        \x20\x20and still inconsistently spaced\n\
2655                        \x20\x20and even worse\n";
2656        assert_eq!(fix_aligned(content), expected);
2657        // And the fix is a fixpoint.
2658        assert_eq!(fix_aligned(expected), expected);
2659    }
2660
2661    #[test]
2662    fn aligned_already_aligned_not_flagged() {
2663        let content = "- item\n  continuation at content column\n";
2664        assert!(check_aligned(content).is_empty());
2665    }
2666
2667    #[test]
2668    fn aligned_tight_partial_indent_flagged() {
2669        // 1 space under "- " (content col 2): tight partial under-indent.
2670        let content = "- item\n continuation\n";
2671        let warnings = check_aligned(content);
2672        assert_eq!(warnings.len(), 1);
2673        assert_eq!(fix_aligned(content), "- item\n  continuation\n");
2674    }
2675
2676    #[test]
2677    fn aligned_post_blank_zero_indent_still_new_paragraph() {
2678        // After a blank line, 0-indent content is a NEW paragraph that has left
2679        // the list - aligned mode must not reindent it back into the item.
2680        let content = "- item\n\nnew paragraph\n";
2681        assert!(check_aligned(content).is_empty());
2682        assert_eq!(fix_aligned(content), content);
2683    }
2684
2685    // ── aligned: structural blocks must NOT be pulled into the list ────
2686
2687    #[test]
2688    fn aligned_top_level_blockquote_after_list_untouched() {
2689        // A blockquote tight after a list item is a list-breaking separator,
2690        // not continuation. `in_list_block` is false for it, so aligned mode
2691        // must leave it alone (no reindent into the item).
2692        let content = "- item\n> quote\n";
2693        assert!(check_aligned(content).is_empty());
2694        assert_eq!(fix_aligned(content), content);
2695    }
2696
2697    #[test]
2698    fn aligned_top_level_fence_after_list_untouched() {
2699        let content = "- item\n```\ncode\n```\n";
2700        assert!(check_aligned(content).is_empty());
2701        assert_eq!(fix_aligned(content), content);
2702    }
2703
2704    #[test]
2705    fn aligned_top_level_table_after_list_untouched() {
2706        let content = "- item\n| a | b |\n|---|---|\n| 1 | 2 |\n";
2707        assert!(check_aligned(content).is_empty());
2708        assert_eq!(fix_aligned(content), content);
2709    }
2710
2711    // ── aligned: nested lists ──────────────────────────────────────────
2712
2713    #[test]
2714    fn aligned_nested_tight_lazy_continuation_aligns_to_inner() {
2715        // A tight lazy continuation after a nested item is, per CommonMark,
2716        // continuation of the innermost open item, so it aligns to the inner
2717        // item's content column (4), not the outer's (2). The outer item must
2718        // defer to the inner one.
2719        let content = "- Outer\n  - Inner\ncontinuation\n";
2720        let warnings = check_aligned(content);
2721        assert_eq!(warnings.len(), 1);
2722        assert_eq!(fix_aligned(content), "- Outer\n  - Inner\n    continuation\n");
2723    }
2724
2725    #[test]
2726    fn aligned_nested_continuation_already_aligned_not_flagged() {
2727        let content = "- L1\n  - L2\n    cont of L2 at 4\n";
2728        assert!(check_aligned(content).is_empty());
2729    }
2730
2731    #[test]
2732    fn aligned_nested_idempotent() {
2733        let content = "- Outer\n  - Inner\ncontinuation\n";
2734        let once = fix_aligned(content);
2735        assert_eq!(fix_aligned(&once), once);
2736    }
2737
2738    #[test]
2739    fn aligned_three_level_nesting_aligns_to_innermost() {
2740        // The saw_nested cascade defers through every level, so the tight lazy
2741        // line aligns to L3's content column (6), the innermost open item.
2742        let content = "- L1\n  - L2\n    - L3\ncont\n";
2743        assert_eq!(fix_aligned(content), "- L1\n  - L2\n    - L3\n      cont\n");
2744    }
2745
2746    #[test]
2747    fn aligned_continuation_after_sibling_owned_by_last_item() {
2748        // Tight lazy continuation after the second sibling belongs to that
2749        // sibling (no nesting), so it aligns to its content column (2).
2750        let content = "- a\n- b\nlazy\n";
2751        assert_eq!(fix_aligned(content), "- a\n- b\n  lazy\n");
2752    }
2753
2754    #[test]
2755    fn aligned_multi_digit_ordered_marker_aligns_to_content_column() {
2756        let content = "10. Item\nwrap\n";
2757        assert_eq!(fix_aligned(content), "10. Item\n    wrap\n");
2758    }
2759
2760    #[test]
2761    fn aligned_setext_heading_after_list_left_alone() {
2762        // A setext heading is not prose continuation; aligned must not reindent
2763        // it (the walk terminates on the heading), leaving the document intact.
2764        let content = "- item\nText\n===\n";
2765        assert!(check_aligned(content).is_empty());
2766        assert_eq!(fix_aligned(content), content);
2767    }
2768
2769    #[test]
2770    fn aligned_latent_marker_in_continuation_is_idempotent() {
2771        // Regression (fuzzer-found): a list-marker-looking line ("2. ") that the
2772        // parser absorbs as lazy continuation can be promoted to a real list
2773        // item once an earlier continuation line is reindented, re-attributing
2774        // later lines and breaking single-pass idempotency. Such items are not
2775        // reindented at all.
2776        let content = "# \n- \n``\n2. \n![]()";
2777        let once = fix_aligned(content);
2778        assert_eq!(fix_aligned(&once), once, "fix must be idempotent in one pass");
2779        assert_eq!(once, content, "item with a latent marker is left untouched");
2780    }
2781
2782    #[test]
2783    fn aligned_latent_table_in_continuation_is_idempotent() {
2784        // Regression (fuzzer-found): a table-looking line that the parser
2785        // absorbs as lazy continuation (so it is NOT yet `in_table_block`) can
2786        // be promoted to a real table once an earlier line is reindented. Like
2787        // a latent marker, this re-parses the block, so the item is left alone.
2788        let content = "- \n![`]()\n|  | ` |\n| --- | --- |";
2789        let once = fix_aligned(content);
2790        assert_eq!(fix_aligned(&once), once, "fix must be idempotent in one pass");
2791        assert_eq!(once, content, "item with a latent table is left untouched");
2792    }
2793
2794    #[test]
2795    fn aligned_blockquote_nested_list_not_touched() {
2796        // Lists inside blockquotes are a documented MD077 limitation (the scan
2797        // breaks at the blockquote prefix). Aligned inherits that conservative
2798        // no-false-positive behavior.
2799        let content = "> - item\n> wrap\n";
2800        assert!(check_aligned(content).is_empty());
2801        assert_eq!(fix_aligned(content), content);
2802    }
2803
2804    // ── aligned: GFM task list items ───────────────────────────────────
2805
2806    #[test]
2807    fn aligned_task_post_checkbox_column_accepted() {
2808        // Continuation aligned to the post-checkbox column (content_col + 4 = 6)
2809        // stays valid so aligned mode doesn't fight MD013 reflow.
2810        let content = "- [ ] Task\n      wrap\n";
2811        assert!(check_aligned(content).is_empty());
2812        assert_eq!(fix_aligned(content), content);
2813    }
2814
2815    #[test]
2816    fn aligned_task_under_indent_snaps_to_content_column() {
2817        let content = "- [ ] Task\nwrap\n";
2818        let warnings = check_aligned(content);
2819        assert_eq!(warnings.len(), 1);
2820        assert_eq!(fix_aligned(content), "- [ ] Task\n  wrap\n");
2821    }
2822
2823    // ── aligned: MkDocs flavor ─────────────────────────────────────────
2824
2825    #[test]
2826    fn aligned_mkdocs_tight_under_indent_snaps_to_four() {
2827        // MkDocs raises the required indent to max(content_col, 4) = 4 for "- ".
2828        let content = "- item\nwrap\n";
2829        let warnings = check_aligned_mkdocs(content);
2830        assert_eq!(warnings.len(), 1);
2831        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
2832        assert_eq!(aligned_rule().fix(&ctx).unwrap(), "- item\n    wrap\n");
2833    }
2834
2835    // ── any (default) regression: tight lazy continuation untouched ────
2836
2837    #[test]
2838    fn any_default_does_not_flag_tight_lazy_continuation() {
2839        // The default style must preserve CommonMark lazy continuation.
2840        let content = "- item\nwrapped at zero indent\n";
2841        assert!(check(content).is_empty());
2842        assert_eq!(fix(content), content);
2843    }
2844
2845    #[test]
2846    fn from_config_aligned_enables_tight_flagging() {
2847        // End-to-end: `[MD077] style = "aligned"` wires through from_config.
2848        let mut config = crate::config::Config::default();
2849        let mut rule_config = crate::config::RuleConfig::default();
2850        rule_config
2851            .values
2852            .insert("style".to_string(), toml::Value::String("aligned".to_string()));
2853        config.rules.insert("MD077".to_string(), rule_config);
2854
2855        let rule = MD077ListContinuationIndent::from_config(&config);
2856        let ctx = LintContext::new("- item\nwrap\n", MarkdownFlavor::Standard, None);
2857        assert_eq!(rule.check(&ctx).unwrap().len(), 1);
2858    }
2859
2860    #[test]
2861    fn from_config_default_is_any() {
2862        // No config -> default `any` -> tight lazy continuation untouched.
2863        let config = crate::config::Config::default();
2864        let rule = MD077ListContinuationIndent::from_config(&config);
2865        let ctx = LintContext::new("- item\nwrap\n", MarkdownFlavor::Standard, None);
2866        assert!(rule.check(&ctx).unwrap().is_empty());
2867    }
2868
2869    #[test]
2870    fn aligned_tight_underindented_fence_inside_item_left_alone() {
2871        // A fenced block is a structural construct; aligned mode does not
2872        // reindent it (the `in_code_block` guard), so a tight under-indented
2873        // fence is a no-op rather than a risky delimiter-only rewrite.
2874        let content = "- item\n ```\n code\n ```\n";
2875        assert!(check_aligned(content).is_empty());
2876        assert_eq!(fix_aligned(content), content);
2877    }
2878
2879    #[test]
2880    fn aligned_task_under_indent_fix_is_idempotent() {
2881        let content = "- [ ] Task\nwrap\n";
2882        let once = fix_aligned(content);
2883        assert_eq!(fix_aligned(&once), once);
2884    }
2885
2886    #[test]
2887    fn aligned_partial_indent_fix_is_idempotent() {
2888        let content = "- item\n continuation\n";
2889        let once = fix_aligned(content);
2890        assert_eq!(fix_aligned(&once), once);
2891    }
2892}