use crate::converter::inline::wrapped::{InlineDelimiters, emit_wrapped_inline};
use crate::options::{ConversionOptions, OutputFormat};
#[cfg(feature = "visitor")]
use std::borrow::Cow;
use tl::{NodeHandle, Parser};
type Context = crate::converter::Context;
type DomContext = crate::converter::DomContext;
pub fn handle_mark(
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
#[allow(unused_imports)]
use crate::converter::{get_text_content, serialize_node, walk_node};
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
#[cfg(feature = "visitor")]
let mark_output = if let Some(ref visitor_handle) = ctx.visitor {
use crate::visitor::{NodeContext, NodeType, VisitResult};
let text_content = get_text_content(node_handle, parser, dom_ctx);
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Mark,
tag.name().as_utf8_str(),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
true,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_mark(&node_ctx, &text_content)
};
match visit_result {
VisitResult::Continue => None,
VisitResult::Custom(custom) => Some(custom),
VisitResult::Skip => Some(String::new()),
VisitResult::PreserveHtml => Some(serialize_node(node_handle, parser)),
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
None
}
}
} else {
None
};
#[cfg(feature = "visitor")]
if let Some(custom_output) = mark_output {
output.push_str(&custom_output);
return;
}
if ctx.convert_as_inline {
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
return;
}
use crate::options::HighlightStyle;
let child_ctx = if options.highlight_style == HighlightStyle::Bold {
Context {
in_strong: true,
..ctx.clone()
}
} else {
ctx.clone()
};
let mut content = String::with_capacity(32);
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(
child_handle,
parser,
&mut content,
options,
&child_ctx,
depth + 1,
dom_ctx,
);
}
let (open, close, merge_symbol) = resolve_mark_delimiters(options);
emit_wrapped_inline(
output,
&content,
&InlineDelimiters {
open: &open,
close: &close,
merge_symbol,
sibling_tag_names: &MARK_SIBLING_TAGS,
},
node_handle,
parser,
dom_ctx,
);
}
fn resolve_mark_delimiters(options: &ConversionOptions) -> (String, String, Option<char>) {
use crate::options::HighlightStyle;
match options.highlight_style {
HighlightStyle::DoubleEqual => {
if options.output_format == OutputFormat::Djot {
("{=".to_owned(), "=}".to_owned(), None)
} else {
("==".to_owned(), "==".to_owned(), Some('='))
}
}
HighlightStyle::Html => ("<mark>".to_owned(), "</mark>".to_owned(), None),
HighlightStyle::Bold => {
let marker: String = [options.strong_em_symbol; 2].iter().collect();
(marker.clone(), marker, Some(options.strong_em_symbol))
}
HighlightStyle::None => (String::new(), String::new(), None),
}
}
const STRIKETHROUGH_SIBLING_TAGS: [&str; 3] = ["del", "s", "strike"];
const INSERTED_SIBLING_TAGS: [&str; 1] = ["ins"];
const MARK_SIBLING_TAGS: [&str; 1] = ["mark"];
fn emit_strikethrough_wrapped(
output: &mut String,
content: &str,
options: &ConversionOptions,
node_handle: &NodeHandle,
parser: &Parser,
dom_ctx: &DomContext,
) {
if options.output_format == OutputFormat::Djot {
emit_wrapped_inline(
output,
content,
&InlineDelimiters {
open: "{-",
close: "-}",
merge_symbol: None,
sibling_tag_names: &STRIKETHROUGH_SIBLING_TAGS,
},
node_handle,
parser,
dom_ctx,
);
} else {
emit_wrapped_inline(
output,
content,
&InlineDelimiters {
open: "~~",
close: "~~",
merge_symbol: Some('~'),
sibling_tag_names: &STRIKETHROUGH_SIBLING_TAGS,
},
node_handle,
parser,
dom_ctx,
);
}
}
fn emit_inserted_wrapped(
output: &mut String,
content: &str,
options: &ConversionOptions,
node_handle: &NodeHandle,
parser: &Parser,
dom_ctx: &DomContext,
) {
if options.output_format == OutputFormat::Djot {
emit_wrapped_inline(
output,
content,
&InlineDelimiters {
open: "{+",
close: "+}",
merge_symbol: None,
sibling_tag_names: &INSERTED_SIBLING_TAGS,
},
node_handle,
parser,
dom_ctx,
);
} else {
emit_wrapped_inline(
output,
content,
&InlineDelimiters {
open: "==",
close: "==",
merge_symbol: Some('='),
sibling_tag_names: &INSERTED_SIBLING_TAGS,
},
node_handle,
parser,
dom_ctx,
);
}
}
#[allow(unused_variables)]
pub fn handle_strikethrough(
tag_name: &str,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
use crate::converter::walk_node;
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
if ctx.in_code {
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
} else {
let mut content = String::with_capacity(32);
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, &mut content, options, ctx, depth + 1, dom_ctx);
}
#[cfg(feature = "visitor")]
let strikethrough_output = if let Some(ref visitor_handle) = ctx.visitor {
use crate::converter::get_text_content;
use crate::visitor::{NodeContext, NodeType, VisitResult};
let text_content = get_text_content(node_handle, parser, dom_ctx);
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Strikethrough,
Cow::Borrowed(tag_name),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
true,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_strikethrough(&node_ctx, &text_content)
};
match visit_result {
VisitResult::Continue => None,
VisitResult::Custom(custom) => Some(custom),
VisitResult::Skip => Some(String::new()),
VisitResult::PreserveHtml => {
use crate::converter::serialize_node;
Some(serialize_node(node_handle, parser))
}
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
None
}
}
} else {
None
};
#[cfg(feature = "visitor")]
if let Some(custom_output) = strikethrough_output {
output.push_str(&custom_output);
} else {
emit_strikethrough_wrapped(output, &content, options, node_handle, parser, dom_ctx);
}
#[cfg(not(feature = "visitor"))]
{
emit_strikethrough_wrapped(output, &content, options, node_handle, parser, dom_ctx);
}
}
}
pub fn handle_inserted(
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
use crate::converter::walk_node;
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
if ctx.in_code {
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
return;
}
let mut content = String::with_capacity(32);
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, &mut content, options, ctx, depth + 1, dom_ctx);
}
#[cfg(feature = "visitor")]
let underline_output = if let Some(ref visitor_handle) = ctx.visitor {
use crate::converter::get_text_content;
use crate::visitor::{NodeContext, NodeType, VisitResult};
let text_content = get_text_content(node_handle, parser, dom_ctx);
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Underline,
Cow::Borrowed("ins"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
true,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_underline(&node_ctx, &text_content)
};
match visit_result {
VisitResult::Continue => None,
VisitResult::Custom(custom) => Some(custom),
VisitResult::Skip => Some(String::new()),
VisitResult::PreserveHtml => {
use crate::converter::serialize_node;
Some(serialize_node(node_handle, parser))
}
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
None
}
}
} else {
None
};
#[cfg(feature = "visitor")]
if let Some(custom_output) = underline_output {
output.push_str(&custom_output);
} else {
emit_inserted_wrapped(output, &content, options, node_handle, parser, dom_ctx);
}
#[cfg(not(feature = "visitor"))]
{
emit_inserted_wrapped(output, &content, options, node_handle, parser, dom_ctx);
}
}
pub fn handle_underline(
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
use crate::converter::walk_node;
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
#[cfg(feature = "visitor")]
if let Some(ref visitor_handle) = ctx.visitor {
use crate::converter::get_text_content;
use crate::visitor::{NodeContext, NodeType, VisitResult};
let text_content = get_text_content(node_handle, parser, dom_ctx);
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Underline,
Cow::Borrowed("u"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
true,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_underline(&node_ctx, &text_content)
};
match visit_result {
VisitResult::Continue => {
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
}
VisitResult::Custom(custom) => {
output.push_str(&custom);
}
VisitResult::Skip => {}
VisitResult::PreserveHtml => {
use crate::converter::serialize_node;
output.push_str(&serialize_node(node_handle, parser));
}
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
}
}
} else {
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
}
#[cfg(not(feature = "visitor"))]
{
let children = tag.children();
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
}
}
#[cfg(all(test, feature = "visitor"))]
mod tests {
use crate::convert;
use crate::options::ConversionOptions;
use crate::visitor::{HtmlVisitor, NodeContext, VisitResult};
use std::sync::{Arc, Mutex};
#[derive(Debug)]
struct MarkSkipVisitor;
impl HtmlVisitor for MarkSkipVisitor {
fn visit_mark(&mut self, _ctx: &NodeContext, _text: &str) -> VisitResult {
VisitResult::Skip
}
}
#[derive(Debug)]
struct MarkCustomVisitor;
impl HtmlVisitor for MarkCustomVisitor {
fn visit_mark(&mut self, _ctx: &NodeContext, _text: &str) -> VisitResult {
VisitResult::Custom("REPLACED".to_string())
}
}
#[derive(Debug)]
struct MarkPreserveVisitor;
impl HtmlVisitor for MarkPreserveVisitor {
fn visit_mark(&mut self, _ctx: &NodeContext, _text: &str) -> VisitResult {
VisitResult::PreserveHtml
}
}
fn make_visitor<V: HtmlVisitor + 'static>(v: V) -> ConversionOptions {
ConversionOptions {
visitor: Some(Arc::new(Mutex::new(v))),
..ConversionOptions::default()
}
}
#[test]
fn test_visitor_mark_skip() {
let html = "<p>before <mark>highlighted</mark> after</p>";
let result = convert(html, Some(make_visitor(MarkSkipVisitor))).unwrap();
let content = result.content.unwrap_or_default();
assert!(
!content.contains("highlighted"),
"mark content should be absent: {content}"
);
assert!(
content.contains("before"),
"surrounding text should be present: {content}"
);
}
#[test]
fn test_visitor_mark_custom() {
let html = "<p>before <mark>highlighted</mark> after</p>";
let result = convert(html, Some(make_visitor(MarkCustomVisitor))).unwrap();
let content = result.content.unwrap_or_default();
assert!(
content.contains("REPLACED"),
"custom output should be present: {content}"
);
}
#[test]
fn test_visitor_mark_preserve_html() {
let html = "<p>before <mark>highlighted</mark> after</p>";
let result = convert(html, Some(make_visitor(MarkPreserveVisitor))).unwrap();
let content = result.content.unwrap_or_default();
assert!(
content.contains("<mark>highlighted</mark>"),
"original html should be preserved: {content}"
);
}
}