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

ilai-deutel / kibi / 21543479100

31 Jan 2026 11:02AM UTC coverage: 69.562% (+1.3%) from 68.233%
21543479100

Pull #416

github

web-flow
Merge b5f4c1f82 into 2685b408a
Pull Request #416: Add Ctrl+/ comment toggle functionality

51 of 52 new or added lines in 4 files covered. (98.08%)

1 existing line in 1 file now uncovered.

889 of 1278 relevant lines covered (69.56%)

1074.34 hits per line

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

68.51
/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 as scsr};
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 TOGGLE_COMMENT: u8 = 31;
23
const BACKSPACE: u8 = 127;
24

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

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

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

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

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

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

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

81
/// The `Editor` struct, contains the state and configuration of the text
82
/// editor.
83
#[derive(Default)]
84
pub struct Editor {
85
    /// If not `None`, the current prompt mode (`Save`, `Find`, `GoTo`, or
86
    /// `Execute`). If `None`, we are in regular edition mode.
87
    prompt_mode: Option<PromptMode>,
88
    /// The current state of the cursor.
89
    cursor: CursorState,
90
    /// The padding size used on the left for line numbering.
91
    ln_pad: usize,
92
    /// The width of the current window. Will be updated when the window is
93
    /// resized.
94
    window_width: usize,
95
    /// The number of rows that can be used for the editor, excluding the status
96
    /// bar and the message bar
97
    screen_rows: usize,
98
    /// The number of columns that can be used for the editor, excluding the
99
    /// part used for line numbers
100
    screen_cols: usize,
101
    /// The collection of rows, including the content and the syntax
102
    /// highlighting information.
103
    rows: Vec<Row>,
104
    /// Whether the document has been modified since it was open.
105
    dirty: bool,
106
    /// The configuration for the editor.
107
    config: Config,
108
    /// The number of consecutive times the user has tried to quit without
109
    /// saving. After `config.quit_times`, the program will exit.
110
    quit_times: usize,
111
    /// The file name. If None, the user will be prompted for a file name the
112
    /// first time they try to save.
113
    // TODO: It may be better to store a PathBuf instead
114
    file_name: Option<String>,
115
    /// The current status message being shown.
116
    status_msg: Option<StatusMessage>,
117
    /// The syntax configuration corresponding to the current file's extension.
118
    syntax: SyntaxConf,
119
    /// The number of bytes contained in `rows`. This excludes new lines.
120
    n_bytes: u64,
121
    /// The copied buffer of a row
122
    copied_row: Vec<u8>,
123
    /// Whether to use ANSI color escape codes for rendering
124
    use_color: bool,
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.
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✔
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,111✔
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).
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) {
594✔
216
        self.cursor.x = self.cursor.x.min(self.current_row().map_or(0, |row| row.chars.len()));
594✔
217
    }
594✔
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✔
229
                self.update_window_size()?;
×
230
                self.refresh_screen()?;
×
231
            }
154✔
232
            // Match on the next byte received or, if the first byte is <ESC> ('\x1b'), on
233
            // the next few bytes.
234
            if let Some(a) = bytes.next().transpose()? {
154✔
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,
×
253
                                (Some(c), Some(b'~')) if c == b'4' || c == b'8' => Key::End,
×
254
                                (Some(b'3'), Some(b'~')) => Key::Delete,
×
255
                                (Some(b'5'), Some(b'~')) => Key::PageUp,
×
256
                                (Some(b'6'), Some(b'~')) => Key::PageDown,
×
257
                                (Some(b'5'), Some(d @ b'A'..=b'D')) => Key::CtrlArrow(get_akey(d)),
22✔
258
                                _ => Key::Escape,
×
259
                            }
260
                        }
261
                        (b'O', Some(c @ b'a'..=b'd')) => Key::CtrlArrow(get_akey(c)),
×
262
                        _ => Key::Escape,
11✔
263
                    },
264
                    _ => Key::Escape,
×
265
                });
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
275
        (self.screen_rows, self.window_width) = (wsize.0.saturating_sub(2), wsize.1);
×
276
        self.update_screen_cols();
×
277
        Ok(())
×
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) {
1,650✔
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 = scsr(Some(self.rows.len()), |u| Some(u / 10).filter(|u| *u > 0)).count();
1,727✔
288
        let show_line_num = self.config.show_line_num && n_digits + 2 < self.window_width / 4;
1,650✔
289
        self.ln_pad = if show_line_num { n_digits + 2 } else { 0 };
1,650✔
290
        self.screen_cols = self.window_width.saturating_sub(self.ln_pad);
1,650✔
291
    }
1,650✔
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) {
6,314✔
297
        let mut hl_state = if y > 0 { self.rows[y - 1].hl_state } else { HlState::Normal };
6,314✔
298
        for row in self.rows.iter_mut().skip(y) {
6,314✔
299
            let previous_hl_state = row.hl_state;
6,193✔
300
            hl_state = row.update(&self.syntax, hl_state, self.config.tab_stop);
6,193✔
301
            if ignore_following_rows || hl_state == previous_hl_state {
6,193✔
302
                return;
6,116✔
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
    }
6,314✔
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) {
4,334✔
321
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
4,334✔
322
            row.chars.insert(self.cursor.x, c);
4,037✔
323
        } else {
4,037✔
324
            self.rows.push(Row::new(vec![c]));
297✔
325
            // The number of rows has changed. The left padding may need to be updated.
297✔
326
            self.update_screen_cols();
297✔
327
        }
297✔
328
        self.update_row(self.cursor.y, false);
4,334✔
329
        (self.cursor.x, self.n_bytes, self.dirty) = (self.cursor.x + 1, self.n_bytes + 1, true);
4,334✔
330
    }
4,334✔
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,067✔
336
        let (position, new_row_chars) = if self.cursor.x == 0 {
1,067✔
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);
418✔
342
            self.update_row(self.cursor.y, false);
418✔
343
            (self.cursor.y + 1, new_chars)
418✔
344
        };
345
        self.rows.insert(position, Row::new(new_row_chars));
1,067✔
346
        self.update_row(position, false);
1,067✔
347
        self.update_screen_cols();
1,067✔
348
        self.cursor.move_to_next_line();
1,067✔
349
        self.dirty = true;
1,067✔
350
    }
1,067✔
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
    /// Toggle comment on the current line using the appropriate comment symbol
418
    /// from the syntax configuration. If the line is already commented,
419
    /// uncomment it. If not, add a comment symbol at the beginning.
420
    fn toggle_comment(&mut self) {
66✔
421
        // Get the first single-line comment start symbol from syntax config
422
        let Some(sym) = self.syntax.sl_comment_start.first() else { return };
66✔
423
        let Some(row) = self.rows.get_mut(self.cursor.y) else { return };
66✔
424
        // Find the first non-whitespace character position
425
        let pos = row.chars.iter().position(|&c| !(c as char).is_whitespace()).unwrap_or(0);
154✔
426

427
        // Check if the line is already commented
428
        let n_update = if row.chars.get(pos..pos + sym.len()) == Some(sym.as_bytes()) {
66✔
429
            let to_remove = sym.len() + usize::from(row.chars.get(pos + sym.len()) == Some(&b' '));
33✔
430
            // Remove the comment and return the removed size as a negative integer
431
            0isize.saturating_sub_unsigned(row.chars.drain(pos..pos + to_remove).len())
33✔
432
        } else {
433
            // Insert comment at the first non-whitespace position
434
            row.chars.splice(pos..pos, iter::chain(sym.bytes(), iter::once(b' ')));
33✔
435
            1isize.saturating_add_unsigned(sym.len())
33✔
436
        };
437
        self.n_bytes = self.n_bytes.saturating_add_signed(n_update as i64);
66✔
438
        if self.cursor.x >= pos {
66✔
439
            self.cursor.x = self.cursor.x.saturating_add_signed(n_update);
44✔
440
        }
44✔
441

442
        self.update_row(self.cursor.y, false);
66✔
443
        // Update cursor position to ensure it's valid after row update
444
        self.update_cursor_x_position();
66✔
445
        self.dirty = true;
66✔
446
    }
