edamame 0.1.5

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
468
469
470
471
472
473
474
475
476
//! Fuzzy-searchable command palette.  An empty query shows every action in named sections;
//! typing collapses them into a flat [`SearchableList`] ranking.  UI-only: selecting a row
//! yields an [`Action`] that the adapter dispatches through `edit_ops::apply`.

mod actions;

use self::actions::{label_for, ALL_ACTIONS};

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    text::{Line, Span},
};

use crate::config::{Action, KeyMap, Theme};
use crate::ui::content_width::max_row_width;
use crate::ui::modal_row::{format_modal_row, RowLayout};
use crate::ui::searchable_list::{
    draw_searchable_list_modal, ListModalOpts, RowCtx, SearchableList, VisibleRow, MAX_LIST_ROWS,
};

/// One palette row.  The chord is shown beside the label so users learn bindings organically.
#[derive(Debug, Clone)]
pub struct PaletteEntry {
    pub action: Action,
    pub label: String,
    pub chord: Option<String>,
}

const PLACEHOLDER: &str = "Search commands…";

/// Width of the "(no matches)" copy, a floor on the modal width.
const NO_MATCHES_WIDTH: u16 = 12;

/// Build the palette's list component from `keymap`.
///
/// A single `Export…` entry covers every target; the format is chosen inside the export modal.
/// `vim_enabled` drops `Exit to preview`: vim never rests in Preview, so the action would flip
/// the editor there only for the next keystroke to leave again.  The keybinds overlay and the
/// hint line hide it for the same reason.
pub fn build_palette_list(keymap: &KeyMap, vim_enabled: bool) -> SearchableList<PaletteEntry> {
    SearchableList::new(build_entries(keymap, vim_enabled), |e: &PaletteEntry| {
        e.label.as_str()
    })
    .with_sections(palette_sections)
}

/// Render the palette modal; returns the `esc` close-hint rect for click hit-testing.
pub fn render_palette(
    list: &mut SearchableList<PaletteEntry>,
    area: Rect,
    buf: &mut Buffer,
    theme: &Theme,
    cursor_visible: bool,
) -> Option<Rect> {
    let content_width = palette_content_width(list.items())
        .max(NO_MATCHES_WIDTH)
        .max(PLACEHOLDER.chars().count() as u16 + 2);
    draw_searchable_list_modal(
        list,
        area,
        buf,
        ListModalOpts {
            title: "Command Palette",
            content_width,
            max_list_rows: MAX_LIST_ROWS,
            vertical_pad: 0,
            theme,
            cursor_visible,
            placeholder: PLACEHOLDER,
            empty_text: "(no matches)",
        },
        |ctx| match ctx {
            RowCtx::Header { title, width } => format_section_header(title, theme, width),
            RowCtx::Item {
                item,
                focused,
                width,
            } => format_row(item, focused, theme, width),
        },
    )
}

/// Body width: max over all entries of `marker(2) + label + gap(1) + chord`.  Sized on the whole
/// list so the modal doesn't jiggle as the user filters.
fn palette_content_width(entries: &[PaletteEntry]) -> u16 {
    max_row_width(entries, |e| {
        let label_w = e.label.chars().count();
        let chord_w = e.chord.as_deref().map(|c| c.chars().count()).unwrap_or(0);
        2 + label_w + 1 + chord_w
    })
}

fn format_row(entry: &PaletteEntry, focused: bool, theme: &Theme, width: u16) -> Line<'static> {
    let chord = entry.chord.as_deref().unwrap_or("");
    format_modal_row(
        &entry.label,
        chord,
        focused,
        false,
        theme,
        RowLayout::RightAlign(width),
    )
}

/// `─ Title ───────`
fn format_section_header(title: &str, theme: &Theme, width: u16) -> Line<'static> {
    let prefix = format!("─ {} ", title);
    let prefix_w = prefix.chars().count();
    let remaining = (width as usize).saturating_sub(prefix_w);
    let text = format!("{}{}", prefix, "─".repeat(remaining));
    Line::from(Span::styled(text, theme.modal_section_heading))
}

