on master help sign in
feat: Make it possible to keybind `TypableCommands` (#1169)

* Make TypableCommands mappable * Fix pr comments * Update PartialEq implementation

commita06871a68971aa1eff8f54e8b3d751683f9d2c12 authorOskar Nehlin <oskar.d.nehlin@gmail.com> dateSat 4 Dec 2021, 15:47 (5 years ago) parent70c6253
3 files changed+136−69
helix-term/src/commands.rs+112−46 helix-term/src/keymap.rs+18−18 helix-term/src/ui/editor.rs+6−5
helix-term/src/commands.rs+112−46
@@ -134,47 +134,76 @@ fn align_view(doc: &Document, view: &mut View, align: Align) {
134134 view.offset.row = line.saturating_sub(relative);
135135}
136136
137−/// A command is composed of a static name, and a function that takes the current state plus a count,
138−/// and does a side-effect on the state (usually by creating and applying a transaction).
139−#[derive(Copy, Clone)]
140−pub struct Command {
141− name: &'static str,
142− fun: fn(cx: &mut Context),
143− doc: &'static str,
144−}
145−
146−macro_rules! commands {
137+/// A MappableCommand is either a static command like "jump_view_up" or a Typable command like
138+/// :format. It causes a side-effect on the state (usually by creating and applying a transaction).
139+/// Both of these types of commands can be mapped with keybindings in the config.toml.
140+#[derive(Clone)]
141+pub enum MappableCommand {
142+ Typable {
143+ name: String,
144+ args: Vec<String>,
145+ doc: String,
146+ },
147+ Static {
148+ name: &'static str,
149+ fun: fn(cx: &mut Context),
150+ doc: &'static str,
151+ },
152+}
153+
154+macro_rules! static_commands {
147155 ( $($name:ident, $doc:literal,)* ) => {
148156 $(
149157 #[allow(non_upper_case_globals)]
150− pub const $name: Self = Self {
158+ pub const $name: Self = Self::Static {
151159 name: stringify!($name),
152160 fun: $name,
153161 doc: $doc
154162 };
155163 )*
156164
157− pub const COMMAND_LIST: &'static [Self] = &[
165+ pub const STATIC_COMMAND_LIST: &'static [Self] = &[
158166 $( Self::$name, )*
159167 ];
160168 }
161169}
162170
163−impl Command {
171+impl MappableCommand {
164172 pub fn execute(&self, cx: &mut Context) {
165− (self.fun)(cx);
173+ match &self {
174+ MappableCommand::Typable { name, args, doc: _ } => {
175+ let args: Vec<&str> = args.iter().map(|arg| arg.as_str()).collect();
176+ if let Some(command) = cmd::TYPABLE_COMMAND_MAP.get(name.as_str()) {
177+ let mut cx = compositor::Context {
178+ editor: cx.editor,
179+ jobs: cx.jobs,
180+ scroll: None,
181+ };
182+ if let Err(e) = (command.fun)(&mut cx, &args, PromptEvent::Validate) {
183+ cx.editor.set_error(format!("{}", e));
184+ }
185+ }
186+ }
187+ MappableCommand::Static { fun, .. } => (fun)(cx),
188+ }
166189 }
167190
168− pub fn name(&self) -> &'static str {
169− self.name
191+ pub fn name(&self) -> &str {
192+ match &self {
193+ MappableCommand::Typable { name, .. } => name,
194+ MappableCommand::Static { name, .. } => name,
195+ }
170196 }
171197
172− pub fn doc(&self) -> &'static str {
173− self.doc
198+ pub fn doc(&self) -> &str {
199+ match &self {
200+ MappableCommand::Typable { doc, .. } => doc,
201+ MappableCommand::Static { doc, .. } => doc,
202+ }
174203 }
175204
176205 #[rustfmt::skip]
177− commands!(
206+ static_commands!(
178207 no_op, "Do nothing",
179208 move_char_left, "Move left",
180209 move_char_right, "Move right",
@@ -367,33 +396,51 @@ impl Command {
367396 );
368397}
369398
370−impl fmt::Debug for Command {
399+impl fmt::Debug for MappableCommand {
371400 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372− let Command { name, .. } = self;
373− f.debug_tuple("Command").field(name).finish()
401+ f.debug_tuple("MappableCommand")
402+ .field(&self.name())
403+ .finish()
374404 }
375405}
376406
377−impl fmt::Display for Command {
407+impl fmt::Display for MappableCommand {
378408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379− let Command { name, .. } = self;
380− f.write_str(name)
409+ f.write_str(self.name())
381410 }
382411}
383412
384−impl std::str::FromStr for Command {
413+impl std::str::FromStr for MappableCommand {
385414 type Err = anyhow::Error;
386415
387416 fn from_str(s: &str) -> Result<Self, Self::Err> {
388− Command::COMMAND_LIST
389− .iter()
390− .copied()
391− .find(|cmd| cmd.name == s)
392− .ok_or_else(|| anyhow!("No command named '{}'", s))
417+ if let Some(suffix) = s.strip_prefix(':') {
418+ let mut typable_command = suffix.split(' ').into_iter().map(|arg| arg.trim());
419+ let name = typable_command
420+ .next()
421+ .ok_or_else(|| anyhow!("Expected typable command name"))?;
422+ let args = typable_command
423+ .map(|s| s.to_owned())
424+ .collect::<Vec<String>>();
425+ cmd::TYPABLE_COMMAND_MAP
426+ .get(name)
427+ .map(|cmd| MappableCommand::Typable {
428+ name: cmd.name.to_owned(),
429+ doc: format!(":{} {:?}", cmd.name, args),
430+ args,
431+ })
432+ .ok_or_else(|| anyhow!("No TypableCommand named '{}'", s))
433+ } else {
434+ MappableCommand::STATIC_COMMAND_LIST
435+ .iter()
436+ .cloned()
437+ .find(|cmd| cmd.name() == s)
438+ .ok_or_else(|| anyhow!("No command named '{}'", s))
439+ }
393440 }
394441}
395442
396−impl<'de> Deserialize<'de> for Command {
443+impl<'de> Deserialize<'de> for MappableCommand {
397444 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
398445 where
399446 D: Deserializer<'de>,
@@ -403,9 +450,27 @@ impl<'de> Deserialize<'de> for Command {
403450 }
404451}
405452
406−impl PartialEq for Command {
453+impl PartialEq for MappableCommand {
407454 fn eq(&self, other: &Self) -> bool {
408− self.name() == other.name()
455+ match (self, other) {
456+ (
457+ MappableCommand::Typable {
458+ name: first_name, ..
459+ },
460+ MappableCommand::Typable {
461+ name: second_name, ..
462+ },
463+ ) => first_name == second_name,
464+ (
465+ MappableCommand::Static {
466+ name: first_name, ..
467+ },
468+ MappableCommand::Static {
469+ name: second_name, ..
470+ },
471+ ) => first_name == second_name,
472+ _ => false,
473+ }
409474 }
410475}
411476
@@ -2843,15 +2908,16 @@ mod cmd {
28432908 }
28442909 ];
28452910
2846− pub static COMMANDS: Lazy<HashMap<&'static str, &'static TypableCommand>> = Lazy::new(|| {
2847− TYPABLE_COMMAND_LIST
2848− .iter()
2849− .flat_map(|cmd| {
2850− std::iter::once((cmd.name, cmd))
2851− .chain(cmd.aliases.iter().map(move |&alias| (alias, cmd)))
2852− })
2853− .collect()
2854− });
2911+ pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =
2912+ Lazy::new(|| {
2913+ TYPABLE_COMMAND_LIST
2914+ .iter()
2915+ .flat_map(|cmd| {
2916+ std::iter::once((cmd.name, cmd))
2917+ .chain(cmd.aliases.iter().map(move |&alias| (alias, cmd)))
2918+ })
2919+ .collect()
2920+ });
28552921}
28562922
28572923fn command_mode(cx: &mut Context) {
@@ -2877,7 +2943,7 @@ fn command_mode(cx: &mut Context) {
28772943 if let Some(cmd::TypableCommand {
28782944 completer: Some(completer),
28792945 ..
2880− }) = cmd::COMMANDS.get(parts[0])
2946+ }) = cmd::TYPABLE_COMMAND_MAP.get(parts[0])
28812947 {
28822948 completer(part)
28832949 .into_iter()
@@ -2912,7 +2978,7 @@ fn command_mode(cx: &mut Context) {
29122978 }
29132979
29142980 // Handle typable commands
2915− if let Some(cmd) = cmd::COMMANDS.get(parts[0]) {
2981+ if let Some(cmd) = cmd::TYPABLE_COMMAND_MAP.get(parts[0]) {
29162982 if let Err(e) = (cmd.fun)(cx, &parts[1..], event) {
29172983 cx.editor.set_error(format!("{}", e));
29182984 }
@@ -2925,7 +2991,7 @@ fn command_mode(cx: &mut Context) {
29252991 prompt.doc_fn = Box::new(|input: &str| {
29262992 let part = input.split(' ').next().unwrap_or_default();
29272993
2928− if let Some(cmd::TypableCommand { doc, .. }) = cmd::COMMANDS.get(part) {
2994+ if let Some(cmd::TypableCommand { doc, .. }) = cmd::TYPABLE_COMMAND_MAP.get(part) {
29292995 return Some(doc);
29302996 }
29312997
helix-term/src/keymap.rs+18−18
@@ -1,4 +1,4 @@
1−pub use crate::commands::Command;
1+pub use crate::commands::MappableCommand;
22use crate::config::Config;
33use helix_core::hashmap;
44use helix_view::{document::Mode, info::Info, input::KeyEvent};
@@ -92,7 +92,7 @@ macro_rules! alt {
9292#[macro_export]
9393macro_rules! keymap {
9494 (@trie $cmd:ident) => {
95− $crate::keymap::KeyTrie::Leaf($crate::commands::Command::$cmd)
95+ $crate::keymap::KeyTrie::Leaf($crate::commands::MappableCommand::$cmd)
9696 };
9797
9898 (@trie
@@ -260,8 +260,8 @@ impl DerefMut for KeyTrieNode {
260260#[derive(Debug, Clone, PartialEq, Deserialize)]
261261#[serde(untagged)]
262262pub enum KeyTrie {
263− Leaf(Command),
264− Sequence(Vec<Command>),
263+ Leaf(MappableCommand),
264+ Sequence(Vec<MappableCommand>),
265265 Node(KeyTrieNode),
266266}
267267
@@ -304,9 +304,9 @@ impl KeyTrie {
304304pub enum KeymapResultKind {
305305 /// Needs more keys to execute a command. Contains valid keys for next keystroke.
306306 Pending(KeyTrieNode),
307− Matched(Command),
307+ Matched(MappableCommand),
308308 /// Matched a sequence of commands to execute.
309− MatchedSequence(Vec<Command>),
309+ MatchedSequence(Vec<MappableCommand>),
310310 /// Key was not found in the root keymap
311311 NotFound,
312312 /// Key is invalid in combination with previous keys. Contains keys leading upto
@@ -386,10 +386,10 @@ impl Keymap {
386386 };
387387
388388 let trie = match trie_node.search(&[*first]) {
389− Some(&KeyTrie::Leaf(cmd)) => {
390− return KeymapResult::new(KeymapResultKind::Matched(cmd), self.sticky())
389+ Some(KeyTrie::Leaf(ref cmd)) => {
390+ return KeymapResult::new(KeymapResultKind::Matched(cmd.clone()), self.sticky())
391391 }
392− Some(&KeyTrie::Sequence(ref cmds)) => {
392+ Some(KeyTrie::Sequence(ref cmds)) => {
393393 return KeymapResult::new(
394394 KeymapResultKind::MatchedSequence(cmds.clone()),
395395 self.sticky(),
@@ -408,9 +408,9 @@ impl Keymap {
408408 }
409409 KeymapResult::new(KeymapResultKind::Pending(map.clone()), self.sticky())
410410 }
411− Some(&KeyTrie::Leaf(cmd)) => {
411+ Some(&KeyTrie::Leaf(ref cmd)) => {
412412 self.state.clear();
413− return KeymapResult::new(KeymapResultKind::Matched(cmd), self.sticky());
413+ return KeymapResult::new(KeymapResultKind::Matched(cmd.clone()), self.sticky());
414414 }
415415 Some(&KeyTrie::Sequence(ref cmds)) => {
416416 self.state.clear();
@@ -833,36 +833,36 @@ mod tests {
833833 let keymap = merged_config.keys.0.get_mut(&Mode::Normal).unwrap();
834834 assert_eq!(
835835 keymap.get(key!('i')).kind,
836− KeymapResultKind::Matched(Command::normal_mode),
836+ KeymapResultKind::Matched(MappableCommand::normal_mode),
837837 "Leaf should replace leaf"
838838 );
839839 assert_eq!(
840840 keymap.get(key!('无')).kind,
841− KeymapResultKind::Matched(Command::insert_mode),
841+ KeymapResultKind::Matched(MappableCommand::insert_mode),
842842 "New leaf should be present in merged keymap"
843843 );
844844 // Assumes that z is a node in the default keymap
845845 assert_eq!(
846846 keymap.get(key!('z')).kind,
847− KeymapResultKind::Matched(Command::jump_backward),
847+ KeymapResultKind::Matched(MappableCommand::jump_backward),
848848 "Leaf should replace node"
849849 );
850850 // Assumes that `g` is a node in default keymap
851851 assert_eq!(
852852 keymap.root().search(&[key!('g'), key!('$')]).unwrap(),
853− &KeyTrie::Leaf(Command::goto_line_end),
853+ &KeyTrie::Leaf(MappableCommand::goto_line_end),
854854 "Leaf should be present in merged subnode"
855855 );
856856 // Assumes that `gg` is in default keymap
857857 assert_eq!(
858858 keymap.root().search(&[key!('g'), key!('g')]).unwrap(),
859− &KeyTrie::Leaf(Command::delete_char_forward),
859+ &KeyTrie::Leaf(MappableCommand::delete_char_forward),
860860 "Leaf should replace old leaf in merged subnode"
861861 );
862862 // Assumes that `ge` is in default keymap
863863 assert_eq!(
864864 keymap.root().search(&[key!('g'), key!('e')]).unwrap(),
865− &KeyTrie::Leaf(Command::goto_last_line),
865+ &KeyTrie::Leaf(MappableCommand::goto_last_line),
866866 "Old leaves in subnode should be present in merged node"
867867 );
868868
@@ -896,7 +896,7 @@ mod tests {
896896 .root()
897897 .search(&[key!(' '), key!('s'), key!('v')])
898898 .unwrap(),
899− &KeyTrie::Leaf(Command::vsplit),
899+ &KeyTrie::Leaf(MappableCommand::vsplit),
900900 "Leaf should be present in merged subnode"
901901 );
902902 // Make sure an order was set during merge
helix-term/src/ui/editor.rs+6−5
@@ -31,7 +31,7 @@ use tui::buffer::Buffer as Surface;
3131pub struct EditorView {
3232 keymaps: Keymaps,
3333 on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
34− last_insert: (commands::Command, Vec<KeyEvent>),
34+ last_insert: (commands::MappableCommand, Vec<KeyEvent>),
3535 pub(crate) completion: Option<Completion>,
3636 spinners: ProgressSpinners,
3737 autoinfo: Option<Info>,
@@ -48,7 +48,7 @@ impl EditorView {
4848 Self {
4949 keymaps,
5050 on_next_key: None,
51− last_insert: (commands::Command::normal_mode, Vec::new()),
51+ last_insert: (commands::MappableCommand::normal_mode, Vec::new()),
5252 completion: None,
5353 spinners: ProgressSpinners::default(),
5454 autoinfo: None,
@@ -875,7 +875,7 @@ impl EditorView {
875875 return EventResult::Ignored;
876876 }
877877
878− commands::Command::yank_main_selection_to_primary_clipboard.execute(cxt);
878+ commands::MappableCommand::yank_main_selection_to_primary_clipboard.execute(cxt);
879879
880880 EventResult::Consumed(None)
881881 }
@@ -893,7 +893,8 @@ impl EditorView {
893893 }
894894
895895 if modifiers == crossterm::event::KeyModifiers::ALT {
896− commands::Command::replace_selections_with_primary_clipboard.execute(cxt);
896+ commands::MappableCommand::replace_selections_with_primary_clipboard
897+ .execute(cxt);
897898
898899 return EventResult::Consumed(None);
899900 }
@@ -907,7 +908,7 @@ impl EditorView {
907908 let doc = editor.document_mut(editor.tree.get(view_id).doc).unwrap();
908909 doc.set_selection(view_id, Selection::point(pos));
909910 editor.tree.focus = view_id;
910− commands::Command::paste_primary_clipboard_before.execute(cxt);
911+ commands::MappableCommand::paste_primary_clipboard_before.execute(cxt);
911912 return EventResult::Consumed(None);
912913 }
913914