Skip to main content

rumdl_lib/rules/
md013_line_length.rs

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