forked from nushell/reedline
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
267 lines (236 loc) · 8.29 KB
/
main.rs
File metadata and controls
267 lines (236 loc) · 8.29 KB
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
use {
crossterm::{
event::{poll, Event, KeyCode, KeyEvent, KeyModifiers},
terminal, Result,
},
nu_ansi_term::{Color, Style},
reedline::{
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
get_reedline_default_keybindings, get_reedline_edit_commands,
get_reedline_keybinding_modifiers, get_reedline_keycodes, get_reedline_prompt_edit_modes,
get_reedline_reedline_events, CompletionMenu, DefaultCompleter, DefaultHinter,
DefaultPrompt, EditMode, Emacs, ExampleHighlighter, FileBackedHistory, HistoryMenu,
Keybindings, Reedline, ReedlineEvent, Signal, Vi,
},
std::{
io::{stdout, Write},
time::Duration,
},
};
fn main() -> anyhow::Result<()> {
// quick command like parameter handling
let vi_mode = matches!(std::env::args().nth(1), Some(x) if x == "--vi");
let debug_mode = matches!(std::env::args().nth(2), Some(x) if x == "--debug");
let args: Vec<String> = std::env::args().collect();
// if -k is passed, show the events
if args.len() > 1 && args[1] == "-k" {
println!("Ready to print events (Abort with ESC):");
print_events()?;
println!();
return Ok(());
};
if args.len() > 1 && args[1] == "--list" {
get_all_keybinding_info();
println!();
return Ok(());
}
let history = Box::new(
FileBackedHistory::with_file(50, "history.txt".into())?, // .with_time(FormatTimeType::Time("[hour]:[minute]:[second]".to_string())),
);
let commands = vec![
"test".into(),
"clear".into(),
"exit".into(),
"history 1".into(),
"history 2".into(),
"history 3".into(),
"history 4".into(),
"history 5".into(),
"logout".into(),
"login".into(),
"hello world".into(),
"hello world reedline".into(),
"hello world something".into(),
"hello world another".into(),
"hello world 1".into(),
"hello world 2".into(),
"hello world 3".into(),
"hello world 4".into(),
"hello another very large option for hello word that will force one column".into(),
"this is the reedline crate".into(),
];
let completer = Box::new(DefaultCompleter::new_with_wordlen(commands.clone(), 2));
let mut line_editor = Reedline::create()?
.with_history(history)?
.with_completer(completer)
.with_quick_completions(false)
.with_highlighter(Box::new(ExampleHighlighter::new(commands)))
.with_hinter(Box::new(
DefaultHinter::default().with_style(Style::new().fg(Color::DarkGray)),
))
.with_ansi_colors(true);
// Adding default menus for the compiled reedline
let completion_menu = Box::new(CompletionMenu::default());
let history_menu = Box::new(HistoryMenu::default());
line_editor = line_editor
.with_menu(completion_menu)
.with_menu(history_menu);
let edit_mode: Box<dyn EditMode> = if vi_mode {
let mut normal_keybindings = default_vi_normal_keybindings();
let mut insert_keybindings = default_vi_insert_keybindings();
add_menu_keybindings(&mut normal_keybindings);
add_menu_keybindings(&mut insert_keybindings);
Box::new(Vi::new(insert_keybindings, normal_keybindings))
} else {
let mut keybindings = default_emacs_keybindings();
add_menu_keybindings(&mut keybindings);
Box::new(Emacs::new(keybindings))
};
line_editor = line_editor.with_edit_mode(edit_mode);
if debug_mode {
line_editor = line_editor.with_debug_mode();
}
let prompt = DefaultPrompt::new();
loop {
let sig = line_editor.read_line(&prompt);
match sig {
Ok(Signal::CtrlD) => {
break;
}
Ok(Signal::Success(buffer)) => {
if (buffer.trim() == "exit") || (buffer.trim() == "logout") {
break;
}
if buffer.trim() == "clear" {
line_editor.clear_screen()?;
continue;
}
if buffer.trim() == "history" {
line_editor.print_history()?;
continue;
}
println!("Our buffer: {}", buffer);
}
Ok(Signal::CtrlC) => {
// Prompt has been cleared and should start on the next line
}
Ok(Signal::CtrlL) => {
line_editor.clear_screen()?;
}
Err(err) => {
println!("Error: {:?}", err);
}
}
}
println!();
Ok(())
}
/// **For debugging purposes only:** Track the terminal events observed by [`Reedline`] and print them.
pub fn print_events() -> Result<()> {
stdout().flush()?;
terminal::enable_raw_mode()?;
let result = print_events_helper();
terminal::disable_raw_mode()?;
result
}
// this fn is totally ripped off from crossterm's examples
// it's really a diagnostic routine to see if crossterm is
// even seeing the events. if you press a key and no events
// are printed, it's a good chance your terminal is eating
// those events.
fn print_events_helper() -> Result<()> {
loop {
// Wait up to 5s for another event
if poll(Duration::from_millis(5_000))? {
// It's guaranteed that read() wont block if `poll` returns `Ok(true)`
let event = crossterm::event::read()?;
if let Event::Key(KeyEvent { code, modifiers }) = event {
match code {
KeyCode::Char(c) => {
println!(
"Char: {} code: {:#08x}; Modifier {:?}; Flags {:#08b}\r",
c,
u32::from(c),
modifiers,
modifiers
);
}
_ => {
println!(
"Keycode: {:?}; Modifier {:?}; Flags {:#08b}\r",
code, modifiers, modifiers
);
}
}
} else {
println!("Event::{:?}\r", event);
}
// hit the esc key to git out
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
} else {
// Timeout expired, no event for 5s
println!("Waiting for you to type...\r");
}
}
Ok(())
}
fn add_menu_keybindings(keybindings: &mut Keybindings) {
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('x'),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("history_menu".to_string()),
ReedlineEvent::MenuPageNext,
]),
);
keybindings.add_binding(
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
KeyCode::Char('x'),
ReedlineEvent::MenuPagePrevious,
);
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("completion_menu".to_string()),
ReedlineEvent::MenuNext,
]),
);
keybindings.add_binding(
KeyModifiers::SHIFT,
KeyCode::BackTab,
ReedlineEvent::MenuPrevious,
);
}
/// List all keybinding information
fn get_all_keybinding_info() {
println!("--Key Modifiers--");
for mods in get_reedline_keybinding_modifiers().iter() {
println!("{}", mods);
}
println!("\n--Modes--");
for modes in get_reedline_prompt_edit_modes().iter() {
println!("{}", modes);
}
println!("\n--Key Codes--");
for kcs in get_reedline_keycodes().iter() {
println!("{}", kcs);
}
println!("\n--Reedline Events--");
for rle in get_reedline_reedline_events().iter() {
println!("{}", rle);
}
println!("\n--Edit Commands--");
for edit in get_reedline_edit_commands().iter() {
println!("{}", edit);
}
println!("\n--Default Keybindings--");
for (mode, modifier, code, event) in get_reedline_default_keybindings() {
println!(
"mode: {}, keymodifiers: {}, keycode: {}, event: {}",
mode, modifier, code, event
)
}
}