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