use crate::converter::main_helpers::{tag_name_eq, trim_trailing_whitespace};
use crate::converter::utility::content::normalized_tag_name;
use crate::options::{ConversionOptions, ListIndentType};
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 calculate_list_continuation_indent(depth: usize) -> usize {
if depth > 0 { 2 * depth - 1 } else { 0 }
}
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_depth: usize,
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 => {
let indent_level = calculate_list_continuation_indent(list_depth);
for _ in 0..indent_level {
output.push('\t');
}
}
ListIndentType::Spaces => {
for _ in 0..list_indent_columns {
output.push(' ');
}
}
}
}
pub fn continuation_indent_string(
list_depth: usize,
list_indent_columns: usize,
options: &ConversionOptions,
) -> Option<String> {
match options.list_indent_type {
ListIndentType::Tabs => {
let indent_level = calculate_list_continuation_indent(list_depth);
if indent_level == 0 {
return None;
}
Some("\t".repeat(indent_level))
}
ListIndentType::Spaces => {
if list_indent_columns == 0 {
return None;
}
Some(" ".repeat(list_indent_columns))
}
}
}
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;
let comment_text = loop {
cursor = cursor.checked_sub(1)?;
match siblings.get(cursor)?.get(parser) {
Some(tl::Node::Comment(bytes)) => break bytes.as_utf8_str().into_owned(),
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(comment_text)
} else {
None
}
}
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 {
if let Some(rest) = text[digit_count..].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 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(output, options.br_in_tables);
}
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
}
}
pub fn is_list_item(node_handle: tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
if let Some(info) = dom_ctx.tag_info(node_handle.get_inner(), parser) {
return info.name == "li";
}
matches!(
node_handle.get(parser),
Some(tl::Node::Tag(tag)) if tag_name_eq(tag.name().as_utf8_str(), "li")
)
}
#[allow(clippy::too_many_arguments)]
pub fn process_list_children(
node_handle: tl::NodeHandle,
parser: &tl::Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
is_ordered: bool,
is_loose: bool,
nested_depth: usize,
start_counter: i64,
dom_ctx: &DomContext,
) {
let mut counter = start_counter;
let mut counter_saturated = false;
if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
let children = tag.children();
{
let mut list_ctx = Context {
in_ordered_list: is_ordered,
list_counter: if is_ordered { counter } else { 0 },
in_list: true,
list_depth: nested_depth,
ul_depth: if is_ordered { ctx.ul_depth } else { ctx.ul_depth + 1 },
loose_list: is_loose,
prev_item_had_blocks: false,
..ctx.clone()
};
for child_handle in children.top().iter() {
if let Some(tl::Node::Raw(bytes)) = child_handle.get(parser) {
if bytes.as_utf8_str().trim().is_empty() {
continue;
}
}
if is_ordered {
list_ctx.list_counter = counter;
}
use crate::converter::walk_node;
walk_node(child_handle, parser, output, options, &list_ctx, depth + 1, dom_ctx);
if is_ordered && is_list_item(*child_handle, parser, dom_ctx) {
if counter == i64::MAX {
if !counter_saturated {
tracing::warn!(
target: "html_to_markdown::list",
counter,
"ordered list counter reached i64::MAX; subsequent items repeat this value"
);
counter_saturated = true;
}
} else {
counter += 1;
}
}
}
}
}
}