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

ilai-deutel / kibi / 19543534761

20 Nov 2025 04:14PM UTC coverage: 68.233% (+0.06%) from 68.178%
19543534761

push

github

ilai-deutel
[Assets] New logo, screenshots; improved recording; generation scripts (#520)

842 of 1234 relevant lines covered (68.23%)

958.04 hits per line

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

66.62
/src/editor.rs
1
use std::fmt::{Display, Write as _};
2
use std::io::{self, BufRead, BufReader, ErrorKind, Read, Seek, Write};
3
use std::iter::{self, repeat, successors};
4
use std::{fs::File, path::Path, process::Command, time::Instant};
5

6
use crate::row::{HlState, Row};
7
use crate::{Config, Error, ansi_escape::*, syntax::Conf as SyntaxConf, sys, terminal};
8

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

24
const WELCOME_MESSAGE: &str = concat!("Kibi ", env!("KIBI_VERSION"));
25
const HELP_MESSAGE: &str = "^S save | ^Q quit | ^F find | ^G go to | ^D duplicate | ^E execute | \
26
                            ^C copy | ^X cut | ^V paste";
27

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

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

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

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

68
impl CursorState {
69
    const fn move_to_next_line(&mut self) { (self.x, self.y) = (0, self.y + 1); }
1,089✔
70

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

384
    fn delete_current_row(&mut self) {
231✔
385
        if self.cursor.y < self.rows.len() {
231✔
386
            self.rows[self.cursor.y].chars.clear();
220✔
387
            self.cursor.x = 0;
220✔
388
            self.cursor.y = std::cmp::min(self.cursor.y + 1, self.rows.len() - 1);
220✔
389
            self.delete_char();
220✔
390
            self.cursor.x = 0;
220✔
391
        }
220✔
392
    }
231✔
393

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) {
×
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
        let y = (self.cursor.y + 1).min(self.rows.len());
×
411
        self.rows.insert(y, Row::new(self.copied_row.clone()));
×
412
        self.update_row(y, false);
×
413
        (self.cursor.y, self.dirty) = (y, true);
×
414
        self.update_screen_cols();
×
415
    }
×
416

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

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

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

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

492
    /// Draw the left part of the screen: line numbers and vertical bar.
493
    fn draw_left_padding<T: Display>(&self, buffer: &mut String, val: T) {
88✔
494
        if self.ln_pad >= 2 {
88✔
495
            // \u{2502}: pipe "│"
44✔
496
            let s = format!("{:>1$} \u{2502}", val, self.ln_pad - 2);
44✔
497
            // \x1b[38;5;240m: Dark grey color
44✔
498
            push_colored(buffer, "\x1b[38;5;240m", &s, self.use_color);
44✔
499
        }
44✔
500
    }
88✔
501

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

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

529
    /// Draw the status bar on the terminal, by adding characters to the buffer.
530
    fn draw_status_bar(&self, buffer: &mut String) {
×
531
        // Left part of the status bar
532
        let modified = if self.dirty { " (modified)" } else { "" };
×
533
        let mut left =
×
534
            format!("{:.30}{modified}", self.file_name.as_deref().unwrap_or("[No Name]"));
×
535
        left.truncate(self.window_width);
×
536

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

542
        // Draw
543
        let rw = self.window_width.saturating_sub(left.len());
×
544
        push_colored(buffer, WBG, &format!("{left}{right:>rw$.rw$}\r\n"), self.use_color);
×
545
    }
×
546

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

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

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

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

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

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

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

702
/// Set up the terminal and run the text editor. If `file_name` is not None,
703
/// load the file.
704
///
705
/// Update the panic hook to restore the terminal on panic.
706
///
707
/// # Errors
708
///
709
/// Will Return `Err` if any error occur when registering the window size signal
710
/// handler, enabling raw mode, or running the editor.
711
pub fn run<I: BufRead>(file_name: Option<&str>, input: &mut I) -> Result<(), Error> {
120✔
712
    sys::register_winsize_change_signal_handler()?;
120✔
713
    let orig_term_mode = sys::enable_raw_mode()?;
120✔
714
    let mut editor = Editor { config: Config::load(), ..Default::default() };
×
715
    editor.use_color = !std::env::var("NO_COLOR").is_ok_and(|val| !val.is_empty());
×
716

717
    print!("{USE_ALTERNATE_SCREEN}");
×
718

719
    let prev_hook = std::panic::take_hook();
×
720
    std::panic::set_hook(Box::new(move |info| {
×
721
        terminal::restore_terminal(&orig_term_mode).unwrap_or_else(|e| eprintln!("{e}"));
×
722
        prev_hook(info);
×
723
    }));
×
724

725
    let result = editor.run(file_name, input);
×
726

727
    // Restore the original terminal mode.
728
    terminal::restore_terminal(&orig_term_mode)?;
×
729

730
    result
×
731
}
120✔
732

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

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

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

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

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

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

860
    use rstest::rstest;
861

862
    use super::*;
863
    use crate::syntax::HlType;
864

865
    fn assert_row_chars_equal(editor: &Editor, expected: &[&[u8]]) {
264✔
866
        assert_eq!(
264✔
867
            editor.rows.len(),
264✔
868
            expected.len(),
264✔
869
            "editor has {} rows, expected {}",
870
            editor.rows.len(),
×
871
            expected.len()
×
872
        );
873
        for (i, (row, expected)) in editor.rows.iter().zip(expected).enumerate() {
506✔
874
            assert_eq!(
506✔
875
                row.chars,
876
                *expected,
877
                "comparing characters for row {}\n  left: {}\n  right: {}",
878
                i,
879
                String::from_utf8_lossy(&row.chars),
×
880
                String::from_utf8_lossy(expected)
×
881
            );
882
        }
883
    }
264✔
884

885
    fn assert_row_synthax_highlighting_types_equal(editor: &Editor, expected: &[&[HlType]]) {
33✔
886
        assert_eq!(
33✔
887
            editor.rows.len(),
33✔
888
            expected.len(),
33✔
889
            "editor has {} rows, expected {}",
890
            editor.rows.len(),
×
891
            expected.len()
×
892
        );
893
        for (i, (row, expected)) in editor.rows.iter().zip(expected).enumerate() {
165✔
894
            assert_eq!(row.hl, *expected, "comparing HlTypes for row {i}",);
165✔
895
        }
896
    }
33✔
897

898
    #[rstest]
899
    #[case(0, "0B")]
900
    #[case(1, "1B")]
901
    #[case(1023, "1023B")]
902
    #[case(1024, "1.00kB")]
903
    #[case(1536, "1.50kB")]
904
    // round down!
905
    #[case(21 * 1024 - 11, "20.98kB")]
906
    #[case(21 * 1024 - 10, "20.99kB")]
907
    #[case(21 * 1024 - 3, "20.99kB")]
908
    #[case(21 * 1024, "21.00kB")]
909
    #[case(21 * 1024 + 3, "21.00kB")]
910
    #[case(21 * 1024 + 10, "21.00kB")]
911
    #[case(21 * 1024 + 11, "21.01kB")]
912
    #[case(1024 * 1024 - 1, "1023.99kB")]
913
    #[case(1024 * 1024, "1.00MB")]
914
    #[case(1024 * 1024 + 1, "1.00MB")]
915
    #[case(100 * 1024 * 1024 * 1024, "100.00GB")]
916
    #[case(313 * 1024 * 1024 * 1024 * 1024, "313.00TB")]
917
    fn format_size_output(#[case] input: u64, #[case] expected_output: &str) {
918
        assert_eq!(format_size(input), expected_output);
919
    }
920

921
    #[test]
922
    fn editor_insert_byte() {
11✔
923
        let mut editor = Editor::default();
11✔
924
        let editor_cursor_x_before = editor.cursor.x;
11✔
925

926
        editor.insert_byte(b'X');
11✔
927
        editor.insert_byte(b'Y');
11✔
928
        editor.insert_byte(b'Z');
11✔
929

930
        assert_eq!(editor.cursor.x, editor_cursor_x_before + 3);
11✔
931
        assert_eq!(editor.rows.len(), 1);
11✔
932
        assert_eq!(editor.n_bytes, 3);
11✔
933
        assert_eq!(editor.rows[0].chars, [b'X', b'Y', b'Z']);
11✔
934
    }
11✔
935

936
    #[test]
937
    fn editor_insert_new_line() {
11✔
938
        let mut editor = Editor::default();
11✔
939
        let editor_cursor_y_before = editor.cursor.y;
11✔
940

941
        for _ in 0..3 {
33✔
942
            editor.insert_new_line();
33✔
943
        }
33✔
944

945
        assert_eq!(editor.cursor.y, editor_cursor_y_before + 3);
11✔
946
        assert_eq!(editor.rows.len(), 3);
11✔
947
        assert_eq!(editor.n_bytes, 0);
11✔
948

949
        for row in &editor.rows {
33✔
950
            assert_eq!(row.chars, []);
33✔
951
        }
952
    }
11✔
953

954
    #[test]
955
    fn editor_delete_char() {
11✔
956
        let mut editor = Editor::default();
11✔
957
        for b in b"Hello world!" {
132✔
958
            editor.insert_byte(*b);
132✔
959
        }
132✔
960
        editor.delete_char();
11✔
961
        assert_row_chars_equal(&editor, &[b"Hello world"]);
11✔
962
        editor.move_cursor(&AKey::Left, true);
11✔
963
        editor.move_cursor(&AKey::Left, false);
11✔
964
        editor.move_cursor(&AKey::Left, false);
11✔
965
        editor.delete_char();
11✔
966
        assert_row_chars_equal(&editor, &[b"Helo world"]);
11✔
967
    }
11✔
968

969
    #[test]
970
    fn editor_delete_next_char() {
11✔
971
        let mut editor = Editor::default();
11✔
972
        for &b in b"Hello world!\nHappy New Year!" {
308✔
973
            editor.process_keypress(&Key::Char(b));
308✔
974
        }
308✔
975
        editor.process_keypress(&Key::Delete);
11✔
976
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New Year!"]);
11✔
977
        editor.move_cursor(&AKey::Left, true);
11✔
978
        editor.process_keypress(&Key::Delete);
11✔
979
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New ear!"]);
11✔
980
        editor.move_cursor(&AKey::Left, true);
11✔
981
        editor.move_cursor(&AKey::Left, true);
11✔
982
        editor.move_cursor(&AKey::Left, true);
11✔
983
        editor.process_keypress(&Key::Delete);
11✔
984
        assert_row_chars_equal(&editor, &[b"Hello world!Happy New ear!"]);
11✔
985
    }
11✔
986

987
    #[test]
988
    fn editor_move_cursor_left() {
11✔
989
        let mut editor = Editor::default();
11✔
990
        for &b in b"Hello world!\nHappy New Year!" {
308✔
991
            editor.process_keypress(&Key::Char(b));
308✔
992
        }
308✔
993

994
        // check current position
995
        assert_eq!(editor.cursor.x, 15);
11✔
996
        assert_eq!(editor.cursor.y, 1);
11✔
997

998
        editor.move_cursor(&AKey::Left, true);
11✔
999
        assert_eq!(editor.cursor.x, 10);
11✔
1000
        assert_eq!(editor.cursor.y, 1);
11✔
1001

1002
        editor.move_cursor(&AKey::Left, false);
11✔
1003
        assert_eq!(editor.cursor.x, 9);
11✔
1004
        assert_eq!(editor.cursor.y, 1);
11✔
1005

1006
        editor.move_cursor(&AKey::Left, true);
11✔
1007
        assert_eq!(editor.cursor.x, 6);
11✔
1008
        assert_eq!(editor.cursor.y, 1);
11✔
1009

1010
        editor.move_cursor(&AKey::Left, true);
11✔
1011
        assert_eq!(editor.cursor.x, 0);
11✔
1012
        assert_eq!(editor.cursor.y, 1);
11✔
1013

1014
        editor.move_cursor(&AKey::Left, false);
11✔
1015
        assert_eq!(editor.cursor.x, 12);
11✔
1016
        assert_eq!(editor.cursor.y, 0);
11✔
1017

1018
        editor.move_cursor(&AKey::Left, true);
11✔
1019
        assert_eq!(editor.cursor.x, 6);
11✔
1020
        assert_eq!(editor.cursor.y, 0);
11✔
1021

1022
        editor.move_cursor(&AKey::Left, true);
11✔
1023
        assert_eq!(editor.cursor.x, 0);
11✔
1024
        assert_eq!(editor.cursor.y, 0);
11✔
1025

1026
        editor.move_cursor(&AKey::Left, false);
11✔
1027
        assert_eq!(editor.cursor.x, 0);
11✔
1028
        assert_eq!(editor.cursor.y, 0);
11✔
1029
    }
11✔
1030

1031
    #[test]
1032
    fn editor_move_cursor_up() {
11✔
1033
        let mut editor = Editor::default();
11✔
1034
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
308✔
1035
            editor.process_keypress(&Key::Char(b));
308✔
1036
        }
308✔
1037

1038
        // check current position
1039
        assert_eq!(editor.cursor.x, 16);
11✔
1040
        assert_eq!(editor.cursor.y, 2);
11✔
1041

1042
        editor.move_cursor(&AKey::Up, false);
11✔
1043
        assert_eq!(editor.cursor.x, 2);
11✔
1044
        assert_eq!(editor.cursor.y, 1);
11✔
1045

1046
        editor.move_cursor(&AKey::Up, true);
11✔
1047
        assert_eq!(editor.cursor.x, 2);
11✔
1048
        assert_eq!(editor.cursor.y, 0);
11✔
1049

1050
        editor.move_cursor(&AKey::Up, false);
11✔
1051
        assert_eq!(editor.cursor.x, 2);
11✔
1052
        assert_eq!(editor.cursor.y, 0);
11✔
1053
    }
