Skip to main content

rumdl_lib/rules/
md013_line_length.rs

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