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