repl-lang 1.1.1

Read-eval-print loop scaffolding: line editing, session state, and incremental input feed.
Documentation
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! A terminal-agnostic single-line editor with history and a kill buffer.

use alloc::{collections::VecDeque, string::String};

use crate::{
    Edit,
    text::{next_unit, prev_unit, text_width, word_left, word_right},
};

/// The editing state of one input line: its text, the cursor, a kill buffer,
/// and a bounded history of submitted lines.
///
/// `Editor` is the "line editing" part of a REPL with the terminal taken out.
/// It holds no file descriptors and draws nothing. The host translates key
/// events into [`Edit`] commands, calls [`apply`](Editor::apply), and redraws
/// from [`line`](Editor::line) and [`column`](Editor::column) when `apply`
/// reports a change. On Enter it calls [`submit`](Editor::submit), which hands
/// back the finished line and records it in the history. That split makes the
/// editor identical on every platform and testable without a terminal.
///
/// Positions are byte offsets into [`line`](Editor::line) and always fall on a
/// `char` boundary, so slicing the line at [`cursor`](Editor::cursor) is
/// always valid. The cursor moves in display units (a visible character plus
/// any combining marks attached to it), so it never separates a letter from its
/// accent.
///
/// # Memory
///
/// The line, the kill buffer, and every history slot are reused rather than
/// reallocated. Once the history has filled to capacity, submitting a line
/// recycles the oldest slot's buffer, so a long session settles into editing
/// and submitting without touching the allocator except to grow a buffer past
/// its previous high-water mark.
///
/// # Examples
///
/// ```
/// use repl_lang::{Edit, Editor};
///
/// let mut editor = Editor::new();
/// editor.insert("let x = 1");
/// assert_eq!(editor.submit(), "let x = 1");
/// assert_eq!(editor.line(), "");
///
/// // The submitted line is one step back in the history.
/// assert!(editor.apply(Edit::HistoryPrev));
/// assert_eq!(editor.line(), "let x = 1");
/// ```
#[derive(Clone, Debug)]
pub struct Editor {
    /// The line being edited.
    line: String,
    /// Byte offset of the cursor in `line`; always on a `char` boundary.
    cursor: usize,
    /// Text removed by the last kill command, for `Yank`.
    kill: String,
    /// The last line returned by `submit`; its buffer becomes the next line's.
    submitted: String,
    /// Submitted lines, oldest first.
    history: VecDeque<String>,
    /// Maximum number of history entries kept.
    capacity: usize,
    /// Index into `history` while browsing it with `HistoryPrev`/`HistoryNext`.
    browsing: Option<usize>,
    /// The entry being shown was the oldest and has since been dropped to make
    /// room, so `browsing` is `Some(0)` but the shown entry sits just before
    /// index 0: `HistoryNext` goes to index 0 and `HistoryPrev` has nowhere
    /// to go.
    shown_dropped: bool,
    /// The line being typed when browsing started, restored when browsing ends.
    draft: String,
}

impl Default for Editor {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Editor {
    /// The number of history entries [`Editor::new`] keeps.
    pub const DEFAULT_HISTORY: usize = 1000;

    /// Creates an empty editor that keeps the last
    /// [`DEFAULT_HISTORY`](Editor::DEFAULT_HISTORY) submitted lines.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let editor = Editor::new();
    /// assert_eq!(editor.line(), "");
    /// assert_eq!(editor.cursor(), 0);
    /// assert_eq!(editor.history().len(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::with_history(Self::DEFAULT_HISTORY)
    }

    /// Creates an empty editor that keeps at most `capacity` history entries.
    ///
    /// When the history is full, submitting a line drops the oldest entry. A
    /// capacity of `0` disables history: nothing is recorded and the history
    /// commands do nothing. No history memory is reserved up front; slots are
    /// allocated as lines are submitted, then recycled once the limit is
    /// reached.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::with_history(2);
    /// for line in ["a", "b", "c"] {
    ///     editor.insert(line);
    ///     editor.submit();
    /// }
    /// // Only the two most recent lines are kept, oldest first.
    /// assert!(editor.history().eq(["b", "c"]));
    /// ```
    #[must_use]
    pub fn with_history(capacity: usize) -> Self {
        Self {
            line: String::new(),
            cursor: 0,
            kill: String::new(),
            submitted: String::new(),
            history: VecDeque::new(),
            capacity,
            browsing: None,
            shown_dropped: false,
            draft: String::new(),
        }
    }

