ushell_input 0.1.0

Core of the shell framework.
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
#![allow(clippy::unbuffered_bytes)]

use heapless::{String, Vec};
/// InputParser is a generic, configurable command-line input handler designed for embedded or constrained environments. It supports:
/// - Autocompletion
/// - Input history
/// - Command parsing
/// - Special key handling (arrows, backspace, tab, etc.)
/// - Inline command help and shortcuts
///
/// It integrates with:
/// - Autocomplete
/// - History
/// - InputBuffer
/// - DisplayRenderer
use std::io::{self, Write};

use crate::autocomplete::Autocomplete;
use crate::history::History;
use crate::input::buffer::InputBuffer;
use crate::input::key_reader::Key;
use crate::input::key_reader::platform::read_key;
use crate::input::renderer::DisplayRenderer;

/// # Type Parameters
/// - `NC`: Maximum number of autocomplete candidates.
/// - `FNL`: Maximum number of characters used for autocomplete matching.
/// - `IML`: Maximum input buffer length.
/// - `HTC`: History capacity (number of entries).
/// - `HME`: Maximum entry length in history.
///
/// # Fields
/// - `shell_commands`: Static list of available shell commands and their descriptions.
/// - `shell_datatypes`: Description of supported argument types.
/// - `shell_shortcuts`: Description of available keyboard shortcuts.
/// - `autocomplete`: Autocomplete engine for input suggestions.
/// - `history`: Command history manager (heap-allocated or stack-based depending on feature flags).
/// - `buffer`: Input buffer for editing and cursor movement (heap-allocated or stack-based depending on feature flags).
/// - `prompt`: Static prompt string displayed to the user.
///
pub struct InputParser<
    'a,
    const NC: usize,
    const FNL: usize,
    const IML: usize,
    const HTC: usize,
    const HME: usize,
> {
    shell_commands: &'static [(&'static str, &'static str)],
    shell_datatypes: &'static str,
    shell_shortcuts: &'static str,
    autocomplete: Autocomplete<'a, NC, FNL>,

    #[cfg(feature = "heap-history")]
    history: Box<History<HTC, HME>>,
    #[cfg(not(feature = "heap-history"))]
    history: History<HTC, HME>,

    #[cfg(feature = "heap-input-buffer")]
    buffer: Box<InputBuffer<IML>>,
    #[cfg(not(feature = "heap-input-buffer"))]
    buffer: InputBuffer<IML>,

    prompt: &'static str,
}

