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
//! Central keymap system — the Emacs-inspired "active keymap chain".
//!
//! One registry, queried by render.rs on every keypress. It resolves a key
//! to a command based on context (the current editor mode) and an ordered
//! stack of layers (runtime > user config > extension defaults). First hit
//! wins; `resolve()` returns the name of the layer that won for
//! introspection.
//!
//! Design notes:
//! - Keys are canonical `Key` values, not `crossterm::KeyEvent`, so the
//!   registry is testable without terminal types and Lua can rebind via
//!   `Key::parse("C-x C-s")`.
//! - Layers are owned `HashMap<Key, String>` keyed by full key sequences
//!   (including modifiers) — prefix chords like `C-x C-s` work naturally
//!   because "C-x" maps to a sub-binding path.
//! - Context narrows before priority: a binding for `(mode=insert)`
//!   shadows `(mode=*)`.
//!
//! This replaces the "vi first, then basic" dispatch ladder that lived in
//! render.rs with a single data-driven `resolve` call.

use std::collections::HashMap;
use std::fmt;

/// Canonical key representation.
///
/// `parse()` converts Emacs-style notation:
/// - `"C-x"` → Control+X
/// - `"M-x"` → Alt+X
/// - `"C-M-x"` → Control+Alt+X
/// - `"x"`  → plain X
/// - `"<Return>"` → Enter
/// - `"<Tab>"` → Tab
/// - `"<Esc>"` → Escape
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Key {
    pub code: KeyCodeInner,
    pub ctrl: bool,
    pub alt: bool,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum KeyCodeInner {
    Char(char),
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
    Enter,
    Backspace,
    Tab,
    Escape,
}

impl Key {
    /// Parse a key spec like "C-x", "M-l", "<Tab>", or "a".
    pub fn parse(spec: &str) -> Option<Self> {
        let spec = spec.trim();
        let mut ctrl = false;
        let mut alt = false;
        let mut rest = spec;

        // Extract modifier prefixes
        loop {
            if rest.starts_with("C-") {
                ctrl = true;
                rest = &rest[2..];
            } else if rest.starts_with("M-") {
                alt = true;
                rest = &rest[2..];
            } else if rest.starts_with("C-M-") {
                ctrl = true;
                alt = true;
                rest = &rest[4..];
            } else {
                break;
            }
        }

        // Special keys in angle brackets
        if let Some(without_brackets) = rest.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
            let special = match without_brackets.to_ascii_lowercase().as_str() {
                "return" | "enter" | "cr" => KeyCodeInner::Enter,
                "tab" => KeyCodeInner::Tab,
                "esc" | "escape" => KeyCodeInner::Escape,
                "backspace" | "bs" | "del" => KeyCodeInner::Backspace,
                "left" => KeyCodeInner::Left,
                "right" => KeyCodeInner::Right,
                "up" => KeyCodeInner::Up,
                "down" => KeyCodeInner::Down,
                "home" => KeyCodeInner::Home,
                "end" => KeyCodeInner::End,
                "pageup" | "prior" => KeyCodeInner::PageUp,
                "pagedown" | "next" => KeyCodeInner::PageDown,
                _ => return None,
            };
            return Some(Self {
                code: special,
                ctrl,
                alt,
            });
        }

        // Single char (possibly with modifiers)
        let chars: Vec<char> = rest.chars().collect();
        if chars.len() == 1 {
            let c = chars[0];
            // With Ctrl, only certain chars make sense; store as-is
            Some(Self {
                code: KeyCodeInner::Char(c),
                ctrl,
                alt,
            })
        } else {
            None
        }
    }

    /// Render this key in Emacs notation (for the `keys` command).
    pub fn to_emacs(self) -> String {
        let mut s = String::new();
        if self.ctrl {
            s.push_str("C-");
        }
        if self.alt {
            s.push_str("M-");
        }
        match self.code {
            KeyCodeInner::Char(c) => {
                s.push(c);
            }
            KeyCodeInner::Enter => s.push_str("<Return>"),
            KeyCodeInner::Tab => s.push_str("<Tab>"),
            KeyCodeInner::Escape => s.push_str("<Esc>"),
            KeyCodeInner::Backspace => s.push_str("<Backspace>"),
            KeyCodeInner::Left => s.push_str("<Left>"),
            KeyCodeInner::Right => s.push_str("<Right>"),
            KeyCodeInner::Up => s.push_str("<Up>"),
            KeyCodeInner::Down => s.push_str("<Down>"),
            KeyCodeInner::Home => s.push_str("<Home>"),
            KeyCodeInner::End => s.push_str("<End>"),
            KeyCodeInner::PageUp => s.push_str("<PageUp>"),
            KeyCodeInner::PageDown => s.push_str("<PageDown>"),
        }
        s
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_emacs())
    }
}

