• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ilai-deutel / kibi / 19265285593

11 Nov 2025 12:15PM UTC coverage: 62.885% (-0.4%) from 63.31%
19265285593

Pull #496

github

web-flow
Merge ea5196d00 into a8471331e
Pull Request #496: Code re-organization to facilitate testing and reduce LOC

6 of 22 new or added lines in 2 files covered. (27.27%)

130 existing lines in 3 files now uncovered.

715 of 1137 relevant lines covered (62.88%)

709.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

59.25
/src/editor.rs
1
// "False positive, see https://github.com/rust-lang/rust-clippy/issues/13358#issuecomment-2767079754"
2
#![allow(unfulfilled_lint_expectations)]
3
#![expect(clippy::wildcard_imports)]
4

5
use std::fmt::{Display, Write as _};
6
use std::io::{self, BufRead, BufReader, ErrorKind, Read, Seek, Write};
7
use std::iter::{self, repeat, successors};
8
use std::{fs::File, path::Path, process::Command, time::Instant};
9

10
use crate::row::{HlState, Row};
11
use crate::{Config, Error, ansi_escape::*, syntax::Conf as SyntaxConf, sys, terminal};
12

UNCOV
13
const fn ctrl_key(key: u8) -> u8 { key & 0x1f }
×
14
const EXIT: u8 = ctrl_key(b'Q');
15
const DELETE_BIS: u8 = ctrl_key(b'H');
16
const REFRESH_SCREEN: u8 = ctrl_key(b'L');
17
const SAVE: u8 = ctrl_key(b'S');
18
const FIND: u8 = ctrl_key(b'F');
19
const GOTO: u8 = ctrl_key(b'G');
20
const CUT: u8 = ctrl_key(b'X');
21
const COPY: u8 = ctrl_key(b'C');
22
const PASTE: u8 = ctrl_key(b'V');
23
const DUPLICATE: u8 = ctrl_key(b'D');
24
const EXECUTE: u8 = ctrl_key(b'E');
25
const REMOVE_LINE: u8 = ctrl_key(b'R');
26
const BACKSPACE: u8 = 127;
27

28
const HELP_MESSAGE: &str = "^S save | ^Q quit | ^F find | ^G go to | ^D duplicate | ^E execute | \
29
                            ^C copy | ^X cut | ^V paste";
30

31
/// `set_status!` sets a formatted status message for the editor.
32
/// Example usage: `set_status!(editor, "{file_size} written to {file_name}")`
33
macro_rules! set_status { ($editor:expr, $($arg:expr),*) => ($editor.status_msg = Some(StatusMessage::new(format!($($arg),*)))) }
34

35
/// Enum of input keys
36
#[cfg_attr(test, derive(Debug, PartialEq))]
37
enum Key {
38
    Arrow(AKey),
39
    CtrlArrow(AKey),
40
    PageUp,
41
    PageDown,
42
    Home,
43
    End,
44
    Delete,
45
    Escape,
46
    Char(u8),
47
}
48

49
/// Enum of arrow keys
50
#[cfg_attr(test, derive(Debug, PartialEq))]
51
enum AKey {
52
    Left,
53
    Right,
54
    Up,
55
    Down,
56
}
57

58
/// Describes the cursor position and the screen offset
59
#[derive(Debug, Default, Clone, PartialEq)]
60
struct CursorState {
61
    /// x position (indexing the characters, not the columns)
62
    x: usize,
63
    /// y position (row number, 0-indexed)
64
    y: usize,
65
    /// Row offset
66
    roff: usize,
67
    /// Column offset
68
    coff: usize,
69
}
70

71
impl CursorState {
72
    const fn move_to_next_line(&mut self) { (self.x, self.y) = (0, self.y + 1); }
242✔
73

74
    /// Scroll the terminal window vertically and horizontally (i.e. adjusting
75
    /// the row offset and the column offset) so that the cursor can be
76
    /// shown.
UNCOV
77
    fn scroll(&mut self, rx: usize, screen_rows: usize, screen_cols: usize) {
×
UNCOV
78
        self.roff = self.roff.clamp(self.y.saturating_sub(screen_rows.saturating_sub(1)), self.y);
×
UNCOV
79
        self.coff = self.coff.clamp(rx.saturating_sub(screen_cols.saturating_sub(1)), rx);
×
UNCOV
80
    }
×
81
}
82

83
/// The `Editor` struct, contains the state and configuration of the text
84
/// editor.
85
#[derive(Default)]
86
pub struct Editor {
87
    /// If not `None`, the current prompt mode (`Save`, `Find`, `GoTo`, or
88
    /// `Execute`). If `None`, we are in regular edition mode.
89
    prompt_mode: Option<PromptMode>,
90
    /// The current state of the cursor.
91
    cursor: CursorState,
92
    /// The padding size used on the left for line numbering.
93
    ln_pad: usize,
94
    /// The width of the current window. Will be updated when the window is
95
    /// resized.
96
    window_width: usize,
97
    /// The number of rows that can be used for the editor, excluding the status
98
    /// bar and the message bar
99
    screen_rows: usize,
100
    /// The number of columns that can be used for the editor, excluding the
101
    /// part used for line numbers
102
    screen_cols: usize,
103
    /// The collection of rows, including the content and the syntax
104
    /// highlighting information.
105
    rows: Vec<Row>,
106
    /// Whether the document has been modified since it was open.
107
    dirty: bool,
108
    /// The configuration for the editor.
109
    config: Config,
110
    /// The number of consecutive times the user has tried to quit without
111
    /// saving. After `config.quit_times`, the program will exit.
112
    quit_times: usize,
113
    /// The file name. If None, the user will be prompted for a file name the
114
    /// first time they try to save.
115
    // TODO: It may be better to store a PathBuf instead
116
    file_name: Option<String>,
117
    /// The current status message being shown.
118
    status_msg: Option<StatusMessage>,
119
    /// The syntax configuration corresponding to the current file's extension.
120
    syntax: SyntaxConf,
121
    /// The number of bytes contained in `rows`. This excludes new lines.
122
    n_bytes: u64,
123
    /// The copied buffer of a row
124
    copied_row: Vec<u8>,
125
}
126

127
/// Describes a status message, shown at the bottom at the screen.
128
struct StatusMessage {
129
    /// The message to display.
130
    msg: String,
131
    /// The `Instant` the status message was first displayed.
132
    time: Instant,
133
}
134

135
impl StatusMessage {
136
    /// Create a new status message and set time to the current date/time.
UNCOV
137
    fn new(msg: String) -> Self { Self { msg, time: Instant::now() } }
×
138
}
139

140
/// Pretty-format a size in bytes.
141
fn format_size(n: u64) -> String {
187✔
142
    if n < 1024 {
187✔
143
        return format!("{n}B");
33✔
144
    }
154✔
145
    // i is the largest value such that 1024 ^ i < n
146
    let i = n.ilog2() / 10;
154✔
147

148
    // Compute the size with two decimal places (rounded down) as the last two
149
    // digits of q This avoid float formatting reducing the binary size
150
    let q = 100 * n / (1024 << ((i - 1) * 10));
154✔
151
    format!("{}.{:02}{}B", q / 100, q % 100, b" kMGTPEZ"[i as usize] as char)
154✔
152
}
187✔
153

154
/// Return an Arrow Key given an ANSI code.
155
///
156
/// The argument must be a valide arrow key ANSI code (`a`, `b`, `c` or `d`),
157
/// case-insensitive).
158
fn get_akey(c: u8) -> AKey {
66✔
159
    match c {
66✔
160
        b'a' | b'A' => AKey::Up,
11✔
161
        b'b' | b'B' => AKey::Down,
11✔
162
        b'c' | b'C' => AKey::Right,
33✔
163
        b'd' | b'D' => AKey::Left,
11✔
UNCOV
164
        _ => unreachable!("Invalid ANSI code for arrow key {}", c),
×
165
    }
166
}
66✔
167

