Skip to main content

rumdl_lib/rules/
md013_line_length.rs

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