    /// The text of the line being edited.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("1 + 2");
    /// assert_eq!(editor.line(), "1 + 2");
    /// ```
    #[inline]
    #[must_use]
    pub fn line(&self) -> &str {
        &self.line
    }

    /// The cursor position as a byte offset into [`line`](Editor::line).
    ///
    /// The offset is always on a `char` boundary, so `&line[..cursor]` and
    /// `&line[cursor..]` are always valid. Use it to find the word under the
    /// cursor for completion; use [`column`](Editor::column) to place the
    /// terminal cursor.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::{Edit, Editor};
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("pri");
    /// assert_eq!(editor.cursor(), 3);
    ///
    /// // The text before the cursor is the prefix to complete.
    /// let prefix = &editor.line()[..editor.cursor()];
    /// assert_eq!(prefix, "pri");
    ///
    /// assert!(editor.apply(Edit::Home));
    /// assert_eq!(editor.cursor(), 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// The cursor's position in terminal columns, counted from the start of the
    /// line.
    ///
    /// This is the display width of the text before the cursor: wide characters
    /// (CJK ideographs, most emoji) count two columns and combining marks count
    /// none. After drawing the prompt and the line, a host moves the terminal
    /// cursor to `prompt_width + column()`.
    ///
    /// The width is computed on each call, in time linear in the text before
    /// the cursor.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("x = 世界");
    /// assert_eq!(editor.cursor(), 10); // bytes: 4 ASCII + 2 × 3
    /// assert_eq!(editor.column(), 8);  // columns: 4 ASCII + 2 × 2
    /// ```
    #[must_use]
    pub fn column(&self) -> usize {
        let before = &self.line[..self.cursor];
        // A recalled multi-line entry: count from the start of the cursor's
        // own line.
        let start = before.rfind('\n').map_or(0, |at| at + 1);
        text_width(&before[start..])
    }

    /// Applies one editing command and reports whether the line or the cursor
    /// changed.
    ///
    /// A command that cannot do anything — moving left at the start of the
    /// line, deleting at the end, yanking an empty kill buffer, inserting a
    /// control or bidirectional formatting character — leaves the editor untouched and returns `false`, so
    /// the host can skip a redraw or ring the bell.
    ///
    /// The kill commands replace the kill buffer with the text they remove;
    /// a kill that removes nothing leaves the buffer as it was.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::{Edit, Editor};
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("hello world");
    ///
    /// assert!(editor.apply(Edit::KillWordLeft));
    /// assert_eq!(editor.line(), "hello ");
    ///
    /// assert!(editor.apply(Edit::Home));
    /// assert!(editor.apply(Edit::Yank));
    /// assert_eq!(editor.line(), "worldhello ");
    /// assert_eq!(editor.cursor(), 5); // just past the yanked text
    ///
    /// // Commands with nothing to do report `false`.
    /// assert!(editor.apply(Edit::Home));
    /// assert!(!editor.apply(Edit::Left));
    /// assert!(!editor.apply(Edit::Insert('\t'))); // control characters are refused
    /// ```
    pub fn apply(&mut self, edit: Edit) -> bool {
        match edit {
            Edit::Insert(c) => self.insert_char(c),
            Edit::Backspace => self.backspace(),
            Edit::Delete => self.delete(),
            Edit::Left => self.move_to(prev_unit(&self.line, self.cursor)),
            Edit::Right => self.move_to(next_unit(&self.line, self.cursor)),
            Edit::WordLeft => self.move_to(word_left(&self.line, self.cursor)),
            Edit::WordRight => self.move_to(word_right(&self.line, self.cursor)),
            Edit::Home => self.move_to(0),
            Edit::End => self.move_to(self.line.len()),
            Edit::KillToStart => self.kill_range(0, self.cursor),
            Edit::KillToEnd => self.kill_range(self.cursor, self.line.len()),
            Edit::KillWordLeft => self.kill_range(word_left(&self.line, self.cursor), self.cursor),
            Edit::KillWordRight => {
                self.kill_range(self.cursor, word_right(&self.line, self.cursor))
            }
            Edit::Yank => self.yank(),
            Edit::HistoryPrev => self.history_prev(),
            Edit::HistoryNext => self.history_next(),
        }
    }