168
impl Editor {
169
    /// Return the current row if the cursor points to an existing row, `None`
170
    /// otherwise.
171
    fn current_row(&self) -> Option<&Row> { self.rows.get(self.cursor.y) }
1,012✔
172

173
    /// Return the position of the cursor, in terms of rendered characters (as
174
    /// opposed to `self.cursor.x`, which is the position of the cursor in
175
    /// terms of bytes).
UNCOV
176
    fn rx(&self) -> usize { self.current_row().map_or(0, |r| r.cx2rx[self.cursor.x]) }
×
177

178
    /// Move the cursor following an arrow key (← → ↑ ↓).
179
    fn move_cursor(&mut self, key: &AKey, ctrl: bool) {
495✔
180
        match (key, self.current_row()) {
495✔
181
            (AKey::Left, Some(row)) if self.cursor.x > 0 => {
165✔
182
                let mut cursor_x = self.cursor.x - row.get_char_size(row.cx2rx[self.cursor.x] - 1);
132✔
183
                // ← moving to previous word
184
                while ctrl && cursor_x > 0 && row.chars[cursor_x - 1] != b' ' {
539✔
185
                    cursor_x -= row.get_char_size(row.cx2rx[cursor_x] - 1);
407✔
186
                }
407✔
187
                self.cursor.x = cursor_x;
132✔
188
            }
189
            // ← at the beginning of the line: move to the end of the previous line. The x
190
            // position will be adjusted after this `match` to accommodate the current row
191
            // length, so we can just set here to the maximum possible value here.
192
            (AKey::Left, _) if self.cursor.y > 0 =>
44✔
193
                (self.cursor.y, self.cursor.x) = (self.cursor.y - 1, usize::MAX),
33✔
194
            (AKey::Right, Some(row)) if self.cursor.x < row.chars.len() => {
99✔
195
                let mut cursor_x = self.cursor.x + row.get_char_size(row.cx2rx[self.cursor.x]);
55✔
196
                // → moving to next word
197
                while ctrl && cursor_x < row.chars.len() && row.chars[cursor_x] != b' ' {
275✔
198
                    cursor_x += row.get_char_size(row.cx2rx[cursor_x]);
220✔
199
                }
220✔
200
                self.cursor.x = cursor_x;
55✔
201
            }
202
            (AKey::Right, Some(_)) => self.cursor.move_to_next_line(),
44✔
203
            // TODO: For Up and Down, move self.cursor.x to be consistent with tabs and UTF-8
204
            //  characters, i.e. according to rx
205
            (AKey::Up, _) if self.cursor.y > 0 => self.cursor.y -= 1,
154✔
206
            (AKey::Down, Some(_)) => self.cursor.y += 1,
44✔
207
            _ => (),
44✔
208
        }
209
        self.update_cursor_x_position();
495✔
210
    }
495✔
211

212
    /// Update the cursor x position. If the cursor y position has changed, the
213
    /// current position might be illegal (x is further right than the last
214
    /// character of the row). If that is the case, clamp `self.cursor.x`.
215
    fn update_cursor_x_position(&mut self) {
495✔
216
        self.cursor.x = self.cursor.x.min(self.current_row().map_or(0, |row| row.chars.len()));
495✔
217
    }
495✔
218

219
    /// Run a loop to obtain the key that was pressed. At each iteration of the
220
    /// loop (until a key is pressed), we listen to the `ws_changed` channel
221
    /// to check if a window size change signal has been received. When
222
    /// bytes are received, we match to a corresponding `Key`. In particular,
223
    /// we handle ANSI escape codes to return `Key::Delete`, `Key::Home` etc.
224
    fn loop_until_keypress(&mut self, input: &mut impl BufRead) -> Result<Key, Error> {
154✔
225
        let mut bytes = input.bytes();
154✔
226
        loop {
227
            // Handle window size if a signal has be received
228
            if sys::has_window_size_changed() {
154✔
UNCOV
229
                self.update_window_size()?;
×
UNCOV
230
                self.refresh_screen()?;
×
231
            }
154✔
232
            if let Some(a) = bytes.next().transpose()? {
154✔
233
                // Match on the next byte received or, if the first byte is <ESC> ('\x1b'), on
234
                // the next few bytes.
235
                if a != b'\x1b' {
154✔
236
                    return Ok(Key::Char(a));
33✔
237
                }
121✔
238
                return Ok(match bytes.next().transpose()? {
121✔
239
                    Some(b @ (b'[' | b'O')) => match (b, bytes.next().transpose()?) {
121✔
240
                        (b'[', Some(c @ b'A'..=b'D')) => Key::Arrow(get_akey(c)),
66✔
241
                        (b'[' | b'O', Some(b'H')) => Key::Home,
22✔
242
                        (b'[' | b'O', Some(b'F')) => Key::End,
22✔
243
                        (b'[', mut c @ Some(b'0'..=b'8')) => {
33✔
244
                            let mut d = bytes.next().transpose()?;
22✔
245
                            if (c, d) == (Some(b'1'), Some(b';')) {
22✔
246
                                // 1 is the default modifier value. Therefore, <ESC>[1;5C is
247
                                // equivalent to <ESC>[5C, etc.
248
                                c = bytes.next().transpose()?;
11✔
249
                                d = bytes.next().transpose()?;
11✔
250
                            }
11✔
251
                            match (c, d) {
22✔
252
                                (Some(c), Some(b'~')) if c == b'1' || c == b'7' => Key::Home,
×
UNCOV
253
                                (Some(c), Some(b'~')) if c == b'4' || c == b'8' => Key::End,
×
254
                                (Some(b'3'), Some(b'~')) => Key::Delete,
×
UNCOV
255
                                (Some(b'5'), Some(b'~')) => Key::PageUp,
×
UNCOV
256
                                (Some(b'6'), Some(b'~')) => Key::PageDown,
×
257
                                (Some(b'5'), Some(d @ b'A'..=b'D')) => Key::CtrlArrow(get_akey(d)),
22✔
UNCOV
258
                                _ => Key::Escape,
×
259
                            }
260
                        }
UNCOV
261
                        (b'O', Some(c @ b'a'..=b'd')) => Key::CtrlArrow(get_akey(c)),
×
262
                        _ => Key::Escape,
11✔
263
                    },
UNCOV
264
                    _ => Key::Escape,
×
265
                });
UNCOV
266
            }
×
267
        }
268
    }
154✔
269

270
    /// Update the `screen_rows`, `window_width`, `screen_cols` and `ln_padding`
271
    /// attributes.
272
    fn update_window_size(&mut self) -> Result<(), Error> {
×
273
        let wsize = sys::get_window_size().or_else(|_| terminal::get_window_size_using_cursor())?;
×
274
        // Make room for the status bar and status message
UNCOV
275
        (self.screen_rows, self.window_width) = (wsize.0.saturating_sub(2), wsize.1);
×
UNCOV
276
        self.update_screen_cols();
×
UNCOV
277
        Ok(())
×
UNCOV
278
    }
×
279

280
    /// Update the `screen_cols` and `ln_padding` attributes based on the
281
    /// maximum number of digits for line numbers (since the left padding
282
    /// depends on this number of digits).
283
    fn update_screen_cols(&mut self) {
308✔
284
        // The maximum number of digits to use for the line number is the number of
285
        // digits of the last line number. This is equal to the number of times
286
        // we can divide this number by ten, computed below using `successors`.
287
        let n_digits =
308✔
288
            successors(Some(self.rows.len()), |u| Some(u / 10).filter(|u| *u > 0)).count();
308✔
289
        let show_line_num = self.config.show_line_num && n_digits + 2 < self.window_width / 4;
308✔
290
        self.ln_pad = if show_line_num { n_digits + 2 } else { 0 };
308✔
291
        self.screen_cols = self.window_width.saturating_sub(self.ln_pad);
308✔
292
    }
308✔
293

294
    /// Update a row, given its index. If `ignore_following_rows` is `false` and
295
    /// the highlight state has changed during the update (for instance, it
296
    /// is now in "multi-line comment" state, keep updating the next rows
297
    fn update_row(&mut self, y: usize, ignore_following_rows: bool) {
2,442✔
298
        let mut hl_state = if y > 0 { self.rows[y - 1].hl_state } else { HlState::Normal };
2,442✔
299
        for row in self.rows.iter_mut().skip(y) {
2,442✔
300
            let previous_hl_state = row.hl_state;
2,431✔
301
            hl_state = row.update(&self.syntax, hl_state, self.config.tab_stop);
2,431✔
302
            if ignore_following_rows || hl_state == previous_hl_state {
2,431✔
303
                return;
2,431✔
UNCOV
304
            }
×
305
            // If the state has changed (for instance, a multi-line comment
306
            // started in this row), continue updating the following
307
            // rows
308
        }
309
    }
2,442✔
310

311
    /// Update all the rows.
312
    fn update_all_rows(&mut self) {
×
313
        let mut hl_state = HlState::Normal;
×
UNCOV
314
        for row in &mut self.rows {
×
UNCOV
315
            hl_state = row.update(&self.syntax, hl_state, self.config.tab_stop);
×
UNCOV
316
        }
×
UNCOV
317
    }
×
318

319
    /// Insert a byte at the current cursor position. If there is no row at the
320
    /// current cursor position, add a new row and insert the byte.
321
    fn insert_byte(&mut self, c: u8) {
2,046✔
322
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
2,046✔
323
            row.chars.insert(self.cursor.x, c);
1,947✔
324
        } else {
1,947✔
325
            self.rows.push(Row::new(vec![c]));
99✔
326
            // The number of rows has changed. The left padding may need to be updated.
99✔
327
            self.update_screen_cols();
99✔
328
        }
99✔
329
        self.update_row(self.cursor.y, false);
2,046✔
330
        (self.cursor.x, self.n_bytes, self.dirty) = (self.cursor.x + 1, self.n_bytes + 1, true);
2,046✔
331
    }
