rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Editing the command line like a text field: moving by character, word and line, and the keys
//! to send the shell to get its cursor there or to delete a range.
//!
//! The shell owns the command line, so selecting and deleting is done by sending it cursor
//! keys and Backspace. This is the pure part: positions are character indexes into the line.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Move {
    Left,
    Right,
    WordLeft,
    WordRight,
    Home,
    End,
}

/// 0 is white space, 1 is part of a word, 2 is a separator (punctuation).
fn class(c: char) -> u8 {
    if c.is_whitespace() {
        0
    } else if c.is_alphanumeric() || c == '_' {
        1
    } else {
        2
    }
}

/// Start of the word before `from`: skip spaces, then the run of the same kind of character, so
/// `src/main.rs` takes `rs`, `.`, `main`, `/`, `src` in turn.
pub fn word_left(chars: &[char], from: usize) -> usize {
    let mut i = from.min(chars.len());
    while i > 0 && class(chars[i - 1]) == 0 {
        i -= 1;
    }
    if i == 0 {
        return 0;
    }
    let kind = class(chars[i - 1]);
    while i > 0 && class(chars[i - 1]) == kind {
        i -= 1;
    }
    i
}

/// End of the word after `from`.
pub fn word_right(chars: &[char], from: usize) -> usize {
    let n = chars.len();
    let mut i = from.min(n);
    while i < n && class(chars[i]) == 0 {
        i += 1;
    }
    if i == n {
        return n;
    }
    let kind = class(chars[i]);
    while i < n && class(chars[i]) == kind {
        i += 1;
    }
    i
}

/// Where the cursor ends up after a move.
pub fn target(chars: &[char], cursor: usize, mv: Move) -> usize {
    let n = chars.len();
    match mv {
        Move::Left => cursor.saturating_sub(1),
        Move::Right => (cursor + 1).min(n),
        Move::WordLeft => word_left(chars, cursor),
        Move::WordRight => word_right(chars, cursor),
        Move::Home => 0,
        Move::End => n,
    }
}

/// The keys that move the shell's cursor from `from` to `to`.
pub fn move_keys(from: usize, to: usize, app_cursor: bool) -> Vec<u8> {
    let (left, right): (&[u8], &[u8]) = if app_cursor { (b"\x1bOD", b"\x1bOC") } else { (b"\x1b[D", b"\x1b[C") };
    if to < from { left.repeat(from - to) } else { right.repeat(to - from) }
}

/// The keys that delete `lo..hi` with the cursor at `cursor`: go to the end of the range, then
/// Backspace over it. The cursor is left at `lo`.
pub fn delete_keys(lo: usize, hi: usize, cursor: usize, app_cursor: bool) -> Vec<u8> {
    let mut keys = move_keys(cursor, hi, app_cursor);
    keys.extend(std::iter::repeat_n(0x7f, hi - lo));
    keys
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chars(s: &str) -> Vec<char> {
        s.chars().collect()
    }

    #[test]
    fn words_stop_at_separators() {
        let c = chars("cd src/main.rs  --flag");
        // From the end, backwards: flag, --, rs, ., main, /, src, cd.
        let mut stops = Vec::new();
        let mut at = c.len();
        while at > 0 {
            at = word_left(&c, at);
            stops.push(at);
        }
        assert_eq!(stops, vec![18, 16, 12, 11, 7, 6, 3, 0]);
        // And forwards.
        let mut stops = Vec::new();
        let mut at = 0;
        while at < c.len() {
            at = word_right(&c, at);
            stops.push(at);
        }
        assert_eq!(stops, vec![2, 6, 7, 11, 12, 14, 18, 22]);
    }

    #[test]
    fn moves_are_clamped_to_the_line() {
        let c = chars("abc def");
        assert_eq!(target(&c, 0, Move::Left), 0);
        assert_eq!(target(&c, 7, Move::Right), 7);
        assert_eq!(target(&c, 4, Move::Left), 3);
        assert_eq!(target(&c, 3, Move::WordLeft), 0);
        assert_eq!(target(&c, 3, Move::WordRight), 7);
        assert_eq!(target(&c, 5, Move::Home), 0);
        assert_eq!(target(&c, 1, Move::End), 7);
        assert_eq!(target(&[], 0, Move::WordLeft), 0);
        assert_eq!(target(&[], 0, Move::WordRight), 0);
        // Only separators and spaces.
        let c = chars("  ");
        assert_eq!((word_left(&c, 2), word_right(&c, 0)), (0, 2));
    }

    #[test]
    fn keys_for_moving_and_deleting() {
        assert_eq!(move_keys(5, 3, false), b"\x1b[D\x1b[D");
        assert_eq!(move_keys(3, 5, false), b"\x1b[C\x1b[C");
        assert_eq!(move_keys(3, 4, true), b"\x1bOC");
        assert!(move_keys(4, 4, false).is_empty());
        // Delete 2..5 with the cursor at 7: back to 5, then three Backspaces.
        assert_eq!(delete_keys(2, 5, 7, false), b"\x1b[D\x1b[D\x7f\x7f\x7f");
        // Cursor before the range: forward to its end first.
        let mut expected = b"".repeat(4);
        expected.extend_from_slice(b"");
        assert_eq!(delete_keys(2, 5, 1, false), expected);
        // Cursor already at the end of the range: only Backspace.
        assert_eq!(delete_keys(2, 5, 5, false), b"\x7f\x7f\x7f");
    }
}