use crate::converter::block::container::HandlerContext;
use crate::converter::utility::content::normalized_tag_name;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use super::cell::{
cell_text_content, collect_table_cells, convert_table_cell, emit_cell_text, get_colspan_rowspan, render_cell_text,
};
const MAX_TABLE_COLS: usize = 1000;
const MAX_CELL_WIDTH: usize = 200;
pub struct CellTextCache {
entries: HashMap<u32, String>,
enabled: bool,
}
impl CellTextCache {
pub fn new(enabled: bool) -> Self {
Self {
entries: HashMap::new(),
enabled,
}
}
pub(super) const fn enable(&mut self) {
self.enabled = true;
}
pub(super) fn store(&mut self, node_id: u32, text: String) {
if self.enabled {
self.entries.insert(node_id, text);
}
}
pub(super) fn take(&mut self, node_id: u32) -> Option<String> {
if self.enabled {
self.entries.remove(&node_id)
} else {
None
}
}
}
#[derive(Default)]
pub struct RenderedWidths {
widths: Vec<usize>,
edits: Vec<WidthEdit>,
}
#[cfg(feature = "visitor")]
pub(super) struct RenderedWidthCheckpoint {
widths: Vec<usize>,
edits: usize,
}
enum WidthEdit {
Cell {
padding: Range<usize>,
column: usize,
text_len: usize,
},
Separator {
padding: Range<usize>,
columns: usize,
},
}
impl RenderedWidths {
#[cfg(feature = "visitor")]
pub(super) fn checkpoint(&self) -> RenderedWidthCheckpoint {
RenderedWidthCheckpoint {
widths: self.widths.clone(),
edits: self.edits.len(),
}
}
#[cfg(feature = "visitor")]
pub(super) fn rollback(&mut self, checkpoint: RenderedWidthCheckpoint) {
self.widths = checkpoint.widths;
self.edits.truncate(checkpoint.edits);
}
fn record_cell(&mut self, padding: Range<usize>, column: usize, text_len: usize) {
if column >= MAX_TABLE_COLS {
return;
}
if column >= self.widths.len() {
self.widths.resize(column + 1, 0);
}
self.widths[column] = self.widths[column].max(text_len.min(MAX_CELL_WIDTH));
self.edits.push(WidthEdit::Cell {
padding,
column,
text_len,
});
}
fn commit_row(&mut self, first_edit: usize, output_start: usize) {
for edit in &mut self.edits[first_edit..] {
let padding = match edit {
WidthEdit::Cell { padding, .. } | WidthEdit::Separator { padding, .. } => padding,
};
padding.start += output_start;
padding.end += output_start;
}
}
pub fn repad(self, output: &mut String, output_start: usize, options: &crate::options::ConversionOptions) {
if self.edits.is_empty() {
return;
}
let original = output.split_off(output_start);
output.reserve(original.len());
let mut copied = 0;
for edit in self.edits {
let padding = match &edit {
WidthEdit::Cell { padding, .. } | WidthEdit::Separator { padding, .. } => padding,
};
output.push_str(&original[copied..padding.start - output_start]);
copied = padding.end - output_start;
match edit {
WidthEdit::Cell { column, text_len, .. } => {
let width = self.widths.get(column).copied().unwrap_or(0);
output.extend(std::iter::repeat_n(' ', width.saturating_sub(text_len)));
}
WidthEdit::Separator { columns, .. } => {
emit_header_separator(output, options, columns, &self.widths);
}
}
}
output.push_str(&original[copied..]);
}
}
#[derive(Clone, Copy)]
pub struct RowEnv<'p> {
pub parser: &'p tl::Parser<'p>,
pub options: &'p crate::options::ConversionOptions,
pub ctx: &'p super::super::super::Context,
pub dom_ctx: &'p super::super::super::DomContext,
}
fn append_layout_cell_text(cell_handle: &tl::NodeHandle, row_text: &mut String, env: RowEnv<'_>, depth: usize) {
if env.ctx.excluded_node_ids.contains(&cell_handle.get_inner()) {
return;
}
let Some(tl::Node::Tag(cell_tag)) = cell_handle.get(env.parser) else {
return;
};
let cell_name: Cow<'_, str> = env.dom_ctx.tag_info(cell_handle.get_inner(), env.parser).map_or_else(
|| normalized_tag_name(cell_tag.name().as_utf8_str()).into_owned().into(),
|info| Cow::Borrowed(info.name.as_str()),
);
if !matches!(cell_name.as_ref(), "td" | "th" | "cell") {
return;
}
let mut cell_text = String::new();
let cell_allow_inline_images = true;
let cell_ctx = super::super::super::Context {
convert_as_inline: true,
in_layout_cell: true,
cell_allow_inline_images,
in_cell_of_inputs: super::scanner::cell_holds_only_inputs(
*cell_handle,
env.parser,
env.dom_ctx,
env.options.br_in_tables,
),
..env.ctx.clone()
};
let cell_children = cell_tag.children();
for cell_child in cell_children.top().iter() {
super::super::super::walk_node(
cell_child,
env.parser,
&mut cell_text,
crate::converter::block::container::HandlerContext::new(env.options, &cell_ctx, depth + 1, env.dom_ctx),
);
}
let cell_content = crate::text::normalize_whitespace_cow(&cell_text);
if !cell_content.trim().is_empty() {
if !row_text.is_empty() {
row_text.push(' ');
}
row_text.push_str(cell_content.trim());
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn append_layout_row(row_handle: &tl::NodeHandle, output: &mut String, env: RowEnv<'_>, depth: usize) {
if env.ctx.excluded_node_ids.contains(&row_handle.get_inner()) {
return;
}
let Some(tl::Node::Tag(row_tag)) = row_handle.get(env.parser) else {
return;
};
let mut row_text = String::new();
let row_children = row_tag.children();
for cell_handle in row_children.top().iter() {
append_layout_cell_text(cell_handle, &mut row_text, env, depth);
}
append_layout_text(output, &row_text, env.options, env.ctx);
}
pub(super) fn append_layout_text(
output: &mut String,
row_text: &str,
options: &crate::options::ConversionOptions,
ctx: &super::super::super::Context,
) {
let trimmed = row_text.trim();
if !trimmed.is_empty() {
if !output.is_empty() && !output.ends_with('\n') {
output.push('\n');
}
let marker = layout_row_bullet(options, ctx);
let formatted = strip_leading_bullet(trimmed, options);
output.push(marker);
output.push(' ');
output.push_str(formatted);
output.push('\n');
}
}
fn layout_row_bullet(options: &crate::options::ConversionOptions, ctx: &super::super::super::Context) -> char {
let bullets: Vec<char> = options.bullets.chars().collect();
if bullets.is_empty() {
return '*';
}
bullets[ctx.ul_depth % bullets.len()]
}
fn strip_leading_bullet<'a>(trimmed: &'a str, options: &crate::options::ConversionOptions) -> &'a str {
for bullet in options.bullets.chars().chain(['-', '*', '+']) {
let mut marker = String::with_capacity(2);
marker.push(bullet);
marker.push(' ');
if let Some(rest) = trimmed.strip_prefix(marker.as_str()) {
return rest.trim_start();
}
}
trimmed
}
fn skip_rowspan_columns(col: &mut usize, rowspan_tracker: &mut [Option<usize>]) {
while *col < rowspan_tracker.len() {
let Some(Some(remaining)) = rowspan_tracker.get_mut(*col) else {
break;
};
if *remaining == 0 {
break;
}
*remaining -= 1;
if *remaining == 0 {
rowspan_tracker[*col] = None;
}
*col += 1;
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn collect_row_cell_widths(
node_handle: &tl::NodeHandle,
env: RowEnv<'_>,
col_widths: &mut Vec<usize>,
rowspan_tracker: &mut Vec<Option<usize>>,
cell_cache: &mut CellTextCache,
depth: usize,
) {
let mut cells = Vec::new();
collect_table_cells(node_handle, env.parser, env.dom_ctx, env.ctx, &mut cells);
let mut col = 0usize;
let mut cell_iter = cells.iter();
loop {
skip_rowspan_columns(&mut col, rowspan_tracker);
let Some(cell_handle) = cell_iter.next() else {
break;
};
let text = cell_text_content(cell_handle, env.parser, env.options, env.ctx, env.dom_ctx, depth + 1);
let width = text.chars().count().min(MAX_CELL_WIDTH);
cell_cache.store(cell_handle.get_inner(), text);
if col >= col_widths.len() {
col_widths.resize(col + 1, 0);
}
if width > col_widths[col] {
col_widths[col] = width;
}
let (colspan, rowspan) = get_colspan_rowspan(cell_handle, env.parser);
if rowspan > 1 {
if col >= rowspan_tracker.len() {
rowspan_tracker.resize(col + 1, None);
}
rowspan_tracker[col] = Some(rowspan - 1);
}
col = col.saturating_add(colspan);
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn emit_row_cell(
cell_handle: &tl::NodeHandle,
row_text: &mut String,
env: RowEnv<'_>,
emission: CellEmission,
render: &mut RowRender<'_>,
is_single_cell_row: bool,
) {
let deferred_tables = is_single_cell_row.then_some(&mut *render.deferred_tables);
if let Some(widths) = render.rendered_widths.as_deref_mut() {
let text = render.cell_cache.take(cell_handle.get_inner()).unwrap_or_else(|| {
render_cell_text(
cell_handle,
env.parser,
HandlerContext::new(env.options, env.ctx, emission.depth, env.dom_ctx),
deferred_tables,
)
});
let text_len = text.chars().count();
let padding_start = row_text.len() + 1 + text.len();
emit_cell_text(cell_handle, env.parser, row_text, &text, emission.col_width);
let old_padding = emission.col_width.unwrap_or(0).saturating_sub(text_len);
widths.record_cell(padding_start..padding_start + old_padding, emission.column, text_len);
return;
}
if let Some(text) = render.cell_cache.take(cell_handle.get_inner()) {
emit_cell_text(cell_handle, env.parser, row_text, &text, emission.col_width);
} else {
convert_table_cell(
cell_handle,
env.parser,
row_text,
HandlerContext::new(env.options, env.ctx, emission.depth, env.dom_ctx),
emission.col_width,
deferred_tables,
);
}
}
#[derive(Clone, Copy)]
struct CellEmission {
col_width: Option<usize>,
depth: usize,
column: usize,
}
const MIN_SEPARATOR_DASHES: usize = 3;
fn emit_rowspan_continuation(
col_index: &mut usize,
total_cols: usize,
rowspan_tracker: &mut [Option<usize>],
col_widths: &[usize],
row_text: &mut String,
rendered_widths: Option<&mut RenderedWidths>,
) -> bool {
if *col_index >= total_cols {
return false;
}
let Some(Some(remaining_rows)) = rowspan_tracker.get_mut(*col_index) else {
return false;
};
if *remaining_rows == 0 {
return false;
}
let width = col_widths.get(*col_index).copied();
let padding_start = row_text.len() + 1;
row_text.push(' ');
if let Some(w) = width {
for _ in 0..w {
row_text.push(' ');
}
}
row_text.push_str(" |");
if let Some(widths) = rendered_widths {
widths.record_cell(padding_start..padding_start + width.unwrap_or(0), *col_index, 0);
}
*remaining_rows -= 1;
if *remaining_rows == 0 {
rowspan_tracker[*col_index] = None;
}
*col_index += 1;
true
}
#[cfg(feature = "visitor")]
fn run_row_visitor_hook(node_handle: &tl::NodeHandle, output: &mut String, visit: RowVisit<'_>) -> Option<bool> {
visit.env.ctx.visitor.as_ref()?;
let cell_contents = visitor_cell_contents(visit);
run_row_visitor_with_contents(node_handle, output, visit, &cell_contents)
}
#[cfg(feature = "visitor")]
pub(super) fn run_row_visitor_with_contents(
node_handle: &tl::NodeHandle,
output: &mut String,
visit: RowVisit<'_>,
cell_contents: &[String],
) -> Option<bool> {
use crate::visitor::{NodeContext, NodeType, VisitResult};
let visitor_handle = visit.env.ctx.visitor.as_ref()?;
let tl::Node::Tag(tag) = node_handle.get(visit.env.parser)? else {
return None;
};
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::TableRow,
Cow::Borrowed("tr"),
tag,
visit.depth,
visit.row_index,
Some(Cow::Borrowed("table")),
false,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_table_row(&node_ctx, cell_contents, visit.is_header)
};
match visit_result {
VisitResult::Continue => None,
VisitResult::Skip => Some(true),
VisitResult::Custom(custom) => {
output.push_str(&custom);
Some(true)
}
VisitResult::Error(err) => {
if visit.env.ctx.visitor_error.borrow().is_none() {
*visit.env.ctx.visitor_error.borrow_mut() = Some(err);
}
Some(true)
}
VisitResult::PreserveHtml => {
output.push_str(&super::super::super::serialize_node(node_handle, visit.env.parser));
Some(true)
}
}
}
#[cfg(feature = "visitor")]
#[derive(Clone, Copy)]
pub(super) struct RowVisit<'a> {
pub(super) env: RowEnv<'a>,
pub(super) cells: &'a [tl::NodeHandle],
pub(super) row_index: usize,
pub(super) is_header: bool,
pub(super) depth: usize,
}
#[cfg(feature = "visitor")]
fn visitor_cell_contents(visit: RowVisit<'_>) -> Vec<String> {
let mut collect_ctx = super::super::super::Context {
in_table_cell: true,
..visit.env.ctx.clone()
};
#[cfg(feature = "metadata")]
{
collect_ctx.metadata_collector = None;
}
collect_ctx.structure_collector = None;
#[cfg(feature = "inline-images")]
{
collect_ctx.inline_collector = None;
}
visit
.cells
.iter()
.map(|cell_handle| visitor_cell_text(cell_handle, visit.env, &collect_ctx, visit.depth))
.collect()
}
#[cfg(feature = "visitor")]
fn visitor_cell_text(
cell_handle: &tl::NodeHandle,
env: RowEnv<'_>,
collect_ctx: &super::super::super::Context,
depth: usize,
) -> String {
let mut text = String::new();
if let Some(tl::Node::Tag(tag)) = cell_handle.get(env.parser) {
let cell_ctx = collect_ctx.for_cell(*cell_handle, env.parser, env.dom_ctx, env.options.br_in_tables);
for child_handle in tag.children().top().iter() {
super::super::super::walk_node(
child_handle,
env.parser,
&mut text,
crate::converter::block::container::HandlerContext::new(env.options, &cell_ctx, depth + 1, env.dom_ctx),
);
}
}
crate::text::normalize_whitespace_cow(&text).trim().to_string()
}
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn convert_table_row(
node_handle: &tl::NodeHandle,
output: &mut String,
env: RowEnv<'_>,
render: &mut RowRender<'_>,
) -> bool {
let mut row_text = String::with_capacity(256);
let mut cells = Vec::new();
collect_table_cells(node_handle, env.parser, env.dom_ctx, env.ctx, &mut cells);
let is_single_cell_row = cells.len() == 1;
if cells.is_empty() {
return false;
}
#[cfg(feature = "visitor")]
let visitor_output_start = output.len();
#[cfg(feature = "visitor")]
if !render.visitor_is_complete {
if let Some(early_return) = run_row_visitor_hook(
node_handle,
output,
RowVisit {
env,
cells: &cells,
row_index: render.row_index,
is_header: render.is_header,
depth: render.depth,
},
) {
*render.has_content |= output.len() > visitor_output_start;
return early_return;
}
}
let cell_ctx = super::super::super::Context {
in_table_cell: true,
..env.ctx.clone()
};
let row_env = RowEnv { ctx: &cell_ctx, ..env };
let first_width_edit = render.rendered_widths.as_ref().map_or(0, |widths| widths.edits.len());
let mut filled_cols = render_row_cells(&cells, &mut row_text, row_env, render, is_single_cell_row);
*render.has_content |= row_text.chars().any(|ch| ch != '|' && !ch.is_whitespace());
pad_row(
&mut row_text,
&mut filled_cols,
render.total_cols,
render.col_widths,
render.rendered_widths.as_deref_mut(),
);
append_rendered_row(output, &row_text, env.options, render, first_width_edit);
true
}
fn append_rendered_row(
output: &mut String,
row_text: &str,
options: &crate::options::ConversionOptions,
render: &mut RowRender<'_>,
first_width_edit: usize,
) {
if let Some(widths) = render.rendered_widths.as_deref_mut() {
widths.commit_row(first_width_edit, output.len() + 1);
}
output.push('|');
output.push_str(row_text);
output.push('\n');
if render.row_index == 0 {
let separator_start = output.len();
emit_header_separator(output, options, render.header_cols, render.col_widths);
if let Some(widths) = render.rendered_widths.as_deref_mut() {
widths.edits.push(WidthEdit::Separator {
padding: separator_start..output.len(),
columns: render.header_cols,
});
}
}
}
pub struct RowRender<'a> {
pub visitor_is_complete: bool,
pub row_index: usize,
pub has_content: &'a mut bool,
pub has_span: bool,
pub rowspan_tracker: &'a mut [Option<usize>],
pub total_cols: usize,
pub header_cols: usize,
pub depth: usize,
pub is_header: bool,
pub col_widths: &'a [usize],
pub cell_cache: &'a mut CellTextCache,
pub deferred_tables: &'a mut Vec<String>,
pub rendered_widths: Option<&'a mut RenderedWidths>,
}
fn render_row_cells(
cells: &[tl::NodeHandle],
row_text: &mut String,
env: RowEnv<'_>,
render: &mut RowRender<'_>,
is_single_cell_row: bool,
) -> usize {
if !render.has_span {
for (cell_index, cell_handle) in cells.iter().enumerate() {
emit_row_cell(
cell_handle,
row_text,
env,
CellEmission {
col_width: render.col_widths.get(cell_index).copied(),
depth: render.depth + 1,
column: cell_index,
},
render,
is_single_cell_row,
);
}
return cells.len();
}
render_spanned_row(cells, row_text, env, render, is_single_cell_row)
}
fn render_spanned_row(
cells: &[tl::NodeHandle],
row_text: &mut String,
env: RowEnv<'_>,
render: &mut RowRender<'_>,
is_single_cell_row: bool,
) -> usize {
let mut col_index = 0;
let mut cell_iter = cells.iter();
loop {
if emit_rowspan_continuation(
&mut col_index,
render.total_cols,
render.rowspan_tracker,
render.col_widths,
row_text,
render.rendered_widths.as_deref_mut(),
) {
continue;
}
let Some(cell_handle) = cell_iter.next() else {
break;
};
emit_row_cell(
cell_handle,
row_text,
env,
CellEmission {
col_width: render.col_widths.get(col_index).copied(),
depth: render.depth + 1,
column: col_index,
},
render,
is_single_cell_row,
);
let (colspan, rowspan) = get_colspan_rowspan(cell_handle, env.parser);
if rowspan > 1 && col_index < render.total_cols {
render.rowspan_tracker[col_index] = Some(rowspan - 1);
}
col_index = col_index.saturating_add(colspan);
}
col_index
}
fn pad_row(
row_text: &mut String,
filled_cols: &mut usize,
total_cols: usize,
col_widths: &[usize],
mut rendered_widths: Option<&mut RenderedWidths>,
) {
while *filled_cols < total_cols {
let width = col_widths.get(*filled_cols).copied();
let padding_start = row_text.len() + 1;
row_text.push(' ');
if let Some(width) = width {
row_text.extend(std::iter::repeat_n(' ', width));
}
row_text.push_str(" |");
if let Some(widths) = rendered_widths.as_deref_mut() {
widths.record_cell(padding_start..padding_start + width.unwrap_or(0), *filled_cols, 0);
}
*filled_cols += 1;
}
}
fn emit_header_separator(
output: &mut String,
options: &crate::options::ConversionOptions,
header_cols: usize,
col_widths: &[usize],
) {
let total_cols = header_cols.clamp(1, MAX_TABLE_COLS);
let is_djot = options.output_format == crate::options::OutputFormat::Djot;
output.push('|');
if !is_djot {
output.push(' ');
}
for index in 0..total_cols {
if index > 0 {
output.push_str(if is_djot { "|" } else { " | " });
}
let dash_count = col_widths.get(index).copied().unwrap_or(0).max(MIN_SEPARATOR_DASHES);
output.extend(std::iter::repeat_n('-', dash_count));
}
if !is_djot {
output.push(' ');
}
output.push_str("|\n");
}
#[cfg(test)]
mod width_tests {
use super::{MAX_CELL_WIDTH, MAX_TABLE_COLS, RenderedWidths};
#[test]
fn should_limit_recorded_widths_and_padding_to_supported_columns() {
let mut widths = RenderedWidths::default();
widths.record_cell(0..0, MAX_TABLE_COLS - 1, MAX_CELL_WIDTH + 1);
assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
assert_eq!(widths.widths[MAX_TABLE_COLS - 1], MAX_CELL_WIDTH);
assert_eq!(widths.edits.len(), 1);
widths.record_cell(0..0, MAX_TABLE_COLS, 1);
assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
assert_eq!(widths.edits.len(), 1);
widths.record_cell(0..0, usize::MAX, 1);
assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
assert_eq!(widths.edits.len(), 1);
}
}