paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use crate::core::Extension;
use crate::extensions::keymap::Keymap;
use crate::extensions::keymap_registry::KeymapRegistry;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use runact::Runtime;
use std::any::Any;

/// ViInputExtension: vi-style keybindings (h/j/k/l movement, modes).
/// Includes vi modes (Normal, Insert, Command, Search) plus visual mode
/// (VisualChar, VisualLine).
/// For basic/text-editor keybindings, use InputExtension instead.
#[allow(dead_code)]
pub struct ViInputExtension {
    mode: EditorMode,
    command_buffer: String,
    last_command: Option<String>,
    // Visual mode state
    visual_mode: Option<VisualMode>,
    selection_start: Option<(usize, usize)>,
    clipboard: Option<String>,
    // Per-mode keymaps
    normal_keymap: Keymap,
    insert_keymap: Keymap,
    visual_keymap: Keymap,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorMode {
    /// Default mode — basic/text-editor keybindings (arrows, direct typing).
    Basic,
    Normal,
    Insert,
    Command,
    Search,
    /// Terminal panel active: keys encode to PTY bytes.
    Terminal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VisualMode {
    Char,
    Line,
}

impl Extension for ViInputExtension {
    fn name(&self) -> &str {
        "vi-input"
    }

    fn init(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn shutdown(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_key(&mut self, _ch: char) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_render(&mut self, _runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

#[allow(dead_code)]
impl ViInputExtension {
    pub fn new() -> Self {
        let mut normal_keymap = Keymap::new("normal");
        normal_keymap.load_defaults();
        let mut insert_keymap = Keymap::new("insert");
        insert_keymap.load_defaults();
        let mut visual_keymap = Keymap::new("visual");
        visual_keymap.load_defaults();
        Self {
            mode: EditorMode::Basic,
            command_buffer: String::new(),
            last_command: None,
            visual_mode: None,
            selection_start: None,
            clipboard: None,
            normal_keymap,
            insert_keymap,
            visual_keymap,
        }
    }

    pub fn mode(&self) -> EditorMode {
        self.mode
    }

    pub fn command_buffer(&self) -> &str {
        &self.command_buffer
    }

    pub fn visual_mode(&self) -> Option<VisualMode> {
        self.visual_mode
    }

    pub fn selection_start(&self) -> Option<(usize, usize)> {
        self.selection_start
    }

    pub fn is_in_visual_mode(&self) -> bool {
        self.visual_mode.is_some()
    }

    /// Register all vi mode keybindings as named layers in the central
    /// KeymapRegistry. The extension owns its mode names — the registry
    /// and main.rs never need to know about vi modes.
    pub fn register_layers(&self, reg: &mut KeymapRegistry) {
        reg.register(self.normal_keymap.to_layer("vi-normal", 20, "normal"));
        reg.register(self.insert_keymap.to_layer("vi-insert", 20, "insert"));
        reg.register(self.visual_keymap.to_layer("vi-visual", 20, "visual"));
    }

    /// Translate a character key press into a command string.
    pub fn handle_char_key(&mut self, ch: char) -> Option<String> {
        // When in visual mode, keys extend selection or perform yank/delete
        if let Some(_vm) = self.visual_mode {
            return self.handle_visual_key(ch);
        }

        match self.mode {
            EditorMode::Insert => {
                // Esc switches back to Normal
                if ch == '\x1b' {
                    self.mode = EditorMode::Normal;
                    return None;
                }
                // Keymap first — Enter/Backspace/Tab are bound control keys
                // and must resolve before the control-char filter below.
                let key = Self::char_to_key_event(ch);
                if let Some(cmd) = self.insert_keymap.resolve(&key) {
                    return Some(cmd.to_string());
                }
                // Unbound control chars are ignored; printable chars insert
                if ch.is_control() {
                    return None;
                }
                Some(format!("insert {}", ch))
            }
            EditorMode::Basic => match ch {
                'i' => {
                    self.mode = EditorMode::Insert;
                    None
                }
                ':' => {
                    self.mode = EditorMode::Command;
                    self.command_buffer.clear();
                    None
                }
                '/' => {
                    self.mode = EditorMode::Search;
                    self.command_buffer.clear();
                    None
                }
                _ => None,
            },
            EditorMode::Normal => self.handle_normal_mode_key(ch),
            EditorMode::Command => {
                if ch == '\r' || ch == '\n' {
                    let cmd = self.command_buffer.clone();
                    self.command_buffer.clear();
                    self.mode = EditorMode::Normal;
                    self.last_command = Some(cmd.clone());
                    Some(cmd)
                } else if ch == '\x08' || ch == '\x7f' {
                    self.command_buffer.pop();
                    None
                } else if ch == '\x1b' {
                    self.command_buffer.clear();
                    self.mode = EditorMode::Normal;
                    None
                } else if ch.is_control() {
                    None
                } else {
                    self.command_buffer.push(ch);
                    None
                }
            }
            EditorMode::Search => {
                if ch == '\r' || ch == '\n' {
                    let pattern = self.command_buffer.clone();
                    self.command_buffer.clear();
                    self.mode = EditorMode::Normal;
                    self.last_command = Some(pattern.clone());
                    Some(format!("search {}", pattern))
                } else if ch == '\x08' || ch == '\x7f' {
                    self.command_buffer.pop();
                    None
                } else if ch == '\x1b' {
                    self.command_buffer.clear();
                    self.mode = EditorMode::Normal;
                    None
                } else if ch.is_control() {
                    None
                } else {
                    self.command_buffer.push(ch);
                    None
                }
            }
            // Terminal mode: keys are encoded to PTY bytes by the terminal
            // extension (handle_key in the event loop), never commands.
            // Esc exits Terminal back to Normal.
            EditorMode::Terminal => {
                if ch == '\x1b' {
                    self.mode = EditorMode::Normal;
                }
                None
            }
        }
    }

    fn handle_normal_mode_key(&mut self, ch: char) -> Option<String> {
        // Check for visual mode entry first
        match ch {
            'v' => {
                self.visual_mode = Some(VisualMode::Char);
                self.selection_start = None;
                return None;
            }
            'V' => {
                self.visual_mode = Some(VisualMode::Line);
                self.selection_start = None;
                return None;
            }
            _ => {}
        }

        // Mode-switch keys (not in keymap)
        match ch {
            'i' => {
                self.mode = EditorMode::Insert;
                return None;
            }
            ':' => {
                self.mode = EditorMode::Command;
                self.command_buffer.clear();
                return None;
            }
            '/' => {
                self.mode = EditorMode::Search;
                self.command_buffer.clear();
                return None;
            }
            _ => {}
        }

        // Use keymap for movement and editing commands
        let key = Self::char_to_key_event(ch);
        if let Some(cmd) = self.normal_keymap.resolve(&key) {
            return Some(cmd.to_string());
        }

        None
    }

    fn handle_visual_key(&mut self, ch: char) -> Option<String> {
        // Escape exits visual mode
        if ch == '\x1b' {
            self.visual_mode = None;
            self.selection_start = None;
            return Some("escape".to_string());
        }

        // Check keymap for movement/yank/delete
        let key = Self::char_to_key_event(ch);
        if let Some(cmd) = self.visual_keymap.resolve(&key) {
            // For yank/delete, exit visual mode after the operation
            match cmd {
                "delete-selection" => {
                    let _ = self.cut_selection();
                    self.visual_mode = None;
                    self.selection_start = None;
                    return Some("delete".to_string());
                }
                "yank-selection" => {
                    let _ = self.yank_selection();
                    self.visual_mode = None;
                    self.selection_start = None;
                    return Some("yank".to_string());
                }
                _ => return Some(cmd.to_string()),
            }
        }

        None
    }

    fn yank_selection(&self) -> bool {
        // Selection is from self.selection_start to current cursor
        // For now, just copy the current line
        self.selection_start.is_some()
    }

    fn cut_selection(&self) -> bool {
        self.selection_start.is_some()
    }

    /// Convert a char (from key_to_char) back into a KeyEvent for keymap lookup.
    /// Detects shift-modified characters so keymap bindings with SHIFT resolve correctly.
    fn char_to_key_event(ch: char) -> KeyEvent {
        use KeyCode::*;
        match ch {
            '\x1b' => KeyEvent::new(Esc, KeyModifiers::NONE),
            '\r' | '\n' => KeyEvent::new(Enter, KeyModifiers::NONE),
            '\x08' | '\x7f' => KeyEvent::new(Backspace, KeyModifiers::NONE),
            '\t' => KeyEvent::new(Tab, KeyModifiers::NONE),
            c if c.is_ascii_uppercase() => KeyEvent::new(KeyCode::Char(c), KeyModifiers::SHIFT),
            c if "!@#$%^&*()_+{}|:\"<>?~".contains(c) => {
                KeyEvent::new(KeyCode::Char(c), KeyModifiers::SHIFT)
            }
            c => KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE),
        }
    }

    /// Set the visual mode selection start (called from render when entering visual mode)
    pub fn set_selection_start(&mut self, row: usize, col: usize) {
        self.selection_start = Some((row, col));
    }

    /// Set the clipboard contents (used by paste operations)
    pub fn set_clipboard(&mut self, text: String) {
        self.clipboard = Some(text);
    }

    pub fn take_clipboard(&mut self) -> Option<String> {
        self.clipboard.take()
    }

    /// Set the current editor mode.
    pub fn set_mode(&mut self, mode: EditorMode) {
        self.mode = mode;
    }

    pub fn take_last_command(&mut self) -> Option<String> {
        self.last_command.take()
    }
}

/// Search for pattern, find next occurrence after cursor (forward=true) or before (forward=false)
#[allow(dead_code)]
pub fn search_forward(
    lines: &[&str],
    start_row: usize,
    start_col: usize,
    pattern: &str,
) -> Option<(usize, usize)> {
    if pattern.is_empty() {
        return None;
    }
    // Check start row from start_col onwards
    if let Some(line) = lines.get(start_row) {
        if let Some(pos) = line[start_col..].find(pattern) {
            return Some((start_row, start_col + pos));
        }
    }
    // Check remaining rows
    for row in (start_row + 1)..lines.len() {
        if let Some(pos) = lines.get(row).and_then(|l| l.find(pattern)) {
            return Some((row, pos));
        }
    }
    None
}

#[allow(dead_code)]
pub fn search_backward(
    lines: &[&str],
    start_row: usize,
    start_col: usize,
    pattern: &str,
) -> Option<(usize, usize)> {
    if pattern.is_empty() {
        return None;
    }
    // Check start row backwards from start_col
    if let Some(line) = lines.get(start_row) {
        let prefix = &line[..start_col.min(line.len())];
        if let Some(pos) = prefix.rfind(pattern) {
            return Some((start_row, pos));
        }
    }
    // Check preceding rows backwards
    for row in (0..start_row).rev() {
        if let Some(pos) = lines.get(row).and_then(|l| l.rfind(pattern)) {
            return Some((row, pos));
        }
    }
    None
}

impl Default for ViInputExtension {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_extension_starts_basic() {
        let ext = ViInputExtension::new();
        assert_eq!(ext.mode(), EditorMode::Basic);
        assert!(!ext.is_in_visual_mode());
    }

    #[test]
    fn test_enter_visual_char_mode() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('v');
        assert!(ext.is_in_visual_mode());
        assert_eq!(ext.visual_mode(), Some(VisualMode::Char));
    }

    #[test]
    fn test_enter_visual_line_mode() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('V');
        assert!(ext.is_in_visual_mode());
        assert_eq!(ext.visual_mode(), Some(VisualMode::Line));
    }

    #[test]
    fn test_visual_mode_escape_exits() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('v');
        assert!(ext.is_in_visual_mode());
        let cmd = ext.handle_char_key('\x1b');
        assert!(!ext.is_in_visual_mode());
        assert_eq!(cmd, Some("escape".to_string()));
    }

    #[test]
    fn test_visual_mode_yank() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('v');
        ext.set_selection_start(0, 0);
        let cmd = ext.handle_char_key('y');
        assert!(!ext.is_in_visual_mode());
        assert_eq!(cmd, Some("yank".to_string()));
    }

    #[test]
    fn test_visual_mode_delete() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('v');
        ext.set_selection_start(0, 0);
        let cmd = ext.handle_char_key('d');
        assert!(!ext.is_in_visual_mode());
        assert_eq!(cmd, Some("delete".to_string()));
    }

