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