edamame 0.1.2

A fast TUI Markdown editor and viewer
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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::config::{Action, KeyMap};
use crate::editor::{EditorState, Mode};

use super::diff_keys;
use super::ModeHandler;

/// The default (non-modal) keybinding handler.
///
/// Priority:
/// 1. If the key is in the `KeyMap`, return the bound action.
/// 2. If the key is a printable character (no non-Shift modifier), return
///    `InsertChar` when in Rendered or Raw mode (or when transitioning from
///    Preview — the editor state machine handles the mode switch).
/// 3. Otherwise return `None`.
pub struct DefaultHandler<'k> {
    keymap: &'k KeyMap,
}

impl<'k> DefaultHandler<'k> {
    pub fn new(keymap: &'k KeyMap) -> Self {
        Self { keymap }
    }
}

impl<'k> ModeHandler for DefaultHandler<'k> {
    fn handle(&mut self, event: KeyEvent, state: &EditorState) -> Option<Action> {
        // Diff Review sub-mode owns the keymap.  Bare keys (`y` /
        // `n` / `Y` / `N` / `i` / Tab / Shift-Tab / Enter / Esc) are
        // mapped to diff actions before the global keymap gets a
        // look-in, because the global keymap binds Tab to
        // `InsertTab` etc.  Review's bindings are hard-coded here;
        // there is no Edit sub-mode yet.
        if state.mode == Mode::Diff {
            if let Some(action) = diff_review_handle(&event) {
                return Some(action);
            }
        }

        // The search flow owns its keys the same way: search keys map to
        // search actions before the global keymap gets a look-in (which
        // would otherwise turn Tab into `InsertTab` and Esc into
        // `ExitToPreview`).  A *capturing* replace flow intercepts the full
        // set (`Tab`/`Shift+Tab`/`r`/`a`/`Esc`); a non-capturing navigate
        // flow intercepts only the navigation keys (`Tab`/`Shift+Tab`/`Esc`)
        // so `r`/`a` and every printable key fall through to normal editing
        // with the match highlights left in place.
        if let Some(search) = state.search.as_ref() {
            if let Some(action) = crate::search::search_action_for(&event) {
                let capturing = search.is_replace_flow();
                if capturing
                    || matches!(
                        action,
                        Action::SearchNext | Action::SearchPrev | Action::SearchExit
                    )
                {
                    return Some(action);
                }
            }
        }

        // 1. Check the keymap first (explicit bindings take priority).
        if let Some(action) = self.keymap.action_for(&event) {
            // Preview-mode guard: Ctrl-* chords must not cause an implicit
            // transition into edit mode — users want to read and copy in
            // Preview without `Ctrl+Z`, `Ctrl+D`, `Ctrl+Left`, etc.
            // exiting it on them.  Drop any Ctrl-bound action that isn't on
            // the Preview-safe allow-list.
            if state.mode == Mode::Preview
                && event.modifiers.contains(KeyModifiers::CONTROL)
                && !preview_safe_action(action)
            {
                return None;
            }
            return Some(action.clone());
        }

        // 2. Ctrl+Backspace fallbacks. Different terminals encode this chord
        //    wildly differently; none of the encodings below is covered by the
        //    `ctrl+backspace` binding (which matches `KeyCode::Backspace` with
        //    exactly `CONTROL`).  We also match on `modifiers.contains(CONTROL)`
        //    rather than strict equality so combinations like Ctrl+Shift+BS also
        //    delete a word back.
        if is_ctrl_backspace(&event) {
            // Same Preview guard — ctrl+backspace is destructive, no-op in
            // Preview.
            if state.mode == Mode::Preview {
                return None;
            }
            return Some(Action::DeleteWordBack);
        }

        // 3. Printable character → InsertChar (in any mode; edit_ops handles
        //    the preview → rendered transition).
        if let KeyCode::Char(ch) = event.code {
            let only_shift =
                event.modifiers == KeyModifiers::NONE || event.modifiers == KeyModifiers::SHIFT;
            if only_shift {
                return Some(Action::InsertChar(ch));
            }
        }

        None
    }
}

