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