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