strop-editor 0.1.1

strop — a modal text editor in Rust: see the cut before you make it
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
//! Normal mode: the grammar's home. Operators, motions, counts,
//! registers, dot-repeat, the ex-line — and the live preview query.

use strop_core::Range;
use strop_grammar::{self as grammar, Command, Op, Parse, Resolved};

use super::{Editor, Key, Mode};

impl Editor {
    pub(crate) fn feed_normal(&mut self, key: Key) {
        // readonly surfaces (git browser/blame/etc.): q closes, Enter
        // dives, motions and yank fall through, edits refuse (0001 §3)
        if self.buf().readonly {
            return self.feed_readonly(key);
        }
        if !self.pending.is_empty() {
            return self.feed_pending(key);
        }
        let Key::Char(c) = key else {
            return;
        };
        match c {
            '1'..='9' => self.pending.push(c),
            '0' => self.run_motion("0"),
            'h' | 'j' | 'k' | 'l' | 'w' | 'b' | 'e' | 'W' | 'B' | 'E' | '$' | 'G' | '%' => {
                self.run_motion(&c.to_string())
            }
            'g' | 'd' | 'y' | 'c' | 'f' | 'F' | 't' | 'T' | '/' | ':' | '"' | 'r' | '>' | '<'
            | ' ' | '[' | ']' => self.pending.push(c),
            // aliases — dot-repeat replays the alias key itself
            'D' => self.alias("D", "d$"),
            'C' => self.alias("C", "c$"),
            'Y' => self.alias("Y", "yy"),
            's' => self.alias("s", "cl"),
            'X' => self.alias("X", "dh"),
            'i' => self.enter_insert_from("i"),
            'a' => {
                self.cursor =
                    (self.cursor + 1).min(self.buf().line_end(self.buf().line_of(self.cursor)));
                self.enter_insert_from("a");
            }
            'A' => {
                self.cursor = self.buf().line_end(self.buf().line_of(self.cursor));
                self.enter_insert_from("A");
            }
            'o' => {
                let indent = self.auto_indent_full_line();
                let end = self.buf().line_end(self.buf().line_of(self.cursor));
                let text = format!("\n{indent}");
                self.buf_mut().insert(end, &text);
                self.cursor = end + text.len();
                self.enter_insert_from("o");
                // dot-repeat replays 'o', which re-derives the indent —
                // recording it too would double it
            }
            'O' => {
                let indent = self.auto_indent_full_line();
                let start = self.buf().line_start(self.buf().line_of(self.cursor));
                let text = format!("{indent}\n");
                self.buf_mut().insert(start, &text);
                self.cursor = start + indent.len();
                self.enter_insert_from("O");
                // same as 'o': indent is derived, not recorded
            }
            'x' => {
                let end =
                    (self.cursor + 1).min(self.buf().line_end(self.buf().line_of(self.cursor)));
                if end > self.cursor {
                    let range = Range::charwise(self.cursor, end);
                    let text = self.buf_mut().delete(range);
                    self.set_register(None, text, false);
                    self.flash(range);
                    self.last_cmd_keys = "x".into();
                    self.last_insert = None;
                }
            }
            'p' => {
                self.paste(None, false);
                self.last_cmd_keys = "p".into();
                self.last_insert = None;
            }
            'P' => {
                self.paste(None, true);
                self.last_cmd_keys = "P".into();
                self.last_insert = None;
            }
            'v' => {
                self.mode = Mode::Visual;
                self.anchor = self.cursor;
            }
            'V' => {
                self.mode = Mode::VisualLine;
                self.anchor = self.cursor;
            }
            'J' => self.join_lines(),
            '.' => self.dot_repeat(),
            'u' => self.message = "undo arrives with the undo tree (M4)".into(),
            _ => {}
        }
    }

    /// Alias keys (D → d$, …): execute the expansion, remember the alias
    /// so dot-repeat replays through the same path.
    fn alias(&mut self, alias_key: &str, expansion: &str) {
        self.feed_text(expansion);
        self.last_cmd_keys = alias_key.into();
    }

