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