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