    /// Inserts `text` at the cursor, as a paste would, and reports whether
    /// anything was inserted.
    ///
    /// Control characters and bidirectional formatting characters in `text`
    /// are dropped, exactly as [`Edit::Insert`] refuses them one at a time;
    /// everything else is
    /// inserted in a single pass. A host that receives a multi-line paste
    /// should split it into lines and submit them one by one.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::{Edit, Editor};
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("fn main() {}");
    /// assert!(editor.apply(Edit::Left));
    /// editor.insert(" body ");
    /// assert_eq!(editor.line(), "fn main() { body }");
    ///
    /// // Control characters are dropped from pasted text.
    /// let mut editor = Editor::new();
    /// editor.insert("a\tb\u{1b}c");
    /// assert_eq!(editor.line(), "abc");
    /// assert!(!editor.insert("\n"));
    /// ```
    pub fn insert(&mut self, text: &str) -> bool {
        let before = self.line.len();
        for segment in text.split(is_refused) {
            self.line.insert_str(self.cursor, segment);
            self.cursor += segment.len();
        }
        self.line.len() != before
    }

    /// Empties the line and moves the cursor to the start, keeping the kill
    /// buffer and the history. Returns `true` if the line was not already
    /// empty.
    ///
    /// This is the editor half of an interrupt (`Ctrl-C`): abandon what is
    /// being typed and start over. If the history was being browsed, browsing
    /// ends and the line parked when it began is dropped as well.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("half-typed");
    /// assert!(editor.clear());
    /// assert_eq!(editor.line(), "");
    /// assert!(!editor.clear());
    /// ```
    pub fn clear(&mut self) -> bool {
        self.forget_draft();
        let changed = !self.line.is_empty();
        self.line.clear();
        self.cursor = 0;
        changed
    }

    /// Finishes the line: returns its text, records it in the history, and
    /// leaves the editor empty for the next line.
    ///
    /// A line is recorded unless it is blank (empty or only whitespace) or
    /// identical to the most recent history entry, and only if the history
    /// capacity is not `0`.
    ///
    /// Submitting while browsing the history submits the recalled line as
    /// edited; the line parked when browsing began is dropped. Either way the
    /// next [`HistoryPrev`](Edit::HistoryPrev) starts from the newest entry.
    ///
    /// The returned text stays borrowed from the editor, which keeps the
    /// buffer for reuse: the next submit recycles it as the following line.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::new();
    /// editor.insert("1 + 1");
    /// assert_eq!(editor.submit(), "1 + 1");
    ///
    /// // Blank lines and immediate repeats are not recorded.
    /// editor.insert("   ");
    /// assert_eq!(editor.submit(), "   ");
    /// editor.insert("1 + 1");
    /// editor.submit();
    /// assert_eq!(editor.history().len(), 1);
    /// ```
    pub fn submit(&mut self) -> &str {
        self.forget_draft();
        core::mem::swap(&mut self.line, &mut self.submitted);
        self.line.clear();
        self.cursor = 0;
        // Browsing ended above, so recording cannot move a browse position.
        let _dropped = record(&mut self.history, self.capacity, &self.submitted);
        &self.submitted
    }

    /// Records `line` in the history as if it had been submitted, without
    /// touching the line being edited.
    ///
    /// Use it to restore a history saved from an earlier session. The same
    /// rules as [`submit`](Editor::submit) apply: blank lines and repeats of
    /// the newest entry are skipped, and the oldest entry is dropped once the
    /// history is full.
    ///
    /// Bidirectional formatting characters are removed, and so are control
    /// characters, except the two a multi-line entry
    /// is made of: newlines and tabs are kept, so an entry such as
    /// `"let x =\n\t42"` comes back as it was entered instead of with its lines
    /// run together. A `"\r\n"` or a lone `'\r'` is kept as one `'\n'`.
    /// Everything else — escape (`ESC`), the other C0 and C1 controls, and
    /// `DEL` — is removed, so a recalled entry can never put a terminal
    /// control sequence into the line.
    ///
    /// Recording while the history is being browsed keeps the browse on the
    /// entry it shows. If that entry is the oldest and is dropped to make
    /// room, `HistoryPrev` has nothing older to go to and `HistoryNext` moves
    /// to the oldest entry that is left.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::{Edit, Editor};
    ///
    /// let saved = "let x = 1\nx * 2\n";
    /// let mut editor = Editor::new();
    /// for line in saved.lines() {
    ///     editor.add_history(line);
    /// }
    /// assert!(editor.apply(Edit::HistoryPrev));
    /// assert_eq!(editor.line(), "x * 2");
    ///
    /// // A multi-line entry keeps its lines; escape sequences lose their `ESC`.
    /// editor.add_history("fn f() {\r\n\treturn 1\r\n}\u{1b}[0m");
    /// assert_eq!(editor.history().next_back(), Some("fn f() {\n\treturn 1\n}[0m"));
    /// ```
    pub fn add_history(&mut self, line: &str) {
        if line.contains(|c: char| is_refused(c) && c != '\n' && c != '\t') {
            let clean = recallable(line);
            self.record(&clean);
        } else {
            self.record(line);
        }
    }