66✔
447

448
    /// Try to load a file. If found, load the rows and update the render and
449
    /// syntax highlighting. If not found, do not return an error.
450
    fn load(&mut self, path: &Path) -> Result<(), Error> {
×
451
        let mut file = match File::open(path) {
×
452
            Err(e) if e.kind() == ErrorKind::NotFound => {
×
453
                self.rows.push(Row::new(Vec::new()));
×
454
                return Ok(());
×
455
            }
456
            r => r,
×
457
        }?;
×
458
        let ft = file.metadata()?.file_type();
×
459
        if !(ft.is_file() || ft.is_symlink()) {
×
460
            return Err(io::Error::new(ErrorKind::InvalidInput, "Invalid input file type").into());
×
461
        }
×
462
        for line in BufReader::new(&file).split(b'\n') {
×
463
            self.rows.push(Row::new(line?));
×
464
        }
465
        // If the file ends with an empty line or is empty, we need to append an empty
466
        // row to `self.rows`. Unfortunately, BufReader::split doesn't yield an
467
        // empty Vec in this case, so we need to check the last byte directly.
468
        file.seek(io::SeekFrom::End(0))?;
×
469
        #[expect(clippy::unbuffered_bytes)]
470
        if file.bytes().next().transpose()?.is_none_or(|b| b == b'\n') {
×
471
            self.rows.push(Row::new(Vec::new()));
×
472
        }
×
473
        self.update_all_rows();
×
474
        // The number of rows has changed. The left padding may need to be updated.
475
        self.update_screen_cols();
×
476
        self.n_bytes = self.rows.iter().map(|row| row.chars.len() as u64).sum();
×
477
        Ok(())
×
478
    }
×
479

480
    /// Save the text to a file, given its name.
481
    fn save(&self, file_name: &str) -> Result<usize, io::Error> {
×
482
        let mut file = File::create(file_name)?;
×
483
        let mut written = 0;
×
484
        for (i, row) in self.rows.iter().enumerate() {
×
485
            file.write_all(&row.chars)?;
×
486
            written += row.chars.len();
×
487
            if i != (self.rows.len() - 1) {
×
488
                file.write_all(b"\n")?;
×
489
                written += 1;
×
490
            }
×
491
        }
492
        file.sync_all()?;
×
493
        Ok(written)
×
494
    }
×
495

496
    /// Save the text to a file and handle all errors. Errors and success
497
    /// messages will be printed to the status bar. Return whether the file
498
    /// was successfully saved.
499
    fn save_and_handle_io_errors(&mut self, file_name: &str) -> bool {
×
500
        let saved = self.save(file_name);
×
501
        // Print error or success message to the status bar
502
        match saved.as_ref() {
×
503
            Ok(w) => set_status!(self, "{} written to {}", format_size(*w as u64), file_name),
×
504
            Err(err) => set_status!(self, "Can't save! I/O error: {err}"),
×
505
        }
506
        // If save was successful, set dirty to false.
507
        self.dirty &= saved.is_err();
×
508
        saved.is_ok()
×
509
    }
×
510

511
    /// Save to a file after obtaining the file path from the prompt. If
512
    /// successful, the `file_name` attribute of the editor will be set and
513
    /// syntax highlighting will be updated.
514
    fn save_as(&mut self, file_name: String) {
×
515
        if self.save_and_handle_io_errors(&file_name) {
×
516
            // If save was successful
×
517
            self.syntax = SyntaxConf::find(&file_name, &sys::data_dirs());
×
518
            self.file_name = Some(file_name);
×
519
            self.update_all_rows();
×
520
        }
×
521
    }
×
522

523
    /// Draw the left part of the screen: line numbers and vertical bar.
524
    fn draw_left_padding<T: Display>(&self, buffer: &mut String, val: T) {
88✔
525
        if self.ln_pad >= 2 {
88✔
526
            // \u{2502}: pipe "│"
44✔
527
            let s = format!("{:>1$} \u{2502}", val, self.ln_pad - 2);
44✔
528
            // \x1b[38;5;240m: Dark grey color
44✔
529
            push_colored(buffer, "\x1b[38;5;240m", &s, self.use_color);
44✔
530
        }
44✔
531
    }
88✔
532

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

538
    /// Draw rows of text and empty rows on the terminal, by adding characters
539
    /// to the buffer.
540
    fn draw_rows(&self, buffer: &mut String) -> Result<(), Error> {
×
541
        let row_it = self.rows.iter().map(Some).chain(repeat(None)).enumerate();
×
542
        for (i, row) in row_it.skip(self.cursor.roff).take(self.screen_rows) {
×
543
            buffer.push_str(CLEAR_LINE_RIGHT_OF_CURSOR);
×
544
            if let Some(row) = row {
×
545
                // Draw a row of text
×
546
                self.draw_left_padding(buffer, i + 1);
×
547
                row.draw(self.cursor.coff, self.screen_cols, buffer, self.use_color);
×
548
            } else {
×
549
                // Draw an empty row
550
                self.draw_left_padding(buffer, '~');
×
551
                if self.is_empty() && i == self.screen_rows / 3 {
×
552
                    write!(buffer, "{:^1$.1$}", WELCOME_MESSAGE, self.screen_cols)?;
×
553
                }
×
554
            }
555
            buffer.push_str("\r\n");
×
556
        }
557
        Ok(())
×
558
    }
×
559

560
    /// Draw the status bar on the terminal, by adding characters to the buffer.
561
    fn draw_status_bar(&self, buffer: &mut String) {
×
562
        // Left part of the status bar
563
        let modified = if self.dirty { " (modified)" } else { "" };
×
564
        let mut left =
×
565
            format!("{:.30}{modified}", self.file_name.as_deref().unwrap_or("[No Name]"));
×
566
        left.truncate(self.window_width);
×
567

568
        // Right part of the status bar
569
        let size = format_size(self.n_bytes + self.rows.len().saturating_sub(1) as u64);
×
570
        let right =
×
571
            format!("{} | {size} | {}:{}", self.syntax.name, self.cursor.y + 1, self.rx() + 1);
×
572

573
        // Draw
574
        let rw = self.window_width.saturating_sub(left.len());
×
575
        push_colored(buffer, WBG, &format!("{left}{right:>rw$.rw$}\r\n"), self.use_color);
×
576
    }
×
577

578
    /// Draw the message bar on the terminal, by adding characters to the
579
    /// buffer.
580
    fn draw_message_bar(&self, buffer: &mut String) {
×
581
        buffer.push_str(CLEAR_LINE_RIGHT_OF_CURSOR);
×
582
        let msg_duration = self.config.message_dur;
×
583
        if let Some(sm) = self.status_msg.as_ref().filter(|sm| sm.time.elapsed() < msg_duration) {
×
584
            buffer.push_str(&sm.msg[..sm.msg.len().min(self.window_width)]);
×
585
        }
×
586
    }
×
587

588
    /// Refresh the screen: update the offsets, draw the rows, the status bar,
589
    /// the message bar, and move the cursor to the correct position.
