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