use crate::converter::block::container::HandlerContext;
const MAX_TABLE_COLS: usize = 1000;
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn get_colspan(node_handle: &tl::NodeHandle, parser: &tl::Parser) -> usize {
if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
if let Some(Some(bytes)) = tag.attributes().get("colspan") {
if let Ok(colspan) = bytes.as_utf8_str().parse::<usize>() {
return clamp_table_span(colspan);
}
}
}
1
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn get_colspan_rowspan(node_handle: &tl::NodeHandle, parser: &tl::Parser) -> (usize, usize) {
if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
let attrs = tag.attributes();
let colspan = attrs
.get("colspan")
.flatten()
.and_then(|v| v.as_utf8_str().parse::<usize>().ok())
.map_or(1, clamp_table_span);
let rowspan = attrs
.get("rowspan")
.flatten()
.and_then(|v| v.as_utf8_str().parse::<usize>().ok())
.map_or(1, clamp_table_span);
(colspan, rowspan)
} else {
(1, 1)
}
}
fn clamp_table_span(value: usize) -> usize {
if value == 0 { 1 } else { value.min(MAX_TABLE_COLS) }
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn collect_table_cells(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
dom_ctx: &super::super::super::DomContext,
ctx: &super::super::super::Context,
cells: &mut Vec<tl::NodeHandle>,
) {
cells.clear();
if ctx.excluded_node_ids.contains(&node_handle.get_inner()) {
return;
}
if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
let children = tag.children();
for child_handle in children.top().iter() {
if ctx.excluded_node_ids.contains(&child_handle.get_inner()) {
continue;
}
if let Some(cell_name) = dom_ctx.tag_name_for(*child_handle, parser) {
if matches!(cell_name.as_ref(), "th" | "td" | "cell") {
cells.push(*child_handle);
}
}
}
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn cell_text_content(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
options: &crate::options::ConversionOptions,
ctx: &super::super::super::Context,
dom_ctx: &super::super::super::DomContext,
depth: usize,
) -> String {
let cell_ctx = super::super::super::Context {
in_table_cell: true,
..ctx.clone()
};
render_cell_text(
node_handle,
parser,
HandlerContext::new(options, &cell_ctx, depth, dom_ctx),
None,
)
}
const CELL_TEXT_CAPACITY: usize = 128;
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn render_cell_text(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
handler: HandlerContext<'_>,
mut deferred_tables: Option<&mut Vec<String>>,
) -> String {
let mut text = String::with_capacity(CELL_TEXT_CAPACITY);
render_cell_content(node_handle, parser, &mut text, handler, &mut deferred_tables);
finalize_cell_text(text, handler.options)
}
fn render_cell_content(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
text: &mut String,
handler: HandlerContext<'_>,
deferred_tables: &mut Option<&mut Vec<String>>,
) {
let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
return;
};
let children = tag.children();
let has_tag_or_comment_child = children
.top()
.iter()
.any(|child_handle| matches!(child_handle.get(parser), Some(tl::Node::Tag(_) | tl::Node::Comment(_))));
if !has_tag_or_comment_child {
let raw = handler.dom_ctx.text_content(*node_handle, parser);
let normalized = if handler.options.whitespace_mode == crate::options::WhitespaceMode::Normalized {
crate::text::normalize_cell_whitespace_cow(raw.as_str())
} else {
crate::text::fold_cell_line_breaks_verbatim_cow(raw.as_str())
};
*text = escape_cell_text(normalized.as_ref(), handler.options);
return;
}
let cell_ctx = handler
.ctx
.for_cell(*node_handle, parser, handler.dom_ctx, handler.options.br_in_tables);
let handler = HandlerContext::new(handler.options, &cell_ctx, handler.depth, handler.dom_ctx);
let mut table_ends = Vec::new();
for child_handle in children.top().iter() {
render_cell_child(child_handle, parser, text, handler, deferred_tables);
if deferred_tables.is_none() && super::utils::is_or_contains_table(child_handle, parser, handler.dom_ctx) {
table_ends.push(text.len());
}
}
separate_nested_table_following_content(text, &table_ends, handler.options.br_in_tables);
}
pub fn separate_nested_table_following_content(text: &mut String, table_ends: &[usize], br_in_tables: bool) {
if table_ends.is_empty() {
return;
}
let original = std::mem::take(text);
let mut start = 0;
let content_end = original.trim_end().len();
for &end in table_ends {
if end <= start {
continue;
}
let Some(piece) = original.get(start..end) else {
continue;
};
let Some(following) = original.get(end..) else { continue };
text.push_str(piece);
if end < content_end && !following.starts_with(char::is_whitespace) && !following.starts_with("<br>") {
text.push_str(if br_in_tables { "<br>" } else { " " });
}
start = end;
}
text.push_str(&original[start..]);
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn nested_table_width_text(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
dom_ctx: &super::super::super::DomContext,
ctx: &super::super::super::Context,
br_in_tables: bool,
) -> String {
let mut text = String::with_capacity(64);
let mut row_gap = false;
let mut cell_gap = false;
let mut stack = vec![*node_handle];
while let Some(handle) = stack.pop() {
if ctx.excluded_node_ids.contains(&handle.get_inner()) {
continue;
}
match handle.get(parser) {
Some(tl::Node::Raw(bytes)) => {
let raw = bytes.as_utf8_str();
let decoded = crate::text::decode_html_entities_cow(raw.as_ref());
if decoded.trim().is_empty() {
cell_gap |= !text.is_empty();
continue;
}
if text.is_empty() {
} else if row_gap {
crate::converter::emit_table_cell_break(&mut text, br_in_tables);
} else if cell_gap && !text.ends_with(char::is_whitespace) {
text.push(' ');
}
row_gap = false;
cell_gap = false;
text.push_str(decoded.as_ref());
}
Some(tl::Node::Tag(tag)) => {
row_gap |= super::utils::is_tag_name(&handle, parser, dom_ctx, "tr");
cell_gap |= ["td", "th"]
.iter()
.any(|name| super::utils::is_tag_name(&handle, parser, dom_ctx, name));
if let Some(children) = dom_ctx.children_of(handle.get_inner()) {
stack.extend(children.iter().rev().copied());
} else {
let first = stack.len();
stack.extend(tag.children().top().iter().copied());
stack[first..].reverse();
}
}
_ => {}
}
}
text
}
fn render_cell_child(
child_handle: &tl::NodeHandle,
parser: &tl::Parser,
text: &mut String,
handler: HandlerContext<'_>,
deferred_tables: &mut Option<&mut Vec<String>>,
) {
if !super::utils::is_or_contains_table(child_handle, parser, handler.dom_ctx) {
super::super::super::walk_node(
child_handle,
parser,
text,
crate::converter::block::container::HandlerContext::new(
handler.options,
handler.ctx,
handler.depth + 1,
handler.dom_ctx,
),
);
return;
}
let mut nested = String::new();
let nested_context = crate::converter::Context {
allow_nested_table_markup: deferred_tables.is_some(),
..handler.ctx.clone()
};
super::super::super::walk_node(
child_handle,
parser,
&mut nested,
crate::converter::block::container::HandlerContext::new(
handler.options,
&nested_context,
handler.depth + 1,
handler.dom_ctx,
),
);
if let Some(buf) = deferred_tables.as_deref_mut() {
let trimmed = nested.trim();
if !trimmed.is_empty() {
buf.push(trimmed.to_string());
}
return;
}
if nested.contains('|') {
nested = crate::converter::utility::escaping::escape_bare_pipes_outside_code_spans(&nested);
}
let nested = fold_nested_table_rows(&nested, handler.options.br_in_tables);
if !nested.is_empty() && !text.trim_end().is_empty() {
crate::converter::emit_table_cell_break(text, handler.options.br_in_tables);
}
text.push_str(&nested);
}
pub(super) fn finalize_cell_text(mut text: String, options: &crate::options::ConversionOptions) -> String {
trim_in_place(&mut text);
if text.contains('\n') {
text = text.replace('\n', " ");
}
if text.contains('|') {
match options.output_format {
crate::options::OutputFormat::Markdown => {
text = crate::converter::utility::escaping::escape_cell_pipes(&text).into_owned();
}
crate::options::OutputFormat::Djot => {
text = crate::converter::utility::escaping::escape_bare_pipes_outside_code_spans(&text);
}
crate::options::OutputFormat::Plain => {}
}
}
text
}
pub fn fold_nested_table_rows(nested: &str, br_in_tables: bool) -> String {
let separator = if br_in_tables { "<br>" } else { " " };
nested
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join(separator)
}
fn trim_in_place(text: &mut String) {
let end = text.trim_end().len();
text.truncate(end);
let start = text.len() - text.trim_start().len();
text.drain(..start);
}
fn escape_cell_text(text: &str, options: &crate::options::ConversionOptions) -> String {
let escaped = crate::text::escape(
text,
options.escape_misc,
options.escape_asterisks,
options.escape_underscores,
options.escape_ascii,
);
let escaped = if options.escape_misc || options.escape_ascii {
escaped.into_owned()
} else {
escaped.replace('|', r"\|")
};
crate::converter::utility::escaping::escape_djot_table_cell_literal(&escaped, options.output_format, true)
.into_owned()
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn convert_table_cell(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
output: &mut String,
handler: HandlerContext<'_>,
col_width: Option<usize>,
deferred_tables: Option<&mut Vec<String>>,
) {
let text = render_cell_text(node_handle, parser, handler, deferred_tables);
emit_cell_text(node_handle, parser, output, &text, col_width);
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn emit_cell_text(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
output: &mut String,
text: &str,
col_width: Option<usize>,
) {
let colspan = get_colspan(node_handle, parser);
output.push(' ');
output.push_str(text);
if let Some(width) = col_width {
let text_len = text.chars().count();
if text_len < width {
for _ in 0..(width - text_len) {
output.push(' ');
}
}
}
for _ in 0..colspan {
output.push_str(" |");
}
}
#[cfg(test)]
mod tests {
#[test]
fn rich_formatting_preserved_in_cells() {
let html = "<table><tr><th>H</th></tr><tr><td><strong>Bold</strong> and <em>italic</em></td></tr></table>";
let result = crate::convert(html, None).unwrap();
let content = result.content.unwrap_or_default();
assert!(
content.contains("**Bold**") || content.contains("__Bold__"),
"bold should be preserved: {content}"
);
assert!(
content.contains("*italic*") || content.contains("_italic_"),
"italic should be preserved: {content}"
);
}
}