1use super::*;
2
3pub fn format_markdown(input: &str) -> String {
13 format_markdown_inner(input, PRETTIER_PRINT_WIDTH, 0)
14}
15
16fn format_markdown_inner(input: &str, width: usize, depth: usize) -> String {
28 let base_opts: &'static Options = vscode_tidy_options_ref();
29 let prepared: Cow<'_, str> = normalize_markdown_triple_emphasis_prepass(input);
30 let formatted: String = if width == PRETTIER_PRINT_WIDTH {
31 tidy::markdown::format_with(&prepared, &base_opts.markdown, |code: Code<'_>| {
32 format_markdown_embedded(code, base_opts, depth)
33 })
34 } else {
35 let mut custom_opts: Options = base_opts.clone();
36 custom_opts.markdown.width = width;
37 tidy::markdown::format_with(&prepared, &custom_opts.markdown, |code: Code<'_>| {
38 format_markdown_embedded(code, &custom_opts, depth)
39 })
40 };
41 normalize_markdown_prettier_quirks(formatted)
42}
43
44#[inline(always)]
55fn lowercase_embed_lang<'a>(lang: &str, buf: &'a mut [u8; 16]) -> Option<&'a str> {
56 let bytes: &[u8] = lang.as_bytes();
57 let len: usize = bytes.len();
58 if len == 0 || len > buf.len() {
59 return None;
60 }
61 for (dst, &src) in buf[..len].iter_mut().zip(bytes.iter()) {
62 *dst = src.to_ascii_lowercase();
63 }
64 from_utf8(&buf[..len]).ok()
65}
66
67#[inline(always)]
78fn is_supported_embed_lang(lang: &str, depth: usize) -> bool {
79 MD_EMBED_YAML.contains(&lang)
80 || lang == MD_EMBED_JSON
81 || lang == MD_EMBED_JSONC
82 || lang == MD_EMBED_JSON5
83 || MD_EMBED_JS.contains(&lang)
84 || MD_EMBED_TS.contains(&lang)
85 || lang == MD_EMBED_CSS
86 || lang == MD_EMBED_SCSS
87 || lang == MD_EMBED_LESS
88 || lang == MD_EMBED_HTML
89 || lang == MD_EMBED_VUE
90 || (MD_EMBED_MARKDOWN.contains(&lang) && depth < MD_MAX_EMBED_DEPTH)
91}
92
93fn format_markdown_embedded(code: Code<'_>, base_opts: &Options, depth: usize) -> Option<String> {
105 let mut lang_buf: [u8; 16] = [0u8; 16];
106 let lang: &str = lowercase_embed_lang(code.lang, &mut lang_buf)?;
107 if !is_supported_embed_lang(lang, depth) {
108 return None;
109 }
110 if MD_EMBED_MARKDOWN.contains(&lang) {
111 return Some(format_markdown_inner(code.text, code.width, depth + 1));
112 }
113 let mut sub_opts: Options = base_opts.clone();
114 sub_opts.share(&Shared {
115 width: Some(code.width),
116 ..Shared::default()
117 });
118 sub_opts.js.semi = true;
119 sub_opts.js.single_quote = true;
120 sub_opts.js.jsdoc = false;
121 sub_opts.yaml.single_quote = true;
122 if MD_EMBED_YAML.contains(&lang) {
123 return tidy::yaml::format(code.text, &sub_opts.yaml).ok();
124 }
125 if lang == MD_EMBED_JSON {
126 sub_opts.json.dialect = tidy::json::Dialect::Json;
127 return tidy::json::format(code.text, &sub_opts.json).ok();
128 }
129 if lang == MD_EMBED_JSONC {
130 sub_opts.json.dialect = tidy::json::Dialect::Jsonc;
131 return tidy::json::format(code.text, &sub_opts.json).ok();
132 }
133 if lang == MD_EMBED_JSON5 {
134 sub_opts.json.dialect = tidy::json::Dialect::Json5;
135 return tidy::json::format(code.text, &sub_opts.json).ok();
136 }
137 if MD_EMBED_JS.contains(&lang) {
138 let hint: &str = if lang == "cjs" {
139 MD_HINT_CJS
140 } else if lang == "jsx" {
141 MD_HINT_JSX
142 } else {
143 MD_HINT_JS
144 };
145 let mut embed: Verbatim = Verbatim;
146 return tidy::format(
147 code.text,
148 Language::Js(tidy::js::Dialect::Js),
149 &sub_opts,
150 Some(hint),
151 &mut embed,
152 )
153 .ok();
154 }
155 if MD_EMBED_TS.contains(&lang) {
156 let hint: &str = if lang == "cts" {
157 MD_HINT_CTS
158 } else if lang == "tsx" {
159 MD_HINT_TSX
160 } else {
161 MD_HINT_TS
162 };
163 let mut embed: Verbatim = Verbatim;
164 return tidy::format(
165 code.text,
166 Language::Js(tidy::js::Dialect::Ts),
167 &sub_opts,
168 Some(hint),
169 &mut embed,
170 )
171 .ok();
172 }
173 if lang == MD_EMBED_CSS {
174 return tidy::format(
175 code.text,
176 Language::Css(Dialect::Css),
177 &sub_opts,
178 None,
179 &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
180 )
181 .ok();
182 }
183 if lang == MD_EMBED_SCSS {
184 return tidy::format(
185 code.text,
186 Language::Css(Dialect::Scss),
187 &sub_opts,
188 None,
189 &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
190 )
191 .ok();
192 }
193 if lang == MD_EMBED_LESS {
194 return tidy::format(
195 code.text,
196 Language::Css(Dialect::Less),
197 &sub_opts,
198 None,
199 &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
200 )
201 .ok();
202 }
203 if lang == MD_EMBED_HTML {
204 return tidy::format(
205 code.text,
206 Language::Html,
207 &sub_opts,
208 None,
209 &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
210 )
211 .ok();
212 }
213 if lang == MD_EMBED_VUE {
214 return tidy::format(
215 code.text,
216 Language::Vue,
217 &sub_opts,
218 Some(MD_HINT_VUE),
219 &mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
220 )
221 .ok();
222 }
223 None
224}
225
226fn normalize_markdown_triple_emphasis_prepass(input: &str) -> Cow<'_, str> {
238 if !input.contains(MD_TRIPLE_STAR) && !input.contains(MD_TRIPLE_UNDER) {
239 return Cow::Borrowed(input);
240 }
241 let has_trailing_lf: bool = input.ends_with(TEXT_LF);
242 let body: &str = if has_trailing_lf {
243 &input[..input.len() - 1]
244 } else {
245 input
246 };
247 let mut out: Option<String> = None;
248 let mut line_start: usize = 0;
249 let mut active_fence: Option<(char, usize, usize)> = None;
250 let mut prev_bq_depth: usize = 0;
251 let mut list_indent_stack: Vec<usize> = Vec::new();
252 let mut prev_can_start_indented_code: bool = true;
253 let mut indented_code_threshold: Option<usize> = None;
254 let mut frontmatter_fence: Option<&str> = None;
255 let mut is_first_line: bool = true;
256 for line in body.split(TEXT_LF) {
257 let line_len: usize = line.len();
258 if is_first_line {
259 is_first_line = false;
260 let first_clean: &str = line.trim_end_matches(TEXT_CR);
261 if first_clean == MD_FRONTMATTER_YAML || first_clean == MD_FRONTMATTER_TOML {
262 let remaining: &str = body.get(line_len + 1..).unwrap_or("");
263 let has_close: bool = remaining
264 .split(TEXT_LF)
265 .any(|l: &str| l.trim_end_matches(TEXT_CR) == first_clean);
266 if has_close {
267 frontmatter_fence = Some(first_clean);
268 line_start += line_len + 1;
269 continue;
270 }
271 }
272 } else if let Some(fence) = frontmatter_fence {
273 if line.trim_end_matches(TEXT_CR) == fence {
274 frontmatter_fence = None;
275 }
276 line_start += line_len + 1;
277 continue;
278 }
279 let clean: &str = line.trim_end_matches(TEXT_CR);
280 let (bq_depth, _bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
281 strip_blockquote_and_measure_indent(clean);
282 let mut rewritten: Cow<'_, str> = Cow::Borrowed(line);
283 if let Some((fence_ch, fence_len, fence_base)) = active_fence {
284 if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
285 active_fence = None;
286 prev_can_start_indented_code = true;
287 }
288 } else {
289 if bq_depth != prev_bq_depth {
290 list_indent_stack.clear();
291 indented_code_threshold = None;
292 prev_can_start_indented_code = true;
293 prev_bq_depth = bq_depth;
294 }
295 let in_indented_code: bool =
296 indented_code_threshold.is_some_and(|threshold: usize| indent_cols >= threshold);
297 if stripped.is_empty() || in_indented_code {
298 prev_can_start_indented_code = true;
299 } else {
300 indented_code_threshold = None;
301 while list_indent_stack
302 .last()
303 .is_some_and(|&col: &usize| indent_cols < col)
304 {
305 list_indent_stack.pop();
306 }
307 let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
308 let rel_indent: usize = indent_cols.saturating_sub(base_indent);
309 if rel_indent >= 4 && prev_can_start_indented_code {
310 indented_code_threshold = Some(base_indent + 4);
311 prev_can_start_indented_code = true;
312 } else {
313 let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
314 && let Some((marker_cols, after)) = parse_list_marker(stripped)
315 {
316 let next_col: usize = indent_cols + marker_cols;
317 list_indent_stack.push(next_col);
318 (next_col, after)
319 } else {
320 (base_indent, stripped)
321 };
322 if rel_indent < 4
323 && let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
324 {
325 active_fence = Some((fence_ch, fence_len, fence_base));
326 prev_can_start_indented_code = false;
327 } else if rel_indent < 4 && is_thematic_break_line(stripped) {
328 prev_can_start_indented_code = true;
329 } else {
330 prev_can_start_indented_code =
331 rel_indent < 4 && is_atx_heading_or_dash_break(stripped);
332 if let Cow::Owned(mut changed) = rewrite_triple_emphasis_line(clean) {
333 if line.ends_with(TEXT_CR) {
334 changed.push(TEXT_CR);
335 }
336 rewritten = Cow::Owned(changed);
337 }
338 }
339 }
340 }
341 }
342 match (&mut out, rewritten) {
343 (Some(buf), line_cow) => {
344 buf.push(TEXT_LF);
345 buf.push_str(&line_cow);
346 }
347 (None, Cow::Owned(changed)) => {
348 let mut buf: String = String::with_capacity(input.len() + 16);
349 buf.push_str(&input[..line_start]);
350 buf.push_str(&changed);
351 out = Some(buf);
352 }
353 (None, Cow::Borrowed(_)) => {}
354 }
355 line_start += line_len + 1;
356 }
357 match out {
358 Some(mut buf) => {
359 if has_trailing_lf {
360 buf.push(TEXT_LF);
361 }
362 Cow::Owned(buf)
363 }
364 None => Cow::Borrowed(input),
365 }
366}
367
368#[inline(always)]
378fn is_thematic_break_line(stripped: &str) -> bool {
379 let mut marker: u8 = 0;
380 let mut count: usize = 0;
381 for &b in stripped.as_bytes() {
382 if b == b' ' || b == b'\t' {
383 continue;
384 }
385 if b != MD_BYTE_STAR && b != MD_BYTE_UNDER {
386 return false;
387 }
388 if marker == 0 {
389 marker = b;
390 } else if marker != b {
391 return false;
392 }
393 count += 1;
394 }
395 count >= 3
396}
397
398fn rewrite_triple_emphasis_line(line: &str) -> Cow<'_, str> {
408 if !line.contains(MD_TRIPLE_STAR) && !line.contains(MD_TRIPLE_UNDER) {
409 return Cow::Borrowed(line);
410 }
411 let bytes: &[u8] = line.as_bytes();
412 let len: usize = bytes.len();
413 let mut out: Option<String> = None;
414 let mut i: usize = 0;
415 while i < len {
416 if bytes[i] == b'\\' && i + 1 < len {
417 let next_len: usize = if bytes[i + 1] < 0x80 {
418 1
419 } else {
420 line[(i + 1)..]
421 .chars()
422 .next()
423 .map(char::len_utf8)
424 .unwrap_or(1)
425 };
426 if let Some(ref mut buf) = out {
427 buf.push_str(&line[i..(i + 1 + next_len)]);
428 }
429 i += 1 + next_len;
430 continue;
431 }
432 if bytes[i] == MD_BYTE_BACKTICK {
433 let end_code: usize = scan_inline_code_span(bytes, i);
434 if let Some(ref mut buf) = out {
435 buf.push_str(&line[i..end_code]);
436 }
437 i = end_code;
438 continue;
439 }
440 if bytes[i] == MD_BYTE_RBRACKET
441 && i + 1 < len
442 && bytes[i + 1] == MD_BYTE_LPAREN
443 && let Some(end_link) = scan_inline_link_tail(bytes, i + 2)
444 {
445 if let Some(ref mut buf) = out {
446 buf.push_str(&line[i..end_link]);
447 }
448 i = end_link;
449 continue;
450 }
451 if bytes[i] == MD_BYTE_LT
452 && let Some(end_angle) = scan_autolink_or_tag(bytes, i)
453 {
454 if let Some(ref mut buf) = out {
455 buf.push_str(&line[i..end_angle]);
456 }
457 i = end_angle;
458 continue;
459 }
460 if (bytes[i] == MD_BYTE_STAR || bytes[i] == MD_BYTE_UNDER)
461 && i + 2 < len
462 && bytes[i + 1] == bytes[i]
463 && bytes[i + 2] == bytes[i]
464 {
465 let delim: u8 = bytes[i];
466 let prev_not_delim: bool = i == 0 || bytes[i - 1] != delim;
467 let next_not_delim: bool = i + 3 < len && bytes[i + 3] != delim;
468 let next_not_ws: bool = i + 3 < len && !bytes[i + 3].is_ascii_whitespace();
469 let under_boundary_ok: bool = delim != MD_BYTE_UNDER
470 || i == 0
471 || !line[..i]
472 .chars()
473 .next_back()
474 .is_some_and(char::is_alphanumeric);
475 if prev_not_delim
476 && next_not_delim
477 && next_not_ws
478 && under_boundary_ok
479 && let Some(close_idx) = find_closing_triple_emphasis(line, i + 3, delim)
480 {
481 let buf: &mut String = out.get_or_insert_with(|| {
482 let mut s: String = String::with_capacity(len);
483 s.push_str(&line[..i]);
484 s
485 });
486 buf.push_str(MD_PRETTIER_BOLD_ITALIC_OPEN);
487 buf.push_str(&line[(i + 3)..close_idx]);
488 buf.push_str(MD_PRETTIER_BOLD_ITALIC_CLOSE);
489 i = close_idx + 3;
490 continue;
491 }
492 }
493 let ch_len: usize = if bytes[i] < 0x80 {
494 1
495 } else {
496 line[i..].chars().next().map(char::len_utf8).unwrap_or(1)
497 };
498 if let Some(ref mut buf) = out {
499 buf.push_str(&line[i..(i + ch_len)]);
500 }
501 i += ch_len;
502 }
503 match out {
504 Some(buf) => Cow::Owned(buf),
505 None => Cow::Borrowed(line),
506 }
507}
508
509fn scan_inline_link_tail(bytes: &[u8], start: usize) -> Option<usize> {
520 let len: usize = bytes.len();
521 let mut i: usize = start;
522 while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
523 i += 1;
524 }
525 let after_dest: usize = scan_link_destination(bytes, i)?;
526 let mut j: usize = after_dest;
527 while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
528 j += 1;
529 }
530 if j < len && bytes[j] == MD_BYTE_RPAREN {
531 return Some(j + 1);
532 }
533 if j > after_dest
534 && j < len
535 && (bytes[j] == MD_BYTE_DQUOTE || bytes[j] == MD_BYTE_SQUOTE || bytes[j] == MD_BYTE_LPAREN)
536 {
537 let close_delim: u8 = if bytes[j] == MD_BYTE_LPAREN {
538 MD_BYTE_RPAREN
539 } else {
540 bytes[j]
541 };
542 j += 1;
543 while j < len {
544 if bytes[j] == b'\\' && j + 1 < len {
545 j += 2;
546 continue;
547 }
548 if bytes[j] == close_delim {
549 j += 1;
550 break;
551 }
552 j += 1;
553 }
554 while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
555 j += 1;
556 }
557 if j < len && bytes[j] == MD_BYTE_RPAREN {
558 return Some(j + 1);
559 }
560 }
561 None
562}
563
564fn scan_autolink_or_tag(bytes: &[u8], start: usize) -> Option<usize> {
575 let len: usize = bytes.len();
576 if start + 2 >= len {
577 return None;
578 }
579 let next: u8 = bytes[start + 1];
580 if !next.is_ascii_alphabetic() && next != MD_BYTE_SLASH && next != MD_BYTE_BANG {
581 return None;
582 }
583 let mut i: usize = start + 2;
584 while i < len {
585 if bytes[i] == MD_BYTE_GT {
586 return Some(i + 1);
587 }
588 if bytes[i] == MD_BYTE_LT {
589 return None;
590 }
591 i += 1;
592 }
593 None
594}
595
596fn find_closing_triple_emphasis(line: &str, start: usize, delim: u8) -> Option<usize> {
608 let bytes: &[u8] = line.as_bytes();
609 let len: usize = bytes.len();
610 let mut i: usize = start;
611 while i + 2 < len {
612 if bytes[i] == b'\\' && i + 1 < len {
613 i += 2;
614 continue;
615 }
616 if bytes[i] == MD_BYTE_BACKTICK {
617 i = scan_inline_code_span(bytes, i);
618 continue;
619 }
620 if bytes[i] == delim && bytes[i + 1] == delim && bytes[i + 2] == delim {
621 let prev_ok: bool =
622 i > start && bytes[i - 1] != delim && !bytes[i - 1].is_ascii_whitespace();
623 let next_not_delim: bool = i + 3 >= len || bytes[i + 3] != delim;
624 let under_boundary_ok: bool = delim != MD_BYTE_UNDER
625 || i + 3 >= len
626 || !line[(i + 3)..]
627 .chars()
628 .next()
629 .is_some_and(char::is_alphanumeric);
630 if prev_ok && next_not_delim && under_boundary_ok {
631 return Some(i);
632 }
633 }
634 i += 1;
635 }
636 None
637}
638
639fn normalize_markdown_prettier_quirks(input: String) -> String {
651 if !input.contains('"') && !input.contains(MD_FENCE_BACKTICK) && !input.contains(MD_FENCE_TILDE)
652 {
653 return input;
654 }
655 let has_trailing_lf: bool = input.ends_with(TEXT_LF);
656 let body: &str = if has_trailing_lf {
657 &input[..input.len() - 1]
658 } else {
659 input.as_str()
660 };
661 let mut out: Option<String> = None;
662 let mut line_start: usize = 0;
663 let mut active_fence: Option<(char, usize, usize)> = None;
664 let mut fence_just_opened: bool = false;
665 let mut prev_bq_depth: usize = 0;
666 let mut list_indent_stack: Vec<usize> = Vec::new();
667 let mut prev_can_start_indented_code: bool = true;
668 let mut indented_code_threshold: Option<usize> = None;
669 let mut frontmatter_fence: Option<&str> = None;
670 let mut is_first_line: bool = true;
671 for line in body.split(TEXT_LF) {
672 let line_len: usize = line.len();
673 if is_first_line {
674 is_first_line = false;
675 if line == MD_FRONTMATTER_YAML || line == MD_FRONTMATTER_TOML {
676 let remaining: &str = body.get(line_len + 1..).unwrap_or("");
677 if remaining.split(TEXT_LF).any(|l: &str| l == line) {
678 frontmatter_fence = Some(line);
679 line_start += line_len + 1;
680 continue;
681 }
682 }
683 } else if let Some(fence) = frontmatter_fence {
684 if line == fence {
685 frontmatter_fence = None;
686 }
687 line_start += line_len + 1;
688 continue;
689 }
690 let (bq_depth, bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
691 strip_blockquote_and_measure_indent(line);
692 if let Some((fence_ch, fence_len, fence_base)) = active_fence {
693 let mut insert_blank: Option<&str> = None;
694 if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
695 if fence_just_opened {
696 insert_blank = Some(line[..bq_end].trim_end_matches([TEXT_SPACE, TEXT_TAB]));
697 }
698 active_fence = None;
699 fence_just_opened = false;
700 prev_can_start_indented_code = true;
701 } else {
702 fence_just_opened = false;
703 }
704 if let Some(blank_prefix) = insert_blank {
705 if let Some(ref mut buf) = out {
706 buf.push(TEXT_LF);
707 buf.push_str(blank_prefix);
708 buf.push(TEXT_LF);
709 buf.push_str(line);
710 } else {
711 let mut buf: String = String::with_capacity(input.len() + 16);
712 buf.push_str(&input[..line_start]);
713 buf.push_str(blank_prefix);
714 buf.push(TEXT_LF);
715 buf.push_str(line);
716 out = Some(buf);
717 }
718 } else if let Some(ref mut buf) = out {
719 buf.push(TEXT_LF);
720 buf.push_str(line);
721 }
722 line_start += line_len + 1;
723 continue;
724 }
725 if bq_depth != prev_bq_depth {
726 list_indent_stack.clear();
727 indented_code_threshold = None;
728 prev_can_start_indented_code = true;
729 prev_bq_depth = bq_depth;
730 }
731 let mut rewritten: Cow<'_, str> = Cow::Borrowed(line);
732 let in_indented_code: bool =
733 indented_code_threshold.is_some_and(|threshold: usize| indent_cols >= threshold);
734 if stripped.is_empty() || in_indented_code {
735 prev_can_start_indented_code = true;
736 } else {
737 indented_code_threshold = None;
738 while list_indent_stack
739 .last()
740 .is_some_and(|&col: &usize| indent_cols < col)
741 {
742 list_indent_stack.pop();
743 }
744 let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
745 let rel_indent: usize = indent_cols.saturating_sub(base_indent);
746 if rel_indent >= 4 && prev_can_start_indented_code {
747 indented_code_threshold = Some(base_indent + 4);
748 prev_can_start_indented_code = true;
749 } else {
750 let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
751 && let Some((marker_cols, after)) = parse_list_marker(stripped)
752 {
753 let next_col: usize = indent_cols + marker_cols;
754 list_indent_stack.push(next_col);
755 (next_col, after)
756 } else {
757 (base_indent, stripped)
758 };
759 if rel_indent < 4
760 && let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
761 {
762 active_fence = Some((fence_ch, fence_len, fence_base));
763 fence_just_opened = true;
764 prev_can_start_indented_code = false;
765 } else {
766 prev_can_start_indented_code = rel_indent < 4
767 && (is_thematic_break_line(stripped)
768 || is_atx_heading_or_dash_break(stripped));
769 if line.contains('"') {
770 let step_def: Cow<'_, str> = normalize_link_def_title(line, stripped);
771 match step_def {
772 Cow::Borrowed(s) => {
773 rewritten = normalize_inline_prettier_line(s);
774 }
775 Cow::Owned(s) => {
776 let final_line: String = match normalize_inline_prettier_line(&s) {
777 Cow::Borrowed(_) => s,
778 Cow::Owned(inline_changed) => inline_changed,
779 };
780 rewritten = Cow::Owned(final_line);
781 }
782 }
783 }
784 }
785 }
786 }
787 match (&mut out, rewritten) {
788 (Some(buf), line_cow) => {
789 buf.push(TEXT_LF);
790 buf.push_str(&line_cow);
791 }
792 (None, Cow::Owned(changed)) => {
793 let mut buf: String = String::with_capacity(input.len() + 16);
794 buf.push_str(&input[..line_start]);
795 buf.push_str(&changed);
796 out = Some(buf);
797 }
798 (None, Cow::Borrowed(_)) => {}
799 }
800 line_start += line_len + 1;
801 }
802 match out {
803 Some(mut buf) => {
804 if has_trailing_lf {
805 buf.push(TEXT_LF);
806 }
807 buf
808 }
809 None => input,
810 }
811}
812
813#[inline(always)]
823fn strip_blockquote_and_measure_indent(line: &str) -> (usize, usize, usize, &str) {
824 let bytes: &[u8] = line.as_bytes();
825 let len: usize = bytes.len();
826 let mut idx: usize = 0;
827 let mut bq_depth: usize = 0;
828 let mut bq_end: usize = 0;
829 loop {
830 let mut scan: usize = idx;
831 let mut ws_cols: usize = 0;
832 while scan < len {
833 if bytes[scan] == b' ' {
834 ws_cols += 1;
835 scan += 1;
836 } else if bytes[scan] == b'\t' {
837 ws_cols += 4 - (ws_cols % 4);
838 scan += 1;
839 } else {
840 break;
841 }
842 }
843 if ws_cols < 4 && scan < len && bytes[scan] == MD_BYTE_GT {
844 bq_depth += 1;
845 scan += 1;
846 bq_end = scan;
847 if scan < len && bytes[scan] == b' ' {
848 scan += 1;
849 }
850 idx = scan;
851 continue;
852 }
853 return (bq_depth, bq_end, ws_cols, &line[scan..]);
854 }
855}
856
857#[inline(always)]
867fn parse_list_marker(stripped: &str) -> Option<(usize, &str)> {
868 let bytes: &[u8] = stripped.as_bytes();
869 let len: usize = bytes.len();
870 if len == 0 {
871 return None;
872 }
873 let marker_len: usize =
874 if bytes[0] == MD_BYTE_DASH || bytes[0] == MD_BYTE_STAR || bytes[0] == MD_BYTE_PLUS {
875 1
876 } else if bytes[0].is_ascii_digit() {
877 let digits: usize = bytes
878 .iter()
879 .take(9)
880 .take_while(|&&b: &&u8| b.is_ascii_digit())
881 .count();
882 if digits == 0
883 || digits >= len
884 || (bytes[digits] != MD_BYTE_DOT && bytes[digits] != MD_BYTE_RPAREN)
885 {
886 return None;
887 }
888 digits + 1
889 } else {
890 return None;
891 };
892 if marker_len == len {
893 return Some((marker_len + 1, ""));
894 }
895 if bytes[marker_len] != b' ' && bytes[marker_len] != b'\t' {
896 return None;
897 }
898 let mut scan: usize = marker_len;
899 let mut ws_cols: usize = 0;
900 while scan < len {
901 if bytes[scan] == b' ' {
902 ws_cols += 1;
903 scan += 1;
904 } else if bytes[scan] == b'\t' {
905 ws_cols += 4 - ((marker_len + ws_cols) % 4);
906 scan += 1;
907 } else {
908 break;
909 }
910 }
911 if scan == len || ws_cols >= 5 {
912 return Some((marker_len + 1, ""));
913 }
914 Some((marker_len + ws_cols, &stripped[scan..]))
915}
916
917#[inline(always)]
927fn is_atx_heading_or_dash_break(stripped: &str) -> bool {
928 let bytes: &[u8] = stripped.as_bytes();
929 if bytes.is_empty() {
930 return false;
931 }
932 if bytes[0] == MD_BYTE_HASH {
933 let hashes: usize = bytes
934 .iter()
935 .take_while(|&&b: &&u8| b == MD_BYTE_HASH)
936 .count();
937 if (1..=6).contains(&hashes) {
938 return hashes == bytes.len() || bytes[hashes] == b' ' || bytes[hashes] == b'\t';
939 }
940 return false;
941 }
942 if bytes[0] != MD_BYTE_DASH {
943 return false;
944 }
945 let mut dashes: usize = 0;
946 for &b in bytes {
947 if b == b' ' || b == b'\t' {
948 continue;
949 }
950 if b != MD_BYTE_DASH {
951 return false;
952 }
953 dashes += 1;
954 }
955 dashes >= 3
956}
957
958#[inline(always)]
968fn parse_opening_fence(stripped: &str) -> Option<(char, usize)> {
969 let bytes: &[u8] = stripped.as_bytes();
970 let first: u8 = *bytes.first()?;
971 if first != MD_BYTE_BACKTICK && first != MD_BYTE_TILDE {
972 return None;
973 }
974 let len: usize = bytes.iter().take_while(|&&b: &&u8| b == first).count();
975 if len < 3 {
976 return None;
977 }
978 if first == MD_BYTE_BACKTICK && bytes[len..].contains(&MD_BYTE_BACKTICK) {
979 return None;
980 }
981 Some((first as char, len))
982}
983
984#[inline(always)]
996fn is_closing_fence(stripped: &str, fence_ch: char, fence_len: usize) -> bool {
997 let trimmed: &[u8] = stripped.trim_end_matches([TEXT_SPACE, TEXT_TAB]).as_bytes();
998 let target: u8 = fence_ch as u8;
999 let count: usize = trimmed.iter().take_while(|&&b: &&u8| b == target).count();
1000 count >= fence_len && count == trimmed.len()
1001}
1002
1003fn normalize_link_def_title<'a>(line: &'a str, trimmed: &str) -> Cow<'a, str> {
1014 if !trimmed.starts_with('[') || trimmed.starts_with("[^") {
1015 return Cow::Borrowed(line);
1016 }
1017 let prefix_len: usize = line.len() - trimmed.len();
1018 let bytes: &[u8] = trimmed.as_bytes();
1019 let len: usize = bytes.len();
1020 let mut i: usize = 1;
1021 while i < len {
1022 if bytes[i] == b'\\' && i + 1 < len {
1023 i += 2;
1024 continue;
1025 }
1026 if bytes[i] == MD_BYTE_RBRACKET {
1027 break;
1028 }
1029 i += 1;
1030 }
1031 if i + 1 >= len || bytes[i] != MD_BYTE_RBRACKET || bytes[i + 1] != MD_BYTE_COLON {
1032 return Cow::Borrowed(line);
1033 }
1034 i += 2;
1035 while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
1036 i += 1;
1037 }
1038 let Some(after_dest) = scan_link_destination(bytes, i) else {
1039 return Cow::Borrowed(line);
1040 };
1041 let mut ws: usize = after_dest;
1042 while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
1043 ws += 1;
1044 }
1045 if ws == after_dest || ws >= len || bytes[ws] != MD_BYTE_DQUOTE {
1046 return Cow::Borrowed(line);
1047 }
1048 let Some(close_quote) = scan_double_quoted_title(bytes, ws) else {
1049 return Cow::Borrowed(line);
1050 };
1051 if !trimmed[(close_quote + 1)..]
1052 .trim_matches([TEXT_SPACE, TEXT_TAB])
1053 .is_empty()
1054 {
1055 return Cow::Borrowed(line);
1056 }
1057 let inner: &str = &trimmed[(ws + 1)..close_quote];
1058 let Some((open_ch, converted, close_ch)) = convert_double_title_to_prettier(inner) else {
1059 return Cow::Borrowed(line);
1060 };
1061 let mut out: String = String::with_capacity(line.len());
1062 out.push_str(&line[..(prefix_len + ws)]);
1063 out.push(open_ch);
1064 out.push_str(&converted);
1065 out.push(close_ch);
1066 out.push_str(&trimmed[(close_quote + 1)..]);
1067 Cow::Owned(out)
1068}
1069
1070fn normalize_inline_prettier_line(line: &str) -> Cow<'_, str> {
1080 if !line.contains("](") || !line.contains('"') {
1081 return Cow::Borrowed(line);
1082 }
1083 let bytes: &[u8] = line.as_bytes();
1084 let len: usize = bytes.len();
1085 let mut out: Option<String> = None;
1086 let mut i: usize = 0;
1087 while i < len {
1088 if bytes[i] == b'\\' && i + 1 < len {
1089 let next_len: usize = if bytes[i + 1] < 0x80 {
1090 1
1091 } else {
1092 line[(i + 1)..]
1093 .chars()
1094 .next()
1095 .map(char::len_utf8)
1096 .unwrap_or(1)
1097 };
1098 if let Some(ref mut buf) = out {
1099 buf.push_str(&line[i..(i + 1 + next_len)]);
1100 }
1101 i += 1 + next_len;
1102 continue;
1103 }
1104 if bytes[i] == MD_BYTE_BACKTICK {
1105 let end_code: usize = scan_inline_code_span(bytes, i);
1106 if let Some(ref mut buf) = out {
1107 buf.push_str(&line[i..end_code]);
1108 }
1109 i = end_code;
1110 continue;
1111 }
1112 if bytes[i] == MD_BYTE_RBRACKET
1113 && i + 1 < len
1114 && bytes[i + 1] == MD_BYTE_LPAREN
1115 && let Some((replacement, next_i)) = try_rewrite_inline_link_title(line, i)
1116 {
1117 let buf: &mut String = out.get_or_insert_with(|| {
1118 let mut s: String = String::with_capacity(len);
1119 s.push_str(&line[..i]);
1120 s
1121 });
1122 buf.push_str(&replacement);
1123 i = next_i;
1124 continue;
1125 }
1126 let ch_len: usize = if bytes[i] < 0x80 {
1127 1
1128 } else {
1129 line[i..].chars().next().map(char::len_utf8).unwrap_or(1)
1130 };
1131 if let Some(ref mut buf) = out {
1132 buf.push_str(&line[i..(i + ch_len)]);
1133 }
1134 i += ch_len;
1135 }
1136 match out {
1137 Some(buf) => Cow::Owned(buf),
1138 None => Cow::Borrowed(line),
1139 }
1140}
1141
1142fn scan_inline_code_span(bytes: &[u8], start: usize) -> usize {
1153 let len: usize = bytes.len();
1154 let ticks: usize = bytes[start..]
1155 .iter()
1156 .take_while(|&&b: &&u8| b == MD_BYTE_BACKTICK)
1157 .count();
1158 let mut i: usize = start + ticks;
1159 while i < len {
1160 if bytes[i] == MD_BYTE_BACKTICK {
1161 let run: usize = bytes[i..]
1162 .iter()
1163 .take_while(|&&b: &&u8| b == MD_BYTE_BACKTICK)
1164 .count();
1165 if run == ticks {
1166 return i + run;
1167 }
1168 i += run;
1169 continue;
1170 }
1171 i += 1;
1172 }
1173 start + ticks
1174}
1175
1176fn try_rewrite_inline_link_title(line: &str, bracket_idx: usize) -> Option<(String, usize)> {
1187 let bytes: &[u8] = line.as_bytes();
1188 let len: usize = bytes.len();
1189 let mut i: usize = bracket_idx + 2;
1190 while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
1191 i += 1;
1192 }
1193 let after_dest: usize = scan_link_destination(bytes, i)?;
1194 let mut ws: usize = after_dest;
1195 while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
1196 ws += 1;
1197 }
1198 if ws == after_dest || ws >= len || bytes[ws] != MD_BYTE_DQUOTE {
1199 return None;
1200 }
1201 let close_quote: usize = scan_double_quoted_title(bytes, ws)?;
1202 let mut tail: usize = close_quote + 1;
1203 while tail < len && (bytes[tail] == b' ' || bytes[tail] == b'\t') {
1204 tail += 1;
1205 }
1206 if tail >= len || bytes[tail] != MD_BYTE_RPAREN {
1207 return None;
1208 }
1209 let inner: &str = &line[(ws + 1)..close_quote];
1210 let (open_ch, converted, close_ch): (char, String, char) =
1211 convert_double_title_to_prettier(inner)?;
1212 let mut out: String = String::with_capacity(tail + 1 - bracket_idx);
1213 out.push_str(&line[bracket_idx..ws]);
1214 out.push(open_ch);
1215 out.push_str(&converted);
1216 out.push(close_ch);
1217 out.push_str(&line[(close_quote + 1)..=tail]);
1218 Some((out, tail + 1))
1219}
1220
1221fn scan_link_destination(bytes: &[u8], start: usize) -> Option<usize> {
1232 let len: usize = bytes.len();
1233 if start >= len {
1234 return None;
1235 }
1236 if bytes[start] == MD_BYTE_LT {
1237 let mut i: usize = start + 1;
1238 while i < len {
1239 if bytes[i] == b'\\' && i + 1 < len {
1240 i += 2;
1241 continue;
1242 }
1243 if bytes[i] == MD_BYTE_GT {
1244 return Some(i + 1);
1245 }
1246 if bytes[i] == MD_BYTE_LT {
1247 return None;
1248 }
1249 i += 1;
1250 }
1251 return None;
1252 }
1253 let mut i: usize = start;
1254 let mut paren_depth: usize = 0;
1255 while i < len {
1256 let b: u8 = bytes[i];
1257 if b == b'\\' && i + 1 < len {
1258 i += 2;
1259 continue;
1260 }
1261 if b == b' ' || b == b'\t' {
1262 break;
1263 }
1264 if b == MD_BYTE_LPAREN {
1265 paren_depth += 1;
1266 } else if b == MD_BYTE_RPAREN {
1267 if paren_depth == 0 {
1268 break;
1269 }
1270 paren_depth -= 1;
1271 }
1272 i += 1;
1273 }
1274 if i == start || paren_depth != 0 {
1275 return None;
1276 }
1277 Some(i)
1278}
1279
1280fn scan_double_quoted_title(bytes: &[u8], open_quote: usize) -> Option<usize> {
1291 let len: usize = bytes.len();
1292 let mut i: usize = open_quote + 1;
1293 while i < len {
1294 if bytes[i] == b'\\' && i + 1 < len {
1295 i += 2;
1296 continue;
1297 }
1298 if bytes[i] == MD_BYTE_DQUOTE {
1299 return Some(i);
1300 }
1301 i += 1;
1302 }
1303 None
1304}
1305
1306fn convert_double_title_to_prettier(inner: &str) -> Option<(char, String, char)> {
1318 let has_single: bool = inner.contains('\'');
1319 let has_escaped_double: bool = inner.contains('"');
1320 let (open_ch, close_ch): (char, char) = if !has_single {
1321 ('\'', '\'')
1322 } else if has_escaped_double && !inner.contains('(') && !inner.contains(')') {
1323 ('(', ')')
1324 } else {
1325 return None;
1326 };
1327 let bytes: &[u8] = inner.as_bytes();
1328 let len: usize = bytes.len();
1329 let mut out: String = String::with_capacity(len);
1330 let mut i: usize = 0;
1331 while i < len {
1332 if bytes[i] == b'\\' && i + 1 < len {
1333 if bytes[i + 1] == MD_BYTE_DQUOTE {
1334 out.push('"');
1335 } else {
1336 out.push('\\');
1337 let next_len: usize = if bytes[i + 1] < 0x80 {
1338 1
1339 } else {
1340 inner[(i + 1)..]
1341 .chars()
1342 .next()
1343 .map(char::len_utf8)
1344 .unwrap_or(1)
1345 };
1346 out.push_str(&inner[(i + 1)..(i + 1 + next_len)]);
1347 i += 1 + next_len;
1348 continue;
1349 }
1350 i += 2;
1351 continue;
1352 }
1353 let ch_len: usize = if bytes[i] < 0x80 {
1354 1
1355 } else {
1356 inner[i..].chars().next().map(char::len_utf8).unwrap_or(1)
1357 };
1358 out.push_str(&inner[i..(i + ch_len)]);
1359 i += ch_len;
1360 }
1361 Some((open_ch, out, close_ch))
1362}