use crate::converter::code_scan::CodeScan;
use crate::options::CodeBlockStyle;
use crate::options::ConversionOptions;
use crate::options::HiddenContent;
use crate::options::NewlineStyle;
use crate::options::conversion::{DEFAULT_MAX_DEPTH, MAX_CONFIGURABLE_DEPTH};
mod head;
use head::document_head_search;
pub use head::{
document_head, end_tag_starts_body, 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 => DEFAULT_MAX_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().record(output);
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, style: CodeBlockStyle) {
if !output.contains("\n\n\n") {
return;
}
let mut cleaned = String::with_capacity(output.len());
let mut fences = CodeScan::new(style, output);
let mut consecutive = 0usize;
for line in output.split_inclusive('\n') {
let content = line.strip_suffix('\n').unwrap_or(line);
if fences.is_code(content) || !content.is_empty() {
consecutive = 1;
cleaned.push_str(line);
} else {
consecutive += 1;
if consecutive <= 2 {
cleaned.push_str(line);
}
}
}
*output = cleaned;
}
pub fn trim_line_end_whitespace(output: &mut String, style: CodeBlockStyle) {
if output.is_empty() {
return;
}
let mut cleaned = String::with_capacity(output.len());
let mut fences = CodeScan::new(style, output);
for line in output.split('\n') {
if fences.is_code(line) {
cleaned.push_str(line);
cleaned.push('\n');
continue;
}
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 preserves_menu(options: &ConversionOptions) -> bool {
options.preserve_tags.iter().any(|tag| tag.eq_ignore_ascii_case("menu"))
}
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",
];
const 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 const 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())
}
const 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(super) fn repair_with_html5ever_bounded(input: &str) -> Option<(String, Option<crate::types::WarningKind>)> {
repair_with_html5ever(input, false)
}
pub(super) fn repair_with_html5ever(
input: &str,
template_contents: bool,
) -> Option<(String, Option<crate::types::WarningKind>)> {
use crate::converter::anchor_origin::{RepairTree, 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 RepairTree { dom, limit, unparsed } = parse_with_anchor_origins(&expanded);
if limit == Some(crate::types::WarningKind::TruncatedInput) {
tracing::warn!(
target: "html_to_markdown::convert",
"HTML tree repair reached its node budget; continuing with the original structure"
);
return Some((input.to_owned(), limit));
}
collapse_split_anchors(&dom.document);
let mut buf = Vec::with_capacity(input.len());
let handle = if template_contents {
SerializableHandle::with_template_contents(dom.document)
} else {
SerializableHandle::from(dom.document)
};
serialize(&mut buf, &handle, SerializeOpts::default()).ok()?;
let mut html = String::from_utf8(buf).ok()?;
if limit.is_some() {
tracing::warn!(
target: "html_to_markdown::convert",
"HTML tree repair reached its depth limit; the rest of the input keeps its original structure"
);
const DOCUMENT_END: &str = "</body></html>";
let end = if html.ends_with(DOCUMENT_END) {
DOCUMENT_END.len()
} else {
0
};
html.insert_str(html.len() - end, &unparsed);
}
Some((html, limit))
}
pub fn repair_head_content_outside_head(
input: &str,
hidden_content: HiddenContent,
) -> Option<(String, Option<crate::types::WarningKind>)> {
if !has_head_content_outside_head(input) {
return None;
}
repair_with_html5ever(input, hidden_content != HiddenContent::Drop)
}
pub fn has_head_content_outside_head(input: &str) -> bool {
may_hold_head_content_outside_head(input)
&& crate::dom::parse(input, crate::dom::ParserOptions)
.is_ok_and(|dom| document_head_search(dom.children(), dom.parser()).content_outside_head)
}
fn may_hold_head_content_outside_head(input: &str) -> bool {
let prefix_end = crate::converter::utility::preprocessing::metadata_prefix_end(input);
let image_starts_body = is_start_tag_at(input.as_bytes(), b"img", prefix_end);
let bytes = &input.as_bytes()[..prefix_end];
let Some(head_start) = last_start_tag(bytes, b"head") else {
return first_start_tag(bytes, b"title").is_some();
};
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",
];
image_starts_body
|| HEAD_CONTENT
.iter()
.any(|name| first_start_tag(&bytes[..head_start], name).is_some())
|| title_follows_head_end(bytes)
}
fn title_follows_head_end(bytes: &[u8]) -> bool {
let Some(head_end) = first_start_tag(bytes, b"/head") else {
return false;
};
let rest = &bytes[head_end..];
let Some(title) = first_start_tag(rest, b"title") else {
return false;
};
first_start_tag(rest, b"body").is_none_or(|body| title < body)
}
fn first_start_tag(bytes: &[u8], name: &[u8]) -> Option<usize> {
source_tags(bytes).find(|&start| is_start_tag_at(bytes, name, start))
}
fn last_start_tag(bytes: &[u8], name: &[u8]) -> Option<usize> {
source_tags(bytes)
.filter(|&start| is_start_tag_at(bytes, name, start))
.last()
}
fn source_tags(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
let mut position = 0;
std::iter::from_fn(move || {
let start = position + memchr::memchr(b'<', bytes.get(position..)?)?;
position = crate::converter::utility::preprocessing::skip_opaque_region(bytes, start)
.or_else(|| crate::converter::utility::preprocessing::find_tag_end(bytes, start + 1))
.unwrap_or(start + 1);
Some(start)
})
}
#[cfg(test)]
thread_local! {
static START_TAG_CANDIDATE_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn is_start_tag_at(bytes: &[u8], name: &[u8], start: usize) -> bool {
#[cfg(test)]
START_TAG_CANDIDATE_CHECKS.with(|checks| checks.set(checks.get() + 1));
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 is_inline_element(tag_name: &str) -> bool {
matches!(
tag_name,
"a" | "abbr"
| "b"
| "bdi"
| "bdo"
| "br"
| "cite"
| "code"
| "data"
| "dfn"
| "em"
| "font"
| "i"
| "kbd"
| "mark"
| "q"
| "rp"
| "rt"
| "ruby"
| "s"
| "samp"
| "tt"
| "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"
)
}
pub(super) fn repair_limit_warning(limit: crate::types::WarningKind) -> crate::types::ProcessingWarning {
use crate::converter::anchor_origin::MAX_REPAIR_DEPTH;
crate::types::ProcessingWarning {
kind: crate::types::WarningKind::MalformedHtml,
message: if limit == crate::types::WarningKind::TruncatedInput {
"HTML tree repair exceeded its node budget; continued with the original structure.".to_owned()
} else {
format!(
"HTML tree repair reached the depth limit of {MAX_REPAIR_DEPTH}; continued with the original structure."
)
},
}
}
#[cfg(test)]
mod tests;