Skip to main content

rumdl_lib/rules/
md013_line_length.rs

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