twrite-core 0.9.2

Headless buffer, movement, syntax, and hook primitives for twrite
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
use std::fmt;

use crate::{EditorBuffer, KeyCode, Modifiers, Selection};

/// Well-known context menu item ids for the built-in edit actions.
///
/// Hooks may return an item with one of these ids to override the
/// corresponding default (label, hint, enabled state); the hook's
/// version wins and keeps the default's position.
pub const CUT_ID: &str = "cut";
/// Well-known id for the built-in Copy action.
pub const COPY_ID: &str = "copy";
/// Well-known id for the built-in Paste action.
pub const PASTE_ID: &str = "paste";
/// Well-known id for the built-in Select All action.
pub const SELECT_ALL_ID: &str = "select_all";
/// Well-known id for the built-in Undo action.
pub const UNDO_ID: &str = "undo";
/// Well-known id for the built-in Redo action.
pub const REDO_ID: &str = "redo";
/// Well-known id for the built-in Delete action.
pub const DELETE_ID: &str = "delete";

/// Frontend-supplied capabilities the core cannot observe headlessly.
///
/// The OS clipboard lives outside `twrite-core`; GPUI hosts read it once
/// per right-click and pass the result in. Everything else derives from
/// the buffer + selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ContextMenuCaps {
    /// Whether a non-empty selection exists.
    pub has_selection: bool,
    /// Whether the OS clipboard currently holds text (supplied by the host).
    pub clipboard_has_text: bool,
    /// Whether an undo transaction is available.
    pub can_undo: bool,
    /// Whether a redo transaction is available.
    pub can_redo: bool,
    /// Whether the selection already spans the whole document.
    pub is_full_doc_selected: bool,
}

impl ContextMenuCaps {
    /// Derives buffer-observable caps; the host ORs in `clipboard_has_text`.
    pub fn from_buffer(
        buffer: &EditorBuffer,
        selection: Option<&Selection>,
        clipboard_has_text: bool,
    ) -> Self {
        let has_selection = selection.is_some_and(|s| !s.byte_range().is_empty());
        let is_full_doc_selected = selection.is_some_and(|s| {
            let range = s.byte_range();
            range.start == 0 && range.end == buffer.len_bytes() && !range.is_empty()
        });
        Self {
            has_selection,
            clipboard_has_text,
            can_undo: buffer.can_undo(),
            can_redo: buffer.can_redo(),
            is_full_doc_selected,
        }
    }
}

/// One row in the right-click context menu.
///
/// Hooks own the meaning of custom ids; frontends only draw rows and
/// route clicks back through `on_context_menu_action` / built-in dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextMenuItem {
    /// Stable id (`"cut"`, `"copy"`, ... or hook-defined e.g. `"md.toggle-task"`).
    pub id: &'static str,
    /// Primary row text.
    pub label: String,
    /// Structured keybinding hint, rendered as right-aligned kbd chips.
    pub hint: Option<KeyHint>,
    /// Whether the row is clickable. Disabled rows render dimmed.
    pub enabled: bool,
    /// Whether a separator renders directly below this row.
    pub divider_after: bool,
}

impl ContextMenuItem {
    /// Creates an enabled item with no hint.
    pub fn new(id: &'static str, label: &str) -> Self {
        Self {
            id,
            label: label.to_string(),
            hint: None,
            enabled: true,
            divider_after: false,
        }
    }

    /// Creates an enabled item with a structured keybinding hint.
    pub fn with_hint(id: &'static str, label: &str, hint: KeyHint) -> Self {
        Self {
            id,
            label: label.to_string(),
            hint: Some(hint),
            enabled: true,
            divider_after: false,
        }
    }

    /// Marks the item as disabled (renders dimmed, ignores clicks).
    pub fn disabled(mut self) -> Self {
        self.enabled = false;
        self
    }

    /// Requests a separator directly below this row.
    pub fn with_divider(mut self) -> Self {
        self.divider_after = true;
        self
    }
}

/// Structured keybinding hint for menu rows.
///
/// Display is canonicalized (`Ctrl+Shift+Z`), so inconsistent free text
/// (`"ctrl + l"` vs `"Ctrl+U"`) is impossible by construction. The hinted
/// key is a [`KeyCode`], shared with hook matching and keymaps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyHint {
    /// Active modifiers, rendered first in canonical Ctrl, Alt, Shift, Meta order.
    pub modifiers: Modifiers,
    /// The hinted key.
    pub code: KeyCode,
}