11✔
1054

1055
    #[test]
1056
    fn editor_move_cursor_right() {
11✔
1057
        let mut editor = Editor::default();
11✔
1058
        for &b in b"Hello world\nHappy New Year" {
286✔
1059
            editor.process_keypress(&Key::Char(b));
286✔
1060
        }
286✔
1061

1062
        // check current position
1063
        assert_eq!(editor.cursor.x, 14);
11✔
1064
        assert_eq!(editor.cursor.y, 1);
11✔
1065

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

1070
        editor.move_cursor(&AKey::Right, false);
11✔
1071
        assert_eq!(editor.cursor.x, 0);
11✔
1072
        assert_eq!(editor.cursor.y, 2);
11✔
1073

1074
        editor.move_cursor(&AKey::Up, true);
11✔
1075
        editor.move_cursor(&AKey::Up, true);
11✔
1076
        assert_eq!(editor.cursor.x, 0);
11✔
1077
        assert_eq!(editor.cursor.y, 0);
11✔
1078

1079
        editor.move_cursor(&AKey::Right, true);
11✔
1080
        assert_eq!(editor.cursor.x, 5);
11✔
1081
        assert_eq!(editor.cursor.y, 0);
11✔
1082

1083
        editor.move_cursor(&AKey::Right, true);
11✔
1084
        assert_eq!(editor.cursor.x, 11);
11✔
1085
        assert_eq!(editor.cursor.y, 0);
11✔
1086

1087
        editor.move_cursor(&AKey::Right, false);
11✔
1088
        assert_eq!(editor.cursor.x, 0);
11✔
1089
        assert_eq!(editor.cursor.y, 1);
11✔
1090
    }
