wasi-shell 1.0.17

A modular WASI-compatible shell with piping and redirection
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
use std::io::{self, Read, Write};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

const KEY_UP: u32 = 0x110001;
const KEY_DOWN: u32 = 0x110002;
const KEY_RIGHT: u32 = 0x110003;
const KEY_LEFT: u32 = 0x110004;
const KEY_HOME: u32 = 0x110005;
const KEY_END: u32 = 0x110006;
const KEY_DELETE: u32 = 0x110007;

// ---------------------------------------------------------------------------
// Platform-specific raw terminal mode
// ---------------------------------------------------------------------------

#[cfg(unix)]
struct RawModeGuard {
    original: libc::termios,
}

#[cfg(unix)]
impl RawModeGuard {
    fn enter() -> io::Result<Self> {
        let mut original: libc::termios = unsafe { std::mem::zeroed() };
        if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut original) } != 0 {
            return Err(io::Error::last_os_error());
        }
        let mut raw = original;
        raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
        raw.c_cc[libc::VMIN] = 1;
        raw.c_cc[libc::VTIME] = 0;
        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &raw) } != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Self { original })
    }
}

#[cfg(unix)]
impl Drop for RawModeGuard {
    fn drop(&mut self) {
        unsafe {
            libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &self.original);
        }
    }
}

// ---- Windows ----

#[cfg(windows)]
mod win32 {
    #[link(name = "kernel32")]
    unsafe extern "system" {
        pub fn GetStdHandle(nStdHandle: u32) -> isize;
        pub fn GetConsoleMode(hConsoleHandle: isize, lpMode: *mut u32) -> i32;
        pub fn SetConsoleMode(hConsoleHandle: isize, dwMode: u32) -> i32;
    }

    pub const STD_INPUT_HANDLE: u32 = 0xFFFF_FFF6; // (DWORD)-10
    pub const ENABLE_PROCESSED_INPUT: u32 = 0x0001;
    pub const ENABLE_LINE_INPUT: u32 = 0x0002;
    pub const ENABLE_ECHO_INPUT: u32 = 0x0004;
    pub const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200;
}

#[cfg(windows)]
struct RawModeGuard {
    handle: isize,
    original_mode: u32,
}

#[cfg(windows)]
impl RawModeGuard {
    fn enter() -> io::Result<Self> {
        let handle = unsafe { win32::GetStdHandle(win32::STD_INPUT_HANDLE) };
        if handle == -1 {
            return Err(io::Error::last_os_error());
        }
        let mut original_mode: u32 = 0;
        if unsafe { win32::GetConsoleMode(handle, &mut original_mode) } == 0 {
            return Err(io::Error::last_os_error());
        }
        let new_mode = (original_mode
            & !(win32::ENABLE_LINE_INPUT
                | win32::ENABLE_ECHO_INPUT
                | win32::ENABLE_PROCESSED_INPUT))
            | win32::ENABLE_VIRTUAL_TERMINAL_INPUT;
        if unsafe { win32::SetConsoleMode(handle, new_mode) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Self {
            handle,
            original_mode,
        })
    }
}

#[cfg(windows)]
impl Drop for RawModeGuard {
    fn drop(&mut self) {
        unsafe {
            win32::SetConsoleMode(self.handle, self.original_mode);
        }
    }
}

// ---- WASI ----

#[cfg(target_os = "wasi")]
struct RawModeGuard;

#[cfg(target_os = "wasi")]
impl RawModeGuard {
    fn enter() -> io::Result<Self> {
        Ok(Self)
    }
}

// ---------------------------------------------------------------------------
// LineHandler trait
// ---------------------------------------------------------------------------

/// Trait for handling lines read by [`LineReader`].
///
/// Implement this to inject command-execution logic into the REPL loop.
///
/// # Return values
///
/// - `Ok(LoopAction::Continue)` โ€” prompt for the next line.
/// - `Ok(LoopAction::Break)` โ€” exit the loop normally.
/// - `Err(msg)` โ€” print the error and continue.
pub trait LineHandler {
    fn handle_line(&self, line: &str) -> Result<LoopAction, String>;
}

/// Controls the REPL loop flow after a line is handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopAction {
    /// Continue reading the next line.
    Continue,
    /// Exit the REPL loop.
    Break,
}

// Blanket impl: closures that return Result<LoopAction, String>
impl<F> LineHandler for F
where
    F: Fn(&str) -> Result<LoopAction, String>,
{
    fn handle_line(&self, line: &str) -> Result<LoopAction, String> {
        self(line)
    }
}

// ---------------------------------------------------------------------------
// KeyEvent, KeyEventHandler, and LineBuffer
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyEvent {
    Char(char),
    Enter,
    Backspace,
    Delete,
    Up,
    Down,
    Left,
    Right,
    Home,
    End,
    CtrlA,
    CtrlE,
    CtrlU,
    CtrlK,
    CtrlW,
    CtrlD,
    CtrlC,
    Esc,
}