impl KeyHint {
    /// Creates a hint. Single ASCII lowercase `Char` keys uppercase for
    /// canonical form (`Char('l')` and `Char('L')` compare and render
    /// identically); everything else is stored verbatim.
    pub fn new(code: KeyCode, modifiers: Modifiers) -> Self {
        let code = match code {
            KeyCode::Char(c) if c.is_ascii_lowercase() => KeyCode::Char(c.to_ascii_uppercase()),
            other => other,
        };
        Self { modifiers, code }
    }

    /// Single-modifier helpers for the common cases.
    pub fn ctrl(code: KeyCode) -> Self {
        Self::new(code, Modifiers::ctrl())
    }

    /// Single-modifier helper (Alt / Option).
    pub fn alt(code: KeyCode) -> Self {
        Self::new(code, Modifiers::alt())
    }

    /// Single-modifier helper.
    pub fn shift(code: KeyCode) -> Self {
        Self::new(code, Modifiers::shift())
    }

    /// Single-modifier helper (Meta / Command / Windows).
    pub fn meta(code: KeyCode) -> Self {
        Self::new(code, Modifiers::meta())
    }

    /// Display parts in render order: active modifiers first (canonical
    /// Ctrl, Alt, Shift, Meta order), then the display key. One kbd chip
    /// per part.
    pub fn parts(&self) -> Vec<String> {
        let mut parts = Vec::with_capacity(5);
        if self.modifiers.ctrl {
            parts.push("Ctrl".to_string());
        }
        if self.modifiers.alt {
            parts.push("Alt".to_string());
        }
        if self.modifiers.shift {
            parts.push("Shift".to_string());
        }
        if self.modifiers.meta {
            parts.push("Meta".to_string());
        }
        parts.push(self.code.display());
        parts
    }
}

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

/// Read-only snapshot passed to hooks contributing menu items.
///
/// `clicked_row` / `clicked_col` are buffer coordinates of the right-click
/// (row = zero-based buffer row, col = source byte offset within that
/// line's text, clamped to the line length) so hooks can offer
/// position-aware actions (e.g. "Toggle task checkbox" only on task lines).
pub struct ContextMenuContext<'a> {
    /// The underlying text buffer (read-only for item contribution).
    pub buffer: &'a EditorBuffer,
    /// The active selection range, if any.
    pub selection: Option<&'a Selection>,
    /// Current cursor byte offset.
    pub cursor_offset: usize,
    /// Zero-based buffer row that was right-clicked.
    pub clicked_row: usize,
    /// Source byte offset within the clicked line that was right-clicked.
    pub clicked_col: usize,
    /// Frontend-supplied capabilities (clipboard, undo/redo availability).
    pub caps: ContextMenuCaps,
}

/// Headless open/closed menu state + resolved item list.
///
/// Owned by the host (the GPUI `Editor`) mirroring `PromptState`: hooks
/// contribute items via `EditorHook::context_menu_items`, the host merges
/// with [`default_context_items`] via [`collect_context_items`], and the
/// frontend only draws rows. Click position (pixels) stays in the GPUI
/// layer; this type never touches screen coordinates.
#[derive(Debug, Clone, Default)]
pub struct ContextMenuState {
    items: Vec<ContextMenuItem>,
    open: bool,
}

impl ContextMenuState {
    /// Creates a closed menu.
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether a menu is currently open.
    pub fn is_open(&self) -> bool {
        self.open
    }

    /// Current item rows.
    pub fn items(&self) -> &[ContextMenuItem] {
        &self.items
    }

    /// Opens the menu with a pre-merged item list.
    pub fn open(&mut self, items: Vec<ContextMenuItem>) {
        self.items = items;
        self.open = true;
    }

    /// Closes the menu, clearing the item list.
    pub fn close(&mut self) {
        self.items.clear();
        self.open = false;
    }
}