    /// The history, oldest entry first.
    ///
    /// Iterate it in reverse for newest-first, or write it out line by line to
    /// persist the history between sessions.
    ///
    /// # Examples
    ///
    /// ```
    /// use repl_lang::Editor;
    ///
    /// let mut editor = Editor::new();
    /// for line in ["first", "second"] {
    ///     editor.insert(line);
    ///     editor.submit();
    /// }
    /// assert_eq!(editor.history().next_back(), Some("second"));
    /// let saved: Vec<&str> = editor.history().collect();
    /// assert_eq!(saved, ["first", "second"]);
    /// ```
    pub fn history(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator + '_ {
        self.history.iter().map(String::as_str)
    }

    /// Moves the cursor, reporting whether it moved.
    #[inline]
    fn move_to(&mut self, pos: usize) -> bool {
        let moved = pos != self.cursor;
        self.cursor = pos;
        moved
    }

    fn insert_char(&mut self, c: char) -> bool {
        if is_refused(c) {
            return false;
        }
        self.line.insert(self.cursor, c);
        self.cursor += c.len_utf8();
        true
    }

    fn backspace(&mut self) -> bool {
        if self.cursor == 0 {
            return false;
        }
        let start = prev_unit(&self.line, self.cursor);
        self.line.replace_range(start..self.cursor, "");
        self.cursor = start;
        true
    }

    fn delete(&mut self) -> bool {
        let end = next_unit(&self.line, self.cursor);
        if end == self.cursor {
            return false;
        }
        self.line.replace_range(self.cursor..end, "");
        true
    }

    /// Moves `line[start..end]` into the kill buffer and leaves the cursor at
    /// `start`.
    fn kill_range(&mut self, start: usize, end: usize) -> bool {
        if start == end {
            return false;
        }
        self.kill.clear();
        self.kill.push_str(&self.line[start..end]);
        self.line.replace_range(start..end, "");
        self.cursor = start;
        true
    }

    fn yank(&mut self) -> bool {
        if self.kill.is_empty() {
            return false;
        }
        self.line.insert_str(self.cursor, &self.kill);
        self.cursor += self.kill.len();
        true
    }

    fn history_prev(&mut self) -> bool {
        let target = match self.browsing {
            None => match self.history.len().checked_sub(1) {
                Some(newest) => {
                    // Park the line being typed; `history_next` brings it back.
                    core::mem::swap(&mut self.line, &mut self.draft);
                    newest
                }
                None => return false,
            },
            Some(0) => return false,
            Some(index) => index - 1,
        };
        self.load(target);
        true
    }

    fn history_next(&mut self) -> bool {
        match self.browsing {
            None => false,
            Some(_) if self.shown_dropped => {
                self.load(0);
                true
            }
            Some(index) if index + 1 < self.history.len() => {
                self.load(index + 1);
                true
            }
            Some(_) => {
                self.restore_draft();
                true
            }
        }
    }

    /// Replaces the line with a copy of history entry `index`, cursor at the end.
    fn load(&mut self, index: usize) {
        self.line.clear();
        if let Some(entry) = self.history.get(index) {
            self.line.push_str(entry);
        }
        self.cursor = self.line.len();
        self.browsing = Some(index);
        self.shown_dropped = false;
    }

    /// Records `line` in the history, keeping an in-progress browse on the
    /// entry it shows.
    fn record(&mut self, line: &str) {
        if record(&mut self.history, self.capacity, line) {
            // The oldest entry was dropped, so every index shifts down by one.
            // If the dropped entry is the one being shown, the browse now sits
            // just before index 0.
            match self.browsing {
                Some(0) => self.shown_dropped = true,
                Some(index) => self.browsing = Some(index - 1),
                None => {}
            }
        }
    }