11✔
1091

1092
    #[test]
1093
    fn editor_move_cursor_down() {
11✔
1094
        let mut editor = Editor::default();
11✔
1095
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
308✔
1096
            editor.process_keypress(&Key::Char(b));
308✔
1097
        }
308✔
1098

1099
        // check current position
1100
        assert_eq!(editor.cursor.x, 16);
11✔
1101
        assert_eq!(editor.cursor.y, 2);
11✔
1102

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

1107
        editor.move_cursor(&AKey::Up, false);
11✔
1108
        editor.move_cursor(&AKey::Up, false);
11✔
1109
        editor.move_cursor(&AKey::Up, false);
11✔
1110

1111
        assert_eq!(editor.cursor.x, 0);
11✔
1112
        assert_eq!(editor.cursor.y, 0);
11✔
1113

1114
        editor.move_cursor(&AKey::Right, true);
11✔
1115
        assert_eq!(editor.cursor.x, 8);
11✔
1116
        assert_eq!(editor.cursor.y, 0);
11✔
1117

1118
        editor.move_cursor(&AKey::Down, true);
11✔
1119
        assert_eq!(editor.cursor.x, 2);
11✔
1120
        assert_eq!(editor.cursor.y, 1);
11✔
1121

1122
        editor.move_cursor(&AKey::Down, true);