2,046✔
332

333
    /// Insert a new line at the current cursor position and move the cursor to
334
    /// the start of the new line. If the cursor is in the middle of a row,
335
    /// split off that row.
336
    fn insert_new_line(&mut self) {
198✔
337
        let (position, new_row_chars) = if self.cursor.x == 0 {
198✔
338
            (self.cursor.y, Vec::new())
55✔
339
        } else {
340
            // self.rows[self.cursor.y] must exist, since cursor.x = 0 for any cursor.y ≥
341
            // row.len()
342
            let new_chars = self.rows[self.cursor.y].chars.split_off(self.cursor.x);
143✔
343
            self.update_row(self.cursor.y, false);
143✔
344
            (self.cursor.y + 1, new_chars)
143✔
345
        };
346
        self.rows.insert(position, Row::new(new_row_chars));
198✔
347
        self.update_row(position, false);
198✔
348
        self.update_screen_cols();
198✔
349
        self.cursor.move_to_next_line();
198✔
350
        self.dirty = true;
198✔
351
    }
198✔
352

353
    /// Delete a character at the current cursor position. If the cursor is
354
    /// located at the beginning of a row that is not the first or last row,
355
    /// merge the current row and the previous row. If the cursor is located
356
    /// after the last row, move up to the last character of the previous row.
357
    fn delete_char(&mut self) {
55✔
358
        if self.cursor.x > 0 {
55✔
359
            let row = &mut self.rows[self.cursor.y];
33✔
360
            // Obtain the number of bytes to be removed: could be 1-4 (UTF-8 character
361
            // size).
362
            let n_bytes_to_remove = row.get_char_size(row.cx2rx[self.cursor.x] - 1);
33✔
363
            row.chars.splice(self.cursor.x - n_bytes_to_remove..self.cursor.x, iter::empty());
33✔
364
            self.update_row(self.cursor.y, false);
33✔
365
            self.cursor.x -= n_bytes_to_remove;
33✔
366
            self.dirty = if self.is_empty() { self.file_name.is_some() } else { true };
33✔
367
            self.n_bytes -= n_bytes_to_remove as u64;
33✔
368
        } else if self.cursor.y < self.rows.len() && self.cursor.y > 0 {
22✔
369
            let row = self.rows.remove(self.cursor.y);
11✔
370
            let previous_row = &mut self.rows[self.cursor.y - 1];
11✔
371
            self.cursor.x = previous_row.chars.len();
11✔
372
            previous_row.chars.extend(&row.chars);
11✔
373
            self.update_row(self.cursor.y - 1, true);
11✔
374
            self.update_row(self.cursor.y, false);
11✔
375
            // The number of rows has changed. The left padding may need to be updated.
11✔
376
            self.update_screen_cols();
11✔
377
            (self.dirty, self.cursor.y) = (self.dirty, self.cursor.y - 1);
11✔
378
        } else if self.cursor.y == self.rows.len() {
11✔
379
            // If the cursor is located after the last row, pressing backspace is equivalent
11✔
380
            // to pressing the left arrow key.
11✔
381
            self.move_cursor(&AKey::Left, false);
11✔
382
        }
11✔
383
    }
55✔
384

385
    fn delete_current_row(&mut self) {
×
386
        if self.cursor.y < self.rows.len() {
×
387
            self.rows[self.cursor.y].chars.clear();
×
388
            self.update_row(self.cursor.y, false);
×
UNCOV
389
            self.cursor.move_to_next_line();
×
390
            self.delete_char();
×
391
        }
×
392
    }
×
393

UNCOV
394
    fn duplicate_current_row(&mut self) {
×
395
        self.copy_current_row();
×
396
        self.paste_current_row();
×
397
    }
×
398

399
    fn copy_current_row(&mut self) {
×
UNCOV
400
        if let Some(row) = self.current_row() {
×
401
            self.copied_row = row.chars.clone();
×
402
        }
×
403
    }
×
404

405
    fn paste_current_row(&mut self) {
×
406
        if self.copied_row.is_empty() {
×
407
            return;
×
408
        }
×
409
        self.n_bytes += self.copied_row.len() as u64;
×
410
        if self.cursor.y == self.rows.len() {
×
411
            self.rows.push(Row::new(self.copied_row.clone()));
×
412
        } else {
×
UNCOV
413
            self.rows.insert(self.cursor.y + 1, Row::new(self.copied_row.clone()));
×
414
        }
×
415
        self.update_row(self.cursor.y + usize::from(self.cursor.y + 1 != self.rows.len()), false);
×
UNCOV
416
        (self.cursor.y, self.dirty) = (self.cursor.y + 1, true);
×
417
        // The line number has changed
UNCOV
418
        self.update_screen_cols();
×
419
    }
×
420

421
    /// Try to load a file. If found, load the rows and update the render and
422
    /// syntax highlighting. If not found, do not return an error.
423
    fn load(&mut self, path: &Path) -> Result<(), Error> {
×
UNCOV
424
        let mut file = match File::open(path) {
×
425
            Err(e) if e.kind() == ErrorKind::NotFound => {
×
426
                self.rows.push(Row::new(Vec::new()));
×
427
                return Ok(());
×
428
            }
429
            r => r,
×
430
        }?;
×
431
        let ft = file.metadata()?.file_type();
×
432
        if !(ft.is_file() || ft.is_symlink()) {
×
UNCOV
433
            return Err(io::Error::new(ErrorKind::InvalidInput, "Invalid input file type").into());
×
UNCOV
434
        }
×
UNCOV
435
        for line in BufReader::new(&file).split(b'\n') {
×
UNCOV
436
            self.rows.push(Row::new(line?));
×
437
        }
438
        // If the file ends with an empty line or is empty, we need to append an empty
439
        // row to `self.rows`. Unfortunately, BufReader::split doesn't yield an
440
        // empty Vec in this case, so we need to check the last byte directly.
441
        file.seek(io::SeekFrom::End(0))?;
×
442
        #[expect(clippy::unbuffered_bytes)]
UNCOV
443
        if file.bytes().next().transpose()?.is_none_or(|b| b == b'\n') {
×
444
            self.rows.push(Row::new(Vec::new()));
×
445
        }
×
446
        self.update_all_rows();
×
447
        // The number of rows has changed. The left padding may need to be updated.
UNCOV
448
        self.update_screen_cols();
×
UNCOV
449
        self.n_bytes = self.rows.iter().map(|row| row.chars.len() as u64).sum();
×
450
        Ok(())
×
451
    }
×
452

453
    /// Save the text to a file, given its name.
