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