/// Empty-query layout: `Suggested` in curated order, then each category in [`SECTION_ORDER`].
/// Suggested actions also appear in their category.
fn palette_sections(entries: &[PaletteEntry]) -> Vec<VisibleRow> {
    let mut rows = Vec::new();
    rows.push(VisibleRow::Header("Suggested".to_owned()));
    let mut suggested: Vec<usize> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| is_suggested(&e.action))
        .map(|(i, _)| i)
        .collect();
    suggested.sort_by_key(|&i| {
        SUGGESTED_ACTIONS
            .iter()
            .position(|a| a == &entries[i].action)
            .unwrap_or(usize::MAX)
    });
    for idx in suggested {
        rows.push(VisibleRow::Item(idx));
    }
    for &section in SECTION_ORDER {
        let items: Vec<usize> = entries
            .iter()
            .enumerate()
            .filter(|(_, e)| section_of(&e.action) == section)
            .map(|(i, _)| i)
            .collect();
        if !items.is_empty() {
            rows.push(VisibleRow::Header(section.to_owned()));
            for idx in items {
                rows.push(VisibleRow::Item(idx));
            }
        }
    }
    rows
}

/// Curated entries shown first when the palette opens with no input.
const SUGGESTED_ACTIONS: &[Action] = &[
    Action::OpenSettings,
    Action::SwitchTheme,
    Action::OpenKeybinds,
    Action::GoToSection,
    Action::InsertTable,
    Action::ToggleTableButtons,
    Action::ExportHtml,
    Action::OpenInExternalEditor,
    Action::ShowMarkdownCheatSheet,
    Action::BrowseTips,
    Action::ShowAbout,
];

fn is_suggested(action: &Action) -> bool {
    SUGGESTED_ACTIONS.contains(action)
}

/// Section order for the empty-state view; each action maps to one section via [`section_of`].
const SECTION_ORDER: &[&str] = &["File", "Edit", "View", "Navigate", "Table", "Tools"];

fn section_of(action: &Action) -> &'static str {
    match action {
        Action::Save | Action::SaveAs | Action::Open | Action::ExportHtml | Action::Quit => "File",
        Action::Undo
        | Action::Redo
        | Action::Copy
        | Action::Cut
        | Action::Paste
        | Action::SelectAll
        | Action::BoldSelection
        | Action::ItalicizeSelection
        | Action::InlineCodeSelection
        | Action::StrikethroughSelection
        | Action::HighlightSelection
        | Action::ToggleCheckbox
        | Action::InsertTable
        | Action::InsertImage
        | Action::InsertLink
        | Action::InsertFootnote
        | Action::DeleteFootnote
        | Action::RenumberFootnotes
        | Action::FixListNumbering
        | Action::PasteImage => "Edit",
        Action::ExitToPreview
        | Action::ToggleRawMode
        | Action::EnterEditMode
        | Action::ToggleTableButtons
        | Action::ToggleBigH1
        | Action::ToggleLineNumbers
        | Action::ToggleBlinkCursor
        | Action::ToggleAutosave
        | Action::ToggleVisualLineNav
        | Action::ToggleVimMode
        | Action::ToggleLimitWidth
        | Action::ToggleDiffOnChange => "View",
        Action::FollowLinkUnderCursor
        | Action::NavigateBack
        | Action::NavigateForward
        | Action::GoToSection
        | Action::OpenSearch => "Navigate",
        Action::TableMoveRowUp
        | Action::TableMoveRowDown
        | Action::TableMoveColumnLeft
        | Action::TableMoveColumnRight
        | Action::TableInsertRowAbove
        | Action::TableInsertRowBelow
        | Action::TableInsertColumnLeft
        | Action::TableInsertColumnRight
        | Action::TableDeleteRow
        | Action::TableDeleteColumn => "Table",
        Action::OpenSettings
        | Action::OpenWelcome
        | Action::OpenKeybinds
        | Action::SwitchTheme
        | Action::CreateCustomTheme
        | Action::ShowMarkdownCheatSheet
        | Action::BrowseTips
        | Action::OpenDoc(_)
        | Action::OpenInExternalEditor
        | Action::ShowAbout
        | Action::CheckForUpdates => "Tools",
        _ => "Other",
    }
}