454
    fn save(&self, file_name: &str) -> Result<usize, io::Error> {
×
455
        let mut file = File::create(file_name)?;
×
456
        let mut written = 0;
×
457
        for (i, row) in self.rows.iter().enumerate() {
×
458
            file.write_all(&row.chars)?;
×
459
            written += row.chars.len();
×
UNCOV
460
            if i != (self.rows.len() - 1) {
×
461
                file.write_all(b"\n")?;
×
462
                written += 1;
×
463
            }
×
464
        }
UNCOV
465
        file.sync_all()?;
×
UNCOV
466
        Ok(written)
×
UNCOV
467
    }
×
468

469
    /// Save the text to a file and handle all errors. Errors and success
470
    /// messages will be printed to the status bar. Return whether the file
471
    /// was successfully saved.
472
    fn save_and_handle_io_errors(&mut self, file_name: &str) -> bool {
×
473
        let saved = self.save(file_name);
×
474
        // Print error or success message to the status bar
UNCOV
475
        match saved.as_ref() {
×
476
            Ok(w) => set_status!(self, "{} written to {}", format_size(*w as u64), file_name),
×
477
            Err(err) => set_status!(self, "Can't save! I/O error: {err}"),
×
478
        }
479
        // If save was successful, set dirty to false.
UNCOV
480
        self.dirty &= saved.is_err();
×
UNCOV
481
        saved.is_ok()
×
UNCOV
482
    }
×
483

484
    /// Save to a file after obtaining the file path from the prompt. If
485
    /// successful, the `file_name` attribute of the editor will be set and
486
    /// syntax highlighting will be updated.
487
    fn save_as(&mut self, file_name: String) {
×
488
        if self.save_and_handle_io_errors(&file_name) {
×
489
            // If save was successful
×
490
            self.syntax = SyntaxConf::find(&file_name, &sys::data_dirs());
×
UNCOV
491
            self.file_name = Some(file_name);
×
UNCOV
492
            self.update_all_rows();
×
493
        }
×
494
    }
×
495

496
    /// Draw the left part of the screen: line numbers and vertical bar.
497
    fn draw_left_padding<T: Display>(&self, buffer: &mut String, val: T) -> Result<(), Error> {
×
498
        if self.ln_pad >= 2 {
×
499
            // \x1b[38;5;240m: Dark grey color; \u{2502}: pipe "│"
UNCOV
500
            write!(buffer, "\x1b[38;5;240m{:>2$} \u{2502}{}", val, RESET_FMT, self.ln_pad - 2)?;
×
UNCOV
501
        }
×
UNCOV
502
        Ok(())
×
UNCOV
503
    }
×
504

505
    /// Return whether the file being edited is empty or not. If there is more
506
    /// than one row, even if all the rows are empty, `is_empty` returns
507
    /// `false`, since the text contains new lines.
508
    fn is_empty(&self) -> bool { self.rows.len() <= 1 && self.n_bytes == 0 }
33✔
509

510
    /// Draw rows of text and empty rows on the terminal, by adding characters
511
    /// to the buffer.
512
    fn draw_rows(&self, buffer: &mut String) -> Result<(), Error> {
×
UNCOV
513
        let row_it = self.rows.iter().map(Some).chain(repeat(None)).enumerate();
×
514
        for (i, row) in row_it.skip(self.cursor.roff).take(self.screen_rows) {
×
515
            buffer.push_str(CLEAR_LINE_RIGHT_OF_CURSOR);
×
UNCOV
516
            if let Some(row) = row {
×
517
                // Draw a row of text
518
                self.draw_left_padding(buffer, i + 1)?;
×
519
                row.draw(self.cursor.coff, self.screen_cols, buffer)?;
×
520
            } else {
521
                // Draw an empty row
522
                self.draw_left_padding(buffer, '~')?;
×
UNCOV
523
                if self.is_empty() && i == self.screen_rows / 3 {
×
524
                    let welcome_message = concat!("Kibi ", env!("KIBI_VERSION"));
×
UNCOV
525
                    write!(buffer, "{:^1$.1$}", welcome_message, self.screen_cols)?;
×
526
                }
×
527
            }
UNCOV
528
            buffer.push_str("\r\n");
×
529
        }
530
        Ok(())
×
UNCOV
531
    }
×
532

533
    /// Draw the status bar on the terminal, by adding characters to the buffer.
534
    fn draw_status_bar(&self, buffer: &mut String) -> Result<(), Error> {
×
535
        // Left part of the status bar
UNCOV
536
        let modified = if self.dirty { " (modified)" } else { "" };
×
UNCOV
537
        let mut left =
×
538
            format!("{:.30}{modified}", self.file_name.as_deref().unwrap_or("[No Name]"));
×
539
        left.truncate(self.window_width);
×
540

541
        // Right part of the status bar
UNCOV
542
        let size = format_size(self.n_bytes + self.rows.len().saturating_sub(1) as u64);
×
543
        let right =
×
544
            format!("{} | {size} | {}:{}", self.syntax.name, self.cursor.y + 1, self.rx() + 1);
×
545

546
        // Draw
UNCOV
547
        let rw = self.window_width.saturating_sub(left.len());
×
UNCOV
548
        write!(buffer, "{REVERSE_VIDEO}{left}{right:>rw$.rw$}{RESET_FMT}\r\n")?;
×
UNCOV
549
        Ok(())
×
550
    }
×
551

552
    /// Draw the message bar on the terminal, by adding characters to the
553
    /// buffer.
554
    fn draw_message_bar(&self, buffer: &mut String) {
×
555
        buffer.push_str(CLEAR_LINE_RIGHT_OF_CURSOR);
×
556
        let msg_duration = self.config.message_dur;
×
UNCOV
557
        if let Some(sm) = self.status_msg.as_ref().filter(|sm| sm.time.elapsed() < msg_duration) {
×
UNCOV
558
            buffer.push_str(&sm.msg[..sm.msg.len().min(self.window_width)]);
×
UNCOV
559
        }
×
560
    }
×
561

562
    /// Refresh the screen: update the offsets, draw the rows, the status bar,
563
    /// the message bar, and move the cursor to the correct position.
564
    fn refresh_screen(&mut self) -> Result<(), Error> {
×
565
        self.cursor.scroll(self.rx(), self.screen_rows, self.screen_cols);
×
566
        let mut buffer = format!("{HIDE_CURSOR}{MOVE_CURSOR_TO_START}");
×
UNCOV
567
        self.draw_rows(&mut buffer)?;
×
UNCOV
568
        self.draw_status_bar(&mut buffer)?;
×
569
        self.draw_message_bar(&mut buffer);
×
UNCOV
570
        let (cursor_x, cursor_y) = if self.prompt_mode.is_none() {
×
571
            // If not in prompt mode, position the cursor according to the `cursor`
572
            // attributes.
573
            (self.rx() - self.cursor.coff + 1 + self.ln_pad, self.cursor.y - self.cursor.roff + 1)
×
574
        } else {
575
            // If in prompt mode, position the cursor on the prompt line at the end of the
576
            // line.
577
            (self.status_msg.as_ref().map_or(0, |sm| sm.msg.len() + 1), self.screen_rows + 2)
×
578
        };
579
        // Finally, print `buffer` and move the cursor
UNCOV
580
        print!("{buffer}\x1b[{cursor_y};{cursor_x}H{SHOW_CURSOR}");
×
UNCOV
581
        io::stdout().flush().map_err(Error::from)
×
UNCOV
582
    }
×
583

584
    /// Process a key that has been pressed, when not in prompt mode. Returns
585
    /// whether the program should exit, and optionally the prompt mode to
586
    /// switch to.
