use std::collections::HashMap;
use continuity_text::{Position, Selection};
use ropey::Rope;
use crate::edit_markdown::{line_text, split_leading_list_marker};
use crate::edit_planning::{finalize_specs, line_content_end, EditSpec};
use crate::selection_edit::SelectionEditPlan;
use crate::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ContainerKind {
ListItem,
BlockQuote,
}
pub(crate) fn finalize_block_toggle_specs(
rope: &Rope,
mut specs: Vec<EditSpec>,
selections_before: Vec<Selection>,
selections_after: Vec<Selection>,
) -> Result<Option<SelectionEditPlan>, Error> {
if specs.is_empty() {
return Ok(None);
}
let rewritten = collect_rewritten_lines(rope, &specs);
let separator_lines = compute_separator_lines(rope, &rewritten);
if separator_lines.is_empty() {
return Ok(finalize_specs(specs, selections_before, selections_after));
}
for &line in &separator_lines {
let at = line_content_end(rope, line);
specs.push(EditSpec::insert(rope, at, line_ending_at(rope, line))?);
}
let selections_after = shift_selections_past_separators(&selections_after, &separator_lines);
Ok(finalize_specs(specs, selections_before, selections_after))
}
fn line_ending_at(rope: &Rope, line: usize) -> String {
let content_end = line_content_end(rope, line);
let line_end = if line + 1 < rope.len_lines() {
rope.line_to_byte(line + 1)
} else {
rope.len_bytes()
};
let ending = rope.byte_slice(content_end..line_end).to_string();
if ending.is_empty() {
"\n".to_string()
} else {
ending
}
}
fn collect_rewritten_lines(rope: &Rope, specs: &[EditSpec]) -> Vec<(usize, String)> {
let mut out = Vec::with_capacity(specs.len());
for spec in specs {
if spec.inserted.contains('\n') {
continue;
}
let line = rope.byte_to_line(spec.start);
if rope.line_to_byte(line) != spec.start || line_content_end(rope, line) != spec.end {
continue;
}
out.push((line, spec.inserted.clone()));
}
out.sort_by_key(|(line, _)| *line);
out.dedup_by_key(|(line, _)| *line);
out
}
fn compute_separator_lines(rope: &Rope, rewritten: &[(usize, String)]) -> Vec<usize> {
if rewritten.is_empty() {
return Vec::new();
}
let new_text: HashMap<usize, &str> = rewritten
.iter()
.map(|(line, text)| (*line, text.as_str()))
.collect();
let mut out = Vec::new();
for (first, last) in contiguous_runs(rewritten) {
if let Some(line) = leading_separator(rope, &new_text, first) {
out.push(line);
}
if let Some(line) = trailing_separator(rope, &new_text, last) {
out.push(line);
}
}
out.sort_unstable();
out.dedup();
out
}
fn leading_separator(rope: &Rope, new_text: &HashMap<usize, &str>, first: usize) -> Option<usize> {
if first == 0 || new_text.contains_key(&(first - 1)) {
return None;
}
let previous = line_text(rope, first - 1);
if previous.is_empty() {
return None;
}
let old = line_text(rope, first);
let new = new_text.get(&first)?;
let was_joined = is_joined(&previous, &old);
let is_now_joined = is_joined(&previous, new);
(is_now_joined && !was_joined).then_some(first - 1)
}
fn trailing_separator(rope: &Rope, new_text: &HashMap<usize, &str>, last: usize) -> Option<usize> {
let next = last + 1;
if next >= rope.len_lines() || new_text.contains_key(&next) {
return None;
}
let following = line_text(rope, next);
let old = line_text(rope, last);
if old.is_empty() {
return None;
}
let new = new_text.get(&last)?;
if !is_joined(new, &following) {
return None;
}
let was_joined = is_joined(&old, &following);
let opened_container = match container_kind(new) {
Some(kind) => Some(kind) != container_kind(&old),
None => false,
};
(!was_joined || opened_container).then_some(last)
}
fn contiguous_runs(rewritten: &[(usize, String)]) -> Vec<(usize, usize)> {
let mut runs = Vec::new();
let mut start = rewritten[0].0;
let mut previous = start;
for &(line, _) in &rewritten[1..] {
if line != previous + 1 {
runs.push((start, previous));
start = line;
}
previous = line;
}
runs.push((start, previous));
runs
}
fn is_joined(leading: &str, following: &str) -> bool {
is_paragraph_continuable_line(leading) && is_lazy_continuation_line(following)
}
fn is_paragraph_continuable_line(text: &str) -> bool {
let body = text.trim_start_matches([' ', '\t']);
if body.trim().is_empty() || starts_leaf_block(body) {
return false;
}
!strip_container_markers(body).trim().is_empty()
}
fn is_lazy_continuation_line(text: &str) -> bool {
let indent: usize = text
.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.map(|c| if c == '\t' { 4 } else { 1 })
.sum();
let body = text.trim_start_matches([' ', '\t']);
if body.trim().is_empty() {
return false;
}
if indent >= 4 {
return true;
}
!starts_new_block(body)
}
fn starts_new_block(body: &str) -> bool {
if starts_leaf_block(body) || body.starts_with('>') {
return true;
}
for marker in ["- ", "* ", "+ "] {
if let Some(rest) = body.strip_prefix(marker) {
return !rest.trim().is_empty();
}
}
if let Some(rest) = body
.strip_prefix("1. ")
.or_else(|| body.strip_prefix("1) "))
{
return !rest.trim().is_empty();
}
false
}
fn starts_leaf_block(body: &str) -> bool {
is_atx_heading(body)
|| body.starts_with("```")
|| body.starts_with("~~~")
|| is_thematic_break(body)
|| body.starts_with('<')
}
fn is_atx_heading(body: &str) -> bool {
let hashes = body.chars().take_while(|c| *c == '#').count();
if hashes == 0 || hashes > 6 {
return false;
}
matches!(body[hashes..].chars().next(), None | Some(' ') | Some('\t'))
}
fn is_thematic_break(body: &str) -> bool {
let stripped: String = body.chars().filter(|c| *c != ' ' && *c != '\t').collect();
stripped.len() >= 3
&& ['-', '*', '_']
.iter()
.any(|marker| stripped.chars().all(|c| c == *marker))
}
fn strip_container_markers(body: &str) -> &str {
let mut rest = body;
loop {
if let Some(stripped) = rest.strip_prefix('>') {
rest = stripped.trim_start_matches([' ', '\t']);
continue;
}
let (marker, after) = split_leading_list_marker(rest);
if marker.is_empty() {
return rest;
}
rest = after;
}
}
fn container_kind(text: &str) -> Option<ContainerKind> {
let body = text.trim_start_matches([' ', '\t']);
if body.starts_with('>') {
return Some(ContainerKind::BlockQuote);
}
let (marker, _) = split_leading_list_marker(body);
(!marker.is_empty()).then_some(ContainerKind::ListItem)
}
fn shift_selections_past_separators(
selections: &[Selection],
separator_lines: &[usize],
) -> Vec<Selection> {
let shift = |position: Position| -> Position {
let moved = separator_lines
.iter()
.filter(|&&line| (position.line as usize) > line)
.count();
Position::new(
position.line.saturating_add(moved as u32),
position.byte_in_line,
)
};
selections
.iter()
.map(|selection| Selection {
anchor: shift(selection.anchor),
head: shift(selection.head),
kind: selection.kind,
})
.collect()
}
#[cfg(test)]
mod tests;