From 0ac3ad7860a3c5435dcef3c721f5f4cedf702e8a Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 7 Jun 2021 18:04:46 +0200 Subject: [PATCH 01/19] Add convenience/clarity wrapper for Range initialization --- helix-core/src/selection.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/helix-core/src/selection.rs b/helix-core/src/selection.rs index 7dafc97a9461..78d39b5225cb 100644 --- a/helix-core/src/selection.rs +++ b/helix-core/src/selection.rs @@ -35,6 +35,10 @@ impl Range { } } + pub fn single(head: usize) -> Self { + Self::new(head, head) + } + /// Start of the range. #[inline] #[must_use] From c01981cc759ae1bf6ae2cb61a36e88da3df05af6 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Sat, 12 Jun 2021 10:52:00 +0200 Subject: [PATCH 02/19] Add keycode parse and display methods --- helix-term/src/keymap.rs | 183 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 182 insertions(+), 1 deletion(-) diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 39bd5f3be0bf..470f11304786 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -1,7 +1,8 @@ use crate::commands::{self, Command}; +use anyhow::{anyhow, Error}; use helix_core::hashmap; use helix_view::document::Mode; -use std::collections::HashMap; +use std::{collections::HashMap, fmt::Display, str::FromStr}; // Kakoune-inspired: // mode = { @@ -377,3 +378,183 @@ pub fn default() -> Keymaps { ), ) } + +// Newtype wrapper over keys to allow toml serialization/parsing +#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Hash)] +pub struct RepresentableKeyEvent(pub KeyEvent); +impl Display for RepresentableKeyEvent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self(key) = self; + f.write_fmt(format_args!( + "{}{}{}", + if key.modifiers | KeyModifiers::SHIFT == KeyModifiers::SHIFT { + "S-" + } else { + "" + }, + if key.modifiers | KeyModifiers::ALT == KeyModifiers::ALT { + "A-" + } else { + "" + }, + if key.modifiers | KeyModifiers::CONTROL == KeyModifiers::CONTROL { + "C-" + } else { + "" + }, + ))?; + match key.code { + KeyCode::Backspace => f.write_str("Bs")?, + KeyCode::Enter => f.write_str("Enter")?, + KeyCode::Left => f.write_str("Left")?, + KeyCode::Right => f.write_str("Right")?, + KeyCode::Up => f.write_str("Up")?, + KeyCode::Down => f.write_str("Down")?, + KeyCode::Home => f.write_str("Home")?, + KeyCode::End => f.write_str("End")?, + KeyCode::PageUp => f.write_str("PageUp")?, + KeyCode::PageDown => f.write_str("PageDown")?, + KeyCode::Tab => f.write_str("Tab")?, + KeyCode::BackTab => f.write_str("BackTab")?, + KeyCode::Delete => f.write_str("Del")?, + KeyCode::Insert => f.write_str("Insert")?, + KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?, + KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?, + KeyCode::Null => f.write_str("Null")?, + KeyCode::Esc => f.write_str("Esc")?, + }; + Ok(()) + } +} + +impl FromStr for RepresentableKeyEvent { + type Err = Error; + + fn from_str(s: &str) -> Result { + let mut tokens: Vec<_> = s.split("-").collect(); + let code = match tokens.pop().ok_or(anyhow!("Missing key code"))? { + "Bs" => KeyCode::Backspace, + "Enter" => KeyCode::Enter, + "Left" => KeyCode::Left, + "Right" => KeyCode::Right, + "Up" => KeyCode::Down, + "Home" => KeyCode::Home, + "End" => KeyCode::End, + "PageUp" => KeyCode::PageUp, + "PageDown" => KeyCode::PageDown, + "Tab" => KeyCode::Tab, + "BackTab" => KeyCode::BackTab, + "Del" => KeyCode::Delete, + "Insert" => KeyCode::Insert, + single if single.len() == 1 => KeyCode::Char(single.chars().nth(0).unwrap()), + function if function.len() > 1 && &function[0..1] == "F" => { + let function = str::parse::(&function[1..])?; + (function > 0 && function < 13) + .then(|| KeyCode::F(function)) + .ok_or(anyhow!("Invalid function key '{}'", function))? + } + invalid => return Err(anyhow!("Invalid key code '{}'", invalid)), + }; + + let mut modifiers = KeyModifiers::NONE; + for token in tokens { + let flag = match token { + "S" => KeyModifiers::SHIFT, + "A" => KeyModifiers::ALT, + "C" => KeyModifiers::CONTROL, + _ => return Err(anyhow!("Invalid key modifier '{}-'", token)), + }; + + if modifiers | flag == flag { + return Err(anyhow!("Repeated key modifier '{}-'", token)); + } + modifiers |= flag; + } + + Ok(RepresentableKeyEvent(KeyEvent{ code, modifiers })) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn parsing_unmodified_keys() { + assert_eq!( + str::parse::("Bs").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::Backspace, + modifiers: KeyModifiers::NONE + }) + ); + + assert_eq!( + str::parse::("Left").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::Left, + modifiers: KeyModifiers::NONE + }) + ); + + assert_eq!( + str::parse::(",").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::Char(','), + modifiers: KeyModifiers::NONE + }) + ); + + assert_eq!( + str::parse::("w").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::Char('w'), + modifiers: KeyModifiers::NONE + }) + ); + + assert_eq!( + str::parse::("F12").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::NONE + }) + ); + } + + fn parsing_modified_keys() { + assert_eq!( + str::parse::("S-Bs").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::Backspace, + modifiers: KeyModifiers::SHIFT + }) + ); + + assert_eq!( + str::parse::("C-A-S-F12").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT + }) + ); + assert_eq!( + str::parse::("S-C-2").unwrap(), + RepresentableKeyEvent(KeyEvent { + code: KeyCode::F(2), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL + }) + ); + } + + #[test] + fn parsing_nonsensical_keys_fails() { + assert!(str::parse::("F13").is_err()); + assert!(str::parse::("F0").is_err()); + assert!(str::parse::("aaa").is_err()); + assert!(str::parse::("S-S-a").is_err()); + assert!(str::parse::("C-A-S-C-1").is_err()); + assert!(str::parse::("FU").is_err()); + assert!(str::parse::("123").is_err()); + } +} From 104b4220b2e9f7341ae11f00eb172ee02d776380 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Sat, 12 Jun 2021 11:39:24 +0200 Subject: [PATCH 03/19] Add remapping functions and tests --- helix-term/src/keymap.rs | 59 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 470f11304786..715ec5413a34 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -1,5 +1,5 @@ use crate::commands::{self, Command}; -use anyhow::{anyhow, Error}; +use anyhow::{anyhow, Error, Result}; use helix_core::hashmap; use helix_view::document::Mode; use std::{collections::HashMap, fmt::Display, str::FromStr}; @@ -99,6 +99,9 @@ pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; pub type Keymap = HashMap; pub type Keymaps = HashMap; +pub type Remap = HashMap; +pub type Remaps = HashMap; + #[macro_export] macro_rules! key { ($($ch:tt)*) => { @@ -456,7 +459,7 @@ impl FromStr for RepresentableKeyEvent { invalid => return Err(anyhow!("Invalid key code '{}'", invalid)), }; - let mut modifiers = KeyModifiers::NONE; + let mut modifiers = KeyModifiers::empty(); for token in tokens { let flag = match token { "S" => KeyModifiers::SHIFT, @@ -465,20 +468,68 @@ impl FromStr for RepresentableKeyEvent { _ => return Err(anyhow!("Invalid key modifier '{}-'", token)), }; - if modifiers | flag == flag { + if modifiers.contains(flag) { return Err(anyhow!("Repeated key modifier '{}-'", token)); } - modifiers |= flag; + modifiers.insert(flag); } Ok(RepresentableKeyEvent(KeyEvent{ code, modifiers })) } } +pub fn parse_remaps(remaps: &str) -> Result { + type TomlCompatibleRemaps = HashMap>; + let toml_remaps: TomlCompatibleRemaps = toml::from_str(remaps)?; + let mut remaps = Remaps::new(); + + for (mode, map) in toml_remaps { + let mode = Mode::from_str(&mode)?; + let mut remap = Remap::new(); + + for (source_key, target_key) in map { + let source_key = str::parse::(&source_key)?; + let target_key = str::parse::(&target_key)?; + remap.insert(source_key.0, target_key.0); + } + remaps.insert(mode, remap); + } + Ok(remaps) +} + #[cfg(test)] mod test { use super::*; + #[test] + fn parsing_remaps_file() { + let sample_remaps = "\ + [Insert]\n\ + y = \"x\"\n\ + S-C-a = \"F12\"\n\ + + [Normal] + A-F12 = \"S-C-w\"\n\ + "; + + let parsed = parse_remaps(sample_remaps).unwrap(); + assert_eq!( + parsed, + hashmap!( + Mode::Insert => hashmap!( + KeyEvent { code: KeyCode::Char('y'), modifiers: KeyModifiers::NONE } + => KeyEvent { code: KeyCode::Char('x'), modifiers: KeyModifiers::NONE }, + KeyEvent { code: KeyCode::Char('a'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL } + => KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::NONE }, + ), + Mode::Normal => hashmap!( + KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::ALT } + => KeyEvent { code: KeyCode::Char('w'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL }, + ) + ) + ) + } + #[test] fn parsing_unmodified_keys() { assert_eq!( From 815cfd6b63bf63da362d1c4ac6d4b1eb90e5739d Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Sat, 12 Jun 2021 18:11:22 +0200 Subject: [PATCH 04/19] Implement key remapping --- helix-term/src/application.rs | 11 ++++++++--- helix-term/src/keymap.rs | 21 ++++++++++++--------- helix-term/src/main.rs | 10 ++++++++-- helix-term/src/ui/editor.rs | 21 +++++++++++++++++++-- helix-view/src/document.rs | 27 ++++++++++++++++++++++++++- 5 files changed, 73 insertions(+), 17 deletions(-) diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index bf829f2ca7b5..3e22f784d06f 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -1,7 +1,7 @@ use helix_lsp::lsp; use helix_view::{document::Mode, Document, Editor, Theme, View}; -use crate::{args::Args, compositor::Compositor, ui}; +use crate::{args::Args, compositor::Compositor, keymap::Remaps, ui}; use log::{error, info}; @@ -40,13 +40,18 @@ pub struct Application { } impl Application { - pub fn new(mut args: Args) -> Result { + pub fn new(mut args: Args, remaps: Option) -> Result { use helix_view::editor::Action; let mut compositor = Compositor::new()?; let size = compositor.size(); let mut editor = Editor::new(size); - compositor.push(Box::new(ui::EditorView::new())); + let mut editor_view = Box::new(ui::EditorView::new()); + if let Some(remaps) = remaps { + editor_view.apply_remaps(remaps); + } + + compositor.push(editor_view); if !args.files.is_empty() { let first = &args.files[0]; // we know it's not empty diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 715ec5413a34..4f62684de274 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -1,4 +1,5 @@ -use crate::commands::{self, Command}; +use crate::commands; +pub use crate::commands::Command; use anyhow::{anyhow, Error, Result}; use helix_core::hashmap; use helix_view::document::Mode; @@ -390,17 +391,17 @@ impl Display for RepresentableKeyEvent { let Self(key) = self; f.write_fmt(format_args!( "{}{}{}", - if key.modifiers | KeyModifiers::SHIFT == KeyModifiers::SHIFT { + if key.modifiers.contains(KeyModifiers::SHIFT) { "S-" } else { "" }, - if key.modifiers | KeyModifiers::ALT == KeyModifiers::ALT { + if key.modifiers.contains(KeyModifiers::ALT) { "A-" } else { "" }, - if key.modifiers | KeyModifiers::CONTROL == KeyModifiers::CONTROL { + if key.modifiers.contains(KeyModifiers::CONTROL) { "C-" } else { "" @@ -434,8 +435,8 @@ impl FromStr for RepresentableKeyEvent { type Err = Error; fn from_str(s: &str) -> Result { - let mut tokens: Vec<_> = s.split("-").collect(); - let code = match tokens.pop().ok_or(anyhow!("Missing key code"))? { + let mut tokens: Vec<_> = s.split('-').collect(); + let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? { "Bs" => KeyCode::Backspace, "Enter" => KeyCode::Enter, "Left" => KeyCode::Left, @@ -449,12 +450,14 @@ impl FromStr for RepresentableKeyEvent { "BackTab" => KeyCode::BackTab, "Del" => KeyCode::Delete, "Insert" => KeyCode::Insert, - single if single.len() == 1 => KeyCode::Char(single.chars().nth(0).unwrap()), + "Null" => KeyCode::Null, + "Esc" => KeyCode::Esc, + single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()), function if function.len() > 1 && &function[0..1] == "F" => { let function = str::parse::(&function[1..])?; (function > 0 && function < 13) .then(|| KeyCode::F(function)) - .ok_or(anyhow!("Invalid function key '{}'", function))? + .ok_or_else(|| anyhow!("Invalid function key '{}'", function))? } invalid => return Err(anyhow!("Invalid key code '{}'", invalid)), }; @@ -474,7 +477,7 @@ impl FromStr for RepresentableKeyEvent { modifiers.insert(flag); } - Ok(RepresentableKeyEvent(KeyEvent{ code, modifiers })) + Ok(RepresentableKeyEvent(KeyEvent { code, modifiers })) } } diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index 9d4e1c5b1097..5ba592f70698 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -1,6 +1,6 @@ use helix_term::application::Application; use helix_term::args::Args; - +use helix_term::keymap::parse_remaps; use std::path::PathBuf; use anyhow::{Context, Result}; @@ -89,10 +89,16 @@ FLAGS: std::fs::create_dir_all(&conf_dir).ok(); } + let remaps = if let Ok(remaps) = std::fs::read_to_string(conf_dir.join("keymap.toml")) { + Some(parse_remaps(&remaps).context("Invalid keymap.toml file")?) + } else { + None + }; + setup_logging(logpath, args.verbosity).context("failed to initialize logging")?; // TODO: use the thread local executor to spawn the application task separately from the work pool - let mut app = Application::new(args).context("unable to create new appliction")?; + let mut app = Application::new(args, remaps).context("unable to create new application")?; app.run().await.unwrap(); Ok(()) diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 00305fc84fd0..f34e872bfc51 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -2,7 +2,7 @@ use crate::{ commands, compositor::{Component, Compositor, Context, EventResult}, key, - keymap::{self, Keymaps}, + keymap::{self, Keymaps, Remaps}, ui::Completion, }; @@ -12,7 +12,7 @@ use helix_core::{ Position, Range, }; use helix_view::{document::Mode, Document, Editor, Theme, View}; -use std::borrow::Cow; +use std::{borrow::Cow, collections::HashMap}; use crossterm::{ cursor, @@ -568,6 +568,23 @@ impl EditorView { completion.required_size((size.width, size.height)); self.completion = Some(completion); } + + pub fn apply_remaps(&mut self, remaps: Remaps) { + for (mode, remap) in remaps { + let mut new_pairs = HashMap::::new(); + for (source, target) in remap { + if let Some(command) = self.keymap.get(&mode).map(|m| m.get(&target)).flatten() { + new_pairs.insert(source, *command); + } + } + + for (key, command) in new_pairs { + self.keymap + .get_mut(&mode) + .map(|mut m| m.insert(key, command)); + } + } + } } impl Component for EditorView { diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 75a0e9fa5266..7f5a547ac425 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -1,7 +1,9 @@ -use anyhow::{Context, Error}; +use anyhow::{anyhow, Context, Error}; use std::cell::Cell; +use std::fmt::Display; use std::future::Future; use std::path::{Component, Path, PathBuf}; +use std::str::FromStr; use std::sync::Arc; use helix_core::{ @@ -76,6 +78,29 @@ impl fmt::Debug for Document { } } +impl Display for Mode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Mode::Normal => f.write_str("Normal"), + Mode::Select => f.write_str("Select"), + Mode::Insert => f.write_str("Insert"), + } + } +} + +impl FromStr for Mode { + type Err = Error; + + fn from_str(s: &str) -> Result { + match s { + "Normal" => Ok(Mode::Normal), + "Select" => Ok(Mode::Select), + "Insert" => Ok(Mode::Insert), + _ => Err(anyhow!("Invalid mode '{}'", s)), + } + } +} + /// Like std::mem::replace() except it allows the replacement value to be mapped from the /// original value. fn take_with(mut_ref: &mut T, closure: F) From d99b60627e5d9114f22d9de154f7194fc0426670 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Sat, 12 Jun 2021 18:24:01 +0200 Subject: [PATCH 05/19] Add remapping book entry --- book/src/SUMMARY.md | 1 + book/src/remapping.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 book/src/remapping.md diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 474c2e7005e2..3ea1fb9ac95f 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -4,4 +4,5 @@ - [Usage](./usage.md) - [Configuration](./configuration.md) - [Keymap](./keymap.md) + - [Key Remapping](./remapping.md) - [Hooks](./hooks.md) diff --git a/book/src/remapping.md b/book/src/remapping.md new file mode 100644 index 000000000000..4baa792a7938 --- /dev/null +++ b/book/src/remapping.md @@ -0,0 +1,38 @@ +# Key Remapping + +One-way key remapping is supported via a simple TOML configuration file. + +To remap keys, write a `keymap.toml` file in your `helix` configuration +directory (default `~/.config/helix` in Linux systems) with a structure like +this: + +```toml +# At most one section each of 'Normal', 'Insert' and 'Select' +[Normal] +a = "w" # Maps the 'a' key to 'w' (move to next word) +w = "i" # Maps the 'w' key to 'i' (enter insert mode) +C-S-Esc = "f" # Maps Control-Shift-Escape to 'f' (find char) + +[Insert] +A-x = "Esc" # Maps Alt-X to 'Esc' (leave insert mode) +``` + +Control, Shift and Alt modifiers are encoded respectively with the prefixes +`C-`, `S-` and `A-`. Special keys are encoded as follows: + +* Backspace => `Bs` +* Enter => `Enter` +* Left => `Left` +* Right => `Right` +* Up => `Up` +* Down => `Down` +* Home => `Home` +* End => `End` +* PageUp => `PageUp` +* PageDown => `PageDown` +* Tab => `Tab` +* BackTab => `BackTab` +* Delete => `Del` +* Insert => `Insert` +* Null => `Null` (No associated key) +* Esc => `Esc` From d7e0f66b6f0826f084edf7203659c0339decb197 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Sat, 12 Jun 2021 19:08:39 +0200 Subject: [PATCH 06/19] Use raw string literal for toml --- helix-term/src/keymap.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 4f62684de274..897c047542f4 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -506,14 +506,14 @@ mod test { #[test] fn parsing_remaps_file() { - let sample_remaps = "\ - [Insert]\n\ - y = \"x\"\n\ - S-C-a = \"F12\"\n\ + let sample_remaps = r#" + [Insert] + y = "x" + S-C-a = "F12" [Normal] - A-F12 = \"S-C-w\"\n\ - "; + A-F12 = "S-C-w" + "#; let parsed = parse_remaps(sample_remaps).unwrap(); assert_eq!( From 8460780bb93998a7fbf81151c29e7faa07047ddc Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 12:41:10 +0200 Subject: [PATCH 07/19] Add command constants --- helix-term/src/commands.rs | 169 +++++++++++++++++++++++++---- helix-term/src/keymap.rs | 208 ++++++++++++++++++------------------ helix-term/src/ui/editor.rs | 12 +-- 3 files changed, 258 insertions(+), 131 deletions(-) diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 09048f48b19e..9313049bb610 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -128,7 +128,132 @@ fn align_view(doc: &Document, view: &mut View, align: Align) { /// A command is a function that takes the current state and a count, and does a side-effect on the /// state (usually by creating and applying a transaction). -pub type Command = fn(cx: &mut Context); +//pub type Command = fn(cx: &mut Context); + +#[derive(Clone)] +pub enum Command { + /// Regular commands are reached only by their bound key/combination + Regular(fn(cx: &mut Context)), + /// Typable commands can be bound to keys and also typed through `:` + Typable(fn(cx: &mut Context), TypableCommandData), +} + +impl Command { + pub fn execute(&self, cx: &mut Context) { + match self { + Command::Regular(function) => function(cx), + Command::Typable(function, _) => function(cx), + } + } + + pub const MOVE_CHAR_LEFT: Self = Self::Regular(move_char_left); + pub const MOVE_CHAR_RIGHT: Self = Self::Regular(move_char_right); + pub const MOVE_LINE_UP: Self = Self::Regular(move_line_up); + pub const MOVE_LINE_DOWN: Self = Self::Regular(move_line_down); + pub const MOVE_LINE_END: Self = Self::Regular(move_line_end); + pub const MOVE_LINE_START: Self = Self::Regular(move_line_start); + pub const MOVE_FIRST_NONWHITESPACE: Self = Self::Regular(move_first_nonwhitespace); + pub const MOVE_NEXT_WORD_START: Self = Self::Regular(move_next_word_start); + pub const MOVE_PREV_WORD_START: Self = Self::Regular(move_prev_word_start); + pub const MOVE_NEXT_WORD_END: Self = Self::Regular(move_next_word_end); + pub const MOVE_FILE_START: Self = Self::Regular(move_file_start); + pub const MOVE_FILE_END: Self = Self::Regular(move_file_end); + pub const EXTEND_NEXT_WORD_START: Self = Self::Regular(extend_next_word_start); + pub const EXTEND_PREV_WORD_START: Self = Self::Regular(extend_prev_word_start); + pub const EXTEND_NEXT_WORD_END: Self = Self::Regular(extend_next_word_end); + pub const FIND_TILL_CHAR: Self = Self::Regular(find_till_char); + pub const FIND_NEXT_CHAR: Self = Self::Regular(find_next_char); + pub const EXTEND_TILL_CHAR: Self = Self::Regular(extend_till_char); + pub const EXTEND_NEXT_CHAR: Self = Self::Regular(extend_next_char); + pub const TILL_PREV_CHAR: Self = Self::Regular(till_prev_char); + pub const FIND_PREV_CHAR: Self = Self::Regular(find_prev_char); + pub const EXTEND_TILL_PREV_CHAR: Self = Self::Regular(extend_till_prev_char); + pub const EXTEND_PREV_CHAR: Self = Self::Regular(extend_prev_char); + pub const EXTEND_FIRST_NONWHITESPACE: Self = Self::Regular(extend_first_nonwhitespace); + pub const REPLACE: Self = Self::Regular(replace); + pub const PAGE_UP: Self = Self::Regular(page_up); + pub const PAGE_DOWN: Self = Self::Regular(page_down); + pub const HALF_PAGE_UP: Self = Self::Regular(half_page_up); + pub const HALF_PAGE_DOWN: Self = Self::Regular(half_page_down); + pub const EXTEND_CHAR_LEFT: Self = Self::Regular(extend_char_left); + pub const EXTEND_CHAR_RIGHT: Self = Self::Regular(extend_char_right); + pub const EXTEND_LINE_UP: Self = Self::Regular(extend_line_up); + pub const EXTEND_LINE_DOWN: Self = Self::Regular(extend_line_down); + pub const EXTEND_LINE_END: Self = Self::Regular(extend_line_end); + pub const EXTEND_LINE_START: Self = Self::Regular(extend_line_start); + pub const SELECT_ALL: Self = Self::Regular(select_all); + pub const SELECT_REGEX: Self = Self::Regular(select_regex); + pub const SPLIT_SELECTION: Self = Self::Regular(split_selection); + pub const SPLIT_SELECTION_ON_NEWLINE: Self = Self::Regular(split_selection_on_newline); + pub const SEARCH: Self = Self::Regular(search); + pub const SEARCH_NEXT: Self = Self::Regular(search_next); + pub const EXTEND_SEARCH_NEXT: Self = Self::Regular(extend_search_next); + pub const SEARCH_SELECTION: Self = Self::Regular(search_selection); + pub const SELECT_LINE: Self = Self::Regular(select_line); + pub const EXTEND_LINE: Self = Self::Regular(extend_line); + pub const DELETE_SELECTION: Self = Self::Regular(delete_selection); + pub const CHANGE_SELECTION: Self = Self::Regular(change_selection); + pub const COLLAPSE_SELECTION: Self = Self::Regular(collapse_selection); + pub const FLIP_SELECTIONS: Self = Self::Regular(flip_selections); + pub const INSERT_MODE: Self = Self::Regular(insert_mode); + pub const APPEND_MODE: Self = Self::Regular(append_mode); + pub const COMMAND_MODE: Self = Self::Regular(command_mode); + pub const FILE_PICKER: Self = Self::Regular(file_picker); + pub const BUFFER_PICKER: Self = Self::Regular(buffer_picker); + pub const SYMBOL_PICKER: Self = Self::Regular(symbol_picker); + pub const PREPEND_TO_LINE: Self = Self::Regular(prepend_to_line); + pub const APPEND_TO_LINE: Self = Self::Regular(append_to_line); + pub const OPEN_BELOW: Self = Self::Regular(open_below); + pub const OPEN_ABOVE: Self = Self::Regular(open_above); + pub const NORMAL_MODE: Self = Self::Regular(normal_mode); + pub const GOTO_MODE: Self = Self::Regular(goto_mode); + pub const SELECT_MODE: Self = Self::Regular(select_mode); + pub const EXIT_SELECT_MODE: Self = Self::Regular(exit_select_mode); + pub const GOTO_DEFINITION: Self = Self::Regular(goto_definition); + pub const GOTO_TYPE_DEFINITION: Self = Self::Regular(goto_type_definition); + pub const GOTO_IMPLEMENTATION: Self = Self::Regular(goto_implementation); + pub const GOTO_REFERENCE: Self = Self::Regular(goto_reference); + pub const GOTO_FIRST_DIAG: Self = Self::Regular(goto_first_diag); + pub const GOTO_LAST_DIAG: Self = Self::Regular(goto_last_diag); + pub const GOTO_NEXT_DIAG: Self = Self::Regular(goto_next_diag); + pub const GOTO_PREV_DIAG: Self = Self::Regular(goto_prev_diag); + pub const SIGNATURE_HELP: Self = Self::Regular(signature_help); + pub const INSERT_TAB: Self = Self::Regular(insert::insert_tab); + pub const INSERT_NEWLINE: Self = Self::Regular(insert::insert_newline); + pub const DELETE_CHAR_BACKWARD: Self = Self::Regular(insert::delete_char_backward); + pub const DELETE_CHAR_FORWARD: Self = Self::Regular(insert::delete_char_forward); + pub const DELETE_WORD_BACKWARD: Self = Self::Regular(insert::delete_word_backward); + pub const UNDO: Self = Self::Regular(undo); + pub const REDO: Self = Self::Regular(redo); + pub const YANK: Self = Self::Regular(yank); + pub const REPLACE_WITH_YANKED: Self = Self::Regular(replace_with_yanked); + pub const PASTE_AFTER: Self = Self::Regular(paste_after); + pub const PASTE_BEFORE: Self = Self::Regular(paste_before); + pub const INDENT: Self = Self::Regular(indent); + pub const UNINDENT: Self = Self::Regular(unindent); + pub const FORMAT_SELECTIONS: Self = Self::Regular(format_selections); + pub const JOIN_SELECTIONS: Self = Self::Regular(join_selections); + pub const KEEP_SELECTIONS: Self = Self::Regular(keep_selections); + pub const KEEP_PRIMARY_SELECTION: Self = Self::Regular(keep_primary_selection); + pub const SAVE: Self = Self::Regular(save); + pub const COMPLETION: Self = Self::Regular(completion); + pub const HOVER: Self = Self::Regular(hover); + pub const TOGGLE_COMMENTS: Self = Self::Regular(toggle_comments); + pub const EXPAND_SELECTION: Self = Self::Regular(expand_selection); + pub const MATCH_BRACKETS: Self = Self::Regular(match_brackets); + pub const JUMP_FORWARD: Self = Self::Regular(jump_forward); + pub const JUMP_BACKWARD: Self = Self::Regular(jump_backward); + pub const WINDOW_MODE: Self = Self::Regular(window_mode); + pub const ROTATE_VIEW: Self = Self::Regular(rotate_view); + pub const HSPLIT: Self = Self::Regular(hsplit); + pub const VSPLIT: Self = Self::Regular(vsplit); + pub const WCLOSE: Self = Self::Regular(wclose); + pub const SELECT_REGISTER: Self = Self::Regular(select_register); + pub const SPACE_MODE: Self = Self::Regular(space_mode); + pub const VIEW_MODE: Self = Self::Regular(view_mode); + pub const LEFT_BRACKET_MODE: Self = Self::Regular(left_bracket_mode); + pub const RIGHT_BRACKET_MODE: Self = Self::Regular(right_bracket_mode); +} pub fn move_char_left(cx: &mut Context) { let count = cx.count(); @@ -903,7 +1028,7 @@ mod cmd { use ui::completers::{self, Completer}; #[derive(Clone)] - pub struct Command { + pub struct TypableCommandData { pub name: &'static str, pub alias: Option<&'static str>, pub doc: &'static str, @@ -1100,106 +1225,106 @@ mod cmd { _quit_all(editor, args, event, true) } - pub const COMMAND_LIST: &[Command] = &[ - Command { + pub const COMMAND_LIST: &[TypableCommandData] = &[ + TypableCommandData { name: "quit", alias: Some("q"), doc: "Close the current view.", fun: quit, completer: None, }, - Command { + TypableCommandData { name: "quit!", alias: Some("q!"), doc: "Close the current view.", fun: force_quit, completer: None, }, - Command { + TypableCommandData { name: "open", alias: Some("o"), doc: "Open a file from disk into the current view.", fun: open, completer: Some(completers::filename), }, - Command { + TypableCommandData { name: "write", alias: Some("w"), doc: "Write changes to disk. Accepts an optional path (:write some/path.txt)", fun: write, completer: Some(completers::filename), }, - Command { + TypableCommandData { name: "new", alias: Some("n"), doc: "Create a new scratch buffer.", fun: new_file, completer: Some(completers::filename), }, - Command { + TypableCommandData { name: "format", alias: Some("fmt"), doc: "Format the file using a formatter.", fun: format, completer: None, }, - Command { + TypableCommandData { name: "earlier", alias: Some("ear"), doc: "Jump back to an earlier point in edit history. Accepts a number of steps or a time span.", fun: earlier, completer: None, }, - Command { + TypableCommandData { name: "later", alias: Some("lat"), doc: "Jump to a later point in edit history. Accepts a number of steps or a time span.", fun: later, completer: None, }, - Command { + TypableCommandData { name: "write-quit", alias: Some("wq"), doc: "Writes changes to disk and closes the current view. Accepts an optional path (:wq some/path.txt)", fun: write_quit, completer: Some(completers::filename), }, - Command { + TypableCommandData { name: "write-quit!", alias: Some("wq!"), doc: "Writes changes to disk and closes the current view forcefully. Accepts an optional path (:wq! some/path.txt)", fun: force_write_quit, completer: Some(completers::filename), }, - Command { + TypableCommandData { name: "write-all", alias: Some("wa"), doc: "Writes changes from all views to disk.", fun: write_all, completer: None, }, - Command { + TypableCommandData { name: "write-quit-all", alias: Some("wqa"), doc: "Writes changes from all views to disk and close all views.", fun: write_all_quit, completer: None, }, - Command { + TypableCommandData { name: "write-quit-all!", alias: Some("wqa!"), doc: "Writes changes from all views to disk and close all views forcefully (ignoring unsaved changes).", fun: force_write_all_quit, completer: None, }, - Command { + TypableCommandData { name: "quit-all", alias: Some("qa"), doc: "Close all views.", fun: quit_all, completer: None, }, - Command { + TypableCommandData { name: "quit-all!", alias: Some("qa!"), doc: "Close all views forcefully (ignoring unsaved changes).", @@ -1209,7 +1334,7 @@ mod cmd { ]; - pub static COMMANDS: Lazy> = Lazy::new(|| { + pub static COMMANDS: Lazy> = Lazy::new(|| { let mut map = HashMap::new(); for cmd in COMMAND_LIST { @@ -1246,7 +1371,7 @@ pub fn command_mode(cx: &mut Context) { } else { let part = parts.last().unwrap(); - if let Some(cmd::Command { + if let Some(cmd::TypableCommandData { completer: Some(completer), .. }) = cmd::COMMANDS.get(parts[0]) @@ -1287,7 +1412,7 @@ pub fn command_mode(cx: &mut Context) { prompt.doc_fn = Box::new(|input: &str| { let part = input.split(' ').next().unwrap_or_default(); - if let Some(cmd::Command { doc, .. }) = cmd::COMMANDS.get(part) { + if let Some(cmd::TypableCommandData { doc, .. }) = cmd::COMMANDS.get(part) { return Some(doc); } @@ -2706,6 +2831,8 @@ pub fn rotate_view(cx: &mut Context) { // split helper, clear it later use helix_view::editor::Action; + +use self::cmd::TypableCommandData; fn split(cx: &mut Context, action: Action) { use helix_view::editor::Action; let (view, doc) = cx.current(); diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 897c047542f4..638e866ffd8d 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -133,84 +133,84 @@ macro_rules! alt { pub fn default() -> Keymaps { let normal = hashmap!( - key!('h') => commands::move_char_left as Command, - key!('j') => commands::move_line_down, - key!('k') => commands::move_line_up, - key!('l') => commands::move_char_right, + key!('h') => commands::Command::MOVE_CHAR_LEFT, + key!('j') => commands::Command::MOVE_LINE_DOWN, + key!('k') => commands::Command::MOVE_LINE_UP, + key!('l') => commands::Command::MOVE_CHAR_RIGHT, KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE - } => commands::move_char_left, + } => commands::Command::MOVE_CHAR_LEFT, KeyEvent { code: KeyCode::Down, modifiers: KeyModifiers::NONE - } => commands::move_line_down, + } => commands::Command::MOVE_LINE_DOWN, KeyEvent { code: KeyCode::Up, modifiers: KeyModifiers::NONE - } => commands::move_line_up, + } => commands::Command::MOVE_LINE_UP, KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE - } => commands::move_char_right, + } => commands::Command::MOVE_CHAR_RIGHT, - key!('t') => commands::find_till_char, - key!('f') => commands::find_next_char, - key!('T') => commands::till_prev_char, - key!('F') => commands::find_prev_char, + key!('t') => commands::Command::FIND_TILL_CHAR, + key!('f') => commands::Command::FIND_NEXT_CHAR, + key!('T') => commands::Command::TILL_PREV_CHAR, + key!('F') => commands::Command::FIND_PREV_CHAR, // and matching set for select mode (extend) // - key!('r') => commands::replace, - key!('R') => commands::replace_with_yanked, + key!('r') => commands::Command::REPLACE, + key!('R') => commands::Command::REPLACE_WITH_YANKED, KeyEvent { code: KeyCode::Home, modifiers: KeyModifiers::NONE - } => commands::move_line_start, + } => commands::Command::MOVE_LINE_START, KeyEvent { code: KeyCode::End, modifiers: KeyModifiers::NONE - } => commands::move_line_end, - - key!('w') => commands::move_next_word_start, - key!('b') => commands::move_prev_word_start, - key!('e') => commands::move_next_word_end, - - key!('v') => commands::select_mode, - key!('g') => commands::goto_mode, - key!(':') => commands::command_mode, - - key!('i') => commands::insert_mode, - key!('I') => commands::prepend_to_line, - key!('a') => commands::append_mode, - key!('A') => commands::append_to_line, - key!('o') => commands::open_below, - key!('O') => commands::open_above, + } => commands::Command::MOVE_LINE_END, + + key!('w') => commands::Command::MOVE_NEXT_WORD_START, + key!('b') => commands::Command::MOVE_PREV_WORD_START, + key!('e') => commands::Command::MOVE_NEXT_WORD_END, + + key!('v') => commands::Command::SELECT_MODE, + key!('g') => commands::Command::GOTO_MODE, + key!(':') => commands::Command::COMMAND_MODE, + + key!('i') => commands::Command::INSERT_MODE, + key!('I') => commands::Command::PREPEND_TO_LINE, + key!('a') => commands::Command::APPEND_MODE, + key!('A') => commands::Command::APPEND_TO_LINE, + key!('o') => commands::Command::OPEN_BELOW, + key!('O') => commands::Command::OPEN_ABOVE, // [ ] equivalents too (add blank new line, no edit) - key!('d') => commands::delete_selection, + key!('d') => commands::Command::DELETE_SELECTION, // TODO: also delete without yanking - key!('c') => commands::change_selection, + key!('c') => commands::Command::CHANGE_SELECTION, // TODO: also change delete without yanking - // key!('r') => commands::replace_with_char, + // key!('r') => commands::Command::REPLACE_WITH_CHAR, - key!('s') => commands::select_regex, - alt!('s') => commands::split_selection_on_newline, - key!('S') => commands::split_selection, - key!(';') => commands::collapse_selection, - alt!(';') => commands::flip_selections, - key!('%') => commands::select_all, - key!('x') => commands::select_line, - key!('X') => commands::extend_line, + key!('s') => commands::Command::SELECT_REGEX, + alt!('s') => commands::Command::SPLIT_SELECTION_ON_NEWLINE, + key!('S') => commands::Command::SPLIT_SELECTION, + key!(';') => commands::Command::COLLAPSE_SELECTION, + alt!(';') => commands::Command::FLIP_SELECTIONS, + key!('%') => commands::Command::SELECT_ALL, + key!('x') => commands::Command::SELECT_LINE, + key!('X') => commands::Command::EXTEND_LINE, // or select mode X? // extend_to_whole_line, crop_to_whole_line - key!('m') => commands::match_brackets, + key!('m') => commands::Command::MATCH_BRACKETS, // TODO: refactor into // key!('m') => commands::select_to_matching, // key!('M') => commands::back_select_to_matching, @@ -220,39 +220,39 @@ pub fn default() -> Keymaps { // repeat_select // TODO: figure out what key to use - // key!('[') => commands::expand_selection, ?? - key!('[') => commands::left_bracket_mode, - key!(']') => commands::right_bracket_mode, + // key!('[') => commands::Command::EXPAND_SELECTION, ?? + key!('[') => commands::Command::LEFT_BRACKET_MODE, + key!(']') => commands::Command::RIGHT_BRACKET_MODE, - key!('/') => commands::search, + key!('/') => commands::Command::SEARCH, // ? for search_reverse - key!('n') => commands::search_next, - key!('N') => commands::extend_search_next, + key!('n') => commands::Command::SEARCH_NEXT, + key!('N') => commands::Command::EXTEND_SEARCH_NEXT, // N for search_prev - key!('*') => commands::search_selection, + key!('*') => commands::Command::SEARCH_SELECTION, - key!('u') => commands::undo, - key!('U') => commands::redo, + key!('u') => commands::Command::UNDO, + key!('U') => commands::Command::REDO, - key!('y') => commands::yank, + key!('y') => commands::Command::YANK, // yank_all - key!('p') => commands::paste_after, + key!('p') => commands::Command::PASTE_AFTER, // paste_all - key!('P') => commands::paste_before, + key!('P') => commands::Command::PASTE_BEFORE, - key!('>') => commands::indent, - key!('<') => commands::unindent, - key!('=') => commands::format_selections, - key!('J') => commands::join_selections, + key!('>') => commands::Command::INDENT, + key!('<') => commands::Command::UNINDENT, + key!('=') => commands::Command::FORMAT_SELECTIONS, + key!('J') => commands::Command::JOIN_SELECTIONS, // TODO: conflicts hover/doc - key!('K') => commands::keep_selections, + key!('K') => commands::Command::KEEP_SELECTIONS, // TODO: and another method for inverse // TODO: clashes with space mode - key!(' ') => commands::keep_primary_selection, + key!(' ') => commands::Command::KEEP_PRIMARY_SELECTION, - // key!('q') => commands::record_macro, - // key!('Q') => commands::replay_macro, + // key!('q') => commands::Command::RECORD_MACRO, + // key!('Q') => commands::Command::REPLAY_MACRO, // ~ / apostrophe => change case // & align selections @@ -263,39 +263,39 @@ pub fn default() -> Keymaps { KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::normal_mode, + } => commands::Command::NORMAL_MODE, KeyEvent { code: KeyCode::PageUp, modifiers: KeyModifiers::NONE - } => commands::page_up, - ctrl!('b') => commands::page_up, + } => commands::Command::PAGE_UP, + ctrl!('b') => commands::Command::PAGE_UP, KeyEvent { code: KeyCode::PageDown, modifiers: KeyModifiers::NONE - } => commands::page_down, - ctrl!('f') => commands::page_down, - ctrl!('u') => commands::half_page_up, - ctrl!('d') => commands::half_page_down, + } => commands::Command::PAGE_DOWN, + ctrl!('f') => commands::Command::PAGE_DOWN, + ctrl!('u') => commands::Command::HALF_PAGE_UP, + ctrl!('d') => commands::Command::HALF_PAGE_DOWN, - ctrl!('w') => commands::window_mode, + ctrl!('w') => commands::Command::WINDOW_MODE, // move under c - ctrl!('c') => commands::toggle_comments, - key!('K') => commands::hover, + ctrl!('c') => commands::Command::TOGGLE_COMMENTS, + key!('K') => commands::Command::HOVER, // z family for save/restore/combine from/to sels from register KeyEvent { // supposedly ctrl!('i') but did not work code: KeyCode::Tab, modifiers: KeyModifiers::NONE, - } => commands::jump_forward, - ctrl!('o') => commands::jump_backward, - // ctrl!('s') => commands::save_selection, + } => commands::Command::JUMP_FORWARD, + ctrl!('o') => commands::Command::JUMP_BACKWARD, + // ctrl!('s') => commands::Command::SAVE_SELECTION, - key!(' ') => commands::space_mode, - key!('z') => commands::view_mode, + key!(' ') => commands::Command::SPACE_MODE, + key!('z') => commands::Command::VIEW_MODE, - key!('"') => commands::select_register, + key!('"') => commands::Command::SELECT_REGISTER, ); // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether // we keep this separate select mode. More keys can fit into normal mode then, but it's weird @@ -303,49 +303,49 @@ pub fn default() -> Keymaps { let mut select = normal.clone(); select.extend( hashmap!( - key!('h') => commands::extend_char_left as Command, - key!('j') => commands::extend_line_down, - key!('k') => commands::extend_line_up, - key!('l') => commands::extend_char_right, + key!('h') => commands::Command::EXTEND_CHAR_LEFT, + key!('j') => commands::Command::EXTEND_LINE_DOWN, + key!('k') => commands::Command::EXTEND_LINE_UP, + key!('l') => commands::Command::EXTEND_CHAR_RIGHT, KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE - } => commands::extend_char_left, + } => commands::Command::EXTEND_CHAR_LEFT, KeyEvent { code: KeyCode::Down, modifiers: KeyModifiers::NONE - } => commands::extend_line_down, + } => commands::Command::EXTEND_LINE_DOWN, KeyEvent { code: KeyCode::Up, modifiers: KeyModifiers::NONE - } => commands::extend_line_up, + } => commands::Command::EXTEND_LINE_UP, KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE - } => commands::extend_char_right, + } => commands::Command::EXTEND_CHAR_RIGHT, - key!('w') => commands::extend_next_word_start, - key!('b') => commands::extend_prev_word_start, - key!('e') => commands::extend_next_word_end, + key!('w') => commands::Command::EXTEND_NEXT_WORD_START, + key!('b') => commands::Command::EXTEND_PREV_WORD_START, + key!('e') => commands::Command::EXTEND_NEXT_WORD_END, - key!('t') => commands::extend_till_char, - key!('f') => commands::extend_next_char, + key!('t') => commands::Command::EXTEND_TILL_CHAR, + key!('f') => commands::Command::EXTEND_NEXT_CHAR, - key!('T') => commands::extend_till_prev_char, - key!('F') => commands::extend_prev_char, + key!('T') => commands::Command::EXTEND_TILL_PREV_CHAR, + key!('F') => commands::Command::EXTEND_PREV_CHAR, KeyEvent { code: KeyCode::Home, modifiers: KeyModifiers::NONE - } => commands::extend_line_start, + } => commands::Command::EXTEND_LINE_START, KeyEvent { code: KeyCode::End, modifiers: KeyModifiers::NONE - } => commands::extend_line_end, + } => commands::Command::EXTEND_LINE_END, KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::exit_select_mode, + } => commands::Command::EXIT_SELECT_MODE, ) .into_iter(), ); @@ -359,26 +359,26 @@ pub fn default() -> Keymaps { KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::normal_mode as Command, + } => commands::Command::NORMAL_MODE, KeyEvent { code: KeyCode::Backspace, modifiers: KeyModifiers::NONE - } => commands::insert::delete_char_backward, + } => commands::Command::DELETE_CHAR_BACKWARD, KeyEvent { code: KeyCode::Delete, modifiers: KeyModifiers::NONE - } => commands::insert::delete_char_forward, + } => commands::Command::DELETE_CHAR_FORWARD, KeyEvent { code: KeyCode::Enter, modifiers: KeyModifiers::NONE - } => commands::insert::insert_newline, + } => commands::Command::INSERT_NEWLINE, KeyEvent { code: KeyCode::Tab, modifiers: KeyModifiers::NONE - } => commands::insert::insert_tab, + } => commands::Command::INSERT_TAB, - ctrl!('x') => commands::completion, - ctrl!('w') => commands::insert::delete_word_backward, + ctrl!('x') => commands::Command::COMPLETION, + ctrl!('w') => commands::Command::DELETE_WORD_BACKWARD, ), ) } diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index f34e872bfc51..3380510e324a 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -45,7 +45,7 @@ impl EditorView { Self { keymap: keymap::default(), on_next_key: None, - last_insert: (commands::normal_mode, Vec::new()), + last_insert: (commands::Command::NORMAL_MODE, Vec::new()), completion: None, } } @@ -512,7 +512,7 @@ impl EditorView { fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) { if let Some(command) = self.keymap[&Mode::Insert].get(&event) { - command(cx); + command.execute(cx); } else if let KeyEvent { code: KeyCode::Char(ch), .. @@ -533,7 +533,7 @@ impl EditorView { // special handling for repeat operator key!('.') => { // first execute whatever put us into insert mode - (self.last_insert.0)(cxt); + self.last_insert.0.execute(cxt); // then replay the inputs for key in &self.last_insert.1 { self.insert_mode(cxt, *key) @@ -550,7 +550,7 @@ impl EditorView { cxt.register = cxt.editor.register.take(); if let Some(command) = self.keymap[&mode].get(&event) { - command(cxt); + command.execute(cxt); } } } @@ -574,7 +574,7 @@ impl EditorView { let mut new_pairs = HashMap::::new(); for (source, target) in remap { if let Some(command) = self.keymap.get(&mode).map(|m| m.get(&target)).flatten() { - new_pairs.insert(source, *command); + new_pairs.insert(source, command.clone()); } } @@ -681,7 +681,7 @@ impl Component for EditorView { // how we entered insert mode is important, and we should track that so // we can repeat the side effect. - self.last_insert.0 = self.keymap[&mode][&key]; + self.last_insert.0 = self.keymap[&mode][&key].clone(); self.last_insert.1.clear(); } (Mode::Insert, Mode::Normal) => { From da470691322361c94501d5e3013ca9a2ea9cc99e Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:23:05 +0200 Subject: [PATCH 08/19] Make command functions private --- helix-term/src/commands.rs | 559 +++++++++++++++++++----------------- helix-term/src/keymap.rs | 208 +++++++------- helix-term/src/ui/editor.rs | 2 +- 3 files changed, 398 insertions(+), 371 deletions(-) diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 9313049bb610..fba9a9531934 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -20,6 +20,7 @@ use helix_lsp::{ OffsetEncoding, }; use movement::Movement; +use anyhow::anyhow; use crate::{ compositor::{Callback, Component, Compositor}, @@ -28,7 +29,7 @@ use crate::{ use crate::application::{LspCallbackWrapper, LspCallbacks}; use futures_util::FutureExt; -use std::future::Future; +use std::{fmt, future::Future, path::Display, str::FromStr}; use std::{ borrow::Cow, @@ -37,6 +38,7 @@ use std::{ use crossterm::event::{KeyCode, KeyEvent}; use once_cell::sync::Lazy; +use insert::*; pub struct Context<'a> { pub register: helix_view::RegisterSelection, @@ -131,131 +133,136 @@ fn align_view(doc: &Document, view: &mut View, align: Align) { //pub type Command = fn(cx: &mut Context); #[derive(Clone)] -pub enum Command { - /// Regular commands are reached only by their bound key/combination - Regular(fn(cx: &mut Context)), - /// Typable commands can be bound to keys and also typed through `:` - Typable(fn(cx: &mut Context), TypableCommandData), +pub struct Command(fn(cx: &mut Context), &'static str); + +macro_rules! commands { + ( $($name: ident),* ) => { + $( + #[allow(non_upper_case_globals)] + pub const $name: Self = Self($name, stringify!($name)); + )* + + pub const COMMAND_LIST: &'static [Self] = &[ + $( Self::$name, )* + ]; + } } impl Command { - pub fn execute(&self, cx: &mut Context) { - match self { - Command::Regular(function) => function(cx), - Command::Typable(function, _) => function(cx), - } - } + pub fn execute(&self, cx: &mut Context) { (self.0)(cx); } + + commands!( + move_char_left, + move_char_right, + move_line_up, + move_line_down, + move_line_end, + move_line_start, + move_first_nonwhitespace, + move_next_word_start, + move_prev_word_start, + move_next_word_end, + move_file_start, + move_file_end, + extend_next_word_start, + extend_prev_word_start, + extend_next_word_end, + find_till_char, + find_next_char, + extend_till_char, + extend_next_char, + till_prev_char, + find_prev_char, + extend_till_prev_char, + extend_prev_char, + extend_first_nonwhitespace, + replace, + page_up, + page_down, + half_page_up, + half_page_down, + extend_char_left, + extend_char_right, + extend_line_up, + extend_line_down, + extend_line_end, + extend_line_start, + select_all, + select_regex, + split_selection, + split_selection_on_newline, + search, + search_next, + extend_search_next, + search_selection, + select_line, + extend_line, + delete_selection, + change_selection, + collapse_selection, + flip_selections, + insert_mode, + append_mode, + command_mode, + file_picker, + buffer_picker, + symbol_picker, + prepend_to_line, + append_to_line, + open_below, + open_above, + normal_mode, + goto_mode, + select_mode, + exit_select_mode, + goto_definition, + goto_type_definition, + goto_implementation, + goto_reference, + goto_first_diag, + goto_last_diag, + goto_next_diag, + goto_prev_diag, + signature_help, + insert_tab, + insert_newline, + delete_char_backward, + delete_char_forward, + delete_word_backward, + undo, + redo, + yank, + replace_with_yanked, + paste_after, + paste_before, + indent, + unindent, + format_selections, + join_selections, + keep_selections, + keep_primary_selection, + save, + completion, + hover, + toggle_comments, + expand_selection, + match_brackets, + jump_forward, + jump_backward, + window_mode, + rotate_view, + hsplit, + vsplit, + wclose, + select_register, + space_mode, + view_mode, + left_bracket_mode, + right_bracket_mode + ); +} - pub const MOVE_CHAR_LEFT: Self = Self::Regular(move_char_left); - pub const MOVE_CHAR_RIGHT: Self = Self::Regular(move_char_right); - pub const MOVE_LINE_UP: Self = Self::Regular(move_line_up); - pub const MOVE_LINE_DOWN: Self = Self::Regular(move_line_down); - pub const MOVE_LINE_END: Self = Self::Regular(move_line_end); - pub const MOVE_LINE_START: Self = Self::Regular(move_line_start); - pub const MOVE_FIRST_NONWHITESPACE: Self = Self::Regular(move_first_nonwhitespace); - pub const MOVE_NEXT_WORD_START: Self = Self::Regular(move_next_word_start); - pub const MOVE_PREV_WORD_START: Self = Self::Regular(move_prev_word_start); - pub const MOVE_NEXT_WORD_END: Self = Self::Regular(move_next_word_end); - pub const MOVE_FILE_START: Self = Self::Regular(move_file_start); - pub const MOVE_FILE_END: Self = Self::Regular(move_file_end); - pub const EXTEND_NEXT_WORD_START: Self = Self::Regular(extend_next_word_start); - pub const EXTEND_PREV_WORD_START: Self = Self::Regular(extend_prev_word_start); - pub const EXTEND_NEXT_WORD_END: Self = Self::Regular(extend_next_word_end); - pub const FIND_TILL_CHAR: Self = Self::Regular(find_till_char); - pub const FIND_NEXT_CHAR: Self = Self::Regular(find_next_char); - pub const EXTEND_TILL_CHAR: Self = Self::Regular(extend_till_char); - pub const EXTEND_NEXT_CHAR: Self = Self::Regular(extend_next_char); - pub const TILL_PREV_CHAR: Self = Self::Regular(till_prev_char); - pub const FIND_PREV_CHAR: Self = Self::Regular(find_prev_char); - pub const EXTEND_TILL_PREV_CHAR: Self = Self::Regular(extend_till_prev_char); - pub const EXTEND_PREV_CHAR: Self = Self::Regular(extend_prev_char); - pub const EXTEND_FIRST_NONWHITESPACE: Self = Self::Regular(extend_first_nonwhitespace); - pub const REPLACE: Self = Self::Regular(replace); - pub const PAGE_UP: Self = Self::Regular(page_up); - pub const PAGE_DOWN: Self = Self::Regular(page_down); - pub const HALF_PAGE_UP: Self = Self::Regular(half_page_up); - pub const HALF_PAGE_DOWN: Self = Self::Regular(half_page_down); - pub const EXTEND_CHAR_LEFT: Self = Self::Regular(extend_char_left); - pub const EXTEND_CHAR_RIGHT: Self = Self::Regular(extend_char_right); - pub const EXTEND_LINE_UP: Self = Self::Regular(extend_line_up); - pub const EXTEND_LINE_DOWN: Self = Self::Regular(extend_line_down); - pub const EXTEND_LINE_END: Self = Self::Regular(extend_line_end); - pub const EXTEND_LINE_START: Self = Self::Regular(extend_line_start); - pub const SELECT_ALL: Self = Self::Regular(select_all); - pub const SELECT_REGEX: Self = Self::Regular(select_regex); - pub const SPLIT_SELECTION: Self = Self::Regular(split_selection); - pub const SPLIT_SELECTION_ON_NEWLINE: Self = Self::Regular(split_selection_on_newline); - pub const SEARCH: Self = Self::Regular(search); - pub const SEARCH_NEXT: Self = Self::Regular(search_next); - pub const EXTEND_SEARCH_NEXT: Self = Self::Regular(extend_search_next); - pub const SEARCH_SELECTION: Self = Self::Regular(search_selection); - pub const SELECT_LINE: Self = Self::Regular(select_line); - pub const EXTEND_LINE: Self = Self::Regular(extend_line); - pub const DELETE_SELECTION: Self = Self::Regular(delete_selection); - pub const CHANGE_SELECTION: Self = Self::Regular(change_selection); - pub const COLLAPSE_SELECTION: Self = Self::Regular(collapse_selection); - pub const FLIP_SELECTIONS: Self = Self::Regular(flip_selections); - pub const INSERT_MODE: Self = Self::Regular(insert_mode); - pub const APPEND_MODE: Self = Self::Regular(append_mode); - pub const COMMAND_MODE: Self = Self::Regular(command_mode); - pub const FILE_PICKER: Self = Self::Regular(file_picker); - pub const BUFFER_PICKER: Self = Self::Regular(buffer_picker); - pub const SYMBOL_PICKER: Self = Self::Regular(symbol_picker); - pub const PREPEND_TO_LINE: Self = Self::Regular(prepend_to_line); - pub const APPEND_TO_LINE: Self = Self::Regular(append_to_line); - pub const OPEN_BELOW: Self = Self::Regular(open_below); - pub const OPEN_ABOVE: Self = Self::Regular(open_above); - pub const NORMAL_MODE: Self = Self::Regular(normal_mode); - pub const GOTO_MODE: Self = Self::Regular(goto_mode); - pub const SELECT_MODE: Self = Self::Regular(select_mode); - pub const EXIT_SELECT_MODE: Self = Self::Regular(exit_select_mode); - pub const GOTO_DEFINITION: Self = Self::Regular(goto_definition); - pub const GOTO_TYPE_DEFINITION: Self = Self::Regular(goto_type_definition); - pub const GOTO_IMPLEMENTATION: Self = Self::Regular(goto_implementation); - pub const GOTO_REFERENCE: Self = Self::Regular(goto_reference); - pub const GOTO_FIRST_DIAG: Self = Self::Regular(goto_first_diag); - pub const GOTO_LAST_DIAG: Self = Self::Regular(goto_last_diag); - pub const GOTO_NEXT_DIAG: Self = Self::Regular(goto_next_diag); - pub const GOTO_PREV_DIAG: Self = Self::Regular(goto_prev_diag); - pub const SIGNATURE_HELP: Self = Self::Regular(signature_help); - pub const INSERT_TAB: Self = Self::Regular(insert::insert_tab); - pub const INSERT_NEWLINE: Self = Self::Regular(insert::insert_newline); - pub const DELETE_CHAR_BACKWARD: Self = Self::Regular(insert::delete_char_backward); - pub const DELETE_CHAR_FORWARD: Self = Self::Regular(insert::delete_char_forward); - pub const DELETE_WORD_BACKWARD: Self = Self::Regular(insert::delete_word_backward); - pub const UNDO: Self = Self::Regular(undo); - pub const REDO: Self = Self::Regular(redo); - pub const YANK: Self = Self::Regular(yank); - pub const REPLACE_WITH_YANKED: Self = Self::Regular(replace_with_yanked); - pub const PASTE_AFTER: Self = Self::Regular(paste_after); - pub const PASTE_BEFORE: Self = Self::Regular(paste_before); - pub const INDENT: Self = Self::Regular(indent); - pub const UNINDENT: Self = Self::Regular(unindent); - pub const FORMAT_SELECTIONS: Self = Self::Regular(format_selections); - pub const JOIN_SELECTIONS: Self = Self::Regular(join_selections); - pub const KEEP_SELECTIONS: Self = Self::Regular(keep_selections); - pub const KEEP_PRIMARY_SELECTION: Self = Self::Regular(keep_primary_selection); - pub const SAVE: Self = Self::Regular(save); - pub const COMPLETION: Self = Self::Regular(completion); - pub const HOVER: Self = Self::Regular(hover); - pub const TOGGLE_COMMENTS: Self = Self::Regular(toggle_comments); - pub const EXPAND_SELECTION: Self = Self::Regular(expand_selection); - pub const MATCH_BRACKETS: Self = Self::Regular(match_brackets); - pub const JUMP_FORWARD: Self = Self::Regular(jump_forward); - pub const JUMP_BACKWARD: Self = Self::Regular(jump_backward); - pub const WINDOW_MODE: Self = Self::Regular(window_mode); - pub const ROTATE_VIEW: Self = Self::Regular(rotate_view); - pub const HSPLIT: Self = Self::Regular(hsplit); - pub const VSPLIT: Self = Self::Regular(vsplit); - pub const WCLOSE: Self = Self::Regular(wclose); - pub const SELECT_REGISTER: Self = Self::Regular(select_register); - pub const SPACE_MODE: Self = Self::Regular(space_mode); - pub const VIEW_MODE: Self = Self::Regular(view_mode); - pub const LEFT_BRACKET_MODE: Self = Self::Regular(left_bracket_mode); - pub const RIGHT_BRACKET_MODE: Self = Self::Regular(right_bracket_mode); -} - -pub fn move_char_left(cx: &mut Context) { +fn move_char_left(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -265,7 +272,7 @@ pub fn move_char_left(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_char_right(cx: &mut Context) { +fn move_char_right(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -275,7 +282,7 @@ pub fn move_char_right(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_line_up(cx: &mut Context) { +fn move_line_up(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -285,7 +292,7 @@ pub fn move_line_up(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_line_down(cx: &mut Context) { +fn move_line_down(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -295,7 +302,7 @@ pub fn move_line_down(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_line_end(cx: &mut Context) { +fn move_line_end(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -311,7 +318,7 @@ pub fn move_line_end(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_line_start(cx: &mut Context) { +fn move_line_start(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -326,7 +333,7 @@ pub fn move_line_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_first_nonwhitespace(cx: &mut Context) { +fn move_first_nonwhitespace(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -348,7 +355,7 @@ pub fn move_first_nonwhitespace(cx: &mut Context) { // Range::new(if Move { pos } if Extend { range.anchor }, pos) // since these all really do the same thing -pub fn move_next_word_start(cx: &mut Context) { +fn move_next_word_start(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -360,7 +367,7 @@ pub fn move_next_word_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_prev_word_start(cx: &mut Context) { +fn move_prev_word_start(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -372,7 +379,7 @@ pub fn move_prev_word_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_next_word_end(cx: &mut Context) { +fn move_next_word_end(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -384,13 +391,13 @@ pub fn move_next_word_end(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn move_file_start(cx: &mut Context) { +fn move_file_start(cx: &mut Context) { push_jump(cx.editor); let (view, doc) = cx.current(); doc.set_selection(view.id, Selection::point(0)); } -pub fn move_file_end(cx: &mut Context) { +fn move_file_end(cx: &mut Context) { push_jump(cx.editor); let (view, doc) = cx.current(); let text = doc.text(); @@ -398,7 +405,7 @@ pub fn move_file_end(cx: &mut Context) { doc.set_selection(view.id, Selection::point(last_line)); } -pub fn extend_next_word_start(cx: &mut Context) { +fn extend_next_word_start(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -412,7 +419,7 @@ pub fn extend_next_word_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_prev_word_start(cx: &mut Context) { +fn extend_prev_word_start(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -425,7 +432,7 @@ pub fn extend_prev_word_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_next_word_end(cx: &mut Context) { +fn extend_next_word_end(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -483,16 +490,16 @@ where }) } -pub fn find_till_char(cx: &mut Context) { +fn find_till_char(cx: &mut Context) { _find_char( cx, - search::find_nth_next, + search::find_nth_next, false, /* inclusive */ false, /* extend */ ) } -pub fn find_next_char(cx: &mut Context) { +fn find_next_char(cx: &mut Context) { _find_char( cx, search::find_nth_next, @@ -501,7 +508,7 @@ pub fn find_next_char(cx: &mut Context) { ) } -pub fn extend_till_char(cx: &mut Context) { +fn extend_till_char(cx: &mut Context) { _find_char( cx, search::find_nth_next, @@ -510,7 +517,7 @@ pub fn extend_till_char(cx: &mut Context) { ) } -pub fn extend_next_char(cx: &mut Context) { +fn extend_next_char(cx: &mut Context) { _find_char( cx, search::find_nth_next, @@ -519,7 +526,7 @@ pub fn extend_next_char(cx: &mut Context) { ) } -pub fn till_prev_char(cx: &mut Context) { +fn till_prev_char(cx: &mut Context) { _find_char( cx, search::find_nth_prev, @@ -528,7 +535,7 @@ pub fn till_prev_char(cx: &mut Context) { ) } -pub fn find_prev_char(cx: &mut Context) { +fn find_prev_char(cx: &mut Context) { _find_char( cx, search::find_nth_prev, @@ -537,7 +544,7 @@ pub fn find_prev_char(cx: &mut Context) { ) } -pub fn extend_till_prev_char(cx: &mut Context) { +fn extend_till_prev_char(cx: &mut Context) { _find_char( cx, search::find_nth_prev, @@ -546,7 +553,7 @@ pub fn extend_till_prev_char(cx: &mut Context) { ) } -pub fn extend_prev_char(cx: &mut Context) { +fn extend_prev_char(cx: &mut Context) { _find_char( cx, search::find_nth_prev, @@ -555,7 +562,7 @@ pub fn extend_prev_char(cx: &mut Context) { ) } -pub fn extend_first_nonwhitespace(cx: &mut Context) { +fn extend_first_nonwhitespace(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -573,7 +580,7 @@ pub fn extend_first_nonwhitespace(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn replace(cx: &mut Context) { +fn replace(cx: &mut Context) { // need to wait for next key cx.on_next_key(move |cx, event| { let ch = match event { @@ -653,31 +660,31 @@ fn scroll(cx: &mut Context, offset: usize, direction: Direction) { doc.set_selection(view.id, Selection::point(pos)); } -pub fn page_up(cx: &mut Context) { +fn page_up(cx: &mut Context) { let view = cx.view(); let offset = view.area.height as usize; scroll(cx, offset, Direction::Backward); } -pub fn page_down(cx: &mut Context) { +fn page_down(cx: &mut Context) { let view = cx.view(); let offset = view.area.height as usize; scroll(cx, offset, Direction::Forward); } -pub fn half_page_up(cx: &mut Context) { +fn half_page_up(cx: &mut Context) { let view = cx.view(); let offset = view.area.height as usize / 2; scroll(cx, offset, Direction::Backward); } -pub fn half_page_down(cx: &mut Context) { +fn half_page_down(cx: &mut Context) { let view = cx.view(); let offset = view.area.height as usize / 2; scroll(cx, offset, Direction::Forward); } -pub fn extend_char_left(cx: &mut Context) { +fn extend_char_left(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -687,7 +694,7 @@ pub fn extend_char_left(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_char_right(cx: &mut Context) { +fn extend_char_right(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -697,7 +704,7 @@ pub fn extend_char_right(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_line_up(cx: &mut Context) { +fn extend_line_up(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -707,7 +714,7 @@ pub fn extend_line_up(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_line_down(cx: &mut Context) { +fn extend_line_down(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -717,7 +724,7 @@ pub fn extend_line_down(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_line_end(cx: &mut Context) { +fn extend_line_end(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -733,7 +740,7 @@ pub fn extend_line_end(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn extend_line_start(cx: &mut Context) { +fn extend_line_start(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc.selection(view.id).transform(|range| { @@ -748,14 +755,14 @@ pub fn extend_line_start(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn select_all(cx: &mut Context) { +fn select_all(cx: &mut Context) { let (view, doc) = cx.current(); let end = doc.text().len_chars().saturating_sub(1); doc.set_selection(view.id, Selection::single(0, end)) } -pub fn select_regex(cx: &mut Context) { +fn select_regex(cx: &mut Context) { let prompt = ui::regex_prompt(cx, "select:".to_string(), move |view, doc, regex| { let text = doc.text().slice(..); if let Some(selection) = selection::select_on_matches(text, doc.selection(view.id), ®ex) @@ -767,7 +774,7 @@ pub fn select_regex(cx: &mut Context) { cx.push_layer(Box::new(prompt)); } -pub fn split_selection(cx: &mut Context) { +fn split_selection(cx: &mut Context) { let prompt = ui::regex_prompt(cx, "split:".to_string(), move |view, doc, regex| { let text = doc.text().slice(..); let selection = selection::split_on_matches(text, doc.selection(view.id), ®ex); @@ -777,7 +784,7 @@ pub fn split_selection(cx: &mut Context) { cx.push_layer(Box::new(prompt)); } -pub fn split_selection_on_newline(cx: &mut Context) { +fn split_selection_on_newline(cx: &mut Context) { let (view, doc) = cx.current(); let text = doc.text().slice(..); // only compile the regex once @@ -829,7 +836,7 @@ fn _search(doc: &mut Document, view: &mut View, contents: &str, regex: &Regex, e } // TODO: use one function for search vs extend -pub fn search(cx: &mut Context) { +fn search(cx: &mut Context) { let (view, doc) = cx.current(); // TODO: could probably share with select_on_matches? @@ -852,7 +859,7 @@ pub fn search(cx: &mut Context) { } // can't search next for ""compose"" for some reason -pub fn _search_next(cx: &mut Context, extend: bool) { +fn _search_next(cx: &mut Context, extend: bool) { if let Some(query) = register::get('\\') { let query = query.first().unwrap(); let (view, doc) = cx.current(); @@ -862,15 +869,15 @@ pub fn _search_next(cx: &mut Context, extend: bool) { } } -pub fn search_next(cx: &mut Context) { +fn search_next(cx: &mut Context) { _search_next(cx, false); } -pub fn extend_search_next(cx: &mut Context) { +fn extend_search_next(cx: &mut Context) { _search_next(cx, true); } -pub fn search_selection(cx: &mut Context) { +fn search_selection(cx: &mut Context) { let (view, doc) = cx.current(); let contents = doc.text().slice(..); let query = doc.selection(view.id).primary().fragment(contents); @@ -885,7 +892,7 @@ pub fn search_selection(cx: &mut Context) { // -pub fn select_line(cx: &mut Context) { +fn select_line(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); @@ -900,7 +907,7 @@ pub fn select_line(cx: &mut Context) { doc.set_selection(view.id, Selection::single(start, end)); } -pub fn extend_line(cx: &mut Context) { +fn extend_line(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); @@ -923,7 +930,7 @@ pub fn extend_line(cx: &mut Context) { // heuristic: append changes to history after each command, unless we're in insert mode fn _delete_selection(reg: char, doc: &mut Document, view_id: ViewId) { - // first yank the selection + // first yank the selection let values: Vec = doc .selection(view_id) .fragments(doc.text().slice(..)) @@ -942,7 +949,7 @@ fn _delete_selection(reg: char, doc: &mut Document, view_id: ViewId) { doc.apply(&transaction, view_id); } -pub fn delete_selection(cx: &mut Context) { +fn delete_selection(cx: &mut Context) { let reg = cx.register.name(); let (view, doc) = cx.current(); _delete_selection(reg, doc, view.id); @@ -950,17 +957,17 @@ pub fn delete_selection(cx: &mut Context) { doc.append_changes_to_history(view.id); // exit select mode, if currently in select mode - exit_select_mode(cx); + exit_select_mode(cx); } -pub fn change_selection(cx: &mut Context) { +fn change_selection(cx: &mut Context) { let reg = cx.register.name(); let (view, doc) = cx.current(); _delete_selection(reg, doc, view.id); enter_insert_mode(doc); } -pub fn collapse_selection(cx: &mut Context) { +fn collapse_selection(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc .selection(view.id) @@ -969,7 +976,7 @@ pub fn collapse_selection(cx: &mut Context) { doc.set_selection(view.id, selection); } -pub fn flip_selections(cx: &mut Context) { +fn flip_selections(cx: &mut Context) { let (view, doc) = cx.current(); let selection = doc .selection(view.id) @@ -983,7 +990,7 @@ fn enter_insert_mode(doc: &mut Document) { } // inserts at the start of each selection -pub fn insert_mode(cx: &mut Context) { +fn insert_mode(cx: &mut Context) { let (view, doc) = cx.current(); enter_insert_mode(doc); @@ -994,7 +1001,7 @@ pub fn insert_mode(cx: &mut Context) { } // inserts at the end of each selection -pub fn append_mode(cx: &mut Context) { +fn append_mode(cx: &mut Context) { let (view, doc) = cx.current(); enter_insert_mode(doc); doc.restore_cursor = true; @@ -1028,7 +1035,7 @@ mod cmd { use ui::completers::{self, Completer}; #[derive(Clone)] - pub struct TypableCommandData { + pub struct TypableCommand { pub name: &'static str, pub alias: Option<&'static str>, pub doc: &'static str, @@ -1081,7 +1088,7 @@ mod cmd { .map(|config| config.auto_format) .unwrap_or_default(); if autofmt { - doc.format(view.id); // TODO: merge into save + doc.format(view.id); // TODO: merge into save } tokio::spawn(doc.save()); Ok(()) @@ -1225,106 +1232,106 @@ mod cmd { _quit_all(editor, args, event, true) } - pub const COMMAND_LIST: &[TypableCommandData] = &[ - TypableCommandData { + pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ + TypableCommand { name: "quit", alias: Some("q"), doc: "Close the current view.", fun: quit, completer: None, }, - TypableCommandData { + TypableCommand { name: "quit!", alias: Some("q!"), doc: "Close the current view.", fun: force_quit, completer: None, }, - TypableCommandData { + TypableCommand { name: "open", alias: Some("o"), doc: "Open a file from disk into the current view.", fun: open, completer: Some(completers::filename), }, - TypableCommandData { + TypableCommand { name: "write", alias: Some("w"), doc: "Write changes to disk. Accepts an optional path (:write some/path.txt)", fun: write, completer: Some(completers::filename), }, - TypableCommandData { + TypableCommand { name: "new", alias: Some("n"), doc: "Create a new scratch buffer.", fun: new_file, completer: Some(completers::filename), }, - TypableCommandData { + TypableCommand { name: "format", alias: Some("fmt"), doc: "Format the file using a formatter.", fun: format, completer: None, }, - TypableCommandData { + TypableCommand { name: "earlier", alias: Some("ear"), doc: "Jump back to an earlier point in edit history. Accepts a number of steps or a time span.", fun: earlier, completer: None, }, - TypableCommandData { + TypableCommand { name: "later", alias: Some("lat"), doc: "Jump to a later point in edit history. Accepts a number of steps or a time span.", fun: later, completer: None, }, - TypableCommandData { + TypableCommand { name: "write-quit", alias: Some("wq"), doc: "Writes changes to disk and closes the current view. Accepts an optional path (:wq some/path.txt)", fun: write_quit, completer: Some(completers::filename), }, - TypableCommandData { + TypableCommand { name: "write-quit!", alias: Some("wq!"), doc: "Writes changes to disk and closes the current view forcefully. Accepts an optional path (:wq! some/path.txt)", fun: force_write_quit, completer: Some(completers::filename), }, - TypableCommandData { + TypableCommand { name: "write-all", alias: Some("wa"), doc: "Writes changes from all views to disk.", fun: write_all, completer: None, }, - TypableCommandData { + TypableCommand { name: "write-quit-all", alias: Some("wqa"), doc: "Writes changes from all views to disk and close all views.", fun: write_all_quit, completer: None, }, - TypableCommandData { + TypableCommand { name: "write-quit-all!", alias: Some("wqa!"), doc: "Writes changes from all views to disk and close all views forcefully (ignoring unsaved changes).", fun: force_write_all_quit, completer: None, }, - TypableCommandData { + TypableCommand { name: "quit-all", alias: Some("qa"), doc: "Close all views.", fun: quit_all, completer: None, }, - TypableCommandData { + TypableCommand { name: "quit-all!", alias: Some("qa!"), doc: "Close all views forcefully (ignoring unsaved changes).", @@ -1334,10 +1341,10 @@ mod cmd { ]; - pub static COMMANDS: Lazy> = Lazy::new(|| { + pub static COMMANDS: Lazy> = Lazy::new(|| { let mut map = HashMap::new(); - for cmd in COMMAND_LIST { + for cmd in TYPABLE_COMMAND_LIST { map.insert(cmd.name, cmd); if let Some(alias) = cmd.alias { map.insert(alias, cmd); @@ -1348,8 +1355,8 @@ mod cmd { }); } -pub fn command_mode(cx: &mut Context) { - // TODO: completion items should have a info section that would get displayed in +fn command_mode(cx: &mut Context) { + // TODO: completion items should have a info section that would get displayed in // a popup above the prompt when items are tabbed over let mut prompt = Prompt::new( @@ -1363,7 +1370,7 @@ pub fn command_mode(cx: &mut Context) { if parts.len() <= 1 { use std::{borrow::Cow, ops::Range}; let end = 0..; - cmd::COMMAND_LIST + cmd::TYPABLE_COMMAND_LIST .iter() .filter(|command| command.name.contains(input)) .map(|command| (end.clone(), Cow::Borrowed(command.name))) @@ -1371,7 +1378,7 @@ pub fn command_mode(cx: &mut Context) { } else { let part = parts.last().unwrap(); - if let Some(cmd::TypableCommandData { + if let Some(cmd::TypableCommand { completer: Some(completer), .. }) = cmd::COMMANDS.get(parts[0]) @@ -1412,7 +1419,7 @@ pub fn command_mode(cx: &mut Context) { prompt.doc_fn = Box::new(|input: &str| { let part = input.split(' ').next().unwrap_or_default(); - if let Some(cmd::TypableCommandData { doc, .. }) = cmd::COMMANDS.get(part) { + if let Some(cmd::TypableCommand { doc, .. }) = cmd::COMMANDS.get(part) { return Some(doc); } @@ -1422,13 +1429,13 @@ pub fn command_mode(cx: &mut Context) { cx.push_layer(Box::new(prompt)); } -pub fn file_picker(cx: &mut Context) { +fn file_picker(cx: &mut Context) { let root = find_root(None).unwrap_or_else(|| PathBuf::from("./")); let picker = ui::file_picker(root); cx.push_layer(Box::new(picker)); } -pub fn buffer_picker(cx: &mut Context) { +fn buffer_picker(cx: &mut Context) { use std::path::{Path, PathBuf}; let current = cx.editor.view().doc; @@ -1459,7 +1466,7 @@ pub fn buffer_picker(cx: &mut Context) { cx.push_layer(Box::new(picker)); } -pub fn symbol_picker(cx: &mut Context) { +fn symbol_picker(cx: &mut Context) { fn nested_to_flat( list: &mut Vec, file: &lsp::TextDocumentIdentifier, @@ -1530,14 +1537,14 @@ pub fn symbol_picker(cx: &mut Context) { } // I inserts at the first nonwhitespace character of each line with a selection -pub fn prepend_to_line(cx: &mut Context) { +fn prepend_to_line(cx: &mut Context) { move_first_nonwhitespace(cx); let doc = cx.doc(); enter_insert_mode(doc); } // A inserts at the end of each line with a selection -pub fn append_to_line(cx: &mut Context) { +fn append_to_line(cx: &mut Context) { let (view, doc) = cx.current(); enter_insert_mode(doc); @@ -1580,8 +1587,8 @@ fn open(cx: &mut Context, open: Open) { let index = doc.text().line_to_char(line).saturating_sub(1); - // TODO: share logic with insert_newline for indentation - let indent_level = indent::suggested_indent_for_pos( + // TODO: share logic with insert_newline for indentation + let indent_level = indent::suggested_indent_for_pos( doc.language_config(), doc.syntax(), text, @@ -1614,16 +1621,16 @@ fn open(cx: &mut Context, open: Open) { } // o inserts a new line after each line with a selection -pub fn open_below(cx: &mut Context) { +fn open_below(cx: &mut Context) { open(cx, Open::Below) } // O inserts a new line before each line with a selection -pub fn open_above(cx: &mut Context) { +fn open_above(cx: &mut Context) { open(cx, Open::Above) } -pub fn normal_mode(cx: &mut Context) { +fn normal_mode(cx: &mut Context) { let (view, doc) = cx.current(); doc.mode = Mode::Normal; @@ -1661,7 +1668,7 @@ fn switch_to_last_accessed_file(cx: &mut Context) { } } -pub fn goto_mode(cx: &mut Context) { +fn goto_mode(cx: &mut Context) { if let Some(count) = cx._count { push_jump(cx.editor); @@ -1687,10 +1694,10 @@ pub fn goto_mode(cx: &mut Context) { (Mode::Normal, 'l') => move_line_end(cx), (Mode::Select, 'h') => extend_line_start(cx), (Mode::Select, 'l') => extend_line_end(cx), - (_, 'd') => goto_definition(cx), - (_, 'y') => goto_type_definition(cx), - (_, 'r') => goto_reference(cx), - (_, 'i') => goto_implementation(cx), + (_, 'd') => goto_definition(cx), + (_, 'y') => goto_type_definition(cx), + (_, 'r') => goto_reference(cx), + (_, 'i') => goto_implementation(cx), (Mode::Normal, 's') => move_first_nonwhitespace(cx), (Mode::Select, 's') => extend_first_nonwhitespace(cx), @@ -1722,11 +1729,11 @@ pub fn goto_mode(cx: &mut Context) { }) } -pub fn select_mode(cx: &mut Context) { +fn select_mode(cx: &mut Context) { cx.doc().mode = Mode::Select; } -pub fn exit_select_mode(cx: &mut Context) { +fn exit_select_mode(cx: &mut Context) { cx.doc().mode = Mode::Normal; } @@ -1786,7 +1793,7 @@ fn _goto( } } -pub fn goto_definition(cx: &mut Context) { +fn goto_definition(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -1823,7 +1830,7 @@ pub fn goto_definition(cx: &mut Context) { ); } -pub fn goto_type_definition(cx: &mut Context) { +fn goto_type_definition(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -1860,7 +1867,7 @@ pub fn goto_type_definition(cx: &mut Context) { ); } -pub fn goto_implementation(cx: &mut Context) { +fn goto_implementation(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -1897,7 +1904,7 @@ pub fn goto_implementation(cx: &mut Context) { ); } -pub fn goto_reference(cx: &mut Context) { +fn goto_reference(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -1935,7 +1942,7 @@ fn goto_pos(editor: &mut Editor, pos: usize) { align_view(doc, view, Align::Center); } -pub fn goto_first_diag(cx: &mut Context) { +fn goto_first_diag(cx: &mut Context) { let editor = &mut cx.editor; let (view, doc) = editor.current(); @@ -1949,7 +1956,7 @@ pub fn goto_first_diag(cx: &mut Context) { goto_pos(editor, diag); } -pub fn goto_last_diag(cx: &mut Context) { +fn goto_last_diag(cx: &mut Context) { let editor = &mut cx.editor; let (view, doc) = editor.current(); @@ -1963,7 +1970,7 @@ pub fn goto_last_diag(cx: &mut Context) { goto_pos(editor, diag); } -pub fn goto_next_diag(cx: &mut Context) { +fn goto_next_diag(cx: &mut Context) { let editor = &mut cx.editor; let (view, doc) = editor.current(); @@ -1984,7 +1991,7 @@ pub fn goto_next_diag(cx: &mut Context) { goto_pos(editor, diag); } -pub fn goto_prev_diag(cx: &mut Context) { +fn goto_prev_diag(cx: &mut Context) { let editor = &mut cx.editor; let (view, doc) = editor.current(); @@ -2006,7 +2013,7 @@ pub fn goto_prev_diag(cx: &mut Context) { goto_pos(editor, diag); } -pub fn signature_help(cx: &mut Context) { +fn signature_help(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { @@ -2157,7 +2164,7 @@ pub mod insert { } } - pub fn insert_tab(cx: &mut Context) { + pub fn insert_tab(cx: &mut Context) { let (view, doc) = cx.current(); // TODO: round out to nearest indentation level (for example a line with 3 spaces should // indent by one to reach 4 spaces). @@ -2235,7 +2242,7 @@ pub mod insert { } // TODO: handle indent-aware delete - pub fn delete_char_backward(cx: &mut Context) { + pub fn delete_char_backward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2250,7 +2257,7 @@ pub mod insert { doc.apply(&transaction, view.id); } - pub fn delete_char_forward(cx: &mut Context) { + pub fn delete_char_forward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2265,7 +2272,7 @@ pub mod insert { doc.apply(&transaction, view.id); } - pub fn delete_word_backward(cx: &mut Context) { + pub fn delete_word_backward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2282,19 +2289,19 @@ pub mod insert { // TODO: each command could simply return a Option, then the higher level handles // storing it? -pub fn undo(cx: &mut Context) { +fn undo(cx: &mut Context) { let view_id = cx.view().id; cx.doc().undo(view_id); } -pub fn redo(cx: &mut Context) { +fn redo(cx: &mut Context) { let view_id = cx.view().id; cx.doc().redo(view_id); } // Yank / Paste -pub fn yank(cx: &mut Context) { +fn yank(cx: &mut Context) { // TODO: should selections be made end inclusive? let (view, doc) = cx.current(); let values: Vec = doc @@ -2355,7 +2362,7 @@ fn _paste(reg: char, doc: &mut Document, view: &View, action: Paste) -> Option replace // default insert -pub fn paste_after(cx: &mut Context) { +fn paste_after(cx: &mut Context) { let reg = cx.register.name(); let (view, doc) = cx.current(); @@ -2395,7 +2402,7 @@ pub fn paste_after(cx: &mut Context) { } } -pub fn paste_before(cx: &mut Context) { +fn paste_before(cx: &mut Context) { let reg = cx.register.name(); let (view, doc) = cx.current(); @@ -2422,7 +2429,7 @@ fn get_lines(doc: &Document, view_id: ViewId) -> Vec { lines } -pub fn indent(cx: &mut Context) { +fn indent(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let lines = get_lines(doc, view.id); @@ -2441,7 +2448,7 @@ pub fn indent(cx: &mut Context) { doc.append_changes_to_history(view.id); } -pub fn unindent(cx: &mut Context) { +fn unindent(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let lines = get_lines(doc, view.id); @@ -2481,7 +2488,7 @@ pub fn unindent(cx: &mut Context) { doc.append_changes_to_history(view.id); } -pub fn format_selections(cx: &mut Context) { +fn format_selections(cx: &mut Context) { let (view, doc) = cx.current(); // via lsp if available @@ -2527,7 +2534,7 @@ pub fn format_selections(cx: &mut Context) { doc.append_changes_to_history(view.id); } -pub fn join_selections(cx: &mut Context) { +fn join_selections(cx: &mut Context) { use movement::skip_while; let (view, doc) = cx.current(); let text = doc.text(); @@ -2571,7 +2578,7 @@ pub fn join_selections(cx: &mut Context) { doc.append_changes_to_history(view.id); } -pub fn keep_selections(cx: &mut Context) { +fn keep_selections(cx: &mut Context) { // keep selections matching regex let prompt = ui::regex_prompt(cx, "keep:".to_string(), move |view, doc, regex| { let text = doc.text().slice(..); @@ -2584,7 +2591,7 @@ pub fn keep_selections(cx: &mut Context) { cx.push_layer(Box::new(prompt)); } -pub fn keep_primary_selection(cx: &mut Context) { +fn keep_primary_selection(cx: &mut Context) { let (view, doc) = cx.current(); let range = doc.selection(view.id).primary(); @@ -2594,14 +2601,14 @@ pub fn keep_primary_selection(cx: &mut Context) { // -pub fn save(cx: &mut Context) { +fn save(cx: &mut Context) { // Spawns an async task to actually do the saving. This way we prevent blocking. // TODO: handle save errors somehow? tokio::spawn(cx.doc().save()); } -pub fn completion(cx: &mut Context) { +fn completion(cx: &mut Context) { // trigger on trigger char, or if user calls it // (or on word char typing??) // after it's triggered, if response marked is_incomplete, update on every subsequent keypress @@ -2691,7 +2698,7 @@ pub fn completion(cx: &mut Context) { //} } -pub fn hover(cx: &mut Context) { +fn hover(cx: &mut Context) { let (view, doc) = cx.current(); let language_server = match doc.language_server() { @@ -2741,7 +2748,7 @@ pub fn hover(cx: &mut Context) { } // comments -pub fn toggle_comments(cx: &mut Context) { +fn toggle_comments(cx: &mut Context) { let (view, doc) = cx.current(); let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id)); @@ -2751,7 +2758,7 @@ pub fn toggle_comments(cx: &mut Context) { // tree sitter node selection -pub fn expand_selection(cx: &mut Context) { +fn expand_selection(cx: &mut Context) { let (view, doc) = cx.current(); if let Some(syntax) = doc.syntax() { @@ -2761,7 +2768,7 @@ pub fn expand_selection(cx: &mut Context) { } } -pub fn match_brackets(cx: &mut Context) { +fn match_brackets(cx: &mut Context) { let (view, doc) = cx.current(); if let Some(syntax) = doc.syntax() { @@ -2775,7 +2782,7 @@ pub fn match_brackets(cx: &mut Context) { // -pub fn jump_forward(cx: &mut Context) { +fn jump_forward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); @@ -2789,7 +2796,7 @@ pub fn jump_forward(cx: &mut Context) { }; } -pub fn jump_backward(cx: &mut Context) { +fn jump_backward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); @@ -2807,7 +2814,7 @@ pub fn jump_backward(cx: &mut Context) { }; } -pub fn window_mode(cx: &mut Context) { +fn window_mode(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2815,24 +2822,24 @@ pub fn window_mode(cx: &mut Context) { } = event { match ch { - 'w' => rotate_view(cx), - 'h' => hsplit(cx), - 'v' => vsplit(cx), - 'q' => wclose(cx), + 'w' => rotate_view(cx), + 'h' => hsplit(cx), + 'v' => vsplit(cx), + 'q' => wclose(cx), _ => {} } } }) } -pub fn rotate_view(cx: &mut Context) { +fn rotate_view(cx: &mut Context) { cx.editor.focus_next() } // split helper, clear it later use helix_view::editor::Action; -use self::cmd::TypableCommandData; +use self::cmd::TypableCommand; fn split(cx: &mut Context, action: Action) { use helix_view::editor::Action; let (view, doc) = cx.current(); @@ -2848,21 +2855,21 @@ fn split(cx: &mut Context, action: Action) { doc.set_selection(view.id, selection); } -pub fn hsplit(cx: &mut Context) { +fn hsplit(cx: &mut Context) { split(cx, Action::HorizontalSplit); } -pub fn vsplit(cx: &mut Context) { +fn vsplit(cx: &mut Context) { split(cx, Action::VerticalSplit); } -pub fn wclose(cx: &mut Context) { +fn wclose(cx: &mut Context) { let view_id = cx.view().id; // close current split cx.editor.close(view_id, /* close_buffer */ false); } -pub fn select_register(cx: &mut Context) { +fn select_register(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2874,7 +2881,7 @@ pub fn select_register(cx: &mut Context) { }) } -pub fn space_mode(cx: &mut Context) { +fn space_mode(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2896,7 +2903,7 @@ pub fn space_mode(cx: &mut Context) { }) } -pub fn view_mode(cx: &mut Context) { +fn view_mode(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2939,7 +2946,7 @@ pub fn view_mode(cx: &mut Context) { }) } -pub fn left_bracket_mode(cx: &mut Context) { +fn left_bracket_mode(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2955,7 +2962,7 @@ pub fn left_bracket_mode(cx: &mut Context) { }) } -pub fn right_bracket_mode(cx: &mut Context) { +fn right_bracket_mode(cx: &mut Context) { cx.on_next_key(move |cx, event| { if let KeyEvent { code: KeyCode::Char(ch), @@ -2970,3 +2977,23 @@ pub fn right_bracket_mode(cx: &mut Context) { } }) } + +impl fmt::Display for Command { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Command(_, name) = self; + f.write_str(name) + } +} + +impl std::str::FromStr for Command { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + for command in Command::COMMAND_LIST { + if command.1 == s { + return Ok(command.clone()); + } + } + Err(anyhow!("No command with name '{}'", s)) + } +} diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 638e866ffd8d..ada5f2459a9c 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -133,84 +133,84 @@ macro_rules! alt { pub fn default() -> Keymaps { let normal = hashmap!( - key!('h') => commands::Command::MOVE_CHAR_LEFT, - key!('j') => commands::Command::MOVE_LINE_DOWN, - key!('k') => commands::Command::MOVE_LINE_UP, - key!('l') => commands::Command::MOVE_CHAR_RIGHT, + key!('h') => commands::Command::move_char_left, + key!('j') => commands::Command::move_line_down, + key!('k') => commands::Command::move_line_up, + key!('l') => commands::Command::move_char_right, KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_CHAR_LEFT, + } => commands::Command::move_char_left, KeyEvent { code: KeyCode::Down, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_LINE_DOWN, + } => commands::Command::move_line_down, KeyEvent { code: KeyCode::Up, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_LINE_UP, + } => commands::Command::move_line_up, KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_CHAR_RIGHT, + } => commands::Command::move_char_right, - key!('t') => commands::Command::FIND_TILL_CHAR, - key!('f') => commands::Command::FIND_NEXT_CHAR, - key!('T') => commands::Command::TILL_PREV_CHAR, - key!('F') => commands::Command::FIND_PREV_CHAR, + key!('t') => commands::Command::find_till_char, + key!('f') => commands::Command::find_next_char, + key!('T') => commands::Command::till_prev_char, + key!('F') => commands::Command::find_prev_char, // and matching set for select mode (extend) // - key!('r') => commands::Command::REPLACE, - key!('R') => commands::Command::REPLACE_WITH_YANKED, + key!('r') => commands::Command::replace, + key!('R') => commands::Command::replace_with_yanked, KeyEvent { code: KeyCode::Home, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_LINE_START, + } => commands::Command::move_line_start, KeyEvent { code: KeyCode::End, modifiers: KeyModifiers::NONE - } => commands::Command::MOVE_LINE_END, - - key!('w') => commands::Command::MOVE_NEXT_WORD_START, - key!('b') => commands::Command::MOVE_PREV_WORD_START, - key!('e') => commands::Command::MOVE_NEXT_WORD_END, - - key!('v') => commands::Command::SELECT_MODE, - key!('g') => commands::Command::GOTO_MODE, - key!(':') => commands::Command::COMMAND_MODE, - - key!('i') => commands::Command::INSERT_MODE, - key!('I') => commands::Command::PREPEND_TO_LINE, - key!('a') => commands::Command::APPEND_MODE, - key!('A') => commands::Command::APPEND_TO_LINE, - key!('o') => commands::Command::OPEN_BELOW, - key!('O') => commands::Command::OPEN_ABOVE, + } => commands::Command::move_line_end, + + key!('w') => commands::Command::move_next_word_start, + key!('b') => commands::Command::move_prev_word_start, + key!('e') => commands::Command::move_next_word_end, + + key!('v') => commands::Command::select_mode, + key!('g') => commands::Command::goto_mode, + key!(':') => commands::Command::command_mode, + + key!('i') => commands::Command::insert_mode, + key!('I') => commands::Command::prepend_to_line, + key!('a') => commands::Command::append_mode, + key!('A') => commands::Command::append_to_line, + key!('o') => commands::Command::open_below, + key!('O') => commands::Command::open_above, // [ ] equivalents too (add blank new line, no edit) - key!('d') => commands::Command::DELETE_SELECTION, + key!('d') => commands::Command::delete_selection, // TODO: also delete without yanking - key!('c') => commands::Command::CHANGE_SELECTION, + key!('c') => commands::Command::change_selection, // TODO: also change delete without yanking - // key!('r') => commands::Command::REPLACE_WITH_CHAR, + // key!('r') => commands::Command::replace_with_char, - key!('s') => commands::Command::SELECT_REGEX, - alt!('s') => commands::Command::SPLIT_SELECTION_ON_NEWLINE, - key!('S') => commands::Command::SPLIT_SELECTION, - key!(';') => commands::Command::COLLAPSE_SELECTION, - alt!(';') => commands::Command::FLIP_SELECTIONS, - key!('%') => commands::Command::SELECT_ALL, - key!('x') => commands::Command::SELECT_LINE, - key!('X') => commands::Command::EXTEND_LINE, + key!('s') => commands::Command::select_regex, + alt!('s') => commands::Command::split_selection_on_newline, + key!('S') => commands::Command::split_selection, + key!(';') => commands::Command::collapse_selection, + alt!(';') => commands::Command::flip_selections, + key!('%') => commands::Command::select_all, + key!('x') => commands::Command::select_line, + key!('X') => commands::Command::extend_line, // or select mode X? // extend_to_whole_line, crop_to_whole_line - key!('m') => commands::Command::MATCH_BRACKETS, + key!('m') => commands::Command::match_brackets, // TODO: refactor into // key!('m') => commands::select_to_matching, // key!('M') => commands::back_select_to_matching, @@ -220,39 +220,39 @@ pub fn default() -> Keymaps { // repeat_select // TODO: figure out what key to use - // key!('[') => commands::Command::EXPAND_SELECTION, ?? - key!('[') => commands::Command::LEFT_BRACKET_MODE, - key!(']') => commands::Command::RIGHT_BRACKET_MODE, + // key!('[') => commands::Command::expand_selection, ?? + key!('[') => commands::Command::left_bracket_mode, + key!(']') => commands::Command::right_bracket_mode, - key!('/') => commands::Command::SEARCH, + key!('/') => commands::Command::search, // ? for search_reverse - key!('n') => commands::Command::SEARCH_NEXT, - key!('N') => commands::Command::EXTEND_SEARCH_NEXT, + key!('n') => commands::Command::search_next, + key!('N') => commands::Command::extend_search_next, // N for search_prev - key!('*') => commands::Command::SEARCH_SELECTION, + key!('*') => commands::Command::search_selection, - key!('u') => commands::Command::UNDO, - key!('U') => commands::Command::REDO, + key!('u') => commands::Command::undo, + key!('U') => commands::Command::redo, - key!('y') => commands::Command::YANK, + key!('y') => commands::Command::yank, // yank_all - key!('p') => commands::Command::PASTE_AFTER, + key!('p') => commands::Command::paste_after, // paste_all - key!('P') => commands::Command::PASTE_BEFORE, + key!('P') => commands::Command::paste_before, - key!('>') => commands::Command::INDENT, - key!('<') => commands::Command::UNINDENT, - key!('=') => commands::Command::FORMAT_SELECTIONS, - key!('J') => commands::Command::JOIN_SELECTIONS, + key!('>') => commands::Command::indent, + key!('<') => commands::Command::unindent, + key!('=') => commands::Command::format_selections, + key!('J') => commands::Command::join_selections, // TODO: conflicts hover/doc - key!('K') => commands::Command::KEEP_SELECTIONS, + key!('K') => commands::Command::keep_selections, // TODO: and another method for inverse // TODO: clashes with space mode - key!(' ') => commands::Command::KEEP_PRIMARY_SELECTION, + key!(' ') => commands::Command::keep_primary_selection, - // key!('q') => commands::Command::RECORD_MACRO, - // key!('Q') => commands::Command::REPLAY_MACRO, + // key!('q') => commands::Command::record_macro, + // key!('Q') => commands::Command::replay_macro, // ~ / apostrophe => change case // & align selections @@ -263,39 +263,39 @@ pub fn default() -> Keymaps { KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::Command::NORMAL_MODE, + } => commands::Command::normal_mode, KeyEvent { code: KeyCode::PageUp, modifiers: KeyModifiers::NONE - } => commands::Command::PAGE_UP, - ctrl!('b') => commands::Command::PAGE_UP, + } => commands::Command::page_up, + ctrl!('b') => commands::Command::page_up, KeyEvent { code: KeyCode::PageDown, modifiers: KeyModifiers::NONE - } => commands::Command::PAGE_DOWN, - ctrl!('f') => commands::Command::PAGE_DOWN, - ctrl!('u') => commands::Command::HALF_PAGE_UP, - ctrl!('d') => commands::Command::HALF_PAGE_DOWN, + } => commands::Command::page_down, + ctrl!('f') => commands::Command::page_down, + ctrl!('u') => commands::Command::half_page_up, + ctrl!('d') => commands::Command::half_page_down, - ctrl!('w') => commands::Command::WINDOW_MODE, + ctrl!('w') => commands::Command::window_mode, // move under c - ctrl!('c') => commands::Command::TOGGLE_COMMENTS, - key!('K') => commands::Command::HOVER, + ctrl!('c') => commands::Command::toggle_comments, + key!('K') => commands::Command::hover, // z family for save/restore/combine from/to sels from register KeyEvent { // supposedly ctrl!('i') but did not work code: KeyCode::Tab, modifiers: KeyModifiers::NONE, - } => commands::Command::JUMP_FORWARD, - ctrl!('o') => commands::Command::JUMP_BACKWARD, - // ctrl!('s') => commands::Command::SAVE_SELECTION, + } => commands::Command::jump_forward, + ctrl!('o') => commands::Command::jump_backward, + // ctrl!('s') => commands::Command::save_selection, - key!(' ') => commands::Command::SPACE_MODE, - key!('z') => commands::Command::VIEW_MODE, + key!(' ') => commands::Command::space_mode, + key!('z') => commands::Command::view_mode, - key!('"') => commands::Command::SELECT_REGISTER, + key!('"') => commands::Command::select_register, ); // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether // we keep this separate select mode. More keys can fit into normal mode then, but it's weird @@ -303,49 +303,49 @@ pub fn default() -> Keymaps { let mut select = normal.clone(); select.extend( hashmap!( - key!('h') => commands::Command::EXTEND_CHAR_LEFT, - key!('j') => commands::Command::EXTEND_LINE_DOWN, - key!('k') => commands::Command::EXTEND_LINE_UP, - key!('l') => commands::Command::EXTEND_CHAR_RIGHT, + key!('h') => commands::Command::extend_char_left, + key!('j') => commands::Command::extend_line_down, + key!('k') => commands::Command::extend_line_up, + key!('l') => commands::Command::extend_char_right, KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_CHAR_LEFT, + } => commands::Command::extend_char_left, KeyEvent { code: KeyCode::Down, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_LINE_DOWN, + } => commands::Command::extend_line_down, KeyEvent { code: KeyCode::Up, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_LINE_UP, + } => commands::Command::extend_line_up, KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_CHAR_RIGHT, + } => commands::Command::extend_char_right, - key!('w') => commands::Command::EXTEND_NEXT_WORD_START, - key!('b') => commands::Command::EXTEND_PREV_WORD_START, - key!('e') => commands::Command::EXTEND_NEXT_WORD_END, + key!('w') => commands::Command::extend_next_word_start, + key!('b') => commands::Command::extend_prev_word_start, + key!('e') => commands::Command::extend_next_word_end, - key!('t') => commands::Command::EXTEND_TILL_CHAR, - key!('f') => commands::Command::EXTEND_NEXT_CHAR, + key!('t') => commands::Command::extend_till_char, + key!('f') => commands::Command::extend_next_char, - key!('T') => commands::Command::EXTEND_TILL_PREV_CHAR, - key!('F') => commands::Command::EXTEND_PREV_CHAR, + key!('T') => commands::Command::extend_till_prev_char, + key!('F') => commands::Command::extend_prev_char, KeyEvent { code: KeyCode::Home, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_LINE_START, + } => commands::Command::extend_line_start, KeyEvent { code: KeyCode::End, modifiers: KeyModifiers::NONE - } => commands::Command::EXTEND_LINE_END, + } => commands::Command::extend_line_end, KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::Command::EXIT_SELECT_MODE, + } => commands::Command::exit_select_mode, ) .into_iter(), ); @@ -359,26 +359,26 @@ pub fn default() -> Keymaps { KeyEvent { code: KeyCode::Esc, modifiers: KeyModifiers::NONE - } => commands::Command::NORMAL_MODE, + } => commands::Command::normal_mode, KeyEvent { code: KeyCode::Backspace, modifiers: KeyModifiers::NONE - } => commands::Command::DELETE_CHAR_BACKWARD, + } => commands::Command::delete_char_backward, KeyEvent { code: KeyCode::Delete, modifiers: KeyModifiers::NONE - } => commands::Command::DELETE_CHAR_FORWARD, + } => commands::Command::delete_char_forward, KeyEvent { code: KeyCode::Enter, modifiers: KeyModifiers::NONE - } => commands::Command::INSERT_NEWLINE, + } => commands::Command::insert_newline, KeyEvent { code: KeyCode::Tab, modifiers: KeyModifiers::NONE - } => commands::Command::INSERT_TAB, + } => commands::Command::insert_tab, - ctrl!('x') => commands::Command::COMPLETION, - ctrl!('w') => commands::Command::DELETE_WORD_BACKWARD, + ctrl!('x') => commands::Command::completion, + ctrl!('w') => commands::Command::delete_word_backward, ), ) } diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 3380510e324a..15dc7fec5c18 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -45,7 +45,7 @@ impl EditorView { Self { keymap: keymap::default(), on_next_key: None, - last_insert: (commands::Command::NORMAL_MODE, Vec::new()), + last_insert: (commands::Command::normal_mode, Vec::new()), completion: None, } } From f336d097d2909e606277cbaaa5ac9674dbb26bb2 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:35:38 +0200 Subject: [PATCH 09/19] Map directly to commands --- helix-term/src/application.rs | 4 ++-- helix-term/src/commands.rs | 10 +++++++++- helix-term/src/keymap.rs | 33 +++++++++++++++++---------------- helix-term/src/ui/editor.rs | 17 ++++------------- 4 files changed, 32 insertions(+), 32 deletions(-) diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index 74254c15c446..eb8d49080320 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -1,7 +1,7 @@ use helix_lsp::lsp; use helix_view::{document::Mode, Document, Editor, Theme, View}; -use crate::{args::Args, compositor::Compositor, keymap::Remaps, ui}; +use crate::{args::Args, compositor::Compositor, keymap::Keymaps, ui}; use log::{error, info}; @@ -40,7 +40,7 @@ pub struct Application { } impl Application { - pub fn new(mut args: Args, remaps: Option) -> Result { + pub fn new(mut args: Args, remaps: Option) -> Result { use helix_view::editor::Action; let mut compositor = Compositor::new()?; let size = compositor.size(); diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index fba9a9531934..ba40203e8cf8 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -150,6 +150,7 @@ macro_rules! commands { impl Command { pub fn execute(&self, cx: &mut Context) { (self.0)(cx); } + pub fn name(&self) -> &'static str { self.1 } commands!( move_char_left, @@ -2994,6 +2995,13 @@ impl std::str::FromStr for Command { return Ok(command.clone()); } } - Err(anyhow!("No command with name '{}'", s)) + Err(anyhow!("No command named '{}'", s)) + } +} + +impl fmt::Debug for Command { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Command(_, name) = self; + f.debug_tuple("Command").field(name).finish() } } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index ada5f2459a9c..aacf5849f44f 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -100,9 +100,6 @@ pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; pub type Keymap = HashMap; pub type Keymaps = HashMap; -pub type Remap = HashMap; -pub type Remaps = HashMap; - #[macro_export] macro_rules! key { ($($ch:tt)*) => { @@ -481,19 +478,19 @@ impl FromStr for RepresentableKeyEvent { } } -pub fn parse_remaps(remaps: &str) -> Result { +pub fn parse_remaps(remaps: &str) -> Result { type TomlCompatibleRemaps = HashMap>; let toml_remaps: TomlCompatibleRemaps = toml::from_str(remaps)?; - let mut remaps = Remaps::new(); + let mut remaps = Keymaps::new(); for (mode, map) in toml_remaps { let mode = Mode::from_str(&mode)?; - let mut remap = Remap::new(); + let mut remap = Keymap::new(); - for (source_key, target_key) in map { - let source_key = str::parse::(&source_key)?; - let target_key = str::parse::(&target_key)?; - remap.insert(source_key.0, target_key.0); + for (key, command) in map { + let key = str::parse::(&key)?; + let command = str::parse::(&command)?; + remap.insert(key.0, command); } remaps.insert(mode, remap); } @@ -504,15 +501,19 @@ pub fn parse_remaps(remaps: &str) -> Result { mod test { use super::*; + impl PartialEq for Command { + fn eq(&self, other: &Self) -> bool { self.name() == other.name() } + } + #[test] fn parsing_remaps_file() { let sample_remaps = r#" [Insert] - y = "x" - S-C-a = "F12" + y = "move_line_down" + S-C-a = "delete_selection" [Normal] - A-F12 = "S-C-w" + A-F12 = "move_next_word_end" "#; let parsed = parse_remaps(sample_remaps).unwrap(); @@ -521,13 +522,13 @@ mod test { hashmap!( Mode::Insert => hashmap!( KeyEvent { code: KeyCode::Char('y'), modifiers: KeyModifiers::NONE } - => KeyEvent { code: KeyCode::Char('x'), modifiers: KeyModifiers::NONE }, + => commands::Command::move_line_down, KeyEvent { code: KeyCode::Char('a'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL } - => KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::NONE }, + => commands::Command::delete_selection, ), Mode::Normal => hashmap!( KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::ALT } - => KeyEvent { code: KeyCode::Char('w'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL }, + => commands::Command::move_next_word_end, ) ) ) diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 15dc7fec5c18..6031ac68d3f7 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -2,7 +2,7 @@ use crate::{ commands, compositor::{Component, Compositor, Context, EventResult}, key, - keymap::{self, Keymaps, Remaps}, + keymap::{self, Keymaps}, ui::Completion, }; @@ -569,19 +569,10 @@ impl EditorView { self.completion = Some(completion); } - pub fn apply_remaps(&mut self, remaps: Remaps) { + pub fn apply_remaps(&mut self, remaps: Keymaps) { for (mode, remap) in remaps { - let mut new_pairs = HashMap::::new(); - for (source, target) in remap { - if let Some(command) = self.keymap.get(&mode).map(|m| m.get(&target)).flatten() { - new_pairs.insert(source, command.clone()); - } - } - - for (key, command) in new_pairs { - self.keymap - .get_mut(&mode) - .map(|mut m| m.insert(key, command)); + for (key, command) in remap { + self.keymap.get_mut(&mode).map(|mut m| m.insert(key, command)); } } } From 2cd3a7c0aaf0d52339930866730289f5f7b15b33 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:43:19 +0200 Subject: [PATCH 10/19] Match key parsing/displaying to Kakoune --- helix-term/src/keymap.rs | 85 +++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 35 deletions(-) diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index aacf5849f44f..53db2bb959da 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -405,24 +405,30 @@ impl Display for RepresentableKeyEvent { }, ))?; match key.code { - KeyCode::Backspace => f.write_str("Bs")?, - KeyCode::Enter => f.write_str("Enter")?, - KeyCode::Left => f.write_str("Left")?, - KeyCode::Right => f.write_str("Right")?, - KeyCode::Up => f.write_str("Up")?, - KeyCode::Down => f.write_str("Down")?, - KeyCode::Home => f.write_str("Home")?, - KeyCode::End => f.write_str("End")?, - KeyCode::PageUp => f.write_str("PageUp")?, - KeyCode::PageDown => f.write_str("PageDown")?, - KeyCode::Tab => f.write_str("Tab")?, - KeyCode::BackTab => f.write_str("BackTab")?, - KeyCode::Delete => f.write_str("Del")?, - KeyCode::Insert => f.write_str("Insert")?, + KeyCode::Backspace => f.write_str("backspace")?, + KeyCode::Enter => f.write_str("ret")?, + KeyCode::Left => f.write_str("left")?, + KeyCode::Right => f.write_str("right")?, + KeyCode::Up => f.write_str("up")?, + KeyCode::Down => f.write_str("down")?, + KeyCode::Home => f.write_str("home")?, + KeyCode::End => f.write_str("end")?, + KeyCode::PageUp => f.write_str("pageup")?, + KeyCode::PageDown => f.write_str("pagedown")?, + KeyCode::Tab => f.write_str("tab")?, + KeyCode::BackTab => f.write_str("backtab")?, + KeyCode::Delete => f.write_str("del")?, + KeyCode::Insert => f.write_str("ins")?, + KeyCode::Null => f.write_str("null")?, + KeyCode::Esc => f.write_str("esc")?, + KeyCode::Char('<') => f.write_str("lt")?, + KeyCode::Char('>') => f.write_str("gt")?, + KeyCode::Char('+') => f.write_str("plus")?, + KeyCode::Char('-') => f.write_str("minus")?, + KeyCode::Char(';') => f.write_str("semicolon")?, + KeyCode::Char('%') => f.write_str("percent")?, KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?, KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?, - KeyCode::Null => f.write_str("Null")?, - KeyCode::Esc => f.write_str("Esc")?, }; Ok(()) } @@ -434,21 +440,28 @@ impl FromStr for RepresentableKeyEvent { fn from_str(s: &str) -> Result { let mut tokens: Vec<_> = s.split('-').collect(); let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? { - "Bs" => KeyCode::Backspace, - "Enter" => KeyCode::Enter, - "Left" => KeyCode::Left, - "Right" => KeyCode::Right, - "Up" => KeyCode::Down, - "Home" => KeyCode::Home, - "End" => KeyCode::End, - "PageUp" => KeyCode::PageUp, - "PageDown" => KeyCode::PageDown, - "Tab" => KeyCode::Tab, - "BackTab" => KeyCode::BackTab, - "Del" => KeyCode::Delete, - "Insert" => KeyCode::Insert, - "Null" => KeyCode::Null, - "Esc" => KeyCode::Esc, + "backspace" => KeyCode::Backspace, + "space" => KeyCode::Char(' '), + "ret" => KeyCode::Enter, + "lt" => KeyCode::Char('<'), + "gt" => KeyCode::Char('>'), + "plus" => KeyCode::Char('+'), + "minus" => KeyCode::Char('-'), + "semicolon" => KeyCode::Char(';'), + "percent" => KeyCode::Char('%'), + "left" => KeyCode::Left, + "right" => KeyCode::Right, + "up" => KeyCode::Down, + "home" => KeyCode::Home, + "end" => KeyCode::End, + "pageup" => KeyCode::PageUp, + "pagedown" => KeyCode::PageDown, + "tab" => KeyCode::Tab, + "backtab" => KeyCode::BackTab, + "del" => KeyCode::Delete, + "ins" => KeyCode::Insert, + "null" => KeyCode::Null, + "esc" => KeyCode::Esc, single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()), function if function.len() > 1 && &function[0..1] == "F" => { let function = str::parse::(&function[1..])?; @@ -537,7 +550,7 @@ mod test { #[test] fn parsing_unmodified_keys() { assert_eq!( - str::parse::("Bs").unwrap(), + str::parse::("backspace").unwrap(), RepresentableKeyEvent(KeyEvent { code: KeyCode::Backspace, modifiers: KeyModifiers::NONE @@ -545,7 +558,7 @@ mod test { ); assert_eq!( - str::parse::("Left").unwrap(), + str::parse::("left").unwrap(), RepresentableKeyEvent(KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE @@ -579,9 +592,9 @@ mod test { fn parsing_modified_keys() { assert_eq!( - str::parse::("S-Bs").unwrap(), + str::parse::("S-minus").unwrap(), RepresentableKeyEvent(KeyEvent { - code: KeyCode::Backspace, + code: KeyCode::Char('-'), modifiers: KeyModifiers::SHIFT }) ); @@ -593,6 +606,7 @@ mod test { modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT }) ); + assert_eq!( str::parse::("S-C-2").unwrap(), RepresentableKeyEvent(KeyEvent { @@ -611,5 +625,6 @@ mod test { assert!(str::parse::("C-A-S-C-1").is_err()); assert!(str::parse::("FU").is_err()); assert!(str::parse::("123").is_err()); + assert!(str::parse::("S--").is_err()); } } From 0fdbd11c6e37b3cc0f45fbae78debb8ff0f8eb01 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:44:15 +0200 Subject: [PATCH 11/19] Formatting pass --- helix-term/src/commands.rs | 50 ++++++++++++++++++++----------------- helix-term/src/keymap.rs | 4 ++- helix-term/src/ui/editor.rs | 4 ++- 3 files changed, 33 insertions(+), 25 deletions(-) diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index ba40203e8cf8..4e79cb98b331 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -14,13 +14,13 @@ use helix_view::{ Document, DocumentId, Editor, ViewId, }; +use anyhow::anyhow; use helix_lsp::{ lsp, util::{lsp_pos_to_pos, lsp_range_to_range, pos_to_lsp_pos, range_to_lsp_range}, OffsetEncoding, }; use movement::Movement; -use anyhow::anyhow; use crate::{ compositor::{Callback, Component, Compositor}, @@ -37,8 +37,8 @@ use std::{ }; use crossterm::event::{KeyCode, KeyEvent}; -use once_cell::sync::Lazy; use insert::*; +use once_cell::sync::Lazy; pub struct Context<'a> { pub register: helix_view::RegisterSelection, @@ -149,8 +149,12 @@ macro_rules! commands { } impl Command { - pub fn execute(&self, cx: &mut Context) { (self.0)(cx); } - pub fn name(&self) -> &'static str { self.1 } + pub fn execute(&self, cx: &mut Context) { + (self.0)(cx); + } + pub fn name(&self) -> &'static str { + self.1 + } commands!( move_char_left, @@ -494,7 +498,7 @@ where fn find_till_char(cx: &mut Context) { _find_char( cx, - search::find_nth_next, + search::find_nth_next, false, /* inclusive */ false, /* extend */ ) @@ -931,7 +935,7 @@ fn extend_line(cx: &mut Context) { // heuristic: append changes to history after each command, unless we're in insert mode fn _delete_selection(reg: char, doc: &mut Document, view_id: ViewId) { - // first yank the selection + // first yank the selection let values: Vec = doc .selection(view_id) .fragments(doc.text().slice(..)) @@ -958,7 +962,7 @@ fn delete_selection(cx: &mut Context) { doc.append_changes_to_history(view.id); // exit select mode, if currently in select mode - exit_select_mode(cx); + exit_select_mode(cx); } fn change_selection(cx: &mut Context) { @@ -1089,7 +1093,7 @@ mod cmd { .map(|config| config.auto_format) .unwrap_or_default(); if autofmt { - doc.format(view.id); // TODO: merge into save + doc.format(view.id); // TODO: merge into save } tokio::spawn(doc.save()); Ok(()) @@ -1357,7 +1361,7 @@ mod cmd { } fn command_mode(cx: &mut Context) { - // TODO: completion items should have a info section that would get displayed in + // TODO: completion items should have a info section that would get displayed in // a popup above the prompt when items are tabbed over let mut prompt = Prompt::new( @@ -1588,8 +1592,8 @@ fn open(cx: &mut Context, open: Open) { let index = doc.text().line_to_char(line).saturating_sub(1); - // TODO: share logic with insert_newline for indentation - let indent_level = indent::suggested_indent_for_pos( + // TODO: share logic with insert_newline for indentation + let indent_level = indent::suggested_indent_for_pos( doc.language_config(), doc.syntax(), text, @@ -1695,10 +1699,10 @@ fn goto_mode(cx: &mut Context) { (Mode::Normal, 'l') => move_line_end(cx), (Mode::Select, 'h') => extend_line_start(cx), (Mode::Select, 'l') => extend_line_end(cx), - (_, 'd') => goto_definition(cx), - (_, 'y') => goto_type_definition(cx), - (_, 'r') => goto_reference(cx), - (_, 'i') => goto_implementation(cx), + (_, 'd') => goto_definition(cx), + (_, 'y') => goto_type_definition(cx), + (_, 'r') => goto_reference(cx), + (_, 'i') => goto_implementation(cx), (Mode::Normal, 's') => move_first_nonwhitespace(cx), (Mode::Select, 's') => extend_first_nonwhitespace(cx), @@ -2165,7 +2169,7 @@ pub mod insert { } } - pub fn insert_tab(cx: &mut Context) { + pub fn insert_tab(cx: &mut Context) { let (view, doc) = cx.current(); // TODO: round out to nearest indentation level (for example a line with 3 spaces should // indent by one to reach 4 spaces). @@ -2243,7 +2247,7 @@ pub mod insert { } // TODO: handle indent-aware delete - pub fn delete_char_backward(cx: &mut Context) { + pub fn delete_char_backward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2258,7 +2262,7 @@ pub mod insert { doc.apply(&transaction, view.id); } - pub fn delete_char_forward(cx: &mut Context) { + pub fn delete_char_forward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2273,7 +2277,7 @@ pub mod insert { doc.apply(&transaction, view.id); } - pub fn delete_word_backward(cx: &mut Context) { + pub fn delete_word_backward(cx: &mut Context) { let count = cx.count(); let (view, doc) = cx.current(); let text = doc.text().slice(..); @@ -2823,10 +2827,10 @@ fn window_mode(cx: &mut Context) { } = event { match ch { - 'w' => rotate_view(cx), - 'h' => hsplit(cx), - 'v' => vsplit(cx), - 'q' => wclose(cx), + 'w' => rotate_view(cx), + 'h' => hsplit(cx), + 'v' => vsplit(cx), + 'q' => wclose(cx), _ => {} } } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 53db2bb959da..d9351972fc8c 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -515,7 +515,9 @@ mod test { use super::*; impl PartialEq for Command { - fn eq(&self, other: &Self) -> bool { self.name() == other.name() } + fn eq(&self, other: &Self) -> bool { + self.name() == other.name() + } } #[test] diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 6031ac68d3f7..98e997345e41 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -572,7 +572,9 @@ impl EditorView { pub fn apply_remaps(&mut self, remaps: Keymaps) { for (mode, remap) in remaps { for (key, command) in remap { - self.keymap.get_mut(&mode).map(|mut m| m.insert(key, command)); + self.keymap + .get_mut(&mode) + .map(|mut m| m.insert(key, command)); } } } From 818978bd18d7ce846b2f0c7972096a99cc9749b4 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:53:16 +0200 Subject: [PATCH 12/19] Update documentation --- book/src/remapping.md | 48 +++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/book/src/remapping.md b/book/src/remapping.md index 4baa792a7938..21098df68673 100644 --- a/book/src/remapping.md +++ b/book/src/remapping.md @@ -9,30 +9,38 @@ this: ```toml # At most one section each of 'Normal', 'Insert' and 'Select' [Normal] -a = "w" # Maps the 'a' key to 'w' (move to next word) -w = "i" # Maps the 'w' key to 'i' (enter insert mode) -C-S-Esc = "f" # Maps Control-Shift-Escape to 'f' (find char) +a = "move_char_left" # Maps the 'a' key to the move_char_left command +w = "move_line_up" # Maps the 'w' key move_line_up +C-S-Esc = "select_line" # Maps Control-Shift-Escape to select_line [Insert] -A-x = "Esc" # Maps Alt-X to 'Esc' (leave insert mode) +A-x = "normal_mode" # Maps Alt-X to enter normal mode ``` Control, Shift and Alt modifiers are encoded respectively with the prefixes `C-`, `S-` and `A-`. Special keys are encoded as follows: -* Backspace => `Bs` -* Enter => `Enter` -* Left => `Left` -* Right => `Right` -* Up => `Up` -* Down => `Down` -* Home => `Home` -* End => `End` -* PageUp => `PageUp` -* PageDown => `PageDown` -* Tab => `Tab` -* BackTab => `BackTab` -* Delete => `Del` -* Insert => `Insert` -* Null => `Null` (No associated key) -* Esc => `Esc` +* Backspace => "backspace" +* Space => "space" +* Return/Enter => "ret" +* < => "lt" +* > => "gt" +* + => "plus" +* - => "minus" +* ; => "semicolon" +* % => "percent" +* Left => "left" +* Right => "right" +* Up => "up" +* Home => "home" +* End => "end" +* Page Up => "pageup" +* Page Down => "pagedown" +* Tab => "tab" +* Back Tab => "backtab" +* Delete => "del" +* Insert => "ins" +* Null => "null" +* Escape => "esc" + +Commands can be found in the source code at `../../helix-term/src/commands.rs` From 26211d0657cb4d6e441018d70e6da515e8b41e02 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Mon, 14 Jun 2021 23:55:36 +0200 Subject: [PATCH 13/19] Formatting --- helix-term/src/commands.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 56deb3bd3085..f5468901f80d 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -128,10 +128,8 @@ fn align_view(doc: &Document, view: &mut View, align: Align) { view.first_line = line.saturating_sub(relative); } -/// A command is a function that takes the current state and a count, and does a side-effect on the -/// state (usually by creating and applying a transaction). -//pub type Command = fn(cx: &mut Context); - +/// A command is composed of a static name, and a function that takes the current state plus a count, +/// and does a side-effect on the state (usually by creating and applying a transaction). #[derive(Clone)] pub struct Command(fn(cx: &mut Context), &'static str); @@ -152,6 +150,7 @@ impl Command { pub fn execute(&self, cx: &mut Context) { (self.0)(cx); } + pub fn name(&self) -> &'static str { self.1 } From d47c7bae99148b7fef0151a3bffcfc49fbca6263 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Tue, 15 Jun 2021 09:00:03 +0200 Subject: [PATCH 14/19] Fix example in the book --- book/src/remapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/remapping.md b/book/src/remapping.md index 21098df68673..1f1b222264f3 100644 --- a/book/src/remapping.md +++ b/book/src/remapping.md @@ -11,7 +11,7 @@ this: [Normal] a = "move_char_left" # Maps the 'a' key to the move_char_left command w = "move_line_up" # Maps the 'w' key move_line_up -C-S-Esc = "select_line" # Maps Control-Shift-Escape to select_line +C-S-esc = "select_line" # Maps Control-Shift-Escape to select_line [Insert] A-x = "normal_mode" # Maps Alt-X to enter normal mode From 9e57822413d6611d83f0baa8f33db4a06e7b147b Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Tue, 15 Jun 2021 09:32:42 +0200 Subject: [PATCH 15/19] Refactor into single config file --- book/src/remapping.md | 8 +- helix-term/src/application.rs | 8 +- helix-term/src/config.rs | 26 ++++ helix-term/src/keymap.rs | 244 +++++++++++++++++----------------- helix-term/src/lib.rs | 2 + helix-term/src/main.rs | 15 ++- 6 files changed, 166 insertions(+), 137 deletions(-) create mode 100644 helix-term/src/config.rs diff --git a/book/src/remapping.md b/book/src/remapping.md index 1f1b222264f3..10d657a16418 100644 --- a/book/src/remapping.md +++ b/book/src/remapping.md @@ -2,18 +2,18 @@ One-way key remapping is supported via a simple TOML configuration file. -To remap keys, write a `keymap.toml` file in your `helix` configuration +To remap keys, write a `config.toml` file in your `helix` configuration directory (default `~/.config/helix` in Linux systems) with a structure like this: ```toml -# At most one section each of 'Normal', 'Insert' and 'Select' -[Normal] +# At most one section each of 'keys.Normal', 'keys.Insert' and 'keys.Select' +[keys.Normal] a = "move_char_left" # Maps the 'a' key to the move_char_left command w = "move_line_up" # Maps the 'w' key move_line_up C-S-esc = "select_line" # Maps Control-Shift-Escape to select_line -[Insert] +[keys.Insert] A-x = "normal_mode" # Maps Alt-X to enter normal mode ``` diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index eb8d49080320..4bc533306252 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -1,7 +1,7 @@ use helix_lsp::lsp; use helix_view::{document::Mode, Document, Editor, Theme, View}; -use crate::{args::Args, compositor::Compositor, keymap::Keymaps, ui}; +use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui}; use log::{error, info}; @@ -40,15 +40,15 @@ pub struct Application { } impl Application { - pub fn new(mut args: Args, remaps: Option) -> Result { + pub fn new(mut args: Args, config: Option) -> Result { use helix_view::editor::Action; let mut compositor = Compositor::new()?; let size = compositor.size(); let mut editor = Editor::new(size); let mut editor_view = Box::new(ui::EditorView::new()); - if let Some(remaps) = remaps { - editor_view.apply_remaps(remaps); + if let Some(Config { keys: Some(keys) }) = config { + editor_view.apply_remaps(keys); } compositor.push(editor_view); diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs new file mode 100644 index 000000000000..6df16ffe83d4 --- /dev/null +++ b/helix-term/src/config.rs @@ -0,0 +1,26 @@ +use std::{collections::HashMap, str::FromStr}; +use anyhow::{Result, Error}; + +use serde::{Serialize, Deserialize}; + +use crate::keymap::{Keymaps, parse_remaps}; + +pub struct Config { + pub keys: Option, +} + +#[derive(Serialize, Deserialize)] +struct TomlConfig { + keys: Option>>, +} + +impl FromStr for Config { + type Err = Error; + + fn from_str(s: &str) -> Result { + let toml_config: TomlConfig = toml::from_str(&s)?; + Ok(Self { + keys: toml_config.keys.map(|r| parse_remaps(&r)).transpose()? + }) + } +} diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index d19d63191678..a936b427e00c 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -136,65 +136,65 @@ macro_rules! alt { pub fn default() -> Keymaps { let normal = hashmap!( - key!('h') => commands::Command::move_char_left, - key!('j') => commands::Command::move_line_down, - key!('k') => commands::Command::move_line_up, - key!('l') => commands::Command::move_char_right, - - key!(Left) => commands::Command::move_char_left, - key!(Down) => commands::Command::move_line_down, - key!(Up) => commands::Command::move_line_up, - key!(Right) => commands::Command::move_char_right, - - key!('t') => commands::Command::find_till_char, - key!('f') => commands::Command::find_next_char, - key!('T') => commands::Command::till_prev_char, - key!('F') => commands::Command::find_prev_char, + key!('h') => Command::move_char_left, + key!('j') => Command::move_line_down, + key!('k') => Command::move_line_up, + key!('l') => Command::move_char_right, + + key!(Left) => Command::move_char_left, + key!(Down) => Command::move_line_down, + key!(Up) => Command::move_line_up, + key!(Right) => Command::move_char_right, + + key!('t') => Command::find_till_char, + key!('f') => Command::find_next_char, + key!('T') => Command::till_prev_char, + key!('F') => Command::find_prev_char, // and matching set for select mode (extend) // - key!('r') => commands::Command::replace, - key!('R') => commands::Command::replace_with_yanked, - - key!(Home) => commands::Command::move_line_start, - key!(End) => commands::Command::move_line_end, - - key!('w') => commands::Command::move_next_word_start, - key!('b') => commands::Command::move_prev_word_start, - key!('e') => commands::Command::move_next_word_end, - - key!('v') => commands::Command::select_mode, - key!('g') => commands::Command::goto_mode, - key!(':') => commands::Command::command_mode, - - key!('i') => commands::Command::insert_mode, - key!('I') => commands::Command::prepend_to_line, - key!('a') => commands::Command::append_mode, - key!('A') => commands::Command::append_to_line, - key!('o') => commands::Command::open_below, - key!('O') => commands::Command::open_above, + key!('r') => Command::replace, + key!('R') => Command::replace_with_yanked, + + key!(Home) => Command::move_line_start, + key!(End) => Command::move_line_end, + + key!('w') => Command::move_next_word_start, + key!('b') => Command::move_prev_word_start, + key!('e') => Command::move_next_word_end, + + key!('v') => Command::select_mode, + key!('g') => Command::goto_mode, + key!(':') => Command::command_mode, + + key!('i') => Command::insert_mode, + key!('I') => Command::prepend_to_line, + key!('a') => Command::append_mode, + key!('A') => Command::append_to_line, + key!('o') => Command::open_below, + key!('O') => Command::open_above, // [ ] equivalents too (add blank new line, no edit) - key!('d') => commands::Command::delete_selection, + key!('d') => Command::delete_selection, // TODO: also delete without yanking - key!('c') => commands::Command::change_selection, + key!('c') => Command::change_selection, // TODO: also change delete without yanking - // key!('r') => commands::Command::replace_with_char, + // key!('r') => Command::replace_with_char, - key!('s') => commands::Command::select_regex, - alt!('s') => commands::Command::split_selection_on_newline, - key!('S') => commands::Command::split_selection, - key!(';') => commands::Command::collapse_selection, - alt!(';') => commands::Command::flip_selections, - key!('%') => commands::Command::select_all, - key!('x') => commands::Command::select_line, - key!('X') => commands::Command::extend_line, + key!('s') => Command::select_regex, + alt!('s') => Command::split_selection_on_newline, + key!('S') => Command::split_selection, + key!(';') => Command::collapse_selection, + alt!(';') => Command::flip_selections, + key!('%') => Command::select_all, + key!('x') => Command::select_line, + key!('X') => Command::extend_line, // or select mode X? // extend_to_whole_line, crop_to_whole_line - key!('m') => commands::Command::match_brackets, + key!('m') => Command::match_brackets, // TODO: refactor into // key!('m') => commands::select_to_matching, // key!('M') => commands::back_select_to_matching, @@ -204,39 +204,39 @@ pub fn default() -> Keymaps { // repeat_select // TODO: figure out what key to use - // key!('[') => commands::Command::expand_selection, ?? - key!('[') => commands::Command::left_bracket_mode, - key!(']') => commands::Command::right_bracket_mode, + // key!('[') => Command::expand_selection, ?? + key!('[') => Command::left_bracket_mode, + key!(']') => Command::right_bracket_mode, - key!('/') => commands::Command::search, + key!('/') => Command::search, // ? for search_reverse - key!('n') => commands::Command::search_next, - key!('N') => commands::Command::extend_search_next, + key!('n') => Command::search_next, + key!('N') => Command::extend_search_next, // N for search_prev - key!('*') => commands::Command::search_selection, + key!('*') => Command::search_selection, - key!('u') => commands::Command::undo, - key!('U') => commands::Command::redo, + key!('u') => Command::undo, + key!('U') => Command::redo, - key!('y') => commands::Command::yank, + key!('y') => Command::yank, // yank_all - key!('p') => commands::Command::paste_after, + key!('p') => Command::paste_after, // paste_all - key!('P') => commands::Command::paste_before, + key!('P') => Command::paste_before, - key!('>') => commands::Command::indent, - key!('<') => commands::Command::unindent, - key!('=') => commands::Command::format_selections, - key!('J') => commands::Command::join_selections, + key!('>') => Command::indent, + key!('<') => Command::unindent, + key!('=') => Command::format_selections, + key!('J') => Command::join_selections, // TODO: conflicts hover/doc - key!('K') => commands::Command::keep_selections, + key!('K') => Command::keep_selections, // TODO: and another method for inverse // TODO: clashes with space mode - key!(' ') => commands::Command::keep_primary_selection, + key!(' ') => Command::keep_primary_selection, - // key!('q') => commands::Command::record_macro, - // key!('Q') => commands::Command::replay_macro, + // key!('q') => Command::record_macro, + // key!('Q') => Command::replay_macro, // ~ / apostrophe => change case // & align selections @@ -244,31 +244,31 @@ pub fn default() -> Keymaps { // C / altC = copy (repeat) selections on prev/next lines - key!(Esc) => commands::Command::normal_mode, - key!(PageUp) => commands::Command::page_up, - key!(PageDown) => commands::Command::page_down, - ctrl!('b') => commands::Command::page_up, - ctrl!('f') => commands::Command::page_down, - ctrl!('u') => commands::Command::half_page_up, - ctrl!('d') => commands::Command::half_page_down, + key!(Esc) => Command::normal_mode, + key!(PageUp) => Command::page_up, + key!(PageDown) => Command::page_down, + ctrl!('b') => Command::page_up, + ctrl!('f') => Command::page_down, + ctrl!('u') => Command::half_page_up, + ctrl!('d') => Command::half_page_down, - ctrl!('w') => commands::Command::window_mode, + ctrl!('w') => Command::window_mode, // move under c - ctrl!('c') => commands::Command::toggle_comments, - key!('K') => commands::Command::hover, + ctrl!('c') => Command::toggle_comments, + key!('K') => Command::hover, // z family for save/restore/combine from/to sels from register // supposedly ctrl!('i') but did not work - key!(Tab) => commands::Command::jump_forward, - ctrl!('o') => commands::Command::jump_backward, - // ctrl!('s') => commands::Command::save_selection, + key!(Tab) => Command::jump_forward, + ctrl!('o') => Command::jump_backward, + // ctrl!('s') => Command::save_selection, - key!(' ') => commands::Command::space_mode, - key!('z') => commands::Command::view_mode, + key!(' ') => Command::space_mode, + key!('z') => Command::view_mode, - key!('"') => commands::Command::select_register, + key!('"') => Command::select_register, ); // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether // we keep this separate select mode. More keys can fit into normal mode then, but it's weird @@ -276,28 +276,28 @@ pub fn default() -> Keymaps { let mut select = normal.clone(); select.extend( hashmap!( - key!('h') => commands::Command::extend_char_left, - key!('j') => commands::Command::extend_line_down, - key!('k') => commands::Command::extend_line_up, - key!('l') => commands::Command::extend_char_right, - - key!(Left) => commands::Command::extend_char_left, - key!(Down) => commands::Command::extend_line_down, - key!(Up) => commands::Command::extend_line_up, - key!(Right) => commands::Command::extend_char_right, - - key!('w') => commands::Command::extend_next_word_start, - key!('b') => commands::Command::extend_prev_word_start, - key!('e') => commands::Command::extend_next_word_end, - - key!('t') => commands::Command::extend_till_char, - key!('f') => commands::Command::extend_next_char, - - key!('T') => commands::Command::extend_till_prev_char, - key!('F') => commands::Command::extend_prev_char, - key!(Home) => commands::Command::extend_line_start, - key!(End) => commands::Command::extend_line_end, - key!(Esc) => commands::Command::exit_select_mode, + key!('h') => Command::extend_char_left, + key!('j') => Command::extend_line_down, + key!('k') => Command::extend_line_up, + key!('l') => Command::extend_char_right, + + key!(Left) => Command::extend_char_left, + key!(Down) => Command::extend_line_down, + key!(Up) => Command::extend_line_up, + key!(Right) => Command::extend_char_right, + + key!('w') => Command::extend_next_word_start, + key!('b') => Command::extend_prev_word_start, + key!('e') => Command::extend_next_word_end, + + key!('t') => Command::extend_till_char, + key!('f') => Command::extend_next_char, + + key!('T') => Command::extend_till_prev_char, + key!('F') => Command::extend_prev_char, + key!(Home) => Command::extend_line_start, + key!(End) => Command::extend_line_end, + key!(Esc) => Command::exit_select_mode, ) .into_iter(), ); @@ -308,13 +308,13 @@ pub fn default() -> Keymaps { Mode::Normal => normal, Mode::Select => select, Mode::Insert => hashmap!( - key!(Esc) => commands::Command::normal_mode as Command, - key!(Backspace) => commands::Command::delete_char_backward, - key!(Delete) => commands::Command::delete_char_forward, - key!(Enter) => commands::Command::insert_newline, - key!(Tab) => commands::Command::insert_tab, - ctrl!('x') => commands::Command::completion, - ctrl!('w') => commands::Command::delete_word_backward, + key!(Esc) => Command::normal_mode as Command, + key!(Backspace) => Command::delete_char_backward, + key!(Delete) => Command::delete_char_forward, + key!(Enter) => Command::insert_newline, + key!(Tab) => Command::insert_tab, + ctrl!('x') => Command::completion, + ctrl!('w') => Command::delete_word_backward, ), ) } @@ -430,9 +430,7 @@ impl FromStr for RepresentableKeyEvent { } } -pub fn parse_remaps(remaps: &str) -> Result { - type TomlCompatibleRemaps = HashMap>; - let toml_remaps: TomlCompatibleRemaps = toml::from_str(remaps)?; +pub fn parse_remaps(toml_remaps: &HashMap>) -> Result { let mut remaps = Keymaps::new(); for (mode, map) in toml_remaps { @@ -451,6 +449,8 @@ pub fn parse_remaps(remaps: &str) -> Result { #[cfg(test)] mod test { + use crate::config::Config; + use super::*; impl PartialEq for Command { @@ -460,29 +460,29 @@ mod test { } #[test] - fn parsing_remaps_file() { + fn parsing_remaps_config_file() { let sample_remaps = r#" - [Insert] + [keys.Insert] y = "move_line_down" S-C-a = "delete_selection" - [Normal] + [keys.Normal] A-F12 = "move_next_word_end" "#; - let parsed = parse_remaps(sample_remaps).unwrap(); + let config = Config::from_str(sample_remaps).unwrap(); assert_eq!( - parsed, + config.keys.unwrap(), hashmap!( Mode::Insert => hashmap!( KeyEvent { code: KeyCode::Char('y'), modifiers: KeyModifiers::NONE } - => commands::Command::move_line_down, + => Command::move_line_down, KeyEvent { code: KeyCode::Char('a'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL } - => commands::Command::delete_selection, + => Command::delete_selection, ), Mode::Normal => hashmap!( KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::ALT } - => commands::Command::move_next_word_end, + => Command::move_next_word_end, ) ) ) diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs index 2fd403589280..934935be7120 100644 --- a/helix-term/src/lib.rs +++ b/helix-term/src/lib.rs @@ -6,3 +6,5 @@ pub mod commands; pub mod compositor; pub mod keymap; pub mod ui; +pub mod config; + diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index 5ba592f70698..01f99304abb0 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -1,7 +1,8 @@ use helix_term::application::Application; use helix_term::args::Args; -use helix_term::keymap::parse_remaps; +use helix_term::config::Config; use std::path::PathBuf; +use std::str::FromStr; use anyhow::{Context, Result}; @@ -38,6 +39,7 @@ fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> { Ok(()) } + #[tokio::main] async fn main() -> Result<()> { let cache_dir = helix_core::cache_dir(); @@ -89,16 +91,15 @@ FLAGS: std::fs::create_dir_all(&conf_dir).ok(); } - let remaps = if let Ok(remaps) = std::fs::read_to_string(conf_dir.join("keymap.toml")) { - Some(parse_remaps(&remaps).context("Invalid keymap.toml file")?) - } else { - None - }; + let config = std::fs::read_to_string(conf_dir.join("config.toml")) + .ok() + .map(|s| Config::from_str(&s)) + .transpose()?; setup_logging(logpath, args.verbosity).context("failed to initialize logging")?; // TODO: use the thread local executor to spawn the application task separately from the work pool - let mut app = Application::new(args, remaps).context("unable to create new application")?; + let mut app = Application::new(args, config).context("unable to create new application")?; app.run().await.unwrap(); Ok(()) From 4c6fa7c7872f0632c743ab8df99f27c60f56b21f Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Tue, 15 Jun 2021 09:36:10 +0200 Subject: [PATCH 16/19] Formatting --- helix-term/src/config.rs | 8 ++++---- helix-term/src/lib.rs | 3 +-- helix-term/src/main.rs | 1 - 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs index 6df16ffe83d4..49825dc5c59c 100644 --- a/helix-term/src/config.rs +++ b/helix-term/src/config.rs @@ -1,9 +1,9 @@ +use anyhow::{Error, Result}; use std::{collections::HashMap, str::FromStr}; -use anyhow::{Result, Error}; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; -use crate::keymap::{Keymaps, parse_remaps}; +use crate::keymap::{parse_remaps, Keymaps}; pub struct Config { pub keys: Option, @@ -20,7 +20,7 @@ impl FromStr for Config { fn from_str(s: &str) -> Result { let toml_config: TomlConfig = toml::from_str(&s)?; Ok(Self { - keys: toml_config.keys.map(|r| parse_remaps(&r)).transpose()? + keys: toml_config.keys.map(|r| parse_remaps(&r)).transpose()?, }) } } diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs index 934935be7120..601903720753 100644 --- a/helix-term/src/lib.rs +++ b/helix-term/src/lib.rs @@ -4,7 +4,6 @@ pub mod application; pub mod args; pub mod commands; pub mod compositor; +pub mod config; pub mod keymap; pub mod ui; -pub mod config; - diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index 01f99304abb0..e5701c0aab58 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -39,7 +39,6 @@ fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> { Ok(()) } - #[tokio::main] async fn main() -> Result<()> { let cache_dir = helix_core::cache_dir(); From 5a096e40be3715dfe7bf733943467ef6268b1229 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Tue, 15 Jun 2021 10:04:29 +0200 Subject: [PATCH 17/19] Refactor configuration and add keymap newtype wrappers --- helix-term/src/application.rs | 8 +- helix-term/src/config.rs | 12 +- helix-term/src/keymap.rs | 481 +++++++++++++++++++--------------- helix-term/src/main.rs | 4 +- helix-term/src/ui/editor.rs | 24 +- 5 files changed, 291 insertions(+), 238 deletions(-) diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index 4bc533306252..f5cba365155f 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -40,17 +40,13 @@ pub struct Application { } impl Application { - pub fn new(mut args: Args, config: Option) -> Result { + pub fn new(mut args: Args, config: Config) -> Result { use helix_view::editor::Action; let mut compositor = Compositor::new()?; let size = compositor.size(); let mut editor = Editor::new(size); - let mut editor_view = Box::new(ui::EditorView::new()); - if let Some(Config { keys: Some(keys) }) = config { - editor_view.apply_remaps(keys); - } - + let mut editor_view = Box::new(ui::EditorView::new(config.keymaps)); compositor.push(editor_view); if !args.files.is_empty() { diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs index 49825dc5c59c..414c1ebd5bb7 100644 --- a/helix-term/src/config.rs +++ b/helix-term/src/config.rs @@ -3,10 +3,11 @@ use std::{collections::HashMap, str::FromStr}; use serde::{Deserialize, Serialize}; -use crate::keymap::{parse_remaps, Keymaps}; +use crate::keymap::{parse_keymaps, Keymaps}; +#[derive(Default)] pub struct Config { - pub keys: Option, + pub keymaps: Keymaps, } #[derive(Serialize, Deserialize)] @@ -20,7 +21,12 @@ impl FromStr for Config { fn from_str(s: &str) -> Result { let toml_config: TomlConfig = toml::from_str(&s)?; Ok(Self { - keys: toml_config.keys.map(|r| parse_remaps(&r)).transpose()?, + keymaps: toml_config + .keys + .map(|r| parse_keymaps(&r)) + .transpose()? + .or_else(|| Some(Keymaps::default())) + .unwrap(), }) } } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index a936b427e00c..e00bc6af7d30 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -3,7 +3,12 @@ pub use crate::commands::Command; use anyhow::{anyhow, Error, Result}; use helix_core::hashmap; use helix_view::document::Mode; -use std::{collections::HashMap, fmt::Display, str::FromStr}; +use std::{ + collections::HashMap, + fmt::Display, + ops::{Deref, DerefMut}, + str::FromStr, +}; // Kakoune-inspired: // mode = { @@ -97,8 +102,10 @@ use std::{collections::HashMap, fmt::Display, str::FromStr}; // #[cfg(feature = "term")] pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; -pub type Keymap = HashMap; -pub type Keymaps = HashMap; +#[derive(Clone, Debug)] +pub struct Keymap(pub HashMap); +#[derive(Clone, Debug)] +pub struct Keymaps(pub HashMap); #[macro_export] macro_rules! key { @@ -134,189 +141,191 @@ macro_rules! alt { }; } -pub fn default() -> Keymaps { - let normal = hashmap!( - key!('h') => Command::move_char_left, - key!('j') => Command::move_line_down, - key!('k') => Command::move_line_up, - key!('l') => Command::move_char_right, - - key!(Left) => Command::move_char_left, - key!(Down) => Command::move_line_down, - key!(Up) => Command::move_line_up, - key!(Right) => Command::move_char_right, - - key!('t') => Command::find_till_char, - key!('f') => Command::find_next_char, - key!('T') => Command::till_prev_char, - key!('F') => Command::find_prev_char, - // and matching set for select mode (extend) - // - key!('r') => Command::replace, - key!('R') => Command::replace_with_yanked, - - key!(Home) => Command::move_line_start, - key!(End) => Command::move_line_end, - - key!('w') => Command::move_next_word_start, - key!('b') => Command::move_prev_word_start, - key!('e') => Command::move_next_word_end, - - key!('v') => Command::select_mode, - key!('g') => Command::goto_mode, - key!(':') => Command::command_mode, - - key!('i') => Command::insert_mode, - key!('I') => Command::prepend_to_line, - key!('a') => Command::append_mode, - key!('A') => Command::append_to_line, - key!('o') => Command::open_below, - key!('O') => Command::open_above, - // [ ] equivalents too (add blank new line, no edit) - - - key!('d') => Command::delete_selection, - // TODO: also delete without yanking - key!('c') => Command::change_selection, - // TODO: also change delete without yanking - - // key!('r') => Command::replace_with_char, - - key!('s') => Command::select_regex, - alt!('s') => Command::split_selection_on_newline, - key!('S') => Command::split_selection, - key!(';') => Command::collapse_selection, - alt!(';') => Command::flip_selections, - key!('%') => Command::select_all, - key!('x') => Command::select_line, - key!('X') => Command::extend_line, - // or select mode X? - // extend_to_whole_line, crop_to_whole_line - - - key!('m') => Command::match_brackets, - // TODO: refactor into - // key!('m') => commands::select_to_matching, - // key!('M') => commands::back_select_to_matching, - // select mode extend equivalents - - // key!('.') => commands::repeat_insert, - // repeat_select - - // TODO: figure out what key to use - // key!('[') => Command::expand_selection, ?? - key!('[') => Command::left_bracket_mode, - key!(']') => Command::right_bracket_mode, - - key!('/') => Command::search, - // ? for search_reverse - key!('n') => Command::search_next, - key!('N') => Command::extend_search_next, - // N for search_prev - key!('*') => Command::search_selection, - - key!('u') => Command::undo, - key!('U') => Command::redo, - - key!('y') => Command::yank, - // yank_all - key!('p') => Command::paste_after, - // paste_all - key!('P') => Command::paste_before, - - key!('>') => Command::indent, - key!('<') => Command::unindent, - key!('=') => Command::format_selections, - key!('J') => Command::join_selections, - // TODO: conflicts hover/doc - key!('K') => Command::keep_selections, - // TODO: and another method for inverse - - // TODO: clashes with space mode - key!(' ') => Command::keep_primary_selection, - - // key!('q') => Command::record_macro, - // key!('Q') => Command::replay_macro, - - // ~ / apostrophe => change case - // & align selections - // _ trim selections - - // C / altC = copy (repeat) selections on prev/next lines - - key!(Esc) => Command::normal_mode, - key!(PageUp) => Command::page_up, - key!(PageDown) => Command::page_down, - ctrl!('b') => Command::page_up, - ctrl!('f') => Command::page_down, - ctrl!('u') => Command::half_page_up, - ctrl!('d') => Command::half_page_down, - - ctrl!('w') => Command::window_mode, - - // move under c - ctrl!('c') => Command::toggle_comments, - key!('K') => Command::hover, - - // z family for save/restore/combine from/to sels from register - - // supposedly ctrl!('i') but did not work - key!(Tab) => Command::jump_forward, - ctrl!('o') => Command::jump_backward, - // ctrl!('s') => Command::save_selection, - - key!(' ') => Command::space_mode, - key!('z') => Command::view_mode, - - key!('"') => Command::select_register, - ); - // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether - // we keep this separate select mode. More keys can fit into normal mode then, but it's weird - // because some selection operations can now be done from normal mode, some from select mode. - let mut select = normal.clone(); - select.extend( - hashmap!( - key!('h') => Command::extend_char_left, - key!('j') => Command::extend_line_down, - key!('k') => Command::extend_line_up, - key!('l') => Command::extend_char_right, - - key!(Left) => Command::extend_char_left, - key!(Down) => Command::extend_line_down, - key!(Up) => Command::extend_line_up, - key!(Right) => Command::extend_char_right, - - key!('w') => Command::extend_next_word_start, - key!('b') => Command::extend_prev_word_start, - key!('e') => Command::extend_next_word_end, - - key!('t') => Command::extend_till_char, - key!('f') => Command::extend_next_char, - - key!('T') => Command::extend_till_prev_char, - key!('F') => Command::extend_prev_char, - key!(Home) => Command::extend_line_start, - key!(End) => Command::extend_line_end, - key!(Esc) => Command::exit_select_mode, - ) - .into_iter(), - ); - - hashmap!( - // as long as you cast the first item, rust is able to infer the other cases - // TODO: select could be normal mode with some bindings merged over - Mode::Normal => normal, - Mode::Select => select, - Mode::Insert => hashmap!( - key!(Esc) => Command::normal_mode as Command, - key!(Backspace) => Command::delete_char_backward, - key!(Delete) => Command::delete_char_forward, - key!(Enter) => Command::insert_newline, - key!(Tab) => Command::insert_tab, - ctrl!('x') => Command::completion, - ctrl!('w') => Command::delete_word_backward, - ), - ) +impl Default for Keymaps { + fn default() -> Self { + let normal = Keymap(hashmap!( + key!('h') => Command::move_char_left, + key!('j') => Command::move_line_down, + key!('k') => Command::move_line_up, + key!('l') => Command::move_char_right, + + key!(Left) => Command::move_char_left, + key!(Down) => Command::move_line_down, + key!(Up) => Command::move_line_up, + key!(Right) => Command::move_char_right, + + key!('t') => Command::find_till_char, + key!('f') => Command::find_next_char, + key!('T') => Command::till_prev_char, + key!('F') => Command::find_prev_char, + // and matching set for select mode (extend) + // + key!('r') => Command::replace, + key!('R') => Command::replace_with_yanked, + + key!(Home) => Command::move_line_start, + key!(End) => Command::move_line_end, + + key!('w') => Command::move_next_word_start, + key!('b') => Command::move_prev_word_start, + key!('e') => Command::move_next_word_end, + + key!('v') => Command::select_mode, + key!('g') => Command::goto_mode, + key!(':') => Command::command_mode, + + key!('i') => Command::insert_mode, + key!('I') => Command::prepend_to_line, + key!('a') => Command::append_mode, + key!('A') => Command::append_to_line, + key!('o') => Command::open_below, + key!('O') => Command::open_above, + // [ ] equivalents too (add blank new line, no edit) + + + key!('d') => Command::delete_selection, + // TODO: also delete without yanking + key!('c') => Command::change_selection, + // TODO: also change delete without yanking + + // key!('r') => Command::replace_with_char, + + key!('s') => Command::select_regex, + alt!('s') => Command::split_selection_on_newline, + key!('S') => Command::split_selection, + key!(';') => Command::collapse_selection, + alt!(';') => Command::flip_selections, + key!('%') => Command::select_all, + key!('x') => Command::select_line, + key!('X') => Command::extend_line, + // or select mode X? + // extend_to_whole_line, crop_to_whole_line + + + key!('m') => Command::match_brackets, + // TODO: refactor into + // key!('m') => commands::select_to_matching, + // key!('M') => commands::back_select_to_matching, + // select mode extend equivalents + + // key!('.') => commands::repeat_insert, + // repeat_select + + // TODO: figure out what key to use + // key!('[') => Command::expand_selection, ?? + key!('[') => Command::left_bracket_mode, + key!(']') => Command::right_bracket_mode, + + key!('/') => Command::search, + // ? for search_reverse + key!('n') => Command::search_next, + key!('N') => Command::extend_search_next, + // N for search_prev + key!('*') => Command::search_selection, + + key!('u') => Command::undo, + key!('U') => Command::redo, + + key!('y') => Command::yank, + // yank_all + key!('p') => Command::paste_after, + // paste_all + key!('P') => Command::paste_before, + + key!('>') => Command::indent, + key!('<') => Command::unindent, + key!('=') => Command::format_selections, + key!('J') => Command::join_selections, + // TODO: conflicts hover/doc + key!('K') => Command::keep_selections, + // TODO: and another method for inverse + + // TODO: clashes with space mode + key!(' ') => Command::keep_primary_selection, + + // key!('q') => Command::record_macro, + // key!('Q') => Command::replay_macro, + + // ~ / apostrophe => change case + // & align selections + // _ trim selections + + // C / altC = copy (repeat) selections on prev/next lines + + key!(Esc) => Command::normal_mode, + key!(PageUp) => Command::page_up, + key!(PageDown) => Command::page_down, + ctrl!('b') => Command::page_up, + ctrl!('f') => Command::page_down, + ctrl!('u') => Command::half_page_up, + ctrl!('d') => Command::half_page_down, + + ctrl!('w') => Command::window_mode, + + // move under c + ctrl!('c') => Command::toggle_comments, + key!('K') => Command::hover, + + // z family for save/restore/combine from/to sels from register + + // supposedly ctrl!('i') but did not work + key!(Tab) => Command::jump_forward, + ctrl!('o') => Command::jump_backward, + // ctrl!('s') => Command::save_selection, + + key!(' ') => Command::space_mode, + key!('z') => Command::view_mode, + + key!('"') => Command::select_register, + )); + // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether + // we keep this separate select mode. More keys can fit into normal mode then, but it's weird + // because some selection operations can now be done from normal mode, some from select mode. + let mut select = normal.clone(); + select.0.extend( + hashmap!( + key!('h') => Command::extend_char_left, + key!('j') => Command::extend_line_down, + key!('k') => Command::extend_line_up, + key!('l') => Command::extend_char_right, + + key!(Left) => Command::extend_char_left, + key!(Down) => Command::extend_line_down, + key!(Up) => Command::extend_line_up, + key!(Right) => Command::extend_char_right, + + key!('w') => Command::extend_next_word_start, + key!('b') => Command::extend_prev_word_start, + key!('e') => Command::extend_next_word_end, + + key!('t') => Command::extend_till_char, + key!('f') => Command::extend_next_char, + + key!('T') => Command::extend_till_prev_char, + key!('F') => Command::extend_prev_char, + key!(Home) => Command::extend_line_start, + key!(End) => Command::extend_line_end, + key!(Esc) => Command::exit_select_mode, + ) + .into_iter(), + ); + + Keymaps(hashmap!( + // as long as you cast the first item, rust is able to infer the other cases + // TODO: select could be normal mode with some bindings merged over + Mode::Normal => normal, + Mode::Select => select, + Mode::Insert => Keymap(hashmap!( + key!(Esc) => Command::normal_mode as Command, + key!(Backspace) => Command::delete_char_backward, + key!(Delete) => Command::delete_char_forward, + key!(Enter) => Command::insert_newline, + key!(Tab) => Command::insert_tab, + ctrl!('x') => Command::completion, + ctrl!('w') => Command::delete_word_backward, + )), + )) + } } // Newtype wrapper over keys to allow toml serialization/parsing @@ -430,21 +439,44 @@ impl FromStr for RepresentableKeyEvent { } } -pub fn parse_remaps(toml_remaps: &HashMap>) -> Result { - let mut remaps = Keymaps::new(); +pub fn parse_keymaps(toml_keymaps: &HashMap>) -> Result { + let mut keymaps = Keymaps::default(); - for (mode, map) in toml_remaps { + for (mode, map) in toml_keymaps { let mode = Mode::from_str(&mode)?; - let mut remap = Keymap::new(); - for (key, command) in map { let key = str::parse::(&key)?; let command = str::parse::(&command)?; - remap.insert(key.0, command); + keymaps.0.get_mut(&mode).unwrap().0.insert(key.0, command); } - remaps.insert(mode, remap); } - Ok(remaps) + Ok(keymaps) +} + +impl Deref for Keymap { + type Target = HashMap; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Deref for Keymaps { + type Target = HashMap; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Keymap { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl DerefMut for Keymaps { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } } #[cfg(test)] @@ -460,8 +492,8 @@ mod test { } #[test] - fn parsing_remaps_config_file() { - let sample_remaps = r#" + fn parsing_keymaps_config_file() { + let sample_keymaps = r#" [keys.Insert] y = "move_line_down" S-C-a = "delete_selection" @@ -470,22 +502,49 @@ mod test { A-F12 = "move_next_word_end" "#; - let config = Config::from_str(sample_remaps).unwrap(); + let config = Config::from_str(sample_keymaps).unwrap(); assert_eq!( - config.keys.unwrap(), - hashmap!( - Mode::Insert => hashmap!( - KeyEvent { code: KeyCode::Char('y'), modifiers: KeyModifiers::NONE } - => Command::move_line_down, - KeyEvent { code: KeyCode::Char('a'), modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL } - => Command::delete_selection, - ), - Mode::Normal => hashmap!( - KeyEvent { code: KeyCode::F(12), modifiers: KeyModifiers::ALT } - => Command::move_next_word_end, - ) - ) - ) + *config + .keymaps + .0 + .get(&Mode::Insert) + .unwrap() + .0 + .get(&KeyEvent { + code: KeyCode::Char('y'), + modifiers: KeyModifiers::NONE + }) + .unwrap(), + Command::move_line_down + ); + assert_eq!( + *config + .keymaps + .0 + .get(&Mode::Insert) + .unwrap() + .0 + .get(&KeyEvent { + code: KeyCode::Char('a'), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL + }) + .unwrap(), + Command::delete_selection + ); + assert_eq!( + *config + .keymaps + .0 + .get(&Mode::Normal) + .unwrap() + .0 + .get(&KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::ALT + }) + .unwrap(), + Command::move_next_word_end + ); } #[test] diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index e5701c0aab58..745cc50937f0 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -93,7 +93,9 @@ FLAGS: let config = std::fs::read_to_string(conf_dir.join("config.toml")) .ok() .map(|s| Config::from_str(&s)) - .transpose()?; + .transpose()? + .or_else(|| Some(Config::default())) + .unwrap(); setup_logging(logpath, args.verbosity).context("failed to initialize logging")?; diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 4eb1011ee7df..e648df59946b 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -26,7 +26,7 @@ use tui::{ }; pub struct EditorView { - keymap: Keymaps, + keymaps: Keymaps, on_next_key: Option>, last_insert: (commands::Command, Vec), completion: Option, @@ -36,14 +36,14 @@ const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter impl Default for EditorView { fn default() -> Self { - Self::new() + Self::new(Keymaps::default()) } } impl EditorView { - pub fn new() -> Self { + pub fn new(keymaps: Keymaps) -> Self { Self { - keymap: keymap::default(), + keymaps, on_next_key: None, last_insert: (commands::Command::normal_mode, Vec::new()), completion: None, @@ -531,7 +531,7 @@ impl EditorView { } fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) { - if let Some(command) = self.keymap[&Mode::Insert].get(&event) { + if let Some(command) = self.keymaps[&Mode::Insert].get(&event) { command.execute(cx); } else if let KeyEvent { code: KeyCode::Char(ch), @@ -569,7 +569,7 @@ impl EditorView { // set the register cxt.register = cxt.editor.register.take(); - if let Some(command) = self.keymap[&mode].get(&event) { + if let Some(command) = self.keymaps[&mode].get(&event) { command.execute(cxt); } } @@ -588,16 +588,6 @@ impl EditorView { completion.required_size((size.width, size.height)); self.completion = Some(completion); } - - pub fn apply_remaps(&mut self, remaps: Keymaps) { - for (mode, remap) in remaps { - for (key, command) in remap { - self.keymap - .get_mut(&mode) - .map(|mut m| m.insert(key, command)); - } - } - } } impl Component for EditorView { @@ -694,7 +684,7 @@ impl Component for EditorView { // how we entered insert mode is important, and we should track that so // we can repeat the side effect. - self.last_insert.0 = self.keymap[&mode][&key].clone(); + self.last_insert.0 = self.keymaps[&mode][&key].clone(); self.last_insert.1.clear(); } (Mode::Insert, Mode::Normal) => { From 41792a27c3369bfdacb30600601e76f5702646c7 Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Thu, 17 Jun 2021 12:12:46 +0200 Subject: [PATCH 18/19] Address first batch of PR comments --- book/src/remapping.md | 10 ++++++---- helix-term/src/commands.rs | 27 +++++++++++++-------------- helix-term/src/config.rs | 3 +-- helix-term/src/keymap.rs | 9 +++++---- helix-term/src/ui/editor.rs | 2 +- helix-view/src/document.rs | 12 ++++++------ 6 files changed, 32 insertions(+), 31 deletions(-) diff --git a/book/src/remapping.md b/book/src/remapping.md index 10d657a16418..313ac72e7fe2 100644 --- a/book/src/remapping.md +++ b/book/src/remapping.md @@ -1,19 +1,21 @@ # Key Remapping -One-way key remapping is supported via a simple TOML configuration file. +One-way key remapping is temporarily supported via a simple TOML configuration +file. (More powerful solutions such as rebinding via commands will be +available in the feature). To remap keys, write a `config.toml` file in your `helix` configuration directory (default `~/.config/helix` in Linux systems) with a structure like this: ```toml -# At most one section each of 'keys.Normal', 'keys.Insert' and 'keys.Select' -[keys.Normal] +# At most one section each of 'keys.normal', 'keys.insert' and 'keys.select' +[keys.normal] a = "move_char_left" # Maps the 'a' key to the move_char_left command w = "move_line_up" # Maps the 'w' key move_line_up C-S-esc = "select_line" # Maps Control-Shift-Escape to select_line -[keys.Insert] +[keys.insert] A-x = "normal_mode" # Maps Alt-X to enter normal mode ``` diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index ea195e53c7bf..c08013b68aa8 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -130,14 +130,14 @@ fn align_view(doc: &Document, view: &mut View, align: Align) { /// A command is composed of a static name, and a function that takes the current state plus a count, /// and does a side-effect on the state (usually by creating and applying a transaction). -#[derive(Clone)] -pub struct Command(fn(cx: &mut Context), &'static str); +#[derive(Copy, Clone)] +pub struct Command(&'static str, fn(cx: &mut Context)); macro_rules! commands { - ( $($name: ident),* ) => { + ( $($name:ident),* ) => { $( #[allow(non_upper_case_globals)] - pub const $name: Self = Self($name, stringify!($name)); + pub const $name: Self = Self(stringify!($name), $name); )* pub const COMMAND_LIST: &'static [Self] = &[ @@ -148,11 +148,11 @@ macro_rules! commands { impl Command { pub fn execute(&self, cx: &mut Context) { - (self.0)(cx); + (self.1)(cx); } pub fn name(&self) -> &'static str { - self.1 + self.0 } commands!( @@ -3030,7 +3030,7 @@ fn right_bracket_mode(cx: &mut Context) { impl fmt::Display for Command { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let Command(_, name) = self; + let Command(name, _) = self; f.write_str(name) } } @@ -3039,18 +3039,17 @@ impl std::str::FromStr for Command { type Err = anyhow::Error; fn from_str(s: &str) -> Result { - for command in Command::COMMAND_LIST { - if command.1 == s { - return Ok(command.clone()); - } - } - Err(anyhow!("No command named '{}'", s)) + Command::COMMAND_LIST + .iter() + .copied() + .find(|cmd| cmd.0 == s) + .ok_or_else(|| anyhow!("No command named '{}'", s)) } } impl fmt::Debug for Command { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let Command(_, name) = self; + let Command(name, _) = self; f.debug_tuple("Command").field(name).finish() } } diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs index 414c1ebd5bb7..757185344aae 100644 --- a/helix-term/src/config.rs +++ b/helix-term/src/config.rs @@ -25,8 +25,7 @@ impl FromStr for Config { .keys .map(|r| parse_keymaps(&r)) .transpose()? - .or_else(|| Some(Keymaps::default())) - .unwrap(), + .unwrap_or_else(Keymaps::default), }) } } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index e00bc6af7d30..9757e8ec6645 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -411,8 +411,9 @@ impl FromStr for RepresentableKeyEvent { "null" => KeyCode::Null, "esc" => KeyCode::Esc, single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()), - function if function.len() > 1 && &function[0..1] == "F" => { - let function = str::parse::(&function[1..])?; + function if function.len() > 1 && function.starts_with('F') => { + let function: String = function.chars().skip(1).collect(); + let function = str::parse::(&function)?; (function > 0 && function < 13) .then(|| KeyCode::F(function)) .ok_or_else(|| anyhow!("Invalid function key '{}'", function))? @@ -494,11 +495,11 @@ mod test { #[test] fn parsing_keymaps_config_file() { let sample_keymaps = r#" - [keys.Insert] + [keys.insert] y = "move_line_down" S-C-a = "delete_selection" - [keys.Normal] + [keys.normal] A-F12 = "move_next_word_end" "#; diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index e648df59946b..8b1b93265063 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -684,7 +684,7 @@ impl Component for EditorView { // how we entered insert mode is important, and we should track that so // we can repeat the side effect. - self.last_insert.0 = self.keymaps[&mode][&key].clone(); + self.last_insert.0 = self.keymaps[&mode][&key]; self.last_insert.1.clear(); } (Mode::Insert, Mode::Normal) => { diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 010ba1147f3f..254e01b0ec1e 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -91,9 +91,9 @@ impl fmt::Debug for Document { impl Display for Mode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Mode::Normal => f.write_str("Normal"), - Mode::Select => f.write_str("Select"), - Mode::Insert => f.write_str("Insert"), + Mode::Normal => f.write_str("normal"), + Mode::Select => f.write_str("select"), + Mode::Insert => f.write_str("insert"), } } } @@ -103,9 +103,9 @@ impl FromStr for Mode { fn from_str(s: &str) -> Result { match s { - "Normal" => Ok(Mode::Normal), - "Select" => Ok(Mode::Select), - "Insert" => Ok(Mode::Insert), + "normal" => Ok(Mode::Normal), + "select" => Ok(Mode::Select), + "insert" => Ok(Mode::Insert), _ => Err(anyhow!("Invalid mode '{}'", s)), } } From 321105672c06bbd8d8aadf660063a8351f4b278f Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Thu, 17 Jun 2021 12:25:34 +0200 Subject: [PATCH 19/19] Replace FromStr with custom deserialize --- helix-term/src/config.rs | 18 ++++++++++-------- helix-term/src/keymap.rs | 2 +- helix-term/src/main.rs | 3 +-- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs index 757185344aae..bd84e0b145ed 100644 --- a/helix-term/src/config.rs +++ b/helix-term/src/config.rs @@ -1,7 +1,7 @@ use anyhow::{Error, Result}; use std::{collections::HashMap, str::FromStr}; -use serde::{Deserialize, Serialize}; +use serde::{de::Error as SerdeError, Deserialize, Serialize}; use crate::keymap::{parse_keymaps, Keymaps}; @@ -15,16 +15,18 @@ struct TomlConfig { keys: Option>>, } -impl FromStr for Config { - type Err = Error; - - fn from_str(s: &str) -> Result { - let toml_config: TomlConfig = toml::from_str(&s)?; +impl<'de> Deserialize<'de> for Config { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let config = TomlConfig::deserialize(deserializer)?; Ok(Self { - keymaps: toml_config + keymaps: config .keys .map(|r| parse_keymaps(&r)) - .transpose()? + .transpose() + .map_err(|e| D::Error::custom(format!("Error deserializing keymap: {}", e)))? .unwrap_or_else(Keymaps::default), }) } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 9757e8ec6645..a2fdbdd17e23 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -503,7 +503,7 @@ mod test { A-F12 = "move_next_word_end" "#; - let config = Config::from_str(sample_keymaps).unwrap(); + let config: Config = toml::from_str(sample_keymaps).unwrap(); assert_eq!( *config .keymaps diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index 745cc50937f0..ef912480b5dd 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -2,7 +2,6 @@ use helix_term::application::Application; use helix_term::args::Args; use helix_term::config::Config; use std::path::PathBuf; -use std::str::FromStr; use anyhow::{Context, Result}; @@ -92,7 +91,7 @@ FLAGS: let config = std::fs::read_to_string(conf_dir.join("config.toml")) .ok() - .map(|s| Config::from_str(&s)) + .map(|s| toml::from_str(&s)) .transpose()? .or_else(|| Some(Config::default())) .unwrap();