Skip to main content

read_loop/
read-loop.rs

1use modalkit::{
2    env::{
3        emacs::keybindings::{EmacsBindings, EmacsMachine},
4        mixed::MixedChoice,
5        vim::keybindings::{VimBindings, VimMachine},
6    },
7    key::TerminalKey,
8    keybindings::InputBindings,
9};
10use scansion::{ReadLine, ReadLineInfo};
11
12fn main() -> Result<(), std::io::Error> {
13    let mode = select_mode();
14    let mut rl = create_readline(mode)?;
15
16    println!("Reading input in {mode:?} mode; 'q' or 'quit' quits the loop.");
17
18    loop {
19        match rl.readline(Some("> ".to_string())) {
20            Ok(s) => {
21                match s.trim() {
22                    "q" | "quit" => {
23                        return Ok(());
24                    },
25                    _ => {
26                        println!("User typed: {:?}", s);
27                    },
28                }
29            },
30            Err(e) => {
31                // Print out editor error messages.
32                println!("{}", e);
33            },
34        }
35    }
36}
37
38fn select_mode() -> MixedChoice {
39    let mut args = std::env::args();
40    let _ = args.next();
41
42    match args.next() {
43        Some(arg) => {
44            match arg.as_str().trim() {
45                "e" | "emacs" => MixedChoice::Emacs,
46                "v" | "vim" => MixedChoice::Vim,
47                m => panic!("Unknown environment: {:?}", m),
48            }
49        },
50        None => MixedChoice::Vim,
51    }
52}
53
54fn create_readline(mode: MixedChoice) -> Result<ReadLine, std::io::Error> {
55    match mode {
56        MixedChoice::Emacs => {
57            let mut emacs = EmacsMachine::empty();
58            EmacsBindings::default().submit_on_enter().setup(&mut emacs);
59            ReadLine::new(emacs)
60        },
61        _ => {
62            let mut vi = VimMachine::<TerminalKey, ReadLineInfo>::empty();
63            VimBindings::default().submit_on_enter().setup(&mut vi);
64            ReadLine::new(vi)
65        },
66    }
67}