/// Builds the built-in edit rows for the given capabilities.
///
/// Order: Undo, Redo, Cut, Copy, Paste, Delete, Select All. The last
/// default carries `divider_after = true` so renderers draw a separator
/// before hook-contributed rows (removed by [`collect_context_items`]
/// when no hook rows follow).
pub fn default_context_items(caps: ContextMenuCaps) -> Vec<ContextMenuItem> {
    let mut items = vec![
        with_enabled(
            ContextMenuItem::with_hint(UNDO_ID, "Undo", KeyHint::ctrl(KeyCode::Char('Z'))),
            caps.can_undo,
        ),
        with_enabled(
            ContextMenuItem::with_hint(REDO_ID, "Redo", KeyHint::ctrl(KeyCode::Char('Y'))),
            caps.can_redo,
        ),
        with_enabled(
            ContextMenuItem::with_hint(CUT_ID, "Cut", KeyHint::ctrl(KeyCode::Char('X'))),
            caps.has_selection,
        ),
        with_enabled(
            ContextMenuItem::with_hint(COPY_ID, "Copy", KeyHint::ctrl(KeyCode::Char('C'))),
            caps.has_selection,
        ),
        with_enabled(
            ContextMenuItem::with_hint(PASTE_ID, "Paste", KeyHint::ctrl(KeyCode::Char('V'))),
            caps.clipboard_has_text,
        ),
        with_enabled(
            ContextMenuItem::new(DELETE_ID, "Delete"),
            caps.has_selection,
        ),
    ];
    let select_all = if caps.is_full_doc_selected {
        ContextMenuItem::with_hint(
            SELECT_ALL_ID,
            "Select All",
            KeyHint::ctrl(KeyCode::Char('A')),
        )
        .disabled()
    } else {
        ContextMenuItem::with_hint(
            SELECT_ALL_ID,
            "Select All",
            KeyHint::ctrl(KeyCode::Char('A')),
        )
    };
    items.push(select_all.with_divider());
    items
}

fn with_enabled(mut item: ContextMenuItem, enabled: bool) -> ContextMenuItem {
    item.enabled = enabled;
    item
}