pub trait KeyEventHandler {
    fn on_key_event(&mut self, key: KeyEvent);
}

struct NoopKeyEventHandler;

impl KeyEventHandler for NoopKeyEventHandler {
    fn on_key_event(&mut self, _key: KeyEvent) {}
}

fn previous_grapheme_boundary(s: &str, cursor: usize) -> usize {
    s[..cursor]
        .grapheme_indices(true)
        .map(|(idx, _)| idx)
        .last()
        .unwrap_or(0)
}

fn next_grapheme_boundary(s: &str, cursor: usize) -> usize {
    if cursor >= s.len() {
        return s.len();
    }

    let mut iter = s[cursor..].grapheme_indices(true);
    iter.next();
    iter.next().map(|(idx, _)| cursor + idx).unwrap_or(s.len())
}

/// A stateful editor for a single line of text buffer.
pub struct LineBuffer {
    pub buffer: String,
    pub cursor_pos: usize,
}

impl LineBuffer {
    /// Create a new `LineBuffer` initialized for a new line.
    pub const fn new() -> Self {
        Self {
            buffer: String::new(),
            cursor_pos: 0,
        }
    }

    pub fn set_buffer(&mut self, text: String) {
        self.buffer = text;
        self.cursor_pos = self.buffer.len();
    }

    pub fn apply_key(&mut self, key: KeyEvent) {
        match key {
            KeyEvent::Char(ch) => {
                self.buffer.insert(self.cursor_pos, ch);
                self.cursor_pos += ch.len_utf8();
            }
            KeyEvent::Backspace => {
                if self.cursor_pos > 0 {
                    let start = previous_grapheme_boundary(&self.buffer, self.cursor_pos);
                    self.buffer.drain(start..self.cursor_pos);
                    self.cursor_pos = start;
                }
            }
            KeyEvent::Delete => {
                if self.cursor_pos < self.buffer.len() {
                    let end = next_grapheme_boundary(&self.buffer, self.cursor_pos);
                    self.buffer.drain(self.cursor_pos..end);
                }
            }
            KeyEvent::Left => {
                if self.cursor_pos > 0 {
                    self.cursor_pos = previous_grapheme_boundary(&self.buffer, self.cursor_pos);
                }
            }
            KeyEvent::Right => {
                if self.cursor_pos < self.buffer.len() {
                    self.cursor_pos = next_grapheme_boundary(&self.buffer, self.cursor_pos);
                }
            }
            KeyEvent::Home | KeyEvent::CtrlA => {
                self.cursor_pos = 0;
            }
            KeyEvent::End | KeyEvent::CtrlE => {
                self.cursor_pos = self.buffer.len();
            }
            KeyEvent::CtrlU => {
                self.buffer.clear();
                self.cursor_pos = 0;
            }
            KeyEvent::CtrlK => {
                self.buffer.truncate(self.cursor_pos);
            }
            KeyEvent::CtrlW => {
                if self.cursor_pos > 0 {
                    let before_cursor = &self.buffer[..self.cursor_pos];
                    let mut new_pos = 0;
                    let mut seen_word = false;
                    for (idx, grapheme) in before_cursor.grapheme_indices(true).rev() {
                        let is_space = grapheme.chars().all(char::is_whitespace);
                        if !seen_word && is_space {
                            continue;
                        }
                        if is_space {
                            new_pos = idx + grapheme.len();
                            break;
                        }
                        seen_word = true;
                        new_pos = idx;
                    }
                    self.buffer.drain(new_pos..self.cursor_pos);
                    self.cursor_pos = new_pos;
                }
            }
            KeyEvent::Esc => {}
            _ => {}
        }
    }
}

// ---------------------------------------------------------------------------
// History
// ---------------------------------------------------------------------------

pub trait History {
    fn push(&mut self, line: &str);
    fn len(&self) -> usize;
    fn get(&self, index: usize) -> Option<String>;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

pub struct InMemoryHistory {
    entries: Vec<String>,
    max_len: usize,
}

impl InMemoryHistory {
    pub const fn new(max_len: usize) -> Self {
        Self {
            entries: Vec::new(),
            max_len,
        }
    }
}

impl History for InMemoryHistory {
    fn push(&mut self, line: &str) {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            return;
        }
        if self.entries.last().map(|s| s.as_str()) == Some(trimmed) {
            return;
        }
        self.entries.push(trimmed.to_string());
        if self.entries.len() > self.max_len {
            self.entries.remove(0);
        }
    }

    fn len(&self) -> usize {
        self.entries.len()
    }

    fn get(&self, index: usize) -> Option<String> {
        self.entries.get(index).cloned()
    }
}

// ---------------------------------------------------------------------------
// LineEditor
// ---------------------------------------------------------------------------