    /// Ends history browsing by bringing back the line that was being typed
    /// when it started.
    fn restore_draft(&mut self) {
        self.shown_dropped = false;
        if self.browsing.take().is_some() {
            core::mem::swap(&mut self.line, &mut self.draft);
            self.draft.clear();
            self.cursor = self.line.len();
        }
    }

    /// Ends history browsing and drops the parked draft: the recalled line,
    /// edited or not, is what the user chose to keep.
    fn forget_draft(&mut self) {
        self.browsing = None;
        self.shown_dropped = false;
        self.draft.clear();
    }
}

/// `line` as a history entry may hold it: newlines and tabs kept, `"\r\n"` and
/// a lone `'\r'` turned into `'\n'`, and every other control character and
/// every bidirectional formatting character removed.
fn recallable(line: &str) -> String {
    let mut clean = String::with_capacity(line.len());
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\r' if chars.peek() == Some(&'\n') => {}
            '\r' | '\n' => clean.push('\n'),
            '\t' => clean.push('\t'),
            c if is_refused(c) => {}
            c => clean.push(c),
        }
    }
    clean
}

/// Appends `line` to `history` under the editor's recording rules, recycling
/// the oldest entry's buffer once `capacity` is reached. Returns `true` if the
/// oldest entry was dropped to make room.
fn record(history: &mut VecDeque<String>, capacity: usize, line: &str) -> bool {
    if capacity == 0
        || line.trim().is_empty()
        || history.back().is_some_and(|newest| newest == line)
    {
        return false;
    }
    let dropped = history.len() >= capacity;
    let mut slot = if dropped {
        history.pop_front().unwrap_or_default()
    } else {
        String::new()
    };
    slot.clear();
    slot.push_str(line);
    history.push_back(slot);
    dropped
}

/// Characters that never enter the line by typing or pasting, and that a
/// history entry drops (apart from the newlines and tabs it keeps): every
/// control character, and the bidirectional formatting characters. The
/// latter are invisible and reorder how the text around them is displayed,
/// so a line holding them can show something other than what it contains.
fn is_refused(c: char) -> bool {
    c.is_control()
        || matches!(
            c,
            '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
        )
}

#[cfg(test)]
#[allow(unused_results)]
mod tests {
    use super::*;

    fn typed(text: &str) -> Editor {
        let mut editor = Editor::new();
        assert!(editor.insert(text));
        editor
    }

    #[test]
    fn test_insert_char_advances_cursor_by_utf8_len() {
        let mut editor = Editor::new();
        assert!(editor.apply(Edit::Insert('é')));
        assert_eq!(editor.cursor(), 2);
        assert!(editor.apply(Edit::Insert('世')));
        assert_eq!(editor.cursor(), 5);
        assert_eq!(editor.line(), "é世");
    }

    #[test]
    fn test_insert_control_char_is_refused() {
        let mut editor = Editor::new();
        for c in ['\n', '\r', '\t', '\u{1b}', '\u{7f}', '\u{85}'] {
            assert!(!editor.apply(Edit::Insert(c)), "{c:?} was accepted");
        }
        assert_eq!(editor.line(), "");
    }

    #[test]
    fn test_insert_in_middle_keeps_tail() {
        let mut editor = typed("ac");
        assert!(editor.apply(Edit::Left));
        assert!(editor.apply(Edit::Insert('b')));
        assert_eq!(editor.line(), "abc");
        assert_eq!(editor.cursor(), 2);
    }

    #[test]
    fn test_insert_str_only_controls_returns_false() {
        let mut editor = Editor::new();
        assert!(!editor.insert("\n\t\r"));
        assert!(!editor.insert(""));
    }

    #[test]
    fn test_backspace_at_start_returns_false() {
        let mut editor = typed("x");
        assert!(editor.apply(Edit::Home));
        assert!(!editor.apply(Edit::Backspace));
        assert_eq!(editor.line(), "x");
    }

    #[test]
    fn test_backspace_removes_whole_combining_unit() {
        let mut editor = typed("ae\u{0301}");
        assert!(editor.apply(Edit::Backspace));
        assert_eq!(editor.line(), "a");
        assert_eq!(editor.cursor(), 1);
    }