587
    fn process_keypress(&mut self, key: &Key) -> (bool, Option<PromptMode>) {
2,101✔
588
        // This won't be mutated, unless key is Key::Character(EXIT)
589
        let mut reset_quit_times = true;
2,101✔
590
        let mut prompt_mode = None;
2,101✔
591

592
        match key {
2,101✔
593
            Key::Arrow(arrow) => self.move_cursor(arrow, false),
×
594
            Key::CtrlArrow(arrow) => self.move_cursor(arrow, true),
×
595
            Key::PageUp => {
×
596
                self.cursor.y = self.cursor.roff.saturating_sub(self.screen_rows);
×
597
                self.update_cursor_x_position();
×
598
            }
×
UNCOV
599
            Key::PageDown => {
×
UNCOV
600
                self.cursor.y = (self.cursor.roff + 2 * self.screen_rows - 1).min(self.rows.len());
×
UNCOV
601
                self.update_cursor_x_position();
×
602
            }
×
603
            Key::Home => self.cursor.x = 0,
22✔
604
            Key::End => self.cursor.x = self.current_row().map_or(0, |row| row.chars.len()),
22✔
605
            Key::Char(b'\r' | b'\n') => self.insert_new_line(), // Enter
143✔
UNCOV
606
            Key::Char(BACKSPACE | DELETE_BIS) => self.delete_char(), // Backspace or Ctrl + H
×
UNCOV
607
            Key::Char(REMOVE_LINE) => self.delete_current_row(),
×
608
            Key::Delete => {
33✔
609
                self.move_cursor(&AKey::Right, false);
33✔
610
                self.delete_char();
33✔
611
            }
33✔
612
            Key::Escape | Key::Char(REFRESH_SCREEN) => (),
×
613
            Key::Char(EXIT) => {
NEW
614
                if !self.dirty || self.quit_times + 1 >= self.config.quit_times {
×
615
                    return (true, None);
×
616
                }
×
NEW
617
                let r = self.config.quit_times - self.quit_times - 1;
×
NEW
UNCOV
618
                set_status!(self, "Press Ctrl+Q {0} more time{1:.2$} to quit.", r, "s", r - 1);
×
NEW
619
                reset_quit_times = false;
×
620
            }
621
            Key::Char(SAVE) => match self.file_name.take() {
×
622
                // TODO: Can we avoid using take() then reassigning the value to file_name?
623
                Some(file_name) => {
×
UNCOV
624
                    self.save_and_handle_io_errors(&file_name);
×
UNCOV
625
                    self.file_name = Some(file_name);
×
626
                }
×
627
                None => prompt_mode = Some(PromptMode::Save(String::new())),
×
628
            },
629
            Key::Char(FIND) =>
630
                prompt_mode = Some(PromptMode::Find(String::new(), self.cursor.clone(), None)),
×
631
            Key::Char(GOTO) => prompt_mode = Some(PromptMode::GoTo(String::new())),
×
632
            Key::Char(DUPLICATE) => self.duplicate_current_row(),
×
633
            Key::Char(CUT) => {
×
634
                self.copy_current_row();
×
635
                self.delete_current_row();
×
UNCOV
636
            }
×
UNCOV
637
            Key::Char(COPY) => self.copy_current_row(),
×
638
            Key::Char(PASTE) => self.paste_current_row(),
×
UNCOV
639
            Key::Char(EXECUTE) => prompt_mode = Some(PromptMode::Execute(String::new())),
×
640
            Key::Char(c) => self.insert_byte(*c),
1,881✔
641
        }
642
        self.quit_times = if reset_quit_times { 0 } else { self.quit_times + 1 };
2,101✔
643
        (false, prompt_mode)
2,101✔
644
    }
2,101✔
645

646
    /// Try to find a query, this is called after pressing Ctrl-F and for each
647
    /// key that is pressed. `last_match` is the last row that was matched,
648
    /// `forward` indicates whether to search forward or backward. Returns
649
    /// the row of a new match, or `None` if the search was unsuccessful.
650
    fn find(&mut self, query: &str, last_match: Option<usize>, forward: bool) -> Option<usize> {
132✔
651
        // Number of rows to search
652
        let num_rows = if query.is_empty() { 0 } else { self.rows.len() };
132✔
653
        let mut current = last_match.unwrap_or_else(|| num_rows.saturating_sub(1));
132✔
654
        // TODO: Handle multiple matches per line
655
        for _ in 0..num_rows {
132✔
656
            current = (current + if forward { 1 } else { num_rows - 1 }) % num_rows;
110✔
657
            let row = &mut self.rows[current];
110✔
658
            if let Some(cx) = row.chars.windows(query.len()).position(|w| w == query.as_bytes()) {
110✔
659
                // self.cursor.coff: Try to reset the column offset; if the match is after the
660
                // offset, this will be updated in self.cursor.scroll() so that
661
                // the result is visible
UNCOV
662
                (self.cursor.x, self.cursor.y, self.cursor.coff) = (cx, current, 0);
×
UNCOV
663
                let rx = row.cx2rx[cx];
×
UNCOV
664
                row.match_segment = Some(rx..rx + query.len());
×
UNCOV
665
                return Some(current);
×
666
            }
110✔
667
        }
668
        None
132✔
669
    }
132✔
670

671
    /// If `file_name` is not None, load the file. Then run the text editor.
672
    ///
673
    /// # Errors
674
    ///
675
    /// Will Return `Err` if any error occur.
NEW
676
    pub fn run<I: BufRead>(&mut self, file_name: Option<&str>, input: &mut I) -> Result<(), Error> {
×
NEW
677
        self.update_window_size()?;
×
NEW
678
        set_status!(self, "{HELP_MESSAGE}");
×
NEW
679
        self.refresh_screen()?;
×
680

681
        if let Some(path) = file_name.map(sys::path) {
×
682
            self.syntax = SyntaxConf::find(&path.to_string_lossy(), &sys::data_dirs());
×
683
            self.load(path.as_path())?;
×
684
            self.file_name = Some(path.to_string_lossy().to_string());
×
UNCOV
685
        } else {
×
686
            self.rows.push(Row::new(Vec::new()));
×
687
            self.file_name = None;
×
688
        }
×
689
        loop {
690
            if let Some(mode) = &self.prompt_mode {
×
UNCOV
691
                set_status!(self, "{}", mode.status_msg());
×
692
            }
×
UNCOV
693
            self.refresh_screen()?;
×
NEW
694
            let key = self.loop_until_keypress(input)?;
×
695
            // TODO: Can we avoid using take()?
696
            self.prompt_mode = match self.prompt_mode.take() {
×
697
                // process_keypress returns (should_quit, prompt_mode)
698
                None => match self.process_keypress(&key) {
×
UNCOV
699
                    (true, _) => return Ok(()),
×
UNCOV
700
                    (false, prompt_mode) => prompt_mode,
×
701
                },
UNCOV
702
                Some(prompt_mode) => prompt_mode.process_keypress(self, &key),
×
703
            }
704
        }
705
    }
×
706
}
707

708
/// Set up the terminal and run the text editor. If `file_name` is not None,
709
/// load the file.
710
///
711
/// # Errors
712
///
713
/// Will Return `Err` if any error occur when registering the window size signal
714
/// handler, enabling raw mode, or running the editor.
715
pub fn run<I: BufRead>(file_name: Option<&str>, input: &mut I) -> Result<(), Error> {
120✔
716
    sys::register_winsize_change_signal_handler()?;
120✔
717
    let orig_term_mode = sys::enable_raw_mode()?;
120✔
NEW
718
    print!("{USE_ALTERNATE_SCREEN}");
×
719

NEW
720
    let mut editor = Editor { config: Config::load(), ..Default::default() };
×
NEW
721
    let result = editor.run(file_name, input);
×
722

723
    // Restore the original terminal mode.
NEW
724
    sys::set_term_mode(&orig_term_mode)?;
×
NEW
725
    print!("{USE_MAIN_SCREEN}");
×
NEW
726
    io::stdout().flush()?;
×
727

NEW
728
    result
×
729
}
120✔
730

731
/// The prompt mode.
732
#[cfg_attr(test, derive(Debug, PartialEq))]
733
enum PromptMode {
734
    /// Save(prompt buffer)
735
    Save(String),
736
    /// Find(prompt buffer, saved cursor state, last match)
737
    Find(String, CursorState, Option<usize>),
738
    /// GoTo(prompt buffer)
739
    GoTo(String),
740
    /// Execute(prompt buffer)
741
    Execute(String),
742
}
743