/// A minimal line editor with command history.
///
/// Supports:
/// - Up/Down arrow keys to navigate command history
/// - Left/Right arrow keys to move the cursor within the line
/// - Home/End to jump to the beginning/end of the line
/// - Delete to remove the character under the cursor
/// - Backspace to remove the character before the cursor
/// - Ctrl-U to clear the line, Ctrl-K to kill to end of line
/// - Ctrl-W to delete the previous word
/// - Ctrl-A / Ctrl-E for Home / End
pub struct LineEditor<H: History = InMemoryHistory> {
    line_buffer: LineBuffer,
    history: H,
    history_idx: usize,
    saved_input: String,
    esc_buf: smallvec::SmallVec<[u8; 4]>,
}

impl LineEditor<InMemoryHistory> {
    /// Create a new `LineEditor` with the given maximum history size.
    pub const fn new(max_history: usize) -> Self {
        Self::with_history_and_len(InMemoryHistory::new(max_history), 0)
    }
}

impl<H: History> LineEditor<H> {
    pub fn with_history(history: H) -> Self {
        let history_idx = history.len();
        Self {
            line_buffer: LineBuffer::new(),
            history,
            history_idx,
            saved_input: String::new(),
            esc_buf: smallvec::SmallVec::new_const(),
        }
    }

    pub const fn with_history_and_len(history: H, len: usize) -> Self {
        Self {
            line_buffer: LineBuffer::new(),
            history,
            history_idx: len,
            saved_input: String::new(),
            esc_buf: smallvec::SmallVec::new_const(),
        }
    }

    pub fn buffer(&self) -> &str {
        &self.line_buffer.buffer
    }

    pub fn cursor_pos(&self) -> usize {
        self.line_buffer.cursor_pos
    }

    /// Prepares the internal state for a new line of input.
    pub fn start_new_line(&mut self) {
        self.line_buffer.buffer.clear();
        self.line_buffer.cursor_pos = 0;
        self.history_idx = self.history.len();
        self.saved_input.clear();
        self.esc_buf.clear();
    }

    pub fn input_char(&mut self, code: u32) -> Option<String> {
        self.input_char_with_handler(code, &mut NoopKeyEventHandler)
    }

    pub fn input_char_with_handler<K: KeyEventHandler>(
        &mut self,
        code: u32,
        handler: &mut K,
    ) -> Option<String> {
        // 1. Handle escape sequence state machine
        if code == 27 {
            self.esc_buf.clear();
            self.esc_buf.push(27);
            return None;
        }

        if !self.esc_buf.is_empty() {
            self.esc_buf.push(code as u8);
            let seq = self.esc_buf.as_slice();

            let key = match seq {
                [27, b'[', b'A'] => Some(KeyEvent::Up),
                [27, b'[', b'B'] => Some(KeyEvent::Down),
                [27, b'[', b'C'] => Some(KeyEvent::Right),
                [27, b'[', b'D'] => Some(KeyEvent::Left),
                [27, b'[', b'H'] => Some(KeyEvent::Home),
                [27, b'[', b'F'] => Some(KeyEvent::End),
                [27, b'[', b'3', b'~'] => Some(KeyEvent::Delete),
                _ => {
                    // Check if it's still potentially a valid prefix
                    if seq.len() >= 4 || (seq.len() == 2 && seq[1] != b'[') {
                        // Invalid or unsupported sequence
                        self.esc_buf.clear();
                        None
                    } else {
                        // Keep waiting for more bytes
                        return None;
                    }
                }
            };

            if let Some(k) = key {
                self.esc_buf.clear();
                return self.handle_key_event(k, handler);
            }
            // If the sequence was invalid, we fall through to process the current 'code'
        }

        // 2. Map single code to KeyEvent
        let key = match code {
            // Control characters
            1 => KeyEvent::CtrlA,
            3 => KeyEvent::CtrlC,
            4 => KeyEvent::CtrlD,
            5 => KeyEvent::CtrlE,
            8 | 127 => KeyEvent::Backspace,
            11 => KeyEvent::CtrlK,
            13 | 10 => KeyEvent::Enter,
            21 => KeyEvent::CtrlU,
            23 => KeyEvent::CtrlW,
            27 => KeyEvent::Esc,

            // Custom codes for special keys (defined by the caller/LineEditor)
            KEY_UP => KeyEvent::Up,
            KEY_DOWN => KeyEvent::Down,
            KEY_RIGHT => KeyEvent::Right,
            KEY_LEFT => KeyEvent::Left,
            KEY_HOME => KeyEvent::Home,
            KEY_END => KeyEvent::End,
            KEY_DELETE => KeyEvent::Delete,

            // Printable characters
            c if c >= 0x20 => match char::from_u32(c) {
                Some(ch) if !ch.is_control() => KeyEvent::Char(ch),
                _ => return None,
            },
            _ => return None,
        };

        self.handle_key_event(key, handler)
    }

