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 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))
})
}
fn svg_title(handle: tl::NodeHandle, parser: &tl::Parser<'_>) -> String {
let Some(tl::Node::Tag(svg)) = handle.get(parser) else {
return String::from("SVG Image");
};
svg.children()
.top()
.iter()
.filter_map(|child| child.get(parser).and_then(tl::Node::as_tag))
.find(|tag| tag.name().as_utf8_str().as_ref().eq_ignore_ascii_case("title"))
.map_or_else(
|| String::from("SVG Image"),
|title| {
let text = title
.children()
.top()
.iter()
.filter_map(|child| child.get(parser).and_then(tl::Node::as_raw))
.map(|raw| raw.as_utf8_str())
.collect::<String>();
let trimmed = text.trim();
if trimmed.is_empty() {
String::from("SVG Image")
} else {
trimmed.to_owned()
}
},
)
}
fn find_raw_text_close(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<usize> {
let len = bytes.len();
let mut idx = open_end;
while idx < len {
match memchr3(b'<', b'<', b'<', &bytes[idx..]) {
Some(off) => idx += off,
None => return None,
}
if idx + 2 < len && bytes[idx + 1] == b'/' {
let after_slash = idx + 2;
if after_slash + tag_name.len() <= len
&& bytes[after_slash..after_slash + tag_name.len()].eq_ignore_ascii_case(tag_name)
{
let post_name = after_slash + tag_name.len();
if matches!(bytes.get(post_name), Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r')) {
return find_tag_end(bytes, post_name);
}
}
}
idx += 1;
}
None
}
fn find_tag_end(bytes: &[u8], start: usize) -> Option<usize> {
memchr::memchr(b'>', &bytes[start..]).map(|offset| start + offset + 1)
}
#[inline]
const fn bail_unsupported(spec: &TagSpec, _offset: usize) -> Result<(), BailReason> {
match spec.kind {
TagKind::RawText(_) => 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 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)
}
fn prepare_open_state(
state: &mut Tier1State,
spec: &TagSpec,
name_lower: &[u8],
options: &ConversionOptions,
) -> Result<(), BailReason> {
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);
}
let is_link_block = matches!(
spec.kind,
TagKind::Block
| TagKind::Paragraph
| TagKind::Heading(_)
| TagKind::Blockquote
| TagKind::Pre
| TagKind::List(_)
| TagKind::Table
| TagKind::Summary
);
if is_link_block && state.stack.iter().any(|frame| matches!(frame.spec.kind, TagKind::Link)) {
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 => open_marker(state, "==")?,
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.br_in_tables),
TagKind::Summary => open_summary_container(state, options.br_in_tables)?,
TagKind::Figcaption => open_figcaption(state),
TagKind::Button => {}
TagKind::Inline => {}
_ => {}
}
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], br_in_tables: bool) {
if block_container_is_passthrough(name_lower) {
return;
}
if state.in_table_cell() {
break_cell_before_block(state, 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.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(())
}