aboutsummaryrefslogtreecommitdiff
path: root/helix-view/src/prompt.rs
blob: 98389a9744044a3597994eb30b617a0c70898baf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::commands;
use crate::View;
use crossterm::event::{KeyCode, KeyEvent};
use std::string::String;

pub struct Prompt {
    pub buffer: String,
    pub cursor_loc: usize,
}

impl Prompt {
    pub fn new() -> Prompt {
        let prompt = Prompt {
            buffer: String::from(""),
            cursor_loc: 0,
        };
        prompt
    }

    pub fn insert_char(&mut self, c: char) {
        self.buffer.insert(self.cursor_loc, c);
        self.cursor_loc += 1;
    }

    pub fn move_char_left_prompt(&mut self) {
        if self.cursor_loc > 1 {
            self.cursor_loc -= 1;
        }
    }

    pub fn move_char_right_prompt(&mut self) {
        if self.cursor_loc < self.buffer.len() {
            self.cursor_loc += 1;
        }
    }

    pub fn delete_char_backwards(&mut self) {
        if self.cursor_loc > 0 {
            self.buffer.remove(self.cursor_loc - 1);
            self.cursor_loc -= 1;
        }
    }

    pub fn handle_input(&mut self, key_event: KeyEvent, view: &mut View) {
        match key_event {
            KeyEvent {
                code: KeyCode::Char(c),
                ..
            } => self.insert_char(c),
            KeyEvent {
                code: KeyCode::Esc, ..
            } => commands::normal_mode(view, 1),
            KeyEvent {
                code: KeyCode::Right,
                ..
            } => self.move_char_right_prompt(),
            KeyEvent {
                code: KeyCode::Left,
                ..
            } => self.move_char_left_prompt(),
            KeyEvent {
                code: KeyCode::Backspace,
                ..
            } => self.delete_char_backwards(),
            _ => (),
        }
    }
}