/// Actions that are allowed to run in Preview mode when triggered by a
/// Ctrl-* key chord.  Everything else gets suppressed by the handler so
/// Preview-mode users can safely read and copy without their clipboard /
/// quit / selection chords accidentally dropping them into edit mode.
fn preview_safe_action(action: &Action) -> bool {
    matches!(
        action,
        Action::Quit
            | Action::Copy
            | Action::SelectAll
            | Action::Save
            | Action::Open
            | Action::ToggleRawMode
            | Action::EnterEditMode
            | Action::ExitToPreview
            | Action::ScrollUp
            | Action::ScrollDown
            | Action::ScrollPageUp
            | Action::ScrollPageDown
            | Action::ScrollToTop
            | Action::ScrollToBottom
            // Overlay-opening actions are read-only:
            // they pop a modal that absorbs subsequent input.
            // Suppressing them in Preview would leave Ctrl-P unable
            // to launch the command palette while the user is just
            // browsing.
            | Action::ShowCommandPalette
            | Action::ShowMarkdownCheatSheet
            // Opening the manual replaces the document rather than
            // popping a modal, but it is read-only in the sense that
            // matters here: it starts no edit and the dirty guard
            // protects anything unsaved.
            | Action::OpenDoc(_)
            | Action::ShowAbout
            | Action::CheckForUpdates
            | Action::OpenSettings
            | Action::OpenWelcome
            | Action::OpenKeybinds
            | Action::SwitchTheme
            | Action::CreateCustomTheme
            | Action::ExportHtml
            | Action::OpenConfigFolder
            // Both are palette-only by default but a user may bind a
            // chord — allow them to fire from Preview without first
            // entering edit mode.  `OpenInExternalEditor` saves and
            // suspends the TUI; `ToggleTableButtons` flips a config
            // flag — neither needs the buffer to be in an editing mode.
            | Action::OpenInExternalEditor
            | Action::ToggleTableButtons
            // The persisted setting toggles are likewise palette-only by
            // default but bind-able; each is a buffer-read-only config
            // flip, safe to fire while browsing in Preview.
            | Action::ToggleBigH1
            | Action::ToggleLineNumbers
            | Action::ToggleBlinkCursor
            | Action::ToggleAutosave
            | Action::ToggleVisualLineNav
            | Action::ToggleVimMode
            | Action::ToggleLimitWidth
            | Action::ToggleDiffOnChange
            // `InsertTable` is allowed from Preview so
            // the default Ctrl+Shift+T chord opens the rows/columns
            // modal without requiring the user to enter edit mode
            // first.  The modal itself absorbs subsequent input;
            // pre-flight blank-line checks fire only when the user
            // hits Insert.
            | Action::InsertTable
            // `SaveAs` opens a path-input modal — read-only with respect
            // to the buffer until the user submits a path, so it's safe to
            // launch from Preview.
            | Action::SaveAs
            // `GoToSection` opens the heading-jump picker; the cursor
            // motion that Enter applies is benign in Preview because
            // the cursor isn't drawn there anyway.
            | Action::GoToSection
            // `OpenSearch` opens the search/replace modal — read-only
            // with respect to the buffer until the user confirms, so
            // Ctrl+F works while just browsing in Preview.
            | Action::OpenSearch
    )
}

/// Map a bare key to the corresponding diff-Review action, mirroring
/// the §9 default bind table.  Returns `None` for keys that aren't
/// diff-specific — those fall through to the global keymap (which
/// handles `Ctrl-Q` / `Ctrl-S` / overlay openers / scrolling
/// uniformly across modes).
///
/// Hard-coded rather than read from a separate KeyMap because the
/// review bindings need to win over the global keymap's `Tab` →
/// `InsertTab`.  This could become a proper layered keymap once an
/// Edit sub-mode lands and rebinding review keys matters.
///
/// The mapping itself lives in `diff_keys::DIFF_REVIEW_BINDINGS` — the
/// single source of truth shared with the hint bar, keybinds overlay,
/// decision divider, and diff-intro modal — so behavior and the
/// displayed glyphs can never drift.
fn diff_review_handle(event: &KeyEvent) -> Option<Action> {
    diff_keys::diff_action_for(event)
}

