aboutsummaryrefslogtreecommitdiff
path: root/helix-term
diff options
context:
space:
mode:
Diffstat (limited to 'helix-term')
-rw-r--r--helix-term/src/application.rs7
-rw-r--r--helix-term/src/commands.rs425
-rw-r--r--helix-term/src/config.rs33
-rw-r--r--helix-term/src/keymap.rs688
-rw-r--r--helix-term/src/lib.rs1
-rw-r--r--helix-term/src/main.rs11
-rw-r--r--helix-term/src/ui/editor.rs27
7 files changed, 853 insertions, 339 deletions
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 3d043441..f5cba365 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, config::Config, keymap::Keymaps, ui};
use log::{error, info};
@@ -40,13 +40,14 @@ pub struct Application {
}
impl Application {
- pub fn new(mut args: Args) -> Result<Self, Error> {
+ pub fn new(mut args: Args, config: Config) -> Result<Self, Error> {
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(config.keymaps));
+ 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/commands.rs b/helix-term/src/commands.rs
index e6ecda06..3ec06aaa 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -15,11 +15,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 insert::*;
use movement::Movement;
use crate::{
@@ -29,7 +31,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,
@@ -133,11 +135,145 @@ 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(Copy, Clone)]
+pub struct Command(&'static str, fn(cx: &mut Context));
+
+macro_rules! commands {
+ ( $($name:ident),* ) => {
+ $(
+ #[allow(non_upper_case_globals)]
+ pub const $name: Self = Self(stringify!($name), $name);
+ )*
+
+ pub const COMMAND_LIST: &'static [Self] = &[
+ $( Self::$name, )*
+ ];
+ }
+}
-pub fn move_char_left(cx: &mut Context) {
+impl Command {
+ pub fn execute(&self, cx: &mut Context) {
+ (self.1)(cx);
+ }
+
+ pub fn name(&self) -> &'static str {
+ self.0
+ }
+
+ 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
+ );
+}
+
+fn move_char_left(cx: &mut Context) {
let count = cx.count();
let (view, doc) = cx.current();
let text = doc.text().slice(..);
@@ -147,7 +283,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(..);
@@ -157,7 +293,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(..);
@@ -167,7 +303,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(..);
@@ -177,7 +313,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| {
@@ -193,7 +329,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| {
@@ -208,7 +344,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| {
@@ -230,7 +366,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(..);
@@ -242,7 +378,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(..);
@@ -254,7 +390,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(..);
@@ -266,13 +402,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();
@@ -280,7 +416,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(..);
@@ -294,7 +430,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(..);
@@ -307,7 +443,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(..);
@@ -365,7 +501,7 @@ where
})
}
-pub fn find_till_char(cx: &mut Context) {
+fn find_till_char(cx: &mut Context) {
find_char_impl(
cx,
search::find_nth_next,
@@ -374,7 +510,7 @@ pub fn find_till_char(cx: &mut Context) {
)
}
-pub fn find_next_char(cx: &mut Context) {
+fn find_next_char(cx: &mut Context) {
find_char_impl(
cx,
search::find_nth_next,
@@ -383,7 +519,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_impl(
cx,
search::find_nth_next,
@@ -392,7 +528,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_impl(
cx,
search::find_nth_next,
@@ -401,7 +537,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_impl(
cx,
search::find_nth_prev,
@@ -410,7 +546,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_impl(
cx,
search::find_nth_prev,
@@ -419,7 +555,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_impl(
cx,
search::find_nth_prev,
@@ -428,7 +564,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_impl(
cx,
search::find_nth_prev,
@@ -437,7 +573,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| {
@@ -455,7 +591,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 {
@@ -535,31 +671,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(..);
@@ -569,7 +705,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(..);
@@ -579,7 +715,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(..);
@@ -589,7 +725,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(..);
@@ -599,7 +735,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| {
@@ -615,7 +751,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| {
@@ -630,14 +766,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), &regex)
@@ -649,7 +785,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), &regex);
@@ -659,7 +795,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
@@ -711,7 +847,7 @@ fn search_impl(doc: &mut Document, view: &mut View, contents: &str, regex: &Rege
}
// 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?
@@ -733,9 +869,8 @@ pub fn search(cx: &mut Context) {
cx.push_layer(Box::new(prompt));
}
-// can't search next for ""compose"" for some reason
-pub fn search_next_impl(cx: &mut Context, extend: bool) {
+fn search_next_impl(cx: &mut Context, extend: bool) {
let (view, doc, registers) = cx.current_with_registers();
if let Some(query) = registers.read('\\') {
let query = query.first().unwrap();
@@ -745,15 +880,15 @@ pub fn search_next_impl(cx: &mut Context, extend: bool) {
}
}
-pub fn search_next(cx: &mut Context) {
+fn search_next(cx: &mut Context) {
search_next_impl(cx, false);
}
-pub fn extend_search_next(cx: &mut Context) {
+fn extend_search_next(cx: &mut Context) {
search_next_impl(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);
@@ -768,7 +903,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();
@@ -783,7 +918,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();
@@ -825,7 +960,7 @@ fn delete_selection_impl(reg: &mut Register, 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_name = cx.selected_register.name();
let (view, doc, registers) = cx.current_with_registers();
let reg = registers.get_or_insert(reg_name);
@@ -837,7 +972,7 @@ pub fn delete_selection(cx: &mut Context) {
exit_select_mode(cx);
}
-pub fn change_selection(cx: &mut Context) {
+fn change_selection(cx: &mut Context) {
let reg_name = cx.selected_register.name();
let (view, doc, registers) = cx.current_with_registers();
let reg = registers.get_or_insert(reg_name);
@@ -845,7 +980,7 @@ pub fn change_selection(cx: &mut Context) {
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)
@@ -854,7 +989,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)
@@ -868,7 +1003,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);
@@ -879,7 +1014,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;
@@ -913,7 +1048,7 @@ mod cmd {
use ui::completers::{self, Completer};
#[derive(Clone)]
- pub struct Command {
+ pub struct TypableCommand {
pub name: &'static str,
pub alias: Option<&'static str>,
pub doc: &'static str,
@@ -1152,113 +1287,113 @@ mod cmd {
quit_all_impl(editor, args, event, true)
}
- pub const COMMAND_LIST: &[Command] = &[
- Command {
+ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
+ TypableCommand {
name: "quit",
alias: Some("q"),
doc: "Close the current view.",
fun: quit,
completer: None,
},
- Command {
+ TypableCommand {
name: "quit!",
alias: Some("q!"),
doc: "Close the current view.",
fun: force_quit,
completer: None,
},
- Command {
+ TypableCommand {
name: "open",
alias: Some("o"),
doc: "Open a file from disk into the current view.",
fun: open,
completer: Some(completers::filename),
},
- Command {
+ 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),
},
- Command {
+ TypableCommand {
name: "new",
alias: Some("n"),
doc: "Create a new scratch buffer.",
fun: new_file,
completer: Some(completers::filename),
},
- Command {
+ TypableCommand {
name: "format",
alias: Some("fmt"),
doc: "Format the file using a formatter.",
fun: format,
completer: None,
},
- Command {
+ TypableCommand {
name: "indent-style",
alias: None,
doc: "Set the indentation style for editing. ('t' for tabs or 1-8 for number of spaces.)",
fun: set_indent_style,
completer: None,
},
- Command {
+ 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,
},
- Command {
+ 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,
},
- Command {
+ 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),
},
- Command {
+ 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),
},
- Command {
+ TypableCommand {
name: "write-all",
alias: Some("wa"),
doc: "Writes changes from all views to disk.",
fun: write_all,
completer: None,
},
- Command {
+ 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,
},
- Command {
+ 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,
},
- Command {
+ TypableCommand {
name: "quit-all",
alias: Some("qa"),
doc: "Close all views.",
fun: quit_all,
completer: None,
},
- Command {
+ TypableCommand {
name: "quit-all!",
alias: Some("qa!"),
doc: "Close all views forcefully (ignoring unsaved changes).",
@@ -1268,10 +1403,10 @@ mod cmd {
];
- pub static COMMANDS: Lazy<HashMap<&'static str, &'static Command>> = Lazy::new(|| {
+ pub static COMMANDS: Lazy<HashMap<&'static str, &'static TypableCommand>> = 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);
@@ -1282,7 +1417,7 @@ mod cmd {
});
}
-pub fn command_mode(cx: &mut Context) {
+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
@@ -1297,7 +1432,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)))
@@ -1305,7 +1440,7 @@ pub fn command_mode(cx: &mut Context) {
} else {
let part = parts.last().unwrap();
- if let Some(cmd::Command {
+ if let Some(cmd::TypableCommand {
completer: Some(completer),
..
}) = cmd::COMMANDS.get(parts[0])
@@ -1346,7 +1481,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::TypableCommand { doc, .. }) = cmd::COMMANDS.get(part) {
return Some(doc);
}
@@ -1356,13 +1491,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;
@@ -1393,7 +1528,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<lsp::SymbolInformation>,
file: &lsp::TextDocumentIdentifier,
@@ -1464,14 +1599,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);
@@ -1550,16 +1685,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;
@@ -1597,7 +1732,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);
@@ -1658,11 +1793,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;
}
@@ -1722,7 +1857,7 @@ fn goto_impl(
}
}
-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,
@@ -1759,7 +1894,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,
@@ -1796,7 +1931,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,
@@ -1833,7 +1968,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,
@@ -1871,7 +2006,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();
@@ -1885,7 +2020,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();
@@ -1899,7 +2034,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();
@@ -1920,7 +2055,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();
@@ -1942,7 +2077,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() {
@@ -2218,19 +2353,19 @@ pub mod insert {
// TODO: each command could simply return a Option<transaction>, 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<String> = doc
@@ -2295,7 +2430,7 @@ fn paste_impl(
Some(transaction)
}
-pub fn replace_with_yanked(cx: &mut Context) {
+fn replace_with_yanked(cx: &mut Context) {
let reg_name = cx.selected_register.name();
let (view, doc, registers) = cx.current_with_registers();
@@ -2324,7 +2459,7 @@ pub fn replace_with_yanked(cx: &mut Context) {
// replace => replace
// default insert
-pub fn paste_after(cx: &mut Context) {
+fn paste_after(cx: &mut Context) {
let reg_name = cx.selected_register.name();
let (view, doc, registers) = cx.current_with_registers();
@@ -2337,7 +2472,7 @@ pub fn paste_after(cx: &mut Context) {
}
}
-pub fn paste_before(cx: &mut Context) {
+fn paste_before(cx: &mut Context) {
let reg_name = cx.selected_register.name();
let (view, doc, registers) = cx.current_with_registers();
@@ -2367,7 +2502,7 @@ fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
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);
@@ -2386,7 +2521,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);
@@ -2426,7 +2561,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
@@ -2472,7 +2607,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();
@@ -2516,7 +2651,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(..);
@@ -2529,7 +2664,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();
@@ -2539,14 +2674,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
@@ -2636,7 +2771,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() {
@@ -2686,7 +2821,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));
@@ -2696,7 +2831,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() {
@@ -2706,7 +2841,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() {
@@ -2720,7 +2855,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();
@@ -2734,7 +2869,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();
@@ -2752,7 +2887,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),
@@ -2770,12 +2905,14 @@ pub fn window_mode(cx: &mut Context) {
})
}
-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::TypableCommand;
fn split(cx: &mut Context, action: Action) {
use helix_view::editor::Action;
let (view, doc) = cx.current();
@@ -2791,21 +2928,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),
@@ -2817,7 +2954,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),
@@ -2839,7 +2976,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),
@@ -2882,7 +3019,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),
@@ -2898,7 +3035,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),
@@ -2913,3 +3050,29 @@ 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<Self, Self::Err> {
+ 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;
+ f.debug_tuple("Command").field(name).finish()
+ }
+}
diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs
new file mode 100644
index 00000000..bd84e0b1
--- /dev/null
+++ b/helix-term/src/config.rs
@@ -0,0 +1,33 @@
+use anyhow::{Error, Result};
+use std::{collections::HashMap, str::FromStr};
+
+use serde::{de::Error as SerdeError, Deserialize, Serialize};
+
+use crate::keymap::{parse_keymaps, Keymaps};
+
+#[derive(Default)]
+pub struct Config {
+ pub keymaps: Keymaps,
+}
+
+#[derive(Serialize, Deserialize)]
+struct TomlConfig {
+ keys: Option<HashMap<String, HashMap<String, String>>>,
+}
+
+impl<'de> Deserialize<'de> for Config {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let config = TomlConfig::deserialize(deserializer)?;
+ Ok(Self {
+ keymaps: config
+ .keys
+ .map(|r| parse_keymaps(&r))
+ .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 1402d29d..a2fdbdd1 100644
--- a/helix-term/src/keymap.rs
+++ b/helix-term/src/keymap.rs
@@ -1,7 +1,14 @@
-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;
-use std::collections::HashMap;
+use std::{
+ collections::HashMap,
+ fmt::Display,
+ ops::{Deref, DerefMut},
+ str::FromStr,
+};
// Kakoune-inspired:
// mode = {
@@ -95,8 +102,10 @@ use std::collections::HashMap;
// #[cfg(feature = "term")]
pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
-pub type Keymap = HashMap<KeyEvent, Command>;
-pub type Keymaps = HashMap<Mode, Keymap>;
+#[derive(Clone, Debug)]
+pub struct Keymap(pub HashMap<KeyEvent, Command>);
+#[derive(Clone, Debug)]
+pub struct Keymaps(pub HashMap<Mode, Keymap>);
#[macro_export]
macro_rules! key {
@@ -132,188 +141,491 @@ 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!(Left) => commands::move_char_left,
- key!(Down) => commands::move_line_down,
- key!(Up) => commands::move_line_up,
- key!(Right) => commands::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,
- // and matching set for select mode (extend)
- //
- key!('r') => commands::replace,
- key!('R') => commands::replace_with_yanked,
-
- key!(Home) => commands::move_line_start,
- key!(End) => 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,
- // [<space> ]<space> equivalents too (add blank new line, no edit)
-
-
- key!('d') => commands::delete_selection,
- // TODO: also delete without yanking
- key!('c') => commands::change_selection,
- // TODO: also change delete without yanking
-
- // key!('r') => commands::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,
- // or select mode X?
- // extend_to_whole_line, crop_to_whole_line
-
-
- key!('m') => commands::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!('[') => commands::expand_selection, ??
- key!('[') => commands::left_bracket_mode,
- key!(']') => commands::right_bracket_mode,
-
- key!('/') => commands::search,
- // ? for search_reverse
- key!('n') => commands::search_next,
- key!('N') => commands::extend_search_next,
- // N for search_prev
- key!('*') => commands::search_selection,
-
- key!('u') => commands::undo,
- key!('U') => commands::redo,
-
- key!('y') => commands::yank,
- // yank_all
- key!('p') => commands::paste_after,
- // paste_all
- key!('P') => commands::paste_before,
-
- key!('>') => commands::indent,
- key!('<') => commands::unindent,
- key!('=') => commands::format_selections,
- key!('J') => commands::join_selections,
- // TODO: conflicts hover/doc
- key!('K') => commands::keep_selections,
- // TODO: and another method for inverse
-
- // TODO: clashes with space mode
- key!(' ') => commands::keep_primary_selection,
-
- // key!('q') => commands::record_macro,
- // key!('Q') => commands::replay_macro,
-
- // ~ / apostrophe => change case
- // & align selections
- // _ trim selections
-
- // C / altC = copy (repeat) selections on prev/next lines
-
- key!(Esc) => commands::normal_mode,
- key!(PageUp) => commands::page_up,
- key!(PageDown) => commands::page_down,
- ctrl!('b') => commands::page_up,
- ctrl!('f') => commands::page_down,
- ctrl!('u') => commands::half_page_up,
- ctrl!('d') => commands::half_page_down,
-
- ctrl!('w') => commands::window_mode,
-
- // move under <space>c
- ctrl!('c') => commands::toggle_comments,
- key!('K') => commands::hover,
-
- // z family for save/restore/combine from/to sels from register
-
- // supposedly ctrl!('i') but did not work
- key!(Tab) => commands::jump_forward,
- ctrl!('o') => commands::jump_backward,
- // ctrl!('s') => commands::save_selection,
-
- key!(' ') => commands::space_mode,
- key!('z') => commands::view_mode,
-
- key!('"') => commands::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') => 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!(Left) => commands::extend_char_left,
- key!(Down) => commands::extend_line_down,
- key!(Up) => commands::extend_line_up,
- key!(Right) => commands::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!('t') => commands::extend_till_char,
- key!('f') => commands::extend_next_char,
-
- key!('T') => commands::extend_till_prev_char,
- key!('F') => commands::extend_prev_char,
- key!(Home) => commands::extend_line_start,
- key!(End) => commands::extend_line_end,
- key!(Esc) => commands::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) => commands::normal_mode as Command,
- key!(Backspace) => commands::insert::delete_char_backward,
- key!(Delete) => commands::insert::delete_char_forward,
- key!(Enter) => commands::insert::insert_newline,
- key!(Tab) => commands::insert::insert_tab,
-
- ctrl!('x') => commands::completion,
- ctrl!('w') => commands::insert::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,
+ // [<space> ]<space> 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 <space>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
+#[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.contains(KeyModifiers::SHIFT) {
+ "S-"
+ } else {
+ ""
+ },
+ if key.modifiers.contains(KeyModifiers::ALT) {
+ "A-"
+ } else {
+ ""
+ },
+ if key.modifiers.contains(KeyModifiers::CONTROL) {
+ "C-"
+ } else {
+ ""
+ },
+ ))?;
+ match key.code {
+ 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))?,
+ };
+ Ok(())
+ }
+}
+
+impl FromStr for RepresentableKeyEvent {
+ type Err = Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let mut tokens: Vec<_> = s.split('-').collect();
+ let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? {
+ "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.starts_with('F') => {
+ let function: String = function.chars().skip(1).collect();
+ let function = str::parse::<u8>(&function)?;
+ (function > 0 && function < 13)
+ .then(|| KeyCode::F(function))
+ .ok_or_else(|| anyhow!("Invalid function key '{}'", function))?
+ }
+ invalid => return Err(anyhow!("Invalid key code '{}'", invalid)),
+ };
+
+ let mut modifiers = KeyModifiers::empty();
+ 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.contains(flag) {
+ return Err(anyhow!("Repeated key modifier '{}-'", token));
+ }
+ modifiers.insert(flag);
+ }
+
+ Ok(RepresentableKeyEvent(KeyEvent { code, modifiers }))
+ }
+}
+
+pub fn parse_keymaps(toml_keymaps: &HashMap<String, HashMap<String, String>>) -> Result<Keymaps> {
+ let mut keymaps = Keymaps::default();
+
+ for (mode, map) in toml_keymaps {
+ let mode = Mode::from_str(&mode)?;
+ for (key, command) in map {
+ let key = str::parse::<RepresentableKeyEvent>(&key)?;
+ let command = str::parse::<Command>(&command)?;
+ keymaps.0.get_mut(&mode).unwrap().0.insert(key.0, command);
+ }
+ }
+ Ok(keymaps)
+}
+
+impl Deref for Keymap {
+ type Target = HashMap<KeyEvent, Command>;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl Deref for Keymaps {
+ type Target = HashMap<Mode, Keymap>;
+ 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)]
+mod test {
+ use crate::config::Config;
+
+ use super::*;
+
+ impl PartialEq for Command {
+ fn eq(&self, other: &Self) -> bool {
+ self.name() == other.name()
+ }
+ }
+
+ #[test]
+ fn parsing_keymaps_config_file() {
+ let sample_keymaps = r#"
+ [keys.insert]
+ y = "move_line_down"
+ S-C-a = "delete_selection"
+
+ [keys.normal]
+ A-F12 = "move_next_word_end"
+ "#;
+
+ let config: Config = toml::from_str(sample_keymaps).unwrap();
+ assert_eq!(
+ *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]
+ fn parsing_unmodified_keys() {
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("backspace").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::Backspace,
+ modifiers: KeyModifiers::NONE
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("left").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::Left,
+ modifiers: KeyModifiers::NONE
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>(",").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::Char(','),
+ modifiers: KeyModifiers::NONE
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("w").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::Char('w'),
+ modifiers: KeyModifiers::NONE
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("F12").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::F(12),
+ modifiers: KeyModifiers::NONE
+ })
+ );
+ }
+
+ fn parsing_modified_keys() {
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("S-minus").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::Char('-'),
+ modifiers: KeyModifiers::SHIFT
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("C-A-S-F12").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::F(12),
+ modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
+ })
+ );
+
+ assert_eq!(
+ str::parse::<RepresentableKeyEvent>("S-C-2").unwrap(),
+ RepresentableKeyEvent(KeyEvent {
+ code: KeyCode::F(2),
+ modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
+ })
+ );
+ }
+
+ #[test]
+ fn parsing_nonsensical_keys_fails() {
+ assert!(str::parse::<RepresentableKeyEvent>("F13").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("F0").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("aaa").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("S-S-a").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("C-A-S-C-1").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("FU").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("123").is_err());
+ assert!(str::parse::<RepresentableKeyEvent>("S--").is_err());
+ }
}
diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs
index 2fd40358..60190372 100644
--- a/helix-term/src/lib.rs
+++ b/helix-term/src/lib.rs
@@ -4,5 +4,6 @@ pub mod application;
pub mod args;
pub mod commands;
pub mod compositor;
+pub mod config;
pub mod keymap;
pub mod ui;
diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs
index 9d4e1c5b..ef912480 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::config::Config;
use std::path::PathBuf;
use anyhow::{Context, Result};
@@ -89,10 +89,17 @@ FLAGS:
std::fs::create_dir_all(&conf_dir).ok();
}
+ let config = std::fs::read_to_string(conf_dir.join("config.toml"))
+ .ok()
+ .map(|s| toml::from_str(&s))
+ .transpose()?
+ .or_else(|| Some(Config::default()))
+ .unwrap();
+
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, config).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 63b3e277..07107c9e 100644
--- a/helix-term/src/ui/editor.rs
+++ b/helix-term/src/ui/editor.rs
@@ -11,10 +11,7 @@ use helix_core::{
syntax::{self, HighlightEvent},
Position, Range,
};
-use helix_view::{
- document::{IndentStyle, Mode},
- Document, Editor, Theme, View,
-};
+use helix_view::{document::Mode, Document, Editor, Theme, View};
use std::borrow::Cow;
use crossterm::{
@@ -30,7 +27,7 @@ use tui::{
};
pub struct EditorView {
- keymap: Keymaps,
+ keymaps: Keymaps,
on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
last_insert: (commands::Command, Vec<KeyEvent>),
completion: Option<Completion>,
@@ -40,16 +37,16 @@ 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::normal_mode, Vec::new()),
+ last_insert: (commands::Command::normal_mode, Vec::new()),
completion: None,
}
}
@@ -546,8 +543,8 @@ impl EditorView {
}
fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) {
- if let Some(command) = self.keymap[&Mode::Insert].get(&event) {
- command(cx);
+ if let Some(command) = self.keymaps[&Mode::Insert].get(&event) {
+ command.execute(cx);
} else if let KeyEvent {
code: KeyCode::Char(ch),
..
@@ -568,7 +565,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)
@@ -584,8 +581,8 @@ impl EditorView {
// set the register
cxt.selected_register = cxt.editor.selected_register.take();
- if let Some(command) = self.keymap[&mode].get(&event) {
- command(cxt);
+ if let Some(command) = self.keymaps[&mode].get(&event) {
+ command.execute(cxt);
}
}
}
@@ -699,7 +696,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.keymaps[&mode][&key];
self.last_insert.1.clear();
}
(Mode::Insert, Mode::Normal) => {