impl<'a, const NC: usize, const FNL: usize, const IML: usize, const HTC: usize, const HME: usize>
    InputParser<'a, NC, FNL, IML, HTC, HME>
{
    /// Creates a new instance of `InputParser` with the provided shell configuration and prompt.
    ///
    /// # Parameters
    /// - `shell_commands`: A static list of command names and their descriptions.
    /// - `shell_datatypes`: A static string describing supported argument types.
    /// - `shell_shortcuts`: A static string listing available keyboard shortcuts.
    /// - `prompt`: The prompt string displayed to the user during input.
    ///
    /// # Behavior
    /// - Initializes autocomplete candidates from the command names.
    /// - Constructs the history and input buffer, using heap or stack allocation depending on feature flags.
    ///
    pub fn new(
        shell_commands: &'static [(&'static str, &'static str)],
        shell_datatypes: &'static str,
        shell_shortcuts: &'static str,
        prompt: &'static str,
    ) -> Self {
        let mut candidates = Vec::<&'a str, NC>::new();
        for &(first, _) in shell_commands {
            candidates.push(first).unwrap();
        }

        #[cfg(feature = "heap-history")]
        let history = Box::new(History::<HTC, HME>::new());
        #[cfg(not(feature = "heap-history"))]
        let history = History::<HTC, HME>::new();

        #[cfg(feature = "heap-input-buffer")]
        let buffer = Box::new(InputBuffer::<IML>::new());
        #[cfg(not(feature = "heap-input-buffer"))]
        let buffer = InputBuffer::<IML>::new();

        Self {
            shell_commands,
            shell_datatypes,
            shell_shortcuts,
            autocomplete: Autocomplete::<'a, NC, FNL>::new(candidates),
            history,
            buffer,
            prompt,
        }
    }

    /// Handles a single character input from the user.
    ///
    /// If the character is successfully inserted into the input buffer:
    /// - Updates the autocomplete engine with the first FNL characters.
    /// - Retrieves the current autocomplete suggestion.
    /// - If the suggestion differs from the input prefix, overwrites the buffer with the suggestion.
    ///
    /// If the character cannot be inserted (e.g., buffer full):
    /// - Displays a boundary marker and flushes stdout.
    ///
    /// Finally, renders the updated buffer and prompt to the display.
    ///
    pub fn handle_char(&mut self, ch: char) {
        if self.buffer.insert(ch) {
            let input_full = self.buffer.to_string();
            let autocomplete_input: String<FNL> = input_full.chars().take(FNL).collect();
            self.autocomplete.update_input(autocomplete_input);
            let suggestion = self.autocomplete.current_input();
            let input_prefix: String<FNL> = input_full.chars().take(FNL).collect();
            if suggestion != input_prefix {
                let mut new_buf = String::<IML>::new();
                new_buf.push_str(suggestion).ok();
                for c in input_full.chars().skip(FNL) {
                    let _ = new_buf.push(c);
                }
                self.buffer.overwrite(&new_buf);
            }
        } else {
            DisplayRenderer::boundary_marker();
            let _ = io::stdout().flush();
        }
        let cursor_pos = self.buffer.cursor().min(self.buffer.len());
        DisplayRenderer::render(self.prompt, &self.buffer.to_string(), cursor_pos);
    }

    /// Handles the backspace key event within the input buffer.
    ///
    /// If a character is successfully removed from the buffer:
    /// - Converts the buffer to a string.
    /// - Extracts up to `FNL` characters from the input.
    /// - Updates the autocomplete system with the truncated input.
    ///
    /// If no character can be removed (e.g., buffer is empty), triggers a bell sound.
    ///
    /// Finally, re-renders the prompt and buffer display to reflect the current state.
    ///
    pub fn handle_backspace(&mut self) {
        if self.buffer.backspace() {
            let input_full = self.buffer.to_string();
            let mut input_fn = String::<FNL>::new();
            for c in input_full.chars().take(FNL) {
                let _ = input_fn.push(c);
            }
            self.autocomplete.update_input(input_fn);
        } else {
            DisplayRenderer::bell();
        }
        DisplayRenderer::render(self.prompt, &self.buffer.to_string(), self.buffer.cursor());
    }

    /// Handles the tab key event to cycle through autocomplete suggestions.
    ///
    /// If `reverse` is `true`, triggers reverse cycling (Shift+Tab); otherwise, cycles forward.
    ///
    /// Updates the input buffer with the current autocomplete suggestion:
    /// - Takes up to `FNL` characters from the suggestion.
    /// - Appends the remainder of the original input (after `FNL`).
    ///
    /// Overwrites the buffer with the new input and re-renders the prompt and buffer display.
    ///
    pub fn handle_tab(&mut self, reverse: bool) {
        if reverse {
            self.autocomplete.cycle_backward();
        } else {
            self.autocomplete.cycle_forward();
        }
        let suggestion = self.autocomplete.current_input();
        let input_full = self.buffer.to_string();
        let mut new_buf = String::<IML>::new();
        for c in suggestion.chars().take(FNL) {
            let _ = new_buf.push(c);
        }
        for c in input_full.chars().skip(FNL) {
            let _ = new_buf.push(c);
        }
        self.buffer.overwrite(&new_buf);
        DisplayRenderer::render(self.prompt, &self.buffer.to_string(), self.buffer.cursor());
    }

    /// Finalizes the input process by returning the current buffer content as a string.
    ///
    /// Converts the internal buffer to a `String<IML>` and returns it without modification.
    ///
    pub fn finalize(&mut self) -> String<IML> {
        self.buffer.to_string()
    }

    /// Displays a formatted list of available shell commands.
    ///
    /// Prints each command name and its specification, aligned for readability.
    /// Calculates the maximum command name length to ensure consistent formatting.
    ///
    pub fn list_commands(&self) {
        println!("\r\nCommands:");
        let max_name_len = self
            .shell_commands
            .iter()
            .map(|(name, _)| name.len())
            .max()
            .unwrap_or(0);
        for (name, spec) in self.shell_commands {
            println!("{:>width$} : {}", name, spec, width = max_name_len);
        }
    }

    /// Displays all available shell commands, shortcuts, and argument types.
    ///
    /// - Calls `list_commands()` to print the command list.
    /// - Prints predefined shell shortcuts.
    ///
    fn list_all(&self) {
        self.list_commands();
        print!(
            "\nShortcuts:\n### : list all\n##  : list cmds\n#q  : exit\n#h  : list history\n#c  : clear history\n#N  : exec from history at index N\n"
        );
        print!("\nUser shortcuts:\n{}\n", self.shell_shortcuts);
        print!("\nArg types:\n{}\n", self.shell_datatypes);
    }

    /// Handles special hashtag-prefixed input commands.
    ///
    /// Supports the following commands:
    /// - `"q"`: Quits or exits the current context (returns `false`, no output).
    /// - `"#"`: Displays available commands via `list_all()`.
    /// - `"h"`: Shows command history.
    /// - `"c"`: Clears command history.
    /// - Numeric input: Attempts to retrieve a history entry by index.
    ///
    /// Returns a tuple:
    /// - `bool`: Indicates whether the command was handled.
    ///
    fn handle_hashtag(&mut self, input: &str) -> (bool, Option<String<IML>>) {
        match input {
            "q" => (false, None),
            "#" => {
                self.list_commands();
                (true, None)
            }
            "##" => {
                self.list_all();
                (true, None)
            }
            "h" => {
                self.history.show::<IML>();
                (true, None)
            }
            "c" => {
                self.history.clear();
                println!("History cleared");
                (true, None)
            }
            _ => {
                if let Ok(index) = input.parse::<usize>() {
                    if let Some(entry) = self.history.get(index) {
                        return (true, Some(entry));
                    } else {
                        println!("No history entry at index {}", index);
                    }
                } else {
                    println!("Not implemented");
                }
                (true, None)
            }
        }
    }

    /// Parses user input from `stdin` and handles interactive editing and command execution.
    ///
    /// Supports various key bindings for editing and navigation:
    /// - `Enter`: Finalizes input.
    /// - `Backspace`: Deletes character before cursor.
    /// - `Tab` / `Shift+Tab`: Cycles autocomplete suggestions.
    /// - `Ctrl+U`: Deletes from cursor to start of line.
    /// - `Ctrl+K`: Deletes from cursor to end of line.
    /// - `Ctrl+D`: Clears the entire buffer.
    /// - Arrow keys: Navigates through buffer or command history.
    /// - `Home` / `End`: Moves cursor to start/end of line.
    /// - `Delete`: Deletes character at cursor.
    ///
    /// After input is finalized:
    /// - If input starts with `#`, it is treated as a special command (e.g., history or help).
    /// - Otherwise, the input is executed via the provided `exec` callback and stored in history.
    ///
    /// Returns `true` if input was successfully handled or executed, `false` if the user requested to quit.
    ///
    pub fn parse_input<F>(&mut self, exec: F) -> bool
    where
        F: Fn(&String<IML>),
    {
        DisplayRenderer::render(self.prompt, "", 0);

        loop {
            let key = match read_key() {
                Ok(k) => k,
                Err(_) => continue,
            };

            match key {
                Key::Enter => {
                    println!();
                    break;
                }

                Key::Backspace => {
                    self.handle_backspace();
                }

                Key::Tab => {
                    self.handle_tab(false);
                }

                Key::ShiftTab => {
                    self.handle_tab(true);
                }

                Key::CtrlU => {
                    self.buffer.delete_to_start();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::CtrlK => {
                    self.buffer.delete_to_end();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::CtrlD => {
                    self.buffer.clear();
                    DisplayRenderer::render(self.prompt, "", 0);
                }

                Key::ArrowLeft => {
                    self.buffer.move_left();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::ArrowRight => {
                    self.buffer.move_right();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::ArrowUp => {
                    if let Some(cmd) = self.history.get_next_entry::<IML>() {
                        self.buffer.overwrite(&cmd);
                        DisplayRenderer::render(
                            self.prompt,
                            &self.buffer.to_string(),
                            self.buffer.cursor(),
                        );
                    }
                }

                Key::ArrowDown => {
                    if let Some(cmd) = self.history.get_prev_entry::<IML>() {
                        self.buffer.overwrite(&cmd);
                        DisplayRenderer::render(
                            self.prompt,
                            &self.buffer.to_string(),
                            self.buffer.cursor(),
                        );
                    }
                }

                Key::Home => {
                    self.buffer.move_home();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::End => {
                    self.buffer.move_end();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::Delete => {
                    self.buffer.delete_at_cursor();
                    DisplayRenderer::render(
                        self.prompt,
                        &self.buffer.to_string(),
                        self.buffer.cursor(),
                    );
                }

                Key::PageUp => {
                    if let Some(cmd) = self.history.get_first_entry::<IML>() {
                        self.buffer.overwrite(&cmd);
                        DisplayRenderer::render(
                            self.prompt,
                            &self.buffer.to_string(),
                            self.buffer.cursor(),
                        );
                    }
                }

                Key::PageDown => {
                    if let Some(cmd) = self.history.get_last_entry::<IML>() {
                        self.buffer.overwrite(&cmd);
                        DisplayRenderer::render(
                            self.prompt,
                            &self.buffer.to_string(),
                            self.buffer.cursor(),
                        );
                    }
                }

                Key::Char(c) => {
                    if Self::valid_byte(c as u8) {
                        self.handle_char(c);
                    }
                }

                _ => {}
            }
        }

        // Finalize input
        let mut retval = true;
        let final_input = self.finalize();

        if !final_input.is_empty() {
            if let Some(stripped) = final_input.strip_prefix('#') {
                let (new_retval, maybe_history_command) = self.handle_hashtag(stripped);
                retval = new_retval;
                if let Some(history_command) = maybe_history_command {
                    exec(&history_command);
                }
            } else {
                exec(&final_input);
                self.history.push(&final_input);
            }

            self.buffer.clear();
        }

        retval
    }

    /// Checks whether a given byte represents a valid ASCII character for input.
    ///
    /// A byte is considered valid if:
    /// - It is an ASCII character.
    /// - It is alphanumeric, a space, or falls within the printable ASCII range (`'!'` to `'~'`).
    ///
    /// Returns `true` if the byte is valid for input; otherwise, returns `false`.
    ///
    fn valid_byte(b: u8) -> bool {
        let c = b as char;
        c.is_ascii() && (c.is_ascii_alphanumeric() || c == ' ' || matches!(c, '!'..='~'))
    }
}

// ==================== TESTS =======================

#[cfg(test)]
mod input_parser_tests {
    use super::*;
    use heapless::String;

    // Test constants
    const TEST_COMMANDS: &[(&str, &str)] = &[
        ("help", "Display help information"),
        ("exit", "Exit the shell"),
        ("list", "List items"),
        ("test", "Run tests"),
        ("hello", "Say hello"),
    ];

    const TEST_DATATYPES: &str = "string, int, bool";
    const TEST_SHORTCUTS: &str = "Ctrl+C: Cancel\nCtrl+Z: Undo";
    const TEST_PROMPT: &str = "> ";

    // Type aliases for test configurations
    type TestParser = InputParser<'static, 10, 32, 128, 20, 64>;
    type SmallParser = InputParser<'static, 5, 16, 32, 5, 32>;

    // ==================== CONSTRUCTOR TESTS ====================

    #[test]
    fn test_new_creates_valid_parser() {
        let parser = TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Parser should be created successfully
        assert_eq!(parser.prompt, TEST_PROMPT);
    }

    #[test]
    fn test_new_with_empty_commands() {
        let empty_commands: &[(&str, &str)] = &[];
        let parser = InputParser::<10, 32, 128, 20, 64>::new(
            empty_commands,
            TEST_DATATYPES,
            TEST_SHORTCUTS,
            TEST_PROMPT,
        );

        assert_eq!(parser.prompt, TEST_PROMPT);
    }

    #[test]
    fn test_new_with_maximum_commands() {
        let max_commands: &[(&str, &str)] = &[
            ("cmd1", "desc1"),
            ("cmd2", "desc2"),
            ("cmd3", "desc3"),
            ("cmd4", "desc4"),
            ("cmd5", "desc5"),
        ];

        let parser = InputParser::<5, 16, 32, 5, 32>::new(
            max_commands,
            TEST_DATATYPES,
            TEST_SHORTCUTS,
            TEST_PROMPT,
        );

        assert_eq!(parser.prompt, TEST_PROMPT);
    }

    // ==================== HANDLE_CHAR TESTS ====================

    #[test]
    fn test_handle_char_single_character() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('h');
        let result = parser.finalize();

        assert!(result.starts_with('h'));
    }

    #[test]
    fn test_handle_char_multiple_characters() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "hello".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        // Autocomplete may modify input, so check it contains key characters
        assert!(result.contains("hel"));
        assert!(result.len() > 0);
    }

    #[test]
    fn test_handle_char_with_autocomplete() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type 'h' which should autocomplete to 'help' or 'hello'
        parser.handle_char('h');
        let result = parser.finalize();

        assert!(result.starts_with('h'));
        assert!(result.len() > 0);
    }

    #[test]
    fn test_handle_char_special_characters() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let special_chars = "!@#$%^&*()";
        for c in special_chars.chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        assert!(result.len() > 0);
    }

    #[test]
    fn test_handle_char_numbers() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "1234567890".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        assert!(result.contains("1234567890"));
    }

    #[test]
    fn test_handle_char_spaces() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "hello world".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        assert!(result.contains(' '));
    }

    #[test]
    fn test_handle_char_buffer_overflow() {
        let mut parser =
            SmallParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Try to fill buffer beyond capacity
        for _ in 0..50 {
            parser.handle_char('a');
        }

        let result = parser.finalize();
        // Buffer should be limited to its capacity
        assert!(result.len() <= 32);
    }

    // ==================== HANDLE_BACKSPACE TESTS ====================

    #[test]
    fn test_handle_backspace_removes_character() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('a');
        parser.handle_char('b');
        parser.handle_backspace();

        let result = parser.finalize();
        assert_eq!(result.as_str(), "a");
    }

    #[test]
    fn test_handle_backspace_on_empty_buffer() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Backspace on empty buffer should not crash
        parser.handle_backspace();

        let result = parser.finalize();
        assert!(result.is_empty());
    }

    #[test]
    fn test_handle_backspace_multiple_times() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "hello".chars() {
            parser.handle_char(c);
        }

        // Remove 3 characters
        parser.handle_backspace();
        parser.handle_backspace();
        parser.handle_backspace();

        let result = parser.finalize();
        // Due to autocomplete, result may differ, but should be shorter
        assert!(result.len() <= 5);
        assert!(result.len() > 0);
    }

    #[test]
    fn test_handle_backspace_clears_entire_input() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "test".chars() {
            parser.handle_char(c);
        }

        let current_len = parser.buffer.len();

        // Remove all characters - may need extra backspaces due to autocomplete
        for _ in 0..(current_len + 5) {
            parser.handle_backspace();
        }

        let result = parser.finalize();
        assert!(result.is_empty());
    }

    // ==================== HANDLE_TAB TESTS ====================

    #[test]
    fn test_handle_tab_forward_cycling() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('h');
        let first = parser.buffer.to_string();

        parser.handle_tab(false);
        let second = parser.buffer.to_string();

        // Tab should change the suggestion
        // May be same if only one match
        assert!(first.len() > 0 && second.len() > 0);
    }

    #[test]
    fn test_handle_tab_reverse_cycling() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('h');
        parser.handle_tab(true); // Shift+Tab

        let result = parser.finalize();
        assert!(result.starts_with('h'));
    }

    #[test]
    fn test_handle_tab_with_no_matches() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('z'); // No commands start with 'z'
        parser.handle_tab(false);

        let result = parser.finalize();
        assert!(result.len() > 0);
    }

    #[test]
    fn test_handle_tab_preserves_suffix() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type command and arguments
        for c in "h arg1 arg2".chars() {
            parser.handle_char(c);
        }

        parser.handle_tab(false);
        let result = parser.finalize();

        // Arguments should be preserved
        assert!(result.contains("arg"));
    }

    // ==================== FINALIZE TESTS ====================

    #[test]
    fn test_finalize_returns_buffer_content() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "test command".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        assert!(result.contains("test"));
    }

    #[test]
    fn test_finalize_empty_buffer() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let result = parser.finalize();
        assert!(result.is_empty());
    }

    #[test]
    fn test_finalize_multiple_calls() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "test".chars() {
            parser.handle_char(c);
        }

        let result1 = parser.finalize();
        let result2 = parser.finalize();

        // Multiple calls should return same content
        assert_eq!(result1, result2);
    }

    // ==================== HANDLE_HASHTAG TESTS ====================

    #[test]
    fn test_handle_hashtag_quit_command() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("q");

        assert!(!retval); // Should return false for quit
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_help_command() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("#");

        assert!(retval); // Should return true
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_full_help_command() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("##");

        assert!(retval);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_history_command() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("h");

        assert!(retval);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_clear_history() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Add some history
        parser
            .history
            .push(&String::<64>::try_from("test1").unwrap());
        parser
            .history
            .push(&String::<64>::try_from("test2").unwrap());

        let (retval, cmd) = parser.handle_hashtag("c");

        assert!(retval);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_numeric_index() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Add history entry
        let test_cmd = String::<64>::try_from("test command").unwrap();
        parser.history.push(&test_cmd);

        let (retval, _cmd) = parser.handle_hashtag("0");

        assert!(retval);
        // Should return the history command if it exists
    }

    #[test]
    fn test_handle_hashtag_invalid_index() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("999");

        assert!(retval);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_handle_hashtag_invalid_command() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let (retval, cmd) = parser.handle_hashtag("invalid");

        assert!(retval);
        assert!(cmd.is_none());
    }

    // ==================== VALID_BYTE TESTS ====================

    #[test]
    fn test_valid_byte_alphanumeric() {
        assert!(TestParser::valid_byte(b'a'));
        assert!(TestParser::valid_byte(b'Z'));
        assert!(TestParser::valid_byte(b'0'));
        assert!(TestParser::valid_byte(b'9'));
    }

    #[test]
    fn test_valid_byte_space() {
        assert!(TestParser::valid_byte(b' '));
    }

    #[test]
    fn test_valid_byte_special_characters() {
        assert!(TestParser::valid_byte(b'!'));
        assert!(TestParser::valid_byte(b'@'));
        assert!(TestParser::valid_byte(b'#'));
        assert!(TestParser::valid_byte(b'$'));
        assert!(TestParser::valid_byte(b'~'));
    }

    #[test]
    fn test_valid_byte_non_ascii() {
        assert!(!TestParser::valid_byte(128));
        assert!(!TestParser::valid_byte(255));
    }

    #[test]
    fn test_valid_byte_control_characters() {
        assert!(!TestParser::valid_byte(0)); // NULL
        assert!(!TestParser::valid_byte(1)); // SOH
        assert!(!TestParser::valid_byte(27)); // ESC
        assert!(!TestParser::valid_byte(127)); // DEL
    }

    #[test]
    fn test_valid_byte_printable_range() {
        // Test full printable range
        for b in b'!'..=b'~' {
            assert!(TestParser::valid_byte(b));
        }
    }

    // ==================== LIST_COMMANDS TESTS ====================

    #[test]
    fn test_list_commands_does_not_panic() {
        let parser = TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Should not panic
        parser.list_commands();
    }

    #[test]
    fn test_list_commands_with_empty_list() {
        let empty_commands: &[(&str, &str)] = &[];
        let parser = InputParser::<10, 32, 128, 20, 64>::new(
            empty_commands,
            TEST_DATATYPES,
            TEST_SHORTCUTS,
            TEST_PROMPT,
        );

        // Should not panic with empty commands
        parser.list_commands();
    }

    // ==================== INTEGRATION TESTS ====================

    #[test]
    fn test_autocomplete_behavior_with_matching_prefix() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type 'h' which should autocomplete to 'help' or 'hello'
        parser.handle_char('h');
        let result = parser.finalize();

        // Autocomplete should expand the input
        assert!(result.len() >= 1);
        assert!(result.starts_with('h'));
    }

    #[test]
    fn test_autocomplete_preserves_suffix_after_fnl() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type a full command that matches
        for c in "help".chars() {
            parser.handle_char(c);
        }

        // Add content beyond FNL characters
        for c in " these are arguments that should be preserved".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        // Arguments after FNL should be preserved
        assert!(result.contains("preserved"));
    }

    #[test]
    fn test_no_autocomplete_for_non_matching_input() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type characters that don't match any command
        for c in "xyz123".chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        // Should preserve original input when no match
        assert!(result.contains("xyz"));
    }

    #[test]
    fn test_full_input_cycle() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type a command - use one that doesn't trigger autocomplete changes
        for c in "xyz".chars() {
            parser.handle_char(c);
        }

        // Add some arguments
        parser.handle_char(' ');
        for c in "arg".chars() {
            parser.handle_char(c);
        }

        // Remove last character
        parser.handle_backspace();

        // Add it back
        parser.handle_char('g');

        let result = parser.finalize();
        // Check that we have a reasonable result with our input
        assert!(result.contains("xyz"));
        assert!(result.contains("arg"));
    }

    #[test]
    fn test_autocomplete_and_backspace() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('h');
        parser.handle_tab(false);
        parser.handle_backspace();
        parser.handle_backspace();

        let result = parser.finalize();
        // Should still have some content or be shorter
        assert!(result.len() < 10);
    }

    #[test]
    fn test_multiple_tab_cycles() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('h');

        // Cycle through multiple suggestions
        for _ in 0..3 {
            parser.handle_tab(false);
        }

        let result = parser.finalize();
        assert!(result.starts_with('h'));
    }

    #[test]
    fn test_mixed_operations() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        parser.handle_char('t');
        parser.handle_char('e');
        parser.handle_backspace();
        parser.handle_char('e');
        parser.handle_char('s');
        parser.handle_char('t');
        parser.handle_char(' ');
        parser.handle_tab(false);

        let result = parser.finalize();
        assert!(result.len() > 0);
    }

    // ==================== EDGE CASE TESTS ====================

    #[test]
    fn test_very_long_input() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Try to add more characters than buffer can hold
        for i in 0..150 {
            parser.handle_char(((i % 26) as u8 + b'a') as char);
        }

        let result = parser.finalize();
        assert!(result.len() <= 128); // Should be limited by IML
    }

    #[test]
    fn test_rapid_backspace_sequence() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        for c in "test".chars() {
            parser.handle_char(c);
        }

        // Rapid backspaces including past buffer start
        for _ in 0..10 {
            parser.handle_backspace();
        }

        let result = parser.finalize();
        assert!(result.is_empty());
    }

    #[test]
    #[allow(unused_comparisons)]
    fn test_tab_with_empty_input() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Tab on empty input
        parser.handle_tab(false);

        let result = parser.finalize();
        // Should handle gracefully
        assert!(result.len() >= 0);
    }

    #[test]
    fn test_special_characters_sequence() {
        let mut parser =
            TestParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        let special_seq = "!@#$%^&*()_+-={}[]|:;<>?,./";
        for c in special_seq.chars() {
            parser.handle_char(c);
        }

        let result = parser.finalize();
        assert!(result.len() > 0);
    }

    // ==================== BOUNDARY TESTS ====================

    #[test]
    fn test_exact_buffer_capacity() {
        let mut parser =
            SmallParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Fill exactly to capacity
        for _ in 0..32 {
            parser.handle_char('a');
        }

        let result = parser.finalize();
        assert!(result.len() <= 32);
    }

    #[test]
    fn test_autocomplete_at_fnl_boundary() {
        let mut parser =
            SmallParser::new(TEST_COMMANDS, TEST_DATATYPES, TEST_SHORTCUTS, TEST_PROMPT);

        // Type exactly FNL characters
        for _ in 0..16 {
            parser.handle_char('h');
        }

        parser.handle_tab(false);

        let result = parser.finalize();
        assert!(result.len() > 0);
    }

    #[test]
    fn test_history_at_capacity() {
        let mut parser = InputParser::<5, 16, 32, 3, 32>::new(
            TEST_COMMANDS,
            TEST_DATATYPES,
            TEST_SHORTCUTS,
            TEST_PROMPT,
        );

        // Fill history to capacity
        for i in 0..5 {
            let cmd = String::<32>::try_from(format!("cmd{}", i).as_str()).unwrap();
            parser.history.push(&cmd);
        }

        // Should handle gracefully when at capacity
        let (retval, _) = parser.handle_hashtag("h");
        assert!(retval);
    }
}