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