/// Focus context — the "when" clause for binding resolution.
///
/// `mode` is the editor mode (Basic, Normal, Insert, ...).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Context {
    pub mode: String,
}

impl Context {
    pub fn new(mode: &str) -> Self {
        Self {
            mode: mode.to_string(),
        }
    }
}

/// A single binding: key → command_name.
struct Binding {
    command: String,
}

/// A named, prioritized set of bindings — one layer in the resolution chain.
///
/// Layers are searched in priority order (highest first); first hit wins.
/// `source` is the owning extension/config so conflicts are auditable.
#[allow(dead_code)]
pub struct Layer {
    pub name: String,
    pub priority: i32,
    pub context: Option<Context>, // None = matches any context
    bindings: HashMap<Key, Binding>,
}

#[allow(dead_code)]
impl Layer {
    pub fn new(name: &str, priority: i32, context: Option<Context>) -> Self {
        Self {
            name: name.to_string(),
            priority,
            context,
            bindings: HashMap::new(),
        }
    }

    /// Bind a key to a command.
    pub fn bind(&mut self, key: Key, command: &str) {
        self.bindings.insert(
            key,
            Binding {
                command: command.to_string(),
            },
        );
    }

    /// Resolve a key. Only succeeds if the context matches.
    fn resolve(&self, key: Key, ctx: &Context) -> Option<&str> {
        if !self.matches_context(ctx) {
            return None;
        }
        self.bindings.get(&key).map(|b| b.command.as_str())
    }

    /// A binding matches if the layer's context is None (global) or the
    /// mode matches. Mode `"*"` matches any mode.
    fn matches_context(&self, ctx: &Context) -> bool {
        match &self.context {
            None => true,
            Some(layer_ctx) => layer_ctx.mode == "*" || layer_ctx.mode == ctx.mode,
        }
    }

    /// All bindings with their resolved key notation (for introspection).
    pub fn entries(&self) -> Vec<(Key, &str)> {
        self.bindings
            .iter()
            .map(|(k, b)| (*k, b.command.as_str()))
            .collect()
    }
}

/// What a key resolves to, including which layer won.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct Resolution {
    pub command: String,
    pub source: String,
    pub source_priority: i32,
}

/// The central keymap registry.
///
/// Owned by the RenderExtension (or passed to extensions that need to
/// inspect/rebind keys). On every keypress, call `resolve` with the current
/// context — one data-driven lookup replaces all hand-rolled dispatch ladders.
#[allow(dead_code)]
pub struct KeymapRegistry {
    layers: Vec<Layer>,
}

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

#[allow(dead_code)]
impl KeymapRegistry {
    pub fn new() -> Self {
        Self { layers: Vec::new() }
    }

    /// Register a layer. Layers with higher `priority` are checked first.
    /// Replaces any existing layer with the same name.
    pub fn register(&mut self, layer: Layer) {
        self.layers.retain(|l| l.name != layer.name);
        self.layers.push(layer);
        // Keep sorted: highest priority first
        self.layers.sort_by_key(|l| std::cmp::Reverse(l.priority));
    }

    /// Rebind a key in an existing layer (by name). Returns true if the
    /// layer exists and the key was bound/unbound.
    pub fn rebind(&mut self, layer_name: &str, key_spec: &str, command: &str) -> bool {
        let key = match Key::parse(key_spec) {
            Some(k) => k,
            None => return false,
        };
        if let Some(layer) = self.layers.iter_mut().find(|l| l.name == layer_name) {
            if command.is_empty() {
                layer.bindings.remove(&key);
            } else {
                layer.bind(key, command);
            }
            true
        } else {
            false
        }
    }

    /// Resolve a key for the given context.
    /// Returns the winning command + the layer that provided it.
    pub fn resolve(&self, key: Key, ctx: &Context) -> Option<Resolution> {
        for layer in &self.layers {
            if let Some(cmd) = layer.resolve(key, ctx) {
                return Some(Resolution {
                    command: cmd.to_string(),
                    source: layer.name.clone(),
                    source_priority: layer.priority,
                });
            }
        }
        None
    }

