use crate::converter::main_helpers::effective_max_depth;
use crate::converter::media::MediaContext;
use crate::converter::utility::content::normalized_tag_name;
use crate::converter::utility::escaping::escape_link_label;
use crate::converter::utility::serialization::escape_html_attribute_value;
use crate::converter::utility::svg_attrs::canonical_svg_attr;
use crate::options::conversion::NATIVE_STACK_SAFE_DEPTH;
use crate::options::{ConversionOptions, HiddenContent};
use crate::dom::{NodeHandle, Parser};
#[allow(unused_imports)]
use std::collections::BTreeMap;
#[cfg(feature = "inline-images")]
use crate::inline_images::{InlineImageBuild, InlineImageCollector, InlineImageFormat, InlineImageSource};
#[cfg(feature = "inline-images")]
type InlineCollectorHandle = std::rc::Rc<std::cell::RefCell<InlineImageCollector>>;
#[cfg(feature = "inline-images")]
#[allow(clippy::trivially_copy_pass_by_ref)]
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::option_if_let_else)]
pub fn handle_inline_svg(
collector_ref: &InlineCollectorHandle,
node_handle: &NodeHandle,
parser: &Parser,
title_opt: Option<String>,
attributes: BTreeMap<String, String>,
) {
let max_size = {
let borrow = collector_ref.borrow();
if !borrow.capture_svg() {
return;
}
borrow.max_decoded_size()
};
if max_size == 0 {
let mut collector = collector_ref.borrow_mut();
let index = collector.next_index();
collector.warn_skip(index, "max SVG payload size is zero");
return;
}
let mut collector = collector_ref.borrow_mut();
let index = collector.next_index();
let serialized = serialize_element(node_handle, parser);
if serialized.is_empty() {
collector.warn_skip(index, "unable to serialize SVG element");
return;
}
let data = serialized.into_bytes();
if data.len() as u64 > max_size {
collector.warn_skip(
index,
format!(
"serialized SVG payload ({} bytes) exceeds configured max ({})",
data.len(),
max_size
),
);
return;
}
let description = attributes
.get("aria-label")
.and_then(|value| non_empty_trimmed(value))
.or_else(|| title_opt.as_deref().and_then(non_empty_trimmed));
let filename_candidate = attributes
.get("data-filename")
.cloned()
.or_else(|| attributes.get("filename").cloned())
.or_else(|| attributes.get("data-name").cloned());
let image = collector.build_image(InlineImageBuild {
data,
format: InlineImageFormat::Svg,
filename: filename_candidate,
description,
dimensions: None,
source: InlineImageSource::SvgElement,
attributes,
});
collector.push_image(index, image);
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize_element(node_handle: &NodeHandle, parser: &Parser) -> String {
serialize_element_at_depth(node_handle, parser, 0, NATIVE_STACK_SAFE_DEPTH)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize_node(node_handle: &NodeHandle, parser: &Parser) -> String {
serialize_node_at_depth(node_handle, parser, 0, NATIVE_STACK_SAFE_DEPTH)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize_element_at_depth(node_handle: &NodeHandle, parser: &Parser, depth: usize, max_depth: usize) -> String {
if let Some(crate::dom::Node::Tag(tag)) = node_handle.get(parser) {
let tag_name = normalized_tag_name(tag.name().as_utf8_str());
let mut html = String::with_capacity(256);
html.push('<');
html.push_str(&tag_name);
let mut attrs: Vec<_> = tag.attributes().iter().collect();
attrs.sort_by(|(a, _), (b, _)| a.as_ref().cmp(b.as_ref()));
for (key, value_opt) in attrs {
html.push(' ');
let key_str = key.as_ref();
let canonical = canonical_svg_attr(key_str);
html.push_str(canonical.unwrap_or(key_str));
if let Some(value) = value_opt {
if !value.is_empty() {
html.push_str("=\"");
html.push_str(&escape_html_attribute_value(&value));
html.push('"');
}
}
}
let has_children = !tag.children().top().is_empty();
if has_children {
html.push('>');
if depth >= max_depth {
tracing::warn!(
target: "html_to_markdown::convert",
max_depth,
tag = %tag_name,
"SVG/MathML serialization reached the effective depth limit; descendants were skipped"
);
} else {
let children = tag.children();
for child_handle in children.top() {
html.push_str(&serialize_node_at_depth(child_handle, parser, depth + 1, max_depth));
}
}
html.push_str("</");
html.push_str(&tag_name);
html.push('>');
} else {
html.push_str(" />");
}
return html;
}
String::new()
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize_node_at_depth(node_handle: &NodeHandle, parser: &Parser, depth: usize, max_depth: usize) -> String {
if let Some(node) = node_handle.get(parser) {
match node {
crate::dom::Node::Raw(bytes) => bytes.as_utf8_str().to_string(),
crate::dom::Node::Tag(_) => serialize_element_at_depth(node_handle, parser, depth, max_depth),
_ => String::new(),
}
} else {
String::new()
}
}
#[cfg(feature = "inline-images")]
fn non_empty_trimmed(value: &str) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
#[derive(Clone, Copy)]
enum GraphicScope {
Drawing { of_svg: bool, named: bool },
Label,
Text,
Html,
}
enum GraphicStep {
Visit(crate::dom::NodeHandle, GraphicScope, usize),
Space,
EndPart,
}
#[derive(Default)]
struct GraphicParts {
use_accessible_names: bool,
label: Option<String>,
parts: Vec<String>,
current: String,
}
impl GraphicParts {
fn end_part(&mut self) {
let part = self.current.split_whitespace().collect::<Vec<_>>().join(" ");
self.current.clear();
if !part.is_empty() && self.label.as_deref() != Some(part.as_str()) {
self.parts.push(part);
}
}
}
fn is_aria_hidden(tag: &crate::dom::HTMLTag<'_>) -> bool {
tag.attributes()
.get("aria-hidden")
.flatten()
.is_some_and(|value| value.as_utf8_str().trim().eq_ignore_ascii_case("true"))
}
fn is_hidden_in_graphic(tag: &crate::dom::HTMLTag<'_>, hidden_content: HiddenContent) -> bool {
use crate::converter::utility::preprocessing::{HiddenStyleReason, style_value_hidden_reason};
hidden_content == HiddenContent::Drop
&& ["display", "visibility"].iter().any(|property| {
tag.attributes().get(*property).flatten().is_some_and(|value| {
let declaration = format!("{property}:{}", value.as_utf8_str());
style_value_hidden_reason(&declaration) == Some(HiddenStyleReason::Definitive)
})
})
}
fn system_language_holds(tag: &crate::dom::HTMLTag<'_>) -> bool {
let Some(value) = ["systemLanguage", "systemlanguage"]
.iter()
.find_map(|key| tag.attributes().get(*key))
else {
return true;
};
value.is_some_and(|value| {
value.as_utf8_str().split(',').any(|language| {
let language = language.trim();
language.eq_ignore_ascii_case("en")
|| language
.get(..3)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("en-"))
})
})
}
pub fn graphic_text(
svg: &crate::dom::HTMLTag<'_>,
parser: &Parser<'_>,
options: &ConversionOptions,
policy: crate::convert_api::AccessibleNamePolicy,
) -> String {
graphic_text_with_depth(svg, parser, options, policy, usize::MAX)
}
#[cfg(feature = "metadata")]
pub(in crate::converter) fn preserved_graphic_text(
svg: &crate::dom::HTMLTag<'_>,
parser: &Parser<'_>,
options: &ConversionOptions,
policy: crate::convert_api::AccessibleNamePolicy,
remaining_depth: usize,
) -> String {
graphic_text_with_depth(svg, parser, options, policy, remaining_depth)
}
fn graphic_text_with_depth(
svg: &crate::dom::HTMLTag<'_>,
parser: &Parser<'_>,
options: &ConversionOptions,
policy: crate::convert_api::AccessibleNamePolicy,
remaining_depth: usize,
) -> String {
let hidden_content = options.hidden_content;
if is_hidden_in_graphic(svg, hidden_content) {
return String::new();
}
let named = policy.0 && !is_aria_hidden(svg);
let mut out = GraphicParts {
use_accessible_names: policy.0,
..GraphicParts::default()
};
if named {
if let Some(label) = crate::converter::utility::attributes::decoded_attribute(svg, "aria-label") {
out.current.push_str(&label);
out.end_part();
out.label = out.parts.first().cloned();
}
}
let mut stack = Vec::new();
push_graphic_children(
&mut stack,
svg,
GraphicScope::Drawing { of_svg: true, named },
remaining_depth,
);
while let Some(step) = stack.pop() {
let (handle, scope, remaining_depth) = match step {
GraphicStep::Visit(handle, scope, remaining_depth) => (handle, scope, remaining_depth),
GraphicStep::Space => {
out.current.push(' ');
continue;
}
GraphicStep::EndPart => {
out.end_part();
continue;
}
};
match handle.get(parser) {
Some(crate::dom::Node::Raw(bytes)) if !matches!(scope, GraphicScope::Drawing { .. }) => {
out.current
.push_str(&crate::text::decode_html_entities_cow(bytes.as_utf8_str().as_ref()));
}
Some(crate::dom::Node::Tag(tag)) if is_hidden_in_graphic(tag, hidden_content) => {}
Some(crate::dom::Node::Tag(tag)) => {
visit_graphic_tag(tag, parser, scope, &mut stack, &mut out, remaining_depth);
}
_ => {}
}
}
out.end_part();
out.parts.join(" ")
}
fn push_graphic_children(
stack: &mut Vec<GraphicStep>,
tag: &crate::dom::HTMLTag<'_>,
scope: GraphicScope,
remaining_depth: usize,
) {
if remaining_depth == 0 {
return;
}
stack.extend(
tag.children()
.top()
.as_slice()
.iter()
.rev()
.map(|child| GraphicStep::Visit(*child, scope, remaining_depth - 1)),
);
}
fn push_graphic_part(
stack: &mut Vec<GraphicStep>,
out: &mut GraphicParts,
tag: &crate::dom::HTMLTag<'_>,
scope: GraphicScope,
remaining_depth: usize,
) {
out.end_part();
stack.push(GraphicStep::EndPart);
push_graphic_children(stack, tag, scope, remaining_depth);
}
fn visit_graphic_tag(
tag: &crate::dom::HTMLTag<'_>,
parser: &Parser<'_>,
scope: GraphicScope,
stack: &mut Vec<GraphicStep>,
out: &mut GraphicParts,
remaining_depth: usize,
) {
let name = normalized_tag_name(tag.name().as_utf8_str());
let nested_svg = |named: bool| GraphicScope::Drawing {
of_svg: true,
named: named && !is_aria_hidden(tag),
};
match (scope, &*name) {
(GraphicScope::Drawing { of_svg, named }, "title" | "desc") => {
if of_svg && named {
push_graphic_part(stack, out, tag, GraphicScope::Label, remaining_depth);
}
}
(GraphicScope::Drawing { .. }, "text") => {
push_graphic_part(stack, out, tag, GraphicScope::Text, remaining_depth);
}
(GraphicScope::Drawing { .. }, "foreignobject") => {
push_graphic_part(stack, out, tag, GraphicScope::Html, remaining_depth);
}
(GraphicScope::Drawing { named, .. }, "svg") => {
push_graphic_children(stack, tag, nested_svg(named), remaining_depth);
}
(GraphicScope::Drawing { named, .. }, "g" | "a") => {
push_graphic_children(
stack,
tag,
GraphicScope::Drawing { of_svg: false, named },
remaining_depth,
);
}
(GraphicScope::Drawing { named, .. }, "switch") if remaining_depth > 0 => {
push_graphic_switch(stack, tag, parser, named, remaining_depth);
}
(GraphicScope::Drawing { .. }, _) => {}
(GraphicScope::Label, _) => push_graphic_children(stack, tag, GraphicScope::Label, remaining_depth),
(GraphicScope::Text, "title" | "desc") | (GraphicScope::Html, "script" | "style" | "template") => {}
(GraphicScope::Text, _) => {
push_graphic_children(stack, tag, GraphicScope::Text, remaining_depth);
if ["x", "y"].iter().any(|key| tag.attributes().get(*key).is_some()) {
stack.push(GraphicStep::Space);
}
}
(GraphicScope::Html, "svg") => {
out.end_part();
stack.push(GraphicStep::EndPart);
push_graphic_children(stack, tag, nested_svg(out.use_accessible_names), remaining_depth);
}
(GraphicScope::Html, "br") => out.current.push(' '),
(GraphicScope::Html, html_name) => {
let is_block = crate::converter::utility::content::is_block_level_element(html_name);
if is_block {
stack.push(GraphicStep::Space);
}
push_graphic_children(stack, tag, GraphicScope::Html, remaining_depth);
if is_block {
stack.push(GraphicStep::Space);
}
}
}
}
fn push_graphic_switch(
stack: &mut Vec<GraphicStep>,
tag: &crate::dom::HTMLTag<'_>,
parser: &Parser<'_>,
named: bool,
remaining_depth: usize,
) {
let first = tag
.children()
.top()
.iter()
.find(|child| {
matches!(child.get(parser), Some(crate::dom::Node::Tag(child_tag))
if system_language_holds(child_tag))
})
.copied();
stack.extend(first.map(|child| {
GraphicStep::Visit(
child,
GraphicScope::Drawing { of_svg: false, named },
remaining_depth - 1,
)
}));
}
pub fn handle_svg(
node_handle: &NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
) {
let MediaContext { options, ctx, .. } = context;
#[cfg(feature = "inline-images")]
if let Some(ref collector_ref) = ctx.inline_collector {
collect_inline_svg(collector_ref, *node_handle, tag, parser, context.dom_ctx);
}
if options.skip_images {
return;
}
let inline_data = super::inline_data_treatment(options.inline_data_media, "data:image/svg+xml");
if inline_data == crate::options::InlineDataMedia::DropElement {
ctx.inline_data_replaced.set(true);
return;
}
let title = graphic_text(tag, parser, options, ctx.accessible_names);
#[cfg(feature = "metadata")]
crate::converter::heading_metadata::append(ctx, &title);
if ctx.in_code || ctx.convert_as_inline || inline_data == crate::options::InlineDataMedia::AltTextOnly {
super::record_text_label(&title, ctx);
}
if ctx.in_code {
output.push_str(&title);
} else if ctx.convert_as_inline || inline_data == crate::options::InlineDataMedia::AltTextOnly {
write_graphic_as_text(*node_handle, parser, output, context, &title);
} else {
write_graphic_as_image(*node_handle, parser, output, context, &title);
}
}
#[cfg(feature = "inline-images")]
fn collect_inline_svg(
collector_ref: &InlineCollectorHandle,
node_handle: NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &Parser,
dom_ctx: &crate::converter::DomContext,
) {
let title_opt = tag
.children()
.top()
.iter()
.find(|child| {
matches!(child.get(parser), Some(crate::dom::Node::Tag(child_tag))
if child_tag.name().as_utf8_str().eq_ignore_ascii_case("title"))
})
.map(|child| {
crate::converter::utility::content::get_text_content(child, parser, dom_ctx)
.trim()
.to_string()
});
let mut attributes_map = BTreeMap::new();
for (key, value_opt) in tag.attributes().iter() {
let key_str = key.to_string();
let keep = key_str == "width"
|| key_str == "height"
|| key_str == "filename"
|| key_str == "aria-label"
|| key_str.starts_with("data-");
if keep {
let value = value_opt.map(|value| value.to_string()).unwrap_or_default();
attributes_map.insert(key_str, value);
}
}
handle_inline_svg(collector_ref, &node_handle, parser, title_opt, attributes_map);
}
fn write_graphic_as_text(
node_handle: NodeHandle,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
title: &str,
) {
let MediaContext {
options, ctx, dom_ctx, ..
} = context;
let escaped = crate::text::escape(
title,
options.escape_misc,
options.escape_asterisks,
options.escape_underscores,
options.escape_ascii,
);
if !escaped.is_empty() {
crate::converter::text_node::push_running_text(
output,
&escaped,
crate::converter::text_node::TextSite {
node_handle: &node_handle,
parser,
options,
ctx,
dom_ctx,
},
);
}
}
fn write_graphic_as_image(
node_handle: NodeHandle,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
title: &str,
) {
use base64::{Engine as _, engine::general_purpose::STANDARD};
let MediaContext { options, depth, .. } = context;
let max_depth = effective_max_depth(options).min(depth.saturating_add(NATIVE_STACK_SAFE_DEPTH));
let svg_html = serialize_element_at_depth(&node_handle, parser, depth, max_depth);
let base64_svg = STANDARD.encode(svg_html.as_bytes());
output.push_str(";
output.push_str(&base64_svg);
output.push(')');
}
pub fn handle_math(
node_handle: &NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
) {
let MediaContext {
options, ctx, dom_ctx, ..
} = context;
use crate::converter::utility::content::get_math_text_content;
use crate::text;
let text_content = get_math_text_content(node_handle, parser, dom_ctx, options.hidden_content);
if text_content.is_empty() {
return;
}
let escaped_text = text::escape(
&text_content,
options.escape_misc,
options.escape_asterisks,
options.escape_underscores,
options.escape_ascii,
);
let is_display_block = tag
.attributes()
.get("display")
.flatten()
.is_some_and(|v| v.as_utf8_str() == "block");
if is_display_block && !ctx.in_paragraph && !ctx.convert_as_inline {
output.push_str("\n\n");
}
output.push_str(&escaped_text);
if is_display_block && !ctx.in_paragraph && !ctx.convert_as_inline {
output.push_str("\n\n");
}
}
#[cfg(test)]
mod tests {
#[test]
fn should_escape_svg_title_caption_that_would_open_a_new_image_link() {
let html = "<svg><title>a](https://evil.example/payload)</title></svg>";
let result = crate::convert(html, None).unwrap();
let content = result.content.unwrap_or_default();
assert_eq!(
content,
"](data:image/svg+xml;base64,\
PHN2Zz48dGl0bGU+YV0oaHR0cHM6Ly9ldmlsLmV4YW1wbGUvcGF5bG9hZCk8L3RpdGxlPjwvc3ZnPg==)\n"
);
}
}
#[cfg(test)]
mod attribute_escaping_tests {
use super::serialize_element;
#[test]
fn should_escape_a_quote_inside_a_reconstructed_attribute_value() {
let html = r#"<foo title='x" onclick="alert(1)" y=' data-safe="1">"#;
let dom = crate::dom::parse(html, crate::dom::ParserOptions).unwrap();
let parser = dom.parser();
let node_handle = dom
.children()
.iter()
.find(|handle| matches!(handle.get(parser), Some(crate::dom::Node::Tag(_))))
.expect("tag node");
let result = serialize_element(node_handle, parser);
assert_eq!(
result,
"<foo data-safe=\"1\" title=\"x" onclick="alert(1)" y=\" />"
);
}
}