744
// TODO: Use trait with mode_status_msg and process_keypress, implement the
745
// trait for separate  structs for Save and Find?
746
impl PromptMode {
747
    /// Return the status message to print for the selected `PromptMode`.
UNCOV
748
    fn status_msg(&self) -> String {
×
UNCOV
749
        match self {
×
750
            Self::Save(buffer) => format!("Save as: {buffer}"),
×
751
            Self::Find(buffer, ..) => format!("Search (Use ESC/Arrows/Enter): {buffer}"),
×
752
            Self::GoTo(buffer) => format!("Enter line number[:column number]: {buffer}"),
×
753
            Self::Execute(buffer) => format!("Command to execute: {buffer}"),
×
754
        }
755
    }
×
756

757
    /// Process a keypress event for the selected `PromptMode`.
758
    fn process_keypress(self, ed: &mut Editor, key: &Key) -> Option<Self> {
154✔
759
        ed.status_msg = None;
154✔
760
        match self {
154✔
UNCOV
761
            Self::Save(b) => match process_prompt_keypress(b, key) {
×
UNCOV
762
                PromptState::Active(b) => return Some(Self::Save(b)),
×
763
                PromptState::Cancelled => set_status!(ed, "Save aborted"),
×
764
                PromptState::Completed(file_name) => ed.save_as(file_name),
×
765
            },
766
            Self::Find(b, saved_cursor, last_match) => {
154✔
767
                if let Some(row_idx) = last_match {
154✔
UNCOV
768
                    ed.rows[row_idx].match_segment = None;
×
769
                }
154✔
770
                match process_prompt_keypress(b, key) {
154✔
771
                    PromptState::Active(query) => {
132✔
772
                        #[expect(clippy::wildcard_enum_match_arm)]
773
                        let (last_match, forward) = match key {
132✔
774
                            Key::Arrow(AKey::Right | AKey::Down) | Key::Char(FIND) =>
UNCOV
775
                                (last_match, true),
×
UNCOV
776
                            Key::Arrow(AKey::Left | AKey::Up) => (last_match, false),
×
777
                            _ => (None, true),
132✔
778
                        };
779
                        let curr_match = ed.find(&query, last_match, forward);
132✔
780
                        return Some(Self::Find(query, saved_cursor, curr_match));
132✔
781
                    }
782
                    // The prompt was cancelled. Restore the previous position.
UNCOV
783
                    PromptState::Cancelled => ed.cursor = saved_cursor,
×
784
                    // Cursor has already been moved, do nothing
785
                    PromptState::Completed(_) => (),
22✔
786
                }
787
            }
UNCOV
788
            Self::GoTo(b) => match process_prompt_keypress(b, key) {
×
UNCOV
789
                PromptState::Active(b) => return Some(Self::GoTo(b)),
×
790
                PromptState::Cancelled => (),
×
791
                PromptState::Completed(b) => {
×
792
                    let mut split = b.splitn(2, ':')
×
793
                        // saturating_sub: Lines and cols are 1-indexed
794
                        .map(|u| u.trim().parse().map(|s: usize| s.saturating_sub(1)));
×
UNCOV
795
                    match (split.next().transpose(), split.next().transpose()) {
×
796
                        (Ok(Some(y)), Ok(x)) => {
×
797
                            ed.cursor.y = y.min(ed.rows.len());
×
798
                            if let Some(rx) = x {
×
799
                                ed.cursor.x = ed.current_row().map_or(0, |r| r.rx2cx[rx]);
×
800
                            } else {
×
801
                                ed.update_cursor_x_position();
×
802
                            }
×
803
                        }
804
                        (Err(e), _) | (_, Err(e)) => set_status!(ed, "Parsing error: {e}"),
×
UNCOV
805
                        (Ok(None), _) => (),
×
806
                    }
807
                }
808
            },
UNCOV
809
            Self::Execute(b) => match process_prompt_keypress(b, key) {
×
UNCOV
810
                PromptState::Active(b) => return Some(Self::Execute(b)),
×
811
                PromptState::Cancelled => (),
×
812
                PromptState::Completed(b) => {
×
813
                    let mut args = b.split_whitespace();
×
814
                    match Command::new(args.next().unwrap_or_default()).args(args).output() {
×
815
                        Ok(out) if !out.status.success() =>
×
816
                            set_status!(ed, "{}", String::from_utf8_lossy(&out.stderr).trim_end()),
×
817
                        Ok(out) => out.stdout.into_iter().for_each(|c| match c {
×
818
                            b'\n' => ed.insert_new_line(),
×
819
                            c => ed.insert_byte(c),
×
820
                        }),
×
821
                        Err(e) => set_status!(ed, "{e}"),
×
822
                    }
823
                }
824
            },
825
        }
826
        None
22✔
827
    }
154✔
828
}
829

830
/// The state of the prompt after processing a keypress event.
831
#[cfg_attr(test, derive(Debug, PartialEq))]
832
enum PromptState {
833
    // Active contains the current buffer
834
    Active(String),
835
    // Completed contains the final string
836
    Completed(String),
837
    Cancelled,
838
}
839

840
/// Process a prompt keypress event and return the new state for the prompt.
841
fn process_prompt_keypress(mut buffer: String, key: &Key) -> PromptState {
374✔
842
    #[expect(clippy::wildcard_enum_match_arm)]
843
    match key {
209✔
844
        Key::Char(b'\r') => return PromptState::Completed(buffer),
33✔
845
        Key::Escape | Key::Char(EXIT) => return PromptState::Cancelled,
22✔
846
        Key::Char(BACKSPACE | DELETE_BIS) => _ = buffer.pop(),
99✔
847
        Key::Char(c @ 0..=126) if !c.is_ascii_control() => buffer.push(*c as char),
220✔
848
        // No-op
849
        _ => (),
22✔
850
    }
851
    PromptState::Active(buffer)
319✔
852
}
374✔
853

