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, ReflowLengthMode, blockquote_continuation_style, dominant_blockquote_prefix,
16    reflow_blockquote_content, split_into_sentences,
17};
18use pulldown_cmark::LinkType;
19use toml;
20
21mod block_builder;
22mod helpers;
23pub mod md013_config;
24use crate::utils::is_template_directive_only;
25use block_builder::{Block, BlockBuilder};
26use helpers::{
27    extract_list_marker_and_content, has_hard_break, is_github_alert_marker, is_horizontal_rule, is_html_only_line,
28    is_list_item, is_standalone_link_or_image_line, is_unwrappable_line, split_into_segments,
29    trim_preserving_hard_break,
30};
31pub use md013_config::MD013Config;
32use md013_config::{LengthMode, ReflowMode};
33
34#[cfg(test)]
35mod tests;
36use unicode_width::UnicodeWidthStr;
37
38#[derive(Clone, Default)]
39pub struct MD013LineLength {
40    pub(crate) config: MD013Config,
41}
42
43/// Blockquote paragraph line collected for reflow, with original line index for range computation.
44struct CollectedBlockquoteLine {
45    line_idx: usize,
46    data: BlockquoteLineData,
47}
48
49impl MD013LineLength {
50    pub fn new(line_length: usize, code_blocks: bool, tables: bool, headings: bool, strict: bool) -> Self {
51        Self {
52            config: MD013Config {
53                line_length: crate::types::LineLength::new(line_length),
54                code_blocks,
55                tables,
56                headings,
57                paragraphs: true,  // Default to true for backwards compatibility
58                blockquotes: true, // Default to true for backwards compatibility
59                strict,
60                stern: false,
61                heading_line_length: None,
62                code_block_line_length: None,
63                reflow: false,
64                reflow_mode: ReflowMode::default(),
65                length_mode: LengthMode::default(),
66                abbreviations: Vec::new(),
67                require_sentence_capital: true,
68            },
69        }
70    }
71
72    pub fn from_config_struct(config: MD013Config) -> Self {
73        Self { config }
74    }
75
76    /// Return a clone with code block checking disabled.
77    /// Used for doc comment linting where code blocks are Rust code managed by rustfmt.
78    pub fn with_code_blocks_disabled(&self) -> Self {
79        let mut clone = self.clone();
80        clone.config.code_blocks = false;
81        clone
82    }
83
84    /// Convert MD013 LengthMode to text_reflow ReflowLengthMode
85    fn reflow_length_mode(&self) -> ReflowLengthMode {
86        match self.config.length_mode {
87            LengthMode::Chars => ReflowLengthMode::Chars,
88            LengthMode::Visual => ReflowLengthMode::Visual,
89            LengthMode::Bytes => ReflowLengthMode::Bytes,
90        }
91    }
92
93    fn should_ignore_line(
94        &self,
95        line: &str,
96        _lines: &[&str],
97        current_line: usize,
98        ctx: &crate::lint_context::LintContext,
99    ) -> bool {
100        if self.config.strict {
101            return false;
102        }
103
104        // Quick check for common patterns before expensive regex
105        let trimmed = line.trim();
106
107        // Only skip if the entire line is a URL (quick check first)
108        if (trimmed.starts_with("http://") || trimmed.starts_with("https://")) && URL_PATTERN.is_match(trimmed) {
109            return true;
110        }
111
112        // Only skip if the entire line is an image reference (quick check first)
113        if trimmed.starts_with("![") && trimmed.ends_with(']') && IMAGE_REF_PATTERN.is_match(trimmed) {
114            return true;
115        }
116
117        // Note: link reference definitions are handled as always-exempt (even in strict mode)
118        // in the main check loop, so they don't need to be checked here.
119
120        // Code blocks with long strings (only check if in code block)
121        if ctx.line_info(current_line + 1).is_some_and(|info| info.in_code_block)
122            && !trimmed.is_empty()
123            && !line.contains(' ')
124            && !line.contains('\t')
125        {
126            return true;
127        }
128
129        false
130    }
131
132    /// Check if rule should skip based on provided config (used for inline config support)
133    fn should_skip_with_config(&self, ctx: &crate::lint_context::LintContext, config: &MD013Config) -> bool {
134        // Skip if content is empty
135        if ctx.content.is_empty() {
136            return true;
137        }
138
139        // For sentence-per-line, semantic-line-breaks, or normalize mode, never skip based on line length
140        if config.reflow
141            && (config.reflow_mode == ReflowMode::SentencePerLine
142                || config.reflow_mode == ReflowMode::SemanticLineBreaks
143                || config.reflow_mode == ReflowMode::Normalize)
144        {
145            return false;
146        }
147
148        // Use the smallest applicable budget across line/heading/code-block
149        // contexts so a stricter context-specific limit doesn't get masked by
150        // the document-wide budget.
151        let min_limit = config.min_effective_line_length();
152        if min_limit.is_unlimited() {
153            return true;
154        }
155        let min_limit_bytes = min_limit.get();
156
157        // Quick check: if total content is shorter than the smallest line limit,
158        // definitely skip.
159        if ctx.content.len() <= min_limit_bytes {
160            return true;
161        }
162
163        // Skip if no line exceeds the smallest applicable limit.
164        !ctx.lines.iter().any(|line| line.byte_len > min_limit_bytes)
165    }
166
167    fn normalize_mode_needs_reflow<'a, I>(&self, lines: I, config: &MD013Config) -> bool
168    where
169        I: IntoIterator<Item = &'a str>,
170    {
171        let mut line_count = 0;
172        let check_length = !config.line_length.is_unlimited();
173
174        for line in lines {
175            line_count += 1;
176            if check_length && self.calculate_effective_length(line) > config.line_length.get() {
177                return true;
178            }
179        }
180
181        line_count > 1
182    }
183}
184
185impl Rule for MD013LineLength {
186    fn name(&self) -> &'static str {
187        "MD013"
188    }
189
190    fn description(&self) -> &'static str {
191        "Line length should not be excessive"
192    }
193
194    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
195        // Use pre-parsed inline config from LintContext
196        let config_override = ctx.inline_config().get_rule_config("MD013");
197
198        // Apply configuration override if present
199        let effective_config = if let Some(json_config) = config_override {
200            if let Some(obj) = json_config.as_object() {
201                let mut config = self.config.clone();
202                if let Some(line_length) = obj.get("line_length").and_then(serde_json::Value::as_u64) {
203                    config.line_length = crate::types::LineLength::new(line_length as usize);
204                }
205                if let Some(code_blocks) = obj.get("code_blocks").and_then(serde_json::Value::as_bool) {
206                    config.code_blocks = code_blocks;
207                }
208                if let Some(tables) = obj.get("tables").and_then(serde_json::Value::as_bool) {
209                    config.tables = tables;
210                }
211                if let Some(headings) = obj.get("headings").and_then(serde_json::Value::as_bool) {
212                    config.headings = headings;
213                }
214                if let Some(blockquotes) = obj.get("blockquotes").and_then(serde_json::Value::as_bool) {
215                    config.blockquotes = blockquotes;
216                }
217                if let Some(strict) = obj.get("strict").and_then(serde_json::Value::as_bool) {
218                    config.strict = strict;
219                }
220                if let Some(reflow) = obj.get("reflow").and_then(serde_json::Value::as_bool) {
221                    config.reflow = reflow;
222                }
223                if let Some(reflow_mode) = obj.get("reflow_mode").and_then(|v| v.as_str()) {
224                    config.reflow_mode = match reflow_mode {
225                        "default" => ReflowMode::Default,
226                        "normalize" => ReflowMode::Normalize,
227                        "sentence-per-line" => ReflowMode::SentencePerLine,
228                        "semantic-line-breaks" => ReflowMode::SemanticLineBreaks,
229                        _ => ReflowMode::default(),
230                    };
231                }
232                config
233            } else {
234                self.config.clone()
235            }
236        } else {
237            self.config.clone()
238        };
239
240        // Fast early return using should_skip with EFFECTIVE config (after inline overrides)
241        // But don't skip if we're in reflow mode with Normalize or SentencePerLine
242        if self.should_skip_with_config(ctx, &effective_config)
243            && !(effective_config.reflow
244                && (effective_config.reflow_mode == ReflowMode::Normalize
245                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
246                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
247        {
248            return Ok(Vec::new());
249        }
250
251        // Direct implementation without DocumentStructure
252        let mut warnings = Vec::new();
253
254        // Special handling: line_length = 0 means "no line length limit"
255        // Skip all line length checks, but still allow reflow if enabled
256        let skip_length_checks = effective_config.line_length.is_unlimited();
257
258        // Pre-filter lines that could be problematic to avoid processing all lines.
259        // Use the smallest applicable budget across line/heading/code-block contexts
260        // so candidates aren't dropped when a stricter context-specific budget applies.
261        let prefilter_limit = effective_config.min_effective_line_length();
262        let prefilter_skip = prefilter_limit.is_unlimited();
263        let mut candidate_lines = Vec::new();
264        if !skip_length_checks && !prefilter_skip {
265            for (line_idx, line_info) in ctx.lines.iter().enumerate() {
266                // Skip front matter - it should never be linted
267                if line_info.in_front_matter {
268                    continue;
269                }
270
271                // Quick length check first
272                if line_info.byte_len > prefilter_limit.get() {
273                    candidate_lines.push(line_idx);
274                }
275            }
276        }
277
278        // If no candidate lines and not in normalize or sentence-per-line mode, early return
279        if candidate_lines.is_empty()
280            && !(effective_config.reflow
281                && (effective_config.reflow_mode == ReflowMode::Normalize
282                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
283                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
284        {
285            return Ok(warnings);
286        }
287
288        let lines = ctx.raw_lines();
289
290        // Create a quick lookup set for heading lines
291        // We need this for both the heading skip check AND the paragraphs check
292        let heading_lines_set: std::collections::HashSet<usize> = ctx
293            .lines
294            .iter()
295            .enumerate()
296            .filter(|(_, line)| line.heading.is_some())
297            .map(|(idx, _)| idx + 1)
298            .collect();
299
300        // Use pre-computed table blocks from context
301        // We need this for both the table skip check AND the paragraphs check
302        let table_blocks = &ctx.table_blocks;
303        let mut table_lines_set = std::collections::HashSet::new();
304        for table in table_blocks {
305            table_lines_set.insert(table.header_line + 1);
306            table_lines_set.insert(table.delimiter_line + 1);
307            for &line in &table.content_lines {
308                table_lines_set.insert(line + 1);
309            }
310        }
311
312        // Process candidate lines for line length checks
313        'line_loop: for &line_idx in &candidate_lines {
314            let line_number = line_idx + 1;
315            let line = lines[line_idx];
316
317            // Calculate actual line length (used in warning messages)
318            let effective_length = self.calculate_effective_length(line);
319
320            // Pick the context-specific limit: heading > code-block > paragraph.
321            // Headings dominate over code-block context if a setext underline ever
322            // overlaps a fenced range (defensive — these are mutually exclusive in
323            // practice, but the explicit ordering documents intent).
324            let is_heading_line = heading_lines_set.contains(&line_number);
325            let in_code_block = ctx.line_info(line_number).is_some_and(|info| info.in_code_block);
326            let line_limit = if is_heading_line {
327                effective_config.effective_heading_line_length().get()
328            } else if in_code_block {
329                effective_config.effective_code_block_line_length().get()
330            } else {
331                effective_config.line_length.get()
332            };
333
334            // A context-specific limit of 0 means "unlimited for this context".
335            if line_limit == 0 {
336                continue;
337            }
338
339            // Stern mode: like default, but the trailing-token forgiveness is
340            // disabled — a line with whitespace that exceeds the limit is a
341            // violation even if the excess is the final token. The "unwrappable"
342            // line exemption (single token, optionally prefixed by # or >) is
343            // still honored. Strict overrides stern entirely.
344            if effective_config.stern && !effective_config.strict && is_unwrappable_line(line) {
345                continue;
346            }
347
348            // Trailing-token forgiveness: only in default mode (not strict, not stern).
349            // If the line only exceeds the limit because of a long token at the end
350            // (URL, link chain, identifier), it passes. This matches markdownlint's
351            // behavior: line.replace(/\S*$/u, "#")
352            let check_length = if effective_config.strict || effective_config.stern {
353                effective_length
354            } else {
355                match line.rfind(char::is_whitespace) {
356                    Some(pos) => {
357                        let ws_char = line[pos..].chars().next().unwrap();
358                        let prefix_end = pos + ws_char.len_utf8();
359                        self.calculate_string_length(&line[..prefix_end]) + 1
360                    }
361                    None => 1, // No whitespace — entire line is a single token
362                }
363            };
364
365            // Skip lines where the check length is within the limit
366            if check_length <= line_limit {
367                continue;
368            }
369
370            // Semantic link understanding: suppress when excess comes entirely from inline URLs
371            if !effective_config.strict {
372                let text_only_length = self.calculate_text_only_length(effective_length, line_number, ctx);
373                if text_only_length <= line_limit {
374                    continue;
375                }
376            }
377
378            // Skip mkdocstrings and pymdown blocks (already handled by LintContext)
379            if ctx.lines[line_idx].in_mkdocstrings || ctx.lines[line_idx].in_pymdown_block {
380                continue;
381            }
382
383            // Skip MyST comments (% comment) — structural lines, not prose
384            if ctx.lines[line_idx].is_myst_comment {
385                continue;
386            }
387
388            // Link reference definitions are always exempt, even in strict mode.
389            // There's no way to shorten them without breaking the URL.
390            // Also check after stripping list markers, since list items may
391            // contain link ref defs as their content.
392            {
393                let trimmed = line.trim();
394                if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
395                    continue;
396                }
397                if is_list_item(trimmed) {
398                    let (_, content) = extract_list_marker_and_content(trimmed);
399                    let content_trimmed = content.trim();
400                    if content_trimmed.starts_with('[')
401                        && content_trimmed.contains("]:")
402                        && LINK_REF_PATTERN.is_match(content_trimmed)
403                    {
404                        continue;
405                    }
406                }
407            }
408
409            // Skip various block types efficiently
410            if !effective_config.strict {
411                // Lines whose only content is a link/image are exempt.
412                // After stripping list markers, blockquote markers, and emphasis,
413                // if only a link or image remains, there is no way to shorten it.
414                if is_standalone_link_or_image_line(line) {
415                    continue;
416                }
417
418                // Lines consisting entirely of HTML tags are exempt.
419                // Badge lines, images with attributes, and similar inline HTML
420                // are long due to URLs in attributes and can't be meaningfully shortened.
421                if is_html_only_line(line) {
422                    continue;
423                }
424
425                // Skip setext heading underlines
426                if !line.trim().is_empty() && line.trim().chars().all(|c| c == '=' || c == '-') {
427                    continue;
428                }
429
430                // Skip block elements according to config flags
431                // The flags mean: true = check these elements, false = skip these elements
432                // So we skip when the flag is FALSE and the line is in that element type
433                if (!effective_config.headings && heading_lines_set.contains(&line_number))
434                    || (!effective_config.code_blocks
435                        && ctx.line_info(line_number).is_some_and(|info| info.in_code_block))
436                    || (!effective_config.tables && table_lines_set.contains(&line_number))
437                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
438                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
439                    || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
440                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
441                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
442                    || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
443                    || ctx.line_info(line_number).is_some_and(|info| info.in_pymdown_block)
444                {
445                    continue;
446                }
447
448                // Check if this is a paragraph/regular text line
449                // If paragraphs = false, skip lines that are NOT in special blocks
450                // Blockquote content is treated as paragraph text, so it's not
451                // included in the special blocks list here.
452                if !effective_config.paragraphs {
453                    let is_special_block = heading_lines_set.contains(&line_number)
454                        || ctx.line_info(line_number).is_some_and(|info| info.in_code_block)
455                        || table_lines_set.contains(&line_number)
456                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
457                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
458                        || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
459                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
460                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
461                        || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
462                        || ctx
463                            .line_info(line_number)
464                            .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container);
465
466                    // Skip regular paragraph text when paragraphs = false
467                    if !is_special_block {
468                        continue;
469                    }
470                }
471
472                // Skip blockquote lines when blockquotes = false.
473                // Also skip lazy continuation lines that belong to a blockquote
474                // (lines without `>` prefix that follow a blockquote line).
475                if !effective_config.blockquotes {
476                    if ctx.lines[line_number - 1].blockquote.is_some() {
477                        continue;
478                    }
479                    // Check for lazy continuation: scan backwards through
480                    // non-blank lines to find if this paragraph started with
481                    // a blockquote marker
482                    if !line.trim().is_empty() {
483                        let mut scan = line_number.saturating_sub(2);
484                        loop {
485                            if ctx.lines[scan].blockquote.is_some() {
486                                // Found a blockquote ancestor — this is a lazy continuation
487                                continue 'line_loop;
488                            }
489                            if lines[scan].trim().is_empty() || scan == 0 {
490                                break;
491                            }
492                            scan -= 1;
493                        }
494                    }
495                }
496
497                // Skip lines that are only a URL, image ref, or link ref
498                if self.should_ignore_line(line, lines, line_idx, ctx) {
499                    continue;
500                }
501            }
502
503            // In sentence-per-line mode, check if this is a single long sentence
504            // If so, emit a warning without a fix (user must manually rephrase)
505            if effective_config.reflow_mode == ReflowMode::SentencePerLine {
506                let sentences = split_into_sentences(line.trim());
507                if sentences.len() == 1 {
508                    // Single sentence that's too long - warn but don't auto-fix
509                    let message = format!("Line length {effective_length} exceeds {line_limit} characters");
510
511                    let (start_line, start_col, end_line, end_col) =
512                        calculate_excess_range(line_number, line, line_limit);
513
514                    warnings.push(LintWarning {
515                        rule_name: Some(self.name().to_string()),
516                        message,
517                        line: start_line,
518                        column: start_col,
519                        end_line,
520                        end_column: end_col,
521                        severity: Severity::Warning,
522                        fix: None, // No auto-fix for long single sentences
523                    });
524                    continue;
525                }
526                // Multiple sentences will be handled by paragraph-based reflow
527                continue;
528            }
529
530            // In semantic-line-breaks mode, skip per-line checks —
531            // all reflow is handled at the paragraph level with cascading splits
532            if effective_config.reflow_mode == ReflowMode::SemanticLineBreaks {
533                continue;
534            }
535
536            // Don't provide fix for individual lines when reflow is enabled
537            // Paragraph-based fixes will be handled separately
538            let fix = None;
539
540            let message = format!("Line length {effective_length} exceeds {line_limit} characters");
541
542            // Calculate precise character range for the excess portion
543            let (start_line, start_col, end_line, end_col) = calculate_excess_range(line_number, line, line_limit);
544
545            warnings.push(LintWarning {
546                rule_name: Some(self.name().to_string()),
547                message,
548                line: start_line,
549                column: start_col,
550                end_line,
551                end_column: end_col,
552                severity: Severity::Warning,
553                fix,
554            });
555        }
556
557        // If reflow is enabled, generate paragraph-based fixes
558        if effective_config.reflow {
559            let paragraph_warnings = self.generate_paragraph_fixes(ctx, &effective_config, lines);
560            // Merge paragraph warnings with line warnings, removing duplicates
561            for pw in paragraph_warnings {
562                // Remove any line warnings that overlap with this paragraph
563                warnings.retain(|w| w.line < pw.line || w.line > pw.end_line);
564                warnings.push(pw);
565            }
566        }
567
568        Ok(warnings)
569    }
570
571    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
572        // For CLI usage, apply fixes from warnings
573        // LSP will use the warning-based fixes directly
574        let warnings = self.check(ctx)?;
575        let warnings =
576            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
577
578        // If there are no fixes, return content unchanged
579        if !warnings.iter().any(|w| w.fix.is_some()) {
580            return Ok(ctx.content.to_string());
581        }
582
583        // Apply warning-based fixes
584        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
585            .map_err(|e| LintError::FixFailed(format!("Failed to apply fixes: {e}")))
586    }
587
588    fn as_any(&self) -> &dyn std::any::Any {
589        self
590    }
591
592    fn category(&self) -> RuleCategory {
593        RuleCategory::Whitespace
594    }
595
596    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
597        self.should_skip_with_config(ctx, &self.config)
598    }
599
600    fn default_config_section(&self) -> Option<(String, toml::Value)> {
601        let table = crate::rule_config_serde::config_schema_table(&MD013Config::default())?;
602        if table.is_empty() {
603            None
604        } else {
605            Some((MD013Config::RULE_NAME.to_string(), toml::Value::Table(table)))
606        }
607    }
608
609    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
610        let mut aliases = std::collections::HashMap::new();
611        aliases.insert("enable_reflow".to_string(), "reflow".to_string());
612        aliases.insert("strict_sentences".to_string(), "require-sentence-capital".to_string());
613        aliases.insert("strict-sentences".to_string(), "require-sentence-capital".to_string());
614        Some(aliases)
615    }
616
617    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
618    where
619        Self: Sized,
620    {
621        let mut rule_config = crate::rule_config_serde::load_rule_config::<MD013Config>(config);
622        // Use global line_length if rule-specific config still has default value
623        if rule_config.line_length.get() == 80 {
624            rule_config.line_length = config.global.line_length;
625        }
626        Box::new(Self::from_config_struct(rule_config))
627    }
628}
629
630impl MD013LineLength {
631    fn is_blockquote_content_boundary(
632        &self,
633        content: &str,
634        line_num: usize,
635        ctx: &crate::lint_context::LintContext,
636    ) -> bool {
637        let trimmed = content.trim();
638
639        trimmed.is_empty()
640            || ctx.line_info(line_num).is_some_and(|info| {
641                info.in_code_block
642                    || info.in_front_matter
643                    || info.in_html_block
644                    || info.in_html_comment
645                    || info.in_esm_block
646                    || info.in_jsx_expression
647                    || info.in_jsx_block
648                    || info.in_mdx_comment
649                    || info.in_mkdocstrings
650                    || info.in_pymdown_block
651                    || info.in_mkdocs_container()
652                    || info.is_div_marker
653            })
654            || trimmed.starts_with('#')
655            || trimmed.starts_with("```")
656            || trimmed.starts_with("~~~")
657            || trimmed.starts_with('>')
658            || TableUtils::is_potential_table_row(content)
659            || is_list_item(trimmed)
660            || is_horizontal_rule(content)
661            || (trimmed.starts_with('[') && content.contains("]:"))
662            || is_template_directive_only(content)
663            || is_standalone_attr_list(content)
664            || is_snippet_block_delimiter(content)
665            || is_github_alert_marker(trimmed)
666            || is_html_only_line(content)
667    }
668
669    fn generate_blockquote_paragraph_fix(
670        &self,
671        ctx: &crate::lint_context::LintContext,
672        config: &MD013Config,
673        lines: &[&str],
674        line_index: &LineIndex,
675        start_idx: usize,
676        line_ending: &str,
677    ) -> (Option<LintWarning>, usize) {
678        let Some(start_bq) = ctx.lines.get(start_idx).and_then(|line| line.blockquote.as_deref()) else {
679            return (None, start_idx + 1);
680        };
681        let target_level = start_bq.nesting_level;
682
683        let mut collected: Vec<CollectedBlockquoteLine> = Vec::new();
684        let mut i = start_idx;
685
686        while i < lines.len() {
687            if !collected.is_empty() && has_hard_break(&collected[collected.len() - 1].data.content) {
688                break;
689            }
690
691            let line_num = i + 1;
692            if line_num > ctx.lines.len() {
693                break;
694            }
695
696            if lines[i].trim().is_empty() {
697                break;
698            }
699
700            let line_bq = ctx.lines[i].blockquote.as_deref();
701            if let Some(bq) = line_bq {
702                if bq.nesting_level != target_level {
703                    break;
704                }
705
706                if self.is_blockquote_content_boundary(&bq.content, line_num, ctx) {
707                    break;
708                }
709
710                collected.push(CollectedBlockquoteLine {
711                    line_idx: i,
712                    data: BlockquoteLineData::explicit(trim_preserving_hard_break(&bq.content), bq.prefix.clone()),
713                });
714                i += 1;
715                continue;
716            }
717
718            let lazy_content = lines[i].trim_start();
719            if self.is_blockquote_content_boundary(lazy_content, line_num, ctx) {
720                break;
721            }
722
723            collected.push(CollectedBlockquoteLine {
724                line_idx: i,
725                data: BlockquoteLineData::lazy(trim_preserving_hard_break(lazy_content)),
726            });
727            i += 1;
728        }
729
730        if collected.is_empty() {
731            return (None, start_idx + 1);
732        }
733
734        let next_idx = i;
735        let paragraph_start = collected[0].line_idx;
736        let end_line = collected[collected.len() - 1].line_idx;
737        let line_data: Vec<BlockquoteLineData> = collected.iter().map(|l| l.data.clone()).collect();
738        let paragraph_text = line_data
739            .iter()
740            .map(|d| d.content.as_str())
741            .collect::<Vec<_>>()
742            .join(" ");
743
744        let contains_definition_list = line_data
745            .iter()
746            .any(|d| crate::utils::is_definition_list_item(&d.content));
747        if contains_definition_list {
748            return (None, next_idx);
749        }
750
751        let contains_snippets = line_data.iter().any(|d| is_snippet_block_delimiter(&d.content));
752        if contains_snippets {
753            return (None, next_idx);
754        }
755
756        let needs_reflow = match config.reflow_mode {
757            ReflowMode::Normalize => {
758                self.normalize_mode_needs_reflow(line_data.iter().map(|d| d.content.as_str()), config)
759            }
760            ReflowMode::SentencePerLine => {
761                let sentences = split_into_sentences(&paragraph_text);
762                sentences.len() > 1 || line_data.len() > 1
763            }
764            ReflowMode::SemanticLineBreaks => {
765                let sentences = split_into_sentences(&paragraph_text);
766                sentences.len() > 1
767                    || line_data.len() > 1
768                    || collected
769                        .iter()
770                        .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get())
771            }
772            ReflowMode::Default => collected
773                .iter()
774                .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get()),
775        };
776
777        if !needs_reflow {
778            return (None, next_idx);
779        }
780
781        let fallback_prefix = start_bq.prefix.clone();
782        let explicit_prefix = dominant_blockquote_prefix(&line_data, &fallback_prefix);
783        let continuation_style = blockquote_continuation_style(&line_data);
784
785        let reflow_line_length = if config.line_length.is_unlimited() {
786            usize::MAX
787        } else {
788            config
789                .line_length
790                .get()
791                .saturating_sub(self.calculate_string_length(&explicit_prefix))
792                .max(1)
793        };
794
795        let reflow_options = crate::utils::text_reflow::ReflowOptions {
796            line_length: reflow_line_length,
797            break_on_sentences: true,
798            preserve_breaks: false,
799            sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
800            semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
801            abbreviations: config.abbreviations_for_reflow(),
802            length_mode: self.reflow_length_mode(),
803            attr_lists: ctx.flavor.supports_attr_lists(),
804            myst_roles: ctx.flavor.supports_myst_roles(),
805            require_sentence_capital: config.require_sentence_capital,
806            max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
807                Some(4)
808            } else {
809                None
810            },
811        };
812
813        let reflowed_with_style =
814            reflow_blockquote_content(&line_data, &explicit_prefix, continuation_style, &reflow_options);
815
816        if reflowed_with_style.is_empty() {
817            return (None, next_idx);
818        }
819
820        let reflowed_text = reflowed_with_style.join(line_ending);
821
822        let start_range = line_index.whole_line_range(paragraph_start + 1);
823        let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
824            line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
825        } else {
826            line_index.whole_line_range(end_line + 1)
827        };
828        let byte_range = start_range.start..end_range.end;
829
830        let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
831            format!("{reflowed_text}{line_ending}")
832        } else {
833            reflowed_text
834        };
835
836        let original_text = &ctx.content[byte_range.clone()];
837        if original_text == replacement {
838            return (None, next_idx);
839        }
840
841        let (warning_line, warning_end_line) = match config.reflow_mode {
842            ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
843            ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => (paragraph_start + 1, end_line + 1),
844            ReflowMode::Default => {
845                let violating_line = collected
846                    .iter()
847                    .find(|line| self.calculate_effective_length(lines[line.line_idx]) > config.line_length.get())
848                    .map_or(paragraph_start + 1, |line| line.line_idx + 1);
849                (violating_line, violating_line)
850            }
851        };
852
853        let warning = LintWarning {
854            rule_name: Some(self.name().to_string()),
855            message: match config.reflow_mode {
856                ReflowMode::Normalize => format!(
857                    "Paragraph could be normalized to use line length of {} characters",
858                    config.line_length.get()
859                ),
860                ReflowMode::SentencePerLine => {
861                    let num_sentences = split_into_sentences(&paragraph_text).len();
862                    if line_data.len() == 1 {
863                        format!("Line contains {num_sentences} sentences (one sentence per line required)")
864                    } else {
865                        let num_lines = line_data.len();
866                        format!(
867                            "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
868                        )
869                    }
870                }
871                ReflowMode::SemanticLineBreaks => {
872                    let num_sentences = split_into_sentences(&paragraph_text).len();
873                    format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
874                }
875                ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
876            },
877            line: warning_line,
878            column: 1,
879            end_line: warning_end_line,
880            end_column: lines[warning_end_line.saturating_sub(1)].chars().count() + 1,
881            severity: Severity::Warning,
882            fix: Some(crate::rule::Fix::new(byte_range, replacement)),
883        };
884
885        (Some(warning), next_idx)
886    }
887
888    /// Generate paragraph-based fixes
889    fn generate_paragraph_fixes(
890        &self,
891        ctx: &crate::lint_context::LintContext,
892        config: &MD013Config,
893        lines: &[&str],
894    ) -> Vec<LintWarning> {
895        let mut warnings = Vec::new();
896        let line_index = LineIndex::new(ctx.content);
897
898        // Detect the content's line ending style to preserve it in replacements.
899        // The LSP receives content from editors which may use CRLF (Windows).
900        // Replacements must match the original line endings to avoid false positives.
901        let line_ending = crate::utils::line_ending::detect_line_ending(ctx.content);
902
903        let mut i = 0;
904        while i < lines.len() {
905            let line_num = i + 1;
906
907            // Handle blockquote paragraphs with style-preserving reflow.
908            // Skip blockquotes when blockquotes=false or paragraphs=false
909            if line_num > 0 && line_num <= ctx.lines.len() && ctx.lines[line_num - 1].blockquote.is_some() {
910                if !config.blockquotes || !config.paragraphs {
911                    // Skip past all blockquote lines (explicit and lazy continuations).
912                    // A lazy continuation is a non-blank line without `>` that follows
913                    // a blockquote line and isn't a structural element.
914                    let mut saw_explicit_bq = false;
915                    while i < lines.len() && i < ctx.lines.len() {
916                        if ctx.lines[i].blockquote.is_some() {
917                            saw_explicit_bq = true;
918                            i += 1;
919                        } else if saw_explicit_bq
920                            && !lines[i].trim().is_empty()
921                            && !lines[i].trim_start().starts_with('#')
922                            && !lines[i].trim_start().starts_with('>')
923                        {
924                            // Lazy continuation of preceding blockquote
925                            i += 1;
926                        } else {
927                            break;
928                        }
929                    }
930                    continue;
931                }
932                let (warning, next_idx) =
933                    self.generate_blockquote_paragraph_fix(ctx, config, lines, &line_index, i, line_ending);
934                if let Some(warning) = warning {
935                    warnings.push(warning);
936                }
937                i = next_idx;
938                continue;
939            }
940
941            // Skip special structures (but NOT MkDocs containers - those get special handling)
942            let should_skip_due_to_line_info = ctx.line_info(line_num).is_some_and(|info| {
943                info.in_code_block
944                    || info.in_front_matter
945                    || info.in_html_block
946                    || info.in_html_comment
947                    || info.in_esm_block
948                    || info.in_jsx_expression
949                    || info.in_jsx_block
950                    || info.in_mdx_comment
951                    || info.in_mkdocstrings
952                    || info.in_pymdown_block
953            });
954
955            // Skip link reference definitions but NOT footnote definitions.
956            // Footnote definitions (`[^id]: prose`) contain reflowable text,
957            // while link reference definitions (`[ref]: URL`) contain URLs
958            // that cannot be shortened.
959            let is_link_ref_def =
960                lines[i].trim().starts_with('[') && !lines[i].trim().starts_with("[^") && lines[i].contains("]:");
961
962            if should_skip_due_to_line_info
963                || lines[i].trim().starts_with('#')
964                || TableUtils::is_potential_table_row(lines[i])
965                || lines[i].trim().is_empty()
966                || is_horizontal_rule(lines[i])
967                || is_template_directive_only(lines[i])
968                || is_link_ref_def
969                || ctx.line_info(line_num).is_some_and(|info| info.is_div_marker)
970                || is_html_only_line(lines[i])
971            {
972                i += 1;
973                continue;
974            }
975
976            // Handle footnote definitions: `[^id]: prose text that can be reflowed`
977            // Supports multi-paragraph footnotes with code blocks, blockquotes,
978            // tables, and lists preserved verbatim.
979            // Validate structure: must start with `[^`, contain `]:`, and the ID
980            // must not contain `[` or `]` (prevents false matches on nested brackets)
981            if lines[i].trim().starts_with("[^") && lines[i].contains("]:") && {
982                let after_caret = &lines[i].trim()[2..];
983                after_caret
984                    .find("]:")
985                    .is_some_and(|pos| pos > 0 && !after_caret[..pos].contains(['[', ']']))
986            } {
987                let footnote_start = i;
988                let line = lines[i];
989
990                // Extract the prefix `[^id]:`
991                let Some(colon_pos) = line.find("]:") else {
992                    i += 1;
993                    continue;
994                };
995                let prefix_end = colon_pos + 2;
996                let prefix = &line[..prefix_end];
997
998                // Content starts after `]: ` (with optional space)
999                let content_start = if line[prefix_end..].starts_with(' ') {
1000                    prefix_end + 1
1001                } else {
1002                    prefix_end
1003                };
1004                let first_content = &line[content_start..];
1005
1006                // CommonMark footnotes use 4-space continuation indent
1007                const FN_INDENT: usize = 4;
1008
1009                // --- Line classification for footnote content ---
1010                #[derive(Debug, Clone)]
1011                enum FnLineType {
1012                    Content(String),
1013                    Verbatim(String, usize), // preserved text, original indent
1014                    Empty,
1015                }
1016
1017                // Helper: compute visual indent (tabs = 4 spaces)
1018                let visual_indent = |s: &str| -> usize {
1019                    s.chars()
1020                        .take_while(|c| c.is_whitespace())
1021                        .map(|c| if c == '\t' { 4 } else { 1 })
1022                        .sum::<usize>()
1023                };
1024
1025                // Helper: check if a trimmed line is a fence marker (homogeneous chars)
1026                let is_fence = |s: &str| -> bool {
1027                    let t = s.trim();
1028                    let fence_char = t.chars().next();
1029                    matches!(fence_char, Some('`') | Some('~'))
1030                        && t.chars().take_while(|&c| c == fence_char.unwrap()).count() >= 3
1031                };
1032
1033                // Helper: check if a trimmed line is a setext underline
1034                let is_setext_underline = |s: &str| -> bool {
1035                    let t = s.trim();
1036                    !t.is_empty()
1037                        && (t.chars().all(|c| c == '=' || c == ' ') || t.chars().all(|c| c == '-' || c == ' '))
1038                        && t.contains(['=', '-'])
1039                };
1040
1041                // Deferred body: `[^id]:\n    content` — first line has no content,
1042                // actual content starts on the next indented line
1043                let deferred_body = first_content.trim().is_empty();
1044
1045                // Collect all lines belonging to this footnote definition
1046                let mut fn_lines: Vec<FnLineType> = Vec::new();
1047                if !deferred_body {
1048                    fn_lines.push(FnLineType::Content(first_content.to_string()));
1049                }
1050                let mut last_consumed = i;
1051                i += 1;
1052
1053                // Strip only the footnote continuation indent, preserving
1054                // internal indentation (e.g., code block body indent)
1055                let strip_fn_indent = |s: &str| -> String {
1056                    let mut chars = s.chars();
1057                    let mut stripped = 0;
1058                    while stripped < FN_INDENT {
1059                        match chars.next() {
1060                            Some('\t') => stripped += 4,
1061                            Some(c) if c.is_whitespace() => stripped += 1,
1062                            _ => break,
1063                        }
1064                    }
1065                    chars.as_str().to_string()
1066                };
1067
1068                let mut in_fenced_code = false;
1069                let mut consecutive_blanks = 0u32;
1070
1071                while i < lines.len() {
1072                    let next = lines[i];
1073                    let next_trimmed = next.trim();
1074
1075                    // Blank line handling
1076                    if next_trimmed.is_empty() {
1077                        consecutive_blanks += 1;
1078                        // 2+ consecutive blanks terminate the footnote
1079                        if consecutive_blanks >= 2 {
1080                            break;
1081                        }
1082
1083                        // Inside a fenced code block, blank lines are part of the code
1084                        if in_fenced_code {
1085                            consecutive_blanks = 0; // Don't count blanks inside code blocks
1086                            fn_lines.push(FnLineType::Verbatim(String::new(), 0));
1087                            last_consumed = i;
1088                            i += 1;
1089                            continue;
1090                        }
1091
1092                        // Peek ahead: if next non-blank line is indented >= FN_INDENT,
1093                        // this blank is an internal paragraph separator
1094                        if i + 1 < lines.len() {
1095                            let peek = lines[i + 1];
1096                            let peek_indent = visual_indent(peek);
1097                            if !peek.trim().is_empty() && peek_indent >= FN_INDENT {
1098                                fn_lines.push(FnLineType::Empty);
1099                                last_consumed = i;
1100                                i += 1;
1101                                continue;
1102                            }
1103                        }
1104                        // No valid continuation after blank — end of footnote
1105                        break;
1106                    }
1107
1108                    consecutive_blanks = 0;
1109                    let indent = visual_indent(next);
1110
1111                    // Not indented enough — end of footnote
1112                    if indent < FN_INDENT {
1113                        break;
1114                    }
1115
1116                    // Inside a fenced code block: everything is verbatim until closing fence
1117                    if in_fenced_code {
1118                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1119                        if is_fence(next_trimmed) {
1120                            in_fenced_code = false;
1121                        }
1122                        last_consumed = i;
1123                        i += 1;
1124                        continue;
1125                    }
1126
1127                    // Fence opener — start verbatim code block
1128                    if is_fence(next_trimmed) {
1129                        in_fenced_code = true;
1130                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1131                        last_consumed = i;
1132                        i += 1;
1133                        continue;
1134                    }
1135
1136                    // Indented code block: indent >= FN_INDENT + 4 (= 8 spaces)
1137                    if indent >= FN_INDENT + 4 {
1138                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1139                        last_consumed = i;
1140                        i += 1;
1141                        continue;
1142                    }
1143
1144                    // Structural content that must be preserved verbatim
1145                    if next_trimmed.starts_with('#')
1146                        || is_list_item(next_trimmed)
1147                        || next_trimmed.starts_with('>')
1148                        || TableUtils::is_potential_table_row(next_trimmed)
1149                        || is_setext_underline(next_trimmed)
1150                        || is_horizontal_rule(next_trimmed)
1151                        || crate::utils::mkdocs_footnotes::is_footnote_definition(next_trimmed)
1152                    {
1153                        // Preserve verbatim: blockquotes, tables, lists, setext
1154                        // underlines, and horizontal rules inside the footnote
1155                        if next_trimmed.starts_with('>')
1156                            || TableUtils::is_potential_table_row(next_trimmed)
1157                            || is_list_item(next_trimmed)
1158                            || is_setext_underline(next_trimmed)
1159                            || is_horizontal_rule(next_trimmed)
1160                        {
1161                            fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1162                            last_consumed = i;
1163                            i += 1;
1164                            continue;
1165                        }
1166                        // Headings, new footnote defs, link refs — end the footnote
1167                        break;
1168                    }
1169
1170                    // Link reference definitions inside footnotes are not reflowable
1171                    if next_trimmed.starts_with('[')
1172                        && !next_trimmed.starts_with("[^")
1173                        && next_trimmed.contains("]:")
1174                        && LINK_REF_PATTERN.is_match(next_trimmed)
1175                    {
1176                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1177                        last_consumed = i;
1178                        i += 1;
1179                        continue;
1180                    }
1181
1182                    // HTML-only lines inside footnotes are not reflowable
1183                    if is_html_only_line(next_trimmed) {
1184                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
1185                        last_consumed = i;
1186                        i += 1;
1187                        continue;
1188                    }
1189
1190                    // Regular prose content
1191                    fn_lines.push(FnLineType::Content(next_trimmed.to_string()));
1192                    last_consumed = i;
1193                    i += 1;
1194                }
1195
1196                // Nothing collected or only empty lines
1197                if fn_lines.iter().all(|l| matches!(l, FnLineType::Empty)) || fn_lines.is_empty() {
1198                    continue;
1199                }
1200
1201                // --- Group into blocks ---
1202                #[derive(Debug)]
1203                enum FnBlock {
1204                    Paragraph(Vec<String>),
1205                    Verbatim(Vec<(String, usize)>), // (content, indent) preserved as-is
1206                }
1207
1208                let mut blocks: Vec<FnBlock> = Vec::new();
1209                let mut current_para: Vec<String> = Vec::new();
1210                let mut current_verbatim: Vec<(String, usize)> = Vec::new();
1211
1212                for fl in &fn_lines {
1213                    match fl {
1214                        FnLineType::Content(s) => {
1215                            if !current_verbatim.is_empty() {
1216                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
1217                            }
1218                            current_para.push(s.clone());
1219                        }
1220                        FnLineType::Verbatim(s, indent) => {
1221                            if !current_para.is_empty() {
1222                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
1223                            }
1224                            current_verbatim.push((s.clone(), *indent));
1225                        }
1226                        FnLineType::Empty => {
1227                            if !current_para.is_empty() {
1228                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
1229                            }
1230                            if !current_verbatim.is_empty() {
1231                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
1232                            }
1233                        }
1234                    }
1235                }
1236                if !current_para.is_empty() {
1237                    blocks.push(FnBlock::Paragraph(current_para));
1238                }
1239                if !current_verbatim.is_empty() {
1240                    blocks.push(FnBlock::Verbatim(current_verbatim));
1241                }
1242
1243                // --- Reflow paragraphs and reconstruct ---
1244                let prefix_display_width = prefix.chars().count() + 1; // +1 for space
1245                let reflow_line_length = if config.line_length.is_unlimited() {
1246                    usize::MAX
1247                } else {
1248                    config
1249                        .line_length
1250                        .get()
1251                        .saturating_sub(FN_INDENT.max(prefix_display_width))
1252                        .max(20)
1253                };
1254                let reflow_options = crate::utils::text_reflow::ReflowOptions {
1255                    line_length: reflow_line_length,
1256                    break_on_sentences: true,
1257                    preserve_breaks: false,
1258                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
1259                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
1260                    abbreviations: config.abbreviations_for_reflow(),
1261                    length_mode: self.reflow_length_mode(),
1262                    attr_lists: ctx.flavor.supports_attr_lists(),
1263                    myst_roles: ctx.flavor.supports_myst_roles(),
1264                    require_sentence_capital: config.require_sentence_capital,
1265                    max_list_continuation_indent: None,
1266                };
1267
1268                let indent_str = " ".repeat(FN_INDENT);
1269                let mut result_lines: Vec<String> = Vec::new();
1270                let mut is_first_block = true;
1271
1272                for block in &blocks {
1273                    match block {
1274                        FnBlock::Paragraph(para_lines) => {
1275                            let paragraph_text = para_lines.join(" ");
1276                            let paragraph_text = paragraph_text.trim();
1277                            if paragraph_text.is_empty() {
1278                                continue;
1279                            }
1280
1281                            let reflowed = crate::utils::text_reflow::reflow_line(paragraph_text, &reflow_options);
1282                            if reflowed.is_empty() {
1283                                continue;
1284                            }
1285
1286                            // Blank line separator between blocks
1287                            if !result_lines.is_empty() {
1288                                result_lines.push(String::new());
1289                            }
1290
1291                            for (idx, rline) in reflowed.iter().enumerate() {
1292                                if is_first_block && idx == 0 {
1293                                    result_lines.push(format!("{prefix} {rline}"));
1294                                } else {
1295                                    result_lines.push(format!("{indent_str}{rline}"));
1296                                }
1297                            }
1298                            is_first_block = false;
1299                        }
1300                        FnBlock::Verbatim(verb_lines) => {
1301                            // Blank line separator between blocks
1302                            if !result_lines.is_empty() {
1303                                result_lines.push(String::new());
1304                            }
1305
1306                            if is_first_block {
1307                                // Verbatim as first block in a deferred-body footnote
1308                                if deferred_body {
1309                                    result_lines.push(prefix.to_string());
1310                                }
1311                                is_first_block = false;
1312                            }
1313                            for (content, _orig_indent) in verb_lines {
1314                                result_lines.push(format!("{indent_str}{content}"));
1315                            }
1316                        }
1317                    }
1318                }
1319
1320                // If nothing was produced, skip
1321                if result_lines.is_empty() {
1322                    continue;
1323                }
1324
1325                let reflowed_text = result_lines.join(line_ending);
1326
1327                // Calculate byte range using last_consumed
1328                let start_range = line_index.whole_line_range(footnote_start + 1);
1329                let end_range = if last_consumed == lines.len() - 1 && !ctx.content.ends_with('\n') {
1330                    line_index.line_text_range(last_consumed + 1, 1, lines[last_consumed].len() + 1)
1331                } else {
1332                    line_index.whole_line_range(last_consumed + 1)
1333                };
1334                let byte_range = start_range.start..end_range.end;
1335
1336                let replacement = if last_consumed < lines.len() - 1 || ctx.content.ends_with('\n') {
1337                    format!("{reflowed_text}{line_ending}")
1338                } else {
1339                    reflowed_text
1340                };
1341
1342                let original_text = &ctx.content[byte_range.clone()];
1343                let max_length = (footnote_start..=last_consumed)
1344                    .map(|idx| self.calculate_effective_length(lines[idx]))
1345                    .max()
1346                    .unwrap_or(0);
1347                let line_limit = if config.line_length.is_unlimited() {
1348                    usize::MAX
1349                } else {
1350                    config.line_length.get()
1351                };
1352                if original_text != replacement && max_length > line_limit {
1353                    warnings.push(LintWarning {
1354                        rule_name: Some(self.name().to_string()),
1355                        message: format!(
1356                            "Line length {} exceeds {} characters",
1357                            max_length,
1358                            config.line_length.get()
1359                        ),
1360                        line: footnote_start + 1,
1361                        column: 1,
1362                        end_line: last_consumed + 1,
1363                        end_column: lines[last_consumed].chars().count() + 1,
1364                        severity: Severity::Warning,
1365                        fix: Some(crate::rule::Fix::new(byte_range, replacement)),
1366                    });
1367                }
1368                continue;
1369            }
1370
1371            // Handle MkDocs container content (admonitions and tabs) with indent-preserving reflow
1372            if ctx
1373                .line_info(line_num)
1374                .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container)
1375            {
1376                // Skip admonition/tab marker lines — only reflow their indented content
1377                let current_line = lines[i];
1378                if mkdocs_admonitions::is_admonition_start(current_line) || mkdocs_tabs::is_tab_marker(current_line) {
1379                    i += 1;
1380                    continue;
1381                }
1382
1383                let container_start = i;
1384
1385                // Detect the actual indent level from the first content line
1386                // (supports nested admonitions with 8+ spaces)
1387                let first_line = lines[i];
1388                let base_indent_len = first_line.len() - first_line.trim_start().len();
1389                let base_indent: String = " ".repeat(base_indent_len);
1390
1391                // Collect consecutive MkDocs container paragraph lines
1392                let mut container_lines: Vec<&str> = Vec::new();
1393                while i < lines.len() {
1394                    let current_line_num = i + 1;
1395                    let line_info = ctx.line_info(current_line_num);
1396
1397                    // Stop if we leave the MkDocs container
1398                    if !line_info.is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container) {
1399                        break;
1400                    }
1401
1402                    let line = lines[i];
1403
1404                    // Stop at paragraph boundaries within the container
1405                    if line.trim().is_empty() {
1406                        break;
1407                    }
1408
1409                    // Skip list items, code blocks, headings, HTML-only lines within containers
1410                    if is_list_item(line.trim())
1411                        || line.trim().starts_with("```")
1412                        || line.trim().starts_with("~~~")
1413                        || line.trim().starts_with('#')
1414                        || is_html_only_line(line)
1415                    {
1416                        break;
1417                    }
1418
1419                    container_lines.push(line);
1420                    i += 1;
1421                }
1422
1423                if container_lines.is_empty() {
1424                    // Must advance i to avoid infinite loop when we encounter
1425                    // non-paragraph content (code block, list, heading, empty line)
1426                    // at the start of an MkDocs container
1427                    i += 1;
1428                    continue;
1429                }
1430
1431                // Strip the base indent from each line and join for reflow
1432                let stripped_lines: Vec<&str> = container_lines
1433                    .iter()
1434                    .map(|line| {
1435                        if line.starts_with(&base_indent) {
1436                            &line[base_indent_len..]
1437                        } else {
1438                            line.trim_start()
1439                        }
1440                    })
1441                    .collect();
1442                let paragraph_text = stripped_lines.join(" ");
1443
1444                // Check if reflow is needed
1445                let needs_reflow = match config.reflow_mode {
1446                    ReflowMode::Normalize => self.normalize_mode_needs_reflow(container_lines.iter().copied(), config),
1447                    ReflowMode::SentencePerLine => {
1448                        let sentences = split_into_sentences(&paragraph_text);
1449                        sentences.len() > 1 || container_lines.len() > 1
1450                    }
1451                    ReflowMode::SemanticLineBreaks => {
1452                        let sentences = split_into_sentences(&paragraph_text);
1453                        sentences.len() > 1
1454                            || container_lines.len() > 1
1455                            || container_lines
1456                                .iter()
1457                                .any(|line| self.calculate_effective_length(line) > config.line_length.get())
1458                    }
1459                    ReflowMode::Default => container_lines
1460                        .iter()
1461                        .any(|line| self.calculate_effective_length(line) > config.line_length.get()),
1462                };
1463
1464                if !needs_reflow {
1465                    continue;
1466                }
1467
1468                // Calculate byte range for this container paragraph
1469                let start_range = line_index.whole_line_range(container_start + 1);
1470                let end_line = container_start + container_lines.len() - 1;
1471                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
1472                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
1473                } else {
1474                    line_index.whole_line_range(end_line + 1)
1475                };
1476                let byte_range = start_range.start..end_range.end;
1477
1478                // Reflow with adjusted line length (accounting for the 4-space indent)
1479                let reflow_line_length = if config.line_length.is_unlimited() {
1480                    usize::MAX
1481                } else {
1482                    config.line_length.get().saturating_sub(base_indent_len).max(1)
1483                };
1484                let reflow_options = crate::utils::text_reflow::ReflowOptions {
1485                    line_length: reflow_line_length,
1486                    break_on_sentences: true,
1487                    preserve_breaks: false,
1488                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
1489                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
1490                    abbreviations: config.abbreviations_for_reflow(),
1491                    length_mode: self.reflow_length_mode(),
1492                    attr_lists: ctx.flavor.supports_attr_lists(),
1493                    myst_roles: ctx.flavor.supports_myst_roles(),
1494                    require_sentence_capital: config.require_sentence_capital,
1495                    max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
1496                        Some(4)
1497                    } else {
1498                        None
1499                    },
1500                };
1501                let reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);
1502
1503                // Re-add the 4-space indent to each reflowed line
1504                let reflowed_with_indent: Vec<String> =
1505                    reflowed.iter().map(|line| format!("{base_indent}{line}")).collect();
1506                let reflowed_text = reflowed_with_indent.join(line_ending);
1507
1508                // Preserve trailing newline
1509                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
1510                    format!("{reflowed_text}{line_ending}")
1511                } else {
1512                    reflowed_text
1513                };
1514
1515                // Only generate a warning if the replacement is different
1516                let original_text = &ctx.content[byte_range.clone()];
1517                if original_text != replacement {
1518                    warnings.push(LintWarning {
1519                        rule_name: Some(self.name().to_string()),
1520                        message: format!(
1521                            "Line length {} exceeds {} characters (in MkDocs container)",
1522                            container_lines.iter().map(|l| l.len()).max().unwrap_or(0),
1523                            config.line_length.get()
1524                        ),
1525                        line: container_start + 1,
1526                        column: 1,
1527                        end_line: end_line + 1,
1528                        end_column: lines[end_line].chars().count() + 1,
1529                        severity: Severity::Warning,
1530                        fix: Some(crate::rule::Fix::new(byte_range, replacement)),
1531                    });
1532                }
1533                continue;
1534            }
1535
1536            // Helper function to detect semantic line markers
1537            let is_semantic_line = |content: &str| -> bool {
1538                let trimmed = content.trim_start();
1539                let semantic_markers = [
1540                    "NOTE:",
1541                    "WARNING:",
1542                    "IMPORTANT:",
1543                    "CAUTION:",
1544                    "TIP:",
1545                    "DANGER:",
1546                    "HINT:",
1547                    "INFO:",
1548                ];
1549                semantic_markers.iter().any(|marker| trimmed.starts_with(marker))
1550            };
1551
1552            // Helper function to detect fence markers (opening or closing)
1553            let is_fence_marker = |content: &str| -> bool {
1554                let trimmed = content.trim_start();
1555                trimmed.starts_with("```") || trimmed.starts_with("~~~")
1556            };
1557
1558            // Check if this is a list item - handle it specially
1559            let trimmed = lines[i].trim();
1560            if is_list_item(trimmed) {
1561                // Collect the entire list item including continuation lines
1562                let list_start = i;
1563                let (marker, first_content) = extract_list_marker_and_content(lines[i]);
1564                let marker_len = marker.len();
1565
1566                // Checkbox ([ ]/[x]/[X]) is inline content, not part of the list marker.
1567                // Use the base bullet/number marker width for continuation recognition
1568                // so that continuation lines at 2+ spaces are collected for "- [ ] " items.
1569                let base_marker_len = if marker.contains("[ ] ") || marker.contains("[x] ") || marker.contains("[X] ") {
1570                    marker.find('[').unwrap_or(marker_len)
1571                } else {
1572                    marker_len
1573                };
1574
1575                // MkDocs flavor requires at least 4 spaces for list continuation
1576                // after a blank line (multi-paragraph list items). For non-blank
1577                // continuation (lines directly following the marker line), use
1578                // the natural marker width so that 2-space indent is recognized.
1579                let item_indent = ctx.lines[i].indent;
1580                let min_continuation_indent = if ctx.flavor.requires_strict_list_indent() {
1581                    // Use 4-space relative indent from the list item's nesting level
1582                    item_indent + (base_marker_len - item_indent).max(4)
1583                } else {
1584                    marker_len
1585                };
1586                let content_continuation_indent = base_marker_len;
1587
1588                // Track lines and their types (content, code block, fence, nested list)
1589                #[derive(Clone)]
1590                enum LineType {
1591                    Content(String),
1592                    CodeBlock(String, usize),         // content and original indent
1593                    SemanticLine(String), // Lines starting with NOTE:, WARNING:, etc that should stay separate
1594                    SnippetLine(String),  // MkDocs Snippets delimiters (-8<-) that must stay on their own line
1595                    DivMarker(String),    // Quarto/Pandoc div markers (::: opening or closing)
1596                    AdmonitionHeader(String, usize), // header text (e.g. "!!! note") and original indent
1597                    AdmonitionContent(String, usize), // body content text and original indent
1598                    Table(String, usize), // GFM table row, preserved verbatim with original indent
1599                    Empty,
1600                }
1601
1602                let mut list_item_lines: Vec<LineType> = vec![LineType::Content(first_content)];
1603                i += 1;
1604
1605                // Collect continuation lines using ctx.lines for metadata
1606                while i < lines.len() {
1607                    let line_info = &ctx.lines[i];
1608
1609                    // Use pre-computed is_blank from ctx
1610                    if line_info.is_blank {
1611                        // Empty line - check if next line is indented (part of list item)
1612                        if i + 1 < lines.len() {
1613                            let next_info = &ctx.lines[i + 1];
1614
1615                            // Check if next line is indented enough to be continuation
1616                            if !next_info.is_blank && next_info.indent >= min_continuation_indent {
1617                                // This blank line is between paragraphs/blocks in the list item
1618                                list_item_lines.push(LineType::Empty);
1619                                i += 1;
1620                                continue;
1621                            }
1622                        }
1623                        // No indented line after blank, end of list item
1624                        break;
1625                    }
1626
1627                    // Use pre-computed indent from ctx
1628                    let indent = line_info.indent;
1629
1630                    // Valid continuation must be indented at least content_continuation_indent.
1631                    // For non-blank continuation, use marker_len (e.g. 2 for "- ").
1632                    // MkDocs strict 4-space requirement applies only after blank lines.
1633                    if indent >= content_continuation_indent {
1634                        let trimmed = line_info.content(ctx.content).trim();
1635
1636                        // Check for MkDocs admonition lines inside list items BEFORE
1637                        // checking in_code_block. Lines inside code blocks within
1638                        // admonitions have both in_admonition and in_code_block set;
1639                        // admonition membership takes priority so the entire admonition
1640                        // structure (including embedded code blocks) is preserved.
1641                        if line_info.in_admonition {
1642                            let raw_content = line_info.content(ctx.content);
1643                            if mkdocs_admonitions::is_admonition_start(raw_content) {
1644                                let header_text = raw_content[indent..].trim_end().to_string();
1645                                list_item_lines.push(LineType::AdmonitionHeader(header_text, indent));
1646                            } else {
1647                                let body_text = raw_content[indent..].trim_end().to_string();
1648                                list_item_lines.push(LineType::AdmonitionContent(body_text, indent));
1649                            }
1650                            i += 1;
1651                            continue;
1652                        }
1653
1654                        // Use pre-computed in_code_block from ctx
1655                        if line_info.in_code_block {
1656                            list_item_lines.push(LineType::CodeBlock(
1657                                line_info.content(ctx.content)[indent..].to_string(),
1658                                indent,
1659                            ));
1660                            i += 1;
1661                            continue;
1662                        }
1663
1664                        // Check if this is a SIBLING list item (breaks parent)
1665                        // Nested lists are indented >= marker_len and are PART of the parent item
1666                        // Siblings are at indent < marker_len (at or before parent marker)
1667                        if is_list_item(trimmed) && indent < marker_len {
1668                            // This is a sibling item at same or higher level - end parent item
1669                            break;
1670                        }
1671
1672                        // Nested list items are always processed independently
1673                        // by the outer loop, so break when we encounter one.
1674                        // If a blank line was collected before this, uncollect it
1675                        // so the outer loop preserves the blank between parent and nested.
1676                        if is_list_item(trimmed) && indent >= marker_len {
1677                            if matches!(list_item_lines.last(), Some(LineType::Empty)) {
1678                                list_item_lines.pop();
1679                                i -= 1;
1680                            }
1681                            break;
1682                        }
1683
1684                        // Normal continuation vs indented code block.
1685                        // Use min_continuation_indent for the threshold since
1686                        // code blocks start 4 spaces beyond the expected content
1687                        // level (which is min_continuation_indent for MkDocs).
1688                        if indent <= min_continuation_indent + 3 {
1689                            // Extract content (remove indentation and trailing whitespace)
1690                            // Preserve hard breaks (2 trailing spaces) while removing excessive whitespace
1691                            // See: https://github.com/rvben/rumdl/issues/76
1692                            let content = trim_preserving_hard_break(&line_info.content(ctx.content)[indent..]);
1693
1694                            // Check if this is a div marker (::: opening or closing)
1695                            // These must be preserved on their own line, not merged into paragraphs
1696                            if line_info.is_div_marker {
1697                                list_item_lines.push(LineType::DivMarker(content));
1698                            }
1699                            // Check if this is a fence marker (opening or closing)
1700                            // These should be treated as code block lines, not paragraph content
1701                            else if is_fence_marker(&content) {
1702                                list_item_lines.push(LineType::CodeBlock(content, indent));
1703                            }
1704                            // Check if this is a semantic line (NOTE:, WARNING:, etc.)
1705                            else if is_semantic_line(&content) {
1706                                list_item_lines.push(LineType::SemanticLine(content));
1707                            }
1708                            // Check if this is a snippet block delimiter (-8<- or --8<--)
1709                            // These must be preserved on their own lines for MkDocs Snippets extension
1710                            else if is_snippet_block_delimiter(&content) {
1711                                list_item_lines.push(LineType::SnippetLine(content));
1712                            }
1713                            // Check if this is a GFM table row. Tables nested inside list
1714                            // items must be preserved verbatim — joining them with prose
1715                            // breaks the column structure.
1716                            //
1717                            // `is_potential_table_row` is intentionally permissive at the
1718                            // row level: any line with `|` and 2+ cells qualifies. To avoid
1719                            // misclassifying prose continuation lines that contain a literal
1720                            // pipe (e.g. "use grep | sort to ..."), require one of:
1721                            //   - the row is pipe-bordered (`| ... |`), the canonical form
1722                            //     for tables nested in lists; or
1723                            //   - the next line is a delimiter row (this is a header); or
1724                            //   - the previous classified line was already a Table (this is
1725                            //     a continuation row).
1726                            else if TableUtils::is_potential_table_row(&content) && {
1727                                let pipe_bordered = content.trim().starts_with('|') && content.trim().ends_with('|');
1728                                let next_is_delim = ctx
1729                                    .lines
1730                                    .get(i + 1)
1731                                    .is_some_and(|next| TableUtils::is_delimiter_row(next.content(ctx.content)));
1732                                let prev_was_table = matches!(list_item_lines.last(), Some(LineType::Table(..)));
1733                                pipe_bordered || next_is_delim || prev_was_table
1734                            } {
1735                                list_item_lines.push(LineType::Table(content, indent));
1736                            } else {
1737                                list_item_lines.push(LineType::Content(content));
1738                            }
1739                            i += 1;
1740                        } else {
1741                            // indent >= min_continuation_indent + 4: indented code block
1742                            list_item_lines.push(LineType::CodeBlock(
1743                                line_info.content(ctx.content)[indent..].to_string(),
1744                                indent,
1745                            ));
1746                            i += 1;
1747                        }
1748                    } else {
1749                        // Not indented enough, end of list item
1750                        break;
1751                    }
1752                }
1753
1754                // Determine the output continuation indent.
1755                // Normalize/Default modes canonicalize to min_continuation_indent
1756                // (fixing over-indented continuation). Semantic/SentencePerLine
1757                // modes preserve the user's actual indent since they only fix
1758                // line breaking, not indentation.
1759                let indent_size = match config.reflow_mode {
1760                    ReflowMode::SemanticLineBreaks | ReflowMode::SentencePerLine => {
1761                        // Find indent of the first plain text continuation line,
1762                        // skipping the marker line (index 0), nested list items,
1763                        // code blocks, and blank lines.
1764                        list_item_lines
1765                            .iter()
1766                            .enumerate()
1767                            .skip(1)
1768                            .find_map(|(k, lt)| {
1769                                if matches!(lt, LineType::Content(_)) {
1770                                    Some(ctx.lines[list_start + k].indent)
1771                                } else {
1772                                    None
1773                                }
1774                            })
1775                            .unwrap_or(min_continuation_indent)
1776                    }
1777                    _ => min_continuation_indent,
1778                };
1779                // For checkbox items in mkdocs flavor, enforce minimum indent so
1780                // continuation lines use the structural list indent (4), not the
1781                // content-aligned indent (6) which Python-Markdown doesn't support
1782                let has_checkbox = base_marker_len < marker_len;
1783                let indent_size = if has_checkbox && ctx.flavor.requires_strict_list_indent() {
1784                    indent_size.max(min_continuation_indent)
1785                } else {
1786                    indent_size
1787                };
1788                let expected_indent = " ".repeat(indent_size);
1789
1790                // Split list_item_lines into blocks (paragraphs, code blocks, nested lists, semantic lines, and HTML blocks)
1791                let mut builder = BlockBuilder::new();
1792                for line in &list_item_lines {
1793                    match line {
1794                        LineType::Empty => builder.feed_blank_line(),
1795                        LineType::Content(content) => builder.feed_content(content),
1796                        LineType::CodeBlock(content, indent) => builder.feed_code_line(content, *indent),
1797                        LineType::SemanticLine(content) => builder.feed_semantic_line(content),
1798                        LineType::SnippetLine(content) => builder.feed_snippet_line(content),
1799                        LineType::DivMarker(content) => builder.feed_div_marker(content),
1800                        LineType::AdmonitionHeader(header_text, indent) => {
1801                            builder.feed_admonition_header(header_text, *indent)
1802                        }
1803                        LineType::AdmonitionContent(content, indent) => {
1804                            builder.feed_admonition_content(content, *indent)
1805                        }
1806                        LineType::Table(content, indent) => builder.feed_table_line(content, *indent),
1807                    }
1808                }
1809                let blocks = builder.finalize();
1810
1811                // Helper: check if a line (raw source or stripped content) is exempt
1812                // from line-length checks. Link reference definitions are always exempt;
1813                // standalone link/image lines are exempt when strict mode is off.
1814                // Also checks content after stripping list markers, since list item
1815                // continuation lines may contain link ref defs.
1816                let is_exempt_line = |raw_line: &str| -> bool {
1817                    let trimmed = raw_line.trim();
1818                    // Link reference definitions: always exempt
1819                    if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
1820                        return true;
1821                    }
1822                    // Also check after stripping list markers (for list item content)
1823                    if is_list_item(trimmed) {
1824                        let (_, content) = extract_list_marker_and_content(trimmed);
1825                        let content_trimmed = content.trim();
1826                        if content_trimmed.starts_with('[')
1827                            && content_trimmed.contains("]:")
1828                            && LINK_REF_PATTERN.is_match(content_trimmed)
1829                        {
1830                            return true;
1831                        }
1832                    }
1833                    // Standalone link/image lines: exempt when not strict
1834                    if !config.strict && is_standalone_link_or_image_line(raw_line) {
1835                        return true;
1836                    }
1837                    // HTML-only lines: exempt when not strict
1838                    if !config.strict && is_html_only_line(raw_line) {
1839                        return true;
1840                    }
1841                    false
1842                };
1843
1844                // Check if reflowing is needed (only for content paragraphs, not code blocks or nested lists)
1845                // Exclude link reference definitions and standalone link lines from content
1846                // so they don't pollute combined_content or trigger false reflow.
1847                let content_lines: Vec<String> = list_item_lines
1848                    .iter()
1849                    .filter_map(|line| {
1850                        if let LineType::Content(s) = line {
1851                            if is_exempt_line(s) {
1852                                return None;
1853                            }
1854                            Some(s.clone())
1855                        } else {
1856                            None
1857                        }
1858                    })
1859                    .collect();
1860
1861                // Check if we need to reflow this list item
1862                // We check the combined content to see if it exceeds length limits
1863                let combined_content = content_lines.join(" ").trim().to_string();
1864
1865                // Helper to check if we should reflow in normalize mode
1866                let should_normalize = || {
1867                    // Don't normalize if the list item only contains nested lists, code blocks, or semantic lines
1868                    // DO normalize if it has plain text content that spans multiple lines
1869                    let has_code_blocks = blocks.iter().any(|b| matches!(b, Block::Code { .. }));
1870                    let has_semantic_lines = blocks.iter().any(|b| matches!(b, Block::SemanticLine(_)));
1871                    let has_snippet_lines = blocks.iter().any(|b| matches!(b, Block::SnippetLine(_)));
1872                    let has_div_markers = blocks.iter().any(|b| matches!(b, Block::DivMarker(_)));
1873                    let has_admonitions = blocks.iter().any(|b| matches!(b, Block::Admonition { .. }));
1874                    let has_tables = blocks.iter().any(|b| matches!(b, Block::Table { .. }));
1875                    let has_paragraphs = blocks.iter().any(|b| matches!(b, Block::Paragraph(_)));
1876
1877                    // If we have structural blocks but no paragraphs, don't normalize
1878                    if (has_code_blocks
1879                        || has_semantic_lines
1880                        || has_snippet_lines
1881                        || has_div_markers
1882                        || has_admonitions
1883                        || has_tables)
1884                        && !has_paragraphs
1885                    {
1886                        return false;
1887                    }
1888
1889                    // If we have paragraphs, check if they span multiple lines or there are multiple blocks
1890                    if has_paragraphs {
1891                        // Count only paragraphs that contain at least one non-exempt line.
1892                        // Paragraphs consisting entirely of link ref defs or standalone links
1893                        // should not trigger normalization.
1894                        let paragraph_count = blocks
1895                            .iter()
1896                            .filter(|b| {
1897                                if let Block::Paragraph(para_lines) = b {
1898                                    !para_lines.iter().all(|line| is_exempt_line(line))
1899                                } else {
1900                                    false
1901                                }
1902                            })
1903                            .count();
1904                        if paragraph_count > 1 {
1905                            // Multiple non-exempt paragraph blocks should be normalized
1906                            return true;
1907                        }
1908
1909                        // Single paragraph block: normalize if it has multiple content lines
1910                        if content_lines.len() > 1 {
1911                            return true;
1912                        }
1913                    }
1914
1915                    false
1916                };
1917
1918                let needs_reflow = match config.reflow_mode {
1919                    ReflowMode::Normalize => {
1920                        // Only reflow if:
1921                        // 1. Any non-exempt paragraph, when joined, exceeds the limit, OR
1922                        // 2. Any admonition content line exceeds the limit, OR
1923                        // 3. The list item should be normalized (has multi-line plain text)
1924                        let any_paragraph_exceeds = blocks.iter().any(|block| match block {
1925                            Block::Paragraph(para_lines) => {
1926                                if para_lines.iter().all(|line| is_exempt_line(line)) {
1927                                    return false;
1928                                }
1929                                let joined = para_lines.join(" ");
1930                                let with_marker = format!("{}{}", " ".repeat(indent_size), joined.trim());
1931                                self.calculate_effective_length(&with_marker) > config.line_length.get()
1932                            }
1933                            Block::Admonition {
1934                                content_lines,
1935                                header_indent,
1936                                ..
1937                            } => content_lines.iter().any(|(content, indent)| {
1938                                if content.is_empty() {
1939                                    return false;
1940                                }
1941                                let with_indent = format!("{}{}", " ".repeat(*indent.max(header_indent)), content);
1942                                self.calculate_effective_length(&with_indent) > config.line_length.get()
1943                            }),
1944                            _ => false,
1945                        });
1946                        if any_paragraph_exceeds {
1947                            true
1948                        } else {
1949                            should_normalize()
1950                        }
1951                    }
1952                    ReflowMode::SentencePerLine => {
1953                        // Check if list item has multiple sentences
1954                        let sentences = split_into_sentences(&combined_content);
1955                        sentences.len() > 1
1956                    }
1957                    ReflowMode::SemanticLineBreaks => {
1958                        let sentences = split_into_sentences(&combined_content);
1959                        sentences.len() > 1
1960                            || (list_start..i).any(|line_idx| {
1961                                let line = lines[line_idx];
1962                                let trimmed = line.trim();
1963                                if trimmed.is_empty() || is_exempt_line(line) {
1964                                    return false;
1965                                }
1966                                self.calculate_effective_length(line) > config.line_length.get()
1967                            })
1968                    }
1969                    ReflowMode::Default => {
1970                        // In default mode, only reflow if any individual non-exempt line exceeds limit
1971                        (list_start..i).any(|line_idx| {
1972                            let line = lines[line_idx];
1973                            let trimmed = line.trim();
1974                            // Skip blank lines and exempt lines
1975                            if trimmed.is_empty() || is_exempt_line(line) {
1976                                return false;
1977                            }
1978                            self.calculate_effective_length(line) > config.line_length.get()
1979                        })
1980                    }
1981                };
1982
1983                if needs_reflow {
1984                    let start_range = line_index.whole_line_range(list_start + 1);
1985                    let end_line = i - 1;
1986                    let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
1987                        line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
1988                    } else {
1989                        line_index.whole_line_range(end_line + 1)
1990                    };
1991                    let byte_range = start_range.start..end_range.end;
1992
1993                    // Reflow each block (paragraphs only, preserve code blocks)
1994                    // When line_length = 0 (no limit), use a very large value for reflow
1995                    let reflow_line_length = if config.line_length.is_unlimited() {
1996                        usize::MAX
1997                    } else {
1998                        config.line_length.get().saturating_sub(indent_size).max(1)
1999                    };
2000                    let reflow_options = crate::utils::text_reflow::ReflowOptions {
2001                        line_length: reflow_line_length,
2002                        break_on_sentences: true,
2003                        preserve_breaks: false,
2004                        sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
2005                        semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
2006                        abbreviations: config.abbreviations_for_reflow(),
2007                        length_mode: self.reflow_length_mode(),
2008                        attr_lists: ctx.flavor.supports_attr_lists(),
2009                        myst_roles: ctx.flavor.supports_myst_roles(),
2010                        require_sentence_capital: config.require_sentence_capital,
2011                        max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
2012                            Some(4)
2013                        } else {
2014                            None
2015                        },
2016                    };
2017
2018                    let mut result: Vec<String> = Vec::new();
2019                    let mut is_first_block = true;
2020
2021                    for (block_idx, block) in blocks.iter().enumerate() {
2022                        match block {
2023                            Block::Paragraph(para_lines) => {
2024                                // If every line in this paragraph is exempt (link ref defs,
2025                                // standalone links), preserve the paragraph verbatim instead
2026                                // of reflowing it. Reflowing would corrupt link ref defs.
2027                                let all_exempt = para_lines.iter().all(|line| is_exempt_line(line));
2028
2029                                if all_exempt {
2030                                    for (idx, line) in para_lines.iter().enumerate() {
2031                                        if is_first_block && idx == 0 {
2032                                            result.push(format!("{marker}{line}"));
2033                                            is_first_block = false;
2034                                        } else {
2035                                            result.push(format!("{expected_indent}{line}"));
2036                                        }
2037                                    }
2038                                } else {
2039                                    // Split the paragraph into segments at hard break boundaries
2040                                    // Each segment can be reflowed independently
2041                                    let segments = split_into_segments(para_lines);
2042
2043                                    for (segment_idx, segment) in segments.iter().enumerate() {
2044                                        // Check if this segment ends with a hard break and what type
2045                                        let hard_break_type = segment.last().and_then(|line| {
2046                                            let line = line.strip_suffix('\r').unwrap_or(line);
2047                                            if line.ends_with('\\') {
2048                                                Some("\\")
2049                                            } else if line.ends_with("  ") {
2050                                                Some("  ")
2051                                            } else {
2052                                                None
2053                                            }
2054                                        });
2055
2056                                        // Join and reflow the segment (removing the hard break marker for processing)
2057                                        let segment_for_reflow: Vec<String> = segment
2058                                            .iter()
2059                                            .map(|line| {
2060                                                // Strip hard break marker (2 spaces or backslash) for reflow processing
2061                                                if line.ends_with('\\') {
2062                                                    line[..line.len() - 1].trim_end().to_string()
2063                                                } else if line.ends_with("  ") {
2064                                                    line[..line.len() - 2].trim_end().to_string()
2065                                                } else {
2066                                                    line.clone()
2067                                                }
2068                                            })
2069                                            .collect();
2070
2071                                        let segment_text = segment_for_reflow.join(" ").trim().to_string();
2072                                        if !segment_text.is_empty() {
2073                                            let reflowed =
2074                                                crate::utils::text_reflow::reflow_line(&segment_text, &reflow_options);
2075
2076                                            if is_first_block && segment_idx == 0 {
2077                                                // First segment of first block starts with marker
2078                                                result.push(format!("{marker}{}", reflowed[0]));
2079                                                for line in reflowed.iter().skip(1) {
2080                                                    result.push(format!("{expected_indent}{line}"));
2081                                                }
2082                                                is_first_block = false;
2083                                            } else {
2084                                                // Subsequent segments
2085                                                for line in reflowed {
2086                                                    result.push(format!("{expected_indent}{line}"));
2087                                                }
2088                                            }
2089
2090                                            // If this segment had a hard break, add it back to the last line
2091                                            // Preserve the original hard break format (backslash or two spaces)
2092                                            if let Some(break_marker) = hard_break_type
2093                                                && let Some(last_line) = result.last_mut()
2094                                            {
2095                                                last_line.push_str(break_marker);
2096                                            }
2097                                        }
2098                                    }
2099                                }
2100
2101                                // Add blank line after paragraph block if there's a next block.
2102                                // Check if next block is a code block that doesn't want a preceding blank.
2103                                // Also don't add blank lines before snippet lines (they should stay tight).
2104                                // Only add if not already ending with one (avoids double blanks).
2105                                if block_idx < blocks.len() - 1 {
2106                                    let next_block = &blocks[block_idx + 1];
2107                                    let should_add_blank = match next_block {
2108                                        Block::Code {
2109                                            has_preceding_blank, ..
2110                                        } => *has_preceding_blank,
2111                                        Block::Table {
2112                                            has_preceding_blank, ..
2113                                        } => *has_preceding_blank,
2114                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2115                                        _ => true, // For all other blocks, add blank line
2116                                    };
2117                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2118                                        result.push(String::new());
2119                                    }
2120                                }
2121                            }
2122                            Block::Code {
2123                                lines: code_lines,
2124                                has_preceding_blank: _,
2125                            } => {
2126                                // Preserve code blocks as-is with original indentation
2127                                // NOTE: Blank line before code block is handled by the previous block
2128                                // (see paragraph block's logic above)
2129
2130                                for (idx, (content, orig_indent)) in code_lines.iter().enumerate() {
2131                                    if is_first_block && idx == 0 {
2132                                        // First line of first block gets marker
2133                                        result.push(format!(
2134                                            "{marker}{}",
2135                                            " ".repeat(orig_indent - marker_len) + content
2136                                        ));
2137                                        is_first_block = false;
2138                                    } else if content.is_empty() {
2139                                        result.push(String::new());
2140                                    } else {
2141                                        result.push(format!("{}{}", " ".repeat(*orig_indent), content));
2142                                    }
2143                                }
2144                            }
2145                            Block::SemanticLine(content) => {
2146                                // Preserve semantic lines (NOTE:, WARNING:, etc.) as-is on their own line.
2147                                // Only add blank before if not already ending with one.
2148                                if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2149                                    result.push(String::new());
2150                                }
2151
2152                                if is_first_block {
2153                                    // First block starts with marker
2154                                    result.push(format!("{marker}{content}"));
2155                                    is_first_block = false;
2156                                } else {
2157                                    // Subsequent blocks use expected indent
2158                                    result.push(format!("{expected_indent}{content}"));
2159                                }
2160
2161                                // Add blank line after semantic line if there's a next block.
2162                                // Only add if not already ending with one.
2163                                if block_idx < blocks.len() - 1 {
2164                                    let next_block = &blocks[block_idx + 1];
2165                                    let should_add_blank = match next_block {
2166                                        Block::Code {
2167                                            has_preceding_blank, ..
2168                                        } => *has_preceding_blank,
2169                                        Block::Table {
2170                                            has_preceding_blank, ..
2171                                        } => *has_preceding_blank,
2172                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2173                                        _ => true, // For all other blocks, add blank line
2174                                    };
2175                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2176                                        result.push(String::new());
2177                                    }
2178                                }
2179                            }
2180                            Block::SnippetLine(content) => {
2181                                // Preserve snippet delimiters (-8<-) as-is on their own line
2182                                // Unlike semantic lines, snippet lines don't add extra blank lines
2183                                if is_first_block {
2184                                    // First block starts with marker
2185                                    result.push(format!("{marker}{content}"));
2186                                    is_first_block = false;
2187                                } else {
2188                                    // Subsequent blocks use expected indent
2189                                    result.push(format!("{expected_indent}{content}"));
2190                                }
2191                                // No blank lines added before or after snippet delimiters
2192                            }
2193                            Block::DivMarker(content) => {
2194                                // Preserve div markers (::: opening or closing) as-is on their own line
2195                                if is_first_block {
2196                                    result.push(format!("{marker}{content}"));
2197                                    is_first_block = false;
2198                                } else {
2199                                    result.push(format!("{expected_indent}{content}"));
2200                                }
2201                            }
2202                            Block::Html {
2203                                lines: html_lines,
2204                                has_preceding_blank: _,
2205                            } => {
2206                                // Preserve HTML blocks exactly as-is with original indentation
2207                                // NOTE: Blank line before HTML block is handled by the previous block
2208
2209                                for (idx, line) in html_lines.iter().enumerate() {
2210                                    if is_first_block && idx == 0 {
2211                                        // First line of first block gets marker
2212                                        result.push(format!("{marker}{line}"));
2213                                        is_first_block = false;
2214                                    } else if line.is_empty() {
2215                                        // Preserve blank lines inside HTML blocks
2216                                        result.push(String::new());
2217                                    } else {
2218                                        // Preserve lines with their original content (already includes indentation)
2219                                        result.push(format!("{expected_indent}{line}"));
2220                                    }
2221                                }
2222
2223                                // Add blank line after HTML block if there's a next block.
2224                                // Only add if not already ending with one (avoids double blanks
2225                                // when the HTML block itself contained a trailing blank line).
2226                                if block_idx < blocks.len() - 1 {
2227                                    let next_block = &blocks[block_idx + 1];
2228                                    let should_add_blank = match next_block {
2229                                        Block::Code {
2230                                            has_preceding_blank, ..
2231                                        } => *has_preceding_blank,
2232                                        Block::Html {
2233                                            has_preceding_blank, ..
2234                                        } => *has_preceding_blank,
2235                                        Block::Table {
2236                                            has_preceding_blank, ..
2237                                        } => *has_preceding_blank,
2238                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2239                                        _ => true, // For all other blocks, add blank line
2240                                    };
2241                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2242                                        result.push(String::new());
2243                                    }
2244                                }
2245                            }
2246                            Block::Table {
2247                                lines: table_lines,
2248                                has_preceding_blank: _,
2249                            } => {
2250                                // Preserve table rows verbatim with their original indentation.
2251                                // Reflowing rows would corrupt column alignment and inject `|`
2252                                // characters mid-paragraph (issue #590).
2253                                // The leading blank line is emitted by the previous block.
2254                                for (idx, (content, orig_indent)) in table_lines.iter().enumerate() {
2255                                    if is_first_block && idx == 0 {
2256                                        // First line of first block gets the list marker
2257                                        result.push(format!(
2258                                            "{marker}{}",
2259                                            " ".repeat(orig_indent.saturating_sub(marker_len)) + content
2260                                        ));
2261                                        is_first_block = false;
2262                                    } else {
2263                                        result.push(format!("{}{}", " ".repeat(*orig_indent), content));
2264                                    }
2265                                }
2266
2267                                // Add blank line after table block if there's a next block.
2268                                if block_idx < blocks.len() - 1 {
2269                                    let next_block = &blocks[block_idx + 1];
2270                                    let should_add_blank = match next_block {
2271                                        Block::Code {
2272                                            has_preceding_blank, ..
2273                                        } => *has_preceding_blank,
2274                                        Block::Html {
2275                                            has_preceding_blank, ..
2276                                        } => *has_preceding_blank,
2277                                        Block::Table {
2278                                            has_preceding_blank, ..
2279                                        } => *has_preceding_blank,
2280                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2281                                        _ => true,
2282                                    };
2283                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2284                                        result.push(String::new());
2285                                    }
2286                                }
2287                            }
2288                            Block::Admonition {
2289                                header,
2290                                header_indent,
2291                                content_lines: admon_lines,
2292                            } => {
2293                                // Reconstruct admonition block with header at original indent
2294                                // and body content reflowed to fit within the line length limit
2295
2296                                // Add blank line before admonition if not first block
2297                                if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2298                                    result.push(String::new());
2299                                }
2300
2301                                // Output the header at its original indent
2302                                let header_indent_str = " ".repeat(*header_indent);
2303                                if is_first_block {
2304                                    result.push(format!(
2305                                        "{marker}{}",
2306                                        " ".repeat(header_indent.saturating_sub(marker_len)) + header
2307                                    ));
2308                                    is_first_block = false;
2309                                } else {
2310                                    result.push(format!("{header_indent_str}{header}"));
2311                                }
2312
2313                                // Derive body indent from the first non-empty content line's
2314                                // stored indent, falling back to header_indent + 4 for
2315                                // empty-body admonitions
2316                                let body_indent = admon_lines
2317                                    .iter()
2318                                    .find(|(content, _)| !content.is_empty())
2319                                    .map_or(header_indent + 4, |(_, indent)| *indent);
2320                                let body_indent_str = " ".repeat(body_indent);
2321
2322                                // Segment body content into code blocks (verbatim) and
2323                                // text paragraphs (reflowable), separated by blank lines.
2324                                // Code lines store (content, orig_indent) to reconstruct
2325                                // internal indentation relative to body_indent.
2326                                enum AdmonSegment {
2327                                    Text(Vec<String>),
2328                                    Code(Vec<(String, usize)>),
2329                                }
2330
2331                                let mut segments: Vec<AdmonSegment> = Vec::new();
2332                                let mut current_text: Vec<String> = Vec::new();
2333                                let mut current_code: Vec<(String, usize)> = Vec::new();
2334                                let mut in_admon_code = false;
2335                                // Track the opening fence character so closing fences
2336                                // must match (backticks close backticks, tildes close tildes)
2337                                let mut fence_char: char = '`';
2338
2339                                // Opening fences: ``` or ~~~ followed by optional info string
2340                                let get_opening_fence = |s: &str| -> Option<(char, usize)> {
2341                                    let t = s.trim_start();
2342                                    if t.starts_with("```") {
2343                                        Some(('`', t.bytes().take_while(|&b| b == b'`').count()))
2344                                    } else if t.starts_with("~~~") {
2345                                        Some(('~', t.bytes().take_while(|&b| b == b'~').count()))
2346                                    } else {
2347                                        None
2348                                    }
2349                                };
2350                                // Closing fences: ONLY fence chars + optional trailing spaces
2351                                let get_closing_fence = |s: &str| -> Option<(char, usize)> {
2352                                    let t = s.trim();
2353                                    if t.starts_with("```") && t.bytes().all(|b| b == b'`') {
2354                                        Some(('`', t.len()))
2355                                    } else if t.starts_with("~~~") && t.bytes().all(|b| b == b'~') {
2356                                        Some(('~', t.len()))
2357                                    } else {
2358                                        None
2359                                    }
2360                                };
2361                                let mut fence_len: usize = 3;
2362
2363                                for (content, orig_indent) in admon_lines {
2364                                    if in_admon_code {
2365                                        // Closing fence must use the same character, be
2366                                        // at least as long, and have no info string
2367                                        if let Some((ch, len)) = get_closing_fence(content)
2368                                            && ch == fence_char
2369                                            && len >= fence_len
2370                                        {
2371                                            current_code.push((content.clone(), *orig_indent));
2372                                            in_admon_code = false;
2373                                            segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2374                                            continue;
2375                                        }
2376                                        current_code.push((content.clone(), *orig_indent));
2377                                    } else if let Some((ch, len)) = get_opening_fence(content) {
2378                                        if !current_text.is_empty() {
2379                                            segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2380                                        }
2381                                        in_admon_code = true;
2382                                        fence_char = ch;
2383                                        fence_len = len;
2384                                        current_code.push((content.clone(), *orig_indent));
2385                                    } else if content.is_empty() {
2386                                        if !current_text.is_empty() {
2387                                            segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2388                                        }
2389                                    } else {
2390                                        current_text.push(content.clone());
2391                                    }
2392                                }
2393                                if in_admon_code && !current_code.is_empty() {
2394                                    segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2395                                }
2396                                if !current_text.is_empty() {
2397                                    segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2398                                }
2399
2400                                // Build reflow options once for all text segments
2401                                let admon_reflow_length = if config.line_length.is_unlimited() {
2402                                    usize::MAX
2403                                } else {
2404                                    config.line_length.get().saturating_sub(body_indent).max(1)
2405                                };
2406
2407                                let admon_reflow_options = crate::utils::text_reflow::ReflowOptions {
2408                                    line_length: admon_reflow_length,
2409                                    break_on_sentences: true,
2410                                    preserve_breaks: false,
2411                                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
2412                                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
2413                                    abbreviations: config.abbreviations_for_reflow(),
2414                                    length_mode: self.reflow_length_mode(),
2415                                    attr_lists: ctx.flavor.supports_attr_lists(),
2416                                    myst_roles: ctx.flavor.supports_myst_roles(),
2417                                    require_sentence_capital: config.require_sentence_capital,
2418                                    max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
2419                                        Some(4)
2420                                    } else {
2421                                        None
2422                                    },
2423                                };
2424
2425                                // Output each segment
2426                                for segment in &segments {
2427                                    // Blank line before each segment (after the header or previous segment)
2428                                    result.push(String::new());
2429
2430                                    match segment {
2431                                        AdmonSegment::Code(lines) => {
2432                                            for (line, orig_indent) in lines {
2433                                                if line.is_empty() {
2434                                                    // Preserve blank lines inside code blocks
2435                                                    result.push(String::new());
2436                                                } else {
2437                                                    // Reconstruct with body_indent + any extra
2438                                                    // indentation the line had beyond body_indent
2439                                                    let extra = orig_indent.saturating_sub(body_indent);
2440                                                    let indent_str = " ".repeat(body_indent + extra);
2441                                                    result.push(format!("{indent_str}{line}"));
2442                                                }
2443                                            }
2444                                        }
2445                                        AdmonSegment::Text(lines) => {
2446                                            let paragraph_text = lines.join(" ").trim().to_string();
2447                                            if paragraph_text.is_empty() {
2448                                                continue;
2449                                            }
2450                                            let reflowed = crate::utils::text_reflow::reflow_line(
2451                                                &paragraph_text,
2452                                                &admon_reflow_options,
2453                                            );
2454                                            for line in &reflowed {
2455                                                result.push(format!("{body_indent_str}{line}"));
2456                                            }
2457                                        }
2458                                    }
2459                                }
2460
2461                                // Add blank line after admonition if there's a next block
2462                                if block_idx < blocks.len() - 1 {
2463                                    let next_block = &blocks[block_idx + 1];
2464                                    let should_add_blank = match next_block {
2465                                        Block::Code {
2466                                            has_preceding_blank, ..
2467                                        } => *has_preceding_blank,
2468                                        Block::Table {
2469                                            has_preceding_blank, ..
2470                                        } => *has_preceding_blank,
2471                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
2472                                        _ => true,
2473                                    };
2474                                    if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2475                                        result.push(String::new());
2476                                    }
2477                                }
2478                            }
2479                        }
2480                    }
2481
2482                    let reflowed_text = result.join(line_ending);
2483
2484                    // Preserve trailing newline
2485                    let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
2486                        format!("{reflowed_text}{line_ending}")
2487                    } else {
2488                        reflowed_text
2489                    };
2490
2491                    // Get the original text to compare
2492                    let original_text = &ctx.content[byte_range.clone()];
2493
2494                    // Physical-line-length scan, shared by the Normalize-mode gate and its
2495                    // message. The list-item reflow preserves code blocks, HTML blocks,
2496                    // admonition headers, fence markers, semantic markers, and snippet/div
2497                    // markers verbatim; only paragraph content and admonition bodies are
2498                    // restructured. Only those lines drive the length warning, so that
2499                    // preserved-but-overlong content does not keep the paragraph-level
2500                    // warning alive when the reflow would not fix that line.
2501                    let should_count_for_length = |line_idx: usize| -> bool {
2502                        let line = lines[line_idx];
2503                        let trimmed = line.trim();
2504                        if trimmed.is_empty() || is_exempt_line(line) {
2505                            return false;
2506                        }
2507                        let info = &ctx.lines[line_idx];
2508                        if info.in_code_block || info.in_html_block {
2509                            return false;
2510                        }
2511                        if info.in_admonition && mkdocs_admonitions::is_admonition_start(line) {
2512                            return false;
2513                        }
2514                        if is_fence_marker(line) || is_semantic_line(line) {
2515                            return false;
2516                        }
2517                        if is_snippet_block_delimiter(line) {
2518                            return false;
2519                        }
2520                        if line.trim_start().starts_with(":::") {
2521                            return false;
2522                        }
2523                        true
2524                    };
2525                    let max_physical_length = (list_start..i)
2526                        .filter(|&idx| should_count_for_length(idx))
2527                        .map(|idx| self.calculate_effective_length(lines[idx]))
2528                        .max()
2529                        .unwrap_or(0);
2530                    // `line-length = 0` means "no limit", so no physical line can be
2531                    // "over"; the message below then describes a structural join rather
2532                    // than a length violation.
2533                    let any_paragraph_line_over =
2534                        !config.line_length.is_unlimited() && max_physical_length > config.line_length.get();
2535
2536                    // Normalize mode reflows list-item prose just like paragraphs:
2537                    // joining continuation lines and re-wrapping to `line-length`.
2538                    // `prose_changed` is true only when the reflow alters the words or
2539                    // line breaks, not when it would merely re-indent continuation
2540                    // lines or trim trailing whitespace. Comparing the texts with each
2541                    // line's leading and trailing whitespace removed isolates "did the
2542                    // words/line breaks change" from "did the surrounding whitespace
2543                    // change". Continuation indentation is MD077's responsibility and
2544                    // trailing whitespace is MD009's; an MD013 warning for either would
2545                    // both duplicate those rules and resurface a persistent advisory on
2546                    // already-fitting items that users disable MD013 fixing to avoid.
2547                    let prose_changed = {
2548                        let stripped = |text: &str| text.lines().map(str::trim).collect::<Vec<_>>().join("\n");
2549                        stripped(original_text) != stripped(&replacement)
2550                    };
2551                    // Warn when the reflow rewraps prose (the normalize feature for
2552                    // list items), or when a physical line genuinely exceeds the limit
2553                    // and the reflow can change something (a true length violation,
2554                    // even if all that changes is the continuation indent). A line that
2555                    // is already optimal in both respects produces no warning.
2556                    let gate_ok = prose_changed || (any_paragraph_line_over && original_text != replacement);
2557                    if gate_ok {
2558                        // Generate an appropriate message based on why reflow is needed
2559                        let message = match config.reflow_mode {
2560                            ReflowMode::SentencePerLine => {
2561                                let num_sentences = split_into_sentences(&combined_content).len();
2562                                let num_lines = content_lines.len();
2563                                if num_lines == 1 {
2564                                    // Single line with multiple sentences
2565                                    format!("Line contains {num_sentences} sentences (one sentence per line required)")
2566                                } else {
2567                                    // Multiple lines - could be split sentences or mixed
2568                                    format!(
2569                                        "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
2570                                    )
2571                                }
2572                            }
2573                            ReflowMode::SemanticLineBreaks => {
2574                                let num_sentences = split_into_sentences(&combined_content).len();
2575                                format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
2576                            }
2577                            ReflowMode::Normalize => {
2578                                // When a physical line genuinely exceeds the limit, report
2579                                // it as a length violation. Otherwise the reflow is a
2580                                // structural normalization (joining/re-wrapping multi-line
2581                                // content that already fits), mirroring the paragraph path.
2582                                if any_paragraph_line_over {
2583                                    format!(
2584                                        "Line length {} exceeds {} characters",
2585                                        max_physical_length,
2586                                        config.line_length.get()
2587                                    )
2588                                } else {
2589                                    format!(
2590                                        "List item could be normalized to use line length of {} characters",
2591                                        config.line_length.get()
2592                                    )
2593                                }
2594                            }
2595                            ReflowMode::Default => {
2596                                // Report the actual longest non-exempt line, not the combined content
2597                                let max_length = (list_start..i)
2598                                    .filter(|&line_idx| {
2599                                        let line = lines[line_idx];
2600                                        let trimmed = line.trim();
2601                                        !trimmed.is_empty() && !is_exempt_line(line)
2602                                    })
2603                                    .map(|line_idx| self.calculate_effective_length(lines[line_idx]))
2604                                    .max()
2605                                    .unwrap_or(0);
2606                                format!(
2607                                    "Line length {} exceeds {} characters",
2608                                    max_length,
2609                                    config.line_length.get()
2610                                )
2611                            }
2612                        };
2613
2614                        warnings.push(LintWarning {
2615                            rule_name: Some(self.name().to_string()),
2616                            message,
2617                            line: list_start + 1,
2618                            column: 1,
2619                            end_line: end_line + 1,
2620                            end_column: lines[end_line].chars().count() + 1,
2621                            severity: Severity::Warning,
2622                            fix: Some(crate::rule::Fix::new(byte_range, replacement)),
2623                        });
2624                    }
2625                }
2626                continue;
2627            }
2628
2629            // Found start of a paragraph - collect all lines in it
2630            let paragraph_start = i;
2631            let mut paragraph_lines = vec![lines[i]];
2632            i += 1;
2633
2634            while i < lines.len() {
2635                let next_line = lines[i];
2636                let next_line_num = i + 1;
2637                let next_trimmed = next_line.trim();
2638
2639                // Stop at paragraph boundaries
2640                if next_trimmed.is_empty()
2641                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_code_block)
2642                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_front_matter)
2643                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_block)
2644                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_comment)
2645                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_esm_block)
2646                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_expression)
2647                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_block)
2648                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_mdx_comment)
2649                    || ctx
2650                        .line_info(next_line_num)
2651                        .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container)
2652                    || (next_line_num > 0
2653                        && next_line_num <= ctx.lines.len()
2654                        && ctx.lines[next_line_num - 1].blockquote.is_some())
2655                    || next_trimmed.starts_with('#')
2656                    || TableUtils::is_potential_table_row(next_line)
2657                    || is_list_item(next_trimmed)
2658                    || is_horizontal_rule(next_line)
2659                    || (next_trimmed.starts_with('[') && next_line.contains("]:"))
2660                    || is_template_directive_only(next_line)
2661                    || is_standalone_attr_list(next_line)
2662                    || is_snippet_block_delimiter(next_line)
2663                    || ctx.line_info(next_line_num).is_some_and(|info| info.is_div_marker)
2664                    || is_html_only_line(next_line)
2665                {
2666                    break;
2667                }
2668
2669                // Check if the previous line ends with a hard break (2+ spaces or backslash)
2670                if i > 0 && has_hard_break(lines[i - 1]) {
2671                    // Don't include lines after hard breaks in the same paragraph
2672                    break;
2673                }
2674
2675                paragraph_lines.push(next_line);
2676                i += 1;
2677            }
2678
2679            // Compute the common leading indent of all non-empty paragraph lines,
2680            // but only when those lines are structurally inside a list block.
2681            // Indented continuation lines that follow a nested list arrive here
2682            // with their structural indentation intact (e.g. 2 spaces for a
2683            // top-level list item). Stripping the indent before reflow and
2684            // re-applying it afterward prevents the fixer from moving those
2685            // lines to column 0.
2686            //
2687            // The list-block guard is essential: top-level paragraphs that happen
2688            // to start with spaces (insignificant in Markdown) must NOT have those
2689            // spaces preserved or injected by the fixer.
2690            let common_indent: String = if ctx.is_in_list_block(paragraph_start + 1) {
2691                let min_len = paragraph_lines
2692                    .iter()
2693                    .filter(|l| !l.trim().is_empty())
2694                    .map(|l| l.len() - l.trim_start().len())
2695                    .min()
2696                    .unwrap_or(0);
2697                paragraph_lines
2698                    .iter()
2699                    .find(|l| !l.trim().is_empty())
2700                    .map(|l| l[..min_len].to_string())
2701                    .unwrap_or_default()
2702            } else {
2703                String::new()
2704            };
2705
2706            // Combine paragraph lines into a single string for processing.
2707            // This must be done BEFORE the needs_reflow check for sentence-per-line mode.
2708            let paragraph_text = if common_indent.is_empty() {
2709                paragraph_lines.join(" ")
2710            } else {
2711                paragraph_lines
2712                    .iter()
2713                    .map(|l| {
2714                        if l.starts_with(common_indent.as_str()) {
2715                            &l[common_indent.len()..]
2716                        } else {
2717                            l.trim_start()
2718                        }
2719                    })
2720                    .collect::<Vec<_>>()
2721                    .join(" ")
2722            };
2723
2724            // Skip reflowing if this paragraph contains definition list items
2725            // Definition lists are multi-line structures that should not be joined
2726            let contains_definition_list = paragraph_lines
2727                .iter()
2728                .any(|line| crate::utils::is_definition_list_item(line));
2729
2730            if contains_definition_list {
2731                // Don't reflow definition lists - skip this paragraph
2732                i = paragraph_start + paragraph_lines.len();
2733                continue;
2734            }
2735
2736            // Skip reflowing if this paragraph contains MkDocs Snippets markers
2737            // Snippets blocks (-8<- ... -8<-) should be preserved exactly
2738            let contains_snippets = paragraph_lines.iter().any(|line| is_snippet_block_delimiter(line));
2739
2740            if contains_snippets {
2741                // Don't reflow Snippets blocks - skip this paragraph
2742                i = paragraph_start + paragraph_lines.len();
2743                continue;
2744            }
2745
2746            // Check if this paragraph needs reflowing
2747            let needs_reflow = match config.reflow_mode {
2748                ReflowMode::Normalize => self.normalize_mode_needs_reflow(paragraph_lines.iter().copied(), config),
2749                ReflowMode::SentencePerLine => {
2750                    // In sentence-per-line mode, check if the JOINED paragraph has multiple sentences
2751                    // Note: we check the joined text because sentences can span multiple lines
2752                    let sentences = split_into_sentences(&paragraph_text);
2753
2754                    // Always reflow if multiple sentences on one line
2755                    if sentences.len() > 1 {
2756                        true
2757                    } else if paragraph_lines.len() > 1 {
2758                        // For single-sentence paragraphs spanning multiple lines:
2759                        // Reflow if they COULD fit on one line (respecting line-length constraint)
2760                        if config.line_length.is_unlimited() {
2761                            // No line-length constraint - always join single sentences
2762                            true
2763                        } else {
2764                            // Only join if it fits within line-length.
2765                            // paragraph_text has the common indent stripped, so add it
2766                            // back to get the true output length before comparing.
2767                            let effective_length =
2768                                self.calculate_effective_length(&paragraph_text) + common_indent.len();
2769                            effective_length <= config.line_length.get()
2770                        }
2771                    } else {
2772                        false
2773                    }
2774                }
2775                ReflowMode::SemanticLineBreaks => {
2776                    let sentences = split_into_sentences(&paragraph_text);
2777                    // Reflow if multiple sentences, multiple lines, or any line exceeds limit
2778                    sentences.len() > 1
2779                        || paragraph_lines.len() > 1
2780                        || paragraph_lines
2781                            .iter()
2782                            .any(|line| self.calculate_effective_length(line) > config.line_length.get())
2783                }
2784                ReflowMode::Default => {
2785                    // In default mode, only reflow if lines exceed limit
2786                    paragraph_lines
2787                        .iter()
2788                        .any(|line| self.calculate_effective_length(line) > config.line_length.get())
2789                }
2790            };
2791
2792            if needs_reflow {
2793                // Calculate byte range for this paragraph
2794                // Use whole_line_range for each line and combine
2795                let start_range = line_index.whole_line_range(paragraph_start + 1);
2796                let end_line = paragraph_start + paragraph_lines.len() - 1;
2797
2798                // For the last line, we want to preserve any trailing newline
2799                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
2800                    // Last line without trailing newline - use line_text_range
2801                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
2802                } else {
2803                    // Not the last line or has trailing newline - use whole_line_range
2804                    line_index.whole_line_range(end_line + 1)
2805                };
2806
2807                let byte_range = start_range.start..end_range.end;
2808
2809                // Check if the paragraph ends with a hard break and what type
2810                let hard_break_type = paragraph_lines.last().and_then(|line| {
2811                    let line = line.strip_suffix('\r').unwrap_or(line);
2812                    if line.ends_with('\\') {
2813                        Some("\\")
2814                    } else if line.ends_with("  ") {
2815                        Some("  ")
2816                    } else {
2817                        None
2818                    }
2819                });
2820
2821                // Reflow the paragraph
2822                // When line_length = 0 (no limit), use a very large value for reflow
2823                let reflow_line_length = if config.line_length.is_unlimited() {
2824                    usize::MAX
2825                } else {
2826                    config.line_length.get()
2827                };
2828                let reflow_options = crate::utils::text_reflow::ReflowOptions {
2829                    line_length: reflow_line_length,
2830                    break_on_sentences: true,
2831                    preserve_breaks: false,
2832                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
2833                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
2834                    abbreviations: config.abbreviations_for_reflow(),
2835                    length_mode: self.reflow_length_mode(),
2836                    attr_lists: ctx.flavor.supports_attr_lists(),
2837                    myst_roles: ctx.flavor.supports_myst_roles(),
2838                    require_sentence_capital: config.require_sentence_capital,
2839                    max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
2840                        Some(4)
2841                    } else {
2842                        None
2843                    },
2844                };
2845                let mut reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);
2846
2847                // Re-apply the common indent to each non-empty reflowed line so
2848                // that the replacement preserves the original structural indentation.
2849                if !common_indent.is_empty() {
2850                    for line in &mut reflowed {
2851                        if !line.is_empty() {
2852                            *line = format!("{common_indent}{line}");
2853                        }
2854                    }
2855                }
2856
2857                // If the original paragraph ended with a hard break, preserve it
2858                // Preserve the original hard break format (backslash or two spaces)
2859                if let Some(break_marker) = hard_break_type
2860                    && !reflowed.is_empty()
2861                {
2862                    let last_idx = reflowed.len() - 1;
2863                    if !has_hard_break(&reflowed[last_idx]) {
2864                        reflowed[last_idx].push_str(break_marker);
2865                    }
2866                }
2867
2868                let reflowed_text = reflowed.join(line_ending);
2869
2870                // Preserve trailing newline if the original paragraph had one
2871                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
2872                    format!("{reflowed_text}{line_ending}")
2873                } else {
2874                    reflowed_text
2875                };
2876
2877                // Get the original text to compare
2878                let original_text = &ctx.content[byte_range.clone()];
2879
2880                // Only generate a warning if the replacement is different from the original
2881                if original_text != replacement {
2882                    // Create warning with actual fix
2883                    // In default mode, report the specific line that violates
2884                    // In normalize mode, report the whole paragraph
2885                    // In sentence-per-line mode, report the entire paragraph
2886                    let (warning_line, warning_end_line) = match config.reflow_mode {
2887                        ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
2888                        ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => {
2889                            // Highlight the entire paragraph that needs reformatting
2890                            (paragraph_start + 1, paragraph_start + paragraph_lines.len())
2891                        }
2892                        ReflowMode::Default => {
2893                            // Find the first line that exceeds the limit
2894                            let mut violating_line = paragraph_start;
2895                            for (idx, line) in paragraph_lines.iter().enumerate() {
2896                                if self.calculate_effective_length(line) > config.line_length.get() {
2897                                    violating_line = paragraph_start + idx;
2898                                    break;
2899                                }
2900                            }
2901                            (violating_line + 1, violating_line + 1)
2902                        }
2903                    };
2904
2905                    warnings.push(LintWarning {
2906                        rule_name: Some(self.name().to_string()),
2907                        message: match config.reflow_mode {
2908                            ReflowMode::Normalize => format!(
2909                                "Paragraph could be normalized to use line length of {} characters",
2910                                config.line_length.get()
2911                            ),
2912                            ReflowMode::SentencePerLine => {
2913                                let num_sentences = split_into_sentences(&paragraph_text).len();
2914                                if paragraph_lines.len() == 1 {
2915                                    // Single line with multiple sentences
2916                                    format!("Line contains {num_sentences} sentences (one sentence per line required)")
2917                                } else {
2918                                    let num_lines = paragraph_lines.len();
2919                                    // Multiple lines - could be split sentences or mixed
2920                                    format!("Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)")
2921                                }
2922                            },
2923                            ReflowMode::SemanticLineBreaks => {
2924                                let num_sentences = split_into_sentences(&paragraph_text).len();
2925                                format!(
2926                                    "Paragraph should use semantic line breaks ({num_sentences} sentences)"
2927                                )
2928                            },
2929                            ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
2930                        },
2931                        line: warning_line,
2932                        column: 1,
2933                        end_line: warning_end_line,
2934                        end_column: lines[warning_end_line.saturating_sub(1)].chars().count() + 1,
2935                        severity: Severity::Warning,
2936                        fix: Some(crate::rule::Fix::new(byte_range, replacement)),
2937                    });
2938                }
2939            }
2940        }
2941
2942        warnings
2943    }
2944
2945    /// Calculate string length based on the configured length mode
2946    fn calculate_string_length(&self, s: &str) -> usize {
2947        match self.config.length_mode {
2948            LengthMode::Chars => s.chars().count(),
2949            LengthMode::Visual => s.width(),
2950            LengthMode::Bytes => s.len(),
2951        }
2952    }
2953
2954    /// Calculate effective line length
2955    ///
2956    /// Returns the actual display length of the line using the configured length mode.
2957    fn calculate_effective_length(&self, line: &str) -> usize {
2958        self.calculate_string_length(line)
2959    }
2960
2961    /// Calculate line length with inline link/image URLs removed.
2962    ///
2963    /// For each inline link `[text](url)` or image `![alt](url)` on the line,
2964    /// computes the "savings" from removing the URL portion (keeping only `[text]`
2965    /// or `![alt]`). Returns `effective_length - total_savings`.
2966    ///
2967    /// Handles nested constructs (e.g., `[![img](url)](url)`) by only counting the
2968    /// outermost construct to avoid double-counting.
2969    fn calculate_text_only_length(
2970        &self,
2971        effective_length: usize,
2972        line_number: usize,
2973        ctx: &crate::lint_context::LintContext,
2974    ) -> usize {
2975        let line_range = ctx.line_index.line_content_range(line_number);
2976        let line_byte_end = line_range.end;
2977
2978        // Collect inline links/images on this line: (byte_offset, byte_end, text_only_display_len)
2979        let mut constructs: Vec<(usize, usize, usize)> = Vec::new();
2980
2981        // Binary search: links are sorted by byte_offset, so link.line is non-decreasing
2982        let link_start = ctx.links.partition_point(|l| l.line < line_number);
2983        for link in &ctx.links[link_start..] {
2984            if link.line != line_number {
2985                break;
2986            }
2987            if link.is_reference {
2988                continue;
2989            }
2990            if !matches!(link.link_type, LinkType::Inline) {
2991                continue;
2992            }
2993            if link.byte_end > line_byte_end {
2994                continue;
2995            }
2996            let text_only_len = 2 + self.calculate_string_length(&link.text);
2997            constructs.push((link.byte_offset, link.byte_end, text_only_len));
2998        }
2999
3000        let img_start = ctx.images.partition_point(|i| i.line < line_number);
3001        for image in &ctx.images[img_start..] {
3002            if image.line != line_number {
3003                break;
3004            }
3005            if image.is_reference {
3006                continue;
3007            }
3008            if !matches!(image.link_type, LinkType::Inline) {
3009                continue;
3010            }
3011            if image.byte_end > line_byte_end {
3012                continue;
3013            }
3014            let text_only_len = 3 + self.calculate_string_length(&image.alt_text);
3015            constructs.push((image.byte_offset, image.byte_end, text_only_len));
3016        }
3017
3018        if constructs.is_empty() {
3019            return effective_length;
3020        }
3021
3022        // Sort by byte offset to handle overlapping/nested constructs
3023        constructs.sort_by_key(|&(start, _, _)| start);
3024
3025        let mut total_savings: usize = 0;
3026        let mut last_end: usize = 0;
3027
3028        for (start, end, text_only_len) in &constructs {
3029            // Skip constructs nested inside a previously counted one
3030            if *start < last_end {
3031                continue;
3032            }
3033            // Full construct length in configured length mode
3034            let full_source = &ctx.content[*start..*end];
3035            let full_len = self.calculate_string_length(full_source);
3036            total_savings += full_len.saturating_sub(*text_only_len);
3037            last_end = *end;
3038        }
3039
3040        effective_length.saturating_sub(total_savings)
3041    }
3042}