    #[test]
    fn test_delete_at_end_returns_false() {
        let mut editor = typed("x");
        assert!(!editor.apply(Edit::Delete));
    }

    #[test]
    fn test_delete_removes_unit_under_cursor() {
        let mut editor = typed("世界");
        assert!(editor.apply(Edit::Home));
        assert!(editor.apply(Edit::Delete));
        assert_eq!(editor.line(), "界");
        assert_eq!(editor.cursor(), 0);
    }

    #[test]
    fn test_left_right_at_bounds_return_false() {
        let mut editor = typed("ab");
        assert!(!editor.apply(Edit::Right));
        assert!(!editor.apply(Edit::End));
        assert!(editor.apply(Edit::Home));
        assert!(!editor.apply(Edit::Left));
        assert!(!editor.apply(Edit::Home));
    }

    #[test]
    fn test_column_counts_wide_and_zero_width() {
        let editor = typed("a世e\u{0301}");
        assert_eq!(editor.column(), 4);
    }

    #[test]
    fn test_kill_to_end_then_yank_round_trips() {
        let mut editor = typed("abc def");
        assert!(editor.apply(Edit::WordLeft));
        assert!(editor.apply(Edit::KillToEnd));
        assert_eq!(editor.line(), "abc ");
        assert!(!editor.apply(Edit::KillToEnd)); // nothing after the cursor
        assert!(editor.apply(Edit::Yank));
        assert_eq!(editor.line(), "abc def");
    }

    #[test]
    fn test_empty_kill_keeps_previous_kill_buffer() {
        let mut editor = typed("one two");
        assert!(editor.apply(Edit::KillWordLeft));
        assert!(!editor.apply(Edit::KillWordRight)); // at end: kills nothing
        assert!(editor.apply(Edit::Yank));
        assert_eq!(editor.line(), "one two");
    }

    #[test]
    fn test_kill_word_right_from_start() {
        let mut editor = typed("  alpha beta");
        assert!(editor.apply(Edit::Home));
        assert!(editor.apply(Edit::KillWordRight));
        assert_eq!(editor.line(), " beta");
        assert_eq!(editor.cursor(), 0);
    }

    #[test]
    fn test_yank_with_empty_kill_buffer_returns_false() {
        let mut editor = Editor::new();
        assert!(!editor.apply(Edit::Yank));
    }

    #[test]
    fn test_submit_returns_line_and_resets() {
        let mut editor = typed("print 1");
        assert_eq!(editor.submit(), "print 1");
        assert_eq!(editor.line(), "");
        assert_eq!(editor.cursor(), 0);
        assert!(editor.history().eq(["print 1"]));
    }

    #[test]
    fn test_submit_skips_blank_and_duplicate() {
        let mut editor = Editor::new();
        for line in ["a", "a", "", "  ", "b", "a"] {
            editor.insert(line);
            editor.submit();
        }
        assert!(editor.history().eq(["a", "b", "a"]));
    }

    #[test]
    fn test_history_capacity_zero_records_nothing() {
        let mut editor = Editor::with_history(0);
        editor.insert("x");
        assert_eq!(editor.submit(), "x");
        assert_eq!(editor.history().len(), 0);
        assert!(!editor.apply(Edit::HistoryPrev));
    }

    #[test]
    fn test_add_history_strips_control_characters_but_keeps_lines() {
        let mut editor = Editor::new();
        editor.add_history("a\tb\u{1b}[0m\u{7f}\u{9b}");
        editor.add_history("\n\t"); // only whitespace: blank, skipped
        editor.add_history("one\r\ntwo\rthree\n");
        assert!(editor.history().eq(["a\tb[0m", "one\ntwo\nthree\n"]));
        assert!(editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.line(), "one\ntwo\nthree\n");
        assert!(editor.apply(Edit::HistoryPrev));
        assert!(
            !editor
                .line()
                .contains(|c: char| c.is_control() && c != '\t' && c != '\n')
        );
    }

    #[test]
    fn test_add_history_multi_line_entry_does_not_merge_tokens() {
        // 1.0.0 stored "let x =\n42" as "let x =42" and "a\nb" as "ab".
        let mut editor = Editor::new();
        editor.add_history("a\nb");
        assert!(editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.submit(), "a\nb");
    }

