fn emit_close_for_implicit(
state: &mut Tier1State,
options: &ConversionOptions,
table_probes: &mut Vec<TableLayoutProbe>,
) -> Result<(), BailReason> {
let frame = state.stack.pop().ok_or_else(|| BailReason::DepthMismatch {
tag: String::from("(implicit)"),
expected: 1,
actual: 0,
})?;
let spec = frame.spec;
state.escape_ctx = frame.prev_escape_ctx;
state.last_closed_custom_element = std::ptr::eq(spec, &raw const CUSTOM_ELEMENT_INLINE_SPEC);
match spec.kind {
TagKind::Paragraph => close_paragraph(state),
TagKind::Heading(n) => close_heading(state, &frame, n, true, options)?,
TagKind::Blockquote => close_blockquote(state, &frame, options),
TagKind::Pre => close_pre(state, &frame, options),
TagKind::Strong
if state.summary_at_top()
|| state.escape_ctx.contains(EscapeCtx::STRONG)
|| state.escape_ctx.contains(EscapeCtx::CODE)
|| state.escape_ctx.contains(EscapeCtx::PRE) => {}
TagKind::Strong => close_inline_marker(state, &frame, "**")?,
TagKind::Emphasis
if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
TagKind::Emphasis => close_inline_marker(state, &frame, "*")?,
TagKind::Strikethrough
if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
TagKind::Strikethrough => close_inline_marker(state, &frame, "~~")?,
TagKind::Inserted
if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
TagKind::Inserted => {}
TagKind::Code => close_code(state, &frame, false, options)?,
TagKind::Link => close_link(state, &frame, options)?,
TagKind::List(ListKind::Definition) => close_dl(state, &frame, options),
TagKind::List(kind) => close_list(state, kind),
TagKind::ListItem => close_list_item(state, &frame)?,
TagKind::DefinitionTerm => close_dt(state),
TagKind::DefinitionDescription => close_dd(state),
TagKind::TableCell { .. } => close_table_cell(state, true, options)?,
TagKind::TableRow => close_table_row(state),
TagKind::Summary => close_summary(state, &frame),
TagKind::Figcaption => close_figcaption(state, &frame),
TagKind::LineEndControl => close_line_end_control(state, &frame),
TagKind::Table => close_table(state, options, table_probes)?,
TagKind::Block | TagKind::Inline => {}
TagKind::LineBreak
| TagKind::Image
| TagKind::Hr
| TagKind::TableHead
| TagKind::TableBody
| TagKind::TableFoot
| TagKind::TableCaption
| TagKind::Media
| TagKind::RawText(_)
| TagKind::Ignored => {}
}
Ok(())
}
fn close_paragraph(state: &mut Tier1State) {
if state.escape_ctx.contains(EscapeCtx::CODE | EscapeCtx::HEADING)
&& !state.escape_ctx.contains(EscapeCtx::PRE)
&& !state.in_table_cell()
{
return;
}
if state.in_table_cell() {
return;
}
trim_trailing_inline_whitespace(state);
state.cell_or_output_mut().push_str("\n\n");
}
fn close_heading(
state: &mut Tier1State,
frame: &OpenTag,
n: u8,
is_implicit: bool,
options: &ConversionOptions,
) -> Result<(), BailReason> {
if close_heading_in_cell(state, frame, is_implicit, options.br_in_tables) {
return Ok(());
}
trim_trailing_inline_whitespace(state);
let buf = state.cell_or_output_mut();
let content_start = clamp_to_char_boundary(buf, frame.content_start);
if !is_implicit && discard_empty_heading(buf, content_start) {
return Ok(());
}
normalize_heading_body(buf, content_start);
trim_heading_body(buf, content_start);
escape_heading_closing_sequence(buf, content_start, options);
let prefix = heading_prefix(n);
buf.insert_str(content_start, prefix);
ensure_blank_line_buf(state.cell_or_output_mut());
Ok(())
}
fn close_heading_in_cell(state: &mut Tier1State, frame: &OpenTag, is_implicit: bool, br_in_tables: bool) -> bool {
if !state.in_table_cell() {
return false;
}
let cell_buf = state.cell_or_output_mut();
while cell_buf.len() > frame.content_start && (cell_buf.ends_with(' ') || cell_buf.ends_with('\t')) {
cell_buf.pop();
}
if !is_implicit {
let content_start = clamp_to_char_boundary(cell_buf, frame.content_start);
if cell_buf[content_start..].trim().is_empty() {
cell_buf.truncate(content_start);
}
}
separate_closed_block_in_cell(state, frame.content_start, br_in_tables);
true
}
fn discard_empty_heading(buf: &mut String, content_start: usize) -> bool {
if !buf[content_start..].trim().is_empty() {
return false;
}
buf.truncate(content_start);
let trimmed_len = buf.trim_end_matches('\n').len();
if trimmed_len > 0 {
buf.truncate(trimmed_len);
buf.push('\n');
} else {
buf.clear();
}
true
}
fn normalize_heading_body(buf: &mut String, content_start: usize) {
if !buf[content_start..].contains('\n') {
return;
}
let content = buf[content_start..].to_owned();
let mut normalized = String::with_capacity(content.len());
let mut prev_was_space = false;
for ch in content.chars() {
let is_ws = matches!(ch, ' ' | '\t' | '\n' | '\r');
if is_ws && !prev_was_space {
normalized.push(' ');
} else if !is_ws {
normalized.push(ch);
}
prev_was_space = is_ws;
}
buf.truncate(content_start);
buf.push_str(normalized.trim_end());
}
fn trim_heading_body(buf: &mut String, content_start: usize) {
let trailing_start = buf[content_start..]
.char_indices()
.rev()
.find(|&(_, character)| !character.is_whitespace())
.map_or(content_start, |(index, character)| {
content_start + index + character.len_utf8()
});
buf.truncate(trailing_start);
let leading_len = buf[content_start..]
.char_indices()
.find(|&(_, character)| !character.is_whitespace())
.map_or(buf.len() - content_start, |(index, _)| index);
buf.replace_range(content_start..content_start + leading_len, "");
}
fn escape_heading_closing_sequence(buf: &mut String, content_start: usize, options: &ConversionOptions) {
if options.output_format != crate::options::OutputFormat::Markdown {
return;
}
if let Some(offset) = crate::converter::utility::escaping::atx_closing_sequence_offset(&buf[content_start..]) {
buf.insert(content_start + offset, '\\');
}
}
fn close_blockquote(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) {
let (br_in_tables, style) = (options.br_in_tables, options.code_block_style);
if close_blockquote_in_cell(state, frame, br_in_tables) {
return;
}
let content_start = clamp_to_char_boundary(&state.output, frame.content_start);
let content = prepare_blockquote_content(&state.output[content_start..], style);
let prefixed = prefix_blockquote_lines(&content);
state.output.truncate(content_start);
separate_blockquote_prefix(&mut state.output, frame.prev_escape_ctx);
push_list_item_continuation_lines(state, &prefixed);
let in_list_item = state
.stack
.iter()
.any(|open_frame| matches!(open_frame.spec.kind, TagKind::ListItem));
if !in_list_item {
state.ensure_blank_line();
}
}
fn close_blockquote_in_cell(state: &mut Tier1State, frame: &OpenTag, br_in_tables: bool) -> bool {
if !state.in_table_cell() {
return false;
}
if !state.escape_ctx.contains(EscapeCtx::CODE) {
separate_closed_block_in_cell(state, frame.content_start, br_in_tables);
return true;
}
let cell_buf = state.cell_or_output_mut();
let content_start = clamp_to_char_boundary(cell_buf, frame.content_start);
let content = cell_buf.split_off(content_start);
if !content.trim().is_empty() {
if !cell_buf.is_empty() && !cell_buf.ends_with('\n') {
cell_buf.push('\n');
}
cell_buf.push_str(content.trim());
cell_buf.push('\n');
}
true
}
fn prepare_blockquote_content(content: &str, style: crate::options::CodeBlockStyle) -> String {
let range = crate::converter::code_scan::trimmed_quotes_content_range(content, style);
content[range].to_owned()
}
fn separate_blockquote_prefix(output: &mut String, previous_context: EscapeCtx) {
if previous_context.contains(EscapeCtx::BLOCKQUOTE) {
if output.ends_with("\n\n") {
output.pop();
}
return;
}
if output.is_empty() {
return;
}
if output.ends_with("\n\n") {
output.pop();
} else if output.ends_with('\n') {
output.push('\n');
} else {
output.push_str("\n\n");
}
}
fn renders_into_own_buffer(kind: TagKind, name_lower: &[u8], ctx: EscapeCtx) -> bool {
match kind {
TagKind::Blockquote
| TagKind::Heading(_)
| TagKind::Pre
| TagKind::DefinitionTerm
| TagKind::DefinitionDescription => true,
TagKind::Code | TagKind::Strong | TagKind::Emphasis | TagKind::Strikethrough | TagKind::Inserted => {
!ctx.contains(EscapeCtx::CODE)
}
_ => matches!(name_lower, b"sub" | b"sup" | b"abbr"),
}
}
fn cell_scratch_start(state: &Tier1State) -> usize {
innermost_own_buffer(state).map_or(0, |frame| frame.content_start)
}
fn innermost_own_buffer(state: &Tier1State) -> Option<&OpenTag> {
state
.stack
.iter()
.rev()
.take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. } | TagKind::Summary))
.find(|frame| frame.own_buffer)
}
fn cell_needs_tier2(state: &mut Tier1State, spec: &TagSpec, name_lower: &[u8]) -> bool {
if !state.in_table_cell() {
return false;
}
if matches!(name_lower, b"legend" | b"figcaption" | b"label") {
return true;
}
let definition = matches!(spec.kind, TagKind::DefinitionTerm | TagKind::DefinitionDescription);
if definition && state.table_stack.last().is_some_and(|ts| ts.definition_in_cell) {
return true;
}
let sectioning = matches!(
name_lower,
b"article" | b"section" | b"nav" | b"aside" | b"header" | b"footer" | b"main"
);
let in_inline_buffer = state
.stack
.iter()
.rev()
.take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. } | TagKind::Summary))
.any(|frame| frame.own_buffer && !frame.spec.is_block);
let inline_buffer = innermost_own_buffer(state)
.filter(|frame| {
!frame.spec.is_block
|| matches!(
frame.spec.kind,
TagKind::DefinitionTerm | TagKind::DefinitionDescription
)
})
.map(|frame| frame.content_start);
let cell_buf = state.cell_or_output_mut();
let buffer_so_far = inline_buffer.map(|start| &cell_buf[clamp_to_char_boundary(cell_buf, start)..]);
let at_buffer_start = buffer_so_far.is_some_and(|text| text.trim().is_empty());
let break_at_buffer_start = matches!(spec.kind, TagKind::LineBreak) && at_buffer_start;
let block_at_buffer_start = spec.is_block && at_buffer_start && !cell_buf.trim().is_empty();
(sectioning && !cell_buf.is_empty())
|| (spec.is_block && in_inline_buffer)
|| break_at_buffer_start
|| block_at_buffer_start
}
fn trim_start_of_cell_content(state: &mut Tier1State, content_start: usize) -> Result<(), BailReason> {
if !state.in_table_cell() {
return Ok(());
}
let cell_buf = state.cell_or_output_mut();
let start = clamp_to_char_boundary(cell_buf, content_start);
let content = cell_buf[start..].trim_start();
let leading = cell_buf.len() - start - content.len();
if leading > 0 && content.starts_with("---") {
return Err(BailReason::TableBlockChildInCell);
}
cell_buf.replace_range(start..start + leading, "");
Ok(())
}
fn check_whitespace_led_block_in_cell(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
if !frame.starts_with_whitespace || !state.in_table_cell() {
return Ok(());
}
let cell_buf = state.cell_or_output_mut();
let start = clamp_to_char_boundary(cell_buf, frame.content_start);
if cell_buf[start..].trim().is_empty() {
return Ok(());
}
Err(BailReason::TableBlockChildInCell)
}
fn with_cell_scratch<R>(state: &mut Tier1State, write: impl FnOnce(&mut String) -> R) -> R {
let start = cell_scratch_start(state);
let cell_buf = state.cell_or_output_mut();
let start = clamp_to_char_boundary(cell_buf, start);
if start == 0 {
return write(cell_buf);
}
let mut scratch = cell_buf.split_off(start);
let result = write(&mut scratch);
cell_buf.push_str(&scratch);
result
}
fn separate_block_in_cell_at(state: &mut Tier1State, at: usize, br_in_tables: bool) {
if state.escape_ctx.intersects(EscapeCtx::HEADING | EscapeCtx::CODE) {
return;
}
let scratch_start = cell_scratch_start(state);
let cell_buf = state.cell_or_output_mut();
let at = clamp_to_char_boundary(cell_buf, at);
let scratch_start = clamp_to_char_boundary(cell_buf, scratch_start.min(at));
if cell_buf[scratch_start..at].trim().is_empty() {
return;
}
let content = cell_buf.split_off(at);
crate::converter::main_helpers::separate_block_in_cell(cell_buf, br_in_tables);
cell_buf.push_str(content.trim_start());
}
fn separate_closed_block_in_cell(state: &mut Tier1State, content_start: usize, br_in_tables: bool) {
let cell_buf = state.cell_or_output_mut();
let content_start = clamp_to_char_boundary(cell_buf, content_start);
if cell_buf[content_start..].trim().is_empty() {
return;
}
separate_block_in_cell_at(state, content_start, br_in_tables);
}
fn close_pre(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) {
if close_pre_in_cell(state, frame, options) {
return;
}
let content_start = clamp_to_char_boundary(&state.output, frame.content_start);
let raw = state.output[content_start..].to_owned();
state.output.truncate(content_start);
if raw.is_empty() {
state.pre_lang = None;
return;
}
let content = crate::converter::handlers::code_block::process_pre_content(raw, options.whitespace_mode, true);
let mut rendered = String::with_capacity(content.len() + 16);
crate::converter::handlers::code_block::render_code_block(
&content,
state.pre_lang.take().as_deref(),
&mut rendered,
options,
);
push_list_item_continuation_lines(state, &rendered);
state.pre_lang = None;
}
fn start_line_in_pre(state: &mut Tier1State, name_lower: &[u8]) -> bool {
if !state.escape_ctx.contains(EscapeCtx::PRE) || state.in_table_cell() {
return false;
}
if !std::str::from_utf8(name_lower).is_ok_and(crate::converter::handlers::code_block::is_line_element_in_pre) {
return false;
}
state.ensure_newline();
true
}
fn close_pre_in_cell(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) -> bool {
if !state.in_table_cell() {
return false;
}
let break_offsets = std::mem::take(&mut state.pre_cell_break_offsets);
let cell_buf = state.cell_or_output_mut();
let content_start = clamp_to_char_boundary(cell_buf, frame.content_start);
let content = cell_buf.split_off(content_start);
let relative_offsets = break_offsets
.into_iter()
.filter_map(|offset| offset.checked_sub(content_start))
.filter(|&offset| offset < content.len())
.collect::<Vec<_>>();
if !content.trim_matches('\n').is_empty() {
crate::converter::main_helpers::separate_block_in_cell(cell_buf, options.br_in_tables);
crate::converter::handlers::code_block::format_preformatted_cell_content(
&content,
&relative_offsets,
cell_buf,
options.br_in_tables,
options.whitespace_mode == crate::options::WhitespaceMode::Strict,
);
}
true
}
fn indent_fresh_list_item_text_line(state: &mut Tier1State) {
if state.in_table_cell() || state.in_summary() || state.in_table_caption() {
return;
}
let in_list_item = state
.stack
.iter()
.any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
if !in_list_item {
return;
}
let indent_width = state.list_continuation_indent_width();
if indent_width == 0 {
return;
}
let dest = state.cell_or_output_mut();
if dest.ends_with('\n') && !dest.ends_with("\n\n") {
let indent: String = std::iter::repeat_n(' ', indent_width).collect();
dest.push_str(&indent);
}
}
fn indent_list_item_text_continuation_lines(buffer: &mut String, from: usize, indent_width: usize) {
let emitted = &buffer[from..];
if indent_width == 0 || !emitted.contains('\n') || emitted.contains("\n\n") {
return;
}
let indent = " ".repeat(indent_width);
let mut indented = String::with_capacity(emitted.len() + indent.len());
let mut lines = emitted.split_inclusive('\n').peekable();
while let Some(line) = lines.next() {
indented.push_str(line);
if lines.peek().is_some() {
indented.push_str(&indent);
}
}
buffer.truncate(from);
buffer.push_str(&indented);
}
fn push_list_item_continuation_lines(state: &mut Tier1State, rendered: &str) {
let indent_width = state.list_continuation_indent_width();
if indent_width == 0 {
state.output.push_str(rendered);
return;
}
let is_continuation = !state.output.is_empty() && !line_is_bare_list_marker(&state.output);
let indent: String = std::iter::repeat_n(' ', indent_width).collect();
for (index, segment) in rendered.split_inclusive('\n').enumerate() {
let line = segment.strip_suffix('\n').unwrap_or(segment);
if line.is_empty() || (index == 0 && !is_continuation) {
state.output.push_str(segment);
} else {
state.output.push_str(&indent);
state.output.push_str(segment);
}
}
}