Skip to main content

tui/event/
names.rs

1//! The name, short label and description of every intent, the one table the keymap files
2//! and the help read. Names are kebab-case verb-object; only `select-tab`,
3//! `new-window`, `select-window` and `new-report` take an argument.
4
5use tvui::Change;
6use tvui::keymap::Action;
7
8use super::{BuilderKey, Intent, ScriptKey, TemplateKey};
9use crate::tabs::reports::ReportKind;
10use crate::view::Tab;
11
12/// A genuine parameter of an intent: the values a keymap line can name.
13trait Arg: Copy + 'static {
14    const VALUES: &'static [Self];
15    fn arg(self) -> String;
16}
17
18impl Arg for Tab {
19    const VALUES: &'static [Self] = &Tab::ALL;
20    fn arg(self) -> String {
21        self.label().to_lowercase().replace(' ', "-")
22    }
23}
24
25impl Arg for u8 {
26    const VALUES: &'static [Self] = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
27
28    fn arg(self) -> String {
29        self.to_string()
30    }
31}
32
33impl Arg for ReportKind {
34    const VALUES: &'static [Self] = &ReportKind::ALL;
35    fn arg(self) -> String {
36        match self {
37            ReportKind::Balance => "balance",
38            ReportKind::Activity => "activity",
39            ReportKind::Breakdown => "breakdown",
40        }
41        .to_string()
42    }
43}
44
45fn no_arg(name: &str, arg: Option<&str>) -> Result<(), String> {
46    match arg {
47        Some(_) => Err(format!("`{name}` takes no argument")),
48        None => Ok(()),
49    }
50}
51
52fn parse_arg<T: Arg>(name: &str, arg: Option<&str>) -> Result<T, String> {
53    let arg = arg.ok_or_else(|| format!("`{name}` needs an argument"))?;
54    let found = T::VALUES.iter().copied().find(|value| value.arg() == arg);
55    found.ok_or_else(|| {
56        let known: Vec<String> = T::VALUES.iter().map(|value| value.arg()).collect();
57        format!(
58            "`{name}`: unknown argument `{arg}`; known: {}",
59            known.join(", ")
60        )
61    })
62}
63
64macro_rules! intents {
65    (
66        unit { $(($($u:tt)+) => $un:literal, $ul:literal, $ud:literal;)* }
67        payload { $($pv:ident($pt:ty) => $pn:literal, $pl:literal, $pd:literal;)* }
68        unbindable { $($bp:pat,)* }
69    ) => {
70        impl Action for Intent {
71            fn parse(name: &str, arg: Option<&str>) -> Result<Intent, String> {
72                match name {
73                    $($un => no_arg(name, arg).map(|()| $($u)+),)*
74                    $($pn => parse_arg::<$pt>(name, arg).map(Intent::$pv),)*
75                    _ => Err(format!("unknown action `{name}`")),
76                }
77            }
78        }
79
80        impl Intent {
81            /// The keymap name and argument; `None` for an intent no key can be bound to.
82            #[must_use]
83            pub fn name(&self) -> Option<(&'static str, Option<String>)> {
84                match self {
85                    $($($u)+ => Some(($un, None)),)*
86                    $(Intent::$pv(value) => Some(($pn, Some(value.arg()))),)*
87                    $($bp => None,)*
88                }
89            }
90
91            /// The label of a hint or menu item; `None` for an intent no key can be bound to.
92            #[must_use]
93            pub fn label(&self) -> Option<&'static str> {
94                match self {
95                    $($($u)+ => Some($ul),)*
96                    $(Intent::$pv(_) => Some($pl),)*
97                    $($bp => None,)*
98                }
99            }
100
101            /// One line for the help; `None` for an intent no key can be bound to.
102            #[must_use]
103            pub fn description(&self) -> Option<&'static str> {
104                match self {
105                    $($($u)+ => Some($ud),)*
106                    $(Intent::$pv(_) => Some($pd),)*
107                    $($bp => None,)*
108                }
109            }
110
111            /// Every bindable intent, one per payload value.
112            #[cfg(test)]
113            pub(super) fn all_bindable() -> Vec<Intent> {
114                let mut all = vec![$($($u)+),*];
115                $(all.extend(<$pt as Arg>::VALUES.iter().map(|value| Intent::$pv(*value)));)*
116                all
117            }
118        }
119    };
120}
121
122intents! {
123    unit {
124        (Intent::Quit) => "quit", "Quit", "Ask, then leave the application";
125        (Intent::QuitNow) => "quit-now", "Quit", "Leave the application at once";
126        (Intent::CloseOrQuit) => "close-or-quit", "Close/Quit", "Close the front window, or ask to quit when none is open";
127        (Intent::NextWindow) => "next-window", "Next", "Bring the rearmost window to the front";
128        (Intent::SizeWindow) => "size-window", "Size/move", "Move or size the front window with the arrow keys";
129        (Intent::Drag(Change::Move(-1, 0))) => "move-window-left", "Move", "Move the window one column left";
130        (Intent::Drag(Change::Move(1, 0))) => "move-window-right", "Move right", "Move the window one column right";
131        (Intent::Drag(Change::Move(0, -1))) => "move-window-up", "Move up", "Move the window one row up";
132        (Intent::Drag(Change::Move(0, 1))) => "move-window-down", "Move down", "Move the window one row down";
133        (Intent::Drag(Change::Grow(-1, 0))) => "size-window-narrower", "Size", "Make the window one column narrower";
134        (Intent::Drag(Change::Grow(1, 0))) => "size-window-wider", "Wider", "Make the window one column wider";
135        (Intent::Drag(Change::Grow(0, -1))) => "size-window-shorter", "Shorter", "Make the window one row shorter";
136        (Intent::Drag(Change::Grow(0, 1))) => "size-window-taller", "Taller", "Make the window one row taller";
137        (Intent::Drag(Change::Move(-8, 0))) => "move-window-far-left", "Far left", "Move the window eight columns left";
138        (Intent::Drag(Change::Move(8, 0))) => "move-window-far-right", "Far right", "Move the window eight columns right";
139        (Intent::Drag(Change::Move(0, -4))) => "move-window-far-up", "Far up", "Move the window four rows up";
140        (Intent::Drag(Change::Move(0, 4))) => "move-window-far-down", "Far down", "Move the window four rows down";
141        (Intent::Drag(Change::Grow(-8, 0))) => "size-window-far-narrower", "Much narrower", "Make the window eight columns narrower";
142        (Intent::Drag(Change::Grow(8, 0))) => "size-window-far-wider", "Much wider", "Make the window eight columns wider";
143        (Intent::Drag(Change::Grow(0, -4))) => "size-window-far-shorter", "Much shorter", "Make the window four rows shorter";
144        (Intent::Drag(Change::Grow(0, 4))) => "size-window-far-taller", "Much taller", "Make the window four rows taller";
145        (Intent::Drag(Change::Left)) => "move-window-to-left", "To left", "Put the window at the left edge of the desktop";
146        (Intent::Drag(Change::Right)) => "move-window-to-right", "To right", "Put the window at the right edge of the desktop";
147        (Intent::Drag(Change::Top)) => "move-window-to-top", "To top", "Put the window at the top edge of the desktop";
148        (Intent::Drag(Change::Bottom)) => "move-window-to-bottom", "To bottom", "Put the window at the bottom edge of the desktop";
149        (Intent::DragDone) => "confirm-window-change", "OK", "Keep the window as it is now";
150        (Intent::DragCancel) => "cancel-window-change", "Cancel", "Put the window back as it was";
151        (Intent::ToggleZoom) => "toggle-zoom", "Zoom", "Zoom the front window to the desktop, or restore it";
152        (Intent::Tile) => "tile", "Tile", "Lay the windows out side by side";
153        (Intent::Cascade) => "cascade", "Cascade", "Stack the windows from the desktop corner";
154        (Intent::CloseAll) => "close-all", "Close all", "Close every window";
155        (Intent::NextField) => "next-field", "Next field", "Go to the next form field";
156        (Intent::NewRow) => "new-row", "New", "Create a row in the active tab";
157        (Intent::DeleteRow) => "delete-row", "Delete", "Delete the selected row of the active tab";
158        (Intent::PrevWindow) => "prev-window", "Previous", "Send the front window to the back";
159        (Intent::PrevField) => "prev-field", "Previous field", "Go to the previous form field";
160        (Intent::OpenCommandLine) => "open-command-line", "Cmd", "Open the command line";
161        (Intent::CloseTopmost) => "close", "Close", "Close the topmost overlay or the command line";
162        (Intent::CloseWindow) => "close-window", "Close", "Close the front window, or cancel the dialog";
163        (Intent::Submit) => "submit", "OK", "Submit the form or the command line";
164        (Intent::Press) => "press", "Press", "Press the focused button of the form, else submit it";
165        (Intent::ConfirmYes) => "confirm", "Yes", "Confirm the prompt";
166        (Intent::DeleteBackward) => "delete-backward", "Backspace", "Delete the character before the cursor";
167        (Intent::MoveLeft) => "move-left", "Left", "Move the cursor left";
168        (Intent::MoveRight) => "move-right", "Right", "Move the cursor right";
169        (Intent::MoveHome) => "move-home", "Home", "Move the cursor to the start of the line";
170        (Intent::MoveEnd) => "move-end", "End", "Move the cursor to the end of the line";
171        (Intent::MoveUp) => "move-up", "Up", "Move the cursor up a line";
172        (Intent::MoveDown) => "move-down", "Down", "Move the cursor down a line";
173        (Intent::InsertNewline) => "insert-newline", "Newline", "Type a line break";
174        (Intent::KillToEnd) => "delete-to-end", "Delete to end", "Delete to the end of the line";
175        (Intent::KillWordBackward) => "delete-word-backward", "Delete word", "Delete the word before the cursor";
176        (Intent::OpenHelp) => "open-help", "Help", "Show the key help";
177        (Intent::OpenMenu) => "open-menu", "Menu", "Open the menu bar";
178        (Intent::CloseMenu) => "close-menu", "Close menu", "Close the menu";
179        (Intent::MenuNext) => "menu-next", "Next", "Select the next menu item";
180        (Intent::MenuPrev) => "menu-prev", "Previous", "Select the previous menu item";
181        (Intent::MenuFirst) => "menu-first", "First", "Select the first menu item";
182        (Intent::MenuLast) => "menu-last", "Last", "Select the last menu item";
183        (Intent::MenuLeft) => "menu-left", "Left", "Open the menu to the left";
184        (Intent::MenuRight) => "menu-right", "Right", "Open the menu to the right";
185        (Intent::MenuSelect) => "menu-select", "Go", "Choose the selected menu item";
186        (Intent::ConsoleFocus) => "focus-console", "Focus", "Focus the console prompt";
187        (Intent::ConsoleBlur) => "leave-console", "Leave", "Leave the console prompt";
188        (Intent::ConsoleSubmit) => "submit-console", "Run", "Evaluate the console line";
189        (Intent::ConsoleInterrupt) => "interrupt-console", "Interrupt", "Interrupt the running evaluation";
190        (Intent::ConsoleHistoryPrev) => "prev-history", "Older", "Recall the previous console line";
191        (Intent::ConsoleHistoryNext) => "next-history", "Newer", "Recall the next console line";
192        (Intent::ConsoleCyclePane) => "cycle-console-pane", "Pane", "Switch between the prompt and the scrollback";
193        (Intent::ScrollLineUp) => "scroll-line-up", "Scroll up", "Scroll up a line";
194        (Intent::ScrollLineDown) => "scroll-line-down", "Scroll", "Scroll down a line";
195        (Intent::ScrollPageUp) => "scroll-page-up", "Page up", "Scroll up a page";
196        (Intent::ScrollPageDown) => "scroll-page-down", "Page down", "Scroll down a page";
197        (Intent::ScrollTop) => "scroll-top", "Top", "Scroll to the top";
198        (Intent::ScrollEnd) => "scroll-end", "End", "Scroll to the end";
199        (Intent::ListSelectNext) => "next-row", "Next", "Select the next row";
200        (Intent::ListSelectPrev) => "prev-row", "Previous", "Select the previous row";
201        (Intent::ListSelectFirst) => "first-row", "First", "Select the first row";
202        (Intent::ListSelectLast) => "last-row", "Last", "Select the last row";
203        (Intent::ListViewDown) => "select-view-down", "Page down", "Move the selection down a page";
204        (Intent::ListViewUp) => "select-view-up", "Page up", "Move the selection up a page";
205        (Intent::ListPageNext) => "next-page", "Next page", "Show the next page of rows";
206        (Intent::ListPagePrev) => "prev-page", "Previous page", "Show the previous page of rows";
207        (Intent::ListFilter) => "filter-transactions", "Filter", "Open the transaction filter";
208        (Intent::ListFilterClear) => "clear-transaction-filter", "Clear filter", "Drop the transaction filter";
209        (Intent::ListMark) => "mark-transaction", "Mark", "Mark the selected transaction";
210        (Intent::ListUnmarkAll) => "unmark-all", "Unmark all", "Clear all marks";
211        (Intent::ListDeleteMarked) => "delete-marked", "Delete marked", "Delete the marked transactions";
212        (Intent::EditRow) => "edit-row", "Edit", "Edit the selected row of the active tab, or the last report";
213        (Intent::ListDetail) => "show-detail", "Detail", "Show the selected transaction";
214        (Intent::DetailEdit) => "edit-detail", "Edit", "Edit the transaction shown";
215        (Intent::ListMergeAccount) => "merge-account", "Merge", "Merge the selected account into another";
216        (Intent::ListAccountTransactions) => "show-account-transactions", "Transactions", "Show the transactions of the selected account";
217        (Intent::RefreshTab) => "refresh-tab", "Refresh", "Reload the tab";
218        (Intent::ReportChart) => "toggle-report-chart", "Chart", "Switch the report between table and chart";
219        (Intent::ReportCsv) => "fetch-report-csv", "CSV", "Fetch the report as CSV";
220        (Intent::CsvCopy) => "copy-csv", "Copy", "Copy the CSV to the clipboard";
221        (Intent::CsvSave) => "save-csv", "Save", "Save the CSV to a file";
222        (Intent::SelectOpen) => "open-select", "Open", "Open the option list";
223        (Intent::SelectConfirm) => "confirm-select", "Pick", "Choose the highlighted option and close the list";
224        (Intent::SelectCancel) => "cancel-select", "Close list", "Close the list and keep the value it had";
225        (Intent::SelectNext) => "next-option", "Next", "Choose the next option";
226        (Intent::SelectPrev) => "prev-option", "Previous", "Choose the previous option";
227        (Intent::SelectPageDown) => "next-option-page", "Page down", "Move the open list down a page";
228        (Intent::SelectPageUp) => "prev-option-page", "Page up", "Move the open list up a page";
229        (Intent::CellNext) => "next-cell", "Next cell", "Move to the next cell, or the next field at the last one";
230        (Intent::CellPrev) => "prev-cell", "Previous cell", "Move to the previous cell, or the previous field at the first one";
231        (Intent::CellUp) => "move-cell-up", "Up", "Choose the previous option in a select cell, else move up a row";
232        (Intent::CellDown) => "move-cell-down", "Down", "Choose the next option in a select cell, else move down a row";
233        (Intent::SplitAddRow) => "add-row", "Add row", "Add a row";
234        (Intent::SplitRemoveRow) => "remove-row", "Remove row", "Remove the focused row";
235        (Intent::ToggleSplitTags) => "toggle-tags", "Tags", "Open or close the split's tags; test the template in a template form";
236        (Intent::CompleteSuggestion) => "complete-suggestion", "Suggest", "Fill the cell with its suggestion";
237        (Intent::OpenFilterBuilder) => "open-filter-builder", "Builder", "Open the filter builder";
238        (Intent::CompleteCommandLine) => "complete-command-line", "Complete", "Complete the command line word";
239        (Intent::DateStepBack) => "prev-day", "Day back", "Step the date back a day";
240        (Intent::DateStepForward) => "next-day", "Day forward", "Step the date forward a day";
241        (Intent::Template(TemplateKey::Test)) => "test-template", "Test", "Render the template into a draft";
242        (Intent::Template(TemplateKey::Pick)) => "pick-template", "Template", "Start a transaction from a template";
243        (Intent::Script(ScriptKey::Toggle)) => "toggle-script", "Toggle", "Switch the selected script on or off";
244        (Intent::Builder(BuilderKey::Prev)) => "prev-filter-row", "Previous", "Move to the previous filter row";
245        (Intent::Builder(BuilderKey::Next)) => "next-filter-row", "Next", "Move to the next filter row";
246        (Intent::Builder(BuilderKey::Open)) => "open-filter-row", "Edit", "Step into the group or edit the row";
247        (Intent::Builder(BuilderKey::Add)) => "add-filter-row", "Add", "Add a filter row";
248        (Intent::Builder(BuilderKey::Back)) => "leave-filter-group", "Back", "Step out to the enclosing group";
249        (Intent::Builder(BuilderKey::Delete)) => "delete-filter-row", "Delete", "Delete the filter row";
250        (Intent::Builder(BuilderKey::Logic)) => "cycle-filter-logic", "And/or/not", "Switch the group between and, or and not";
251        (Intent::OpenOptions) => "open-options", "Options...", "Open the options dialog: theme, keymap and colours";
252        (Intent::ApplyOptions) => "apply-options", "Apply", "Save the options and keep the dialog";
253        (Intent::Builder(BuilderKey::Apply)) => "apply-filter", "Apply", "Write the rows into the filter field";
254        (Intent::MoveWordForward) => "move-word-forward", "Word forward", "Move the cursor to the next word";
255        (Intent::MoveWordBackward) => "move-word-backward", "Word back", "Move the cursor to the previous word";
256        (Intent::DeleteForward) => "delete-forward", "Delete", "Delete the character under the cursor";
257        (Intent::DeleteWordForward) => "delete-word-forward", "Delete word", "Delete the word after the cursor";
258        (Intent::EnterNormalMode) => "enter-normal-mode", "Normal", "Stop typing and switch to normal mode";
259        (Intent::InsertAtCursor) => "insert-at-cursor", "Insert", "Start typing at the cursor";
260        (Intent::InsertAfterCursor) => "insert-after-cursor", "Append", "Start typing after the cursor";
261        (Intent::InsertAtLineStart) => "insert-at-line-start", "Insert at start", "Start typing at the start of the line";
262        (Intent::InsertAtLineEnd) => "insert-at-line-end", "Append at end", "Start typing at the end of the line";
263    }
264    payload {
265        SelectTab(Tab) => "select-tab", "Go to tab", "Go to a tab";
266        SelectWindow(u8) => "select-window", "Window", "Raise the window with this number";
267        NewWindow(Tab) => "new-window", "New window", "Open a new window of a view";
268        ReportNew(ReportKind) => "new-report", "New report", "Open a new report form";
269    }
270    unbindable {
271        Intent::InsertChar(_),
272        Intent::Drag(_),
273        Intent::RaiseWindow(_),
274        Intent::ListSelectRow(_),
275        Intent::SelectPick(_),
276        // The plain intents carry the names of the vim moves they equal.
277        Intent::RowNext,
278        Intent::RowPrev,
279    }
280}
281
282#[cfg(test)]
283mod tests;