chronogit 0.4.0

A read-only terminal UI for Git history, diffs, and source code
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
//! Translation from terminal key events to semantic application actions.
//!
//! Built-in Vim-oriented bindings can be selectively replaced by an optional
//! keymap file. Multi-key sequences are resolved without ambiguous prefixes and
//! expire after 750 milliseconds.

mod config;

use std::path::Path;
use std::time::{Duration, Instant};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::{Action, SearchDirection, SemanticNavigationKind};

pub use config::KeyMapError;

const SEQUENCE_TIMEOUT: Duration = Duration::from_millis(750);

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(super) struct KeyStroke {
    code: KeyCode,
    modifiers: KeyModifiers,
}

impl KeyStroke {
    fn from_event(key: KeyEvent) -> Self {
        let mut modifiers = key.modifiers;
        if matches!(key.code, KeyCode::Char(_)) {
            modifiers.remove(KeyModifiers::SHIFT);
        }
        modifiers &= KeyModifiers::CONTROL | KeyModifiers::ALT;
        Self {
            code: key.code,
            modifiers,
        }
    }

    pub(super) fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
        Self { code, modifiers }
    }
}

#[derive(Clone, Debug)]
pub(super) struct Binding {
    sequence: Vec<KeyStroke>,
    action: Action,
}

impl Binding {
    pub(super) fn new(sequence: Vec<KeyStroke>, action: Action) -> Self {
        Self { sequence, action }
    }
}

/// Stateful key-to-action translator with support for multi-key sequences.
///
/// `Ctrl-C` is reserved for [`Action::Quit`] regardless of configuration. While
/// a search prompt is active, printable characters edit the query and pending
/// normal-mode sequences are cleared.
#[derive(Debug)]
pub struct KeyMapper {
    bindings: Vec<Binding>,
    pending: Vec<KeyStroke>,
    pending_since: Option<Instant>,
}

impl KeyMapper {
    /// Creates a mapper using all built-in bindings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            bindings: config::default_bindings(),
            pending: Vec::new(),
            pending_since: None,
        }
    }

    /// Loads built-in bindings with optional validated overrides.
    ///
    /// An explicit `path` must exist. With `None`, the mapper tries
    /// `$XDG_CONFIG_HOME/chronogit/keymap.conf` and then
    /// `~/.config/chronogit/keymap.conf`; a missing implicit file falls back to
    /// defaults.
    ///
    /// # Errors
    ///
    /// Returns [`KeyMapError`] when a selected file cannot be read, contains an
    /// unknown action or key, or introduces duplicate or prefix-ambiguous keys.
    pub fn load(path: Option<&Path>) -> Result<Self, KeyMapError> {
        Ok(Self {
            bindings: config::load_bindings(path)?,
            pending: Vec::new(),
            pending_since: None,
        })
    }

    /// Consumes one key event and returns a completed semantic action.
    ///
    /// `None` means the key is either unbound or is a valid prefix awaiting the
    /// next stroke. `search_input_active` switches printable keys to query-edit
    /// actions while retaining the reserved focus, confirmation, cancellation,
    /// and `Ctrl-C` controls.
    pub fn map(&mut self, key: KeyEvent, search_input_active: bool) -> Option<Action> {
        if matches!(key.code, KeyCode::Char('c')) && key.modifiers.contains(KeyModifiers::CONTROL) {
            self.clear_pending();
            return Some(Action::Quit);
        }
        if search_input_active {
            self.clear_pending();
            return match (key.code, key.modifiers) {
                (KeyCode::Enter, _) => Some(Action::ConfirmSearch),
                (KeyCode::Esc, _) => Some(Action::CancelSearch),
                (KeyCode::Char('j'), modifiers)
                    if modifiers.contains(KeyModifiers::CONTROL)
                        && !modifiers.contains(KeyModifiers::ALT) =>
                {
                    Some(Action::FocusRight)
                }
                (KeyCode::Char('k'), modifiers)
                    if modifiers.contains(KeyModifiers::CONTROL)
                        && !modifiers.contains(KeyModifiers::ALT) =>
                {
                    Some(Action::FocusLeft)
                }
                (KeyCode::Backspace, _) => Some(Action::DeleteSearch),
                (KeyCode::Char(character), modifiers)
                    if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
                {
                    Some(Action::InsertSearch(character))
                }
                _ => None,
            };
        }

        if self
            .pending_since
            .is_some_and(|started| started.elapsed() > SEQUENCE_TIMEOUT)
        {
            self.clear_pending();
        }
        let stroke = KeyStroke::from_event(key);
        self.pending.push(stroke.clone());
        if let Some(action) = self.resolve_pending() {
            return Some(action);
        }
        if self
            .bindings
            .iter()
            .any(|binding| binding.sequence.starts_with(&self.pending))
        {
            self.pending_since.get_or_insert_with(Instant::now);
            return None;
        }

        self.clear_pending();
        self.pending.push(stroke);
        if let Some(action) = self.resolve_pending() {
            return Some(action);
        }
        if self
            .bindings
            .iter()
            .any(|binding| binding.sequence.starts_with(&self.pending))
        {
            self.pending_since = Some(Instant::now());
        } else {
            self.clear_pending();
        }
        None
    }

    fn resolve_pending(&mut self) -> Option<Action> {
        let action = self
            .bindings
            .iter()
            .find(|binding| binding.sequence == self.pending)
            .map(|binding| binding.action)?;
        let has_longer = self.bindings.iter().any(|binding| {
            binding.sequence.len() > self.pending.len()
                && binding.sequence.starts_with(&self.pending)
        });
        if has_longer {
            None
        } else {
            self.clear_pending();
            Some(action)
        }
    }

    fn clear_pending(&mut self) {
        self.pending.clear();
        self.pending_since = None;
    }
}

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