    #[test]
    fn test_visual_mode_movement() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        ext.handle_char_key('v');
        assert_eq!(ext.handle_char_key('h'), Some("left".to_string()));
        assert_eq!(ext.handle_char_key('j'), Some("down".to_string()));
        assert_eq!(ext.handle_char_key('k'), Some("up".to_string()));
        assert_eq!(ext.handle_char_key('l'), Some("right".to_string()));
    }

    #[test]
    fn test_normal_mode_hjkl_commands() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        ext.handle_char_key('\x1b');
        assert_eq!(ext.mode(), EditorMode::Normal);
        assert_eq!(ext.handle_char_key('h'), Some("left".to_string()));
        assert_eq!(ext.handle_char_key('j'), Some("down".to_string()));
        assert_eq!(ext.handle_char_key('k'), Some("up".to_string()));
        assert_eq!(ext.handle_char_key('l'), Some("right".to_string()));
    }

    #[test]
    fn test_insert_mode_escape_returns_normal() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        assert_eq!(ext.mode(), EditorMode::Insert);
        let cmd = ext.handle_char_key('\x1b');
        assert!(cmd.is_none());
        assert_eq!(ext.mode(), EditorMode::Normal);
    }

    #[test]
    fn test_insert_mode_characters() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        assert_eq!(ext.handle_char_key('a'), Some("insert a".to_string()));
        assert_eq!(ext.handle_char_key('b'), Some("insert b".to_string()));
        assert_eq!(ext.handle_char_key('x'), Some("insert x".to_string()));
    }

    #[test]
    fn test_insert_mode_enter_newline() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        assert_eq!(ext.mode(), EditorMode::Insert);
        // Enter in Insert mode must insert a newline
        assert_eq!(ext.handle_char_key('\r'), Some("newline".to_string()));
        assert_eq!(ext.handle_char_key('\n'), Some("newline".to_string()));
    }

    #[test]
    fn test_insert_mode_backspace_delete() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        // Backspace in Insert mode must delete the char before cursor
        assert_eq!(ext.handle_char_key('\x08'), Some("delete".to_string()));
        assert_eq!(ext.handle_char_key('\x7f'), Some("delete".to_string()));
    }

    #[test]
    fn test_insert_mode_tab_inserts() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        assert_eq!(ext.handle_char_key('\t'), Some("insert-tab".to_string()));
    }

    #[test]
    fn test_insert_mode_other_control_chars_ignored() {
        let mut ext = ViInputExtension::new();
        ext.handle_char_key('i');
        // Ctrl-style control chars that have no binding are ignored
        assert_eq!(ext.handle_char_key('\x01'), None);
        assert_eq!(ext.handle_char_key('\x02'), None);
    }

    #[test]
    fn test_command_mode() {
        let mut ext = ViInputExtension::new();
        ext.set_mode(EditorMode::Normal);
        assert!(ext.handle_char_key(':').is_none());
        assert_eq!(ext.mode(), EditorMode::Command);
        ext.handle_char_key('w');
        let cmd = ext.handle_char_key('\r');
        assert_eq!(cmd, Some("w".to_string()));
        assert_eq!(ext.mode(), EditorMode::Normal);
    }

    #[test]
    fn test_visual_mode_paste() {
        let mut ext = ViInputExtension::new();
        ext.set_clipboard("test".to_string());
        assert_eq!(ext.take_clipboard(), Some("test".to_string()));
        assert_eq!(ext.take_clipboard(), None);
    }
}