use crate::converter::utility::escaping::is_block_level_name;
use crate::converter::utility::white_space::{FORM_FEED, is_collapsible, mark_edges, owed_part};
use crate::options::{ConversionOptions, HiddenContent};
use crate::text;
use std::borrow::Cow;
#[cfg(feature = "visitor")]
use std::collections::BTreeMap;
pub use crate::converter::DomContext;
#[cfg(feature = "visitor")]
pub fn collect_tag_attributes(tag: &tl::HTMLTag) -> BTreeMap<String, String> {
tag.attributes()
.iter()
.filter_map(|(k, v)| v.as_ref().map(|val| (k.to_string(), val.to_string())))
.collect()
}
pub fn chomp_inline(text: &str) -> (&str, &str, &str) {
if text.is_empty() {
return ("", "", "");
}
let has_trailing_linebreak = text.ends_with(" \n") || text.ends_with("\\\n");
if text.trim().is_empty() && !has_trailing_linebreak {
return (if text.contains(FORM_FEED) { text } else { " " }, "", "");
}
let (start_run, end_run) = mark_edges(text);
let prefix = if start_run.contains(FORM_FEED) {
start_run
} else if text.starts_with(&[' ', '\t'][..]) {
" "
} else {
""
};
let suffix = if has_trailing_linebreak {
if text.ends_with(" \n") { " \n" } else { "\\\n" }
} else if end_run.contains(FORM_FEED) {
end_run
} else if text.ends_with(&[' ', '\t'][..]) {
" "
} else {
""
};
let trimmed = if has_trailing_linebreak {
text.strip_suffix(" \n").map_or_else(
|| text.strip_suffix("\\\n").map_or_else(|| text.trim(), |s| s.trim()),
|s| s.trim(),
)
} else {
text.trim()
};
(prefix, suffix, trimmed)
}
pub fn link_label_edges(content: &str) -> (&str, &str, &str) {
let is_edge_space = |character: char| character.is_whitespace() && character != '\n';
let after_start = content.trim_start_matches(is_edge_space);
let leading = &content[..content.len() - after_start.len()];
let starts_at_break = after_start.starts_with('\n') || after_start.starts_with("\\\n");
let start = if starts_at_break && !leading.contains(FORM_FEED) {
0
} else if after_start.starts_with('\n') {
leading.strip_suffix(" ").unwrap_or(leading).len()
} else {
leading.len()
};
let before_end = content[start..].trim_end_matches(is_edge_space);
let end = if before_end.ends_with('\n') {
content.len()
} else {
start + before_end.len()
};
let prefix = edge_space(&content[..start]);
let suffix = edge_space(&content[end..]);
(prefix, suffix, &content[start..end])
}
fn edge_space(run: &str) -> &str {
if run.contains(FORM_FEED) {
run
} else {
space_if(!run.is_empty())
}
}
pub fn link_text_edges(link_text: &LinkText) -> (&'static str, &'static str) {
let text = link_text.text.as_str();
let starts_at_break = link_text
.breaks
.is_some_and(|(first, _)| first <= text.len() - text.trim_start().len());
let ends_at_break = link_text.breaks.is_some_and(|(_, last)| last >= text.trim_end().len());
let is_space = |edge: Option<char>| edge.is_some_and(char::is_whitespace);
(
space_if(!starts_at_break && is_space(text.chars().next())),
space_if(!ends_at_break && is_space(text.chars().next_back())),
)
}
const fn space_if(owed: bool) -> &'static str {
if owed { " " } else { "" }
}
#[derive(Debug, Clone, Default)]
pub struct LinkText {
pub text: String,
pub breaks: Option<(usize, usize)>,
}
pub fn merge_adjacent_emphasis(output: &mut String, symbol: char, count: usize) -> bool {
if count == 0 {
return false;
}
let mut rev = output.chars().rev();
for _ in 0..count {
match rev.next() {
Some(c) if c == symbol => {}
_ => return false,
}
}
if let Some(preceding) = rev.next() {
if preceding == symbol || preceding == '\\' {
return false;
}
}
let new_len = output.len() - symbol.len_utf8() * count;
output.truncate(new_len);
true
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn get_text_content(node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> String {
dom_ctx.text_content(*node_handle, parser)
}
pub(in crate::converter) fn get_math_text_content(
node_handle: &tl::NodeHandle,
parser: &tl::Parser,
dom_ctx: &DomContext,
hidden_content: HiddenContent,
) -> String {
super::math::text_content(node_handle, parser, dom_ctx, hidden_content)
}
pub fn push_inline_prefix(
output: &mut String,
prefix: &str,
options: &crate::options::ConversionOptions,
ctx: &crate::converter::context::Context,
) {
if keeps_source_white_space(options, ctx) {
output.push_str(prefix);
} else {
let owed = owed_part(output, prefix);
output.push_str(owed);
}
}
#[must_use]
pub const fn keeps_source_white_space(
options: &crate::options::ConversionOptions,
ctx: &crate::converter::context::Context,
) -> bool {
ctx.in_code || matches!(options.whitespace_mode, crate::options::WhitespaceMode::Strict)
}
#[must_use]
pub fn is_inline_code(tag_name: &str) -> bool {
matches!(tag_name, "code" | "kbd" | "samp")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NextElement {
Block,
Inline,
InlineAroundBlock,
}
impl NextElement {
#[must_use]
pub const fn new(is_inline: bool, content_starts_with_block: bool) -> Self {
match (is_inline, content_starts_with_block) {
(true, true) => Self::InlineAroundBlock,
(true, false) => Self::Inline,
(false, _) => Self::Block,
}
}
}
#[must_use]
pub const fn line_end_before_element(in_running_text: bool, next: NextElement) -> char {
if in_running_text || matches!(next, NextElement::Inline) {
' '
} else {
'\n'
}
}
#[must_use]
pub fn without_trailing_line_end_in_source(raw: &str) -> Option<&str> {
let kept = raw.trim_end_matches(is_collapsible);
(raw[kept.len()..].contains('\n') && !kept.is_empty()).then_some(kept)
}
#[must_use]
pub fn ends_with_zero_width_space_in_source(raw: &str) -> bool {
raw.rfind('&').map_or_else(
|| raw.ends_with(ZERO_WIDTH_SPACE),
|start| text::decode_html_entities_cow(&raw[start..]).ends_with(ZERO_WIDTH_SPACE),
)
}
#[must_use]
pub fn is_text_wrapper(tag_name: &str) -> bool {
matches!(
tag_name,
"a" | "abbr"
| "b"
| "bdi"
| "bdo"
| "cite"
| "code"
| "data"
| "del"
| "dfn"
| "em"
| "i"
| "ins"
| "kbd"
| "mark"
| "s"
| "samp"
| "small"
| "span"
| "strike"
| "strong"
| "sub"
| "sup"
| "time"
| "u"
| "var"
)
}
pub const ZERO_WIDTH_SPACE: char = '\u{200b}';
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn node_is_block_level(handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
let Some(tl::Node::Tag(tag)) = handle.get(parser) else {
return false;
};
dom_ctx.tag_info(handle.get_inner(), parser).map_or_else(
|| {
let tag_name = normalized_tag_name(tag.name().as_utf8_str());
is_block_level_element(tag_name.as_ref())
},
|info| info.is_block,
)
}
pub fn collect_link_label_text(
children: &[tl::NodeHandle],
parser: &tl::Parser,
dom_ctx: &DomContext,
options: &ConversionOptions,
) -> (LinkText, Vec<tl::NodeHandle>, bool) {
let mut block_nodes = Vec::new();
let text = walk_link_text(children, parser, dom_ctx, options, |handle| {
block_nodes.push(handle);
false
});
let saw_block = !block_nodes.is_empty();
(text, block_nodes, saw_block)
}
pub fn link_text_content(
children: &[tl::NodeHandle],
parser: &tl::Parser,
dom_ctx: &DomContext,
options: &ConversionOptions,
) -> LinkText {
walk_link_text(children, parser, dom_ctx, options, |_| true)
}
pub fn link_accessible_name<'a>(aria_label: Option<&'a str>, title: Option<&'a str>) -> Option<&'a str> {
[aria_label, title]
.into_iter()
.flatten()
.map(str::trim)
.find(|name| !name.is_empty())
}
#[allow(clippy::match_wildcard_for_single_variants)]
fn walk_link_text(
children: &[tl::NodeHandle],
parser: &tl::Parser,
dom_ctx: &DomContext,
options: &ConversionOptions,
mut enter_block: impl FnMut(tl::NodeHandle) -> bool,
) -> LinkText {
let mut text = String::new();
let mut breaks: Option<(usize, usize)> = None;
let mut stack: Vec<_> = children.iter().rev().copied().collect();
while let Some(handle) = stack.pop() {
let Some(node) = handle.get(parser) else {
continue;
};
match node {
tl::Node::Raw(bytes) => {
let raw = bytes.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
text.push_str(decoded.as_ref());
}
tl::Node::Tag(tag) if tag.name().as_utf8_str().eq_ignore_ascii_case("svg") => {
text.push_str(&crate::converter::media::svg::graphic_text(tag, parser, options));
}
tl::Node::Tag(tag) if tag.name().as_utf8_str().eq_ignore_ascii_case("br") => {
breaks = Some((breaks.map_or(text.len(), |(first, _)| first), text.len()));
}
tl::Node::Tag(tag) => {
if !node_is_block_level(&handle, parser, dom_ctx) || enter_block(handle) {
push_label_children(&mut stack, handle, tag, dom_ctx);
}
}
_ => {}
}
}
LinkText { text, breaks }
}
fn push_label_children(
stack: &mut Vec<tl::NodeHandle>,
handle: tl::NodeHandle,
tag: &tl::HTMLTag<'_>,
dom_ctx: &DomContext,
) {
if let Some(children) = dom_ctx.children_of(handle.get_inner()) {
stack.extend(children.iter().rev().copied());
return;
}
let mut children: Vec<_> = tag.children().top().iter().copied().collect();
children.reverse();
stack.extend(children);
}
const HARD_BREAK_MARKERS: [&str; 2] = [" \n", "\\\n"];
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn normalize_link_label(label: &str) -> String {
let mut segments: Vec<String> = Vec::new();
let mut markers: Vec<&'static str> = Vec::new();
let mut rest = label;
while let Some((marker_pos, marker)) = find_earliest_hard_break_marker(rest) {
let mut segment = String::new();
collapse_whitespace_into(&mut segment, &rest[..marker_pos]);
segments.push(segment);
markers.push(marker);
rest = &rest[marker_pos + marker.len()..];
}
let mut segment = String::new();
collapse_whitespace_into(&mut segment, rest);
segments.push(segment);
let label = assemble_label(segments, markers);
protect_adjacent_hard_breaks(&label).into_owned()
}
pub fn indent_continuation_lines(label: &mut String, indent: &str) {
if !label.contains('\n') {
return;
}
let original = std::mem::take(label);
let mut lines = original.split('\n');
let mut indented = lines.next().unwrap_or_default().to_string();
for line in lines {
indented.push('\n');
if !line.is_empty() {
indented.push_str(indent);
indented.push_str(line.trim_start_matches([' ', '\t']));
}
}
*label = indented;
}
pub fn protect_adjacent_hard_breaks(label: &str) -> Cow<'_, str> {
if !label.contains(" \n \n") && !label.contains("\\\n \n") {
return Cow::Borrowed(label);
}
let protected = label.replace(" \n \n", " \n\\\n");
Cow::Owned(protected.replace("\\\n \n", "\\\n\\\n"))
}
pub fn assemble_label(mut segments: Vec<String>, mut markers: Vec<&'static str>) -> String {
if let Some(first) = segments.first_mut() {
*first = first.trim_start().to_string();
}
if let Some(last) = segments.last_mut() {
*last = last.trim_end().to_string();
}
let mut leading = "";
while segments.len() > 1 && segments[0].is_empty() {
segments.remove(0);
leading = markers.remove(0);
}
let mut trailing = "";
while segments.len() > 1 && segments.last().is_some_and(String::is_empty) {
segments.pop();
trailing = markers.pop().unwrap_or("");
}
if segments.iter().all(String::is_empty) {
return String::new();
}
let mut result = String::with_capacity(label_capacity(&segments, &markers, leading, trailing));
result.push_str(leading);
for (index, segment) in segments.iter().enumerate() {
if index > 0 {
result.push_str(markers.get(index - 1).copied().unwrap_or(""));
}
result.push_str(segment);
}
result.push_str(trailing);
result
}
fn label_capacity(segments: &[String], markers: &[&str], leading: &str, trailing: &str) -> usize {
segments.iter().map(String::len).sum::<usize>()
+ markers.iter().map(|marker| marker.len()).sum::<usize>()
+ leading.len()
+ trailing.len()
}
fn find_earliest_hard_break_marker(text: &str) -> Option<(usize, &'static str)> {
HARD_BREAK_MARKERS
.iter()
.filter_map(|marker| text.find(marker).map(|pos| (pos, *marker)))
.min_by_key(|(pos, _)| *pos)
}
pub fn collapse_whitespace_into(out: &mut String, segment: &str) {
if segment.is_empty() {
return;
}
let folded: Cow<'_, str> = if segment.contains(['\n', '\r']) {
Cow::Owned(segment.replace(['\n', '\r'], " "))
} else {
Cow::Borrowed(segment)
};
out.push_str(text::normalize_whitespace_cow(folded.as_ref()).as_ref());
}
pub fn normalized_tag_name(raw: Cow<'_, str>) -> Cow<'_, str> {
if raw.as_bytes().iter().any(u8::is_ascii_uppercase) {
let mut owned = raw.into_owned();
owned.make_ascii_lowercase();
Cow::Owned(owned)
} else {
raw
}
}
pub fn is_block_level_element(tag_name: &str) -> bool {
is_block_level_name(tag_name, crate::converter::main_helpers::is_inline_element(tag_name))
}
pub const fn floor_char_boundary(s: &str, index: usize) -> usize {
if index >= s.len() {
s.len()
} else {
let mut i = index;
while i > 0 && !s.is_char_boundary(i) {
i -= 1;
}
i
}
}
#[cfg(test)]
mod tests {
use super::{
LinkText, ends_with_zero_width_space_in_source, link_label_edges, link_text_edges,
without_trailing_line_end_in_source,
};
use crate::converter::utility::white_space::with_white_space_references_decoded;
#[test]
fn a_link_label_gives_up_the_white_space_at_its_edges() {
for (content, edges) in [
("Go", ("", "", "Go")),
(" Go ", (" ", " ", "Go")),
("\tGo\t", (" ", " ", "Go")),
(" Go", (" ", "", "Go")),
("Go\r", ("", " ", "Go")),
(" ", (" ", "", "")),
("", ("", "", "")),
("Go \nnow", ("", "", "Go \nnow")),
] {
assert_eq!(link_label_edges(content), edges, "{content:?}");
}
}
#[test]
fn a_unicode_space_at_a_link_label_edge_is_the_space_of_that_edge() {
for (content, edges) in [
("\u{a0}Go\u{a0}", (" ", " ", "Go")),
("\u{202f}Go", (" ", "", "Go")),
("Go\u{202f}", ("", " ", "Go")),
("\u{2003}**Go**", (" ", "", "**Go**")),
(" \u{a0}Go\u{a0} ", (" ", " ", "Go")),
("\u{a0}", (" ", "", "")),
] {
assert_eq!(link_label_edges(content), edges, "{content:?}");
}
}
#[test]
fn a_form_feed_at_a_link_label_edge_is_given_back_as_it_is() {
for (content, edges) in [
("\u{c}Go", ("\u{c}", "", "Go")),
("Go\u{c}", ("", "\u{c}", "Go")),
(" \u{c}Go ", (" \u{c}", " ", "Go")),
("\u{a0}Go\u{c} ", (" ", "\u{c} ", "Go")),
("\u{c}", ("\u{c}", "", "")),
("Go\u{c}now", ("", "", "Go\u{c}now")),
] {
assert_eq!(link_label_edges(content), edges, "{content:?}");
}
}
#[test]
fn should_move_the_whole_leading_form_feed_edge_outside_a_label_but_keep_its_break_marker() {
let cases = [
("\u{c} \nMenu", ("\u{c}", "", " \nMenu")),
("\u{c} \n菜单", ("\u{c} ", "", " \n菜单")),
("\u{c}\t\u{c} \nMenu", ("\u{c}\t\u{c}", "", " \nMenu")),
("\u{c}\\\nMenu", ("\u{c}", "", "\\\nMenu")),
(" \u{c}\t\\\n菜单", (" \u{c}\t", "", "\\\n菜单")),
("Menu \n\u{c}", ("", "", "Menu \n\u{c}")),
("菜单\\\n \u{c}\t", ("", "", "菜单\\\n \u{c}\t")),
(
"\u{c} \\\n菜单\\\n\u{c} \u{c}",
("\u{c} ", "", "\\\n菜单\\\n\u{c} \u{c}"),
),
(" \nMenu", ("", "", " \nMenu")),
("Menu \n\u{a0}", ("", "", "Menu \n\u{a0}")),
];
assert_eq!(cases.len(), 10);
for (content, expected) in cases {
assert_eq!(link_label_edges(content), expected, "{content:?}");
}
}
#[test]
fn a_line_break_at_a_link_label_edge_keeps_that_side_whole() {
for (content, edges) in [
("Go \n", ("", "", "Go \n")),
("Go\n", ("", "", "Go\n")),
("Go\\\n", ("", "", "Go\\\n")),
("Go \n\u{a0}", ("", "", "Go \n\u{a0}")),
(" \nGo", ("", "", " \nGo")),
("\\\nGo", ("", "", "\\\nGo")),
(" \nGo", ("", "", " \nGo")),
("\u{a0} \nGo", ("", "", "\u{a0} \nGo")),
(" \nGo \n", ("", "", " \nGo \n")),
(" \n", ("", "", " \n")),
(" Go \n", (" ", "", "Go \n")),
(" Go \n\u{a0}", (" ", "", "Go \n\u{a0}")),
(" \nGo ", ("", " ", " \nGo")),
(" \nGo\u{a0}", ("", " ", " \nGo")),
] {
assert_eq!(link_label_edges(content), edges, "{content:?}");
}
}
#[test]
fn the_text_of_a_link_gives_one_space_for_the_white_space_at_each_end() {
for (text, edges) in [
("https://e.org/", ("", "")),
(" https://e.org/", (" ", "")),
("https://e.org/\n", ("", " ")),
("\t\thttps://e.org/ \r\n", (" ", " ")),
("\u{a0}https://e.org/\u{a0}", (" ", " ")),
("\u{200b}https://e.org/", ("", "")),
("", ("", "")),
] {
let link_text = LinkText {
text: text.to_owned(),
breaks: None,
};
assert_eq!(link_text_edges(&link_text), edges, "{text:?}");
}
}
#[test]
fn white_space_beside_a_line_break_at_an_end_of_a_link_gives_no_space() {
for (text, breaks, edges) in [
("https://e.org/\u{a0}", (14, 14), ("", "")),
("https://e.org/ ", (15, 15), ("", "")),
("\u{a0}https://e.org/ ", (0, 0), ("", " ")),
(" https://e.org/", (1, 1), ("", "")),
(" https://e.org/ ", (5, 5), (" ", " ")),
(" https://e.org/ ", (0, 16), ("", "")),
] {
let link_text = LinkText {
text: text.to_owned(),
breaks: Some(breaks),
};
assert_eq!(link_text_edges(&link_text), edges, "{text:?} {breaks:?}");
}
}
#[test]
fn a_source_text_that_ends_with_a_line_end_loses_its_trailing_white_space() {
for (raw, kept) in [
("one\n", "one"),
("one \t\r\n ", "one"),
("one ", "one"),
("one
", "one"),
("one
", "one"),
("one
", "one"),
("one ", "one"),
("one\n ", "one"),
("one \n", "one"),
("one		  ", "one"),
("a & b ", "a & b"),
("one&#10;\n", "one&#10;"),
("one \n", "one "),
("one &\n", "one &"),
("é ", "é"),
] {
let text = with_white_space_references_decoded(raw);
assert_eq!(without_trailing_line_end_in_source(&text), Some(kept), "{raw:?}");
}
}
#[test]
fn a_source_text_with_no_line_end_at_its_end_or_no_other_text_is_not_changed() {
for raw in [
"",
"one",
"one ",
"one ",
"one	 ",
"one&#10;",
"one&NewLine;",
"one&NewLines;",
"one&NEWLINE;",
"one two",
"one\n ",
"\n",
" \n ",
" ",
"  \n",
] {
let text = with_white_space_references_decoded(raw);
assert_eq!(without_trailing_line_end_in_source(&text), None, "{raw:?}");
}
}
#[test]
fn a_source_text_ends_with_a_zero_width_space_as_a_character_or_a_reference() {
for raw in [
"one\u{200b}",
"one​",
"one​",
"one​",
"a & b\u{200b}",
"a & b​",
] {
assert!(ends_with_zero_width_space_in_source(raw), "{raw:?}");
}
for raw in [
"one",
"",
"one\u{200b}two",
"one&#8203;",
"one​two",
"one𔁮",
] {
assert!(!ends_with_zero_width_space_in_source(raw), "{raw:?}");
}
}
}