1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#![cfg_attr(not(doctest), doc = include_str!("../README.md"))]

use std::fmt::Display;
use std::io::{self, stdout, StdoutLock, Write};

use crossterm::event::{self, Event, KeyCode, KeyEventState, KeyModifiers};
use crossterm::{cursor, queue, terminal};

mod history;
pub use history::History;

/// A highlighting scheme to apply to the user input.
pub struct Highlight<'a>(pub &'a dyn Fn(&str) -> String);

/// A completion function to apply to the user input.
///
/// The arguments are the input, the start of the selection, and the end.
/// The selection will be replaced in its entirety.
pub struct Completion<'a>(pub &'a dyn Fn(&str, usize, usize) -> Vec<String>);

/// The default characters on which to break words.
pub const WORD_BREAKS: &str = "-_=+[]{}()<>,./\\`'\";:!@#$%^&*?|~ ";

/// The result of [`Editor::read`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditResult {
    Ok(String),
    Cancel,
    Quit,
}

/// A line editor.
///
/// Ctrl-C returns an [`EditResult::Cancel`];
/// Ctrl-D returns an [`EditResult::Quit`].
///
/// Example:
/// ```no_run
/// # use linoleum::{Editor, EditResult};
/// let mut editor = Editor::new(" > ");
/// match editor.read().expect("Failed to read line") {
///     EditResult::Ok(s) => println!("You entered: '{s}'"),
///     EditResult::Cancel => println!("You canceled!"),
///     EditResult::Quit => std::process::exit(1),
/// }
/// ```
pub struct Editor<'a, 'b, 'c, P: Display> {
    pub prompt: P,
    pub word_breaks: &'a str,
    pub highlight: Option<Highlight<'b>>,
    pub history: Option<History>,
    pub completion: Option<Completion<'c>>,
}

impl<'a, 'b, 'c, P: Display> Editor<'a, 'b, 'c, P> {
    /// Creates a new editor with empty highlight and default word breaks.
    ///
    /// Example:
    /// ```
    /// # use linoleum::Editor;
    /// let editor = Editor::new(" > ");
    /// ```
    pub fn new(prompt: P) -> Self {
        Self {
            prompt,
            word_breaks: WORD_BREAKS,
            highlight: None,
            history: None,
            completion: None,
        }
    }

    /// Sets the word break characters the editor respects.
    ///
    /// Example:
    /// ```
    /// # use linoleum::Editor;
    /// // Create a new editor that doesn't break words.
    /// let editor = Editor::new(" > ")
    ///     .word_breaks("");
    /// ```
    pub fn word_breaks(mut self, word_breaks: &'a str) -> Self {
        self.word_breaks = word_breaks;
        self
    }

    /// Sets the highlighter of the editor.
    ///
    /// Example:
    /// ```
    /// # use linoleum::{Editor, Highlight};
    /// fn underline(s: &str, pat: &str) -> String {
    ///     // ...
    ///     # s.to_string()
    /// }
    ///
    /// // Create a new editor with a highlighter.
    /// let editor = Editor::new(" > ")
    ///     .highlight(Highlight(&|s| underline(s, "hello, world!")));
    /// ```
    pub fn highlight(mut self, highlight: Highlight<'b>) -> Self {
        self.highlight = Some(highlight);
        self
    }

    /// Sets the completion function.
    ///
    /// Example:
    /// ```
    /// # use linoleum::{Editor, Completion};
    /// fn complete(s: &str, _start: usize, _end: usize) -> Vec<String> {
    ///     let s = "hello".to_string();
    ///     if s.starts_with(&s) {
    ///         vec![s]
    ///     } else {
    ///         Vec::new()
    ///     }
    /// }
    /// let editor = Editor::new(" > ")
    ///     .completion(Completion(&complete));
    /// ```
    pub fn completion(mut self, completion: Completion<'c>) -> Self {
        self.completion = Some(completion);
        self
    }

    /// Updates the prompt of the editor.
    ///
    /// Example:
    /// ```
    /// # use linoleum::{Editor, Completion};
    /// let mut editor = Editor::new(" > ");
    /// // ...
    /// editor.prompt("{~} ");
    /// ```
    pub fn prompt(&mut self, prompt: P) {
        self.prompt = prompt;
    }

