Skip to main content

crate_cli/fmt/markdown/
fn.rs

1use super::*;
2
3/// Formats Markdown (`.md` / `.markdown`) matching VS Code `esbenp.prettier-vscode` (`tabWidth: 2`, `singleQuote: true`, `proseWrap: "preserve"`, `embeddedLanguageFormatting: "auto"`, LF).
4///
5/// # Arguments
6///
7/// - `&str` - Raw Markdown source text.
8///
9/// # Returns
10///
11/// - `String` - Formatted Markdown document ending with a single `\n`.
12pub fn format_markdown(input: &str) -> String {
13    let normalized: String = normalize_line_endings(input);
14    let raw_lines: Vec<&str> = normalized.split(TEXT_LF).collect();
15    let total: usize = raw_lines.len();
16    let mut out_lines: Vec<String> = Vec::new();
17    let mut idx: usize = 0;
18    let mut prev_block: MdBlockKind = MdBlockKind::None;
19    let mut pending_blank: bool = false;
20    let mut list_indents: Vec<usize> = Vec::new();
21    if let Some((fm_lines, next_idx)) = try_parse_frontmatter(&raw_lines) {
22        out_lines.extend(fm_lines);
23        idx = next_idx;
24        prev_block = MdBlockKind::Frontmatter;
25    }
26    while idx < total {
27        let raw_line: &str = raw_lines[idx];
28        let trimmed: &str = raw_line.trim();
29        if trimmed.is_empty() {
30            if !out_lines.is_empty() {
31                pending_blank = true;
32            }
33            idx += 1;
34            continue;
35        }
36        if let Some(fence) = parse_fence_open(raw_line) {
37            let fence_indent: usize = fence.get_indent();
38            let in_list: bool = matches!(prev_block, MdBlockKind::List(_)) && fence_indent > 0;
39            let norm_indent: usize = if in_list {
40                normalize_nested_indent(&list_indents, fence_indent)
41            } else {
42                list_indents.clear();
43                0
44            };
45            let needs_sep: bool = pending_blank || !in_list;
46            if !out_lines.is_empty() && (needs_sep || prev_block != MdBlockKind::None) {
47                push_single_blank(&mut out_lines);
48            }
49            pending_blank = false;
50            let (block_lines, next_idx): (Vec<String>, usize) =
51                format_fenced_code_block(&raw_lines, idx, &fence, norm_indent);
52            out_lines.extend(block_lines);
53            idx = next_idx;
54            if !in_list {
55                prev_block = MdBlockKind::CodeFence;
56            }
57            continue;
58        }
59        if let Some((table_lines, next_idx)) = try_parse_gfm_table(&raw_lines, idx) {
60            list_indents.clear();
61            if !out_lines.is_empty() {
62                push_single_blank(&mut out_lines);
63            }
64            pending_blank = false;
65            out_lines.extend(table_lines);
66            idx = next_idx;
67            prev_block = MdBlockKind::Table;
68            continue;
69        }
70        if let Some(heading) = format_atx_heading(trimmed) {
71            list_indents.clear();
72            if !out_lines.is_empty() {
73                push_single_blank(&mut out_lines);
74            }
75            pending_blank = false;
76            out_lines.push(heading);
77            idx += 1;
78            prev_block = MdBlockKind::Heading;
79            continue;
80        }
81        if is_thematic_break(trimmed) {
82            list_indents.clear();
83            if !out_lines.is_empty() {
84                push_single_blank(&mut out_lines);
85            }
86            pending_blank = false;
87            out_lines.push(MD_THEMATIC_BREAK.to_string());
88            idx += 1;
89            prev_block = MdBlockKind::ThematicBreak;
90            continue;
91        }
92        if trimmed.starts_with('>') {
93            list_indents.clear();
94            if !out_lines.is_empty() && (pending_blank || prev_block != MdBlockKind::Blockquote) {
95                push_single_blank(&mut out_lines);
96            }
97            pending_blank = false;
98            out_lines.push(format_blockquote_line(trimmed));
99            idx += 1;
100            prev_block = MdBlockKind::Blockquote;
101            continue;
102        }
103        if let Some(item) = parse_list_item(raw_line) {
104            let cur_kind: ListKind = item.get_kind();
105            let switching_kind: bool = match prev_block {
106                MdBlockKind::List(prev_kind) => prev_kind != cur_kind && item.get_raw_indent() == 0,
107                MdBlockKind::None => false,
108                _ => true,
109            };
110            if !out_lines.is_empty() && (pending_blank || switching_kind) {
111                push_single_blank(&mut out_lines);
112                if switching_kind {
113                    list_indents.clear();
114                }
115            }
116            pending_blank = false;
117            let out_indent: usize =
118                resolve_list_item_indent(&mut list_indents, item.get_raw_indent());
119            let mut formatted: String = String::with_capacity(
120                out_indent + item.get_marker().len() + 1 + item.get_body().len(),
121            );
122            push_spaces(&mut formatted, out_indent);
123            formatted.push_str(item.get_marker());
124            if !item.get_body().is_empty() {
125                formatted.push(TEXT_SPACE);
126                formatted.push_str(item.get_body());
127            }
128            out_lines.push(formatted);
129            idx += 1;
130            prev_block = MdBlockKind::List(cur_kind);
131            continue;
132        }
133        if is_html_block_line(trimmed) {
134            list_indents.clear();
135            let needs_blank: bool =
136                !out_lines.is_empty() && (pending_blank || prev_block != MdBlockKind::Html);
137            if needs_blank {
138                push_single_blank(&mut out_lines);
139            }
140            pending_blank = false;
141            out_lines.push(
142                raw_line
143                    .trim_end_matches([TEXT_SPACE, TEXT_TAB])
144                    .to_string(),
145            );
146            idx += 1;
147            prev_block = MdBlockKind::Html;
148            continue;
149        }
150        let raw_indent: usize = count_leading_spaces_md(raw_line);
151        let list_continuation: bool = matches!(prev_block, MdBlockKind::List(_)) && raw_indent >= 2;
152        if list_continuation {
153            if pending_blank {
154                push_single_blank(&mut out_lines);
155            }
156            pending_blank = false;
157            let cont_indent: usize = normalize_nested_indent(&list_indents, raw_indent);
158            let mut line: String = String::with_capacity(cont_indent + trimmed.len());
159            push_spaces(&mut line, cont_indent);
160            line.push_str(trimmed);
161            out_lines.push(line);
162            idx += 1;
163            continue;
164        }
165        list_indents.clear();
166        let needs_blank: bool =
167            !out_lines.is_empty() && (pending_blank || prev_block != MdBlockKind::Paragraph);
168        if needs_blank {
169            push_single_blank(&mut out_lines);
170        }
171        pending_blank = false;
172        out_lines.push(normalize_inline_emphasis(
173            raw_line.trim_end_matches([TEXT_SPACE, TEXT_TAB]),
174        ));
175        idx += 1;
176        prev_block = MdBlockKind::Paragraph;
177    }
178    while let Some(last) = out_lines.last() {
179        if last.is_empty() {
180            let _: Option<String> = out_lines.pop();
181        } else {
182            break;
183        }
184    }
185    if out_lines.is_empty() {
186        return String::new();
187    }
188    let mut out: String = out_lines.join("\n");
189    out.push(TEXT_LF);
190    out
191}
192
193/// Ensures the output line vector ends with at most one blank line.
194///
195/// # Arguments
196///
197/// - `&mut Vec<String>` - Output line buffer.
198fn push_single_blank(out_lines: &mut Vec<String>) {
199    if let Some(last) = out_lines.last()
200        && !last.is_empty()
201    {
202        out_lines.push(String::new());
203    }
204}
205
206/// Parses and formats a leading YAML frontmatter block (`---\n...\n---`) if present at line 0.
207///
208/// # Arguments
209///
210/// - `&[&str]` - All lines of the Markdown document.
211///
212/// # Returns
213///
214/// - `Option<(Vec<String>, usize)>` - Formatted frontmatter lines and the next line index after the closing `---`.
215fn try_parse_frontmatter(raw_lines: &[&str]) -> Option<(Vec<String>, usize)> {
216    if raw_lines.len() < 2 || raw_lines[0].trim() != MD_FRONTMATTER_FENCE {
217        return None;
218    }
219    let mut close_idx: Option<usize> = None;
220    for (i, line) in raw_lines.iter().enumerate().skip(1) {
221        if line.trim() == MD_FRONTMATTER_FENCE {
222            close_idx = Some(i);
223            break;
224        }
225    }
226    let end_idx: usize = close_idx?;
227    let yaml_src: String = raw_lines[1..end_idx].join("\n");
228    let formatted_yaml: String = format_yaml(&yaml_src);
229    let mut out: Vec<String> = Vec::new();
230    out.push(MD_FRONTMATTER_FENCE.to_string());
231    if !formatted_yaml.is_empty() {
232        for line in formatted_yaml.trim_end_matches(TEXT_LF).split(TEXT_LF) {
233            out.push(line.to_string());
234        }
235    }
236    out.push(MD_FRONTMATTER_FENCE.to_string());
237    Some((out, end_idx + 1))
238}
239
240/// Attempts to parse an opening fenced code block line (` ``` ` or ` ~~~ `).
241///
242/// # Arguments
243///
244/// - `&str` - Raw Markdown line.
245///
246/// # Returns
247///
248/// - `Option<FenceOpen>` - Parsed opening fence metadata if matched.
249fn parse_fence_open(raw_line: &str) -> Option<FenceOpen> {
250    let indent: usize = count_leading_spaces_md(raw_line);
251    let trimmed: &str = raw_line.trim_start_matches([TEXT_SPACE, TEXT_TAB]);
252    let first: char = trimmed.chars().next()?;
253    if first != '`' && first != '~' {
254        return None;
255    }
256    let fence_len: usize = trimmed.chars().take_while(|c: &char| *c == first).count();
257    if fence_len < 3 {
258        return None;
259    }
260    let rest: &str = trimmed[fence_len..].trim();
261    if first == '`' && rest.contains('`') {
262        return None;
263    }
264    Some(FenceOpen::new(indent, first, fence_len, rest.to_string()))
265}
266
267/// Formats a fenced code block including Prettier embedded language formatting for `json`, `jsonc`, `yaml`, and `yml`.
268///
269/// # Arguments
270///
271/// - `&[&str]` - All lines of the document.
272/// - `usize` - Line index of the opening fence.
273/// - `&FenceOpen` - Parsed opening fence metadata.
274/// - `usize` - Target normalized leading indentation in spaces.
275///
276/// # Returns
277///
278/// - `(Vec<String>, usize)` - Formatted code block lines and the next line index after the closing fence.
279fn format_fenced_code_block(
280    raw_lines: &[&str],
281    start_idx: usize,
282    fence: &FenceOpen,
283    target_indent: usize,
284) -> (Vec<String>, usize) {
285    let mut body_lines: Vec<String> = Vec::new();
286    let mut cursor: usize = start_idx + 1;
287    let raw_indent: usize = fence.get_indent();
288    let fence_char: char = fence.get_fence_char();
289    let fence_len: usize = fence.get_fence_len();
290    while cursor < raw_lines.len() {
291        let candidate: &str = raw_lines[cursor].trim();
292        let close_count: usize = candidate
293            .chars()
294            .take_while(|c: &char| *c == fence_char)
295            .count();
296        if close_count >= fence_len && candidate.len() == close_count {
297            cursor += 1;
298            break;
299        }
300        body_lines.push(strip_up_to_spaces(raw_lines[cursor], raw_indent).to_string());
301        cursor += 1;
302    }
303    let lang: String = fence
304        .get_info()
305        .split_whitespace()
306        .next()
307        .unwrap_or("")
308        .to_ascii_lowercase();
309    let body_joined: String = body_lines.join("\n");
310    let formatted_body: Option<String> = match lang.as_str() {
311        MD_LANG_JSON => format_json(&body_joined).ok(),
312        MD_LANG_JSONC => Some(format_jsonc(&body_joined)),
313        MD_LANG_YAML | MD_LANG_YML => Some(format_yaml(&body_joined)),
314        _ => None,
315    };
316    let final_lines: Vec<String> = if let Some(ref embedded) = formatted_body {
317        if embedded.is_empty() {
318            Vec::new()
319        } else {
320            embedded
321                .trim_end_matches(TEXT_LF)
322                .split(TEXT_LF)
323                .map(|s: &str| s.to_string())
324                .collect()
325        }
326    } else {
327        body_lines
328    };
329    let out_fence_len: usize = compute_safe_backtick_fence(&final_lines, fence_len);
330    let mut fence_marker: String = String::with_capacity(out_fence_len);
331    for _ in 0..out_fence_len {
332        fence_marker.push('`');
333    }
334    let mut out: Vec<String> = Vec::with_capacity(final_lines.len() + 2);
335    let mut open_line: String =
336        String::with_capacity(target_indent + fence_marker.len() + fence.get_info().len());
337    push_spaces(&mut open_line, target_indent);
338    open_line.push_str(&fence_marker);
339    open_line.push_str(fence.get_info());
340    out.push(open_line);
341    for line in final_lines {
342        if line.is_empty() {
343            out.push(String::new());
344        } else {
345            let mut indented: String = String::with_capacity(target_indent + line.len());
346            push_spaces(&mut indented, target_indent);
347            indented.push_str(&line);
348            out.push(indented);
349        }
350    }
351    let mut close_line: String = String::with_capacity(target_indent + fence_marker.len());
352    push_spaces(&mut close_line, target_indent);
353    close_line.push_str(&fence_marker);
354    out.push(close_line);
355    (out, cursor)
356}
357
358/// Computes the minimum backtick fence length that will not collide with any backtick run inside `body_lines`.
359///
360/// # Arguments
361///
362/// - `&[String]` - Formatted code block lines.
363/// - `usize` - Original opening fence length.
364///
365/// # Returns
366///
367/// - `usize` - Safe backtick fence length (`>= 3`).
368fn compute_safe_backtick_fence(body_lines: &[String], original_len: usize) -> usize {
369    let mut max_run: usize = 0;
370    for line in body_lines {
371        let mut run: usize = 0;
372        for ch in line.chars() {
373            if ch == '`' {
374                run += 1;
375                if run > max_run {
376                    max_run = run;
377                }
378            } else {
379                run = 0;
380            }
381        }
382    }
383    let needed: usize = if max_run >= 3 { max_run + 1 } else { 3 };
384    needed.max(original_len.clamp(3, 4))
385}
386
387/// Strips up to `max_spaces` leading ASCII spaces (or equivalent tabs) from a line.
388///
389/// # Arguments
390///
391/// - `&str` - Raw line.
392/// - `usize` - Maximum number of leading spaces to remove.
393///
394/// # Returns
395///
396/// - `&str` - Sliced line with leading indentation removed.
397fn strip_up_to_spaces(line: &str, max_spaces: usize) -> &str {
398    let bytes: &[u8] = line.as_bytes();
399    let mut i: usize = 0;
400    let mut removed: usize = 0;
401    while i < bytes.len() && removed < max_spaces {
402        if bytes[i] == b' ' {
403            i += 1;
404            removed += 1;
405        } else if bytes[i] == b'\t' {
406            i += 1;
407            removed += PRETTIER_TAB_WIDTH;
408        } else {
409            break;
410        }
411    }
412    &line[i..]
413}
414
415/// Attempts to parse and format a GFM pipe table starting at `start_idx` using exact Prettier column alignment.
416///
417/// # Arguments
418///
419/// - `&[&str]` - All lines of the document.
420/// - `usize` - Candidate header row index.
421///
422/// # Returns
423///
424/// - `Option<(Vec<String>, usize)>` - Formatted table lines and next line index if a valid GFM table starts here.
425fn try_parse_gfm_table(raw_lines: &[&str], start_idx: usize) -> Option<(Vec<String>, usize)> {
426    if start_idx + 1 >= raw_lines.len() {
427        return None;
428    }
429    let header_raw: &str = raw_lines[start_idx].trim();
430    let sep_raw: &str = raw_lines[start_idx + 1].trim();
431    if !header_raw.contains('|') || !sep_raw.contains('|') {
432        return None;
433    }
434    let alignments: Vec<TableAlign> = parse_table_separator(sep_raw)?;
435    let header_cells: Vec<String> = split_table_row(header_raw);
436    if header_cells.is_empty() || header_cells.len() != alignments.len() {
437        return None;
438    }
439    let col_count: usize = alignments.len();
440    let mut rows: Vec<Vec<String>> = vec![header_cells];
441    let mut cursor: usize = start_idx + 2;
442    while cursor < raw_lines.len() {
443        let row_trimmed: &str = raw_lines[cursor].trim();
444        if row_trimmed.is_empty() || !row_trimmed.contains('|') {
445            break;
446        }
447        let mut cells: Vec<String> = split_table_row(row_trimmed);
448        while cells.len() < col_count {
449            cells.push(String::new());
450        }
451        cells.truncate(col_count);
452        rows.push(cells);
453        cursor += 1;
454    }
455    let mut col_widths: Vec<usize> = vec![MD_TABLE_MIN_COL_WIDTH; col_count];
456    for row in &rows {
457        for (c, cell) in row.iter().enumerate() {
458            let w: usize = str_display_width(cell);
459            if w > col_widths[c] {
460                col_widths[c] = w;
461            }
462        }
463    }
464    let mut out: Vec<String> = Vec::with_capacity(rows.len() + 1);
465    out.push(format_table_data_row(&rows[0], &col_widths, &alignments));
466    out.push(format_table_sep_row(&col_widths, &alignments));
467    for row in rows.iter().skip(1) {
468        out.push(format_table_data_row(row, &col_widths, &alignments));
469    }
470    Some((out, cursor))
471}
472
473/// Parses a GFM table delimiter row into per-column alignments.
474///
475/// # Arguments
476///
477/// - `&str` - Trimmed separator row line.
478///
479/// # Returns
480///
481/// - `Option<Vec<TableAlign>>` - Column alignments if every cell is a valid GFM delimiter cell.
482fn parse_table_separator(line: &str) -> Option<Vec<TableAlign>> {
483    let cells: Vec<String> = split_table_row(line);
484    if cells.is_empty() {
485        return None;
486    }
487    let mut aligns: Vec<TableAlign> = Vec::with_capacity(cells.len());
488    for cell in cells {
489        let trimmed: &str = cell.trim();
490        if trimmed.is_empty() {
491            return None;
492        }
493        let left: bool = trimmed.starts_with(':');
494        let right: bool = trimmed.ends_with(':');
495        let inner: &str = trimmed.trim_matches(':');
496        if inner.is_empty() || !inner.chars().all(|c: char| c == '-') {
497            return None;
498        }
499        let align: TableAlign = match (left, right) {
500            (true, true) => TableAlign::Center,
501            (true, false) => TableAlign::Left,
502            (false, true) => TableAlign::Right,
503            (false, false) => TableAlign::None,
504        };
505        aligns.push(align);
506    }
507    Some(aligns)
508}
509
510/// Splits a GFM table row into trimmed cells, respecting escaped pipes `\|` and inline backtick code spans.
511///
512/// # Arguments
513///
514/// - `&str` - Trimmed GFM table row.
515///
516/// # Returns
517///
518/// - `Vec<String>` - Trimmed cell contents.
519fn split_table_row(row: &str) -> Vec<String> {
520    let mut inner: &str = row.trim();
521    if let Some(stripped) = inner.strip_prefix('|') {
522        inner = stripped;
523    }
524    if inner.ends_with('|') && !ends_with_escaped_pipe(inner) {
525        inner = &inner[..(inner.len() - 1)];
526    }
527    let bytes: &[u8] = inner.as_bytes();
528    let len: usize = bytes.len();
529    let mut cells: Vec<String> = Vec::new();
530    let mut start: usize = 0;
531    let mut i: usize = 0;
532    let mut in_code: bool = false;
533    while i < len {
534        if bytes[i] == b'\\' && i + 1 < len {
535            i += 2;
536            continue;
537        }
538        if bytes[i] == b'`' {
539            in_code = !in_code;
540            i += 1;
541            continue;
542        }
543        if bytes[i] == b'|' && !in_code {
544            cells.push(inner[start..i].trim().to_string());
545            start = i + 1;
546        }
547        i += 1;
548    }
549    cells.push(inner[start..].trim().to_string());
550    cells
551}
552
553/// Returns `true` when `s` ends with an escaped pipe (`\|`) preceded by an odd number of backslashes.
554///
555/// # Arguments
556///
557/// - `&str` - Table row slice ending in `|`.
558///
559/// # Returns
560///
561/// - `bool` - Whether the trailing `|` is escaped.
562fn ends_with_escaped_pipe(s: &str) -> bool {
563    let bytes: &[u8] = s.as_bytes();
564    if bytes.len() < 2 || bytes[bytes.len() - 1] != b'|' {
565        return false;
566    }
567    let mut backslashes: usize = 0;
568    let mut idx: usize = bytes.len() - 1;
569    while idx > 0 && bytes[idx - 1] == b'\\' {
570        backslashes += 1;
571        idx -= 1;
572    }
573    backslashes % 2 == 1
574}
575
576/// Formats a single GFM table header or body row padded to Prettier column widths and alignments.
577///
578/// # Arguments
579///
580/// - `&[String]` - Row cells.
581/// - `&[usize]` - Column display widths.
582/// - `&[TableAlign]` - Column alignments.
583///
584/// # Returns
585///
586/// - `String` - Formatted pipe-delimited row.
587fn format_table_data_row(cells: &[String], widths: &[usize], alignments: &[TableAlign]) -> String {
588    let mut out: String = String::from("|");
589    for (idx, cell) in cells.iter().enumerate() {
590        let col_w: usize = widths[idx];
591        let cell_w: usize = str_display_width(cell);
592        let pad: usize = col_w.saturating_sub(cell_w);
593        out.push(TEXT_SPACE);
594        match alignments[idx] {
595            TableAlign::None | TableAlign::Left => {
596                out.push_str(cell);
597                push_spaces(&mut out, pad);
598            }
599            TableAlign::Right => {
600                push_spaces(&mut out, pad);
601                out.push_str(cell);
602            }
603            TableAlign::Center => {
604                let left_pad: usize = pad / 2;
605                let right_pad: usize = pad - left_pad;
606                push_spaces(&mut out, left_pad);
607                out.push_str(cell);
608                push_spaces(&mut out, right_pad);
609            }
610        }
611        out.push_str(" |");
612    }
613    out
614}
615
616/// Formats a GFM table separator row matching Prettier dash counts and alignment colons.
617///
618/// # Arguments
619///
620/// - `&[usize]` - Column display widths (`>= 3`).
621/// - `&[TableAlign]` - Column alignments.
622///
623/// # Returns
624///
625/// - `String` - Formatted delimiter row.
626fn format_table_sep_row(widths: &[usize], alignments: &[TableAlign]) -> String {
627    let mut out: String = String::from("|");
628    for (idx, &width) in widths.iter().enumerate() {
629        out.push(TEXT_SPACE);
630        match alignments[idx] {
631            TableAlign::None => {
632                for _ in 0..width {
633                    out.push('-');
634                }
635            }
636            TableAlign::Left => {
637                out.push(':');
638                for _ in 0..width.saturating_sub(1) {
639                    out.push('-');
640                }
641            }
642            TableAlign::Right => {
643                for _ in 0..width.saturating_sub(1) {
644                    out.push('-');
645                }
646                out.push(':');
647            }
648            TableAlign::Center => {
649                out.push(':');
650                for _ in 0..width.saturating_sub(2) {
651                    out.push('-');
652                }
653                out.push(':');
654            }
655        }
656        out.push_str(" |");
657    }
658    out
659}
660
661/// Parses and normalizes an ATX heading (`#`..`###### Title`).
662///
663/// # Arguments
664///
665/// - `&str` - Trimmed Markdown line.
666///
667/// # Returns
668///
669/// - `Option<String>` - Normalized heading line if valid ATX heading.
670fn format_atx_heading(trimmed: &str) -> Option<String> {
671    let level: usize = trimmed.chars().take_while(|c: &char| *c == '#').count();
672    if level == 0 || level > 6 {
673        return None;
674    }
675    let rest: &str = &trimmed[level..];
676    if !rest.is_empty() && !rest.starts_with(TEXT_SPACE) && !rest.starts_with(TEXT_TAB) {
677        return None;
678    }
679    let title: &str = rest.trim().trim_end_matches('#').trim_end();
680    let hashes: &str = &trimmed[..level];
681    if title.is_empty() {
682        return Some(hashes.to_string());
683    }
684    Some(format!("{hashes} {title}"))
685}
686
687/// Returns `true` when `trimmed` is a CommonMark thematic break (`---`, `***`, `___`, with optional spaces).
688///
689/// # Arguments
690///
691/// - `&str` - Trimmed Markdown line.
692///
693/// # Returns
694///
695/// - `bool` - Whether the line is a thematic break.
696fn is_thematic_break(trimmed: &str) -> bool {
697    let mut marker: Option<char> = None;
698    let mut count: usize = 0;
699    for ch in trimmed.chars() {
700        if ch == TEXT_SPACE || ch == TEXT_TAB {
701            continue;
702        }
703        if ch != '-' && ch != '*' && ch != '_' {
704            return false;
705        }
706        if let Some(m) = marker {
707            if m != ch {
708                return false;
709            }
710        } else {
711            marker = Some(ch);
712        }
713        count += 1;
714    }
715    count >= 3
716}
717
718/// Formats a Markdown blockquote line (bare `>` for empty lines, `> content` for non-empty lines).
719///
720/// # Arguments
721///
722/// - `&str` - Trimmed blockquote line starting with `>`.
723///
724/// # Returns
725///
726/// - `String` - Normalized blockquote line.
727fn format_blockquote_line(trimmed: &str) -> String {
728    let mut rest: &str = trimmed;
729    let mut depth: usize = 0;
730    while let Some(after) = rest.strip_prefix('>') {
731        depth += 1;
732        rest = after.trim_start_matches([TEXT_SPACE, TEXT_TAB]);
733    }
734    let mut out: String = String::with_capacity(depth * 2 + rest.len());
735    for i in 0..depth {
736        if i > 0 {
737            out.push(TEXT_SPACE);
738        }
739        out.push('>');
740    }
741    if !rest.is_empty() {
742        out.push(TEXT_SPACE);
743        out.push_str(rest);
744    }
745    out
746}
747
748/// Attempts to parse a Markdown unordered or ordered list item line.
749///
750/// # Arguments
751///
752/// - `&str` - Raw Markdown line.
753///
754/// # Returns
755///
756/// - `Option<ListItemLine>` - Parsed list item metadata if matched.
757fn parse_list_item(raw_line: &str) -> Option<ListItemLine> {
758    let raw_indent: usize = count_leading_spaces_md(raw_line);
759    let trimmed: &str = raw_line.trim_start_matches([TEXT_SPACE, TEXT_TAB]);
760    if let Some(rest) = trimmed
761        .strip_prefix("- ")
762        .or_else(|| trimmed.strip_prefix("* "))
763        .or_else(|| trimmed.strip_prefix("+ "))
764    {
765        return Some(ListItemLine::new(
766            raw_indent,
767            ListKind::Unordered,
768            "-".to_string(),
769            rest.trim().to_string(),
770        ));
771    }
772    let digits_len: usize = trimmed
773        .bytes()
774        .take_while(|b: &u8| b.is_ascii_digit())
775        .count();
776    if digits_len > 0 && digits_len <= 9 && digits_len < trimmed.len() {
777        let bytes: &[u8] = trimmed.as_bytes();
778        let delim: u8 = bytes[digits_len];
779        if (delim == b'.' || delim == b')')
780            && digits_len + 1 < trimmed.len()
781            && (bytes[digits_len + 1] == b' ' || bytes[digits_len + 1] == b'\t')
782        {
783            let number: &str = &trimmed[..digits_len];
784            let body: &str = trimmed[(digits_len + 1)..].trim();
785            return Some(ListItemLine::new(
786                raw_indent,
787                ListKind::Ordered,
788                format!("{number}."),
789                body.to_string(),
790            ));
791        }
792    }
793    None
794}
795
796/// Normalizes a list item's raw indentation to Prettier's 2-space nesting steps.
797///
798/// # Arguments
799///
800/// - `&mut Vec<usize>` - Stack of active raw list indentation levels.
801/// - `usize` - Raw leading space count of the current list item.
802///
803/// # Returns
804///
805/// - `usize` - Normalized output indentation (`2 * level`).
806fn resolve_list_item_indent(list_indents: &mut Vec<usize>, raw_indent: usize) -> usize {
807    while let Some(&top) = list_indents.last() {
808        if raw_indent < top {
809            let _: Option<usize> = list_indents.pop();
810        } else {
811            break;
812        }
813    }
814    if list_indents.last().copied() != Some(raw_indent) {
815        list_indents.push(raw_indent);
816    }
817    list_indents.len().saturating_sub(1) * PRETTIER_TAB_WIDTH
818}
819
820/// Computes normalized indentation for content nested inside an active list item.
821///
822/// # Arguments
823///
824/// - `&[usize]` - Active raw list indentation stack.
825/// - `usize` - Raw indentation of the nested element.
826///
827/// # Returns
828///
829/// - `usize` - Normalized output indentation in spaces.
830fn normalize_nested_indent(list_indents: &[usize], raw_indent: usize) -> usize {
831    if list_indents.is_empty() {
832        return (raw_indent / PRETTIER_TAB_WIDTH) * PRETTIER_TAB_WIDTH;
833    }
834    let level: usize = list_indents
835        .iter()
836        .filter(|&&ind: &&usize| ind < raw_indent)
837        .count();
838    level.max(1) * PRETTIER_TAB_WIDTH
839}
840
841/// Counts leading indentation columns of a Markdown line (expanding tabs as 2 spaces).
842///
843/// # Arguments
844///
845/// - `&str` - Raw Markdown line.
846///
847/// # Returns
848///
849/// - `usize` - Indentation width in spaces.
850fn count_leading_spaces_md(line: &str) -> usize {
851    let mut count: usize = 0;
852    for ch in line.chars() {
853        if ch == TEXT_SPACE {
854            count += 1;
855        } else if ch == TEXT_TAB {
856            count += PRETTIER_TAB_WIDTH;
857        } else {
858            break;
859        }
860    }
861    count
862}
863
864/// Returns `true` when `trimmed` begins with a raw HTML block tag or comment (`<center>`, `<div>`, `<!--`, `<img`, etc.).
865///
866/// # Arguments
867///
868/// - `&str` - Trimmed Markdown line.
869///
870/// # Returns
871///
872/// - `bool` - Whether the line should be treated as an HTML block line.
873fn is_html_block_line(trimmed: &str) -> bool {
874    if !trimmed.starts_with('<') {
875        return false;
876    }
877    if trimmed.starts_with("<!--") || trimmed.starts_with("</") {
878        return true;
879    }
880    let rest: &str = &trimmed[1..];
881    let tag_len: usize = rest
882        .bytes()
883        .take_while(|b: &u8| b.is_ascii_alphanumeric() || *b == b'-')
884        .count();
885    if tag_len == 0 {
886        return false;
887    }
888    let after: &str = &rest[tag_len..];
889    after.is_empty()
890        || after.starts_with('>')
891        || after.starts_with(TEXT_SPACE)
892        || after.starts_with('/')
893}
894
895/// Normalizes standalone Markdown `*italic*` emphasis spans to Prettier's `_italic_` style outside inline code spans, leaving `**bold**` and intraword asterisks untouched.
896///
897/// # Arguments
898///
899/// - `&str` - Single Markdown paragraph line.
900///
901/// # Returns
902///
903/// - `String` - Line with Prettier-aligned `_italic_` emphasis markers.
904fn normalize_inline_emphasis(line: &str) -> String {
905    if !line.contains('*') {
906        return line.to_string();
907    }
908    let bytes: &[u8] = line.as_bytes();
909    let len: usize = bytes.len();
910    let mut out: String = String::with_capacity(len);
911    let mut i: usize = 0;
912    let mut in_code: bool = false;
913    while i < len {
914        if bytes[i] == b'\\' && i + 1 < len {
915            out.push_str(&line[i..(i + 2)]);
916            i += 2;
917            continue;
918        }
919        if bytes[i] == b'`' {
920            in_code = !in_code;
921            out.push('`');
922            i += 1;
923            continue;
924        }
925        if !in_code && bytes[i] == b'*' {
926            let star_run: usize = bytes[i..].iter().take_while(|&&b: &&u8| b == b'*').count();
927            let prev_is_alnum: bool = i > 0 && bytes[i - 1].is_ascii_alphanumeric();
928            if star_run == 1
929                && !prev_is_alnum
930                && i + 1 < len
931                && bytes[i + 1] != b' '
932                && bytes[i + 1] != b'\t'
933                && let Some(close_idx) = find_closing_single_star(bytes, i + 1)
934            {
935                out.push('_');
936                out.push_str(&line[(i + 1)..close_idx]);
937                out.push('_');
938                i = close_idx + 1;
939                continue;
940            }
941            out.push_str(&line[i..(i + star_run)]);
942            i += star_run;
943            continue;
944        }
945        let ch_len: usize = line[i..].chars().next().map(char::len_utf8).unwrap_or(1);
946        out.push_str(&line[i..(i + ch_len)]);
947        i += ch_len;
948    }
949    out
950}
951
952/// Finds the matching closing single `*` for a Prettier `_italic_` span starting after the opening `*`.
953///
954/// # Arguments
955///
956/// - `&[u8]` - Paragraph line bytes.
957/// - `usize` - Byte offset immediately after the opening `*`.
958///
959/// # Returns
960///
961/// - `Option<usize>` - Byte offset of the closing `*` if valid emphasis span.
962fn find_closing_single_star(bytes: &[u8], start: usize) -> Option<usize> {
963    let len: usize = bytes.len();
964    let mut i: usize = start;
965    let mut in_code: bool = false;
966    while i < len {
967        if bytes[i] == b'\\' && i + 1 < len {
968            i += 2;
969            continue;
970        }
971        if bytes[i] == b'`' {
972            in_code = !in_code;
973            i += 1;
974            continue;
975        }
976        if !in_code && bytes[i] == b'*' {
977            let star_run: usize = bytes[i..].iter().take_while(|&&b: &&u8| b == b'*').count();
978            if star_run == 1 {
979                let prev_non_ws: bool = i > start && bytes[i - 1] != b' ' && bytes[i - 1] != b'\t';
980                let next_is_alnum: bool = i + 1 < len && bytes[i + 1].is_ascii_alphanumeric();
981                if prev_non_ws && !next_is_alnum {
982                    return Some(i);
983                }
984            }
985            i += star_run;
986            continue;
987        }
988        i += 1;
989    }
990    None
991}