11✔
1123
        assert_eq!(editor.cursor.x, 2);
11✔
1124
        assert_eq!(editor.cursor.y, 2);
11✔
1125

1126
        editor.move_cursor(&AKey::Down, true);
11✔
1127
        assert_eq!(editor.cursor.x, 0);
11✔
1128
        assert_eq!(editor.cursor.y, 3);
11✔
1129

1130
        editor.move_cursor(&AKey::Down, false);
11✔
1131
        assert_eq!(editor.cursor.x, 0);
11✔
1132
        assert_eq!(editor.cursor.y, 3);
11✔
1133
    }
11✔
1134

1135
    #[test]
1136
    fn editor_press_home_key() {
11✔
1137
        let mut editor = Editor::default();
11✔
1138
        for &b in b"Hello\nWorld\nand\nFerris!" {
253✔
1139
            editor.process_keypress(&Key::Char(b));
253✔
1140
        }
253✔
1141

1142
        // check current position
1143
        assert_eq!(editor.cursor.x, 7);
11✔
1144
        assert_eq!(editor.cursor.y, 3);
11✔
1145

1146
        editor.process_keypress(&Key::Home);
11✔
1147
        assert_eq!(editor.cursor.x, 0);
11✔
1148
        assert_eq!(editor.cursor.y, 3);
11✔
1149

1150
        editor.move_cursor(&AKey::Up, false);
11✔
1151
        editor.move_cursor(&AKey::Up, false);
11✔
1152
        editor.move_cursor(&AKey::Up, false);
11✔
1153

1154
        assert_eq!(editor.cursor.x, 0);
11✔
1155
        assert_eq!(editor.cursor.y, 0);
11✔
1156

1157
        editor.move_cursor(&AKey::Right, true);
11✔
1158
        assert_eq!(editor.cursor.x, 5);
11✔
1159
        assert_eq!(editor.cursor.y, 0);
11✔
1160

1161
        editor.process_keypress(&Key::Home);
11✔
1162
        assert_eq!(editor.cursor.x, 0);
11✔
1163
        assert_eq!(editor.cursor.y, 0);
11✔
1164
    }
