use super::{ListContext, is_list_item};
use crate::converter::main_helpers::{tag_name_eq, trim_trailing_whitespace};
use crate::converter::utility::content::normalized_tag_name;
use crate::options::{ConversionOptions, ListIndentType, OutputFormat};
use tl;
type Context = crate::converter::Context;
type DomContext = crate::converter::DomContext;
pub const DEFAULT_ORDERED_LIST_START: i64 = 1;
pub fn parse_ordered_list_start(raw: &str) -> i64 {
let trimmed = raw.trim();
if let Ok(value) = trimmed.parse::<i64>() {
return value;
}
let (is_negative, digits) = match trimmed.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, trimmed.strip_prefix('+').unwrap_or(trimmed)),
};
if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) {
let clamped = if is_negative { i64::MIN } else { i64::MAX };
tracing::warn!(
target: "html_to_markdown::list",
raw_value = trimmed,
clamped_value = clamped,
"ol start attribute magnitude out of range; clamping to i64 bounds"
);
return clamped;
}
if !trimmed.is_empty() {
tracing::warn!(
target: "html_to_markdown::list",
raw_value = trimmed,
default_value = DEFAULT_ORDERED_LIST_START,
"ol start attribute is not a valid integer; using default start"
);
}
DEFAULT_ORDERED_LIST_START
}
pub const fn tabs_for_column(list_indent_columns: usize) -> usize {
list_indent_columns.div_ceil(4)
}
const BLOCK_FORCING_CHILD_TAGS: [&str; 6] = ["div", "blockquote", "pre", "table", "hr", "dl"];
fn resolve_tag_name(node_handle: tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> Option<String> {
if let Some(info) = dom_ctx.tag_info(node_handle.get_inner(), parser) {
return Some(info.name.clone());
}
match node_handle.get(parser) {
Some(tl::Node::Tag(tag)) => Some(normalized_tag_name(tag.name().as_utf8_str()).into_owned()),
_ => None,
}
}
pub fn is_loose_list(node_handle: tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
return false;
};
let children = tag.children();
let items: Vec<tl::NodeHandle> = children
.top()
.iter()
.copied()
.filter(|child_handle| {
dom_ctx.tag_info(child_handle.get_inner(), parser).map_or_else(
|| {
matches!(
child_handle.get(parser),
Some(tl::Node::Tag(child_tag))
if tag_name_eq(child_tag.name().as_utf8_str(), "li")
)
},
|info| info.name == "li",
)
})
.collect();
let Some(last_index) = items.len().checked_sub(1) else {
return false;
};
for (index, item_handle) in items.iter().enumerate() {
let Some(tl::Node::Tag(item_tag)) = item_handle.get(parser) else {
continue;
};
let is_last = index == last_index;
let li_children = item_tag.children();
for li_child_handle in li_children.top().iter() {
let Some(name) = resolve_tag_name(*li_child_handle, parser, dom_ctx) else {
continue;
};
if name == "p" {
return true;
}
if is_last {
continue;
}
if BLOCK_FORCING_CHILD_TAGS.contains(&name.as_str()) {
return true;
}
if matches!(name.as_str(), "ul" | "ol") && is_loose_list(*li_child_handle, parser, dom_ctx) {
return true;
}
}
}
false
}
pub fn add_list_continuation_indent(
output: &mut String,
list_indent_columns: usize,
blank_line: bool,
options: &ConversionOptions,
) {
trim_trailing_whitespace(output);
if blank_line {
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');
}
match options.list_indent_type {
ListIndentType::Tabs => {
for _ in 0..tabs_for_column(list_indent_columns) {
output.push('\t');
}
}
ListIndentType::Spaces => {
for _ in 0..list_indent_columns {
output.push(' ');
}
}
}
}
pub fn continuation_indent_string(list_indent_columns: usize, options: &ConversionOptions) -> Option<String> {
match options.list_indent_type {
ListIndentType::Tabs => {
let tabs = tabs_for_column(list_indent_columns);
if tabs == 0 {
return None;
}
Some("\t".repeat(tabs))
}
ListIndentType::Spaces => {
if list_indent_columns == 0 {
return None;
}
Some(" ".repeat(list_indent_columns))
}
}
}
pub fn indent_list_item_line_start(output: &mut String, ctx: &Context, options: &ConversionOptions) {
if ctx.in_list_item
&& !ctx.in_code
&& !ctx.in_ruby
&& !ctx.in_table_cell
&& !ctx.convert_as_inline
&& output.ends_with('\n')
&& !output.ends_with("\n\n")
{
if let Some(indent) = continuation_indent_string(ctx.list_indent_columns, options) {
output.push_str(&indent);
}
}
}
pub fn indent_column(list_indent_columns: usize, options: &ConversionOptions) -> usize {
continuation_indent_string(list_indent_columns, options).map_or(0, |indent| {
crate::converter::utility::escaping::leading_indent(&indent).1
})
}
pub fn block_is_real(ctx: &Context, options: &ConversionOptions) -> bool {
indent_column(ctx.list_indent_columns, options).saturating_sub(indent_column(ctx.real_item_columns, options)) < 4
}
pub fn block_columns(ctx: &Context, options: &ConversionOptions) -> usize {
if ctx.quote_starts_after_markers && !block_is_real(ctx, options) {
ctx.real_item_columns
} else {
ctx.list_indent_columns
}
}
pub fn marker_starts_item(
output: &str,
marker_line_start: Option<usize>,
marker: &str,
enclosing_columns: usize,
previous: (&PreviousMarker, usize),
options: &ConversionOptions,
) -> bool {
let Some(line_start) = marker_line_start else {
return false;
};
let enclosing_column = indent_column(enclosing_columns, options);
let marker_column = crate::converter::utility::escaping::leading_indent(&output[line_start..]).1;
let column = marker_column.saturating_sub(enclosing_column);
if !paragraph_is_open_before(output, line_start, enclosing_column, previous) {
return column < 4;
}
let line = format!("{}{marker}x", " ".repeat(column));
crate::converter::utility::escaping::line_opens_block(&line)
}
pub fn list_needs_blank_line(
(output, line_start): (&str, usize),
line: &str,
enclosing_columns: usize,
previous: (&PreviousMarker, usize),
options: &ConversionOptions,
) -> bool {
!marker_line_interrupts(line, options)
&& paragraph_is_open_before(output, line_start, indent_column(enclosing_columns, options), previous)
}
fn marker_line_interrupts(line: &str, options: &ConversionOptions) -> bool {
options.output_format != OutputFormat::Djot && marker_line_can_interrupt(line)
}
fn marker_line_can_interrupt(line: &str) -> bool {
use crate::converter::utility::escaping::{is_heading_underline, line_opens_block};
line_opens_block(line) && !is_heading_underline(line.trim_start_matches([' ', '\t']))
}
pub fn marker_line_after_text_needs_blank_line(output: &str, line_start: usize) -> bool {
!marker_line_can_interrupt(written_marker_line(output, line_start))
}
fn written_marker_line(output: &str, line_start: usize) -> &str {
let written = &output[line_start..];
written[..written.find('\n').unwrap_or(written.len())].trim_start_matches([' ', '\t'])
}
fn column_of_written_marker(output: &str, end: usize) -> String {
let start = output[..end].rfind('\n').map_or(0, |pos| pos + 1);
output[start..end]
.chars()
.map(|ch| if ch == '\t' { '\t' } else { ' ' })
.collect()
}
fn bare_marker_line_is_rule(output: &str, end: usize) -> bool {
let start = output[..end].rfind('\n').map_or(0, |pos| pos + 1);
let line_end = output[end..].find('\n').map_or(output.len(), |pos| end + pos);
let mut rest = output[start..line_end].trim_start_matches([' ', '\t']);
loop {
if crate::converter::utility::escaping::is_rule(rest) {
return true;
}
match strip_leading_bare_marker(rest) {
Some(next) => rest = next,
None => return false,
}
}
}
pub use super::{ItemLineScan, LastList, PreviousMarker, switched_delimiter};
fn paragraph_is_open_before(
output: &str,
line_start: usize,
enclosing_column: usize,
(previous, buffer): (&PreviousMarker, usize),
) -> bool {
let open = paragraph_is_open(
&output[..line_start],
enclosing_column,
previous.get(buffer, output, enclosing_column),
);
previous.set(buffer, output, line_start, enclosing_column, open);
open
}
fn paragraph_is_open(output: &str, enclosing_column: usize, previous: Option<(usize, bool)>) -> bool {
use crate::converter::utility::escaping::{leading_indent, opens_block};
let text = output.strip_suffix('\n').unwrap_or(output);
let mut end = text.len();
loop {
let start = text[..end].rfind('\n').map_or(0, |pos| pos + 1);
if start == 0 {
return true;
}
let line = &text[start..end];
end = start - 1;
if line.trim().is_empty() {
return false;
}
let (indent, column) = leading_indent(line);
if column < enclosing_column {
return true;
}
if column - enclosing_column >= 4 {
continue;
}
let rest = &line[indent..];
if opens_block(rest) {
return false;
}
if strip_leading_bare_marker(rest).is_none() {
return true;
}
if let Some((_, open)) = previous.filter(|&(line_start, _)| line_start == start) {
return open;
}
}
}
pub fn preceding_same_type_list_separator_comment(
node_handle: tl::NodeHandle,
parser: &tl::Parser,
dom_ctx: &DomContext,
tag_name: &str,
) -> Option<String> {
let id = node_handle.get_inner();
let siblings = match dom_ctx.parent_of(id) {
Some(parent_id) => dom_ctx.children_of(parent_id)?,
None => &dom_ctx.root_children,
};
let position = dom_ctx
.sibling_index(id)
.or_else(|| siblings.iter().position(|handle| handle.get_inner() == id))?;
let mut cursor = position;
loop {
cursor = cursor.checked_sub(1)?;
match siblings.get(cursor)?.get(parser) {
Some(tl::Node::Comment(_)) => break,
Some(tl::Node::Raw(raw)) if raw.as_utf8_str().trim().is_empty() => {}
_ => return None,
}
}
let previous_list_name = loop {
cursor = cursor.checked_sub(1)?;
let sibling = *siblings.get(cursor)?;
if let Some(tl::Node::Raw(raw)) = sibling.get(parser) {
if raw.as_utf8_str().trim().is_empty() {
continue;
}
}
break resolve_tag_name(sibling, parser, dom_ctx)?;
};
if previous_list_name == tag_name {
Some("<!-- -->".to_owned())
} else {
None
}
}
pub(super) fn strip_leading_bare_marker(text: &str) -> Option<&str> {
let digit_count = text.bytes().take_while(u8::is_ascii_digit).count();
if digit_count > 0 {
let rest = &text[digit_count..];
if let Some(rest) = rest.strip_prefix(". ").or_else(|| rest.strip_prefix(") ")) {
return Some(rest);
}
}
let mut chars = text.chars();
let first = chars.next()?;
if matches!(first, '-' | '*' | '+') {
return chars.as_str().strip_prefix(' ');
}
None
}
pub fn line_is_bare_list_marker(output: &str) -> bool {
let line_start = output.rfind('\n').map_or(0, |pos| pos + 1);
let mut rest = output[line_start..].trim_start_matches([' ', '\t']);
if rest.is_empty() {
return false;
}
while let Some(next) = strip_leading_bare_marker(rest) {
if next.is_empty() {
return true;
}
rest = next;
}
false
}
pub fn item_is_open(output: &str, indent: &str, ctx: &Context) -> bool {
if !ctx.list_item_open {
return false;
}
let content = output.trim_end();
if content.is_empty() {
return true;
}
let last_start = content.rfind('\n').map_or(0, |pos| pos + 1);
let before = lines_are_open(&output[..last_start], indent, &ctx.item_lines);
let last = output[last_start..].split('\n').next().unwrap_or_default();
match before {
_ if strip_leading_bare_marker(last.trim_start_matches([' ', '\t'])).is_some() => true,
None => true,
Some(_) if indent.is_empty() || !last.starts_with(indent) => false,
Some(open) => open,
}
}
pub(super) fn lines_are_open(output: &str, indent: &str, scan: &ItemLineScan) -> Option<bool> {
let buffer = output.as_ptr() as usize;
let (start, below) = scan
.read(buffer, indent, output)
.unwrap_or_else(|| (last_marker_line_start(output), None));
let mut open = below;
for line in output[start..].split('\n').filter(|line| !line.trim().is_empty()) {
open = Some(match open {
_ if strip_leading_bare_marker(line.trim_start_matches([' ', '\t'])).is_some() => true,
None => true,
Some(_) if indent.is_empty() || !line.starts_with(indent) => false,
Some(open) => open,
});
}
scan.write(buffer, indent, output, open);
open
}
fn last_marker_line_start(output: &str) -> usize {
let mut end = output.len();
while end > 0 {
let start = output[..end - 1].rfind('\n').map_or(0, |pos| pos + 1);
if strip_leading_bare_marker(output[start..end].trim_start_matches([' ', '\t'])).is_some() {
return start;
}
end = start;
}
0
}
pub fn nested_block_context(output: &str, ctx: &Context, options: &ConversionOptions) -> Context {
let indent = continuation_indent_string(ctx.list_indent_columns, options).unwrap_or_default();
Context {
list_item_open: item_is_open(output, &indent, ctx),
item_lines: ItemLineScan::new_item(),
..ctx.clone()
}
}
pub fn trim_whitespace_after_bare_marker(output: &mut String) -> bool {
let content_end = output.trim_end().len();
if content_end == output.len() {
return line_is_bare_list_marker(output);
}
let tail = output[content_end..].to_string();
output.truncate(content_end);
output.push(' ');
if line_is_bare_list_marker(output) {
return true;
}
output.truncate(content_end);
output.push_str(&tail);
false
}
pub fn start_block_in_list_item(output: &mut String, ctx: &Context, options: &ConversionOptions) {
if trim_whitespace_after_bare_marker(output) {
return;
}
let indent = continuation_indent_string(ctx.list_indent_columns, options).unwrap_or_default();
if item_is_open(output, &indent, ctx) {
add_list_continuation_indent(output, ctx.list_indent_columns, true, options);
} else {
trim_trailing_whitespace(output);
if !output.ends_with("\n\n") {
output.push_str(if output.ends_with('\n') { "\n" } else { "\n\n" });
}
}
}
pub fn add_list_leading_separator(output: &mut String, ctx: &Context, options: &ConversionOptions) {
if ctx.in_table_cell {
let is_table_continuation =
!output.is_empty() && !output.ends_with('|') && !output.ends_with(' ') && !output.ends_with("<br>");
if is_table_continuation {
crate::converter::main_helpers::emit_table_cell_break_in_context(output, options.br_in_tables, ctx);
}
return;
}
if !output.is_empty() && !ctx.in_list {
let needs_newline = !output.ends_with("\n\n") && !line_is_bare_list_marker(output);
if needs_newline {
output.push_str("\n\n");
}
return;
}
if ctx.in_list_item && !output.is_empty() {
if line_is_bare_list_marker(output) {
return;
}
if ctx.loose_list {
trim_trailing_whitespace(output);
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') {
trim_trailing_whitespace(output);
output.push('\n');
}
}
}
pub fn add_nested_list_trailing_separator(output: &mut String, ctx: &Context) {
if !ctx.in_list_item {
return;
}
if ctx.loose_list {
if !output.ends_with("\n\n") {
if !output.ends_with('\n') {
output.push('\n');
}
output.push('\n');
}
} else if !output.ends_with('\n') {
output.push('\n');
}
}
pub const fn calculate_list_nesting_depth(ctx: &Context) -> usize {
if ctx.in_list && !ctx.in_list_item {
ctx.list_depth + 1
} else {
ctx.list_depth
}
}
#[derive(Clone, Copy)]
pub(super) struct ListChildrenContext<'a> {
pub list: ListContext<'a>,
pub ordered: bool,
pub loose: bool,
pub nested_depth: usize,
pub start_counter: i64,
pub delimiter: Option<char>,
}
#[derive(Default)]
struct MarkerPosition {
line_start: Option<usize>,
bare_end: Option<usize>,
}
struct ListChildProcessor<'a> {
config: ListChildrenContext<'a>,
item_ctx: Context,
counter: i64,
counter_saturated: bool,
first_item: bool,
}
impl<'a> ListChildProcessor<'a> {
fn new(config: ListChildrenContext<'a>) -> Self {
let context = config.list.ctx;
let counter = config.start_counter;
let item_ctx = Context {
in_ordered_list: config.ordered,
list_counter: if config.ordered { counter } else { 0 },
in_list: true,
list_depth: config.nested_depth,
ul_depth: if config.ordered {
context.ul_depth
} else {
context.ul_depth + 1
},
loose_list: config.loose,
prev_item_had_blocks: false,
ordered_delimiter: config.delimiter,
..context.clone()
};
Self {
config,
item_ctx,
counter,
counter_saturated: false,
first_item: true,
}
}
fn marker_before(
&mut self,
child_handle: tl::NodeHandle,
parser: &tl::Parser,
output: &mut String,
) -> MarkerPosition {
let context = self.config.list.ctx;
if !self.first_item || !is_list_item(child_handle, parser, self.config.list.dom_ctx) {
return MarkerPosition::default();
}
self.first_item = false;
let item_block = context.in_list_item && context.inline_depth == 0 && !context.text_in_markers;
if !item_block {
return MarkerPosition::default();
}
if line_is_bare_list_marker(output) {
return MarkerPosition {
bare_end: Some(output.len()),
..MarkerPosition::default()
};
}
if !output.ends_with('\n') {
return MarkerPosition::default();
}
let marker = if self.config.ordered {
format!("{}. x", self.counter)
} else {
String::from("- x")
};
if list_needs_blank_line(
(output, output.len()),
&marker,
context.real_item_columns,
(&context.previous_marker, std::ptr::from_ref::<String>(output) as usize),
self.config.list.options,
) {
output.push('\n');
MarkerPosition::default()
} else {
MarkerPosition {
line_start: (!context.in_marker_span && marker_line_interrupts(&marker, self.config.list.options))
.then_some(output.len()),
bare_end: None,
}
}
}
fn marker_after(&self, output: &mut String, position: MarkerPosition) {
let context = self.config.list.ctx;
if let Some(line_start) = position.line_start {
let line = written_marker_line(output, line_start);
if list_needs_blank_line(
(output, line_start),
line,
context.real_item_columns,
(&context.previous_marker, std::ptr::from_ref::<String>(output) as usize),
self.config.list.options,
) {
output.insert(line_start, '\n');
}
}
if let Some(end) = position.bare_end.filter(|&end| bare_marker_line_is_rule(output, end)) {
let indent = column_of_written_marker(output, end);
output.replace_range(end - 1..end, &format!("\n{indent}"));
}
}
fn advance_counter(&mut self, child_handle: tl::NodeHandle, parser: &tl::Parser) {
if !self.config.ordered || !is_list_item(child_handle, parser, self.config.list.dom_ctx) {
return;
}
if self.counter < i64::MAX {
self.counter += 1;
} else if !self.counter_saturated {
tracing::warn!(
target: "html_to_markdown::list",
counter = self.counter,
"ordered list counter reached i64::MAX; subsequent items repeat this value"
);
self.counter_saturated = true;
}
}
fn render(&mut self, child_handle: &tl::NodeHandle, parser: &tl::Parser, output: &mut String) {
if self.config.ordered {
self.item_ctx.list_counter = self.counter;
}
let marker = self.marker_before(*child_handle, parser, output);
crate::converter::walk_node(
child_handle,
parser,
output,
crate::converter::block::container::HandlerContext::new(
self.config.list.options,
&self.item_ctx,
self.config.list.depth + 1,
self.config.list.dom_ctx,
),
);
self.marker_after(output, marker);
self.advance_counter(*child_handle, parser);
}
}
fn is_whitespace_node(node_handle: &tl::NodeHandle, parser: &tl::Parser) -> bool {
matches!(node_handle.get(parser), Some(tl::Node::Raw(bytes)) if bytes.as_utf8_str().trim().is_empty())
}
pub(super) fn process_list_children(
node_handle: tl::NodeHandle,
parser: &tl::Parser,
output: &mut String,
context: ListChildrenContext<'_>,
) {
let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
return;
};
let mut processor = ListChildProcessor::new(context);
for child_handle in tag.children().top().iter() {
if !is_whitespace_node(child_handle, parser) {
processor.render(child_handle, parser, output);
}
}
}
mod heap;
pub(super) use heap::{ListWalkEnd, open_children_walk};