590
    fn refresh_screen(&mut self) -> Result<(), Error> {
×
591
        self.cursor.scroll(self.rx(), self.screen_rows, self.screen_cols);
×
592
        let mut buffer = format!("{HIDE_CURSOR}{MOVE_CURSOR_TO_START}");
×
593
        self.draw_rows(&mut buffer)?;
×
594
        self.draw_status_bar(&mut buffer);
×
595
        self.draw_message_bar(&mut buffer);
×
596
        let (cursor_x, cursor_y) = if self.prompt_mode.is_none() {
×
597
            // If not in prompt mode, position the cursor according to the `cursor`
598
            // attributes.
599
            (self.rx() - self.cursor.coff + 1 + self.ln_pad, self.cursor.y - self.cursor.roff + 1)
×
600
        } else {
601
            // If in prompt mode, position the cursor on the prompt line at the end of the
602
            // line.
603
            (self.status_msg.as_ref().map_or(0, |sm| sm.msg.len() + 1), self.screen_rows + 2)
×
604
        };
605
        // Finally, print `buffer` and move the cursor
606
        print!("{buffer}\x1b[{cursor_y};{cursor_x}H{SHOW_CURSOR}");
×
607
        io::stdout().flush().map_err(Error::from)
×
608
    }
×
609

610
    /// Process a key that has been pressed, when not in prompt mode. Returns
611
    /// whether the program should exit, and optionally the prompt mode to
612
    /// switch to.
613
    fn process_keypress(&mut self, key: &Key) -> (bool, Option<PromptMode>) {
4,213✔
614
        // This won't be mutated, unless key is Key::Character(EXIT)
615
        let mut reset_quit_times = true;
4,213✔
616
        let mut prompt_mode = None;
4,213✔
617

618
        match key {
4,213✔
619
            Key::Arrow(arrow) => self.move_cursor(arrow, false),
×
620
            Key::CtrlArrow(arrow) => self.move_cursor(arrow, true),
×
621
            Key::PageUp => {
11✔
622
                self.cursor.y = self.cursor.roff.saturating_sub(self.screen_rows);
11✔
623
                self.update_cursor_x_position();
11✔
624
            }
11✔
625
            Key::PageDown => {
22✔
626
                self.cursor.y = (self.cursor.roff + 2 * self.screen_rows - 1).min(self.rows.len());
22✔
627
                self.update_cursor_x_position();
22✔
628
            }
22✔
629
            Key::Home => self.cursor.x = 0,
22✔
630
            Key::End => self.cursor.x = self.current_row().map_or(0, |row| row.chars.len()),
22✔
631
            Key::Char(b'\r' | b'\n') => self.insert_new_line(), // Enter
418✔
632
            Key::Char(BACKSPACE | DELETE_BIS) => self.delete_char(), // Backspace or Ctrl + H
×
633
            Key::Char(REMOVE_LINE) => self.delete_current_row(),
×
634
            Key::Delete => {
33✔
635
                self.move_cursor(&AKey::Right, false);
33✔
636
                self.delete_char();
33✔
637
            }
33✔
638
            Key::Escape | Key::Char(REFRESH_SCREEN) => (),
×
639
            Key::Char(EXIT) => {
640
                if !self.dirty || self.quit_times + 1 >= self.config.quit_times {
×
641
                    return (true, None);
×
642
                }
×
643
                let r = self.config.quit_times - self.quit_times - 1;
×
644
                set_status!(self, "Press Ctrl+Q {0} more time{1:.2$} to quit.", r, "s", r - 1);
×
645
                reset_quit_times = false;
×
646
            }
647
            Key::Char(SAVE) => match self.file_name.take() {
×
648
                // TODO: Can we avoid using take() then reassigning the value to file_name?
649
                Some(file_name) => {
×
650
                    self.save_and_handle_io_errors(&file_name);
×
651
                    self.file_name = Some(file_name);
×
652
                }
×
653
                None => prompt_mode = Some(PromptMode::Save(String::new())),
×
654
            },
655
            Key::Char(FIND) =>
656
                prompt_mode = Some(PromptMode::Find(String::new(), self.cursor.clone(), None)),
×
657
            Key::Char(GOTO) => prompt_mode = Some(PromptMode::GoTo(String::new())),
×
658
            Key::Char(DUPLICATE) => self.duplicate_current_row(),
×
659
            Key::Char(CUT) => {
×
660
                self.copy_current_row();
×
661
                self.delete_current_row();
×
662
            }
×
663
            Key::Char(COPY) => self.copy_current_row(),
×
664
            Key::Char(PASTE) => self.paste_current_row(),
×
665
            Key::Char(TOGGLE_COMMENT) => self.toggle_comment(),
66✔
UNCOV
666
            Key::Char(EXECUTE) => prompt_mode = Some(PromptMode::Execute(String::new())),
×
667
            Key::Char(c) => self.insert_byte(*c),
3,619✔
668
        }
669
        self.quit_times = if reset_quit_times { 0 } else { self.quit_times + 1 };
4,213✔
670
        (false, prompt_mode)
4,213✔
671
    }
4,213✔
672

673
    /// Try to find a query, this is called after pressing Ctrl-F and for each
674
    /// key that is pressed. `last_match` is the last row that was matched,
675
    /// `forward` indicates whether to search forward or backward. Returns
676
    /// the row of a new match, or `None` if the search was unsuccessful.
677
    fn find(&mut self, query: &str, last_match: Option<usize>, forward: bool) -> Option<usize> {
132✔
678
        // Number of rows to search
679
        let num_rows = if query.is_empty() { 0 } else { self.rows.len() };
132✔
680
        let mut current = last_match.unwrap_or_else(|| num_rows.saturating_sub(1));
132✔
681
        // TODO: Handle multiple matches per line
682
        for _ in 0..num_rows {
132✔
683
            current = (current + if forward { 1 } else { num_rows - 1 }) % num_rows;
110✔
684
            let row = &mut self.rows[current];
110✔
685
            if let Some(cx) = row.chars.windows(query.len()).position(|w| w == query.as_bytes()) {
110✔
686
                // self.cursor.coff: Try to reset the column offset; if the match is after the
687
                // offset, this will be updated in self.cursor.scroll() so that
688
                // the result is visible
689
                (self.cursor.x, self.cursor.y, self.cursor.coff) = (cx, current, 0);
×
690
                let rx = row.cx2rx[cx];
×
691
                row.match_segment = Some(rx..rx + query.len());
×
692
                return Some(current);
×
693
            }
110✔
694
        }
695
        None
132✔
696
    }
132✔
697

698
    /// If `file_name` is not None, load the file. Then run the text editor.
699
    ///
700
    /// # Errors
701
    ///
702
    /// Will Return `Err` if any error occur.
703
    pub fn run<I: BufRead>(&mut self, file_name: Option<&str>, input: &mut I) -> Result<(), Error> {
×
704
        self.update_window_size()?;
×
705
        set_status!(self, "{HELP_MESSAGE}");
×
706

707
        if let Some(path) = file_name.map(sys::path) {
×
708
            self.syntax = SyntaxConf::find(&path.to_string_lossy(), &sys::data_dirs());
×
709
            self.load(path.as_path())?;
×
710
            self.file_name = Some(path.to_string_lossy().to_string());
×
711
        } else {
×
712
            self.rows.push(Row::new(Vec::new()));
×
713
            self.file_name = None;
×
714
        }
×
715
        loop {
716
            if let Some(mode) = &self.prompt_mode {
×
717
                set_status!(self, "{}", mode.status_msg());
×
718
            }
×
719
            self.refresh_screen()?;
×
720
            let key = self.loop_until_keypress(input)?;
×
721
            // TODO: Can we avoid using take()?
722
            self.prompt_mode = match self.prompt_mode.take() {
×
723
                // process_keypress returns (should_quit, prompt_mode)
724
                None => match self.process_keypress(&key) {
×
725
                    (true, _) => return Ok(()),
×
726
                    (false, prompt_mode) => prompt_mode,
×
727
                },
728
                Some(prompt_mode) => prompt_mode.process_keypress(self, &key),
×
729
            }
730
        }
731
    }
