use crate::converter::list::ListContext;
use crate::converter::list::utils::add_list_leading_separator;
use crate::converter::main_helpers::effective_max_depth;
use crate::converter::main_helpers::strip_trailing_backslash_breaks;
use crate::converter::main_helpers::trim_trailing_whitespace;
use crate::converter::utility::content::normalized_tag_name;
use crate::converter::walk_node;
use crate::options::{ConversionOptions, NewlineStyle, OutputFormat};
#[cfg(feature = "visitor")]
use std::borrow::Cow;
type Context = crate::converter::Context;
type DomContext = crate::converter::DomContext;
pub fn handle_li(
node_handle: &crate::dom::NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
context: ListContext<'_>,
) {
let mut line_after_text = None;
write_li(node_handle, tag, parser, output, context, &mut line_after_text);
if let Some(line_start) = line_after_text {
if line_start < output.len()
&& crate::converter::list::utils::marker_line_after_text_needs_blank_line(output, line_start)
{
output.insert(line_start, '\n');
}
}
}
#[derive(Clone, Copy)]
struct TaskInfo {
is_task: bool,
checked: bool,
checkbox: Option<crate::dom::NodeHandle>,
}
enum FirstContent {
Checkbox(bool, crate::dom::NodeHandle),
Other,
Nothing,
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn find_checkbox<'a>(
node_handle: &crate::dom::NodeHandle,
parser: &'a crate::dom::Parser<'a>,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
) -> FirstContent {
let mut pending = vec![(*node_handle, depth)];
while let Some((handle, depth)) = pending.pop() {
if depth >= effective_max_depth(options) {
ctx.depth_limit_reached.set(true);
return FirstContent::Other;
}
match handle.get(parser) {
Some(crate::dom::Node::Raw(raw)) if !raw.as_utf8_str().trim().is_empty() => return FirstContent::Other,
Some(crate::dom::Node::Tag(tag)) => {
match normalized_tag_name(tag.name().as_utf8_str()).as_ref() {
"input" => {
if let Some(checked) = crate::converter::form::elements::checkbox_state(tag) {
return FirstContent::Checkbox(checked, handle);
}
continue;
}
"ul" | "ol" | "img" | "hr" => return FirstContent::Other,
"script" | "style" | "template" | "noscript" => continue,
_ => {}
}
let start = pending.len();
pending.extend(tag.children().top().iter().copied().map(|handle| (handle, depth + 1)));
pending[start..].reverse();
}
_ => {}
}
}
FirstContent::Nothing
}
impl TaskInfo {
fn new(node_handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser, context: ListContext<'_>) -> Self {
match find_checkbox(node_handle, parser, context.options, context.ctx, context.depth) {
FirstContent::Checkbox(checked, checkbox) => Self {
is_task: true,
checked,
checkbox: Some(checkbox),
},
FirstContent::Other | FirstContent::Nothing => Self {
is_task: false,
checked: false,
checkbox: None,
},
}
}
}
struct ItemMarker<'a> {
task: TaskInfo,
numbered: bool,
ctx: &'a Context,
options: &'a ConversionOptions,
}
impl<'a> ItemMarker<'a> {
fn new(task: TaskInfo, ctx: &'a Context, options: &'a ConversionOptions) -> Self {
let numbered = ctx.in_ordered_list && !(task.is_task && options.output_format == OutputFormat::Djot);
Self {
task,
numbered,
ctx,
options,
}
}
fn list_marker(&self) -> String {
if self.numbered {
format!(
"{}{} ",
self.ctx.list_counter,
self.ctx.ordered_delimiter.unwrap_or('.')
)
} else if self.task.is_task {
String::from("- ")
} else {
format!("{} ", unordered_bullet(self.ctx, self.options))
}
}
fn full_marker(&self) -> String {
if self.task.is_task {
format!(
"{}{} ",
self.list_marker(),
if self.task.checked { "[x]" } else { "[ ]" }
)
} else {
self.list_marker()
}
}
fn width(&self) -> usize {
if self.numbered {
self.options
.list_indent_width
.max(format!("{}. ", self.ctx.list_counter).chars().count())
} else {
self.options.list_indent_width.max(2)
}
}
}
fn separate_marker_from_text(output: &mut String, marker: &ItemMarker<'_>, line_after_text: &mut Option<usize>) {
let line_start = output.rfind('\n').map_or(0, |position| position + 1);
if marker.ctx.in_table_cell
|| output[line_start..].trim().is_empty()
|| crate::converter::list::utils::line_is_bare_list_marker(output)
{
return;
}
output.push('\n');
if crate::converter::utility::escaping::line_opens_block(&format!("{}x", marker.full_marker())) {
if !marker.ctx.in_marker_text() {
*line_after_text = Some(output.len());
}
} else {
output.push('\n');
}
}
fn marker_column(output: &mut String, ctx: &Context, options: &ConversionOptions) -> (Option<usize>, usize) {
let marker_line_start = (!output.is_empty() && output.ends_with('\n')).then_some(output.len());
let marker_follows_markers = output.is_empty() && ctx.in_marker_text();
let buffer_column = ctx
.inline_buffer_column
.filter(|_| output.is_empty() && !marker_follows_markers);
let column = if let Some(column) = buffer_column {
column
} else if ctx.list_depth > 0 && (output.is_empty() || output.ends_with('\n')) {
let indent = crate::converter::list::utils::continuation_indent_string(
crate::converter::list::utils::block_columns(ctx, options),
options,
)
.unwrap_or_default();
output.push_str(&indent);
if marker_follows_markers {
ctx.list_indent_columns
} else {
crate::converter::utility::escaping::leading_indent(&indent).1
}
} else {
ctx.list_indent_columns
};
(marker_line_start, column)
}
fn has_block_children(tag: &crate::dom::HTMLTag, parser: &crate::dom::Parser, dom_ctx: &DomContext) -> bool {
tag.children().top().iter().any(|child_handle| {
if let Some(info) = dom_ctx.tag_info(child_handle.get_inner(), parser) {
matches!(
info.name.as_str(),
"p" | "div" | "blockquote" | "pre" | "table" | "hr" | "dl"
)
} else if let Some(crate::dom::Node::Tag(child_tag)) = child_handle.get(parser) {
matches!(
normalized_tag_name(child_tag.name().as_utf8_str()).as_ref(),
"p" | "div" | "blockquote" | "pre" | "table" | "hr" | "dl"
)
} else {
false
}
})
}
fn item_context(
output: &String,
marker_line_start: Option<usize>,
marker_column: usize,
marker: &ItemMarker<'_>,
) -> Context {
let list_item_open = !marker.ctx.in_marker_text();
let item_is_real = list_item_open || {
let full_marker = marker.full_marker();
!(marker.ctx.escapes_hyphens && full_marker.starts_with('-'))
&& crate::converter::list::utils::marker_starts_item(
output,
marker_line_start,
&full_marker,
marker.ctx.real_item_columns,
(
&marker.ctx.previous_marker,
std::ptr::from_ref::<String>(output) as usize,
),
marker.options,
)
};
let marker_width = marker.width();
Context {
in_list_item: true,
list_item_open,
list_depth: marker.ctx.list_depth + 1,
list_indent_columns: marker_column + marker_width,
real_item_columns: if item_is_real {
marker_column + marker_width
} else {
marker.ctx.real_item_columns
},
first_writer: marker.task.is_task.then(FirstWriter::default),
task_item_scope: marker
.task
.is_task
.then_some((marker.ctx.list_depth + 1, marker.ctx.blockquote_depth))
.or(marker.ctx.task_item_scope),
..marker.ctx.clone()
}
}
fn is_checkbox_node(node_handle: &crate::dom::NodeHandle, checkbox: Option<crate::dom::NodeHandle>) -> bool {
checkbox.is_some_and(|checkbox| node_handle == &checkbox)
}
fn contains_checkbox<'a>(
node_handle: &crate::dom::NodeHandle,
parser: &'a crate::dom::Parser<'a>,
checkbox: Option<crate::dom::NodeHandle>,
context: ListContext<'_>,
) -> bool {
if context.depth >= effective_max_depth(context.options) {
context.ctx.depth_limit_reached.set(true);
return false;
}
if is_checkbox_node(node_handle, checkbox) {
return true;
}
let Some(crate::dom::Node::Tag(node_tag)) = node_handle.get(parser) else {
return false;
};
node_tag.children().top().iter().any(|child_handle| {
contains_checkbox(
child_handle,
parser,
checkbox,
ListContext {
depth: context.depth + 1,
..context
},
)
})
}
fn render_li_content<'a>(
node_handle: &crate::dom::NodeHandle,
parser: &'a crate::dom::Parser<'a>,
output: &mut String,
checkbox: Option<crate::dom::NodeHandle>,
context: ListContext<'_>,
) {
if context.depth >= effective_max_depth(context.options) {
context.ctx.depth_limit_reached.set(true);
return;
}
if is_checkbox_node(node_handle, checkbox) {
return;
}
if contains_checkbox(node_handle, parser, checkbox, context) {
if let Some(crate::dom::Node::Tag(node_tag)) = node_handle.get(parser) {
for child_handle in node_tag.children().top() {
render_li_content(
child_handle,
parser,
output,
checkbox,
ListContext {
depth: context.depth + 1,
..context
},
);
}
}
} else {
walk_node(
node_handle,
parser,
output,
crate::converter::block::container::HandlerContext::new(
context.options,
context.ctx,
context.depth,
context.dom_ctx,
),
);
}
}
fn collect_task_text(
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
marker: &ItemMarker<'_>,
item_ctx: &Context,
context: ListContext<'_>,
) -> String {
let mut task_text = String::new();
let item_ctx = item_ctx.with_inline_break_owner(&task_text);
for child_handle in tag.children().top() {
render_li_content(
child_handle,
parser,
&mut task_text,
marker.task.checkbox,
ListContext {
ctx: &item_ctx,
depth: context.depth + 1,
..context
},
);
}
task_text
}
fn first_task_block<'a>(task_text: &'a str, parser: &crate::dom::Parser, item_ctx: &Context) -> Option<&'a str> {
match item_ctx
.first_writer
.as_ref()
.and_then(|first_writer| first_writer.content(parser, item_ctx))
{
Some(TaskFirstContent::Block) => Some(task_text.trim()),
Some(TaskFirstContent::CodeBlock) => {
let code_content = task_text.trim_end();
let first = code_content.len() - code_content.trim_start().len();
Some(&code_content[code_content[..first].rfind('\n').map_or(0, |position| position + 1)..])
}
_ => None,
}
}
fn write_task_content(
output: &mut String,
task_text: &str,
first_block: Option<&str>,
item_ctx: &Context,
context: ListContext<'_>,
) {
const CHECKBOX_CONTENT: &str = "  ";
let item_starts = item_ctx.list_item_open && !context.ctx.in_table_cell && !context.ctx.convert_as_inline;
let writes_checkbox_content =
item_starts && context.options.output_format == OutputFormat::Markdown && !context.ctx.in_code;
let indent =
crate::converter::list::utils::continuation_indent_string(item_ctx.list_indent_columns, context.options);
match (indent, first_block) {
(Some(indent), Some(block)) if item_starts => {
let first_line = block.lines().next().unwrap_or_default();
if writes_checkbox_content {
output.push_str(CHECKBOX_CONTENT);
}
let separator = if crate::converter::utility::escaping::is_heading_underline(first_line)
|| !crate::converter::utility::escaping::line_opens_block(first_line)
{
"\n\n"
} else {
"\n"
};
output.push_str(separator);
output.push_str(&indent);
output.push_str(block);
}
_ if writes_checkbox_content && task_text.trim().is_empty() => output.push_str(CHECKBOX_CONTENT),
_ => {
output.push(' ');
output.push_str(task_text.trim());
}
}
}
fn render_task_item(
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
marker: &ItemMarker<'_>,
item_ctx: &Context,
context: ListContext<'_>,
) {
if !context.ctx.in_heading {
output.push_str(&marker.list_marker());
}
output.push_str(if marker.task.checked { "[x]" } else { "[ ]" });
let task_text = collect_task_text(tag, parser, marker, item_ctx, context);
let first_block = first_task_block(&task_text, parser, item_ctx);
write_task_content(output, &task_text, first_block, item_ctx, context);
}
struct ItemRenderContext<'render, 'context> {
marker: &'render ItemMarker<'context>,
item_ctx: &'render Context,
list: ListContext<'context>,
}
fn write_regular_children(
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
render: &ItemRenderContext<'_, '_>,
) -> (usize, usize) {
let item_start = output.len();
let item_ctx = render.item_ctx.with_inline_break_owner(output);
let mut text_end = item_start;
for child_handle in tag.children().top() {
let is_nested_list = child_handle.get(parser).is_some_and(|node| {
let crate::dom::Node::Tag(child_tag) = node else {
return false;
};
matches!(
normalized_tag_name(child_tag.name().as_utf8_str()).as_ref(),
"ul" | "ol"
)
});
walk_node(
child_handle,
parser,
output,
crate::converter::block::container::HandlerContext::new(
render.list.options,
&item_ctx,
render.list.depth + 1,
render.list.dom_ctx,
),
);
if !is_nested_list {
text_end = output.len();
}
}
(item_start, text_end)
}
#[cfg(feature = "visitor")]
fn visit_regular_item(
node_handle: &crate::dom::NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
render: &ItemRenderContext<'_, '_>,
) -> bool {
use crate::visitor::{NodeContext, NodeType, VisitResult};
let Some(visitor_handle) = render.list.ctx.visitor.as_ref() else {
return false;
};
let parent_tag = render
.list
.dom_ctx
.parent_of(node_handle.get_inner())
.and_then(|parent_id| {
render
.list
.dom_ctx
.tag_name_for(render.list.dom_ctx.node_handle(parent_id).copied()?, parser)
})
.map(std::borrow::Cow::into_owned);
let index = render.list.dom_ctx.sibling_index(node_handle.get_inner()).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::ListItem,
Cow::Borrowed("li"),
tag,
render.list.depth,
index,
parent_tag.map(Cow::Owned),
false,
);
let line_start = output.rfind('\n').map_or(0, |position| position + 1);
let last_line = &output[line_start..];
let marker_text = render.marker.list_marker().trim_end().to_string();
let text_start = last_line
.find(&marker_text)
.map_or(0, |position| position + marker_text.len());
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_list_item(
&node_ctx,
render.list.ctx.in_ordered_list,
&marker_text,
last_line[text_start..].trim(),
)
};
match visit_result {
VisitResult::Continue => false,
VisitResult::Custom(custom) => {
crate::converter::structure_capture::replace_element(render.list.ctx, Some(&custom));
replace_regular_item_output(output, line_start, &custom, render.list.ctx.in_table_cell);
true
}
VisitResult::Skip => {
crate::converter::structure_capture::replace_element(render.list.ctx, None);
output.truncate(line_start);
true
}
VisitResult::PreserveHtml => {
let html = crate::converter::serialize_node(node_handle, parser);
crate::converter::structure_capture::replace_element(render.list.ctx, Some(&html));
replace_regular_item_output(output, line_start, &html, render.list.ctx.in_table_cell);
true
}
VisitResult::Error(error) => {
crate::converter::structure_capture::replace_element(render.list.ctx, None);
if render.list.ctx.visitor_error.borrow().is_none() {
*render.list.ctx.visitor_error.borrow_mut() = Some(error);
}
true
}
}
}
#[cfg(feature = "visitor")]
fn replace_regular_item_output(output: &mut String, line_start: usize, replacement: &str, in_table_cell: bool) {
output.truncate(line_start);
output.push_str(replacement);
if !in_table_cell && !output.ends_with('\n') {
output.push('\n');
}
}
fn render_regular_item(
node_handle: &crate::dom::NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
render: &ItemRenderContext<'_, '_>,
) -> bool {
#[cfg(not(feature = "visitor"))]
let _ = node_handle;
if render.list.ctx.in_table_cell {
add_list_leading_separator(output, render.list.ctx, render.list.options);
} else if !render.list.ctx.in_heading {
output.push_str(&render.marker.list_marker());
}
let (item_start, _) = write_regular_children(tag, parser, output, render);
trim_trailing_whitespace(output);
if render.list.options.newline_style == NewlineStyle::Backslash {
strip_trailing_backslash_breaks(output, item_start);
}
#[cfg(feature = "visitor")]
{
visit_regular_item(node_handle, tag, parser, output, render)
}
#[cfg(not(feature = "visitor"))]
{
false
}
}
fn finish_list_item(output: &mut String, ctx: &Context, has_block_children: bool) {
if ctx.in_table_cell {
return;
}
if has_block_children || ctx.loose_list || ctx.prev_item_had_blocks {
if !output.ends_with("\n\n") {
if output.ends_with('\n') {
output.push('\n');
} else {
output.push_str("\n\n");
}
}
} else if !output.ends_with('\n') {
output.push('\n');
}
}
fn write_li(
node_handle: &crate::dom::NodeHandle,
tag: &crate::dom::HTMLTag,
parser: &crate::dom::Parser,
output: &mut String,
context: ListContext<'_>,
line_after_text: &mut Option<usize>,
) {
let ListContext {
options,
ctx,
depth: _,
dom_ctx,
} = context;
let task = TaskInfo::new(node_handle, parser, context);
let marker = ItemMarker::new(task, ctx, options);
separate_marker_from_text(output, &marker, line_after_text);
let (marker_line_start, marker_column) = marker_column(output, ctx, options);
let li_ctx = item_context(output, marker_line_start, marker_column, &marker);
let has_block_children = has_block_children(tag, parser, dom_ctx);
if marker.task.is_task {
render_task_item(tag, parser, output, &marker, &li_ctx, context);
} else {
let render = ItemRenderContext {
marker: &marker,
item_ctx: &li_ctx,
list: context,
};
if render_regular_item(node_handle, tag, parser, output, &render) {
return;
}
}
finish_list_item(output, ctx, has_block_children);
}
enum TaskFirstContent {
Text,
Block,
CodeBlock,
}
#[derive(Clone, Default)]
pub struct FirstWriter(std::rc::Rc<std::cell::RefCell<FirstWriterState>>);
#[derive(Default)]
struct FirstWriterState {
node: Option<crate::dom::NodeHandle>,
first_line: String,
}
impl FirstWriter {
pub fn is_open(&self) -> bool {
self.0.borrow().node.is_none()
}
pub(crate) fn starts_with_blockquote(&self, parser: &crate::dom::Parser) -> bool {
let state = self.0.borrow();
state.node.is_some_and(|node| {
let Some(crate::dom::Node::Tag(tag)) = node.get(parser) else {
return false;
};
normalized_tag_name(tag.name().as_utf8_str()) == "blockquote"
})
}
pub fn record(&self, node: crate::dom::NodeHandle, parser: &crate::dom::Parser, written: Option<&str>) {
let child_starts_blockquote = self.starts_with_blockquote(parser);
let mut state = self.0.borrow_mut();
let Some(text) = written.map(str::trim_start).filter(|text| !text.is_empty()) else {
*state = FirstWriterState::default();
return;
};
let first_line = text.split('\n').next().unwrap_or_default();
let container = state.node.is_some()
&& is_container(node, parser)
&& (first_line.starts_with(state.first_line.as_str()) || child_starts_blockquote);
if !container {
state.node = Some(node);
state.first_line = first_line.to_string();
}
}
fn content(&self, parser: &crate::dom::Parser, ctx: &Context) -> Option<TaskFirstContent> {
let state = self.0.borrow();
let Some(crate::dom::Node::Tag(tag)) = state.node?.get(parser) else {
return Some(TaskFirstContent::Text);
};
let name = normalized_tag_name(tag.name().as_utf8_str());
Some(match block_content(&name) {
Some(block) => block,
None if ctx.preserve_tags.contains(name.as_ref())
&& crate::converter::utility::escaping::opens_block(&state.first_line) =>
{
TaskFirstContent::Block
}
None => TaskFirstContent::Text,
})
}
}
fn is_container(node: crate::dom::NodeHandle, parser: &crate::dom::Parser) -> bool {
let Some(crate::dom::Node::Tag(tag)) = node.get(parser) else {
return false;
};
block_content(&normalized_tag_name(tag.name().as_utf8_str())).is_none()
}
fn block_content(name: &str) -> Option<TaskFirstContent> {
match name {
"pre" => Some(TaskFirstContent::CodeBlock),
"blockquote" | "ul" | "ol" | "hr" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table" => {
Some(TaskFirstContent::Block)
}
_ => None,
}
}
fn unordered_bullet(ctx: &Context, options: &ConversionOptions) -> char {
let bullets: Vec<char> = options.bullets.chars().collect();
let bullet_index = if ctx.ul_depth > 0 { ctx.ul_depth - 1 } else { 0 };
if bullets.is_empty() {
'*'
} else {
bullets[bullet_index % bullets.len()]
}
}
mod heap;
pub use heap::{TaskItemEnd, close_task, open_regular};