Skip to main content

paperos/extensions/
basic_input.rs

1use crate::core::Extension;
2use crate::extensions::keymap::Keymap;
3use crate::extensions::keymap_registry::KeymapRegistry;
4use crossterm::event::{KeyCode, KeyEvent};
5use runact::Runtime;
6use std::any::Any;
7
8#[cfg(test)]
9use crossterm::event::KeyModifiers;
10
11/// InputExtension: default editor keybindings (basic/text-editor mode).
12/// Arrow keys move cursor, typing inserts directly, no mode switching.
13/// Alt-x (M-x) opens an Emacs-style command prompt for running commands.
14/// Vi-style keybindings are provided by ViInputExtension (see vi_input.rs).
15#[allow(dead_code)]
16pub struct InputExtension {
17    active: bool,
18    keymap: Keymap,
19}
20
21#[allow(dead_code)]
22impl InputExtension {
23    pub fn new() -> Self {
24        let mut keymap = Keymap::new("basic");
25        keymap.load_defaults();
26        Self {
27            active: true,
28            keymap,
29        }
30    }
31
32    pub fn set_active(&mut self, active: bool) {
33        self.active = active;
34    }
35
36    pub fn is_active(&self) -> bool {
37        self.active
38    }
39
40    /// Handle a key event. Returns the command string to run, or None.
41    /// In Basic mode, arrow keys and printable chars generate commands.
42    /// Note: Alt+x is NOT handled here — it's intercepted by render.rs
43    /// before reaching this method, making it mode-independent.
44    pub fn handle_key(&mut self, key: &KeyEvent) -> Option<String> {
45        if !self.active {
46            return None;
47        }
48
49        // Check keymap first
50        if let Some(cmd) = self.keymap.resolve(key) {
51            return Some(cmd.to_string());
52        }
53
54        // Printable characters not in keymap → insert
55        match key.code {
56            KeyCode::Char(ch) if !ch.is_control() => Some(format!("insert {}", ch)),
57            _ => None,
58        }
59    }
60
61    /// Get a reference to the keymap (for testing/inspection).
62    pub fn keymap(&self) -> &Keymap {
63        &self.keymap
64    }
65
66    /// Register this extension's default keybindings as a named layer in the
67    /// central KeymapRegistry. The extension owns its mode name — the
68    /// registry and main.rs never need to know about "basic" or "vi".
69    pub fn register_layers(&self, reg: &mut KeymapRegistry) {
70        reg.register(self.keymap.to_layer("basic-defaults", 10, "basic"));
71    }
72}
73
74impl Extension for InputExtension {
75    fn name(&self) -> &str {
76        "input"
77    }
78
79    fn init(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
80        Ok(())
81    }
82
83    fn shutdown(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
84        Ok(())
85    }
86
87    fn on_key(&mut self, _ch: char) -> Result<(), Box<dyn std::error::Error>> {
88        Ok(())
89    }
90
91    fn on_render(&mut self, _runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
92        Ok(())
93    }
94
95    /// Global bindings: scroll/navigation keys available in all modes.
96    /// These are merged into the global layer by main.rs — no hardcoded
97    /// key strings in main.rs beyond M-x.
98    fn global_bindings(&self) -> Vec<(&'static str, &'static str)> {
99        vec![
100            ("C-d", "scroll-down"),
101            ("C-u", "scroll-up"),
102            ("C-f", "page-down"),
103            ("C-b", "page-up"),
104            ("C-<Left>", "scroll-left"),
105            ("C-<Right>", "scroll-right"),
106        ]
107    }
108
109    fn as_any(&self) -> &dyn Any {
110        self
111    }
112
113    fn as_any_mut(&mut self) -> &mut dyn Any {
114        self
115    }
116}
117
118impl Default for InputExtension {
119    fn default() -> Self {
120        Self::new()
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    fn key(code: KeyCode) -> KeyEvent {
129        KeyEvent::new(code, KeyModifiers::NONE)
130    }
131
132    fn alt_x() -> KeyEvent {
133        KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)
134    }
135
136    #[test]
137    fn test_basic_mode_arrow_keys() {
138        let mut ext = InputExtension::new();
139        assert!(ext.is_active());
140        assert_eq!(
141            ext.handle_key(&key(KeyCode::Left)),
142            Some("left".to_string())
143        );
144        assert_eq!(
145            ext.handle_key(&key(KeyCode::Right)),
146            Some("right".to_string())
147        );
148        assert_eq!(ext.handle_key(&key(KeyCode::Up)), Some("up".to_string()));
149        assert_eq!(
150            ext.handle_key(&key(KeyCode::Down)),
151            Some("down".to_string())
152        );
153    }
154
155    #[test]
156    fn test_basic_mode_typing() {
157        let mut ext = InputExtension::new();
158        assert_eq!(
159            ext.handle_key(&key(KeyCode::Char('a'))),
160            Some("insert a".to_string())
161        );
162        assert_eq!(
163            ext.handle_key(&key(KeyCode::Char('Z'))),
164            Some("insert Z".to_string())
165        );
166        assert_eq!(
167            ext.handle_key(&key(KeyCode::Tab)),
168            Some("insert-tab".to_string())
169        );
170    }
171
172    #[test]
173    fn test_basic_mode_control_chars_ignored() {
174        let mut ext = InputExtension::new();
175        assert!(ext.handle_key(&key(KeyCode::Char('\x01'))).is_none());
176        assert!(ext.handle_key(&key(KeyCode::Char('\x1b'))).is_none());
177    }
178
179    #[test]
180    fn test_alt_x_not_intercepted_by_input() {
181        // Alt+x is intercepted by render.rs before reaching input.
182        // InputExtension itself processes it as a normal key ('x').
183        let mut ext = InputExtension::new();
184        assert_eq!(ext.handle_key(&alt_x()), Some("insert x".to_string()));
185    }
186
187    #[test]
188    fn test_basic_mode_inactive_returns_none() {
189        let mut ext = InputExtension::new();
190        ext.set_active(false);
191        assert!(!ext.is_active());
192        assert!(ext.handle_key(&key(KeyCode::Char('a'))).is_none());
193        assert!(ext.handle_key(&key(KeyCode::Left)).is_none());
194    }
195
196    #[test]
197    fn test_basic_mode_special_keys() {
198        let mut ext = InputExtension::new();
199        assert_eq!(ext.handle_key(&key(KeyCode::Home)), Some("0".to_string()));
200        assert_eq!(ext.handle_key(&key(KeyCode::End)), Some("$".to_string()));
201        assert_eq!(
202            ext.handle_key(&key(KeyCode::Enter)),
203            Some("newline".to_string())
204        );
205        assert_eq!(
206            ext.handle_key(&key(KeyCode::Backspace)),
207            Some("delete".to_string())
208        );
209    }
210}