use crate::dom::{NodeHandle, Parser};
type DomContext = crate::converter::DomContext;
type Context = crate::converter::Context;
type ConversionOptions = crate::options::ConversionOptions;
#[derive(Clone, Copy)]
pub struct InlineSite<'p> {
pub node_handle: &'p NodeHandle,
pub parser: &'p Parser<'p>,
pub dom_ctx: &'p DomContext,
pub ctx: &'p Context,
pub options: &'p ConversionOptions,
}
pub const EMPHASIS_SIBLING_TAGS: [&str; 4] = ["em", "i", "var", "dfn"];
pub const STRONG_SIBLING_TAGS: [&str; 2] = ["strong", "b"];
#[derive(Clone, Copy)]
pub struct InlineDelimiters<'a> {
pub open: &'a str,
pub close: &'a str,
pub merge_symbol: Option<char>,
pub sibling_tag_names: &'a [&'a str],
}
pub fn wrap_block_runs(content: &str, open: &str, close: &str) -> String {
let (prefix, suffix, trimmed) = crate::converter::chomp_inline(content);
let mut wrapped = String::with_capacity(content.len() + open.len() + close.len());
wrapped.push_str(prefix);
for (index, block) in trimmed.split("\n\n").enumerate() {
if index > 0 {
wrapped.push_str("\n\n");
}
if block.trim_matches([' ', '\t']).is_empty() {
wrapped.push_str(block);
} else {
let body_start = markdown_block_prefix_len(block);
let body_end = block.trim_end_matches([' ', '\t']).len();
if body_end <= body_start {
wrapped.push_str(block);
continue;
}
wrapped.push_str(&block[..body_start]);
wrapped.push_str(open);
wrapped.push_str(&block[body_start..body_end]);
wrapped.push_str(close);
wrapped.push_str(&block[body_end..]);
}
}
wrapped.push_str(suffix);
wrapped
}
pub fn needs_block_wrapping(content: &str) -> bool {
let is_heading = |block: &str| {
let block = block.trim_start_matches([' ', '\t']);
block.starts_with('#') && markdown_block_prefix_len(block) > 0
};
let trimmed = content.trim();
(is_heading(trimmed) && !trimmed.contains('\n'))
|| (block_runs_are_single_line(content)
&& content.contains("\n\n")
&& content.split("\n\n").all(|block| {
let indentation = block.bytes().take_while(|byte| matches!(byte, b' ' | b'\t')).count();
is_heading(block) || markdown_block_prefix_len(block) == indentation
}))
}
pub fn block_runs_are_single_line(content: &str) -> bool {
content.split("\n\n").all(|block| !block.contains('\n'))
}
pub fn emit_first_block_wrapped(
output: &mut String,
content: &str,
open: &str,
close: &str,
ctx: &Context,
parser: &Parser<'_>,
) -> bool {
if open.is_empty()
|| !ctx
.first_writer
.as_ref()
.is_some_and(|first_writer| first_writer.starts_with_blockquote(parser))
|| !block_runs_are_single_line(content.trim_end_matches('\n'))
|| !crate::converter::utility::escaping::opens_block(content.trim_start())
{
return false;
}
output.push_str(&wrap_block_runs(content, open, close));
true
}
fn markdown_block_prefix_len(block: &str) -> usize {
let bytes = block.as_bytes();
let mut position = bytes.iter().take_while(|byte| matches!(byte, b' ' | b'\t')).count();
while bytes.get(position..position + 2) == Some(b"> ") {
position += 2;
}
if matches!(bytes.get(position), Some(b'-' | b'+' | b'*')) && matches!(bytes.get(position + 1), Some(b' ' | b'\t'))
{
return position + 2;
}
let digits_start = position;
while bytes.get(position).is_some_and(u8::is_ascii_digit) {
position += 1;
}
if position > digits_start
&& matches!(bytes.get(position), Some(b'.' | b')'))
&& matches!(bytes.get(position + 1), Some(b' ' | b'\t'))
{
return position + 2;
}
let heading_start = position;
while bytes.get(position) == Some(&b'#') && position - heading_start < 6 {
position += 1;
}
if position > heading_start && bytes.get(position) == Some(&b' ') {
return position + 1;
}
digits_start
}
fn blank_break_content<'a>(
content: &'a str,
after_breaks: &'a str,
output: &str,
drop_at_paragraph_start: bool,
options: &ConversionOptions,
) -> &'a str {
if drop_at_paragraph_start {
let marker = crate::converter::main_helpers::hard_break_marker(options);
if content.ends_with(marker) && content.trim_end_matches(marker).trim().is_empty() {
""
} else {
after_breaks
}
} else if after_breaks.len() < content.len() && !content.ends_with('\n') {
if after_breaks
.chars()
.all(crate::converter::utility::white_space::is_collapsible)
{
&content[..content.len() - after_breaks.len()]
} else {
" "
}
} else if output.is_empty()
&& content.ends_with('\n')
&& content
.trim_end_matches(crate::converter::main_helpers::hard_break_marker(options))
.chars()
.all(crate::converter::utility::white_space::is_collapsible)
{
&content[content.len() - 1..]
} else {
content
}
}
fn inline_break_owner(output: &String, ctx: &Context) -> Option<usize> {
let (address, start) = ctx
.inline_break_owner
.unwrap_or((ctx.block_output_ptr, ctx.block_content_start));
(std::ptr::from_ref(output) as usize == address).then_some(start)
}
fn move_leading_hard_breaks<'a>(
output: &mut String,
content: &'a str,
ctx: &Context,
options: &ConversionOptions,
) -> &'a str {
if ctx.in_table_cell {
return content;
}
let mut after_breaks = content;
loop {
let candidate = after_breaks.trim_start_matches([' ', '\t']);
let Some(rest) = ["\\\n", "\n"]
.into_iter()
.find_map(|marker| candidate.strip_prefix(marker))
else {
break;
};
after_breaks = rest;
}
let drop_at_paragraph_start = inline_break_owner(output, ctx) == Some(output.len());
if after_breaks
.trim_end_matches(crate::converter::main_helpers::hard_break_marker(options))
.trim()
.is_empty()
{
return blank_break_content(content, after_breaks, output, drop_at_paragraph_start, options);
}
let mut remaining = content;
let mut moved = false;
loop {
let candidate = remaining.trim_start_matches([' ', '\t']);
let Some((marker, rest)) = ["\\\n", "\n"]
.into_iter()
.find_map(|marker| candidate.strip_prefix(marker).map(|rest| (marker, rest)))
else {
break;
};
if !drop_at_paragraph_start {
let starts_on_empty_line = output.ends_with('\n');
crate::converter::list::utils::indent_list_item_line_start(output, ctx, options);
let marker = if marker == "\n" {
crate::converter::main_helpers::hard_break_marker(options)
} else {
marker
};
output.push_str(if marker == " \n" && starts_on_empty_line {
"\\\n"
} else {
marker
});
}
remaining = rest;
moved = true;
}
if moved && !drop_at_paragraph_start {
crate::converter::list::utils::indent_list_item_line_start(output, ctx, options);
}
if moved {
remaining = remaining.trim_start_matches([' ', '\t']);
}
remaining
}
fn emit_break_sentinel(output: &mut String, content: &str, ctx: &Context, options: &ConversionOptions) -> bool {
if content != "\n" {
return false;
}
let owner_start = inline_break_owner(output, ctx);
if owner_start == Some(output.len()) {
return true;
}
output.push_str(if output.is_empty() && owner_start.is_none() {
"\n"
} else {
crate::converter::main_helpers::hard_break_marker(options)
});
true
}
#[cfg(test)]
thread_local! {
static BLANK_PREFIX_NODE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn has_leading_blank_source(site: InlineSite<'_>) -> bool {
site.dom_ctx
.children_of(site.node_handle.get_inner())
.and_then(|children| children.first())
.inspect(|_| {
#[cfg(test)]
BLANK_PREFIX_NODE_READS.with(|reads| reads.set(reads.get() + 1));
})
.and_then(|child| child.get(site.parser))
.is_some_and(|node| {
matches!(node, crate::dom::Node::Raw(raw)
if raw.as_utf8_str().starts_with(crate::converter::utility::white_space::is_collapsible))
})
}
fn keeps_hard_break(content: &str, site: InlineSite<'_>) -> bool {
let marker = crate::converter::main_helpers::hard_break_marker(site.options);
let body = content.trim_start_matches([' ', '\t']);
let lone = body == "\n" || body == marker;
((content.len() > marker.len() && content.ends_with(marker))
|| (lone && (site.ctx.block_content_start != 0 || site.ctx.in_link)))
&& !site
.dom_ctx
.children_of(site.node_handle.get_inner())
.and_then(|children| children.last())
.and_then(|child| child.get(site.parser))
.is_some_and(|node| {
matches!(node, crate::dom::Node::Raw(raw)
if raw.as_utf8_str().ends_with(crate::converter::utility::white_space::is_collapsible))
})
}
fn strong_separator_content<'a>(output: &str, content: &'a str, keeps_break: bool, site: InlineSite<'_>) -> &'a str {
let ctx = site.ctx;
if keeps_break
|| !content.ends_with('\n')
|| !content
.trim_end_matches(crate::converter::main_helpers::hard_break_marker(site.options))
.chars()
.all(crate::converter::utility::white_space::is_collapsible)
|| ctx.in_strong
|| ctx.in_code
|| ctx.in_code_block
{
return content;
}
if (has_leading_blank_source(site)
|| site
.dom_ctx
.tag_info(site.node_handle.get_inner(), site.parser)
.is_some_and(|tag| EMPHASIS_SIBLING_TAGS.contains(&tag.name.as_str())))
&& site
.dom_ctx
.holds_authored_break(site.node_handle.get_inner(), site.parser)
{
return content;
}
let previous =
crate::converter::utility::siblings::get_previous_sibling_tag(site.node_handle, site.parser, site.dom_ctx);
if !previous.is_some_and(|tag| {
STRONG_SIBLING_TAGS.contains(&tag) && !ctx.strip_tags.contains(tag) && !ctx.preserve_tags.contains(tag)
}) {
return content;
}
let marker = if site.options.output_format == crate::options::OutputFormat::Djot {
String::from("*")
} else {
[site.options.strong_em_symbol; 2].iter().collect()
};
if output.ends_with(&marker) { " " } else { content }
}
fn strict_blank_separator<'a>(content: &'a str, site: InlineSite<'_>) -> &'a str {
if site.options.whitespace_mode == crate::options::WhitespaceMode::Strict
&& !site.ctx.in_code
&& !site.ctx.in_code_block
&& content.contains('\n')
&& content
.chars()
.all(crate::converter::utility::white_space::is_collapsible)
&& !site
.dom_ctx
.holds_authored_break(site.node_handle.get_inner(), site.parser)
{
" "
} else {
content
}
}
fn inline_edges<'a>(content: &'a str, options: &crate::options::ConversionOptions) -> (&'a str, &'a str, &'a str) {
use crate::converter::chomp_inline;
let (mut prefix, mut suffix, trimmed) = chomp_inline(content);
if options.whitespace_mode == crate::options::WhitespaceMode::Normalized && !trimmed.is_empty() {
if content.starts_with(crate::text::is_unicode_space) {
prefix = " ";
}
if content.ends_with(crate::text::is_unicode_space) {
suffix = " ";
}
}
(prefix, suffix, trimmed)
}
fn emit_blank_wrapper(output: &mut String, content: &str, prefix: &str, suffix: &str, site: InlineSite<'_>) -> bool {
let InlineSite {
node_handle,
parser,
dom_ctx,
ctx,
options,
} = site;
let marker = crate::converter::main_helpers::hard_break_marker(options);
let blank_body = content.trim_end_matches(marker);
if output.ends_with([' ', '\t'])
&& !content.starts_with(crate::converter::utility::white_space::is_collapsible)
&& blank_body.chars().all(char::is_whitespace)
&& !blank_body
.chars()
.all(crate::converter::utility::white_space::is_collapsible)
{
let body = blank_body.trim_matches(crate::converter::utility::white_space::is_collapsible);
output.push_str(body);
let breaks = &content[blank_body.len()..];
if breaks.is_empty() {
crate::converter::append_inline_suffix(output, suffix, !body.is_empty(), node_handle, parser, dom_ctx);
} else {
output.push_str(breaks);
}
return true;
}
if blank_body.trim().is_empty() {
if content.is_empty() {
return true;
}
if crate::converter::utility::white_space::space_is_owed_in(output, ctx) {
output.push_str(prefix);
}
crate::converter::append_inline_suffix(output, suffix, false, node_handle, parser, dom_ctx);
return true;
}
false
}
pub fn emit_wrapped_inline(
output: &mut String,
content: &str,
delimiters: &InlineDelimiters<'_>,
site: InlineSite<'_>,
) {
let InlineSite {
node_handle,
parser,
dom_ctx,
ctx,
options,
} = site;
let InlineDelimiters {
open,
close,
merge_symbol,
sibling_tag_names,
} = *delimiters;
use crate::converter::utility::siblings::get_previous_sibling_tag;
use crate::converter::{append_inline_suffix, merge_adjacent_emphasis};
if !open.is_empty() && content.trim_start().starts_with('#') && needs_block_wrapping(content) {
output.push_str(&wrap_block_runs(content, open, close));
return;
}
let moved = move_leading_hard_breaks(output, strict_blank_separator(content, site), ctx, options);
let content = strong_separator_content(output, moved, keeps_hard_break(content, site), site);
let (prefix, suffix, trimmed) = inline_edges(content, options);
if emit_break_sentinel(output, content, ctx, options) {
return;
}
if emit_blank_wrapper(output, content, prefix, suffix, site) {
return;
}
crate::converter::utility::content::push_inline_prefix(output, prefix, options, ctx);
let sibling_is_matching_tag =
get_previous_sibling_tag(node_handle, parser, dom_ctx).is_some_and(|name| sibling_tag_names.contains(&name));
let merged = prefix.is_empty()
&& sibling_is_matching_tag
&& merge_symbol.is_some_and(|symbol| {
open.chars().all(|c| c == symbol) && merge_adjacent_emphasis(output, symbol, open.chars().count())
});
if !merged {
output.push_str(open);
}
output.push_str(trimmed);
output.push_str(close);
append_inline_suffix(output, suffix, !trimmed.is_empty(), node_handle, parser, dom_ctx);
}
pub fn emit_code_span(
span: &str,
content: &str,
output: &mut String,
node_handle: &NodeHandle,
parser: &Parser,
dom_ctx: &DomContext,
) {
use crate::converter::merge_adjacent_emphasis;
use crate::converter::utility::siblings::get_previous_sibling_tag;
let is_plain_single_backtick_pair =
span.len() == content.len() + 2 && span.starts_with('`') && span.ends_with('`') && !content.contains('`');
let previous_is_code_sibling = get_previous_sibling_tag(node_handle, parser, dom_ctx)
.is_some_and(|name| matches!(name, "code" | "kbd" | "samp"));
if is_plain_single_backtick_pair && previous_is_code_sibling && merge_adjacent_emphasis(output, '`', 1) {
output.push_str(&span[1..]);
} else {
output.push_str(span);
}
}
pub fn emit_whitespace_only_inline_body(content: &str, output: &mut String) {
use crate::converter::chomp_inline;
let (prefix, _, _) = chomp_inline(content);
if !output.ends_with(' ') {
output.push_str(prefix);
}
}
#[cfg(test)]
mod tests {
#[test]
#[allow(clippy::print_stdout)]
fn should_bound_nested_blank_break_prefix_and_content_reads() {
let mut jobs = 0;
for depth in [4, 16, 64, 256] {
for newline_style in [crate::NewlineStyle::Spaces, crate::NewlineStyle::Backslash] {
let source = format!("<p><b>a</b>{}<br>{}b</p>", "<em>".repeat(depth), "</em>".repeat(depth));
let dom = crate::dom::parse(&source, crate::dom::ParserOptions).expect("nested break nodes");
let nodes = dom.nodes().len();
assert_eq!(nodes, depth + 5);
super::BLANK_PREFIX_NODE_READS.with(|reads| reads.set(0));
crate::converter::dom_context::AUTHORED_BREAK_CACHE_STATS.with(|stats| stats.set((0, 0)));
crate::converter::dom_context::HOLDS_TEXT_NODE_READS.with(|reads| reads.set(0));
let result = crate::convert(
&source,
crate::ConversionOptions {
tier_strategy: crate::TierStrategy::Tier2,
extract_metadata: false,
newline_style,
max_depth: Some(1024),
..Default::default()
},
)
.expect("nested breaks");
let prefix_reads = super::BLANK_PREFIX_NODE_READS.with(std::cell::Cell::get);
let content_reads = crate::converter::dom_context::HOLDS_TEXT_NODE_READS.with(std::cell::Cell::get);
let marker = if newline_style == crate::NewlineStyle::Spaces {
" \n"
} else {
"\\\n"
};
assert_eq!(result.content.as_deref(), Some(format!("**a**{marker}b\n").as_str()));
assert_eq!(prefix_reads, depth);
assert_eq!(content_reads, depth);
let (entries, capacity) =
crate::converter::dom_context::AUTHORED_BREAK_CACHE_STATS.with(std::cell::Cell::get);
assert_eq!(entries, depth);
assert!(capacity <= 2 * depth);
assert!(content_reads > 0 && content_reads <= 4 * nodes);
std::println!(
"break-cost {depth} {nodes} {prefix_reads} {content_reads} {entries} {capacity} {newline_style:?}"
);
jobs += 1;
}
}
assert_eq!(jobs, 8);
}
use super::move_leading_hard_breaks;
use crate::converter::Context;
use crate::converter::context::ContextParameters;
use crate::converter::url_resolve::OwnPage;
use crate::options::ConversionOptions;
#[test]
fn should_drop_break_only_content_in_the_paragraphs_own_empty_buffer() {
let options = ConversionOptions::default();
let mut output = String::new();
let mut context = Context::new(
&options,
ContextParameters {
accessible_names: Default::default(),
inline_collector: None,
#[cfg(feature = "metadata")]
metadata_collector: None,
kept_scripts: crate::converter::utility::preprocessing::KeptScripts::default(),
#[cfg(feature = "visitor")]
visitor: None,
structure_collector: None,
reference_collector: None,
base_url: None,
own_page: OwnPage::UnknownWithoutBase,
},
);
context.in_paragraph = true;
context.block_output_ptr = std::ptr::from_ref::<String>(&output) as usize;
let remaining = move_leading_hard_breaks(&mut output, " \n", &context, &options);
assert_eq!(remaining, "");
assert_eq!(output, "");
}
}