use continuity_buffer::Buffer;
use continuity_text::{Position, Selection};
use ropey::Rope;
use crate::edit_planning::{finalize_specs, line_content_end, EditSpec};
use crate::selection_edit::SelectionEditPlan;
use crate::Error;
use super::{
detect_list_marker, list_newline_action, ListMarker, ListMarkerKind, ListNewlineAction,
};
pub(crate) fn try_ordered_continue_with_renumber(
rope: &Rope,
selection: Selection,
) -> Result<Option<SelectionEditPlan>, Error> {
let head = selection.head;
let line = head.line as usize;
let line_start = rope.line_to_byte(line);
let line_end = line_content_end(rope, line);
let line_text = rope.byte_slice(line_start..line_end).to_string();
let indent = crate::edit_lines::leading_whitespace_for(rope, line);
if line_text.len() < indent.len() {
return Ok(None);
}
let body = &line_text[indent.len()..];
let is_ordered =
detect_list_marker(body).is_some_and(|m| matches!(m.kind, ListMarkerKind::Ordered(_)));
if !is_ordered {
return Ok(None);
}
match list_newline_action(&indent, body, " ") {
ListNewlineAction::Continue { ref next_marker }
if next_marker.ends_with(". ") && !next_marker.contains('[') =>
{
}
_ => return Ok(None),
}
let Some((start_line, end_line, run_indent)) = ordered_list_range(rope, line) else {
return Ok(None);
};
let byte = head.to_byte_offset(rope)?;
let mut items: Vec<(usize, u32)> = Vec::new();
let mut items_up_to_caret: u32 = 0;
for run_line in start_line..=end_line {
if !is_ordered_at_exact_indent(rope, run_line, &run_indent) {
continue;
}
let index = items.len() as u32 + 1;
items.push((run_line, index));
if run_line <= line {
items_up_to_caret = index;
}
}
let new_number = items_up_to_caret.saturating_add(1);
let inserted = format!("\n{run_indent}{new_number}. ");
let mut specs = vec![EditSpec::insert(rope, byte, inserted.clone())?];
for (renumber_line, item_index) in items {
let rl_start = rope.line_to_byte(renumber_line);
let rl_end = line_content_end(rope, renumber_line);
let rl_text = rope.byte_slice(rl_start..rl_end).to_string();
let rl_body = &rl_text[run_indent.len()..];
let Some(rl_marker) = detect_list_marker(rl_body) else {
continue;
};
let final_number = if renumber_line <= line {
item_index
} else {
item_index.saturating_add(1)
};
let after_marker = &rl_body[rl_marker.prefix_len..];
let new_line = format!("{run_indent}{final_number}. {after_marker}");
if new_line != rl_text {
specs.push(EditSpec::replace(rope, rl_start, rl_end, new_line)?);
}
}
let new_line_index = head.line.saturating_add(1);
let new_col = (run_indent.len() + format!("{new_number}. ").len()) as u32;
let selections_after = vec![Selection::caret_at(Position::new(new_line_index, new_col))];
Ok(finalize_specs(specs, vec![selection], selections_after))
}
pub(crate) fn plan_markdown_renumber_list(
buffer: &Buffer,
) -> Result<Option<SelectionEditPlan>, Error> {
let rope = buffer.rope();
let selections_before = buffer.selections().to_vec();
let mut specs = Vec::new();
let mut visited: ahash::AHashSet<u32> = ahash::AHashSet::new();
for selection in &selections_before {
let caret_line = selection.head.line as usize;
let Some((start_line, end_line, indent)) = ordered_list_range(rope, caret_line) else {
continue;
};
if visited.contains(&(start_line as u32)) {
continue;
}
visited.insert(start_line as u32);
specs.extend(renumber_run_specs(rope, start_line, end_line, &indent)?);
}
Ok(finalize_specs(
specs,
selections_before.clone(),
selections_before,
))
}
pub(crate) fn renumber_run_specs(
rope: &Rope,
start_line: usize,
end_line: usize,
indent: &str,
) -> Result<Vec<EditSpec>, Error> {
let mut specs = Vec::new();
let mut counter: u32 = 1;
for line in start_line..=end_line {
let line_start = rope.line_to_byte(line);
let line_end = line_content_end(rope, line);
let line_text = rope.byte_slice(line_start..line_end).to_string();
if line_text.len() < indent.len() || !line_text.starts_with(indent) {
continue;
}
let body = &line_text[indent.len()..];
let Some(marker) = detect_list_marker(body) else {
continue;
};
if !matches!(marker.kind, ListMarkerKind::Ordered(_)) {
continue;
}
let after_marker = &body[marker.prefix_len..];
let new_line = format!("{indent}{counter}. {after_marker}");
if new_line != line_text {
specs.push(EditSpec::replace(rope, line_start, line_end, new_line)?);
}
counter = counter.saturating_add(1);
}
Ok(specs)
}
pub(crate) fn ordered_list_range_for(
rope: &Rope,
caret_line: usize,
) -> Option<(usize, usize, String)> {
ordered_list_range(rope, caret_line)
}
pub(crate) fn is_ordered_marker(marker: &ListMarker) -> bool {
matches!(marker.kind, ListMarkerKind::Ordered(_))
}
fn ordered_list_range(rope: &Rope, caret_line: usize) -> Option<(usize, usize, String)> {
let total = rope.len_lines();
if total == 0 || caret_line >= total {
return None;
}
let indent = caret_line_indent_for(rope, caret_line);
let body = line_body(rope, caret_line, &indent);
let marker = detect_list_marker(&body)?;
if !matches!(marker.kind, ListMarkerKind::Ordered(_)) {
return None;
}
let mut start = caret_line;
while start > 0 && is_ordered_at_indent(rope, start - 1, &indent) {
start -= 1;
}
let mut end = caret_line;
while end + 1 < total && is_ordered_at_indent(rope, end + 1, &indent) {
end += 1;
}
Some((start, end, indent))
}
fn caret_line_indent_for(rope: &Rope, line: usize) -> String {
let start = rope.line_to_byte(line);
let end = line_content_end(rope, line);
let text = rope.byte_slice(start..end).to_string();
text.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect()
}
fn line_body(rope: &Rope, line: usize, indent: &str) -> String {
let start = rope.line_to_byte(line);
let end = line_content_end(rope, line);
let text = rope.byte_slice(start..end).to_string();
text[indent.len().min(text.len())..].to_string()
}
fn is_ordered_at_exact_indent(rope: &Rope, line: usize, indent: &str) -> bool {
if caret_line_indent_for(rope, line) != indent {
return false;
}
let body = line_body(rope, line, indent);
detect_list_marker(&body)
.map(|m| matches!(m.kind, ListMarkerKind::Ordered(_)))
.unwrap_or(false)
}
fn is_ordered_at_indent(rope: &Rope, line: usize, indent: &str) -> bool {
let line_indent = caret_line_indent_for(rope, line);
if line_indent.len() > indent.len() && line_indent.starts_with(indent) {
return true;
}
if line_indent != indent {
return false;
}
let body = line_body(rope, line, indent);
detect_list_marker(&body)
.map(|m| matches!(m.kind, ListMarkerKind::Ordered(_)))
.unwrap_or(false)
}