use crate::options::ConversionOptions;
use crate::options::NewlineStyle;
use crate::options::conversion::{MAX_CONFIGURABLE_DEPTH, NATIVE_STACK_SAFE_DEPTH};
mod head;
use head::document_head_search;
pub use head::{
document_head, extract_head_metadata, format_metadata_frontmatter, is_ignorable_before_head, starts_body,
};
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);
}
}
pub fn emit_table_cell_break_in_context(output: &mut String, br_in_tables: bool, ctx: &crate::converter::Context) {
if br_in_tables && let Some(ref offsets) = ctx.pre_cell_break_offsets {
trim_trailing_whitespace(output);
offsets.borrow_mut().push(output.len());
output.push('\n');
} else {
emit_table_cell_break(output, br_in_tables);
}
}
#[must_use]
pub const fn hard_break_marker(options: &ConversionOptions) -> &'static str {
if matches!(options.output_format, crate::options::OutputFormat::Djot) {
return "\\\n";
}
match options.newline_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 repair_head_content_before_explicit_head(input: &str) -> Option<String> {
let head_start = last_start_tag(input.as_bytes(), b"head")?;
const HEAD_CONTENT: [&[u8]; 11] = [
b"base",
b"basefont",
b"bgsound",
b"link",
b"meta",
b"noframes",
b"noscript",
b"script",
b"style",
b"template",
b"title",
];
if !HEAD_CONTENT
.iter()
.any(|name| first_start_tag(input.as_bytes(), name).is_some_and(|start| start < head_start))
{
return None;
}
let dom = tl::parse(input, tl::ParserOptions::default()).ok()?;
if !document_head_search(dom.children(), dom.parser()).1 {
return None;
}
repair_with_html5ever(input)
}
fn first_start_tag(bytes: &[u8], name: &[u8]) -> Option<usize> {
bytes
.iter()
.enumerate()
.find_map(|(start, _)| is_start_tag_at(bytes, name, start).then_some(start))
}
fn last_start_tag(bytes: &[u8], name: &[u8]) -> Option<usize> {
bytes
.iter()
.enumerate()
.rev()
.find_map(|(start, _)| is_start_tag_at(bytes, name, start).then_some(start))
}
fn is_start_tag_at(bytes: &[u8], name: &[u8], start: usize) -> bool {
if bytes.get(start) != Some(&b'<') {
return false;
}
let tag_start = start + 1;
let tag_end = tag_start + name.len();
bytes
.get(tag_start..tag_end)
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))
&& bytes
.get(tag_end)
.is_some_and(|next| next.is_ascii_whitespace() || matches!(next, b'/' | b'>'))
}
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(" ", false));
assert!(is_ignorable_before_head(" ", 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>"));
}
}