pub(super) fn action_for_name(name: &str) -> Option<Action> {
    match name {
        "quit" => Some(Action::Quit),
        "show_changes" => Some(Action::ShowChanges),
        "show_history" => Some(Action::ShowHistory),
        "show_graph" => Some(Action::ShowGraph),
        "show_code" => Some(Action::ShowCode),
        "focus_previous" => Some(Action::FocusLeft),
        "focus_next" => Some(Action::FocusRight),
        "move_up" => Some(Action::MoveUp),
        "move_down" => Some(Action::MoveDown),
        "move_top" => Some(Action::MoveTop),
        "move_bottom" => Some(Action::MoveBottom),
        "half_page_up" => Some(Action::HalfPageUp),
        "half_page_down" => Some(Action::HalfPageDown),
        "scroll_left" => Some(Action::ScrollLeft),
        "scroll_right" => Some(Action::ScrollRight),
        "cursor_left" => Some(Action::MoveCursorLeft),
        "cursor_right" => Some(Action::MoveCursorRight),
        "lsp_hover" => Some(Action::ToggleLspHover),
        "go_to_definition" => Some(Action::GoToSemanticTarget(
            SemanticNavigationKind::Definition,
        )),
        "go_to_implementation" => Some(Action::GoToSemanticTarget(
            SemanticNavigationKind::Implementation,
        )),
        "go_to_type_definition" => Some(Action::GoToSemanticTarget(
            SemanticNavigationKind::TypeDefinition,
        )),
        "go_to_declaration" => Some(Action::GoToSemanticTarget(
            SemanticNavigationKind::Declaration,
        )),
        "semantic_back" => Some(Action::GoBackFromSemanticTarget),
        "semantic_forward" => Some(Action::GoForwardFromSemanticTarget),
        "refresh" => Some(Action::Refresh),
        "toggle_message" => Some(Action::ToggleMessage),
        "toggle_details" => Some(Action::ToggleDetails),
        "toggle_tree" => Some(Action::ToggleTree),
        "activate" => Some(Action::Activate),
        "file_search" => Some(Action::OpenFileSearch),
        "content_search" => Some(Action::OpenContentSearch),
        "search_forward" => Some(Action::StartSearch(SearchDirection::Forward)),
        "search_backward" => Some(Action::StartSearch(SearchDirection::Backward)),
        "next_match" => Some(Action::NextMatch),
        "previous_match" => Some(Action::PreviousMatch),
        "toggle_help" => Some(Action::ToggleHelp),
        "close" => Some(Action::CloseOverlay),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    use super::KeyMapper;
    use crate::app::{Action, SemanticNavigationKind};

    #[test]
    fn maps_navigation_sequences_graph_and_global_search() {
        let mut mapper = KeyMapper::new();
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), false),
            Some(Action::CloseOverlay)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), false),
            Some(Action::CloseOverlay)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT),
                false
            ),
            Some(Action::Quit)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL),
                false
            ),
            Some(Action::FocusRight)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL),
                false
            ),
            Some(Action::FocusLeft)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE), false),
            Some(Action::MoveDown)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE), false),
            Some(Action::MoveCursorLeft)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::NONE), false),
            Some(Action::MoveCursorRight)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE), false),
            None
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::NONE), false),
            Some(Action::ScrollRight)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('3'), KeyModifiers::NONE), false),
            Some(Action::ShowGraph)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('4'), KeyModifiers::NONE), false),
            Some(Action::ShowCode)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE), false),
            None
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::NONE), false),
            Some(Action::OpenFileSearch)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE), false),
            None
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE), false),
            Some(Action::MoveTop)
        );
        for (suffix, kind) in [
            ('d', SemanticNavigationKind::Definition),
            ('i', SemanticNavigationKind::Implementation),
            ('y', SemanticNavigationKind::TypeDefinition),
            ('D', SemanticNavigationKind::Declaration),
        ] {
            assert_eq!(
                mapper.map(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE), false),
                None
            );
            assert_eq!(
                mapper.map(
                    KeyEvent::new(KeyCode::Char(suffix), KeyModifiers::NONE),
                    false
                ),
                Some(Action::GoToSemanticTarget(kind))
            );
        }
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE), false),
            Some(Action::MoveCursorRight)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('K'), KeyModifiers::SHIFT),
                false
            ),
            Some(Action::ToggleLspHover)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('o'), KeyModifiers::CONTROL),
                false
            ),
            Some(Action::GoBackFromSemanticTarget)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('i'), KeyModifiers::CONTROL),
                false
            ),
            Some(Action::GoForwardFromSemanticTarget)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE), false),
            Some(Action::GoForwardFromSemanticTarget)
        );
    }

    #[test]
    fn search_input_accepts_q_and_reserves_control_keys() {
        let mut mapper = KeyMapper::new();
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), true),
            Some(Action::InsertSearch('q'))
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT), true),
            Some(Action::InsertSearch('Q'))
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE), true),
            Some(Action::DeleteSearch)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), true),
            Some(Action::ConfirmSearch)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL),
                true
            ),
            Some(Action::FocusRight)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL),
                true
            ),
            Some(Action::FocusLeft)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
                true
            ),
            Some(Action::Quit)
        );
    }

    #[test]
    fn explicit_config_replaces_selected_defaults() {
        let directory = tempfile::tempdir()
            .unwrap_or_else(|error| panic!("could not create temp directory: {error}"));
        let path = directory.path().join("keymap.conf");
        fs::write(
            &path,
            "[bindings]\nshow_graph = x\nfile_search = ctrl-p\ntoggle_tree = f\nsemantic_forward = tab\n",
        )
        .unwrap_or_else(|error| panic!("could not write keymap: {error}"));
        let mut mapper = KeyMapper::load(Some(&path)).unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), false),
            Some(Action::ShowGraph)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('3'), KeyModifiers::NONE), false),
            None
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL),
                false
            ),
            Some(Action::OpenFileSearch)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::NONE), false),
            Some(Action::ToggleTree)
        );
        assert_eq!(
            mapper.map(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE), false),
            Some(Action::GoForwardFromSemanticTarget)
        );
        assert_eq!(
            mapper.map(
                KeyEvent::new(KeyCode::Char('i'), KeyModifiers::CONTROL),
                false
            ),
            None,
            "an explicit semantic_forward binding replaces its defaults"
        );
    }

    #[test]
    fn invalid_or_ambiguous_config_is_rejected() {
        let directory = tempfile::tempdir()
            .unwrap_or_else(|error| panic!("could not create temp directory: {error}"));
        let path = directory.path().join("keymap.conf");
        fs::write(&path, "unknown = x\n")
            .unwrap_or_else(|error| panic!("could not write keymap: {error}"));
        assert!(KeyMapper::load(Some(&path)).is_err());
        fs::write(&path, "show_graph = space\nfile_search = space f\n")
            .unwrap_or_else(|error| panic!("could not write keymap: {error}"));
        assert!(KeyMapper::load(Some(&path)).is_err());
        fs::write(&path, "show_graph = f0\n")
            .unwrap_or_else(|error| panic!("could not write keymap: {error}"));
        assert!(KeyMapper::load(Some(&path)).is_err());
    }
}