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