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
use anyhow::Result;
use crossterm::{
cursor::{Hide, MoveToColumn, MoveUp, Show},
event::{
self, Event, KeyCode, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags,
PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags, poll,
},
execute, queue,
style::{Color, Print, ResetColor, SetForegroundColor},
terminal::{Clear, ClearType, disable_raw_mode, enable_raw_mode},
};
use std::io::{self, Write};
use std::time::Duration;
/// Options for configuring inline input behavior
#[derive(Debug, Clone)]
pub struct InlineInputOpts {
placeholder: Option<String>,
escape_to_exit: bool,
}
impl InlineInputOpts {
/// Create new input options with default settings
pub fn new() -> Self {
Self {
placeholder: None,
escape_to_exit: false,
}
}
/// Set placeholder text that will be pre-filled in the input
pub fn placeholder<S: Into<String>>(mut self, text: S) -> Self {
self.placeholder = Some(text.into());
self
}
/// Enable escape-to-exit mode where:
/// - Escape exits the input
/// - Enter inserts newlines instead of submitting
/// - Shift+Enter still inserts newlines
pub fn escape_to_exit(mut self) -> Self {
self.escape_to_exit = true;
self
}
}
impl Default for InlineInputOpts {
fn default() -> Self {
Self::new()
}
}
pub struct InlinePrompt;
impl InlinePrompt {
/// Ask user for text input with optional configuration
pub fn input(message: &str, opts: Option<InlineInputOpts>) -> Result<String> {
let opts = opts.unwrap_or_default();
print!("{message} ");
// Initialize input with placeholder text if provided
let mut input = if let Some(ref placeholder) = opts.placeholder {
placeholder.clone()
} else {
String::new()
};
let mut stdout = io::stdout();
let terminal_width = crossterm::terminal::size()?.0 as usize;
let prompt_len = message.len() + 1; // message + " "
// Track current line and column position
let mut current_col = prompt_len;
enable_raw_mode()?;
// Always try to enable enhanced keyboard protocol
// Some terminals support it even if detection fails
let enhancement_result = queue!(
stdout,
PushKeyboardEnhancementFlags(
KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_EVENT_TYPES
)
);
let supports_keyboard_enhancement = enhancement_result.is_ok();
execute!(stdout, Show)?;
// If we have initial text, display it and update cursor tracking
if !input.is_empty() {
for ch in input.chars() {
if ch == '\n' {
execute!(stdout, Print("\n"), MoveToColumn(0))?;
current_col = 0;
} else {
execute!(stdout, Print(ch))?;
current_col += 1;
if current_col >= terminal_width {
current_col = 0;
}
}
}
}
loop {
if poll(Duration::from_millis(50))? {
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Enter => {
if opts.escape_to_exit {
// In escape-to-exit mode: Enter always inserts newline
input.push('\n');
execute!(stdout, Print("\n"), MoveToColumn(0))?;
current_col = 0;
} else if key.modifiers.contains(KeyModifiers::SHIFT) {
// Normal mode: Shift+Enter inserts newline
input.push('\n');
execute!(stdout, Print("\n"), MoveToColumn(0))?;
current_col = 0;
} else {
// Normal mode: Regular Enter submits
break;
}
}
KeyCode::Esc => {
if opts.escape_to_exit {
// In escape-to-exit mode: Esc submits
break;
} else {
// Normal mode: Esc cancels (return empty string)
input.clear();
break;
}
}
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
disable_raw_mode()?;
execute!(stdout, Show)?;
println!("\nExiting...");
std::process::exit(0);
}
KeyCode::Char(c) => {
input.push(c);
execute!(stdout, Print(c))?;
}
KeyCode::Backspace => {
if !input.is_empty() {
let last_char = input.chars().last().unwrap();
if last_char == '\n' {
// Removing a newline - move cursor up and to end of previous line
input.pop();
execute!(stdout, MoveUp(1))?;
// Calculate where to position cursor on the previous line
let lines: Vec<&str> = input.split('\n').collect();
if let Some(last_line) = lines.last() {
// Only add prompt_len if we're on the first line
let cursor_pos = if lines.len() == 1 {
prompt_len + last_line.len()
} else {
last_line.len()
};
execute!(stdout, MoveToColumn(cursor_pos as u16))?;
} else {
// If no lines left, we're back at the prompt
execute!(stdout, MoveToColumn(prompt_len as u16))?;
}
} else {
// Regular character backspace
input.pop();
// For now, just use simple backspace
// TODO: Handle line wrapping properly with newlines
execute!(stdout, Print("\x08 \x08"))?;
}
}
}
_ => {}
}
}
}
}
}
// Disable enhanced keyboard protocol if it was enabled
if supports_keyboard_enhancement {
queue!(stdout, PopKeyboardEnhancementFlags)?;
}
disable_raw_mode()?;
println!();
Ok(input)
}
/// Legacy method for backward compatibility
pub fn input_with_placeholder(message: &str, placeholder: Option<&str>) -> Result<String> {
let opts = placeholder.map(|p| InlineInputOpts::new().placeholder(p));
Self::input(message, opts)
}
/// Ask user for yes/no confirmation
pub fn confirm(message: &str, default: bool) -> Result<bool> {
let options = if default {
["Yes", "No"]
} else {
["No", "Yes"]
};
let selected = Self::select(message, &options)?;
Ok(if default {
selected == 0
} else {
selected == 1
})
}
/// Ask user to select from a list of options
pub fn select(message: &str, options: &[&str]) -> Result<usize> {
println!("{message}");
let mut selected = 0;
let mut stdout = io::stdout();
// Print all options initially
for (i, option) in options.iter().enumerate() {
if i == selected {
println!("❯ {option}");
} else {
println!(" {option}");
}
}
enable_raw_mode()?;
execute!(stdout, Hide)?;
loop {
if poll(Duration::from_millis(50))? {
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Up => {
selected = if selected > 0 {
selected - 1
} else {
options.len() - 1
};
Self::redraw_options(&mut stdout, options, selected)?;
}
KeyCode::Down => {
selected = (selected + 1) % options.len();
Self::redraw_options(&mut stdout, options, selected)?;
}
KeyCode::Enter => break,
KeyCode::Char('c')
if key
.modifiers
.contains(crossterm::event::KeyModifiers::CONTROL) =>
{
disable_raw_mode()?;
execute!(stdout, Show)?;
println!("\nExiting...");
std::process::exit(0);
}
_ => {}
}
}
}
}
}
disable_raw_mode()?;
execute!(stdout, Show)?;
Ok(selected)
}
fn redraw_options(stdout: &mut io::Stdout, options: &[&str], selected: usize) -> Result<()> {
// Move cursor up to the first option and to column 0
execute!(stdout, MoveUp(options.len() as u16), MoveToColumn(0))?;
// Redraw all options
for (i, option) in options.iter().enumerate() {
execute!(stdout, MoveToColumn(0), Clear(ClearType::CurrentLine))?;
if i == selected {
execute!(
stdout,
SetForegroundColor(Color::Cyan),
Print(format!("❯ {option}")),
ResetColor
)?;
} else {
execute!(stdout, Print(format!(" {option}")))?;
}
// Move to next line (except for the last option)
if i < options.len() - 1 {
execute!(stdout, Print("\n"))?;
}
}
// Ensure we end up at the correct position
execute!(stdout, Print("\n"))?;
Ok(())
}
}