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
use crossterm::event::{KeyCode, KeyModifiers};
use hjkl_engine::{CursorShape, Input as EngineInput, Key as EngineKey, VimMode};
use hjkl_form::TextFieldEditor;
use super::{App, SearchDir};
/// Walk backwards from `caret` to find the start of the token under the
/// caret. A token starts at the beginning of the string or after any
/// ASCII whitespace character.
fn find_token_start(line: &str, caret: usize) -> usize {
let bytes = line.as_bytes();
let mut i = caret;
while i > 0 {
let b = bytes[i - 1];
if b.is_ascii_whitespace() {
break;
}
i -= 1;
}
i
}
/// Build an [`hjkl_ex::ExpandContext`] from app state for tab-time inline
/// expansion. Same wiring as `build_expand_context` in ex_dispatch.rs.
/// cword/cwword stay None (see TODO in ex_dispatch.rs).
fn build_inline_expand_context(app: &App) -> hjkl_ex::ExpandContext<'_> {
let alt_path = app
.prev_active
.and_then(|i| app.slots.get(i))
.and_then(|s| s.filename.as_deref());
hjkl_ex::ExpandContext {
current_path: app.active().filename.as_deref(),
alt_path,
cword: None,
cwword: None,
cwd: None,
}
}
/// Active wildmenu state for the command-line prompt. `None` outside
/// completion (no Tab pressed yet, or after acceptance/cancel).
#[derive(Clone, Debug)]
pub(crate) struct CommandCompletion {
/// Original typed text the user can revert to with <Esc>.
pub original: String,
/// Sorted, dedup'd candidate strings.
pub candidates: Vec<String>,
/// Currently selected candidate index, or None on initial Tab when
/// we replaced with the longest common prefix (no specific selection yet).
pub selected: Option<usize>,
/// Byte range in the field text that the candidate replaces.
pub replace_range: std::ops::Range<usize>,
}
/// Replace the full text of a TextFieldEditor, leaving cursor at the end in
/// Insert mode. Uses the public `set_text` method (rebuilds the inner editor)
/// then calls `enter_insert_at_end`.
fn set_field_text(field: &mut TextFieldEditor, text: &str) {
field.set_text(text);
field.enter_insert_at_end();
}
impl App {
pub(crate) fn open_command_prompt(&mut self) {
let mut field = TextFieldEditor::new(true);
field.enter_insert_at_end();
self.command_field = Some(field);
}
/// Open the command prompt with `prefill` pre-typed and the cursor at end.
/// Used by the visual-mode `:` interceptor to seed `'<,'>` so the user
/// can append a range-aware command like `sort`.
pub(crate) fn open_command_prompt_with(&mut self, prefill: &str) {
let mut field = TextFieldEditor::new(true);
field.enter_insert_at_end();
for c in prefill.chars() {
let input = EngineInput {
key: EngineKey::Char(c),
ctrl: false,
alt: false,
shift: false,
};
field.handle_input(input);
}
self.command_field = Some(field);
}
pub(crate) fn handle_command_field_key(&mut self, key: crossterm::event::KeyEvent) {
// Intercept Tab / S-Tab BEFORE converting to EngineInput.
// crossterm sends KeyCode::BackTab for Shift+Tab (terminal sends \x1b[Z).
if key.code == KeyCode::Tab && !key.modifiers.contains(KeyModifiers::CONTROL) {
self.advance_command_completion(true);
return;
}
if key.code == KeyCode::BackTab {
self.advance_command_completion(false);
return;
}
let input: EngineInput = key.into();
let field = match self.command_field.as_mut() {
Some(f) => f,
None => return,
};
if input.key == EngineKey::Enter {
let text = field.text();
self.command_field = None;
self.command_completion = None;
self.dispatch_ex(text.trim());
return;
}
if input.key == EngineKey::Esc {
if let Some(comp) = self.command_completion.take() {
// Revert field text to the original typed text.
let field = self.command_field.as_mut().unwrap();
set_field_text(field, &comp.original);
return;
}
let field = self.command_field.as_mut().unwrap();
if field.text().is_empty() {
self.command_field = None;
} else if field.vim_mode() == VimMode::Insert {
field.enter_normal();
} else {
self.command_field = None;
}
return;
}
// Backspace on an empty prompt dismisses it (vim/neovim parity:
// the leading `:` itself counts as the dismissable prefix).
if input.key == EngineKey::Backspace
&& self
.command_field
.as_ref()
.is_some_and(|f| f.text().is_empty())
{
self.command_field = None;
self.command_completion = None;
return;
}
// Any other key while completion is active: commit current candidate
// (field text already has it) and clear completion state.
if self.command_completion.is_some() {
self.command_completion = None;
}
let field = self.command_field.as_mut().unwrap();
field.handle_input(input);
}
/// Advance (or initialize) wildmenu completion state.
/// `forward=true` means Tab (next); `false` means S-Tab (prev).
pub(crate) fn advance_command_completion(&mut self, forward: bool) {
if self.command_field.is_none() {
return;
}
if let Some(comp) = self.command_completion.as_mut() {
// Cycling phase — bump selected index.
if comp.candidates.is_empty() {
return;
}
let n = comp.candidates.len();
let new_idx = match comp.selected {
None => {
if forward {
0
} else {
n - 1
}
}
Some(i) if forward => (i + 1) % n,
Some(i) => (i + n - 1) % n,
};
comp.selected = Some(new_idx);
let candidate = comp.candidates[new_idx].clone();
let field = self.command_field.as_mut().unwrap();
let new_text = format!("{}{}", &field.text()[..comp.replace_range.start], candidate);
let new_replace_end = comp.replace_range.start + candidate.len();
comp.replace_range = comp.replace_range.start..new_replace_end;
set_field_text(field, &new_text);
return;
}
// First Tab — compute completion.
let line = {
let field = self.command_field.as_ref().unwrap();
field.text()
};
let caret = line.len(); // caret at end for completion
// Phase 7: tab-time inline expansion. If the token under the caret
// starts with a filename-expansion prefix (`%`, `#`, `<cword>`,
// `<cWORD>`), expand it in place so the user sees the literal path
// before pressing Enter.
{
let token_start = find_token_start(&line, caret);
let token = &line[token_start..caret];
if token.starts_with('%')
|| token.starts_with('#')
|| token.starts_with("<cword>")
|| token.starts_with("<cWORD>")
{
let ctx = build_inline_expand_context(self);
if let Some(expanded) = hjkl_ex::expand_filename(&ctx, token) {
let new_text =
format!("{}{}{}", &line[..token_start], expanded, &line[caret..]);
let field = self.command_field.as_mut().unwrap();
set_field_text(field, &new_text);
return; // don't fall through to candidate completion
}
}
}
let host_reg = super::ex_host_cmds::host_registry();
let editor_reg = hjkl_ex::default_registry::<crate::host::TuiHost>();
// Build arg sources.
let cwd = std::env::current_dir().ok();
let settings: Vec<String> = hjkl_ex::all_setting_names();
let buffers: Vec<String> = self
.slots
.iter()
.filter_map(|s| {
let name = s
.filename
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default();
if name.is_empty() { None } else { Some(name) }
})
.collect();
// TODO(phase6): wire register names from live editor state.
let registers: Vec<String> = {
let r = self.active().editor.registers();
let mut regs: Vec<String> = Vec::new();
if !r.unnamed.text.is_empty() {
regs.push("\"\"".into());
}
if !r.yank_zero.text.is_empty() {
regs.push("\"0".into());
}
for (i, slot) in r.delete_ring.iter().enumerate() {
if !slot.text.is_empty() {
regs.push(format!("\"{}", i + 1));
}
}
for (i, slot) in r.named.iter().enumerate() {
if !slot.text.is_empty() {
regs.push(format!("\"{}", (b'a' + i as u8) as char));
}
}
regs
};
let marks: Vec<String> = self
.active()
.editor
.marks()
.map(|(c, _)| c.to_string())
.collect();
let sources = hjkl_ex::ArgSources {
cwd: cwd.as_deref(),
settings: &settings,
buffers: &buffers,
registers: ®isters,
marks: &marks,
};
let comp = hjkl_ex::complete(&line, caret, &editor_reg, host_reg, &sources);
if comp.candidates.is_empty() {
return;
}
let original = line.clone();
if comp.candidates.len() == 1 {
// Single match — insert fully, close menu.
let cand = comp.candidates[0].clone();
let new_text = format!("{}{}", &line[..comp.replace_range.start], cand);
let field = self.command_field.as_mut().unwrap();
set_field_text(field, &new_text);
return; // no command_completion stored — menu stays closed
}
// Multiple matches — replace with longest common prefix and store state.
let lcp = hjkl_ex::longest_common_prefix(&comp.candidates);
let prefix_text = if lcp.len() > comp.replace_range.len() {
format!("{}{}", &line[..comp.replace_range.start], lcp)
} else {
line.clone()
};
{
let field = self.command_field.as_mut().unwrap();
set_field_text(field, &prefix_text);
}
self.command_completion = Some(CommandCompletion {
original,
candidates: comp.candidates,
selected: None,
replace_range: comp.replace_range,
});
}
pub(crate) fn open_search_prompt(&mut self, dir: SearchDir) {
let mut field = TextFieldEditor::new(true);
field.enter_insert_at_end();
self.search_field = Some(field);
self.search_dir = dir;
self.active_mut().editor.set_search_pattern(None);
}
pub(crate) fn cancel_search_prompt(&mut self) {
self.search_field = None;
let last = self.active().editor.last_search().map(str::to_owned);
match last {
Some(p) if !p.is_empty() => {
if let Ok(re) = regex::Regex::new(&p) {
self.active_mut().editor.set_search_pattern(Some(re));
} else {
self.active_mut().editor.set_search_pattern(None);
}
}
_ => self.active_mut().editor.set_search_pattern(None),
}
}
pub(crate) fn handle_search_field_key(&mut self, key: crossterm::event::KeyEvent) {
let input: EngineInput = key.into();
let field = match self.search_field.as_mut() {
Some(f) => f,
None => return,
};
if input.key == EngineKey::Enter {
let pattern = field.text();
self.search_field = None;
self.commit_search(&pattern);
return;
}
if input.key == EngineKey::Esc {
if field.text().is_empty() {
self.cancel_search_prompt();
return;
}
if field.vim_mode() == VimMode::Insert {
field.enter_normal();
} else {
self.cancel_search_prompt();
}
return;
}
// Backspace on an empty prompt dismisses it (vim/neovim parity:
// the leading `/` or `?` itself counts as the dismissable prefix).
if input.key == EngineKey::Backspace && field.text().is_empty() {
self.cancel_search_prompt();
return;
}
let dirty = field.handle_input(input);
if dirty {
self.live_preview_search();
}
}
pub(crate) fn live_preview_search(&mut self) {
let pattern = match self.search_field.as_ref() {
Some(f) => f.text(),
None => return,
};
if pattern.is_empty() {
self.active_mut().editor.set_search_pattern(None);
return;
}
let case_insensitive = self.active().editor.settings().ignore_case
&& !(self.active().editor.settings().smartcase
&& pattern.chars().any(|c| c.is_uppercase()));
let effective: std::borrow::Cow<'_, str> = if case_insensitive {
std::borrow::Cow::Owned(format!("(?i){pattern}"))
} else {
std::borrow::Cow::Borrowed(pattern.as_str())
};
match regex::Regex::new(&effective) {
Ok(re) => self.active_mut().editor.set_search_pattern(Some(re)),
Err(_) => self.active_mut().editor.set_search_pattern(None),
}
}
pub(crate) fn commit_search(&mut self, pattern: &str) {
let effective: Option<String> = if pattern.is_empty() {
self.active().editor.last_search().map(str::to_owned)
} else {
Some(pattern.to_owned())
};
let Some(p) = effective else {
self.active_mut().editor.set_search_pattern(None);
return;
};
let case_insensitive = self.active().editor.settings().ignore_case
&& !(self.active().editor.settings().smartcase && p.chars().any(|c| c.is_uppercase()));
let compile_src: std::borrow::Cow<'_, str> = if case_insensitive {
std::borrow::Cow::Owned(format!("(?i){p}"))
} else {
std::borrow::Cow::Borrowed(p.as_str())
};
match regex::Regex::new(&compile_src) {
Ok(re) => {
self.active_mut().editor.set_search_pattern(Some(re));
let forward = self.search_dir == SearchDir::Forward;
// Vim semantics for the / and ? prompts are asymmetric:
// /<pat><CR> — searches AT-OR-AFTER the cursor (cursor
// stays on the match if it's already on one)
// ?<pat><CR> — searches strictly BEFORE the cursor
// (always moves to a previous match)
// skip_current=false on forward prevents /<CR> from
// double-stepping past the cursor's match (counter went
// 0/3 → 2/3 because the cursor advanced past M1).
// skip_current=true on backward keeps the existing /?:
// behavior of jumping to the previous match.
if forward {
self.active_mut().editor.search_advance_forward(false);
} else {
self.active_mut().editor.search_advance_backward(true);
}
// search_advance_* moves the cursor without going through
// the engine's vim::step end-of-step hook, so the viewport
// doesn't auto-scroll. Reveal the cursor + sync the
// focused window's stored top_row so the next render
// shows the match instead of the old viewport.
self.active_mut().editor.ensure_cursor_in_scrolloff();
self.sync_viewport_from_editor();
self.active_mut().editor.set_last_search(Some(p), forward);
}
Err(e) => {
self.active_mut().editor.set_search_pattern(None);
self.status_message = Some(format!("E: bad search pattern: {e}"));
}
}
}
/// Dispatch a prompt-opening [`crate::keymap_actions::AppAction`].
///
/// Handles variants:
/// - OpenCommandPrompt (`:` — open the ex command prompt)
/// - OpenSearchPrompt (`/` / `?` — open incremental search)
pub(crate) fn dispatch_prompt_action(&mut self, action: crate::keymap_actions::AppAction) {
use crate::keymap_actions::AppAction;
match action {
// Guard: `@:` chord expects `:` as the register name, so
// pending_state.is_some() means this key is already claimed by
// the pending-state reducer (route_chord_key dispatched here via
// dispatch_keymap_in_mode). In that scenario the keymap itself
// should not have matched `:` (pending_state blocks the Normal
// trie path in route_chord_key), so this guard is defensive.
AppAction::OpenCommandPrompt if self.pending_state.is_none() => {
self.open_command_prompt();
}
AppAction::OpenCommandPrompt => {}
AppAction::OpenSearchPrompt(dir) => {
self.open_search_prompt(dir);
}
_ => {}
}
}
}
/// Resolve the cursor shape for an active prompt field (`command_field` or
/// `search_field`). Insert mode → Bar; anything else → Block.
pub(crate) fn prompt_cursor_shape(field: &TextFieldEditor) -> CursorShape {
match field.vim_mode() {
hjkl_form::VimMode::Insert => CursorShape::Bar,
_ => CursorShape::Block,
}
}