fn close_code(
state: &mut Tier1State,
frame: &OpenTag,
trim_boundary_whitespace: bool,
options: &ConversionOptions,
) -> Result<(), BailReason> {
if state.escape_ctx.contains(EscapeCtx::PRE) || state.escape_ctx.contains(EscapeCtx::CODE) {
return Ok(());
}
let buf = state.cell_or_output_mut();
let content_start = clamp_to_char_boundary(buf, frame.content_start);
if content_start >= buf.len() {
if frame.dropped_whitespace_only_text {
return Err(BailReason::WhitespaceOnlyInlineEmphasis);
}
return Ok(());
}
if buf[..content_start].ends_with('`') {
return Err(BailReason::AdjacentInlineEmphasis);
}
let (leading, content, trailing) = code_span_parts(&buf[content_start..], trim_boundary_whitespace);
buf.truncate(content_start);
buf.push_str(&leading);
let mut first = true;
for segment in content.split('\n').filter(|segment| !segment.is_empty()) {
if !first {
buf.push_str(crate::converter::main_helpers::hard_break_marker(options));
}
format_inline_code_segment(buf, segment);
first = false;
}
buf.push_str(&trailing);
Ok(())
}
fn code_span_parts(original: &str, trim_boundary_whitespace: bool) -> (String, String, String) {
let trimmed = original.trim();
if !trim_boundary_whitespace || trimmed.is_empty() {
return (String::new(), original.to_owned(), String::new());
}
let leading_len = original.len() - original.trim_start().len();
let trailing_start = original.trim_end().len();
(
original[..leading_len].to_owned(),
trimmed.to_owned(),
original[trailing_start..].to_owned(),
)
}
fn format_inline_code_segment(buf: &mut String, content: &str) {
let contains_backtick = content.contains('`');
let first_char = content.chars().next();
let last_char = content.chars().last();
let starts_with_space = first_char == Some(' ');
let ends_with_space = last_char == Some(' ');
let starts_with_backtick = first_char == Some('`');
let ends_with_backtick = last_char == Some('`');
let needs_spaces =
starts_with_backtick || ends_with_backtick || (starts_with_space && ends_with_space && contains_backtick);
let num_backticks = if contains_backtick {
min_safe_code_span_delimiter_length(content)
} else {
1
};
for _ in 0..num_backticks {
buf.push('`');
}
if needs_spaces {
buf.push(' ');
}
buf.push_str(content);
if needs_spaces {
buf.push(' ');
}
for _ in 0..num_backticks {
buf.push('`');
}
}
fn longest_consecutive_backtick_run(content: &str) -> usize {
content
.chars()
.fold((0usize, 0usize), |(max, current), c| {
if c == '`' {
let next = current + 1;
(max.max(next), next)
} else {
(max, 0)
}
})
.0
}
fn min_safe_code_span_delimiter_length(content: &str) -> usize {
let mut run_lengths = std::collections::HashSet::new();
let mut current = 0usize;
for c in content.chars() {
if c == '`' {
current += 1;
} else {
if current > 0 {
run_lengths.insert(current);
}
current = 0;
}
}
if current > 0 {
run_lengths.insert(current);
}
let mut candidate = 1usize;
while run_lengths.contains(&candidate) {
candidate += 1;
}
candidate
}
fn is_byte_subsequence(needle: &str, haystack: &str) -> bool {
let mut needle_bytes = needle.bytes();
let Some(mut want) = needle_bytes.next() else {
return true;
};
for byte in haystack.bytes() {
if byte == want {
match needle_bytes.next() {
Some(next_want) => want = next_want,
None => return true,
}
}
}
false
}
fn try_emit_autolink(
dest: &mut String,
trim_start: usize,
frame: &OpenTag,
href_str: &str,
has_nested_tag: bool,
options: &ConversionOptions,
) -> Result<bool, BailReason> {
if !options.autolinks || options.default_title || href_str.is_empty() || !has_uri_scheme(href_str) {
return Ok(false);
}
let mailto_suffix = href_str.strip_prefix("mailto:");
let label = &dest[trim_start..];
if has_nested_tag {
let could_be_autolink = is_byte_subsequence(href_str, label)
|| mailto_suffix.is_some_and(|suffix| is_byte_subsequence(suffix, label));
if could_be_autolink {
return Err(BailReason::LinkAutolinkNestedMarkup);
}
}
let rendered = if label == href_str {
href_str
} else if mailto_suffix == Some(label) {
mailto_suffix.unwrap_or(href_str)
} else {
return Ok(false);
};
let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
let label_start = if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
dest.remove(bracket_pos);
trim_start - 1
} else {
trim_start
};
let rendered = rendered.to_owned();
dest.truncate(label_start);
dest.push('<');
dest.push_str(&rendered);
dest.push('>');
Ok(true)
}
fn trim_label_preserving_boundary_hard_breaks(dest: &mut String, trim_start: usize, keeps_breaks: bool, marker: &str) {
if !keeps_breaks {
let label = &dest[trim_start..];
if label.contains(marker) {
let folded = label.replace(marker, " ");
dest.truncate(trim_start);
dest.push_str(&folded);
}
let trimmed = dest[trim_start..].trim_matches(|c: char| c.is_whitespace()).to_owned();
dest.truncate(trim_start);
dest.push_str(&trimmed);
return;
}
let label = &dest[trim_start..];
let without_trailing = label.trim_end_matches(marker);
let has_trailing_break = without_trailing.len() != label.len();
let body = without_trailing.trim_end_matches(|c: char| c.is_whitespace());
let without_leading = body.trim_start_matches(marker);
let has_leading_break = without_leading.len() != body.len();
let mut rebuilt = String::with_capacity(without_leading.len() + 2 * marker.len());
if !without_leading.is_empty() {
if has_leading_break {
rebuilt.push_str(marker);
}
rebuilt.push_str(without_leading);
if has_trailing_break {
rebuilt.push_str(marker);
}
}
if rebuilt.len() != label.len() {
dest.truncate(trim_start);
dest.push_str(&rebuilt);
}
if let std::borrow::Cow::Owned(protected) =
crate::converter::utility::content::protect_adjacent_hard_breaks(&dest[trim_start..])
{
dest.truncate(trim_start);
dest.push_str(&protected);
}
}
fn close_link(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) -> Result<(), BailReason> {
let (href, title, has_nested_tag) = state.link_stack.pop().unwrap_or((None, None, false));
let keeps_boundary_hard_breaks = !state.escape_ctx.contains(EscapeCtx::HEADING) && !state.in_table_cell();
let dest = state.cell_or_output_mut();
let trim_start = clamp_to_char_boundary(dest, frame.content_start);
trim_label_preserving_boundary_hard_breaks(
dest,
trim_start,
keeps_boundary_hard_breaks,
crate::converter::main_helpers::hard_break_marker(options),
);
normalize_link_label_nbsp(dest, trim_start);
if let Some(href_str) = href.as_deref() {
if try_emit_autolink(dest, trim_start, frame, href_str, has_nested_tag, options)? {
return Ok(());
}
}
if let Some(href_str) = href.as_deref() {
if href_str.starts_with('#') && dest.len() == trim_start + 1 && dest.as_bytes()[trim_start] == b'^' {
dest.truncate(trim_start);
dest.push('↑');
}
}
if let Some(href) = href {
emit_markdown_link_close(dest, trim_start, &href, title.as_deref(), options);
} else {
let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
dest.remove(bracket_pos);
}
}
Ok(())
}
fn normalize_link_label_nbsp(dest: &mut String, trim_start: usize) {
if !dest[trim_start..].contains('\u{00a0}') {
return;
}
let normalized = dest[trim_start..]
.chars()
.map(|character| if character == '\u{00a0}' { ' ' } else { character })
.collect::<String>();
dest.truncate(trim_start);
dest.push_str(&normalized);
}
fn emit_markdown_link_close(
dest: &mut String,
trim_start: usize,
href: &str,
title: Option<&str>,
options: &ConversionOptions,
) {
if let std::borrow::Cow::Owned(escaped_label) =
crate::converter::utility::escaping::escape_link_label(&dest[trim_start..])
{
dest.truncate(trim_start);
dest.push_str(&escaped_label);
}
dest.push_str("](");
crate::converter::inline::link::append_url_destination(dest, href, options.url_escape_style, title.is_some());
if let Some(title) = title {
let escaped_title = crate::converter::inline::link::escape_markdown_title(title);
dest.push_str(" \"");
dest.push_str(&escaped_title);
dest.push('"');
}
dest.push(')');
}
fn close_list(state: &mut Tier1State, kind: ListKind) {
state.list_depth = state.list_depth.saturating_sub(1);
if matches!(kind, ListKind::Unordered) {
state.ul_depth = state.ul_depth.saturating_sub(1);
}
if state.in_table_cell() {
return;
}
let dest = state.cell_or_output_mut();
if !dest.ends_with('\n') {
dest.push('\n');
}
if kind == ListKind::Ordered {
let end = dest.trim_end().len();
state.last_ordered_list_end = Some(end);
}
}
fn close_list_item(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
if state.in_table_cell() {
let cell_buf = state.cell_or_output_mut();
while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
cell_buf.pop();
}
return Ok(());
}
state.list_item_marker_widths.pop();
let after_text = state.list_items_after_text.pop().unwrap_or_default();
trim_trailing_inline_whitespace(state);
let follows_text = state.list_depth > 1 || after_text;
let dest = state.cell_or_output_mut();
let marker_line = dest
.get(clamp_to_char_boundary(dest, frame.content_start)..)
.unwrap_or_default();
if follows_text && marker_line.split('\n').next().unwrap_or_default().trim().is_empty() {
return Err(BailReason::EmptyNestedListItem);
}
let had_block_children = {
let start = clamp_to_char_boundary(dest, frame.content_start);
dest[start..].contains("\n\n")
};
if had_block_children {
if !dest.ends_with("\n\n") {
if dest.ends_with('\n') {
dest.push('\n');
} else {
dest.push_str("\n\n");
}
}
} else if !dest.is_empty() && !dest.ends_with('\n') {
dest.push('\n');
}
Ok(())
}
fn open_dl(state: &mut Tier1State) {
if state.in_table_cell() {
return;
}
state.ensure_blank_line();
}
fn open_dt(state: &mut Tier1State) {
mark_definition_in_cell(state);
}
fn open_dd(state: &mut Tier1State) {
mark_definition_in_cell(state);
}
fn mark_definition_in_cell(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut().filter(|ts| ts.in_cell) {
ts.definition_in_cell = true;
}
}
fn close_dt(state: &mut Tier1State) {
if state.in_table_cell() {
return;
}
trim_trailing_inline_whitespace(state);
let buf = state.cell_or_output_mut();
if buf.is_empty() || buf.ends_with('\n') {
return;
}
buf.push('\n');
}
fn close_dd(state: &mut Tier1State) {
if state.in_table_cell() {
return;
}
trim_trailing_inline_whitespace(state);
let buf = state.cell_or_output_mut();
if buf.is_empty() {
return;
}
if buf.ends_with("\n\n") {
return;
}
if buf.ends_with('\n') {
buf.push('\n');
} else {
buf.push_str("\n\n");
}
}
fn close_dl(state: &mut Tier1State, frame: &OpenTag) {
if state.in_table_cell() {
return;
}
let buf = state.cell_or_output_mut();
if buf.len() <= frame.content_start {
return;
}
while buf.len() > frame.content_start {
let last = buf.as_bytes()[buf.len() - 1];
if matches!(last, b' ' | b'\t' | b'\n' | b'\r') {
buf.pop();
} else {
break;
}
}
if buf.len() == frame.content_start {
return;
}
buf.push_str("\n\n");
}