/// Merges defaults with hook-contributed rows.
///
/// * When `include_defaults` is false, only hook rows are used.
/// * Hook rows append in order after the defaults.
/// * A hook row whose `id` matches a default (or an earlier hook row)
///   replaces it in place, keeping the original position.
/// * The trailing divider on the defaults block is dropped when no hook
///   rows follow, so a defaults-only menu has no stray separator.
pub fn collect_context_items(
    include_defaults: bool,
    caps: ContextMenuCaps,
    hook_rows: Vec<Vec<ContextMenuItem>>,
) -> Vec<ContextMenuItem> {
    let mut merged: Vec<ContextMenuItem> = if include_defaults {
        default_context_items(caps)
    } else {
        Vec::new()
    };
    let mut hook_count = 0;
    for rows in hook_rows {
        for row in rows {
            if let Some(pos) = merged.iter().position(|m| m.id == row.id) {
                merged[pos] = row;
            } else {
                merged.push(row);
                hook_count += 1;
            }
        }
    }
    if hook_count == 0
        && let Some(last) = merged.last_mut()
    {
        last.divider_after = false;
    }
    merged
}

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

    fn caps_all() -> ContextMenuCaps {
        ContextMenuCaps {
            has_selection: true,
            clipboard_has_text: true,
            can_undo: true,
            can_redo: true,
            is_full_doc_selected: false,
        }
    }

    #[test]
    fn defaults_enablement_matrix() {
        let items = default_context_items(ContextMenuCaps::default());
        // Nothing available: only Select All enabled.
        for item in &items {
            if item.id == SELECT_ALL_ID {
                assert!(item.enabled);
            } else {
                assert!(!item.enabled, "{} should be disabled", item.id);
            }
        }
        // Last default carries the hook-block separator.
        assert!(items.last().unwrap().divider_after);

        let items = default_context_items(caps_all());
        assert!(items.iter().all(|i| i.enabled));
    }

    #[test]
    fn select_all_disabled_when_full_doc_selected() {
        let caps = ContextMenuCaps {
            is_full_doc_selected: true,
            ..caps_all()
        };
        let select = default_context_items(caps)
            .into_iter()
            .find(|i| i.id == SELECT_ALL_ID)
            .unwrap();
        assert!(!select.enabled);
    }

    #[test]
    fn state_open_close_lifecycle() {
        let mut state = ContextMenuState::new();
        assert!(!state.is_open());
        state.open(default_context_items(caps_all()));
        assert!(state.is_open());
        assert_eq!(state.items().len(), 7);
        state.close();
        assert!(!state.is_open());
        assert!(state.items().is_empty());
    }

    #[test]
    fn collect_merges_hooks_after_defaults() {
        let merged = collect_context_items(
            true,
            caps_all(),
            vec![vec![ContextMenuItem::new("md.toggle-task", "Toggle task")]],
        );
        assert_eq!(merged.len(), 8);
        assert_eq!(merged[7].id, "md.toggle-task");
        // Hook rows present: defaults-block divider retained.
        assert!(merged[6].divider_after);
    }

    #[test]
    fn collect_drops_trailing_divider_without_hooks() {
        let merged = collect_context_items(true, caps_all(), vec![]);
        assert!(!merged.last().unwrap().divider_after);
    }

    #[test]
    fn collect_hook_overrides_default_by_id() {
        let merged = collect_context_items(
            true,
            ContextMenuCaps::default(),
            vec![vec![ContextMenuItem::new(COPY_ID, "Copy link")]],
        );
        let copy = merged.iter().find(|i| i.id == COPY_ID).unwrap();
        assert_eq!(copy.label, "Copy link");
        assert!(copy.enabled);
        // Override replaces in place: no extra row.
        assert_eq!(merged.len(), 7);
    }

    #[test]
    fn collect_without_defaults_uses_hooks_only() {
        let merged = collect_context_items(
            false,
            ContextMenuCaps::default(),
            vec![vec![ContextMenuItem::new("custom", "Custom")]],
        );
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn key_hint_display_is_canonical_order() {
        let hint = KeyHint::new(
            KeyCode::Char('z'),
            Modifiers {
                shift: true,
                ctrl: true,
                ..Modifiers::empty()
            },
        );
        assert_eq!(hint.to_string(), "Ctrl+Shift+Z");
        assert_eq!(hint.parts(), vec!["Ctrl", "Shift", "Z"]);
    }

    #[test]
    fn key_hint_single_letters_normalize_case() {
        // 'l' and 'L' are the same hint: the old free-text drift
        // ("ctrl + l" vs "Ctrl+U") cannot be expressed anymore.
        assert_eq!(
            KeyHint::new(KeyCode::Char('l'), Modifiers::ctrl()),
            KeyHint::ctrl(KeyCode::Char('L'))
        );
        assert_eq!(KeyHint::ctrl(KeyCode::Char('l')).to_string(), "Ctrl+L");
    }

    #[test]
    fn key_hint_named_keys_render_mixed() {
        assert_eq!(KeyHint::ctrl(KeyCode::Enter).to_string(), "Ctrl+Enter");
        assert_eq!(KeyHint::ctrl(KeyCode::Char(' ')).to_string(), "Ctrl+ ");
        assert_eq!(KeyHint::ctrl(KeyCode::Escape).to_string(), "Ctrl+Esc");
        assert_eq!(
            KeyHint::ctrl(KeyCode::Backspace).to_string(),
            "Ctrl+Backspace"
        );
        assert_eq!(KeyHint::ctrl(KeyCode::Delete).to_string(), "Ctrl+Delete");
        assert_eq!(KeyHint::ctrl(KeyCode::Up).to_string(), "Ctrl+↑");
        assert_eq!(
            KeyHint::new(KeyCode::F(5), Modifiers::empty()).to_string(),
            "F5"
        );
        assert_eq!(
            KeyHint::new(KeyCode::Char('/'), Modifiers::empty()).to_string(),
            "/"
        );
    }

    #[test]
    fn builtin_rows_carry_structured_hints() {
        let items = default_context_items(caps_all());
        let undo = items.iter().find(|i| i.id == UNDO_ID).unwrap();
        assert_eq!(undo.hint, Some(KeyHint::ctrl(KeyCode::Char('Z'))));
        assert_eq!(undo.hint.as_ref().unwrap().to_string(), "Ctrl+Z");
        let delete = items.iter().find(|i| i.id == DELETE_ID).unwrap();
        assert_eq!(delete.hint, None);
    }

    #[test]
    fn caps_from_buffer_derives_selection_and_history() {
        let mut buffer = EditorBuffer::new("hello world");
        buffer.insert("!");
        let sel = Selection::range(0, 5);
        let caps = ContextMenuCaps::from_buffer(&buffer, Some(&sel), true);
        assert!(caps.has_selection);
        assert!(caps.clipboard_has_text);
        assert!(caps.can_undo);
        assert!(!caps.can_redo);
        assert!(!caps.is_full_doc_selected);

        let full = Selection::range(0, buffer.len_bytes());
        let caps = ContextMenuCaps::from_buffer(&buffer, Some(&full), false);
        assert!(caps.is_full_doc_selected);

        let caps = ContextMenuCaps::from_buffer(&buffer, None, false);
        assert!(!caps.has_selection);
    }
}