×
732
}
733

734
/// Set up the terminal and run the text editor. If `file_name` is not None,
735
/// load the file.
736
///
737
/// Update the panic hook to restore the terminal on panic.
738
///
739
/// # Errors
740
///
741
/// Will Return `Err` if any error occur when registering the window size signal
742
/// handler, enabling raw mode, or running the editor.
743
pub fn run<I: BufRead>(file_name: Option<&str>, input: &mut I) -> Result<(), Error> {
120✔
744
    sys::register_winsize_change_signal_handler()?;
120✔
745
    let orig_term_mode = sys::enable_raw_mode()?;
120✔
746
    let mut editor = Editor { config: Config::load(), ..Default::default() };
×
747
    editor.use_color = !std::env::var("NO_COLOR").is_ok_and(|val| !val.is_empty());
×
748

749
    print!("{USE_ALTERNATE_SCREEN}");
×
750

751
    let prev_hook = std::panic::take_hook();
×
752
    std::panic::set_hook(Box::new(move |info| {
×
753
        terminal::restore_terminal(&orig_term_mode).unwrap_or_else(|e| eprintln!("{e}"));
×
754
        prev_hook(info);
×
755
    }));
×
756

757
    let result = editor.run(file_name, input);
×
758

759
    // Restore the original terminal mode.
760
    terminal::restore_terminal(&orig_term_mode)?;
×
761

762
    result
×
763
}
120✔
764

765
/// The prompt mode.
766
#[cfg_attr(test, derive(Debug, PartialEq))]
767
enum PromptMode {
768
    /// Save(prompt buffer)
769
    Save(String),
770
    /// Find(prompt buffer, saved cursor state, last match)
771
    Find(String, CursorState, Option<usize>),
772
    /// GoTo(prompt buffer)
773
    GoTo(String),
774
    /// Execute(prompt buffer)
775
    Execute(String),
776
}
777

778
// TODO: Use trait with mode_status_msg and process_keypress, implement the
779
// trait for separate  structs for Save and Find?
780
impl PromptMode {
781
    /// Return the status message to print for the selected `PromptMode`.
782
    fn status_msg(&self) -> String {
×
783
        match self {
×
784
            Self::Save(buffer) => format!("Save as: {buffer}"),
×
785
            Self::Find(buffer, ..) => format!("Search (Use ESC/Arrows/Enter): {buffer}"),
×
786
            Self::GoTo(buffer) => format!("Enter line number[:column number]: {buffer}"),
×
787
            Self::Execute(buffer) => format!("Command to execute: {buffer}"),
×
788
        }
789
    }
×
790

791
    /// Process a keypress event for the selected `PromptMode`.
792
    fn process_keypress(self, ed: &mut Editor, key: &Key) -> Option<Self> {
154✔
793
        ed.status_msg = None;
154✔
794
        match self {
154✔
795
            Self::Save(b) => match process_prompt_keypress(b, key) {
×
796
                PromptState::Active(b) => return Some(Self::Save(b)),
×
797
                PromptState::Cancelled => set_status!(ed, "Save aborted"),
×
798
                PromptState::Completed(file_name) => ed.save_as(file_name),
×
799
            },
800
            Self::Find(b, saved_cursor, last_match) => {
154✔
801
                if let Some(row_idx) = last_match {
154✔
802
                    ed.rows[row_idx].match_segment = None;
×
803
                }
154✔
804
                match process_prompt_keypress(b, key) {
154✔
805
                    PromptState::Active(query) => {
132✔
806
                        #[expect(clippy::wildcard_enum_match_arm)]
807
                        let (last_match, forward) = match key {
132✔
808
                            Key::Arrow(AKey::Right | AKey::Down) | Key::Char(FIND) =>
809
                                (last_match, true),
×
810
                            Key::Arrow(AKey::Left | AKey::Up) => (last_match, false),
×
811
                            _ => (None, true),
132✔
812
                        };
813
                        let curr_match = ed.find(&query, last_match, forward);
132✔
814
                        return Some(Self::Find(query, saved_cursor, curr_match));
132✔
815
                    }
816
                    // The prompt was cancelled. Restore the previous position.
817
                    PromptState::Cancelled => ed.cursor = saved_cursor,
×
818
                    // Cursor has already been moved, do nothing
819
                    PromptState::Completed(_) => (),
22✔
820
                }
821
            }
822
            Self::GoTo(b) => match process_prompt_keypress(b, key) {
×
823
                PromptState::Active(b) => return Some(Self::GoTo(b)),
×
824
                PromptState::Cancelled => (),
×
825
                PromptState::Completed(b) => {
×
826
                    let mut split = b.splitn(2, ':')
×
827
                        // saturating_sub: Lines and cols are 1-indexed
828
                        .map(|u| u.trim().parse().map(|s: usize| s.saturating_sub(1)));
×
829
                    match (split.next().transpose(), split.next().transpose()) {
×
830
                        (Ok(Some(y)), Ok(x)) => {
×
831
                            ed.cursor.y = y.min(ed.rows.len());
×
832
                            if let Some(rx) = x {
×
833
                                ed.cursor.x = ed.current_row().map_or(0, |r| r.rx2cx[rx]);
×
834
                            } else {
×
835
                                ed.update_cursor_x_position();
×
836
                            }
×
837
                        }
838
                        (Err(e), _) | (_, Err(e)) => set_status!(ed, "Parsing error: {e}"),
×
839
                        (Ok(None), _) => (),
×
840
                    }
841
                }
842
            },
843
            Self::Execute(b) => match process_prompt_keypress(b, key) {
×
844
                PromptState::Active(b) => return Some(Self::Execute(b)),
×
845
                PromptState::Cancelled => (),
×
846
                PromptState::Completed(b) => {
×
847
                    let mut args = b.split_whitespace();
×
848
                    match Command::new(args.next().unwrap_or_default()).args(args).output() {
×
849
                        Ok(out) if !out.status.success() =>
×
850
                            set_status!(ed, "{}", String::from_utf8_lossy(&out.stderr).trim_end()),
×
851
                        Ok(out) => out.stdout.into_iter().for_each(|c| match c {
×
852
                            b'\n' => ed.insert_new_line(),
×
853
                            c => ed.insert_byte(c),
×
854
                        }),
×
855
                        Err(e) => set_status!(ed, "{e}"),
×
856
                    }
857
                }
858
            },
859
        }
860
        None
22✔
861
    }
154✔
862
}
863

864
/// The state of the prompt after processing a keypress event.
865
#[cfg_attr(test, derive(Debug, PartialEq))]
866
enum PromptState {
867
    // Active contains the current buffer
868
    Active(String),
869
    // Completed contains the final string
870
    Completed(String),
871
    Cancelled,
872
}
873

874
/// Process a prompt keypress event and return the new state for the prompt.
875
fn process_prompt_keypress(mut buffer: String, key: &Key) -> PromptState {
374✔
876
    #[expect(clippy::wildcard_enum_match_arm)]
877
    match key {
209✔
878
        Key::Char(b'\r') => return PromptState::Completed(buffer),
33✔
879
        Key::Escape | Key::Char(EXIT) => return PromptState::Cancelled,
22✔
880
        Key::Char(BACKSPACE | DELETE_BIS) => _ = buffer.pop(),
99✔
881
        Key::Char(c @ 0..=126) if !c.is_ascii_control() => buffer.push(*c as char),
220✔
882
        // No-op
883
        _ => (),
22✔
884
    }
885
    PromptState::Active(buffer)
319✔
886
}
374✔
887