854
#[cfg(test)]
855
mod tests {
856
    use std::io::Cursor;
857

858
    use rstest::rstest;
859

860
    use super::*;
861

862
    fn assert_row_chars_equal(editor: &Editor, expected: &[&[u8]]) {
55✔
863
        assert_eq!(editor.rows.len(), expected.len());
55✔
864
        for (i, (row, expected)) in editor.rows.iter().zip(expected).enumerate() {
77✔
865
            assert_eq!(
77✔
866
                row.chars,
867
                *expected,
UNCOV
868
                "comparing characters for row {}\n  left: {}\n  right: {})",
×
869
                i,
870
                String::from_utf8_lossy(&row.chars),
×
UNCOV
871
                String::from_utf8_lossy(expected)
×
872
            );
873
        }
874
    }
55✔
875

876
    #[rstest]
877
    #[case(0, "0B")]
878
    #[case(1, "1B")]
879
    #[case(1023, "1023B")]
880
    #[case(1024, "1.00kB")]
881
    #[case(1536, "1.50kB")]
882
    // round down!
883
    #[case(21 * 1024 - 11, "20.98kB")]
884
    #[case(21 * 1024 - 10, "20.99kB")]
885
    #[case(21 * 1024 - 3, "20.99kB")]
886
    #[case(21 * 1024, "21.00kB")]
887
    #[case(21 * 1024 + 3, "21.00kB")]
888
    #[case(21 * 1024 + 10, "21.00kB")]
889
    #[case(21 * 1024 + 11, "21.01kB")]
890
    #[case(1024 * 1024 - 1, "1023.99kB")]
891
    #[case(1024 * 1024, "1.00MB")]
892
    #[case(1024 * 1024 + 1, "1.00MB")]
893
    #[case(100 * 1024 * 1024 * 1024, "100.00GB")]
894
    #[case(313 * 1024 * 1024 * 1024 * 1024, "313.00TB")]
895
    fn format_size_output(#[case] input: u64, #[case] expected_output: &str) {
896
        assert_eq!(format_size(input), expected_output);
897
    }
898

899
    #[test]
900
    fn editor_insert_byte() {
11✔
901
        let mut editor = Editor::default();
11✔
902
        let editor_cursor_x_before = editor.cursor.x;
11✔
903

904
        editor.insert_byte(b'X');
11✔
905
        editor.insert_byte(b'Y');
11✔
906
        editor.insert_byte(b'Z');
11✔
907

908
        assert_eq!(editor.cursor.x, editor_cursor_x_before + 3);
11✔
909
        assert_eq!(editor.rows.len(), 1);
11✔
910
        assert_eq!(editor.n_bytes, 3);
11✔
911
        assert_eq!(editor.rows[0].chars, [b'X', b'Y', b'Z']);
11✔
912
    }
11✔
913

914
    #[test]
915
    fn editor_insert_new_line() {
11✔
916
        let mut editor = Editor::default();
11✔
917
        let editor_cursor_y_before = editor.cursor.y;
11✔
918

919
        for _ in 0..3 {
44✔
920
            editor.insert_new_line();
33✔
921
        }
33✔
922

923
        assert_eq!(editor.cursor.y, editor_cursor_y_before + 3);
11✔
924
        assert_eq!(editor.rows.len(), 3);
11✔
925
        assert_eq!(editor.n_bytes, 0);
11✔
926

927
        for row in &editor.rows {
44✔
928
            assert_eq!(row.chars, []);
33✔
929
        }
930
    }
11✔
931

932
    #[test]
933
    fn editor_delete_char() {
11✔
934
        let mut editor = Editor::default();
11✔
935
        for b in b"Hello world!" {
143✔
936
            editor.insert_byte(*b);
132✔
937
        }
132✔
938
        editor.delete_char();
11✔
939
        assert_row_chars_equal(&editor, &[b"Hello world"]);
11✔
940
        editor.move_cursor(&AKey::Left, true);
11✔
941
        editor.move_cursor(&AKey::Left, false);
11✔
942
        editor.move_cursor(&AKey::Left, false);
11✔
943
        editor.delete_char();
11✔
944
        assert_row_chars_equal(&editor, &[b"Helo world"]);
11✔
945
    }
11✔
946

947
    #[test]
948
    fn editor_delete_next_char() {
11✔
949
        let mut editor = Editor::default();
11✔
950
        for &b in b"Hello world!\nHappy New Year!" {
319✔
951
            editor.process_keypress(&Key::Char(b));
308✔
952
        }
308✔
953
        editor.process_keypress(&Key::Delete);
11✔
954
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New Year!"]);
11✔
955
        editor.move_cursor(&AKey::Left, true);
11✔
956
        editor.process_keypress(&Key::Delete);
11✔
957
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New ear!"]);
11✔
958
        editor.move_cursor(&AKey::Left, true);
11✔
959
        editor.move_cursor(&AKey::Left, true);
11✔
960
        editor.move_cursor(&AKey::Left, true);
11✔
961
        editor.process_keypress(&Key::Delete);
11✔
962
        assert_row_chars_equal(&editor, &[b"Hello world!Happy New ear!"]);
11✔
963
    }
11✔
964

965
    #[test]
966
    fn editor_move_cursor_left() {
11✔
967
        let mut editor = Editor::default();
11✔
968
        for &b in b"Hello world!\nHappy New Year!" {
319✔
969
            editor.process_keypress(&Key::Char(b));
308✔
970
        }
308✔
971

972
        // check current position
973
        assert_eq!(editor.cursor.x, 15);
11✔
974
        assert_eq!(editor.cursor.y, 1);
11✔
975

976
        editor.move_cursor(&AKey::Left, true);
11✔
977
        assert_eq!(editor.cursor.x, 10);
11✔
978
        assert_eq!(editor.cursor.y, 1);
11✔
979

980
        editor.move_cursor(&AKey::Left, false);
11✔
981
        assert_eq!(editor.cursor.x, 9);
11✔
982
        assert_eq!(editor.cursor.y, 1);
11✔
983

984
        editor.move_cursor(&AKey::Left, true);
11✔
985
        assert_eq!(editor.cursor.x, 6);
11✔
986
        assert_eq!(editor.cursor.y, 1);
11✔
987

988
        editor.move_cursor(&AKey::Left, true);
11✔
989
        assert_eq!(editor.cursor.x, 0);
11✔
990
        assert_eq!(editor.cursor.y, 1);
11✔
991

992
        editor.move_cursor(&AKey::Left, false);
11✔
993
        assert_eq!(editor.cursor.x, 12);
11✔
994
        assert_eq!(editor.cursor.y, 0);
11✔
995

996
        editor.move_cursor(&AKey::Left, true);
11✔
997
        assert_eq!(editor.cursor.x, 6);
11✔
998
        assert_eq!(editor.cursor.y, 0);
11✔
999

1000
        editor.move_cursor(&AKey::Left, true);
11✔
1001
        assert_eq!(editor.cursor.x, 0);
11✔
1002
        assert_eq!(editor.cursor.y, 0);
11✔
1003

1004
        editor.move_cursor(&AKey::Left, false);
11✔
1005
        assert_eq!(editor.cursor.x, 0);
11✔
1006
        assert_eq!(editor.cursor.y, 0);
11✔
1007
    }
11✔
1008

1009
    #[test]
1010
    fn editor_move_cursor_up() {
11✔
1011
        let mut editor = Editor::default();
11✔
1012
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
319✔
1013
            editor.process_keypress(&Key::Char(b));
308✔
1014
        }
308✔
1015

1016
        // check current position
1017
        assert_eq!(editor.cursor.x, 16);
11✔
1018
        assert_eq!(editor.cursor.y, 2);
11✔
1019

1020
        editor.move_cursor(&AKey::Up, false);
11✔
1021
        assert_eq!(editor.cursor.x, 2);
11✔
1022
        assert_eq!(editor.cursor.y, 1);
11✔
1023

1024
        editor.move_cursor(&AKey::Up, true);
11✔
1025
        assert_eq!(editor.cursor.x, 2);
11✔
1026
        assert_eq!(editor.cursor.y, 0);
11✔
1027

1028
        editor.move_cursor(&AKey::Up, false);
11✔
1029
        assert_eq!(editor.cursor.x, 2);
11✔
1030
        assert_eq!(editor.cursor.y, 0);
11✔
1031
    }
11✔
1032

1033
    #[test]
1034
    fn editor_move_cursor_right() {
11✔
1035
        let mut editor = Editor::default();
11✔
1036
        for &b in b"Hello world\nHappy New Year" {
297✔
1037
            editor.process_keypress(&Key::Char(b));
286✔
1038
        }
286✔
1039

1040
        // check current position
1041
        assert_eq!(editor.cursor.x, 14);
11✔
1042
        assert_eq!(editor.cursor.y, 1);
11✔
1043

1044
        editor.move_cursor(&AKey::Right, false);
11✔
1045
        assert_eq!(editor.cursor.x, 0);
11✔
1046
        assert_eq!(editor.cursor.y, 2);
11✔
1047

1048
        editor.move_cursor(&AKey::Right, false);
11✔
1049
        assert_eq!(editor.cursor.x, 0);
11✔
1050
        assert_eq!(editor.cursor.y, 2);
11✔
1051

1052
        editor.move_cursor(&AKey::Up, true);
11✔
1053
        editor.move_cursor(&AKey::Up, true);
11✔
1054
        assert_eq!(editor.cursor.x, 0);
11✔
1055
        assert_eq!(editor.cursor.y, 0);
11✔
1056

1057
        editor.move_cursor(&AKey::Right, true);
11✔
1058
        assert_eq!(editor.cursor.x, 5);
11✔
1059
        assert_eq!(editor.cursor.y, 0);
11✔
1060

1061
        editor.move_cursor(&AKey::Right, true);
11✔
1062
        assert_eq!(editor.cursor.x, 11);
11✔
1063
        assert_eq!(editor.cursor.y, 0);
11✔
1064

1065
        editor.move_cursor(&AKey::Right, false);
11✔
1066
        assert_eq!(editor.cursor.x, 0);
11✔
1067
        assert_eq!(editor.cursor.y, 1);
11✔
1068
    }
11✔
1069

1070
    #[test]
1071
    fn editor_move_cursor_down() {
11✔
1072
        let mut editor = Editor::default();
11✔
1073
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
319✔
1074
            editor.process_keypress(&Key::Char(b));
308✔
1075
        }
308✔
1076

1077
        // check current position
1078
        assert_eq!(editor.cursor.x, 16);
11✔
1079
        assert_eq!(editor.cursor.y, 2);
11✔
1080

1081
        editor.move_cursor(&AKey::Down, false);
11✔
1082
        assert_eq!(editor.cursor.x, 0);
11✔
1083
        assert_eq!(editor.cursor.y, 3);
