Skip to main content

fresh_core/
action.rs

1use serde::{Deserialize, Serialize};
2
3/// Context in which a keybinding is active
4#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ts_rs::TS)]
5#[ts(export)]
6pub enum KeyContext {
7    /// Global bindings that work in all contexts (checked first with highest priority)
8    Global,
9    /// Normal editing mode
10    Normal,
11    /// Prompt/minibuffer is active
12    Prompt,
13    /// Popup window is visible
14    Popup,
15    /// File explorer has focus
16    FileExplorer,
17    /// Menu bar is active
18    Menu,
19    /// Terminal has focus
20    Terminal,
21    /// Settings modal is active
22    Settings,
23    /// Buffer-local mode context (e.g. "search-replace-list")
24    Mode(String),
25}
26
27impl KeyContext {
28    /// Check if a context should allow input
29    pub fn allows_text_input(&self) -> bool {
30        matches!(self, Self::Normal | Self::Prompt)
31    }
32
33    /// Parse context from a "when" string
34    pub fn from_when_clause(when: &str) -> Option<Self> {
35        let trimmed = when.trim();
36        if let Some(mode_name) = trimmed.strip_prefix("mode:") {
37            return Some(Self::Mode(mode_name.to_string()));
38        }
39        Some(match trimmed {
40            "global" => Self::Global,
41            "prompt" => Self::Prompt,
42            "popup" => Self::Popup,
43            "fileExplorer" | "file_explorer" => Self::FileExplorer,
44            "normal" => Self::Normal,
45            "menu" => Self::Menu,
46            "terminal" => Self::Terminal,
47            "settings" => Self::Settings,
48            _ => return None,
49        })
50    }
51
52    /// Convert context to "when" clause string
53    pub fn to_when_clause(&self) -> String {
54        match self {
55            Self::Global => "global".to_string(),
56            Self::Normal => "normal".to_string(),
57            Self::Prompt => "prompt".to_string(),
58            Self::Popup => "popup".to_string(),
59            Self::FileExplorer => "fileExplorer".to_string(),
60            Self::Menu => "menu".to_string(),
61            Self::Terminal => "terminal".to_string(),
62            Self::Settings => "settings".to_string(),
63            Self::Mode(name) => format!("mode:{}", name),
64        }
65    }
66}
67
68/// High-level actions that can be performed in the editor
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
70#[ts(export)]
71pub enum Action {
72    // Character input
73    InsertChar(char),
74    InsertNewline,
75    InsertTab,
76
77    // Basic movement
78    MoveLeft,
79    MoveRight,
80    MoveUp,
81    MoveDown,
82    MoveWordLeft,
83    MoveWordRight,
84    MoveLineStart,
85    MoveLineEnd,
86    MovePageUp,
87    MovePageDown,
88    MoveDocumentStart,
89    MoveDocumentEnd,
90
91    // Selection movement (extends selection while moving)
92    SelectLeft,
93    SelectRight,
94    SelectUp,
95    SelectDown,
96    SelectWordLeft,
97    SelectWordRight,
98    SelectLineStart,
99    SelectLineEnd,
100    SelectDocumentStart,
101    SelectDocumentEnd,
102    SelectPageUp,
103    SelectPageDown,
104    SelectAll,
105    SelectWord,
106    SelectLine,
107    ExpandSelection,
108
109    // Block/rectangular selection (column-wise)
110    BlockSelectLeft,
111    BlockSelectRight,
112    BlockSelectUp,
113    BlockSelectDown,
114
115    // Editing
116    DeleteBackward,
117    DeleteForward,
118    DeleteWordBackward,
119    DeleteWordForward,
120    DeleteLine,
121    DeleteToLineEnd,
122    DeleteToLineStart,
123    TransposeChars,
124    OpenLine,
125
126    // View
127    Recenter,
128
129    // Selection
130    SetMark,
131
132    // Clipboard
133    Copy,
134    CopyWithTheme(String),
135    Cut,
136    Paste,
137
138    // Vi-style yank (copy without selection, then restore cursor)
139    YankWordForward,
140    YankWordBackward,
141    YankToLineEnd,
142    YankToLineStart,
143
144    // Multi-cursor
145    AddCursorAbove,
146    AddCursorBelow,
147    AddCursorNextMatch,
148    RemoveSecondaryCursors,
149
150    // File operations
151    Save,
152    SaveAs,
153    Open,
154    SwitchProject,
155    New,
156    Close,
157    CloseTab,
158    Quit,
159    Revert,
160    ToggleAutoRevert,
161    FormatBuffer,
162
163    // Navigation
164    GotoLine,
165    ScanLineIndex,
166    GoToMatchingBracket,
167    JumpToNextError,
168    JumpToPreviousError,
169
170    // Smart editing
171    SmartHome,
172    DedentSelection,
173    ToggleComment,
174    /// Cycle through dabbrev completions (Emacs Alt+/ style).
175    /// Unlike popup-based completion, this inserts the best match directly
176    /// and cycles through alternatives on repeated invocations.
177    DabbrevExpand,
178
179    // Bookmarks
180    SetBookmark(char),
181    JumpToBookmark(char),
182    ClearBookmark(char),
183    ListBookmarks,
184
185    // Search options
186    ToggleSearchCaseSensitive,
187    ToggleSearchWholeWord,
188    ToggleSearchRegex,
189    ToggleSearchConfirmEach,
190
191    // Macros
192    StartMacroRecording,
193    StopMacroRecording,
194    PlayMacro(char),
195    ToggleMacroRecording(char),
196    ShowMacro(char),
197    ListMacros,
198    PromptRecordMacro,
199    PromptPlayMacro,
200    PlayLastMacro,
201
202    // Bookmarks (prompt-based)
203    PromptSetBookmark,
204    PromptJumpToBookmark,
205
206    // Undo/redo
207    Undo,
208    Redo,
209
210    // View
211    ScrollUp,
212    ScrollDown,
213    ShowHelp,
214    ShowKeyboardShortcuts,
215    ShowWarnings,
216    ShowLspStatus,
217    ClearWarnings,
218    CommandPalette,
219    ToggleLineWrap,
220    ToggleReadOnly,
221    TogglePageView,
222    SetPageWidth,
223    InspectThemeAtCursor,
224    SelectTheme,
225    SelectKeybindingMap,
226    SelectCursorStyle,
227    SelectLocale,
228
229    // Buffer/tab navigation
230    NextBuffer,
231    PrevBuffer,
232    SwitchToPreviousTab,
233    SwitchToTabByName,
234
235    // Tab scrolling
236    ScrollTabsLeft,
237    ScrollTabsRight,
238
239    // Position history navigation
240    NavigateBack,
241    NavigateForward,
242
243    // Split view operations
244    SplitHorizontal,
245    SplitVertical,
246    CloseSplit,
247    NextSplit,
248    PrevSplit,
249    IncreaseSplitSize,
250    DecreaseSplitSize,
251    ToggleMaximizeSplit,
252
253    // Prompt mode actions
254    PromptConfirm,
255    /// PromptConfirm with recorded text for macro playback
256    PromptConfirmWithText(String),
257    PromptCancel,
258    PromptBackspace,
259    PromptDelete,
260    PromptMoveLeft,
261    PromptMoveRight,
262    PromptMoveStart,
263    PromptMoveEnd,
264    PromptSelectPrev,
265    PromptSelectNext,
266    PromptPageUp,
267    PromptPageDown,
268    PromptAcceptSuggestion,
269    PromptMoveWordLeft,
270    PromptMoveWordRight,
271    // Advanced prompt editing (word operations, clipboard)
272    PromptDeleteWordForward,
273    PromptDeleteWordBackward,
274    PromptDeleteToLineEnd,
275    PromptCopy,
276    PromptCut,
277    PromptPaste,
278    // Prompt selection actions
279    PromptMoveLeftSelecting,
280    PromptMoveRightSelecting,
281    PromptMoveHomeSelecting,
282    PromptMoveEndSelecting,
283    PromptSelectWordLeft,
284    PromptSelectWordRight,
285    PromptSelectAll,
286
287    // File browser actions
288    FileBrowserToggleHidden,
289
290    // Popup mode actions
291    PopupSelectNext,
292    PopupSelectPrev,
293    PopupPageUp,
294    PopupPageDown,
295    PopupConfirm,
296    PopupCancel,
297
298    // File explorer operations
299    ToggleFileExplorer,
300    // Menu bar visibility
301    ToggleMenuBar,
302    // Tab bar visibility
303    ToggleTabBar,
304    FocusFileExplorer,
305    FocusEditor,
306    FileExplorerUp,
307    FileExplorerDown,
308    FileExplorerPageUp,
309    FileExplorerPageDown,
310    FileExplorerExpand,
311    FileExplorerCollapse,
312    FileExplorerOpen,
313    FileExplorerRefresh,
314    FileExplorerNewFile,
315    FileExplorerNewDirectory,
316    FileExplorerDelete,
317    FileExplorerRename,
318    FileExplorerToggleHidden,
319    FileExplorerToggleGitignored,
320
321    // LSP operations
322    LspCompletion,
323    LspGotoDefinition,
324    LspReferences,
325    LspRename,
326    LspHover,
327    LspSignatureHelp,
328    LspCodeActions,
329    LspRestart,
330    LspStop,
331    ToggleInlayHints,
332    ToggleMouseHover,
333
334    // View toggles
335    ToggleLineNumbers,
336    ToggleScrollSync,
337    ToggleMouseCapture,
338    ToggleDebugHighlights, // Debug mode: show highlight/overlay byte ranges
339    SetBackground,
340    SetBackgroundBlend,
341
342    // Buffer settings (per-buffer overrides)
343    SetTabSize,
344    SetLineEnding,
345    ToggleIndentationStyle,
346    ToggleTabIndicators,
347    ResetBufferSettings,
348
349    // Config operations
350    DumpConfig,
351
352    // Search and replace
353    Search,
354    FindInSelection,
355    FindNext,
356    FindPrevious,
357    FindSelectionNext,     // Quick find next occurrence of selection (Ctrl+F3)
358    FindSelectionPrevious, // Quick find previous occurrence of selection (Ctrl+Shift+F3)
359    Replace,
360    QueryReplace, // Interactive replace (y/n/!/q for each match)
361
362    // Menu navigation
363    MenuActivate,     // Open menu bar (Alt or F10)
364    MenuClose,        // Close menu (Esc)
365    MenuLeft,         // Navigate to previous menu
366    MenuRight,        // Navigate to next menu
367    MenuUp,           // Navigate to previous item in menu
368    MenuDown,         // Navigate to next item in menu
369    MenuExecute,      // Execute selected menu item (Enter)
370    MenuOpen(String), // Open a specific menu by name (e.g., "File", "Edit")
371
372    // Keybinding map switching
373    SwitchKeybindingMap(String), // Switch to a named keybinding map (e.g., "default", "emacs", "vscode")
374
375    // Plugin custom actions
376    PluginAction(String),
377
378    // Load the current buffer's contents as a plugin
379    LoadPluginFromBuffer,
380
381    // Settings operations
382    OpenSettings,        // Open the settings modal
383    CloseSettings,       // Close the settings modal
384    SettingsSave,        // Save settings changes
385    SettingsReset,       // Reset current setting to default
386    SettingsToggleFocus, // Toggle focus between category and settings panels
387    SettingsActivate,    // Activate/toggle the current setting
388    SettingsSearch,      // Start search in settings
389    SettingsHelp,        // Show settings help overlay
390    SettingsIncrement,   // Increment number value or next dropdown option
391    SettingsDecrement,   // Decrement number value or previous dropdown option
392
393    // Terminal operations
394    OpenTerminal,          // Open a new terminal in the current split
395    CloseTerminal,         // Close the current terminal
396    FocusTerminal,         // Focus the terminal buffer (if viewing terminal, focus input)
397    TerminalEscape,        // Escape from terminal mode back to editor
398    ToggleKeyboardCapture, // Toggle keyboard capture mode (all keys go to terminal)
399    TerminalPaste,         // Paste clipboard contents into terminal as a single batch
400
401    // Shell command operations
402    ShellCommand,        // Run shell command on buffer/selection, output to new buffer
403    ShellCommandReplace, // Run shell command on buffer/selection, replace content
404
405    // Case conversion
406    ToUpperCase, // Convert selection to uppercase
407    ToLowerCase, // Convert selection to lowercase
408
409    // Input calibration
410    CalibrateInput, // Open the input calibration wizard
411
412    // No-op
413    None,
414}