888
#[cfg(test)]
889
mod tests {
890
    use std::io::Cursor;
891

892
    use rstest::rstest;
893

894
    use super::*;
895
    use crate::syntax::HlType;
896

897
    fn assert_row_chars_equal(editor: &Editor, expected: &[&[u8]]) {
264✔
898
        assert_eq!(
264✔
899
            editor.rows.len(),
264✔
900
            expected.len(),
264✔
901
            "editor has {} rows, expected {}",
902
            editor.rows.len(),
×
903
            expected.len()
×
904
        );
905
        for (i, (row, expected)) in editor.rows.iter().zip(expected).enumerate() {
506✔
906
            assert_eq!(
506✔
907
                row.chars,
908
                *expected,
909
                "comparing characters for row {}\n  left: {}\n  right: {}",
910
                i,
911
                String::from_utf8_lossy(&row.chars),
×
912
                String::from_utf8_lossy(expected)
×
913
            );
914
        }
915
    }
264✔
916

917
    fn assert_row_synthax_highlighting_types_equal(editor: &Editor, expected: &[&[HlType]]) {
33✔
918
        assert_eq!(
33✔
919
            editor.rows.len(),
33✔
920
            expected.len(),
33✔
921
            "editor has {} rows, expected {}",
922
            editor.rows.len(),
×
923
            expected.len()
×
924
        );
925
        for (i, (row, expected)) in editor.rows.iter().zip(expected).enumerate() {
165✔
926
            assert_eq!(row.hl, *expected, "comparing HlTypes for row {i}",);
165✔
927
        }
928
    }
33✔
929

930
    #[rstest]
931
    #[case(0, "0B")]
932
    #[case(1, "1B")]
933
    #[case(1023, "1023B")]
934
    #[case(1024, "1.00kB")]
935
    #[case(1536, "1.50kB")]
936
    // round down!
937
    #[case(21 * 1024 - 11, "20.98kB")]
938
    #[case(21 * 1024 - 10, "20.99kB")]
939
    #[case(21 * 1024 - 3, "20.99kB")]
940
    #[case(21 * 1024, "21.00kB")]
941
    #[case(21 * 1024 + 3, "21.00kB")]
942
    #[case(21 * 1024 + 10, "21.00kB")]
943
    #[case(21 * 1024 + 11, "21.01kB")]
944
    #[case(1024 * 1024 - 1, "1023.99kB")]
945
    #[case(1024 * 1024, "1.00MB")]
946
    #[case(1024 * 1024 + 1, "1.00MB")]
947
    #[case(100 * 1024 * 1024 * 1024, "100.00GB")]
948
    #[case(313 * 1024 * 1024 * 1024 * 1024, "313.00TB")]
949
    fn format_size_output(#[case] input: u64, #[case] expected_output: &str) {
950
        assert_eq!(format_size(input), expected_output);
951
    }
952

953
    #[test]
954
    fn editor_insert_byte() {
11✔
955
        let mut editor = Editor::default();
11✔
956
        let editor_cursor_x_before = editor.cursor.x;
11✔
957

958
        editor.insert_byte(b'X');
11✔
959
        editor.insert_byte(b'Y');
11✔
960
        editor.insert_byte(b'Z');
11✔
961

962
        assert_eq!(editor.cursor.x, editor_cursor_x_before + 3);
11✔
963
        assert_eq!(editor.rows.len(), 1);
11✔
964
        assert_eq!(editor.n_bytes, 3);
11✔
965
        assert_eq!(editor.rows[0].chars, [b'X', b'Y', b'Z']);
11✔
966
    }
11✔
967

968
    #[test]
969
    fn editor_insert_new_line() {
11✔
970
        let mut editor = Editor::default();
11✔
971
        let editor_cursor_y_before = editor.cursor.y;
11✔
972

973
        for _ in 0..3 {
33✔
974
            editor.insert_new_line();
33✔
975
        }
33✔
976

977
        assert_eq!(editor.cursor.y, editor_cursor_y_before + 3);
11✔
978
        assert_eq!(editor.rows.len(), 3);
11✔
979
        assert_eq!(editor.n_bytes, 0);
11✔
980

981
        for row in &editor.rows {
33✔
982
            assert_eq!(row.chars, []);
33✔
983
        }
984
    }
11✔
985

986
    #[test]
987
    fn editor_delete_char() {
11✔
988
        let mut editor = Editor::default();
11✔
989
        for b in b"Hello world!" {
132✔
990
            editor.insert_byte(*b);
132✔
991
        }
132✔
992
        editor.delete_char();
11✔
993
        assert_row_chars_equal(&editor, &[b"Hello world"]);
11✔
994
        editor.move_cursor(&AKey::Left, true);
11✔
995
        editor.move_cursor(&AKey::Left, false);
11✔
996
        editor.move_cursor(&AKey::Left, false);
11✔
997
        editor.delete_char();
11✔
998
        assert_row_chars_equal(&editor, &[b"Helo world"]);
11✔
999
    }
11✔
1000

1001
    #[test]
1002
    fn editor_delete_next_char() {
11✔
1003
        let mut editor = Editor::default();
11✔
1004
        for &b in b"Hello world!\nHappy New Year!" {
308✔
1005
            editor.process_keypress(&Key::Char(b));
308✔
1006
        }
308✔
1007
        editor.process_keypress(&Key::Delete);
11✔
1008
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New Year!"]);
11✔
1009
        editor.move_cursor(&AKey::Left, true);
11✔
1010
        editor.process_keypress(&Key::Delete);
11✔
1011
        assert_row_chars_equal(&editor, &[b"Hello world!", b"Happy New ear!"]);
11✔
1012
        editor.move_cursor(&AKey::Left, true);
11✔
1013
        editor.move_cursor(&AKey::Left, true);
11✔
1014
        editor.move_cursor(&AKey::Left, true);
11✔
1015
        editor.process_keypress(&Key::Delete);
11✔
1016
        assert_row_chars_equal(&editor, &[b"Hello world!Happy New ear!"]);
11✔
1017
    }
11✔
1018

1019
    #[test]
1020
    fn editor_move_cursor_left() {
11✔
1021
        let mut editor = Editor::default();
11✔
1022
        for &b in b"Hello world!\nHappy New Year!" {
308✔
1023
            editor.process_keypress(&Key::Char(b));
308✔
1024
        }
308✔
1025

1026
        // check current position
1027
        assert_eq!(editor.cursor.x, 15);
11✔
1028
        assert_eq!(editor.cursor.y, 1);
11✔
1029

1030
        editor.move_cursor(&AKey::Left, true);
11✔
1031
        assert_eq!(editor.cursor.x, 10);
11✔
1032
        assert_eq!(editor.cursor.y, 1);
11✔
1033

1034
        editor.move_cursor(&AKey::Left, false);
11✔
1035
        assert_eq!(editor.cursor.x, 9);
11✔
1036
        assert_eq!(editor.cursor.y, 1);
11✔
1037

1038
        editor.move_cursor(&AKey::Left, true);
11✔
1039
        assert_eq!(editor.cursor.x, 6);
11✔
1040
        assert_eq!(editor.cursor.y, 1);
11✔
1041

1042
        editor.move_cursor(&AKey::Left, true);
11✔
1043
        assert_eq!(editor.cursor.x, 0);
11✔
1044
        assert_eq!(editor.cursor.y, 1);
11✔
1045

1046
        editor.move_cursor(&AKey::Left, false);
11✔
1047
        assert_eq!(editor.cursor.x, 12);
11✔
1048
        assert_eq!(editor.cursor.y, 0);
11✔
1049

1050
        editor.move_cursor(&AKey::Left, true);
11✔
1051
        assert_eq!(editor.cursor.x, 6);
11✔
1052
        assert_eq!(editor.cursor.y, 0);
11✔
1053

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

1058
        editor.move_cursor(&AKey::Left, false);
11✔
1059
        assert_eq!(editor.cursor.x, 0);
11✔
1060
        assert_eq!(editor.cursor.y, 0);
11✔
1061
    }
11✔
1062

1063
    #[test]
1064
    fn editor_move_cursor_up() {
11✔
1065
        let mut editor = Editor::default();
11✔
1066
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
308✔
1067
            editor.process_keypress(&Key::Char(b));
308✔
1068
        }
308✔
1069

1070
        // check current position
1071
        assert_eq!(editor.cursor.x, 16);
11✔
1072
        assert_eq!(editor.cursor.y, 2);
11✔
1073

1074
        editor.move_cursor(&AKey::Up, false);
11✔
1075
        assert_eq!(editor.cursor.x, 2);
11✔
1076
        assert_eq!(editor.cursor.y, 1);
11✔
1077

1078
        editor.move_cursor(&AKey::Up, true);
11✔
1079
        assert_eq!(editor.cursor.x, 2);
11✔
1080
        assert_eq!(editor.cursor.y, 0);
11✔
1081

1082
        editor.move_cursor(&AKey::Up, false);
11✔
1083
        assert_eq!(editor.cursor.x, 2);
11✔
1084
        assert_eq!(editor.cursor.y, 0);
11✔
1085
    }
