fn close_table(
state: &mut Tier1State,
options: &ConversionOptions,
table_probes: &mut Vec<TableLayoutProbe>,
) -> Result<(), BailReason> {
let Some(ts) = state.table_stack.pop() else {
return Ok(());
};
let probe = table_probes.pop().unwrap_or_default();
table_probes.truncate(state.table_stack.len());
validate_table_layout(&ts, &probe)?;
render_closed_table(state, ts, table_probes, options);
Ok(())
}
fn validate_table_layout(
table: &crate::converter::tier1::state::TableState,
probe: &TableLayoutProbe,
) -> Result<(), BailReason> {
let has_caption = table.caption_text.is_some();
if !table.has_th
&& !has_caption
&& !probe.has_span
&& probe.nested_table_count > 0
&& table.rows.len() == 1
&& table.first_row_col_count == Some(1)
{
return Err(BailReason::TableNestedTable);
}
if !table.has_th && !has_caption && table_requires_layout_fallback(table, probe) {
return Err(BailReason::Classifier);
}
if table.had_single_cell_nested_table_row {
return Err(BailReason::TableNestedTableInSingleCellRow);
}
Ok(())
}
fn table_requires_layout_fallback(
table: &crate::converter::tier1::state::TableState,
probe: &TableLayoutProbe,
) -> bool {
let expanded_columns = |row: &Vec<(String, u16)>| row.iter().map(|(_, span)| usize::from(*span)).sum::<usize>();
let expected_columns = table.first_row_col_count.unwrap_or(0);
let inconsistent_columns = table.rows.iter().any(|row| expanded_columns(row) != expected_columns);
let link_heavy = table.rows.len() <= 2 && table.link_count >= 3;
let blank = table.rows.is_empty()
|| table
.rows
.iter()
.all(|row| row.iter().all(|(cell, _)| cell.trim().is_empty()));
let multiple_nested_tables = probe.nested_table_count > 1;
let spanning_borderless = probe.has_span && probe.border_zero;
inconsistent_columns || link_heavy || blank || multiple_nested_tables || spanning_borderless
}
fn render_closed_table(
state: &mut Tier1State,
table: crate::converter::tier1::state::TableState,
table_probes: &mut [TableLayoutProbe],
options: &ConversionOptions,
) {
if table.inline_mode {
if let Some(outer) = state.table_stack.last_mut() {
outer.had_nested_table = true;
}
if let Some(outer_probe) = table_probes.last_mut() {
outer_probe.nested_table_count += 1;
}
let mut nested = table.caption_text.as_deref().unwrap_or_default().to_string();
for row in &table.rows {
let mut row_cells = row.iter().filter(|(cell, _)| !cell.is_empty());
if let Some((first, _)) = row_cells.next() {
if !nested.is_empty() {
crate::converter::main_helpers::emit_table_cell_break(&mut nested, options.br_in_tables);
}
nested.push_str(first);
for (cell, _) in row_cells {
nested.push(' ');
nested.push_str(cell);
}
}
}
let write_nested = |dest: &mut String| {
if !nested.is_empty() && !dest.trim_end().is_empty() {
crate::converter::main_helpers::emit_table_cell_break(dest, options.br_in_tables);
}
dest.push_str(&nested);
};
let in_block = state
.stack
.iter()
.rev()
.take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. }))
.any(|frame| {
matches!(
frame.spec.kind,
TagKind::Blockquote | TagKind::Heading(_) | TagKind::Pre
)
});
if in_block {
with_cell_scratch(state, write_nested);
} else {
write_nested(state.cell_or_output_mut());
if !nested.is_empty()
&& let Some(outer) = state.table_stack.last_mut()
{
outer.nested_table_ends.push(outer.current_cell.len());
}
}
} else {
emit_gfm_table(&mut state.output, table, options.output_format);
}
}
fn close_table_head(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.in_thead = false;
}
}
fn close_table_body(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.seen_tbody_close = true;
}
}
fn close_table_caption(state: &mut Tier1State) {
let Some(ts) = state.table_stack.last_mut() else {
return;
};
ts.in_caption = false;
let raw = std::mem::take(&mut ts.caption_buf);
let trimmed = raw.trim();
if !trimmed.is_empty() {
ts.caption_text = Some(trimmed.replace('-', r"\-"));
}
}
fn close_table_row(state: &mut Tier1State) {
let Some(ts) = state.table_stack.last_mut() else {
return;
};
if ts.current_row.is_empty() {
return;
}
if ts.pending_single_cell_nested_table && ts.current_row.len() == 1 {
ts.had_single_cell_nested_table_row = true;
}
ts.pending_single_cell_nested_table = false;
let col_count: usize = ts.current_row.iter().map(|(_, c)| usize::from(*c)).sum();
if ts.first_row_col_count.is_none() {
ts.first_row_col_count = Some(col_count);
}
let row = std::mem::take(&mut ts.current_row);
ts.rows.push(row);
}
fn close_table_cell(state: &mut Tier1State, is_implicit: bool, options: &ConversionOptions) -> Result<(), BailReason> {
let Some(ts) = state.table_stack.last_mut() else {
return Ok(());
};
ts.in_cell = false;
crate::converter::block::table::cell::separate_nested_table_following_content(
&mut ts.current_cell,
&ts.nested_table_ends,
options.br_in_tables,
);
ts.nested_table_ends.clear();
let cell_text_raw = ts.current_cell.trim().to_owned();
let cell_text = if cell_text_raw.contains('\n') {
cell_text_raw.replace('\n', " ")
} else {
cell_text_raw
};
let cell_text = cell_text.trim().to_owned();
let allow_pipes = ts.had_nested_table;
ts.had_nested_table = false;
if !is_implicit && !allow_pipes && cell_text.contains('|') {
return Err(BailReason::TableBlockChildInCell);
}
ts.pending_single_cell_nested_table = allow_pipes && ts.current_row.is_empty();
let colspan = ts.current_cell_colspan;
ts.current_row.push((cell_text, colspan));
ts.current_cell.clear();
ts.current_cell_colspan = 1;
Ok(())
}
fn ends_with_ordered_marker(s: &str) -> bool {
let bytes = s.as_bytes();
let len = bytes.len();
if len < 3 || bytes[len - 1] != b' ' {
return false;
}
let punct = bytes[len - 2];
if punct != b'.' && punct != b')' {
return false;
}
let mut i = len - 2;
while i > 0 && bytes[i - 1].is_ascii_digit() {
i -= 1;
}
i < len - 2 && (i == 0 || !bytes[i - 1].is_ascii_digit())
}
fn output_ends_with_inline_close_marker(output: &str) -> bool {
if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
return false;
}
if output.ends_with("**") || output.ends_with('`') || output.ends_with(')') {
return true;
}
output.ends_with('*') && !output.ends_with("**")
}
fn output_ends_with_inline_text(output: &str) -> bool {
if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
return false;
}
!output_ends_with_inline_close_marker(output)
}
fn separate_inline_after_block(state: &mut Tier1State, br_in_tables: bool) -> Result<(), BailReason> {
if state.escape_ctx.contains(EscapeCtx::CODE) {
return Ok(());
}
if state.in_table_cell() {
let at = state.cell_or_output_mut().len();
separate_block_in_cell_at(state, at, br_in_tables);
return Ok(());
}
if state.list_continuation_indent_width() > 0 && !inside_stray_definition(state) {
return Err(BailReason::ListItemUnsupportedBlockChild);
}
if state.list_depth > 0 {
return Ok(());
}
let dest = state.cell_or_output_mut();
if dest.len() > 1 && dest.ends_with('\n') && !dest.ends_with("\n\n") {
dest.push('\n');
}
Ok(())
}
fn in_heading(state: &Tier1State) -> bool {
state
.stack
.iter()
.rev()
.take_while(|frame| !matches!(frame.spec.kind, TagKind::TableCell { .. }))
.any(|frame| matches!(frame.spec.kind, TagKind::Heading(_)))
}
fn is_inline_tag(name_lower: &[u8]) -> bool {
std::str::from_utf8(name_lower).is_ok_and(crate::converter::main_helpers::is_inline_element)
}
fn is_block_tag(name_lower: &[u8]) -> bool {
std::str::from_utf8(name_lower).is_ok_and(crate::converter::utility::content::is_block_level_element)
}