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