11✔
1086

1087
    #[test]
1088
    fn editor_move_cursor_right() {
11✔
1089
        let mut editor = Editor::default();
11✔
1090
        for &b in b"Hello world\nHappy New Year" {
286✔
1091
            editor.process_keypress(&Key::Char(b));
286✔
1092
        }
286✔
1093

1094
        // check current position
1095
        assert_eq!(editor.cursor.x, 14);
11✔
1096
        assert_eq!(editor.cursor.y, 1);
11✔
1097

1098
        editor.move_cursor(&AKey::Right, false);
11✔
1099
        assert_eq!(editor.cursor.x, 0);
11✔
1100
        assert_eq!(editor.cursor.y, 2);
11✔
1101

1102
        editor.move_cursor(&AKey::Right, false);
11✔
1103
        assert_eq!(editor.cursor.x, 0);
11✔
1104
        assert_eq!(editor.cursor.y, 2);
11✔
1105

1106
        editor.move_cursor(&AKey::Up, true);
11✔
1107
        editor.move_cursor(&AKey::Up, true);
11✔
1108
        assert_eq!(editor.cursor.x, 0);
11✔
1109
        assert_eq!(editor.cursor.y, 0);
11✔
1110

1111
        editor.move_cursor(&AKey::Right, true);
11✔
1112
        assert_eq!(editor.cursor.x, 5);
11✔
1113
        assert_eq!(editor.cursor.y, 0);
11✔
1114

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

1119
        editor.move_cursor(&AKey::Right, false);
11✔
1120
        assert_eq!(editor.cursor.x, 0);
11✔
1121
        assert_eq!(editor.cursor.y, 1);
11✔
1122
    }
11✔
1123

1124
    #[test]
1125
    fn editor_move_cursor_down() {
11✔
1126
        let mut editor = Editor::default();
11✔
1127
        for &b in b"abcdefgh\nij\nklmnopqrstuvwxyz" {
308✔
1128
            editor.process_keypress(&Key::Char(b));
308✔
1129
        }
308✔
1130

1131
        // check current position
1132
        assert_eq!(editor.cursor.x, 16);
11✔
1133
        assert_eq!(editor.cursor.y, 2);
11✔
1134

1135
        editor.move_cursor(&AKey::Down, false);
11✔
1136
        assert_eq!(editor.cursor.x, 0);
11✔
1137
        assert_eq!(editor.cursor.y, 3);
11✔
1138

1139
        editor.move_cursor(&AKey::Up, false);
11✔
1140
        editor.move_cursor(&AKey::Up, false);
11✔
1141
        editor.move_cursor(&AKey::Up, false);
11✔
1142

1143
        assert_eq!(editor.cursor.x, 0);
11✔
1144
        assert_eq!(editor.cursor.y, 0);
11✔
1145

1146
        editor.move_cursor(&AKey::Right, true);
11✔
1147
        assert_eq!(editor.cursor.x, 8);
11✔
1148
        assert_eq!(editor.cursor.y, 0);
11✔
1149

1150
        editor.move_cursor(&AKey::Down, true);
11✔
1151
        assert_eq!(editor.cursor.x, 2);
11✔
1152
        assert_eq!(editor.cursor.y, 1);
11✔
1153

1154
        editor.move_cursor(&AKey::Down, true);
11✔
1155
        assert_eq!(editor.cursor.x, 2);
11✔
1156
        assert_eq!(editor.cursor.y, 2);
11✔
1157

1158
        editor.move_cursor(&AKey::Down, true);
11✔
1159
        assert_eq!(editor.cursor.x, 0);
11✔
1160
        assert_eq!(editor.cursor.y, 3);
11✔
1161

1162
        editor.move_cursor(&AKey::Down, false);
11✔
1163
        assert_eq!(editor.cursor.x, 0);
11✔
1164
        assert_eq!(editor.cursor.y, 3);
11✔
1165
    }
11✔
1166

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

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

1178
        editor.process_keypress(&Key::Home);
11✔
1179
        assert_eq!(editor.cursor.x, 0);
11✔
1180
        assert_eq!(editor.cursor.y, 3);
11✔
1181

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

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

1189
        editor.move_cursor(&AKey::Right, true);
11✔
1190
        assert_eq!(editor.cursor.x, 5);
11✔
1191
        assert_eq!(editor.cursor.y, 0);
11✔
1192

1193
        editor.process_keypress(&Key::Home);
11✔
1194
        assert_eq!(editor.cursor.x, 0);
11✔
1195
        assert_eq!(editor.cursor.y, 0);
11✔
1196
    }
11✔
1197

1198
    #[test]
1199
    fn editor_press_end_key() {
11✔
1200
        let mut editor = Editor::default();
11✔
1201
        for &b in b"Hello\nWorld\nand\nFerris!" {
253✔
1202
            editor.process_keypress(&Key::Char(b));
253✔
1203
        }
253✔
1204

1205
        // check current position
1206
        assert_eq!(editor.cursor.x, 7);
11✔
1207
        assert_eq!(editor.cursor.y, 3);
11✔
1208

1209
        editor.process_keypress(&Key::End);
11✔
1210
        assert_eq!(editor.cursor.x, 7);
11✔
1211
        assert_eq!(editor.cursor.y, 3);
11✔
1212

1213
        editor.move_cursor(&AKey::Up, false);
11✔
1214
        editor.move_cursor(&AKey::Up, false);
11✔
1215
        editor.move_cursor(&AKey::Up, false);
11✔
1216

1217
        assert_eq!(editor.cursor.x, 3);
11✔
1218
        assert_eq!(editor.cursor.y, 0);
11✔
1219

1220
        editor.process_keypress(&Key::End);
11✔
1221
        assert_eq!(editor.cursor.x, 5);
11✔
1222
        assert_eq!(editor.cursor.y, 0);
11✔
1223
    }
11✔
1224

1225
    #[test]
1226
    fn editor_page_up_moves_cursor_to_viewport_top() {
11✔
1227
        let mut editor = Editor { screen_rows: 4, ..Default::default() };
11✔
1228
        for _ in 0..10 {
110✔
1229
            editor.insert_new_line();
110✔
1230
        }
110✔
1231

1232
        (editor.cursor.y, editor.cursor.x) = (3, 0);
11✔
1233
        editor.insert_byte(b'a');
11✔
1234
        editor.insert_byte(b'b');
11✔
1235

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

1239
        assert!(!should_quit);
11✔
1240
        assert!(prompt_mode.is_none());
11✔
1241
        assert_eq!(editor.cursor.y, 3);
11✔
1242
        assert_eq!(editor.cursor.x, 2);
11✔
1243
    }