    #[test]
    fn test_recalled_multi_line_entry_edits_by_line() {
        let mut editor = Editor::new();
        editor.add_history("ab\n\tcd");
        assert!(editor.apply(Edit::HistoryPrev));
        // The cursor's column counts from the start of its own line; the tab
        // is one column.
        assert_eq!(editor.column(), 3);
        assert!(editor.apply(Edit::Home));
        assert!(editor.apply(Edit::WordRight));
        assert_eq!(editor.cursor(), 2);
        assert_eq!(editor.column(), 2);
        // The newline is its own unit: one step over it, one backspace for it.
        assert!(editor.apply(Edit::Right));
        assert_eq!((editor.cursor(), editor.column()), (3, 0));
        assert!(editor.apply(Edit::Backspace));
        assert_eq!(editor.line(), "ab\tcd");
        assert_eq!(editor.column(), 2);
    }

    #[test]
    fn test_history_ring_drops_oldest_at_capacity() {
        let mut editor = Editor::with_history(3);
        for line in ["1", "2", "3", "4", "5"] {
            editor.add_history(line);
        }
        assert!(editor.history().eq(["3", "4", "5"]));
    }

    #[test]
    fn test_history_prev_next_restores_draft() {
        let mut editor = Editor::new();
        editor.add_history("old");
        editor.add_history("new");
        editor.insert("draft");

        assert!(editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.line(), "new");
        assert!(editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.line(), "old");
        assert!(!editor.apply(Edit::HistoryPrev)); // oldest reached
        assert!(editor.apply(Edit::HistoryNext));
        assert_eq!(editor.line(), "new");
        assert!(editor.apply(Edit::HistoryNext));
        assert_eq!(editor.line(), "draft");
        assert_eq!(editor.cursor(), 5);
        assert!(!editor.apply(Edit::HistoryNext)); // not browsing any more
    }

    #[test]
    fn test_history_prev_on_empty_history_returns_false() {
        let mut editor = typed("x");
        assert!(!editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.line(), "x");
    }

    #[test]
    fn test_editing_recalled_entry_leaves_history_intact() {
        let mut editor = Editor::new();
        editor.add_history("abc");
        assert!(editor.apply(Edit::HistoryPrev));
        assert!(editor.apply(Edit::Backspace));
        assert_eq!(editor.line(), "ab");
        assert!(editor.history().eq(["abc"]));
        assert_eq!(editor.submit(), "ab");
        assert!(editor.history().eq(["abc", "ab"]));
    }

    #[test]
    fn test_submit_while_browsing_submits_recalled_line() {
        let mut editor = Editor::new();
        editor.add_history("again");
        editor.insert("draft");
        assert!(editor.apply(Edit::HistoryPrev));
        assert_eq!(editor.submit(), "again");
        // The draft was discarded with the browse; the duplicate not recorded.
        assert_eq!(editor.line(), "");
        assert!(editor.history().eq(["again"]));
    }

    #[test]
    fn test_add_history_while_browsing_at_capacity_keeps_entry() {
        let mut editor = Editor::with_history(2);
        editor.add_history("a");
        editor.add_history("b");
        assert!(editor.apply(Edit::HistoryPrev)); // on "b" (index 1)
        editor.add_history("c"); // drops "a"; "b" is now index 0
        assert!(editor.apply(Edit::HistoryNext));
        assert_eq!(editor.line(), "c");
    }

    #[test]
    fn test_clear_ends_browse_and_empties_line() {
        let mut editor = Editor::new();
        editor.add_history("x");
        editor.insert("draft");
        assert!(editor.apply(Edit::HistoryPrev));
        assert!(editor.clear());
        assert_eq!(editor.line(), "");
        assert!(!editor.apply(Edit::HistoryNext));
    }

    #[test]
    fn test_submit_steady_state_reuses_buffers() {
        let mut editor = Editor::with_history(2);
        for line in ["aaaa", "bbbb", "cccc"] {
            editor.insert(line);
            editor.submit();
        }
        // Once the ring is full, a submit recycles the oldest slot.
        let before = editor
            .history()
            .map(str::as_ptr)
            .collect::<alloc::vec::Vec<_>>();
        editor.insert("dddd");
        editor.submit();
        let after = editor
            .history()
            .map(str::as_ptr)
            .collect::<alloc::vec::Vec<_>>();
        assert_eq!(after[0], before[1]);
        assert_eq!(after[1], before[0]);
    }
}