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