11✔
1244

1245
    #[test]
1246
    fn editor_page_down_moves_cursor_to_viewport_bottom() {
11✔
1247
        let mut editor = Editor { screen_rows: 4, ..Default::default() };
11✔
1248
        for _ in 0..12 {
132✔
1249
            editor.insert_new_line();
132✔
1250
        }
132✔
1251

1252
        (editor.cursor.y, editor.cursor.x) = (11, 0);
11✔
1253
        editor.insert_byte(b'x');
11✔
1254
        editor.insert_byte(b'y');
11✔
1255
        editor.insert_byte(b'z');
11✔
1256

1257
        (editor.cursor.x, editor.cursor.roff) = (6, 4);
11✔
1258
        let (should_quit, prompt_mode) = editor.process_keypress(&Key::PageDown);
11✔
1259
        assert!(!should_quit);
11✔
1260
        assert!(prompt_mode.is_none());
11✔
1261
        assert_eq!(editor.cursor.y, 11);
11✔
1262
        assert_eq!(editor.cursor.x, 3);
11✔
1263

1264
        (editor.cursor.x, editor.cursor.roff) = (9, 11);
11✔
1265
        let (should_quit, prompt_mode_again) = editor.process_keypress(&Key::PageDown);
11✔
1266
        assert!(!should_quit);
11✔
1267
        assert!(prompt_mode_again.is_none());
11✔
1268
        assert_eq!(editor.cursor.y, editor.rows.len());
11✔
1269
        assert_eq!(editor.cursor.x, 0);
11✔
1270
    }
11✔
1271

1272
    #[rstest]
1273
    #[case::beginning_of_first_row(b"Hello\nWorld!\n", (0, 0), &[&b"World!"[..], &b""[..]], 0)]
1274
    #[case::middle_of_first_row(b"Hello\nWorld!\n", (3, 0), &[&b"World!"[..], &b""[..]], 0)]
1275
    #[case::end_of_first_row(b"Hello\nWorld!\n", (5, 0), &[&b"World!"[..], &b""[..]], 0)]
1276
    #[case::empty_first_row(b"\nHello", (0, 0), &[&b"Hello"[..]], 0)]
1277
    #[case::beginning_of_only_row(b"Hello", (0, 0), &[&b""[..]], 0)]
1278
    #[case::middle_of_only_row(b"Hello", (3, 0), &[&b""[..]], 0)]
1279
    #[case::end_of_only_row(b"Hello", (5, 0), &[&b""[..]], 0)]
1280
    #[case::beginning_of_middle_row(b"Hello\nWorld!\n", (0, 1), &[&b"Hello"[..], &b""[..]], 1)]
1281
    #[case::middle_of_middle_row(b"Hello\nWorld!\n", (3, 1), &[&b"Hello"[..], &b""[..]], 1)]
1282
    #[case::end_of_middle_row(b"Hello\nWorld!\n", (6, 1), &[&b"Hello"[..], &b""[..]], 1)]
1283
    #[case::empty_middle_row(b"Hello\n\nWorld!", (0, 1), &[&b"Hello"[..], &b"World!"[..]], 1)]
1284
    #[case::beginning_of_last_row(b"Hello\nWorld!", (0, 1), &[&b"Hello"[..]], 0)]
1285
    #[case::middle_of_last_row(b"Hello\nWorld!", (3, 1), &[&b"Hello"[..]], 0)]
1286
    #[case::end_of_last_row(b"Hello\nWorld!", (6, 1), &[&b"Hello"[..]], 0)]
1287
    #[case::empty_last_row(b"Hello\n", (0, 1), &[&b"Hello"[..]], 0)]
1288
    #[case::after_last_row(b"Hello\nWorld!", (0, 2), &[&b"Hello"[..], &b"World!"[..]], 2)]
1289
    fn delete_current_row_updates_buffer_and_position(
1290
        #[case] initial_buffer: &[u8], #[case] cursor_position: (usize, usize),
1291
        #[case] expected_rows: &[&[u8]], #[case] expected_cursor_row: usize,
1292
    ) {
1293
        let mut editor = Editor::default();
1294
        for &b in initial_buffer {
1295
            editor.process_keypress(&Key::Char(b));
1296
        }
1297
        (editor.cursor.x, editor.cursor.y) = cursor_position;
1298

1299
        editor.delete_current_row();
1300

1301
        assert_row_chars_equal(&editor, expected_rows);
1302
        assert_eq!(
1303
            (editor.cursor.x, editor.cursor.y),
1304
            (0, expected_cursor_row),
1305
            "cursor is at {}:{}, expected {}:0",
1306
            editor.cursor.y,
1307
            editor.cursor.x,
1308
            expected_cursor_row
1309
        );
1310
    }
1311

1312
    #[rstest]
1313
    #[case::first_row(0)]
1314
    #[case::middle_row(5)]
1315
    #[case::last_row(9)]
1316
    fn delete_current_row_updates_screen_cols_and_ln_pad(#[case] current_row: usize) {
1317
        let mut editor = Editor { window_width: 100, ..Default::default() };
1318
        for _ in 0..10 {
1319
            editor.insert_new_line();
1320
        }
1321
        assert_eq!(editor.screen_cols, 96);
1322
        assert_eq!(editor.ln_pad, 4);
1323

1324
        editor.cursor.y = current_row;
1325
        editor.delete_current_row();
1326

1327
        assert_eq!(editor.screen_cols, 97);
1328
        assert_eq!(editor.ln_pad, 3);
1329
    }
1330

1331
    #[test]
1332
    fn delete_current_row_updates_syntax_highlighting() {
11✔
1333
        let mut editor = Editor {
11✔
1334
            syntax: SyntaxConf {
11✔
1335
                ml_comment_delims: Some(("/*".to_owned(), "*/".to_owned())),
11✔
1336
                ..Default::default()
11✔
1337
            },
11✔
1338
            ..Default::default()
11✔
1339
        };
11✔
1340
        for &b in b"A\nb/*c\nd\ne\nf*/g\nh" {
187✔
1341
            editor.process_keypress(&Key::Char(b));
187✔
1342
        }
187✔
1343

1344
        assert_row_chars_equal(&editor, &[b"A", b"b/*c", b"d", b"e", b"f*/g", b"h"]);
11✔
1345
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1346
            &[HlType::Normal],
11✔
1347
            &[HlType::Normal, HlType::MlComment, HlType::MlComment, HlType::MlComment],
11✔
1348
            &[HlType::MlComment],
11✔
1349
            &[HlType::MlComment],
11✔
1350
            &[HlType::MlComment, HlType::MlComment, HlType::MlComment, HlType::Normal],
11✔
1351
            &[HlType::Normal],
11✔
1352
        ]);
11✔
1353

1354
        (editor.cursor.x, editor.cursor.y) = (0, 4);
11✔
1355
        editor.delete_current_row();
11✔
1356

1357
        assert_row_chars_equal(&editor, &[b"A", b"b/*c", b"d", b"e", b"h"]);
11✔
1358
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1359
            &[HlType::Normal],
11✔
1360
            &[HlType::Normal, HlType::MlComment, HlType::MlComment, HlType::MlComment],
11✔
1361
            &[HlType::MlComment],
11✔
1362
            &[HlType::MlComment],
11✔
1363
            &[HlType::MlComment],
11✔
1364
        ]);
11✔
1365

1366
        (editor.cursor.x, editor.cursor.y) = (0, 1);
11✔
1367
        editor.delete_current_row();
11✔
1368

