Skip to main content

tui/widgets/
editor.rs

1//! Text-input editor: a buffer with a cursor and the editing operations the
2//! keymap names. It does no I/O, so it can be tested without a terminal; the only trace of
3//! drawing it keeps is the scroll position of the text it is shown in.
4
5use std::cell::Cell;
6
7use tvui::Viewport;
8
9mod lines;
10
11pub use lines::TEXT_AREA_ROWS;
12
13/// A text buffer with a cursor. Loaded text is kept verbatim, newlines
14/// included; a single-line editor cannot type one, a multi-line one
15/// ([`Editor::multiline`]) can and moves by lines.
16#[derive(Debug, Clone, Default)]
17pub struct Editor {
18    buffer: String,
19    cursor: usize,
20    multiline: bool,
21    scroll: Cell<Viewport>,
22}
23
24impl Editor {
25    #[must_use]
26    pub fn with_buffer(buffer: impl Into<String>) -> Self {
27        let buf: String = buffer.into();
28        let cursor = buf.chars().count();
29        Self {
30            buffer: buf,
31            cursor,
32            multiline: false,
33            scroll: Cell::default(),
34        }
35    }
36
37    #[must_use]
38    pub fn buffer(&self) -> &str {
39        &self.buffer
40    }
41
42    /// The cell the draw of the field showing this editor keeps its scroll in.
43    #[must_use]
44    pub fn scroll(&self) -> &Cell<Viewport> {
45        &self.scroll
46    }
47
48    /// Where the field showing this editor is scrolled to.
49    #[must_use]
50    pub fn viewport(&self) -> Viewport {
51        self.scroll.get()
52    }
53
54    /// Remember the scroll the drawing of the field ended at; the frame only borrows the editor.
55    pub fn set_viewport(&self, viewport: Viewport) {
56        self.scroll.set(viewport);
57    }
58
59    #[must_use]
60    pub fn cursor(&self) -> usize {
61        self.cursor
62    }
63
64    /// Puts the cursor before character `index`, or at the end when the text is shorter.
65    pub fn set_cursor(&mut self, index: usize) {
66        self.cursor = index.min(self.buffer.chars().count());
67    }
68
69    /// Replace the entire buffer with `new`, placing the cursor at the end.
70    pub fn replace_buffer(&mut self, new: impl Into<String>) {
71        let buf: String = new.into();
72        self.cursor = buf.chars().count();
73        self.buffer = buf;
74    }
75
76    fn chars(&self) -> Vec<char> {
77        self.buffer.chars().collect()
78    }
79
80    fn rebuild(&mut self, chars: &[char]) {
81        self.buffer = chars.iter().collect();
82        if self.cursor > chars.len() {
83            self.cursor = chars.len();
84        }
85    }
86
87    /// Insert a single character at the cursor.
88    pub fn insert_char(&mut self, c: char) {
89        let mut chars = self.chars();
90        chars.insert(self.cursor, c);
91        self.cursor += 1;
92        self.rebuild(&chars);
93    }
94
95    pub fn delete_backward(&mut self) {
96        let mut chars = self.chars();
97        let span = self.terminator_span(&chars, self.cursor, true).unwrap_or(1);
98        let Some(start) = self.cursor.checked_sub(span) else {
99            return;
100        };
101        chars.drain(start..self.cursor);
102        self.cursor = start;
103        self.rebuild(&chars);
104    }
105
106    pub fn delete_forward(&mut self) {
107        let mut chars = self.chars();
108        if self.cursor < chars.len() {
109            let span = self
110                .terminator_span(&chars, self.cursor, false)
111                .unwrap_or(1);
112            chars.drain(self.cursor..self.cursor + span);
113            self.rebuild(&chars);
114        }
115    }
116
117    pub fn move_left(&mut self) {
118        self.cursor = self.cursor.saturating_sub(1);
119        if self.inside_crlf() {
120            self.cursor -= 1;
121        }
122    }
123
124    pub fn move_right(&mut self) {
125        if self.cursor < self.buffer.chars().count() {
126            self.cursor += 1;
127        }
128        if self.inside_crlf() {
129            self.cursor += 1;
130        }
131    }
132
133    pub fn move_home(&mut self) {
134        self.cursor = self.home_target();
135    }
136
137    pub fn move_end(&mut self) {
138        self.cursor = self.end_target();
139    }
140
141    /// Delete from the cursor to end-of-line (emacs C-k).
142    /// In a multi-line editor it stops at the line end, and at the line end
143    /// it deletes the line terminator instead.
144    pub fn kill_to_end(&mut self) {
145        let end = self.end_target();
146        if self.multiline && self.cursor == end {
147            self.delete_forward();
148            return;
149        }
150        let mut chars = self.chars();
151        chars.drain(self.cursor..end);
152        self.rebuild(&chars);
153    }
154
155    /// Delete the word before the cursor (emacs C-w).
156    pub fn kill_word_backward(&mut self) {
157        let mut chars = self.chars();
158        let mut i = self.cursor;
159        while i > 0 && chars[i - 1].is_whitespace() {
160            i -= 1;
161        }
162        while i > 0 && !chars[i - 1].is_whitespace() {
163            i -= 1;
164        }
165        chars.drain(i..self.cursor);
166        self.cursor = i;
167        self.rebuild(&chars);
168    }
169
170    pub fn word_forward(&mut self) {
171        let chars = self.chars();
172        let mut i = self.cursor;
173        while i < chars.len() && !chars[i].is_whitespace() {
174            i += 1;
175        }
176        while i < chars.len() && chars[i].is_whitespace() {
177            i += 1;
178        }
179        self.cursor = i;
180    }
181
182    pub fn word_backward(&mut self) {
183        let chars = self.chars();
184        let mut i = self.cursor;
185        while i > 0 && chars[i - 1].is_whitespace() {
186            i -= 1;
187        }
188        while i > 0 && !chars[i - 1].is_whitespace() {
189            i -= 1;
190        }
191        self.cursor = i;
192    }
193
194    pub fn delete_word_forward(&mut self) {
195        let mut chars = self.chars();
196        let start = self.cursor;
197        let mut i = start;
198        while i < chars.len() && !chars[i].is_whitespace() {
199            i += 1;
200        }
201        while i < chars.len() && chars[i].is_whitespace() {
202            i += 1;
203        }
204        chars.drain(start..i);
205        self.rebuild(&chars);
206    }
207}
208
209#[cfg(test)]
210#[path = "editor_tests.rs"]
211mod tests;