    fn feed_pending(&mut self, key: Key) {
        let is_ex = self.pending.starts_with(':');
        let is_search = !is_ex && self.pending.contains('/');
        match key {
            Key::Esc => self.pending.clear(),
            Key::Backspace => {
                self.pending.pop();
            }
            Key::Enter if is_ex => self.run_ex(),
            Key::Enter if is_search => {
                self.pending.push('\r');
                self.resolve_pending();
            }
            Key::Enter => self.pending.clear(),
            Key::Up | Key::Down | Key::Tab | Key::Backtab => {}
            Key::Char(c) => {
                // Space leader (0003 §2): one namespace, which-key overlay
                if self.pending == " " {
                    self.pending.clear();
                    return match c {
                        'f' => self.open_picker(strop_picker::Kind::Files),
                        'b' => self.open_picker(strop_picker::Kind::Buffers),
                        '/' => self.open_picker(strop_picker::Kind::Grep),
                        'g' => {
                            self.pending = " g".into();
                        }
                        _ => {
                            self.message =
                                "Space: f files · b buffers · / grep · g git (j, s, u land M4)"
                                    .into()
                        }
                    };
                }
                // git namespace (0003 §4): working-surface verbs (M2)
                if self.pending == " g" {
                    return self.feed_git_pending(c);
                }
                // hunk motions (0001 pillar 3.1)
                if (self.pending == "]" || self.pending == "[") && c == 'c' {
                    let forward = self.pending == "]";
                    self.pending.clear();
                    return self.jump_hunk(forward);
                }
                // r<char>: replace the char under the cursor, stay normal
                if self.pending == "r" {
                    self.pending.clear();
                    return self.replace_char(c);
                }
                // "xp / "xP: paste from a named register
                if self.pending.len() == 2
                    && self.pending.starts_with('"')
                    && (c == 'p' || c == 'P')
                {
                    let reg = self.pending.chars().nth(1);
                    self.pending.clear();
                    self.paste(reg, c == 'P');
                    return;
                }
                self.pending.push(c);
                if !is_ex {
                    self.resolve_pending();
                }
            }
        }
    }

    fn resolve_pending(&mut self) {
        match grammar::parse(&self.pending) {
            Parse::Incomplete => {}
            Parse::Invalid => {
                self.message = format!("not an editor command: {}", self.pending);
                self.pending.clear();
            }
            Parse::Complete(cmd) => {
                self.pending.clear();
                match cmd.op {
                    None => self.move_cursor(&cmd),
                    Some(_) => self.execute(&cmd),
                }
            }
        }
    }

    fn run_motion(&mut self, keys: &str) {
        if let Parse::Complete(cmd) = grammar::parse(keys) {
            self.move_cursor(&cmd);
        }
    }

    pub(crate) fn move_cursor(&mut self, cmd: &Command) {
        if let Some(r) = grammar::resolve(self.buf(), self.cursor, cmd) {
            self.cursor = grammar::cursor_after(self.buf(), self.cursor, cmd, &r);
            self.clamp_cursor();
        }
    }

    /// The live preview: what would the pending keys do right now?
    /// Same resolver the executor uses — the preview cannot lie.
    pub fn preview(&self) -> Option<Resolved> {
        if self.pending.is_empty() {
            return None;
        }
        match grammar::parse(&self.pending) {
            Parse::Complete(cmd) if cmd.op.is_some() => {
                grammar::resolve(self.buf(), self.cursor, &cmd)
            }
            _ => {
                // partial search: d/foo mid-typing previews cursor→first match
                if let Some(idx) = self.pending.find('/') {
                    let pat = &self.pending[idx + 1..];
                    if !pat.is_empty() {
                        if let Some(hit) = grammar::search_forward(self.buf(), self.cursor + 1, pat)
                        {
                            return Some(Resolved {
                                range: Range::charwise(self.cursor, hit),
                                inclusive: false,
                                spec: format!("search /{pat}"),
                            });
                        }
                    }
                }
                None
            }
        }
    }

    /// Pending f/F/t/T awaiting its char: the leap-style candidates.
    pub fn find_candidates(&self) -> Option<(u8, bool)> {
        let b = self.pending.as_bytes();
        let (&pfx, _) = b.split_last()?;
        let backward = matches!(pfx, b'F' | b'T');
        if !matches!(pfx, b'f' | b'F' | b't' | b'T') {
            return None;
        }
        Some((pfx, backward))
    }

    /// Pending search pattern (incsearch highlight), if any.
    pub fn search_pattern(&self) -> Option<&str> {
        self.pending
            .find('/')
            .map(|i| &self.pending[i + 1..])
            .filter(|p| !p.is_empty())
    }

    fn execute(&mut self, cmd: &Command) {
        let Some(r) = grammar::resolve(self.buf(), self.cursor, cmd) else {
            self.message = "no target".into();
            return;
        };
        match cmd.op.unwrap() {
            Op::Yank => {
                let text = self.buf().slice_string(r.range);
                self.set_register(cmd.register, text, r.range.linewise);
                self.flash(r.range);
            }
            Op::Indent | Op::Dedent => {
                self.apply_indent(r.range, cmd.op.unwrap() == Op::Indent);
                self.flash(Range::charwise(self.cursor, self.cursor));
            }
            Op::Delete | Op::Change => {
                let text = self.buf_mut().delete(r.range);
                self.set_register(cmd.register, text, r.range.linewise);
                self.cursor = r.range.start;
                self.clamp_cursor();
                self.flash(Range::charwise(self.cursor, self.cursor));
                if cmd.op.unwrap() == Op::Change {
                    self.enter_insert_from(&cmd.keys);
                }
            }
        }
        self.last_cmd_keys = cmd.keys.clone();
        self.last_insert = None;
    }