    fn handle_key_event<K: KeyEventHandler>(
        &mut self,
        key: KeyEvent,
        handler: &mut K,
    ) -> Option<String> {
        handler.on_key_event(key);

        if key == KeyEvent::Enter {
            let final_line = self.line_buffer.buffer.clone();
            self.history.push(&final_line);
            self.start_new_line();
            return Some(final_line);
        }

        match key {
            KeyEvent::Up => {
                if !self.history.is_empty() && self.history_idx > 0 {
                    if self.history_idx == self.history.len() {
                        self.saved_input = self.line_buffer.buffer.clone();
                    }
                    self.history_idx -= 1;
                    if let Some(hist_line) = self.history.get(self.history_idx) {
                        self.line_buffer.set_buffer(hist_line);
                    }
                }
            }
            KeyEvent::Down => {
                if self.history_idx < self.history.len() {
                    self.history_idx += 1;
                    if self.history_idx == self.history.len() {
                        self.line_buffer.set_buffer(self.saved_input.clone());
                    } else if let Some(hist_line) = self.history.get(self.history_idx) {
                        self.line_buffer.set_buffer(hist_line);
                    }
                }
            }
            _ => {
                self.line_buffer.apply_key(key);
            }
        }

        None
    }

    /// Read a line interactively with arrow-key history navigation.
    ///
    /// Returns `Ok(Some(line))` on success, `Ok(None)` on EOF (Ctrl-D).
    pub fn read_line(
        &mut self,
        prompt: &str,
        cancel_token: Option<wasibox_core::CancellationToken>,
    ) -> io::Result<Option<String>> {
        let mut stdout = io::stdout();
        write!(stdout, "{}", prompt)?;
        stdout.flush()?;

        let _guard = RawModeGuard::enter()?;

        let mut reader = io::stdin();
        self.read_line_from(&mut reader, &mut stdout, prompt, cancel_token)
    }

    /// Read a line interactively using a provided reader.
    pub fn read_line_with_stdin(
        &mut self,
        prompt: &str,
        cancel_token: Option<wasibox_core::CancellationToken>,
        mut reader: Box<dyn Read>,
    ) -> io::Result<Option<String>> {
        let mut stdout = io::stdout();
        write!(stdout, "{}", prompt)?;
        stdout.flush()?;

        let _guard = RawModeGuard::enter()?;

        self.read_line_from(&mut reader, &mut stdout, prompt, cancel_token)
    }

