idet-core 0.2.0

Shared text-editing library for a Micro-like terminal editor and a gedit-like egui GUI
Documentation
//! Moving the current line, paragraph or markdown section up or down.

/// Direction in which [`move_segment`] shifts text.
#[derive(Clone, Copy)]
pub enum LineMove {
    /// Move towards the start of the text.
    Up,
    /// Move towards the end of the text.
    Down,
}

/// How much text [`move_segment`] treats as one unit.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Segment {
    /// The single line holding the cursor.
    Line,
    /// The run of non-blank lines around the cursor.
    Block,
    /// A markdown heading with everything below it, subsections included.
    Section,
}

/// Swaps the line at `cursor` with its neighbour in `direction`.
///
/// `cursor` is a character index; the cursor stays on the moved line. Returns
/// the new text and cursor, or `None` when there is no neighbouring line.
#[must_use]
pub fn move_line(text: &str, cursor: usize, direction: LineMove) -> Option<(String, usize)> {
    move_segment(text, cursor, Segment::Line, direction)
}

/// Swaps the segment holding `cursor` with the neighbouring one in `direction`.
///
/// `cursor` is a character index and keeps its position inside the segment as
/// it moves. Blank lines separating two blocks stay where they are. Returns
/// the new text and cursor, or `None` when the cursor is outside any segment
/// or has no neighbour to swap with.
#[must_use]
pub fn move_segment(
    text: &str,
    cursor: usize,
    segment: Segment,
    direction: LineMove,
) -> Option<(String, usize)> {
    let lines: Vec<&str> = text.split('\n').collect();
    let (line, column) = line_column(text, cursor);
    let (start, end) = segment_range(&lines, line, segment)?;
    let (other_start, other_end) = neighbour_range(&lines, start, end, segment, direction)?;
    let moving_first = start < other_start;
    let (first, second) = if moving_first {
        ((start, end), (other_start, other_end))
    } else {
        ((other_start, other_end), (start, end))
    };
    let mut swapped: Vec<&str> = Vec::with_capacity(lines.len());
    swapped.extend_from_slice(&lines[..first.0]);
    swapped.extend_from_slice(&lines[second.0..second.1]);
    swapped.extend_from_slice(&lines[first.1..second.0]);
    swapped.extend_from_slice(&lines[first.0..first.1]);
    swapped.extend_from_slice(&lines[second.1..]);
    let moved_start = if moving_first {
        first.0 + (second.1 - second.0) + (second.0 - first.1)
    } else {
        first.0
    };
    let target_line = moved_start + (line - start);
    let target_column = column.min(swapped[target_line].chars().count());
    let moved_cursor = cursor_at(&swapped, target_line, target_column);
    Some((swapped.join("\n"), moved_cursor))
}

fn segment_range(lines: &[&str], line: usize, segment: Segment) -> Option<(usize, usize)> {
    match segment {
        Segment::Line => Some((line, line + 1)),
        Segment::Block => {
            if lines[line].trim().is_empty() {
                return None;
            }
            let mut start = line;
            while start > 0 && !lines[start - 1].trim().is_empty() {
                start -= 1;
            }
            let mut end = line + 1;
            while end < lines.len() && !lines[end].trim().is_empty() {
                end += 1;
            }
            Some((start, end))
        }
        Segment::Section => {
            let start = (0..=line)
                .rev()
                .find(|&index| heading_level(lines[index]).is_some())?;
            let level = heading_level(lines[start])?;
            Some((start, section_end(lines, start, level)))
        }
    }
}

fn neighbour_range(
    lines: &[&str],
    start: usize,
    end: usize,
    segment: Segment,
    direction: LineMove,
) -> Option<(usize, usize)> {
    match (segment, direction) {
        (Segment::Line, LineMove::Up) => Some((start.checked_sub(1)?, start)),
        (Segment::Line, LineMove::Down) => (end < lines.len()).then_some((end, end + 1)),
        (Segment::Block, LineMove::Up) => {
            let mut other_end = start;
            while other_end > 0 && lines[other_end - 1].trim().is_empty() {
                other_end -= 1;
            }
            let mut other_start = other_end.checked_sub(1)?;
            while other_start > 0 && !lines[other_start - 1].trim().is_empty() {
                other_start -= 1;
            }
            Some((other_start, other_end))
        }
        (Segment::Block, LineMove::Down) => {
            let mut other_start = end;
            while other_start < lines.len() && lines[other_start].trim().is_empty() {
                other_start += 1;
            }
            if other_start == lines.len() {
                return None;
            }
            let mut other_end = other_start + 1;
            while other_end < lines.len() && !lines[other_end].trim().is_empty() {
                other_end += 1;
            }
            Some((other_start, other_end))
        }
        (Segment::Section, LineMove::Up) => {
            let level = heading_level(lines[start])?;
            let other_start = (0..start)
                .rev()
                .find(|&index| heading_level(lines[index]).is_some())?;
            (heading_level(lines[other_start]) == Some(level)).then_some((other_start, start))
        }
        (Segment::Section, LineMove::Down) => {
            let level = heading_level(lines[start])?;
            (heading_level(lines.get(end)?) == Some(level))
                .then(|| (end, section_end(lines, end, level)))
        }
    }
}

fn section_end(lines: &[&str], start: usize, level: usize) -> usize {
    ((start + 1)..lines.len())
        .find(|&index| heading_level(lines[index]).is_some_and(|found| found <= level))
        .unwrap_or(lines.len())
}

fn heading_level(line: &str) -> Option<usize> {
    let hashes = line.chars().take_while(|&c| c == '#').count();
    (hashes > 0 && line.chars().nth(hashes) == Some(' ')).then_some(hashes)
}

/// Locates the zero-indexed `(line, column)` of the character at `cursor`.
#[must_use]
pub fn line_column(text: &str, cursor: usize) -> (usize, usize) {
    let mut line = 0;
    let mut column = 0;
    for (index, character) in text.chars().enumerate() {
        if index == cursor {
            break;
        }
        if character == '\n' {
            line += 1;
            column = 0;
        } else {
            column += 1;
        }
    }
    (line, column)
}

/// Converts a `(line, column)` position back into a character index, given
/// `text` already split on `\n`.
#[must_use]
pub fn cursor_at(lines: &[&str], line: usize, column: usize) -> usize {
    let preceding: usize = lines[..line].iter().map(|l| l.chars().count() + 1).sum();
    preceding + column
}