    /// Find which layer (if any) would handle a key — for `describe-key`.
    pub fn describe_key(&self, key: Key, ctx: &Context) -> Option<&Layer> {
        self.layers
            .iter()
            .find(|&layer| layer.matches_context(ctx) && layer.bindings.contains_key(&key))
            .map(|v| v as _)
    }

    /// All layers, highest priority first (for `keys` command introspection).
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }

    /// All bindings visible in a given context (merged, shadowed ones excluded).
    pub fn bindings_for(&self, ctx: &Context) -> Vec<(Key, String, String)> {
        let mut seen: HashMap<Key, (String, String)> = HashMap::new();
        for layer in &self.layers {
            if layer.matches_context(ctx) {
                for (k, cmd) in layer.entries() {
                    // First hit wins (layers are in priority order)
                    seen.entry(k)
                        .or_insert_with(|| (cmd.to_string(), layer.name.clone()));
                }
            }
        }
        let mut result: Vec<_> = seen.into_iter().collect();
        result.sort_by_key(|a| a.0.to_emacs());
        result.into_iter().map(|(k, (c, s))| (k, c, s)).collect()
    }
}

// (Conversion to crossterm events lives in `keymap_convert.rs`.)
// Unit tests follow below.

// ----------------------------------------------------------------------------
// Unit tests
// ----------------------------------------------------------------------------

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

    #[test]
    fn test_parse_simple_char() {
        let k = Key::parse("a").unwrap();
        assert_eq!(k.code, KeyCodeInner::Char('a'));
        assert!(!k.ctrl);
        assert!(!k.alt);
    }

    #[test]
    fn test_parse_ctrl() {
        let k = Key::parse("C-d").unwrap();
        assert_eq!(k.code, KeyCodeInner::Char('d'));
        assert!(k.ctrl);
        assert!(!k.alt);
    }

    #[test]
    fn test_parse_alt() {
        let k = Key::parse("M-x").unwrap();
        assert_eq!(k.code, KeyCodeInner::Char('x'));
        assert!(!k.ctrl);
        assert!(k.alt);
    }

    #[test]
    fn test_parse_ctrl_alt() {
        let k = Key::parse("C-M-x").unwrap();
        assert_eq!(k.code, KeyCodeInner::Char('x'));
        assert!(k.ctrl);
        assert!(k.alt);
    }

    #[test]
    fn test_parse_special_keys() {
        assert_eq!(Key::parse("<Return>").unwrap().code, KeyCodeInner::Enter);
        assert_eq!(Key::parse("<Tab>").unwrap().code, KeyCodeInner::Tab);
        assert_eq!(Key::parse("<Esc>").unwrap().code, KeyCodeInner::Escape);
        assert_eq!(
            Key::parse("<Backspace>").unwrap().code,
            KeyCodeInner::Backspace
        );
        assert_eq!(Key::parse("<Left>").unwrap().code, KeyCodeInner::Left);
    }

    #[test]
    fn test_parse_invalid() {
        assert!(Key::parse("xyz").is_none());
        assert!(Key::parse("C-xyz").is_none()); // multi-char base
        assert!(Key::parse("<Bogus>").is_none());
    }

    #[test]
    fn test_to_emacs_roundtrip() {
        let k = Key::parse("C-x").unwrap();
        assert_eq!(k.to_emacs(), "C-x");
        let k2 = Key::parse("<Return>").unwrap();
        assert_eq!(k2.to_emacs(), "<Return>");
        let k3 = Key::parse("M-x").unwrap();
        assert_eq!(k3.to_emacs(), "M-x");
    }

    #[test]
    fn test_resolve_first_hit_wins() {
        let mut reg = KeymapRegistry::new();

        // Lower priority layer
        let mut defaults = Layer::new("basic-defaults", 10, None);
        defaults.bind(Key::parse("h").unwrap(), "left");
        reg.register(defaults);

        // Higher priority layer shadows "h"
        let mut vi = Layer::new("vi-normal", 100, Some(Context::new("normal")));
        vi.bind(Key::parse("h").unwrap(), "vi-left");
        reg.register(vi);

        // In Normal mode, vi wins
        let ctx = Context::new("normal");
        let r = reg.resolve(Key::parse("h").unwrap(), &ctx).unwrap();
        assert_eq!(r.command, "vi-left");
        assert_eq!(r.source, "vi-normal");

        // In Basic mode, vi layer doesn't match → basic wins
        let ctx = Context::new("basic");
        let r = reg.resolve(Key::parse("h").unwrap(), &ctx).unwrap();
        assert_eq!(r.command, "left");
        assert_eq!(r.source, "basic-defaults");
    }

    #[test]
    fn test_resolve_no_binding() {
        let reg = KeymapRegistry::new();
        let ctx = Context::new("normal");
        assert!(reg.resolve(Key::parse("z").unwrap(), &ctx).is_none());
    }

    #[test]
    fn test_global_context_wildcard() {
        let mut reg = KeymapRegistry::new();
        let mut global = Layer::new("global", 10, Some(Context::new("*")));
        global.bind(Key::parse("C-x").unwrap(), "command-mode");
        reg.register(global);

        // Should match regardless of mode
        let r = reg
            .resolve(Key::parse("C-x").unwrap(), &Context::new("insert"))
            .unwrap();
        assert_eq!(r.command, "command-mode");
    }

    #[test]
    fn test_rebind_existing_layer() {
        let mut reg = KeymapRegistry::new();
        let mut layer = Layer::new("my-layer", 50, None);
        layer.bind(Key::parse("a").unwrap(), "cmd-a");
        reg.register(layer);

        // Rebind 'a' to a new command
        assert!(reg.rebind("my-layer", "a", "cmd_a2"));
        let r = reg
            .resolve(Key::parse("a").unwrap(), &Context::new("any"))
            .unwrap();
        assert_eq!(r.command, "cmd_a2");

        // Unbind by passing empty command
        assert!(reg.rebind("my-layer", "a", ""));
        assert!(reg
            .resolve(Key::parse("a").unwrap(), &Context::new("any"))
            .is_none());
    }

    #[test]
    fn test_rebind_nonexistent_layer() {
        let mut reg = KeymapRegistry::new();
        assert!(!reg.rebind("no-such-layer", "a", "cmd"));
    }

    #[test]
    fn test_layer_replaces_same_name() {
        let mut reg = KeymapRegistry::new();
        let mut l1 = Layer::new("dup", 50, None);
        l1.bind(Key::parse("a").unwrap(), "first");
        reg.register(l1);

        let mut l2 = Layer::new("dup", 200, None);
        l2.bind(Key::parse("b").unwrap(), "second");
        reg.register(l2);

        // Should have only one "dup" layer, and it should be at priority 200
        assert_eq!(reg.layers().iter().filter(|l| l.name == "dup").count(), 1);

        // 'a' should no longer resolve (replaced layer dropped the binding)
        assert!(reg
            .resolve(Key::parse("a").unwrap(), &Context::new("x"))
            .is_none());
        // 'b' should resolve
        assert!(reg
            .resolve(Key::parse("b").unwrap(), &Context::new("x"))
            .is_some());
    }

    #[test]
    fn test_bindings_for_excludes_shadowed() {
        let mut reg = KeymapRegistry::new();
        let mut lower = Layer::new("lower", 10, None);
        lower.bind(Key::parse("a").unwrap(), "cmd_a_lower");
        lower.bind(Key::parse("b").unwrap(), "cmd_b");
        reg.register(lower);

        let mut upper = Layer::new("upper", 100, None);
        upper.bind(Key::parse("a").unwrap(), "cmd_a_upper");
        reg.register(upper);

        let ctx = Context::new("*");
        let bindings = reg.bindings_for(&ctx);

        // 'a' should appear once (from upper layer), 'b' from lower
        let a_entry = bindings
            .iter()
            .find(|(k, _, _)| k.to_emacs() == "a")
            .unwrap();
        assert_eq!(a_entry.1, "cmd_a_upper");
        assert_eq!(a_entry.2, "upper");

        let b_entry = bindings
            .iter()
            .find(|(k, _, _)| k.to_emacs() == "b")
            .unwrap();
        assert_eq!(b_entry.1, "cmd_b");
        assert_eq!(b_entry.2, "lower");
    }

    #[test]
    fn test_describe_key_returns_winning_layer() {
        let mut reg = KeymapRegistry::new();
        let mut l = Layer::new("my-layer", 10, Some(Context::new("normal")));
        l.bind(Key::parse("j").unwrap(), "down");
        reg.register(l);

        let layer = reg
            .describe_key(Key::parse("j").unwrap(), &Context::new("normal"))
            .unwrap();
        assert_eq!(layer.name, "my-layer");
    }

    #[test]
    fn test_describe_key_returns_none_for_unbound() {
        let reg = KeymapRegistry::new();
        assert!(reg
            .describe_key(Key::parse("z").unwrap(), &Context::new("normal"))
            .is_none());
    }
}