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
//! normal/pending.rs — prompt effects (R7): one reducer consumer,
//! independent of the surface that opened the prompt. Editing,
//! incsearch, acceptance and cancellation all live here; the surfaces
//! only route keys to the shared `PendingInput`.
use strop_core::Range;
use strop_grammar::{self as grammar, Command, Parse};
use crate::editor::pending::{
PendingEffect, PendingEvent, PromptContext, SearchOrigin, TextPrompt,
};
use crate::editor::{input::ParserState, Editor, Key, Mode};
impl Editor {
/// A text line opened (`: / ? |`) with the typed entry state that
/// survived the crossing — counts, register, operator.
pub(crate) fn begin_text_line(&mut self, sigil: char, state: ParserState) {
self.cancel_pending();
let origin = SearchOrigin {
pane_index: self.active_pane,
pane: self.view().clone(),
revision: self.buf().revision(),
};
let context = match sigil {
':' => PromptContext::Ex(origin),
'/' | '?' => PromptContext::Search {
origin,
state,
backward: sigil == '?',
},
'|' => {
if self.buf().readonly {
self.message = "readonly buffer".into();
return;
}
let visual = matches!(
self.mode,
Mode::Visual | Mode::VisualLine | Mode::VisualBlock
);
let range = if visual {
let Some(range) = self.visual_range() else {
return;
};
range
} else {
let line = self.buf().line_of(self.head());
Range::charwise(
self.buf().line_start(line),
self.buf().line_start(line + 1).min(self.buf().len_bytes()),
)
};
PromptContext::Pipe {
origin,
range,
visual,
}
}
_ => unreachable!("Walker only emits text-line sigils"),
};
self.pending.open(TextPrompt::new(context));
}
/// The saved origin still describes this editor: same pane slot,
/// same document incarnation, unchanged revision. Service results
/// and edits invalidate it; delivery-time checks are the backstop.
pub(crate) fn pending_origin_valid(&self, origin: &SearchOrigin) -> bool {
self.active_pane == origin.pane_index
&& self
.panes
.get(origin.pane_index)
.is_some_and(|p| p.doc == origin.pane.doc)
&& self
.docs
.get(origin.pane.doc)
.is_some_and(|d| d.buf.revision() == origin.revision)
}
fn restore_prompt_origin(&mut self, origin: &SearchOrigin) -> bool {
if !self.pending_origin_valid(origin) {
return false;
}
// Never clamp/normalize: those operations would change saved
// anchors, duplicate cursors or a deliberately parked viewport.
self.panes[origin.pane_index] = origin.pane.clone();
true
}
/// Abort the open prompt (if any), restoring its origin first.
/// Called before anything replaces the pane/document/revision the
/// prompt was opened against — never on rejected service results.
pub(crate) fn cancel_pending(&mut self) {
if let PendingEffect::Aborted(prompt) = self.pending.reduce(PendingEvent::Cancel) {
self.resolution.cancel_preview();
self.restore_prompt_origin(prompt.origin());
}
}
pub(crate) fn feed_pending(&mut self, key: Key) {
self.feed_pending_event(PendingEvent::Key(key));
}
/// The shared prompt entrypoint: keys, pastes and completion events
/// all reduce through the same owner.
pub(crate) fn feed_pending_event(&mut self, event: PendingEvent) {
if self
.pending
.prompt()
.is_some_and(|p| !self.pending_origin_valid(p.origin()))
{
self.cancel_pending();
self.message = "input cancelled: document or pane changed".into();
return;
}
match self.pending.reduce(event) {
PendingEffect::None | PendingEffect::ModeChanged => {}
PendingEffect::Edited => self.incsearch_jump(),
PendingEffect::CompleteEx => self.ex_tab_complete(),
PendingEffect::Repaint => self.needs_repaint = true,
PendingEffect::Rejected(error) => self.message = error.into(),
PendingEffect::Aborted(prompt) => {
self.restore_prompt_origin(prompt.origin());
}
PendingEffect::Accepted(prompt) => self.accept_prompt(prompt),
}
}
fn accept_prompt(&mut self, prompt: TextPrompt) {
if !self.restore_prompt_origin(prompt.origin()) {
self.message = "input cancelled: document or pane changed".into();
return;
}
match prompt.context() {
PromptContext::Ex(_) => self.run_ex(prompt.body()),
PromptContext::Pipe { range, visual, .. } => {
if self.buf().readonly {
self.message = "readonly buffer".into();
return;
}
self.pipe_run(range.start.get(), range.end.get(), prompt.body());
if *visual {
self.mode = Mode::Normal;
}
}
PromptContext::Search { .. } => {
let command = match self.search_prompt_command(&prompt, true) {
Ok(Some(command)) => command,
Ok(None) => return,
Err(error) => {
self.message = error;
return;
}
};
if self.defer_resolution(
&command,
self.all_cursors(),
super::super::resolution::ResolutionPurpose::Execute,
) {
return;
}
// Runtime query errors must be discovered for every
// cursor BEFORE dispatch changes last_search, history
// or a register.
if let Err(error) = self.search_prompt_heads(&prompt, &command) {
self.message = error;
return;
}
self.dispatch_grammar(&command);
}
}
}
/// The typed command a search prompt currently stands for. An
/// empty body with `repeat_empty` reuses the last compiled query
/// (vim: `/⏎` / `?⏎`); the count/register/operator stay those of
/// THIS entry. Direction comes from the prompt's own sigil.
pub(crate) fn search_prompt_command(
&self,
prompt: &TextPrompt,
repeat_empty: bool,
) -> Result<Option<Command>, String> {
let Some((_, state)) = prompt.search() else {
return Ok(None);
};
let query = if prompt.body().is_empty() {
if !repeat_empty {
return Ok(None);
}
self.last_search
.as_ref()
.ok_or_else(|| "no previous search".to_string())?
.query
.clone()
} else {
grammar::CompiledQuery::compile(prompt.body(), false).map_err(|e| e.to_string())?
};
let target = if prompt.backward() == Some(true) {
grammar::Motion::SearchBackward(query)
} else {
grammar::Motion::Search(query)
};
Ok(Some(Command {
op: state.op,
register: state.register,
count: state.count(),
target: grammar::Target::Motion(target),
// Execution records the typed command for dot repeat.
keys: String::new(),
}))
}
/// Where every cursor of the saved origin lands for this command —
/// the exact execution resolver (`resolve_many`), so incsearch and
/// Enter can never disagree.
fn search_prompt_heads(
&self,
prompt: &TextPrompt,
command: &Command,
) -> Result<Vec<usize>, String> {
let (origin, _) = prompt.search().expect("search context");
let heads = origin.pane.sels.heads();
let resolved = self.resolved_many(command, &heads)?;
Ok(heads
.into_iter()
.zip(resolved)
.map(|(head, hit)| {
hit.map_or(head, |hit| {
self.clamp_pos(grammar::cursor_after(self.buf(), head, command, &hit))
})
})
.collect())
}
/// Live incsearch (vim parity): while a `/`/`?` prompt is open every
/// cursor tracks the pattern's match from the saved origin — typing
/// AND deleting re-resolve, all cursors at once. No match parks at
/// the origin (vim keeps position and reports E486).
pub(crate) fn incsearch_jump(&mut self) {
let Some(prompt) = self.pending.prompt().cloned() else {
return;
};
let Some((origin, _)) = prompt.search() else {
return;
};
if !self.pending_origin_valid(origin) {
return;
}
let command = self.search_prompt_command(&prompt, false);
self.restore_prompt_origin(origin);
let command = match command {
Ok(Some(command)) => command,
Ok(None) => {
self.resolution.cancel_preview();
return;
}
Err(error) => {
self.resolution.cancel_preview();
self.message = error;
return;
}
};
if self.defer_resolution(
&command,
origin.pane.sels.heads(),
super::super::resolution::ResolutionPurpose::IncSearch,
) {
return;
}
match self.search_prompt_heads(&prompt, &command) {
Ok(heads) => {
let mut heads = heads.into_iter();
self.set_head(heads.next().expect("primary selection"));
self.sels_mut().set_extras(heads);
self.clamp_cursor();
}
Err(error) => self.message = error,
}
}
/// Pending search pattern (incsearch highlight), if any: the `/` or
/// `?` prompt's body. Pipe and ex bodies never misread as patterns.
pub fn search_pattern(&self) -> Option<&str> {
let prompt = self.pending.prompt()?;
prompt.search()?;
(!prompt.body().is_empty()).then_some(prompt.body())
}
/// vim Enter: [count] lines down, first non-blank. With the blame
/// gutter on, Enter dives into the line's commit instead (0011 §3).
pub fn enter_pub(&mut self) {
if self.dive_from_blame() {
return;
}
let n = self.walker.state.count1.unwrap_or(1);
let line = (self.buf().line_of(self.head()) + n).min(self.buf().last_content_line());
let s = self.buf().line_start(line);
let e = self.buf().line_end(line);
let mut p = s;
while p < e
&& self
.buf()
.byte_at(p)
.is_some_and(|b| b == b' ' || b == b'\t')
{
p += 1;
}
self.set_head(p.min(e));
self.clamp_cursor();
}
pub fn run_motion(&mut self, keys: &str) {
match grammar::parse(keys) {
Parse::Complete(cmd) => self.move_cursor(&cmd),
Parse::QueryError(error) => self.message = error.to_string(),
Parse::Incomplete | Parse::Invalid => {}
}
}
}