fn emit_svg_from_slice(
svg_slice: &str,
svg_start_offset: usize,
state: &mut Tier1State,
options: &ConversionOptions,
) -> Result<(), BailReason> {
if svg_slice.contains("<;
dest.push_str(&base64_svg);
dest.push(')');
Ok(())
}
fn holds_hidden_element(svg_slice: &str) -> bool {
use crate::converter::utility::preprocessing::{find_tag_end, tag_has_hidden_attribute, tag_has_hidden_style};
let mut from = 1;
while let Some(start) = svg_slice
.get(from..)
.and_then(|rest| rest.find('<'))
.map(|at| from + at)
{
let end = find_tag_end(svg_slice.as_bytes(), start + 1)
.unwrap_or(svg_slice.len())
.max(start + 1);
let tag = &svg_slice[start..end];
if tag_has_hidden_attribute(tag) || tag_has_hidden_style(tag) {
return true;
}
from = end;
}
false
}
fn find_svg_handle(dom: &tl::VDom<'_>) -> Option<tl::NodeHandle> {
dom.nodes().iter().enumerate().find_map(|(index, node)| {
let tl::Node::Tag(tag) = node else { return None };
tag.name()
.as_utf8_str()
.as_ref()
.eq_ignore_ascii_case("svg")
.then(|| tl::NodeHandle::new(index as u32))
})
}
#[inline]
const fn bail_unsupported(spec: &TagSpec, _offset: usize) -> Result<(), BailReason> {
match spec.kind {
TagKind::RawText(_) => Err(BailReason::Classifier),
TagKind::Media => Err(BailReason::Classifier),
TagKind::Ignored => Err(BailReason::Classifier),
_ => Ok(()),
}
}
fn block_container_is_passthrough(name_lower: &[u8]) -> bool {
matches!(name_lower, b"colgroup" | b"col" | b"base" | b"html" | b"body")
}
fn is_transparent_plain_form(name_lower: &[u8], options: &ConversionOptions) -> bool {
name_lower == b"form" && options.output_format == crate::options::OutputFormat::Plain
}
fn emit_open(
state: &mut Tier1State,
spec: &'static TagSpec,
name_lower: &[u8],
attrs: &[(&[u8], Option<&[u8]>)],
table_probes: &mut Vec<TableLayoutProbe>,
options: &ConversionOptions,
) -> Result<(), BailReason> {
prepare_open_state(state, spec, name_lower, options)?;
emit_open_kind(state, spec, name_lower, attrs, table_probes, options)
}
const fn is_block_open_kind(spec: &TagSpec) -> bool {
matches!(
spec.kind,
TagKind::Block
| TagKind::Paragraph
| TagKind::Heading(_)
| TagKind::Blockquote
| TagKind::Pre
| TagKind::List(_)
| TagKind::Table
| TagKind::Summary
| TagKind::DefinitionTerm
| TagKind::DefinitionDescription
)
}
fn validate_code_open(state: &Tier1State, spec: &TagSpec, is_link_block: bool) -> Result<(), BailReason> {
let in_code = state.escape_ctx.intersects(EscapeCtx::CODE | EscapeCtx::PRE);
if in_code && matches!(spec.kind, TagKind::Link) {
return Err(BailReason::Classifier);
}
if is_link_block
&& in_code
&& !state.escape_ctx.intersects(EscapeCtx::PRE | EscapeCtx::HEADING)
&& !state.in_table_cell()
{
return Err(BailReason::Classifier);
}
Ok(())
}
fn hand_over_link_or_form_group_in_code(
state: &Tier1State,
spec: &TagSpec,
name_lower: &[u8],
) -> Result<(), BailReason> {
if matches!(spec.kind, TagKind::Link) && state.escape_ctx.intersects(EscapeCtx::CODE | EscapeCtx::PRE) {
return Err(BailReason::Classifier);
}
if matches!(name_lower, b"fieldset" | b"legend")
&& state.escape_ctx.contains(EscapeCtx::CODE)
&& !state.escape_ctx.contains(EscapeCtx::PRE)
{
return Err(BailReason::Classifier);
}
Ok(())
}
fn prepare_open_state(
state: &mut Tier1State,
spec: &TagSpec,
name_lower: &[u8],
options: &ConversionOptions,
) -> Result<(), BailReason> {
hand_over_link_or_form_group_in_code(state, spec, name_lower)?;
if std::mem::take(&mut state.last_closed_list)
&& matches!(spec.kind, TagKind::Pre)
&& options.code_block_style == crate::options::CodeBlockStyle::Indented
&& !state.in_table_cell()
{
state.ensure_blank_line();
push_list_item_continuation_lines(state, "<!-- -->\n\n");
}
state.last_closed_custom_element = false;
state.last_emitted_was_img = false;
if std::mem::take(&mut state.last_closed_block) && is_inline_tag(name_lower) {
if state.in_table_cell() {
return Err(BailReason::TableBlockChildInCell);
}
separate_inline_after_block(state, options.br_in_tables)?;
}
if name_lower == b"q" || (name_lower == b"mark" && options.highlight_style != crate::options::HighlightStyle::None)
{
return Err(BailReason::InlineMarkerNotReproduced);
}
if matches!(
name_lower,
b"select" | b"option" | b"optgroup" | b"datalist" | b"button"
) {
return Err(BailReason::FormControl);
}
let is_link_block = is_block_open_kind(spec);
if is_link_block && state.stack.iter().any(|frame| matches!(frame.spec.kind, TagKind::Link)) {
return Err(BailReason::Classifier);
}
validate_code_open(state, spec, is_link_block)?;
let in_marks = |frame: &OpenTag| {
matches!(
frame.spec.kind,
TagKind::Strong | TagKind::Emphasis | TagKind::Strikethrough | TagKind::Inserted
)
};
if is_link_block && state.escape_ctx.contains(EscapeCtx::HEADING) && state.stack.iter().any(in_marks) {
return Err(BailReason::Classifier);
}
Ok(())
}
fn emit_open_kind(
state: &mut Tier1State,
spec: &TagSpec,
name_lower: &[u8],
attrs: &[(&[u8], Option<&[u8]>)],
table_probes: &mut Vec<TableLayoutProbe>,
options: &ConversionOptions,
) -> Result<(), BailReason> {
match spec.kind {
TagKind::Paragraph => open_paragraph(state, options.br_in_tables),
TagKind::Heading(_) => open_heading(state),
TagKind::Blockquote => {
if find_attr(attrs, b"cite").is_some_and(|value| !value.is_empty()) {
return Err(BailReason::BlockquoteCite);
}
open_blockquote(state);
}
TagKind::Pre => open_pre(state, attrs),
TagKind::List(ListKind::Definition) => open_dl(state),
TagKind::List(kind) => open_list(state, kind, options),
TagKind::ListItem => open_list_item(state, options),
TagKind::DefinitionTerm => open_dt(state),
TagKind::DefinitionDescription => open_dd(state),
TagKind::Strong => open_strong(state)?,
TagKind::Emphasis => open_emphasis(state)?,
TagKind::Strikethrough => open_marker(state, "~~")?,
TagKind::Inserted => {}
TagKind::Code if !state.escape_ctx.contains(EscapeCtx::PRE) && !state.escape_ctx.contains(EscapeCtx::CODE) => {}
TagKind::Code if state.pre_lang.is_none() && state.escape_ctx.contains(EscapeCtx::PRE) => {
if let Some(lang) = extract_language_from_class(attrs) {
state.pre_lang = Some(lang);
}
}
TagKind::Link => open_link(state),
TagKind::Table => open_table(state, attrs, table_probes),
TagKind::TableCaption => open_table_caption(state),
TagKind::TableHead => open_table_head(state)?,
TagKind::TableBody => open_table_body(state)?,
TagKind::TableFoot => open_table_foot(state),
TagKind::TableRow => open_table_row(state),
TagKind::TableCell { is_header } => open_table_cell(state, attrs, is_header, table_probes)?,
TagKind::Block => open_block_container(state, name_lower, options),
TagKind::Summary => open_summary_container(state, options.br_in_tables)?,
TagKind::Figcaption => open_figcaption(state),
TagKind::LineEndControl => open_line_end_control(state)?,
TagKind::Inline => {}
_ => {}
}
Ok(())
}
fn open_line_end_control(state: &Tier1State) -> Result<(), BailReason> {
if state.escape_ctx.intersects(EscapeCtx::CODE | EscapeCtx::PRE) {
return Err(BailReason::FormControl);
}
let in_inline_container = state.stack.iter().any(|frame| {
matches!(
frame.spec.kind,
TagKind::Heading(_) | TagKind::Summary | TagKind::Figcaption | TagKind::Link | TagKind::TableCaption
)
});
let in_inline_element = state
.stack
.last()
.is_some_and(|parent| crate::converter::form::spacing::line_goes_on_in(Some(parent.spec)));
if in_inline_container || in_inline_element {
return Err(BailReason::FormControl);
}
Ok(())
}
fn open_strong(state: &mut Tier1State) -> Result<(), BailReason> {
let suppressed = state.summary_at_top()
|| state.escape_ctx.contains(EscapeCtx::STRONG)
|| state.escape_ctx.contains(EscapeCtx::CODE)
|| state.escape_ctx.contains(EscapeCtx::PRE);
if suppressed {
return Ok(());
}
if state.cell_or_output_mut().ends_with("**") {
return Err(BailReason::AdjacentInlineEmphasis);
}
state.cell_or_output_mut().push_str("**");
Ok(())
}
fn open_emphasis(state: &mut Tier1State) -> Result<(), BailReason> {
if state.escape_ctx.intersects(EscapeCtx::CODE | EscapeCtx::PRE) {
return Ok(());
}
let output = state.cell_or_output_mut();
if output.ends_with('*') && !output.ends_with("**") {
return Err(BailReason::AdjacentInlineEmphasis);
}
output.push('*');
Ok(())
}
fn open_marker(state: &mut Tier1State, marker: &str) -> Result<(), BailReason> {
if state.escape_ctx.intersects(EscapeCtx::CODE | EscapeCtx::PRE) {
return Ok(());
}
if state.cell_or_output_mut().ends_with(marker) {
return Err(BailReason::AdjacentInlineEmphasis);
}
state.cell_or_output_mut().push_str(marker);
Ok(())
}
fn open_block_container(state: &mut Tier1State, name_lower: &[u8], options: &ConversionOptions) {
if block_container_is_passthrough(name_lower)
|| is_transparent_plain_form(name_lower, options)
|| start_line_in_pre(state, name_lower)
{
return;
}
if state.in_table_cell() {
break_cell_before_block(state, options.br_in_tables);
return;
}
let output = state.cell_or_output_mut();
if !output.is_empty() && !output.ends_with("\n\n") {
crate::converter::tier1::state::trim_trailing_horizontal(output);
output.push_str("\n\n");
}
}
fn open_summary_container(state: &mut Tier1State, br_in_tables: bool) -> Result<(), BailReason> {
if state.in_summary() {
return Err(BailReason::Classifier);
}
if state.in_table_cell() {
break_cell_before_block(state, br_in_tables);
}
open_summary(state);
Ok(())
}
fn break_cell_before_block(state: &mut Tier1State, br_in_tables: bool) {
if state.escape_ctx.contains(EscapeCtx::PRE) {
let should_break = {
let cell_buf = state.cell_or_output_mut();
!cell_buf.is_empty() && !cell_buf.ends_with('|') && !cell_buf.ends_with("<br>") && !cell_buf.ends_with('\n')
};
if should_break {
emit_tier1_table_cell_break(state, br_in_tables);
}
return;
}
with_cell_scratch(state, |cell_buf| {
if !cell_buf.is_empty() && !cell_buf.ends_with('|') && !cell_buf.ends_with("<br>") && !cell_buf.ends_with('\n')
{
crate::converter::main_helpers::emit_table_cell_break(cell_buf, br_in_tables);
}
});
}
fn emit_tier1_table_cell_break(state: &mut Tier1State, br_in_tables: bool) {
if br_in_tables && state.escape_ctx.contains(EscapeCtx::PRE) {
let offset = {
let output = state.cell_or_output_mut();
crate::converter::main_helpers::trim_trailing_whitespace(output);
output.len()
};
state.pre_cell_break_offsets.push(offset);
state.cell_or_output_mut().push('\n');
} else {
crate::converter::main_helpers::emit_table_cell_break(state.cell_or_output_mut(), br_in_tables);
}
}
fn open_paragraph(state: &mut Tier1State, br_in_tables: bool) {
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() {
if state.escape_ctx.contains(EscapeCtx::PRE) {
break_cell_before_block(state, br_in_tables);
return;
}
with_cell_scratch(state, |cell_buf| {
if !cell_buf.is_empty() && !cell_buf.ends_with("<br>") && !cell_buf.ends_with('\n') {
crate::converter::main_helpers::emit_table_cell_break(cell_buf, br_in_tables);
}
});
return;
}
let in_list_item = state
.stack
.iter()
.any(|frame| matches!(frame.spec.kind, TagKind::ListItem));
if in_list_item {
let dest = state.cell_or_output_mut();
if dest.ends_with("- ") || dest.ends_with("* ") || dest.ends_with("+ ") || ends_with_ordered_marker(dest) {
return;
}
}
let dest = state.cell_or_output_mut();
crate::converter::tier1::state::trim_trailing_horizontal(dest);
if !dest.is_empty() && !dest.ends_with("\n\n") {
dest.push_str("\n\n");
}
}
fn open_heading(state: &mut Tier1State) {
if state.in_table_cell() {
return;
}
ensure_blank_line_buf(state.cell_or_output_mut());
}
fn ensure_blank_line_buf(buf: &mut String) {
if buf.is_empty() {
return;
}
while buf.ends_with(' ') || buf.ends_with('\t') {
buf.pop();
}
if buf.ends_with("\n\n") {
return;
}
if buf.ends_with('\n') {
buf.push('\n');
} else {
buf.push_str("\n\n");
}
}
fn open_blockquote(state: &mut Tier1State) {
if state.escape_ctx.contains(EscapeCtx::BLOCKQUOTE) {
state.ensure_blank_line();
}
}
fn open_pre(state: &mut Tier1State, attrs: &[(&[u8], Option<&[u8]>)]) {
state.ensure_blank_line();
if state.in_table_cell() {
state.pre_cell_break_offsets.clear();
}
if let Some(lang) = extract_language_from_class(attrs) {
state.pre_lang = Some(lang);
}
}
fn extract_language_from_class(attrs: &[(&[u8], Option<&[u8]>)]) -> Option<String> {
let class_bytes = find_attr(attrs, b"class")?;
let class = decode_attr(class_bytes).ok()?;
for cls in class.split_ascii_whitespace() {
if let Some(rest) = cls.strip_prefix("language-") {
return Some(rest.to_owned());
}
if let Some(rest) = cls.strip_prefix("lang-") {
return Some(rest.to_owned());
}
}
None
}
fn strip_leading_bare_marker(text: &str) -> Option<&str> {
let digit_count = text.bytes().take_while(u8::is_ascii_digit).count();
if digit_count > 0 {
if let Some(rest) = text[digit_count..].strip_prefix(". ") {
return Some(rest);
}
}
let mut chars = text.chars();
let first = chars.next()?;
if matches!(first, '-' | '*' | '+') {
return chars.as_str().strip_prefix(' ');
}
None
}
fn inside_stray_definition(state: &Tier1State) -> bool {
for frame in state.stack.iter().rev() {
match frame.spec.kind {
TagKind::DefinitionTerm | TagKind::DefinitionDescription => return true,
TagKind::ListItem | TagKind::List(_) => return false,
_ => {}
}
}
false
}
fn line_is_bare_list_marker(output: &str) -> bool {
let line_start = output.rfind('\n').map_or(0, |pos| pos + 1);
let mut rest = output[line_start..].trim_start_matches([' ', '\t']);
if rest.is_empty() {
return false;
}
while let Some(next) = strip_leading_bare_marker(rest) {
if next.is_empty() {
return true;
}
rest = next;
}
false
}
fn open_list(state: &mut Tier1State, kind: ListKind, options: &ConversionOptions) {
if state.in_table_cell() {
with_cell_scratch(state, |cell_buf| {
if !cell_buf.is_empty()
&& !cell_buf.ends_with('|')
&& !cell_buf.ends_with(' ')
&& !cell_buf.ends_with("<br>")
{
if options.br_in_tables {
cell_buf.push_str("<br>");
} else {
cell_buf.push(' ');
}
}
});
state.list_depth = state.list_depth.saturating_add(1);
if matches!(kind, ListKind::Unordered) {
state.ul_depth = state.ul_depth.saturating_add(1);
}
return;
}
let current_list_depth = state.list_depth;
{
let dest = state.cell_or_output_mut();
if !dest.is_empty() {
if current_list_depth == 0 {
let needs_newline = !dest.ends_with("\n\n") && !line_is_bare_list_marker(dest);
if needs_newline {
dest.push_str("\n\n");
}
} else {
let needs_newline = !dest.ends_with('\n') && !line_is_bare_list_marker(dest);
if needs_newline {
crate::converter::tier1::state::trim_trailing_horizontal(dest);
dest.push('\n');
}
}
}
}
state.list_depth = state.list_depth.saturating_add(1);
if matches!(kind, ListKind::Unordered) {
state.ul_depth = state.ul_depth.saturating_add(1);
}
}
const TIER1_BULLETS: [u8; 3] = [b'-', b'*', b'+'];
fn open_list_item(state: &mut Tier1State, options: &ConversionOptions) {
if state.in_table_cell() {
if find_parent_list_kind(&state.stack) == Some(ListKind::Ordered) {
increment_ol_counter(&mut state.stack);
}
with_cell_scratch(state, |cell_buf| {
if !cell_buf.is_empty()
&& !cell_buf.ends_with('|')
&& !cell_buf.ends_with(' ')
&& !cell_buf.ends_with("<br>")
{
if options.br_in_tables {
cell_buf.push_str("<br>");
} else {
cell_buf.push(' ');
}
}
});
return;
}
let parent_kind = find_parent_list_kind(&state.stack);
let indent_depth = state.list_depth.saturating_sub(1);
let ordered_index = (parent_kind == Some(ListKind::Ordered)).then(|| {
let counter = increment_ol_counter(&mut state.stack);
find_ol_start(&state.stack).saturating_sub(1) + counter
});
let line_start = state.output.rfind('\n').map_or(0, |pos| pos + 1);
let after_text = !state.output[line_start..].trim().is_empty() && !line_is_bare_list_marker(&state.output);
state.list_items_after_text.push(after_text);
if after_text {
state.output.push('\n');
if ordered_index
.is_some_and(|index| !crate::converter::utility::escaping::line_opens_block(&format!("{index}. x")))
{
state.output.push('\n');
}
}
if indent_depth > 0 && (state.output.is_empty() || state.output.ends_with('\n')) {
push_list_item_indent(&mut state.output, indent_depth);
}
if let Some(index) = ordered_index {
let marker = format!("{index}. ");
state.list_item_marker_widths.push(marker.len());
state.output.push_str(&marker);
} else {
let bullet_idx = state.ul_depth.saturating_sub(1) as usize % TIER1_BULLETS.len();
state.list_item_marker_widths.push(2);
state.output.push(TIER1_BULLETS[bullet_idx] as char);
state.output.push(' ');
}
}
fn open_link(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.link_count += 1;
}
state.cell_or_output_mut().push('[');
}
#[derive(Debug, Clone, Copy, Default)]
struct TableLayoutProbe {
nested_table_count: usize,
has_span: bool,
border_zero: bool,
}
fn open_table(state: &mut Tier1State, attrs: &[(&[u8], Option<&[u8]>)], table_probes: &mut Vec<TableLayoutProbe>) {
let inline_mode = !state.table_stack.is_empty();
state.table_stack.push(crate::converter::tier1::state::TableState {
inline_mode,
..Default::default()
});
table_probes.push(TableLayoutProbe {
border_zero: find_attr(attrs, b"border").is_some_and(|value| value == b"0".as_slice()),
..TableLayoutProbe::default()
});
}
fn open_table_caption(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.caption_buf.clear();
ts.in_caption = true;
}
}
fn open_table_head(state: &mut Tier1State) -> Result<(), BailReason> {
if let Some(ts) = state.table_stack.last_mut() {
if ts.seen_tbody_close || ts.seen_tfoot {
return Err(BailReason::TableSectionOrder);
}
ts.in_thead = true;
}
Ok(())
}
fn open_table_body(state: &mut Tier1State) -> Result<(), BailReason> {
if let Some(ts) = state.table_stack.last_mut() {
if ts.seen_tfoot {
return Err(BailReason::TableSectionOrder);
}
}
Ok(())
}
fn open_table_foot(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.seen_tfoot = true;
}
}
fn open_table_row(state: &mut Tier1State) {
if let Some(ts) = state.table_stack.last_mut() {
ts.current_row.clear();
}
}
fn open_table_cell(
state: &mut Tier1State,
attrs: &[(&[u8], Option<&[u8]>)],
is_header: bool,
table_probes: &mut [TableLayoutProbe],
) -> Result<(), BailReason> {
let spanning = has_attr(attrs, b"colspan") || has_attr(attrs, b"rowspan");
if let Some(probe) = table_probes.last_mut() {
probe.has_span |= spanning;
}
let colspan = find_attr(attrs, b"colspan")
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(1)
.max(1);
if let Some(ts) = state.table_stack.last_mut() {
ts.current_cell.clear();
ts.in_cell = true;
ts.definition_in_cell = false;
ts.current_cell_colspan = colspan;
if is_header {
ts.has_th = true;
}
}
Ok(())
}