fresh-editor 0.1.90

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
//! Buffer mode system for buffer-local keybindings
//!
//! This module implements an Emacs-style major mode system where each buffer
//! can have its own mode that defines keybindings. Modes support inheritance,
//! allowing derived modes to extend parent modes.

use crossterm::event::{KeyCode, KeyModifiers};
use std::collections::HashMap;

/// A buffer mode that defines keybindings and behavior for a type of buffer
#[derive(Debug, Clone)]
pub struct BufferMode {
    /// Name of this mode (e.g., "special", "diagnostics-list")
    pub name: String,

    /// Parent mode name for inheritance (e.g., "special" is parent of "diagnostics-list")
    pub parent: Option<String>,

    /// Keybindings specific to this mode (key → command name)
    pub keybindings: HashMap<(KeyCode, KeyModifiers), String>,

    /// Chord keybindings (multi-key sequences like "g g" → command name)
    pub chord_keybindings: HashMap<Vec<(KeyCode, KeyModifiers)>, String>,

    /// Whether buffers with this mode are read-only by default
    pub read_only: bool,
}

impl BufferMode {
    /// Create a new buffer mode
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            parent: None,
            keybindings: HashMap::new(),
            chord_keybindings: HashMap::new(),
            read_only: false,
        }
    }

    /// Set the parent mode for inheritance
    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
        self.parent = Some(parent.into());
        self
    }

    /// Add a keybinding to this mode
    pub fn with_binding(
        mut self,
        code: KeyCode,
        modifiers: KeyModifiers,
        command: impl Into<String>,
    ) -> Self {
        self.keybindings.insert((code, modifiers), command.into());
        self
    }

    /// Add a chord keybinding (multi-key sequence) to this mode
    pub fn with_chord_binding(
        mut self,
        sequence: Vec<(KeyCode, KeyModifiers)>,
        command: impl Into<String>,
    ) -> Self {
        self.chord_keybindings.insert(sequence, command.into());
        self
    }

    /// Set whether this mode is read-only by default
    pub fn with_read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    /// Add multiple keybindings at once
    pub fn with_bindings(mut self, bindings: Vec<(KeyCode, KeyModifiers, String)>) -> Self {
        for (code, modifiers, command) in bindings {
            self.keybindings.insert((code, modifiers), command);
        }
        self
    }
}

/// Registry for buffer modes
///
/// Manages all available modes and provides lookup functionality with inheritance.
#[derive(Debug, Clone)]
pub struct ModeRegistry {
    /// All registered modes
    modes: HashMap<String, BufferMode>,
}

impl ModeRegistry {
    /// Create a new mode registry with built-in modes
    pub fn new() -> Self {
        let mut registry = Self {
            modes: HashMap::new(),
        };

        // Register built-in "special" mode (base for all special buffers)
        // This is like Emacs' special-mode
        // Keybindings map to Action names (see Action::from_str)
        let special_mode = BufferMode::new("special")
            .with_read_only(true)
            .with_binding(KeyCode::Char('q'), KeyModifiers::NONE, "close")
            .with_binding(KeyCode::Char('g'), KeyModifiers::NONE, "revert");

        registry.register(special_mode);

        registry
    }

    /// Register a new mode
    pub fn register(&mut self, mode: BufferMode) {
        self.modes.insert(mode.name.clone(), mode);
    }

    /// Get a mode by name
    pub fn get(&self, name: &str) -> Option<&BufferMode> {
        self.modes.get(name)
    }

    /// Normalize a key for lookup: ensures consistent representation of shifted letters
    /// This ensures that pressing 'G' (Shift+g) matches bindings defined as 'G'
    ///
    /// Normalization rules:
    /// - Uppercase char (with or without SHIFT) -> lowercase char with SHIFT
    /// - Lowercase char with SHIFT -> keep as is (already normalized form)
    fn normalize_key(code: KeyCode, modifiers: KeyModifiers) -> (KeyCode, KeyModifiers) {
        if let KeyCode::Char(c) = code {
            if c.is_ascii_uppercase() {
                // Uppercase char -> always normalize to lowercase with SHIFT
                return (
                    KeyCode::Char(c.to_ascii_lowercase()),
                    modifiers | KeyModifiers::SHIFT,
                );
            }
            // Lowercase chars: keep as-is (SHIFT modifier preserved if present)
        }
        (code, modifiers)
    }

