summaryrefslogtreecommitdiff
path: root/src/widgets/luaeditor/buffer.rs
blob: 905950e5b34299193d4ab96bd554852b234e82bf (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use std::str::FromStr;

use super::cursor::{Cursor, CursorMove};

#[derive(Default, Debug)]
pub struct Buffer {
    lines: Vec<String>,
    cursor: Cursor,
}

impl Buffer {
    pub fn new() -> Self {
        Self {
            lines: Vec::new(),
            cursor: Cursor::new().with_position(0, 0).with_max(0, 0),
        }
    }

    fn refresh_line_max(&mut self) {
        self.cursor
            .set_x_max(self.lines[self.cursor.y() as usize].len())
    }

    fn refresh_buffer_max(&mut self) {
        self.cursor.set_y_max(self.lines.len() - 1);
    }

    fn refresh_max(&mut self) {
        self.refresh_line_max();
        self.refresh_buffer_max();
    }

    fn end_balance(&self, level: usize) -> isize {
        let str = "\t".repeat(level);
        let start_count = self
            .lines
            .iter()
            .filter(|s| {
                s.starts_with(&(str.clone() + "if "))
                    || s.starts_with(&(str.clone() + "for "))
                    || s.starts_with(&(str.clone() + "while "))
                    || (s.starts_with(&str) && s.contains("function(") && s.ends_with(")"))
            })
            .count();

        let end_count = self
            .lines
            .iter()
            .filter(|s| s.starts_with(&(str.clone() + "end ")) || **s == (str.clone() + "end"))
            .count();

        (end_count as isize) - (start_count as isize)
    }

    pub fn insert(&mut self, c: char) {
        match c {
            '\n' => {
                let (a, b) = {
                    let line = self.current_line();
                    let (a, b) = line.split_at(self.cursor.x());
                    (a.to_string(), b.to_string())
                };

                let indent_normalized = a.replace("  ", "\t");
                let indent = indent_normalized.len() - indent_normalized.trim_start().len();
                let l = a.trim();
                let insert_end = (l.starts_with("if ") && l.ends_with(" then"))
                    || ((l.starts_with("for ") || l.starts_with("while ")) && l.ends_with(" do"))
                    || (l.contains("function(") && l.ends_with(")"));

                let extra_indent = if insert_end { 1 } else { 0 };

                {
                    *self.current_line_mut() = a;
                }
                self.cursor.move_unchecked(CursorMove::Down(1));
                self.cursor.move_unchecked(CursorMove::Begin);
                self.lines
                    .insert(self.cursor().y(), "\t".repeat(indent + extra_indent) + &b);

                if insert_end && self.end_balance(indent) < 0 {
                    self.lines
                        .insert(self.cursor().y() + 1, "\t".repeat(indent) + "end");
                }

                self.refresh_max();
                self.cursor
                    .move_checked(CursorMove::Right(indent + extra_indent));
            }
            _ => {
                let x = self.cursor().x();
                self.current_line_mut().insert(x, c);
                self.refresh_line_max();
                self.cursor.move_checked(CursorMove::Right(1));
            }
        }
    }

    pub fn delete(&mut self) {
        if self.cursor.is_at_start() && !self.cursor.is_at_top() {
            let old_line = self.current_line_mut().clone();
            self.lines.remove(self.cursor.y());
            self.cursor.move_checked(CursorMove::Up(1));
            self.refresh_line_max();

            let new_x = self.current_line().len();
            self.current_line_mut().push_str(&old_line);
            self.cursor
                .move_checked(CursorMove::Jump((new_x, self.cursor.y())));

            self.refresh_buffer_max()
        } else {
            let x = self.cursor.x() - 1;
            self.current_line_mut().remove(x);
            self.refresh_line_max();
            self.cursor.move_checked(CursorMove::Left(1));
        }
    }

    pub fn line(&self, index: usize) -> Option<&String> {
        self.lines.get(index)
    }

    fn line_mut(&mut self, index: usize) -> Option<&mut String> {
        self.lines.get_mut(index)
    }

    pub fn current_line(&self) -> &String {
        self.line(self.cursor.y() as usize).unwrap()
    }

    fn current_line_mut(&mut self) -> &mut String {
        self.line_mut(self.cursor.y() as usize).unwrap()
    }

    pub fn cursor(&self) -> &Cursor {
        &self.cursor
    }

    pub fn move_cursor(&mut self, m: CursorMove) {
        match m {
            CursorMove::Up(_)
            | CursorMove::Down(_)
            | CursorMove::Top
            | CursorMove::Bottom
            | CursorMove::Jump(_) => {
                self.cursor.move_checked(m);
                self.cursor.set_x_max(self.current_line().len());
                self.cursor.correct_cursor_position();
            }
            CursorMove::Left(_) | CursorMove::Right(_) | CursorMove::Begin | CursorMove::End => {
                self.cursor.move_checked(m)
            }
        }
    }

    pub fn lines(&self) -> &Vec<String> {
        &self.lines
    }
}

impl FromStr for Buffer {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lines: Vec<_> = s.lines().map(|s| s.to_string()).collect();
        let mut buffer = Self::new();
        buffer.lines = lines;

        buffer.refresh_max();

        Ok(buffer)
    }
}