11✔
1084

1085
        editor.move_cursor(&AKey::Up, false);
11✔
1086
        editor.move_cursor(&AKey::Up, false);
11✔
1087
        editor.move_cursor(&AKey::Up, false);
11✔
1088

1089
        assert_eq!(editor.cursor.x, 0);
11✔
1090
        assert_eq!(editor.cursor.y, 0);
11✔
1091

1092
        editor.move_cursor(&AKey::Right, true);
11✔
1093
        assert_eq!(editor.cursor.x, 8);
11✔
1094
        assert_eq!(editor.cursor.y, 0);
11✔
1095

1096
        editor.move_cursor(&AKey::Down, true);
11✔
1097
        assert_eq!(editor.cursor.x, 2);
11✔
1098
        assert_eq!(editor.cursor.y, 1);
11✔
1099

1100
        editor.move_cursor(&AKey::Down, true);
11✔
1101
        assert_eq!(editor.cursor.x, 2);
11✔
1102
        assert_eq!(editor.cursor.y, 2);
11✔
1103

1104
        editor.move_cursor(&AKey::Down, true);
11✔
1105
        assert_eq!(editor.cursor.x, 0);
11✔
1106
        assert_eq!(editor.cursor.y, 3);
11✔
1107

1108
        editor.move_cursor(&AKey::Down, false);
11✔
1109
        assert_eq!(editor.cursor.x, 0);
11✔
1110
        assert_eq!(editor.cursor.y, 3);
11✔
1111
    }
11✔
1112

1113
    #[test]
1114
    fn editor_press_home_key() {
11✔
1115
        let mut editor = Editor::default();
11✔
1116
        for &b in b"Hello\nWorld\nand\nFerris!" {
264✔
1117
            editor.process_keypress(&Key::Char(b));
253✔
1118
        }
253✔
1119

1120
        // check current position
1121
        assert_eq!(editor.cursor.x, 7);
11✔
1122
        assert_eq!(editor.cursor.y, 3);
11✔
1123

1124
        editor.process_keypress(&Key::Home);
11✔
1125
        assert_eq!(editor.cursor.x, 0);
11✔
1126
        assert_eq!(editor.cursor.y, 3);
11✔
1127

1128
        editor.move_cursor(&AKey::Up, false);
11✔
1129
        editor.move_cursor(&AKey::Up, false);
11✔
1130
        editor.move_cursor(&AKey::Up, false);
11✔
1131

1132
        assert_eq!(editor.cursor.x, 0);
11✔
1133
        assert_eq!(editor.cursor.y, 0);
11✔
1134

1135
        editor.move_cursor(&AKey::Right, true);
11✔
1136
        assert_eq!(editor.cursor.x, 5);
11✔
1137
        assert_eq!(editor.cursor.y, 0);
11✔
1138

1139
        editor.process_keypress(&Key::Home);
11✔
1140
        assert_eq!(editor.cursor.x, 0);
11✔
1141
        assert_eq!(editor.cursor.y, 0);
11✔
1142
    }
11✔
1143

1144
    #[test]
1145
    fn editor_press_end_key() {
11✔
1146
        let mut editor = Editor::default();
11✔
1147
        for &b in b"Hello\nWorld\nand\nFerris!" {
264✔
1148
            editor.process_keypress(&Key::Char(b));
253✔
1149
        }
253✔
1150

1151
        // check current position
1152
        assert_eq!(editor.cursor.x, 7);
11✔
1153
        assert_eq!(editor.cursor.y, 3);
11✔
1154

1155
        editor.process_keypress(&Key::End);
11✔
1156
        assert_eq!(editor.cursor.x, 7);
11✔
1157
        assert_eq!(editor.cursor.y, 3);
11✔
1158

1159
        editor.move_cursor(&AKey::Up, false);
11✔
1160
        editor.move_cursor(&AKey::Up, false);
11✔
1161
        editor.move_cursor(&AKey::Up, false);
11✔
1162

1163
        assert_eq!(editor.cursor.x, 3);
11✔
1164
        assert_eq!(editor.cursor.y, 0);
11✔
1165

1166
        editor.process_keypress(&Key::End);
11✔
1167
        assert_eq!(editor.cursor.x, 5);
11✔
1168
        assert_eq!(editor.cursor.y, 0);
11✔
1169
    }
11✔
1170

1171
    #[test]
1172
    fn loop_until_keypress() -> Result<(), Error> {
11✔
1173
        let mut editor = Editor::default();
11✔
1174
        let mut fake_stdin = Cursor::new(
11✔
1175
            b"abc\x1b[A\x1b[B\x1b[C\x1b[D\x1b[H\x1bOH\x1b[F\x1bOF\x1b[1;5C\x1b[5C\x1b[99",
1176
        );
1177
        for expected_key in [
154✔
1178
            Key::Char(b'a'),
11✔
1179
            Key::Char(b'b'),
11✔
1180
            Key::Char(b'c'),
11✔
1181
            Key::Arrow(AKey::Up),
11✔
1182
            Key::Arrow(AKey::Down),
11✔
1183
            Key::Arrow(AKey::Right),
11✔
1184
            Key::Arrow(AKey::Left),
11✔
1185
            Key::Home,
11✔
1186
            Key::Home,
11✔
1187
            Key::End,
11✔
1188
            Key::End,
11✔
1189
            Key::CtrlArrow(AKey::Right),
11✔
1190
            Key::CtrlArrow(AKey::Right),
11✔
1191
            Key::Escape,
11✔
1192
        ] {
1193
            assert_eq!(editor.loop_until_keypress(&mut fake_stdin)?, expected_key);
154✔
1194
        }
1195
        Ok(())
11✔
1196
    }
11✔
1197

1198
    #[rstest]
1199
    #[case::ascii_completed(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(b'\r')], &PromptState::Completed(String::from("Hi")))]
1200
    #[case::escape(&[Key::Char(b'H'), Key::Char(b'i'), Key::Escape], &PromptState::Cancelled)]
1201
    #[case::exit(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(EXIT)], &PromptState::Cancelled)]
1202
    #[case::skip_ascii_control(&[Key::Char(b'\x0A')], &PromptState::Active(String::new()))]
1203
    #[case::unsupported_non_ascii(&[Key::Char(b'\xEF')], &PromptState::Active(String::new()))]
1204
    #[case::backspace(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], &PromptState::Active(String::new()))]
1205
    #[case::delete_bis(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(DELETE_BIS), Key::Char(DELETE_BIS), Key::Char(DELETE_BIS)], &PromptState::Active(String::new()))]
1206
    fn process_prompt_keypresses(#[case] keys: &[Key], #[case] expected_final_state: &PromptState) {
1207
        let mut prompt_state = PromptState::Active(String::new());
1208
        for key in keys {
1209
            if let PromptState::Active(buffer) = prompt_state {
1210
                prompt_state = process_prompt_keypress(buffer, key);
1211
            } else {
1212
                panic!("Prompt state: {prompt_state:?} is not active")
1213
            }
1214
        }
1215
        assert_eq!(prompt_state, *expected_final_state);
1216
    }
1217

1218
    #[rstest]
1219
    #[case(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(b'e'), Key::Char(b'l'), Key::Char(b'l'), Key::Char(b'o')], "Hello")]
1220
    #[case(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], "")]
1221
    fn process_find_keypress_completed(#[case] keys: &[Key], #[case] expected_final_value: &str) {
1222
        let mut ed: Editor = Editor::default();
1223
        ed.insert_new_line();
1224
        let mut prompt_mode = Some(PromptMode::Find(String::new(), CursorState::default(), None));
1225
        for key in keys {
1226
            prompt_mode = prompt_mode
1227
                .take()
1228
                .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, key));
132✔
1229
        }
1230
        assert_eq!(
1231
            prompt_mode,
1232
            Some(PromptMode::Find(
1233
                String::from(expected_final_value),
1234
                CursorState::default(),
1235
                None
1236
            ))
1237
        );
1238
        prompt_mode = prompt_mode
1239
            .take()
1240
            .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, &Key::Char(b'\r')));
22✔
1241
        assert_eq!(prompt_mode, None);
1242
    }
1243
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc