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 // Check if this is a SIBLING list item (breaks parent)
1949 // Nested lists are indented >= marker_len and are PART of the parent item
1950 // Siblings are at indent < marker_len (at or before parent marker)
1951 if is_list_item(trimmed) && indent < marker_len {
1952 // This is a sibling item at same or higher level - end parent item
1953 break;
1954 }
1955
1956 // Nested list items are always processed independently
1957 // by the outer loop, so break when we encounter one.
1958 // If a blank line was collected before this, uncollect it
1959 // so the outer loop preserves the blank between parent and nested.
1960 if is_list_item(trimmed) && indent >= marker_len {
1961 if matches!(list_item_lines.last(), Some(LineType::Empty)) {
1962 list_item_lines.pop();
1963 i -= 1;
1964 }
1965 break;
1966 }
1967
1968 // Normal continuation vs indented code block.
1969 // Use min_continuation_indent for the threshold since
1970 // code blocks start 4 spaces beyond the expected content
1971 // level (which is min_continuation_indent for MkDocs).
1972 if indent <= min_continuation_indent + 3 {
1973 // Extract content (remove indentation and trailing whitespace)
1974 // Preserve hard breaks (2 trailing spaces) while removing excessive whitespace
1975 // See: https://github.com/rvben/rumdl/issues/76
1976 let content = trim_preserving_hard_break(&line_info.content(ctx.content)[indent..]);
1977
1978 // Check if this is a div marker (::: opening or closing)
1979 // These must be preserved on their own line, not merged into paragraphs
1980 if line_info.is_div_marker {
1981 list_item_lines.push(LineType::DivMarker(content));
1982 }
1983 // Check if this is a fence marker (opening or closing)
1984 // These should be treated as code block lines, not paragraph content
1985 else if is_fence_marker(&content) {
1986 list_item_lines.push(LineType::CodeBlock(content, indent));
1987 }
1988 // Check if this is a semantic line (NOTE:, WARNING:, etc.)
1989 else if is_semantic_line(&content) {
1990 list_item_lines.push(LineType::SemanticLine(content));
1991 }
1992 // Check if this is a snippet block delimiter (-8<- or --8<--)
1993 // These must be preserved on their own lines for MkDocs Snippets extension
1994 else if is_snippet_block_delimiter(&content) {
1995 list_item_lines.push(LineType::SnippetLine(content));
1996 }
1997 // Check if this is a GFM table row. Tables nested inside list
1998 // items must be preserved verbatim — joining them with prose
1999 // breaks the column structure.
2000 //
2001 // `is_potential_table_row` is intentionally permissive at the
2002 // row level: any line with `|` and 2+ cells qualifies. To avoid
2003 // misclassifying prose continuation lines that contain a literal
2004 // pipe (e.g. "use grep | sort to ..."), require one of:
2005 // - the row is pipe-bordered (`| ... |`), the canonical form
2006 // for tables nested in lists; or
2007 // - the next line is a delimiter row (this is a header); or
2008 // - the previous classified line was already a Table (this is
2009 // a continuation row).
2010 else if TableUtils::is_potential_table_row(&content) && {
2011 let pipe_bordered = content.trim().starts_with('|') && content.trim().ends_with('|');
2012 let next_is_delim = ctx
2013 .lines
2014 .get(i + 1)
2015 .is_some_and(|next| TableUtils::is_delimiter_row(next.content(ctx.content)));
2016 let prev_was_table = matches!(list_item_lines.last(), Some(LineType::Table(..)));
2017 pipe_bordered || next_is_delim || prev_was_table
2018 } {
2019 list_item_lines.push(LineType::Table(content, indent));
2020 } else {
2021 list_item_lines.push(LineType::Content(content));
2022 }
2023 i += 1;
2024 } else {
2025 // indent >= min_continuation_indent + 4: indented code block
2026 list_item_lines.push(LineType::CodeBlock(
2027 line_info.content(ctx.content)[indent..].to_string(),
2028 indent,
2029 ));
2030 i += 1;
2031 }
2032 } else {
2033 // Not indented enough, end of list item
2034 break;
2035 }
2036 }
2037
2038 // Determine the output continuation indent.
2039 // Normalize/Default modes canonicalize to min_continuation_indent
2040 // (fixing over-indented continuation). Semantic/SentencePerLine
2041 // modes preserve the user's actual indent since they only fix
2042 // line breaking, not indentation.
2043 let indent_size = match config.reflow_mode {
2044 ReflowMode::SemanticLineBreaks | ReflowMode::SentencePerLine => {
2045 // Find indent of the first plain text continuation line,
2046 // skipping the marker line (index 0), nested list items,
2047 // code blocks, and blank lines.
2048 list_item_lines
2049 .iter()
2050 .enumerate()
2051 .skip(1)
2052 .find_map(|(k, lt)| {
2053 if matches!(lt, LineType::Content(_)) {
2054 Some(ctx.lines[list_start + k].indent)
2055 } else {
2056 None
2057 }
2058 })
2059 .unwrap_or(min_continuation_indent)
2060 }
2061 _ => min_continuation_indent,
2062 };
2063 // For checkbox items in mkdocs flavor, enforce minimum indent so
2064 // continuation lines use the structural list indent (4), not the
2065 // content-aligned indent (6) which Python-Markdown doesn't support
2066 let has_checkbox = base_marker_len < marker_len;
2067 let indent_size = if has_checkbox && ctx.flavor.requires_strict_list_indent() {
2068 indent_size.max(min_continuation_indent)
2069 } else {
2070 indent_size
2071 };
2072 let expected_indent = " ".repeat(indent_size);
2073
2074 // Split list_item_lines into blocks (paragraphs, code blocks, nested lists, semantic lines, and HTML blocks)
2075 let mut builder = BlockBuilder::new();
2076 for line in &list_item_lines {
2077 match line {
2078 LineType::Empty => builder.feed_blank_line(),
2079 LineType::Content(content) => builder.feed_content(content),
2080 LineType::CodeBlock(content, indent) => builder.feed_code_line(content, *indent),
2081 LineType::SemanticLine(content) => builder.feed_semantic_line(content),
2082 LineType::SnippetLine(content) => builder.feed_snippet_line(content),
2083 LineType::DivMarker(content) => builder.feed_div_marker(content),
2084 LineType::AdmonitionHeader(header_text, indent) => {
2085 builder.feed_admonition_header(header_text, *indent)
2086 }
2087 LineType::AdmonitionContent(content, indent) => {
2088 builder.feed_admonition_content(content, *indent)
2089 }
2090 LineType::Table(content, indent) => builder.feed_table_line(content, *indent),
2091 }
2092 }
2093 let blocks = builder.finalize();
2094
2095 // Helper: check if a line (raw source or stripped content) is exempt
2096 // from line-length checks. Link reference definitions are always exempt;
2097 // standalone link/image lines are exempt when strict mode is off.
2098 // Also checks content after stripping list markers, since list item
2099 // continuation lines may contain link ref defs.
2100 let is_exempt_line = |raw_line: &str| -> bool {
2101 let trimmed = raw_line.trim();
2102 // Link reference definitions: always exempt
2103 if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
2104 return true;
2105 }
2106 // Also check after stripping list markers (for list item content)
2107 if is_list_item(trimmed) {
2108 let (_, content) = extract_list_marker_and_content(trimmed);
2109 let content_trimmed = content.trim();
2110 if content_trimmed.starts_with('[')
2111 && content_trimmed.contains("]:")
2112 && LINK_REF_PATTERN.is_match(content_trimmed)
2113 {
2114 return true;
2115 }
2116 }
2117 // Standalone link/image lines: exempt when not strict
2118 if !config.strict && is_standalone_link_or_image_line(raw_line) {
2119 return true;
2120 }
2121 // HTML-only lines: exempt when not strict
2122 if !config.strict && is_html_only_line(raw_line) {
2123 return true;
2124 }
2125 false
2126 };
2127
2128 // Check if reflowing is needed (only for content paragraphs, not code blocks or nested lists)
2129 // Exclude link reference definitions and standalone link lines from content
2130 // so they don't pollute combined_content or trigger false reflow.
2131 let content_lines: Vec<String> = list_item_lines
2132 .iter()
2133 .filter_map(|line| {
2134 if let LineType::Content(s) = line {
2135 if is_exempt_line(s) {
2136 return None;
2137 }
2138 Some(s.clone())
2139 } else {
2140 None
2141 }
2142 })
2143 .collect();
2144
2145 // Check if we need to reflow this list item
2146 // We check the combined content to see if it exceeds length limits
2147 let combined_content = content_lines.join(" ").trim().to_string();
2148
2149 // Helper to check if we should reflow in normalize mode
2150 let should_normalize = || {
2151 // Don't normalize if the list item only contains nested lists, code blocks, or semantic lines
2152 // DO normalize if it has plain text content that spans multiple lines
2153 let has_code_blocks = blocks.iter().any(|b| matches!(b, Block::Code { .. }));
2154 let has_semantic_lines = blocks.iter().any(|b| matches!(b, Block::SemanticLine(_)));
2155 let has_snippet_lines = blocks.iter().any(|b| matches!(b, Block::SnippetLine(_)));
2156 let has_div_markers = blocks.iter().any(|b| matches!(b, Block::DivMarker(_)));
2157 let has_admonitions = blocks.iter().any(|b| matches!(b, Block::Admonition { .. }));
2158 let has_tables = blocks.iter().any(|b| matches!(b, Block::Table { .. }));
2159 let has_paragraphs = blocks.iter().any(|b| matches!(b, Block::Paragraph(_)));
2160
2161 // If we have structural blocks but no paragraphs, don't normalize
2162 if (has_code_blocks
2163 || has_semantic_lines
2164 || has_snippet_lines
2165 || has_div_markers
2166 || has_admonitions
2167 || has_tables)
2168 && !has_paragraphs
2169 {
2170 return false;
2171 }
2172
2173 // If we have paragraphs, check if they span multiple lines or there are multiple blocks
2174 if has_paragraphs {
2175 // Count only paragraphs that contain at least one non-exempt line.
2176 // Paragraphs consisting entirely of link ref defs or standalone links
2177 // should not trigger normalization.
2178 let paragraph_count = blocks
2179 .iter()
2180 .filter(|b| {
2181 if let Block::Paragraph(para_lines) = b {
2182 !para_lines.iter().all(|line| is_exempt_line(line))
2183 } else {
2184 false
2185 }
2186 })
2187 .count();
2188 if paragraph_count > 1 {
2189 // Multiple non-exempt paragraph blocks should be normalized
2190 return true;
2191 }
2192
2193 // Single paragraph block: normalize if it has multiple content lines
2194 if content_lines.len() > 1 {
2195 return true;
2196 }
2197 }
2198
2199 false
2200 };
2201
2202 let needs_reflow = match config.reflow_mode {
2203 ReflowMode::Normalize => {
2204 // Only reflow if:
2205 // 1. Any non-exempt paragraph, when joined, exceeds the limit, OR
2206 // 2. Any admonition content line exceeds the limit, OR
2207 // 3. The list item should be normalized (has multi-line plain text)
2208 let any_paragraph_exceeds = blocks.iter().any(|block| match block {
2209 Block::Paragraph(para_lines) => {
2210 if para_lines.iter().all(|line| is_exempt_line(line)) {
2211 return false;
2212 }
2213 let joined = para_lines.join(" ");
2214 let with_marker = format!("{}{}", " ".repeat(indent_size), joined.trim());
2215 self.calculate_effective_length(&with_marker) > config.line_length.get()
2216 }
2217 Block::Admonition {
2218 content_lines,
2219 header_indent,
2220 ..
2221 } => content_lines.iter().any(|(content, indent)| {
2222 if content.is_empty() {
2223 return false;
2224 }
2225 let with_indent = format!("{}{}", " ".repeat(*indent.max(header_indent)), content);
2226 self.calculate_effective_length(&with_indent) > config.line_length.get()
2227 }),
2228 _ => false,
2229 });
2230 if any_paragraph_exceeds {
2231 true
2232 } else {
2233 should_normalize()
2234 }
2235 }
2236 ReflowMode::SentencePerLine => {
2237 // Check if list item has multiple sentences
2238 let sentences = split_into_sentences(&combined_content);
2239 sentences.len() > 1
2240 }
2241 ReflowMode::SemanticLineBreaks => {
2242 let sentences = split_into_sentences(&combined_content);
2243 sentences.len() > 1
2244 || (list_start..i).any(|line_idx| {
2245 let line = lines[line_idx];
2246 let trimmed = line.trim();
2247 if trimmed.is_empty() || is_exempt_line(line) {
2248 return false;
2249 }
2250 self.calculate_effective_length(line) > config.line_length.get()
2251 })
2252 }
2253 ReflowMode::Default => {
2254 // In default mode, only reflow if any individual non-exempt line exceeds limit
2255 (list_start..i).any(|line_idx| {
2256 let line = lines[line_idx];
2257 let trimmed = line.trim();
2258 // Skip blank lines and exempt lines
2259 if trimmed.is_empty() || is_exempt_line(line) {
2260 return false;
2261 }
2262 self.calculate_effective_length(line) > config.line_length.get()
2263 })
2264 }
2265 };
2266
2267 if needs_reflow {
2268 let start_range = line_index.whole_line_range(list_start + 1);
2269 let end_line = i - 1;
2270 let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
2271 line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
2272 } else {
2273 line_index.whole_line_range(end_line + 1)
2274 };
2275 let byte_range = start_range.start..end_range.end;
2276
2277 // Reflow each block (paragraphs only, preserve code blocks)
2278 // When line_length = 0 (no limit), use a very large value for reflow
2279 let reflow_line_length = if config.line_length.is_unlimited() {
2280 usize::MAX
2281 } else {
2282 config.line_length.get().saturating_sub(indent_size).max(1)
2283 };
2284 let reflow_options = crate::utils::text_reflow::ReflowOptions {
2285 line_length: reflow_line_length,
2286 break_on_sentences: true,
2287 preserve_breaks: false,
2288 sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
2289 semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
2290 abbreviations: config.abbreviations_for_reflow(),
2291 length_mode: self.reflow_length_mode(),
2292 attr_lists: ctx.flavor.supports_attr_lists(),
2293 myst_roles: ctx.flavor.supports_myst_roles(),
2294 require_sentence_capital: config.require_sentence_capital,
2295 max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
2296 Some(4)
2297 } else {
2298 None
2299 },
2300 };
2301
2302 let mut result: Vec<String> = Vec::new();
2303 let mut is_first_block = true;
2304
2305 for (block_idx, block) in blocks.iter().enumerate() {
2306 match block {
2307 Block::Paragraph(para_lines) => {
2308 // If every line in this paragraph is exempt (link ref defs,
2309 // standalone links), preserve the paragraph verbatim instead
2310 // of reflowing it. Reflowing would corrupt link ref defs.
2311 let all_exempt = para_lines.iter().all(|line| is_exempt_line(line));
2312
2313 if all_exempt {
2314 for (idx, line) in para_lines.iter().enumerate() {
2315 if is_first_block && idx == 0 {
2316 result.push(format!("{marker}{line}"));
2317 is_first_block = false;
2318 } else {
2319 result.push(format!("{expected_indent}{line}"));
2320 }
2321 }
2322 } else {
2323 // Split the paragraph into segments at hard break boundaries
2324 // Each segment can be reflowed independently
2325 let segments = split_into_segments(para_lines);
2326
2327 for (segment_idx, segment) in segments.iter().enumerate() {
2328 // Check if this segment ends with a hard break and what type
2329 let hard_break_type = segment.last().and_then(|line| {
2330 let line = line.strip_suffix('\r').unwrap_or(line);
2331 if line.ends_with('\\') {
2332 Some("\\")
2333 } else if line.ends_with(" ") {
2334 Some(" ")
2335 } else {
2336 None
2337 }
2338 });
2339
2340 // Join and reflow the segment (removing the hard break marker for processing)
2341 let segment_for_reflow: Vec<String> = segment
2342 .iter()
2343 .map(|line| {
2344 // Strip hard break marker (2 spaces or backslash) for reflow processing
2345 if line.ends_with('\\') {
2346 line[..line.len() - 1].trim_end().to_string()
2347 } else if line.ends_with(" ") {
2348 line[..line.len() - 2].trim_end().to_string()
2349 } else {
2350 line.clone()
2351 }
2352 })
2353 .collect();
2354
2355 let segment_text = segment_for_reflow.join(" ").trim().to_string();
2356 if !segment_text.is_empty() {
2357 let reflowed =
2358 crate::utils::text_reflow::reflow_line(&segment_text, &reflow_options);
2359
2360 if is_first_block && segment_idx == 0 {
2361 // First segment of first block starts with marker
2362 result.push(format!("{marker}{}", reflowed[0]));
2363 for line in reflowed.iter().skip(1) {
2364 result.push(format!("{expected_indent}{line}"));
2365 }
2366 is_first_block = false;
2367 } else {
2368 // Subsequent segments
2369 for line in reflowed {
2370 result.push(format!("{expected_indent}{line}"));
2371 }
2372 }
2373
2374 // If this segment had a hard break, add it back to the last line
2375 // Preserve the original hard break format (backslash or two spaces)
2376 if let Some(break_marker) = hard_break_type
2377 && let Some(last_line) = result.last_mut()
2378 {
2379 last_line.push_str(break_marker);
2380 }
2381 }
2382 }
2383 }
2384
2385 // Add blank line after paragraph block if there's a next block.
2386 // Check if next block is a code block that doesn't want a preceding blank.
2387 // Also don't add blank lines before snippet lines (they should stay tight).
2388 // Only add if not already ending with one (avoids double blanks).
2389 if block_idx < blocks.len() - 1 {
2390 let next_block = &blocks[block_idx + 1];
2391 let should_add_blank = match next_block {
2392 Block::Code {
2393 has_preceding_blank, ..
2394 } => *has_preceding_blank,
2395 Block::Table {
2396 has_preceding_blank, ..
2397 } => *has_preceding_blank,
2398 Block::SnippetLine(_) | Block::DivMarker(_) => false,
2399 _ => true, // For all other blocks, add blank line
2400 };
2401 if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2402 result.push(String::new());
2403 }
2404 }
2405 }
2406 Block::Code {
2407 lines: code_lines,
2408 has_preceding_blank: _,
2409 } => {
2410 // Preserve code blocks as-is with original indentation
2411 // NOTE: Blank line before code block is handled by the previous block
2412 // (see paragraph block's logic above)
2413
2414 for (idx, (content, orig_indent)) in code_lines.iter().enumerate() {
2415 if is_first_block && idx == 0 {
2416 // First line of first block gets marker
2417 result.push(format!(
2418 "{marker}{}",
2419 " ".repeat(orig_indent - marker_len) + content
2420 ));
2421 is_first_block = false;
2422 } else if content.is_empty() {
2423 result.push(String::new());
2424 } else {
2425 result.push(format!("{}{}", " ".repeat(*orig_indent), content));
2426 }
2427 }
2428 }
2429 Block::SemanticLine(content) => {
2430 // Preserve semantic lines (NOTE:, WARNING:, etc.) as-is on their own line.
2431 // Only add blank before if not already ending with one.
2432 if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2433 result.push(String::new());
2434 }
2435
2436 if is_first_block {
2437 // First block starts with marker
2438 result.push(format!("{marker}{content}"));
2439 is_first_block = false;
2440 } else {
2441 // Subsequent blocks use expected indent
2442 result.push(format!("{expected_indent}{content}"));
2443 }
2444
2445 // Add blank line after semantic line if there's a next block.
2446 // Only add if not already ending with one.
2447 if block_idx < blocks.len() - 1 {
2448 let next_block = &blocks[block_idx + 1];
2449 let should_add_blank = match next_block {
2450 Block::Code {
2451 has_preceding_blank, ..
2452 } => *has_preceding_blank,
2453 Block::Table {
2454 has_preceding_blank, ..
2455 } => *has_preceding_blank,
2456 Block::SnippetLine(_) | Block::DivMarker(_) => false,
2457 _ => true, // For all other blocks, add blank line
2458 };
2459 if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2460 result.push(String::new());
2461 }
2462 }
2463 }
2464 Block::SnippetLine(content) => {
2465 // Preserve snippet delimiters (-8<-) as-is on their own line
2466 // Unlike semantic lines, snippet lines don't add extra blank lines
2467 if is_first_block {
2468 // First block starts with marker
2469 result.push(format!("{marker}{content}"));
2470 is_first_block = false;
2471 } else {
2472 // Subsequent blocks use expected indent
2473 result.push(format!("{expected_indent}{content}"));
2474 }
2475 // No blank lines added before or after snippet delimiters
2476 }
2477 Block::DivMarker(content) => {
2478 // Preserve div markers (::: opening or closing) as-is on their own line
2479 if is_first_block {
2480 result.push(format!("{marker}{content}"));
2481 is_first_block = false;
2482 } else {
2483 result.push(format!("{expected_indent}{content}"));
2484 }
2485 }
2486 Block::Html {
2487 lines: html_lines,
2488 has_preceding_blank: _,
2489 } => {
2490 // Preserve HTML blocks exactly as-is with original indentation
2491 // NOTE: Blank line before HTML block is handled by the previous block
2492
2493 for (idx, line) in html_lines.iter().enumerate() {
2494 if is_first_block && idx == 0 {
2495 // First line of first block gets marker
2496 result.push(format!("{marker}{line}"));
2497 is_first_block = false;
2498 } else if line.is_empty() {
2499 // Preserve blank lines inside HTML blocks
2500 result.push(String::new());
2501 } else {
2502 // Preserve lines with their original content (already includes indentation)
2503 result.push(format!("{expected_indent}{line}"));
2504 }
2505 }
2506
2507 // Add blank line after HTML block if there's a next block.
2508 // Only add if not already ending with one (avoids double blanks
2509 // when the HTML block itself contained a trailing blank line).
2510 if block_idx < blocks.len() - 1 {
2511 let next_block = &blocks[block_idx + 1];
2512 let should_add_blank = match next_block {
2513 Block::Code {
2514 has_preceding_blank, ..
2515 } => *has_preceding_blank,
2516 Block::Html {
2517 has_preceding_blank, ..
2518 } => *has_preceding_blank,
2519 Block::Table {
2520 has_preceding_blank, ..
2521 } => *has_preceding_blank,
2522 Block::SnippetLine(_) | Block::DivMarker(_) => false,
2523 _ => true, // For all other blocks, add blank line
2524 };
2525 if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2526 result.push(String::new());
2527 }
2528 }
2529 }
2530 Block::Table {
2531 lines: table_lines,
2532 has_preceding_blank: _,
2533 } => {
2534 // Preserve table rows verbatim with their original indentation.
2535 // Reflowing rows would corrupt column alignment and inject `|`
2536 // characters mid-paragraph (issue #590).
2537 // The leading blank line is emitted by the previous block.
2538 for (idx, (content, orig_indent)) in table_lines.iter().enumerate() {
2539 if is_first_block && idx == 0 {
2540 // First line of first block gets the list marker
2541 result.push(format!(
2542 "{marker}{}",
2543 " ".repeat(orig_indent.saturating_sub(marker_len)) + content
2544 ));
2545 is_first_block = false;
2546 } else {
2547 result.push(format!("{}{}", " ".repeat(*orig_indent), content));
2548 }
2549 }
2550
2551 // Add blank line after table block if there's a next block.
2552 if block_idx < blocks.len() - 1 {
2553 let next_block = &blocks[block_idx + 1];
2554 let should_add_blank = match next_block {
2555 Block::Code {
2556 has_preceding_blank, ..
2557 } => *has_preceding_blank,
2558 Block::Html {
2559 has_preceding_blank, ..
2560 } => *has_preceding_blank,
2561 Block::Table {
2562 has_preceding_blank, ..
2563 } => *has_preceding_blank,
2564 Block::SnippetLine(_) | Block::DivMarker(_) => false,
2565 _ => true,
2566 };
2567 if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2568 result.push(String::new());
2569 }
2570 }
2571 }
2572 Block::Admonition {
2573 header,
2574 header_indent,
2575 content_lines: admon_lines,
2576 } => {
2577 // Reconstruct admonition block with header at original indent
2578 // and body content reflowed to fit within the line length limit
2579
2580 // Add blank line before admonition if not first block
2581 if !is_first_block && result.last().is_none_or(|s: &String| !s.is_empty()) {
2582 result.push(String::new());
2583 }
2584
2585 // Output the header at its original indent
2586 let header_indent_str = " ".repeat(*header_indent);
2587 if is_first_block {
2588 result.push(format!(
2589 "{marker}{}",
2590 " ".repeat(header_indent.saturating_sub(marker_len)) + header
2591 ));
2592 is_first_block = false;
2593 } else {
2594 result.push(format!("{header_indent_str}{header}"));
2595 }
2596
2597 // Derive body indent from the first non-empty content line's
2598 // stored indent, falling back to header_indent + 4 for
2599 // empty-body admonitions
2600 let body_indent = admon_lines
2601 .iter()
2602 .find(|(content, _)| !content.is_empty())
2603 .map_or(header_indent + 4, |(_, indent)| *indent);
2604 let body_indent_str = " ".repeat(body_indent);
2605
2606 // Segment body content into code blocks (verbatim) and
2607 // text paragraphs (reflowable), separated by blank lines.
2608 // Code lines store (content, orig_indent) to reconstruct
2609 // internal indentation relative to body_indent.
2610 enum AdmonSegment {
2611 Text(Vec<String>),
2612 Code(Vec<(String, usize)>),
2613 }
2614
2615 let mut segments: Vec<AdmonSegment> = Vec::new();
2616 let mut current_text: Vec<String> = Vec::new();
2617 let mut current_code: Vec<(String, usize)> = Vec::new();
2618 let mut in_admon_code = false;
2619 // Track the opening fence character so closing fences
2620 // must match (backticks close backticks, tildes close tildes)
2621 let mut fence_char: char = '`';
2622
2623 // Opening fences: ``` or ~~~ followed by optional info string
2624 let get_opening_fence = |s: &str| -> Option<(char, usize)> {
2625 let t = s.trim_start();
2626 if t.starts_with("```") {
2627 Some(('`', t.bytes().take_while(|&b| b == b'`').count()))
2628 } else if t.starts_with("~~~") {
2629 Some(('~', t.bytes().take_while(|&b| b == b'~').count()))
2630 } else {
2631 None
2632 }
2633 };
2634 // Closing fences: ONLY fence chars + optional trailing spaces
2635 let get_closing_fence = |s: &str| -> Option<(char, usize)> {
2636 let t = s.trim();
2637 if t.starts_with("```") && t.bytes().all(|b| b == b'`') {
2638 Some(('`', t.len()))
2639 } else if t.starts_with("~~~") && t.bytes().all(|b| b == b'~') {
2640 Some(('~', t.len()))
2641 } else {
2642 None
2643 }
2644 };
2645 let mut fence_len: usize = 3;
2646
2647 for (content, orig_indent) in admon_lines {
2648 if in_admon_code {
2649 // Closing fence must use the same character, be
2650 // at least as long, and have no info string
2651 if let Some((ch, len)) = get_closing_fence(content)
2652 && ch == fence_char
2653 && len >= fence_len
2654 {
2655 current_code.push((content.clone(), *orig_indent));
2656 in_admon_code = false;
2657 segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2658 continue;
2659 }
2660 current_code.push((content.clone(), *orig_indent));
2661 } else if let Some((ch, len)) = get_opening_fence(content) {
2662 if !current_text.is_empty() {
2663 segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2664 }
2665 in_admon_code = true;
2666 fence_char = ch;
2667 fence_len = len;
2668 current_code.push((content.clone(), *orig_indent));
2669 } else if content.is_empty() {
2670 if !current_text.is_empty() {
2671 segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2672 }
2673 } else {
2674 current_text.push(content.clone());
2675 }
2676 }
2677 if in_admon_code && !current_code.is_empty() {
2678 segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
2679 }
2680 if !current_text.is_empty() {
2681 segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
2682 }
2683
2684 // Build reflow options once for all text segments
2685 let admon_reflow_length = if config.line_length.is_unlimited() {
2686 usize::MAX
2687 } else {
2688 config.line_length.get().saturating_sub(body_indent).max(1)
2689 };
2690
2691 let admon_reflow_options = crate::utils::text_reflow::ReflowOptions {
2692 line_length: admon_reflow_length,
2693 break_on_sentences: true,
2694 preserve_breaks: false,
2695 sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
2696 semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
2697 abbreviations: config.abbreviations_for_reflow(),
2698 length_mode: self.reflow_length_mode(),
2699 attr_lists: ctx.flavor.supports_attr_lists(),
2700 myst_roles: ctx.flavor.supports_myst_roles(),
2701 require_sentence_capital: config.require_sentence_capital,
2702 max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
2703 Some(4)
2704 } else {
2705 None
2706 },
2707 };
2708
2709 // Output each segment
2710 for segment in &segments {
2711 // Blank line before each segment (after the header or previous segment)
2712 result.push(String::new());
2713
2714 match segment {
2715 AdmonSegment::Code(lines) => {
2716 for (line, orig_indent) in lines {
2717 if line.is_empty() {
2718 // Preserve blank lines inside code blocks
2719 result.push(String::new());
2720 } else {
2721 // Reconstruct with body_indent + any extra
2722 // indentation the line had beyond body_indent
2723 let extra = orig_indent.saturating_sub(body_indent);
2724 let indent_str = " ".repeat(body_indent + extra);
2725 result.push(format!("{indent_str}{line}"));
2726 }
2727 }
2728 }
2729 AdmonSegment::Text(lines) => {
2730 let paragraph_text = lines.join(" ").trim().to_string();
2731 if paragraph_text.is_empty() {
2732 continue;
2733 }
2734 let reflowed = crate::utils::text_reflow::reflow_line(
2735 ¶graph_text,
2736 &admon_reflow_options,
2737 );
2738 for line in &reflowed {
2739 result.push(format!("{body_indent_str}{line}"));
2740 }
2741 }
2742 }
2743 }
2744
2745 // Add blank line after admonition if there's a next block
2746 if block_idx < blocks.len() - 1 {
2747 let next_block = &blocks[block_idx + 1];
2748 let should_add_blank = match next_block {
2749 Block::Code {
2750 has_preceding_blank, ..
2751 } => *has_preceding_blank,
2752 Block::Table {
2753 has_preceding_blank, ..
2754 } => *has_preceding_blank,
2755 Block::SnippetLine(_) | Block::DivMarker(_) => false,
2756 _ => true,
2757 };
2758 if should_add_blank && result.last().is_none_or(|s: &String| !s.is_empty()) {
2759 result.push(String::new());
2760 }
2761 }
2762 }
2763 }
2764 }
2765
2766 let reflowed_text = result.join(line_ending);
2767
2768 // Preserve trailing newline
2769 let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
2770 format!("{reflowed_text}{line_ending}")
2771 } else {
2772 reflowed_text
2773 };
2774
2775 // Get the original text to compare
2776 let original_text = &ctx.content[byte_range.clone()];
2777
2778 // Physical-line-length scan, shared by the Normalize-mode gate and its
2779 // message. The list-item reflow preserves code blocks, HTML blocks,
2780 // admonition headers, fence markers, semantic markers, and snippet/div
2781 // markers verbatim; only paragraph content and admonition bodies are
2782 // restructured. Only those lines drive the length warning, so that
2783 // preserved-but-overlong content does not keep the paragraph-level
2784 // warning alive when the reflow would not fix that line.
2785 let should_count_for_length = |line_idx: usize| -> bool {
2786 let line = lines[line_idx];
2787 let trimmed = line.trim();
2788 if trimmed.is_empty() || is_exempt_line(line) {
2789 return false;
2790 }
2791 let info = &ctx.lines[line_idx];
2792 if info.in_code_block || info.in_html_block {
2793 return false;
2794 }
2795 if info.in_admonition && mkdocs_admonitions::is_admonition_start(line) {
2796 return false;
2797 }
2798 if is_fence_marker(line) || is_semantic_line(line) {
2799 return false;
2800 }
2801 if is_snippet_block_delimiter(line) {
2802 return false;
2803 }
2804 if line.trim_start().starts_with(":::") {
2805 return false;
2806 }
2807 true
2808 };
2809 let max_physical_length = (list_start..i)
2810 .filter(|&idx| should_count_for_length(idx))
2811 .map(|idx| self.calculate_effective_length(lines[idx]))
2812 .max()
2813 .unwrap_or(0);
2814 // `line-length = 0` means "no limit", so no physical line can be
2815 // "over"; the message below then describes a structural join rather
2816 // than a length violation.
2817 let any_paragraph_line_over =
2818 !config.line_length.is_unlimited() && max_physical_length > config.line_length.get();
2819
2820 // Normalize mode reflows list-item prose just like paragraphs:
2821 // joining continuation lines and re-wrapping to `line-length`.
2822 // `prose_changed` is true only when the reflow alters the words or
2823 // line breaks, not when it would merely re-indent continuation
2824 // lines or trim trailing whitespace. Comparing the texts with each
2825 // line's leading and trailing whitespace removed isolates "did the
2826 // words/line breaks change" from "did the surrounding whitespace
2827 // change". Continuation indentation is MD077's responsibility and
2828 // trailing whitespace is MD009's; an MD013 warning for either would
2829 // both duplicate those rules and resurface a persistent advisory on
2830 // already-fitting items that users disable MD013 fixing to avoid.
2831 let prose_changed = {
2832 let stripped = |text: &str| text.lines().map(str::trim).collect::<Vec<_>>().join("\n");
2833 stripped(original_text) != stripped(&replacement)
2834 };
2835 // Warn when the reflow rewraps prose (the normalize feature for
2836 // list items), or when a physical line genuinely exceeds the limit
2837 // and the reflow can change something (a true length violation,
2838 // even if all that changes is the continuation indent). A line that
2839 // is already optimal in both respects produces no warning.
2840 let gate_ok = prose_changed || (any_paragraph_line_over && original_text != replacement);
2841 if gate_ok {
2842 // Generate an appropriate message based on why reflow is needed
2843 let message = match config.reflow_mode {
2844 ReflowMode::SentencePerLine => {
2845 let num_sentences = split_into_sentences(&combined_content).len();
2846 let num_lines = content_lines.len();
2847 if num_lines == 1 {
2848 // Single line with multiple sentences
2849 format!("Line contains {num_sentences} sentences (one sentence per line required)")
2850 } else {
2851 // Multiple lines - could be split sentences or mixed
2852 format!(
2853 "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
2854 )
2855 }
2856 }
2857 ReflowMode::SemanticLineBreaks => {
2858 let num_sentences = split_into_sentences(&combined_content).len();
2859 format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
2860 }
2861 ReflowMode::Normalize => {
2862 // When a physical line genuinely exceeds the limit, report
2863 // it as a length violation. Otherwise the reflow is a
2864 // structural normalization (joining/re-wrapping multi-line
2865 // content that already fits), mirroring the paragraph path.
2866 if any_paragraph_line_over {
2867 format!(
2868 "Line length {} exceeds {} characters",
2869 max_physical_length,
2870 config.line_length.get()
2871 )
2872 } else {
2873 format!(
2874 "List item could be normalized to use line length of {} characters",
2875 config.line_length.get()
2876 )
2877 }
2878 }
2879 ReflowMode::Default => {
2880 // Report the actual longest non-exempt line, not the combined content
2881 let max_length = (list_start..i)
2882 .filter(|&line_idx| {
2883 let line = lines[line_idx];
2884 let trimmed = line.trim();
2885 !trimmed.is_empty() && !is_exempt_line(line)
2886 })
2887 .map(|line_idx| self.calculate_effective_length(lines[line_idx]))
2888 .max()
2889 .unwrap_or(0);
2890 format!(
2891 "Line length {} exceeds {} characters",
2892 max_length,
2893 config.line_length.get()
2894 )
2895 }
2896 };
2897
2898 warnings.push(LintWarning {
2899 rule_name: Some(self.name().to_string()),
2900 message,
2901 line: list_start + 1,
2902 column: 1,
2903 end_line: end_line + 1,
2904 end_column: lines[end_line].chars().count() + 1,
2905 severity: Severity::Warning,
2906 fix: Some(crate::rule::Fix::new(byte_range, replacement)),
2907 });
2908 }
2909 }
2910 continue;
2911 }
2912
2913 // Found start of a paragraph - collect all lines in it
2914 let paragraph_start = i;
2915 let mut paragraph_lines = vec![lines[i]];
2916 i += 1;
2917
2918 while i < lines.len() {
2919 let next_line = lines[i];
2920 let next_line_num = i + 1;
2921 let next_trimmed = next_line.trim();
2922
2923 // Stop at paragraph boundaries
2924 if next_trimmed.is_empty()
2925 || ctx.line_info(next_line_num).is_some_and(|info| info.in_code_block)
2926 || ctx.line_info(next_line_num).is_some_and(|info| info.in_front_matter)
2927 || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_block)
2928 || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_comment)
2929 || ctx.line_info(next_line_num).is_some_and(|info| info.in_esm_block)
2930 || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_expression)
2931 || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_block)
2932 || ctx.line_info(next_line_num).is_some_and(|info| info.in_mdx_comment)
2933 || ctx
2934 .line_info(next_line_num)
2935 .is_some_and(super::super::lint_context::types::LineInfo::in_mkdocs_container)
2936 || (next_line_num > 0
2937 && next_line_num <= ctx.lines.len()
2938 && ctx.lines[next_line_num - 1].blockquote.is_some())
2939 || next_trimmed.starts_with('#')
2940 || TableUtils::is_potential_table_row(next_line)
2941 || is_list_item(next_trimmed)
2942 || is_horizontal_rule(next_line)
2943 || (next_trimmed.starts_with('[') && next_line.contains("]:"))
2944 || is_template_directive_only(next_line)
2945 || is_standalone_attr_list(next_line)
2946 || is_snippet_block_delimiter(next_line)
2947 || ctx.line_info(next_line_num).is_some_and(|info| info.is_div_marker)
2948 || is_html_only_line(next_line)
2949 {
2950 break;
2951 }
2952
2953 // Check if the previous line ends with a hard break (2+ spaces or backslash)
2954 if i > 0 && has_hard_break(lines[i - 1]) {
2955 // Don't include lines after hard breaks in the same paragraph
2956 break;
2957 }
2958
2959 paragraph_lines.push(next_line);
2960 i += 1;
2961 }
2962
2963 // Compute the common leading indent of all non-empty paragraph lines,
2964 // but only when those lines are structurally inside a list block.
2965 // Indented continuation lines that follow a nested list arrive here
2966 // with their structural indentation intact (e.g. 2 spaces for a
2967 // top-level list item). Stripping the indent before reflow and
2968 // re-applying it afterward prevents the fixer from moving those
2969 // lines to column 0.
2970 //
2971 // The list-block guard is essential: top-level paragraphs that happen
2972 // to start with spaces (insignificant in Markdown) must NOT have those
2973 // spaces preserved or injected by the fixer.
2974 let common_indent: String = if ctx.is_in_list_block(paragraph_start + 1) {
2975 let min_len = paragraph_lines
2976 .iter()
2977 .filter(|l| !l.trim().is_empty())
2978 .map(|l| l.len() - l.trim_start().len())
2979 .min()
2980 .unwrap_or(0);
2981 paragraph_lines
2982 .iter()
2983 .find(|l| !l.trim().is_empty())
2984 .map(|l| l[..min_len].to_string())
2985 .unwrap_or_default()
2986 } else {
2987 String::new()
2988 };
2989
2990 // Combine paragraph lines into a single string for processing.
2991 // This must be done BEFORE the needs_reflow check for sentence-per-line mode.
2992 let paragraph_text = if common_indent.is_empty() {
2993 paragraph_lines.join(" ")
2994 } else {
2995 paragraph_lines
2996 .iter()
2997 .map(|l| {
2998 if l.starts_with(common_indent.as_str()) {
2999 &l[common_indent.len()..]
3000 } else {
3001 l.trim_start()
3002 }
3003 })
3004 .collect::<Vec<_>>()
3005 .join(" ")
3006 };
3007
3008 // Skip reflowing if this paragraph contains definition list items
3009 // Definition lists are multi-line structures that should not be joined
3010 let contains_definition_list = paragraph_lines
3011 .iter()
3012 .any(|line| crate::utils::is_definition_list_item(line));
3013
3014 if contains_definition_list {
3015 // Don't reflow definition lists - skip this paragraph
3016 i = paragraph_start + paragraph_lines.len();
3017 continue;
3018 }
3019
3020 // Skip reflowing if this paragraph contains MkDocs Snippets markers
3021 // Snippets blocks (-8<- ... -8<-) should be preserved exactly
3022 let contains_snippets = paragraph_lines.iter().any(|line| is_snippet_block_delimiter(line));
3023
3024 if contains_snippets {
3025 // Don't reflow Snippets blocks - skip this paragraph
3026 i = paragraph_start + paragraph_lines.len();
3027 continue;
3028 }
3029
3030 // Check if this paragraph needs reflowing
3031 let needs_reflow = match config.reflow_mode {
3032 ReflowMode::Normalize => self.normalize_mode_needs_reflow(paragraph_lines.iter().copied(), config),
3033 ReflowMode::SentencePerLine => {
3034 // In sentence-per-line mode, check if the JOINED paragraph has multiple sentences
3035 // Note: we check the joined text because sentences can span multiple lines
3036 let sentences = split_into_sentences(¶graph_text);
3037
3038 // Always reflow if multiple sentences on one line
3039 if sentences.len() > 1 {
3040 true
3041 } else if paragraph_lines.len() > 1 {
3042 // For single-sentence paragraphs spanning multiple lines:
3043 // Reflow if they COULD fit on one line (respecting line-length constraint)
3044 if config.line_length.is_unlimited() {
3045 // No line-length constraint - always join single sentences
3046 true
3047 } else {
3048 // Only join if it fits within line-length.
3049 // paragraph_text has the common indent stripped, so add it
3050 // back to get the true output length before comparing.
3051 let effective_length =
3052 self.calculate_effective_length(¶graph_text) + common_indent.len();
3053 effective_length <= config.line_length.get()
3054 }
3055 } else {
3056 false
3057 }
3058 }
3059 ReflowMode::SemanticLineBreaks => {
3060 let sentences = split_into_sentences(¶graph_text);
3061 // Reflow if multiple sentences, multiple lines, or any line exceeds limit
3062 sentences.len() > 1
3063 || paragraph_lines.len() > 1
3064 || paragraph_lines
3065 .iter()
3066 .any(|line| self.calculate_effective_length(line) > config.line_length.get())
3067 }
3068 ReflowMode::Default => {
3069 // In default mode, only reflow if lines exceed limit
3070 paragraph_lines
3071 .iter()
3072 .any(|line| self.calculate_effective_length(line) > config.line_length.get())
3073 }
3074 };
3075
3076 if needs_reflow {
3077 // Calculate byte range for this paragraph
3078 // Use whole_line_range for each line and combine
3079 let start_range = line_index.whole_line_range(paragraph_start + 1);
3080 let end_line = paragraph_start + paragraph_lines.len() - 1;
3081
3082 // For the last line, we want to preserve any trailing newline
3083 let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
3084 // Last line without trailing newline - use line_text_range
3085 line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
3086 } else {
3087 // Not the last line or has trailing newline - use whole_line_range
3088 line_index.whole_line_range(end_line + 1)
3089 };
3090
3091 let byte_range = start_range.start..end_range.end;
3092
3093 // Check if the paragraph ends with a hard break and what type
3094 let hard_break_type = paragraph_lines.last().and_then(|line| {
3095 let line = line.strip_suffix('\r').unwrap_or(line);
3096 if line.ends_with('\\') {
3097 Some("\\")
3098 } else if line.ends_with(" ") {
3099 Some(" ")
3100 } else {
3101 None
3102 }
3103 });
3104
3105 // Reflow the paragraph
3106 // When line_length = 0 (no limit), use a very large value for reflow
3107 let reflow_line_length = if config.line_length.is_unlimited() {
3108 usize::MAX
3109 } else {
3110 config.line_length.get()
3111 };
3112 let reflow_options = crate::utils::text_reflow::ReflowOptions {
3113 line_length: reflow_line_length,
3114 break_on_sentences: true,
3115 preserve_breaks: false,
3116 sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
3117 semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
3118 abbreviations: config.abbreviations_for_reflow(),
3119 length_mode: self.reflow_length_mode(),
3120 attr_lists: ctx.flavor.supports_attr_lists(),
3121 myst_roles: ctx.flavor.supports_myst_roles(),
3122 require_sentence_capital: config.require_sentence_capital,
3123 max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
3124 Some(4)
3125 } else {
3126 None
3127 },
3128 };
3129 let mut reflowed = crate::utils::text_reflow::reflow_line(¶graph_text, &reflow_options);
3130
3131 // Re-apply the common indent to each non-empty reflowed line so
3132 // that the replacement preserves the original structural indentation.
3133 if !common_indent.is_empty() {
3134 for line in &mut reflowed {
3135 if !line.is_empty() {
3136 *line = format!("{common_indent}{line}");
3137 }
3138 }
3139 }
3140
3141 // If the original paragraph ended with a hard break, preserve it
3142 // Preserve the original hard break format (backslash or two spaces)
3143 if let Some(break_marker) = hard_break_type
3144 && !reflowed.is_empty()
3145 {
3146 let last_idx = reflowed.len() - 1;
3147 if !has_hard_break(&reflowed[last_idx]) {
3148 reflowed[last_idx].push_str(break_marker);
3149 }
3150 }
3151
3152 let reflowed_text = reflowed.join(line_ending);
3153
3154 // Preserve trailing newline if the original paragraph had one
3155 let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
3156 format!("{reflowed_text}{line_ending}")
3157 } else {
3158 reflowed_text
3159 };
3160
3161 // Get the original text to compare
3162 let original_text = &ctx.content[byte_range.clone()];
3163
3164 // Only generate a warning if the replacement is different from the original
3165 if original_text != replacement {
3166 // Create warning with actual fix
3167 // In default mode, report the specific line that violates
3168 // In normalize mode, report the whole paragraph
3169 // In sentence-per-line mode, report the entire paragraph
3170 let (warning_line, warning_end_line) = match config.reflow_mode {
3171 ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
3172 ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => {
3173 // Highlight the entire paragraph that needs reformatting
3174 (paragraph_start + 1, paragraph_start + paragraph_lines.len())
3175 }
3176 ReflowMode::Default => {
3177 // Find the first line that exceeds the limit
3178 let mut violating_line = paragraph_start;
3179 for (idx, line) in paragraph_lines.iter().enumerate() {
3180 if self.calculate_effective_length(line) > config.line_length.get() {
3181 violating_line = paragraph_start + idx;
3182 break;
3183 }
3184 }
3185 (violating_line + 1, violating_line + 1)
3186 }
3187 };
3188
3189 warnings.push(LintWarning {
3190 rule_name: Some(self.name().to_string()),
3191 message: match config.reflow_mode {
3192 ReflowMode::Normalize => format!(
3193 "Paragraph could be normalized to use line length of {} characters",
3194 config.line_length.get()
3195 ),
3196 ReflowMode::SentencePerLine => {
3197 let num_sentences = split_into_sentences(¶graph_text).len();
3198 if paragraph_lines.len() == 1 {
3199 // Single line with multiple sentences
3200 format!("Line contains {num_sentences} sentences (one sentence per line required)")
3201 } else {
3202 let num_lines = paragraph_lines.len();
3203 // Multiple lines - could be split sentences or mixed
3204 format!("Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)")
3205 }
3206 },
3207 ReflowMode::SemanticLineBreaks => {
3208 let num_sentences = split_into_sentences(¶graph_text).len();
3209 format!(
3210 "Paragraph should use semantic line breaks ({num_sentences} sentences)"
3211 )
3212 },
3213 ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
3214 },
3215 line: warning_line,
3216 column: 1,
3217 end_line: warning_end_line,
3218 end_column: lines[warning_end_line.saturating_sub(1)].chars().count() + 1,
3219 severity: Severity::Warning,
3220 fix: Some(crate::rule::Fix::new(byte_range, replacement)),
3221 });
3222 }
3223 }
3224 }
3225
3226 warnings
3227 }
3228
3229 /// Calculate string length based on the configured length mode
3230 fn calculate_string_length(&self, s: &str) -> usize {
3231 match self.config.length_mode {
3232 LengthMode::Chars => s.chars().count(),
3233 LengthMode::Visual => s.width(),
3234 LengthMode::Bytes => s.len(),
3235 }
3236 }
3237
3238 /// Calculate effective line length
3239 ///
3240 /// Returns the actual display length of the line using the configured length mode.
3241 fn calculate_effective_length(&self, line: &str) -> usize {
3242 self.calculate_string_length(line)
3243 }
3244
3245 /// Calculate line length with inline link/image URLs removed.
3246 ///
3247 /// For each inline link `[text](url)` or image `` on the line,
3248 /// computes the "savings" from removing the URL portion (keeping only `[text]`
3249 /// or `![alt]`). Returns `effective_length - total_savings`.
3250 ///
3251 /// Handles nested constructs (e.g., `[](url)`) by only counting the
3252 /// outermost construct to avoid double-counting.
3253 fn calculate_text_only_length(
3254 &self,
3255 effective_length: usize,
3256 line_number: usize,
3257 ctx: &crate::lint_context::LintContext,
3258 ) -> usize {
3259 let line_range = ctx.line_index.line_content_range(line_number);
3260 let line_byte_end = line_range.end;
3261
3262 // Collect inline links/images on this line: (byte_offset, byte_end, text_only_display_len)
3263 let mut constructs: Vec<(usize, usize, usize)> = Vec::new();
3264
3265 // Binary search: links are sorted by byte_offset, so link.line is non-decreasing
3266 let link_start = ctx.links.partition_point(|l| l.line < line_number);
3267 for link in &ctx.links[link_start..] {
3268 if link.line != line_number {
3269 break;
3270 }
3271 if link.is_reference {
3272 continue;
3273 }
3274 if !matches!(link.link_type, LinkType::Inline) {
3275 continue;
3276 }
3277 if link.byte_end > line_byte_end {
3278 continue;
3279 }
3280 let text_only_len = 2 + self.calculate_string_length(&link.text);
3281 constructs.push((link.byte_offset, link.byte_end, text_only_len));
3282 }
3283
3284 let img_start = ctx.images.partition_point(|i| i.line < line_number);
3285 for image in &ctx.images[img_start..] {
3286 if image.line != line_number {
3287 break;
3288 }
3289 if image.is_reference {
3290 continue;
3291 }
3292 if !matches!(image.link_type, LinkType::Inline) {
3293 continue;
3294 }
3295 if image.byte_end > line_byte_end {
3296 continue;
3297 }
3298 let text_only_len = 3 + self.calculate_string_length(&image.alt_text);
3299 constructs.push((image.byte_offset, image.byte_end, text_only_len));
3300 }
3301
3302 if constructs.is_empty() {
3303 return effective_length;
3304 }
3305
3306 // Sort by byte offset to handle overlapping/nested constructs
3307 constructs.sort_by_key(|&(start, _, _)| start);
3308
3309 let mut total_savings: usize = 0;
3310 let mut last_end: usize = 0;
3311
3312 for (start, end, text_only_len) in &constructs {
3313 // Skip constructs nested inside a previously counted one
3314 if *start < last_end {
3315 continue;
3316 }
3317 // Full construct length in configured length mode
3318 let full_source = &ctx.content[*start..*end];
3319 let full_len = self.calculate_string_length(full_source);
3320 total_savings += full_len.saturating_sub(*text_only_len);
3321 last_end = *end;
3322 }
3323
3324 effective_length.saturating_sub(total_savings)
3325 }
3326}