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,
}
}
}
#[derive(Clone, Default)]
pub struct LastList(std::rc::Rc<std::cell::RefCell<ListTracker>>);
#[derive(Default)]
struct ListTracker {
frames: Vec<Frame>,
key: Option<ListEnd>,
}
#[derive(Clone, Copy)]
struct Frame {
buffer: usize,
run_start: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Owner {
Run(usize),
Waiting(Option<usize>),
}
const END_BYTES: usize = 32;
struct ListEnd {
owner: Owner,
buffer: usize,
end: usize,
checked: usize,
end_bytes: [u8; END_BYTES],
place: ListPlace,
delimiter: char,
}
impl ListEnd {
fn new(owner: Owner, buffer: usize, output: &str, place: ListPlace, delimiter: char) -> Self {
let mut key = Self {
owner,
buffer,
end: output.len(),
checked: output.len(),
end_bytes: [0; END_BYTES],
place,
delimiter,
};
key.take_end_bytes(output);
key
}
fn take_end_bytes(&mut self, output: &str) {
let bytes = &output.as_bytes()[self.end.saturating_sub(END_BYTES)..self.end];
self.end_bytes = [0; END_BYTES];
self.end_bytes[..bytes.len()].copy_from_slice(bytes);
}
fn holds_end_bytes(&self, output: &str) -> bool {
let start = self.end.saturating_sub(END_BYTES);
output.as_bytes().get(start..self.end) == Some(&self.end_bytes[..self.end - start])
}
fn clean_after(&mut self, output: &str) -> bool {
let start = self.checked.min(output.len()).max(self.end);
self.checked = output.len();
output
.as_bytes()
.get(start..)
.is_some_and(|rest| rest.iter().all(u8::is_ascii_whitespace))
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct ListPlace {
columns: usize,
quotes: usize,
}
impl ListPlace {
const fn of(ctx: &Context) -> Self {
Self {
columns: ctx.list_indent_columns,
quotes: ctx.blockquote_depth,
}
}
}
impl LastList {
pub fn enter(&self, output: &String) {
let mut tracker = self.0.borrow_mut();
let buffer = std::ptr::from_ref::<String>(output) as usize;
let index = tracker.frames.len();
let run_start = match tracker.frames.last() {
Some(parent) if parent.buffer == buffer => parent.run_start,
_ => index,
};
tracker.frames.push(Frame { buffer, run_start });
let ListTracker { key, .. } = &mut *tracker;
if let Some(waiting) = key.as_mut().filter(|key| {
key.owner == Owner::Waiting(index.checked_sub(1)) && key.buffer == buffer && run_start == index
}) {
if waiting.holds_end_bytes(output) {
waiting.owner = Owner::Run(run_start);
if !waiting.clean_after(output) {
*key = None;
}
}
}
}
pub fn leave(&self, output: &str) {
let mut tracker = self.0.borrow_mut();
let Some(frame) = tracker.frames.pop() else { return };
let index = tracker.frames.len();
let ListTracker { key, .. } = &mut *tracker;
let Some(list_end) = key.as_mut() else { return };
if list_end.owner == Owner::Waiting(Some(index)) {
*list_end = ListEnd::new(
Owner::Run(frame.run_start),
frame.buffer,
output,
list_end.place,
list_end.delimiter,
);
}
if list_end.owner == Owner::Run(frame.run_start) {
if !list_end.clean_after(output) {
*key = None;
} else if frame.run_start == index {
list_end.owner = Owner::Waiting(index.checked_sub(1));
}
}
}
pub fn set(&self, output: &str, ctx: &Context, delimiter: char) {
use crate::converter::utility::escaping::{leading_indent, opens_block};
let mut tracker = self.0.borrow_mut();
let Some(frame) = tracker.frames.last().copied() else {
return;
};
let content = output.trim_end_matches(|c: char| c.is_ascii_whitespace());
let line = &content[content.rfind('\n').map_or(0, |pos| pos + 1)..];
let (indent, column) = leading_indent(line);
let rest = &line[indent..];
let closed =
column < ctx.list_indent_columns + 2 && opens_block(rest) && strip_leading_bare_marker(rest).is_none();
tracker.key = (!closed).then(|| {
ListEnd::new(
Owner::Run(frame.run_start),
frame.buffer,
output,
ListPlace::of(ctx),
delimiter,
)
});
}
fn delimiter_before(&self, output: &str, ctx: &Context) -> Option<char> {
let mut tracker = self.0.borrow_mut();
let run = tracker.frames.last()?.run_start;
let key = tracker.key.as_mut()?;
let open = if key.owner == Owner::Run(run) {
key.clean_after(output)
} else {
output.bytes().all(|byte| byte.is_ascii_whitespace())
};
(open && key.place == ListPlace::of(ctx)).then_some(key.delimiter)
}
}
pub fn switched_delimiter(output: &str, ctx: &Context) -> Option<char> {
(!ctx.convert_as_inline
&& ctx.inline_depth == 0
&& !ctx.text_in_markers
&& !ctx.in_marker_span
&& ctx.last_list.delimiter_before(output, ctx) == Some('.'))
.then_some(')')
}
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;
}
}
}
#[derive(Clone, Default)]
pub struct PreviousMarker(std::rc::Rc<std::cell::RefCell<Option<PreviousMarkerState>>>);
struct PreviousMarkerState {
buffer: usize,
line_start: usize,
line_before: String,
enclosing_column: usize,
open: bool,
}
impl PreviousMarker {
fn get(&self, buffer: usize, output: &str, enclosing_column: usize) -> Option<(usize, bool)> {
let state = self.0.borrow();
let state = state.as_ref()?;
(state.buffer == buffer
&& state.enclosing_column == enclosing_column
&& output
.get(..state.line_start)
.is_some_and(|before| before.ends_with(state.line_before.as_str())))
.then_some((state.line_start, state.open))
}
fn set(&self, buffer: usize, output: &str, line_start: usize, enclosing_column: usize, open: bool) {
let before = &output[..line_start];
let line_before = &before[before.trim_end_matches('\n').rfind('\n').map_or(0, |pos| pos + 1)..];
*self.0.borrow_mut() = Some(PreviousMarkerState {
buffer,
line_start,
line_before: line_before.to_string(),
enclosing_column,
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;
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 {
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,
}
}
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
}
#[derive(Clone, Default)]
pub struct ItemLineScan(std::rc::Rc<std::cell::RefCell<Option<ItemLineScanState>>>);
struct ItemLineScanState {
buffer: usize,
indent: String,
end: usize,
last_line_start: usize,
last_line: String,
open: Option<bool>,
}
impl ItemLineScan {
pub fn new_item() -> Self {
Self::default()
}
fn read(&self, buffer: usize, indent: &str, output: &str) -> Option<(usize, Option<bool>)> {
let state = self.0.borrow();
let state = state.as_ref()?;
(state.buffer == buffer
&& state.indent == indent
&& output.get(state.last_line_start..state.end) == Some(state.last_line.as_str()))
.then_some((state.end, state.open))
}
fn write(&self, buffer: usize, indent: &str, output: &str, open: Option<bool>) {
let last_line_start = output.trim_end().rfind('\n').map_or(0, |pos| pos + 1);
*self.0.borrow_mut() = Some(ItemLineScanState {
buffer,
indent: indent.to_string(),
end: output.len(),
last_line_start,
last_line: output[last_line_start..].to_string(),
open,
});
}
}
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(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,
delimiter: Option<char>,
dom_ctx: &DomContext,
) {
let mut counter = start_counter;
let mut counter_saturated = false;
let mut first_item = true;
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,
ordered_delimiter: delimiter,
..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;
}
let mut marker_line_start = None;
let mut bare_marker_end = None;
if first_item && is_list_item(*child_handle, parser, dom_ctx) {
first_item = false;
let item_block = ctx.in_list_item && ctx.inline_depth == 0 && !ctx.text_in_markers;
if item_block && line_is_bare_list_marker(output) {
bare_marker_end = Some(output.len());
} else if item_block && output.ends_with('\n') {
let marker = if is_ordered {
format!("{counter}. x")
} else {
String::from("- x")
};
if list_needs_blank_line(
(output, output.len()),
&marker,
ctx.real_item_columns,
(&ctx.previous_marker, std::ptr::from_ref::<String>(output) as usize),
options,
) {
output.push('\n');
} else if !ctx.in_marker_span && marker_line_interrupts(&marker, options) {
marker_line_start = Some(output.len());
}
}
}
use crate::converter::walk_node;
walk_node(child_handle, parser, output, options, &list_ctx, depth + 1, dom_ctx);
if let Some(line_start) = marker_line_start {
let line = written_marker_line(output, line_start);
if list_needs_blank_line(
(output, line_start),
line,
ctx.real_item_columns,
(&ctx.previous_marker, std::ptr::from_ref::<String>(output) as usize),
options,
) {
output.insert(line_start, '\n');
}
}
if let Some(end) = bare_marker_end {
if bare_marker_line_is_rule(output, end) {
let indent = column_of_written_marker(output, end);
output.replace_range(end - 1..end, &format!("\n{indent}"));
}
}
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;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn owner_after_sibling_enters(first: &str, second: &str) -> Option<Owner> {
let list = LastList::default();
let root = String::new();
let mut buffer = String::from(first);
list.enter(&root);
list.enter(&buffer);
let place = ListPlace { columns: 0, quotes: 0 };
let address = std::ptr::from_ref::<String>(&buffer) as usize;
list.0.borrow_mut().key = Some(ListEnd::new(Owner::Run(1), address, &buffer, place, '.'));
list.leave(&buffer);
buffer.clear();
buffer.push_str(second);
list.enter(&buffer);
list.0.borrow().key.as_ref().map(|key| key.owner)
}
#[test]
fn a_later_child_takes_the_list_end_back_only_from_the_same_buffer() {
assert_eq!(owner_after_sibling_enters("1. a\n", "1. a\n\n"), Some(Owner::Run(1)));
assert_eq!(
owner_after_sibling_enters("1. a\n", "zzzzzz\n"),
Some(Owner::Waiting(Some(0)))
);
assert_eq!(owner_after_sibling_enters("1. a\n", "1. a\nx"), None);
}
#[test]
fn a_buffer_that_no_longer_reaches_the_list_end_is_not_clean() {
let place = ListPlace { columns: 0, quotes: 0 };
let mut key = ListEnd::new(Owner::Run(0), 0, "1. a\n", place, '.');
assert!(key.clean_after("1. a\n\n"));
assert!(!key.clean_after("1."));
}
#[test]
fn a_later_child_with_another_buffer_leaves_the_list_end_waiting() {
let list = LastList::default();
let root = String::new();
let first = String::from("1. a\n");
let second = first.clone();
list.enter(&root);
list.enter(&first);
let place = ListPlace { columns: 0, quotes: 0 };
let address = std::ptr::from_ref::<String>(&first) as usize;
list.0.borrow_mut().key = Some(ListEnd::new(Owner::Run(1), address, &first, place, '.'));
list.leave(&first);
list.enter(&second);
let owner = list.0.borrow().key.as_ref().map(|key| key.owner);
assert_eq!(owner, Some(Owner::Waiting(Some(0))));
}
#[test]
fn item_line_scan_reads_the_lines_again_after_its_last_line_changed() {
let scan = ItemLineScan::new_item();
let mut output = String::from("- a\n b\n");
assert_eq!(lines_are_open(&output, " ", &scan), Some(true));
output.clear();
output.push_str("a\nb\nzzz\n");
assert_eq!(lines_are_open(&output, " ", &scan), Some(false));
}
#[test]
fn item_line_scan_reads_the_lines_of_another_buffer_again() {
let scan = ItemLineScan::new_item();
let first = String::from("- a\n b\n");
let second = String::from("a\nb\n b\n");
assert_eq!(lines_are_open(&first, " ", &scan), Some(true));
assert_eq!(lines_are_open(&second, " ", &scan), Some(false));
}
#[test]
fn item_line_scan_reads_the_lines_again_for_another_indent() {
let scan = ItemLineScan::new_item();
let output = String::from("- a\n b\n");
assert_eq!(lines_are_open(&output, " ", &scan), Some(true));
assert_eq!(lines_are_open(&output, " ", &scan), Some(false));
}
#[test]
fn previous_marker_answers_only_for_its_buffer_column_and_line_before_its_marker_line() {
let previous = PreviousMarker::default();
previous.set(1, "p\n- a\n", 2, 0, true);
assert_eq!(previous.get(1, "p\n- a\n- b\n", 0), Some((2, true)));
assert_eq!(previous.get(1, "p\n- a\n- b\n", 2), None);
assert_eq!(previous.get(2, "p\n- a\n- b\n", 0), None);
assert_eq!(previous.get(1, "q\n- a\n- b\n", 0), None);
}
}