1369
        assert_row_chars_equal(&editor, &[b"A", b"d", b"e", b"h"]);
11✔
1370
        assert_row_synthax_highlighting_types_equal(&editor, &[
11✔
1371
            &[HlType::Normal],
11✔
1372
            &[HlType::Normal],
11✔
1373
            &[HlType::Normal],
11✔
1374
            &[HlType::Normal],
11✔
1375
        ]);
11✔
1376
    }
11✔
1377

1378
    #[test]
1379
    fn loop_until_keypress() -> Result<(), Error> {
11✔
1380
        let mut editor = Editor::default();
11✔
1381
        let mut fake_stdin = Cursor::new(
11✔
1382
            b"abc\x1b[A\x1b[B\x1b[C\x1b[D\x1b[H\x1bOH\x1b[F\x1bOF\x1b[1;5C\x1b[5C\x1b[99",
1383
        );
1384
        for expected_key in [
154✔
1385
            Key::Char(b'a'),
11✔
1386
            Key::Char(b'b'),
11✔
1387
            Key::Char(b'c'),
11✔
1388
            Key::Arrow(AKey::Up),
11✔
1389
            Key::Arrow(AKey::Down),
11✔
1390
            Key::Arrow(AKey::Right),
11✔
1391
            Key::Arrow(AKey::Left),
11✔
1392
            Key::Home,
11✔
1393
            Key::Home,
11✔
1394
            Key::End,
11✔
1395
            Key::End,
11✔
1396
            Key::CtrlArrow(AKey::Right),
11✔
1397
            Key::CtrlArrow(AKey::Right),
11✔
1398
            Key::Escape,
11✔
1399
        ] {
11✔
1400
            assert_eq!(editor.loop_until_keypress(&mut fake_stdin)?, expected_key);
154✔
1401
        }
1402
        Ok(())
11✔
1403
    }
11✔
1404

1405
    #[rstest]
1406
    #[case::ascii_completed(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(b'\r')], &PromptState::Completed(String::from("Hi")))]
1407
    #[case::escape(&[Key::Char(b'H'), Key::Char(b'i'), Key::Escape], &PromptState::Cancelled)]
1408
    #[case::exit(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(EXIT)], &PromptState::Cancelled)]
1409
    #[case::skip_ascii_control(&[Key::Char(b'\x0A')], &PromptState::Active(String::new()))]
1410
    #[case::unsupported_non_ascii(&[Key::Char(b'\xEF')], &PromptState::Active(String::new()))]
1411
    #[case::backspace(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], &PromptState::Active(String::new()))]
1412
    #[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()))]
1413
    fn process_prompt_keypresses(#[case] keys: &[Key], #[case] expected_final_state: &PromptState) {
1414
        let mut prompt_state = PromptState::Active(String::new());
1415
        for key in keys {
1416
            if let PromptState::Active(buffer) = prompt_state {
1417
                prompt_state = process_prompt_keypress(buffer, key);
1418
            } else {
1419
                panic!("Prompt state: {prompt_state:?} is not active")
1420
            }
1421
        }
1422
        assert_eq!(prompt_state, *expected_final_state);
1423
    }
1424

1425
    #[rstest]
1426
    #[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")]
1427
    #[case(&[Key::Char(b'H'), Key::Char(b'i'), Key::Char(BACKSPACE), Key::Char(BACKSPACE), Key::Char(BACKSPACE)], "")]
1428
    fn process_find_keypress_completed(#[case] keys: &[Key], #[case] expected_final_value: &str) {
1429
        let mut ed: Editor = Editor::default();
1430
        ed.insert_new_line();
1431
        let mut prompt_mode = Some(PromptMode::Find(String::new(), CursorState::default(), None));
1432
        for key in keys {
1433
            prompt_mode = prompt_mode
1434
                .take()
1435
                .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, key));
132✔
1436
        }
1437
        assert_eq!(
1438
            prompt_mode,
1439
            Some(PromptMode::Find(
1440
                String::from(expected_final_value),
1441
                CursorState::default(),
1442
                None
1443
            ))
1444
        );
1445
        prompt_mode = prompt_mode
1446
            .take()
1447
            .and_then(|prompt_mode| prompt_mode.process_keypress(&mut ed, &Key::Char(b'\r')));
22✔
1448
        assert_eq!(prompt_mode, None);
1449
    }
1450

1451
    #[rstest]
1452
    #[case(100, true, 12345, "\u{1b}[38;5;240m12345 │\u{1b}[m")]
1453
    #[case(100, true, "~", "\u{1b}[38;5;240m~ │\u{1b}[m")]
1454
    #[case(10, true, 12345, "")]
1455
    #[case(10, true, "~", "")]
1456
    #[case(100, false, 12345, "12345 │")]
1457
    #[case(100, false, "~", "~ │")]
1458
    #[case(10, false, 12345, "")]
1459
    #[case(10, false, "~", "")]
1460
    fn draw_left_padding<T: Display>(
1461
        #[case] window_width: usize, #[case] use_color: bool, #[case] value: T,
1462
        #[case] expected: &'static str,
1463
    ) {
1464
        let mut editor = Editor { window_width, use_color, ..Default::default() };
1465
        editor.update_screen_cols();
1466

1467
        let mut buffer = String::new();
1468
        editor.draw_left_padding(&mut buffer, value);
1469
        assert_eq!(buffer, expected);
1470
    }
1471

1472
    #[test]
1473
    fn editor_toggle_comment() {
11✔
1474
        let mut editor = Editor::default();
11✔
1475

1476
        // Set up Python syntax configuration for testing
1477
        editor.syntax.sl_comment_start = vec!["#".to_owned()];
11✔
1478

1479
        for b in b"def hello():\n    print(\"Hello\")\n    return True" {
517✔
1480
            if *b == b'\n' {
517✔
1481
                editor.insert_new_line();
22✔
1482
            } else {
495✔
1483
                editor.insert_byte(*b);
495✔
1484
            }
495✔
1485
        }
1486

1487
        // Test commenting a line
1488
        editor.cursor.y = 0; // First line
11✔
1489
        editor.cursor.x = 0;
11✔
1490
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT));
11✔
1491
        assert_eq!(editor.rows[0].chars, b"# def hello():");
11✔
1492

1493
        // Test uncommenting the same line
1494
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT));
11✔
1495
        assert_eq!(editor.rows[0].chars, b"def hello():");
11✔
1496

1497
        // Test commenting an indented line
1498
        editor.cursor.y = 1; // Second line (indented)
11✔
1499
        editor.cursor.x = 0;
11✔
1500
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT));
11✔
1501
        assert_eq!(editor.rows[1].chars, b"    # print(\"Hello\")");
11✔
1502

1503
        // Test uncommenting the indented line
1504
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT));
11✔
1505
        assert_eq!(editor.rows[1].chars, b"    print(\"Hello\")");
11✔
1506

1507
        // Test the bug case: cursor at end of line during toggle
1508
        editor.cursor.y = 0; // First line
11✔
1509
        editor.cursor.x = editor.rows[0].chars.len(); // Position at end
11✔
1510
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT)); // Comment
11✔
1511
        assert_eq!(editor.rows[0].chars, b"# def hello():");
11✔
1512

1513
        // Now uncomment with cursor still at end - this should not panic
1514
        editor.cursor.x = editor.rows[0].chars.len(); // Position at end again
11✔
1515
        editor.process_keypress(&Key::Char(TOGGLE_COMMENT)); // Uncomment
11✔
1516
        assert_eq!(editor.rows[0].chars, b"def hello():");
11✔
1517

1518
        // Verify cursor position is valid
1519
        assert!(editor.cursor.x <= editor.rows[0].chars.len());
11✔
1520
    }
11✔
1521
}
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