/// Does this event represent Ctrl+Backspace in some terminal's encoding?
///
/// - kitty keyboard protocol: `Backspace` + CONTROL
/// - xterm / macOS Terminal / older Alacritty: raw `\x08` (Ctrl+H in ASCII)
///   with or without the CONTROL modifier (crossterm may or may not set it)
/// - urxvt, modern Alacritty without kitty protocol: `\x7f` + CONTROL
/// - Some terminals translate Ctrl+Backspace to Ctrl+H directly: `h`/`H` + CONTROL
pub(crate) fn is_ctrl_backspace(event: &KeyEvent) -> bool {
    let has_ctrl = event.modifiers.contains(KeyModifiers::CONTROL);
    match event.code {
        KeyCode::Backspace if has_ctrl => true,
        KeyCode::Char('\x08') => true,
        KeyCode::Char('\x7f') if has_ctrl => true,
        KeyCode::Char('h') | KeyCode::Char('H') if has_ctrl => true,
        _ => false,
    }
}

/// Does this event represent Ctrl+Delete?  Unlike Ctrl+Backspace there is no
/// ASCII control-code encoding, so every terminal reports it as the `Delete`
/// key with the CONTROL modifier set.
pub(crate) fn is_ctrl_delete(event: &KeyEvent) -> bool {
    matches!(event.code, KeyCode::Delete) && event.modifiers.contains(KeyModifiers::CONTROL)
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{KeyBindingOverrides, KeyMap};
    use crate::document::Buffer;
    use crate::editor::{EditorState, Mode};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn keymap() -> KeyMap {
        KeyMap::build(&KeyBindingOverrides::default()).unwrap()
    }

    fn state(mode: Mode) -> EditorState {
        let theme = Box::leak(Box::new(crate::config::Theme::default()));
        let mut s = EditorState::new(Buffer::new(), theme);
        s.mode = mode;
        s
    }

    // ── Read-only documentation pages ─────────────────────────────

    fn readonly_state(mode: Mode) -> EditorState {
        let mut s = state(mode);
        s.readonly = true;
        s
    }

    /// A read-only page has **no bespoke key table**: it resolves every
    /// key through the ordinary keymap, exactly as an editable document
    /// does.  There was briefly a vim-flavored scroll table here
    /// (`j`/`k`, `Ctrl-D`/`Ctrl-U`, `Space`); it was removed, and this
    /// is the guard that it does not creep back.  Scrolling a page is
    /// the arrow keys, `PageUp`/`PageDown`, `Home`/`End` and the wheel,
    /// which the keymap already owns.
    #[test]
    fn a_read_only_page_resolves_keys_through_the_ordinary_keymap() {
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let readonly = readonly_state(Mode::Preview);
        let editable = state(Mode::Preview);
        for (code, mods) in [
            (KeyCode::Char('j'), KeyModifiers::NONE),
            (KeyCode::Char('k'), KeyModifiers::NONE),
            (KeyCode::Char('g'), KeyModifiers::NONE),
            (KeyCode::Char(' '), KeyModifiers::NONE),
            (KeyCode::Char('d'), KeyModifiers::CONTROL),
            (KeyCode::Char('u'), KeyModifiers::CONTROL),
            (KeyCode::Home, KeyModifiers::NONE),
            (KeyCode::End, KeyModifiers::NONE),
        ] {
            let ev = KeyEvent::new(code, mods);
            assert_eq!(
                h.handle(ev, &readonly),
                h.handle(ev, &editable),
                "{code:?} must resolve the same on a read-only page"
            );
        }
    }

    /// Preview's "press any key to edit" is unchanged — `j` starts
    /// editing an ordinary document, and is merely refused downstream
    /// on a read-only one.
    #[test]
    fn an_ordinary_preview_still_edits_on_a_letter_key() {
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let st = state(Mode::Preview);
        assert_eq!(
            h.handle(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE), &st),
            Some(Action::InsertChar('j'))
        );
    }

    /// Falling through is what keeps every bound chord working: the
    /// table only claims the handful of keys it lists.
    #[test]
    fn unbound_keys_still_reach_the_keymap_on_a_read_only_page() {
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let st = readonly_state(Mode::Preview);
        assert_eq!(
            h.handle(
                KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL),
                &st
            ),
            Some(Action::Quit)
        );
    }

    /// The handler knows nothing about `readonly` at all.
    ///
    /// It used to answer `None` for every unbound key on a read-only
    /// page, because the App's gate flashed "read-only" once per
    /// keystroke and a hand resting on the letter keys would strobe the
    /// hint line.  Both halves of that are gone: a read-only document
    /// rests in Preview, where `edit_ops::enter_edit_if_preview` refuses
    /// the transition (and `apply_delta` the write) *silently*.  So the
    /// synthesized action is produced and then goes nowhere, which is
    /// one guard instead of two.
    #[test]
    fn a_read_only_page_no_longer_suppresses_the_keymap_bypassing_arms() {
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let st = readonly_state(Mode::Preview);
        // Arm 3: a printable key with no reading binding.
        assert_eq!(
            h.handle(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE), &st),
            Some(Action::InsertChar('z'))
        );
        // Arm 2: a `Ctrl-Backspace` encoding the keymap does not match.
        // Dropped in Preview by the Preview guard, not by `readonly`.
        let ev = KeyEvent::new(
            KeyCode::Backspace,
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        );
        assert_eq!(h.handle(ev, &st), None);
        assert_eq!(
            h.handle(ev, &readonly_state(Mode::Rendered)),
            Some(Action::DeleteWordBack)
        );
    }

    #[test]
    fn bound_chords_still_resolve_on_a_read_only_page() {
        // Every bound chord still produces its action; the App's
        // `readonly_safe_action` decides which of them may run.
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let st = readonly_state(Mode::Rendered);
        let ev = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL);
        assert_eq!(h.handle(ev, &st), Some(Action::Quit));
    }

    #[test]
    fn an_ordinary_document_still_types() {
        let km = keymap();
        let mut h = DefaultHandler::new(&km);
        let st = state(Mode::Rendered);
        assert_eq!(
            h.handle(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE), &st),
            Some(Action::InsertChar('a'))
        );
    }

    #[test]
    fn ctrl_q_returns_quit() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        let event = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL);
        assert_eq!(
            handler.handle(event, &state(Mode::Preview)),
            Some(Action::Quit)
        );
    }

    #[test]
    fn printable_char_returns_insert() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        let event = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        assert_eq!(
            handler.handle(event, &state(Mode::Rendered)),
            Some(Action::InsertChar('a'))
        );
    }

    #[test]
    fn ctrl_char_not_insert() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        // Ctrl+A is bound to MoveLineStart, not InsertChar.
        let event = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL);
        let action = handler.handle(event, &state(Mode::Rendered));
        assert_ne!(action, Some(Action::InsertChar('a')));
    }

    #[test]
    fn ctrl_c_returns_copy() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        let event = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert_eq!(
            handler.handle(event, &state(Mode::Rendered)),
            Some(Action::Copy)
        );
    }

    #[test]
    fn preview_ctrl_c_and_ctrl_a_still_fire() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        // Clipboard and select-all are allowed in Preview.
        assert_eq!(
            handler.handle(
                KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
                &state(Mode::Preview)
            ),
            Some(Action::Copy)
        );
        assert_eq!(
            handler.handle(
                KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL),
                &state(Mode::Preview)
            ),
            Some(Action::SelectAll)
        );
        // Quit must always be allowed.
        assert_eq!(
            handler.handle(
                KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL),
                &state(Mode::Preview)
            ),
            Some(Action::Quit)
        );
    }

    #[test]
    fn preview_suppresses_non_safelisted_ctrl_chords() {
        let km = keymap();
        let mut handler = DefaultHandler::new(&km);
        // Ctrl+Z (Undo) and Ctrl+D (DeleteLine) would normally enter edit
        // mode; in Preview they must drop out so the user stays in read mode.
        for ch in ['z', 'd', 'x', 'v'] {
            let event = KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL);
            assert_eq!(
                handler.handle(event, &state(Mode::Preview)),
                None,
                "ctrl+{ch} should be suppressed in Preview mode",
            );
        }
    }
}