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