Skip to main content

crate_cli/fmt/markdown/
fn.rs

1use super::*;
2
3/// Formats Markdown (`.md` / `.markdown` / `.mdx`) matching VS Code `esbenp.prettier-vscode` (Prettier 3.7.4: `tabWidth: 2`, `singleQuote: true`, `semi: true`, `printWidth: 80`, `proseWrap: "preserve"`, `embeddedLanguageFormatting: "auto"`, LF).
4///
5/// # Arguments
6///
7/// - `&str` - Raw Markdown source text.
8///
9/// # Returns
10///
11/// - `String` - Formatted Markdown document matching Prettier 3.7.4.
12pub fn format_markdown(input: &str) -> String {
13    format_markdown_inner(input, PRETTIER_PRINT_WIDTH, 0)
14}
15
16/// Formats Markdown at a specific line width and embedded recursion depth.
17///
18/// # Arguments
19///
20/// - `&str` - Raw Markdown text.
21/// - `usize` - Target maximum line width.
22/// - `usize` - Current embedded Markdown nesting depth.
23///
24/// # Returns
25///
26/// - `String` - Formatted Markdown text with Prettier 3.7.4 parity post-processing.
27fn format_markdown_inner(input: &str, width: usize, depth: usize) -> String {
28    let mut opts: Options = vscode_tidy_options();
29    opts.markdown.width = width;
30    let prepared: String = normalize_markdown_triple_emphasis_prepass(input);
31    let formatted: String =
32        tidy::markdown::format_with(&prepared, &opts.markdown, |code: Code<'_>| {
33            format_markdown_embedded(code, &opts, depth)
34        });
35    normalize_markdown_prettier_quirks(&formatted)
36}
37
38/// Formats Prettier-supported YAML frontmatter and embedded fenced code blocks inside Markdown, leaving non-Prettier languages verbatim.
39///
40/// # Arguments
41///
42/// - `Code<'_>` - Embedded code slice, language tag, and available column width.
43/// - `&Options` - Base VS Code formatter options.
44/// - `usize` - Current embedded Markdown nesting depth.
45///
46/// # Returns
47///
48/// - `Option<String>` - Formatted embedded code if supported and valid, or `None` to preserve verbatim.
49fn format_markdown_embedded(code: Code<'_>, base_opts: &Options, depth: usize) -> Option<String> {
50    let lang_lower: String = code.lang.to_ascii_lowercase();
51    let lang: &str = lang_lower.as_str();
52    let mut sub_opts: Options = base_opts.clone();
53    sub_opts.share(&Shared {
54        width: Some(code.width),
55        ..Shared::default()
56    });
57    sub_opts.js.semi = true;
58    sub_opts.js.single_quote = true;
59    sub_opts.js.jsdoc = false;
60    sub_opts.yaml.single_quote = true;
61    if MD_EMBED_YAML.contains(&lang) {
62        return tidy::yaml::format(code.text, &sub_opts.yaml).ok();
63    }
64    if lang == MD_EMBED_JSON {
65        sub_opts.json.dialect = tidy::json::Dialect::Json;
66        return tidy::json::format(code.text, &sub_opts.json).ok();
67    }
68    if lang == MD_EMBED_JSONC {
69        sub_opts.json.dialect = tidy::json::Dialect::Jsonc;
70        return tidy::json::format(code.text, &sub_opts.json).ok();
71    }
72    if lang == MD_EMBED_JSON5 {
73        sub_opts.json.dialect = tidy::json::Dialect::Json5;
74        return tidy::json::format(code.text, &sub_opts.json).ok();
75    }
76    if MD_EMBED_JS.contains(&lang) {
77        let hint: &str = if lang == "cjs" {
78            MD_HINT_CJS
79        } else if lang == "jsx" {
80            MD_HINT_JSX
81        } else {
82            MD_HINT_JS
83        };
84        let mut embed: Verbatim = Verbatim;
85        return tidy::format(
86            code.text,
87            Language::Js(tidy::js::Dialect::Js),
88            &sub_opts,
89            Some(hint),
90            &mut embed,
91        )
92        .ok();
93    }
94    if MD_EMBED_TS.contains(&lang) {
95        let hint: &str = if lang == "cts" {
96            MD_HINT_CTS
97        } else if lang == "tsx" {
98            MD_HINT_TSX
99        } else {
100            MD_HINT_TS
101        };
102        let mut embed: Verbatim = Verbatim;
103        return tidy::format(
104            code.text,
105            Language::Js(tidy::js::Dialect::Ts),
106            &sub_opts,
107            Some(hint),
108            &mut embed,
109        )
110        .ok();
111    }
112    if lang == MD_EMBED_CSS {
113        return tidy::format(
114            code.text,
115            Language::Css(Dialect::Css),
116            &sub_opts,
117            None,
118            &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
119        )
120        .ok();
121    }
122    if lang == MD_EMBED_SCSS {
123        return tidy::format(
124            code.text,
125            Language::Css(Dialect::Scss),
126            &sub_opts,
127            None,
128            &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
129        )
130        .ok();
131    }
132    if lang == MD_EMBED_LESS {
133        return tidy::format(
134            code.text,
135            Language::Css(Dialect::Less),
136            &sub_opts,
137            None,
138            &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
139        )
140        .ok();
141    }
142    if lang == MD_EMBED_HTML {
143        return tidy::format(
144            code.text,
145            Language::Html,
146            &sub_opts,
147            None,
148            &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
149        )
150        .ok();
151    }
152    if lang == MD_EMBED_VUE {
153        return tidy::format(
154            code.text,
155            Language::Vue,
156            &sub_opts,
157            Some(MD_HINT_VUE),
158            &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
159        )
160        .ok();
161    }
162    if MD_EMBED_MARKDOWN.contains(&lang) && depth < MD_MAX_EMBED_DEPTH {
163        return Some(format_markdown_inner(code.text, code.width, depth + 1));
164    }
165    None
166}
167
168/// Pre-pass rewriting triple emphasis (`***...***` and `___...___`) to `**_..._**` outside frontmatter, code blocks, thematic breaks, and inline code spans.
169///
170/// Preserves explicit `_**...**_` spans verbatim so `tidy::markdown` matches Prettier 3.7.4 across all four bold-italic delimiter combinations.
171///
172/// # Arguments
173///
174/// - `&str` - Raw Markdown input before `tidy::markdown`.
175///
176/// # Returns
177///
178/// - `String` - Pre-normalized Markdown ready for `tidy::markdown`.
179fn normalize_markdown_triple_emphasis_prepass(input: &str) -> String {
180    if !input.contains(MD_TRIPLE_STAR) && !input.contains(MD_TRIPLE_UNDER) {
181        return input.to_string();
182    }
183    let has_trailing_lf: bool = input.ends_with(TEXT_LF);
184    let raw_lines: Vec<&str> = input.split(TEXT_LF).collect();
185    let line_count: usize = if has_trailing_lf && !raw_lines.is_empty() {
186        raw_lines.len() - 1
187    } else {
188        raw_lines.len()
189    };
190    let mut out_lines: Vec<String> = Vec::with_capacity(line_count);
191    let mut idx: usize = 0;
192    if line_count >= 2 {
193        let first_clean: &str = raw_lines[0].trim_end_matches(TEXT_CR);
194        if (first_clean == MD_FRONTMATTER_YAML || first_clean == MD_FRONTMATTER_TOML)
195            && let Some(close_rel) = raw_lines[1..line_count]
196                .iter()
197                .position(|l: &&str| l.trim_end_matches(TEXT_CR) == first_clean)
198        {
199            let close_idx: usize = close_rel + 1;
200            for line in &raw_lines[..=close_idx] {
201                out_lines.push((*line).to_string());
202            }
203            idx = close_idx + 1;
204        }
205    }
206    let mut active_fence: Option<(char, usize, usize)> = None;
207    let mut prev_bq_depth: usize = 0;
208    let mut list_indent_stack: Vec<usize> = Vec::new();
209    let mut prev_can_start_indented_code: bool = true;
210    let mut indented_code_threshold: Option<usize> = None;
211    while idx < line_count {
212        let line: &str = raw_lines[idx];
213        let clean: &str = line.trim_end_matches(TEXT_CR);
214        let (bq_depth, _bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
215            strip_blockquote_and_measure_indent(clean);
216        if let Some((fence_ch, fence_len, fence_base)) = active_fence {
217            out_lines.push(line.to_string());
218            if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
219                active_fence = None;
220                prev_can_start_indented_code = true;
221            }
222            idx += 1;
223            continue;
224        }
225        if bq_depth != prev_bq_depth {
226            list_indent_stack.clear();
227            indented_code_threshold = None;
228            prev_can_start_indented_code = true;
229            prev_bq_depth = bq_depth;
230        }
231        if stripped.is_empty() {
232            prev_can_start_indented_code = true;
233            out_lines.push(line.to_string());
234            idx += 1;
235            continue;
236        }
237        if let Some(threshold) = indented_code_threshold {
238            if indent_cols >= threshold {
239                prev_can_start_indented_code = true;
240                out_lines.push(line.to_string());
241                idx += 1;
242                continue;
243            }
244            indented_code_threshold = None;
245        }
246        while list_indent_stack
247            .last()
248            .is_some_and(|&col: &usize| indent_cols < col)
249        {
250            list_indent_stack.pop();
251        }
252        let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
253        let rel_indent: usize = indent_cols.saturating_sub(base_indent);
254        if rel_indent >= 4 && prev_can_start_indented_code {
255            indented_code_threshold = Some(base_indent + 4);
256            prev_can_start_indented_code = true;
257            out_lines.push(line.to_string());
258            idx += 1;
259            continue;
260        }
261        let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
262            && let Some((marker_cols, after)) = parse_list_marker(stripped)
263        {
264            let next_col: usize = indent_cols + marker_cols;
265            list_indent_stack.push(next_col);
266            (next_col, after)
267        } else {
268            (base_indent, stripped)
269        };
270        if rel_indent < 4
271            && let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
272        {
273            active_fence = Some((fence_ch, fence_len, fence_base));
274            prev_can_start_indented_code = false;
275            out_lines.push(line.to_string());
276            idx += 1;
277            continue;
278        }
279        if rel_indent < 4 && is_thematic_break_line(stripped) {
280            prev_can_start_indented_code = true;
281            out_lines.push(line.to_string());
282            idx += 1;
283            continue;
284        }
285        prev_can_start_indented_code = rel_indent < 4 && is_atx_heading_or_dash_break(stripped);
286        let has_cr: bool = line.ends_with(TEXT_CR);
287        let mut rewritten: String = rewrite_triple_emphasis_line(clean);
288        if has_cr {
289            rewritten.push(TEXT_CR);
290        }
291        out_lines.push(rewritten);
292        idx += 1;
293    }
294    let mut out: String = out_lines.join("\n");
295    if has_trailing_lf {
296        out.push(TEXT_LF);
297    }
298    out
299}
300
301/// Returns `true` when `stripped` is a CommonMark thematic break made of `*` or `_`.
302///
303/// # Arguments
304///
305/// - `&str` - Line slice after container indentation and blockquote markers.
306///
307/// # Returns
308///
309/// - `bool` - Whether the line is a `*` or `_` thematic break.
310fn is_thematic_break_line(stripped: &str) -> bool {
311    let mut marker: Option<char> = None;
312    let mut count: usize = 0;
313    for ch in stripped.chars() {
314        if ch == TEXT_SPACE || ch == TEXT_TAB {
315            continue;
316        }
317        if ch != '*' && ch != '_' {
318            return false;
319        }
320        if let Some(prev) = marker {
321            if prev != ch {
322                return false;
323            }
324        } else {
325            marker = Some(ch);
326        }
327        count += 1;
328    }
329    count >= 3
330}
331
332/// Rewrites `***...***` and `___...___` to `**_..._**` within a single Markdown line outside escapes, code spans, autolinks, and link destinations.
333///
334/// # Arguments
335///
336/// - `&str` - Single non-code Markdown line without trailing CR.
337///
338/// # Returns
339///
340/// - `String` - Line with triple emphasis rewritten to `**_..._**`.
341fn rewrite_triple_emphasis_line(line: &str) -> String {
342    if !line.contains(MD_TRIPLE_STAR) && !line.contains(MD_TRIPLE_UNDER) {
343        return line.to_string();
344    }
345    let bytes: &[u8] = line.as_bytes();
346    let len: usize = bytes.len();
347    let mut out: String = String::with_capacity(len);
348    let mut i: usize = 0;
349    while i < len {
350        if bytes[i] == b'\\' && i + 1 < len {
351            let next_len: usize = line[(i + 1)..]
352                .chars()
353                .next()
354                .map(char::len_utf8)
355                .unwrap_or(1);
356            out.push_str(&line[i..(i + 1 + next_len)]);
357            i += 1 + next_len;
358            continue;
359        }
360        if bytes[i] == b'`' {
361            let end_code: usize = scan_inline_code_span(bytes, i);
362            out.push_str(&line[i..end_code]);
363            i = end_code;
364            continue;
365        }
366        if bytes[i] == b']'
367            && i + 1 < len
368            && bytes[i + 1] == b'('
369            && let Some(end_link) = scan_inline_link_tail(bytes, i + 2)
370        {
371            out.push_str(&line[i..end_link]);
372            i = end_link;
373            continue;
374        }
375        if bytes[i] == b'<'
376            && let Some(end_angle) = scan_autolink_or_tag(bytes, i)
377        {
378            out.push_str(&line[i..end_angle]);
379            i = end_angle;
380            continue;
381        }
382        if (bytes[i] == b'*' || bytes[i] == b'_')
383            && i + 2 < len
384            && bytes[i + 1] == bytes[i]
385            && bytes[i + 2] == bytes[i]
386        {
387            let delim: u8 = bytes[i];
388            let prev_not_delim: bool = i == 0 || bytes[i - 1] != delim;
389            let next_not_delim: bool = i + 3 < len && bytes[i + 3] != delim;
390            let next_not_ws: bool = i + 3 < len && !bytes[i + 3].is_ascii_whitespace();
391            let under_boundary_ok: bool = delim != b'_'
392                || i == 0
393                || !line[..i]
394                    .chars()
395                    .next_back()
396                    .is_some_and(char::is_alphanumeric);
397            if prev_not_delim
398                && next_not_delim
399                && next_not_ws
400                && under_boundary_ok
401                && let Some(close_idx) = find_closing_triple_emphasis(line, i + 3, delim)
402            {
403                out.push_str(MD_PRETTIER_BOLD_ITALIC_OPEN);
404                out.push_str(&line[(i + 3)..close_idx]);
405                out.push_str(MD_PRETTIER_BOLD_ITALIC_CLOSE);
406                i = close_idx + 3;
407                continue;
408            }
409        }
410        let ch_len: usize = line[i..].chars().next().map(char::len_utf8).unwrap_or(1);
411        out.push_str(&line[i..(i + ch_len)]);
412        i += ch_len;
413    }
414    out
415}
416
417/// Scans past an inline link `(dest ...)` tail starting right after `](` so destinations are not rewritten.
418///
419/// # Arguments
420///
421/// - `&[u8]` - Line bytes.
422/// - `usize` - Byte index immediately after `](`.
423///
424/// # Returns
425///
426/// - `Option<usize>` - Byte index right after the closing `)` if well-formed.
427fn scan_inline_link_tail(bytes: &[u8], start: usize) -> Option<usize> {
428    let len: usize = bytes.len();
429    let mut i: usize = start;
430    while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
431        i += 1;
432    }
433    let after_dest: usize = scan_link_destination(bytes, i)?;
434    let mut j: usize = after_dest;
435    while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
436        j += 1;
437    }
438    if j < len && bytes[j] == b')' {
439        return Some(j + 1);
440    }
441    if j > after_dest && j < len && (bytes[j] == b'"' || bytes[j] == b'\'' || bytes[j] == b'(') {
442        let close_delim: u8 = if bytes[j] == b'(' { b')' } else { bytes[j] };
443        j += 1;
444        while j < len {
445            if bytes[j] == b'\\' && j + 1 < len {
446                j += 2;
447                continue;
448            }
449            if bytes[j] == close_delim {
450                j += 1;
451                break;
452            }
453            j += 1;
454        }
455        while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
456            j += 1;
457        }
458        if j < len && bytes[j] == b')' {
459            return Some(j + 1);
460        }
461    }
462    None
463}
464
465/// Scans an angle-bracket autolink or raw HTML tag starting at `<` so inner characters are not rewritten.
466///
467/// # Arguments
468///
469/// - `&[u8]` - Line bytes.
470/// - `usize` - Byte index of `<`.
471///
472/// # Returns
473///
474/// - `Option<usize>` - Byte index right after `>` when `<...>` is an autolink or tag.
475fn scan_autolink_or_tag(bytes: &[u8], start: usize) -> Option<usize> {
476    let len: usize = bytes.len();
477    if start + 2 >= len {
478        return None;
479    }
480    let next: u8 = bytes[start + 1];
481    if !next.is_ascii_alphabetic() && next != b'/' && next != b'!' {
482        return None;
483    }
484    let mut i: usize = start + 2;
485    while i < len {
486        if bytes[i] == b'>' {
487            return Some(i + 1);
488        }
489        if bytes[i] == b'<' {
490            return None;
491        }
492        i += 1;
493    }
494    None
495}
496
497/// Finds the matching closing `***` or `___` delimiter for a triple-emphasis span starting at `start`.
498///
499/// # Arguments
500///
501/// - `&str` - Full Markdown line.
502/// - `usize` - Byte index right after the opening 3-byte delimiter.
503/// - `u8` - Delimiter byte (`b'*'` or `b'_'`).
504///
505/// # Returns
506///
507/// - `Option<usize>` - Byte index of the matching closing 3-byte delimiter.
508fn find_closing_triple_emphasis(line: &str, start: usize, delim: u8) -> Option<usize> {
509    let bytes: &[u8] = line.as_bytes();
510    let len: usize = bytes.len();
511    let mut i: usize = start;
512    while i + 2 < len {
513        if bytes[i] == b'\\' && i + 1 < len {
514            i += 2;
515            continue;
516        }
517        if bytes[i] == b'`' {
518            i = scan_inline_code_span(bytes, i);
519            continue;
520        }
521        if bytes[i] == delim && bytes[i + 1] == delim && bytes[i + 2] == delim {
522            let prev_ok: bool =
523                i > start && bytes[i - 1] != delim && !bytes[i - 1].is_ascii_whitespace();
524            let next_not_delim: bool = i + 3 >= len || bytes[i + 3] != delim;
525            let under_boundary_ok: bool = delim != b'_'
526                || i + 3 >= len
527                || !line[(i + 3)..]
528                    .chars()
529                    .next()
530                    .is_some_and(char::is_alphanumeric);
531            if prev_ok && next_not_delim && under_boundary_ok {
532                return Some(i);
533            }
534        }
535        i += 1;
536    }
537    None
538}
539
540/// Applies minimal fence-safe and inline-code-safe Prettier 3.7.4 Markdown parity normalizations on top of `tidy::markdown`.
541///
542/// Inserts the single blank line Prettier emits inside empty fenced code blocks and converts double-quoted link/image/definition titles to Prettier `singleQuote: true` quoting.
543///
544/// # Arguments
545///
546/// - `&str` - Markdown output produced by `tidy::markdown`.
547///
548/// # Returns
549///
550/// - `String` - Prettier 3.7.4 aligned Markdown output.
551fn normalize_markdown_prettier_quirks(input: &str) -> String {
552    if !input.contains('"') && !input.contains(MD_FENCE_BACKTICK) && !input.contains(MD_FENCE_TILDE)
553    {
554        return input.to_string();
555    }
556    let has_trailing_lf: bool = input.ends_with(TEXT_LF);
557    let raw_lines: Vec<&str> = input.split(TEXT_LF).collect();
558    let line_count: usize = if has_trailing_lf && !raw_lines.is_empty() {
559        raw_lines.len() - 1
560    } else {
561        raw_lines.len()
562    };
563    let mut out_lines: Vec<String> = Vec::with_capacity(line_count);
564    let mut idx: usize = 0;
565    if line_count >= 2
566        && (raw_lines[0] == MD_FRONTMATTER_YAML || raw_lines[0] == MD_FRONTMATTER_TOML)
567    {
568        let fence: &str = raw_lines[0];
569        if let Some(close_rel) = raw_lines[1..line_count]
570            .iter()
571            .position(|l: &&str| *l == fence)
572        {
573            let close_idx: usize = close_rel + 1;
574            for line in &raw_lines[..=close_idx] {
575                out_lines.push((*line).to_string());
576            }
577            idx = close_idx + 1;
578        }
579    }
580    let mut active_fence: Option<(char, usize, usize)> = None;
581    let mut fence_just_opened: bool = false;
582    let mut prev_bq_depth: usize = 0;
583    let mut list_indent_stack: Vec<usize> = Vec::new();
584    let mut prev_can_start_indented_code: bool = true;
585    let mut indented_code_threshold: Option<usize> = None;
586    while idx < line_count {
587        let line: &str = raw_lines[idx];
588        let (bq_depth, bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
589            strip_blockquote_and_measure_indent(line);
590        if let Some((fence_ch, fence_len, fence_base)) = active_fence {
591            if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
592                if fence_just_opened {
593                    let blank_prefix: &str =
594                        line[..bq_end].trim_end_matches([TEXT_SPACE, TEXT_TAB]);
595                    out_lines.push(blank_prefix.to_string());
596                }
597                active_fence = None;
598                fence_just_opened = false;
599                prev_can_start_indented_code = true;
600            } else {
601                fence_just_opened = false;
602            }
603            out_lines.push(line.to_string());
604            idx += 1;
605            continue;
606        }
607        if bq_depth != prev_bq_depth {
608            list_indent_stack.clear();
609            indented_code_threshold = None;
610            prev_can_start_indented_code = true;
611            prev_bq_depth = bq_depth;
612        }
613        if stripped.is_empty() {
614            prev_can_start_indented_code = true;
615            out_lines.push(line.to_string());
616            idx += 1;
617            continue;
618        }
619        if let Some(threshold) = indented_code_threshold {
620            if indent_cols >= threshold {
621                prev_can_start_indented_code = true;
622                out_lines.push(line.to_string());
623                idx += 1;
624                continue;
625            }
626            indented_code_threshold = None;
627        }
628        while list_indent_stack
629            .last()
630            .is_some_and(|&col: &usize| indent_cols < col)
631        {
632            list_indent_stack.pop();
633        }
634        let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
635        let rel_indent: usize = indent_cols.saturating_sub(base_indent);
636        if rel_indent >= 4 && prev_can_start_indented_code {
637            indented_code_threshold = Some(base_indent + 4);
638            prev_can_start_indented_code = true;
639            out_lines.push(line.to_string());
640            idx += 1;
641            continue;
642        }
643        let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
644            && let Some((marker_cols, after)) = parse_list_marker(stripped)
645        {
646            let next_col: usize = indent_cols + marker_cols;
647            list_indent_stack.push(next_col);
648            (next_col, after)
649        } else {
650            (base_indent, stripped)
651        };
652        if rel_indent < 4
653            && let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
654        {
655            active_fence = Some((fence_ch, fence_len, fence_base));
656            fence_just_opened = true;
657            prev_can_start_indented_code = false;
658            out_lines.push(line.to_string());
659            idx += 1;
660            continue;
661        }
662        prev_can_start_indented_code = rel_indent < 4
663            && (is_thematic_break_line(stripped) || is_atx_heading_or_dash_break(stripped));
664        let step_def: String = normalize_link_def_title(line);
665        let step_inline: String = normalize_inline_prettier_line(&step_def);
666        out_lines.push(step_inline);
667        idx += 1;
668    }
669    let mut out: String = out_lines.join("\n");
670    if has_trailing_lf {
671        out.push(TEXT_LF);
672    }
673    out
674}
675
676/// Strips CommonMark blockquote markers (`>` with 0..=3 leading spaces and optional 1-column space) and measures remaining column indentation.
677///
678/// # Arguments
679///
680/// - `&str` - Raw Markdown line without trailing CR.
681///
682/// # Returns
683///
684/// - `(usize, usize, usize, &str)` - Blockquote depth, byte offset right after the last `>`, remaining column indentation (tab stop = 4), and content slice.
685fn strip_blockquote_and_measure_indent(line: &str) -> (usize, usize, usize, &str) {
686    let bytes: &[u8] = line.as_bytes();
687    let len: usize = bytes.len();
688    let mut idx: usize = 0;
689    let mut bq_depth: usize = 0;
690    let mut bq_end: usize = 0;
691    loop {
692        let mut scan: usize = idx;
693        let mut ws_cols: usize = 0;
694        while scan < len {
695            if bytes[scan] == b' ' {
696                ws_cols += 1;
697                scan += 1;
698            } else if bytes[scan] == b'\t' {
699                ws_cols += 4 - (ws_cols % 4);
700                scan += 1;
701            } else {
702                break;
703            }
704        }
705        if ws_cols < 4 && scan < len && bytes[scan] == b'>' {
706            bq_depth += 1;
707            scan += 1;
708            bq_end = scan;
709            if scan < len && bytes[scan] == b' ' {
710                scan += 1;
711            }
712            idx = scan;
713            continue;
714        }
715        return (bq_depth, bq_end, ws_cols, &line[scan..]);
716    }
717}
718
719/// Parses a CommonMark unordered (`-`, `*`, `+`) or ordered (`1.`, `1)`) list item marker at the start of `stripped`.
720///
721/// # Arguments
722///
723/// - `&str` - Line content after container indentation and blockquote markers.
724///
725/// # Returns
726///
727/// - `Option<(usize, &str)>` - Marker content column width and remaining text on the line when `stripped` starts a list item.
728fn parse_list_marker(stripped: &str) -> Option<(usize, &str)> {
729    let bytes: &[u8] = stripped.as_bytes();
730    let len: usize = bytes.len();
731    if len == 0 {
732        return None;
733    }
734    let marker_len: usize = if bytes[0] == b'-' || bytes[0] == b'*' || bytes[0] == b'+' {
735        1
736    } else if bytes[0].is_ascii_digit() {
737        let digits: usize = bytes
738            .iter()
739            .take(9)
740            .take_while(|&&b: &&u8| b.is_ascii_digit())
741            .count();
742        if digits == 0 || digits >= len || (bytes[digits] != b'.' && bytes[digits] != b')') {
743            return None;
744        }
745        digits + 1
746    } else {
747        return None;
748    };
749    if marker_len == len {
750        return Some((marker_len + 1, ""));
751    }
752    if bytes[marker_len] != b' ' && bytes[marker_len] != b'\t' {
753        return None;
754    }
755    let mut scan: usize = marker_len;
756    let mut ws_cols: usize = 0;
757    while scan < len {
758        if bytes[scan] == b' ' {
759            ws_cols += 1;
760            scan += 1;
761        } else if bytes[scan] == b'\t' {
762            ws_cols += 4 - ((marker_len + ws_cols) % 4);
763            scan += 1;
764        } else {
765            break;
766        }
767    }
768    if scan == len || ws_cols >= 5 {
769        return Some((marker_len + 1, ""));
770    }
771    Some((marker_len + ws_cols, &stripped[scan..]))
772}
773
774/// Returns `true` when `stripped` is an ATX heading (`#`..`######`) or a `-` thematic break that allows an indented code block on the next line.
775///
776/// # Arguments
777///
778/// - `&str` - Line slice after container indentation and blockquote markers.
779///
780/// # Returns
781///
782/// - `bool` - Whether the line terminates any paragraph and permits a following indented code block.
783fn is_atx_heading_or_dash_break(stripped: &str) -> bool {
784    let hashes: usize = stripped.chars().take_while(|c: &char| *c == '#').count();
785    if (1..=6).contains(&hashes) {
786        let rest: &str = &stripped[hashes..];
787        if rest.is_empty() || rest.starts_with(TEXT_SPACE) || rest.starts_with(TEXT_TAB) {
788            return true;
789        }
790    }
791    let mut dashes: usize = 0;
792    for ch in stripped.chars() {
793        if ch == TEXT_SPACE || ch == TEXT_TAB {
794            continue;
795        }
796        if ch != '-' {
797            return false;
798        }
799        dashes += 1;
800    }
801    dashes >= 3
802}
803
804/// Parses an opening fenced code block delimiter (`` ``` `` or `~~~`) on an unquoted line slice.
805///
806/// # Arguments
807///
808/// - `&str` - Line slice after container indentation and blockquote markers.
809///
810/// # Returns
811///
812/// - `Option<(char, usize)>` - Fence character and delimiter length if an opening fence starts here.
813fn parse_opening_fence(stripped: &str) -> Option<(char, usize)> {
814    let first: char = stripped.chars().next()?;
815    if first != '`' && first != '~' {
816        return None;
817    }
818    let len: usize = stripped.chars().take_while(|c: &char| *c == first).count();
819    if len < 3 {
820        return None;
821    }
822    let info: &str = &stripped[len..];
823    if first == '`' && info.contains('`') {
824        return None;
825    }
826    Some((first, len))
827}
828
829/// Returns `true` when `stripped` is a valid closing fence matching `(fence_ch, fence_len)`.
830///
831/// # Arguments
832///
833/// - `&str` - Line slice after container indentation and blockquote markers.
834/// - `char` - Expected fence character (`` ` `` or `~`).
835/// - `usize` - Minimum closing fence length.
836///
837/// # Returns
838///
839/// - `bool` - Whether this line closes the active fenced code block.
840fn is_closing_fence(stripped: &str, fence_ch: char, fence_len: usize) -> bool {
841    let trimmed: &str = stripped.trim_end_matches([TEXT_SPACE, TEXT_TAB]);
842    let count: usize = trimmed
843        .chars()
844        .take_while(|c: &char| *c == fence_ch)
845        .count();
846    count >= fence_len && count == trimmed.len()
847}
848
849/// Converts a double-quoted title on a CommonMark link reference definition (`[label]: dest "title"`) to single quotes under `singleQuote: true`.
850///
851/// # Arguments
852///
853/// - `&str` - Non-code Markdown line.
854///
855/// # Returns
856///
857/// - `String` - Normalized line with single-quoted definition title when safe.
858fn normalize_link_def_title(line: &str) -> String {
859    let (_bq_depth, _bq_end, _indent_cols, trimmed): (usize, usize, usize, &str) =
860        strip_blockquote_and_measure_indent(line);
861    if !trimmed.starts_with('[') || trimmed.starts_with("[^") {
862        return line.to_string();
863    }
864    let prefix_len: usize = line.len() - trimmed.len();
865    let bytes: &[u8] = trimmed.as_bytes();
866    let len: usize = bytes.len();
867    let mut i: usize = 1;
868    while i < len {
869        if bytes[i] == b'\\' && i + 1 < len {
870            i += 2;
871            continue;
872        }
873        if bytes[i] == b']' {
874            break;
875        }
876        i += 1;
877    }
878    if i + 1 >= len || bytes[i] != b']' || bytes[i + 1] != b':' {
879        return line.to_string();
880    }
881    i += 2;
882    while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
883        i += 1;
884    }
885    let Some(after_dest) = scan_link_destination(bytes, i) else {
886        return line.to_string();
887    };
888    let mut ws: usize = after_dest;
889    while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
890        ws += 1;
891    }
892    if ws == after_dest || ws >= len || bytes[ws] != b'"' {
893        return line.to_string();
894    }
895    let Some(close_quote) = scan_double_quoted_title(bytes, ws) else {
896        return line.to_string();
897    };
898    if !trimmed[(close_quote + 1)..]
899        .trim_matches([TEXT_SPACE, TEXT_TAB])
900        .is_empty()
901    {
902        return line.to_string();
903    }
904    let inner: &str = &trimmed[(ws + 1)..close_quote];
905    let Some((open_ch, converted, close_ch)) = convert_double_title_to_prettier(inner) else {
906        return line.to_string();
907    };
908    let mut out: String = String::with_capacity(line.len());
909    out.push_str(&line[..(prefix_len + ws)]);
910    out.push(open_ch);
911    out.push_str(&converted);
912    out.push(close_ch);
913    out.push_str(&trimmed[(close_quote + 1)..]);
914    out
915}
916
917/// Normalizes inline link/image `"title"` quotes outside inline code spans to match Prettier `singleQuote: true`.
918///
919/// # Arguments
920///
921/// - `&str` - Single non-code Markdown line.
922///
923/// # Returns
924///
925/// - `String` - Normalized Markdown line.
926fn normalize_inline_prettier_line(line: &str) -> String {
927    if !line.contains('"') {
928        return line.to_string();
929    }
930    let bytes: &[u8] = line.as_bytes();
931    let len: usize = bytes.len();
932    let mut out: String = String::with_capacity(len);
933    let mut i: usize = 0;
934    while i < len {
935        if bytes[i] == b'\\' && i + 1 < len {
936            let next_len: usize = line[(i + 1)..]
937                .chars()
938                .next()
939                .map(char::len_utf8)
940                .unwrap_or(1);
941            out.push_str(&line[i..(i + 1 + next_len)]);
942            i += 1 + next_len;
943            continue;
944        }
945        if bytes[i] == b'`' {
946            let end_code: usize = scan_inline_code_span(bytes, i);
947            out.push_str(&line[i..end_code]);
948            i = end_code;
949            continue;
950        }
951        if bytes[i] == b']'
952            && i + 1 < len
953            && bytes[i + 1] == b'('
954            && let Some((replacement, next_i)) = try_rewrite_inline_link_title(line, i)
955        {
956            out.push_str(&replacement);
957            i = next_i;
958            continue;
959        }
960        let ch_len: usize = line[i..].chars().next().map(char::len_utf8).unwrap_or(1);
961        out.push_str(&line[i..(i + ch_len)]);
962        i += ch_len;
963    }
964    out
965}
966
967/// Scans past a CommonMark multi-backtick inline code span starting at `start`.
968///
969/// # Arguments
970///
971/// - `&[u8]` - Line bytes.
972/// - `usize` - Byte offset of the opening backtick.
973///
974/// # Returns
975///
976/// - `usize` - Byte offset immediately after the closing backtick run (or opening run if unclosed).
977fn scan_inline_code_span(bytes: &[u8], start: usize) -> usize {
978    let len: usize = bytes.len();
979    let ticks: usize = bytes[start..]
980        .iter()
981        .take_while(|&&b: &&u8| b == b'`')
982        .count();
983    let mut i: usize = start + ticks;
984    while i < len {
985        if bytes[i] == b'`' {
986            let run: usize = bytes[i..].iter().take_while(|&&b: &&u8| b == b'`').count();
987            if run == ticks {
988                return i + run;
989            }
990            i += run;
991            continue;
992        }
993        i += 1;
994    }
995    start + ticks
996}
997
998/// Attempts to rewrite an inline link or image `](dest "title")` title to Prettier `singleQuote: true` quoting.
999///
1000/// # Arguments
1001///
1002/// - `&str` - Full line string.
1003/// - `usize` - Byte offset of `]` immediately preceding `(`.
1004///
1005/// # Returns
1006///
1007/// - `Option<(String, usize)>` - Rewritten `](...)` slice and byte index after closing `)`, if rewritten.
1008fn try_rewrite_inline_link_title(line: &str, bracket_idx: usize) -> Option<(String, usize)> {
1009    let bytes: &[u8] = line.as_bytes();
1010    let len: usize = bytes.len();
1011    let mut i: usize = bracket_idx + 2;
1012    while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
1013        i += 1;
1014    }
1015    let after_dest: usize = scan_link_destination(bytes, i)?;
1016    let mut ws: usize = after_dest;
1017    while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
1018        ws += 1;
1019    }
1020    if ws == after_dest || ws >= len || bytes[ws] != b'"' {
1021        return None;
1022    }
1023    let close_quote: usize = scan_double_quoted_title(bytes, ws)?;
1024    let mut tail: usize = close_quote + 1;
1025    while tail < len && (bytes[tail] == b' ' || bytes[tail] == b'\t') {
1026        tail += 1;
1027    }
1028    if tail >= len || bytes[tail] != b')' {
1029        return None;
1030    }
1031    let inner: &str = &line[(ws + 1)..close_quote];
1032    let (open_ch, converted, close_ch): (char, String, char) =
1033        convert_double_title_to_prettier(inner)?;
1034    let mut out: String = String::with_capacity(tail + 1 - bracket_idx);
1035    out.push_str(&line[bracket_idx..ws]);
1036    out.push(open_ch);
1037    out.push_str(&converted);
1038    out.push(close_ch);
1039    out.push_str(&line[(close_quote + 1)..=tail]);
1040    Some((out, tail + 1))
1041}
1042
1043/// Scans a CommonMark link destination (`<...>` or balanced-paren non-whitespace token) starting at `start`.
1044///
1045/// # Arguments
1046///
1047/// - `&[u8]` - Line bytes.
1048/// - `usize` - Starting byte offset of the destination.
1049///
1050/// # Returns
1051///
1052/// - `Option<usize>` - Byte offset immediately after the link destination.
1053fn scan_link_destination(bytes: &[u8], start: usize) -> Option<usize> {
1054    let len: usize = bytes.len();
1055    if start >= len {
1056        return None;
1057    }
1058    if bytes[start] == b'<' {
1059        let mut i: usize = start + 1;
1060        while i < len {
1061            if bytes[i] == b'\\' && i + 1 < len {
1062                i += 2;
1063                continue;
1064            }
1065            if bytes[i] == b'>' {
1066                return Some(i + 1);
1067            }
1068            if bytes[i] == b'<' {
1069                return None;
1070            }
1071            i += 1;
1072        }
1073        return None;
1074    }
1075    let mut i: usize = start;
1076    let mut paren_depth: usize = 0;
1077    while i < len {
1078        let b: u8 = bytes[i];
1079        if b == b'\\' && i + 1 < len {
1080            i += 2;
1081            continue;
1082        }
1083        if b == b' ' || b == b'\t' {
1084            break;
1085        }
1086        if b == b'(' {
1087            paren_depth += 1;
1088        } else if b == b')' {
1089            if paren_depth == 0 {
1090                break;
1091            }
1092            paren_depth -= 1;
1093        }
1094        i += 1;
1095    }
1096    if i == start || paren_depth != 0 {
1097        return None;
1098    }
1099    Some(i)
1100}
1101
1102/// Scans a double-quoted Markdown link title starting at `open_quote`.
1103///
1104/// # Arguments
1105///
1106/// - `&[u8]` - Line bytes.
1107/// - `usize` - Byte offset of opening `"`.
1108///
1109/// # Returns
1110///
1111/// - `Option<usize>` - Byte offset of matching closing `"`.
1112fn scan_double_quoted_title(bytes: &[u8], open_quote: usize) -> Option<usize> {
1113    let len: usize = bytes.len();
1114    let mut i: usize = open_quote + 1;
1115    while i < len {
1116        if bytes[i] == b'\\' && i + 1 < len {
1117            i += 2;
1118            continue;
1119        }
1120        if bytes[i] == b'"' {
1121            return Some(i);
1122        }
1123        i += 1;
1124    }
1125    None
1126}
1127
1128/// Converts the interior of a double-quoted Markdown title to Prettier `singleQuote: true` delimiters.
1129///
1130/// Uses single quotes `'...'` whenever no `'` appears (unescaping `\"` to `"`), or parentheses `(...)` when both `'` and `\"` appear without parentheses; otherwise preserves `"..."`.
1131///
1132/// # Arguments
1133///
1134/// - `&str` - Raw inner slice between `"` delimiters.
1135///
1136/// # Returns
1137///
1138/// - `Option<(char, String, char)>` - Opening delimiter, normalized title content, and closing delimiter, or `None` to keep double quotes.
1139fn convert_double_title_to_prettier(inner: &str) -> Option<(char, String, char)> {
1140    let has_single: bool = inner.contains('\'');
1141    let has_escaped_double: bool = inner.contains('"');
1142    let (open_ch, close_ch): (char, char) = if !has_single {
1143        ('\'', '\'')
1144    } else if has_escaped_double && !inner.contains('(') && !inner.contains(')') {
1145        ('(', ')')
1146    } else {
1147        return None;
1148    };
1149    let bytes: &[u8] = inner.as_bytes();
1150    let len: usize = bytes.len();
1151    let mut out: String = String::with_capacity(len);
1152    let mut i: usize = 0;
1153    while i < len {
1154        if bytes[i] == b'\\' && i + 1 < len {
1155            if bytes[i + 1] == b'"' {
1156                out.push('"');
1157            } else {
1158                out.push('\\');
1159                let next_len: usize = inner[(i + 1)..]
1160                    .chars()
1161                    .next()
1162                    .map(char::len_utf8)
1163                    .unwrap_or(1);
1164                out.push_str(&inner[(i + 1)..(i + 1 + next_len)]);
1165                i += 1 + next_len;
1166                continue;
1167            }
1168            i += 2;
1169            continue;
1170        }
1171        let ch_len: usize = inner[i..].chars().next().map(char::len_utf8).unwrap_or(1);
1172        out.push_str(&inner[i..(i + ch_len)]);
1173        i += ch_len;
1174    }
1175    Some((open_ch, out, close_ch))
1176}