/// The full entry list, sorted by label.  See [`build_palette_list`] for the `vim_enabled` gate.
fn build_entries(keymap: &KeyMap, vim_enabled: bool) -> Vec<PaletteEntry> {
    let mut entries: Vec<PaletteEntry> = ALL_ACTIONS
        .iter()
        .filter(|a| !(vim_enabled && **a == Action::ExitToPreview))
        .filter_map(|a| {
            let label = label_for(a)?;
            let chord = keymap.first_key_for(a);
            Some(PaletteEntry {
                action: a.clone(),
                label: label.to_owned(),
                chord,
            })
        })
        .collect();
    entries.sort_by(|a, b| a.label.cmp(&b.label));
    entries
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::KeyBindingOverrides;
    use crate::ui::searchable_list::{ListEvent, VisibleRow};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

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

    #[test]
    fn exit_to_preview_hidden_under_vim() {
        let default = build_entries(&keymap(), false);
        let vim = build_entries(&keymap(), true);
        assert!(default.iter().any(|e| e.action == Action::ExitToPreview));
        assert!(!vim.iter().any(|e| e.action == Action::ExitToPreview));
        let default_rest: Vec<&Action> = default
            .iter()
            .map(|e| &e.action)
            .filter(|a| **a != Action::ExitToPreview)
            .collect();
        let vim_all: Vec<&Action> = vim.iter().map(|e| &e.action).collect();
        assert_eq!(vim_all, default_rest);
    }

    /// Render once so the list observes its visible-window size before scroll assertions.
    fn render(list: &mut SearchableList<PaletteEntry>, w: u16, h: u16) -> String {
        use ratatui::{backend::TestBackend, Terminal};
        let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                let area = frame.area();
                render_palette(list, area, frame.buffer_mut(), theme, true);
            })
            .unwrap();
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect()
    }

    #[test]
    fn empty_state_has_suggested_section_first_in_curated_order() {
        let list = build_palette_list(&keymap(), false);
        let rows = palette_sections(list.items());
        assert!(matches!(&rows[0], VisibleRow::Header(h) if h == "Suggested"));
        let second_header = rows
            .iter()
            .skip(1)
            .position(|r| matches!(r, VisibleRow::Header(_)))
            .unwrap()
            + 1;
        let labels: Vec<String> = rows[1..second_header]
            .iter()
            .filter_map(|r| match r {
                VisibleRow::Item(i) => Some(list.items()[*i].label.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            labels,
            vec![
                "Open settings".to_owned(),
                "Switch theme".to_owned(),
                "Open keybindings".to_owned(),
                "Go to section".to_owned(),
                "Insert table".to_owned(),
                "Toggle table buttons".to_owned(),
                "Export…".to_owned(),
                "Open current file in system editor".to_owned(),
                "Show Markdown cheat sheet".to_owned(),
                "Browse tips".to_owned(),
                "About edamame".to_owned()
            ]
        );
    }

    #[test]
    fn empty_state_shows_all_actions_in_category_sections() {
        let list = build_palette_list(&keymap(), false);
        let rows = palette_sections(list.items());
        let second_header_pos = rows
            .iter()
            .skip(1)
            .position(|r| matches!(r, VisibleRow::Header(_)))
            .unwrap()
            + 1;
        let category_actions: Vec<Action> = rows[second_header_pos..]
            .iter()
            .filter_map(|r| match r {
                VisibleRow::Item(i) => Some(list.items()[*i].action.clone()),
                _ => None,
            })
            .collect();
        for action in ALL_ACTIONS {
            if label_for(action).is_some() {
                assert!(
                    category_actions.contains(action),
                    "action {action} missing from category sections"
                );
            }
        }
    }

    #[test]
    fn typing_save_file_finds_save_file() {
        let mut list = build_palette_list(&keymap(), false);
        for c in "save f".chars() {
            list.handle_key(&key(KeyCode::Char(c)));
        }
        assert_eq!(
            list.focused_item().map(|e| e.action.clone()),
            Some(Action::Save)
        );
    }

    #[test]
    fn enter_with_no_matches_is_continue() {
        let mut list = build_palette_list(&keymap(), false);
        for c in "zzzznotanything".chars() {
            list.handle_key(&key(KeyCode::Char(c)));
        }
        assert_eq!(list.match_count(), 0);
        assert_eq!(list.handle_key(&key(KeyCode::Enter)), ListEvent::Continue);
    }

    #[test]
    fn escape_cancels() {
        let mut list = build_palette_list(&keymap(), false);
        assert_eq!(list.handle_key(&key(KeyCode::Esc)), ListEvent::Cancelled);
    }

    #[test]
    fn enter_returns_focused_action() {
        let mut list = build_palette_list(&keymap(), false);
        for c in "markd".chars() {
            list.handle_key(&key(KeyCode::Char(c)));
        }
        match list.handle_key(&key(KeyCode::Enter)) {
            ListEvent::Submitted(i) => {
                assert_eq!(list.items()[i].action, Action::ShowMarkdownCheatSheet)
            }
            other => panic!("expected Submitted, got {other:?}"),
        }
    }

    #[test]
    fn down_advances_focus_skipping_headers() {
        let mut list = build_palette_list(&keymap(), false);
        let count = list.match_count();
        assert!(count > 1);
        let first = list.focused_item_index();
        list.handle_key(&key(KeyCode::Down));
        assert_ne!(list.focused_item_index(), first);
        for _ in 0..count + 5 {
            list.handle_key(&key(KeyCode::Down));
            assert!(list.focused_item_index().is_some());
        }
    }

    #[test]
    fn ctrl_chars_do_not_pollute_query() {
        let mut list = build_palette_list(&keymap(), false);
        let ctrl_p = KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL);
        list.handle_key(&ctrl_p);
        assert!(list.query().is_empty());
    }

    #[test]
    fn there_is_a_single_export_entry() {
        let entries = build_entries(&keymap(), false);
        let exports: Vec<&PaletteEntry> = entries
            .iter()
            .filter(|e| e.action == Action::ExportHtml)
            .collect();
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].label, "Export…");
    }

    #[test]
    fn entries_carry_the_chord_for_save() {
        let entries = build_entries(&keymap(), false);
        let save = entries.iter().find(|e| e.action == Action::Save).unwrap();
        assert!(save.chord.is_some(), "Save chord should be Ctrl-S");
    }

    #[test]
    fn palette_renders_scrollbar_when_more_rows_than_visible_height() {
        let mut list = build_palette_list(&keymap(), false);
        list.handle_key(&key(KeyCode::Char('e')));
        let contents = render(&mut list, 80, 10);
        assert!(contents.contains('█'), "expected scrollbar thumb glyph");
    }

    #[test]
    fn palette_wheel_scrolls_without_moving_focus() {
        let mut list = build_palette_list(&keymap(), false);
        list.handle_key(&key(KeyCode::Char('e')));
        render(&mut list, 80, 10);
        let focused_before = list.focused_item_index();
        list.scroll_by(2);
        render(&mut list, 80, 10);
        assert_eq!(
            list.focused_item_index(),
            focused_before,
            "wheel must not move focus"
        );
    }
}