11✔
1165

1166
    #[test]
1167
    fn editor_press_end_key() {
11✔
1168
        let mut editor = Editor::default();
11✔
1169
        for &b in b"Hello\nWorld\nand\nFerris!" {
253✔
1170
            editor.process_keypress(&Key::Char(b));
253✔
1171
        }
253✔
1172

1173
        // check current position
1174
        assert_eq!(editor.cursor.x, 7);
11✔
1175
        assert_eq!(editor.cursor.y, 3);
11✔
1176

1177
        editor.process_keypress(&Key::End);
11✔
1178
        assert_eq!(editor.cursor.x, 7);
11✔
1179
        assert_eq!(editor.cursor.y, 3);
11✔
1180

1181
        editor.move_cursor(&AKey::Up, false);
11✔
1182
        editor.move_cursor(&AKey::Up, false);
11✔
1183
        editor.move_cursor(&AKey::Up, false);
11✔
1184

1185
        assert_eq!(editor.cursor.x, 3);
11✔
1186
        assert_eq!(editor.cursor.y, 0);
11✔
1187

1188
        editor.process_keypress(&Key::End);
11✔
1189
        assert_eq!(editor.cursor.x, 5);
11✔
1190
        assert_eq!(editor.cursor.y, 0);
11✔
1191
    }
11✔
1192

1193
    #[test]
1194
    fn editor_page_up_moves_cursor_to_viewport_top() {
11✔
1195
        let mut editor = Editor { screen_rows: 4, ..Default::default() };
11✔
1196
        for _ in 0..10 {
110✔
1197
            editor.insert_new_line();
110✔
1198
        }
110✔
1199

1200
        (editor.cursor.y, editor.cursor.x) = (3, 0);
11✔
1201
        editor.insert_byte(b'a');
11✔
1202
        editor.insert_byte(b'b');
11✔
1203

1204
        (editor.cursor.y, editor.cursor.x, editor.cursor.roff) = (9, 5, 7);
11✔
1205
        let (should_quit, prompt_mode) = editor.process_keypress(&Key::PageUp);
11✔
1206

1207
        assert!(!should_quit);
11✔
1208
        assert!(prompt_mode.is_none());
11✔
1209
        assert_eq!(editor.cursor.y, 3);
11✔
1210
        assert_eq!(editor.cursor.x, 2);
11✔
1211
    }
