Skip to main content

rumdl_lib/rules/
md013_line_length.rs

1/// Rule MD013: Line length
2///
3/// See [docs/md013.md](../../docs/md013.md) for full documentation, configuration, and examples.
4use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use crate::rule_config_serde::RuleConfig;
6use crate::utils::mkdocs_admonitions;
7use crate::utils::mkdocs_attr_list::is_standalone_attr_list;
8use crate::utils::mkdocs_snippets::is_snippet_block_delimiter;
9use crate::utils::mkdocs_tabs;
10use crate::utils::range_utils::LineIndex;
11use crate::utils::range_utils::calculate_excess_range;
12use crate::utils::regex_cache::{IMAGE_REF_PATTERN, LINK_REF_PATTERN, URL_PATTERN};
13use crate::utils::table_utils::TableUtils;
14use crate::utils::text_reflow::{
15    BlockquoteLineData, blockquote_continuation_style, dominant_blockquote_prefix, reflow_blockquote_content,
16    split_into_sentences,
17};
18use pulldown_cmark::LinkType;
19use toml;
20
21mod block_builder;
22mod helpers;
23pub mod md013_config;
24use crate::rules::md030_list_marker_space::MD030Config;
25use crate::utils::is_template_directive_only;
26use block_builder::{Block, BlockBuilder};
27use helpers::{
28    extract_list_marker_and_content, has_hard_break, is_github_alert_marker, is_horizontal_rule, is_html_only_line,
29    is_list_item, is_standalone_link_or_image_line, is_unwrappable_line, source_list_marker, split_into_segments,
30    trim_preserving_hard_break,
31};
32pub use md013_config::MD013Config;
33use md013_config::{LengthMode, ReflowMode};
34
35#[cfg(test)]
36mod tests;
37use unicode_width::UnicodeWidthStr;
38
39#[derive(Clone, Default)]
40pub struct MD013LineLength {
41    pub(crate) config: MD013Config,
42    /// MD030 list-marker spacing, applied when reflowing list items so the rewrite
43    /// uses the configured post-marker spacing rather than a hard-coded single
44    /// space. Defaults to MD030's defaults (a single space everywhere), which
45    /// reproduces the previous behaviour exactly. See [`MD030Config::expected_spaces`].
46    pub(crate) list_spacing: MD030Config,
47}
48
49/// Blockquote paragraph line collected for reflow, with original line index for range computation.
50struct CollectedBlockquoteLine {
51    line_idx: usize,
52    data: BlockquoteLineData,
53}
54
55impl MD013LineLength {
56    pub fn new(line_length: usize, code_blocks: bool, tables: bool, headings: bool, strict: bool) -> Self {
57        Self {
58            config: MD013Config {
59                line_length: crate::types::LineLength::new(line_length),
60                code_blocks,
61                code_spans: true,
62                tables,
63                headings,
64                paragraphs: true,  // Default to true for backwards compatibility
65                blockquotes: true, // Default to true for backwards compatibility
66                strict,
67                stern: false,
68                heading_line_length: None,
69                code_block_line_length: None,
70                reflow: false,
71                reflow_mode: ReflowMode::default(),
72                length_mode: LengthMode::default(),
73                abbreviations: Vec::new(),
74                require_sentence_capital: true,
75                ignore_link_urls: true,
76                atomic_spans: true,
77            },
78            list_spacing: MD030Config::default(),
79        }
80    }
81
82    pub fn from_config_struct(config: MD013Config) -> Self {
83        Self {
84            config,
85            list_spacing: MD030Config::default(),
86        }
87    }
88
89    /// Return a clone with code block checking disabled.
90    /// Used for doc comment linting where code blocks are Rust code managed by rustfmt.
91    pub fn with_code_blocks_disabled(&self) -> Self {
92        let mut clone = self.clone();
93        clone.config.code_blocks = false;
94        clone
95    }
96
97    /// Convert MD013 LengthMode to text_reflow ReflowLengthMode
98    /// Normalized set of reference labels defined in the document.
99    ///
100    /// Passed to reflow so a bare shortcut reference (`[text]`) is treated as an
101    /// atomic link only when its label is actually defined; an undefined
102    /// bracketed run reflows as literal prose.
103    fn defined_reference_labels(ctx: &crate::lint_context::LintContext) -> std::collections::HashSet<String> {
104        ctx.reference_defs
105            .iter()
106            .map(|d| crate::utils::text_reflow::normalize_reference_label(&d.id))
107            .collect()
108    }
109
110    /// Build the reflow options shared by every MD013 fix path.
111    ///
112    /// `line_length` varies per call site (some subtract a list-marker or
113    /// blockquote prefix); every other field is derived uniformly from the
114    /// effective config and the document flavor. Callers that need a different
115    /// `max_list_continuation_indent` override it via struct update.
116    fn reflow_options(
117        ctx: &crate::lint_context::LintContext,
118        config: &MD013Config,
119        line_length: usize,
120    ) -> crate::utils::text_reflow::ReflowOptions {
121        crate::utils::text_reflow::ReflowOptions {
122            line_length,
123            break_on_sentences: true,
124            preserve_breaks: false,
125            sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
126            semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
127            abbreviations: config.abbreviations_for_reflow(),
128            length_mode: config.reflow_length_mode(),
129            attr_lists: ctx.flavor.supports_attr_lists(),
130            myst_roles: ctx.flavor.supports_myst_roles(),
131            require_sentence_capital: config.require_sentence_capital,
132            max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
133                Some(4)
134            } else {
135                None
136            },
137            defined_references: Some(Self::defined_reference_labels(ctx)),
138            atomic_spans: config.atomic_spans,
139        }
140    }
141
142    fn should_ignore_line(
143        &self,
144        line: &str,
145        _lines: &[&str],
146        current_line: usize,
147        ctx: &crate::lint_context::LintContext,
148    ) -> bool {
149        if self.config.strict {
150            return false;
151        }
152
153        // Quick check for common patterns before expensive regex
154        let trimmed = line.trim();
155
156        // Only skip if the entire line is a URL (quick check first)
157        if (trimmed.starts_with("http://") || trimmed.starts_with("https://")) && URL_PATTERN.is_match(trimmed) {
158            return true;
159        }
160
161        // Only skip if the entire line is an image reference (quick check first)
162        if trimmed.starts_with("![") && trimmed.ends_with(']') && IMAGE_REF_PATTERN.is_match(trimmed) {
163            return true;
164        }
165
166        // Note: link reference definitions are handled as always-exempt (even in strict mode)
167        // in the main check loop, so they don't need to be checked here.
168
169        // Code blocks with long strings (only check if in code block)
170        if ctx.line_info(current_line + 1).is_some_and(|info| info.in_code_block)
171            && !trimmed.is_empty()
172            && !line.contains(' ')
173            && !line.contains('\t')
174        {
175            return true;
176        }
177
178        false
179    }
180
181    /// Check if rule should skip based on provided config (used for inline config support)
182    fn should_skip_with_config(&self, ctx: &crate::lint_context::LintContext, config: &MD013Config) -> bool {
183        // Skip if content is empty
184        if ctx.content.is_empty() {
185            return true;
186        }
187
188        // For sentence-per-line, semantic-line-breaks, or normalize mode, never skip based on line length
189        if config.reflow
190            && (config.reflow_mode == ReflowMode::SentencePerLine
191                || config.reflow_mode == ReflowMode::SemanticLineBreaks
192                || config.reflow_mode == ReflowMode::Normalize)
193        {
194            return false;
195        }
196
197        // Use the smallest applicable budget across line/heading/code-block
198        // contexts so a stricter context-specific limit doesn't get masked by
199        // the document-wide budget.
200        let min_limit = config.min_effective_line_length();
201        if min_limit.is_unlimited() {
202            return true;
203        }
204        let min_limit_bytes = min_limit.get();
205
206        // Quick check: if total content is shorter than the smallest line limit,
207        // definitely skip.
208        if ctx.content.len() <= min_limit_bytes {
209            return true;
210        }
211
212        // Skip if no line exceeds the smallest applicable limit.
213        !ctx.lines.iter().any(|line| line.byte_len > min_limit_bytes)
214    }
215
216    fn normalize_mode_needs_reflow<'a, I>(&self, lines: I, config: &MD013Config) -> bool
217    where
218        I: IntoIterator<Item = &'a str>,
219    {
220        let mut line_count = 0;
221        let check_length = !config.line_length.is_unlimited();
222
223        for line in lines {
224            line_count += 1;
225            if check_length && self.calculate_effective_length(line) > config.line_length.get() {
226                return true;
227            }
228        }
229
230        line_count > 1
231    }
232}
233
234impl Rule for MD013LineLength {
235    fn name(&self) -> &'static str {
236        "MD013"
237    }
238
239    fn description(&self) -> &'static str {
240        "Line length should not be excessive"
241    }
242
243    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
244        // Use pre-parsed inline config from LintContext
245        let config_override = ctx.inline_config().get_rule_config("MD013");
246
247        // Apply configuration override if present
248        let effective_config = if let Some(json_config) = config_override {
249            if let Some(obj) = json_config.as_object() {
250                let mut config = self.config.clone();
251                if let Some(line_length) = obj.get("line_length").and_then(serde_json::Value::as_u64) {
252                    config.line_length = crate::types::LineLength::new(line_length as usize);
253                }
254                if let Some(code_blocks) = obj.get("code_blocks").and_then(serde_json::Value::as_bool) {
255                    config.code_blocks = code_blocks;
256                }
257                if let Some(code_spans) = obj.get("code_spans").and_then(serde_json::Value::as_bool) {
258                    config.code_spans = code_spans;
259                }
260                if let Some(tables) = obj.get("tables").and_then(serde_json::Value::as_bool) {
261                    config.tables = tables;
262                }
263                if let Some(headings) = obj.get("headings").and_then(serde_json::Value::as_bool) {
264                    config.headings = headings;
265                }
266                if let Some(blockquotes) = obj.get("blockquotes").and_then(serde_json::Value::as_bool) {
267                    config.blockquotes = blockquotes;
268                }
269                if let Some(strict) = obj.get("strict").and_then(serde_json::Value::as_bool) {
270                    config.strict = strict;
271                }
272                if let Some(stern) = obj.get("stern").and_then(serde_json::Value::as_bool) {
273                    config.stern = stern;
274                }
275                if let Some(v) = obj
276                    .get("ignore_link_urls")
277                    .or_else(|| obj.get("ignore-link-urls"))
278                    .or_else(|| obj.get("semantic_link_understanding"))
279                    .or_else(|| obj.get("semantic-link-understanding"))
280                    .and_then(serde_json::Value::as_bool)
281                {
282                    config.ignore_link_urls = v;
283                }
284                if let Some(reflow) = obj.get("reflow").and_then(serde_json::Value::as_bool) {
285                    config.reflow = reflow;
286                }
287                if let Some(reflow_mode) = obj.get("reflow_mode").and_then(|v| v.as_str()) {
288                    config.reflow_mode = match reflow_mode {
289                        "default" => ReflowMode::Default,
290                        "normalize" => ReflowMode::Normalize,
291                        "sentence-per-line" => ReflowMode::SentencePerLine,
292                        "semantic-line-breaks" => ReflowMode::SemanticLineBreaks,
293                        _ => ReflowMode::default(),
294                    };
295                }
296                config
297            } else {
298                self.config.clone()
299            }
300        } else {
301            self.config.clone()
302        };
303
304        // Fast early return using should_skip with EFFECTIVE config (after inline overrides)
305        // But don't skip if we're in reflow mode with Normalize or SentencePerLine
306        if self.should_skip_with_config(ctx, &effective_config)
307            && !(effective_config.reflow
308                && (effective_config.reflow_mode == ReflowMode::Normalize
309                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
310                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
311        {
312            return Ok(Vec::new());
313        }
314
315        // Direct implementation without DocumentStructure
316        let mut warnings = Vec::new();
317
318        // Special handling: line_length = 0 means "no line length limit"
319        // Skip all line length checks, but still allow reflow if enabled
320        let skip_length_checks = effective_config.line_length.is_unlimited();
321
322        // Pre-filter lines that could be problematic to avoid processing all lines.
323        // Use the smallest applicable budget across line/heading/code-block contexts
324        // so candidates aren't dropped when a stricter context-specific budget applies.
325        let prefilter_limit = effective_config.min_effective_line_length();
326        let prefilter_skip = prefilter_limit.is_unlimited();
327        let mut candidate_lines = Vec::new();
328        if !skip_length_checks && !prefilter_skip {
329            for (line_idx, line_info) in ctx.lines.iter().enumerate() {
330                // Skip front matter - it should never be linted
331                if line_info.in_front_matter {
332                    continue;
333                }
334
335                // Quick length check first
336                if line_info.byte_len > prefilter_limit.get() {
337                    candidate_lines.push(line_idx);
338                }
339            }
340        }
341
342        // If no candidate lines and not in normalize or sentence-per-line mode, early return
343        if candidate_lines.is_empty()
344            && !(effective_config.reflow
345                && (effective_config.reflow_mode == ReflowMode::Normalize
346                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
347                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
348        {
349            return Ok(warnings);
350        }
351
352        let lines = ctx.raw_lines();
353
354        // Whether a 1-indexed line is a heading. `LineInfo::heading` is an O(1)
355        // per-line field, so check it directly at each use site instead of
356        // materializing a full-document HashSet (an extra O(n) pass and
357        // allocation on a rule that runs on virtually every file).
358        let is_heading_line_num = |line_number: usize| -> bool {
359            line_number
360                .checked_sub(1)
361                .and_then(|idx| ctx.lines.get(idx))
362                .is_some_and(|line| line.heading.is_some())
363        };
364
365        // Use pre-computed table blocks from context
366        // We need this for both the table skip check AND the paragraphs check
367        let table_blocks = &ctx.table_blocks;
368        let mut table_lines_set = std::collections::HashSet::new();
369        for table in table_blocks {
370            table_lines_set.insert(table.header_line + 1);
371            table_lines_set.insert(table.delimiter_line + 1);
372            for &line in &table.content_lines {
373                table_lines_set.insert(line + 1);
374            }
375        }
376
377        // Process candidate lines for line length checks
378        'line_loop: for &line_idx in &candidate_lines {
379            let line_number = line_idx + 1;
380            let line = lines[line_idx];
381
382            // Calculate actual line length (used in warning messages)
383            let effective_length = self.calculate_effective_length(line);
384
385            // Pick the context-specific limit: heading > code-block > paragraph.
386            // Headings dominate over code-block context if a setext underline ever
387            // overlaps a fenced range (defensive — these are mutually exclusive in
388            // practice, but the explicit ordering documents intent).
389            let is_heading_line = is_heading_line_num(line_number);
390            let in_code_block = ctx.line_info(line_number).is_some_and(|info| info.in_code_block);
391            let line_limit = if is_heading_line {
392                effective_config.effective_heading_line_length().get()
393            } else if in_code_block {
394                effective_config.effective_code_block_line_length().get()
395            } else {
396                effective_config.line_length.get()
397            };
398
399            // A context-specific limit of 0 means "unlimited for this context".
400            if line_limit == 0 {
401                continue;
402            }
403
404            // Stern mode: like default, but the trailing-token forgiveness is
405            // disabled — a line with whitespace that exceeds the limit is a
406            // violation even if the excess is the final token. The "unwrappable"
407            // line exemption (single token, optionally prefixed by # or >) is
408            // still honored. Strict overrides stern entirely.
409            if effective_config.stern && !effective_config.strict && is_unwrappable_line(line) {
410                continue;
411            }
412
413            // Trailing-token forgiveness: only in default mode (not strict, not stern).
414            // If the line only exceeds the limit because of a long token at the end
415            // (URL, link chain, identifier), it passes. This matches markdownlint's
416            // behavior: line.replace(/\S*$/u, "#")
417            let check_length = if effective_config.strict || effective_config.stern {
418                effective_length
419            } else {
420                match line.rfind(char::is_whitespace) {
421                    Some(pos) => {
422                        let ws_char = line[pos..].chars().next().unwrap();
423                        let prefix_end = pos + ws_char.len_utf8();
424                        self.calculate_string_length(&line[..prefix_end]) + 1
425                    }
426                    None => 1, // No whitespace — entire line is a single token
427                }
428            };
429
430            // Skip lines where the check length is within the limit
431            if check_length <= line_limit {
432                continue;
433            }
434
435            // Ignore inline link/image URLs: suppress when excess comes entirely from inline URLs.
436            // Disabled by `strict` (all forgiveness off) and by `ignore_link_urls = false`
437            // (count link/image URLs toward the line length so such lines are flagged).
438            if !effective_config.strict && effective_config.ignore_link_urls {
439                let length_without_urls = self.length_without_inline_link_urls(effective_length, line_number, ctx);
440                if length_without_urls <= line_limit {
441                    continue;
442                }
443            }
444
445            // Inline code spans cannot be wrapped, so reflow cannot shorten a line
446            // whose excess length is one. When code-span checking is disabled,
447            // suppress a violation that would fit once inline code spans are excluded.
448            if !effective_config.code_spans {
449                let code_span_width: usize = ctx
450                    .code_spans()
451                    .iter()
452                    .filter(|span| span.line == line_number && span.end_line == line_number)
453                    .map(|span| self.calculate_string_length(&ctx.content[span.byte_offset..span.byte_end]))
454                    .sum();
455                if effective_length.saturating_sub(code_span_width) <= line_limit {
456                    continue;
457                }
458            }
459
460            // Skip mkdocstrings and pymdown blocks (already handled by LintContext)
461            if ctx.lines[line_idx].in_mkdocstrings || ctx.lines[line_idx].in_pymdown_block {
462                continue;
463            }
464
465            // Skip MyST comments (% comment) — structural lines, not prose
466            if ctx.lines[line_idx].is_myst_comment {
467                continue;
468            }
469
470            // Link reference definitions are always exempt, even in strict mode.
471            // There's no way to shorten them without breaking the URL.
472            // Also check after stripping list markers, since list items may
473            // contain link ref defs as their content.
474            {
475                let trimmed = line.trim();
476                if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
477                    continue;
478                }
479                if is_list_item(trimmed) {
480                    let (_, content) = extract_list_marker_and_content(trimmed);
481                    let content_trimmed = content.trim();
482                    if content_trimmed.starts_with('[')
483                        && content_trimmed.contains("]:")
484                        && LINK_REF_PATTERN.is_match(content_trimmed)
485                    {
486                        continue;
487                    }
488                }
489            }
490
491            // Skip various block types efficiently
492            if !effective_config.strict {
493                // Lines whose only content is a link/image are exempt.
494                // After stripping list markers, blockquote markers, and emphasis,
495                // if only a link or image remains, there is no way to shorten it.
496                if is_standalone_link_or_image_line(line) {
497                    continue;
498                }
499
500                // Lines consisting entirely of HTML tags are exempt.
501                // Badge lines, images with attributes, and similar inline HTML
502                // are long due to URLs in attributes and can't be meaningfully shortened.
503                if is_html_only_line(line) {
504                    continue;
505                }
506
507                // Skip setext heading underlines
508                if !line.trim().is_empty() && line.trim().chars().all(|c| c == '=' || c == '-') {
509                    continue;
510                }
511
512                // Skip block elements according to config flags
513                // The flags mean: true = check these elements, false = skip these elements
514                // So we skip when the flag is FALSE and the line is in that element type
515                if (!effective_config.headings && is_heading_line_num(line_number))
516                    || (!effective_config.code_blocks
517                        && ctx.line_info(line_number).is_some_and(|info| info.in_code_block))
518                    || (!effective_config.tables && table_lines_set.contains(&line_number))
519                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
520                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
521                    || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
522                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
523                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
524                    || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
525                    || ctx.line_info(line_number).is_some_and(|info| info.in_pymdown_block)
526                {
527                    continue;
528                }
529
530                // Check if this is a paragraph/regular text line
531                // If paragraphs = false, skip lines that are NOT in special blocks
532                // Blockquote content is treated as paragraph text, so it's not
533                // included in the special blocks list here.
534                if !effective_config.paragraphs {
535                    let is_special_block = is_heading_line_num(line_number)
536                        || ctx.line_info(line_number).is_some_and(|info| info.in_code_block)
537                        || table_lines_set.contains(&line_number)
538                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
539                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
540                        || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
541                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
542                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
543                        || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
544                        || ctx
545                            .line_info(line_number)
546                            .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container);
547
548                    // Skip regular paragraph text when paragraphs = false
549                    if !is_special_block {
550                        continue;
551                    }
552                }
553
554                // Skip blockquote lines when blockquotes = false.
555                // Also skip lazy continuation lines that belong to a blockquote
556                // (lines without `>` prefix that follow a blockquote line).
557                if !effective_config.blockquotes {
558                    if ctx.lines[line_number - 1].blockquote.is_some() {
559                        continue;
560                    }
561                    // Check for lazy continuation: scan backwards through
562                    // non-blank lines to find if this paragraph started with
563                    // a blockquote marker
564                    if !line.trim().is_empty() {
565                        let mut scan = line_number.saturating_sub(2);
566                        loop {
567                            if ctx.lines[scan].blockquote.is_some() {
568                                // Found a blockquote ancestor — this is a lazy continuation
569                                continue 'line_loop;
570                            }
571                            if lines[scan].trim().is_empty() || scan == 0 {
572                                break;
573                            }
574                            scan -= 1;
575                        }
576                    }
577                }
578
579                // Skip lines that are only a URL, image ref, or link ref
580                if self.should_ignore_line(line, lines, line_idx, ctx) {
581                    continue;
582                }
583            }
584
585            // In sentence-per-line mode, check if this is a single long sentence
586            // If so, emit a warning without a fix (user must manually rephrase)
587            if effective_config.reflow_mode == ReflowMode::SentencePerLine {
588                let sentences = split_into_sentences(line.trim());
589                if sentences.len() == 1 {
590                    // Single sentence that's too long - warn but don't auto-fix
591                    let message = format!("Line length {effective_length} exceeds {line_limit} characters");
592
593                    let (start_line, start_col, end_line, end_col) =
594                        calculate_excess_range(line_number, line, line_limit);
595
596                    warnings.push(LintWarning {
597                        rule_name: Some(self.name().to_string()),
598                        message,
599                        line: start_line,
600                        column: start_col,
601                        end_line,
602                        end_column: end_col,
603                        severity: Severity::Warning,
604                        fix: None, // No auto-fix for long single sentences
605                    });
606                    continue;
607                }
608                // Multiple sentences will be handled by paragraph-based reflow
609                continue;
610            }
611
612            // In semantic-line-breaks mode, skip per-line checks —
613            // all reflow is handled at the paragraph level with cascading splits
614            if effective_config.reflow_mode == ReflowMode::SemanticLineBreaks {
615                continue;
616            }
617
618            // Don't provide fix for individual lines when reflow is enabled
619            // Paragraph-based fixes will be handled separately
620            let fix = None;
621
622            let message = format!("Line length {effective_length} exceeds {line_limit} characters");
623
624            // Calculate precise character range for the excess portion
625            let (start_line, start_col, end_line, end_col) = calculate_excess_range(line_number, line, line_limit);
626
627            warnings.push(LintWarning {
628                rule_name: Some(self.name().to_string()),
629                message,
630                line: start_line,
631                column: start_col,
632                end_line,
633                end_column: end_col,
634                severity: Severity::Warning,
635                fix,
636            });
637        }
638
639        // If reflow is enabled, generate paragraph-based fixes
640        if effective_config.reflow {
641            let paragraph_warnings = self.generate_paragraph_fixes(ctx, &effective_config, lines);
642            // Merge paragraph warnings with line warnings, removing duplicates
643            for pw in paragraph_warnings {
644                // Remove any line warnings that overlap with this paragraph
645                warnings.retain(|w| w.line < pw.line || w.line > pw.end_line);
646                warnings.push(pw);
647            }
648        }
649
650        Ok(warnings)
651    }
652
653    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
654        // For CLI usage, apply fixes from warnings
655        // LSP will use the warning-based fixes directly
656        let warnings = self.check(ctx)?;
657        let warnings =
658            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
659
660        // If there are no fixes, return content unchanged
661        if !warnings.iter().any(|w| w.fix.is_some()) {
662            return Ok(ctx.content.to_string());
663        }
664
665        // Apply warning-based fixes
666        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
667            .map_err(|e| LintError::FixFailed(format!("Failed to apply fixes: {e}")))
668    }
669
670    fn as_any(&self) -> &dyn std::any::Any {
671        self
672    }
673
674    fn category(&self) -> RuleCategory {
675        RuleCategory::Whitespace
676    }
677
678    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
679        self.should_skip_with_config(ctx, &self.config)
680    }
681
682    fn default_config_section(&self) -> Option<(String, toml::Value)> {
683        let table = crate::rule_config_serde::config_schema_table(&MD013Config::default())?;
684        if table.is_empty() {
685            None
686        } else {
687            Some((MD013Config::RULE_NAME.to_string(), toml::Value::Table(table)))
688        }
689    }
690
691    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
692        let mut aliases = std::collections::HashMap::new();
693        aliases.insert("enable_reflow".to_string(), "reflow".to_string());
694        aliases.insert("strict_sentences".to_string(), "require-sentence-capital".to_string());
695        aliases.insert("strict-sentences".to_string(), "require-sentence-capital".to_string());
696        Some(aliases)
697    }
698
699    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
700    where
701        Self: Sized,
702    {
703        let mut rule_config = crate::rule_config_serde::load_rule_config::<MD013Config>(config);
704        // Use global line_length if rule-specific config still has default value
705        if rule_config.line_length.get() == 80 {
706            rule_config.line_length = config.global.line_length;
707        }
708        let mut rule = Self::from_config_struct(rule_config);
709        // Pull list-marker spacing from MD030 (via the shared serde config loader)
710        // so reflow rewrites list items with the configured spacing rather than a
711        // hard-coded single space.
712        rule.list_spacing = crate::rule_config_serde::load_rule_config::<MD030Config>(config);
713        Box::new(rule)
714    }
715}
716
717impl MD013LineLength {
718    /// True when `line_num` (1-based) sits inside a structure whose lines must be
719    /// preserved verbatim (code block, front matter, HTML/JSX/MDX block, MkDocs
720    /// container, div marker, ...). Used to keep blockquote reflow from touching
721    /// quoted-looking text embedded in such structures.
722    fn line_in_verbatim_context(&self, line_num: usize, ctx: &crate::lint_context::LintContext) -> bool {
723        ctx.line_info(line_num).is_some_and(|info| {
724            info.in_code_block
725                || info.in_front_matter
726                || info.in_html_block
727                || info.in_html_comment
728                || info.in_esm_block
729                || info.in_jsx_expression
730                || info.in_jsx_block
731                || info.in_mdx_comment
732                || info.in_mkdocstrings
733                || info.in_pymdown_block
734                || info.in_mkdocs_container()
735                || info.is_div_marker
736        })
737    }
738
739    fn is_blockquote_content_boundary(
740        &self,
741        content: &str,
742        line_num: usize,
743        ctx: &crate::lint_context::LintContext,
744        strict: bool,
745    ) -> bool {
746        let trimmed = content.trim();
747
748        trimmed.is_empty()
749            || self.line_in_verbatim_context(line_num, ctx)
750            || trimmed.starts_with('#')
751            || trimmed.starts_with("```")
752            || trimmed.starts_with("~~~")
753            || trimmed.starts_with('>')
754            || TableUtils::is_potential_table_row(content)
755            || is_list_item(trimmed)
756            || is_horizontal_rule(content)
757            || (trimmed.starts_with('[') && content.contains("]:"))
758            || is_template_directive_only(content)
759            || is_standalone_attr_list(content)
760            || is_snippet_block_delimiter(content)
761            || is_github_alert_marker(trimmed)
762            || is_html_only_line(content)
763            // A standalone link/image line is exempt from MD013 (non-strict mode),
764            // so it must end the blockquote paragraph rather than be absorbed into
765            // it, mirroring the top-level paragraph reflow boundary.
766            || (!strict && is_standalone_link_or_image_line(content))
767    }
768
769    #[allow(clippy::too_many_arguments)]
770    fn generate_blockquote_paragraph_fix(
771        &self,
772        ctx: &crate::lint_context::LintContext,
773        config: &MD013Config,
774        lines: &[&str],
775        line_index: &LineIndex,
776        start_idx: usize,
777        line_ending: &str,
778        // Extra indent (spaces) to prepend to the emitted `>` prefix so a blockquote
779        // nested in a list item moves with its parent's widened marker. Zero unless a
780        // non-default MD030 widened an ancestor list item.
781        ancestor_shift: isize,
782    ) -> (Option<LintWarning>, usize) {
783        let Some(start_bq) = ctx.lines.get(start_idx).and_then(|line| line.blockquote.as_deref()) else {
784            return (None, start_idx + 1);
785        };
786        let target_level = start_bq.nesting_level;
787
788        let mut collected: Vec<CollectedBlockquoteLine> = Vec::new();
789        let mut i = start_idx;
790
791        while i < lines.len() {
792            if !collected.is_empty() && has_hard_break(&collected[collected.len() - 1].data.content) {
793                break;
794            }
795
796            let line_num = i + 1;
797            if line_num > ctx.lines.len() {
798                break;
799            }
800
801            if lines[i].trim().is_empty() {
802                break;
803            }
804
805            let line_bq = ctx.lines[i].blockquote.as_deref();
806            if let Some(bq) = line_bq {
807                if bq.nesting_level != target_level {
808                    break;
809                }
810
811                if self.is_blockquote_content_boundary(&bq.content, line_num, ctx, config.strict) {
812                    break;
813                }
814
815                collected.push(CollectedBlockquoteLine {
816                    line_idx: i,
817                    data: BlockquoteLineData::explicit(trim_preserving_hard_break(&bq.content), bq.prefix.clone()),
818                });
819                i += 1;
820                continue;
821            }
822
823            let lazy_content = lines[i].trim_start();
824            if self.is_blockquote_content_boundary(lazy_content, line_num, ctx, config.strict) {
825                break;
826            }
827
828            collected.push(CollectedBlockquoteLine {
829                line_idx: i,
830                data: BlockquoteLineData::lazy(trim_preserving_hard_break(lazy_content)),
831            });
832            i += 1;
833        }
834
835        if collected.is_empty() {
836            return (None, start_idx + 1);
837        }
838
839        let next_idx = i;
840        let paragraph_start = collected[0].line_idx;
841        let end_line = collected[collected.len() - 1].line_idx;
842        let line_data: Vec<BlockquoteLineData> = collected.iter().map(|l| l.data.clone()).collect();
843        let paragraph_text = line_data
844            .iter()
845            .map(|d| d.content.as_str())
846            .collect::<Vec<_>>()
847            .join(" ");
848
849        let contains_definition_list = line_data
850            .iter()
851            .any(|d| crate::utils::is_definition_list_item(&d.content));
852        if contains_definition_list {
853            return (None, next_idx);
854        }
855
856        let contains_snippets = line_data.iter().any(|d| is_snippet_block_delimiter(&d.content));
857        if contains_snippets {
858            return (None, next_idx);
859        }
860
861        let needs_reflow = match config.reflow_mode {
862            ReflowMode::Normalize => {
863                self.normalize_mode_needs_reflow(line_data.iter().map(|d| d.content.as_str()), config)
864            }
865            ReflowMode::SentencePerLine => {
866                let sentences = split_into_sentences(&paragraph_text);
867                sentences.len() > 1 || line_data.len() > 1
868            }
869            ReflowMode::SemanticLineBreaks => {
870                let sentences = split_into_sentences(&paragraph_text);
871                sentences.len() > 1
872                    || line_data.len() > 1
873                    || collected
874                        .iter()
875                        .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get())
876            }
877            ReflowMode::Default => collected
878                .iter()
879                .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get()),
880        };
881
882        if !needs_reflow {
883            return (None, next_idx);
884        }
885
886        let fallback_prefix = start_bq.prefix.clone();
887        let explicit_prefix = dominant_blockquote_prefix(&line_data, &fallback_prefix);
888        // Shift the whole quote right to track a widened parent list item's content
889        // column (only widening matters for nesting; a narrowed parent leaves the quote
890        // harmlessly over-indented, which MD027/MD030 tidy).
891        let explicit_prefix = if ancestor_shift > 0 {
892            format!("{}{explicit_prefix}", " ".repeat(ancestor_shift as usize))
893        } else {
894            explicit_prefix
895        };
896        let continuation_style = blockquote_continuation_style(&line_data);
897
898        let reflow_line_length = if config.line_length.is_unlimited() {
899            usize::MAX
900        } else {
901            config
902                .line_length
903                .get()
904                .saturating_sub(self.calculate_string_length(&explicit_prefix))
905                .max(1)
906        };
907
908        let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
909
910        let reflowed_with_style =
911            reflow_blockquote_content(&line_data, &explicit_prefix, continuation_style, &reflow_options);
912
913        if reflowed_with_style.is_empty() {
914            return (None, next_idx);
915        }
916
917        let reflowed_text = reflowed_with_style.join(line_ending);
918
919        let start_range = line_index.whole_line_range(paragraph_start + 1);
920        let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
921            line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
922        } else {
923            line_index.whole_line_range(end_line + 1)
924        };
925        let byte_range = start_range.start..end_range.end;
926
927        let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
928            format!("{reflowed_text}{line_ending}")
929        } else {
930            reflowed_text
931        };
932
933        let original_text = &ctx.content[byte_range.clone()];
934        if original_text == replacement {
935            return (None, next_idx);
936        }
937
938        let (warning_line, warning_end_line) = match config.reflow_mode {
939            ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
940            ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => (paragraph_start + 1, end_line + 1),
941            ReflowMode::Default => {
942                let violating_line = collected
943                    .iter()
944                    .find(|line| self.calculate_effective_length(lines[line.line_idx]) > config.line_length.get())
945                    .map_or(paragraph_start + 1, |line| line.line_idx + 1);
946                (violating_line, violating_line)
947            }
948        };
949
950        let warning = LintWarning {
951            rule_name: Some(self.name().to_string()),
952            message: match config.reflow_mode {
953                ReflowMode::Normalize => format!(
954                    "Paragraph could be normalized to use line length of {} characters",
955                    config.line_length.get()
956                ),
957                ReflowMode::SentencePerLine => {
958                    let num_sentences = split_into_sentences(&paragraph_text).len();
959                    if line_data.len() == 1 {
960                        format!("Line contains {num_sentences} sentences (one sentence per line required)")
961                    } else {
962                        let num_lines = line_data.len();
963                        format!(
964                            "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
965                        )
966                    }
967                }
968                ReflowMode::SemanticLineBreaks => {
969                    let num_sentences = split_into_sentences(&paragraph_text).len();
970                    format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
971                }
972                ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
973            },
974            line: warning_line,
975            column: 1,
976            end_line: warning_end_line,
977            end_column: lines[warning_end_line.saturating_sub(1)].chars().count() + 1,
978            severity: Severity::Warning,
979            fix: Some(crate::rule::Fix::new(byte_range, replacement)),
980        };
981
982        (Some(warning), next_idx)
983    }
984
985    /// Reflow a single list item that lives inside a blockquote.
986    ///
987    /// The blockquote paragraph reflow treats a list marker as a content boundary,
988    /// so `> - long item ...` is never wrapped even though the identical top-level
989    /// item is. This handles that case: it collects one tight, prose-only list item
990    /// at the starting blockquote level, reflows the item body to the configured
991    /// width, and re-emits it with the blockquote prefix preserved and continuation
992    /// lines aligned under the list content.
993    ///
994    /// Sibling and nested list items end collection and are reflowed independently
995    /// by the caller's outer loop (a nested item carries its indent folded into the
996    /// blockquote prefix, so it reflows correctly on its own). Items that are not
997    /// simple tight prose - those embedding a code block, table, fence, or hard
998    /// break - are left untouched (`None`) and the cursor still advances past the
999    /// whole item so its inner lines are never reprocessed as loose prose.
1000    #[allow(clippy::too_many_arguments)]
1001    fn generate_blockquote_list_item_fix(
1002        &self,
1003        ctx: &crate::lint_context::LintContext,
1004        config: &MD013Config,
1005        lines: &[&str],
1006        line_index: &LineIndex,
1007        start_idx: usize,
1008        line_ending: &str,
1009        // Extra indent (spaces) to prepend to the emitted `>` prefix when this quoted
1010        // list lives inside a list item whose marker widened. Zero unless a non-default
1011        // MD030 widened an ancestor list item.
1012        ancestor_shift: isize,
1013    ) -> (Option<LintWarning>, usize) {
1014        use crate::utils::blockquote::effective_indent_in_blockquote;
1015
1016        let Some(start_bq) = ctx.lines.get(start_idx).and_then(|line| line.blockquote.as_deref()) else {
1017            return (None, start_idx + 1);
1018        };
1019
1020        // A `>`-prefixed line can be marked as a blockquote even inside a fenced code
1021        // block (or other verbatim structure); such content must never be reflowed.
1022        if self.line_in_verbatim_context(start_idx + 1, ctx) {
1023            return (None, start_idx + 1);
1024        }
1025
1026        let target_level = start_bq.nesting_level;
1027
1028        // The marker line carries the canonical blockquote prefix: its content begins
1029        // with the list marker, so no list indent has been folded into the prefix.
1030        // Track a widened parent list item's content column so the quote stays nested
1031        // (only widening can detach it; narrowing just over-indents).
1032        let bq_prefix = if ancestor_shift > 0 {
1033            format!("{}{}", " ".repeat(ancestor_shift as usize), start_bq.prefix)
1034        } else {
1035            start_bq.prefix.clone()
1036        };
1037
1038        // A thematic break opens with what looks like a bullet marker (`- - -`).
1039        // It is not a list item, and reflowing it as prose destroys the break.
1040        // The top-level reflow path applies the same exemption.
1041        if is_horizontal_rule(&start_bq.content) {
1042            return (None, start_idx + 1);
1043        }
1044
1045        let (marker, first_body) = extract_list_marker_and_content(&start_bq.content);
1046        if marker.is_empty() {
1047            return (None, start_idx + 1);
1048        }
1049        let marker_width = marker.chars().count();
1050
1051        // Continuation lines of a checkbox item align under the bullet+checkbox, but
1052        // are recognized from the bullet width, matching the top-level list reflow.
1053        let base_marker_width = ["[ ] ", "[x] ", "[X] "]
1054            .iter()
1055            .find_map(|cb| marker.find(*cb))
1056            .unwrap_or(marker_width);
1057
1058        // Collect the item: the marker line plus its tight prose continuation lines.
1059        // `end_idx` always tracks the last consumed line so the cursor advances past
1060        // the entire item, even when it turns out to be too complex to reflow safely.
1061        let first_piece = trim_preserving_hard_break(&first_body);
1062        let mut simple = !has_hard_break(&first_piece);
1063        let mut body_pieces: Vec<String> = vec![first_piece];
1064        let mut end_idx = start_idx;
1065        let mut i = start_idx + 1;
1066
1067        while i < lines.len() {
1068            let Some(bq) = ctx.lines[i].blockquote.as_deref() else {
1069                // A blank line ends the item.
1070                if lines[i].trim().is_empty() {
1071                    break;
1072                }
1073                // A lazy continuation (no `>` marker) is too ambiguous to reflow
1074                // safely. Consume the whole lazy run into this item's span and leave
1075                // the item untouched, so the caller does not reflow the continuation
1076                // in isolation and leave the marker line partially fixed.
1077                simple = false;
1078                while i < lines.len() && ctx.lines[i].blockquote.is_none() && !lines[i].trim().is_empty() {
1079                    end_idx = i;
1080                    i += 1;
1081                }
1082                break;
1083            };
1084            if bq.nesting_level != target_level {
1085                break;
1086            }
1087
1088            let content = bq.content.as_str();
1089            if content.trim().is_empty() {
1090                // Blank quoted line ends the tight paragraph. A following indented
1091                // paragraph (loose item) is reflowed on its own by the prose path.
1092                break;
1093            }
1094
1095            let eff_indent = effective_indent_in_blockquote(lines[i], target_level, 0);
1096            if eff_indent < base_marker_width {
1097                // Dedented: a sibling list item or text outside this item. Stop here
1098                // and let the outer loop classify it.
1099                break;
1100            }
1101            if is_list_item(content) {
1102                // A nested list item: its own item, handled independently.
1103                break;
1104            }
1105
1106            // An embedded structure (code block, table, fence, nested quote, ...)
1107            // means the item is not simple prose: keep consuming so the cursor clears
1108            // the whole structure, but do not produce a fix.
1109            if self.is_blockquote_content_boundary(content, i + 1, ctx, config.strict) {
1110                simple = false;
1111            }
1112
1113            let piece = trim_preserving_hard_break(content);
1114            if has_hard_break(&piece) {
1115                simple = false;
1116            }
1117            body_pieces.push(piece);
1118            end_idx = i;
1119            i += 1;
1120        }
1121
1122        let next_idx = end_idx + 1;
1123
1124        if !simple {
1125            return (None, next_idx);
1126        }
1127
1128        let exceeds_limit =
1129            || (start_idx..=end_idx).any(|idx| self.calculate_effective_length(lines[idx]) > config.line_length.get());
1130        let body_text = body_pieces.join(" ");
1131        let body_text = body_text.trim();
1132
1133        // Some bodies cannot be shortened and must stay verbatim, matching the
1134        // exemptions the top-level list reflow applies: link reference definitions
1135        // always, and (in non-strict mode) standalone links/images and HTML-only
1136        // lines. Reflowing a link reference definition would split it after the
1137        // colon/URL and break the definition.
1138        let is_link_ref_def =
1139            body_text.starts_with('[') && body_text.contains("]:") && LINK_REF_PATTERN.is_match(body_text);
1140        let raw_marker_line = lines[start_idx];
1141        let body_is_unwrappable = is_link_ref_def
1142            || (!config.strict && is_standalone_link_or_image_line(raw_marker_line))
1143            || (!config.strict && is_html_only_line(raw_marker_line));
1144        if body_is_unwrappable {
1145            return (None, next_idx);
1146        }
1147
1148        let needs_reflow = match config.reflow_mode {
1149            ReflowMode::Normalize => body_pieces.len() > 1 || exceeds_limit(),
1150            ReflowMode::Default => exceeds_limit(),
1151            ReflowMode::SentencePerLine => split_into_sentences(body_text).len() > 1 || body_pieces.len() > 1,
1152            ReflowMode::SemanticLineBreaks => split_into_sentences(body_text).len() > 1 || exceeds_limit(),
1153        };
1154        if !needs_reflow {
1155            return (None, next_idx);
1156        }
1157
1158        // Apply MD030 list-marker spacing in the spacing-normalizing modes, mirroring
1159        // the top-level list reflow: derive the post-marker spacing from MD030 and let
1160        // the continuation indent follow the resulting content width. Default MD030 (a
1161        // single space) leaves the marker unchanged. MkDocs keeps its rigid indent.
1162        let (marker, marker_width) = if matches!(config.reflow_mode, ReflowMode::Default | ReflowMode::Normalize)
1163            && !ctx.flavor.requires_strict_list_indent()
1164        {
1165            let is_ordered = marker.starts_with(|c: char| c.is_ascii_digit());
1166            // Bullet/number portion only (e.g. `-`, `1.`); the checkbox is content.
1167            let bullet = marker.split(' ').next().unwrap_or("");
1168            let bullet_len = bullet.chars().count();
1169            let checkbox_tail = &marker[base_marker_width..];
1170            // Decide single- vs multi-line spacing from the rewritten shape. This path
1171            // only handles a single tight prose paragraph (structural or multi-paragraph
1172            // items set `simple = false` and bail out above), so the emitted item stays
1173            // multi-line solely when the joined body wraps past one line. A multi-line
1174            // *source* that collapses onto the marker line must use MD030's single-line
1175            // spacing, matching the top-level reflow. The wrap test measures at the
1176            // single-line content column so it does not depend on the spacing chosen here.
1177            let single_col = self.calculate_string_length(&bq_prefix)
1178                + bullet_len
1179                + self.list_spacing.expected_spaces(is_ordered, false, bullet_len)
1180                + checkbox_tail.chars().count();
1181            let is_multi = !body_text.is_empty()
1182                && self.calculate_effective_length(&format!("{}{body_text}", " ".repeat(single_col)))
1183                    > config.line_length.effective_limit();
1184            let spaces = self.list_spacing.expected_spaces(is_ordered, is_multi, bullet_len);
1185            let new_marker = format!("{bullet}{}{checkbox_tail}", " ".repeat(spaces));
1186            let width = new_marker.chars().count();
1187            (new_marker, width)
1188        } else {
1189            (marker, marker_width)
1190        };
1191
1192        let prefix_width = self.calculate_string_length(&bq_prefix) + self.calculate_string_length(&marker);
1193        let reflow_line_length = if config.line_length.is_unlimited() {
1194            usize::MAX
1195        } else {
1196            config.line_length.get().saturating_sub(prefix_width).max(1)
1197        };
1198
1199        let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
1200
1201        let reflowed = crate::utils::text_reflow::reflow_line(body_text, &reflow_options);
1202        if reflowed.is_empty() {
1203            return (None, next_idx);
1204        }
1205
1206        let continuation_indent = " ".repeat(marker_width);
1207        let reflowed_text = reflowed
1208            .iter()
1209            .enumerate()
1210            .map(|(idx, line)| {
1211                if idx == 0 {
1212                    format!("{bq_prefix}{marker}{line}")
1213                } else {
1214                    format!("{bq_prefix}{continuation_indent}{line}")
1215                }
1216            })
1217            .collect::<Vec<_>>()
1218            .join(line_ending);
1219
1220        let start_range = line_index.whole_line_range(start_idx + 1);
1221        let end_range = if end_idx == lines.len() - 1 && !ctx.content.ends_with('\n') {
1222            line_index.line_text_range(end_idx + 1, 1, lines[end_idx].len() + 1)
1223        } else {
1224            line_index.whole_line_range(end_idx + 1)
1225        };
1226        let byte_range = start_range.start..end_range.end;
1227
1228        let replacement = if end_idx < lines.len() - 1 || ctx.content.ends_with('\n') {
1229            format!("{reflowed_text}{line_ending}")
1230        } else {
1231            reflowed_text
1232        };
1233
1234        let original_text = &ctx.content[byte_range.clone()];
1235        if original_text == replacement {
1236            return (None, next_idx);
1237        }
1238
1239        let message = match config.reflow_mode {
1240            ReflowMode::Normalize => format!(
1241                "Paragraph could be normalized to use line length of {} characters",
1242                config.line_length.get()
1243            ),
1244            ReflowMode::SentencePerLine => {
1245                let num_sentences = split_into_sentences(body_text).len();
1246                format!("List item should have one sentence per line (found {num_sentences} sentences)")
1247            }
1248            ReflowMode::SemanticLineBreaks => {
1249                let num_sentences = split_into_sentences(body_text).len();
1250                format!("List item should use semantic line breaks ({num_sentences} sentences)")
1251            }
1252            ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
1253        };
1254
1255        let warning = LintWarning {
1256            rule_name: Some(self.name().to_string()),
1257            message,
1258            line: start_idx + 1,
1259            column: 1,
1260            end_line: end_idx + 1,
1261            end_column: lines[end_idx].chars().count() + 1,
1262            severity: Severity::Warning,
1263            fix: Some(crate::rule::Fix::new(byte_range, replacement)),
1264        };
1265
1266        (Some(warning), next_idx)
1267    }
1268
1269    /// Generate paragraph-based fixes
1270    fn generate_paragraph_fixes(
1271        &self,
1272        ctx: &crate::lint_context::LintContext,
1273        config: &MD013Config,
1274        lines: &[&str],
1275    ) -> Vec<LintWarning> {
1276        let mut warnings = Vec::new();
1277        let line_index = LineIndex::new(ctx.content);
1278
1279        // Detect the content's line ending style to preserve it in replacements.
1280        // The LSP receives content from editors which may use CRLF (Windows).
1281        // Replacements must match the original line endings to avoid false positives.
1282        let line_ending = crate::utils::line_ending::detect_line_ending(ctx.content);
1283
1284        // Ancestor list-item indent shifts, innermost last. When a reflowed parent's
1285        // marker widens under a non-default MD030 (e.g. ul-multi = 3 moves the parent's
1286        // content from column 2 to 4), its nested list/blockquote children are reflowed
1287        // independently and would otherwise keep their original indent — leaving them
1288        // under the parent's new content column, where a CommonMark parser reparses them
1289        // as siblings rather than children. Each frame is (normalized marker width,
1290        // cumulative shift applied to that item's content column); a descendant adds its
1291        // innermost open ancestor's shift to its own indent so the whole subtree moves
1292        // together. With a default MD030 and no marker padding every shift is 0, so this
1293        // is inert and the output is byte-identical.
1294        let mut list_shift_stack: Vec<(usize, isize)> = Vec::new();
1295
1296        let mut i = 0;
1297        while i < lines.len() {
1298            let line_num = i + 1;
1299
1300            // Close ancestor frames whose list item has ended at this line: a non-blank
1301            // line indented less than the frame's source content column is no longer
1302            // inside that item. Blank lines alone don't close a (loose) list item.
1303            if !list_shift_stack.is_empty()
1304                && let Some(info) = ctx.lines.get(i)
1305                && !info.is_blank
1306            {
1307                while let Some(&(content_column, _)) = list_shift_stack.last() {
1308                    if info.indent < content_column {
1309                        list_shift_stack.pop();
1310                    } else {
1311                        break;
1312                    }
1313                }
1314            }
1315
1316            // Handle blockquote paragraphs with style-preserving reflow.
1317            // Skip blockquotes when blockquotes=false or paragraphs=false
1318            if line_num > 0 && line_num <= ctx.lines.len() && ctx.lines[line_num - 1].blockquote.is_some() {
1319                if !config.blockquotes || !config.paragraphs {
1320                    // Skip past all blockquote lines (explicit and lazy continuations).
1321                    // A lazy continuation is a non-blank line without `>` that follows
1322                    // a blockquote line and isn't a structural element.
1323                    let mut saw_explicit_bq = false;
1324                    while i < lines.len() && i < ctx.lines.len() {
1325                        if ctx.lines[i].blockquote.is_some() {
1326                            saw_explicit_bq = true;
1327                            i += 1;
1328                        } else if saw_explicit_bq
1329                            && !lines[i].trim().is_empty()
1330                            && !lines[i].trim_start().starts_with('#')
1331                            && !lines[i].trim_start().starts_with('>')
1332                        {
1333                            // Lazy continuation of preceding blockquote
1334                            i += 1;
1335                        } else {
1336                            break;
1337                        }
1338                    }
1339                    continue;
1340                }
1341                // A blockquote nested in a list item moves with its parent when the
1342                // parent's marker widens (see `list_shift_stack`); pass that shift so the
1343                // emitted `>` prefix lands under the parent's new content column instead
1344                // of detaching into a sibling.
1345                let ancestor_shift = list_shift_stack.last().map_or(0isize, |&(_, shift)| shift);
1346                // A list item inside the blockquote needs list-aware reflow (marker +
1347                // continuation indent); plain prose goes through the paragraph path.
1348                let is_bq_list_item = ctx.lines[i]
1349                    .blockquote
1350                    .as_deref()
1351                    .is_some_and(|bq| is_list_item(&bq.content));
1352                let (warning, next_idx) = if is_bq_list_item {
1353                    self.generate_blockquote_list_item_fix(
1354                        ctx,
1355                        config,
1356                        lines,
1357                        &line_index,
1358                        i,
1359                        line_ending,
1360                        ancestor_shift,
1361                    )
1362                } else {
1363                    self.generate_blockquote_paragraph_fix(
1364                        ctx,
1365                        config,
1366                        lines,
1367                        &line_index,
1368                        i,
1369                        line_ending,
1370                        ancestor_shift,
1371                    )
1372                };
1373                if let Some(warning) = warning {
1374                    warnings.push(warning);
1375                }
1376                i = next_idx;
1377                continue;
1378            }
1379
1380            // Skip special structures (but NOT MkDocs containers - those get special handling)
1381            let should_skip_due_to_line_info = ctx.line_info(line_num).is_some_and(|info| {
1382                info.in_code_block
1383                    || info.in_front_matter
1384                    || info.in_html_block
1385                    || info.in_html_comment
1386                    || info.in_esm_block
1387                    || info.in_jsx_expression
1388                    || info.in_jsx_block
1389                    || info.in_mdx_comment
1390                    || info.in_mkdocstrings
1391                    || info.in_pymdown_block
1392            });
1393
1394            // Skip link reference definitions but NOT footnote definitions.
1395            // Footnote definitions (`[^id]: prose`) contain reflowable text,
1396            // while link reference definitions (`[ref]: URL`) contain URLs
1397            // that cannot be shortened.
1398            let is_link_ref_def =
1399                lines[i].trim().starts_with('[') && !lines[i].trim().starts_with("[^") && lines[i].contains("]:");
1400
1401            if should_skip_due_to_line_info
1402                || lines[i].trim().starts_with('#')
1403                || TableUtils::is_potential_table_row(lines[i])
1404                || lines[i].trim().is_empty()
1405                || is_horizontal_rule(lines[i])
1406                || is_template_directive_only(lines[i])
1407                || is_link_ref_def
1408                || ctx.line_info(line_num).is_some_and(|info| info.is_div_marker)
1409                || is_html_only_line(lines[i])
1410                || (!config.strict && is_standalone_link_or_image_line(lines[i]))
1411            {
1412                i += 1;
1413                continue;
1414            }
1415
1416            // Handle footnote definitions: `[^id]: prose text that can be reflowed`
1417            // Supports multi-paragraph footnotes with code blocks, blockquotes,
1418            // tables, and lists preserved verbatim.
1419            // Validate structure: must start with `[^`, contain `]:`, and the ID
1420            // must not contain `[` or `]` (prevents false matches on nested brackets)
1421            if lines[i].trim().starts_with("[^") && lines[i].contains("]:") && {
1422                let after_caret = &lines[i].trim()[2..];
1423                after_caret
1424                    .find("]:")
1425                    .is_some_and(|pos| pos > 0 && !after_caret[..pos].contains(['[', ']']))
1426            } {
1427                let footnote_start = i;
1428                let line = lines[i];
1429
1430                // Extract the prefix `[^id]:`
1431                let Some(colon_pos) = line.find("]:") else {
1432                    i += 1;
1433                    continue;
1434                };
1435                let prefix_end = colon_pos + 2;
1436                let prefix = &line[..prefix_end];
1437
1438                // Content starts after `]: ` (with optional space)
1439                let content_start = if line[prefix_end..].starts_with(' ') {
1440                    prefix_end + 1
1441                } else {
1442                    prefix_end
1443                };
1444                let first_content = &line[content_start..];
1445
1446                // CommonMark footnotes use 4-space continuation indent
1447                const FN_INDENT: usize = 4;
1448
1449                // --- Line classification for footnote content ---
1450                #[derive(Debug, Clone)]
1451                enum FnLineType {
1452                    Content(String),
1453                    Verbatim(String, usize), // preserved text, original indent
1454                    Empty,
1455                }
1456
1457                // Helper: compute visual indent (tabs = 4 spaces)
1458                let visual_indent = |s: &str| -> usize {
1459                    s.chars()
1460                        .take_while(|c| c.is_whitespace())
1461                        .map(|c| if c == '\t' { 4 } else { 1 })
1462                        .sum::<usize>()
1463                };
1464
1465                // Helper: check if a trimmed line is a fence marker (homogeneous chars)
1466                let is_fence = |s: &str| -> bool {
1467                    let t = s.trim();
1468                    let fence_char = t.chars().next();
1469                    matches!(fence_char, Some('`') | Some('~'))
1470                        && t.chars().take_while(|&c| c == fence_char.unwrap()).count() >= 3
1471                };
1472
1473                // Helper: check if a trimmed line is a setext underline
1474                let is_setext_underline = |s: &str| -> bool {
1475                    let t = s.trim();
1476                    !t.is_empty()
1477                        && (t.chars().all(|c| c == '=' || c == ' ') || t.chars().all(|c| c == '-' || c == ' '))
1478                        && t.contains(['=', '-'])
1479                };
1480
1481                // Deferred body: `[^id]:\n    content` — first line has no content,
1482                // actual content starts on the next indented line
1483                let deferred_body = first_content.trim().is_empty();
1484
1485                // Collect all lines belonging to this footnote definition
1486                let mut fn_lines: Vec<FnLineType> = Vec::new();
1487                if !deferred_body {
1488                    fn_lines.push(FnLineType::Content(first_content.to_string()));
1489                }
1490                let mut last_consumed = i;
1491                i += 1;
1492
1493                // Strip only the footnote continuation indent, preserving
1494                // internal indentation (e.g., code block body indent)
1495                let strip_fn_indent = |s: &str| -> String {
1496                    let mut chars = s.chars();
1497                    let mut stripped = 0;
1498                    while stripped < FN_INDENT {
1499                        match chars.next() {
1500                            Some('\t') => stripped += 4,
1501                            Some(c) if c.is_whitespace() => stripped += 1,
1502                            _ => break,
1503                        }
1504                    }
1505                    chars.as_str().to_string()
1506                };
1507
1508                let mut in_fenced_code = false;
1509                let mut consecutive_blanks = 0u32;
1510
1511                while i < lines.len() {
1512                    let next = lines[i];
1513                    let next_trimmed = next.trim();
1514
1515                    // Blank line handling
1516                    if next_trimmed.is_empty() {
1517                        consecutive_blanks += 1;
1518                        // 2+ consecutive blanks terminate the footnote
1519                        if consecutive_blanks >= 2 {
1520                            break;
1521                        }
1522
1523                        // Inside a fenced code block, blank lines are part of the code
1524                        if in_fenced_code {
1525                            consecutive_blanks = 0; // Don't count blanks inside code blocks
1526                            fn_lines.push(FnLineType::Verbatim(String::new(), 0));
1527                            last_consumed = i;
1528                            i += 1;
1529                            continue;
1530                        }
1531
1532                        // Peek ahead: if next non-blank line is indented >= FN_INDENT,
1533                        // this blank is an internal paragraph separator
1534                        if i + 1 < lines.len() {
1535                            let peek = lines[i + 1];
1536                            let peek_indent = visual_indent(peek);
1537                            if !peek.trim().is_empty() && peek_indent >= FN_INDENT {
1538                                fn_lines.push(FnLineType::Empty);
1539                                last_consumed = i;
1540                                i += 1;
1541                                continue;
1542                            }
1543                        }
1544                        // No valid continuation after blank — end of footnote
1545                        break;
1546                    }
1547
1548                    consecutive_blanks = 0;
1549                    let indent = visual_indent(next);
1550
1551                    // Not indented enough — end of footnote
1552                    if indent < FN_INDENT {
1553                        break;
1554                    }
1555
1556                    // Inside a fenced code block: everything is verbatim until closing fence
1557                    if in_fenced_code {
1558                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1559                        if is_fence(next_trimmed) {
1560                            in_fenced_code = false;
1561                        }
1562                        last_consumed = i;
1563                        i += 1;
1564                        continue;
1565                    }
1566
1567                    // Fence opener — start verbatim code block
1568                    if is_fence(next_trimmed) {
1569                        in_fenced_code = true;
1570                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1571                        last_consumed = i;
1572                        i += 1;
1573                        continue;
1574                    }
1575
1576                    // Indented code block: indent >= FN_INDENT + 4 (= 8 spaces)
1577                    if indent >= FN_INDENT + 4 {
1578                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1579                        last_consumed = i;
1580                        i += 1;
1581                        continue;
1582                    }
1583
1584                    // Structural content that must be preserved verbatim
1585                    if next_trimmed.starts_with('#')
1586                        || is_list_item(next_trimmed)
1587                        || next_trimmed.starts_with('>')
1588                        || TableUtils::is_potential_table_row(next_trimmed)
1589                        || is_setext_underline(next_trimmed)
1590                        || is_horizontal_rule(next_trimmed)
1591                        || crate::utils::mkdocs_footnotes::is_footnote_definition(next_trimmed)
1592                    {
1593                        // Preserve verbatim: blockquotes, tables, lists, setext
1594                        // underlines, and horizontal rules inside the footnote
1595                        if next_trimmed.starts_with('>')
1596                            || TableUtils::is_potential_table_row(next_trimmed)
1597                            || is_list_item(next_trimmed)
1598                            || is_setext_underline(next_trimmed)
1599                            || is_horizontal_rule(next_trimmed)
1600                        {
1601                            fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1602                            last_consumed = i;
1603                            i += 1;
1604                            continue;
1605                        }
1606                        // Headings, new footnote defs, link refs — end the footnote
1607                        break;
1608                    }
1609
1610                    // Link reference definitions inside footnotes are not reflowable
1611                    if next_trimmed.starts_with('[')
1612                        && !next_trimmed.starts_with("[^")
1613                        && next_trimmed.contains("]:")
1614                        && LINK_REF_PATTERN.is_match(next_trimmed)
1615                    {
1616                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1617                        last_consumed = i;
1618                        i += 1;
1619                        continue;
1620                    }
1621
1622                    // HTML-only lines inside footnotes are not reflowable
1623                    if is_html_only_line(next_trimmed) {
1624                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1625                        last_consumed = i;
1626                        i += 1;
1627                        continue;
1628                    }
1629
1630                    // Regular prose content
1631                    fn_lines.push(FnLineType::Content(next_trimmed.to_string()));
1632                    last_consumed = i;
1633                    i += 1;
1634                }
1635
1636                // Nothing collected or only empty lines
1637                if fn_lines.iter().all(|l| matches!(l, FnLineType::Empty)) || fn_lines.is_empty() {
1638                    continue;
1639                }
1640
1641                // --- Group into blocks ---
1642                #[derive(Debug)]
1643                enum FnBlock {
1644                    Paragraph(Vec<String>),
1645                    Verbatim(Vec<(String, usize)>), // (content, indent) preserved as-is
1646                }
1647
1648                let mut blocks: Vec<FnBlock> = Vec::new();
1649                let mut current_para: Vec<String> = Vec::new();
1650                let mut current_verbatim: Vec<(String, usize)> = Vec::new();
1651
1652                for fl in &fn_lines {
1653                    match fl {
1654                        FnLineType::Content(s) => {
1655                            if !current_verbatim.is_empty() {
1656                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
1657                            }
1658                            current_para.push(s.clone());
1659                        }
1660                        FnLineType::Verbatim(s, indent) => {
1661                            if !current_para.is_empty() {
1662                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
1663                            }
1664                            current_verbatim.push((s.clone(), *indent));
1665                        }
1666                        FnLineType::Empty => {
1667                            if !current_para.is_empty() {
1668                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
1669                            }
1670                            if !current_verbatim.is_empty() {
1671                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
1672                            }
1673                        }
1674                    }
1675                }
1676                if !current_para.is_empty() {
1677                    blocks.push(FnBlock::Paragraph(current_para));
1678                }
1679                if !current_verbatim.is_empty() {
1680                    blocks.push(FnBlock::Verbatim(current_verbatim));
1681                }
1682
1683                // --- Reflow paragraphs and reconstruct ---
1684                let prefix_display_width = prefix.chars().count() + 1; // +1 for space
1685                let reflow_line_length = if config.line_length.is_unlimited() {
1686                    usize::MAX
1687                } else {
1688                    config
1689                        .line_length
1690                        .get()
1691                        .saturating_sub(FN_INDENT.max(prefix_display_width))
1692                        .max(20)
1693                };
1694                // Footnote continuation uses a fixed 4-space indent, so list
1695                // continuation capping does not apply here.
1696                let reflow_options = crate::utils::text_reflow::ReflowOptions {
1697                    max_list_continuation_indent: None,
1698                    ..Self::reflow_options(ctx, config, reflow_line_length)
1699                };
1700
1701                let indent_str = " ".repeat(FN_INDENT);
1702                let mut result_lines: Vec<String> = Vec::new();
1703                let mut is_first_block = true;
1704
1705                for block in &blocks {
1706                    match block {
1707                        FnBlock::Paragraph(para_lines) => {
1708                            let paragraph_text = para_lines.join(" ");
1709                            let paragraph_text = paragraph_text.trim();
1710                            if paragraph_text.is_empty() {
1711                                continue;
1712                            }
1713
1714                            let reflowed = crate::utils::text_reflow::reflow_line(paragraph_text, &reflow_options);
1715                            if reflowed.is_empty() {
1716                                continue;
1717                            }
1718
1719                            // Blank line separator between blocks
1720                            if !result_lines.is_empty() {
1721                                result_lines.push(String::new());
1722                            }
1723
1724                            for (idx, rline) in reflowed.iter().enumerate() {
1725                                if is_first_block && idx == 0 {
1726                                    result_lines.push(format!("{prefix} {rline}"));
1727                                } else {
1728                                    result_lines.push(format!("{indent_str}{rline}"));
1729                                }
1730                            }
1731                            is_first_block = false;
1732                        }
1733                        FnBlock::Verbatim(verb_lines) => {
1734                            // Blank line separator between blocks
1735                            if !result_lines.is_empty() {
1736                                result_lines.push(String::new());
1737                            }
1738
1739                            if is_first_block {
1740                                // Verbatim as first block in a deferred-body footnote
1741                                if deferred_body {
1742                                    result_lines.push(prefix.to_string());
1743                                }
1744                                is_first_block = false;
1745                            }
1746                            for (content, _orig_indent) in verb_lines {
1747                                result_lines.push(format!("{indent_str}{content}"));
1748                            }
1749                        }
1750                    }
1751                }
1752
1753                // If nothing was produced, skip
1754                if result_lines.is_empty() {
1755                    continue;
1756                }
1757
1758                let reflowed_text = result_lines.join(line_ending);
1759
1760                // Calculate byte range using last_consumed
1761                let start_range = line_index.whole_line_range(footnote_start + 1);
1762                let end_range = if last_consumed == lines.len() - 1 && !ctx.content.ends_with('\n') {
1763                    line_index.line_text_range(last_consumed + 1, 1, lines[last_consumed].len() + 1)
1764                } else {
1765                    line_index.whole_line_range(last_consumed + 1)
1766                };
1767                let byte_range = start_range.start..end_range.end;
1768
1769                let replacement = if last_consumed < lines.len() - 1 || ctx.content.ends_with('\n') {
1770                    format!("{reflowed_text}{line_ending}")
1771                } else {
1772                    reflowed_text
1773                };
1774
1775                let original_text = &ctx.content[byte_range.clone()];
1776                let max_length = (footnote_start..=last_consumed)
1777                    .map(|idx| self.calculate_effective_length(lines[idx]))
1778                    .max()
1779                    .unwrap_or(0);
1780                let line_limit = if config.line_length.is_unlimited() {
1781                    usize::MAX
1782                } else {
1783                    config.line_length.get()
1784                };
1785                if original_text != replacement && max_length > line_limit {
1786                    warnings.push(LintWarning {
1787                        rule_name: Some(self.name().to_string()),
1788                        message: format!(
1789                            "Line length {} exceeds {} characters",
1790                            max_length,
1791                            config.line_length.get()
1792                        ),
1793                        line: footnote_start + 1,
1794                        column: 1,
1795                        end_line: last_consumed + 1,
1796                        end_column: lines[last_consumed].chars().count() + 1,
1797                        severity: Severity::Warning,
1798                        fix: Some(crate::rule::Fix::new(byte_range, replacement)),
1799                    });
1800                }
1801                continue;
1802            }
1803
1804            // Handle MkDocs container content (admonitions and tabs) with indent-preserving reflow
1805            if ctx
1806                .line_info(line_num)
1807                .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container)
1808            {
1809                // Skip admonition/tab marker lines — only reflow their indented content
1810                let current_line = lines[i];
1811                if mkdocs_admonitions::is_admonition_start(current_line) || mkdocs_tabs::is_tab_marker(current_line) {
1812                    i += 1;
1813                    continue;
1814                }
1815
1816                let container_start = i;
1817
1818                // Detect the actual indent level from the first content line
1819                // (supports nested admonitions with 8+ spaces)
1820                let first_line = lines[i];
1821                let base_indent_len = first_line.len() - first_line.trim_start().len();
1822                let base_indent: String = " ".repeat(base_indent_len);
1823
1824                // Collect consecutive MkDocs container paragraph lines
1825                let mut container_lines: Vec<&str> = Vec::new();
1826                while i < lines.len() {
1827                    let current_line_num = i + 1;
1828                    let line_info = ctx.line_info(current_line_num);
1829
1830                    // Stop if we leave the MkDocs container
1831                    if !line_info.is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container) {
1832                        break;
1833                    }
1834
1835                    let line = lines[i];
1836
1837                    // Stop at paragraph boundaries within the container
1838                    if line.trim().is_empty() {
1839                        break;
1840                    }
1841
1842                    // Skip list items, code blocks, headings, HTML-only lines within containers
1843                    if is_list_item(line.trim())
1844                        || line.trim().starts_with("```")
1845                        || line.trim().starts_with("~~~")
1846                        || line.trim().starts_with('#')
1847                        || is_html_only_line(line)
1848                    {
1849                        break;
1850                    }
1851
1852                    container_lines.push(line);
1853                    i += 1;
1854                }
1855
1856                if container_lines.is_empty() {
1857                    // Must advance i to avoid infinite loop when we encounter
1858                    // non-paragraph content (code block, list, heading, empty line)
1859                    // at the start of an MkDocs container
1860                    i += 1;
1861                    continue;
1862                }
1863
1864                // Strip the base indent from each line and join for reflow
1865                let stripped_lines: Vec<&str> = container_lines
1866                    .iter()
1867                    .map(|line| {
1868                        if line.starts_with(&base_indent) {
1869                            &line[base_indent_len..]
1870                        } else {
1871                            line.trim_start()
1872                        }
1873                    })
1874                    .collect();
1875                let paragraph_text = stripped_lines.join(" ");
1876
1877                // Check if reflow is needed
1878                let needs_reflow = match config.reflow_mode {
1879                    ReflowMode::Normalize => self.normalize_mode_needs_reflow(container_lines.iter().copied(), config),
1880                    ReflowMode::SentencePerLine => {
1881                        let sentences = split_into_sentences(&paragraph_text);
1882                        sentences.len() > 1 || container_lines.len() > 1
1883                    }
1884                    ReflowMode::SemanticLineBreaks => {
1885                        let sentences = split_into_sentences(&paragraph_text);
1886                        sentences.len() > 1
1887                            || container_lines.len() > 1
1888                            || container_lines
1889                                .iter()
1890                                .any(|line| self.calculate_effective_length(line) > config.line_length.get())
1891                    }
1892                    ReflowMode::Default => container_lines
1893                        .iter()
1894                        .any(|line| self.calculate_effective_length(line) > config.line_length.get()),
1895                };
1896
1897                if !needs_reflow {
1898                    continue;
1899                }
1900
1901                // Calculate byte range for this container paragraph
1902                let start_range = line_index.whole_line_range(container_start + 1);
1903                let end_line = container_start + container_lines.len() - 1;
1904                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
1905                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
1906                } else {
1907                    line_index.whole_line_range(end_line + 1)
1908                };
1909                let byte_range = start_range.start..end_range.end;
1910
1911                // Reflow with adjusted line length (accounting for the 4-space indent)
1912                let reflow_line_length = if config.line_length.is_unlimited() {
1913                    usize::MAX
1914                } else {
1915                    config.line_length.get().saturating_sub(base_indent_len).max(1)
1916                };
1917                let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
1918                let reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);
1919
1920                // Re-add the 4-space indent to each reflowed line
1921                let reflowed_with_indent: Vec<String> =
1922                    reflowed.iter().map(|line| format!("{base_indent}{line}")).collect();
1923                let reflowed_text = reflowed_with_indent.join(line_ending);
1924
1925                // Preserve trailing newline
1926                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
1927                    format!("{reflowed_text}{line_ending}")
1928                } else {
1929                    reflowed_text
1930                };
1931
1932                // Only generate a warning if the replacement is different
1933                let original_text = &ctx.content[byte_range.clone()];
1934                if original_text != replacement {
1935                    warnings.push(LintWarning {
1936                        rule_name: Some(self.name().to_string()),
1937                        message: format!(
1938                            "Line length {} exceeds {} characters (in MkDocs container)",
1939                            container_lines.iter().map(|l| l.len()).max().unwrap_or(0),
1940                            config.line_length.get()
1941                        ),
1942                        line: container_start + 1,
1943                        column: 1,
1944                        end_line: end_line + 1,
1945                        end_column: lines[end_line].chars().count() + 1,
1946                        severity: Severity::Warning,
1947                        fix: Some(crate::rule::Fix::new(byte_range, replacement)),
1948                    });
1949                }
1950                continue;
1951            }
1952
1953            // Helper function to detect semantic line markers
1954            let is_semantic_line = |content: &str| -> bool {
1955                let trimmed = content.trim_start();
1956                let semantic_markers = [
1957                    "NOTE:",
1958                    "WARNING:",
1959                    "IMPORTANT:",
1960                    "CAUTION:",
1961                    "TIP:",
1962                    "DANGER:",
1963                    "HINT:",
1964                    "INFO:",
1965                ];
1966                semantic_markers.iter().any(|marker| trimmed.starts_with(marker))
1967            };
1968
1969            // Helper function to detect fence markers (opening or closing)
1970            let is_fence_marker = |content: &str| -> bool {
1971                let trimmed = content.trim_start();
1972                trimmed.starts_with("```") || trimmed.starts_with("~~~")
1973            };
1974
1975            // Check if this is a list item - handle it specially
1976            let trimmed = lines[i].trim();
1977            if is_list_item(trimmed) {
1978                // Collect the entire list item including continuation lines
1979                let list_start = i;
1980                let (marker, first_content) = extract_list_marker_and_content(lines[i]);
1981                let marker_len = marker.len();
1982                // The normalized marker above is what gets re-emitted; the source marker
1983                // is where the item's content actually starts. Nested blocks move by the
1984                // difference between the two content columns, so the shift must be
1985                // measured against the source, not against the normalized width.
1986                let source_marker = source_list_marker(lines[i]);
1987                let source_content_col = source_marker.as_ref().map_or(marker_len, |m| m.content_col);
1988
1989                // Checkbox ([ ]/[x]/[X]) is inline content, not part of the list marker.
1990                // Use the base bullet/number marker width for continuation recognition
1991                // so that continuation lines at 2+ spaces are collected for "- [ ] " items.
1992                let base_marker_len = if marker.contains("[ ] ") || marker.contains("[x] ") || marker.contains("[X] ") {
1993                    marker.find('[').unwrap_or(marker_len)
1994                } else {
1995                    marker_len
1996                };
1997
1998                // MkDocs flavor requires at least 4 spaces for list continuation
1999                // after a blank line (multi-paragraph list items). For non-blank
2000                // continuation (lines directly following the marker line), use
2001                // the natural marker width so that 2-space indent is recognized.
2002                let item_indent = ctx.lines[i].indent;
2003                let min_continuation_indent = if ctx.flavor.requires_strict_list_indent() {
2004                    // Use 4-space relative indent from the list item's nesting level
2005                    item_indent + (base_marker_len - item_indent).max(4)
2006                } else {
2007                    marker_len
2008                };
2009                let content_continuation_indent = base_marker_len;
2010
2011                // Track lines and their types (content, code block, fence, nested list)
2012                #[derive(Clone)]
2013                enum LineType {
2014                    Content(String),
2015                    CodeBlock(String, usize),         // content and original indent
2016                    SemanticLine(String), // Lines starting with NOTE:, WARNING:, etc that should stay separate
2017                    SnippetLine(String),  // MkDocs Snippets delimiters (-8<-) that must stay on their own line
2018                    DivMarker(String),    // Quarto/Pandoc div markers (::: opening or closing)
2019                    AdmonitionHeader(String, usize), // header text (e.g. "!!! note") and original indent
2020                    AdmonitionContent(String, usize), // body content text and original indent
2021                    Table(String, usize), // GFM table row, preserved verbatim with original indent
2022                    Empty,
2023                }
2024
2025                let mut list_item_lines: Vec<LineType> = vec![LineType::Content(first_content)];
2026                // Set when collection stops at a nested list item or a nested
2027                // blockquote that belongs to this item. Such structure is reflowed
2028                // independently and is therefore absent from `list_item_lines`/`blocks`,
2029                // but it still keeps the emitted item spanning multiple physical lines,
2030                // which the MD030 multi-line spacing decision below must account for.
2031                let mut has_trailing_nested_structure = false;
2032                i += 1;
2033
2034                // Collect continuation lines using ctx.lines for metadata
2035                while i < lines.len() {
2036                    let line_info = &ctx.lines[i];
2037
2038                    // Use pre-computed is_blank from ctx
2039                    if line_info.is_blank {
2040                        // Empty line - check if next line is indented (part of list item)
2041                        if i + 1 < lines.len() {
2042                            let next_info = &ctx.lines[i + 1];
2043
2044                            // Check if next line is indented enough to be continuation
2045                            if !next_info.is_blank && next_info.indent >= min_continuation_indent {
2046                                // This blank line is between paragraphs/blocks in the list item
2047                                list_item_lines.push(LineType::Empty);
2048                                i += 1;
2049                                continue;
2050                            }
2051                        }
2052                        // No indented line after blank, end of list item
2053                        break;
2054                    }
2055
2056                    // Use pre-computed indent from ctx
2057                    let indent = line_info.indent;
2058
2059                    // Valid continuation must be indented at least content_continuation_indent.
2060                    // For non-blank continuation, use marker_len (e.g. 2 for "- ").
2061                    // MkDocs strict 4-space requirement applies only after blank lines.
2062                    if indent >= content_continuation_indent {
2063                        let trimmed = line_info.content(ctx.content).trim();
2064
2065                        // Check for MkDocs admonition lines inside list items BEFORE
2066                        // checking in_code_block. Lines inside code blocks within
2067                        // admonitions have both in_admonition and in_code_block set;
2068                        // admonition membership takes priority so the entire admonition
2069                        // structure (including embedded code blocks) is preserved.
2070                        if line_info.in_admonition {
2071                            let raw_content = line_info.content(ctx.content);
2072                            if mkdocs_admonitions::is_admonition_start(raw_content) {
2073                                let header_text = raw_content[indent..].trim_end().to_string();
2074                                list_item_lines.push(LineType::AdmonitionHeader(header_text, indent));
2075                            } else {
2076                                let body_text = raw_content[indent..].trim_end().to_string();
2077                                list_item_lines.push(LineType::AdmonitionContent(body_text, indent));
2078                            }
2079                            i += 1;
2080                            continue;
2081                        }
2082
2083                        // Use pre-computed in_code_block from ctx
2084                        if line_info.in_code_block {
2085                            list_item_lines.push(LineType::CodeBlock(
2086                                line_info.content(ctx.content)[indent..].to_string(),
2087                                indent,
2088                            ));
2089                            i += 1;
2090                            continue;
2091                        }
2092
2093                        // A blockquote nested inside the list item is reflowed by the
2094                        // blockquote-aware path (it preserves the `>` prefix, including the
2095                        // list indent), not as list-item prose. Collecting it as Content
2096                        // would strip the markers and reflow `>` as words, collapsing the
2097                        // blank `>` line and dropping `>` from wrapped continuations. End
2098                        // the item here so the outer loop routes the blockquote line to
2099                        // generate_blockquote_paragraph_fix. Uncollect a pending blank so
2100                        // the separator between the list prose and the blockquote survives.
2101                        if line_info.blockquote.is_some() {
2102                            has_trailing_nested_structure = true;
2103                            if matches!(list_item_lines.last(), Some(LineType::Empty)) {
2104                                list_item_lines.pop();
2105                                i -= 1;
2106                            }
2107                            break;
2108                        }
2109
2110                        // Check if this is a SIBLING list item (breaks parent)
2111                        // Nested lists are indented >= marker_len and are PART of the parent item
2112                        // Siblings are at indent < marker_len (at or before parent marker)
2113                        if is_list_item(trimmed) && indent < marker_len {
2114                            // This is a sibling item at same or higher level - end parent item
2115                            break;
2116                        }
2117
2118                        // Nested list items are always processed independently
2119                        // by the outer loop, so break when we encounter one.
2120                        // If a blank line was collected before this, uncollect it
2121                        // so the outer loop preserves the blank between parent and nested.
2122                        if is_list_item(trimmed) && indent >= marker_len {
2123                            has_trailing_nested_structure = true;
2124                            if matches!(list_item_lines.last(), Some(LineType::Empty)) {
2125                                list_item_lines.pop();
2126                                i -= 1;
2127                            }
2128                            break;
2129                        }
2130
2131                        // Normal continuation vs indented code block.
2132                        // Use min_continuation_indent for the threshold since
2133                        // code blocks start 4 spaces beyond the expected content
2134                        // level (which is min_continuation_indent for MkDocs).
2135                        if indent <= min_continuation_indent + 3 {
2136                            // Extract content (remove indentation and trailing whitespace)
2137                            // Preserve hard breaks (2 trailing spaces) while removing excessive whitespace
2138                            // See: https://github.com/rvben/rumdl/issues/76
2139                            let content = trim_preserving_hard_break(&line_info.content(ctx.content)[indent..]);
2140
2141                            // Check if this is a div marker (::: opening or closing)
2142                            // These must be preserved on their own line, not merged into paragraphs
2143                            if line_info.is_div_marker {
2144                                list_item_lines.push(LineType::DivMarker(content));
2145                            }
2146                            // Check if this is a fence marker (opening or closing)
2147                            // These should be treated as code block lines, not paragraph content
2148                            else if is_fence_marker(&content) {
2149                                list_item_lines.push(LineType::CodeBlock(content, indent));
2150                            }
2151                            // Check if this is a semantic line (NOTE:, WARNING:, etc.)
2152                            else if is_semantic_line(&content) {
2153                                list_item_lines.push(LineType::SemanticLine(content));
2154                            }
2155                            // Check if this is a snippet block delimiter (-8<- or --8<--)
2156                            // These must be preserved on their own lines for MkDocs Snippets extension
2157                            else if is_snippet_block_delimiter(&content) {
2158                                list_item_lines.push(LineType::SnippetLine(content));
2159                            }
2160                            // Check if this is a GFM table row. Tables nested inside list
2161                            // items must be preserved verbatim — joining them with prose
2162                            // breaks the column structure.
2163                            //
2164                            // `is_potential_table_row` is intentionally permissive at the
2165                            // row level: any line with `|` and 2+ cells qualifies. To avoid
2166                            // misclassifying prose continuation lines that contain a literal
2167                            // pipe (e.g. "use grep | sort to ..."), require one of:
2168                            //   - the row is pipe-bordered (`| ... |`), the canonical form
2169                            //     for tables nested in lists; or
2170                            //   - the next line is a delimiter row (this is a header); or
2171                            //   - the previous classified line was already a Table (this is
2172                            //     a continuation row).
2173                            else if TableUtils::is_potential_table_row(&content) && {
2174                                let pipe_bordered = content.trim().starts_with('|') && content.trim().ends_with('|');
2175                                let next_is_delim = ctx
2176                                    .lines
2177                                    .get(i + 1)
2178                                    .is_some_and(|next| TableUtils::is_delimiter_row(next.content(ctx.content)));
2179                                let prev_was_table = matches!(list_item_lines.last(), Some(LineType::Table(..)));
2180                                pipe_bordered || next_is_delim || prev_was_table
2181                            } {
2182                                list_item_lines.push(LineType::Table(content, indent));
2183                            } else {
2184                                list_item_lines.push(LineType::Content(content));
2185                            }
2186                            i += 1;
2187                        } else {
2188                            // indent >= min_continuation_indent + 4: indented code block
2189                            list_item_lines.push(LineType::CodeBlock(
2190                                line_info.content(ctx.content)[indent..].to_string(),
2191                                indent,
2192                            ));
2193                            i += 1;
2194                        }
2195                    } else {
2196                        // Not indented enough, end of list item
2197                        break;
2198                    }
2199                }
2200
2201                // Determine the output continuation indent.
2202                // Normalize/Default modes canonicalize to min_continuation_indent
2203                // (fixing over-indented continuation). Semantic/SentencePerLine
2204                // modes preserve the user's actual indent since they only fix
2205                // line breaking, not indentation.
2206                let indent_size = match config.reflow_mode {
2207                    ReflowMode::SemanticLineBreaks | ReflowMode::SentencePerLine => {
2208                        // Find indent of the first plain text continuation line,
2209                        // skipping the marker line (index 0), nested list items,
2210                        // code blocks, and blank lines.
2211                        list_item_lines
2212                            .iter()
2213                            .enumerate()
2214                            .skip(1)
2215                            .find_map(|(k, lt)| {
2216                                if matches!(lt, LineType::Content(_)) {
2217                                    Some(ctx.lines[list_start + k].indent)
2218                                } else {
2219                                    None
2220                                }
2221                            })
2222                            .unwrap_or(min_continuation_indent)
2223                    }
2224                    _ => min_continuation_indent,
2225                };
2226                // For checkbox items in mkdocs flavor, enforce minimum indent so
2227                // continuation lines use the structural list indent (4), not the
2228                // content-aligned indent (6) which Python-Markdown doesn't support
2229                let has_checkbox = base_marker_len < marker_len;
2230                let indent_size = if has_checkbox && ctx.flavor.requires_strict_list_indent() {
2231                    indent_size.max(min_continuation_indent)
2232                } else {
2233                    indent_size
2234                };
2235
2236                // Split list_item_lines into blocks (paragraphs, code blocks, nested lists, semantic lines, and HTML blocks)
2237                let mut builder = BlockBuilder::new();
2238                for line in &list_item_lines {
2239                    match line {
2240                        LineType::Empty => builder.feed_blank_line(),
2241                        LineType::Content(content) => builder.feed_content(content),
2242                        LineType::CodeBlock(content, indent) => builder.feed_code_line(content, *indent),
2243                        LineType::SemanticLine(content) => builder.feed_semantic_line(content),
2244                        LineType::SnippetLine(content) => builder.feed_snippet_line(content),
2245                        LineType::DivMarker(content) => builder.feed_div_marker(content),
2246                        LineType::AdmonitionHeader(header_text, indent) => {
2247                            builder.feed_admonition_header(header_text, *indent)
2248                        }
2249                        LineType::AdmonitionContent(content, indent) => {
2250                            builder.feed_admonition_content(content, *indent)
2251                        }
2252                        LineType::Table(content, indent) => builder.feed_table_line(content, *indent),
2253                    }
2254                }
2255                let blocks = builder.finalize();
2256
2257                // Helper: check if a line (raw source or stripped content) is exempt
2258                // from line-length checks. Link reference definitions are always exempt;
2259                // standalone link/image lines are exempt when strict mode is off.
2260                // Also checks content after stripping list markers, since list item
2261                // continuation lines may contain link ref defs.
2262                let is_exempt_line = |raw_line: &str| -> bool {
2263                    let trimmed = raw_line.trim();
2264                    // Link reference definitions: always exempt
2265                    if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
2266                        return true;
2267                    }
2268                    // Also check after stripping list markers (for list item content)
2269                    if is_list_item(trimmed) {
2270                        let (_, content) = extract_list_marker_and_content(trimmed);
2271                        let content_trimmed = content.trim();
2272                        if content_trimmed.starts_with('[')
2273                            && content_trimmed.contains("]:")
2274                            && LINK_REF_PATTERN.is_match(content_trimmed)
2275                        {
2276                            return true;
2277                        }
2278                    }
2279                    // Standalone link/image lines: exempt when not strict
2280                    if !config.strict && is_standalone_link_or_image_line(raw_line) {
2281                        return true;
2282                    }
2283                    // HTML-only lines: exempt when not strict
2284                    if !config.strict && is_html_only_line(raw_line) {
2285                        return true;
2286                    }
2287                    false
2288                };
2289
2290                // Check if reflowing is needed (only for content paragraphs, not code blocks or nested lists)
2291                // Exclude link reference definitions and standalone link lines from content
2292                // so they don't pollute combined_content or trigger false reflow.
2293                let content_lines: Vec<String> = list_item_lines
2294                    .iter()
2295                    .filter_map(|line| {
2296                        if let LineType::Content(s) = line {
2297                            if is_exempt_line(s) {
2298                                return None;
2299                            }
2300                            Some(s.clone())
2301                        } else {
2302                            None
2303                        }
2304                    })
2305                    .collect();
2306
2307                // Check if we need to reflow this list item
2308                // We check the combined content to see if it exceeds length limits
2309                let combined_content = content_lines.join(" ").trim().to_string();
2310
2311                // Helper to check if we should reflow in normalize mode
2312                let should_normalize = || {
2313                    // Don't normalize if the list item only contains nested lists, code blocks, or semantic lines
2314                    // DO normalize if it has plain text content that spans multiple lines
2315                    let has_code_blocks = blocks.iter().any(|b| matches!(b, Block::Code { .. }));
2316                    let has_semantic_lines = blocks.iter().any(|b| matches!(b, Block::SemanticLine(_)));
2317                    let has_snippet_lines = blocks.iter().any(|b| matches!(b, Block::SnippetLine(_)));
2318                    let has_div_markers = blocks.iter().any(|b| matches!(b, Block::DivMarker(_)));
2319                    let has_admonitions = blocks.iter().any(|b| matches!(b, Block::Admonition { .. }));
2320                    let has_tables = blocks.iter().any(|b| matches!(b, Block::Table { .. }));
2321                    let has_paragraphs = blocks.iter().any(|b| matches!(b, Block::Paragraph(_)));
2322
2323                    // If we have structural blocks but no paragraphs, don't normalize
2324                    if (has_code_blocks
2325                        || has_semantic_lines
2326                        || has_snippet_lines
2327                        || has_div_markers
2328                        || has_admonitions
2329                        || has_tables)
2330                        && !has_paragraphs
2331                    {
2332                        return false;
2333                    }
2334
2335                    // If we have paragraphs, check if they span multiple lines or there are multiple blocks
2336                    if has_paragraphs {
2337                        // Count only paragraphs that contain at least one non-exempt line.
2338                        // Paragraphs consisting entirely of link ref defs or standalone links
2339                        // should not trigger normalization.
2340                        let paragraph_count = blocks
2341                            .iter()
2342                            .filter(|b| {
2343                                if let Block::Paragraph(para_lines) = b {
2344                                    !para_lines.iter().all(|line| is_exempt_line(line))
2345                                } else {
2346                                    false
2347                                }
2348                            })
2349                            .count();
2350                        if paragraph_count > 1 {
2351                            // Multiple non-exempt paragraph blocks should be normalized
2352                            return true;
2353                        }
2354
2355                        // Single paragraph block: normalize if it has multiple content lines
2356                        if content_lines.len() > 1 {
2357                            return true;
2358                        }
2359                    }
2360
2361                    false
2362                };
2363
2364                // Integrate MD030 list-marker spacing (and MD007's text-aligned
2365                // continuation). In Default/Normalize modes — the modes that already
2366                // canonicalize spacing/indent — derive the number of spaces after the
2367                // marker from the configured MD030 values instead of forcing a single
2368                // space, then align continuation lines to the resulting content column.
2369                // Sentence/Semantic modes only adjust line breaks, so they keep the
2370                // marker spacing and indentation already present in the source.
2371                //
2372                // With default MD030 (a single space everywhere) the rebuilt marker is
2373                // byte-identical to the source marker, so this is a no-op and existing
2374                // behaviour is preserved; only a non-default MD030 changes the output.
2375                // The MkDocs flavor enforces a rigid structural indent (4 spaces,
2376                // capped via max_list_continuation_indent) that Python-Markdown
2377                // requires; leave its specialized handling untouched.
2378                let (marker, indent_size, code_indent_shift) =
2379                    if matches!(config.reflow_mode, ReflowMode::Default | ReflowMode::Normalize)
2380                        && !ctx.flavor.requires_strict_list_indent()
2381                        && let Some(li) = ctx.lines[list_start].list_item.as_deref()
2382                    {
2383                        let bullet_len = li.marker.len();
2384                        // The checkbox (e.g. `[ ] `) is content, not part of the list
2385                        // marker MD030 governs; carry it over verbatim after the spacing.
2386                        let checkbox_tail = marker[base_marker_len..].to_string();
2387                        // Shift this item right by its ancestors' cumulative marker
2388                        // widening so a nested item stays under its parent's (widened)
2389                        // content column. Zero for top-level items and for the whole
2390                        // tree under default MD030, where the source indent is preserved
2391                        // verbatim (byte-identical output).
2392                        let ancestor_shift = list_shift_stack.last().map_or(0isize, |&(_, shift)| shift);
2393                        let shifted_indent = (item_indent as isize + ancestor_shift).max(0) as usize;
2394                        let indent_prefix = if ancestor_shift == 0 {
2395                            marker[..item_indent].to_string()
2396                        } else {
2397                            " ".repeat(shifted_indent)
2398                        };
2399
2400                        // Decide single- vs multi-line spacing from the *rewritten* shape,
2401                        // not the source. A multi-line source is not enough: plain prose
2402                        // continuation collapses onto the marker line during reflow, so a
2403                        // two-line bullet that fits becomes a single physical line and must
2404                        // use MD030's single-line spacing (otherwise MD013 emits a result
2405                        // that MD030 immediately rewrites). The emitted item stays
2406                        // multi-line only when reflow cannot collapse it:
2407                        //   - the prose wraps past the line length, or
2408                        //   - a structural block remains (code, table, admonition, semantic
2409                        //     line, snippet, div marker, HTML) that is not joinable prose, or
2410                        //   - more than one paragraph remains (blank-separated), or
2411                        //   - a nested list/blockquote follows (reflowed independently, so it
2412                        //     is absent from `blocks` but still keeps the item multi-line).
2413                        // The wrap test uses the single-line content column so it is
2414                        // independent of the spacing we are about to choose (avoiding a
2415                        // circular result). `ol-align-column` ignores this flag entirely in
2416                        // expected_spaces(), so ordered lists are unaffected.
2417                        //
2418                        // This is the rewritten-shape counterpart of MD030's
2419                        // `is_multi_line_list_item` (which keys off the *source*). The two
2420                        // are related but technically distinct and intentionally separate;
2421                        // if the notion of "multi-line" changes in one, revisit the other.
2422                        let single_col = shifted_indent
2423                            + bullet_len
2424                            + self.list_spacing.expected_spaces(li.is_ordered, false, bullet_len)
2425                            + checkbox_tail.len();
2426                        let prose_wraps = !combined_content.is_empty()
2427                            && self
2428                                .calculate_effective_length(&format!("{}{combined_content}", " ".repeat(single_col)))
2429                                > config.line_length.effective_limit();
2430                        let has_structural_block = blocks.iter().any(|b| !matches!(b, Block::Paragraph(_)));
2431                        let multiple_paragraphs =
2432                            blocks.iter().filter(|b| matches!(b, Block::Paragraph(_))).count() > 1;
2433                        let is_multi =
2434                            prose_wraps || has_structural_block || multiple_paragraphs || has_trailing_nested_structure;
2435
2436                        let spaces = self.list_spacing.expected_spaces(li.is_ordered, is_multi, bullet_len);
2437                        let new_marker = format!("{indent_prefix}{}{}{checkbox_tail}", li.marker, " ".repeat(spaces));
2438                        let new_col = new_marker.chars().count();
2439                        let shift = new_col as isize - source_content_col as isize;
2440                        (new_marker, new_col, shift)
2441                    } else {
2442                        // MkDocs enforces a rigid structural indent, so the item is emitted
2443                        // exactly as written and its nested blocks never move. Re-emitting
2444                        // the normalized marker here would narrow the content column while
2445                        // leaving those blocks behind.
2446                        let marker = source_marker.map_or(marker, |m| m.text);
2447                        (marker, indent_size, 0isize)
2448                    };
2449                let expected_indent = " ".repeat(indent_size);
2450
2451                let needs_reflow = match config.reflow_mode {
2452                    ReflowMode::Normalize => {
2453                        // Only reflow if:
2454                        // 1. Any non-exempt paragraph, when joined, exceeds the limit, OR
2455                        // 2. Any admonition content line exceeds the limit, OR
2456                        // 3. The list item should be normalized (has multi-line plain text)
2457                        let any_paragraph_exceeds = blocks.iter().any(|block| match block {
2458                            Block::Paragraph(para_lines) => {
2459                                if para_lines.iter().all(|line| is_exempt_line(line)) {
2460                                    return false;
2461                                }
2462                                let joined = para_lines.join(" ");
2463                                let with_marker = format!("{}{}", " ".repeat(indent_size), joined.trim());
2464                                self.calculate_effective_length(&with_marker) > config.line_length.get()
2465                            }
2466                            Block::Admonition {
2467                                content_lines,
2468                                header_indent,
2469                                ..
2470                            } => content_lines.iter().any(|(content, indent)| {
2471                                if content.is_empty() {
2472                                    return false;
2473                                }
2474                                let with_indent = format!("{}{}", " ".repeat(*indent.max(header_indent)), content);
2475                                self.calculate_effective_length(&with_indent) > config.line_length.get()
2476                            }),
2477                            _ => false,
2478                        });
2479                        if any_paragraph_exceeds {
2480                            true
2481                        } else {
2482                            should_normalize()
2483                        }
2484                    }
2485                    ReflowMode::SentencePerLine => {
2486                        // Check if list item has multiple sentences
2487                        let sentences = split_into_sentences(&combined_content);
2488                        sentences.len() > 1
2489                    }
2490                    ReflowMode::SemanticLineBreaks => {
2491                        let sentences = split_into_sentences(&combined_content);
2492                        sentences.len() > 1
2493                            || (list_start..i).any(|line_idx| {
2494                                let line = lines[line_idx];
2495                                let trimmed = line.trim();
2496                                if trimmed.is_empty() || is_exempt_line(line) {
2497                                    return false;
2498                                }
2499                                self.calculate_effective_length(line) > config.line_length.get()
2500                            })
2501                    }
2502                    ReflowMode::Default => {
2503                        // In default mode, only reflow if any individual non-exempt line exceeds limit
2504                        (list_start..i).any(|line_idx| {
2505                            let line = lines[line_idx];
2506                            let trimmed = line.trim();
2507                            // Skip blank lines and exempt lines
2508                            if trimmed.is_empty() || is_exempt_line(line) {
2509                                return false;
2510                            }
2511                            self.calculate_effective_length(line) > config.line_length.get()
2512                        })
2513                    }
2514                };
2515
2516                // Record this item's frame so its nested children inherit the shift.
2517                // Only a reflowed item's marker actually moves; an unreflowed one keeps
2518                // its source position and so contributes no shift to its children. The
2519                // threshold that decides which following lines are inside this item is
2520                // the normalized marker width, NOT `source_content_col`: the collection
2521                // loop above gathers continuations by that same width, so the frame
2522                // boundary must match it or the two would disagree about ownership of
2523                // lines indented between the normalized and the source content column.
2524                list_shift_stack.push((marker_len, if needs_reflow { code_indent_shift } else { 0 }));
2525
2526                if needs_reflow {
2527                    let start_range = line_index.whole_line_range(list_start + 1);
2528                    let end_line = i - 1;
2529                    let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
2530                        line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
2531                    } else {
2532                        line_index.whole_line_range(end_line + 1)
2533                    };
2534                    let byte_range = start_range.start..end_range.end;
2535
2536                    // Reflow each block (paragraphs only, preserve code blocks)
2537                    // When line_length = 0 (no limit), use a very large value for reflow
2538                    let reflow_line_length = if config.line_length.is_unlimited() {
2539                        usize::MAX
2540                    } else {
2541                        config.line_length.get().saturating_sub(indent_size).max(1)
2542                    };
2543                    let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
2544
2545                    let mut result: Vec<String> = Vec::new();
2546                    let mut is_first_block = true;
2547
2548                    for (block_idx, block) in blocks.iter().enumerate() {
2549                        match block {
2550                            Block::Paragraph(para_lines) => {
2551                                // If every line in this paragraph is exempt (link ref defs,
2552                                // standalone links), preserve the paragraph verbatim instead
2553                                // of reflowing it. Reflowing would corrupt link ref defs.
2554                                let all_exempt = para_lines.iter().all(|line| is_exempt_line(line));
2555
2556                                if all_exempt {
2557                                    for (idx, line) in para_lines.iter().enumerate() {
2558                                        if is_first_block && idx == 0 {
2559                                            result.push(format!("{marker}{line}"));
2560                                            is_first_block = false;
2561                                        } else {
2562                                            result.push(format!("{expected_indent}{line}"));
2563                                        }
2564                                    }
2565                                } else {
2566                                    // Split the paragraph into segments at hard break boundaries
2567                                    // Each segment can be reflowed independently
2568                                    let segments = split_into_segments(para_lines);
2569
2570                                    for (segment_idx, segment) in segments.iter().enumerate() {
2571                                        // Check if this segment ends with a hard break and what type
2572                                        let hard_break_type = segment.last().and_then(|line| {
2573                                            let line = line.strip_suffix('\r').unwrap_or(line);
2574                                            if line.ends_with('\\') {
2575                                                Some("\\")
2576                                            } else if line.ends_with("  ") {
2577                                                Some("  ")
2578                                            } else {
2579                                                None
2580                                            }
2581                                        });
2582
2583                                        // Join and reflow the segment (removing the hard break marker for processing)
2584                                        let segment_for_reflow: Vec<String> = segment
2585                                            .iter()
2586                                            .map(|line| {
2587                                                // Strip hard break marker (2 spaces or backslash) for reflow processing
2588                                                if line.ends_with('\\') {
2589                                                    line[..line.len() - 1].trim_end().to_string()
2590                                                } else if line.ends_with("  ") {
2591                                                    line[..line.len() - 2].trim_end().to_string()
2592                                                } else {
2593                                                    line.clone()
2594                                                }
2595                                            })
2596                                            .collect();
2597
2598                                        let segment_text = segment_for_reflow.join(" ").trim().to_string();
2599                                        if !segment_text.is_empty() {
2600                                            let reflowed =
2601                                                crate::utils::text_reflow::reflow_line(&segment_text, &reflow_options);
2602
2603                                            if is_first_block && segment_idx == 0 {
2604                                                // First segment of first block starts with marker
2605                                                result.push(format!("{marker}{}", reflowed[0]));
2606                                                for line in reflowed.iter().skip(1) {
2607                                                    result.push(format!("{expected_indent}{line}"));
2608                                                }
2609                                                is_first_block = false;
2610                                            } else {
2611                                                // Subsequent segments
2612                                                for line in reflowed {
2613                                                    result.push(format!("{expected_indent}{line}"));
2614                                                }
2615                                            }
2616
2617                                            // If this segment had a hard break, add it back to the last line
2618                                            // Preserve the original hard break format (backslash or two spaces)
2619                                            if let Some(break_marker) = hard_break_type
2620                                                && let Some(last_line) = result.last_mut()
2621                                            {
2622                                                last_line.push_str(break_marker);
2623                                            }
2624                                        }
2625                                    }
2626                                }
2627
2628                                // Add blank line after paragraph block if there's a next block.
2629                                // Check if next block is a code block that doesn't want a preceding blank.
2630                                // Also don't add blank lines before snippet lines (they should stay tight).
2631                                // Only add if not already ending with one (avoids double blanks).
2632                                if block_idx < blocks.len() - 1 {
2633                                    let next_block = &blocks[block_idx + 1];
2634                                    let should_add_blank = match next_block {
2635                                        Block::Code {
2636                                            has_preceding_blank, ..
2637                                        } => *has_preceding_blank,
2638                                        Block::Table {
2639                                            has_preceding_blank, ..
2640                                        } => *has_preceding_blank,
2641                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2642                                        _ => true, // For all other blocks, add blank line
2643                                    };
2644                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2645                                        result.push(String::new());
2646                                    }
2647                                }
2648                            }
2649                            Block::Code {
2650                                lines: code_lines,
2651                                has_preceding_blank: _,
2652                            } => {
2653                                // Preserve code blocks as-is with original indentation
2654                                // NOTE: Blank line before code block is handled by the previous block
2655                                // (see paragraph block's logic above)
2656
2657                                for (idx, (content, orig_indent)) in code_lines.iter().enumerate() {
2658                                    if is_first_block && idx == 0 {
2659                                        // First line of first block gets marker
2660                                        result.push(format!(
2661                                            "{marker}{}",
2662                                            " ".repeat(orig_indent - marker_len) + content.as_str()
2663                                        ));
2664                                        is_first_block = false;
2665                                    } else if content.is_empty() {
2666                                        result.push(String::new());
2667                                    } else {
2668                                        // Shift nested code with the marker so it stays
2669                                        // aligned under content when MD030 widens spacing.
2670                                        result.push(format!(
2671                                            "{}{}",
2672                                            " ".repeat((*orig_indent as isize + code_indent_shift).max(0) as usize),
2673                                            content
2674                                        ));
2675                                    }
2676                                }
2677                            }
2678                            Block::SemanticLine(content) => {
2679                                // Preserve semantic lines (NOTE:, WARNING:, etc.) as-is on their own line.
2680                                // Only add blank before if not already ending with one.
2681                                if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2682                                    result.push(String::new());
2683                                }
2684
2685                                if is_first_block {
2686                                    // First block starts with marker
2687                                    result.push(format!("{marker}{content}"));
2688                                    is_first_block = false;
2689                                } else {
2690                                    // Subsequent blocks use expected indent
2691                                    result.push(format!("{expected_indent}{content}"));
2692                                }
2693
2694                                // Add blank line after semantic line if there's a next block.
2695                                // Only add if not already ending with one.
2696                                if block_idx < blocks.len() - 1 {
2697                                    let next_block = &blocks[block_idx + 1];
2698                                    let should_add_blank = match next_block {
2699                                        Block::Code {
2700                                            has_preceding_blank, ..
2701                                        } => *has_preceding_blank,
2702                                        Block::Table {
2703                                            has_preceding_blank, ..
2704                                        } => *has_preceding_blank,
2705                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2706                                        _ => true, // For all other blocks, add blank line
2707                                    };
2708                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2709                                        result.push(String::new());
2710                                    }
2711                                }
2712                            }
2713                            Block::SnippetLine(content) => {
2714                                // Preserve snippet delimiters (-8<-) as-is on their own line
2715                                // Unlike semantic lines, snippet lines don't add extra blank lines
2716                                if is_first_block {
2717                                    // First block starts with marker
2718                                    result.push(format!("{marker}{content}"));
2719                                    is_first_block = false;
2720                                } else {
2721                                    // Subsequent blocks use expected indent
2722                                    result.push(format!("{expected_indent}{content}"));
2723                                }
2724                                // No blank lines added before or after snippet delimiters
2725                            }
2726                            Block::DivMarker(content) => {
2727                                // Preserve div markers (::: opening or closing) as-is on their own line
2728                                if is_first_block {
2729                                    result.push(format!("{marker}{content}"));
2730                                    is_first_block = false;
2731                                } else {
2732                                    result.push(format!("{expected_indent}{content}"));
2733                                }
2734                            }
2735                            Block::Html {
2736                                lines: html_lines,
2737                                has_preceding_blank: _,
2738                            } => {
2739                                // Preserve HTML blocks exactly as-is with original indentation
2740                                // NOTE: Blank line before HTML block is handled by the previous block
2741
2742                                for (idx, line) in html_lines.iter().enumerate() {
2743                                    if is_first_block && idx == 0 {
2744                                        // First line of first block gets marker
2745                                        result.push(format!("{marker}{line}"));
2746                                        is_first_block = false;
2747                                    } else if line.is_empty() {
2748                                        // Preserve blank lines inside HTML blocks
2749                                        result.push(String::new());
2750                                    } else {
2751                                        // Preserve lines with their original content (already includes indentation)
2752                                        result.push(format!("{expected_indent}{line}"));
2753                                    }
2754                                }
2755
2756                                // Add blank line after HTML block if there's a next block.
2757                                // Only add if not already ending with one (avoids double blanks
2758                                // when the HTML block itself contained a trailing blank line).
2759                                if block_idx < blocks.len() - 1 {
2760                                    let next_block = &blocks[block_idx + 1];
2761                                    let should_add_blank = match next_block {
2762                                        Block::Code {
2763                                            has_preceding_blank, ..
2764                                        } => *has_preceding_blank,
2765                                        Block::Html {
2766                                            has_preceding_blank, ..
2767                                        } => *has_preceding_blank,
2768                                        Block::Table {
2769                                            has_preceding_blank, ..
2770                                        } => *has_preceding_blank,
2771                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2772                                        _ => true, // For all other blocks, add blank line
2773                                    };
2774                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2775                                        result.push(String::new());
2776                                    }
2777                                }
2778                            }
2779                            Block::Table {
2780                                lines: table_lines,
2781                                has_preceding_blank: _,
2782                            } => {
2783                                // Preserve table rows verbatim with their original indentation.
2784                                // Reflowing rows would corrupt column alignment and inject `|`
2785                                // characters mid-paragraph (issue #590).
2786                                // The leading blank line is emitted by the previous block.
2787                                for (idx, (content, orig_indent)) in table_lines.iter().enumerate() {
2788                                    if is_first_block && idx == 0 {
2789                                        // First line of first block gets the list marker
2790                                        result.push(format!(
2791                                            "{marker}{}",
2792                                            " ".repeat(orig_indent.saturating_sub(marker_len)) + content.as_str()
2793                                        ));
2794                                        is_first_block = false;
2795                                    } else {
2796                                        // Shift nested table rows with the marker so they
2797                                        // stay aligned when MD030 widens marker spacing.
2798                                        result.push(format!(
2799                                            "{}{}",
2800                                            " ".repeat((*orig_indent as isize + code_indent_shift).max(0) as usize),
2801                                            content
2802                                        ));
2803                                    }
2804                                }
2805
2806                                // Add blank line after table block if there's a next block.
2807                                if block_idx < blocks.len() - 1 {
2808                                    let next_block = &blocks[block_idx + 1];
2809                                    let should_add_blank = match next_block {
2810                                        Block::Code {
2811                                            has_preceding_blank, ..
2812                                        } => *has_preceding_blank,
2813                                        Block::Html {
2814                                            has_preceding_blank, ..
2815                                        } => *has_preceding_blank,
2816                                        Block::Table {
2817                                            has_preceding_blank, ..
2818                                        } => *has_preceding_blank,
2819                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2820                                        _ => true,
2821                                    };
2822                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2823                                        result.push(String::new());
2824                                    }
2825                                }
2826                            }
2827                            Block::Admonition {
2828                                header,
2829                                header_indent,
2830                                content_lines: admon_lines,
2831                            } => {
2832                                // Reconstruct admonition block with header at original indent
2833                                // and body content reflowed to fit within the line length limit
2834
2835                                // Add blank line before admonition if not first block
2836                                if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2837                                    result.push(String::new());
2838                                }
2839
2840                                // Output the header at its original indent
2841                                let header_indent_str = " ".repeat(*header_indent);
2842                                if is_first_block {
2843                                    result.push(format!(
2844                                        "{marker}{}",
2845                                        " ".repeat(header_indent.saturating_sub(marker_len)) + header.as_str()
2846                                    ));
2847                                    is_first_block = false;
2848                                } else {
2849                                    result.push(format!("{header_indent_str}{header}"));
2850                                }
2851
2852                                // Derive body indent from the first non-empty content line's
2853                                // stored indent, falling back to header_indent + 4 for
2854                                // empty-body admonitions
2855                                let body_indent = admon_lines
2856                                    .iter()
2857                                    .find(|(content, _)| !content.is_empty())
2858                                    .map_or(header_indent + 4, |(_, indent)| *indent);
2859                                let body_indent_str = " ".repeat(body_indent);
2860
2861                                // Segment body content into code blocks (verbatim) and
2862                                // text paragraphs (reflowable), separated by blank lines.
2863                                // Code lines store (content, orig_indent) to reconstruct
2864                                // internal indentation relative to body_indent.
2865                                enum AdmonSegment {
2866                                    Text(Vec<String>),
2867                                    Code(Vec<(String, usize)>),
2868                                }
2869
2870                                let mut segments: Vec<AdmonSegment> = Vec::new();
2871                                let mut current_text: Vec<String> = Vec::new();
2872                                let mut current_code: Vec<(String, usize)> = Vec::new();
2873                                let mut in_admon_code = false;
2874                                // Track the opening fence character so closing fences
2875                                // must match (backticks close backticks, tildes close tildes)
2876                                let mut fence_char: char = '`';
2877
2878                                // Opening fences: ``` or ~~~ followed by optional info string
2879                                let get_opening_fence = |s: &str| -> Option<(char, usize)> {
2880                                    let t = s.trim_start();
2881                                    if t.starts_with("```") {
2882                                        Some(('`', t.bytes().take_while(|&b| b == b'`').count()))
2883                                    } else if t.starts_with("~~~") {
2884                                        Some(('~', t.bytes().take_while(|&b| b == b'~').count()))
2885                                    } else {
2886                                        None
2887                                    }
2888                                };
2889                                // Closing fences: ONLY fence chars + optional trailing spaces
2890                                let get_closing_fence = |s: &str| -> Option<(char, usize)> {
2891                                    let t = s.trim();
2892                                    if t.starts_with("```") && t.bytes().all(|b| b == b'`') {
2893                                        Some(('`', t.len()))
2894                                    } else if t.starts_with("~~~") && t.bytes().all(|b| b == b'~') {
2895                                        Some(('~', t.len()))
2896                                    } else {
2897                                        None
2898                                    }
2899                                };
2900                                let mut fence_len: usize = 3;
2901
2902                                for (content, orig_indent) in admon_lines {
2903                                    if in_admon_code {
2904                                        // Closing fence must use the same character, be
2905                                        // at least as long, and have no info string
2906                                        if let Some((ch, len)) = get_closing_fence(content)
2907                                            && ch == fence_char
2908                                            && len >= fence_len
2909                                        {
2910                                            current_code.push((content.clone(), *orig_indent));
2911                                            in_admon_code = false;
2912                                            segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2913                                            continue;
2914                                        }
2915                                        current_code.push((content.clone(), *orig_indent));
2916                                    } else if let Some((ch, len)) = get_opening_fence(content) {
2917                                        if !current_text.is_empty() {
2918                                            segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2919                                        }
2920                                        in_admon_code = true;
2921                                        fence_char = ch;
2922                                        fence_len = len;
2923                                        current_code.push((content.clone(), *orig_indent));
2924                                    } else if content.is_empty() {
2925                                        if !current_text.is_empty() {
2926                                            segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2927                                        }
2928                                    } else {
2929                                        current_text.push(content.clone());
2930                                    }
2931                                }
2932                                if in_admon_code && !current_code.is_empty() {
2933                                    segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2934                                }
2935                                if !current_text.is_empty() {
2936                                    segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2937                                }
2938
2939                                // Build reflow options once for all text segments
2940                                let admon_reflow_length = if config.line_length.is_unlimited() {
2941                                    usize::MAX
2942                                } else {
2943                                    config.line_length.get().saturating_sub(body_indent).max(1)
2944                                };
2945
2946                                let admon_reflow_options = Self::reflow_options(ctx, config, admon_reflow_length);
2947
2948                                // Output each segment
2949                                for segment in &segments {
2950                                    // Blank line before each segment (after the header or previous segment)
2951                                    result.push(String::new());
2952
2953                                    match segment {
2954                                        AdmonSegment::Code(lines) => {
2955                                            for (line, orig_indent) in lines {
2956                                                if line.is_empty() {
2957                                                    // Preserve blank lines inside code blocks
2958                                                    result.push(String::new());
2959                                                } else {
2960                                                    // Reconstruct with body_indent + any extra
2961                                                    // indentation the line had beyond body_indent
2962                                                    let extra = orig_indent.saturating_sub(body_indent);
2963                                                    let indent_str = " ".repeat(body_indent + extra);
2964                                                    result.push(format!("{indent_str}{line}"));
2965                                                }
2966                                            }
2967                                        }
2968                                        AdmonSegment::Text(lines) => {
2969                                            let paragraph_text = lines.join(" ").trim().to_string();
2970                                            if paragraph_text.is_empty() {
2971                                                continue;
2972                                            }
2973                                            let reflowed = crate::utils::text_reflow::reflow_line(
2974                                                &paragraph_text,
2975                                                &admon_reflow_options,
2976                                            );
2977                                            for line in &reflowed {
2978                                                result.push(format!("{body_indent_str}{line}"));
2979                                            }
2980                                        }
2981                                    }
2982                                }
2983
2984                                // Add blank line after admonition if there's a next block
2985                                if block_idx < blocks.len() - 1 {
2986                                    let next_block = &blocks[block_idx + 1];
2987                                    let should_add_blank = match next_block {
2988                                        Block::Code {
2989                                            has_preceding_blank, ..
2990                                        } => *has_preceding_blank,
2991                                        Block::Table {
2992                                            has_preceding_blank, ..
2993                                        } => *has_preceding_blank,
2994                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2995                                        _ => true,
2996                                    };
2997                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2998                                        result.push(String::new());
2999                                    }
3000                                }
3001                            }
3002                        }
3003                    }
3004
3005                    let reflowed_text = result.join(line_ending);
3006
3007                    // Preserve trailing newline
3008                    let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
3009                        format!("{reflowed_text}{line_ending}")
3010                    } else {
3011                        reflowed_text
3012                    };
3013
3014                    // Get the original text to compare
3015                    let original_text = &ctx.content[byte_range.clone()];
3016
3017                    // Physical-line-length scan, shared by the Normalize-mode gate and its
3018                    // message. The list-item reflow preserves code blocks, HTML blocks,
3019                    // admonition headers, fence markers, semantic markers, and snippet/div
3020                    // markers verbatim; only paragraph content and admonition bodies are
3021                    // restructured. Only those lines drive the length warning, so that
3022                    // preserved-but-overlong content does not keep the paragraph-level
3023                    // warning alive when the reflow would not fix that line.
3024                    let should_count_for_length = |line_idx: usize| -> bool {
3025                        let line = lines[line_idx];
3026                        let trimmed = line.trim();
3027                        if trimmed.is_empty() || is_exempt_line(line) {
3028                            return false;
3029                        }
3030                        let info = &ctx.lines[line_idx];
3031                        if info.in_code_block || info.in_html_block {
3032                            return false;
3033                        }
3034                        if info.in_admonition && mkdocs_admonitions::is_admonition_start(line) {
3035                            return false;
3036                        }
3037                        if is_fence_marker(line) || is_semantic_line(line) {
3038                            return false;
3039                        }
3040                        if is_snippet_block_delimiter(line) {
3041                            return false;
3042                        }
3043                        if line.trim_start().starts_with(":::") {
3044                            return false;
3045                        }
3046                        true
3047                    };
3048                    let max_physical_length = (list_start..i)
3049                        .filter(|&idx| should_count_for_length(idx))
3050                        .map(|idx| self.calculate_effective_length(lines[idx]))
3051                        .max()
3052                        .unwrap_or(0);
3053                    // `line-length = 0` means "no limit", so no physical line can be
3054                    // "over"; the message below then describes a structural join rather
3055                    // than a length violation.
3056                    let any_paragraph_line_over =
3057                        !config.line_length.is_unlimited() && max_physical_length > config.line_length.get();
3058
3059                    // Normalize mode reflows list-item prose just like paragraphs:
3060                    // joining continuation lines and re-wrapping to `line-length`.
3061                    // `prose_changed` is true only when the reflow alters the words or
3062                    // line breaks, not when it would merely re-indent continuation
3063                    // lines or trim trailing whitespace. Comparing the texts with each
3064                    // line's leading and trailing whitespace removed isolates "did the
3065                    // words/line breaks change" from "did the surrounding whitespace
3066                    // change". Continuation indentation is MD077's responsibility and
3067                    // trailing whitespace is MD009's; an MD013 warning for either would
3068                    // both duplicate those rules and resurface a persistent advisory on
3069                    // already-fitting items that users disable MD013 fixing to avoid.
3070                    let prose_changed = {
3071                        let stripped = |text: &str| text.lines().map(str::trim).collect::<Vec<_>>().join("\n");
3072                        stripped(original_text) != stripped(&replacement)
3073                    };
3074                    // Warn when the reflow rewraps prose (the normalize feature for
3075                    // list items), or when a physical line genuinely exceeds the limit
3076                    // and the reflow can change something (a true length violation,
3077                    // even if all that changes is the continuation indent). A line that
3078                    // is already optimal in both respects produces no warning.
3079                    let gate_ok = prose_changed || (any_paragraph_line_over && original_text != replacement);
3080                    if gate_ok {
3081                        // Generate an appropriate message based on why reflow is needed
3082                        let message = match config.reflow_mode {
3083                            ReflowMode::SentencePerLine => {
3084                                let num_sentences = split_into_sentences(&combined_content).len();
3085                                let num_lines = content_lines.len();
3086                                if num_lines == 1 {
3087                                    // Single line with multiple sentences
3088                                    format!("Line contains {num_sentences} sentences (one sentence per line required)")
3089                                } else {
3090                                    // Multiple lines - could be split sentences or mixed
3091                                    format!(
3092                                        "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
3093                                    )
3094                                }
3095                            }
3096                            ReflowMode::SemanticLineBreaks => {
3097                                let num_sentences = split_into_sentences(&combined_content).len();
3098                                format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
3099                            }
3100                            ReflowMode::Normalize => {
3101                                // When a physical line genuinely exceeds the limit, report
3102                                // it as a length violation. Otherwise the reflow is a
3103                                // structural normalization (joining/re-wrapping multi-line
3104                                // content that already fits), mirroring the paragraph path.
3105                                if any_paragraph_line_over {
3106                                    format!(
3107                                        "Line length {} exceeds {} characters",
3108                                        max_physical_length,
3109                                        config.line_length.get()
3110                                    )
3111                                } else {
3112                                    format!(
3113                                        "List item could be normalized to use line length of {} characters",
3114                                        config.line_length.get()
3115                                    )
3116                                }
3117                            }
3118                            ReflowMode::Default => {
3119                                // Report the actual longest non-exempt line, not the combined content
3120                                let max_length = (list_start..i)
3121                                    .filter(|&line_idx| {
3122                                        let line = lines[line_idx];
3123                                        let trimmed = line.trim();
3124                                        !trimmed.is_empty() && !is_exempt_line(line)
3125                                    })
3126                                    .map(|line_idx| self.calculate_effective_length(lines[line_idx]))
3127                                    .max()
3128                                    .unwrap_or(0);
3129                                format!(
3130                                    "Line length {} exceeds {} characters",
3131                                    max_length,
3132                                    config.line_length.get()
3133                                )
3134                            }
3135                        };
3136
3137                        warnings.push(LintWarning {
3138                            rule_name: Some(self.name().to_string()),
3139                            message,
3140                            line: list_start + 1,
3141                            column: 1,
3142                            end_line: end_line + 1,
3143                            end_column: lines[end_line].chars().count() + 1,
3144                            severity: Severity::Warning,
3145                            fix: Some(crate::rule::Fix::new(byte_range, replacement)),
3146                        });
3147                    }
3148                }
3149                continue;
3150            }
3151
3152            // Found start of a paragraph - collect all lines in it
3153            let paragraph_start = i;
3154            let mut paragraph_lines = vec![lines[i]];
3155            i += 1;
3156
3157            while i < lines.len() {
3158                let next_line = lines[i];
3159                let next_line_num = i + 1;
3160                let next_trimmed = next_line.trim();
3161
3162                // Stop at paragraph boundaries
3163                if next_trimmed.is_empty()
3164                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_code_block)
3165                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_front_matter)
3166                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_block)
3167                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_comment)
3168                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_esm_block)
3169                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_expression)
3170                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_block)
3171                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_mdx_comment)
3172                    || ctx
3173                        .line_info(next_line_num)
3174                        .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container)
3175                    || (next_line_num > 0
3176                        && next_line_num <= ctx.lines.len()
3177                        && ctx.lines[next_line_num - 1].blockquote.is_some())
3178                    || next_trimmed.starts_with('#')
3179                    || TableUtils::is_potential_table_row(next_line)
3180                    || is_list_item(next_trimmed)
3181                    || is_horizontal_rule(next_line)
3182                    || (next_trimmed.starts_with('[') && next_line.contains("]:"))
3183                    || is_template_directive_only(next_line)
3184                    || is_standalone_attr_list(next_line)
3185                    || is_snippet_block_delimiter(next_line)
3186                    || ctx.line_info(next_line_num).is_some_and(|info| info.is_div_marker)
3187                    || is_html_only_line(next_line)
3188                    || (!config.strict && is_standalone_link_or_image_line(next_line))
3189                {
3190                    break;
3191                }
3192
3193                // Check if the previous line ends with a hard break (2+ spaces or backslash)
3194                if i > 0 && has_hard_break(lines[i - 1]) {
3195                    // Don't include lines after hard breaks in the same paragraph
3196                    break;
3197                }
3198
3199                paragraph_lines.push(next_line);
3200                i += 1;
3201            }
3202
3203            // Compute the common leading indent of all non-empty paragraph lines,
3204            // but only when those lines are structurally inside a list block.
3205            // Indented continuation lines that follow a nested list arrive here
3206            // with their structural indentation intact (e.g. 2 spaces for a
3207            // top-level list item). Stripping the indent before reflow and
3208            // re-applying it afterward prevents the fixer from moving those
3209            // lines to column 0.
3210            //
3211            // The list-block guard is essential: top-level paragraphs that happen
3212            // to start with spaces (insignificant in Markdown) must NOT have those
3213            // spaces preserved or injected by the fixer.
3214            let common_indent: String = if ctx.is_in_list_block(paragraph_start + 1) {
3215                let min_len = paragraph_lines
3216                    .iter()
3217                    .filter(|l| !l.trim().is_empty())
3218                    .map(|l| l.len() - l.trim_start().len())
3219                    .min()
3220                    .unwrap_or(0);
3221                paragraph_lines
3222                    .iter()
3223                    .find(|l| !l.trim().is_empty())
3224                    .map(|l| l[..min_len].to_string())
3225                    .unwrap_or_default()
3226            } else {
3227                String::new()
3228            };
3229
3230            // Combine paragraph lines into a single string for processing.
3231            // This must be done BEFORE the needs_reflow check for sentence-per-line mode.
3232            let paragraph_text = if common_indent.is_empty() {
3233                paragraph_lines.join(" ")
3234            } else {
3235                paragraph_lines
3236                    .iter()
3237                    .map(|l| {
3238                        if l.starts_with(common_indent.as_str()) {
3239                            &l[common_indent.len()..]
3240                        } else {
3241                            l.trim_start()
3242                        }
3243                    })
3244                    .collect::<Vec<_>>()
3245                    .join(" ")
3246            };
3247
3248            // Skip reflowing if this paragraph contains definition list items
3249            // Definition lists are multi-line structures that should not be joined
3250            let contains_definition_list = paragraph_lines
3251                .iter()
3252                .any(|line| crate::utils::is_definition_list_item(line));
3253
3254            if contains_definition_list {
3255                // Don't reflow definition lists - skip this paragraph
3256                i = paragraph_start + paragraph_lines.len();
3257                continue;
3258            }
3259
3260            // Skip reflowing if this paragraph contains MkDocs Snippets markers
3261            // Snippets blocks (-8<- ... -8<-) should be preserved exactly
3262            let contains_snippets = paragraph_lines.iter().any(|line| is_snippet_block_delimiter(line));
3263
3264            if contains_snippets {
3265                // Don't reflow Snippets blocks - skip this paragraph
3266                i = paragraph_start + paragraph_lines.len();
3267                continue;
3268            }
3269
3270            // Check if this paragraph needs reflowing
3271            let needs_reflow = match config.reflow_mode {
3272                ReflowMode::Normalize => self.normalize_mode_needs_reflow(paragraph_lines.iter().copied(), config),
3273                ReflowMode::SentencePerLine => {
3274                    // In sentence-per-line mode, check if the JOINED paragraph has multiple sentences
3275                    // Note: we check the joined text because sentences can span multiple lines
3276                    let sentences = split_into_sentences(&paragraph_text);
3277
3278                    // Always reflow if multiple sentences on one line
3279                    if sentences.len() > 1 {
3280                        true
3281                    } else if paragraph_lines.len() > 1 {
3282                        // For single-sentence paragraphs spanning multiple lines:
3283                        // Reflow if they COULD fit on one line (respecting line-length constraint)
3284                        if config.line_length.is_unlimited() {
3285                            // No line-length constraint - always join single sentences
3286                            true
3287                        } else {
3288                            // Only join if it fits within line-length.
3289                            // paragraph_text has the common indent stripped, so add it
3290                            // back to get the true output length before comparing.
3291                            let effective_length =
3292                                self.calculate_effective_length(&paragraph_text) + common_indent.len();
3293                            effective_length <= config.line_length.get()
3294                        }
3295                    } else {
3296                        false
3297                    }
3298                }
3299                ReflowMode::SemanticLineBreaks => {
3300                    let sentences = split_into_sentences(&paragraph_text);
3301                    // Reflow if multiple sentences, multiple lines, or any line exceeds limit
3302                    sentences.len() > 1
3303                        || paragraph_lines.len() > 1
3304                        || paragraph_lines
3305                            .iter()
3306                            .any(|line| self.calculate_effective_length(line) > config.line_length.get())
3307                }
3308                ReflowMode::Default => {
3309                    // In default mode, only reflow if lines exceed limit
3310                    paragraph_lines
3311                        .iter()
3312                        .any(|line| self.calculate_effective_length(line) > config.line_length.get())
3313                }
3314            };
3315
3316            if needs_reflow {
3317                // Calculate byte range for this paragraph
3318                // Use whole_line_range for each line and combine
3319                let start_range = line_index.whole_line_range(paragraph_start + 1);
3320                let end_line = paragraph_start + paragraph_lines.len() - 1;
3321
3322                // For the last line, we want to preserve any trailing newline
3323                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
3324                    // Last line without trailing newline - use line_text_range
3325                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
3326                } else {
3327                    // Not the last line or has trailing newline - use whole_line_range
3328                    line_index.whole_line_range(end_line + 1)
3329                };
3330
3331                let byte_range = start_range.start..end_range.end;
3332
3333                // Check if the paragraph ends with a hard break and what type
3334                let hard_break_type = paragraph_lines.last().and_then(|line| {
3335                    let line = line.strip_suffix('\r').unwrap_or(line);
3336                    if line.ends_with('\\') {
3337                        Some("\\")
3338                    } else if line.ends_with("  ") {
3339                        Some("  ")
3340                    } else {
3341                        None
3342                    }
3343                });
3344
3345                // Reflow the paragraph
3346                // When line_length = 0 (no limit), use a very large value for reflow
3347                let reflow_line_length = if config.line_length.is_unlimited() {
3348                    usize::MAX
3349                } else {
3350                    config.line_length.get()
3351                };
3352                let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
3353                let mut reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);
3354
3355                // Re-apply the common indent to each non-empty reflowed line so
3356                // that the replacement preserves the original structural indentation.
3357                if !common_indent.is_empty() {
3358                    for line in &mut reflowed {
3359                        if !line.is_empty() {
3360                            *line = format!("{common_indent}{line}");
3361                        }
3362                    }
3363                }
3364
3365                // If the original paragraph ended with a hard break, preserve it
3366                // Preserve the original hard break format (backslash or two spaces)
3367                if let Some(break_marker) = hard_break_type
3368                    && !reflowed.is_empty()
3369                {
3370                    let last_idx = reflowed.len() - 1;
3371                    if !has_hard_break(&reflowed[last_idx]) {
3372                        reflowed[last_idx].push_str(break_marker);
3373                    }
3374                }
3375
3376                let reflowed_text = reflowed.join(line_ending);
3377
3378                // Preserve trailing newline if the original paragraph had one
3379                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
3380                    format!("{reflowed_text}{line_ending}")
3381                } else {
3382                    reflowed_text
3383                };
3384
3385                // Get the original text to compare
3386                let original_text = &ctx.content[byte_range.clone()];
3387
3388                // Only generate a warning if the replacement is different from the original
3389                if original_text != replacement {
3390                    // Determine which line ranges and messages to report based on the reflow mode.
3391                    let warnings_to_report: Vec<(usize, usize, String)> = match config.reflow_mode {
3392                        ReflowMode::Default => {
3393                            // In default mode, report a warning for *every* line in the paragraph
3394                            // that exceeds the limit. Each warning will carry the same paragraph-level
3395                            // fix, making all of them auto-fixable.
3396                            paragraph_lines
3397                                .iter()
3398                                .enumerate()
3399                                .filter(|(_, line)| self.calculate_effective_length(line) > config.line_length.get())
3400                                .map(|(idx, _)| {
3401                                    let violating_line = paragraph_start + idx + 1;
3402                                    (
3403                                        violating_line,
3404                                        violating_line,
3405                                        format!("Line length exceeds {} characters", config.line_length.get()),
3406                                    )
3407                                })
3408                                .collect()
3409                        }
3410                        ReflowMode::Normalize => {
3411                            // In normalize mode, report the whole paragraph as needing normalization.
3412                            vec![(
3413                                paragraph_start + 1,
3414                                end_line + 1,
3415                                format!(
3416                                    "Paragraph could be normalized to use line length of {} characters",
3417                                    config.line_length.get()
3418                                ),
3419                            )]
3420                        }
3421                        ReflowMode::SentencePerLine => {
3422                            // In sentence-per-line mode, highlight the entire paragraph that needs reformatting.
3423                            let num_sentences = split_into_sentences(&paragraph_text).len();
3424                            let message = if paragraph_lines.len() == 1 {
3425                                // Single line with multiple sentences
3426                                format!("Line contains {num_sentences} sentences (one sentence per line required)")
3427                            } else {
3428                                // Multiple lines - could be split sentences or mixed
3429                                let num_lines = paragraph_lines.len();
3430                                format!(
3431                                    "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
3432                                )
3433                            };
3434                            vec![(paragraph_start + 1, paragraph_start + paragraph_lines.len(), message)]
3435                        }
3436                        ReflowMode::SemanticLineBreaks => {
3437                            // In semantic-line-breaks mode, highlight the entire paragraph.
3438                            let num_sentences = split_into_sentences(&paragraph_text).len();
3439                            vec![(
3440                                paragraph_start + 1,
3441                                paragraph_start + paragraph_lines.len(),
3442                                format!("Paragraph should use semantic line breaks ({num_sentences} sentences)"),
3443                            )]
3444                        }
3445                    };
3446
3447                    // Generate the actual lint warnings. All warnings for this paragraph
3448                    // share the same paragraph-level fix.
3449                    for (w_start, w_end, msg) in warnings_to_report {
3450                        warnings.push(LintWarning {
3451                            rule_name: Some(self.name().to_string()),
3452                            message: msg,
3453                            line: w_start,
3454                            column: 1,
3455                            end_line: w_end,
3456                            end_column: lines[w_end.saturating_sub(1)].chars().count() + 1,
3457                            severity: Severity::Warning,
3458                            fix: Some(crate::rule::Fix::new(byte_range.clone(), replacement.clone())),
3459                        });
3460                    }
3461                }
3462            }
3463        }
3464
3465        warnings
3466    }
3467
3468    /// Calculate string length based on the configured length mode
3469    fn calculate_string_length(&self, s: &str) -> usize {
3470        match self.config.length_mode {
3471            LengthMode::Chars => s.chars().count(),
3472            LengthMode::Visual => s.width(),
3473            LengthMode::Bytes => s.len(),
3474        }
3475    }
3476
3477    /// Calculate effective line length
3478    ///
3479    /// Returns the actual display length of the line using the configured length mode.
3480    fn calculate_effective_length(&self, line: &str) -> usize {
3481        self.calculate_string_length(line)
3482    }
3483
3484    /// Calculate line length with inline link/image URLs removed.
3485    ///
3486    /// For each inline link `[text](url)` or image `![alt](url)` on the line,
3487    /// computes the "savings" from removing the URL portion (keeping only `[text]`
3488    /// or `![alt]`). Returns `effective_length - total_savings`.
3489    ///
3490    /// Handles nested constructs (e.g., `[![img](url)](url)`) by only counting the
3491    /// outermost construct to avoid double-counting.
3492    fn length_without_inline_link_urls(
3493        &self,
3494        effective_length: usize,
3495        line_number: usize,
3496        ctx: &crate::lint_context::LintContext,
3497    ) -> usize {
3498        let line_range = ctx.line_index.line_content_range(line_number);
3499        let line_byte_end = line_range.end;
3500
3501        // Collect inline links/images on this line: (byte_offset, byte_end, text_only_display_len)
3502        let mut constructs: Vec<(usize, usize, usize)> = Vec::new();
3503
3504        // Binary search: links are sorted by byte_offset, so link.line is non-decreasing
3505        let link_start = ctx.links.partition_point(|l| l.line < line_number);
3506        for link in &ctx.links[link_start..] {
3507            if link.line != line_number {
3508                break;
3509            }
3510            if link.is_reference {
3511                continue;
3512            }
3513            if !matches!(link.link_type, LinkType::Inline) {
3514                continue;
3515            }
3516            if link.byte_end > line_byte_end {
3517                continue;
3518            }
3519            let text_only_len = 2 + self.calculate_string_length(&link.text);
3520            constructs.push((link.byte_offset, link.byte_end, text_only_len));
3521        }
3522
3523        let img_start = ctx.images.partition_point(|i| i.line < line_number);
3524        for image in &ctx.images[img_start..] {
3525            if image.line != line_number {
3526                break;
3527            }
3528            if image.is_reference {
3529                continue;
3530            }
3531            if !matches!(image.link_type, LinkType::Inline) {
3532                continue;
3533            }
3534            if image.byte_end > line_byte_end {
3535                continue;
3536            }
3537            let text_only_len = 3 + self.calculate_string_length(&image.alt_text);
3538            constructs.push((image.byte_offset, image.byte_end, text_only_len));
3539        }
3540
3541        if constructs.is_empty() {
3542            return effective_length;
3543        }
3544
3545        // Sort by byte offset to handle overlapping/nested constructs
3546        constructs.sort_by_key(|&(start, _, _)| start);
3547
3548        let mut total_savings: usize = 0;
3549        let mut last_end: usize = 0;
3550
3551        for (start, end, text_only_len) in &constructs {
3552            // Skip constructs nested inside a previously counted one
3553            if *start < last_end {
3554                continue;
3555            }
3556            // Full construct length in configured length mode
3557            let full_source = &ctx.content[*start..*end];
3558            let full_len = self.calculate_string_length(full_source);
3559            total_savings += full_len.saturating_sub(*text_only_len);
3560            last_end = *end;
3561        }
3562
3563        effective_length.saturating_sub(total_savings)
3564    }
3565}