    /// Run an interactive REPL loop, delegating each line to `handler`.
    ///
    /// The loop ends when:
    /// - The handler returns `Ok(LoopAction::Break)`
    /// - EOF is reached (Ctrl-D)
    /// - An I/O error occurs
    pub fn run_loop<P, L>(
        &mut self,
        prompt_fn: P,
        handler: &L,
        cancel_token: wasibox_core::CancellationToken,
    ) -> io::Result<()>
    where
        P: Fn() -> String,
        L: LineHandler,
    {
        loop {
            let prompt = prompt_fn();
            match self.read_line(&prompt, Some(cancel_token.clone()))? {
                None => break,
                Some(line) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    match handler.handle_line(trimmed) {
                        Ok(LoopAction::Continue) => {}
                        Ok(LoopAction::Break) => break,
                        Err(e) => {
                            eprintln!("{}", e);
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Run an interactive REPL loop using a provided reader.
    pub fn run_loop_with_stdin<P, L>(
        &mut self,
        prompt_fn: P,
        handler: &L,
        cancel_token: wasibox_core::CancellationToken,
        mut reader: Box<dyn Read>,
    ) -> io::Result<()>
    where
        P: Fn() -> String,
        L: LineHandler,
    {
        loop {
            let prompt = prompt_fn();
            let _guard = RawModeGuard::enter()?;
            match self.read_line_from(
                &mut reader,
                &mut io::stdout(),
                &prompt,
                Some(cancel_token.clone()),
            )? {
                None => break,
                Some(line) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    match handler.handle_line(trimmed) {
                        Ok(LoopAction::Continue) => {}
                        Ok(LoopAction::Break) => break,
                        Err(e) => {
                            eprintln!("{}", e);
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Testable REPL loop that reads from `reader` and writes to `writer`.
    #[cfg(test)]
    fn run_loop_from<R: Read, W: Write, L: LineHandler>(
        &mut self,
        reader: &mut R,
        writer: &mut W,
        prompt: &str,
        handler: &L,
        cancel_token: Option<wasibox_core::CancellationToken>,
    ) -> io::Result<()> {
        loop {
            write!(writer, "{}", prompt)?;
            writer.flush()?;
            match self.read_line_from(reader, writer, prompt, cancel_token.clone())? {
                None => break,
                Some(line) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    match handler.handle_line(trimmed) {
                        Ok(LoopAction::Continue) => {}
                        Ok(LoopAction::Break) => break,
                        Err(e) => {
                            writeln!(writer, "Error: {}", e)?;
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Core line-editing logic, reading bytes from `reader` and writing to `writer`.
    /// Separated from `read_line` so it can be tested with synthetic input.
    pub fn read_line_from<R: Read, W: Write>(
        &mut self,
        reader: &mut R,
        writer: &mut W,
        prompt: &str,
        cancel_token: Option<wasibox_core::CancellationToken>,
    ) -> io::Result<Option<String>> {
        self.start_new_line();

        loop {
            let b = {
                let mut buf = [0u8; 1];
                reader.read_exact(&mut buf)?;
                buf[0]
            };

            let code = match b {
                // Ctrl-D on empty line => EOF
                4 => {
                    if self.buffer().is_empty() {
                        write!(writer, "\r\n")?;
                        writer.flush()?;
                        return Ok(None);
                    }
                    4
                }
                // Ctrl-C => discard line
                3 => {
                    if let Some(token) = &cancel_token {
                        token.cancel();
                    }
                    write!(writer, "^C\r\n")?;
                    writer.flush()?;
                    self.start_new_line(); // Reset on ctrl-c
                    return Ok(Some(String::new()));
                }
                // ESC => start of escape sequence
                27 => {
                    let seq1 = {
                        let mut buf = [0u8; 1];
                        reader.read_exact(&mut buf)?;
                        buf[0]
                    };
                    if seq1 == b'[' {
                        let seq2 = {
                            let mut buf = [0u8; 1];
                            reader.read_exact(&mut buf)?;
                            buf[0]
                        };
                        match seq2 {
                            b'A' => KEY_UP,    // Up
                            b'B' => KEY_DOWN,  // Down
                            b'C' => KEY_RIGHT, // Right
                            b'D' => KEY_LEFT,  // Left
                            b'H' => KEY_HOME,  // Home
                            b'F' => KEY_END,   // End
                            b'3' => {
                                let seq3 = {
                                    let mut buf = [0u8; 1];
                                    reader.read_exact(&mut buf)?;
                                    buf[0]
                                };
                                if seq3 == b'~' {
                                    KEY_DELETE // Delete
                                } else {
                                    continue;
                                }
                            }
                            _ => continue,
                        }
                    } else {
                        continue;
                    }
                }
                other if other < 0x80 => other as u32,
                other if other >= 0xC0 && other <= 0xF7 => {
                    let mut bytes = vec![other];
                    let expected = if other >= 0xF0 {
                        4
                    } else if other >= 0xE0 {
                        3
                    } else {
                        2
                    };
                    while bytes.len() < expected {
                        let mut cb = [0u8; 1];
                        match reader.read_exact(&mut cb) {
                            Ok(_) => bytes.push(cb[0]),
                            Err(_) => return Ok(None),
                        }
                    }
                    match std::str::from_utf8(&bytes) {
                        Ok(s) => s.chars().next().map(|c| c as u32).unwrap_or(0xFFFD),
                        Err(_) => 0xFFFD,
                    }
                }
                _ => 0xFFFD,
            };

            let old_pos = self.cursor_pos();
            let old_len = self.buffer().len();

            if let Some(completed_line) = self.input_char(code) {
                write!(writer, "\r\n")?;
                writer.flush()?;
                return Ok(Some(completed_line));
            }

            // Redraw optimization
            if char::from_u32(code).is_some_and(|ch| !ch.is_control())
                && old_pos == old_len
                && self.cursor_pos() == self.buffer().len()
            {
                write!(writer, "{}", char::from_u32(code).unwrap())?;
                writer.flush()?;
            } else if code == KEY_LEFT && old_pos > self.cursor_pos() && old_pos > 0 {
                // Left
                let crossed = &self.buffer()[self.cursor_pos()..old_pos];
                write!(writer, "\x1b[{}D", UnicodeWidthStr::width(crossed))?;
                writer.flush()?;
            } else if code == KEY_RIGHT && old_pos < self.cursor_pos() && old_pos < old_len {
                // Right
                let crossed = &self.buffer()[old_pos..self.cursor_pos()];
                write!(writer, "\x1b[{}C", UnicodeWidthStr::width(crossed))?;
                writer.flush()?;
            } else {
                Self::redraw_line(writer, prompt, self.buffer(), self.cursor_pos())?;
            }
        }
    }

    /// Redraw the current line (clear and rewrite).
    fn redraw_line<W: Write>(
        writer: &mut W,
        prompt: &str,
        line: &str,
        cursor_pos: usize,
    ) -> io::Result<()> {
        write!(writer, "\r\x1b[K{}{}", prompt, line)?;
        let total_width = UnicodeWidthStr::width(prompt) + UnicodeWidthStr::width(line);
        let target_width =
            UnicodeWidthStr::width(prompt) + UnicodeWidthStr::width(&line[..cursor_pos]);
        if target_width < total_width {
            write!(writer, "\x1b[{}D", total_width - target_width)?;
        }
        writer.flush()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    /// Helper: build a byte sequence from a list of key inputs.
    fn keys(parts: &[&[u8]]) -> Cursor<Vec<u8>> {
        let mut buf = Vec::new();
        for part in parts {
            buf.extend_from_slice(part);
        }
        Cursor::new(buf)
    }

    const UP: &[u8] = b"\x1b[A";
    const DOWN: &[u8] = b"\x1b[B";
    const ENTER: &[u8] = b"\r";

    #[test]
    fn test_line_editor_basic() {
        let mut editor = LineEditor::new(0);

        assert!(editor.input_char('a' as u32).is_none());
        assert!(editor.input_char('b' as u32).is_none());
        assert_eq!(editor.buffer(), "ab");
        assert_eq!(editor.cursor_pos(), 2);

        assert!(editor.input_char(KEY_LEFT).is_none()); // Left
        assert_eq!(editor.cursor_pos(), 1);

        assert!(editor.input_char('c' as u32).is_none());
        assert_eq!(editor.buffer(), "acb");
        assert_eq!(editor.cursor_pos(), 2);

        assert!(editor.input_char(127).is_none()); // Backspace
        assert_eq!(editor.buffer(), "ab");
        assert_eq!(editor.cursor_pos(), 1);

        let result = editor.input_char(13); // Enter
        assert_eq!(result, Some("ab".to_string()));
    }

    #[test]
    fn test_line_editor_history() {
        let mut editor = LineEditor::new(10);
        editor.input_char('f' as u32);
        editor.input_char('i' as u32);
        editor.input_char('r' as u32);
        editor.input_char('s' as u32);
        editor.input_char('t' as u32);
        editor.input_char(13); // Enter saves "first"

        editor.input_char('s' as u32);
        editor.input_char('e' as u32);
        editor.input_char('c' as u32);
        editor.input_char('o' as u32);
        editor.input_char('n' as u32);
        editor.input_char('d' as u32);
        editor.input_char(13); // Enter saves "second"

        editor.input_char(KEY_UP); // Up
        assert_eq!(editor.buffer(), "second");

        editor.input_char(KEY_UP); // Up
        assert_eq!(editor.buffer(), "first");

        editor.input_char(KEY_DOWN); // Down
        assert_eq!(editor.buffer(), "second");

        editor.input_char(KEY_DOWN); // Down
        assert_eq!(editor.buffer(), ""); // Back to current
    }

    #[test]
    fn test_simple_input() {
        let mut reader = LineEditor::new(100);
        let mut input = keys(&[b"hello", ENTER]);
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("hello".to_string()));
    }

    #[test]
    fn test_eof_on_empty() {
        let mut reader = LineEditor::new(100);
        let mut input = Cursor::new(vec![4u8]); // Ctrl-D
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_history_up_arrow() {
        let mut reader = LineEditor::new(100);
        let mut out = Vec::new();

        // First command
        let mut input = keys(&[b"echo hello", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Second command: press Up then Enter (should recall "echo hello")
        let mut input = keys(&[UP, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("echo hello".to_string()));
    }

    #[test]
    fn test_history_up_down_arrow() {
        let mut reader = LineEditor::new(100);
        let mut out = Vec::new();

        // Enter two commands
        let mut input = keys(&[b"first", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        let mut input = keys(&[b"second", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Up twice => "first", Down once => "second", Enter
        let mut input = keys(&[UP, UP, DOWN, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("second".to_string()));
    }

    #[test]
    fn test_input_char_sequence() {
        let mut editor = LineEditor::new(10);
        editor.input_char('f' as u32);
        editor.input_char('i' as u32);
        editor.input_char('r' as u32);
        editor.input_char('s' as u32);
        editor.input_char('t' as u32);
        editor.input_char(13); // Enter saves "first"

        editor.input_char('s' as u32);
        editor.input_char('e' as u32);
        editor.input_char('c' as u32);
        editor.input_char('o' as u32);
        editor.input_char('n' as u32);
        editor.input_char('d' as u32);
        editor.input_char(13); // Enter saves "second"

        // Send Down arrow as [27, 91, 66]
        // History: ["first", "second"], idx starts at 2
        // Press Up twice to get to "first"
        editor.input_char(KEY_UP); // Up -> "second"
        editor.input_char(KEY_UP); // Up -> "first"
        assert_eq!(editor.buffer(), "first");

        // Now Down via sequence
        editor.input_char(27); // ESC
        editor.input_char(91); // '['
        editor.input_char(66); // 'B' -> Down
        assert_eq!(editor.buffer(), "second");
    }

    #[test]
    fn test_history_down_restores_current_input() {
        let mut reader = LineEditor::new(100);
        let mut out = Vec::new();

        // Enter a command into history
        let mut input = keys(&[b"old", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Type "new", press Up (recalls "old"), press Down (restores "new"), Enter
        let mut input = keys(&[b"new", UP, DOWN, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("new".to_string()));
    }

    #[test]
    fn test_history_dedup() {
        let mut reader = LineEditor::new(100);
        let mut out = Vec::new();

        // Enter same command twice
        let mut input = keys(&[b"dup", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        let mut input = keys(&[b"dup", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Up should recall "dup", another Up should NOT go further
        // (only one entry in history)
        let mut input = keys(&[UP, UP, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("dup".to_string()));
    }

    #[test]
    fn test_history_max_size() {
        let mut reader = LineEditor::new(3);
        let mut out = Vec::new();

        for cmd in &["aaa", "bbb", "ccc", "ddd"] {
            let mut input = keys(&[cmd.as_bytes(), ENTER]);
            reader
                .read_line_from(&mut input, &mut out, "$ ", None)
                .unwrap();
        }

        // Up 3 times should stop at "bbb" (oldest "aaa" was evicted)
        let mut input = keys(&[UP, UP, UP, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("bbb".to_string()));
    }

    #[test]
    fn test_backspace() {
        let mut reader = LineEditor::new(100);
        let mut input = keys(&[b"helloo", &[127], ENTER]);
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("hello".to_string()));
    }

    #[test]
    fn test_ctrl_u_clears_line() {
        let mut reader = LineEditor::new(100);
        let mut input = keys(&[b"garbage", &[21], b"clean", ENTER]); // Ctrl-U = 21
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("clean".to_string()));
    }

    #[test]
    fn test_empty_line_not_in_history() {
        let mut reader = LineEditor::new(100);
        let mut out = Vec::new();

        // Enter a real command
        let mut input = keys(&[b"real", ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Enter an empty line
        let mut input = keys(&[ENTER]);
        reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();

        // Up should still recall "real", not empty
        let mut input = keys(&[UP, ENTER]);
        out.clear();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("real".to_string()));
    }

    // โ”€โ”€ LineHandler / run_loop tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[test]
    fn test_run_loop_with_handler() {
        use std::sync::{Arc, Mutex};

        let executed = Arc::new(Mutex::new(Vec::new()));
        let exec_clone = Arc::clone(&executed);

        let handler = move |line: &str| -> Result<LoopAction, String> {
            exec_clone.lock().unwrap().push(line.to_string());
            Ok(LoopAction::Continue)
        };

        let mut reader = LineEditor::new(100);
        // Type two commands then Ctrl-D
        let mut input = keys(&[b"echo hello", ENTER, b"ls", ENTER, &[4]]);
        let mut out = Vec::new();
        reader
            .run_loop_from(&mut input, &mut out, "$ ", &handler, None)
            .unwrap();

        let cmds = executed.lock().unwrap();
        assert_eq!(cmds.len(), 2);
        assert_eq!(cmds[0], "echo hello");
        assert_eq!(cmds[1], "ls");
    }

    #[test]
    fn test_run_loop_break_on_exit() {
        let handler = |line: &str| -> Result<LoopAction, String> {
            if line == "exit" {
                Ok(LoopAction::Break)
            } else {
                Ok(LoopAction::Continue)
            }
        };

        let mut reader = LineEditor::new(100);
        let mut input = keys(&[b"cmd1", ENTER, b"exit", ENTER, b"cmd2", ENTER]);
        let mut out = Vec::new();
        reader
            .run_loop_from(&mut input, &mut out, "$ ", &handler, None)
            .unwrap();
        // Loop should have stopped after "exit"; "cmd2" is never processed.
    }

    #[test]
    fn test_run_loop_error_continues() {
        use std::sync::{Arc, Mutex};

        let count = Arc::new(Mutex::new(0u32));
        let count_clone = Arc::clone(&count);

        let handler = move |line: &str| -> Result<LoopAction, String> {
            *count_clone.lock().unwrap() += 1;
            if line == "fail" {
                Err("simulated error".to_string())
            } else {
                Ok(LoopAction::Continue)
            }
        };

        let mut reader = LineEditor::new(100);
        let mut input = keys(&[b"ok", ENTER, b"fail", ENTER, b"ok2", ENTER, &[4]]);
        let mut out = Vec::new();
        reader
            .run_loop_from(&mut input, &mut out, "$ ", &handler, None)
            .unwrap();

        // All three commands should have been processed (error doesn't stop loop)
        assert_eq!(*count.lock().unwrap(), 3);
    }

    #[test]
    fn test_run_loop_with_history_navigation() {
        use std::sync::{Arc, Mutex};

        let executed = Arc::new(Mutex::new(Vec::new()));
        let exec_clone = Arc::clone(&executed);

        let handler = move |line: &str| -> Result<LoopAction, String> {
            exec_clone.lock().unwrap().push(line.to_string());
            Ok(LoopAction::Continue)
        };

        let mut reader = LineEditor::new(100);
        // Enter "echo hello", then press Up+Enter to replay it
        let mut input = keys(&[
            b"echo hello",
            ENTER,
            UP,
            ENTER, // replay from history
            &[4],  // EOF
        ]);
        let mut out = Vec::new();
        reader
            .run_loop_from(&mut input, &mut out, "$ ", &handler, None)
            .unwrap();

        let cmds = executed.lock().unwrap();
        assert_eq!(cmds.len(), 2);
        assert_eq!(cmds[0], "echo hello");
        assert_eq!(cmds[1], "echo hello"); // replayed from history
    }

    #[test]
    fn test_run_loop_with_handle_parallel() {
        use crate::{ArcVecWriter, CommandRegistry, handle_parallel};
        use std::sync::{Arc, Mutex};

        let registry = Arc::new(CommandRegistry::with_builtins());
        let output = Arc::new(Mutex::new(Vec::<u8>::new()));

        let reg = Arc::clone(&registry);
        let out_ref = Arc::clone(&output);

        let handler = move |line: &str| -> Result<LoopAction, String> {
            if line == "exit" {
                return Ok(LoopAction::Break);
            }
            let results = handle_parallel(
                vec![line.to_string()],
                Box::new(std::io::empty()),
                Box::new(ArcVecWriter {
                    inner: Arc::clone(&out_ref),
                }),
                Arc::clone(&reg),
                wasibox_core::CancellationToken::new(),
            );
            for res in results {
                res?;
            }
            Ok(LoopAction::Continue)
        };

        let mut reader = LineEditor::new(100);
        // Run "echo hello", then Up+Enter to replay, then "exit"
        let mut input = keys(&[
            b"echo hello",
            ENTER,
            UP,
            ENTER, // replay "echo hello" via history
            b"exit",
            ENTER,
        ]);
        let mut term_out = Vec::new();
        reader
            .run_loop_from(&mut input, &mut term_out, "$ ", &handler, None)
            .unwrap();

        let buf = output.lock().unwrap();
        let result = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = result.trim().lines().collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], "hello");
        assert_eq!(lines[1], "hello"); // replayed from history
    }

    #[test]
    fn test_key_event_handler() {
        struct MockHandler {
            events: Vec<KeyEvent>,
        }
        impl KeyEventHandler for MockHandler {
            fn on_key_event(&mut self, key: KeyEvent) {
                self.events.push(key);
            }
        }

        let mut editor = LineEditor::new(10);
        let mut handler = MockHandler { events: Vec::new() };

        editor.input_char_with_handler('a' as u32, &mut handler);
        editor.input_char_with_handler('b' as u32, &mut handler);
        editor.input_char_with_handler(13, &mut handler);

        assert_eq!(
            handler.events,
            vec![KeyEvent::Char('a'), KeyEvent::Char('b'), KeyEvent::Enter,]
        );
    }

    #[test]
    fn test_unicode_japanese_input_char() {
        let mut editor = LineEditor::new(10);
        editor.input_char('ใ‚' as u32);
        assert_eq!(editor.buffer(), "ใ‚");
        assert_eq!(editor.input_char(13), Some("ใ‚".to_string()));
    }

    #[test]
    fn test_unicode_emoji_input_char() {
        let mut editor = LineEditor::new(10);
        editor.input_char('๐Ÿฆ€' as u32);
        assert_eq!(editor.buffer(), "๐Ÿฆ€");
        assert_eq!(editor.input_char(13), Some("๐Ÿฆ€".to_string()));
    }

    #[test]
    fn test_read_line_from_decodes_utf8_input() {
        let mut reader = LineEditor::new(10);
        let mut input = Cursor::new("echo ใ‚๐Ÿฆ€\r".as_bytes().to_vec());
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some("echo ใ‚๐Ÿฆ€".to_string()));
    }

    #[test]
    fn test_read_line_from_decodes_complex_emoji_input() {
        let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
        let mut reader = LineEditor::new(10);
        let mut input = Cursor::new(format!("echo {family}\r").into_bytes());
        let mut out = Vec::new();
        let result = reader
            .read_line_from(&mut input, &mut out, "$ ", None)
            .unwrap();
        assert_eq!(result, Some(format!("echo {family}")));
    }

    #[test]
    fn test_backspace_removes_complex_emoji_grapheme() {
        let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
        let mut editor = LineEditor::new(10);
        for ch in format!("aใ‚๐Ÿฆ€{family}").chars() {
            editor.input_char(ch as u32);
        }

        editor.input_char(127);
        assert_eq!(editor.buffer(), "aใ‚๐Ÿฆ€");

        editor.input_char(127);
        assert_eq!(editor.buffer(), "aใ‚");

        editor.input_char(127);
        assert_eq!(editor.buffer(), "a");
    }

    #[test]
    fn test_left_right_do_not_split_graphemes() {
        let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
        let mut editor = LineEditor::new(10);
        for ch in format!("a{family}b").chars() {
            editor.input_char(ch as u32);
        }

        editor.input_char(KEY_LEFT);
        editor.input_char(KEY_LEFT);
        editor.input_char('X' as u32);

        assert_eq!(editor.buffer(), format!("aX{family}b"));
    }

    #[test]
    fn test_coptic_codepoint_no_longer_collides_with_special_keys() {
        let mut editor = LineEditor::new(10);
        let coptic = char::from_u32(1001).unwrap();
        editor.input_char(1001);
        assert_eq!(editor.buffer(), coptic.to_string());
    }
}