11✔
1212

1213
    #[test]
1214
    fn editor_page_down_moves_cursor_to_viewport_bottom() {
11✔
1215
        let mut editor = Editor { screen_rows: 4, ..Default::default() };
11✔
1216
        for _ in 0..12 {
132✔
1217
            editor.insert_new_line();
132✔
1218
        }
132✔
1219

1220
        (editor.cursor.y, editor.cursor.x) = (11, 0);
11✔
1221
        editor.insert_byte(b'x');
11✔
1222
        editor.insert_byte(b'y');
11✔
1223
        editor.insert_byte(b'z');
11✔
1224

1225
        (editor.cursor.x, editor.cursor.roff) = (6, 4);
11✔
1226
        let (should_quit, prompt_mode) = editor.process_keypress(&Key::PageDown);
11✔
1227
        assert!(!should_quit);
11✔
1228
        assert!(prompt_mode.is_none());
11✔
1229
        assert_eq!(editor.cursor.y, 11);
11✔
1230
        assert_eq!(editor.cursor.x, 3);
11✔
1231

1232
        (editor.cursor.x, editor.cursor.roff) = (9, 11);
11✔
1233
        let (should_quit, prompt_mode_again) = editor.process_keypress(&Key::PageDown);
11✔
1234
        assert!(!should_quit);
11✔
1235
        assert!(prompt_mode_again.is_none());
11✔
1236
        assert_eq!(editor.cursor.y, editor.rows.len());
11✔
1237
        assert_eq!(editor.cursor.x, 0);
11✔
1238
    }
11✔
1239

1240
    #[rstest]
1241
    #[case::beginning_of_first_row(b"Hello\nWorld!\n", (0, 0), &[&b"World!"[..], &b""[..]], 0)]
1242
    #[case::middle_of_first_row(b"Hello\nWorld!\n", (3, 0), &[&b"World!"[..], &b""[..]], 0)]
1243
    #[case::end_of_first_row(b"Hello\nWorld!\n", (5, 0), &[&b"World!"[..], &b""[..]], 0)]
1244
    #[case::empty_first_row(b"\nHello", (0, 0), &[&b"Hello"[..]], 0)]
1245
    #[case::beginning_of_only_row(b"Hello", (0, 0), &[&b""[..]], 0)]
1246
    #[case::middle_of_only_row(b"Hello", (3, 0), &[&b""[..]], 0)]
1247
    #[case::end_of_only_row(b"Hello", (5, 0), &[&b""[..]], 0)]
1248
    #[case::beginning_of_middle_row(b"Hello\nWorld!\n", (0, 1), &[&b"Hello"[..], &b""[..]], 1)]
1249
    #[case::middle_of_middle_row(b"Hello\nWorld!\n", (3, 1), &[&b"Hello"[..], &b""[..]], 1)]
1250
    #[case::end_of_middle_row(b"Hello\nWorld!\n", (6, 1), &[&b"Hello"[..], &b""[..]], 1)]
1251
    #[case::empty_middle_row(b"Hello\n\nWorld!", (0, 1), &[&b"Hello"[..], &b"World!"[..]], 1)]
1252
    #[case::beginning_of_last_row(b"Hello\nWorld!", (0, 1), &[&b"Hello"[..]], 0)]
1253
    #[case::middle_of_last_row(b"Hello\nWorld!", (3, 1), &[&b"Hello"[..]], 0)]
1254
    #[case::end_of_last_row(b"Hello\nWorld!", (6, 1), &[&b"Hello"[..]], 0)]
1255
    #[case::empty_last_row(b"Hello\n", (0, 1), &[&b"Hello"[..]], 0)]
1256
    #[case::after_last_row(b"Hello\nWorld!", (0, 2), &[&b"Hello"[..], &b"World!"[..]], 2)]