    fn dot_repeat(&mut self) {
        if self.last_cmd_keys.is_empty() && self.last_insert.is_none() {
            return;
        }
        let keys = self.last_cmd_keys.clone();
        let insert = self.last_insert.clone();
        if !keys.is_empty() {
            self.feed_text(&keys);
        }
        if let Some(text) = insert {
            let was_insert = self.mode == Mode::Insert;
            if !was_insert {
                self.enter_insert_from("i");
            }
            for c in text.chars() {
                self.feed(Key::Char(c));
            }
            self.feed(Key::Esc);
            self.message = "repeated".into();
        }
    }

    fn replace_char(&mut self, c: char) {
        let end = (self.cursor + 1).min(self.buf().line_end(self.buf().line_of(self.cursor)));
        if end <= self.cursor || c == '\n' {
            return;
        }
        let cursor = self.cursor;
        self.buf_mut().delete(Range::charwise(cursor, end));
        let mut tmp = [0u8; 4];
        self.buf_mut().insert(cursor, c.encode_utf8(&mut tmp));
        self.flash(Range::charwise(self.cursor, self.cursor + 1));
        self.last_cmd_keys = format!("r{c}");
        self.last_insert = None;
    }

    fn join_lines(&mut self) {
        let line = self.buf().line_of(self.cursor);
        if line + 1 >= self.buf().len_lines() {
            return;
        }
        let eol = self.buf().line_end(line);
        let next_start = self.buf().line_start(line + 1);
        let next_end = self.buf().line_end(line + 1);
        // delete newline + leading whitespace of the next line, add one space
        let mut join_at = next_start;
        while join_at < next_end
            && self.buf().byte(join_at).is_ascii_whitespace()
            && self.buf().byte(join_at) != b'\n'
        {
            join_at += 1;
        }
        self.buf_mut().delete(Range::charwise(eol, join_at));
        if join_at < next_end {
            self.buf_mut().insert(eol, " ");
        }
        self.cursor = eol;
        self.clamp_cursor();
        self.flash(Range::charwise(eol, (eol + 1).min(self.buf().len_bytes())));
        self.last_cmd_keys = "J".into();
        self.last_insert = None;
    }

    /// > / < applied to every line a resolved range covers.
    fn apply_indent(&mut self, range: Range, right: bool) {
        let line = self.buf().line_of(range.start);
        let last = self.buf().line_of(range.end.saturating_sub(1)) + 1;
        for l in line..last {
            let start = self.buf().line_start(l);
            if right {
                let indent = self.config.indent();
                self.buf_mut().insert(start, &indent);
            } else {
                let end = self.buf().line_end(l);
                let width = self.config.tab_size;
                let mut strip = 0;
                while strip < width && start + strip < end && self.buf().byte(start + strip) == b' '
                {
                    strip += 1;
                }
                if strip == 0 && self.buf().byte_at(start) == Some(b'\t') {
                    strip = 1;
                }
                if strip > 0 {
                    self.buf_mut().delete(Range::charwise(start, start + strip));
                }
            }
        }
        self.cursor = self.buf().line_start(line);
        self.clamp_cursor();
    }

    pub(crate) fn run_ex(&mut self) {
        let cmdline = self
            .pending
            .trim_start_matches(':')
            .trim_end_matches('\r')
            .to_string();
        self.pending.clear();
        let (cmd, arg) = cmdline.split_once(' ').unwrap_or((cmdline.as_str(), ""));
        match cmd {
            "w" => match self.buf_mut().save() {
                Ok(()) => self.message = "written".into(),
                Err(e) => self.message = format!("write failed: {e}"),
            },
            "q" => {
                self.close_buffer(false);
            }
            "q!" => {
                self.close_buffer(true);
            }
            "wq" => {
                let _ = self.buf_mut().save();
                self.close_buffer(true);
            }
            "e" | "e!" => {
                if arg.is_empty() {
                    self.message = ":e needs a path".into();
                } else if self.buf().dirty && cmd == "e" {
                    self.message = "unsaved changes — :e! to force".into();
                } else if let Err(e) = self.open_buffer(arg) {
                    self.message = format!("open {arg}: {e}");
                }
            }
            other => self.message = format!("unknown ex: :{other}"),
        }
    }
}