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, indent: None },
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                    // Lists inside blockquotes are out of scope for MD077. Their
603                    // content column is measured on the raw line, so it is
604                    // meaningless for a lazy continuation sitting outside the
605                    // quote: scoping them lets two items with different content
606                    // columns each claim such a line and reindent it the other
607                    // way on alternating passes.
608                    if info.blockquote.is_some() {
609                        continue;
610                    }
611                    let line = info.content(ctx.content);
612                    let task_col = Self::is_task_list_item(line, li.content_column)
613                        .then_some(li.content_column + Self::TASK_CHECKBOX_PREFIX_LEN);
614                    items.push((item_line, li.marker_column, li.content_column, task_col));
615                }
616            }
617        }
618        items.sort_unstable();
619        items.dedup_by_key(|&mut (ln, _, _, _)| ln);
620
621        // Precompute each item's owned-range end. The range ends at the line
622        // before the next item whose marker column is <= this item's (its next
623        // sibling or an ancestor), or the last line if none follows.
624        //
625        // The direct "scan forward for the next marker_col <= mine" is O(n^2) on
626        // a monotonically deepening list, where no later item ever qualifies so
627        // every item scans to the end. A monotonic stack (nearest
628        // smaller-or-equal marker column to the right) computes all range ends in
629        // one linear pass. Walking right-to-left, pop every stacked item whose
630        // marker column is strictly greater than the current one (they can never
631        // be the sibling/ancestor of anything further left that is <= current),
632        // leaving the nearest qualifying item on top.
633        let mut range_ends = vec![total_lines; items.len()];
634        let mut stack: Vec<usize> = Vec::new();
635        for i in (0..items.len()).rev() {
636            let marker_col = items[i].1;
637            while let Some(&top) = stack.last() {
638                if items[top].1 > marker_col {
639                    stack.pop();
640                } else {
641                    break;
642                }
643            }
644            range_ends[i] = stack.last().map_or(total_lines, |&j| items[j].0 - 1);
645            stack.push(i);
646        }
647
648        // Precompute each item's required indent and owned line range so both
649        // passes below scope identically.
650        let scoped: Vec<(usize, usize, usize, Option<usize>, usize, usize)> = items
651            .iter()
652            .enumerate()
653            .map(|(item_idx, &(item_line, marker_col, content_col, task_col))| {
654                // A configured indent replaces the content column, but under a
655                // flavor that requires strict list indentation it may only raise
656                // the 4-space minimum. That minimum is a compatibility floor
657                // rather than a style default: below it the renderer stops
658                // treating the line as continuation, so honoring a smaller
659                // configured value would make `fix` rewrite documents into a
660                // form the flavor's renderer no longer reads as part of the item.
661                let required = match self.config.indent {
662                    Some(indent) if strict_indent => (marker_col + indent).max(4),
663                    Some(indent) => marker_col + indent,
664                    None if strict_indent => content_col.max(4),
665                    None => content_col,
666                };
667                (
668                    item_line,
669                    marker_col,
670                    content_col,
671                    task_col,
672                    required,
673                    range_ends[item_idx],
674                )
675            })
676            .collect();
677
678        // Precompute which lines can ever reach the per-line continuation
679        // callback. `walk_item_continuation` unconditionally skips (regardless of
680        // which item owns the line) blank lines, list-item lines, headings,
681        // horizontal rules, `should_skip_line` lines, and block-level constructs;
682        // only the lines that survive all of those can be flagged. An item whose
683        // owned range contains none of them produces no warning, so both passes
684        // can skip it without walking the range at all.
685        //
686        // This keeps a document of purely deeply-nested list items linear: such a
687        // document has no continuation prose, so every item skips its walk
688        // instead of re-scanning the whole tail (which was O(n^2) in the item
689        // count). Documents that do have continuation prose are unaffected - the
690        // guard only ever skips items that could not have produced a warning.
691        let prose_candidate_lines: Vec<usize> = (1..=total_lines)
692            .filter(|&line_num| {
693                let Some(info) = ctx.line_info(line_num) else {
694                    return false;
695                };
696                let trimmed = info.content(ctx.content).trim_start();
697                !Self::should_skip_line(info, trimmed)
698                    && !info.is_blank
699                    && info.list_item.is_none()
700                    && info.heading.is_none()
701                    && !info.is_horizontal_rule
702                    && !Self::is_block_level_construct(trimmed)
703            })
704            .collect();
705        // True when a continuation candidate falls in `(after_line, range_end]`,
706        // i.e. the half-open range `walk_item_continuation` actually visits.
707        let range_has_prose_candidate = |after_line: usize, range_end: usize| -> bool {
708            let start = prose_candidate_lines.partition_point(|&l| l <= after_line);
709            prose_candidate_lines.get(start).is_some_and(|&l| l <= range_end)
710        };
711
712        // Pass 1 - under-indented continuation.
713        //
714        // Loose under-indent (after a blank line) sits below the content column
715        // and would escape the list item; it is always flagged. Tight
716        // under-indent is valid CommonMark lazy continuation, so it is left
717        // alone under `style = "any"`.
718        //
719        // Under `style = "aligned"`, tight under-indent is additionally flagged
720        // and snapped up to the content column. MD077 scopes past the parser's
721        // block end (to catch escaped loose content), and the parser absorbs
722        // col-0 blockquotes, fences, and tables that sit tight under a list item
723        // as lazy continuation. Reindenting those would change the rendered
724        // structure, so the tight-aligned branch guards two ways: it skips lines
725        // the parser classified in place (code, blockquote - see
726        // `confirmed_structure`), and it bails on an item whose continuation
727        // holds a construct the parser would re-parse once indentation changes
728        // (a latent list marker or table - see `has_latent_structure`). Headings
729        // and horizontal rules already terminate the walk; reference/footnote/
730        // abbreviation definitions are skipped inside it. Erring toward skipping
731        // yields false negatives (safe) rather than structural false positives.
732        //
733        // This pass runs first so that a deeply nested item claims an ambiguous
734        // line - one that is under-indented for it yet over-indented for a
735        // shallower ancestor - before pass 2 can mis-attribute it to the
736        // ancestor as an over-indent and snap it the wrong way.
737        let aligned = self.config.style == ContinuationStyle::Aligned;
738        for &(item_line, marker_col, _content_col, _task_col, required, range_end) in &scoped {
739            // No continuation candidate in this item's range: it cannot produce a
740            // warning, so skip the walk (and the latent-structure scan) entirely.
741            if !range_has_prose_candidate(item_line, range_end) {
742                continue;
743            }
744            // "Latent structure": a line in this item's continuation that the
745            // parser has NOT yet promoted to a list item or table, but that
746            // would be once an earlier continuation line is reindented. Such a
747            // promotion re-attributes the following lines to a different block
748            // (different content column) and breaks single-pass idempotency, so
749            // reindenting anything in the item is unsafe and the whole item is
750            // skipped. This is a *prediction* of how the parser would re-parse
751            // after a fix, which is why it stays a heuristic (markers and tables
752            // are the only constructs the parser absorbs as lazy continuation
753            // rather than flagging on the line itself; code and blockquotes are
754            // classified in place and handled per line below). Well-formed prose
755            // continuation matches neither, so this only bails on pathological
756            // input (a safe false negative). Real nested items never reach the
757            // callback (the walk handles them via `saw_nested`).
758            let has_latent_structure = aligned && Self::item_range_has_latent_structure(ctx, item_line, range_end);
759            // Which setting produced `required` decides what the message may
760            // claim. The content column carries a structural consequence (below
761            // it the content leaves the item) and the strict-flavor minimum
762            // carries a renderer requirement, but a configured indent above
763            // both is a house style, so it is reported as one.
764            let from_configured_indent = self.config.indent.is_some_and(|indent| marker_col + indent == required);
765            Self::walk_item_continuation(ctx, item_line, range_end, marker_col, |line| {
766                let actual = line.actual;
767                let under_indented = actual < required;
768                let loose_escape = line.saw_blank && under_indented;
769                // Don't reindent a line the parser classified in place as a code
770                // block (fenced or indented) or a blockquote: these are read
771                // straight from its per-line output, so the rule cannot drift
772                // from how rumdl parses the document. Headings and horizontal
773                // rules terminate the walk before the callback; latent list
774                // markers and tables are handled by `has_latent_structure`.
775                let confirmed_structure = line.info.in_code_block || line.info.blockquote.is_some();
776                let aligned_tight = aligned
777                    && !has_latent_structure
778                    && !line.saw_blank
779                    && !line.saw_nested
780                    && under_indented
781                    && !confirmed_structure;
782                if (loose_escape || aligned_tight) && flagged_lines.insert(line.line_num) {
783                    let message = if line.saw_blank {
784                        if from_configured_indent {
785                            format!(
786                                "Content after blank line in list item needs {required} spaces of \
787                                 indentation to match the configured indent (found {actual})",
788                            )
789                        } else if strict_indent {
790                            format!(
791                                "Content inside list item needs {required} spaces of indentation \
792                                 for MkDocs compatibility (found {actual})",
793                            )
794                        } else {
795                            format!(
796                                "Content after blank line in list item needs {required} spaces of \
797                                 indentation to remain part of the list (found {actual})",
798                            )
799                        }
800                    } else {
801                        format!("Continuation line under-indented (expected {required}, found {actual})")
802                    };
803                    let outcome = Self::build_under_indent_warning(ctx, line, required, message);
804                    if let Some(closer_line) = outcome.also_flag_line {
805                        flagged_lines.insert(closer_line);
806                    }
807                    warnings.push(outcome.warning);
808                }
809                ControlFlow::Continue(())
810            });
811        }
812
813        // Pass 2 - over-indented continuation (tight or loose): prose pushed
814        // past the content column is snapped back. Fenced code blocks are
815        // skipped here (`!in_code_block`): an over-indented fence is cosmetic
816        // (the code still renders), and reindenting only its delimiters - the
817        // body is skipped by `should_skip_line` - would alter the literal code
818        // content. Indented code blocks (content column + 4 or more) are also
819        // `in_code_block`, so a blank line before such a body does not exempt
820        // it from being recognized as code rather than over-indented prose.
821        for &(item_line, marker_col, content_col, task_col, required, range_end) in &scoped {
822            // No continuation candidate in this item's range: nothing to flag.
823            if !range_has_prose_candidate(item_line, range_end) {
824                continue;
825            }
826            // For task items, gather sibling-column usage once so the auto-fix
827            // can tie-break equidistant over-indents toward whichever valid
828            // column the author is already using.
829            let (uses_content_col, uses_task_col) = match task_col {
830                Some(t) => Self::sibling_column_usage(ctx, item_line, range_end, marker_col, content_col, t),
831                None => (false, false),
832            };
833
834            Self::walk_item_continuation(ctx, item_line, range_end, marker_col, |line| {
835                let actual = line.actual;
836                if actual > required
837                    && !line.info.in_code_block
838                    && Some(actual) != task_col
839                    && !Self::starts_with_list_marker(line.trimmed)
840                    && flagged_lines.insert(line.line_num)
841                {
842                    let fix_target =
843                        Self::compute_fix_target(actual, required, task_col, uses_content_col, uses_task_col);
844                    let message = match task_col {
845                        Some(t) => format!(
846                            "Continuation line over-indented \
847                             (expected {required} or {t}, found {actual})"
848                        ),
849                        None => {
850                            format!("Continuation line over-indented (expected {required}, found {actual})")
851                        }
852                    };
853                    warnings.push(Self::build_over_indent_warning(ctx, line, fix_target, message));
854                }
855                ControlFlow::Continue(())
856            });
857        }
858
859        // The two passes emit independently, so order by position before
860        // returning - callers and tests expect document order.
861        warnings.sort_by_key(|w| (w.line, w.column));
862
863        Ok(warnings)
864    }
865
866    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
867        let warnings = self.check(ctx)?;
868        let warnings =
869            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
870        if warnings.is_empty() {
871            return Ok(ctx.content.to_string());
872        }
873
874        // Sort fixes by byte position descending to apply from end to start
875        let mut fixes: Vec<Fix> = warnings.into_iter().filter_map(|w| w.fix).collect();
876        fixes.sort_by_key(|f| std::cmp::Reverse(f.range.start));
877
878        let mut content = ctx.content.to_string();
879        for fix in fixes {
880            if fix.range.start <= content.len() && fix.range.end <= content.len() {
881                content.replace_range(fix.range, &fix.replacement);
882            }
883        }
884
885        Ok(content)
886    }
887
888    fn category(&self) -> RuleCategory {
889        RuleCategory::List
890    }
891
892    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
893        ctx.content.is_empty() || ctx.list_blocks.is_empty()
894    }
895
896    fn as_any(&self) -> &dyn std::any::Any {
897        self
898    }
899
900    crate::impl_rule_config_methods!(MD077Config);
901}
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906    use crate::config::MarkdownFlavor;
907
908    fn check(content: &str) -> Vec<LintWarning> {
909        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
910        let rule = MD077ListContinuationIndent::default();
911        rule.check(&ctx).unwrap()
912    }
913
914    fn check_mkdocs(content: &str) -> Vec<LintWarning> {
915        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
916        let rule = MD077ListContinuationIndent::default();
917        rule.check(&ctx).unwrap()
918    }
919
920    fn fix(content: &str) -> String {
921        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
922        let rule = MD077ListContinuationIndent::default();
923        rule.fix(&ctx).unwrap()
924    }
925
926    fn fix_mkdocs(content: &str) -> String {
927        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
928        let rule = MD077ListContinuationIndent::default();
929        rule.fix(&ctx).unwrap()
930    }
931
932    fn aligned_rule() -> MD077ListContinuationIndent {
933        MD077ListContinuationIndent::new(ContinuationStyle::Aligned)
934    }
935
936    fn check_aligned(content: &str) -> Vec<LintWarning> {
937        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
938        aligned_rule().check(&ctx).unwrap()
939    }
940
941    fn check_aligned_mkdocs(content: &str) -> Vec<LintWarning> {
942        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
943        aligned_rule().check(&ctx).unwrap()
944    }
945
946    fn fix_aligned(content: &str) -> String {
947        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
948        aligned_rule().fix(&ctx).unwrap()
949    }
950
951    fn fix_aligned_quarto(content: &str) -> String {
952        let ctx = LintContext::new(content, MarkdownFlavor::Quarto, None);
953        aligned_rule().fix(&ctx).unwrap()
954    }
955
956    #[test]
957    fn aligned_idempotent_with_latent_marker_behind_unstable_heading() {
958        // Regression: an empty backtick run (`` ``\n`` ``) is parsed as a setext
959        // heading. That heading used to terminate the latent-structure walk
960        // before it reached the `- ` marker on the next line, so the marker was
961        // not detected as latent. Reindenting the `1. ` continuation then
962        // promoted `- ` to a real list item, producing a fresh under-indent
963        // violation on the second pass and breaking single-pass idempotency.
964        // The latent-structure scan now spans the full owned range, detects the
965        // marker, and leaves the (ambiguous) item alone.
966        let input = "1. \n``\n``\n- \n``";
967        let once = fix_aligned_quarto(input);
968        let twice = fix_aligned_quarto(&once);
969        assert_eq!(once, twice, "MD077 aligned fix must be idempotent (Quarto)");
970    }
971
972    #[test]
973    fn aligned_idempotent_with_lazy_continuation_out_of_a_blockquote() {
974        // Regression: a lazy continuation that follows a blockquote-nested list
975        // item gained one space of indent on every pass, so the formatter never
976        // converged.
977        let input = "- \n> *\n> a\n``";
978        let once = fix_aligned(input);
979        let twice = fix_aligned(&once);
980        assert_eq!(once, twice, "MD077 aligned fix must be idempotent");
981    }
982
983    // ── Tight continuation (no blank line) ─────────────────────────────
984
985    #[test]
986    fn tight_lazy_continuation_zero_indent_not_flagged() {
987        // Zero-indent lazy continuation is valid CommonMark
988        let content = "- Item\ncontinuation\n";
989        assert!(check(content).is_empty());
990    }
991
992    #[test]
993    fn tight_continuation_correct_indent_not_flagged() {
994        // Correctly indented tight continuation (aligns with content column)
995        let content = "1. Item\n   continuation\n";
996        assert!(check(content).is_empty());
997    }
998
999    #[test]
1000    fn tight_continuation_over_indented_ordered() {
1001        // "1. " = 3 chars, but continuation has 4 spaces
1002        let content = "1. This is a list item with multiple lines.\n    The second line is over-indented.\n";
1003        let warnings = check(content);
1004        assert_eq!(warnings.len(), 1);
1005        assert_eq!(warnings[0].line, 2);
1006        assert!(warnings[0].message.contains("over-indented"));
1007    }
1008
1009    #[test]
1010    fn tight_continuation_over_indented_unordered() {
1011        // "- " = 2 chars, but continuation has 3 spaces
1012        let content = "- Item\n   over-indented\n";
1013        let warnings = check(content);
1014        assert_eq!(warnings.len(), 1);
1015        assert_eq!(warnings[0].line, 2);
1016    }
1017
1018    #[test]
1019    fn tight_continuation_multiple_over_indented_lines() {
1020        let content = "1. Item\n    line one\n    line two\n    line three\n";
1021        let warnings = check(content);
1022        assert_eq!(warnings.len(), 3);
1023    }
1024
1025    #[test]
1026    fn tight_continuation_mixed_correct_and_over() {
1027        let content = "1. Item\n   correct\n    over-indented\n   correct again\n";
1028        let warnings = check(content);
1029        assert_eq!(warnings.len(), 1);
1030        assert_eq!(warnings[0].line, 3);
1031    }
1032
1033    #[test]
1034    fn tight_continuation_nested_over_indented() {
1035        // L2 "- " at column 2, content_column = 4. Continuation at 5 is over-indented for L2.
1036        let content = "- L1\n  - L2\n     over-indented continuation of L2\n";
1037        let warnings = check(content);
1038        assert_eq!(warnings.len(), 1);
1039        assert_eq!(warnings[0].line, 3);
1040        // Must report expected=4 (L2's content_col), not expected=2 (L1's)
1041        assert!(warnings[0].message.contains("expected 4"));
1042        assert!(warnings[0].message.contains("found 5"));
1043    }
1044
1045    #[test]
1046    fn tight_continuation_nested_correct_indent_not_flagged() {
1047        // Continuation at 4 spaces is correct for L2 (content_col=4). Must NOT be
1048        // flagged as over-indented relative to L1 (content_col=2).
1049        let content = "- L1\n  - L2\n    correctly indented continuation of L2\n";
1050        assert!(check(content).is_empty());
1051    }
1052
1053    #[test]
1054    fn fix_tight_continuation_nested_over_indented() {
1055        // Fix should reduce to 4 spaces (L2's content_col), not 2 (L1's)
1056        let content = "- L1\n  - L2\n     over-indented continuation of L2\n";
1057        let fixed = fix(content);
1058        assert_eq!(fixed, "- L1\n  - L2\n    over-indented continuation of L2\n");
1059    }
1060
1061    #[test]
1062    fn tight_continuation_under_indented_not_flagged() {
1063        // 2 spaces instead of 3 for "1. " — under-indented, not over-indented.
1064        // Valid lazy continuation in CommonMark, so not flagged.
1065        let content = "1. Item\n  under-indented\n";
1066        assert!(check(content).is_empty());
1067    }
1068
1069    #[test]
1070    fn tight_continuation_tab_over_indented() {
1071        // A tab expands to 4 visual columns, which exceeds content_col=2 for "- "
1072        let content = "- Item\n\tover-indented\n";
1073        let warnings = check(content);
1074        assert_eq!(warnings.len(), 1);
1075    }
1076
1077    #[test]
1078    fn fix_tight_continuation_over_indented_ordered() {
1079        let content = "1. This is a list item with multiple lines.\n    The second line is over-indented.\n";
1080        let fixed = fix(content);
1081        assert_eq!(
1082            fixed,
1083            "1. This is a list item with multiple lines.\n   The second line is over-indented.\n"
1084        );
1085    }
1086
1087    #[test]
1088    fn fix_tight_continuation_over_indented_unordered() {
1089        let content = "- Item\n   over-indented\n";
1090        let fixed = fix(content);
1091        assert_eq!(fixed, "- Item\n  over-indented\n");
1092    }
1093
1094    #[test]
1095    fn fix_tight_continuation_multiple_lines() {
1096        let content = "1. Item\n    line one\n    line two\n";
1097        let fixed = fix(content);
1098        assert_eq!(fixed, "1. Item\n   line one\n   line two\n");
1099    }
1100
1101    #[test]
1102    fn tight_continuation_mkdocs_4space_ordered_not_flagged() {
1103        // MkDocs requires max(3, 4) = 4 spaces for "1. " items.
1104        // 4-space tight continuation is correct, not over-indented.
1105        let content = "1. Item\n    continuation\n";
1106        assert!(check_mkdocs(content).is_empty());
1107    }
1108
1109    #[test]
1110    fn tight_continuation_mkdocs_5space_ordered_flagged() {
1111        // 5 spaces exceeds the MkDocs required indent of 4
1112        let content = "1. Item\n     over-indented\n";
1113        let warnings = check_mkdocs(content);
1114        assert_eq!(warnings.len(), 1);
1115        assert!(warnings[0].message.contains("expected 4"));
1116        assert!(warnings[0].message.contains("found 5"));
1117    }
1118
1119    #[test]
1120    fn fix_tight_continuation_mkdocs_over_indented() {
1121        let content = "1. Item\n     over-indented\n";
1122        let fixed = fix_mkdocs(content);
1123        assert_eq!(fixed, "1. Item\n    over-indented\n");
1124    }
1125
1126    #[test]
1127    fn tight_continuation_deeply_indented_list_markers_not_flagged() {
1128        // Deeply indented list markers (e.g., indent=8 in MD007) may not be
1129        // recognized as list items by the parser. MD077 must not flag them.
1130        let content = "* Level 0\n        * Level 1\n                * Level 2\n";
1131        assert!(check(content).is_empty());
1132    }
1133
1134    #[test]
1135    fn tight_continuation_ordered_marker_not_flagged() {
1136        // Indented ordered list marker should not be flagged
1137        let content = "- Parent\n      1. Child item\n";
1138        assert!(check(content).is_empty());
1139    }
1140
1141    // ── Unordered list: correct indent after blank ────────────────────
1142
1143    #[test]
1144    fn unordered_correct_indent_no_warning() {
1145        let content = "- Item\n\n  continuation\n";
1146        assert!(check(content).is_empty());
1147    }
1148
1149    #[test]
1150    fn unordered_partial_indent_warns() {
1151        // Content with some indent (above marker column) but less than
1152        // content_column is likely an indentation mistake.
1153        let content = "- Item\n\n continuation\n";
1154        let warnings = check(content);
1155        assert_eq!(warnings.len(), 1);
1156        assert_eq!(warnings[0].line, 3);
1157        assert!(warnings[0].message.contains("2 spaces"));
1158        assert!(warnings[0].message.contains("found 1"));
1159    }
1160
1161    #[test]
1162    fn unordered_zero_indent_is_new_paragraph() {
1163        // Content at 0 indent after a top-level list is a new paragraph, not
1164        // under-indented continuation.
1165        let content = "- Item\n\ncontinuation\n";
1166        assert!(check(content).is_empty());
1167    }
1168
1169    // ── Ordered list: CommonMark W+N ──────────────────────────────────
1170
1171    #[test]
1172    fn ordered_3space_correct_commonmark() {
1173        // "1. " is 3 chars, content_column = 3
1174        let content = "1. Item\n\n   continuation\n";
1175        assert!(check(content).is_empty());
1176    }
1177
1178    #[test]
1179    fn ordered_2space_under_indent_commonmark() {
1180        let content = "1. Item\n\n  continuation\n";
1181        let warnings = check(content);
1182        assert_eq!(warnings.len(), 1);
1183        assert!(warnings[0].message.contains("3 spaces"));
1184        assert!(warnings[0].message.contains("found 2"));
1185    }
1186
1187    // ── Multi-digit ordered markers ───────────────────────────────────
1188
1189    #[test]
1190    fn multi_digit_marker_correct() {
1191        // "10. " is 4 chars, content_column = 4
1192        let content = "10. Item\n\n    continuation\n";
1193        assert!(check(content).is_empty());
1194    }
1195
1196    #[test]
1197    fn multi_digit_marker_under_indent() {
1198        let content = "10. Item\n\n   continuation\n";
1199        let warnings = check(content);
1200        assert_eq!(warnings.len(), 1);
1201        assert!(warnings[0].message.contains("4 spaces"));
1202    }
1203
1204    // ── MkDocs flavor: 4-space minimum ────────────────────────────────
1205
1206    #[test]
1207    fn mkdocs_3space_ordered_warns() {
1208        // In MkDocs mode, 3-space indent on "1. " is not enough
1209        let content = "1. Item\n\n   continuation\n";
1210        let warnings = check_mkdocs(content);
1211        assert_eq!(warnings.len(), 1);
1212        assert!(warnings[0].message.contains("4 spaces"));
1213        assert!(warnings[0].message.contains("MkDocs"));
1214    }
1215
1216    #[test]
1217    fn mkdocs_4space_ordered_no_warning() {
1218        let content = "1. Item\n\n    continuation\n";
1219        assert!(check_mkdocs(content).is_empty());
1220    }
1221
1222    #[test]
1223    fn mkdocs_unordered_2space_ok() {
1224        // Unordered "- " has content_column = 2; max(2, 4) = 4 in mkdocs
1225        let content = "- Item\n\n    continuation\n";
1226        assert!(check_mkdocs(content).is_empty());
1227    }
1228
1229    #[test]
1230    fn mkdocs_unordered_2space_warns() {
1231        // "- " has content_column 2; MkDocs requires max(2,4) = 4
1232        let content = "- Item\n\n  continuation\n";
1233        let warnings = check_mkdocs(content);
1234        assert_eq!(warnings.len(), 1);
1235        assert!(warnings[0].message.contains("4 spaces"));
1236    }
1237
1238    // ── Auto-fix ──────────────────────────────────────────────────────
1239
1240    #[test]
1241    fn fix_unordered_indent() {
1242        // Partial indent (above marker column, below content column) gets fixed
1243        let content = "- Item\n\n continuation\n";
1244        let fixed = fix(content);
1245        assert_eq!(fixed, "- Item\n\n  continuation\n");
1246    }
1247
1248    #[test]
1249    fn fix_ordered_indent() {
1250        let content = "1. Item\n\n continuation\n";
1251        let fixed = fix(content);
1252        assert_eq!(fixed, "1. Item\n\n   continuation\n");
1253    }
1254
1255    #[test]
1256    fn fix_mkdocs_indent() {
1257        let content = "1. Item\n\n   continuation\n";
1258        let fixed = fix_mkdocs(content);
1259        assert_eq!(fixed, "1. Item\n\n    continuation\n");
1260    }
1261
1262    // ── Nested lists: only flag continuation, not sub-items ───────────
1263
1264    #[test]
1265    fn nested_list_items_not_flagged() {
1266        let content = "- Parent\n\n  - Child\n";
1267        assert!(check(content).is_empty());
1268    }
1269
1270    #[test]
1271    fn nested_list_zero_indent_is_new_paragraph() {
1272        // Content at 0 indent ends the list, not continuation
1273        let content = "- Parent\n  - Child\n\ncontinuation of parent\n";
1274        assert!(check(content).is_empty());
1275    }
1276
1277    #[test]
1278    fn nested_list_partial_indent_flagged() {
1279        // Content with partial indent (above parent marker, below content col)
1280        let content = "- Parent\n  - Child\n\n continuation of parent\n";
1281        let warnings = check(content);
1282        assert_eq!(warnings.len(), 1);
1283        assert!(warnings[0].message.contains("2 spaces"));
1284    }
1285
1286    // ── Code blocks inside items ─────────────────────────────────────
1287
1288    #[test]
1289    fn code_block_correctly_indented_no_warning() {
1290        // Fence lines and content all at correct indent for "- " (content_column = 2)
1291        let content = "- Item\n\n  ```\n  code\n  ```\n";
1292        assert!(check(content).is_empty());
1293    }
1294
1295    #[test]
1296    fn code_fence_under_indented_warns() {
1297        // Fence opener has 1-space indent, but "- " needs 2.
1298        // Only the opener is flagged — its compound fix also covers the
1299        // interior content and the matching closer (see issue #574).
1300        let content = "- Item\n\n ```\n code\n ```\n";
1301        let warnings = check(content);
1302        assert_eq!(warnings.len(), 1);
1303        assert_eq!(warnings[0].line, 3);
1304    }
1305
1306    #[test]
1307    fn code_fence_under_indented_ordered_mkdocs() {
1308        // Ordered list in MkDocs: "1. " needs max(3, 4) = 4 spaces
1309        // Fence at 3 spaces is correct for CommonMark but wrong for MkDocs
1310        let content = "1. Item\n\n   ```toml\n   key = \"value\"\n   ```\n";
1311        assert!(check(content).is_empty()); // Standard mode: 3 is fine
1312        let warnings = check_mkdocs(content);
1313        assert_eq!(warnings.len(), 1); // MkDocs: opener's compound fix covers the whole block
1314        assert_eq!(warnings[0].line, 3);
1315        assert!(warnings[0].message.contains("4 spaces"));
1316        assert!(warnings[0].message.contains("MkDocs"));
1317    }
1318
1319    #[test]
1320    fn code_fence_tilde_under_indented() {
1321        let content = "- Item\n\n ~~~\n code\n ~~~\n";
1322        let warnings = check(content);
1323        assert_eq!(warnings.len(), 1); // Tilde fences: single compound-fix warning on opener
1324        assert_eq!(warnings[0].line, 3);
1325    }
1326
1327    // ── Multiple blank lines ──────────────────────────────────────────
1328
1329    #[test]
1330    fn multiple_blank_lines_zero_indent_is_new_paragraph() {
1331        // Even with multiple blanks, 0-indent content is a new paragraph
1332        let content = "- Item\n\n\ncontinuation\n";
1333        assert!(check(content).is_empty());
1334    }
1335
1336    #[test]
1337    fn multiple_blank_lines_partial_indent_flags() {
1338        let content = "- Item\n\n\n continuation\n";
1339        let warnings = check(content);
1340        assert_eq!(warnings.len(), 1);
1341    }
1342
1343    // ── Empty items: no continuation to check ─────────────────────────
1344
1345    #[test]
1346    fn empty_item_no_warning() {
1347        let content = "- \n- Second\n";
1348        assert!(check(content).is_empty());
1349    }
1350
1351    // ── Multiple items, only some under-indented ──────────────────────
1352
1353    #[test]
1354    fn multiple_items_mixed_indent() {
1355        let content = "1. First\n\n   correct continuation\n\n2. Second\n\n  wrong continuation\n";
1356        let warnings = check(content);
1357        assert_eq!(warnings.len(), 1);
1358        assert_eq!(warnings[0].line, 7);
1359    }
1360
1361    // ── Task list items ───────────────────────────────────────────────
1362
1363    #[test]
1364    fn task_list_correct_indent() {
1365        // "- [ ] " = content_column is typically at col 6
1366        let content = "- [ ] Task\n\n      continuation\n";
1367        assert!(check(content).is_empty());
1368    }
1369
1370    // ── Frontmatter skipped ───────────────────────────────────────────
1371
1372    #[test]
1373    fn frontmatter_not_flagged() {
1374        let content = "---\ntitle: test\n---\n\n- Item\n\n  continuation\n";
1375        assert!(check(content).is_empty());
1376    }
1377
1378    // ── Fix produces valid output with multiple fixes ─────────────────
1379
1380    #[test]
1381    fn fix_multiple_items() {
1382        let content = "1. First\n\n wrong1\n\n2. Second\n\n wrong2\n";
1383        let fixed = fix(content);
1384        assert_eq!(fixed, "1. First\n\n   wrong1\n\n2. Second\n\n   wrong2\n");
1385    }
1386
1387    #[test]
1388    fn fix_multiline_loose_continuation_all_lines() {
1389        let content = "1. Item\n\n  line one\n  line two\n  line three\n";
1390        let fixed = fix(content);
1391        assert_eq!(fixed, "1. Item\n\n   line one\n   line two\n   line three\n");
1392    }
1393
1394    // ── No false positive when content is after sibling item ──────────
1395
1396    #[test]
1397    fn sibling_item_boundary_respected() {
1398        // The "continuation" after a blank belongs to "- Second", not "- First"
1399        let content = "- First\n- Second\n\n  continuation\n";
1400        assert!(check(content).is_empty());
1401    }
1402
1403    // ── Blockquote-nested lists ────────────────────────────────────────
1404
1405    #[test]
1406    fn blockquote_list_correct_indent_no_warning() {
1407        // Lists inside blockquotes: visual_indent includes the blockquote
1408        // prefix, so comparisons work on raw line columns.
1409        let content = "> - Item\n>\n>   continuation\n";
1410        assert!(check(content).is_empty());
1411    }
1412
1413    #[test]
1414    fn blockquote_list_under_indent_no_false_positive() {
1415        // Under-indented continuation inside a blockquote: visual_indent
1416        // starts at 0 (the `>` char) which is <= marker_col, so the scan
1417        // breaks and no warning is emitted. This is a known false negative
1418        // (not a false positive), which is the safer default.
1419        let content = "> - Item\n>\n> continuation\n";
1420        assert!(check(content).is_empty());
1421    }
1422
1423    // ── Deep nesting (3+ levels) ──────────────────────────────────────
1424
1425    #[test]
1426    fn deep_nesting_correct_indent() {
1427        let content = "- L1\n  - L2\n    - L3\n\n      continuation of L3\n";
1428        assert!(check(content).is_empty());
1429    }
1430
1431    #[test]
1432    fn deep_nesting_under_indent() {
1433        // L3 starts at column 4 with "- " marker, content_column = 6
1434        // Continuation with 5 spaces is under-indented for L3.
1435        let content = "- L1\n  - L2\n    - L3\n\n     continuation of L3\n";
1436        let warnings = check(content);
1437        assert_eq!(warnings.len(), 1);
1438        assert!(warnings[0].message.contains("6 spaces"));
1439        assert!(warnings[0].message.contains("found 5"));
1440    }
1441
1442    #[test]
1443    fn deep_nesting_middle_level_continuation_bullets() {
1444        // A loose continuation of the MIDDLE level (L2, content_column = 4)
1445        // after a deeper L3 list is valid; the L1 walk must not claim it as
1446        // its own over-indented continuation (issue #739).
1447        let content = "- L1\n  - L2\n    - L3\n\n    continuation of L2\n";
1448        assert!(check(content).is_empty());
1449    }
1450
1451    #[test]
1452    fn deep_nesting_middle_level_continuation_ordered() {
1453        // Issue #739 repro: ordered lists, continuation of the level-2 item
1454        // (content_column = 6) after a level-3 bullet list.
1455        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";
1456        assert!(check(content).is_empty());
1457    }
1458
1459    #[test]
1460    fn deep_nesting_outermost_continuation() {
1461        // A loose continuation of the OUTERMOST level (L1, content_column = 2)
1462        // past two open nested levels escapes both and stays valid.
1463        let content = "- L1\n  - L2\n    - L3\n\n  continuation of L1\n";
1464        assert!(check(content).is_empty());
1465    }
1466
1467    #[test]
1468    fn deep_nesting_between_levels_still_flagged() {
1469        // Col 3 sits strictly between L1's content column (2) and L2's (4):
1470        // the deepest applicable item (L2) claims it as loose under-indent.
1471        let content = "- L1\n  - L2\n    - L3\n\n   continuation\n";
1472        let warnings = check(content);
1473        assert_eq!(warnings.len(), 1);
1474        assert!(warnings[0].message.contains("4 spaces"));
1475        assert!(warnings[0].message.contains("found 3"));
1476    }
1477
1478    #[test]
1479    fn deep_nesting_beyond_deepest_still_flagged() {
1480        // Col 7 exceeds even L3's content column (6): over-indent for L3.
1481        let content = "- L1\n  - L2\n    - L3\n\n       continuation\n";
1482        let warnings = check(content);
1483        assert_eq!(warnings.len(), 1);
1484        assert!(warnings[0].message.contains("over-indented"));
1485        assert!(warnings[0].message.contains("expected 6, found 7"));
1486    }
1487
1488    #[test]
1489    fn four_levels_middle_continuation() {
1490        // Continuation of L2 (content_column = 4) after open L3 and L4 lists:
1491        // the walk must pop two deeper levels and still defer to L2.
1492        let content = "- L1\n  - L2\n    - L3\n      - L4\n\n    continuation of L2\n";
1493        assert!(check(content).is_empty());
1494    }
1495
1496    #[test]
1497    fn nested_sibling_closes_deeper_level() {
1498        // L2b closes L2a's deeper L3 list; a continuation at L2b's content
1499        // column belongs to L2b and stays valid.
1500        let content = "- L1\n  - L2a\n    - L3\n  - L2b\n\n    continuation of L2b\n";
1501        assert!(check(content).is_empty());
1502    }
1503
1504    #[test]
1505    fn deep_nesting_middle_level_continuation_fix_preserved() {
1506        // The valid middle-level continuation must survive fix() unchanged.
1507        let content = "- L1\n  - L2\n    - L3\n\n    continuation of L2\n";
1508        assert_eq!(fix(content), content);
1509    }
1510
1511    // ── Tab indentation ───────────────────────────────────────────────
1512
1513    #[test]
1514    fn loose_tab_continuation_over_indented() {
1515        // A tab expands to 4 visual columns, exceeding content_column = 2 for
1516        // "- ". Loose over-indent is flagged just like the tight tab case
1517        // (`tight_continuation_tab_over_indented`), and the fix normalizes the
1518        // tab down to the content-column indent.
1519        let content = "- Item\n\n\tcontinuation\n";
1520        let warnings = check(content);
1521        assert_eq!(warnings.len(), 1);
1522        assert_eq!(warnings[0].line, 3);
1523        assert_eq!(fix(content), "- Item\n\n  continuation\n");
1524    }
1525
1526    // ── Multiple continuation paragraphs ──────────────────────────────
1527
1528    #[test]
1529    fn multiple_continuations_correct() {
1530        let content = "- Item\n\n  para 1\n\n  para 2\n\n  para 3\n";
1531        assert!(check(content).is_empty());
1532    }
1533
1534    #[test]
1535    fn multiple_continuations_second_under_indent() {
1536        // First continuation is correct, second is under-indented
1537        let content = "- Item\n\n  para 1\n\n continuation 2\n";
1538        let warnings = check(content);
1539        assert_eq!(warnings.len(), 1);
1540        assert_eq!(warnings[0].line, 5);
1541    }
1542
1543    // ── Ordered list with `)` marker style ────────────────────────────
1544
1545    #[test]
1546    fn ordered_paren_marker_correct() {
1547        // "1) " is 3 chars, content_column = 3
1548        let content = "1) Item\n\n   continuation\n";
1549        assert!(check(content).is_empty());
1550    }
1551
1552    #[test]
1553    fn ordered_paren_marker_under_indent() {
1554        let content = "1) Item\n\n  continuation\n";
1555        let warnings = check(content);
1556        assert_eq!(warnings.len(), 1);
1557        assert!(warnings[0].message.contains("3 spaces"));
1558    }
1559
1560    // ── Star and plus markers ─────────────────────────────────────────
1561
1562    #[test]
1563    fn star_marker_correct() {
1564        let content = "* Item\n\n  continuation\n";
1565        assert!(check(content).is_empty());
1566    }
1567
1568    #[test]
1569    fn star_marker_under_indent() {
1570        let content = "* Item\n\n continuation\n";
1571        let warnings = check(content);
1572        assert_eq!(warnings.len(), 1);
1573    }
1574
1575    #[test]
1576    fn plus_marker_correct() {
1577        let content = "+ Item\n\n  continuation\n";
1578        assert!(check(content).is_empty());
1579    }
1580
1581    // ── Heading breaks scan ───────────────────────────────────────────
1582
1583    #[test]
1584    fn heading_after_list_no_warning() {
1585        let content = "- Item\n\n# Heading\n";
1586        assert!(check(content).is_empty());
1587    }
1588
1589    // ── Horizontal rule breaks scan ───────────────────────────────────
1590
1591    #[test]
1592    fn hr_after_list_no_warning() {
1593        let content = "- Item\n\n---\n";
1594        assert!(check(content).is_empty());
1595    }
1596
1597    // ── Reference link definitions skip ───────────────────────────────
1598
1599    #[test]
1600    fn reference_link_def_not_flagged() {
1601        let content = "- Item\n\n [link]: https://example.com\n";
1602        assert!(check(content).is_empty());
1603    }
1604
1605    // ── Footnote definitions skip ─────────────────────────────────────
1606
1607    #[test]
1608    fn footnote_def_not_flagged() {
1609        let content = "- Item\n\n [^1]: footnote text\n";
1610        assert!(check(content).is_empty());
1611    }
1612
1613    #[test]
1614    fn footnote_multiline_body_after_list_not_flagged() {
1615        // A footnote definition whose indented body follows a list must not be
1616        // read as over-indented list continuation. The 4-space body lines
1617        // belong to the footnote, not to `- This is a list.` (content col 2).
1618        let content = "# A list followed by a footnote\n\n\
1619                       Here is a paragraph.[^fn]\n\n\
1620                       - This is a list.\n\n\
1621                       [^fn]:\n\
1622                       \x20\x20\x20\x20Here is a footnote that spans multiple lines.\n\
1623                       \x20\x20\x20\x20It should thus be indented by at least four spaces.\n";
1624        assert!(check(content).is_empty());
1625    }
1626
1627    #[test]
1628    fn fix_footnote_multiline_body_after_list_is_noop() {
1629        // The false positive also produced a damaging auto-fix: reindenting the
1630        // footnote body from 4 spaces to 2 broke the footnote (then tripped
1631        // MD068). The fix must leave the footnote untouched.
1632        let content = "# A list followed by a footnote\n\n\
1633                       Here is a paragraph.[^fn]\n\n\
1634                       - This is a list.\n\n\
1635                       [^fn]:\n\
1636                       \x20\x20\x20\x20Here is a footnote that spans multiple lines.\n\
1637                       \x20\x20\x20\x20It should thus be indented by at least four spaces.\n";
1638        assert_eq!(fix(content), content);
1639    }
1640
1641    #[test]
1642    fn footnote_body_indented_past_list_content_col_not_flagged() {
1643        // Footnote body indented well past the list's content column (here a
1644        // single-space list marker would put content col at 2, body at 4) is
1645        // footnote content, not over-indented continuation.
1646        let content = "- Item\n\n[^fn]:\n    Body line one.\n    Body line two.\n";
1647        assert!(check(content).is_empty());
1648    }
1649
1650    #[test]
1651    fn list_inside_footnote_body_continuation_not_flagged() {
1652        // Accepted trade-off: a list living *inside* a footnote body is skipped
1653        // wholesale, so MD077 does not police its continuation indentation.
1654        // Consistent with MD007, which also skips footnote-internal content.
1655        let content = "Text.[^fn]\n\n[^fn]:\n\
1656                       \x20\x20\x20\x20- nested item\n\
1657                       \x20\x20\x20\x20\x20\x20\x20over-indented continuation\n";
1658        assert!(check(content).is_empty());
1659    }
1660
1661    #[test]
1662    fn footnote_multiline_body_after_list_not_flagged_mkdocs() {
1663        // Same protection under the MkDocs flavor. The body sits at 6 spaces,
1664        // past MkDocs's required indent of 4 for `- `, so without skipping
1665        // footnote content it would be flagged as over-indented continuation.
1666        let content = "Here is a paragraph.[^fn]\n\n\
1667                       - This is a list.\n\n\
1668                       [^fn]:\n\
1669                       \x20\x20\x20\x20\x20\x20Footnote body that spans\n\
1670                       \x20\x20\x20\x20\x20\x20multiple indented lines.\n";
1671        assert!(check_mkdocs(content).is_empty());
1672    }
1673
1674    // ── Fix preserves correct content ─────────────────────────────────
1675
1676    #[test]
1677    fn fix_deep_nesting() {
1678        let content = "- L1\n  - L2\n    - L3\n\n     under-indented\n";
1679        let fixed = fix(content);
1680        assert_eq!(fixed, "- L1\n  - L2\n    - L3\n\n      under-indented\n");
1681    }
1682
1683    #[test]
1684    fn fix_mkdocs_unordered() {
1685        // MkDocs: "- " has content_column 2, but MkDocs requires max(2,4) = 4
1686        let content = "- Item\n\n  continuation\n";
1687        let fixed = fix_mkdocs(content);
1688        assert_eq!(fixed, "- Item\n\n    continuation\n");
1689    }
1690
1691    #[test]
1692    fn fix_code_fence_indent() {
1693        // Fence opener, interior, and closer all shift by the same delta so
1694        // the parser keeps pairing the fences and MD031 doesn't misfire.
1695        let content = "- Item\n\n ```\n code\n ```\n";
1696        let fixed = fix(content);
1697        assert_eq!(fixed, "- Item\n\n  ```\n  code\n  ```\n");
1698    }
1699
1700    #[test]
1701    fn fix_mkdocs_code_fence_indent() {
1702        // MkDocs ordered list: fence at 3 spaces needs 4; interior shifts too
1703        let content = "1. Item\n\n   ```toml\n   key = \"val\"\n   ```\n";
1704        let fixed = fix_mkdocs(content);
1705        assert_eq!(fixed, "1. Item\n\n    ```toml\n    key = \"val\"\n    ```\n");
1706    }
1707
1708    // ── Empty document / whitespace-only ──────────────────────────────
1709
1710    #[test]
1711    fn empty_document_no_warning() {
1712        assert!(check("").is_empty());
1713    }
1714
1715    #[test]
1716    fn whitespace_only_no_warning() {
1717        assert!(check("   \n\n  \n").is_empty());
1718    }
1719
1720    // ── No list at all ────────────────────────────────────────────────
1721
1722    #[test]
1723    fn no_list_no_warning() {
1724        let content = "# Heading\n\nSome paragraph.\n\nAnother paragraph.\n";
1725        assert!(check(content).is_empty());
1726    }
1727
1728    // ── Multi-line continuation (additional coverage) ──────────────
1729
1730    #[test]
1731    fn multiline_continuation_all_lines_flagged() {
1732        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";
1733        let warnings = check(content);
1734        assert_eq!(warnings.len(), 3);
1735        assert_eq!(warnings[0].line, 3);
1736        assert_eq!(warnings[1].line, 4);
1737        assert_eq!(warnings[2].line, 5);
1738    }
1739
1740    #[test]
1741    fn multiline_continuation_with_frontmatter_fix() {
1742        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";
1743        let fixed = fix(content);
1744        assert_eq!(
1745            fixed,
1746            "---\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"
1747        );
1748    }
1749
1750    #[test]
1751    fn multiline_continuation_correct_indent_no_warning() {
1752        let content = "1. Item\n\n   line one\n   line two\n   line three\n";
1753        assert!(check(content).is_empty());
1754    }
1755
1756    #[test]
1757    fn multiline_continuation_mixed_indent() {
1758        let content = "1. Item\n\n   correct\n  wrong\n   correct\n";
1759        let warnings = check(content);
1760        assert_eq!(warnings.len(), 1);
1761        assert_eq!(warnings[0].line, 4);
1762    }
1763
1764    #[test]
1765    fn multiline_continuation_unordered() {
1766        let content = "- Item\n\n continuation 1\n continuation 2\n continuation 3\n";
1767        let warnings = check(content);
1768        assert_eq!(warnings.len(), 3);
1769        let fixed = fix(content);
1770        assert_eq!(
1771            fixed,
1772            "- Item\n\n  continuation 1\n  continuation 2\n  continuation 3\n"
1773        );
1774    }
1775
1776    #[test]
1777    fn multiline_continuation_two_items_fix() {
1778        let content = "1. First\n\n  cont a\n  cont b\n\n2. Second\n\n  cont c\n  cont d\n";
1779        let fixed = fix(content);
1780        assert_eq!(
1781            fixed,
1782            "1. First\n\n   cont a\n   cont b\n\n2. Second\n\n   cont c\n   cont d\n"
1783        );
1784    }
1785
1786    #[test]
1787    fn fence_fix_does_not_break_pairing_for_md031() {
1788        // Regression for issue #574: previously MD077 only reindented the
1789        // fence delimiter lines while leaving the code block's interior at
1790        // the old indent. Between iterations of the fix loop the parser
1791        // saw an opener-closer mismatch, and MD031 then injected stray
1792        // blank lines at the fence boundaries. MD077's compound fix must
1793        // now rewrite the whole block atomically so the fences stay paired.
1794        let content = "#### title\n\nabc\n\n\
1795                       1. ab\n\n\
1796                       \x20\x20`aabbccdd`\n\n\
1797                       2. cd\n\n\
1798                       \x20\x20`bbcc dd ee`\n\n\
1799                       \x20\x20```\n\
1800                       \x20\x20abcd\n\
1801                       \x20\x20ef gh\n\
1802                       \x20\x20```\n\n\
1803                       \x20\x20uu\n\n\
1804                       \x20\x20```\n\
1805                       \x20\x20cdef\n\
1806                       \x20\x20gh ij\n\
1807                       \x20\x20```\n";
1808        let expected = "#### title\n\nabc\n\n\
1809                        1. ab\n\n\
1810                        \x20\x20\x20`aabbccdd`\n\n\
1811                        2. cd\n\n\
1812                        \x20\x20\x20`bbcc dd ee`\n\n\
1813                        \x20\x20\x20```\n\
1814                        \x20\x20\x20abcd\n\
1815                        \x20\x20\x20ef gh\n\
1816                        \x20\x20\x20```\n\n\
1817                        \x20\x20\x20uu\n\n\
1818                        \x20\x20\x20```\n\
1819                        \x20\x20\x20cdef\n\
1820                        \x20\x20\x20gh ij\n\
1821                        \x20\x20\x20```\n";
1822        assert_eq!(fix(content), expected);
1823    }
1824
1825    #[test]
1826    fn multiline_continuation_separated_by_blank() {
1827        let content = "1. Item\n\n  para1 line1\n  para1 line2\n\n  para2 line1\n  para2 line2\n";
1828        let warnings = check(content);
1829        assert_eq!(warnings.len(), 4);
1830        let fixed = fix(content);
1831        assert_eq!(
1832            fixed,
1833            "1. Item\n\n   para1 line1\n   para1 line2\n\n   para2 line1\n   para2 line2\n"
1834        );
1835    }
1836
1837    #[test]
1838    fn tab_indented_fence_is_normalized_to_spaces() {
1839        // Leading tabs expand to the next multiple-of-4 column under
1840        // CommonMark, so simply prepending spaces before a tab would
1841        // silently no-op (the tab snaps back to column 4). The compound
1842        // fence fix must replace the leading whitespace with a fresh
1843        // (visual_indent + delta) run of spaces. A `100. ` item has
1844        // content_column = 5, so a tab-indented fence (visual col 4) is
1845        // under-indented by 1 and must end up at 5 spaces after the fix.
1846        let content = "100. ab\n\n\t```\n\tabcd\n\t```\n";
1847        let expected = "100. ab\n\n     ```\n     abcd\n     ```\n";
1848        assert_eq!(fix(content), expected);
1849    }
1850
1851    // ── Loose continuation (after a blank line): over-indent ──────────
1852    //
1853    // Over-indentation is a mistake in both tight and loose continuation:
1854    // the body looks aligned but isn't. A blank line between the marker and
1855    // the body must not exempt it. The only over-indent that is intentional
1856    // after a blank line is an indented code block (content column + 4 or
1857    // more), which the parser marks `in_code_block` and the rule skips.
1858
1859    #[test]
1860    fn loose_continuation_over_indented_flagged() {
1861        // "* " content column is 2; 3 spaces after a blank is over-indented
1862        // (the code-block threshold is content_col + 4 = 6).
1863        let content = "* Item\n\n   over-indented\n";
1864        let warnings = check(content);
1865        assert_eq!(warnings.len(), 1);
1866        assert_eq!(warnings[0].line, 3);
1867        assert!(warnings[0].message.contains("over-indented"));
1868        assert!(warnings[0].message.contains("expected 2"));
1869        assert!(warnings[0].message.contains("found 3"));
1870    }
1871
1872    #[test]
1873    fn loose_continuation_over_indented_multiline_mixed() {
1874        // Over, correct, over — only the two over-indented lines are flagged.
1875        let content = "* Item\n\n   over one\n  correct\n   over two\n";
1876        let warnings = check(content);
1877        assert_eq!(warnings.len(), 2);
1878        assert_eq!(warnings[0].line, 3);
1879        assert_eq!(warnings[1].line, 5);
1880    }
1881
1882    #[test]
1883    fn fix_loose_continuation_over_indented() {
1884        let content = "* Item\n\n   over one\n  correct\n   over two\n";
1885        let fixed = fix(content);
1886        assert_eq!(fixed, "* Item\n\n  over one\n  correct\n  over two\n");
1887    }
1888
1889    #[test]
1890    fn fix_tight_and_loose_items_normalized_identically() {
1891        // The reported document: a tight item and a loose item with the same
1892        // over-indented body must both normalize to the content column.
1893        let content = "---\ntitle: Heading\n---\n\nSome introductory text:\n\n\
1894                       * 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\
1895                       * 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";
1896        let expected = "---\ntitle: Heading\n---\n\nSome introductory text:\n\n\
1897                        * 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\
1898                        * 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";
1899        assert_eq!(fix(content), expected);
1900    }
1901
1902    #[test]
1903    fn multi_paragraph_item_loose_paragraph_over_indented() {
1904        // A tight first paragraph and a loose second paragraph (after an
1905        // internal blank line) are both over-indented; both must be flagged.
1906        let content = "* Item.\n   tight over\n\n   loose over\n";
1907        let warnings = check(content);
1908        assert_eq!(warnings.len(), 2);
1909        assert_eq!(warnings[0].line, 2);
1910        assert_eq!(warnings[1].line, 4);
1911    }
1912
1913    #[test]
1914    fn loose_indented_code_block_not_flagged() {
1915        // content_col = 2; a loose line at content_col + 4 (6 spaces) is a
1916        // CommonMark indented code block, not over-indented prose. The over-
1917        // indent check must never reach it (it is `in_code_block` and skipped).
1918        let content = "- Item\n\n      code line\n";
1919        assert!(check(content).is_empty());
1920    }
1921
1922    #[test]
1923    fn mkdocs_loose_over_indented_flagged() {
1924        // MkDocs requires max(3, 4) = 4 for "1. ". A loose line at 5 spaces is
1925        // over-indented (code-block threshold is content_col + 4 = 7).
1926        let content = "1. Item\n\n     over\n";
1927        let warnings = check_mkdocs(content);
1928        assert_eq!(warnings.len(), 1);
1929        assert_eq!(warnings[0].line, 3);
1930        assert!(warnings[0].message.contains("over-indented"));
1931        assert!(warnings[0].message.contains("expected 4"));
1932        assert!(warnings[0].message.contains("found 5"));
1933    }
1934
1935    #[test]
1936    fn task_list_loose_over_indented_flagged() {
1937        // "- [ ] " content_col = 2, task_col = 6. A loose line at 4 spaces is
1938        // neither valid column and below the code-block threshold (6); flagged.
1939        let content = "- [ ] Task\n\n    over\n";
1940        let warnings = check(content);
1941        assert_eq!(warnings.len(), 1);
1942        assert_eq!(warnings[0].line, 3);
1943    }
1944
1945    #[test]
1946    fn loose_over_indent_boundary_below_code_block_threshold_flagged() {
1947        // content_col = 2; 5 spaces (= content_col + 3) is the deepest loose
1948        // over-indent that is still prose. content_col + 4 (6 spaces) would be
1949        // an indented code block - see `loose_indented_code_block_not_flagged`.
1950        // This pins the boundary so a shift in the parser's threshold is caught.
1951        let content = "- Item\n\n     over\n";
1952        let warnings = check(content);
1953        assert_eq!(warnings.len(), 1);
1954        assert_eq!(warnings[0].line, 3);
1955        assert!(warnings[0].message.contains("expected 2"));
1956        assert!(warnings[0].message.contains("found 5"));
1957    }
1958
1959    #[test]
1960    fn loose_over_indent_does_not_steal_nested_under_indent() {
1961        // Inner content_col = 4, marker_col = 2. A loose continuation at column
1962        // 3 is under-indented for Inner yet over-indented for Outer (content_col
1963        // 2). The under-indent pass must claim it for Inner (snap *up* to 4,
1964        // preserving the apparent nesting), never letting the over-indent pass
1965        // mis-attribute it to Outer and snap it *down* to 2. This is the exact
1966        // ambiguity the two-pass ordering exists to resolve.
1967        let content = "- Outer\n  - Inner\n\n   continuation\n";
1968        let warnings = check(content);
1969        assert_eq!(warnings.len(), 1);
1970        assert_eq!(warnings[0].line, 4);
1971        assert!(warnings[0].message.contains("4 spaces"));
1972        assert!(warnings[0].message.contains("found 3"));
1973        assert_eq!(fix(content), "- Outer\n  - Inner\n\n    continuation\n");
1974    }
1975
1976    #[test]
1977    fn loose_over_indent_attributes_to_deepest_enclosing_item() {
1978        // Inner content_col = 4. A loose continuation at column 5 over-indents
1979        // Inner (the deepest item it sits within), so it is flagged against
1980        // Inner's column 4 - not Outer's column 2 - and snapped to 4.
1981        let content = "- Outer\n  - Inner\n\n     continuation\n";
1982        let warnings = check(content);
1983        assert_eq!(warnings.len(), 1);
1984        assert_eq!(warnings[0].line, 4);
1985        assert!(warnings[0].message.contains("expected 4"));
1986        assert!(warnings[0].message.contains("found 5"));
1987        assert_eq!(fix(content), "- Outer\n  - Inner\n\n    continuation\n");
1988    }
1989
1990    // ── Over-indented fenced code blocks are left untouched ───────────
1991    //
1992    // An over-indented fence is cosmetic: the code still renders inside the
1993    // list item. Reindenting only its delimiters (the body is skipped as code)
1994    // would change the literal code content, so the over-indent pass skips
1995    // anything `in_code_block`. The under-indent path still fixes fences, where
1996    // moving the block up is required to keep it inside the item.
1997
1998    #[test]
1999    fn loose_over_indented_fence_not_flagged() {
2000        let content = "- Item\n\n   ```\n   code\n   ```\n";
2001        assert!(check(content).is_empty());
2002        assert_eq!(fix(content), content);
2003    }
2004
2005    #[test]
2006    fn tight_over_indented_fence_not_flagged() {
2007        let content = "- Item\n   ```\n   code\n   ```\n";
2008        assert!(check(content).is_empty());
2009        assert_eq!(fix(content), content);
2010    }
2011
2012    #[test]
2013    fn over_indented_tilde_fence_not_flagged() {
2014        let content = "- Item\n\n   ~~~\n   code\n   ~~~\n";
2015        assert!(check(content).is_empty());
2016        assert_eq!(fix(content), content);
2017    }
2018
2019    #[test]
2020    fn fence_like_code_content_inside_fenced_block_not_flagged() {
2021        // A ``` line that is the *body* of a ~~~ block must not be treated as
2022        // over-indented continuation; rewriting it would corrupt code content.
2023        let content = "- Item\n\n  ~~~\n   ```\n  ~~~\n";
2024        assert!(check(content).is_empty());
2025        assert_eq!(fix(content), content);
2026    }
2027
2028    #[test]
2029    fn unterminated_over_indented_fence_not_flagged() {
2030        // No closing fence: the last code line must not be mistaken for a
2031        // closer and snapped to the content column.
2032        let content = "- Item\n\n   ```\n   code1\n     code2deeper\n";
2033        assert!(check(content).is_empty());
2034        assert_eq!(fix(content), content);
2035    }
2036
2037    // ── GFM task list items: post-checkbox continuation column ───────
2038    //
2039    // MD013's reflow indents wrapped task-list lines at `content_col + 4`
2040    // (the column after the checkbox). MD077 must accept that column for
2041    // both tight and loose continuation, for every marker flavour, so the
2042    // two rules don't fight over well-formed task items (issue #579).
2043
2044    #[test]
2045    fn task_list_tight_continuation_post_checkbox_reproducer_579() {
2046        // Exact reproducer from the bug report: content wraps to the
2047        // post-checkbox column (6) with no blank line.
2048        let content = "- [ ] Lorem ipsum dolor sit amet, consectetur adipiscing\n      tempor incididunt ut labore.\n";
2049        assert!(check(content).is_empty());
2050    }
2051
2052    #[test]
2053    fn task_list_tight_continuation_dash_unchecked() {
2054        let content = "- [ ] Task\n      continuation\n";
2055        assert!(check(content).is_empty());
2056    }
2057
2058    #[test]
2059    fn task_list_tight_continuation_dash_checked_lower() {
2060        let content = "- [x] Task\n      continuation\n";
2061        assert!(check(content).is_empty());
2062    }
2063
2064    #[test]
2065    fn task_list_tight_continuation_dash_checked_upper() {
2066        let content = "- [X] Task\n      continuation\n";
2067        assert!(check(content).is_empty());
2068    }
2069
2070    #[test]
2071    fn task_list_tight_continuation_star_marker() {
2072        let content = "* [ ] Task\n      continuation\n";
2073        assert!(check(content).is_empty());
2074    }
2075
2076    #[test]
2077    fn task_list_tight_continuation_plus_marker() {
2078        let content = "+ [ ] Task\n      continuation\n";
2079        assert!(check(content).is_empty());
2080    }
2081
2082    #[test]
2083    fn task_list_tight_continuation_content_column_still_valid() {
2084        // Column 2 is the CommonMark-canonical indent for "- " and remains
2085        // valid for task items too.
2086        let content = "- [ ] Task\n  continuation\n";
2087        assert!(check(content).is_empty());
2088    }
2089
2090    #[test]
2091    fn task_list_tight_continuation_between_columns_still_flagged() {
2092        // Column 4 matches neither content_col (2) nor post-checkbox (6).
2093        // A genuine indentation mistake — must remain flagged.
2094        let content = "- [ ] Task\n    continuation\n";
2095        let warnings = check(content);
2096        assert_eq!(warnings.len(), 1);
2097        // Task items advertise both valid columns to the user.
2098        assert!(warnings[0].message.contains("expected 2 or 6"));
2099        assert!(warnings[0].message.contains("found 4"));
2100    }
2101
2102    #[test]
2103    fn task_list_tight_continuation_overshoot_still_flagged() {
2104        // Column 7 overshoots the post-checkbox column. Genuine mistake.
2105        let content = "- [ ] Task\n       continuation\n";
2106        let warnings = check(content);
2107        assert_eq!(warnings.len(), 1);
2108        assert!(warnings[0].message.contains("expected 2 or 6"));
2109        assert!(warnings[0].message.contains("found 7"));
2110    }
2111
2112    // ── Task-list fix output: snap to nearer valid column ────────────
2113
2114    #[test]
2115    fn fix_task_list_overshoot_snaps_to_task_col() {
2116        // Col 7 is 1 away from post-checkbox (6), 5 away from content (2).
2117        // Snap to 6 — the author's intent was almost certainly the
2118        // post-checkbox alignment, not the content column.
2119        let content = "- [ ] Task\n       continuation\n";
2120        let fixed = fix(content);
2121        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2122    }
2123
2124    #[test]
2125    fn fix_task_list_col_5_snaps_to_task_col() {
2126        // Col 5 is 1 away from post-checkbox (6), 3 away from content (2).
2127        let content = "- [ ] Task\n     continuation\n";
2128        let fixed = fix(content);
2129        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2130    }
2131
2132    #[test]
2133    fn fix_task_list_col_3_snaps_to_content_col() {
2134        // Col 3 is 1 away from content (2), 3 away from post-checkbox (6).
2135        let content = "- [ ] Task\n   continuation\n";
2136        let fixed = fix(content);
2137        assert_eq!(fixed, "- [ ] Task\n  continuation\n");
2138    }
2139
2140    #[test]
2141    fn fix_task_list_col_4_ties_to_content_col() {
2142        // Col 4 is equidistant (±2) from both columns. Tie breaks to the
2143        // CommonMark-canonical content column — that's the default indent
2144        // MD077 would produce for a non-task item, so prefer it when the
2145        // author's intent is ambiguous.
2146        let content = "- [ ] Task\n    continuation\n";
2147        let fixed = fix(content);
2148        assert_eq!(fixed, "- [ ] Task\n  continuation\n");
2149    }
2150
2151    #[test]
2152    fn fix_task_list_ordered_overshoot_snaps_to_task_col() {
2153        // "1. [ ] " → content_col = 3, post-checkbox = 7.
2154        // Col 8 is nearer to 7.
2155        let content = "1. [ ] Task\n        continuation\n";
2156        let fixed = fix(content);
2157        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2158    }
2159
2160    #[test]
2161    fn fix_task_list_ordered_under_overshoot_snaps_to_content_col() {
2162        // "1. [ ] " → content_col = 3, post-checkbox = 7.
2163        // Col 4 is nearer to 3.
2164        let content = "1. [ ] Task\n    continuation\n";
2165        let fixed = fix(content);
2166        assert_eq!(fixed, "1. [ ] Task\n   continuation\n");
2167    }
2168
2169    #[test]
2170    fn task_list_tight_continuation_ordered_single_digit() {
2171        // "1. [ ] " → content_col = 3, post-checkbox = 7
2172        let content = "1. [ ] Task\n       continuation\n";
2173        assert!(check(content).is_empty());
2174    }
2175
2176    #[test]
2177    fn task_list_tight_continuation_ordered_multi_digit() {
2178        // "10. [ ] " → content_col = 4, post-checkbox = 8
2179        let content = "10. [ ] Task\n        continuation\n";
2180        assert!(check(content).is_empty());
2181    }
2182
2183    #[test]
2184    fn task_list_tight_continuation_nested_dash() {
2185        // Nested "  - [ ] " at marker_col=2 → content_col=4, post-checkbox=8
2186        let content = "- Parent\n  - [ ] Nested task\n        continuation\n";
2187        assert!(check(content).is_empty());
2188    }
2189
2190    #[test]
2191    fn task_list_loose_continuation_post_checkbox_column_not_flagged() {
2192        // Loose continuation (blank line) at col 6 is also valid. This
2193        // already passed before the fix, but pin the intent: the 6-space
2194        // indent is accepted because it's the task-alignment column, not
2195        // because the under-indent check happens to let it through.
2196        let content = "- [ ] Task\n\n      continuation\n";
2197        assert!(check(content).is_empty());
2198    }
2199
2200    #[test]
2201    fn task_list_empty_body_is_not_a_task() {
2202        // "- [ ]" with nothing after is an empty regular list item, not a
2203        // task. Column 4 continuation has no task alignment to justify it
2204        // and must still be flagged as over-indented. (Col 6 would turn
2205        // the continuation into an indented code block inside the item,
2206        // which is a different code path.)
2207        let content = "- [ ]\n    continuation\n";
2208        let warnings = check(content);
2209        assert_eq!(warnings.len(), 1);
2210        assert!(warnings[0].message.contains("found 4"));
2211    }
2212
2213    #[test]
2214    fn task_list_malformed_checkbox_is_not_a_task() {
2215        // `[~] ` is not a GFM checkbox; only `[ ] `, `[x] `, `[X] ` count.
2216        let content = "- [~] Not a task\n      continuation\n";
2217        let warnings = check(content);
2218        assert_eq!(warnings.len(), 1);
2219    }
2220
2221    // ── MkDocs flavor × task checkbox ─────────────────────────────────
2222    //
2223    // MkDocs strict-indent and task alignment interact: required_min is
2224    // max(content_col, 4), and post-checkbox is content_col + 4. Both are
2225    // independently valid; values between them are flagged.
2226
2227    #[test]
2228    fn task_list_mkdocs_unordered_required_min_valid() {
2229        // "- [ ]" MkDocs: required_min = max(2, 4) = 4, post-checkbox = 6.
2230        let content = "- [ ] Task\n    continuation\n";
2231        assert!(check_mkdocs(content).is_empty());
2232    }
2233
2234    #[test]
2235    fn task_list_mkdocs_unordered_post_checkbox_valid() {
2236        let content = "- [ ] Task\n      continuation\n";
2237        assert!(check_mkdocs(content).is_empty());
2238    }
2239
2240    #[test]
2241    fn task_list_mkdocs_unordered_between_flagged() {
2242        // Column 5 is between required_min=4 and post-checkbox=6.
2243        let content = "- [ ] Task\n     continuation\n";
2244        let warnings = check_mkdocs(content);
2245        assert_eq!(warnings.len(), 1);
2246    }
2247
2248    #[test]
2249    fn task_list_mkdocs_ordered_both_columns_valid() {
2250        // "1. [ ]" MkDocs: required_min = max(3, 4) = 4, post-checkbox = 7.
2251        let at_4 = "1. [ ] Task\n    continuation\n";
2252        assert!(check_mkdocs(at_4).is_empty());
2253        let at_7 = "1. [ ] Task\n       continuation\n";
2254        assert!(check_mkdocs(at_7).is_empty());
2255    }
2256
2257    #[test]
2258    fn task_list_mkdocs_ordered_between_flagged() {
2259        // Column 5 and 6 are between required_min=4 and post-checkbox=7.
2260        let at_5 = "1. [ ] Task\n     continuation\n";
2261        assert_eq!(check_mkdocs(at_5).len(), 1);
2262        let at_6 = "1. [ ] Task\n      continuation\n";
2263        assert_eq!(check_mkdocs(at_6).len(), 1);
2264    }
2265
2266    // ── Context-aware tie-break ──────────────────────────────────────
2267    //
2268    // When a flagged line is exactly equidistant from `content_col` and
2269    // `task_col`, the author's intent is ambiguous. Before picking a
2270    // canonical default, look at whether other continuation lines in the
2271    // same item already use one of the valid columns — if so, snap to the
2272    // column they're using so the fix preserves the author's visible
2273    // convention.
2274
2275    #[test]
2276    fn fix_task_list_tie_sibling_at_task_col_snaps_to_task_col() {
2277        // Col 4 is equidistant from content_col (2) and task_col (6).
2278        // A valid sibling at col 6 proves the author is aligning under the
2279        // checkbox, so the tie resolves to col 6.
2280        let content = "- [ ] Task\n      aligned continuation\n    tied continuation\n";
2281        let fixed = fix(content);
2282        assert_eq!(
2283            fixed,
2284            "- [ ] Task\n      aligned continuation\n      tied continuation\n"
2285        );
2286    }
2287
2288    #[test]
2289    fn fix_task_list_tie_sibling_at_content_col_snaps_to_content_col() {
2290        // Valid sibling at col 2 proves the author is aligning to the
2291        // content column, so the col-4 tie resolves to col 2.
2292        let content = "- [ ] Task\n  aligned continuation\n    tied continuation\n";
2293        let fixed = fix(content);
2294        assert_eq!(fixed, "- [ ] Task\n  aligned continuation\n  tied continuation\n");
2295    }
2296
2297    #[test]
2298    fn fix_task_list_tie_both_siblings_snaps_to_content_col() {
2299        // When siblings exist at both valid columns, the author's pattern
2300        // is self-contradictory. Fall back to the CommonMark-canonical
2301        // content column.
2302        let content = "- [ ] Task\n  at content col\n      at task col\n    tied continuation\n";
2303        let fixed = fix(content);
2304        assert_eq!(
2305            fixed,
2306            "- [ ] Task\n  at content col\n      at task col\n  tied continuation\n"
2307        );
2308    }
2309
2310    #[test]
2311    fn fix_task_list_tie_sees_task_col_through_tight_lazy_continuation() {
2312        // CommonMark allows tight lazy continuation at col ≤ marker_col
2313        // (zero-indent continuation) inside a list item. The pre-pass
2314        // must MIRROR the main check loop's termination semantics: in
2315        // tight mode (no preceding blank) col ≤ marker_col is NOT a
2316        // termination signal — the lazy line still belongs to the item.
2317        //
2318        // This test pins that mirroring: a `lazy` line at col 0 is
2319        // followed by a legitimate task-col sibling at col 6, then a
2320        // tied col-4 line. If the pre-pass terminated eagerly at the
2321        // lazy line, the task-col sibling would be missed and the tied
2322        // line would fall back to content column. With correct
2323        // mirroring, the task-col sibling is seen and the tie resolves
2324        // to col 6.
2325        let content = concat!("- [ ] Task\n", "lazy\n", "      aligned at task col\n", "    tied\n",);
2326        let fixed = fix(content);
2327        assert!(
2328            fixed.contains("\n      tied\n"),
2329            "tied line should snap to col 6 (task col) because a task-col \
2330             sibling is visible past the tight lazy-continuation line; got:\n{fixed}"
2331        );
2332    }
2333
2334    // ── Tab-indented task continuation ───────────────────────────────
2335    //
2336    // Leading tabs expand to the next column that's a multiple of 4 under
2337    // CommonMark. The fix replaces the leading whitespace bytes wholesale,
2338    // turning tabs into space-indented output.
2339
2340    #[test]
2341    fn task_list_tab_indented_continuation_flagged() {
2342        // Two tabs → visual col 8, which overshoots both valid columns
2343        // for `- [ ] ` (content_col=2, task_col=6).
2344        let content = "- [ ] Task\n\t\twrap\n";
2345        let warnings = check(content);
2346        assert_eq!(warnings.len(), 1);
2347        assert!(warnings[0].message.contains("expected 2 or 6"));
2348        assert!(warnings[0].message.contains("found 8"));
2349    }
2350
2351    #[test]
2352    fn fix_task_list_tab_indented_snaps_to_task_col() {
2353        // abs_diff(8, 6) = 2 < abs_diff(8, 2) = 6 → snap to task_col (6).
2354        let content = "- [ ] Task\n\t\twrap\n";
2355        let fixed = fix(content);
2356        assert_eq!(fixed, "- [ ] Task\n      wrap\n");
2357    }
2358
2359    #[test]
2360    fn fix_task_list_single_tab_equidistant_snaps_to_content_col() {
2361        // One tab → visual col 4, equidistant from content_col (2) and
2362        // task_col (6). No siblings → tie-break to content_col.
2363        let content = "- [ ] Task\n\twrap\n";
2364        let fixed = fix(content);
2365        assert_eq!(fixed, "- [ ] Task\n  wrap\n");
2366    }
2367
2368    // ── Blockquote × task-list ───────────────────────────────────────
2369    //
2370    // Blockquote-nested lists are a known limitation on MD077: the list
2371    // parser doesn't always expose them with the same column semantics as
2372    // top-level lists, and the rule prefers a false-negative default to
2373    // avoid spurious warnings inside blockquotes (see
2374    // `blockquote_list_under_indent_no_false_positive`). These tests pin
2375    // the current behavior so any future change is intentional.
2376
2377    #[test]
2378    fn task_list_blockquote_post_checkbox_not_flagged() {
2379        // Post-checkbox alignment inside a blockquote — accepted as valid.
2380        let content = "> - [ ] Task\n>       continuation\n";
2381        assert!(check(content).is_empty());
2382    }
2383
2384    #[test]
2385    fn task_list_blockquote_between_cols_documented_limitation() {
2386        // Col-4-equivalent inside a blockquote is silently accepted — a
2387        // known MD077 limitation on blockquote-nested lists, not a task-
2388        // list-specific choice. Pinning the current behavior.
2389        let content = "> - [ ] Task\n>     continuation\n";
2390        assert!(check(content).is_empty());
2391    }
2392
2393    #[test]
2394    fn task_list_blockquote_overshoot_documented_limitation() {
2395        // Overshoot inside a blockquote — same known limitation.
2396        let content = "> - [ ] Task\n>        continuation\n";
2397        assert!(check(content).is_empty());
2398    }
2399
2400    // ── MkDocs × task × fix output ───────────────────────────────────
2401    //
2402    // MkDocs strict-indent raises `required` to max(content_col, 4) while
2403    // task_col stays at content_col + 4. The snap logic operates on the
2404    // raised required, not on the underlying content_col.
2405
2406    #[test]
2407    fn fix_task_list_mkdocs_unordered_overshoot_snaps_to_task_col() {
2408        // `- [ ]` MkDocs: required=4, task_col=6. Col 7 → abs_diff(7,6)=1
2409        // < abs_diff(7,4)=3. Snap to task_col.
2410        let content = "- [ ] Task\n       continuation\n";
2411        let fixed = fix_mkdocs(content);
2412        assert_eq!(fixed, "- [ ] Task\n      continuation\n");
2413    }
2414
2415    #[test]
2416    fn fix_task_list_mkdocs_unordered_tie_snaps_to_required() {
2417        // `- [ ]` MkDocs: required=4, task_col=6. Col 5 → abs_diff(5,6)=1
2418        // == abs_diff(5,4)=1. Tie with no siblings → required (4).
2419        let content = "- [ ] Task\n     continuation\n";
2420        let fixed = fix_mkdocs(content);
2421        assert_eq!(fixed, "- [ ] Task\n    continuation\n");
2422    }
2423
2424    #[test]
2425    fn fix_task_list_mkdocs_ordered_overshoot_snaps_to_task_col() {
2426        // `1. [ ]` MkDocs: required=4, task_col=7. Col 8 → abs_diff(8,7)=1
2427        // < abs_diff(8,4)=4. Snap to task_col.
2428        let content = "1. [ ] Task\n        continuation\n";
2429        let fixed = fix_mkdocs(content);
2430        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2431    }
2432
2433    #[test]
2434    fn fix_task_list_mkdocs_ordered_near_required_snaps_to_required() {
2435        // `1. [ ]` MkDocs: required=4, task_col=7. Col 5 → abs_diff(5,7)=2
2436        // > abs_diff(5,4)=1. Snap to required (4). `1. [ ] Task\n     wrap`
2437        // has actual=5 which is over `required=4` so it's flagged in
2438        // strict mode, while in standard mode it falls under the lazy-
2439        // continuation window and isn't flagged at all.
2440        let content = "1. [ ] Task\n     continuation\n";
2441        let fixed = fix_mkdocs(content);
2442        assert_eq!(fixed, "1. [ ] Task\n    continuation\n");
2443    }
2444
2445    #[test]
2446    fn fix_task_list_mkdocs_ordered_between_cols_snaps_to_task_col() {
2447        // `1. [ ]` MkDocs: required=4, task_col=7. Col 6 → abs_diff(6,7)=1
2448        // < abs_diff(6,4)=2. Snap to task_col (7).
2449        let content = "1. [ ] Task\n      continuation\n";
2450        let fixed = fix_mkdocs(content);
2451        assert_eq!(fixed, "1. [ ] Task\n       continuation\n");
2452    }
2453
2454    // ── Fix idempotency (property test) ──────────────────────────────
2455    //
2456    // A fix pass on already-fixed content must produce the same content
2457    // — otherwise MD077 would oscillate on repeated invocations. This is
2458    // the core property that issue #579 was about (MD077 vs. MD013 fix
2459    // loop), and the integration test covers the MD013 interaction. The
2460    // property tests below pin the *internal* idempotency of MD077's own
2461    // fix, so any future change that introduces oscillation fails fast.
2462
2463    fn assert_idempotent(content: &str) {
2464        let once = fix(content);
2465        let twice = fix(&once);
2466        assert_eq!(once, twice, "MD077 fix was not idempotent on input: {content:?}");
2467    }
2468
2469    fn assert_idempotent_mkdocs(content: &str) {
2470        let once = fix_mkdocs(content);
2471        let twice = fix_mkdocs(&once);
2472        assert_eq!(
2473            once, twice,
2474            "MD077 (MkDocs) fix was not idempotent on input: {content:?}"
2475        );
2476    }
2477
2478    #[test]
2479    fn idempotent_task_list_between_cols() {
2480        assert_idempotent("- [ ] Task\n    continuation\n");
2481    }
2482
2483    #[test]
2484    fn idempotent_task_list_overshoot() {
2485        assert_idempotent("- [ ] Task\n       continuation\n");
2486    }
2487
2488    #[test]
2489    fn idempotent_task_list_under_post_checkbox() {
2490        assert_idempotent("- [ ] Task\n   continuation\n");
2491    }
2492
2493    #[test]
2494    fn idempotent_task_list_near_post_checkbox() {
2495        assert_idempotent("- [ ] Task\n     continuation\n");
2496    }
2497
2498    #[test]
2499    fn idempotent_task_list_tab_overshoot() {
2500        assert_idempotent("- [ ] Task\n\t\twrap\n");
2501    }
2502
2503    #[test]
2504    fn idempotent_task_list_single_tab() {
2505        assert_idempotent("- [ ] Task\n\twrap\n");
2506    }
2507
2508    #[test]
2509    fn idempotent_task_list_ordered_overshoot() {
2510        assert_idempotent("1. [ ] Task\n        continuation\n");
2511    }
2512
2513    #[test]
2514    fn idempotent_task_list_ordered_under() {
2515        assert_idempotent("1. [ ] Task\n    continuation\n");
2516    }
2517
2518    #[test]
2519    fn idempotent_task_list_tie_with_sibling_at_task_col() {
2520        assert_idempotent("- [ ] Task\n      aligned\n    tied\n");
2521    }
2522
2523    #[test]
2524    fn idempotent_task_list_tie_with_sibling_at_content_col() {
2525        assert_idempotent("- [ ] Task\n  aligned\n    tied\n");
2526    }
2527
2528    #[test]
2529    fn idempotent_task_list_mkdocs_unordered_overshoot() {
2530        assert_idempotent_mkdocs("- [ ] Task\n       continuation\n");
2531    }
2532
2533    #[test]
2534    fn idempotent_task_list_mkdocs_unordered_tie() {
2535        assert_idempotent_mkdocs("- [ ] Task\n     continuation\n");
2536    }
2537
2538    #[test]
2539    fn idempotent_task_list_mkdocs_ordered_overshoot() {
2540        assert_idempotent_mkdocs("1. [ ] Task\n        continuation\n");
2541    }
2542
2543    #[test]
2544    fn idempotent_task_list_mkdocs_ordered_between() {
2545        assert_idempotent_mkdocs("1. [ ] Task\n      continuation\n");
2546    }
2547
2548    #[test]
2549    fn idempotent_task_list_reproducer_579() {
2550        // The exact reproducer from issue #579 already has correct indent
2551        // (col 6 = post-checkbox), so idempotency is trivially true. Pin
2552        // it anyway as a smoke test against future regressions.
2553        assert_idempotent(
2554            "- [ ] Lorem ipsum dolor sit amet, consectetur adipiscing\n      tempor incididunt ut labore.\n",
2555        );
2556    }
2557
2558    #[test]
2559    fn idempotent_non_task_list_still_holds() {
2560        // Non-task items never enter the task_col code path; sanity-check
2561        // that idempotency is preserved for them too.
2562        assert_idempotent("1. Item\n    over-indented\n");
2563        assert_idempotent("- Item\n\n continuation\n");
2564    }
2565
2566    // ── Non-task idempotency: loose-mode under-indent ────────────────
2567    //
2568    // When a blank line precedes the continuation (loose mode),
2569    // under-indented content is flagged and fixed up to the content
2570    // column. Idempotency pins that one pass of the fix is sufficient.
2571
2572    #[test]
2573    fn idempotent_non_task_loose_under_indent_ordered() {
2574        // 1. Item → content col 3; "  x" is 2 spaces, under content col.
2575        assert_idempotent("1. Item\n\n  continuation\n");
2576    }
2577
2578    #[test]
2579    fn idempotent_non_task_loose_under_indent_multi_digit() {
2580        // 10. Item → content col 4; single-space continuation needs 4.
2581        assert_idempotent("10. Item\n\n continuation\n");
2582    }
2583
2584    #[test]
2585    fn idempotent_non_task_tight_over_indent_ordered() {
2586        // Tight-mode over-indent: 5 spaces where content col is 3.
2587        assert_idempotent("1. Item\n     over-indented\n");
2588    }
2589
2590    // ── Non-task idempotency: fenced code block compound fix ─────────
2591    //
2592    // A fence opener that needs re-indenting is repaired by the
2593    // compound-fence fix which shifts opener + interior + closer
2594    // together. Idempotency pins that the compound fix settles in one
2595    // pass and does not oscillate between runs.
2596
2597    #[test]
2598    fn idempotent_non_task_fence_ordered_loose() {
2599        // 1. Item → content col 3; fence at col 2 needs to shift to 3.
2600        assert_idempotent("1. Item\n\n  ```rust\n  let x = 1;\n  ```\n");
2601    }
2602
2603    #[test]
2604    fn idempotent_non_task_fence_tilde_under_indent() {
2605        // Tilde fences use the same compound-fix path as backtick fences.
2606        // Interior below the list scope (col 0 here, required col 3) must
2607        // be promoted up in the same pass as the fence delimiters —
2608        // otherwise a second pass would flag the interior individually
2609        // and defeat idempotency.
2610        assert_idempotent("1. Item\n\n  ~~~\nplain text\n  ~~~\n");
2611    }
2612
2613    #[test]
2614    fn idempotent_non_task_fence_interior_above_required() {
2615        // Interior already above the required column must not be pushed
2616        // further up by the compound fix — authored interior indentation
2617        // is preserved when it doesn't threaten fence pairing.
2618        assert_idempotent("1. Item\n\n  ```\n    deeply indented code\n  ```\n");
2619    }
2620
2621    #[test]
2622    fn fence_fix_promotes_interior_below_scope_in_single_pass() {
2623        // Concrete behavioral check, not just idempotency:
2624        // interior at col 0 with opener at col 2, required 3, must land
2625        // at col 3 (same as opener) so fence pairing is preserved.
2626        let content = "1. Item\n\n  ```\ncode\n  ```\n";
2627        let fixed = fix(content);
2628        assert_eq!(fixed, "1. Item\n\n   ```\n   code\n   ```\n");
2629    }
2630
2631    #[test]
2632    fn fence_fix_preserves_interior_above_required() {
2633        // Opener at col 2 → col 3 (required). Interior at col 4 stays at
2634        // col 4 (above required, no need to push it).
2635        let content = "1. Item\n\n  ```\n    code\n  ```\n";
2636        let fixed = fix(content);
2637        assert_eq!(fixed, "1. Item\n\n   ```\n    code\n   ```\n");
2638    }
2639
2640    // ── Non-task idempotency: MkDocs strict-indent ───────────────────
2641    //
2642    // Under MkDocs flavor, continuation requires max(content_col, 4),
2643    // which can force a fix even when CommonMark would accept the
2644    // content. Pin idempotency for the non-task path there too.
2645
2646    #[test]
2647    fn idempotent_non_task_mkdocs_ordered_at_3_spaces() {
2648        // CommonMark-valid (3 spaces) but MkDocs demands 4 → fix runs.
2649        assert_idempotent_mkdocs("1. Item\n\n   continuation\n");
2650    }
2651
2652    #[test]
2653    fn idempotent_non_task_mkdocs_unordered_at_2_spaces() {
2654        // "- Item" → content col 2, but MkDocs raises the floor to 4.
2655        assert_idempotent_mkdocs("- Item\n\n  continuation\n");
2656    }
2657
2658    #[test]
2659    fn idempotent_non_task_mkdocs_fence_compound() {
2660        // MkDocs non-task fence: opener/interior/closer shift together.
2661        assert_idempotent_mkdocs("1. Item\n\n   ```toml\n   k = 1\n   ```\n");
2662    }
2663
2664    // ── style = "aligned" ──────────────────────────────────────────────
2665
2666    #[test]
2667    fn aligned_tight_zero_indent_continuation_flagged() {
2668        // The core #682 case: a tight 0-indent lazy continuation is valid
2669        // CommonMark (and accepted by `any`), but `aligned` requires it to sit
2670        // at the content column.
2671        let content = "- this is a long line\nthat continues on a second line\n";
2672        let warnings = check_aligned(content);
2673        assert_eq!(warnings.len(), 1);
2674        assert_eq!(warnings[0].line, 2);
2675        assert_eq!(
2676            fix_aligned(content),
2677            "- this is a long line\n  that continues on a second line\n"
2678        );
2679    }
2680
2681    #[test]
2682    fn aligned_full_issue_example_made_consistent() {
2683        // The full #682 example: every continuation line is snapped to the
2684        // content column, producing the consistent result the reporter wants.
2685        let content = "- this is a long line\n\
2686                       that continues on a second line\n\
2687                       - this is another long line\n\
2688                       \x20\x20that continues on the next line\n\
2689                       - yet again a long line\n\
2690                       and still inconsistently spaced\n\
2691                       \x20\x20and even worse\n";
2692        let expected = "- this is a long line\n\
2693                        \x20\x20that continues on a second line\n\
2694                        - this is another long line\n\
2695                        \x20\x20that continues on the next line\n\
2696                        - yet again a long line\n\
2697                        \x20\x20and still inconsistently spaced\n\
2698                        \x20\x20and even worse\n";
2699        assert_eq!(fix_aligned(content), expected);
2700        // And the fix is a fixpoint.
2701        assert_eq!(fix_aligned(expected), expected);
2702    }
2703
2704    #[test]
2705    fn aligned_already_aligned_not_flagged() {
2706        let content = "- item\n  continuation at content column\n";
2707        assert!(check_aligned(content).is_empty());
2708    }
2709
2710    #[test]
2711    fn aligned_tight_partial_indent_flagged() {
2712        // 1 space under "- " (content col 2): tight partial under-indent.
2713        let content = "- item\n continuation\n";
2714        let warnings = check_aligned(content);
2715        assert_eq!(warnings.len(), 1);
2716        assert_eq!(fix_aligned(content), "- item\n  continuation\n");
2717    }
2718
2719    #[test]
2720    fn aligned_post_blank_zero_indent_still_new_paragraph() {
2721        // After a blank line, 0-indent content is a NEW paragraph that has left
2722        // the list - aligned mode must not reindent it back into the item.
2723        let content = "- item\n\nnew paragraph\n";
2724        assert!(check_aligned(content).is_empty());
2725        assert_eq!(fix_aligned(content), content);
2726    }
2727
2728    // ── aligned: structural blocks must NOT be pulled into the list ────
2729
2730    #[test]
2731    fn aligned_top_level_blockquote_after_list_untouched() {
2732        // A blockquote tight after a list item is a list-breaking separator,
2733        // not continuation. `in_list_block` is false for it, so aligned mode
2734        // must leave it alone (no reindent into the item).
2735        let content = "- item\n> quote\n";
2736        assert!(check_aligned(content).is_empty());
2737        assert_eq!(fix_aligned(content), content);
2738    }
2739
2740    #[test]
2741    fn aligned_top_level_fence_after_list_untouched() {
2742        let content = "- item\n```\ncode\n```\n";
2743        assert!(check_aligned(content).is_empty());
2744        assert_eq!(fix_aligned(content), content);
2745    }
2746
2747    #[test]
2748    fn aligned_top_level_table_after_list_untouched() {
2749        let content = "- item\n| a | b |\n|---|---|\n| 1 | 2 |\n";
2750        assert!(check_aligned(content).is_empty());
2751        assert_eq!(fix_aligned(content), content);
2752    }
2753
2754    // ── aligned: nested lists ──────────────────────────────────────────
2755
2756    #[test]
2757    fn aligned_nested_tight_lazy_continuation_aligns_to_inner() {
2758        // A tight lazy continuation after a nested item is, per CommonMark,
2759        // continuation of the innermost open item, so it aligns to the inner
2760        // item's content column (4), not the outer's (2). The outer item must
2761        // defer to the inner one.
2762        let content = "- Outer\n  - Inner\ncontinuation\n";
2763        let warnings = check_aligned(content);
2764        assert_eq!(warnings.len(), 1);
2765        assert_eq!(fix_aligned(content), "- Outer\n  - Inner\n    continuation\n");
2766    }
2767
2768    #[test]
2769    fn aligned_nested_continuation_already_aligned_not_flagged() {
2770        let content = "- L1\n  - L2\n    cont of L2 at 4\n";
2771        assert!(check_aligned(content).is_empty());
2772    }
2773
2774    #[test]
2775    fn aligned_nested_idempotent() {
2776        let content = "- Outer\n  - Inner\ncontinuation\n";
2777        let once = fix_aligned(content);
2778        assert_eq!(fix_aligned(&once), once);
2779    }
2780
2781    #[test]
2782    fn aligned_three_level_nesting_aligns_to_innermost() {
2783        // The saw_nested cascade defers through every level, so the tight lazy
2784        // line aligns to L3's content column (6), the innermost open item.
2785        let content = "- L1\n  - L2\n    - L3\ncont\n";
2786        assert_eq!(fix_aligned(content), "- L1\n  - L2\n    - L3\n      cont\n");
2787    }
2788
2789    #[test]
2790    fn aligned_continuation_after_sibling_owned_by_last_item() {
2791        // Tight lazy continuation after the second sibling belongs to that
2792        // sibling (no nesting), so it aligns to its content column (2).
2793        let content = "- a\n- b\nlazy\n";
2794        assert_eq!(fix_aligned(content), "- a\n- b\n  lazy\n");
2795    }
2796
2797    #[test]
2798    fn aligned_multi_digit_ordered_marker_aligns_to_content_column() {
2799        let content = "10. Item\nwrap\n";
2800        assert_eq!(fix_aligned(content), "10. Item\n    wrap\n");
2801    }
2802
2803    #[test]
2804    fn aligned_setext_heading_after_list_left_alone() {
2805        // A setext heading is not prose continuation; aligned must not reindent
2806        // it (the walk terminates on the heading), leaving the document intact.
2807        let content = "- item\nText\n===\n";
2808        assert!(check_aligned(content).is_empty());
2809        assert_eq!(fix_aligned(content), content);
2810    }
2811
2812    #[test]
2813    fn aligned_latent_marker_in_continuation_is_idempotent() {
2814        // Regression (fuzzer-found): a list-marker-looking line ("2. ") that the
2815        // parser absorbs as lazy continuation can be promoted to a real list
2816        // item once an earlier continuation line is reindented, re-attributing
2817        // later lines and breaking single-pass idempotency. Such items are not
2818        // reindented at all.
2819        let content = "# \n- \n``\n2. \n![]()";
2820        let once = fix_aligned(content);
2821        assert_eq!(fix_aligned(&once), once, "fix must be idempotent in one pass");
2822        assert_eq!(once, content, "item with a latent marker is left untouched");
2823    }
2824
2825    #[test]
2826    fn aligned_latent_table_in_continuation_is_idempotent() {
2827        // Regression (fuzzer-found): a table-looking line that the parser
2828        // absorbs as lazy continuation (so it is NOT yet `in_table_block`) can
2829        // be promoted to a real table once an earlier line is reindented. Like
2830        // a latent marker, this re-parses the block, so the item is left alone.
2831        let content = "- \n![`]()\n|  | ` |\n| --- | --- |";
2832        let once = fix_aligned(content);
2833        assert_eq!(fix_aligned(&once), once, "fix must be idempotent in one pass");
2834        assert_eq!(once, content, "item with a latent table is left untouched");
2835    }
2836
2837    #[test]
2838    fn aligned_blockquote_nested_list_not_touched() {
2839        // Lists inside blockquotes are a documented MD077 limitation (the scan
2840        // breaks at the blockquote prefix). Aligned inherits that conservative
2841        // no-false-positive behavior.
2842        let content = "> - item\n> wrap\n";
2843        assert!(check_aligned(content).is_empty());
2844        assert_eq!(fix_aligned(content), content);
2845    }
2846
2847    // ── aligned: GFM task list items ───────────────────────────────────
2848
2849    #[test]
2850    fn aligned_task_post_checkbox_column_accepted() {
2851        // Continuation aligned to the post-checkbox column (content_col + 4 = 6)
2852        // stays valid so aligned mode doesn't fight MD013 reflow.
2853        let content = "- [ ] Task\n      wrap\n";
2854        assert!(check_aligned(content).is_empty());
2855        assert_eq!(fix_aligned(content), content);
2856    }
2857
2858    #[test]
2859    fn aligned_task_under_indent_snaps_to_content_column() {
2860        let content = "- [ ] Task\nwrap\n";
2861        let warnings = check_aligned(content);
2862        assert_eq!(warnings.len(), 1);
2863        assert_eq!(fix_aligned(content), "- [ ] Task\n  wrap\n");
2864    }
2865
2866    // ── aligned: MkDocs flavor ─────────────────────────────────────────
2867
2868    #[test]
2869    fn aligned_mkdocs_tight_under_indent_snaps_to_four() {
2870        // MkDocs raises the required indent to max(content_col, 4) = 4 for "- ".
2871        let content = "- item\nwrap\n";
2872        let warnings = check_aligned_mkdocs(content);
2873        assert_eq!(warnings.len(), 1);
2874        let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
2875        assert_eq!(aligned_rule().fix(&ctx).unwrap(), "- item\n    wrap\n");
2876    }
2877
2878    // ── any (default) regression: tight lazy continuation untouched ────
2879
2880    #[test]
2881    fn any_default_does_not_flag_tight_lazy_continuation() {
2882        // The default style must preserve CommonMark lazy continuation.
2883        let content = "- item\nwrapped at zero indent\n";
2884        assert!(check(content).is_empty());
2885        assert_eq!(fix(content), content);
2886    }
2887
2888    #[test]
2889    fn from_config_aligned_enables_tight_flagging() {
2890        // End-to-end: `[MD077] style = "aligned"` wires through from_config.
2891        let mut config = crate::config::Config::default();
2892        let mut rule_config = crate::config::RuleConfig::default();
2893        rule_config
2894            .values
2895            .insert("style".to_string(), toml::Value::String("aligned".to_string()));
2896        config.rules.insert("MD077".to_string(), rule_config);
2897
2898        let rule = MD077ListContinuationIndent::from_config(&config);
2899        let ctx = LintContext::new("- item\nwrap\n", MarkdownFlavor::Standard, None);
2900        assert_eq!(rule.check(&ctx).unwrap().len(), 1);
2901    }
2902
2903    #[test]
2904    fn from_config_default_is_any() {
2905        // No config -> default `any` -> tight lazy continuation untouched.
2906        let config = crate::config::Config::default();
2907        let rule = MD077ListContinuationIndent::from_config(&config);
2908        let ctx = LintContext::new("- item\nwrap\n", MarkdownFlavor::Standard, None);
2909        assert!(rule.check(&ctx).unwrap().is_empty());
2910    }
2911
2912    #[test]
2913    fn from_config_indent_sets_fixed_requirement() {
2914        // End-to-end: `[MD077] indent = 4` wires through from_config and
2915        // requires continuation content to sit 4 spaces past the marker.
2916        let mut config = crate::config::Config::default();
2917        let mut rule_config = crate::config::RuleConfig::default();
2918        rule_config.values.insert("indent".to_string(), toml::Value::Integer(4));
2919        config.rules.insert("MD077".to_string(), rule_config);
2920
2921        let rule = MD077ListContinuationIndent::from_config(&config);
2922
2923        // "- item\n    wrap\n" -> continuation at 4 spaces: accepted.
2924        let ok_ctx = LintContext::new("- item\n    wrap\n", MarkdownFlavor::Standard, None);
2925        assert!(rule.check(&ok_ctx).unwrap().is_empty());
2926        assert_eq!(rule.fix(&ok_ctx).unwrap(), "- item\n    wrap\n");
2927
2928        // "- item\n\n  wrap\n" -> continuation at 2 spaces after a blank line:
2929        // flagged as under-indented (would escape the list item).
2930        let bad_ctx = LintContext::new("- item\n\n  wrap\n", MarkdownFlavor::Standard, None);
2931        let warnings = rule.check(&bad_ctx).unwrap();
2932        assert_eq!(warnings.len(), 1);
2933        assert!(warnings[0].message.contains("needs 4 spaces"));
2934    }
2935
2936    #[test]
2937    fn from_config_indent_applies_per_nested_marker() {
2938        // With a fixed indent, each item's requirement is its own marker
2939        // column plus the configured indent (nested item marker at 2 -> 6).
2940        let mut config = crate::config::Config::default();
2941        let mut rule_config = crate::config::RuleConfig::default();
2942        rule_config.values.insert("indent".to_string(), toml::Value::Integer(4));
2943        config.rules.insert("MD077".to_string(), rule_config);
2944
2945        let rule = MD077ListContinuationIndent::from_config(&config);
2946        let ctx = LintContext::new("- a\n  - b\n      wrap\n", MarkdownFlavor::Standard, None);
2947        let warnings = rule.check(&ctx).unwrap();
2948        assert!(
2949            warnings.is_empty(),
2950            "continuation at 6 spaces should pass: {warnings:?}"
2951        );
2952    }
2953
2954    /// A rule configured through the real `[MD077]` config path.
2955    fn rule_with(settings: &[(&str, toml::Value)]) -> Box<dyn Rule> {
2956        let mut config = crate::config::Config::default();
2957        let mut rule_config = crate::config::RuleConfig::default();
2958        for (key, value) in settings {
2959            rule_config.values.insert((*key).to_string(), value.clone());
2960        }
2961        config.rules.insert("MD077".to_string(), rule_config);
2962        MD077ListContinuationIndent::from_config(&config)
2963    }
2964
2965    #[test]
2966    fn configured_indent_cannot_lower_the_strict_flavor_minimum() {
2967        // The MkDocs 4-space minimum is what the renderer needs to read a line
2968        // as part of the item, so `indent = 2` may not pull it down to 2 - that
2969        // would have `fix` rewrite a rendering document into a broken one.
2970        let rule = rule_with(&[("indent", toml::Value::Integer(2))]);
2971
2972        let two = LintContext::new("- item\n\n  wrap\n", MarkdownFlavor::MkDocs, None);
2973        let warnings = rule.check(&two).unwrap();
2974        assert_eq!(warnings.len(), 1, "2 spaces is below the MkDocs minimum: {warnings:?}");
2975        assert!(
2976            warnings[0].message.contains("needs 4 spaces") && warnings[0].message.contains("MkDocs"),
2977            "the requirement comes from MkDocs, so the message must say so: {}",
2978            warnings[0].message
2979        );
2980        assert_eq!(rule.fix(&two).unwrap(), "- item\n\n    wrap\n");
2981
2982        // Control: a document already at the minimum is left alone.
2983        let four = LintContext::new("- item\n\n    wrap\n", MarkdownFlavor::MkDocs, None);
2984        assert!(rule.check(&four).unwrap().is_empty());
2985
2986        // Control: the clamp is scoped to the strict flavor. Under the standard
2987        // flavor the same setting means exactly what it says, and 4 is then an
2988        // over-indent to be snapped back to 2.
2989        let standard = LintContext::new("- item\n\n    wrap\n", MarkdownFlavor::Standard, None);
2990        assert_eq!(rule.check(&standard).unwrap().len(), 1);
2991        assert_eq!(rule.fix(&standard).unwrap(), "- item\n\n  wrap\n");
2992    }
2993
2994    #[test]
2995    fn configured_indent_can_raise_the_strict_flavor_minimum() {
2996        // The clamp is a floor, not a fixed value: above 4 the configured indent
2997        // still governs under the MkDocs flavor.
2998        let rule = rule_with(&[("indent", toml::Value::Integer(6))]);
2999        let ctx = LintContext::new("- item\n\n    wrap\n", MarkdownFlavor::MkDocs, None);
3000        let warnings = rule.check(&ctx).unwrap();
3001        assert_eq!(warnings.len(), 1);
3002        assert!(
3003            warnings[0].message.contains("needs 6 spaces"),
3004            "configured 6 must win over the 4-space floor: {}",
3005            warnings[0].message
3006        );
3007        assert_eq!(rule.fix(&ctx).unwrap(), "- item\n\n      wrap\n");
3008    }
3009
3010    #[test]
3011    fn configured_indent_message_does_not_claim_a_structural_consequence() {
3012        // Two spaces under a `- ` marker keeps the content in the list item, so
3013        // a message blaming list membership would be false. The requirement is
3014        // the configured one and the message has to say which.
3015        let rule = rule_with(&[("indent", toml::Value::Integer(4))]);
3016        let ctx = LintContext::new("- item\n\n  wrap\n", MarkdownFlavor::Standard, None);
3017        let warnings = rule.check(&ctx).unwrap();
3018        assert_eq!(warnings.len(), 1);
3019        assert!(
3020            warnings[0].message.contains("match the configured indent"),
3021            "expected the configured-indent wording, got: {}",
3022            warnings[0].message
3023        );
3024        assert!(
3025            !warnings[0].message.contains("remain part of the list"),
3026            "the content does remain part of the list here: {}",
3027            warnings[0].message
3028        );
3029
3030        // Control: the default rule reports the same document as clean, which is
3031        // what makes the structural claim wrong above.
3032        assert!(check("- item\n\n  wrap\n").is_empty());
3033
3034        // Control: content that really would escape the item still gets the
3035        // structural message, so the wording was narrowed and not replaced.
3036        let escaping = check("- item\n\n wrap\n");
3037        assert_eq!(escaping.len(), 1);
3038        assert!(
3039            escaping[0].message.contains("remain part of the list"),
3040            "unconfigured under-indent keeps its structural message, got: {}",
3041            escaping[0].message
3042        );
3043    }
3044
3045    #[test]
3046    fn configured_indent_leaves_tight_lazy_continuation_to_style() {
3047        // `indent` sets what the requirement is; `style` decides which lines are
3048        // measured against it. A tight continuation is CommonMark lazy
3049        // continuation, so `any` accepts it however the requirement was derived.
3050        let any = rule_with(&[("indent", toml::Value::Integer(4))]);
3051        let ctx = LintContext::new("- item\n  wrap\n", MarkdownFlavor::Standard, None);
3052        assert!(
3053            any.check(&ctx).unwrap().is_empty(),
3054            "style = any accepts tight lazy continuation"
3055        );
3056
3057        let aligned = rule_with(&[
3058            ("indent", toml::Value::Integer(4)),
3059            ("style", toml::Value::String("aligned".to_string())),
3060        ]);
3061        let warnings = aligned.check(&ctx).unwrap();
3062        assert_eq!(warnings.len(), 1, "style = aligned raises it: {warnings:?}");
3063        assert!(warnings[0].message.contains("expected 4"));
3064        assert_eq!(aligned.fix(&ctx).unwrap(), "- item\n    wrap\n");
3065    }
3066
3067    #[test]
3068    fn aligned_tight_underindented_fence_inside_item_left_alone() {
3069        // A fenced block is a structural construct; aligned mode does not
3070        // reindent it (the `in_code_block` guard), so a tight under-indented
3071        // fence is a no-op rather than a risky delimiter-only rewrite.
3072        let content = "- item\n ```\n code\n ```\n";
3073        assert!(check_aligned(content).is_empty());
3074        assert_eq!(fix_aligned(content), content);
3075    }
3076
3077    #[test]
3078    fn aligned_task_under_indent_fix_is_idempotent() {
3079        let content = "- [ ] Task\nwrap\n";
3080        let once = fix_aligned(content);
3081        assert_eq!(fix_aligned(&once), once);
3082    }
3083
3084    #[test]
3085    fn aligned_partial_indent_fix_is_idempotent() {
3086        let content = "- item\n continuation\n";
3087        let once = fix_aligned(content);
3088        assert_eq!(fix_aligned(&once), once);
3089    }
3090}