1257
    fn delete_current_row_updates_buffer_and_position(
1258
        #[case] initial_buffer: &[u8], #[case] cursor_position: (usize, usize),
1259
        #[case] expected_rows: &[&[u8]], #[case] expected_cursor_row: usize,
1260
    ) {
1261
        let mut editor = Editor::default();
1262
        for &b in initial_buffer {
1263
            editor.process_keypress(&Key::Char(b));
1264
        }
1265
        (editor.cursor.x, editor.cursor.y) = cursor_position;
1266

1267
        editor.delete_current_row();
1268

1269
        assert_row_chars_equal(&editor, expected_rows);
1270
        assert_eq!(
1271
            (editor.cursor.x, editor.cursor.y),
1272
            (0, expected_cursor_row),
1273
            "cursor is at {}:{}, expected {}:0",
1274
            editor.cursor.y,
1275
            editor.cursor.x,
1276
            expected_cursor_row
1277
        );
1278
    }
1279

1280
    #[rstest]
1281
    #[case::first_row(0)]
1282
    #[case::middle_row(5)]
1283
    #[case::last_row(9)]
1284
    fn delete_current_row_updates_screen_cols_and_ln_pad(#[case] current_row: usize) {
1285
        let mut editor = Editor { window_width: 100, ..Default::default() };
1286
        for _ in 0..10 {
1287
            editor.insert_new_line();
1288
        }
1289
        assert_eq!(editor.screen_cols, 96);
1290
        assert_eq!(editor.ln_pad, 4);
1291

1292
        editor.cursor.y = current_row;
1293
        editor.delete_current_row();
1294

1295
        assert_eq!(editor.screen_cols, 97);
1296
        assert_eq!(editor.ln_pad, 3);
1297
    }
1298

1299
    #[test]
1300
    fn delete_current_row_updates_syntax_highlighting() {
11✔
1301
        let mut editor = Editor {
11✔
1302
            syntax: SyntaxConf {
11✔
1303
                ml_comment_delims: Some(("/*".to_owned(), "*/".to_owned())),
11✔
1304
                ..Default::default()
11✔
1305
            },
11✔
1306
            ..Default::default()
11✔
1307
        };
11✔
1308
        for &b in b"A\nb/*c\nd\ne\nf*/g\nh" {
187✔
1309
            editor.process_keypress(&Key::Char(b));
187✔
1310
        }
187✔
1311

1312
        assert_row_chars_equal(&editor, &[b"A", b"b/*c", b"d", b"e", b"f*/g", b"h"]);
11✔
1313
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1314
            &[HlType::Normal],
11✔
1315
            &[HlType::Normal, HlType::MlComment, HlType::MlComment, HlType::MlComment],
11✔
1316
            &[HlType::MlComment],
11✔
1317
            &[HlType::MlComment],
11✔
1318
            &[HlType::MlComment, HlType::MlComment, HlType::MlComment, HlType::Normal],
11✔
1319
            &[HlType::Normal],
11✔
1320
        ]);
11✔
1321

1322
        (editor.cursor.x, editor.cursor.y) = (0, 4);
11✔
1323
        editor.delete_current_row();
11✔
1324

1325
        assert_row_chars_equal(&editor, &[b"A", b"b/*c", b"d", b"e", b"h"]);
11✔
1326
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1327
            &[HlType::Normal],
11✔
1328
            &[HlType::Normal, HlType::MlComment, HlType::MlComment, HlType::MlComment],
11✔
1329
            &[HlType::MlComment],
11✔
1330
            &[HlType::MlComment],
11✔
1331
            &[HlType::MlComment],
11✔
1332
        ]);
11✔
1333

1334
        (editor.cursor.x, editor.cursor.y) = (0, 1);
11✔
1335
        editor.delete_current_row();
11✔
1336

1337
        assert_row_chars_equal(&editor, &[b"A", b"d", b"e", b"h"]);
11✔
1338
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1339
            &[HlType::Normal],
11✔
1340
            &[HlType::Normal],
11✔
1341
            &[HlType::Normal],
11✔
1342
            &[HlType::Normal],
11✔
1343
        ]);
11✔
1344
    }
11✔
1345

1346
    #[test]
