use super::*;
pub fn format_markdown(input: &str) -> String {
format_markdown_inner(input, PRETTIER_PRINT_WIDTH, 0)
}
fn format_markdown_inner(input: &str, width: usize, depth: usize) -> String {
let base_opts: &'static Options = vscode_tidy_options_ref();
let prepared: Cow<'_, str> = normalize_markdown_triple_emphasis_prepass(input);
let formatted: String = if width == PRETTIER_PRINT_WIDTH {
tidy::markdown::format_with(&prepared, &base_opts.markdown, |code: Code<'_>| {
format_markdown_embedded(code, base_opts, depth)
})
} else {
let mut custom_opts: Options = base_opts.clone();
custom_opts.markdown.width = width;
tidy::markdown::format_with(&prepared, &custom_opts.markdown, |code: Code<'_>| {
format_markdown_embedded(code, &custom_opts, depth)
})
};
normalize_markdown_prettier_quirks(formatted)
}
#[inline(always)]
fn lowercase_embed_lang<'a>(lang: &str, buf: &'a mut [u8; 16]) -> Option<&'a str> {
let bytes: &[u8] = lang.as_bytes();
let len: usize = bytes.len();
if len == 0 || len > buf.len() {
return None;
}
for (dst, &src) in buf[..len].iter_mut().zip(bytes.iter()) {
*dst = src.to_ascii_lowercase();
}
from_utf8(&buf[..len]).ok()
}
#[inline(always)]
fn is_supported_embed_lang(lang: &str, depth: usize) -> bool {
MD_EMBED_YAML.contains(&lang)
|| lang == MD_EMBED_JSON
|| lang == MD_EMBED_JSONC
|| lang == MD_EMBED_JSON5
|| MD_EMBED_JS.contains(&lang)
|| MD_EMBED_TS.contains(&lang)
|| lang == MD_EMBED_CSS
|| lang == MD_EMBED_SCSS
|| lang == MD_EMBED_LESS
|| lang == MD_EMBED_HTML
|| lang == MD_EMBED_VUE
|| (MD_EMBED_MARKDOWN.contains(&lang) && depth < MD_MAX_EMBED_DEPTH)
}
fn format_markdown_embedded(code: Code<'_>, base_opts: &Options, depth: usize) -> Option<String> {
let mut lang_buf: [u8; 16] = [0u8; 16];
let lang: &str = lowercase_embed_lang(code.lang, &mut lang_buf)?;
if !is_supported_embed_lang(lang, depth) {
return None;
}
if MD_EMBED_MARKDOWN.contains(&lang) {
return Some(format_markdown_inner(code.text, code.width, depth + 1));
}
let mut sub_opts: Options = base_opts.clone();
sub_opts.share(&Shared {
width: Some(code.width),
..Shared::default()
});
sub_opts.js.semi = true;
sub_opts.js.single_quote = true;
sub_opts.js.jsdoc = false;
sub_opts.yaml.single_quote = true;
if MD_EMBED_YAML.contains(&lang) {
return tidy::yaml::format(code.text, &sub_opts.yaml).ok();
}
if lang == MD_EMBED_JSON {
sub_opts.json.dialect = tidy::json::Dialect::Json;
return tidy::json::format(code.text, &sub_opts.json).ok();
}
if lang == MD_EMBED_JSONC {
sub_opts.json.dialect = tidy::json::Dialect::Jsonc;
return tidy::json::format(code.text, &sub_opts.json).ok();
}
if lang == MD_EMBED_JSON5 {
sub_opts.json.dialect = tidy::json::Dialect::Json5;
return tidy::json::format(code.text, &sub_opts.json).ok();
}
if MD_EMBED_JS.contains(&lang) {
let hint: &str = if lang == "cjs" {
MD_HINT_CJS
} else if lang == "jsx" {
MD_HINT_JSX
} else {
MD_HINT_JS
};
let mut embed: Verbatim = Verbatim;
return tidy::format(
code.text,
Language::Js(tidy::js::Dialect::Js),
&sub_opts,
Some(hint),
&mut embed,
)
.ok();
}
if MD_EMBED_TS.contains(&lang) {
let hint: &str = if lang == "cts" {
MD_HINT_CTS
} else if lang == "tsx" {
MD_HINT_TSX
} else {
MD_HINT_TS
};
let mut embed: Verbatim = Verbatim;
return tidy::format(
code.text,
Language::Js(tidy::js::Dialect::Ts),
&sub_opts,
Some(hint),
&mut embed,
)
.ok();
}
if lang == MD_EMBED_CSS {
return tidy::format(
code.text,
Language::Css(Dialect::Css),
&sub_opts,
None,
&mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
)
.ok();
}
if lang == MD_EMBED_SCSS {
return tidy::format(
code.text,
Language::Css(Dialect::Scss),
&sub_opts,
None,
&mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
)
.ok();
}
if lang == MD_EMBED_LESS {
return tidy::format(
code.text,
Language::Css(Dialect::Less),
&sub_opts,
None,
&mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
)
.ok();
}
if lang == MD_EMBED_HTML {
return tidy::format(
code.text,
Language::Html,
&sub_opts,
None,
&mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
)
.ok();
}
if lang == MD_EMBED_VUE {
return tidy::format(
code.text,
Language::Vue,
&sub_opts,
Some(MD_HINT_VUE),
&mut |req: Request<'_>| format_markup_embedded(req, &sub_opts),
)
.ok();
}
None
}
fn normalize_markdown_triple_emphasis_prepass(input: &str) -> Cow<'_, str> {
if !input.contains(MD_TRIPLE_STAR) && !input.contains(MD_TRIPLE_UNDER) {
return Cow::Borrowed(input);
}
let has_trailing_lf: bool = input.ends_with(TEXT_LF);
let body: &str = if has_trailing_lf {
&input[..input.len() - 1]
} else {
input
};
let mut out: Option<String> = None;
let mut line_start: usize = 0;
let mut active_fence: Option<(char, usize, usize)> = None;
let mut prev_bq_depth: usize = 0;
let mut list_indent_stack: Vec<usize> = Vec::new();
let mut prev_can_start_indented_code: bool = true;
let mut indented_code_threshold: Option<usize> = None;
let mut frontmatter_fence: Option<&str> = None;
let mut is_first_line: bool = true;
for line in body.split(TEXT_LF) {
let line_len: usize = line.len();
if is_first_line {
is_first_line = false;
let first_clean: &str = line.trim_end_matches(TEXT_CR);
if first_clean == MD_FRONTMATTER_YAML || first_clean == MD_FRONTMATTER_TOML {
let remaining: &str = body.get(line_len + 1..).unwrap_or("");
let has_close: bool = remaining
.split(TEXT_LF)
.any(|l: &str| l.trim_end_matches(TEXT_CR) == first_clean);
if has_close {
frontmatter_fence = Some(first_clean);
line_start += line_len + 1;
continue;
}
}
} else if let Some(fence) = frontmatter_fence {
if line.trim_end_matches(TEXT_CR) == fence {
frontmatter_fence = None;
}
line_start += line_len + 1;
continue;
}
let clean: &str = line.trim_end_matches(TEXT_CR);
let (bq_depth, _bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
strip_blockquote_and_measure_indent(clean);
let mut rewritten: Cow<'_, str> = Cow::Borrowed(line);
if let Some((fence_ch, fence_len, fence_base)) = active_fence {
if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
active_fence = None;
prev_can_start_indented_code = true;
}
} else {
if bq_depth != prev_bq_depth {
list_indent_stack.clear();
indented_code_threshold = None;
prev_can_start_indented_code = true;
prev_bq_depth = bq_depth;
}
let in_indented_code: bool =
indented_code_threshold.is_some_and(|threshold: usize| indent_cols >= threshold);
if stripped.is_empty() || in_indented_code {
prev_can_start_indented_code = true;
} else {
indented_code_threshold = None;
while list_indent_stack
.last()
.is_some_and(|&col: &usize| indent_cols < col)
{
list_indent_stack.pop();
}
let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
let rel_indent: usize = indent_cols.saturating_sub(base_indent);
if rel_indent >= 4 && prev_can_start_indented_code {
indented_code_threshold = Some(base_indent + 4);
prev_can_start_indented_code = true;
} else {
let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
&& let Some((marker_cols, after)) = parse_list_marker(stripped)
{
let next_col: usize = indent_cols + marker_cols;
list_indent_stack.push(next_col);
(next_col, after)
} else {
(base_indent, stripped)
};
if rel_indent < 4
&& let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
{
active_fence = Some((fence_ch, fence_len, fence_base));
prev_can_start_indented_code = false;
} else if rel_indent < 4 && is_thematic_break_line(stripped) {
prev_can_start_indented_code = true;
} else {
prev_can_start_indented_code =
rel_indent < 4 && is_atx_heading_or_dash_break(stripped);
if let Cow::Owned(mut changed) = rewrite_triple_emphasis_line(clean) {
if line.ends_with(TEXT_CR) {
changed.push(TEXT_CR);
}
rewritten = Cow::Owned(changed);
}
}
}
}
}
match (&mut out, rewritten) {
(Some(buf), line_cow) => {
buf.push(TEXT_LF);
buf.push_str(&line_cow);
}
(None, Cow::Owned(changed)) => {
let mut buf: String = String::with_capacity(input.len() + 16);
buf.push_str(&input[..line_start]);
buf.push_str(&changed);
out = Some(buf);
}
(None, Cow::Borrowed(_)) => {}
}
line_start += line_len + 1;
}
match out {
Some(mut buf) => {
if has_trailing_lf {
buf.push(TEXT_LF);
}
Cow::Owned(buf)
}
None => Cow::Borrowed(input),
}
}
#[inline(always)]
fn is_thematic_break_line(stripped: &str) -> bool {
let mut marker: u8 = 0;
let mut count: usize = 0;
for &b in stripped.as_bytes() {
if b == b' ' || b == b'\t' {
continue;
}
if b != MD_BYTE_STAR && b != MD_BYTE_UNDER {
return false;
}
if marker == 0 {
marker = b;
} else if marker != b {
return false;
}
count += 1;
}
count >= 3
}
fn rewrite_triple_emphasis_line(line: &str) -> Cow<'_, str> {
if !line.contains(MD_TRIPLE_STAR) && !line.contains(MD_TRIPLE_UNDER) {
return Cow::Borrowed(line);
}
let bytes: &[u8] = line.as_bytes();
let len: usize = bytes.len();
let mut out: Option<String> = None;
let mut i: usize = 0;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
let next_len: usize = if bytes[i + 1] < 0x80 {
1
} else {
line[(i + 1)..]
.chars()
.next()
.map(char::len_utf8)
.unwrap_or(1)
};
if let Some(ref mut buf) = out {
buf.push_str(&line[i..(i + 1 + next_len)]);
}
i += 1 + next_len;
continue;
}
if bytes[i] == MD_BYTE_BACKTICK {
let end_code: usize = scan_inline_code_span(bytes, i);
if let Some(ref mut buf) = out {
buf.push_str(&line[i..end_code]);
}
i = end_code;
continue;
}
if bytes[i] == MD_BYTE_RBRACKET
&& i + 1 < len
&& bytes[i + 1] == MD_BYTE_LPAREN
&& let Some(end_link) = scan_inline_link_tail(bytes, i + 2)
{
if let Some(ref mut buf) = out {
buf.push_str(&line[i..end_link]);
}
i = end_link;
continue;
}
if bytes[i] == MD_BYTE_LT
&& let Some(end_angle) = scan_autolink_or_tag(bytes, i)
{
if let Some(ref mut buf) = out {
buf.push_str(&line[i..end_angle]);
}
i = end_angle;
continue;
}
if (bytes[i] == MD_BYTE_STAR || bytes[i] == MD_BYTE_UNDER)
&& i + 2 < len
&& bytes[i + 1] == bytes[i]
&& bytes[i + 2] == bytes[i]
{
let delim: u8 = bytes[i];
let prev_not_delim: bool = i == 0 || bytes[i - 1] != delim;
let next_not_delim: bool = i + 3 < len && bytes[i + 3] != delim;
let next_not_ws: bool = i + 3 < len && !bytes[i + 3].is_ascii_whitespace();
let under_boundary_ok: bool = delim != MD_BYTE_UNDER
|| i == 0
|| !line[..i]
.chars()
.next_back()
.is_some_and(char::is_alphanumeric);
if prev_not_delim
&& next_not_delim
&& next_not_ws
&& under_boundary_ok
&& let Some(close_idx) = find_closing_triple_emphasis(line, i + 3, delim)
{
let buf: &mut String = out.get_or_insert_with(|| {
let mut s: String = String::with_capacity(len);
s.push_str(&line[..i]);
s
});
buf.push_str(MD_PRETTIER_BOLD_ITALIC_OPEN);
buf.push_str(&line[(i + 3)..close_idx]);
buf.push_str(MD_PRETTIER_BOLD_ITALIC_CLOSE);
i = close_idx + 3;
continue;
}
}
let ch_len: usize = if bytes[i] < 0x80 {
1
} else {
line[i..].chars().next().map(char::len_utf8).unwrap_or(1)
};
if let Some(ref mut buf) = out {
buf.push_str(&line[i..(i + ch_len)]);
}
i += ch_len;
}
match out {
Some(buf) => Cow::Owned(buf),
None => Cow::Borrowed(line),
}
}
fn scan_inline_link_tail(bytes: &[u8], start: usize) -> Option<usize> {
let len: usize = bytes.len();
let mut i: usize = start;
while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
i += 1;
}
let after_dest: usize = scan_link_destination(bytes, i)?;
let mut j: usize = after_dest;
while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
j += 1;
}
if j < len && bytes[j] == MD_BYTE_RPAREN {
return Some(j + 1);
}
if j > after_dest
&& j < len
&& (bytes[j] == MD_BYTE_DQUOTE || bytes[j] == MD_BYTE_SQUOTE || bytes[j] == MD_BYTE_LPAREN)
{
let close_delim: u8 = if bytes[j] == MD_BYTE_LPAREN {
MD_BYTE_RPAREN
} else {
bytes[j]
};
j += 1;
while j < len {
if bytes[j] == b'\\' && j + 1 < len {
j += 2;
continue;
}
if bytes[j] == close_delim {
j += 1;
break;
}
j += 1;
}
while j < len && (bytes[j] == b' ' || bytes[j] == b'\t') {
j += 1;
}
if j < len && bytes[j] == MD_BYTE_RPAREN {
return Some(j + 1);
}
}
None
}
fn scan_autolink_or_tag(bytes: &[u8], start: usize) -> Option<usize> {
let len: usize = bytes.len();
if start + 2 >= len {
return None;
}
let next: u8 = bytes[start + 1];
if !next.is_ascii_alphabetic() && next != MD_BYTE_SLASH && next != MD_BYTE_BANG {
return None;
}
let mut i: usize = start + 2;
while i < len {
if bytes[i] == MD_BYTE_GT {
return Some(i + 1);
}
if bytes[i] == MD_BYTE_LT {
return None;
}
i += 1;
}
None
}
fn find_closing_triple_emphasis(line: &str, start: usize, delim: u8) -> Option<usize> {
let bytes: &[u8] = line.as_bytes();
let len: usize = bytes.len();
let mut i: usize = start;
while i + 2 < len {
if bytes[i] == b'\\' && i + 1 < len {
i += 2;
continue;
}
if bytes[i] == MD_BYTE_BACKTICK {
i = scan_inline_code_span(bytes, i);
continue;
}
if bytes[i] == delim && bytes[i + 1] == delim && bytes[i + 2] == delim {
let prev_ok: bool =
i > start && bytes[i - 1] != delim && !bytes[i - 1].is_ascii_whitespace();
let next_not_delim: bool = i + 3 >= len || bytes[i + 3] != delim;
let under_boundary_ok: bool = delim != MD_BYTE_UNDER
|| i + 3 >= len
|| !line[(i + 3)..]
.chars()
.next()
.is_some_and(char::is_alphanumeric);
if prev_ok && next_not_delim && under_boundary_ok {
return Some(i);
}
}
i += 1;
}
None
}
fn normalize_markdown_prettier_quirks(input: String) -> String {
if !input.contains('"') && !input.contains(MD_FENCE_BACKTICK) && !input.contains(MD_FENCE_TILDE)
{
return input;
}
let has_trailing_lf: bool = input.ends_with(TEXT_LF);
let body: &str = if has_trailing_lf {
&input[..input.len() - 1]
} else {
input.as_str()
};
let mut out: Option<String> = None;
let mut line_start: usize = 0;
let mut active_fence: Option<(char, usize, usize)> = None;
let mut fence_just_opened: bool = false;
let mut prev_bq_depth: usize = 0;
let mut list_indent_stack: Vec<usize> = Vec::new();
let mut prev_can_start_indented_code: bool = true;
let mut indented_code_threshold: Option<usize> = None;
let mut frontmatter_fence: Option<&str> = None;
let mut is_first_line: bool = true;
for line in body.split(TEXT_LF) {
let line_len: usize = line.len();
if is_first_line {
is_first_line = false;
if line == MD_FRONTMATTER_YAML || line == MD_FRONTMATTER_TOML {
let remaining: &str = body.get(line_len + 1..).unwrap_or("");
if remaining.split(TEXT_LF).any(|l: &str| l == line) {
frontmatter_fence = Some(line);
line_start += line_len + 1;
continue;
}
}
} else if let Some(fence) = frontmatter_fence {
if line == fence {
frontmatter_fence = None;
}
line_start += line_len + 1;
continue;
}
let (bq_depth, bq_end, indent_cols, stripped): (usize, usize, usize, &str) =
strip_blockquote_and_measure_indent(line);
if let Some((fence_ch, fence_len, fence_base)) = active_fence {
let mut insert_blank: Option<&str> = None;
if indent_cols < fence_base + 4 && is_closing_fence(stripped, fence_ch, fence_len) {
if fence_just_opened {
insert_blank = Some(line[..bq_end].trim_end_matches([TEXT_SPACE, TEXT_TAB]));
}
active_fence = None;
fence_just_opened = false;
prev_can_start_indented_code = true;
} else {
fence_just_opened = false;
}
if let Some(blank_prefix) = insert_blank {
if let Some(ref mut buf) = out {
buf.push(TEXT_LF);
buf.push_str(blank_prefix);
buf.push(TEXT_LF);
buf.push_str(line);
} else {
let mut buf: String = String::with_capacity(input.len() + 16);
buf.push_str(&input[..line_start]);
buf.push_str(blank_prefix);
buf.push(TEXT_LF);
buf.push_str(line);
out = Some(buf);
}
} else if let Some(ref mut buf) = out {
buf.push(TEXT_LF);
buf.push_str(line);
}
line_start += line_len + 1;
continue;
}
if bq_depth != prev_bq_depth {
list_indent_stack.clear();
indented_code_threshold = None;
prev_can_start_indented_code = true;
prev_bq_depth = bq_depth;
}
let mut rewritten: Cow<'_, str> = Cow::Borrowed(line);
let in_indented_code: bool =
indented_code_threshold.is_some_and(|threshold: usize| indent_cols >= threshold);
if stripped.is_empty() || in_indented_code {
prev_can_start_indented_code = true;
} else {
indented_code_threshold = None;
while list_indent_stack
.last()
.is_some_and(|&col: &usize| indent_cols < col)
{
list_indent_stack.pop();
}
let base_indent: usize = list_indent_stack.last().copied().unwrap_or(0);
let rel_indent: usize = indent_cols.saturating_sub(base_indent);
if rel_indent >= 4 && prev_can_start_indented_code {
indented_code_threshold = Some(base_indent + 4);
prev_can_start_indented_code = true;
} else {
let (fence_base, fence_candidate): (usize, &str) = if rel_indent < 4
&& let Some((marker_cols, after)) = parse_list_marker(stripped)
{
let next_col: usize = indent_cols + marker_cols;
list_indent_stack.push(next_col);
(next_col, after)
} else {
(base_indent, stripped)
};
if rel_indent < 4
&& let Some((fence_ch, fence_len)) = parse_opening_fence(fence_candidate)
{
active_fence = Some((fence_ch, fence_len, fence_base));
fence_just_opened = true;
prev_can_start_indented_code = false;
} else {
prev_can_start_indented_code = rel_indent < 4
&& (is_thematic_break_line(stripped)
|| is_atx_heading_or_dash_break(stripped));
if line.contains('"') {
let step_def: Cow<'_, str> = normalize_link_def_title(line, stripped);
match step_def {
Cow::Borrowed(s) => {
rewritten = normalize_inline_prettier_line(s);
}
Cow::Owned(s) => {
let final_line: String = match normalize_inline_prettier_line(&s) {
Cow::Borrowed(_) => s,
Cow::Owned(inline_changed) => inline_changed,
};
rewritten = Cow::Owned(final_line);
}
}
}
}
}
}
match (&mut out, rewritten) {
(Some(buf), line_cow) => {
buf.push(TEXT_LF);
buf.push_str(&line_cow);
}
(None, Cow::Owned(changed)) => {
let mut buf: String = String::with_capacity(input.len() + 16);
buf.push_str(&input[..line_start]);
buf.push_str(&changed);
out = Some(buf);
}
(None, Cow::Borrowed(_)) => {}
}
line_start += line_len + 1;
}
match out {
Some(mut buf) => {
if has_trailing_lf {
buf.push(TEXT_LF);
}
buf
}
None => input,
}
}
#[inline(always)]
fn strip_blockquote_and_measure_indent(line: &str) -> (usize, usize, usize, &str) {
let bytes: &[u8] = line.as_bytes();
let len: usize = bytes.len();
let mut idx: usize = 0;
let mut bq_depth: usize = 0;
let mut bq_end: usize = 0;
loop {
let mut scan: usize = idx;
let mut ws_cols: usize = 0;
while scan < len {
if bytes[scan] == b' ' {
ws_cols += 1;
scan += 1;
} else if bytes[scan] == b'\t' {
ws_cols += 4 - (ws_cols % 4);
scan += 1;
} else {
break;
}
}
if ws_cols < 4 && scan < len && bytes[scan] == MD_BYTE_GT {
bq_depth += 1;
scan += 1;
bq_end = scan;
if scan < len && bytes[scan] == b' ' {
scan += 1;
}
idx = scan;
continue;
}
return (bq_depth, bq_end, ws_cols, &line[scan..]);
}
}
#[inline(always)]
fn parse_list_marker(stripped: &str) -> Option<(usize, &str)> {
let bytes: &[u8] = stripped.as_bytes();
let len: usize = bytes.len();
if len == 0 {
return None;
}
let marker_len: usize =
if bytes[0] == MD_BYTE_DASH || bytes[0] == MD_BYTE_STAR || bytes[0] == MD_BYTE_PLUS {
1
} else if bytes[0].is_ascii_digit() {
let digits: usize = bytes
.iter()
.take(9)
.take_while(|&&b: &&u8| b.is_ascii_digit())
.count();
if digits == 0
|| digits >= len
|| (bytes[digits] != MD_BYTE_DOT && bytes[digits] != MD_BYTE_RPAREN)
{
return None;
}
digits + 1
} else {
return None;
};
if marker_len == len {
return Some((marker_len + 1, ""));
}
if bytes[marker_len] != b' ' && bytes[marker_len] != b'\t' {
return None;
}
let mut scan: usize = marker_len;
let mut ws_cols: usize = 0;
while scan < len {
if bytes[scan] == b' ' {
ws_cols += 1;
scan += 1;
} else if bytes[scan] == b'\t' {
ws_cols += 4 - ((marker_len + ws_cols) % 4);
scan += 1;
} else {
break;
}
}
if scan == len || ws_cols >= 5 {
return Some((marker_len + 1, ""));
}
Some((marker_len + ws_cols, &stripped[scan..]))
}
#[inline(always)]
fn is_atx_heading_or_dash_break(stripped: &str) -> bool {
let bytes: &[u8] = stripped.as_bytes();
if bytes.is_empty() {
return false;
}
if bytes[0] == MD_BYTE_HASH {
let hashes: usize = bytes
.iter()
.take_while(|&&b: &&u8| b == MD_BYTE_HASH)
.count();
if (1..=6).contains(&hashes) {
return hashes == bytes.len() || bytes[hashes] == b' ' || bytes[hashes] == b'\t';
}
return false;
}
if bytes[0] != MD_BYTE_DASH {
return false;
}
let mut dashes: usize = 0;
for &b in bytes {
if b == b' ' || b == b'\t' {
continue;
}
if b != MD_BYTE_DASH {
return false;
}
dashes += 1;
}
dashes >= 3
}
#[inline(always)]
fn parse_opening_fence(stripped: &str) -> Option<(char, usize)> {
let bytes: &[u8] = stripped.as_bytes();
let first: u8 = *bytes.first()?;
if first != MD_BYTE_BACKTICK && first != MD_BYTE_TILDE {
return None;
}
let len: usize = bytes.iter().take_while(|&&b: &&u8| b == first).count();
if len < 3 {
return None;
}
if first == MD_BYTE_BACKTICK && bytes[len..].contains(&MD_BYTE_BACKTICK) {
return None;
}
Some((first as char, len))
}
#[inline(always)]
fn is_closing_fence(stripped: &str, fence_ch: char, fence_len: usize) -> bool {
let trimmed: &[u8] = stripped.trim_end_matches([TEXT_SPACE, TEXT_TAB]).as_bytes();
let target: u8 = fence_ch as u8;
let count: usize = trimmed.iter().take_while(|&&b: &&u8| b == target).count();
count >= fence_len && count == trimmed.len()
}
fn normalize_link_def_title<'a>(line: &'a str, trimmed: &str) -> Cow<'a, str> {
if !trimmed.starts_with('[') || trimmed.starts_with("[^") {
return Cow::Borrowed(line);
}
let prefix_len: usize = line.len() - trimmed.len();
let bytes: &[u8] = trimmed.as_bytes();
let len: usize = bytes.len();
let mut i: usize = 1;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
i += 2;
continue;
}
if bytes[i] == MD_BYTE_RBRACKET {
break;
}
i += 1;
}
if i + 1 >= len || bytes[i] != MD_BYTE_RBRACKET || bytes[i + 1] != MD_BYTE_COLON {
return Cow::Borrowed(line);
}
i += 2;
while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
i += 1;
}
let Some(after_dest) = scan_link_destination(bytes, i) else {
return Cow::Borrowed(line);
};
let mut ws: usize = after_dest;
while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
ws += 1;
}
if ws == after_dest || ws >= len || bytes[ws] != MD_BYTE_DQUOTE {
return Cow::Borrowed(line);
}
let Some(close_quote) = scan_double_quoted_title(bytes, ws) else {
return Cow::Borrowed(line);
};
if !trimmed[(close_quote + 1)..]
.trim_matches([TEXT_SPACE, TEXT_TAB])
.is_empty()
{
return Cow::Borrowed(line);
}
let inner: &str = &trimmed[(ws + 1)..close_quote];
let Some((open_ch, converted, close_ch)) = convert_double_title_to_prettier(inner) else {
return Cow::Borrowed(line);
};
let mut out: String = String::with_capacity(line.len());
out.push_str(&line[..(prefix_len + ws)]);
out.push(open_ch);
out.push_str(&converted);
out.push(close_ch);
out.push_str(&trimmed[(close_quote + 1)..]);
Cow::Owned(out)
}
fn normalize_inline_prettier_line(line: &str) -> Cow<'_, str> {
if !line.contains("](") || !line.contains('"') {
return Cow::Borrowed(line);
}
let bytes: &[u8] = line.as_bytes();
let len: usize = bytes.len();
let mut out: Option<String> = None;
let mut i: usize = 0;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
let next_len: usize = if bytes[i + 1] < 0x80 {
1
} else {
line[(i + 1)..]
.chars()
.next()
.map(char::len_utf8)
.unwrap_or(1)
};
if let Some(ref mut buf) = out {
buf.push_str(&line[i..(i + 1 + next_len)]);
}
i += 1 + next_len;
continue;
}
if bytes[i] == MD_BYTE_BACKTICK {
let end_code: usize = scan_inline_code_span(bytes, i);
if let Some(ref mut buf) = out {
buf.push_str(&line[i..end_code]);
}
i = end_code;
continue;
}
if bytes[i] == MD_BYTE_RBRACKET
&& i + 1 < len
&& bytes[i + 1] == MD_BYTE_LPAREN
&& let Some((replacement, next_i)) = try_rewrite_inline_link_title(line, i)
{
let buf: &mut String = out.get_or_insert_with(|| {
let mut s: String = String::with_capacity(len);
s.push_str(&line[..i]);
s
});
buf.push_str(&replacement);
i = next_i;
continue;
}
let ch_len: usize = if bytes[i] < 0x80 {
1
} else {
line[i..].chars().next().map(char::len_utf8).unwrap_or(1)
};
if let Some(ref mut buf) = out {
buf.push_str(&line[i..(i + ch_len)]);
}
i += ch_len;
}
match out {
Some(buf) => Cow::Owned(buf),
None => Cow::Borrowed(line),
}
}
fn scan_inline_code_span(bytes: &[u8], start: usize) -> usize {
let len: usize = bytes.len();
let ticks: usize = bytes[start..]
.iter()
.take_while(|&&b: &&u8| b == MD_BYTE_BACKTICK)
.count();
let mut i: usize = start + ticks;
while i < len {
if bytes[i] == MD_BYTE_BACKTICK {
let run: usize = bytes[i..]
.iter()
.take_while(|&&b: &&u8| b == MD_BYTE_BACKTICK)
.count();
if run == ticks {
return i + run;
}
i += run;
continue;
}
i += 1;
}
start + ticks
}
fn try_rewrite_inline_link_title(line: &str, bracket_idx: usize) -> Option<(String, usize)> {
let bytes: &[u8] = line.as_bytes();
let len: usize = bytes.len();
let mut i: usize = bracket_idx + 2;
while i < len && (bytes[i] == b' ' || bytes[i] == b'\t') {
i += 1;
}
let after_dest: usize = scan_link_destination(bytes, i)?;
let mut ws: usize = after_dest;
while ws < len && (bytes[ws] == b' ' || bytes[ws] == b'\t') {
ws += 1;
}
if ws == after_dest || ws >= len || bytes[ws] != MD_BYTE_DQUOTE {
return None;
}
let close_quote: usize = scan_double_quoted_title(bytes, ws)?;
let mut tail: usize = close_quote + 1;
while tail < len && (bytes[tail] == b' ' || bytes[tail] == b'\t') {
tail += 1;
}
if tail >= len || bytes[tail] != MD_BYTE_RPAREN {
return None;
}
let inner: &str = &line[(ws + 1)..close_quote];
let (open_ch, converted, close_ch): (char, String, char) =
convert_double_title_to_prettier(inner)?;
let mut out: String = String::with_capacity(tail + 1 - bracket_idx);
out.push_str(&line[bracket_idx..ws]);
out.push(open_ch);
out.push_str(&converted);
out.push(close_ch);
out.push_str(&line[(close_quote + 1)..=tail]);
Some((out, tail + 1))
}
fn scan_link_destination(bytes: &[u8], start: usize) -> Option<usize> {
let len: usize = bytes.len();
if start >= len {
return None;
}
if bytes[start] == MD_BYTE_LT {
let mut i: usize = start + 1;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
i += 2;
continue;
}
if bytes[i] == MD_BYTE_GT {
return Some(i + 1);
}
if bytes[i] == MD_BYTE_LT {
return None;
}
i += 1;
}
return None;
}
let mut i: usize = start;
let mut paren_depth: usize = 0;
while i < len {
let b: u8 = bytes[i];
if b == b'\\' && i + 1 < len {
i += 2;
continue;
}
if b == b' ' || b == b'\t' {
break;
}
if b == MD_BYTE_LPAREN {
paren_depth += 1;
} else if b == MD_BYTE_RPAREN {
if paren_depth == 0 {
break;
}
paren_depth -= 1;
}
i += 1;
}
if i == start || paren_depth != 0 {
return None;
}
Some(i)
}
fn scan_double_quoted_title(bytes: &[u8], open_quote: usize) -> Option<usize> {
let len: usize = bytes.len();
let mut i: usize = open_quote + 1;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
i += 2;
continue;
}
if bytes[i] == MD_BYTE_DQUOTE {
return Some(i);
}
i += 1;
}
None
}
fn convert_double_title_to_prettier(inner: &str) -> Option<(char, String, char)> {
let has_single: bool = inner.contains('\'');
let has_escaped_double: bool = inner.contains('"');
let (open_ch, close_ch): (char, char) = if !has_single {
('\'', '\'')
} else if has_escaped_double && !inner.contains('(') && !inner.contains(')') {
('(', ')')
} else {
return None;
};
let bytes: &[u8] = inner.as_bytes();
let len: usize = bytes.len();
let mut out: String = String::with_capacity(len);
let mut i: usize = 0;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
if bytes[i + 1] == MD_BYTE_DQUOTE {
out.push('"');
} else {
out.push('\\');
let next_len: usize = if bytes[i + 1] < 0x80 {
1
} else {
inner[(i + 1)..]
.chars()
.next()
.map(char::len_utf8)
.unwrap_or(1)
};
out.push_str(&inner[(i + 1)..(i + 1 + next_len)]);
i += 1 + next_len;
continue;
}
i += 2;
continue;
}
let ch_len: usize = if bytes[i] < 0x80 {
1
} else {
inner[i..].chars().next().map(char::len_utf8).unwrap_or(1)
};
out.push_str(&inner[i..(i + ch_len)]);
i += ch_len;
}
Some((open_ch, out, close_ch))
}