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