Skip to main content

rumdl_lib/rules/
md013_line_length.rs

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