1347
    fn loop_until_keypress() -> Result<(), Error> {
11✔
1348
        let mut editor = Editor::default();
11✔
1349
        let mut fake_stdin = Cursor::new(
11✔
1350
            b"abc\x1b[A\x1b[B\x1b[C\x1b[D\x1b[H\x1bOH\x1b[F\x1bOF\x1b[1;5C\x1b[5C\x1b[99",
1351
        );
1352
        for expected_key in [
154✔
1353
            Key::Char(b'a'),
11✔
1354
            Key::Char(b'b'),
11✔
1355
            Key::Char(b'c'),
11✔
1356
            Key::Arrow(AKey::Up),
11✔
1357
            Key::Arrow(AKey::Down),
11✔
1358
            Key::Arrow(AKey::Right),
11✔
1359
            Key::Arrow(AKey::Left),
11✔
1360
            Key::Home,
11✔
1361
            Key::Home,
11✔
1362
            Key::End,
11✔
1363
            Key::End,
11✔
1364
            Key::CtrlArrow(AKey::Right),
11✔
1365
            Key::CtrlArrow(AKey::Right),
11✔
1366
            Key::Escape,
11✔
1367
        ] {
11✔
1368
            assert_eq!(editor.loop_until_keypress(&mut fake_stdin)?, expected_key);
154✔
1369
        }
1370
        Ok(())
11✔
1371
    }
11✔
1372

1373
    #[rstest]
1374
    #[case::ascii_completed(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(b'\r')], &PromptState::Completed(String::from("Hi")))]
1375
    #[case::escape(&[Key::Char(b'H'), Key::Char(b'i'), Key::Escape], &PromptState::Cancelled)]
1376
    #[case::exit(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(EXIT)], &PromptState::Cancelled)]
1377
    #[case::skip_ascii_control(&[Key::Char(b'\x0A')], &PromptState::Active(String::new()))]
1378
    #[case::unsupported_non_ascii(&[Key::Char(b'\xEF')], &PromptState::Active(String::new()))]
1379
    #[case::backspace(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], &PromptState::Active(String::new()))]
1380
    #[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()))]
1381
    fn process_prompt_keypresses(#[case] keys: &[Key], #[case] expected_final_state: &PromptState) {
1382
        let mut prompt_state = PromptState::Active(String::new());
1383
        for key in keys {
1384
            if let PromptState::Active(buffer) = prompt_state {
1385
                prompt_state = process_prompt_keypress(buffer, key);
1386
            } else {
1387
                panic!("Prompt state: {prompt_state:?} is not active")
1388
            }
1389
        }
1390
        assert_eq!(prompt_state, *expected_final_state);
1391
    }
1392

1393
    #[rstest]
1394
    #[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")]
1395
    #[case(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], "")]
1396
    fn process_find_keypress_completed(#[case] keys: &[Key], #[case] expected_final_value: &str) {
1397
        let mut ed: Editor = Editor::default();
1398
        ed.insert_new_line();
1399
        let mut prompt_mode = Some(PromptMode::Find(String::new(), CursorState::default(), None));
1400
        for key in keys {
1401
            prompt_mode = prompt_mode
1402
                .take()
1403
                .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, key));
132✔
1404
        }
1405
        assert_eq!(
1406
            prompt_mode,
1407
            Some(PromptMode::Find(
1408
                String::from(expected_final_value),
1409
                CursorState::default(),
1410
                None
1411
            ))
1412
        );
1413
        prompt_mode = prompt_mode
1414
            .take()
1415
            .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, &Key::Char(b'\r')));
22✔
1416
        assert_eq!(prompt_mode, None);
1417
    }
1418

1419
    #[rstest]
1420
    #[case(100, true, 12345, "\u{1b}[38;5;240m12345 │\u{1b}[m")]
1421
    #[case(100, true, "~", "\u{1b}[38;5;240m~ │\u{1b}[m")]
1422
    #[case(10, true, 12345, "")]
1423
    #[case(10, true, "~", "")]
1424
    #[case(100, false, 12345, "12345 │")]
1425
    #[case(100, false, "~", "~ │")]
1426
    #[case(10, false, 12345, "")]
1427
    #[case(10, false, "~", "")]
1428
    fn draw_left_padding<T: Display>(
1429
        #[case] window_width: usize, #[case] use_color: bool, #[case] value: T,
1430
        #[case] expected: &'static str,
1431
    ) {
1432
        let mut editor = Editor { window_width, use_color, ..Default::default() };
1433
        editor.update_screen_cols();
1434

1435
        let mut buffer = String::new();
1436
        editor.draw_left_padding(&mut buffer, value);
1437
        assert_eq!(buffer, expected);
1438
    }
1439
}
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