    /// Sets the file to use for history.
    ///
    /// Opens and reads the file immediately.
    ///
    /// Example:
    /// ```no_run
    /// # use linoleum::Editor;
    /// let editor = Editor::new(" > ")
    ///     .history("~/.history", 1000)
    ///     .expect("failed to read history");
    /// ```
    pub fn history<S: ToString>(mut self, history: S, max_lines: usize) -> io::Result<Self> {
        self.history = Some(History::new(history.to_string(), max_lines)?);
        Ok(self)
    }

    /// Resets the history index to the most recent.
    ///
    /// Example:
    /// ```no_run
    /// # use linoleum::Editor;
    /// let mut editor = Editor::new(" > ")
    ///     .history("~/.history", 1000)
    ///     .expect("failed to read history");
    /// // ...
    /// editor.reset_history_index();
    /// ```
    pub fn reset_history_index(&mut self) {
        if let Some(h) = &mut self.history {
            h.reset_index();
        }
    }

    /// Saves the history. See [`History::save`].
    pub fn save_history(&self) -> io::Result<()> {
        if let Some(h) = &self.history {
            h.save()
        } else {
            Ok(())
        }
    }

    /// Reads a line from stdin.
    ///
    /// Precedes with prompt. Enters terminal raw mode for the duration
    /// of the read.
    ///
    /// Example:
    /// ```no_run
    /// # use linoleum::{Editor, EditResult};
    /// let mut editor = Editor::new(" > ");
    /// match editor.read().expect("Failed to read line") {
    ///     EditResult::Ok(s) => println!("You entered: '{s}'"),
    ///     EditResult::Cancel => println!("You canceled!"),
    ///     EditResult::Quit => std::process::exit(1),
    /// }
    /// ```
    pub fn read(&mut self) -> io::Result<EditResult> {
        let mut stdout = stdout().lock();

        let prompt = self.prompt.to_string();
        let prompt_length = prompt.len();
        write!(stdout, "{}", prompt)?;
        stdout.flush()?;
        terminal::enable_raw_mode()?;

        let mut data = String::new();
        let mut cursor = 0;

        let mut cursor_line = 0;
        let mut num_lines = 0;

        let mut completion_length = 0;
        let mut completions = Vec::<String>::new();
        let mut completion_index = 0;

        loop {
            let ev = event::read();

            let ev = match ev {
                Ok(ev) => ev,
                Err(e) => {
                    terminal::disable_raw_mode()?;
                    return Err(e);
                }
            };

            if let Event::Key(key) = ev {
                let caps = key.modifiers.contains(KeyModifiers::SHIFT)
                    ^ key.state.contains(KeyEventState::CAPS_LOCK);

                match key.code {
                    KeyCode::Enter => {
                        if completion_length != 0 {
                            let old_cursor = cursor;
                            cursor = self.find_space_boundary(&data, cursor, true);
                            if self.word_breaks.contains(data.chars().nth(cursor).unwrap()) {
                                cursor += 1;
                            }

                            data = data
                                .chars()
                                .take(cursor)
                                .chain(data.chars().skip(old_cursor))
                                .collect();

                            data.insert_str(cursor, completions[completion_index].as_str());
                            cursor += completions[completion_index].len();

                            self.redraw(
                                &mut stdout,
                                &data,
                                prompt_length,
                                &mut cursor_line,
                                &mut num_lines,
                                cursor,
                            )?;
                        } else {
                            break;
                        }
                    }
                    KeyCode::Backspace => {
                        if cursor != 0 {
                            cursor -= 1;
                            data.remove(cursor);
                            self.redraw(
                                &mut stdout,
                                &data,
                                prompt_length,
                                &mut cursor_line,
                                &mut num_lines,
                                cursor,
                            )?;
                        }
                    }
                    KeyCode::Char(mut ch) => {
                        if key.modifiers.contains(KeyModifiers::CONTROL) {
                            if ch == 'h' {
                                let old_cursor = cursor;
                                cursor = self.find_word_boundary(&data, cursor, true);

                                data = data
                                    .chars()
                                    .take(cursor)
                                    .chain(data.chars().skip(old_cursor))
                                    .collect();

                                self.redraw(
                                    &mut stdout,
                                    &data,
                                    prompt_length,
                                    &mut cursor_line,
                                    &mut num_lines,
                                    cursor,
                                )?;
                            } else if ch == 'd' {
                                terminal::disable_raw_mode()?;
                                self.reset_history_index();
                                writeln!(stdout)?;
                                return Ok(if data.is_empty() {
                                    EditResult::Quit
                                } else {
                                    EditResult::Cancel
                                });
                            } else if ch == 'c' {
                                terminal::disable_raw_mode()?;
                                self.reset_history_index();
                                writeln!(stdout)?;
                                return Ok(EditResult::Cancel);
                            }
                        } else {
                            if caps {
                                ch = ch.to_uppercase().next().unwrap();
                            }

                            data.insert(cursor, ch);
                            cursor += 1;
                            self.redraw(
                                &mut stdout,
                                &data,
                                prompt_length,
                                &mut cursor_line,
                                &mut num_lines,
                                cursor,
                            )?;
                        }
                    }
                    KeyCode::Left => {
                        if completion_length != 0 {
                            completion_index = completion_index.saturating_sub(1);

                            self.clear_completions(
                                &mut stdout,
                                completion_length,
                                cursor_line,
                                num_lines,
                            )?;

                            completion_length = self.show_completions(
                                &mut stdout,
                                &completions,
                                cursor_line,
                                num_lines,
                                completion_index,
                            )?;

                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if key.modifiers.contains(KeyModifiers::CONTROL) {
                            cursor = self.find_word_boundary(&data, cursor, true);
                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if cursor != 0 {
                            cursor -= 1;
                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        }
                    }
                    KeyCode::Right => {
                        if completion_length != 0 {
                            completion_index = completion_index.saturating_add(1);

                            self.clear_completions(
                                &mut stdout,
                                completion_length,
                                cursor_line,
                                num_lines,
                            )?;

                            completion_length = self.show_completions(
                                &mut stdout,
                                &completions,
                                cursor_line,
                                num_lines,
                                completion_index,
                            )?;

                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if key.modifiers.contains(KeyModifiers::CONTROL) {
                            cursor = self.find_word_boundary(&data, cursor, false) + 1;
                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if cursor != data.len() {
                            cursor += 1;
                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        }
                    }
                    KeyCode::Up => {
                        if completion_length != 0 {
                            completion_index = completion_index.saturating_sub(2);

                            self.clear_completions(
                                &mut stdout,
                                completion_length,
                                cursor_line,
                                num_lines,
                            )?;

                            completion_length = self.show_completions(
                                &mut stdout,
                                &completions,
                                cursor_line,
                                num_lines,
                                completion_index,
                            )?;

                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if let Some(h) = &mut self.history {
                            if let Some(line) = h.up() {
                                data = line;
                                cursor = data.len();
                                self.redraw(
                                    &mut stdout,
                                    &data,
                                    prompt_length,
                                    &mut cursor_line,
                                    &mut num_lines,
                                    cursor,
                                )?;
                            }
                        }
                    }
                    KeyCode::Down => {
                        if completion_length != 0 {
                            completion_index = completion_index.saturating_add(2);

                            self.clear_completions(
                                &mut stdout,
                                completion_length,
                                cursor_line,
                                num_lines,
                            )?;

                            completion_length = self.show_completions(
                                &mut stdout,
                                &completions,
                                cursor_line,
                                num_lines,
                                completion_index,
                            )?;

                            self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                        } else if let Some(h) = &mut self.history {
                            if let Some(line) = h.down() {
                                data = line;
                                cursor = data.len();
                                self.redraw(
                                    &mut stdout,
                                    &data,
                                    prompt_length,
                                    &mut cursor_line,
                                    &mut num_lines,
                                    cursor,
                                )?;
                            } else {
                                data.clear();
                                cursor = 0;
                                self.redraw(
                                    &mut stdout,
                                    &data,
                                    prompt_length,
                                    &mut cursor_line,
                                    &mut num_lines,
                                    cursor,
                                )?;
                            }
                        }
                    }
                    KeyCode::Home => {
                        cursor = 0;
                        self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                    }
                    KeyCode::End => {
                        cursor = data.len();
                        self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                    }
                    KeyCode::Tab => {
                        if let Some(c) = &self.completion {
                            let word_start = self.find_space_boundary(&data, cursor, true);
                            completions = (c.0)(&data, word_start, cursor);
                        } else {
                            continue;
                        }

                        if completion_length != 0 {
                            self.clear_completions(
                                &mut stdout,
                                completion_length,
                                cursor_line,
                                num_lines,
                            )?;
                        }

                        completion_length = self.show_completions(
                            &mut stdout,
                            &completions,
                            cursor_line,
                            num_lines,
                            completion_index,
                        )?;

                        self.move_to(&mut stdout, prompt_length, &mut cursor_line, cursor)?;
                    }
                    _ => {}
                }

                if completion_length != 0
                    && !matches!(
                        key.code,
                        KeyCode::Tab | KeyCode::Left | KeyCode::Right | KeyCode::Up | KeyCode::Down
                    )
                {
                    self.clear_completions(&mut stdout, completion_length, cursor_line, num_lines)?;
                    completion_length = 0;
                    completion_index = 0;
                }
            }
        }

        terminal::disable_raw_mode()?;
        self.reset_history_index();

        if let Some(h) = &mut self.history {
            h.push(data.clone());
        }

        writeln!(stdout)?;
        Ok(EditResult::Ok(data))
    }

    fn clear_completions(
        &self,
        stdout: &mut StdoutLock,
        completion_length: u16,
        cursor_line: u16,
        num_lines: u16,
    ) -> io::Result<()> {
        if completion_length == 0 {
            return Ok(());
        }

        let n = num_lines - cursor_line;

        if n != 0 {
            queue!(stdout, cursor::MoveDown(n))?;
        }

        for _ in 0..completion_length {
            queue!(
                stdout,
                cursor::MoveDown(1),
                terminal::Clear(terminal::ClearType::CurrentLine),
            )?;
        }

        queue!(stdout, cursor::MoveUp(completion_length))?;

        if n != 0 {
            queue!(stdout, cursor::MoveUp(n),)?;
        }

        stdout.flush()
    }

    fn show_completions(
        &self,
        stdout: &mut StdoutLock,
        completions: &[String],
        cursor_line: u16,
        num_lines: u16,
        completion_index: usize,
    ) -> io::Result<u16> {
        if completions.is_empty() {
            return Ok(0);
        }

        let n = num_lines - cursor_line;

        if n != 0 {
            queue!(stdout, cursor::MoveDown(n))?;
        }

        let mut width = 0;
        for c in completions.chunks(2) {
            let l = &c[0];
            let r = c.get(1);

            width = width.max(l.len() + r.map_or(0, |s| s.len()));
        }

        let completions = completions.chunks(2);

        let mut moved = 0;
        let mut idx = 0;
        for c in completions {
            let l = &c[0];
            let r = c.get(1);

            write!(
                stdout,
                "\r\n {}{l:0width$}\x1b[0m",
                if idx == completion_index {
                    "\x1b[38;5;6m"
                } else {
                    ""
                },
                width = width - r.map_or(0, |s| s.len()),
            )?;

            idx += 1;

            if let Some(r) = r {
                write!(
                    stdout,
                    " {}{r}\x1b[0m",
                    if idx == completion_index {
                        "\x1b[38;5;6m"
                    } else {
                        ""
                    },
                )?;
            }

            idx += 1;
            moved += 1;
        }

        if moved != 0 {
            queue!(stdout, cursor::MoveUp(moved))?;
        }

        if n != 0 {
            queue!(stdout, cursor::MoveUp(n),)?;
        }

        stdout.flush()?;

        Ok(moved)
    }

    /// Finds a word boundary, but only delimited by spaces.
    fn find_space_boundary(&self, data: &str, start: usize, backwards: bool) -> usize {
        let chars: Vec<char> = data.chars().collect();
        let (step, stop) = if backwards {
            (-1, 0)
        } else {
            (1, data.len() as i64 - 1)
        };

        let mut i = start as i64;

        while i != stop {
            i += step;

            if chars[i as usize] == ' ' {
                if start as i64 - i > 1 {
                    i -= step;
                }

                break;
            }
        }

        i as usize
    }

    /// Finds a word boundary.
    fn find_word_boundary(&self, data: &str, start: usize, backwards: bool) -> usize {
        let chars: Vec<char> = data.chars().collect();
        let (step, stop) = if backwards {
            (-1, 0)
        } else {
            (1, data.len() as i64 - 1)
        };

        let mut i = start as i64;

        while i != stop {
            i += step;

            if self.word_breaks.contains(chars[i as usize]) {
                if start as i64 - i > 1 {
                    i -= step;
                }

                break;
            }
        }

        i as usize
    }

    /// Moves the visual cursor to the appropriate position.
    fn move_to(
        &self,
        stdout: &mut StdoutLock,
        prompt_length: usize,
        cursor_line: &mut u16,
        end: usize,
    ) -> io::Result<()> {
        let size = terminal::size()?.0;

        let end = end + prompt_length;
        queue!(stdout, cursor::MoveToColumn(end as u16 % size as u16))?;

        let move_up = *cursor_line as i32 - end as i32 / size as i32;
        let m = move_up.unsigned_abs() as u16;
        #[allow(clippy::comparison_chain)]
        if move_up > 0 {
            queue!(stdout, cursor::MoveUp(m))?;
            *cursor_line -= m;
        } else if move_up < 0 {
            queue!(stdout, cursor::MoveDown(m))?;
            *cursor_line += m;
        }

        stdout.flush()
    }

    fn redraw(
        &self,
        stdout: &mut StdoutLock,
        data: &str,
        prompt_length: usize,
        cursor_line: &mut u16,
        num_lines: &mut u16,
        end: usize,
    ) -> io::Result<()> {
        self.clear(stdout, prompt_length, *cursor_line, *num_lines)?;

        let data = if let Some(h) = &self.highlight {
            (h.0)(data)
        } else {
            data.to_string()
        };

        let mut data = data.as_str();

        let size = terminal::size()?.0;

        let mut cap = (size as usize - prompt_length).min(data.len());
        write!(stdout, "{}", &data[0..cap])?;

        *num_lines = 0;
        *cursor_line = 0;
        let length = data.len() + prompt_length;
        if length > size as usize {
            loop {
                data = &data[cap..];
                if data.is_empty() {
                    break;
                }

                cap = (size as usize).min(data.len());
                write!(stdout, "\r\n{}", &data[0..cap])?;
                *num_lines += 1;
                *cursor_line += 1;
            }

            let end = end + prompt_length;
            queue!(stdout, cursor::MoveToColumn((end % size as usize) as u16))?;

            let move_up = *num_lines as i32 - (end / size as usize) as i32;
            let m = move_up.unsigned_abs() as u16;
            #[allow(clippy::comparison_chain)]
            if move_up > 0 {
                queue!(stdout, cursor::MoveUp(m))?;
                *cursor_line -= m;
            } else if move_up < 0 {
                queue!(stdout, cursor::MoveDown(m))?;
                *cursor_line += m;
            }
        } else if length == size as usize && end == data.len() {
            queue!(stdout, cursor::MoveDown(1), cursor::MoveToColumn(0))?;

            *num_lines += 1;
            *cursor_line += 1;
        } else {
            queue!(stdout, cursor::MoveToColumn((end + prompt_length) as u16))?;
        }

        stdout.flush()
    }

    fn clear(
        &self,
        stdout: &mut StdoutLock,
        prompt_length: usize,
        cursor_line: u16,
        num_lines: u16,
    ) -> io::Result<()> {
        if cursor_line != 0 {
            queue!(stdout, cursor::MoveUp(cursor_line),)?;
        }

        queue!(
            stdout,
            cursor::MoveToColumn(prompt_length as u16),
            terminal::Clear(terminal::ClearType::UntilNewLine),
        )?;

        if num_lines == 0 {
            return Ok(());
        }

        for _ in 0..num_lines {
            queue!(
                stdout,
                cursor::MoveDown(1),
                cursor::MoveToColumn(0),
                terminal::Clear(terminal::ClearType::CurrentLine),
            )?;
        }

        queue!(
            stdout,
            cursor::MoveUp(num_lines),
            cursor::MoveToColumn(prompt_length as u16),
        )?;

        Ok(())
    }
}

impl<'a, 'b, 'c, P: Display> Drop for Editor<'a, 'b, 'c, P> {
    fn drop(&mut self) {
        self.save_history().expect("failed to save history");
    }
}