    /// Resolve a keybinding for a mode, following inheritance chain
    ///
    /// Returns the command name if a binding is found in this mode or any parent.
    pub fn resolve_keybinding(
        &self,
        mode_name: &str,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> Option<String> {
        let mut current_mode_name = Some(mode_name);

        // Normalize the key for consistent lookup
        let (code, modifiers) = Self::normalize_key(code, modifiers);

        // Walk up the inheritance chain
        while let Some(name) = current_mode_name {
            if let Some(mode) = self.modes.get(name) {
                // Check if this mode has the keybinding
                if let Some(command) = mode.keybindings.get(&(code, modifiers)) {
                    return Some(command.clone());
                }

                // Move to parent mode
                current_mode_name = mode.parent.as_deref();
            } else {
                // Mode not found, stop searching
                break;
            }
        }

        None
    }

    /// Check if a mode is read-only (checking inheritance)
    pub fn is_read_only(&self, mode_name: &str) -> bool {
        let mut current_mode_name = Some(mode_name);

        // Walk up the inheritance chain
        while let Some(name) = current_mode_name {
            if let Some(mode) = self.modes.get(name) {
                if mode.read_only {
                    return true;
                }
                current_mode_name = mode.parent.as_deref();
            } else {
                break;
            }
        }

        false
    }

    /// Check if a key sequence could be the start of a chord in this mode
    ///
    /// This is used to determine if we should wait for more keys before
    /// deciding what action to take.
    pub fn is_chord_prefix(
        &self,
        mode_name: &str,
        chord_state: &[(KeyCode, KeyModifiers)],
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> bool {
        // Normalize the key
        let (code, modifiers) = Self::normalize_key(code, modifiers);

        // Build the sequence we're checking
        let mut sequence: Vec<(KeyCode, KeyModifiers)> = chord_state
            .iter()
            .map(|(c, m)| Self::normalize_key(*c, *m))
            .collect();
        sequence.push((code, modifiers));

        let mut current_mode_name = Some(mode_name);

        // Walk up the inheritance chain
        while let Some(name) = current_mode_name {
            if let Some(mode) = self.modes.get(name) {
                // Check if our sequence is a prefix of any chord binding
                for chord_seq in mode.chord_keybindings.keys() {
                    if chord_seq.len() > sequence.len()
                        && chord_seq[..sequence.len()] == sequence[..]
                    {
                        return true;
                    }
                }
                current_mode_name = mode.parent.as_deref();
            } else {
                break;
            }
        }

        false
    }

    /// Resolve a chord keybinding (multi-key sequence) for a mode
    ///
    /// Returns the command name if the full sequence matches a chord binding.
    pub fn resolve_chord_keybinding(
        &self,
        mode_name: &str,
        chord_state: &[(KeyCode, KeyModifiers)],
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> Option<String> {
        // Normalize the key
        let (code, modifiers) = Self::normalize_key(code, modifiers);

        // Build the full sequence
        let mut sequence: Vec<(KeyCode, KeyModifiers)> = chord_state
            .iter()
            .map(|(c, m)| Self::normalize_key(*c, *m))
            .collect();
        sequence.push((code, modifiers));

        tracing::trace!(
            "resolve_chord_keybinding: mode={}, sequence={:?}",
            mode_name,
            sequence
        );

        let mut current_mode_name = Some(mode_name);

        // Walk up the inheritance chain
        while let Some(name) = current_mode_name {
            if let Some(mode) = self.modes.get(name) {
                // Check for exact match
                if let Some(command) = mode.chord_keybindings.get(&sequence) {
                    tracing::trace!("  -> found chord binding: {}", command);
                    return Some(command.clone());
                }
                current_mode_name = mode.parent.as_deref();
            } else {
                break;
            }
        }

        tracing::trace!("  -> no chord binding found");
        None
    }

    /// List all registered mode names
    pub fn list_modes(&self) -> Vec<String> {
        self.modes.keys().cloned().collect()
    }

    /// Check if a mode exists
    pub fn has_mode(&self, name: &str) -> bool {
        self.modes.contains_key(name)
    }

    /// Get all keybindings for a mode (including inherited ones)
    ///
    /// Returns bindings from most specific (this mode) to least specific (root parent).
    /// Later bindings override earlier ones.
    pub fn get_all_keybindings(&self, mode_name: &str) -> HashMap<(KeyCode, KeyModifiers), String> {
        let mut result = HashMap::new();
        let mut chain = Vec::new();

        // Build inheritance chain (root first)
        let mut current = Some(mode_name);
        while let Some(name) = current {
            if let Some(mode) = self.modes.get(name) {
                chain.push(mode);
                current = mode.parent.as_deref();
            } else {
                break;
            }
        }

        // Apply bindings from root to leaf (so leaf overrides)
        for mode in chain.into_iter().rev() {
            result.extend(mode.keybindings.clone());
        }

        result
    }
}

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

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

    #[test]
    fn test_special_mode_exists() {
        let registry = ModeRegistry::new();
        assert!(registry.has_mode("special"));
    }

    #[test]
    fn test_special_mode_keybindings() {
        let registry = ModeRegistry::new();
        let mode = registry.get("special").unwrap();

        assert_eq!(
            mode.keybindings
                .get(&(KeyCode::Char('q'), KeyModifiers::NONE)),
            Some(&"close".to_string())
        );
        assert_eq!(
            mode.keybindings
                .get(&(KeyCode::Char('g'), KeyModifiers::NONE)),
            Some(&"revert".to_string())
        );
    }

    #[test]
    fn test_mode_inheritance() {
        let mut registry = ModeRegistry::new();

        // Create a child mode that inherits from special
        let diagnostics_mode = BufferMode::new("diagnostics-list")
            .with_parent("special")
            .with_binding(KeyCode::Enter, KeyModifiers::NONE, "diagnostics:goto")
            .with_binding(KeyCode::Char('n'), KeyModifiers::NONE, "next-line");

        registry.register(diagnostics_mode);

        // Should find direct binding
        assert_eq!(
            registry.resolve_keybinding("diagnostics-list", KeyCode::Enter, KeyModifiers::NONE),
            Some("diagnostics:goto".to_string())
        );

        // Should find inherited binding from special mode
        assert_eq!(
            registry.resolve_keybinding("diagnostics-list", KeyCode::Char('q'), KeyModifiers::NONE),
            Some("close".to_string())
        );

        // Should not find non-existent binding
        assert_eq!(
            registry.resolve_keybinding("diagnostics-list", KeyCode::Char('x'), KeyModifiers::NONE),
            None
        );
    }

    #[test]
    fn test_mode_read_only_inheritance() {
        let mut registry = ModeRegistry::new();

        // Special mode is read-only
        assert!(registry.is_read_only("special"));

        // Child mode inherits read-only
        let child_mode = BufferMode::new("child").with_parent("special");
        registry.register(child_mode);
        assert!(registry.is_read_only("child"));

        // Non-special mode is not read-only
        let editable_mode = BufferMode::new("editable");
        registry.register(editable_mode);
        assert!(!registry.is_read_only("editable"));
    }

    #[test]
    fn test_get_all_keybindings() {
        let mut registry = ModeRegistry::new();

        let child_mode = BufferMode::new("child")
            .with_parent("special")
            .with_binding(KeyCode::Enter, KeyModifiers::NONE, "child:action")
            // Override parent binding
            .with_binding(KeyCode::Char('q'), KeyModifiers::NONE, "child:quit");

        registry.register(child_mode);

        let all_bindings = registry.get_all_keybindings("child");

        // Should have overridden 'q'
        assert_eq!(
            all_bindings.get(&(KeyCode::Char('q'), KeyModifiers::NONE)),
            Some(&"child:quit".to_string())
        );

        // Should have inherited 'g'
        assert_eq!(
            all_bindings.get(&(KeyCode::Char('g'), KeyModifiers::NONE)),
            Some(&"revert".to_string())
        );

        // Should have child-specific binding
        assert_eq!(
            all_bindings.get(&(KeyCode::Enter, KeyModifiers::NONE)),
            Some(&"child:action".to_string())
        );
    }
}