fn escape_backslash_run(buffer: &mut String, from: usize, run_ends_at_last_byte: bool) {
if memchr::memchr(b'\\', &buffer.as_bytes()[from..]).is_none() {
return;
}
let run = buffer[from..].to_owned();
let run_end = if run_ends_at_last_byte {
run.len()
} else {
run.trim_end().len()
};
let bytes = &run.as_bytes()[..run_end];
let mut rewritten = String::with_capacity(run.len() + 4);
let mut copied_to = 0usize;
for i in memchr::memchr_iter(b'\\', bytes) {
if crate::text::backslash_needs_escape(bytes, i) {
rewritten.push_str(&run[copied_to..i]);
rewritten.push_str(r"\\");
copied_to = i + 1;
}
}
rewritten.push_str(&run[copied_to..]);
buffer.truncate(from);
buffer.push_str(&rewritten);
}
fn decode_entities_into(
out: &mut String,
s: &str,
base_offset: usize,
context: ReferenceContext,
) -> Result<(), BailReason> {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if let Some(pos) = memchr::memchr(b'&', &bytes[i..]) {
let amp_pos = i + pos;
if amp_pos > i {
out.push_str(&s[i..amp_pos]);
}
i = decode_entity_at(bytes, s, amp_pos, out, base_offset, context)?;
} else {
if i < bytes.len() {
out.push_str(&s[i..]);
}
break;
}
}
Ok(())
}
fn decode_and_collapse_into(
out: &mut String,
s: &str,
has_entities: bool,
base_offset: usize,
) -> Result<(), BailReason> {
decode_and_collapse_into_inner(out, s, has_entities, base_offset, false)
}
fn decode_and_collapse_into_inline(
out: &mut String,
s: &str,
has_entities: bool,
base_offset: usize,
) -> Result<(), BailReason> {
decode_and_collapse_into_inner(out, s, has_entities, base_offset, true)
}
fn decode_and_collapse_into_inner(
out: &mut String,
s: &str,
has_entities: bool,
base_offset: usize,
collapse_newlines: bool,
) -> Result<(), BailReason> {
let bytes = s.as_bytes();
let mut i = 0;
let mut prev_was_space = !crate::converter::utility::white_space::space_is_owed(out);
let mut at_line_start = false;
while i < bytes.len() {
let Some(pos) = next_special_byte(bytes, i, has_entities, collapse_newlines) else {
out.push_str(&s[i..]);
break;
};
if pos > i {
out.push_str(&s[i..pos]);
prev_was_space = false;
at_line_start = !collapse_newlines && bytes[pos - 1] == b'\n';
}
let (special, next) = match bytes[pos] {
b'&' => match crate::text::decode_character_reference(s, pos, ReferenceContext::Text) {
Some((end, decoded @ (' ' | '\t' | '\n'), None))
if bytes[end - 1] == b';' && (decoded != '\n' || collapse_newlines) =>
{
(decoded as u8, end)
}
_ => (b'&', pos),
},
byte => (byte, pos + 1),
};
match special {
b' ' | b'\t' if at_line_start => {}
b' ' | b'\t' | b'\n' => {
if !prev_was_space {
out.push(' ');
}
prev_was_space = true;
}
b'&' => {
prev_was_space = false;
at_line_start = false;
i = decode_entity_at(bytes, s, pos, out, base_offset, ReferenceContext::Text)?;
continue;
}
_ => unreachable!(),
}
i = next;
}
Ok(())
}
fn next_special_byte(bytes: &[u8], from: usize, has_entities: bool, collapse_newlines: bool) -> Option<usize> {
let rest = &bytes[from..];
let pos = match (has_entities, collapse_newlines) {
(true, true) => {
let space = memchr3(b' ', b'\t', b'\n', rest);
let entity = memchr::memchr(b'&', rest);
match (space, entity) {
(Some(a), Some(b)) => Some(a.min(b)),
(Some(a), None) | (None, Some(a)) => Some(a),
(None, None) => None,
}
}
(true, false) => memchr3(b' ', b'\t', b'&', rest),
(false, true) => memchr3(b' ', b'\t', b'\n', rest),
(false, false) => memchr::memchr2(b' ', b'\t', rest),
};
pos.map(|pos| from + pos)
}
fn trim_leading_text_whitespace(raw: &str) -> &str {
const WHITESPACE: [char; 4] = [' ', '\t', '\n', '\r'];
let mut rest = raw.trim_start_matches(WHITESPACE);
while rest.starts_with('&') {
match crate::text::decode_character_reference(rest, 0, ReferenceContext::Text) {
Some((end, first, None)) if rest.as_bytes()[end - 1] == b';' && WHITESPACE.contains(&first) => {
rest = rest[end..].trim_start_matches(WHITESPACE);
}
_ => break,
}
}
rest
}
fn source_starts_with_unicode_space(raw: &str) -> bool {
let mut rest = raw;
loop {
let Some(first) = rest.chars().next() else {
return false;
};
let (character, end) = if first == '&' {
match crate::text::decode_character_reference(rest, 0, ReferenceContext::Text) {
Some((end, decoded, None)) if rest.as_bytes()[end - 1] == b';' => (decoded, end),
_ => return false,
}
} else {
(first, first.len_utf8())
};
if !character.is_whitespace() {
return false;
}
if crate::text::is_unicode_space(character) {
return true;
}
rest = &rest[end..];
}
}
fn hand_over_unicode_space_after_space(
state: &mut Tier1State,
raw: &str,
base_offset: usize,
) -> Result<(), BailReason> {
if state.escape_ctx.intersects(EscapeCtx::PRE | EscapeCtx::CODE) || !source_starts_with_unicode_space(raw) {
return Ok(());
}
let in_label = state.link_stack.iter().any(|(href, ..)| href.is_some());
let in_empty_address_link = state.link_stack.iter().any(|(href, ..)| href.as_deref() == Some(""));
let place = state
.text_place
.and_then(|(offset, place)| (offset == base_offset).then_some(place));
let in_heading = state.escape_ctx.contains(EscapeCtx::HEADING);
let in_cell = state.in_table_cell();
let written = state.cell_or_output_mut();
let after_heading_break = in_heading && (written.ends_with(" \n") || written.ends_with("\\\n"));
let after_hard_break = !in_heading
&& !in_cell
&& (written.ends_with(" \n") || written.ends_with("\\\n"))
&& (in_empty_address_link
|| !crate::converter::utility::white_space::is_blank(crate::text::decode_html_entities_cow(raw).as_ref()));
if after_hard_break {
return Err(BailReason::UnicodeSpaceAfterSpace);
}
if in_label {
return Ok(());
}
if (written.ends_with(' ') || after_heading_break)
&& place.is_none_or(|place| unicode_space_is_kept(written, place) || is_blank_after_text(place, raw))
{
return Err(BailReason::UnicodeSpaceAfterSpace);
}
Ok(())
}
fn is_blank_after_text(place: TextPlace, raw: &str) -> bool {
place == TextPlace::AfterText
&& crate::converter::utility::white_space::is_blank(&crate::text::decode_html_entities_cow(raw))
}
fn decode_entity_at(
bytes: &[u8],
s: &str,
amp_pos: usize,
out: &mut String,
base_offset: usize,
context: ReferenceContext,
) -> Result<usize, BailReason> {
let amp = amp_pos;
let name_len = bytes[amp + 1..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric())
.count();
let name_end = amp + 1 + name_len;
if bytes.get(name_end) == Some(&b';') && decode_entity_into(out, &s[amp + 1..name_end]) {
return Ok(name_end + 1);
}
match crate::text::decode_character_reference(s, amp, context) {
Some((reference_end, first, second)) if bytes[reference_end - 1] == b';' => {
out.push(first);
if let Some(second) = second {
out.push(second);
}
Ok(reference_end)
}
Some((reference_end, ..)) => Err(BailReason::UnknownEntity {
name: s[amp + 1..reference_end].into(),
offset: base_offset + amp,
}),
None => {
out.push('&');
Ok(amp + 1)
}
}
}
#[inline]
fn apply_open_escape_ctx(state: &mut Tier1State, spec: &TagSpec) {
if spec.kind == TagKind::Pre {
state.escape_ctx |= EscapeCtx::PRE | EscapeCtx::CODE;
return;
}
let bit = match spec.kind {
TagKind::Code => EscapeCtx::CODE,
TagKind::Link => EscapeCtx::LINK,
TagKind::Blockquote => EscapeCtx::BLOCKQUOTE,
TagKind::Heading(_) => EscapeCtx::HEADING,
TagKind::Strong => EscapeCtx::STRONG,
_ => return,
};
state.escape_ctx |= bit;
}
fn has_attr(attrs: &[(&[u8], Option<&[u8]>)], key: &[u8]) -> bool {
attrs.iter().any(|(k, _)| k.eq_ignore_ascii_case(key))
}
fn find_attr<'a>(attrs: &[(&'a [u8], Option<&'a [u8]>)], key: &[u8]) -> Option<&'a [u8]> {
for (k, v) in attrs {
if k.eq_ignore_ascii_case(key) {
return *v;
}
}
None
}
const fn is_preprocessing_skip_candidate(name_lower: &[u8]) -> bool {
matches!(name_lower, b"nav" | b"header" | b"footer" | b"aside" | b"form")
}
fn should_skip_preprocessing(
name_lower: &[u8],
attrs: &[(&[u8], Option<&[u8]>)],
options: &ConversionOptions,
is_page_header: bool,
) -> bool {
use crate::options::PreprocessingPreset;
if !options.preprocessing.enabled {
return false;
}
if options.preprocessing.preset == PreprocessingPreset::Minimal {
return false;
}
if options.preprocessing.remove_forms && name_lower == b"form" {
return true;
}
if !options.preprocessing.remove_navigation {
return false;
}
if name_lower == b"nav" {
return true;
}
if name_lower == b"header" && is_page_header {
return true;
}
if matches!(name_lower, b"header" | b"footer" | b"aside") {
return byte_attrs_have_navigation_hint(attrs);
}
false
}
fn header_is_page_level(state: &Tier1State, html: &str) -> bool {
let mut in_document_body = false;
for frame in &state.stack {
let Some(name) = html.as_bytes().get(frame.name_range.clone()) else {
continue;
};
if matches_ignore_ascii_case(name, &[b"article", b"section", b"main"]) {
return false;
}
in_document_body |= name.eq_ignore_ascii_case(b"body");
}
in_document_body
}
fn matches_ignore_ascii_case(value: &[u8], candidates: &[&[u8]]) -> bool {
candidates.iter().any(|candidate| value.eq_ignore_ascii_case(candidate))
}
fn byte_attrs_have_navigation_hint(attrs: &[(&[u8], Option<&[u8]>)]) -> bool {
if let Some(role) = find_attr(attrs, b"role") {
let role_lc = role.to_ascii_lowercase();
if matches!(role_lc.as_slice(), b"navigation" | b"menubar" | b"tablist" | b"toolbar") {
return true;
}
}
if let Some(label) = find_attr(attrs, b"aria-label") {
let label_lc = label.to_ascii_lowercase();
const ARIA_SUBSTRINGS: &[&[u8]] = &[b"navigation", b"menu", b"contents", b"table of contents", b"toc"];
if ARIA_SUBSTRINGS
.iter()
.any(|sub| label_lc.windows(sub.len()).any(|w| w == *sub))
{
return true;
}
}
for attr_name in [b"class".as_slice(), b"id".as_slice()] {
if let Some(value) = find_attr(attrs, attr_name) {
if byte_value_has_nav_keyword(value) {
return true;
}
}
}
false
}
fn byte_value_has_nav_keyword(value: &[u8]) -> bool {
let mut start = 0;
let len = value.len();
loop {
while start < len && value[start].is_ascii_whitespace() {
start += 1;
}
if start >= len {
break;
}
let mut end = start;
while end < len && !value[end].is_ascii_whitespace() {
end += 1;
}
let token_bytes = &value[start..end];
let mut buf = [0u8; 64];
let normalised: &[u8] = if token_bytes.len() <= buf.len() {
let n = token_bytes.len();
for (i, &b) in token_bytes.iter().enumerate() {
buf[i] = match b {
b'_' | b':' | b'.' | b'/' => b'-',
_ => b.to_ascii_lowercase(),
};
}
&buf[..n]
} else {
start = end;
continue;
};
if NAV_KEYWORDS.iter().any(|kw| kw.as_bytes() == normalised) {
return true;
}
start = end;
}
false
}
fn extract_link_attrs(attrs: &[(&[u8], Option<&[u8]>)]) -> Result<(Option<String>, Option<String>), BailReason> {
let href = find_attr(attrs, b"href").map(decode_attr).transpose()?;
let title = find_attr(attrs, b"title").map(decode_attr).transpose()?;
Ok((href, title))
}
fn extract_ol_start(attrs: &[(&[u8], Option<&[u8]>)]) -> u16 {
find_attr(attrs, b"start")
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(1)
}
fn decode_attr(bytes: &[u8]) -> Result<String, BailReason> {
let s = std::str::from_utf8(bytes).map_err(|_| BailReason::Classifier)?;
if !s.contains('&') {
return Ok(s.to_owned());
}
let mut out = String::with_capacity(s.len());
decode_entities_into(&mut out, s, 0, ReferenceContext::Attribute)?;
Ok(out)
}
fn pop_matching_frame(stack: &mut Vec<OpenTag>, spec: &'static TagSpec) -> Option<OpenTag> {
let top = stack.last()?;
if kinds_match(&top.spec.kind, &spec.kind) {
stack.pop()
} else {
None
}
}
fn kinds_match(a: &TagKind, b: &TagKind) -> bool {
match (a, b) {
(TagKind::List(la), TagKind::List(lb)) => la == lb,
(TagKind::Heading(_), TagKind::Heading(_)) => true,
(TagKind::TableCell { is_header: a_h }, TagKind::TableCell { is_header: b_h }) => a_h == b_h,
_ => std::mem::discriminant(a) == std::mem::discriminant(b),
}
}
fn find_parent_list_kind(stack: &[OpenTag]) -> Option<ListKind> {
for frame in stack.iter().rev() {
if let TagKind::List(kind) = frame.spec.kind {
return Some(kind);
}
}
None
}
fn increment_ol_counter(stack: &mut [OpenTag]) -> u16 {
for frame in stack.iter_mut().rev() {
if frame.spec.kind == TagKind::List(ListKind::Ordered) {
frame.list_index = frame.list_index.saturating_add(1);
return frame.list_index;
}
}
1
}
fn find_ol_start(stack: &[OpenTag]) -> u16 {
for frame in stack.iter().rev() {
if frame.spec.kind == TagKind::List(ListKind::Ordered) {
return frame.ol_start;
}
}
1
}
fn heading_prefix(n: u8) -> &'static str {
let idx = (n as usize).saturating_sub(1).min(5);
HEADING_PREFIXES[idx]
}
fn push_list_item_indent(out: &mut String, depth: u16) {
let idx = depth as usize;
if idx < LIST_ITEM_INDENTS.len() {
out.push_str(LIST_ITEM_INDENTS[idx]);
} else {
out.reserve(idx * 2);
for _ in 0..idx {
out.push_str(" ");
}
}
}
fn prefix_blockquote_lines(content: &str) -> String {
let content = content.trim_end_matches('\n');
if content.is_empty() {
return String::new();
}
let lines: Vec<&str> = content.split('\n').collect();
let mut result = String::with_capacity(content.len() + lines.len() * 2);
for (i, line) in lines.iter().enumerate() {
if line.is_empty() {
result.push('>');
} else {
result.push_str("> ");
result.push_str(line);
}
if i < lines.len() - 1 {
result.push('\n');
}
}
result.push('\n');
result
}