use std::collections::{BTreeMap, HashSet};
use std::sync::OnceLock;
use crate::options::ConversionOptions;
use crate::options::NewlineStyle;
use crate::options::conversion::{MAX_CONFIGURABLE_DEPTH, NATIVE_STACK_SAFE_DEPTH};
pub fn effective_max_depth(options: &ConversionOptions) -> usize {
match options.max_depth {
None => NATIVE_STACK_SAFE_DEPTH,
Some(explicit) => explicit.min(MAX_CONFIGURABLE_DEPTH),
}
}
pub fn tag_name_eq(a: impl AsRef<str>, b: &str) -> bool {
a.as_ref().eq_ignore_ascii_case(b)
}
pub fn trim_trailing_whitespace(output: &mut String) {
while output.ends_with([' ', '\t']) {
output.pop();
}
}
pub fn is_ascii_whitespace_only(text: &str) -> bool {
text.chars().all(|c| matches!(c, ' ' | '\t' | '\n' | '\r'))
}
pub fn strip_trailing_backslash_breaks(output: &mut String, block_start: usize) {
let block_start = crate::converter::utility::content::floor_char_boundary(output, block_start.min(output.len()));
let mut stripped_breaks = 0usize;
while output.len() > block_start && output[block_start..].ends_with("\\\n") {
let mut new_len = output.len() - "\\\n".len();
let indent_start = output[..new_len].trim_end_matches([' ', '\t']).len();
if indent_start >= block_start && output[..indent_start].ends_with('\n') {
new_len = indent_start;
}
output.truncate(new_len);
stripped_breaks += 1;
}
for _ in 0..stripped_breaks {
output.push('\n');
}
}
pub fn strip_trailing_backslash_breaks_from_fresh_buffer(content: &mut String, newline_style: NewlineStyle) {
if newline_style == NewlineStyle::Backslash {
strip_trailing_backslash_breaks(content, 0);
}
}
pub fn emit_table_cell_break(output: &mut String, br_in_tables: bool) {
trim_trailing_whitespace(output);
if br_in_tables {
output.push_str("<br>");
} else if !output.is_empty() {
output.push(' ');
}
}
pub fn separate_block_in_cell(output: &mut String, br_in_tables: bool) {
let content_end = output.trim_end_matches([' ', '\t', '\n']).len();
output.truncate(content_end);
if !output.is_empty() && !output.ends_with("<br>") {
emit_table_cell_break(output, br_in_tables);
}
}
#[must_use]
pub const fn hard_break_marker(style: NewlineStyle) -> &'static str {
match style {
NewlineStyle::Spaces => " \n",
NewlineStyle::Backslash => "\\\n",
}
}
pub fn collapse_excess_blank_lines(output: &mut String) {
if !output.contains("\n\n\n") {
return;
}
let mut cleaned = String::with_capacity(output.len());
let mut consecutive = 0usize;
for ch in output.chars() {
if ch == '\n' {
consecutive += 1;
if consecutive <= 2 {
cleaned.push(ch);
}
} else {
consecutive = 0;
cleaned.push(ch);
}
}
*output = cleaned;
}
pub fn trim_line_end_whitespace(output: &mut String) {
if output.is_empty() {
return;
}
let mut cleaned = String::with_capacity(output.len());
for line in output.split('\n') {
let content = line.trim_end_matches([' ', '\t']);
cleaned.push_str(content);
if !content.is_empty() && line.ends_with(" ") {
cleaned.push_str(" ");
}
cleaned.push('\n');
}
let trimmed = cleaned.trim_end_matches('\n');
if trimmed.is_empty() {
*output = String::new();
} else {
if trimmed.len() < cleaned.len() {
cleaned.truncate(trimmed.len() + 1);
} else {
cleaned.push('\n');
}
*output = cleaned;
}
}
pub fn has_custom_element_tags(html: &str) -> bool {
let bytes = html.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut namespaced_tags = Vec::new();
while i < len {
if bytes[i] != b'<' {
i += 1;
continue;
}
let after_lt = i + 1;
let Some(&next) = bytes.get(after_lt) else {
break;
};
if next == b'!' {
i = skip_markup_declaration(bytes, i);
continue;
}
if next == b'?' {
i = skip_to_after_gt(bytes, after_lt);
continue;
}
let name_start = if next == b'/' { after_lt + 1 } else { after_lt };
if name_start >= len || !crate::converter::tier1::parse::is_tag_name_start(bytes[name_start]) {
i = after_lt;
continue;
}
let tag_start = name_start;
let mut tag_end = tag_start;
while tag_end < len {
let ch = bytes[tag_end];
if ch == b'>' || ch == b'/' || ch.is_ascii_whitespace() {
break;
}
tag_end += 1;
}
let name = &bytes[tag_start..tag_end];
if name.contains(&b'-') {
return true;
}
let (self_closing, terminator) = scan_tag_terminator(bytes, tag_end);
if namespaced_paragraph_is_misnested(&mut namespaced_tags, name, next == b'/', self_closing) {
return true;
}
i = terminator.saturating_add(if self_closing { 2 } else { 1 });
}
false
}
fn namespaced_paragraph_is_misnested<'a>(
open_tags: &mut Vec<&'a [u8]>,
name: &'a [u8],
closing: bool,
self_closing: bool,
) -> bool {
if closing {
if name.contains(&b':') {
if let Some(position) = open_tags.iter().rposition(|open| open.eq_ignore_ascii_case(name)) {
let unclosed_paragraph = open_tags[position + 1..]
.iter()
.any(|open| open.eq_ignore_ascii_case(b"p"));
open_tags.truncate(position);
return unclosed_paragraph;
}
} else if open_tags.last().is_some_and(|open| open.eq_ignore_ascii_case(name)) {
open_tags.pop();
}
} else if !self_closing && (!open_tags.is_empty() || name.contains(&b':')) && !is_html5_void_element(name) {
open_tags.push(name);
}
false
}
fn skip_markup_declaration(bytes: &[u8], lt_idx: usize) -> usize {
if let Some(end) = crate::converter::utility::preprocessing::skip_opaque_region(bytes, lt_idx) {
return end;
}
skip_to_after_gt(bytes, lt_idx + 2)
}
fn skip_to_after_gt(bytes: &[u8], from: usize) -> usize {
let start = from.min(bytes.len());
match bytes[start..].iter().position(|&b| b == b'>') {
Some(offset) => start + offset + 1,
None => bytes.len(),
}
}
const HTML5_VOID_ELEMENTS: &[&str] = &[
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr",
];
fn skip_closing_tag(bytes: &[u8], mut i: usize, len: usize) -> usize {
while i < len && bytes[i] != b'>' {
i += 1;
}
if i < len {
i += 1;
}
i
}
pub fn scan_tag_name_end(bytes: &[u8], start: usize) -> usize {
let len = bytes.len();
let mut i = start;
while i < len {
let ch = bytes[i];
if ch == b'>' || ch == b'/' || ch.is_ascii_whitespace() {
break;
}
i += 1;
}
i
}
pub fn is_html5_void_element(tag_name_bytes: &[u8]) -> bool {
let tag_name_lower = tag_name_bytes.iter().map(u8::to_ascii_lowercase).collect::<Vec<_>>();
HTML5_VOID_ELEMENTS
.iter()
.any(|v| v.as_bytes() == tag_name_lower.as_slice())
}
fn scan_tag_terminator(bytes: &[u8], start: usize) -> (bool, usize) {
let len = bytes.len();
let mut i = start;
let mut in_single_quote = false;
let mut in_double_quote = false;
while i < len {
match bytes[i] {
b'"' if !in_single_quote => {
in_double_quote = !in_double_quote;
i += 1;
}
b'\'' if !in_double_quote => {
in_single_quote = !in_single_quote;
i += 1;
}
b'/' if !in_single_quote && !in_double_quote => {
if i + 1 < len && bytes[i + 1] == b'>' {
return (true, i);
}
i += 1;
}
b'>' if !in_single_quote && !in_double_quote => {
return (false, i);
}
_ => {
i += 1;
}
}
}
(false, len)
}
pub fn expand_xml_self_closing_tags(input: &str) -> String {
let bytes = input.as_bytes();
let len = bytes.len();
let mut output = String::with_capacity(len);
let mut copy_start = 0usize;
let mut i = 0;
while i < len {
if bytes[i] != b'<' {
i += 1;
continue;
}
let tag_open = i;
i += 1;
if i < len && bytes[i] == b'/' {
i = skip_closing_tag(bytes, i, len);
continue;
}
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
let name_start = i;
i = scan_tag_name_end(bytes, name_start);
let tag_name_bytes = &bytes[name_start..i];
if tag_name_bytes.is_empty() {
continue;
}
let is_void = is_html5_void_element(tag_name_bytes);
let attrs_start = i;
let (self_closing, terminator) = scan_tag_terminator(bytes, attrs_start);
i = terminator;
if self_closing && !is_void {
output.push_str(&input[copy_start..tag_open]);
let tag_name_str = std::str::from_utf8(tag_name_bytes).unwrap_or("");
let attrs_part = &input[attrs_start..i];
output.push('<');
output.push_str(tag_name_str);
output.push_str(attrs_part);
output.push('>');
output.push('<');
output.push('/');
output.push_str(tag_name_str);
output.push('>');
i += 2;
copy_start = i;
} else {
if i < len && bytes[i] == b'/' {
i += 2;
} else if i < len && bytes[i] == b'>' {
i += 1;
}
}
}
output.push_str(&input[copy_start..]);
output
}
pub fn repair_with_html5ever(input: &str) -> Option<String> {
use crate::converter::anchor_origin::{collapse_split_anchors, parse_with_anchor_origins};
use crate::rcdom::SerializableHandle;
use html5ever::serialize::{SerializeOpts, serialize};
let expanded = expand_xml_self_closing_tags(input);
let dom = parse_with_anchor_origins(&expanded);
collapse_split_anchors(&dom.document);
let mut buf = Vec::with_capacity(input.len());
let handle = SerializableHandle::from(dom.document);
serialize(&mut buf, &handle, SerializeOpts::default()).ok()?;
String::from_utf8(buf).ok()
}
pub fn format_metadata_frontmatter(metadata: &BTreeMap<String, String>) -> String {
let mut result = String::from("---\n");
for (key, value) in metadata {
if key == "title" && value.is_empty() {
continue;
}
push_yaml_scalar(&mut result, key);
result.push_str(": ");
push_yaml_scalar(&mut result, value);
result.push('\n');
}
result.push_str("---\n");
result
}
fn push_yaml_scalar(out: &mut String, value: &str) {
if is_plain_yaml_scalar(value) {
out.push_str(value);
return;
}
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if is_yaml_printable(c) => out.push(c),
c => {
use std::fmt::Write as _;
let _ = write!(out, "\\u{:04X}", u32::from(c));
}
}
}
out.push('"');
}
fn is_plain_yaml_scalar(value: &str) -> bool {
let Some(first) = value.chars().next() else {
return false;
};
!matches!(
first,
'-' | '?'
| ':'
| ','
| '['
| ']'
| '{'
| '}'
| '#'
| '&'
| '*'
| '!'
| '|'
| '>'
| '\''
| '"'
| '%'
| '@'
| '`'
) && !value.starts_with(' ')
&& !value.ends_with([' ', ':'])
&& !value.contains(": ")
&& !value.contains(" #")
&& value.chars().all(|c| c != '\t' && is_yaml_printable(c))
&& !yaml_non_string_scalar().is_match(value)
}
fn yaml_non_string_scalar() -> &'static regex::Regex {
static RE: OnceLock<regex::Regex> = OnceLock::new();
RE.get_or_init(|| {
regex::Regex::new(concat!(
r"^(?:~|null|Null|NULL",
r"|true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO|on|On|ON|off|Off|OFF|y|Y|n|N",
r"|[-+]?(?:0b[01_]+|0o[0-7]+|0x[0-9a-fA-F_]+",
r"|[0-9][0-9_]*(?::[0-5]?[0-9])*(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?",
r"|\.[0-9][0-9_]*(?:[eE][-+]?[0-9]+)?|\.(?:inf|Inf|INF))",
r"|\.(?:nan|NaN|NAN)",
r"|[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}",
r"(?:(?:[Tt]|[ \t]+)[0-9]{1,2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9]{1,2}(?::[0-9]{2})?))?)?",
r"|=|<<)$",
))
.expect("YAML scalar type regex is well-formed")
})
}
const fn is_yaml_printable(c: char) -> bool {
matches!(c, '\t' | ' '..='~' | '\u{A0}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')
&& !matches!(c, '\u{2028}' | '\u{2029}' | '\u{FEFF}')
}
fn collect_meta_head_metadata(
child_tag: &tl::HTMLTag,
options: &ConversionOptions,
metadata: &mut BTreeMap<String, String>,
seen: &mut HashSet<String>,
) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("meta")
|| options.strip_tags.iter().any(|t| t == "meta")
|| options.preserve_tags.iter().any(|t| t == "meta")
{
return;
}
if let (Some(name), Some(content)) = (
child_tag.attributes().get("name").flatten(),
crate::converter::utility::attributes::decoded_attribute(child_tag, "content"),
) {
let key = format!("meta-{}", name.as_utf8_str());
if seen.insert(key.to_ascii_lowercase()) {
metadata.insert(key, content.into_owned());
}
}
if let (Some(property), Some(content)) = (
child_tag.attributes().get("property").flatten(),
crate::converter::utility::attributes::decoded_attribute(child_tag, "content"),
) {
let key = format!("meta-{}", property.as_utf8_str());
if seen.insert(key.to_ascii_lowercase()) {
metadata.insert(key, content.into_owned());
}
}
}
fn collect_title_head_metadata(
child_tag: &tl::HTMLTag,
parser: &tl::Parser,
options: &ConversionOptions,
metadata: &mut BTreeMap<String, String>,
seen_title: &mut bool,
) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("title") {
return;
}
let later_title = std::mem::replace(seen_title, true);
if later_title
|| options.strip_tags.iter().any(|t| t == "title")
|| options.preserve_tags.iter().any(|t| t == "title")
{
return;
}
let mut title_content = String::new();
let title_children = child_tag.children();
for title_child in title_children.top().iter() {
if let Some(tl::Node::Raw(raw)) = title_child.get(parser) {
title_content.push_str(raw.as_utf8_str().as_ref());
}
}
let title_content = crate::text::decode_html_entities_cow(title_content.trim()).into_owned();
metadata.insert("title".to_string(), title_content);
}
fn collect_link_head_metadata(child_tag: &tl::HTMLTag, metadata: &mut BTreeMap<String, String>) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("link") {
return;
}
let Some(rel_attr) = child_tag.attributes().get("rel").flatten() else {
return;
};
let rel_str = rel_attr.as_utf8_str();
if !rel_str.contains("canonical") {
return;
}
let Some(href) = crate::converter::utility::attributes::decoded_attribute(child_tag, "href") else {
return;
};
metadata
.entry("canonical".to_string())
.or_insert_with(|| href.into_owned());
}
pub fn extract_head_metadata(
roots: &[tl::NodeHandle],
parser: &tl::Parser,
options: &ConversionOptions,
document_base_href: Option<&str>,
) -> BTreeMap<String, String> {
let mut metadata = head_element_metadata(roots, parser, options);
if let Some(href) = document_base_href {
metadata.insert("base".to_string(), href.to_string());
}
metadata
}
fn head_element_metadata(
roots: &[tl::NodeHandle],
parser: &tl::Parser,
options: &ConversionOptions,
) -> BTreeMap<String, String> {
let mut metadata = BTreeMap::new();
let Some(tl::Node::Tag(head)) = document_head(roots, parser).and_then(|handle| handle.get(parser)) else {
return metadata;
};
let mut seen_meta = HashSet::new();
let mut seen_title = false;
for child_handle in head.children().top().iter() {
if let Some(tl::Node::Tag(child_tag)) = child_handle.get(parser) {
collect_meta_head_metadata(child_tag, options, &mut metadata, &mut seen_meta);
collect_title_head_metadata(child_tag, parser, options, &mut metadata, &mut seen_title);
collect_link_head_metadata(child_tag, &mut metadata);
}
}
metadata
}
pub fn document_head(roots: &[tl::NodeHandle], parser: &tl::Parser) -> Option<tl::NodeHandle> {
let mut work: Vec<_> = roots.iter().rev().copied().collect();
while let Some(handle) = work.pop() {
match handle.get(parser) {
Some(tl::Node::Raw(text)) => {
let next_is_html = matches!(
work.last().and_then(|next| next.get(parser)),
Some(tl::Node::Tag(tag)) if tag.name().as_bytes().eq_ignore_ascii_case(b"html")
);
if !is_ignorable_before_head(&text.as_utf8_str(), next_is_html) {
return None;
}
}
Some(tl::Node::Tag(tag)) => {
let name = tag.name().as_bytes().to_ascii_lowercase();
match name.as_slice() {
b"head" => return Some(handle),
b"html" => {
let first = work.len();
work.extend(tag.children().top().iter().copied());
work[first..].reverse();
}
name if starts_body(name) => return None,
_ => {}
}
}
_ => {}
}
}
None
}
pub fn is_ignorable_before_head(text: &str, next_tag_is_html: bool) -> bool {
next_tag_is_html || text.chars().all(|c| c.is_ascii_whitespace())
}
pub fn starts_body(name: &[u8]) -> bool {
!matches!(
name,
b"html"
| b"head"
| b"base"
| b"basefont"
| b"bgsound"
| b"link"
| b"meta"
| b"noframes"
| b"noscript"
| b"script"
| b"style"
| b"template"
| b"title"
)
}
pub fn has_more_than_one_char(text: &str) -> bool {
let mut chars = text.chars();
chars.next().is_some() && chars.next().is_some()
}
pub fn is_inline_element(tag_name: &str) -> bool {
matches!(
tag_name,
"a" | "abbr"
| "b"
| "bdi"
| "bdo"
| "br"
| "cite"
| "code"
| "data"
| "dfn"
| "em"
| "i"
| "kbd"
| "mark"
| "q"
| "rp"
| "rt"
| "ruby"
| "s"
| "samp"
| "small"
| "span"
| "strong"
| "sub"
| "sup"
| "time"
| "u"
| "var"
| "wbr"
| "del"
| "strike"
| "ins"
| "img"
| "map"
| "area"
| "audio"
| "video"
| "picture"
| "source"
| "track"
| "embed"
| "object"
| "param"
| "input"
| "label"
| "button"
| "select"
| "textarea"
| "output"
| "progress"
| "meter"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_ignorable_before_head() {
assert!(is_ignorable_before_head("", false));
assert!(is_ignorable_before_head(" \n\t", false));
assert!(!is_ignorable_before_head("hello", false));
assert!(!is_ignorable_before_head("x", false));
assert!(!is_ignorable_before_head("\u{FFFD}\u{FFFD}", false));
assert!(is_ignorable_before_head("\u{FFFD}\u{FFFD}", true));
assert!(is_ignorable_before_head("hello", true));
}
#[test]
fn test_trim_line_end_whitespace() {
let mut s = String::new();
trim_line_end_whitespace(&mut s);
assert_eq!("", s.as_str());
let mut s = "\t\n\t\n".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("", s.as_str());
let mut s = "hello, world ".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n", s.as_str());
let mut s = "hello, world \n".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n", s.as_str());
let mut s = "hello, world ".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n", s.as_str());
let mut s = "hello, world \n\n\n".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n", s.as_str());
let mut s = "hello \n- world\n".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello \n- world\n", s.as_str());
let mut s = "hello, world\t\t ".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n", s.as_str());
let mut s = "hello, world\t\t \n.abc def \t \t".to_owned();
trim_line_end_whitespace(&mut s);
assert_eq!("hello, world \n.abc def\n", s.as_str());
}
#[test]
fn test_is_ascii_whitespace_only() {
assert!(is_ascii_whitespace_only(""));
assert!(is_ascii_whitespace_only(" \t\n\r"));
assert!(is_ascii_whitespace_only("\n\n"));
assert!(!is_ascii_whitespace_only("\u{a0}"));
assert!(!is_ascii_whitespace_only("\n\u{a0}"));
assert!(!is_ascii_whitespace_only("a"));
assert!(!is_ascii_whitespace_only(" a "));
}
#[test]
fn test_has_custom_element_tags_ignores_comments() {
assert!(!has_custom_element_tags("<!--c-->"));
assert!(!has_custom_element_tags("<p><!-- a routine comment --></p>"));
assert!(!has_custom_element_tags("<!-- multiple -- dashes -- here -->"));
}
#[test]
fn should_detect_namespaced_elements_for_html5_repair() {
assert!(has_custom_element_tags("<o:p><P></o:p></P>"));
assert!(!has_custom_element_tags("<o:p><P></P></o:p>"));
assert!(!has_custom_element_tags("<o:p>Office text</o:p>"));
assert!(!has_custom_element_tags("<o:p/><P>text</P>"));
assert!(!has_custom_element_tags("<!-- <o:p>comment</o:p> -->"));
assert!(!has_custom_element_tags("<div title='o:p'>text</div>"));
}
#[test]
fn test_has_custom_element_tags_detects_real_custom_element() {
assert!(has_custom_element_tags("<my-widget></my-widget>"));
assert!(has_custom_element_tags("<p></p><my-widget></my-widget>"));
assert!(has_custom_element_tags("<div></my-widget>"));
}
#[test]
fn test_has_custom_element_tags_detects_custom_element_alongside_comment() {
assert!(has_custom_element_tags(
"<!-- a routine comment --><my-widget>hi</my-widget>"
));
assert!(has_custom_element_tags(
"<my-widget><!-- nested comment -->hi</my-widget>"
));
}
#[test]
fn test_has_custom_element_tags_ignores_comment_mentioning_custom_element() {
assert!(!has_custom_element_tags("<!-- <my-widget>hi</my-widget> -->"));
}
#[test]
fn test_has_custom_element_tags_ignores_processing_instruction() {
assert!(!has_custom_element_tags("<?php echo 'a-b'; ?>"));
assert!(!has_custom_element_tags(
"<?xml-stylesheet type=\"text/xsl\" href=\"a-b.xsl\"?>"
));
}
#[test]
fn test_has_custom_element_tags_ignores_cdata_section() {
assert!(!has_custom_element_tags(
"<svg><![CDATA[<my-widget>a-b</my-widget>]]></svg>"
));
}
#[test]
fn test_has_custom_element_tags_ignores_doctype() {
assert!(!has_custom_element_tags("<!doctype html>"));
assert!(!has_custom_element_tags("<!DOCTYPE html><p>no custom elements</p>"));
assert!(has_custom_element_tags("<!DOCTYPE html><my-widget></my-widget>"));
}
#[test]
fn test_has_custom_element_tags_rejects_whitespace_before_name() {
assert!(!has_custom_element_tags("< my-widget>"));
assert!(!has_custom_element_tags("</ my-widget>"));
}
}